blob: 361749073a5c740a71bc03fdc224f6912863e453 [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
Vladimir Marko43354742021-02-03 15:37:01 +00001136static void InitializeObjectVirtualMethodHashes(ObjPtr<mirror::Class> java_lang_Object,
1137 PointerSize pointer_size,
1138 /*out*/ ArrayRef<uint32_t> virtual_method_hashes)
1139 REQUIRES_SHARED(Locks::mutator_lock_) {
1140 ArraySlice<ArtMethod> virtual_methods = java_lang_Object->GetVirtualMethods(pointer_size);
1141 DCHECK_EQ(virtual_method_hashes.size(), virtual_methods.size());
1142 for (size_t i = 0; i != virtual_method_hashes.size(); ++i) {
1143 const char* name = virtual_methods[i].GetName();
1144 virtual_method_hashes[i] = ComputeModifiedUtf8Hash(name);
1145 }
1146}
1147
Jeff Haodcdc85b2015-12-04 14:06:18 -08001148struct TrampolineCheckData {
1149 const void* quick_resolution_trampoline;
1150 const void* quick_imt_conflict_trampoline;
1151 const void* quick_generic_jni_trampoline;
1152 const void* quick_to_interpreter_bridge_trampoline;
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001153 const void* nterp_trampoline;
Andreas Gampe542451c2016-07-26 09:02:02 -07001154 PointerSize pointer_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001155 ArtMethod* m;
1156 bool error;
1157};
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001158
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001159bool ClassLinker::InitFromBootImage(std::string* error_msg) {
1160 VLOG(startup) << __FUNCTION__ << " entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001161 CHECK(!init_done_);
1162
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07001163 Runtime* const runtime = Runtime::Current();
1164 Thread* const self = Thread::Current();
1165 gc::Heap* const heap = runtime->GetHeap();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001166 std::vector<gc::space::ImageSpace*> spaces = heap->GetBootImageSpaces();
1167 CHECK(!spaces.empty());
Vladimir Marko024d69f2019-06-13 10:52:32 +01001168 const ImageHeader& image_header = spaces[0]->GetImageHeader();
1169 uint32_t pointer_size_unchecked = image_header.GetPointerSizeUnchecked();
Andreas Gampe542451c2016-07-26 09:02:02 -07001170 if (!ValidPointerSize(pointer_size_unchecked)) {
1171 *error_msg = StringPrintf("Invalid image pointer size: %u", pointer_size_unchecked);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001172 return false;
1173 }
Vladimir Marko3364d182019-03-13 13:55:01 +00001174 image_pointer_size_ = image_header.GetPointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001175 if (!runtime->IsAotCompiler()) {
1176 // Only the Aot compiler supports having an image with a different pointer size than the
1177 // runtime. This happens on the host for compiling 32 bit tests since we use a 64 bit libart
1178 // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
Andreas Gampe542451c2016-07-26 09:02:02 -07001179 if (image_pointer_size_ != kRuntimePointerSize) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001180 *error_msg = StringPrintf("Runtime must use current image pointer size: %zu vs %zu",
Andreas Gampe542451c2016-07-26 09:02:02 -07001181 static_cast<size_t>(image_pointer_size_),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001182 sizeof(void*));
1183 return false;
1184 }
1185 }
Vladimir Marko3364d182019-03-13 13:55:01 +00001186 DCHECK(!runtime->HasResolutionMethod());
1187 runtime->SetResolutionMethod(image_header.GetImageMethod(ImageHeader::kResolutionMethod));
1188 runtime->SetImtConflictMethod(image_header.GetImageMethod(ImageHeader::kImtConflictMethod));
1189 runtime->SetImtUnimplementedMethod(
1190 image_header.GetImageMethod(ImageHeader::kImtUnimplementedMethod));
1191 runtime->SetCalleeSaveMethod(
1192 image_header.GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod),
1193 CalleeSaveType::kSaveAllCalleeSaves);
1194 runtime->SetCalleeSaveMethod(
1195 image_header.GetImageMethod(ImageHeader::kSaveRefsOnlyMethod),
1196 CalleeSaveType::kSaveRefsOnly);
1197 runtime->SetCalleeSaveMethod(
1198 image_header.GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod),
1199 CalleeSaveType::kSaveRefsAndArgs);
1200 runtime->SetCalleeSaveMethod(
1201 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethod),
1202 CalleeSaveType::kSaveEverything);
1203 runtime->SetCalleeSaveMethod(
1204 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForClinit),
1205 CalleeSaveType::kSaveEverythingForClinit);
1206 runtime->SetCalleeSaveMethod(
1207 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForSuspendCheck),
1208 CalleeSaveType::kSaveEverythingForSuspendCheck);
1209
Jeff Haodcdc85b2015-12-04 14:06:18 -08001210 std::vector<const OatFile*> oat_files =
1211 runtime->GetOatFileManager().RegisterImageOatFiles(spaces);
1212 DCHECK(!oat_files.empty());
1213 const OatHeader& default_oat_header = oat_files[0]->GetOatHeader();
Vladimir Marko7dac8642019-11-06 17:09:30 +00001214 jni_dlsym_lookup_trampoline_ = default_oat_header.GetJniDlsymLookupTrampoline();
Vladimir Markofa458ac2020-02-12 14:08:07 +00001215 jni_dlsym_lookup_critical_trampoline_ = default_oat_header.GetJniDlsymLookupCriticalTrampoline();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001216 quick_resolution_trampoline_ = default_oat_header.GetQuickResolutionTrampoline();
1217 quick_imt_conflict_trampoline_ = default_oat_header.GetQuickImtConflictTrampoline();
1218 quick_generic_jni_trampoline_ = default_oat_header.GetQuickGenericJniTrampoline();
1219 quick_to_interpreter_bridge_trampoline_ = default_oat_header.GetQuickToInterpreterBridge();
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001220 nterp_trampoline_ = default_oat_header.GetNterpTrampoline();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001221 if (kIsDebugBuild) {
1222 // Check that the other images use the same trampoline.
1223 for (size_t i = 1; i < oat_files.size(); ++i) {
1224 const OatHeader& ith_oat_header = oat_files[i]->GetOatHeader();
Vladimir Marko7dac8642019-11-06 17:09:30 +00001225 const void* ith_jni_dlsym_lookup_trampoline_ =
1226 ith_oat_header.GetJniDlsymLookupTrampoline();
Vladimir Markofa458ac2020-02-12 14:08:07 +00001227 const void* ith_jni_dlsym_lookup_critical_trampoline_ =
1228 ith_oat_header.GetJniDlsymLookupCriticalTrampoline();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001229 const void* ith_quick_resolution_trampoline =
1230 ith_oat_header.GetQuickResolutionTrampoline();
1231 const void* ith_quick_imt_conflict_trampoline =
1232 ith_oat_header.GetQuickImtConflictTrampoline();
1233 const void* ith_quick_generic_jni_trampoline =
1234 ith_oat_header.GetQuickGenericJniTrampoline();
1235 const void* ith_quick_to_interpreter_bridge_trampoline =
1236 ith_oat_header.GetQuickToInterpreterBridge();
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001237 const void* ith_nterp_trampoline =
1238 ith_oat_header.GetNterpTrampoline();
Vladimir Marko7dac8642019-11-06 17:09:30 +00001239 if (ith_jni_dlsym_lookup_trampoline_ != jni_dlsym_lookup_trampoline_ ||
Vladimir Markofa458ac2020-02-12 14:08:07 +00001240 ith_jni_dlsym_lookup_critical_trampoline_ != jni_dlsym_lookup_critical_trampoline_ ||
Vladimir Marko7dac8642019-11-06 17:09:30 +00001241 ith_quick_resolution_trampoline != quick_resolution_trampoline_ ||
Jeff Haodcdc85b2015-12-04 14:06:18 -08001242 ith_quick_imt_conflict_trampoline != quick_imt_conflict_trampoline_ ||
1243 ith_quick_generic_jni_trampoline != quick_generic_jni_trampoline_ ||
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001244 ith_quick_to_interpreter_bridge_trampoline != quick_to_interpreter_bridge_trampoline_ ||
1245 ith_nterp_trampoline != nterp_trampoline_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001246 // Make sure that all methods in this image do not contain those trampolines as
1247 // entrypoints. Otherwise the class-linker won't be able to work with a single set.
1248 TrampolineCheckData data;
1249 data.error = false;
1250 data.pointer_size = GetImagePointerSize();
1251 data.quick_resolution_trampoline = ith_quick_resolution_trampoline;
1252 data.quick_imt_conflict_trampoline = ith_quick_imt_conflict_trampoline;
1253 data.quick_generic_jni_trampoline = ith_quick_generic_jni_trampoline;
1254 data.quick_to_interpreter_bridge_trampoline = ith_quick_to_interpreter_bridge_trampoline;
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001255 data.nterp_trampoline = ith_nterp_trampoline;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001256 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001257 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1258 if (obj->IsClass()) {
1259 ObjPtr<mirror::Class> klass = obj->AsClass();
1260 for (ArtMethod& m : klass->GetMethods(data.pointer_size)) {
1261 const void* entrypoint =
1262 m.GetEntryPointFromQuickCompiledCodePtrSize(data.pointer_size);
1263 if (entrypoint == data.quick_resolution_trampoline ||
1264 entrypoint == data.quick_imt_conflict_trampoline ||
1265 entrypoint == data.quick_generic_jni_trampoline ||
1266 entrypoint == data.quick_to_interpreter_bridge_trampoline) {
1267 data.m = &m;
1268 data.error = true;
1269 return;
1270 }
1271 }
1272 }
1273 };
1274 spaces[i]->GetLiveBitmap()->Walk(visitor);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001275 if (data.error) {
1276 ArtMethod* m = data.m;
David Sehr709b0702016-10-13 09:12:37 -07001277 LOG(ERROR) << "Found a broken ArtMethod: " << ArtMethod::PrettyMethod(m);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001278 *error_msg = "Found an ArtMethod with a bad entrypoint";
1279 return false;
1280 }
1281 }
1282 }
1283 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001284
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001285 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Vladimir Markod7e9bbf2019-03-28 13:18:57 +00001286 ObjPtr<mirror::ObjectArray<mirror::Class>>::DownCast(
Vladimir Marko024d69f2019-06-13 10:52:32 +01001287 image_header.GetImageRoot(ImageHeader::kClassRoots)));
Vladimir Markof75613c2018-06-05 12:51:04 +01001288 DCHECK_EQ(GetClassRoot<mirror::Class>(this)->GetClassFlags(), mirror::kClassFlagClass);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001289
Vladimir Marko024d69f2019-06-13 10:52:32 +01001290 DCHECK_EQ(GetClassRoot<mirror::Object>(this)->GetObjectSize(), sizeof(mirror::Object));
1291 ObjPtr<mirror::ObjectArray<mirror::Object>> boot_image_live_objects =
1292 ObjPtr<mirror::ObjectArray<mirror::Object>>::DownCast(
1293 image_header.GetImageRoot(ImageHeader::kBootImageLiveObjects));
1294 runtime->SetSentinel(boot_image_live_objects->Get(ImageHeader::kClearedJniWeakSentinel));
1295 DCHECK(runtime->GetSentinel().Read()->GetClass() == GetClassRoot<mirror::Object>(this));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001296
Vladimir Markod1908512018-11-22 14:57:28 +00001297 for (size_t i = 0u, size = spaces.size(); i != size; ++i) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001298 // Boot class loader, use a null handle.
1299 std::vector<std::unique_ptr<const DexFile>> dex_files;
Vladimir Markod1908512018-11-22 14:57:28 +00001300 if (!AddImageSpace(spaces[i],
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001301 ScopedNullHandle<mirror::ClassLoader>(),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001302 /*out*/&dex_files,
1303 error_msg)) {
1304 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001305 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001306 // Append opened dex files at the end.
1307 boot_dex_files_.insert(boot_dex_files_.end(),
1308 std::make_move_iterator(dex_files.begin()),
1309 std::make_move_iterator(dex_files.end()));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001310 }
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001311 for (const std::unique_ptr<const DexFile>& dex_file : boot_dex_files_) {
1312 OatDexFile::MadviseDexFile(*dex_file, MadviseState::kMadviseStateAtLoad);
1313 }
Vladimir Marko43354742021-02-03 15:37:01 +00001314 InitializeObjectVirtualMethodHashes(GetClassRoot<mirror::Object>(this),
1315 image_pointer_size_,
1316 ArrayRef<uint32_t>(object_virtual_method_hashes_));
Ian Rogers98379392014-02-24 16:53:16 -08001317 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001318
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001319 VLOG(startup) << __FUNCTION__ << " exiting";
1320 return true;
1321}
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08001322
Vladimir Marko4433c432018-12-04 14:57:47 +00001323void ClassLinker::AddExtraBootDexFiles(
1324 Thread* self,
1325 std::vector<std::unique_ptr<const DexFile>>&& additional_dex_files) {
1326 for (std::unique_ptr<const DexFile>& dex_file : additional_dex_files) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08001327 AppendToBootClassPath(self, dex_file.get());
Orion Hodson771708f2021-01-06 15:45:16 +00001328 if (kIsDebugBuild) {
1329 for (const auto& boot_dex_file : boot_dex_files_) {
1330 DCHECK_NE(boot_dex_file->GetLocation(), dex_file->GetLocation());
1331 }
1332 }
Vladimir Marko4433c432018-12-04 14:57:47 +00001333 boot_dex_files_.push_back(std::move(dex_file));
1334 }
1335}
1336
Jeff Hao5872d7c2016-04-27 11:07:41 -07001337bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001338 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001339 return class_loader == nullptr ||
Mathieu Chartier0795f232016-09-27 18:43:30 -07001340 soa.Decode<mirror::Class>(WellKnownClasses::java_lang_BootClassLoader) ==
1341 class_loader->GetClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001342}
1343
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03001344class CHAOnDeleteUpdateClassVisitor {
1345 public:
1346 explicit CHAOnDeleteUpdateClassVisitor(LinearAlloc* alloc)
1347 : allocator_(alloc), cha_(Runtime::Current()->GetClassLinker()->GetClassHierarchyAnalysis()),
1348 pointer_size_(Runtime::Current()->GetClassLinker()->GetImagePointerSize()),
1349 self_(Thread::Current()) {}
1350
1351 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
1352 // This class is going to be unloaded. Tell CHA about it.
1353 cha_->ResetSingleImplementationInHierarchy(klass, allocator_, pointer_size_);
1354 return true;
1355 }
1356 private:
1357 const LinearAlloc* allocator_;
1358 const ClassHierarchyAnalysis* cha_;
1359 const PointerSize pointer_size_;
1360 const Thread* self_;
1361};
1362
Chris Wailes0c61be42018-09-26 17:27:34 -07001363/*
Vladimir Marko8e05f092019-06-10 11:10:38 +01001364 * A class used to ensure that all references to strings interned in an AppImage have been
1365 * properly recorded in the interned references list, and is only ever run in debug mode.
Chris Wailes0c61be42018-09-26 17:27:34 -07001366 */
Vladimir Marko8e05f092019-06-10 11:10:38 +01001367class CountInternedStringReferencesVisitor {
Chang Xingba17dbd2017-06-28 21:27:56 +00001368 public:
Vladimir Marko8e05f092019-06-10 11:10:38 +01001369 CountInternedStringReferencesVisitor(const gc::space::ImageSpace& space,
1370 const InternTable::UnorderedSet& image_interns)
1371 : space_(space),
1372 image_interns_(image_interns),
1373 count_(0u) {}
Chris Wailes0c61be42018-09-26 17:27:34 -07001374
Chris Wailes0c61be42018-09-26 17:27:34 -07001375 void TestObject(ObjPtr<mirror::Object> referred_obj) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001376 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001377 if (referred_obj != nullptr &&
1378 space_.HasAddress(referred_obj.Ptr()) &&
1379 referred_obj->IsString()) {
1380 ObjPtr<mirror::String> referred_str = referred_obj->AsString();
Vladimir Marko8e05f092019-06-10 11:10:38 +01001381 auto it = image_interns_.find(GcRoot<mirror::String>(referred_str));
1382 if (it != image_interns_.end() && it->Read() == referred_str) {
1383 ++count_;
Chris Wailesfbeef462018-10-19 14:16:35 -07001384 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001385 }
Chang Xingba17dbd2017-06-28 21:27:56 +00001386 }
1387
Chris Wailes0c61be42018-09-26 17:27:34 -07001388 void VisitRootIfNonNull(
Chang Xingba17dbd2017-06-28 21:27:56 +00001389 mirror::CompressedReference<mirror::Object>* root) const
1390 REQUIRES_SHARED(Locks::mutator_lock_) {
1391 if (!root->IsNull()) {
1392 VisitRoot(root);
1393 }
1394 }
1395
Chris Wailes0c61be42018-09-26 17:27:34 -07001396 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001397 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001398 TestObject(root->AsMirrorPtr());
Chang Xingba17dbd2017-06-28 21:27:56 +00001399 }
1400
1401 // Visit Class Fields
Chris Wailes0c61be42018-09-26 17:27:34 -07001402 void operator()(ObjPtr<mirror::Object> obj,
1403 MemberOffset offset,
1404 bool is_static ATTRIBUTE_UNUSED) const
Chang Xingba17dbd2017-06-28 21:27:56 +00001405 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko8e05f092019-06-10 11:10:38 +01001406 // References within image or across images don't need a read barrier.
1407 ObjPtr<mirror::Object> referred_obj =
1408 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1409 TestObject(referred_obj);
Chang Xingba17dbd2017-06-28 21:27:56 +00001410 }
1411
1412 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1413 ObjPtr<mirror::Reference> ref) const
1414 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Vladimir Marko8e05f092019-06-10 11:10:38 +01001415 operator()(ref, mirror::Reference::ReferentOffset(), /*is_static=*/ false);
Chang Xingba17dbd2017-06-28 21:27:56 +00001416 }
1417
Vladimir Marko8e05f092019-06-10 11:10:38 +01001418 size_t GetCount() const {
1419 return count_;
1420 }
1421
1422 private:
Chris Wailes0c61be42018-09-26 17:27:34 -07001423 const gc::space::ImageSpace& space_;
Vladimir Marko8e05f092019-06-10 11:10:38 +01001424 const InternTable::UnorderedSet& image_interns_;
1425 mutable size_t count_; // Modified from the `const` callbacks.
Chang Xingba17dbd2017-06-28 21:27:56 +00001426};
1427
Chris Wailes0c61be42018-09-26 17:27:34 -07001428/*
Vladimir Marko8e05f092019-06-10 11:10:38 +01001429 * This function counts references to strings interned in the AppImage.
1430 * This is used in debug build to check against the number of the recorded references.
Chris Wailes0c61be42018-09-26 17:27:34 -07001431 */
Vladimir Marko8e05f092019-06-10 11:10:38 +01001432size_t CountInternedStringReferences(gc::space::ImageSpace& space,
1433 const InternTable::UnorderedSet& image_interns)
1434 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes0c61be42018-09-26 17:27:34 -07001435 const gc::accounting::ContinuousSpaceBitmap* bitmap = space.GetMarkBitmap();
1436 const ImageHeader& image_header = space.GetImageHeader();
1437 const uint8_t* target_base = space.GetMemMap()->Begin();
1438 const ImageSection& objects_section = image_header.GetObjectsSection();
Chris Wailesfbeef462018-10-19 14:16:35 -07001439
1440 auto objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1441 auto objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
Chris Wailes0c61be42018-09-26 17:27:34 -07001442
Vladimir Marko8e05f092019-06-10 11:10:38 +01001443 CountInternedStringReferencesVisitor visitor(space, image_interns);
Chris Wailes0c61be42018-09-26 17:27:34 -07001444 bitmap->VisitMarkedRange(objects_begin,
1445 objects_end,
1446 [&space, &visitor](mirror::Object* obj)
1447 REQUIRES_SHARED(Locks::mutator_lock_) {
1448 if (space.HasAddress(obj)) {
1449 if (obj->IsDexCache()) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001450 obj->VisitReferences</* kVisitNativeRoots= */ true,
1451 kVerifyNone,
1452 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001453 } else {
1454 // Don't visit native roots for non-dex-cache as they can't contain
1455 // native references to strings. This is verified during compilation
1456 // by ImageWriter::VerifyNativeGCRootInvariants.
Chris Wailesfbeef462018-10-19 14:16:35 -07001457 obj->VisitReferences</* kVisitNativeRoots= */ false,
1458 kVerifyNone,
1459 kWithoutReadBarrier>(visitor, visitor);
Chris Wailes0c61be42018-09-26 17:27:34 -07001460 }
1461 }
1462 });
Vladimir Marko8e05f092019-06-10 11:10:38 +01001463 return visitor.GetCount();
1464}
1465
1466template <typename Visitor>
1467static void VisitInternedStringReferences(
1468 gc::space::ImageSpace* space,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001469 const Visitor& visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
1470 const uint8_t* target_base = space->Begin();
1471 const ImageSection& sro_section =
1472 space->GetImageHeader().GetImageStringReferenceOffsetsSection();
1473 const size_t num_string_offsets = sro_section.Size() / sizeof(AppImageReferenceOffsetInfo);
1474
1475 VLOG(image)
1476 << "ClassLinker:AppImage:InternStrings:imageStringReferenceOffsetCount = "
1477 << num_string_offsets;
1478
1479 const auto* sro_base =
1480 reinterpret_cast<const AppImageReferenceOffsetInfo*>(target_base + sro_section.Offset());
1481
1482 for (size_t offset_index = 0; offset_index < num_string_offsets; ++offset_index) {
1483 uint32_t base_offset = sro_base[offset_index].first;
1484
David Srbecky86d6cd52020-12-02 18:13:10 +00001485 uint32_t raw_member_offset = sro_base[offset_index].second;
1486 DCHECK_ALIGNED(base_offset, 2);
1487 DCHECK_ALIGNED(raw_member_offset, 2);
Vladimir Marko8e05f092019-06-10 11:10:38 +01001488
David Srbecky86d6cd52020-12-02 18:13:10 +00001489 ObjPtr<mirror::Object> obj_ptr =
1490 reinterpret_cast<mirror::Object*>(space->Begin() + base_offset);
1491 MemberOffset member_offset(raw_member_offset);
1492 ObjPtr<mirror::String> referred_string =
1493 obj_ptr->GetFieldObject<mirror::String,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001494 kVerifyNone,
David Srbecky86d6cd52020-12-02 18:13:10 +00001495 kWithoutReadBarrier,
1496 /* kIsVolatile= */ false>(member_offset);
1497 DCHECK(referred_string != nullptr);
1498
1499 ObjPtr<mirror::String> visited = visitor(referred_string);
1500 if (visited != referred_string) {
1501 obj_ptr->SetFieldObject</* kTransactionActive= */ false,
1502 /* kCheckTransaction= */ false,
1503 kVerifyNone,
1504 /* kIsVolatile= */ false>(member_offset, visited);
Vladimir Marko8e05f092019-06-10 11:10:38 +01001505 }
1506 }
1507}
1508
1509static void VerifyInternedStringReferences(gc::space::ImageSpace* space)
1510 REQUIRES_SHARED(Locks::mutator_lock_) {
1511 InternTable::UnorderedSet image_interns;
1512 const ImageSection& section = space->GetImageHeader().GetInternedStringsSection();
1513 if (section.Size() > 0) {
1514 size_t read_count;
1515 const uint8_t* data = space->Begin() + section.Offset();
1516 InternTable::UnorderedSet image_set(data, /*make_copy_of_data=*/ false, &read_count);
1517 image_set.swap(image_interns);
1518 }
1519 size_t num_recorded_refs = 0u;
1520 VisitInternedStringReferences(
1521 space,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001522 [&image_interns, &num_recorded_refs](ObjPtr<mirror::String> str)
1523 REQUIRES_SHARED(Locks::mutator_lock_) {
1524 auto it = image_interns.find(GcRoot<mirror::String>(str));
1525 CHECK(it != image_interns.end());
1526 CHECK(it->Read() == str);
1527 ++num_recorded_refs;
1528 return str;
1529 });
1530 size_t num_found_refs = CountInternedStringReferences(*space, image_interns);
1531 CHECK_EQ(num_recorded_refs, num_found_refs);
Chris Wailes0c61be42018-09-26 17:27:34 -07001532}
1533
Andreas Gampe2af99022017-04-25 08:32:59 -07001534// new_class_set is the set of classes that were read from the class table section in the image.
1535// If there was no class table section, it is null.
1536// Note: using a class here to avoid having to make ClassLinker internals public.
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001537class AppImageLoadingHelper {
Andreas Gampe2af99022017-04-25 08:32:59 -07001538 public:
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001539 static void Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001540 ClassLinker* class_linker,
1541 gc::space::ImageSpace* space,
1542 Handle<mirror::ClassLoader> class_loader,
David Srbecky86d6cd52020-12-02 18:13:10 +00001543 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches)
Andreas Gampe2af99022017-04-25 08:32:59 -07001544 REQUIRES(!Locks::dex_lock_)
1545 REQUIRES_SHARED(Locks::mutator_lock_);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001546
Chris Wailesfbeef462018-10-19 14:16:35 -07001547 static void HandleAppImageStrings(gc::space::ImageSpace* space)
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001548 REQUIRES_SHARED(Locks::mutator_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07001549};
1550
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001551void AppImageLoadingHelper::Update(
Andreas Gampe2af99022017-04-25 08:32:59 -07001552 ClassLinker* class_linker,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001553 gc::space::ImageSpace* space,
1554 Handle<mirror::ClassLoader> class_loader,
David Srbecky86d6cd52020-12-02 18:13:10 +00001555 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches)
Andreas Gampe2af99022017-04-25 08:32:59 -07001556 REQUIRES(!Locks::dex_lock_)
1557 REQUIRES_SHARED(Locks::mutator_lock_) {
Chris Wailes23866362018-08-22 16:16:58 -07001558 ScopedTrace app_image_timing("AppImage:Updating");
1559
Vladimir Marko8e05f092019-06-10 11:10:38 +01001560 if (kIsDebugBuild && ClassLinker::kAppImageMayContainStrings) {
1561 // In debug build, verify the string references before applying
1562 // the Runtime::LoadAppImageStartupCache() option.
1563 VerifyInternedStringReferences(space);
1564 }
1565
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001566 Thread* const self = Thread::Current();
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001567 Runtime* const runtime = Runtime::Current();
1568 gc::Heap* const heap = runtime->GetHeap();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001569 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001570 {
Vladimir Marko0f3c7002017-09-07 14:15:56 +01001571 // Register dex caches with the class loader.
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001572 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Alex Lighta9bbc082019-11-14 14:51:41 -08001573 for (auto dex_cache : dex_caches.Iterate<mirror::DexCache>()) {
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001574 const DexFile* const dex_file = dex_cache->GetDexFile();
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001575 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001576 WriterMutexLock mu2(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08001577 CHECK(class_linker->FindDexCacheDataLocked(*dex_file) == nullptr);
Andreas Gampe2af99022017-04-25 08:32:59 -07001578 class_linker->RegisterDexFileLocked(*dex_file, dex_cache, class_loader.Get());
Mathieu Chartier064e9d42016-03-07 17:41:39 -08001579 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001580 }
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001581 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001582
Mathieu Chartier0933cc52018-03-23 14:25:08 -07001583 if (ClassLinker::kAppImageMayContainStrings) {
Chris Wailesfbeef462018-10-19 14:16:35 -07001584 HandleAppImageStrings(space);
Chang Xingba17dbd2017-06-28 21:27:56 +00001585 }
Chris Wailes0c61be42018-09-26 17:27:34 -07001586
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001587 if (kVerifyArtMethodDeclaringClasses) {
Chris Wailes23866362018-08-22 16:16:58 -07001588 ScopedTrace timing("AppImage:VerifyDeclaringClasses");
Mathieu Chartiera0b95212016-03-07 16:13:54 -08001589 ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001590 gc::accounting::HeapBitmap* live_bitmap = heap->GetLiveBitmap();
1591 header.VisitPackedArtMethods([&](ArtMethod& method)
1592 REQUIRES_SHARED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1593 ObjPtr<mirror::Class> klass = method.GetDeclaringClassUnchecked();
1594 if (klass != nullptr) {
1595 CHECK(live_bitmap->Test(klass.Ptr())) << "Image method has unmarked declaring class";
1596 }
1597 }, space->Begin(), kRuntimePointerSize);
Mathieu Chartier03c1dd92016-03-07 16:13:54 -08001598 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001599}
1600
Chris Wailesfbeef462018-10-19 14:16:35 -07001601void AppImageLoadingHelper::HandleAppImageStrings(gc::space::ImageSpace* space) {
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001602 // Iterate over the string reference offsets stored in the image and intern
1603 // the strings they point to.
1604 ScopedTrace timing("AppImage:InternString");
1605
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001606 Runtime* const runtime = Runtime::Current();
1607 InternTable* const intern_table = runtime->GetInternTable();
1608
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001609 // Add the intern table, removing any conflicts. For conflicts, store the new address in a map
1610 // for faster lookup.
1611 // TODO: Optimize with a bitmap or bloom filter
1612 SafeMap<mirror::String*, mirror::String*> intern_remap;
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001613 auto func = [&](InternTable::UnorderedSet& interns)
Mathieu Chartier41c08082018-10-31 11:50:26 -07001614 REQUIRES_SHARED(Locks::mutator_lock_)
1615 REQUIRES(Locks::intern_table_lock_) {
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001616 const size_t non_boot_image_strings = intern_table->CountInterns(
1617 /*visit_boot_images=*/false,
1618 /*visit_non_boot_images=*/true);
Chris Wailesfbeef462018-10-19 14:16:35 -07001619 VLOG(image) << "AppImage:stringsInInternTableSize = " << interns.size();
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001620 VLOG(image) << "AppImage:nonBootImageInternStrings = " << non_boot_image_strings;
1621 // Visit the smaller of the two sets to compute the intersection.
1622 if (interns.size() < non_boot_image_strings) {
1623 for (auto it = interns.begin(); it != interns.end(); ) {
1624 ObjPtr<mirror::String> string = it->Read();
1625 ObjPtr<mirror::String> existing = intern_table->LookupWeakLocked(string);
1626 if (existing == nullptr) {
1627 existing = intern_table->LookupStrongLocked(string);
1628 }
1629 if (existing != nullptr) {
1630 intern_remap.Put(string.Ptr(), existing.Ptr());
1631 it = interns.erase(it);
1632 } else {
1633 ++it;
1634 }
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001635 }
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001636 } else {
1637 intern_table->VisitInterns([&](const GcRoot<mirror::String>& root)
1638 REQUIRES_SHARED(Locks::mutator_lock_)
1639 REQUIRES(Locks::intern_table_lock_) {
1640 auto it = interns.find(root);
1641 if (it != interns.end()) {
1642 ObjPtr<mirror::String> existing = root.Read();
1643 intern_remap.Put(it->Read(), existing.Ptr());
1644 it = interns.erase(it);
1645 }
1646 }, /*visit_boot_images=*/false, /*visit_non_boot_images=*/true);
1647 }
David Srbecky346fd962020-07-27 16:51:00 +01001648 // Consistency check to ensure correctness.
Mathieu Chartier8fc75582018-11-01 14:21:33 -07001649 if (kIsDebugBuild) {
1650 for (GcRoot<mirror::String>& root : interns) {
1651 ObjPtr<mirror::String> string = root.Read();
1652 CHECK(intern_table->LookupWeakLocked(string) == nullptr) << string->ToModifiedUtf8();
1653 CHECK(intern_table->LookupStrongLocked(string) == nullptr) << string->ToModifiedUtf8();
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001654 }
1655 }
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001656 };
Vladimir Marko8e05f092019-06-10 11:10:38 +01001657 intern_table->AddImageStringsToTable(space, func);
1658 if (!intern_remap.empty()) {
Mathieu Chartiera88abfa2019-02-04 11:08:29 -08001659 VLOG(image) << "AppImage:conflictingInternStrings = " << intern_remap.size();
Vladimir Marko8e05f092019-06-10 11:10:38 +01001660 VisitInternedStringReferences(
1661 space,
Vladimir Marko8e05f092019-06-10 11:10:38 +01001662 [&intern_remap](ObjPtr<mirror::String> str) REQUIRES_SHARED(Locks::mutator_lock_) {
1663 auto it = intern_remap.find(str.Ptr());
1664 if (it != intern_remap.end()) {
1665 return ObjPtr<mirror::String>(it->second);
1666 }
1667 return str;
1668 });
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001669 }
1670}
1671
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001672static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file,
1673 const char* location,
1674 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001675 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001676 DCHECK(error_msg != nullptr);
1677 std::unique_ptr<const DexFile> dex_file;
Andreas Gampeb40d3612018-06-26 15:49:42 -07001678 const OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr, error_msg);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001679 if (oat_dex_file == nullptr) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001680 return std::unique_ptr<const DexFile>();
1681 }
1682 std::string inner_error_msg;
1683 dex_file = oat_dex_file->OpenDexFile(&inner_error_msg);
1684 if (dex_file == nullptr) {
1685 *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'",
1686 location,
1687 oat_file->GetLocation().c_str(),
1688 inner_error_msg.c_str());
1689 return std::unique_ptr<const DexFile>();
1690 }
1691
1692 if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) {
1693 *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x",
1694 location,
1695 dex_file->GetLocationChecksum(),
1696 oat_dex_file->GetDexFileLocationChecksum());
1697 return std::unique_ptr<const DexFile>();
1698 }
1699 return dex_file;
1700}
1701
1702bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space,
1703 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1704 std::string* error_msg) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07001705 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001706 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001707 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001708 DCHECK(dex_caches_object != nullptr);
Vladimir Marko4617d582019-03-28 13:48:31 +00001709 ObjPtr<mirror::ObjectArray<mirror::DexCache>> dex_caches =
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001710 dex_caches_object->AsObjectArray<mirror::DexCache>();
1711 const OatFile* oat_file = space->GetOatFile();
Alex Lighta9bbc082019-11-14 14:51:41 -08001712 for (auto dex_cache : dex_caches->Iterate()) {
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001713 std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1714 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1715 dex_file_location.c_str(),
1716 error_msg);
1717 if (dex_file == nullptr) {
1718 return false;
1719 }
1720 dex_cache->SetDexFile(dex_file.get());
1721 out_dex_files->push_back(std::move(dex_file));
1722 }
1723 return true;
1724}
1725
Andreas Gampe0793bec2016-12-01 11:37:33 -08001726// Helper class for ArtMethod checks when adding an image. Keeps all required functionality
1727// together and caches some intermediate results.
Orion Hodson5880c772020-07-28 20:12:08 +01001728class ImageChecker final {
Andreas Gampe0793bec2016-12-01 11:37:33 -08001729 public:
1730 static void CheckObjects(gc::Heap* heap, ClassLinker* class_linker)
1731 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodson5880c772020-07-28 20:12:08 +01001732 ImageChecker ic(heap, class_linker);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001733 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1734 DCHECK(obj != nullptr);
1735 CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
1736 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
1737 if (obj->IsClass()) {
1738 auto klass = obj->AsClass();
1739 for (ArtField& field : klass->GetIFields()) {
1740 CHECK_EQ(field.GetDeclaringClass(), klass);
1741 }
1742 for (ArtField& field : klass->GetSFields()) {
1743 CHECK_EQ(field.GetDeclaringClass(), klass);
1744 }
Orion Hodson5880c772020-07-28 20:12:08 +01001745 const PointerSize pointer_size = ic.pointer_size_;
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001746 for (ArtMethod& m : klass->GetMethods(pointer_size)) {
Orion Hodson5880c772020-07-28 20:12:08 +01001747 ic.CheckArtMethod(&m, klass);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001748 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001749 ObjPtr<mirror::PointerArray> vtable = klass->GetVTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001750 if (vtable != nullptr) {
Orion Hodson5880c772020-07-28 20:12:08 +01001751 ic.CheckArtMethodPointerArray(vtable, nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001752 }
1753 if (klass->ShouldHaveImt()) {
1754 ImTable* imt = klass->GetImt(pointer_size);
1755 for (size_t i = 0; i < ImTable::kSize; ++i) {
Orion Hodson5880c772020-07-28 20:12:08 +01001756 ic.CheckArtMethod(imt->Get(i, pointer_size), nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001757 }
1758 }
1759 if (klass->ShouldHaveEmbeddedVTable()) {
1760 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
Orion Hodson5880c772020-07-28 20:12:08 +01001761 ic.CheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001762 }
1763 }
Vladimir Markoc524e9e2019-03-26 10:54:50 +00001764 ObjPtr<mirror::IfTable> iftable = klass->GetIfTable();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001765 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1766 if (iftable->GetMethodArrayCount(i) > 0) {
Orion Hodson5880c772020-07-28 20:12:08 +01001767 ic.CheckArtMethodPointerArray(iftable->GetMethodArray(i), nullptr);
Andreas Gampe1c158a02017-07-13 17:26:19 -07001768 }
1769 }
1770 }
1771 };
1772 heap->VisitObjects(visitor);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001773 }
1774
Andreas Gampe0793bec2016-12-01 11:37:33 -08001775 private:
Orion Hodson5880c772020-07-28 20:12:08 +01001776 ImageChecker(gc::Heap* heap, ClassLinker* class_linker)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001777 : spaces_(heap->GetBootImageSpaces()),
1778 pointer_size_(class_linker->GetImagePointerSize()) {
1779 space_begin_.reserve(spaces_.size());
1780 method_sections_.reserve(spaces_.size());
1781 runtime_method_sections_.reserve(spaces_.size());
1782 for (gc::space::ImageSpace* space : spaces_) {
1783 space_begin_.push_back(space->Begin());
1784 auto& header = space->GetImageHeader();
1785 method_sections_.push_back(&header.GetMethodsSection());
1786 runtime_method_sections_.push_back(&header.GetRuntimeMethodsSection());
1787 }
1788 }
1789
Orion Hodson5880c772020-07-28 20:12:08 +01001790 void CheckArtMethod(ArtMethod* m, ObjPtr<mirror::Class> expected_class)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001791 REQUIRES_SHARED(Locks::mutator_lock_) {
1792 if (m->IsRuntimeMethod()) {
1793 ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClassUnchecked();
1794 CHECK(declaring_class == nullptr) << declaring_class << " " << m->PrettyMethod();
1795 } else if (m->IsCopied()) {
1796 CHECK(m->GetDeclaringClass() != nullptr) << m->PrettyMethod();
1797 } else if (expected_class != nullptr) {
1798 CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << m->PrettyMethod();
1799 }
1800 if (!spaces_.empty()) {
1801 bool contains = false;
1802 for (size_t i = 0; !contains && i != space_begin_.size(); ++i) {
1803 const size_t offset = reinterpret_cast<uint8_t*>(m) - space_begin_[i];
1804 contains = method_sections_[i]->Contains(offset) ||
1805 runtime_method_sections_[i]->Contains(offset);
1806 }
1807 CHECK(contains) << m << " not found";
1808 }
1809 }
1810
Orion Hodson5880c772020-07-28 20:12:08 +01001811 void CheckArtMethodPointerArray(ObjPtr<mirror::PointerArray> arr,
1812 ObjPtr<mirror::Class> expected_class)
Andreas Gampe0793bec2016-12-01 11:37:33 -08001813 REQUIRES_SHARED(Locks::mutator_lock_) {
1814 CHECK(arr != nullptr);
1815 for (int32_t j = 0; j < arr->GetLength(); ++j) {
1816 auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size_);
1817 // expected_class == null means we are a dex cache.
1818 if (expected_class != nullptr) {
1819 CHECK(method != nullptr);
1820 }
1821 if (method != nullptr) {
Orion Hodson5880c772020-07-28 20:12:08 +01001822 CheckArtMethod(method, expected_class);
Andreas Gampe0793bec2016-12-01 11:37:33 -08001823 }
1824 }
1825 }
1826
Andreas Gampe0793bec2016-12-01 11:37:33 -08001827 const std::vector<gc::space::ImageSpace*>& spaces_;
1828 const PointerSize pointer_size_;
1829
1830 // Cached sections from the spaces.
1831 std::vector<const uint8_t*> space_begin_;
1832 std::vector<const ImageSection*> method_sections_;
1833 std::vector<const ImageSection*> runtime_method_sections_;
1834};
1835
Andreas Gampebe7af222017-07-25 09:57:28 -07001836static void VerifyAppImage(const ImageHeader& header,
1837 const Handle<mirror::ClassLoader>& class_loader,
David Srbecky86d6cd52020-12-02 18:13:10 +00001838 ClassTable* class_table,
1839 gc::space::ImageSpace* space)
Andreas Gampebe7af222017-07-25 09:57:28 -07001840 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001841 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
1842 ObjPtr<mirror::Class> klass = method.GetDeclaringClass();
1843 if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
1844 CHECK_EQ(class_table->LookupByDescriptor(klass), klass)
1845 << mirror::Class::PrettyClass(klass);
1846 }
1847 }, space->Begin(), kRuntimePointerSize);
Andreas Gampebe7af222017-07-25 09:57:28 -07001848 {
1849 // Verify that all direct interfaces of classes in the class table are also resolved.
1850 std::vector<ObjPtr<mirror::Class>> classes;
1851 auto verify_direct_interfaces_in_table = [&](ObjPtr<mirror::Class> klass)
1852 REQUIRES_SHARED(Locks::mutator_lock_) {
1853 if (!klass->IsPrimitive() && klass->GetClassLoader() == class_loader.Get()) {
1854 classes.push_back(klass);
1855 }
1856 return true;
1857 };
1858 class_table->Visit(verify_direct_interfaces_in_table);
1859 Thread* self = Thread::Current();
1860 for (ObjPtr<mirror::Class> klass : classes) {
1861 for (uint32_t i = 0, num = klass->NumDirectInterfaces(); i != num; ++i) {
1862 CHECK(klass->GetDirectInterface(self, klass, i) != nullptr)
1863 << klass->PrettyDescriptor() << " iface #" << i;
1864 }
1865 }
1866 }
Andreas Gampebe7af222017-07-25 09:57:28 -07001867}
1868
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001869bool ClassLinker::AddImageSpace(
1870 gc::space::ImageSpace* space,
1871 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001872 std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1873 std::string* error_msg) {
1874 DCHECK(out_dex_files != nullptr);
1875 DCHECK(error_msg != nullptr);
1876 const uint64_t start_time = NanoTime();
Andreas Gampefa4333d2017-02-14 11:10:34 -08001877 const bool app_image = class_loader != nullptr;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001878 const ImageHeader& header = space->GetImageHeader();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07001879 ObjPtr<mirror::Object> dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001880 DCHECK(dex_caches_object != nullptr);
1881 Runtime* const runtime = Runtime::Current();
1882 gc::Heap* const heap = runtime->GetHeap();
1883 Thread* const self = Thread::Current();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001884 // Check that the image is what we are expecting.
1885 if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) {
1886 *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu",
1887 static_cast<size_t>(space->GetImageHeader().GetPointerSize()),
1888 image_pointer_size_);
1889 return false;
1890 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001891 size_t expected_image_roots = ImageHeader::NumberOfImageRoots(app_image);
1892 if (static_cast<size_t>(header.GetImageRoots()->GetLength()) != expected_image_roots) {
1893 *error_msg = StringPrintf("Expected %zu image roots but got %d",
1894 expected_image_roots,
1895 header.GetImageRoots()->GetLength());
1896 return false;
1897 }
1898 StackHandleScope<3> hs(self);
1899 Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
1900 hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
1901 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1902 header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>()));
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001903 MutableHandle<mirror::ClassLoader> image_class_loader(hs.NewHandle(
Vladimir Markof75613c2018-06-05 12:51:04 +01001904 app_image ? header.GetImageRoot(ImageHeader::kAppImageClassLoader)->AsClassLoader()
1905 : nullptr));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001906 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001907 if (class_roots->GetLength() != static_cast<int32_t>(ClassRoot::kMax)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001908 *error_msg = StringPrintf("Expected %d class roots but got %d",
1909 class_roots->GetLength(),
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001910 static_cast<int32_t>(ClassRoot::kMax));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001911 return false;
1912 }
1913 // Check against existing class roots to make sure they match the ones in the boot image.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01001914 ObjPtr<mirror::ObjectArray<mirror::Class>> existing_class_roots = GetClassRoots();
1915 for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
1916 if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i), existing_class_roots)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001917 *error_msg = "App image class roots must have pointer equality with runtime ones.";
1918 return false;
1919 }
1920 }
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001921 const OatFile* oat_file = space->GetOatFile();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001922 if (oat_file->GetOatHeader().GetDexFileCount() !=
1923 static_cast<uint32_t>(dex_caches->GetLength())) {
1924 *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from "
1925 "image";
1926 return false;
1927 }
1928
Alex Lighta9bbc082019-11-14 14:51:41 -08001929 for (auto dex_cache : dex_caches.Iterate<mirror::DexCache>()) {
David Brazdil3e8aae02019-03-26 18:48:02 +00001930 std::string dex_file_location = dex_cache->GetLocation()->ToModifiedUtf8();
Mathieu Chartierbcb6a722016-03-08 16:49:58 -08001931 std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1932 dex_file_location.c_str(),
1933 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001934 if (dex_file == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001935 return false;
1936 }
1937
David Srbecky86d6cd52020-12-02 18:13:10 +00001938 LinearAlloc* linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader.Get());
1939 DCHECK(linear_alloc != nullptr);
1940 DCHECK_EQ(linear_alloc == Runtime::Current()->GetLinearAlloc(), !app_image);
1941 {
1942 // Native fields are all null. Initialize them and allocate native memory.
1943 WriterMutexLock mu(self, *Locks::dex_lock_);
1944 dex_cache->InitializeNativeFields(dex_file.get(), linear_alloc);
1945 }
1946 if (!app_image) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001947 // Register dex files, keep track of existing ones that are conflicts.
Mathieu Chartier0a19e212019-11-27 14:35:24 -08001948 AppendToBootClassPath(dex_file.get(), dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001949 }
1950 out_dex_files->push_back(std::move(dex_file));
1951 }
1952
1953 if (app_image) {
1954 ScopedObjectAccessUnchecked soa(Thread::Current());
Nicolas Geoffrayf0d30022018-11-20 17:45:38 +00001955 ScopedAssertNoThreadSuspension sants("Checking app image", soa.Self());
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001956 if (IsBootClassLoader(soa, image_class_loader.Get())) {
1957 *error_msg = "Unexpected BootClassLoader in app image";
1958 return false;
1959 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001960 }
1961
Orion Hodson5880c772020-07-28 20:12:08 +01001962 if (kCheckImageObjects) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001963 if (!app_image) {
Orion Hodson5880c772020-07-28 20:12:08 +01001964 ImageChecker::CheckObjects(heap, this);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001965 }
1966 }
1967
1968 // Set entry point to interpreter if in InterpretOnly mode.
1969 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001970 // Set image methods' entry point to interpreter.
1971 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
1972 if (!method.IsRuntimeMethod()) {
1973 DCHECK(method.GetDeclaringClass() != nullptr);
Ulya Trafimovich5439f052020-07-29 10:03:46 +01001974 if (!method.IsNative() && !method.IsResolutionMethod()) {
1975 method.SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
1976 image_pointer_size_);
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001977 }
1978 }
1979 }, space->Begin(), image_pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001980 }
1981
Nicolas Geoffray47171752020-08-31 15:03:20 +01001982 if (!runtime->IsAotCompiler()) {
Nicolas Geoffraybd728b02021-01-27 13:21:35 +00001983 ScopedTrace trace("AppImage:UpdateCodeItemAndNterp");
Nicolas Geoffray47171752020-08-31 15:03:20 +01001984 bool can_use_nterp = interpreter::CanRuntimeUseNterp();
Nicolas Geoffray7e2c9632020-01-09 13:41:10 +00001985 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffray47171752020-08-31 15:03:20 +01001986 // In the image, the `data` pointer field of the ArtMethod contains the code
1987 // item offset. Change this to the actual pointer to the code item.
1988 if (method.HasCodeItem()) {
1989 const dex::CodeItem* code_item = method.GetDexFile()->GetCodeItem(
1990 reinterpret_cast32<uint32_t>(method.GetDataPtrSize(image_pointer_size_)));
Nicolas Geoffraye1d2dce2020-09-21 10:06:31 +01001991 method.SetCodeItem(code_item);
Nicolas Geoffray47171752020-08-31 15:03:20 +01001992 }
1993 // Set image methods' entry point that point to the interpreter bridge to the
1994 // nterp entry point.
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001995 if (method.GetEntryPointFromQuickCompiledCode() == nterp_trampoline_) {
1996 if (can_use_nterp) {
Nicolas Geoffrayb1cf8372021-02-02 13:32:20 +00001997 DCHECK(!NeedsClinitCheckBeforeCall(&method) ||
1998 method.GetDeclaringClass()->IsVisiblyInitialized());
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00001999 method.SetEntryPointFromQuickCompiledCode(interpreter::GetNterpEntryPoint());
2000 } else {
2001 method.SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2002 }
Nicolas Geoffray47171752020-08-31 15:03:20 +01002003 }
Nicolas Geoffray7e2c9632020-01-09 13:41:10 +00002004 }, space->Begin(), image_pointer_size_);
2005 }
2006
Nicolas Geoffray8c41a0b2020-02-06 16:52:11 +00002007 if (runtime->IsVerificationSoftFail()) {
2008 header.VisitPackedArtMethods([&](ArtMethod& method) REQUIRES_SHARED(Locks::mutator_lock_) {
2009 if (!method.IsNative() && method.IsInvokable()) {
2010 method.ClearSkipAccessChecks();
2011 }
2012 }, space->Begin(), image_pointer_size_);
2013 }
2014
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002015 ClassTable* class_table = nullptr;
2016 {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002017 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002018 class_table = InsertClassTableForClassLoader(class_loader.Get());
Mathieu Chartier69731002016-03-02 16:08:31 -08002019 }
2020 // If we have a class table section, read it and use it for verification in
2021 // UpdateAppImageClassLoadersAndDexCaches.
2022 ClassTable::ClassSet temp_set;
Vladimir Marko0f3c7002017-09-07 14:15:56 +01002023 const ImageSection& class_table_section = header.GetClassTableSection();
Mathieu Chartier69731002016-03-02 16:08:31 -08002024 const bool added_class_table = class_table_section.Size() > 0u;
2025 if (added_class_table) {
2026 const uint64_t start_time2 = NanoTime();
2027 size_t read_count = 0;
2028 temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
2029 /*make copy*/false,
2030 &read_count);
Mathieu Chartier69731002016-03-02 16:08:31 -08002031 VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002032 }
2033 if (app_image) {
David Srbecky86d6cd52020-12-02 18:13:10 +00002034 AppImageLoadingHelper::Update(this, space, class_loader, dex_caches);
Mathieu Chartier456b4922018-11-06 10:35:48 -08002035
2036 {
2037 ScopedTrace trace("AppImage:UpdateClassLoaders");
2038 // Update class loader and resolved strings. If added_class_table is false, the resolved
2039 // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002040 ObjPtr<mirror::ClassLoader> loader(class_loader.Get());
Mathieu Chartier456b4922018-11-06 10:35:48 -08002041 for (const ClassTable::TableSlot& root : temp_set) {
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002042 // Note: We probably don't need the read barrier unless we copy the app image objects into
2043 // the region space.
2044 ObjPtr<mirror::Class> klass(root.Read());
2045 // Do not update class loader for boot image classes where the app image
2046 // class loader is only the initiating loader but not the defining loader.
2047 // Avoid read barrier since we are comparing against null.
2048 if (klass->GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>() != nullptr) {
Vladimir Markob68bb7a2020-03-17 10:55:25 +00002049 klass->SetClassLoader(loader);
Mathieu Chartierbc1e0fa2018-11-14 16:18:18 -08002050 }
Mathieu Chartier456b4922018-11-06 10:35:48 -08002051 }
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002052 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002053
Vladimir Marko305c38b2018-02-14 11:50:07 +00002054 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07002055 // Every class in the app image has initially SubtypeCheckInfo in the
2056 // Uninitialized state.
2057 //
2058 // The SubtypeCheck invariants imply that a SubtypeCheckInfo is at least Initialized
2059 // after class initialization is complete. The app image ClassStatus as-is
2060 // are almost all ClassStatus::Initialized, and being in the
2061 // SubtypeCheckInfo::kUninitialized state is violating that invariant.
2062 //
2063 // Force every app image class's SubtypeCheck to be at least kIninitialized.
2064 //
2065 // See also ImageWriter::FixupClass.
Chris Wailes23866362018-08-22 16:16:58 -07002066 ScopedTrace trace("AppImage:RecacluateSubtypeCheckBitstrings");
Igor Murashkin86083f72017-10-27 10:59:04 -07002067 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
2068 for (const ClassTable::TableSlot& root : temp_set) {
Vladimir Marko38b8b252018-01-02 19:07:06 +00002069 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(root.Read());
Igor Murashkin86083f72017-10-27 10:59:04 -07002070 }
2071 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002072 }
2073 if (!oat_file->GetBssGcRoots().empty()) {
2074 // Insert oat file to class table for visiting .bss GC roots.
2075 class_table->InsertOatFile(oat_file);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002076 }
Igor Murashkin86083f72017-10-27 10:59:04 -07002077
Mathieu Chartier69731002016-03-02 16:08:31 -08002078 if (added_class_table) {
2079 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2080 class_table->AddClassSet(std::move(temp_set));
2081 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002082
Mathieu Chartier69731002016-03-02 16:08:31 -08002083 if (kIsDebugBuild && app_image) {
2084 // This verification needs to happen after the classes have been added to the class loader.
2085 // Since it ensures classes are in the class table.
Chris Wailes23866362018-08-22 16:16:58 -07002086 ScopedTrace trace("AppImage:Verify");
David Srbecky86d6cd52020-12-02 18:13:10 +00002087 VerifyAppImage(header, class_loader, class_table, space);
Mathieu Chartier69731002016-03-02 16:08:31 -08002088 }
Andreas Gampebe7af222017-07-25 09:57:28 -07002089
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002090 VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
Andreas Gampe3db9c5d2015-11-17 11:52:46 -08002091 return true;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002092}
2093
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002094bool ClassLinker::ClassInClassTable(ObjPtr<mirror::Class> klass) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002095 ClassTable* const class_table = ClassTableForClassLoader(klass->GetClassLoader());
2096 return class_table != nullptr && class_table->Contains(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002097}
2098
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002099void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002100 // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
2101 // enabling tracing requires the mutator lock, there are no race conditions here.
2102 const bool tracing_enabled = Trace::IsTracingEnabled();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002103 Thread* const self = Thread::Current();
2104 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002105 if (kUseReadBarrier) {
2106 // We do not track new roots for CC.
2107 DCHECK_EQ(0, flags & (kVisitRootFlagNewRoots |
2108 kVisitRootFlagClearRootLog |
2109 kVisitRootFlagStartLoggingNewRoots |
2110 kVisitRootFlagStopLoggingNewRoots));
2111 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002112 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002113 // Argument for how root visiting deals with ArtField and ArtMethod roots.
2114 // There is 3 GC cases to handle:
2115 // Non moving concurrent:
2116 // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002117 // live by the class and class roots.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002118 //
2119 // Moving non-concurrent:
2120 // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
2121 // To prevent missing roots, this case needs to ensure that there is no
2122 // suspend points between the point which we allocate ArtMethod arrays and place them in a
2123 // class which is in the class table.
2124 //
2125 // Moving concurrent:
2126 // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
2127 // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08002128 //
2129 // Use an unbuffered visitor since the class table uses a temporary GcRoot for holding decoded
2130 // ClassTable::TableSlot. The buffered root visiting would access a stale stack location for
2131 // these objects.
2132 UnbufferedRootVisitor root_visitor(visitor, RootInfo(kRootStickyClass));
Andreas Gampe2af99022017-04-25 08:32:59 -07002133 boot_class_table_->VisitRoots(root_visitor);
Mathieu Chartier7778b882015-10-05 16:41:10 -07002134 // If tracing is enabled, then mark all the class loaders to prevent unloading.
neo.chaea2d1b282016-11-08 08:40:46 +09002135 if ((flags & kVisitRootFlagClassLoader) != 0 || tracing_enabled) {
Mathieu Chartier7778b882015-10-05 16:41:10 -07002136 for (const ClassLoaderData& data : class_loaders_) {
2137 GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
2138 root.VisitRoot(visitor, RootInfo(kRootVMInternal));
2139 }
2140 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002141 } else if (!kUseReadBarrier && (flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002142 for (auto& root : new_class_roots_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002143 ObjPtr<mirror::Class> old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002144 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002145 ObjPtr<mirror::Class> new_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002146 // Concurrent moving GC marked new roots through the to-space invariant.
2147 CHECK_EQ(new_ref, old_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002148 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00002149 for (const OatFile* oat_file : new_bss_roots_boot_oat_files_) {
2150 for (GcRoot<mirror::Object>& root : oat_file->GetBssGcRoots()) {
2151 ObjPtr<mirror::Object> old_ref = root.Read<kWithoutReadBarrier>();
2152 if (old_ref != nullptr) {
2153 DCHECK(old_ref->IsClass());
2154 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
2155 ObjPtr<mirror::Object> new_ref = root.Read<kWithoutReadBarrier>();
2156 // Concurrent moving GC marked new roots through the to-space invariant.
2157 CHECK_EQ(new_ref, old_ref);
2158 }
2159 }
2160 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002161 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002162 if (!kUseReadBarrier && (flags & kVisitRootFlagClearRootLog) != 0) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002163 new_class_roots_.clear();
Vladimir Marko1998cd02017-01-13 13:02:58 +00002164 new_bss_roots_boot_oat_files_.clear();
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002165 }
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002166 if (!kUseReadBarrier && (flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002167 log_new_roots_ = true;
Vladimir Marko9b03cb42017-02-16 16:37:03 +00002168 } else if (!kUseReadBarrier && (flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
Vladimir Marko1998cd02017-01-13 13:02:58 +00002169 log_new_roots_ = false;
Mathieu Chartier52e4b432014-06-10 11:22:31 -07002170 }
2171 // We deliberately ignore the class roots in the image since we
2172 // handle image roots by using the MS/CMS rescanning of dirty cards.
2173}
2174
Brian Carlstroma663ea52011-08-19 23:33:41 -07002175// Keep in sync with InitCallback. Anything we visit, we need to
2176// reinit references to when reinitializing a ClassLinker from a
2177// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002178void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier31000802015-06-14 14:14:37 -07002179 class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002180 VisitClassRoots(visitor, flags);
Mathieu Chartier6cfc2c02015-10-12 15:06:16 -07002181 // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
2182 // unloading if we are marking roots.
2183 DropFindArrayClassCache();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002184}
2185
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002186class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
2187 public:
2188 explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
2189 : visitor_(visitor),
2190 done_(false) {}
2191
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002192 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002193 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002194 ClassTable* const class_table = class_loader->GetClassTable();
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002195 if (!done_ && class_table != nullptr) {
2196 DefiningClassLoaderFilterVisitor visitor(class_loader, visitor_);
2197 if (!class_table->Visit(visitor)) {
2198 // If the visitor ClassTable returns false it means that we don't need to continue.
2199 done_ = true;
2200 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002201 }
2202 }
2203
2204 private:
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002205 // Class visitor that limits the class visits from a ClassTable to the classes with
2206 // the provided defining class loader. This filter is used to avoid multiple visits
2207 // of the same class which can be recorded for multiple initiating class loaders.
2208 class DefiningClassLoaderFilterVisitor : public ClassVisitor {
2209 public:
2210 DefiningClassLoaderFilterVisitor(ObjPtr<mirror::ClassLoader> defining_class_loader,
2211 ClassVisitor* visitor)
2212 : defining_class_loader_(defining_class_loader), visitor_(visitor) { }
2213
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002214 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002215 if (klass->GetClassLoader() != defining_class_loader_) {
2216 return true;
2217 }
2218 return (*visitor_)(klass);
2219 }
2220
Vladimir Marko0984e482019-03-27 16:41:41 +00002221 const ObjPtr<mirror::ClassLoader> defining_class_loader_;
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002222 ClassVisitor* const visitor_;
2223 };
2224
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002225 ClassVisitor* const visitor_;
2226 // If done is true then we don't need to do any more visiting.
2227 bool done_;
2228};
2229
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002230void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
Andreas Gampe2af99022017-04-25 08:32:59 -07002231 if (boot_class_table_->Visit(*visitor)) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002232 VisitClassLoaderClassesVisitor loader_visitor(visitor);
2233 VisitClassLoaders(&loader_visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002234 }
2235}
2236
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002237void ClassLinker::VisitClasses(ClassVisitor* visitor) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002238 Thread* const self = Thread::Current();
2239 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
2240 // Not safe to have thread suspension when we are holding a lock.
2241 if (self != nullptr) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002242 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002243 VisitClassesInternal(visitor);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07002244 } else {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002245 VisitClassesInternal(visitor);
Elliott Hughesa2155262011-11-16 16:26:58 -08002246 }
2247}
2248
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002249class GetClassesInToVector : public ClassVisitor {
2250 public:
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002251 bool operator()(ObjPtr<mirror::Class> klass) override {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002252 classes_.push_back(klass);
2253 return true;
2254 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002255 std::vector<ObjPtr<mirror::Class>> classes_;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002256};
2257
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002258class GetClassInToObjectArray : public ClassVisitor {
2259 public:
2260 explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
2261 : arr_(arr), index_(0) {}
2262
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002263 bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002264 ++index_;
2265 if (index_ <= arr_->GetLength()) {
2266 arr_->Set(index_ - 1, klass);
2267 return true;
2268 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002269 return false;
2270 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002271
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002272 bool Succeeded() const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002273 return index_ <= arr_->GetLength();
2274 }
2275
2276 private:
2277 mirror::ObjectArray<mirror::Class>* const arr_;
2278 int32_t index_;
2279};
2280
2281void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002282 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
2283 // is avoiding duplicates.
2284 if (!kMovingClasses) {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002285 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002286 GetClassesInToVector accumulator;
2287 VisitClasses(&accumulator);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002288 for (ObjPtr<mirror::Class> klass : accumulator.classes_) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002289 if (!visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002290 return;
2291 }
2292 }
2293 } else {
Mathieu Chartier268764d2016-09-13 12:09:38 -07002294 Thread* const self = Thread::Current();
Ian Rogersdbf3be02014-08-29 15:40:08 -07002295 StackHandleScope<1> hs(self);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002296 auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002297 // We size the array assuming classes won't be added to the class table during the visit.
2298 // If this assumption fails we iterate again.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002299 while (true) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002300 size_t class_table_size;
2301 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002302 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002303 // Add 100 in case new classes get loaded when we are filling in the object array.
2304 class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
Ian Rogersdbf3be02014-08-29 15:40:08 -07002305 }
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002306 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Ian Rogersdbf3be02014-08-29 15:40:08 -07002307 classes.Assign(
2308 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002309 CHECK(classes != nullptr); // OOME.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -07002310 GetClassInToObjectArray accumulator(classes.Get());
2311 VisitClasses(&accumulator);
2312 if (accumulator.Succeeded()) {
2313 break;
2314 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07002315 }
2316 for (int32_t i = 0; i < classes->GetLength(); ++i) {
2317 // If the class table shrank during creation of the clases array we expect null elements. If
2318 // the class table grew then the loop repeats. If classes are created after the loop has
2319 // finished then we don't visit.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002320 ObjPtr<mirror::Class> klass = classes->Get(i);
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08002321 if (klass != nullptr && !visitor->operator()(klass)) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07002322 return;
2323 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002324 }
2325 }
2326}
2327
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002328ClassLinker::~ClassLinker() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002329 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07002330 for (const ClassLoaderData& data : class_loaders_) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002331 // CHA unloading analysis is not needed. No negative consequences are expected because
2332 // all the classloaders are deleted at the same time.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002333 DeleteClassLoader(self, data, /*cleanup_cha=*/ false);
Mathieu Chartier6b069532015-08-05 15:08:12 -07002334 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07002335 class_loaders_.clear();
Vladimir Markobf121912019-06-04 13:49:05 +01002336 while (!running_visibly_initialized_callbacks_.empty()) {
2337 std::unique_ptr<VisiblyInitializedCallback> callback(
2338 std::addressof(running_visibly_initialized_callbacks_.front()));
2339 running_visibly_initialized_callbacks_.pop_front();
2340 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002341}
2342
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002343void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data, bool cleanup_cha) {
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002344 Runtime* const runtime = Runtime::Current();
2345 JavaVMExt* const vm = runtime->GetJavaVM();
2346 vm->DeleteWeakGlobalRef(self, data.weak_root);
Calin Juravlee5de54c2016-04-20 14:22:09 +01002347 // Notify the JIT that we need to remove the methods and/or profiling info.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002348 if (runtime->GetJit() != nullptr) {
2349 jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2350 if (code_cache != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002351 // For the JIT case, RemoveMethodsIn removes the CHA dependencies.
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002352 code_cache->RemoveMethodsIn(self, *data.allocator);
2353 }
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002354 } else if (cha_ != nullptr) {
Mathieu Chartiercf79cf52017-07-21 11:17:57 -07002355 // If we don't have a JIT, we need to manually remove the CHA dependencies manually.
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07002356 cha_->RemoveDependenciesForLinearAlloc(data.allocator);
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002357 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002358 // Cleanup references to single implementation ArtMethods that will be deleted.
2359 if (cleanup_cha) {
2360 CHAOnDeleteUpdateClassVisitor visitor(data.allocator);
2361 data.class_table->Visit<CHAOnDeleteUpdateClassVisitor, kWithoutReadBarrier>(visitor);
2362 }
Vladimir Marko86c87522020-05-11 16:55:55 +01002363 {
2364 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
2365 auto end = critical_native_code_with_clinit_check_.end();
2366 for (auto it = critical_native_code_with_clinit_check_.begin(); it != end; ) {
2367 if (data.allocator->ContainsUnsafe(it->first)) {
2368 it = critical_native_code_with_clinit_check_.erase(it);
2369 } else {
2370 ++it;
2371 }
2372 }
2373 }
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +03002374
Nicolas Geoffray1dad3f62015-10-23 14:59:54 +01002375 delete data.allocator;
2376 delete data.class_table;
2377}
2378
Vladimir Markobcf17522018-06-01 13:14:32 +01002379ObjPtr<mirror::PointerArray> ClassLinker::AllocPointerArray(Thread* self, size_t length) {
2380 return ObjPtr<mirror::PointerArray>::DownCast(
Andreas Gampe542451c2016-07-26 09:02:02 -07002381 image_pointer_size_ == PointerSize::k64
Vladimir Markobcf17522018-06-01 13:14:32 +01002382 ? ObjPtr<mirror::Array>(mirror::LongArray::Alloc(self, length))
2383 : ObjPtr<mirror::Array>(mirror::IntArray::Alloc(self, length)));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002384}
2385
David Srbecky86d6cd52020-12-02 18:13:10 +00002386ObjPtr<mirror::DexCache> ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002387 StackHandleScope<1> hs(self);
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07002388 auto dex_cache(hs.NewHandle(ObjPtr<mirror::DexCache>::DownCast(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002389 GetClassRoot<mirror::DexCache>(this)->AllocObject(self))));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002390 if (dex_cache == nullptr) {
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002391 self->AssertPendingOOMException();
2392 return nullptr;
2393 }
Vladimir Marko31c3daa2019-06-13 12:18:37 +01002394 // Use InternWeak() so that the location String can be collected when the ClassLoader
2395 // with this DexCache is collected.
2396 ObjPtr<mirror::String> location = intern_table_->InternWeak(dex_file.GetLocation().c_str());
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002397 if (location == nullptr) {
2398 self->AssertPendingOOMException();
2399 return nullptr;
2400 }
David Srbecky86d6cd52020-12-02 18:13:10 +00002401 dex_cache->SetLocation(location);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002402 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07002403}
2404
Vladimir Markobcf17522018-06-01 13:14:32 +01002405ObjPtr<mirror::DexCache> ClassLinker::AllocAndInitializeDexCache(Thread* self,
2406 const DexFile& dex_file,
2407 LinearAlloc* linear_alloc) {
David Srbecky86d6cd52020-12-02 18:13:10 +00002408 ObjPtr<mirror::DexCache> dex_cache = AllocDexCache(self, dex_file);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002409 if (dex_cache != nullptr) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08002410 WriterMutexLock mu(self, *Locks::dex_lock_);
David Srbecky86d6cd52020-12-02 18:13:10 +00002411 dex_cache->InitializeNativeFields(&dex_file, linear_alloc);
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002412 }
Vladimir Markobcf17522018-06-01 13:14:32 +01002413 return dex_cache;
Mathieu Chartier6c60d842016-09-15 10:24:43 -07002414}
2415
Vladimir Marko70e2a762019-07-12 16:49:00 +01002416template <bool kMovable, typename PreFenceVisitor>
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002417ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2418 ObjPtr<mirror::Class> java_lang_Class,
Vladimir Marko70e2a762019-07-12 16:49:00 +01002419 uint32_t class_size,
2420 const PreFenceVisitor& pre_fence_visitor) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002421 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07002422 gc::Heap* heap = Runtime::Current()->GetHeap();
Roland Levillain0e840272018-08-23 19:55:30 +01002423 ObjPtr<mirror::Object> k = (kMovingClasses && kMovable) ?
Vladimir Marko70e2a762019-07-12 16:49:00 +01002424 heap->AllocObject(self, java_lang_Class, class_size, pre_fence_visitor) :
2425 heap->AllocNonMovableObject(self, java_lang_Class, class_size, pre_fence_visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08002426 if (UNLIKELY(k == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002427 self->AssertPendingOOMException();
Ian Rogers6fac4472014-02-25 17:01:10 -08002428 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002429 }
Ian Rogers6fac4472014-02-25 17:01:10 -08002430 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07002431}
2432
Vladimir Marko70e2a762019-07-12 16:49:00 +01002433template <bool kMovable>
2434ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self,
2435 ObjPtr<mirror::Class> java_lang_Class,
2436 uint32_t class_size) {
2437 mirror::Class::InitializeClassVisitor visitor(class_size);
2438 return AllocClass<kMovable>(self, java_lang_Class, class_size, visitor);
2439}
2440
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002441ObjPtr<mirror::Class> ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002442 return AllocClass(self, GetClassRoot<mirror::Class>(this), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07002443}
2444
Vladimir Marko70e2a762019-07-12 16:49:00 +01002445void ClassLinker::AllocPrimitiveArrayClass(Thread* self,
2446 ClassRoot primitive_root,
2447 ClassRoot array_root) {
Roland Levillain0e840272018-08-23 19:55:30 +01002448 // We make this class non-movable for the unlikely case where it were to be
2449 // moved by a sticky-bit (minor) collection when using the Generational
2450 // Concurrent Copying (CC) collector, potentially creating a stale reference
2451 // in the `klass_` field of one of its instances allocated in the Large-Object
2452 // Space (LOS) -- see the comment about the dirty card scanning logic in
2453 // art::gc::collector::ConcurrentCopying::MarkingPhase.
Vladimir Marko70e2a762019-07-12 16:49:00 +01002454 ObjPtr<mirror::Class> array_class = AllocClass</* kMovable= */ false>(
2455 self, GetClassRoot<mirror::Class>(this), mirror::Array::ClassSize(image_pointer_size_));
2456 ObjPtr<mirror::Class> component_type = GetClassRoot(primitive_root, this);
2457 DCHECK(component_type->IsPrimitive());
2458 array_class->SetComponentType(component_type);
2459 SetClassRoot(array_root, array_class);
2460}
2461
2462void ClassLinker::FinishArrayClassSetup(ObjPtr<mirror::Class> array_class) {
2463 ObjPtr<mirror::Class> java_lang_Object = GetClassRoot<mirror::Object>(this);
2464 array_class->SetSuperClass(java_lang_Object);
2465 array_class->SetVTable(java_lang_Object->GetVTable());
2466 array_class->SetPrimitiveType(Primitive::kPrimNot);
2467 ObjPtr<mirror::Class> component_type = array_class->GetComponentType();
2468 array_class->SetClassFlags(component_type->IsPrimitive()
2469 ? mirror::kClassFlagNoReferenceFields
2470 : mirror::kClassFlagObjectArray);
2471 array_class->SetClassLoader(component_type->GetClassLoader());
2472 array_class->SetStatusForPrimitiveOrArray(ClassStatus::kLoaded);
2473 array_class->PopulateEmbeddedVTable(image_pointer_size_);
2474 ImTable* object_imt = java_lang_Object->GetImt(image_pointer_size_);
2475 array_class->SetImt(object_imt, image_pointer_size_);
2476 // Skip EnsureSkipAccessChecksMethods(). We can skip the verified status,
2477 // the kAccVerificationAttempted flag is added below, and there are no
2478 // methods that need the kAccSkipAccessChecks flag.
2479 DCHECK_EQ(array_class->NumMethods(), 0u);
2480
2481 // don't need to set new_class->SetObjectSize(..)
2482 // because Object::SizeOf delegates to Array::SizeOf
2483
2484 // All arrays have java/lang/Cloneable and java/io/Serializable as
2485 // interfaces. We need to set that up here, so that stuff like
2486 // "instanceof" works right.
2487
2488 // Use the single, global copies of "interfaces" and "iftable"
2489 // (remember not to free them for arrays).
2490 {
2491 ObjPtr<mirror::IfTable> array_iftable = GetArrayIfTable();
2492 CHECK(array_iftable != nullptr);
2493 array_class->SetIfTable(array_iftable);
2494 }
2495
2496 // Inherit access flags from the component type.
2497 int access_flags = component_type->GetAccessFlags();
2498 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
2499 access_flags &= kAccJavaFlagsMask;
2500 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
2501 // and remove "interface".
2502 access_flags |= kAccAbstract | kAccFinal;
2503 access_flags &= ~kAccInterface;
2504 // Arrays are access-checks-clean and preverified.
2505 access_flags |= kAccVerificationAttempted;
2506
Vladimir Markob68bb7a2020-03-17 10:55:25 +00002507 array_class->SetAccessFlagsDuringLinking(access_flags);
Vladimir Marko70e2a762019-07-12 16:49:00 +01002508
Vladimir Markobf121912019-06-04 13:49:05 +01002509 // Array classes are fully initialized either during single threaded startup,
2510 // or from a pre-fence visitor, so visibly initialized.
2511 array_class->SetStatusForPrimitiveOrArray(ClassStatus::kVisiblyInitialized);
Vladimir Marko70e2a762019-07-12 16:49:00 +01002512}
2513
2514void ClassLinker::FinishCoreArrayClassSetup(ClassRoot array_root) {
2515 // Do not hold lock on the array class object, the initialization of
2516 // core array classes is done while the process is still single threaded.
2517 ObjPtr<mirror::Class> array_class = GetClassRoot(array_root, this);
2518 FinishArrayClassSetup(array_class);
2519
2520 std::string temp;
2521 const char* descriptor = array_class->GetDescriptor(&temp);
2522 size_t hash = ComputeModifiedUtf8Hash(descriptor);
2523 ObjPtr<mirror::Class> existing = InsertClass(descriptor, array_class, hash);
2524 CHECK(existing == nullptr);
Roland Levillain0e840272018-08-23 19:55:30 +01002525}
2526
Vladimir Markobcf17522018-06-01 13:14:32 +01002527ObjPtr<mirror::ObjectArray<mirror::StackTraceElement>> ClassLinker::AllocStackTraceElementArray(
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07002528 Thread* self,
2529 size_t length) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07002530 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002531 self, GetClassRoot<mirror::ObjectArray<mirror::StackTraceElement>>(this), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002532}
2533
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002534ObjPtr<mirror::Class> ClassLinker::EnsureResolved(Thread* self,
2535 const char* descriptor,
2536 ObjPtr<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002537 DCHECK(klass != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002538 if (kIsDebugBuild) {
2539 StackHandleScope<1> hs(self);
2540 HandleWrapperObjPtr<mirror::Class> h = hs.NewHandleWrapper(&klass);
2541 Thread::PoisonObjectPointersIfDebug();
2542 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002543
2544 // For temporary classes we must wait for them to be retired.
2545 if (init_done_ && klass->IsTemp()) {
2546 CHECK(!klass->IsResolved());
Vladimir Marko72ab6842017-01-20 19:32:50 +00002547 if (klass->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002548 ThrowEarlierClassFailure(klass);
2549 return nullptr;
2550 }
2551 StackHandleScope<1> hs(self);
2552 Handle<mirror::Class> h_class(hs.NewHandle(klass));
2553 ObjectLock<mirror::Class> lock(self, h_class);
2554 // Loop and wait for the resolving thread to retire this class.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002555 while (!h_class->IsRetired() && !h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002556 lock.WaitIgnoringInterrupts();
2557 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00002558 if (h_class->IsErroneousUnresolved()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002559 ThrowEarlierClassFailure(h_class.Get());
2560 return nullptr;
2561 }
2562 CHECK(h_class->IsRetired());
2563 // Get the updated class from class table.
Andreas Gampe34ee6842014-12-02 15:43:52 -08002564 klass = LookupClass(self, descriptor, h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002565 }
2566
Brian Carlstromaded5f72011-10-07 17:15:04 -07002567 // Wait for the class if it has not already been linked.
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002568 size_t index = 0;
2569 // Maximum number of yield iterations until we start sleeping.
2570 static const size_t kNumYieldIterations = 1000;
2571 // How long each sleep is in us.
2572 static const size_t kSleepDurationUS = 1000; // 1 ms.
Vladimir Marko72ab6842017-01-20 19:32:50 +00002573 while (!klass->IsResolved() && !klass->IsErroneousUnresolved()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002574 StackHandleScope<1> hs(self);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002575 HandleWrapperObjPtr<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002576 {
2577 ObjectTryLock<mirror::Class> lock(self, h_class);
2578 // Can not use a monitor wait here since it may block when returning and deadlock if another
2579 // thread has locked klass.
2580 if (lock.Acquired()) {
2581 // Check for circular dependencies between classes, the lock is required for SetStatus.
2582 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2583 ThrowClassCircularityError(h_class.Get());
Vladimir Marko2c64a832018-01-04 11:31:56 +00002584 mirror::Class::SetStatus(h_class, ClassStatus::kErrorUnresolved, self);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002585 return nullptr;
2586 }
2587 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002588 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002589 {
2590 // Handle wrapper deals with klass moving.
2591 ScopedThreadSuspension sts(self, kSuspended);
2592 if (index < kNumYieldIterations) {
2593 sched_yield();
2594 } else {
2595 usleep(kSleepDurationUS);
2596 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002597 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07002598 ++index;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002599 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002600
Vladimir Marko72ab6842017-01-20 19:32:50 +00002601 if (klass->IsErroneousUnresolved()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002602 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002603 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002604 }
2605 // Return the loaded class. No exceptions should be pending.
David Sehr709b0702016-10-13 09:12:37 -07002606 CHECK(klass->IsResolved()) << klass->PrettyClass();
Ian Rogers62d6c772013-02-27 08:32:07 -08002607 self->AssertNoPendingException();
Vladimir Markobcf17522018-06-01 13:14:32 +01002608 return klass;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002609}
2610
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002611using ClassPathEntry = std::pair<const DexFile*, const dex::ClassDef*>;
Ian Rogers68b56852014-08-29 20:19:11 -07002612
2613// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002614ClassPathEntry FindInClassPath(const char* descriptor,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07002615 size_t hash, const std::vector<const DexFile*>& class_path) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002616 for (const DexFile* dex_file : class_path) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08002617 DCHECK(dex_file != nullptr);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002618 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*dex_file, descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002619 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07002620 return ClassPathEntry(dex_file, dex_class_def);
2621 }
2622 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002623 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07002624}
2625
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002626bool ClassLinker::FindClassInSharedLibraries(ScopedObjectAccessAlreadyRunnable& soa,
2627 Thread* self,
2628 const char* descriptor,
2629 size_t hash,
2630 Handle<mirror::ClassLoader> class_loader,
2631 /*out*/ ObjPtr<mirror::Class>* result) {
2632 ArtField* field =
2633 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
2634 ObjPtr<mirror::Object> raw_shared_libraries = field->GetObject(class_loader.Get());
2635 if (raw_shared_libraries == nullptr) {
2636 return true;
2637 }
2638
2639 StackHandleScope<2> hs(self);
2640 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries(
2641 hs.NewHandle(raw_shared_libraries->AsObjectArray<mirror::ClassLoader>()));
2642 MutableHandle<mirror::ClassLoader> temp_loader = hs.NewHandle<mirror::ClassLoader>(nullptr);
Alex Lighta9bbc082019-11-14 14:51:41 -08002643 for (auto loader : shared_libraries.Iterate<mirror::ClassLoader>()) {
2644 temp_loader.Assign(loader);
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002645 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, temp_loader, result)) {
2646 return false; // One of the shared libraries is not supported.
2647 }
2648 if (*result != nullptr) {
2649 return true; // Found the class up the chain.
2650 }
2651 }
2652 return true;
2653}
2654
Nicolas Geoffray7d8d8ff2016-11-02 12:38:05 +00002655bool ClassLinker::FindClassInBaseDexClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2656 Thread* self,
2657 const char* descriptor,
2658 size_t hash,
2659 Handle<mirror::ClassLoader> class_loader,
Vladimir Markobcf17522018-06-01 13:14:32 +01002660 /*out*/ ObjPtr<mirror::Class>* result) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002661 // Termination case: boot class loader.
Andreas Gampef865ea92015-04-13 22:14:19 -07002662 if (IsBootClassLoader(soa, class_loader.Get())) {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002663 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
Andreas Gampef865ea92015-04-13 22:14:19 -07002664 return true;
2665 }
2666
David Brazdil05909d82018-12-06 16:25:16 +00002667 if (IsPathOrDexClassLoader(soa, class_loader) || IsInMemoryDexClassLoader(soa, class_loader)) {
Calin Juravlecdd49122017-07-05 20:09:53 -07002668 // For regular path or dex class loader the search order is:
2669 // - parent
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002670 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002671 // - class loader dex files
Andreas Gampef865ea92015-04-13 22:14:19 -07002672
Calin Juravlecdd49122017-07-05 20:09:53 -07002673 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2674 StackHandleScope<1> hs(self);
2675 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2676 if (!FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result)) {
2677 return false; // One of the parents is not supported.
2678 }
2679 if (*result != nullptr) {
2680 return true; // Found the class up the chain.
2681 }
Andreas Gampef865ea92015-04-13 22:14:19 -07002682
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002683 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2684 return false; // One of the shared library loader is not supported.
2685 }
2686 if (*result != nullptr) {
2687 return true; // Found the class in a shared library.
2688 }
2689
Calin Juravlecdd49122017-07-05 20:09:53 -07002690 // Search the current class loader classpath.
2691 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
Andreas Gampe501c3b02019-04-17 21:54:27 +00002692 return !soa.Self()->IsExceptionPending();
Andreas Gampef865ea92015-04-13 22:14:19 -07002693 }
2694
Calin Juravlecdd49122017-07-05 20:09:53 -07002695 if (IsDelegateLastClassLoader(soa, class_loader)) {
2696 // For delegate last, the search order is:
2697 // - boot class path
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002698 // - shared libraries
Calin Juravlecdd49122017-07-05 20:09:53 -07002699 // - class loader dex files
2700 // - parent
2701 *result = FindClassInBootClassLoaderClassPath(self, descriptor, hash);
2702 if (*result != nullptr) {
2703 return true; // The class is part of the boot class path.
2704 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002705 if (self->IsExceptionPending()) {
2706 // Pending exception means there was an error other than ClassNotFound that must be returned
2707 // to the caller.
2708 return false;
2709 }
Calin Juravlecdd49122017-07-05 20:09:53 -07002710
Nicolas Geoffray80a560c2018-10-26 13:48:51 +01002711 if (!FindClassInSharedLibraries(soa, self, descriptor, hash, class_loader, result)) {
2712 return false; // One of the shared library loader is not supported.
2713 }
2714 if (*result != nullptr) {
2715 return true; // Found the class in a shared library.
2716 }
2717
Calin Juravlecdd49122017-07-05 20:09:53 -07002718 *result = FindClassInBaseDexClassLoaderClassPath(soa, descriptor, hash, class_loader);
2719 if (*result != nullptr) {
2720 return true; // Found the class in the current class loader
2721 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002722 if (self->IsExceptionPending()) {
2723 // Pending exception means there was an error other than ClassNotFound that must be returned
2724 // to the caller.
2725 return false;
2726 }
Calin Juravlecdd49122017-07-05 20:09:53 -07002727
2728 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2729 StackHandleScope<1> hs(self);
2730 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2731 return FindClassInBaseDexClassLoader(soa, self, descriptor, hash, h_parent, result);
2732 }
2733
2734 // Unsupported class loader.
2735 *result = nullptr;
2736 return false;
Calin Juravle415dc3d2017-06-28 11:03:12 -07002737}
2738
Andreas Gampe501c3b02019-04-17 21:54:27 +00002739namespace {
2740
2741// Matches exceptions caught in DexFile.defineClass.
2742ALWAYS_INLINE bool MatchesDexFileCaughtExceptions(ObjPtr<mirror::Throwable> throwable,
2743 ClassLinker* class_linker)
2744 REQUIRES_SHARED(Locks::mutator_lock_) {
2745 return
2746 // ClassNotFoundException.
2747 throwable->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException,
2748 class_linker))
2749 ||
2750 // NoClassDefFoundError. TODO: Reconsider this. b/130746382.
2751 throwable->InstanceOf(Runtime::Current()->GetPreAllocatedNoClassDefFoundError()->GetClass());
2752}
2753
2754// Clear exceptions caught in DexFile.defineClass.
2755ALWAYS_INLINE void FilterDexFileCaughtExceptions(Thread* self, ClassLinker* class_linker)
2756 REQUIRES_SHARED(Locks::mutator_lock_) {
2757 if (MatchesDexFileCaughtExceptions(self->GetException(), class_linker)) {
2758 self->ClearException();
2759 }
2760}
2761
2762} // namespace
2763
Calin Juravle415dc3d2017-06-28 11:03:12 -07002764// Finds the class in the boot class loader.
2765// If the class is found the method returns the resolved class. Otherwise it returns null.
2766ObjPtr<mirror::Class> ClassLinker::FindClassInBootClassLoaderClassPath(Thread* self,
2767 const char* descriptor,
2768 size_t hash) {
2769 ObjPtr<mirror::Class> result = nullptr;
2770 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2771 if (pair.second != nullptr) {
2772 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, nullptr);
2773 if (klass != nullptr) {
2774 result = EnsureResolved(self, descriptor, klass);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002775 } else {
Calin Juravle415dc3d2017-06-28 11:03:12 -07002776 result = DefineClass(self,
2777 descriptor,
2778 hash,
2779 ScopedNullHandle<mirror::ClassLoader>(),
2780 *pair.first,
2781 *pair.second);
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002782 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002783 if (result == nullptr) {
2784 CHECK(self->IsExceptionPending()) << descriptor;
Andreas Gampe501c3b02019-04-17 21:54:27 +00002785 FilterDexFileCaughtExceptions(self, this);
Andreas Gampef865ea92015-04-13 22:14:19 -07002786 }
2787 }
Calin Juravle415dc3d2017-06-28 11:03:12 -07002788 return result;
2789}
Andreas Gampef865ea92015-04-13 22:14:19 -07002790
Calin Juravle415dc3d2017-06-28 11:03:12 -07002791ObjPtr<mirror::Class> ClassLinker::FindClassInBaseDexClassLoaderClassPath(
2792 ScopedObjectAccessAlreadyRunnable& soa,
2793 const char* descriptor,
2794 size_t hash,
2795 Handle<mirror::ClassLoader> class_loader) {
David Brazdil05909d82018-12-06 16:25:16 +00002796 DCHECK(IsPathOrDexClassLoader(soa, class_loader) ||
2797 IsInMemoryDexClassLoader(soa, class_loader) ||
2798 IsDelegateLastClassLoader(soa, class_loader))
Calin Juravle415dc3d2017-06-28 11:03:12 -07002799 << "Unexpected class loader for descriptor " << descriptor;
Andreas Gampef865ea92015-04-13 22:14:19 -07002800
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002801 ObjPtr<mirror::Class> ret;
2802 auto define_class = [&](const DexFile* cp_dex_file) REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002803 const dex::ClassDef* dex_class_def = OatDexFile::FindClassDef(*cp_dex_file, descriptor, hash);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002804 if (dex_class_def != nullptr) {
2805 ObjPtr<mirror::Class> klass = DefineClass(soa.Self(),
2806 descriptor,
2807 hash,
2808 class_loader,
2809 *cp_dex_file,
2810 *dex_class_def);
2811 if (klass == nullptr) {
2812 CHECK(soa.Self()->IsExceptionPending()) << descriptor;
Andreas Gampe501c3b02019-04-17 21:54:27 +00002813 FilterDexFileCaughtExceptions(soa.Self(), this);
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002814 // TODO: Is it really right to break here, and not check the other dex files?
Andreas Gampe501c3b02019-04-17 21:54:27 +00002815 } else {
2816 DCHECK(!soa.Self()->IsExceptionPending());
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002817 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002818 ret = klass;
2819 return false; // Found a Class (or error == nullptr), stop visit.
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002820 }
Andreas Gampeb8e7c372018-02-20 18:24:55 -08002821 return true; // Continue with the next DexFile.
2822 };
2823
2824 VisitClassLoaderDexFiles(soa, class_loader, define_class);
2825 return ret;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07002826}
2827
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01002828ObjPtr<mirror::Class> ClassLinker::FindClass(Thread* self,
2829 const char* descriptor,
2830 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002831 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08002832 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002833 self->AssertNoPendingException();
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07002834 self->PoisonObjectPointers(); // For DefineClass, CreateArrayClass, etc...
Elliott Hughesc3b77c72011-12-15 20:56:48 -08002835 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002836 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2837 // for primitive classes that aren't backed by dex files.
2838 return FindPrimitiveClass(descriptor[0]);
2839 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002840 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002841 // Find the class in the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07002842 ObjPtr<mirror::Class> klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07002843 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002844 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002845 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002846 // Class is not yet loaded.
Andreas Gampefa4333d2017-02-14 11:10:34 -08002847 if (descriptor[0] != '[' && class_loader == nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002848 // Non-array class and the boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002849 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07002850 if (pair.second != nullptr) {
Mathieu Chartier9865bde2015-12-21 09:58:16 -08002851 return DefineClass(self,
2852 descriptor,
2853 hash,
2854 ScopedNullHandle<mirror::ClassLoader>(),
2855 *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07002856 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07002857 } else {
2858 // The boot class loader is searched ahead of the application class loader, failures are
2859 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2860 // trigger the chaining with a proper stack trace.
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002861 ObjPtr<mirror::Throwable> pre_allocated =
2862 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002863 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07002864 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05002865 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002866 }
2867 ObjPtr<mirror::Class> result_ptr;
2868 bool descriptor_equals;
2869 if (descriptor[0] == '[') {
2870 result_ptr = CreateArrayClass(self, descriptor, hash, class_loader);
2871 DCHECK_EQ(result_ptr == nullptr, self->IsExceptionPending());
2872 DCHECK(result_ptr == nullptr || result_ptr->DescriptorEquals(descriptor));
2873 descriptor_equals = true;
Jesse Wilson47daf872011-11-23 11:42:45 -05002874 } else {
Ian Rogers98379392014-02-24 16:53:16 -08002875 ScopedObjectAccessUnchecked soa(self);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002876 bool known_hierarchy =
2877 FindClassInBaseDexClassLoader(soa, self, descriptor, hash, class_loader, &result_ptr);
2878 if (result_ptr != nullptr) {
2879 // The chain was understood and we found the class. We still need to add the class to
2880 // the class table to protect from racy programs that can try and redefine the path list
2881 // which would change the Class<?> returned for subsequent evaluation of const-class.
2882 DCHECK(known_hierarchy);
2883 DCHECK(result_ptr->DescriptorEquals(descriptor));
2884 descriptor_equals = true;
Andreas Gampe501c3b02019-04-17 21:54:27 +00002885 } else if (!self->IsExceptionPending()) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002886 // Either the chain wasn't understood or the class wasn't found.
Andreas Gampe501c3b02019-04-17 21:54:27 +00002887 // If there is a pending exception we didn't clear, it is a not a ClassNotFoundException and
2888 // we should return it instead of silently clearing and retrying.
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002889 //
2890 // If the chain was understood but we did not find the class, let the Java-side
2891 // rediscover all this and throw the exception with the right stack trace. Note that
2892 // the Java-side could still succeed for racy programs if another thread is actively
2893 // modifying the class loader's path list.
Andreas Gampef865ea92015-04-13 22:14:19 -07002894
Alex Light185a4612018-10-04 15:54:25 -07002895 // The runtime is not allowed to call into java from a runtime-thread so just abort.
Alex Lighte9f61032018-09-24 16:04:51 -07002896 if (self->IsRuntimeThread()) {
Calin Juravleccd56952016-12-15 17:57:38 +00002897 // Oops, we can't call into java so we can't run actual class-loader code.
2898 // This is true for e.g. for the compiler (jit or aot).
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002899 ObjPtr<mirror::Throwable> pre_allocated =
2900 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2901 self->SetException(pre_allocated);
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002902 return nullptr;
2903 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002904
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002905 // Inlined DescriptorToDot(descriptor) with extra validation.
2906 //
2907 // Throw NoClassDefFoundError early rather than potentially load a class only to fail
2908 // the DescriptorEquals() check below and give a confusing error message. For example,
2909 // when native code erroneously calls JNI GetFieldId() with signature "java/lang/String"
2910 // instead of "Ljava/lang/String;", the message below using the "dot" names would be
2911 // "class loader [...] returned class java.lang.String instead of java.lang.String".
2912 size_t descriptor_length = strlen(descriptor);
2913 if (UNLIKELY(descriptor[0] != 'L') ||
2914 UNLIKELY(descriptor[descriptor_length - 1] != ';') ||
2915 UNLIKELY(memchr(descriptor + 1, '.', descriptor_length - 2) != nullptr)) {
2916 ThrowNoClassDefFoundError("Invalid descriptor: %s.", descriptor);
2917 return nullptr;
2918 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002919
Vladimir Marko5fdd7782017-04-20 11:26:03 +01002920 std::string class_name_string(descriptor + 1, descriptor_length - 2);
2921 std::replace(class_name_string.begin(), class_name_string.end(), '/', '.');
Andreas Gampe87658f32019-04-18 18:39:02 +00002922 if (known_hierarchy &&
2923 fast_class_not_found_exceptions_ &&
2924 !Runtime::Current()->IsJavaDebuggable()) {
2925 // For known hierarchy, we know that the class is going to throw an exception. If we aren't
2926 // debuggable, optimize this path by throwing directly here without going back to Java
2927 // language. This reduces how many ClassNotFoundExceptions happen.
2928 self->ThrowNewExceptionF("Ljava/lang/ClassNotFoundException;",
2929 "%s",
2930 class_name_string.c_str());
2931 } else {
2932 ScopedLocalRef<jobject> class_loader_object(
2933 soa.Env(), soa.AddLocalReference<jobject>(class_loader.Get()));
2934 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
2935 {
2936 ScopedThreadStateChange tsc(self, kNative);
2937 ScopedLocalRef<jobject> class_name_object(
2938 soa.Env(), soa.Env()->NewStringUTF(class_name_string.c_str()));
2939 if (class_name_object.get() == nullptr) {
2940 DCHECK(self->IsExceptionPending()); // OOME.
2941 return nullptr;
2942 }
2943 CHECK(class_loader_object.get() != nullptr);
2944 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2945 WellKnownClasses::java_lang_ClassLoader_loadClass,
2946 class_name_object.get()));
2947 }
2948 if (result.get() == nullptr && !self->IsExceptionPending()) {
2949 // broken loader - throw NPE to be compatible with Dalvik
2950 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
2951 class_name_string.c_str()).c_str());
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002952 return nullptr;
2953 }
Andreas Gampe87658f32019-04-18 18:39:02 +00002954 result_ptr = soa.Decode<mirror::Class>(result.get());
2955 // Check the name of the returned class.
2956 descriptor_equals = (result_ptr != nullptr) && result_ptr->DescriptorEquals(descriptor);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00002957 }
Andreas Gampe501c3b02019-04-17 21:54:27 +00002958 } else {
2959 DCHECK(!MatchesDexFileCaughtExceptions(self->GetException(), this));
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00002960 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002961 }
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002962
2963 if (self->IsExceptionPending()) {
2964 // If the ClassLoader threw or array class allocation failed, pass that exception up.
2965 // However, to comply with the RI behavior, first check if another thread succeeded.
2966 result_ptr = LookupClass(self, descriptor, hash, class_loader.Get());
2967 if (result_ptr != nullptr && !result_ptr->IsErroneous()) {
2968 self->ClearException();
2969 return EnsureResolved(self, descriptor, result_ptr);
2970 }
2971 return nullptr;
2972 }
2973
2974 // Try to insert the class to the class table, checking for mismatch.
2975 ObjPtr<mirror::Class> old;
2976 {
2977 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2978 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader.Get());
2979 old = class_table->Lookup(descriptor, hash);
2980 if (old == nullptr) {
2981 old = result_ptr; // For the comparison below, after releasing the lock.
2982 if (descriptor_equals) {
Vladimir Markobcf17522018-06-01 13:14:32 +01002983 class_table->InsertWithHash(result_ptr, hash);
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07002984 WriteBarrier::ForEveryFieldWrite(class_loader.Get());
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002985 } // else throw below, after releasing the lock.
2986 }
2987 }
2988 if (UNLIKELY(old != result_ptr)) {
2989 // Return `old` (even if `!descriptor_equals`) to mimic the RI behavior for parallel
2990 // capable class loaders. (All class loaders are considered parallel capable on Android.)
Vladimir Markodfc0de72019-04-01 10:57:55 +01002991 ObjPtr<mirror::Class> loader_class = class_loader->GetClass();
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00002992 const char* loader_class_name =
2993 loader_class->GetDexFile().StringByTypeIdx(loader_class->GetDexTypeIndex());
2994 LOG(WARNING) << "Initiating class loader of type " << DescriptorToDot(loader_class_name)
2995 << " is not well-behaved; it returned a different Class for racing loadClass(\""
2996 << DescriptorToDot(descriptor) << "\").";
2997 return EnsureResolved(self, descriptor, old);
2998 }
2999 if (UNLIKELY(!descriptor_equals)) {
3000 std::string result_storage;
3001 const char* result_name = result_ptr->GetDescriptor(&result_storage);
3002 std::string loader_storage;
3003 const char* loader_class_name = class_loader->GetClass()->GetDescriptor(&loader_storage);
3004 ThrowNoClassDefFoundError(
3005 "Initiating class loader of type %s returned class %s instead of %s.",
3006 DescriptorToDot(loader_class_name).c_str(),
3007 DescriptorToDot(result_name).c_str(),
3008 DescriptorToDot(descriptor).c_str());
3009 return nullptr;
3010 }
Vladimir Markobcf17522018-06-01 13:14:32 +01003011 // Success.
3012 return result_ptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07003013}
3014
Alex Light270db1c2019-12-03 12:20:01 +00003015// Helper for maintaining DefineClass counting. We need to notify callbacks when we start/end a
3016// define-class and how many recursive DefineClasses we are at in order to allow for doing things
3017// like pausing class definition.
3018struct ScopedDefiningClass {
3019 public:
3020 explicit ScopedDefiningClass(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_)
3021 : self_(self), returned_(false) {
3022 Locks::mutator_lock_->AssertSharedHeld(self_);
3023 Runtime::Current()->GetRuntimeCallbacks()->BeginDefineClass();
3024 self_->IncrDefineClassCount();
3025 }
3026 ~ScopedDefiningClass() REQUIRES_SHARED(Locks::mutator_lock_) {
3027 Locks::mutator_lock_->AssertSharedHeld(self_);
3028 CHECK(returned_);
3029 }
3030
3031 ObjPtr<mirror::Class> Finish(Handle<mirror::Class> h_klass)
3032 REQUIRES_SHARED(Locks::mutator_lock_) {
3033 CHECK(!returned_);
3034 self_->DecrDefineClassCount();
3035 Runtime::Current()->GetRuntimeCallbacks()->EndDefineClass();
3036 Thread::PoisonObjectPointersIfDebug();
3037 returned_ = true;
3038 return h_klass.Get();
3039 }
3040
3041 ObjPtr<mirror::Class> Finish(ObjPtr<mirror::Class> klass)
3042 REQUIRES_SHARED(Locks::mutator_lock_) {
3043 StackHandleScope<1> hs(self_);
3044 Handle<mirror::Class> h_klass(hs.NewHandle(klass));
3045 return Finish(h_klass);
3046 }
3047
3048 ObjPtr<mirror::Class> Finish(nullptr_t np ATTRIBUTE_UNUSED)
3049 REQUIRES_SHARED(Locks::mutator_lock_) {
3050 ScopedNullHandle<mirror::Class> snh;
3051 return Finish(snh);
3052 }
3053
3054 private:
3055 Thread* self_;
3056 bool returned_;
3057};
3058
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003059ObjPtr<mirror::Class> ClassLinker::DefineClass(Thread* self,
3060 const char* descriptor,
3061 size_t hash,
3062 Handle<mirror::ClassLoader> class_loader,
3063 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003064 const dex::ClassDef& dex_class_def) {
Alex Light270db1c2019-12-03 12:20:01 +00003065 ScopedDefiningClass sdc(self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003066 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003067 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003068
Brian Carlstromaded5f72011-10-07 17:15:04 -07003069 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003070 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003071 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003072 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003073 klass.Assign(GetClassRoot<mirror::Object>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003074 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003075 klass.Assign(GetClassRoot<mirror::Class>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003076 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003077 klass.Assign(GetClassRoot<mirror::String>(this));
Fred Shih4ee7a662014-07-11 09:59:27 -07003078 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003079 klass.Assign(GetClassRoot<mirror::Reference>(this));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003080 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003081 klass.Assign(GetClassRoot<mirror::DexCache>(this));
Alex Lightd6251582016-10-31 11:12:30 -07003082 } else if (strcmp(descriptor, "Ldalvik/system/ClassExt;") == 0) {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003083 klass.Assign(GetClassRoot<mirror::ClassExt>(this));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003084 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003085 }
3086
Vladimir Markob9c29f62019-03-20 14:22:51 +00003087 // For AOT-compilation of an app, we may use a shortened boot class path that excludes
3088 // some runtime modules. Prevent definition of classes in app class loader that could clash
3089 // with these modules as these classes could be resolved differently during execution.
3090 if (class_loader != nullptr &&
3091 Runtime::Current()->IsAotCompiler() &&
Vladimir Markod1f73512020-04-02 10:50:35 +01003092 IsUpdatableBootClassPathDescriptor(descriptor)) {
Vladimir Markob9c29f62019-03-20 14:22:51 +00003093 ObjPtr<mirror::Throwable> pre_allocated =
3094 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3095 self->SetException(pre_allocated);
Alex Light270db1c2019-12-03 12:20:01 +00003096 return sdc.Finish(nullptr);
Vladimir Markob9c29f62019-03-20 14:22:51 +00003097 }
3098
Calin Juravle33787682019-07-26 14:27:18 -07003099 // For AOT-compilation of an app, we may use only a public SDK to resolve symbols. If the SDK
3100 // checks are configured (a non null SdkChecker) and the descriptor is not in the provided
3101 // public class path then we prevent the definition of the class.
3102 //
3103 // NOTE that we only do the checks for the boot classpath APIs. Anything else, like the app
3104 // classpath is not checked.
3105 if (class_loader == nullptr &&
3106 Runtime::Current()->IsAotCompiler() &&
3107 DenyAccessBasedOnPublicSdk(descriptor)) {
3108 ObjPtr<mirror::Throwable> pre_allocated =
3109 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3110 self->SetException(pre_allocated);
3111 return sdc.Finish(nullptr);
3112 }
3113
Alex Lighte9f61032018-09-24 16:04:51 -07003114 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
3115 // code to be executed. We put it up here so we can avoid all the allocations associated with
3116 // creating the class. This can happen with (eg) jit threads.
3117 if (!self->CanLoadClasses()) {
3118 // Make sure we don't try to load anything, potentially causing an infinite loop.
3119 ObjPtr<mirror::Throwable> pre_allocated =
3120 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
3121 self->SetException(pre_allocated);
Alex Light270db1c2019-12-03 12:20:01 +00003122 return sdc.Finish(nullptr);
Alex Lighte9f61032018-09-24 16:04:51 -07003123 }
3124
Andreas Gampefa4333d2017-02-14 11:10:34 -08003125 if (klass == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003126 // Allocate a class with the status of not ready.
3127 // Interface object should get the right size here. Regular class will
3128 // figure out the right size later and be replaced with one of the right
3129 // size when the class becomes resolved.
Chang Xing0c2c2222017-08-04 14:36:17 -07003130 if (CanAllocClass()) {
3131 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
3132 } else {
Alex Light270db1c2019-12-03 12:20:01 +00003133 return sdc.Finish(nullptr);
Chang Xing0c2c2222017-08-04 14:36:17 -07003134 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07003135 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08003136 if (UNLIKELY(klass == nullptr)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003137 self->AssertPendingOOMException();
Alex Light270db1c2019-12-03 12:20:01 +00003138 return sdc.Finish(nullptr);
Ian Rogersa436fde2013-08-27 23:34:06 -07003139 }
Alex Lightb0f11922017-01-23 14:25:17 -08003140 // Get the real dex file. This will return the input if there aren't any callbacks or they do
3141 // nothing.
3142 DexFile const* new_dex_file = nullptr;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003143 dex::ClassDef const* new_class_def = nullptr;
Alex Lightb0f11922017-01-23 14:25:17 -08003144 // TODO We should ideally figure out some way to move this after we get a lock on the klass so it
3145 // will only be called once.
3146 Runtime::Current()->GetRuntimeCallbacks()->ClassPreDefine(descriptor,
3147 klass,
3148 class_loader,
3149 dex_file,
3150 dex_class_def,
3151 &new_dex_file,
3152 &new_class_def);
Alex Light440b5d92017-01-24 15:32:25 -08003153 // Check to see if an exception happened during runtime callbacks. Return if so.
3154 if (self->IsExceptionPending()) {
Alex Light270db1c2019-12-03 12:20:01 +00003155 return sdc.Finish(nullptr);
Alex Light440b5d92017-01-24 15:32:25 -08003156 }
Alex Lightb0f11922017-01-23 14:25:17 -08003157 ObjPtr<mirror::DexCache> dex_cache = RegisterDexFile(*new_dex_file, class_loader.Get());
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003158 if (dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003159 self->AssertPendingException();
Alex Light270db1c2019-12-03 12:20:01 +00003160 return sdc.Finish(nullptr);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003161 }
3162 klass->SetDexCache(dex_cache);
Alex Lightb0f11922017-01-23 14:25:17 -08003163 SetupClass(*new_dex_file, *new_class_def, klass, class_loader.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07003164
Jeff Hao848f70a2014-01-15 13:49:50 -08003165 // Mark the string class by setting its access flag.
3166 if (UNLIKELY(!init_done_)) {
3167 if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
3168 klass->SetStringClass();
3169 }
3170 }
3171
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003172 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003173 klass->SetClinitThreadId(self->GetTid());
Mathieu Chartier1e4841e2016-12-15 14:21:04 -08003174 // Make sure we have a valid empty iftable even if there are errors.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003175 klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003176
Mathieu Chartier590fee92013-09-13 13:46:47 -07003177 // Add the newly loaded class to the loaded classes table.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003178 ObjPtr<mirror::Class> existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07003179 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003180 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
3181 // this thread to block.
Alex Light270db1c2019-12-03 12:20:01 +00003182 return sdc.Finish(EnsureResolved(self, descriptor, existing));
Brian Carlstromaded5f72011-10-07 17:15:04 -07003183 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003184
Mathieu Chartierc7853442015-03-27 14:35:38 -07003185 // Load the fields and other things after we are inserted in the table. This is so that we don't
3186 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
3187 // other reason is that the field roots are only visited from the class table. So we need to be
3188 // inserted before we allocate / fill in these fields.
Alex Lightb0f11922017-01-23 14:25:17 -08003189 LoadClass(self, *new_dex_file, *new_class_def, klass);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003190 if (self->IsExceptionPending()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003191 VLOG(class_linker) << self->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003192 // An exception occured during load, set status to erroneous while holding klass' lock in case
3193 // notification is necessary.
3194 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003195 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003196 }
Alex Light270db1c2019-12-03 12:20:01 +00003197 return sdc.Finish(nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003198 }
3199
Brian Carlstromaded5f72011-10-07 17:15:04 -07003200 // Finish loading (if necessary) by finding parents
3201 CHECK(!klass->IsLoaded());
Alex Lightb0f11922017-01-23 14:25:17 -08003202 if (!LoadSuperAndInterfaces(klass, *new_dex_file)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003203 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003204 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003205 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003206 }
Alex Light270db1c2019-12-03 12:20:01 +00003207 return sdc.Finish(nullptr);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003208 }
3209 CHECK(klass->IsLoaded());
Andreas Gampe0f01b582017-01-18 15:22:37 -08003210
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07003211 // At this point the class is loaded. Publish a ClassLoad event.
Andreas Gampe0f01b582017-01-18 15:22:37 -08003212 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
Andreas Gampeac30fa22017-01-18 21:02:36 -08003213 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass);
Andreas Gampe0f01b582017-01-18 15:22:37 -08003214
Brian Carlstromaded5f72011-10-07 17:15:04 -07003215 // Link the class (if necessary)
3216 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07003217 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003218 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003219
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003220 MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
Igor Murashkinb1d8c312015-08-04 11:18:43 -07003221 if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07003222 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003223 if (!klass->IsErroneous()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00003224 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07003225 }
Alex Light270db1c2019-12-03 12:20:01 +00003226 return sdc.Finish(nullptr);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003227 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07003228 self->AssertNoPendingException();
Andreas Gampefa4333d2017-02-14 11:10:34 -08003229 CHECK(h_new_class != nullptr) << descriptor;
Vladimir Marko72ab6842017-01-20 19:32:50 +00003230 CHECK(h_new_class->IsResolved() && !h_new_class->IsErroneousResolved()) << descriptor;
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003231
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003232 // Instrumentation may have updated entrypoints for all methods of all
3233 // classes. However it could not update methods of this class while we
3234 // were loading it. Now the class is resolved, we can update entrypoints
3235 // as required by instrumentation.
3236 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
3237 // We must be in the kRunnable state to prevent instrumentation from
3238 // suspending all threads to update entrypoints while we are doing it
3239 // for this class.
3240 DCHECK_EQ(self->GetState(), kRunnable);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07003241 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
Sebastien Hertza8a697f2015-01-15 12:28:47 +01003242 }
3243
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003244 /*
3245 * We send CLASS_PREPARE events to the debugger from here. The
3246 * definition of "preparation" is creating the static fields for a
3247 * class and initializing them to the standard default values, but not
3248 * executing any code (that comes later, during "initialization").
3249 *
3250 * We did the static preparation in LinkClass.
3251 *
3252 * The class has been prepared and resolved but possibly not yet verified
3253 * at this point.
3254 */
Andreas Gampeac30fa22017-01-18 21:02:36 -08003255 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class);
Elliott Hughes4740cdf2011-12-07 14:07:12 -08003256
Tamas Berghammer160e6df2016-01-05 14:29:02 +00003257 // Notify native debugger of the new class and its layout.
3258 jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
3259
Alex Light270db1c2019-12-03 12:20:01 +00003260 return sdc.Finish(h_new_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003261}
3262
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003263uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003264 const dex::ClassDef& dex_class_def) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003265 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07003266 size_t num_8 = 0;
3267 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07003268 size_t num_32 = 0;
3269 size_t num_64 = 0;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003270 ClassAccessor accessor(dex_file, dex_class_def);
3271 // We allow duplicate definitions of the same field in a class_data_item
3272 // but ignore the repeated indexes here, b/21868015.
3273 uint32_t last_field_idx = dex::kDexNoIndex;
3274 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
3275 uint32_t field_idx = field.GetIndex();
3276 // Ordering enforced by DexFileVerifier.
3277 DCHECK(last_field_idx == dex::kDexNoIndex || last_field_idx <= field_idx);
3278 if (UNLIKELY(field_idx == last_field_idx)) {
3279 continue;
3280 }
3281 last_field_idx = field_idx;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003282 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003283 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
3284 char c = descriptor[0];
3285 switch (c) {
3286 case 'L':
3287 case '[':
3288 num_ref++;
3289 break;
3290 case 'J':
3291 case 'D':
3292 num_64++;
3293 break;
3294 case 'I':
3295 case 'F':
3296 num_32++;
3297 break;
3298 case 'S':
3299 case 'C':
3300 num_16++;
3301 break;
3302 case 'B':
3303 case 'Z':
3304 num_8++;
3305 break;
3306 default:
3307 LOG(FATAL) << "Unknown descriptor: " << c;
3308 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003309 }
3310 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003311 return mirror::Class::ComputeClassSize(false,
3312 0,
3313 num_8,
3314 num_16,
3315 num_32,
3316 num_64,
3317 num_ref,
Mathieu Chartiere401d142015-04-22 13:56:20 -07003318 image_pointer_size_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003319}
3320
Alex Lightfc49fec2018-01-16 22:28:36 +00003321// Special case to get oat code without overwriting a trampoline.
3322const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
David Sehr709b0702016-10-13 09:12:37 -07003323 CHECK(method->IsInvokable()) << method->PrettyMethod();
Nicolas Geoffraya7a47592015-11-24 09:17:30 +00003324 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08003325 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07003326 }
Nicolas Geoffray32384402019-07-17 20:06:44 +01003327 const void* code = method->GetOatMethodQuickCode(GetImagePointerSize());
Alex Lightfc49fec2018-01-16 22:28:36 +00003328 if (code != nullptr) {
3329 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08003330 }
Nicolas Geoffray32384402019-07-17 20:06:44 +01003331
3332 jit::Jit* jit = Runtime::Current()->GetJit();
3333 if (jit != nullptr) {
3334 code = jit->GetCodeCache()->GetSavedEntryPointOfPreCompiledMethod(method);
3335 if (code != nullptr) {
3336 return code;
3337 }
3338 }
3339
Alex Lightfc49fec2018-01-16 22:28:36 +00003340 if (method->IsNative()) {
3341 // No code and native? Use generic trampoline.
3342 return GetQuickGenericJniStub();
3343 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003344
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00003345 if (interpreter::CanRuntimeUseNterp() && CanMethodUseNterp(method)) {
Nicolas Geoffray00391822019-12-10 10:17:23 +00003346 return interpreter::GetNterpEntryPoint();
3347 }
3348
Alex Lightfc49fec2018-01-16 22:28:36 +00003349 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07003350}
3351
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003352bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
Alex Light2d441b12018-06-08 15:33:21 -07003353 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003354 if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
3355 return false;
3356 }
3357
Elliott Hughes956af0f2014-12-11 14:34:28 -08003358 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003359 return true;
3360 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003361
3362 Runtime* runtime = Runtime::Current();
3363 instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
3364 if (instr->InterpretOnly()) {
3365 return true;
3366 }
3367
3368 if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
3369 // Doing this check avoids doing compiled/interpreter transitions.
3370 return true;
3371 }
3372
Alex Lightfc588092020-01-23 15:39:08 -08003373 if (Thread::Current()->IsForceInterpreter()) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003374 // Force the use of interpreter when it is required by the debugger.
3375 return true;
3376 }
3377
Alex Light8f34aba2017-10-09 13:46:32 -07003378 if (Thread::Current()->IsAsyncExceptionPending()) {
3379 // Force use of interpreter to handle async-exceptions
3380 return true;
3381 }
3382
Alex Light2d441b12018-06-08 15:33:21 -07003383 if (quick_code == GetQuickInstrumentationEntryPoint()) {
3384 const void* instr_target = instr->GetCodeForInvoke(method);
3385 DCHECK_NE(instr_target, GetQuickInstrumentationEntryPoint()) << method->PrettyMethod();
3386 return ShouldUseInterpreterEntrypoint(method, instr_target);
3387 }
3388
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003389 if (runtime->IsJavaDebuggable()) {
3390 // For simplicity, we ignore precompiled code and go to the interpreter
3391 // assuming we don't already have jitted code.
3392 // We could look at the oat file where `quick_code` is being defined,
3393 // and check whether it's been compiled debuggable, but we decided to
3394 // only rely on the JIT for debuggable apps.
Alex Light6b16d892016-11-11 11:21:04 -08003395 jit::Jit* jit = Runtime::Current()->GetJit();
3396 return (jit == nullptr) || !jit->GetCodeCache()->ContainsPc(quick_code);
3397 }
3398
Nicolas Geoffrayc9de61c2018-11-27 17:34:31 +00003399 if (runtime->IsNativeDebuggable()) {
Calin Juravlee5de54c2016-04-20 14:22:09 +01003400 DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
David Srbeckyf4480162016-03-16 00:06:24 +00003401 // If we are doing native debugging, ignore application's AOT code,
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003402 // since we want to JIT it (at first use) with extra stackmaps for native
3403 // debugging. We keep however all AOT code from the boot image,
3404 // since the JIT-at-first-use is blocking and would result in non-negligible
3405 // startup performance impact.
David Srbeckyf4480162016-03-16 00:06:24 +00003406 return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003407 }
3408
3409 return false;
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003410}
3411
Vladimir Marko86c87522020-05-11 16:55:55 +01003412void ClassLinker::FixupStaticTrampolines(Thread* self, ObjPtr<mirror::Class> klass) {
Alex Light2d441b12018-06-08 15:33:21 -07003413 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Vladimir Markocce414f2019-10-07 08:51:33 +01003414 DCHECK(klass->IsVisiblyInitialized()) << klass->PrettyDescriptor();
Vladimir Marko86c87522020-05-11 16:55:55 +01003415 size_t num_direct_methods = klass->NumDirectMethods();
3416 if (num_direct_methods == 0) {
Ian Rogers1c829822013-09-30 18:18:50 -07003417 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08003418 }
Vladimir Markocce414f2019-10-07 08:51:33 +01003419 if (UNLIKELY(klass->IsProxyClass())) {
3420 return;
3421 }
Vladimir Marko86c87522020-05-11 16:55:55 +01003422 PointerSize pointer_size = image_pointer_size_;
3423 if (std::any_of(klass->GetDirectMethods(pointer_size).begin(),
3424 klass->GetDirectMethods(pointer_size).end(),
3425 [](const ArtMethod& m) { return m.IsCriticalNative(); })) {
3426 // Store registered @CriticalNative methods, if any, to JNI entrypoints.
3427 // Direct methods are a contiguous chunk of memory, so use the ordering of the map.
3428 ArtMethod* first_method = klass->GetDirectMethod(0u, pointer_size);
3429 ArtMethod* last_method = klass->GetDirectMethod(num_direct_methods - 1u, pointer_size);
3430 MutexLock lock(self, critical_native_code_with_clinit_check_lock_);
3431 auto lb = critical_native_code_with_clinit_check_.lower_bound(first_method);
3432 while (lb != critical_native_code_with_clinit_check_.end() && lb->first <= last_method) {
3433 lb->first->SetEntryPointFromJni(lb->second);
3434 lb = critical_native_code_with_clinit_check_.erase(lb);
3435 }
3436 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003437 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07003438 if (!runtime->IsStarted()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08003439 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07003440 return; // OAT file unavailable.
3441 }
Ian Rogers19846512012-02-24 11:42:47 -08003442 }
Alex Light64ad14d2014-08-19 14:23:13 -07003443
Mathieu Chartierf8322842014-05-16 10:59:25 -07003444 const DexFile& dex_file = klass->GetDexFile();
Ian Rogers97b52f82014-08-14 11:34:07 -07003445 bool has_oat_class;
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003446 OatFile::OatClass oat_class = OatFile::FindOatClass(dex_file,
3447 klass->GetDexClassDefIndex(),
3448 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07003449 // Link the code of methods skipped by LinkCode.
Vladimir Marko86c87522020-05-11 16:55:55 +01003450 for (size_t method_index = 0; method_index < num_direct_methods; ++method_index) {
3451 ArtMethod* method = klass->GetDirectMethod(method_index, pointer_size);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003452 if (!method->IsStatic()) {
3453 // Only update static methods.
3454 continue;
Ian Rogers19846512012-02-24 11:42:47 -08003455 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003456 const void* quick_code = nullptr;
Nicolas Geoffray00391822019-12-10 10:17:23 +00003457
3458 // In order:
3459 // 1) Check if we have AOT Code.
3460 // 2) Check if we have JIT Code.
3461 // 3) Check if we can use Nterp.
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003462 if (has_oat_class) {
3463 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003464 quick_code = oat_method.GetQuickCode();
3465 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003466
Vladimir Markocce414f2019-10-07 08:51:33 +01003467 jit::Jit* jit = runtime->GetJit();
Nicolas Geoffray32384402019-07-17 20:06:44 +01003468 if (quick_code == nullptr && jit != nullptr) {
3469 quick_code = jit->GetCodeCache()->GetSavedEntryPointOfPreCompiledMethod(method);
Nicolas Geoffray7989ac92019-04-10 12:42:30 +01003470 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003471
3472 if (quick_code == nullptr &&
3473 interpreter::CanRuntimeUseNterp() &&
Nicolas Geoffrayc39af942021-01-25 08:43:57 +00003474 CanMethodUseNterp(method)) {
Nicolas Geoffray00391822019-12-10 10:17:23 +00003475 quick_code = interpreter::GetNterpEntryPoint();
3476 }
3477
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003478 // Check whether the method is native, in which case it's generic JNI.
Ulya Trafimovich5439f052020-07-29 10:03:46 +01003479 if (quick_code == nullptr && method->IsNative()) {
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003480 quick_code = GetQuickGenericJniStub();
3481 } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003482 // Use interpreter entry point.
Nicolas Geoffray00391822019-12-10 10:17:23 +00003483 if (IsQuickToInterpreterBridge(method->GetEntryPointFromQuickCompiledCode())) {
3484 // If we have the trampoline or the bridge already, no need to update.
3485 // This saves in not dirtying boot image memory.
3486 continue;
3487 }
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003488 quick_code = GetQuickToInterpreterBridge();
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003489 }
Nicolas Geoffray00391822019-12-10 10:17:23 +00003490 CHECK(quick_code != nullptr);
Elliott Hughes956af0f2014-12-11 14:34:28 -08003491 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08003492 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003493 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08003494}
3495
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003496// Does anything needed to make sure that the compiler will not generate a direct invoke to this
3497// method. Should only be called on non-invokable methods.
Nicolas Geoffrayf05f04b2019-10-31 11:50:41 +00003498inline void EnsureThrowsInvocationError(ClassLinker* class_linker, ArtMethod* method)
3499 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07003500 DCHECK(method != nullptr);
3501 DCHECK(!method->IsInvokable());
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003502 method->SetEntryPointFromQuickCompiledCodePtrSize(
3503 class_linker->GetQuickToInterpreterBridgeTrampoline(),
3504 class_linker->GetImagePointerSize());
Alex Light9139e002015-10-09 15:59:48 -07003505}
3506
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003507static void LinkCode(ClassLinker* class_linker,
3508 ArtMethod* method,
3509 const OatFile::OatClass* oat_class,
3510 uint32_t class_def_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light2d441b12018-06-08 15:33:21 -07003511 ScopedAssertNoThreadSuspension sants(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003512 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003513 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01003514 // The following code only applies to a non-compiler runtime.
3515 return;
3516 }
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003517
Ian Rogers62d6c772013-02-27 08:32:07 -08003518 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003519 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Jeff Hao16743632013-05-08 10:59:04 -07003520
Alex Light9139e002015-10-09 15:59:48 -07003521 if (!method->IsInvokable()) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01003522 EnsureThrowsInvocationError(class_linker, method);
Brian Carlstrom92827a52011-10-10 15:50:01 -07003523 return;
3524 }
Ian Rogers19846512012-02-24 11:42:47 -08003525
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003526 const void* quick_code = nullptr;
3527 if (oat_class != nullptr) {
3528 // Every kind of method should at least get an invoke stub from the oat_method.
3529 // non-abstract methods also get their code pointers.
3530 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
3531 quick_code = oat_method.GetQuickCode();
3532 }
3533
3534 bool enter_interpreter = class_linker->ShouldUseInterpreterEntrypoint(method, quick_code);
3535
3536 // Note: this mimics the logic in image_writer.cc that installs the resolution
3537 // stub only if we have compiled code and the method needs a class initialization
3538 // check.
Ulya Trafimovich5439f052020-07-29 10:03:46 +01003539 if (quick_code == nullptr) {
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003540 method->SetEntryPointFromQuickCompiledCode(
3541 method->IsNative() ? GetQuickGenericJniStub() : GetQuickToInterpreterBridge());
3542 } else if (enter_interpreter) {
3543 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Vladimir Marko5115a4d2019-10-17 14:56:47 +01003544 } else if (NeedsClinitCheckBeforeCall(method)) {
3545 DCHECK(!method->GetDeclaringClass()->IsVisiblyInitialized()); // Actually ClassStatus::Idx.
3546 // If we do have code but the method needs a class initialization check before calling
3547 // that code, install the resolution stub that will perform the check.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02003548 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
3549 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003550 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003551 } else {
3552 method->SetEntryPointFromQuickCompiledCode(quick_code);
Ian Rogers0d6de042012-02-29 08:50:26 -08003553 }
jeffhao26c0a1a2012-01-17 16:28:33 -08003554
Ian Rogers62d6c772013-02-27 08:32:07 -08003555 if (method->IsNative()) {
Vladimir Marko86c87522020-05-11 16:55:55 +01003556 // Set up the dlsym lookup stub. Do not go through `UnregisterNative()`
3557 // as the extra processing for @CriticalNative is not needed yet.
3558 method->SetEntryPointFromJni(
3559 method->IsCriticalNative() ? GetJniDlsymLookupCriticalStub() : GetJniDlsymLookupStub());
Andreas Gampe90546832014-03-12 18:07:19 -07003560
Tamas Berghammerdd5e5e92016-02-12 16:29:00 +00003561 if (enter_interpreter || quick_code == nullptr) {
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003562 // We have a native method here without code. Then it should have the generic JNI
3563 // trampoline as entrypoint.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07003564 // TODO: this doesn't handle all the cases where trampolines may be installed.
Nicolas Geoffray5ee206f2019-10-08 15:09:17 +01003565 DCHECK(class_linker->IsQuickGenericJniStub(method->GetEntryPointFromQuickCompiledCode()));
Andreas Gampe90546832014-03-12 18:07:19 -07003566 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07003567 }
3568}
3569
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003570void ClassLinker::SetupClass(const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003571 const dex::ClassDef& dex_class_def,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003572 Handle<mirror::Class> klass,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003573 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08003574 CHECK(klass != nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003575 CHECK(klass->GetDexCache() != nullptr);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003576 CHECK_EQ(ClassStatus::kNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07003577 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003578 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003579
Vladimir Markob4eb1b12018-05-24 11:09:38 +01003580 klass->SetClass(GetClassRoot<mirror::Class>(this));
Andreas Gampe51829322014-08-25 15:05:04 -07003581 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07003582 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Vladimir Markob68bb7a2020-03-17 10:55:25 +00003583 klass->SetAccessFlagsDuringLinking(access_flags);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003584 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08003585 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Vladimir Marko2c64a832018-01-04 11:31:56 +00003586 mirror::Class::SetStatus(klass, ClassStatus::kIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07003587
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003588 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003589 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003590}
Brian Carlstrom934486c2011-07-12 23:42:50 -07003591
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003592LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
3593 LinearAlloc* allocator,
3594 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003595 if (length == 0) {
3596 return nullptr;
3597 }
Vladimir Markocf36d492015-08-12 19:27:26 +01003598 // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
3599 static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
3600 size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003601 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003602 auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003603 CHECK(ret != nullptr);
3604 std::uninitialized_fill_n(&ret->At(0), length, ArtField());
3605 return ret;
Mathieu Chartierc7853442015-03-27 14:35:38 -07003606}
3607
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003608LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
3609 LinearAlloc* allocator,
3610 size_t length) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003611 if (length == 0) {
3612 return nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003613 }
Vladimir Marko14632852015-08-17 12:07:23 +01003614 const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
3615 const size_t method_size = ArtMethod::Size(image_pointer_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01003616 const size_t storage_size =
3617 LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003618 void* array_storage = allocator->Alloc(self, storage_size);
Vladimir Markocf36d492015-08-12 19:27:26 +01003619 auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003620 CHECK(ret != nullptr);
3621 for (size_t i = 0; i < length; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01003622 new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003623 }
3624 return ret;
Mathieu Chartiere401d142015-04-22 13:56:20 -07003625}
3626
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003627LinearAlloc* ClassLinker::GetAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003628 if (class_loader == nullptr) {
3629 return Runtime::Current()->GetLinearAlloc();
3630 }
3631 LinearAlloc* allocator = class_loader->GetAllocator();
3632 DCHECK(allocator != nullptr);
3633 return allocator;
3634}
3635
Mathieu Chartier28357fa2016-10-18 16:27:40 -07003636LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003637 if (class_loader == nullptr) {
3638 return Runtime::Current()->GetLinearAlloc();
3639 }
3640 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3641 LinearAlloc* allocator = class_loader->GetAllocator();
3642 if (allocator == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08003643 RegisterClassLoader(class_loader);
3644 allocator = class_loader->GetAllocator();
3645 CHECK(allocator != nullptr);
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003646 }
3647 return allocator;
3648}
3649
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003650void ClassLinker::LoadClass(Thread* self,
3651 const DexFile& dex_file,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003652 const dex::ClassDef& dex_class_def,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003653 Handle<mirror::Class> klass) {
David Brazdil20c765f2018-10-27 21:45:15 +00003654 ClassAccessor accessor(dex_file,
3655 dex_class_def,
3656 /* parse_hiddenapi_class_data= */ klass->IsBootStrapClassLoaded());
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003657 if (!accessor.HasClassData()) {
3658 return;
3659 }
3660 Runtime* const runtime = Runtime::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003661 {
3662 // Note: We cannot have thread suspension until the field and method arrays are setup or else
3663 // Class::VisitFieldRoots may miss some fields or methods.
Mathieu Chartier268764d2016-09-13 12:09:38 -07003664 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003665 // Load static fields.
Vladimir Marko23682bf2015-06-24 14:28:03 +01003666 // We allow duplicate definitions of the same field in a class_data_item
3667 // but ignore the repeated indexes here, b/21868015.
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003668 LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003669 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3670 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003671 accessor.NumStaticFields());
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07003672 LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3673 allocator,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003674 accessor.NumInstanceFields());
3675 size_t num_sfields = 0u;
Vladimir Marko23682bf2015-06-24 14:28:03 +01003676 size_t num_ifields = 0u;
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003677 uint32_t last_static_field_idx = 0u;
3678 uint32_t last_instance_field_idx = 0u;
Orion Hodsonc069a302017-01-18 09:23:12 +00003679
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003680 // Methods
3681 bool has_oat_class = false;
3682 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
3683 ? OatFile::FindOatClass(dex_file, klass->GetDexClassDefIndex(), &has_oat_class)
3684 : OatFile::OatClass::Invalid();
3685 const OatFile::OatClass* oat_class_ptr = has_oat_class ? &oat_class : nullptr;
3686 klass->SetMethodsPtr(
3687 AllocArtMethodArray(self, allocator, accessor.NumMethods()),
3688 accessor.NumDirectMethods(),
3689 accessor.NumVirtualMethods());
3690 size_t class_def_method_index = 0;
3691 uint32_t last_dex_method_index = dex::kDexNoIndex;
3692 size_t last_class_def_method_index = 0;
3693
3694 // Use the visitor since the ranged based loops are bit slower from seeking. Seeking to the
3695 // methods needs to decode all of the fields.
3696 accessor.VisitFieldsAndMethods([&](
3697 const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3698 uint32_t field_idx = field.GetIndex();
3699 DCHECK_GE(field_idx, last_static_field_idx); // Ordering enforced by DexFileVerifier.
3700 if (num_sfields == 0 || LIKELY(field_idx > last_static_field_idx)) {
3701 LoadField(field, klass, &sfields->At(num_sfields));
3702 ++num_sfields;
3703 last_static_field_idx = field_idx;
3704 }
3705 }, [&](const ClassAccessor::Field& field) REQUIRES_SHARED(Locks::mutator_lock_) {
3706 uint32_t field_idx = field.GetIndex();
3707 DCHECK_GE(field_idx, last_instance_field_idx); // Ordering enforced by DexFileVerifier.
3708 if (num_ifields == 0 || LIKELY(field_idx > last_instance_field_idx)) {
3709 LoadField(field, klass, &ifields->At(num_ifields));
3710 ++num_ifields;
3711 last_instance_field_idx = field_idx;
3712 }
3713 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3714 ArtMethod* art_method = klass->GetDirectMethodUnchecked(class_def_method_index,
3715 image_pointer_size_);
3716 LoadMethod(dex_file, method, klass, art_method);
3717 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3718 uint32_t it_method_index = method.GetIndex();
3719 if (last_dex_method_index == it_method_index) {
3720 // duplicate case
3721 art_method->SetMethodIndex(last_class_def_method_index);
3722 } else {
3723 art_method->SetMethodIndex(class_def_method_index);
3724 last_dex_method_index = it_method_index;
3725 last_class_def_method_index = class_def_method_index;
3726 }
3727 ++class_def_method_index;
3728 }, [&](const ClassAccessor::Method& method) REQUIRES_SHARED(Locks::mutator_lock_) {
3729 ArtMethod* art_method = klass->GetVirtualMethodUnchecked(
3730 class_def_method_index - accessor.NumDirectMethods(),
3731 image_pointer_size_);
3732 LoadMethod(dex_file, method, klass, art_method);
3733 LinkCode(this, art_method, oat_class_ptr, class_def_method_index);
3734 ++class_def_method_index;
3735 });
3736
3737 if (UNLIKELY(num_ifields + num_sfields != accessor.NumFields())) {
David Sehr709b0702016-10-13 09:12:37 -07003738 LOG(WARNING) << "Duplicate fields in class " << klass->PrettyDescriptor()
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003739 << " (unique static fields: " << num_sfields << "/" << accessor.NumStaticFields()
3740 << ", unique instance fields: " << num_ifields << "/" << accessor.NumInstanceFields()
3741 << ")";
Vladimir Marko81819db2015-11-05 15:30:12 +00003742 // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3743 if (sfields != nullptr) {
3744 sfields->SetSize(num_sfields);
3745 }
3746 if (ifields != nullptr) {
3747 ifields->SetSize(num_ifields);
3748 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003749 }
Vladimir Marko81819db2015-11-05 15:30:12 +00003750 // Set the field arrays.
3751 klass->SetSFieldsPtr(sfields);
3752 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07003753 klass->SetIFieldsPtr(ifields);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003754 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
Ian Rogers0571d352011-11-03 19:51:38 -07003755 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07003756 // Ensure that the card is marked so that remembered sets pick up native roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003757 WriteBarrier::ForEveryFieldWrite(klass.Get());
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07003758 self->AllowThreadSuspension();
Brian Carlstrom934486c2011-07-12 23:42:50 -07003759}
3760
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003761void ClassLinker::LoadField(const ClassAccessor::Field& field,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003762 Handle<mirror::Class> klass,
Mathieu Chartierc7853442015-03-27 14:35:38 -07003763 ArtField* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003764 const uint32_t field_idx = field.GetIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003765 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003766 dst->SetDeclaringClass(klass.Get());
David Brazdilf6a8a552018-01-15 18:10:50 +00003767
David Brazdil85865692018-10-30 17:26:20 +00003768 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3769 dst->SetAccessFlags(field.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(field));
Brian Carlstrom934486c2011-07-12 23:42:50 -07003770}
3771
Mathieu Chartier268764d2016-09-13 12:09:38 -07003772void ClassLinker::LoadMethod(const DexFile& dex_file,
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003773 const ClassAccessor::Method& method,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07003774 Handle<mirror::Class> klass,
3775 ArtMethod* dst) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07003776 const uint32_t dex_method_idx = method.GetIndex();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08003777 const dex::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003778 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07003779
Mathieu Chartier268764d2016-09-13 12:09:38 -07003780 ScopedAssertNoThreadSuspension ants("LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07003781 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003782 dst->SetDeclaringClass(klass.Get());
Brian Carlstrom934486c2011-07-12 23:42:50 -07003783
David Brazdil85865692018-10-30 17:26:20 +00003784 // Get access flags from the DexFile and set hiddenapi runtime access flags.
3785 uint32_t access_flags = method.GetAccessFlags() | hiddenapi::CreateRuntimeFlags(method);
David Brazdilf6a8a552018-01-15 18:10:50 +00003786
Ian Rogersdfb325e2013-10-30 01:00:44 -07003787 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003788 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003789 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
3790 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003791 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003792 klass->SetFinalizable();
3793 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003794 std::string temp;
3795 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07003796 // The Enum class declares a "final" finalize() method to prevent subclasses from
3797 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3798 // subclasses, so we exclude it here.
3799 // We also want to avoid setting the flag on Object, where we know that finalize() is
3800 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07003801 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
3802 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07003803 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07003804 }
3805 }
3806 }
3807 } else if (method_name[0] == '<') {
3808 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07003809 bool is_init = (strcmp("<init>", method_name) == 0);
3810 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07003811 if (UNLIKELY(!is_init && !is_clinit)) {
3812 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3813 } else {
3814 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3815 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
David Sehr709b0702016-10-13 09:12:37 -07003816 << klass->PrettyDescriptor() << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07003817 access_flags |= kAccConstructor;
3818 }
3819 }
3820 }
Vladimir Markob0a6aee2017-10-27 10:34:04 +01003821 if (UNLIKELY((access_flags & kAccNative) != 0u)) {
3822 // Check if the native method is annotated with @FastNative or @CriticalNative.
3823 access_flags |= annotations::GetNativeMethodAnnotationAccessFlags(
3824 dex_file, dst->GetClassDef(), dex_method_idx);
3825 }
Ian Rogers241b5de2013-10-09 17:58:57 -07003826 dst->SetAccessFlags(access_flags);
David Srbeckye36e7f22018-11-14 14:21:23 +00003827 // Must be done after SetAccessFlags since IsAbstract depends on it.
3828 if (klass->IsInterface() && dst->IsAbstract()) {
3829 dst->CalculateAndSetImtIndex();
3830 }
Nicolas Geoffray47171752020-08-31 15:03:20 +01003831 if (dst->HasCodeItem()) {
3832 DCHECK_NE(method.GetCodeItemOffset(), 0u);
3833 if (Runtime::Current()->IsAotCompiler()) {
3834 dst->SetDataPtrSize(reinterpret_cast32<void*>(method.GetCodeItemOffset()), image_pointer_size_);
3835 } else {
Nicolas Geoffraye1d2dce2020-09-21 10:06:31 +01003836 dst->SetCodeItem(dst->GetDexFile()->GetCodeItem(method.GetCodeItemOffset()));
Nicolas Geoffray47171752020-08-31 15:03:20 +01003837 }
3838 } else {
3839 dst->SetDataPtrSize(nullptr, image_pointer_size_);
3840 DCHECK_EQ(method.GetCodeItemOffset(), 0u);
3841 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07003842}
3843
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003844void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile* dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00003845 ObjPtr<mirror::DexCache> dex_cache = AllocAndInitializeDexCache(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07003846 self,
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003847 *dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003848 Runtime::Current()->GetLinearAlloc());
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003849 CHECK(dex_cache != nullptr) << "Failed to allocate dex cache for " << dex_file->GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003850 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07003851}
3852
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003853void ClassLinker::AppendToBootClassPath(const DexFile* dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003854 ObjPtr<mirror::DexCache> dex_cache) {
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003855 CHECK(dex_file != nullptr);
3856 CHECK(dex_cache != nullptr) << dex_file->GetLocation();
3857 boot_class_path_.push_back(dex_file);
Andreas Gampebe7af222017-07-25 09:57:28 -07003858 WriterMutexLock mu(Thread::Current(), *Locks::dex_lock_);
Mathieu Chartier0a19e212019-11-27 14:35:24 -08003859 RegisterDexFileLocked(*dex_file, dex_cache, /* class_loader= */ nullptr);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003860}
3861
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003862void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Vladimir Markocd556b02017-02-03 11:47:34 +00003863 ObjPtr<mirror::DexCache> dex_cache,
3864 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003865 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -08003866 Locks::dex_lock_->AssertExclusiveHeld(self);
Vladimir Markocd556b02017-02-03 11:47:34 +00003867 CHECK(dex_cache != nullptr) << dex_file.GetLocation();
David Srbecky86d6cd52020-12-02 18:13:10 +00003868 CHECK_EQ(dex_cache->GetDexFile(), &dex_file) << dex_file.GetLocation();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003869 // For app images, the dex cache location may be a suffix of the dex file location since the
3870 // dex file location is an absolute path.
Mathieu Chartier76172162016-01-26 14:54:06 -08003871 const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3872 const size_t dex_cache_length = dex_cache_location.length();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08003873 CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3874 std::string dex_file_location = dex_file.GetLocation();
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +00003875 // The following paths checks don't work on preopt when using boot dex files, where the dex
3876 // cache location is the one on device, and the dex_file's location is the one on host.
3877 if (!(Runtime::Current()->IsAotCompiler() && class_loader == nullptr && !kIsTargetBuild)) {
3878 CHECK_GE(dex_file_location.length(), dex_cache_length)
3879 << dex_cache_location << " " << dex_file.GetLocation();
3880 const std::string dex_file_suffix = dex_file_location.substr(
3881 dex_file_location.length() - dex_cache_length,
3882 dex_cache_length);
3883 // Example dex_cache location is SettingsProvider.apk and
3884 // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
3885 CHECK_EQ(dex_cache_location, dex_file_suffix);
3886 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003887 const OatFile* oat_file =
3888 (dex_file.GetOatDexFile() != nullptr) ? dex_file.GetOatDexFile()->GetOatFile() : nullptr;
Vladimir Markob066d432018-01-03 13:14:37 +00003889 // Clean up pass to remove null dex caches; null dex caches can occur due to class unloading
3890 // and we are lazily removing null entries. Also check if we need to initialize OatFile data
3891 // (.data.bimg.rel.ro and .bss sections) needed for code execution.
3892 bool initialize_oat_file_data = (oat_file != nullptr) && oat_file->IsExecutable();
Ian Rogers55256cb2017-12-21 17:07:11 -08003893 JavaVMExt* const vm = self->GetJniEnv()->GetVm();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003894 for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
3895 DexCacheData data = *it;
3896 if (self->IsJWeakCleared(data.weak_root)) {
3897 vm->DeleteWeakGlobalRef(self, data.weak_root);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003898 it = dex_caches_.erase(it);
3899 } else {
Vladimir Markob066d432018-01-03 13:14:37 +00003900 if (initialize_oat_file_data &&
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003901 it->dex_file->GetOatDexFile() != nullptr &&
3902 it->dex_file->GetOatDexFile()->GetOatFile() == oat_file) {
Vladimir Markob066d432018-01-03 13:14:37 +00003903 initialize_oat_file_data = false; // Already initialized.
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003904 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07003905 ++it;
3906 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07003907 }
Vladimir Markob066d432018-01-03 13:14:37 +00003908 if (initialize_oat_file_data) {
Vladimir Marko1cedb4a2019-02-06 14:13:28 +00003909 oat_file->InitializeRelocations();
Vladimir Marko0eb882b2017-05-15 13:39:18 +01003910 }
David Brazdila5c3a802019-03-08 14:59:41 +00003911 // Let hiddenapi assign a domain to the newly registered dex file.
3912 hiddenapi::InitializeDexFileDomain(dex_file, class_loader);
3913
Vladimir Markocd556b02017-02-03 11:47:34 +00003914 jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003915 DexCacheData data;
3916 data.weak_root = dex_cache_jweak;
3917 data.dex_file = dex_cache->GetDexFile();
Vladimir Markocd556b02017-02-03 11:47:34 +00003918 data.class_table = ClassTableForClassLoader(class_loader);
David Srbeckyafc60cd2018-12-05 11:59:31 +00003919 AddNativeDebugInfoForDex(self, data.dex_file);
Vladimir Markocd556b02017-02-03 11:47:34 +00003920 DCHECK(data.class_table != nullptr);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003921 // Make sure to hold the dex cache live in the class table. This case happens for the boot class
3922 // path dex caches without an image.
3923 data.class_table->InsertStrongRoot(dex_cache);
Andreas Gampe8a1a0f72020-03-03 16:07:45 -08003924 // Make sure that the dex cache holds the classloader live.
3925 dex_cache->SetClassLoader(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003926 if (class_loader != nullptr) {
3927 // Since we added a strong root to the class table, do the write barrier as required for
3928 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003929 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier72041a02017-07-14 18:23:25 -07003930 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08003931 dex_caches_.push_back(data);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003932}
3933
Alex Light725da8f2020-02-19 14:46:33 -08003934ObjPtr<mirror::DexCache> ClassLinker::DecodeDexCacheLocked(Thread* self, const DexCacheData* data) {
3935 return data != nullptr
3936 ? ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data->weak_root))
Vladimir Markocd556b02017-02-03 11:47:34 +00003937 : nullptr;
3938}
3939
Alex Light725da8f2020-02-19 14:46:33 -08003940bool ClassLinker::IsSameClassLoader(
Vladimir Markocd556b02017-02-03 11:47:34 +00003941 ObjPtr<mirror::DexCache> dex_cache,
Alex Light725da8f2020-02-19 14:46:33 -08003942 const DexCacheData* data,
Vladimir Markocd556b02017-02-03 11:47:34 +00003943 ObjPtr<mirror::ClassLoader> class_loader) {
Alex Light725da8f2020-02-19 14:46:33 -08003944 CHECK(data != nullptr);
3945 DCHECK_EQ(dex_cache->GetDexFile(), data->dex_file);
3946 return data->class_table == ClassTableForClassLoader(class_loader);
Vladimir Markocd556b02017-02-03 11:47:34 +00003947}
3948
Alex Light07f06212017-06-01 14:01:43 -07003949void ClassLinker::RegisterExistingDexCache(ObjPtr<mirror::DexCache> dex_cache,
3950 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartiered4ee442018-06-05 14:23:35 -07003951 SCOPED_TRACE << __FUNCTION__ << " " << dex_cache->GetDexFile()->GetLocation();
Alex Light07f06212017-06-01 14:01:43 -07003952 Thread* self = Thread::Current();
3953 StackHandleScope<2> hs(self);
3954 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
3955 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
3956 const DexFile* dex_file = dex_cache->GetDexFile();
3957 DCHECK(dex_file != nullptr) << "Attempt to register uninitialized dex_cache object!";
3958 if (kIsDebugBuild) {
Alex Light725da8f2020-02-19 14:46:33 -08003959 ReaderMutexLock mu(self, *Locks::dex_lock_);
3960 const DexCacheData* old_data = FindDexCacheDataLocked(*dex_file);
3961 ObjPtr<mirror::DexCache> old_dex_cache = DecodeDexCacheLocked(self, old_data);
Alex Light07f06212017-06-01 14:01:43 -07003962 DCHECK(old_dex_cache.IsNull()) << "Attempt to manually register a dex cache thats already "
3963 << "been registered on dex file " << dex_file->GetLocation();
3964 }
3965 ClassTable* table;
3966 {
3967 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3968 table = InsertClassTableForClassLoader(h_class_loader.Get());
3969 }
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003970 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
3971 // a thread holding the dex lock and blocking on a condition variable regarding
3972 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03003973 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Alex Light07f06212017-06-01 14:01:43 -07003974 WriterMutexLock mu(self, *Locks::dex_lock_);
3975 RegisterDexFileLocked(*dex_file, h_dex_cache.Get(), h_class_loader.Get());
3976 table->InsertStrongRoot(h_dex_cache.Get());
3977 if (h_class_loader.Get() != nullptr) {
3978 // Since we added a strong root to the class table, do the write barrier as required for
3979 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07003980 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Alex Light07f06212017-06-01 14:01:43 -07003981 }
3982}
3983
Alex Lightde7f8782020-02-24 10:14:22 -08003984static void ThrowDexFileAlreadyRegisteredError(Thread* self, const DexFile& dex_file)
3985 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light725da8f2020-02-19 14:46:33 -08003986 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
Alex Lightde7f8782020-02-24 10:14:22 -08003987 "Attempt to register dex file %s with multiple class loaders",
3988 dex_file.GetLocation().c_str());
Alex Light725da8f2020-02-19 14:46:33 -08003989}
3990
Vladimir Markocd556b02017-02-03 11:47:34 +00003991ObjPtr<mirror::DexCache> ClassLinker::RegisterDexFile(const DexFile& dex_file,
3992 ObjPtr<mirror::ClassLoader> class_loader) {
Ian Rogers1f539342012-10-03 21:09:42 -07003993 Thread* self = Thread::Current();
Alex Light725da8f2020-02-19 14:46:33 -08003994 ObjPtr<mirror::DexCache> old_dex_cache;
3995 bool registered_with_another_class_loader = false;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003996 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08003997 ReaderMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08003998 const DexCacheData* old_data = FindDexCacheDataLocked(dex_file);
3999 old_dex_cache = DecodeDexCacheLocked(self, old_data);
4000 if (old_dex_cache != nullptr) {
4001 if (IsSameClassLoader(old_dex_cache, old_data, class_loader)) {
4002 return old_dex_cache;
4003 } else {
4004 // TODO This is not very clean looking. Should maybe try to make a way to request exceptions
4005 // be thrown when it's safe to do so to simplify this.
4006 registered_with_another_class_loader = true;
4007 }
4008 }
Vladimir Markocd556b02017-02-03 11:47:34 +00004009 }
Alex Light725da8f2020-02-19 14:46:33 -08004010 // We need to have released the dex_lock_ to allocate safely.
4011 if (registered_with_another_class_loader) {
4012 ThrowDexFileAlreadyRegisteredError(self, dex_file);
4013 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07004014 }
Mathieu Chartiered4ee442018-06-05 14:23:35 -07004015 SCOPED_TRACE << __FUNCTION__ << " " << dex_file.GetLocation();
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004016 LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
4017 DCHECK(linear_alloc != nullptr);
4018 ClassTable* table;
4019 {
4020 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
4021 table = InsertClassTableForClassLoader(class_loader);
4022 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07004023 // Don't alloc while holding the lock, since allocation may need to
4024 // suspend all threads and another thread may need the dex_lock_ to
4025 // get to a suspend point.
Vladimir Markocd556b02017-02-03 11:47:34 +00004026 StackHandleScope<3> hs(self);
4027 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
David Srbecky86d6cd52020-12-02 18:13:10 +00004028 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004029 {
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004030 // Avoid a deadlock between a garbage collecting thread running a checkpoint,
4031 // a thread holding the dex lock and blocking on a condition variable regarding
4032 // weak references access, and a thread blocking on the dex lock.
Ivan Maidanski2b69b9c2018-05-14 13:50:48 +03004033 gc::ScopedGCCriticalSection gcs(self, gc::kGcCauseClassLinker, gc::kCollectorTypeClassLinker);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004034 WriterMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08004035 const DexCacheData* old_data = FindDexCacheDataLocked(dex_file);
4036 old_dex_cache = DecodeDexCacheLocked(self, old_data);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004037 if (old_dex_cache == nullptr && h_dex_cache != nullptr) {
David Srbecky86d6cd52020-12-02 18:13:10 +00004038 // Do InitializeNativeFields while holding dex lock to make sure two threads don't call it
4039 // at the same time with the same dex cache. Since the .bss is shared this can cause failing
4040 // DCHECK that the arrays are null.
4041 h_dex_cache->InitializeNativeFields(&dex_file, linear_alloc);
Vladimir Markocd556b02017-02-03 11:47:34 +00004042 RegisterDexFileLocked(dex_file, h_dex_cache.Get(), h_class_loader.Get());
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004043 }
Alex Light725da8f2020-02-19 14:46:33 -08004044 if (old_dex_cache != nullptr) {
4045 // Another thread managed to initialize the dex cache faster, so use that DexCache.
4046 // If this thread encountered OOME, ignore it.
4047 DCHECK_EQ(h_dex_cache == nullptr, self->IsExceptionPending());
4048 self->ClearException();
4049 // We cannot call EnsureSameClassLoader() or allocate an exception while holding the
4050 // dex_lock_.
4051 if (IsSameClassLoader(old_dex_cache, old_data, h_class_loader.Get())) {
4052 return old_dex_cache;
4053 } else {
4054 registered_with_another_class_loader = true;
4055 }
4056 }
Vladimir Markocd556b02017-02-03 11:47:34 +00004057 }
Alex Light725da8f2020-02-19 14:46:33 -08004058 if (registered_with_another_class_loader) {
4059 ThrowDexFileAlreadyRegisteredError(self, dex_file);
4060 return nullptr;
Vladimir Markocd556b02017-02-03 11:47:34 +00004061 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08004062 if (h_dex_cache == nullptr) {
Vladimir Markocd556b02017-02-03 11:47:34 +00004063 self->AssertPendingOOMException();
4064 return nullptr;
Brian Carlstrom47d237a2011-10-18 15:08:33 -07004065 }
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -07004066 table->InsertStrongRoot(h_dex_cache.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004067 if (h_class_loader.Get() != nullptr) {
4068 // Since we added a strong root to the class table, do the write barrier as required for
4069 // remembered sets and generational GCs.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004070 WriteBarrier::ForEveryFieldWrite(h_class_loader.Get());
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004071 }
Nicolas Geoffray1d4f0092020-08-07 14:01:05 +01004072 PaletteHooks* hooks = nullptr;
4073 VLOG(class_linker) << "Registered dex file " << dex_file.GetLocation();
Orion Hodsonc5323fe2021-02-04 21:20:30 +00004074 if (PaletteGetHooks(&hooks) == PALETTE_STATUS_OK) {
Nicolas Geoffray1d4f0092020-08-07 14:01:05 +01004075 hooks->NotifyDexFileLoaded(dex_file.GetLocation().c_str());
4076 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004077 return h_dex_cache.Get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07004078}
4079
Vladimir Markocd556b02017-02-03 11:47:34 +00004080bool ClassLinker::IsDexFileRegistered(Thread* self, const DexFile& dex_file) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004081 ReaderMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08004082 return DecodeDexCacheLocked(self, FindDexCacheDataLocked(dex_file)) != nullptr;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004083}
4084
Vladimir Markocd556b02017-02-03 11:47:34 +00004085ObjPtr<mirror::DexCache> ClassLinker::FindDexCache(Thread* self, const DexFile& dex_file) {
4086 ReaderMutexLock mu(self, *Locks::dex_lock_);
Alex Light725da8f2020-02-19 14:46:33 -08004087 const DexCacheData* dex_cache_data = FindDexCacheDataLocked(dex_file);
4088 ObjPtr<mirror::DexCache> dex_cache = DecodeDexCacheLocked(self, dex_cache_data);
Vladimir Markocd556b02017-02-03 11:47:34 +00004089 if (dex_cache != nullptr) {
4090 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07004091 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004092 // Failure, dump diagnostic and abort.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08004093 for (const DexCacheData& data : dex_caches_) {
Alex Light725da8f2020-02-19 14:46:33 -08004094 if (DecodeDexCacheLocked(self, &data) != nullptr) {
Andreas Gampe37c58462017-03-27 15:14:27 -07004095 LOG(FATAL_WITHOUT_ABORT) << "Registered dex file " << data.dex_file->GetLocation();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07004096 }
Brian Carlstrom81a90872015-08-28 09:07:14 -07004097 }
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004098 LOG(FATAL) << "Failed to find DexCache for DexFile " << dex_file.GetLocation()
Alex Light725da8f2020-02-19 14:46:33 -08004099 << " " << &dex_file << " " << dex_cache_data->dex_file;
Ian Rogerse0a02da2014-12-02 14:10:53 -08004100 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004101}
4102
Vladimir Markocd556b02017-02-03 11:47:34 +00004103ClassTable* ClassLinker::FindClassTable(Thread* self, ObjPtr<mirror::DexCache> dex_cache) {
4104 const DexFile* dex_file = dex_cache->GetDexFile();
4105 DCHECK(dex_file != nullptr);
4106 ReaderMutexLock mu(self, *Locks::dex_lock_);
4107 // 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 ObjPtr<mirror::DexCache> registered_dex_cache = DecodeDexCacheLocked(self, &data);
Vladimir Markocd556b02017-02-03 11:47:34 +00004112 if (registered_dex_cache != nullptr) {
4113 CHECK_EQ(registered_dex_cache, dex_cache) << dex_file->GetLocation();
4114 return data.class_table;
4115 }
4116 }
4117 }
4118 return nullptr;
4119}
4120
Alex Light725da8f2020-02-19 14:46:33 -08004121const ClassLinker::DexCacheData* ClassLinker::FindDexCacheDataLocked(const DexFile& dex_file) {
Vladimir Markocd556b02017-02-03 11:47:34 +00004122 // Search assuming unique-ness of dex file.
4123 for (const DexCacheData& data : dex_caches_) {
4124 // Avoid decoding (and read barriers) other unrelated dex caches.
4125 if (data.dex_file == &dex_file) {
Alex Light725da8f2020-02-19 14:46:33 -08004126 return &data;
Vladimir Markocd556b02017-02-03 11:47:34 +00004127 }
4128 }
Alex Light725da8f2020-02-19 14:46:33 -08004129 return nullptr;
Vladimir Markocd556b02017-02-03 11:47:34 +00004130}
4131
Vladimir Marko70e2a762019-07-12 16:49:00 +01004132void ClassLinker::CreatePrimitiveClass(Thread* self,
4133 Primitive::Type type,
4134 ClassRoot primitive_root) {
Vladimir Markoacb906d2018-05-30 10:23:49 +01004135 ObjPtr<mirror::Class> primitive_class =
Mathieu Chartier6beced42016-11-15 15:51:31 -08004136 AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
Vladimir Marko70e2a762019-07-12 16:49:00 +01004137 CHECK(primitive_class != nullptr) << "OOM for primitive class " << type;
4138 // Do not hold lock on the primitive class object, the initialization of
4139 // primitive classes is done while the process is still single threaded.
Vladimir Markob68bb7a2020-03-17 10:55:25 +00004140 primitive_class->SetAccessFlagsDuringLinking(
Vladimir Marko70e2a762019-07-12 16:49:00 +01004141 kAccPublic | kAccFinal | kAccAbstract | kAccVerificationAttempted);
4142 primitive_class->SetPrimitiveType(type);
4143 primitive_class->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
4144 // Skip EnsureSkipAccessChecksMethods(). We can skip the verified status,
4145 // the kAccVerificationAttempted flag was added above, and there are no
4146 // methods that need the kAccSkipAccessChecks flag.
4147 DCHECK_EQ(primitive_class->NumMethods(), 0u);
Vladimir Markobf121912019-06-04 13:49:05 +01004148 // Primitive classes are initialized during single threaded startup, so visibly initialized.
4149 primitive_class->SetStatusForPrimitiveOrArray(ClassStatus::kVisiblyInitialized);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004150 const char* descriptor = Primitive::Descriptor(type);
Mathieu Chartier6beced42016-11-15 15:51:31 -08004151 ObjPtr<mirror::Class> existing = InsertClass(descriptor,
Vladimir Marko70e2a762019-07-12 16:49:00 +01004152 primitive_class,
Mathieu Chartier6beced42016-11-15 15:51:31 -08004153 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004154 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Vladimir Marko70e2a762019-07-12 16:49:00 +01004155 SetClassRoot(primitive_root, primitive_class);
Carl Shapiro565f5072011-07-10 13:39:43 -07004156}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004157
Vladimir Marko02610552018-06-04 14:38:00 +01004158inline ObjPtr<mirror::IfTable> ClassLinker::GetArrayIfTable() {
4159 return GetClassRoot<mirror::ObjectArray<mirror::Object>>(this)->GetIfTable();
4160}
4161
Brian Carlstrombe977852011-07-19 14:54:54 -07004162// Create an array class (i.e. the class object for the array, not the
4163// array itself). "descriptor" looks like "[C" or "[[[[B" or
4164// "[Ljava/lang/String;".
4165//
4166// If "descriptor" refers to an array of primitives, look up the
4167// primitive type's internally-generated class object.
4168//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004169// "class_loader" is the class loader of the class that's referring to
4170// us. It's used to ensure that we're looking for the element type in
4171// the right context. It does NOT become the class loader for the
4172// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07004173//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07004174// Returns null with an exception raised on failure.
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004175ObjPtr<mirror::Class> ClassLinker::CreateArrayClass(Thread* self,
4176 const char* descriptor,
4177 size_t hash,
4178 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07004179 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004180 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004181 StackHandleScope<2> hs(self);
Alex Lighte9f61032018-09-24 16:04:51 -07004182
4183 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4184 // code to be executed. We put it up here so we can avoid all the allocations associated with
4185 // creating the class. This can happen with (eg) jit threads.
4186 if (!self->CanLoadClasses()) {
4187 // Make sure we don't try to load anything, potentially causing an infinite loop.
4188 ObjPtr<mirror::Throwable> pre_allocated =
4189 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4190 self->SetException(pre_allocated);
4191 return nullptr;
4192 }
4193
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004194 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
4195 class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004196 if (component_type == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004197 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004198 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004199 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
4200 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004201 if (component_type == nullptr) {
Andreas Gampedc13d7d2014-07-23 20:18:36 -07004202 DCHECK(self->IsExceptionPending());
4203 return nullptr;
4204 } else {
4205 self->ClearException();
4206 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004207 }
Ian Rogers2d10b202014-05-12 19:15:18 -07004208 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
4209 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
4210 return nullptr;
4211 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004212 // See if the component type is already loaded. Array classes are
4213 // always associated with the class loader of their underlying
4214 // element type -- an array of Strings goes with the loader for
4215 // java/lang/String -- so we need to look for it there. (The
4216 // caller should have checked for the existence of the class
4217 // before calling here, but they did so with *their* class loader,
4218 // not the component type's loader.)
4219 //
4220 // If we find it, the caller adds "loader" to the class' initiating
4221 // loader list, which should prevent us from going through this again.
4222 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004223 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004224 // are the same, because our caller (FindClass) just did the
4225 // lookup. (Even if we get this wrong we still have correct behavior,
4226 // because we effectively do this lookup again when we add the new
4227 // class to the hash table --- necessary because of possible races with
4228 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004229 if (class_loader.Get() != component_type->GetClassLoader()) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00004230 ObjPtr<mirror::Class> new_class =
4231 LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004232 if (new_class != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004233 return new_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004234 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004235 }
Vladimir Marko70e2a762019-07-12 16:49:00 +01004236 // Core array classes, i.e. Object[], Class[], String[] and primitive
4237 // arrays, have special initialization and they should be found above.
4238 DCHECK(!component_type->IsObjectClass() ||
4239 // Guard from false positives for errors before setting superclass.
4240 component_type->IsErroneousUnresolved());
4241 DCHECK(!component_type->IsStringClass());
4242 DCHECK(!component_type->IsClassClass());
4243 DCHECK(!component_type->IsPrimitive());
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004244
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004245 // Fill out the fields in the Class.
4246 //
4247 // It is possible to execute some methods against arrays, because
4248 // all arrays are subclasses of java_lang_Object_, so we need to set
4249 // up a vtable. We can just point at the one in java_lang_Object_.
4250 //
4251 // Array classes are simple enough that we don't need to do a full
4252 // link step.
Vladimir Marko70e2a762019-07-12 16:49:00 +01004253 size_t array_class_size = mirror::Array::ClassSize(image_pointer_size_);
4254 auto visitor = [this, array_class_size, component_type](ObjPtr<mirror::Object> obj,
4255 size_t usable_size)
4256 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markob68bb7a2020-03-17 10:55:25 +00004257 ScopedAssertNoNewTransactionRecords sanntr("CreateArrayClass");
Vladimir Marko70e2a762019-07-12 16:49:00 +01004258 mirror::Class::InitializeClassVisitor init_class(array_class_size);
4259 init_class(obj, usable_size);
4260 ObjPtr<mirror::Class> klass = ObjPtr<mirror::Class>::DownCast(obj);
4261 klass->SetComponentType(component_type.Get());
4262 // Do not hold lock for initialization, the fence issued after the visitor
4263 // returns ensures memory visibility together with the implicit consume
4264 // semantics (for all supported architectures) for any thread that loads
4265 // the array class reference from any memory locations afterwards.
4266 FinishArrayClassSetup(klass);
4267 };
4268 auto new_class = hs.NewHandle<mirror::Class>(
4269 AllocClass(self, GetClassRoot<mirror::Class>(this), array_class_size, visitor));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004270 if (new_class == nullptr) {
Vladimir Marko70e2a762019-07-12 16:49:00 +01004271 self->AssertPendingOOMException();
4272 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004273 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004274
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004275 ObjPtr<mirror::Class> existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08004276 if (existing == nullptr) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004277 // We postpone ClassLoad and ClassPrepare events to this point in time to avoid
4278 // duplicate events in case of races. Array classes don't really follow dedicated
4279 // load and prepare, anyways.
4280 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(new_class);
4281 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(new_class, new_class);
4282
Tamas Berghammer160e6df2016-01-05 14:29:02 +00004283 jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004284 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004285 }
4286 // Another thread must have loaded the class after we
4287 // started but before we finished. Abandon what we've
4288 // done.
4289 //
4290 // (Yes, this happens.)
4291
Vladimir Markobcf17522018-06-01 13:14:32 +01004292 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07004293}
4294
Vladimir Marko9186b182018-11-06 14:55:54 +00004295ObjPtr<mirror::Class> ClassLinker::LookupPrimitiveClass(char type) {
4296 ClassRoot class_root;
Ian Rogers62f05122014-03-21 11:21:29 -07004297 switch (type) {
Vladimir Marko9186b182018-11-06 14:55:54 +00004298 case 'B': class_root = ClassRoot::kPrimitiveByte; break;
4299 case 'C': class_root = ClassRoot::kPrimitiveChar; break;
4300 case 'D': class_root = ClassRoot::kPrimitiveDouble; break;
4301 case 'F': class_root = ClassRoot::kPrimitiveFloat; break;
4302 case 'I': class_root = ClassRoot::kPrimitiveInt; break;
4303 case 'J': class_root = ClassRoot::kPrimitiveLong; break;
4304 case 'S': class_root = ClassRoot::kPrimitiveShort; break;
4305 case 'Z': class_root = ClassRoot::kPrimitiveBoolean; break;
4306 case 'V': class_root = ClassRoot::kPrimitiveVoid; break;
Ian Rogers62f05122014-03-21 11:21:29 -07004307 default:
Vladimir Marko9186b182018-11-06 14:55:54 +00004308 return nullptr;
Carl Shapiro744ad052011-08-06 15:53:36 -07004309 }
Vladimir Marko9186b182018-11-06 14:55:54 +00004310 return GetClassRoot(class_root, this);
4311}
4312
4313ObjPtr<mirror::Class> ClassLinker::FindPrimitiveClass(char type) {
4314 ObjPtr<mirror::Class> result = LookupPrimitiveClass(type);
4315 if (UNLIKELY(result == nullptr)) {
4316 std::string printable_type(PrintableChar(type));
4317 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
4318 }
4319 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004320}
4321
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004322ObjPtr<mirror::Class> ClassLinker::InsertClass(const char* descriptor,
4323 ObjPtr<mirror::Class> klass,
4324 size_t hash) {
Alex Lighte9f61032018-09-24 16:04:51 -07004325 DCHECK(Thread::Current()->CanLoadClasses());
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08004326 if (VLOG_IS_ON(class_linker)) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004327 ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08004328 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004329 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08004330 source += " from ";
4331 source += dex_cache->GetLocation()->ToModifiedUtf8();
4332 }
4333 LOG(INFO) << "Loaded class " << descriptor << source;
4334 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004335 {
4336 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00004337 const ObjPtr<mirror::ClassLoader> class_loader = klass->GetClassLoader();
Mathieu Chartier65975772016-08-05 10:46:36 -07004338 ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004339 ObjPtr<mirror::Class> existing = class_table->Lookup(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004340 if (existing != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004341 return existing;
Mathieu Chartier65975772016-08-05 10:46:36 -07004342 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004343 VerifyObject(klass);
4344 class_table->InsertWithHash(klass, hash);
4345 if (class_loader != nullptr) {
4346 // This is necessary because we need to have the card dirtied for remembered sets.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004347 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier65975772016-08-05 10:46:36 -07004348 }
Vladimir Marko1998cd02017-01-13 13:02:58 +00004349 if (log_new_roots_) {
Mathieu Chartier65975772016-08-05 10:46:36 -07004350 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004351 }
4352 }
Mathieu Chartier65975772016-08-05 10:46:36 -07004353 if (kIsDebugBuild) {
4354 // Test that copied methods correctly can find their holder.
4355 for (ArtMethod& method : klass->GetCopiedMethods(image_pointer_size_)) {
4356 CHECK_EQ(GetHoldingClassOfCopiedMethod(&method), klass);
4357 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08004358 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004359 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004360}
4361
Vladimir Marko1998cd02017-01-13 13:02:58 +00004362void ClassLinker::WriteBarrierForBootOatFileBssRoots(const OatFile* oat_file) {
Mathieu Chartiera1467d02017-02-22 09:22:50 -08004363 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
4364 DCHECK(!oat_file->GetBssGcRoots().empty()) << oat_file->GetLocation();
4365 if (log_new_roots_ && !ContainsElement(new_bss_roots_boot_oat_files_, oat_file)) {
4366 new_bss_roots_boot_oat_files_.push_back(oat_file);
Vladimir Marko1998cd02017-01-13 13:02:58 +00004367 }
4368}
4369
Alex Lighte64300b2015-12-15 15:02:47 -08004370// TODO This should really be in mirror::Class.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004371void ClassLinker::UpdateClassMethods(ObjPtr<mirror::Class> klass,
Alex Lighte64300b2015-12-15 15:02:47 -08004372 LengthPrefixedArray<ArtMethod>* new_methods) {
4373 klass->SetMethodsPtrUnchecked(new_methods,
4374 klass->NumDirectMethods(),
4375 klass->NumDeclaredVirtualMethods());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004376 // Need to mark the card so that the remembered sets and mod union tables get updated.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07004377 WriteBarrier::ForEveryFieldWrite(klass);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004378}
4379
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004380ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4381 const char* descriptor,
4382 ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2ff3b972017-06-05 18:14:53 -07004383 return LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor), class_loader);
4384}
4385
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004386ObjPtr<mirror::Class> ClassLinker::LookupClass(Thread* self,
4387 const char* descriptor,
4388 size_t hash,
4389 ObjPtr<mirror::ClassLoader> class_loader) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01004390 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
4391 ClassTable* const class_table = ClassTableForClassLoader(class_loader);
4392 if (class_table != nullptr) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004393 ObjPtr<mirror::Class> result = class_table->Lookup(descriptor, hash);
Vladimir Marko1a1de672016-10-13 12:53:15 +01004394 if (result != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01004395 return result;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004396 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07004397 }
Vladimir Marko1a1de672016-10-13 12:53:15 +01004398 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004399}
4400
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004401class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
4402 public:
Igor Murashkin2ffb7032017-11-08 13:35:21 -08004403 MoveClassTableToPreZygoteVisitor() {}
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004404
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004405 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004406 REQUIRES(Locks::classlinker_classes_lock_)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004407 REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004408 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07004409 if (class_table != nullptr) {
4410 class_table->FreezeSnapshot();
4411 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07004412 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004413};
4414
4415void ClassLinker::MoveClassTableToPreZygote() {
4416 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Andreas Gampe2af99022017-04-25 08:32:59 -07004417 boot_class_table_->FreezeSnapshot();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004418 MoveClassTableToPreZygoteVisitor visitor;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004419 VisitClassLoaders(&visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08004420}
4421
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004422// Look up classes by hash and descriptor and put all matching ones in the result array.
4423class LookupClassesVisitor : public ClassLoaderVisitor {
4424 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004425 LookupClassesVisitor(const char* descriptor,
4426 size_t hash,
4427 std::vector<ObjPtr<mirror::Class>>* result)
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004428 : descriptor_(descriptor),
4429 hash_(hash),
4430 result_(result) {}
4431
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004432 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004433 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004434 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004435 ObjPtr<mirror::Class> klass = class_table->Lookup(descriptor_, hash_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004436 // Add `klass` only if `class_loader` is its defining (not just initiating) class loader.
4437 if (klass != nullptr && klass->GetClassLoader() == class_loader) {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004438 result_->push_back(klass);
4439 }
4440 }
4441
4442 private:
4443 const char* const descriptor_;
4444 const size_t hash_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004445 std::vector<ObjPtr<mirror::Class>>* const result_;
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004446};
4447
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004448void ClassLinker::LookupClasses(const char* descriptor,
4449 std::vector<ObjPtr<mirror::Class>>& result) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004450 result.clear();
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004451 Thread* const self = Thread::Current();
4452 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004453 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2af99022017-04-25 08:32:59 -07004454 ObjPtr<mirror::Class> klass = boot_class_table_->Lookup(descriptor, hash);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004455 if (klass != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00004456 DCHECK(klass->GetClassLoader() == nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07004457 result.push_back(klass);
4458 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07004459 LookupClassesVisitor visitor(descriptor, hash, &result);
4460 VisitClassLoaders(&visitor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08004461}
4462
Alex Lightf1f10492015-10-07 16:08:36 -07004463bool ClassLinker::AttemptSupertypeVerification(Thread* self,
4464 Handle<mirror::Class> klass,
4465 Handle<mirror::Class> supertype) {
4466 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08004467 DCHECK(klass != nullptr);
4468 DCHECK(supertype != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004469
Alex Lightf1f10492015-10-07 16:08:36 -07004470 if (!supertype->IsVerified() && !supertype->IsErroneous()) {
4471 VerifyClass(self, supertype);
4472 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004473
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004474 if (supertype->IsVerified()
4475 || supertype->ShouldVerifyAtRuntime()
4476 || supertype->IsVerifiedNeedsAccessChecks()) {
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004477 // The supertype is either verified, or we soft failed at AOT time.
4478 DCHECK(supertype->IsVerified() || Runtime::Current()->IsAotCompiler());
Alex Lightf1f10492015-10-07 16:08:36 -07004479 return true;
4480 }
4481 // If we got this far then we have a hard failure.
4482 std::string error_msg =
4483 StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
David Sehr709b0702016-10-13 09:12:37 -07004484 klass->PrettyDescriptor().c_str(),
4485 supertype->PrettyDescriptor().c_str());
Alex Lightf1f10492015-10-07 16:08:36 -07004486 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004487 StackHandleScope<1> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004488 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004489 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004490 // Set during VerifyClass call (if at all).
4491 self->ClearException();
4492 }
4493 // Change into a verify error.
4494 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Andreas Gampefa4333d2017-02-14 11:10:34 -08004495 if (cause != nullptr) {
Alex Lightf1f10492015-10-07 16:08:36 -07004496 self->GetException()->SetCause(cause.Get());
4497 }
4498 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
4499 if (Runtime::Current()->IsAotCompiler()) {
4500 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
4501 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004502 // Need to grab the lock to change status.
4503 ObjectLock<mirror::Class> super_lock(self, klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00004504 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004505 return false;
4506}
4507
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004508verifier::FailureKind ClassLinker::VerifyClass(
Nicolas Geoffray08025182016-10-25 17:20:18 +01004509 Thread* self, Handle<mirror::Class> klass, verifier::HardFailLogMode log_level) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004510 {
4511 // TODO: assert that the monitor on the Class is held
4512 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08004513
Andreas Gampe884f3b82016-03-30 19:52:58 -07004514 // Is somebody verifying this now?
Vladimir Marko2c64a832018-01-04 11:31:56 +00004515 ClassStatus old_status = klass->GetStatus();
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004516 while (old_status == ClassStatus::kVerifying) {
Andreas Gampe884f3b82016-03-30 19:52:58 -07004517 lock.WaitIgnoringInterrupts();
Mathieu Chartier5ef70202017-06-29 10:45:10 -07004518 // WaitIgnoringInterrupts can still receive an interrupt and return early, in this
4519 // case we may see the same status again. b/62912904. This is why the check is
4520 // greater or equal.
4521 CHECK(klass->IsErroneous() || (klass->GetStatus() >= old_status))
David Sehr709b0702016-10-13 09:12:37 -07004522 << "Class '" << klass->PrettyClass()
4523 << "' performed an illegal verification state transition from " << old_status
4524 << " to " << klass->GetStatus();
Andreas Gampe884f3b82016-03-30 19:52:58 -07004525 old_status = klass->GetStatus();
4526 }
jeffhao98eacac2011-09-14 16:11:53 -07004527
Andreas Gampe884f3b82016-03-30 19:52:58 -07004528 // The class might already be erroneous, for example at compile time if we attempted to verify
4529 // this class as a parent to another.
4530 if (klass->IsErroneous()) {
4531 ThrowEarlierClassFailure(klass.Get());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004532 return verifier::FailureKind::kHardFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004533 }
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08004534
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004535 // Don't attempt to re-verify if already verified.
Andreas Gampe884f3b82016-03-30 19:52:58 -07004536 if (klass->IsVerified()) {
Andreas Gampecc1b5352016-12-01 16:58:38 -08004537 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004538 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004539 }
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004540
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004541 if (klass->IsVerifiedNeedsAccessChecks()) {
4542 if (!Runtime::Current()->IsAotCompiler()) {
4543 // Mark the class as having a verification attempt to avoid re-running
4544 // the verifier and avoid calling EnsureSkipAccessChecksMethods.
4545 klass->SetVerificationAttempted();
4546 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
4547 }
4548 return verifier::FailureKind::kAccessChecksFailure;
4549 }
4550
Nicolas Geoffray7cc3ae52017-03-07 14:33:37 +00004551 // For AOT, don't attempt to re-verify if we have already found we should
4552 // verify at runtime.
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004553 if (klass->ShouldVerifyAtRuntime()) {
4554 CHECK(Runtime::Current()->IsAotCompiler());
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004555 return verifier::FailureKind::kSoftFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004556 }
jeffhao98eacac2011-09-14 16:11:53 -07004557
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004558 DCHECK_EQ(klass->GetStatus(), ClassStatus::kResolved);
4559 mirror::Class::SetStatus(klass, ClassStatus::kVerifying, self);
Andreas Gampe884f3b82016-03-30 19:52:58 -07004560
4561 // Skip verification if disabled.
4562 if (!Runtime::Current()->IsVerificationEnabled()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004563 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Andreas Gampecc1b5352016-12-01 16:58:38 -08004564 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004565 return verifier::FailureKind::kNoFailure;
Andreas Gampe884f3b82016-03-30 19:52:58 -07004566 }
Jeff Hao4a200f52014-04-01 14:58:49 -07004567 }
4568
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004569 VLOG(class_linker) << "Beginning verification for class: "
4570 << klass->PrettyDescriptor()
4571 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
4572
Ian Rogers9ffb0392012-09-10 11:56:50 -07004573 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004574 StackHandleScope<2> hs(self);
Alex Lightf1f10492015-10-07 16:08:36 -07004575 MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
4576 // If we have a superclass and we get a hard verification failure we can return immediately.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004577 if (supertype != nullptr && !AttemptSupertypeVerification(self, klass, supertype)) {
Alex Lightf1f10492015-10-07 16:08:36 -07004578 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004579 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004580 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004581
Alex Lightf1f10492015-10-07 16:08:36 -07004582 // Verify all default super-interfaces.
4583 //
4584 // (1) Don't bother if the superclass has already had a soft verification failure.
4585 //
4586 // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
4587 // recursive initialization by themselves. This is because when an interface is initialized
4588 // directly it must not initialize its superinterfaces. We are allowed to verify regardless
4589 // but choose not to for an optimization. If the interfaces is being verified due to a class
4590 // initialization (which would need all the default interfaces to be verified) the class code
4591 // will trigger the recursive verification anyway.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004592 if ((supertype == nullptr || supertype->IsVerified()) // See (1)
Alex Lightf1f10492015-10-07 16:08:36 -07004593 && !klass->IsInterface()) { // See (2)
4594 int32_t iftable_count = klass->GetIfTableCount();
4595 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
4596 // Loop through all interfaces this class has defined. It doesn't matter the order.
4597 for (int32_t i = 0; i < iftable_count; i++) {
4598 iface.Assign(klass->GetIfTable()->GetInterface(i));
Andreas Gampefa4333d2017-02-14 11:10:34 -08004599 DCHECK(iface != nullptr);
Alex Lightf1f10492015-10-07 16:08:36 -07004600 // We only care if we have default interfaces and can skip if we are already verified...
4601 if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
4602 continue;
4603 } else if (UNLIKELY(!AttemptSupertypeVerification(self, klass, iface))) {
4604 // We had a hard failure while verifying this interface. Just return immediately.
4605 CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004606 return verifier::FailureKind::kHardFailure;
Alex Lightf1f10492015-10-07 16:08:36 -07004607 } else if (UNLIKELY(!iface->IsVerified())) {
4608 // We softly failed to verify the iface. Stop checking and clean up.
4609 // Put the iface into the supertype handle so we know what caused us to fail.
4610 supertype.Assign(iface.Get());
4611 break;
Ian Rogers1c5eb702012-02-01 09:18:34 -08004612 }
Ian Rogers1c5eb702012-02-01 09:18:34 -08004613 }
4614 }
4615
Alex Lightf1f10492015-10-07 16:08:36 -07004616 // At this point if verification failed, then supertype is the "first" supertype that failed
4617 // verification (without a specific order). If verification succeeded, then supertype is either
4618 // null or the original superclass of klass and is verified.
Andreas Gampefa4333d2017-02-14 11:10:34 -08004619 DCHECK(supertype == nullptr ||
Alex Lightf1f10492015-10-07 16:08:36 -07004620 supertype.Get() == klass->GetSuperClass() ||
4621 !supertype->IsVerified());
4622
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004623 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07004624 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004625 ClassStatus oat_file_class_status(ClassStatus::kNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004626 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004627
4628 VLOG(class_linker) << "Class preverified status for class "
4629 << klass->PrettyDescriptor()
4630 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4631 << ": "
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004632 << preverified
4633 << "( " << oat_file_class_status << ")";
Bharadwaj Kalandhabhatta271c1e12017-06-27 11:14:49 -07004634
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004635 // If the oat file says the class had an error, re-run the verifier. That way we will get a
4636 // precise error message. To ensure a rerun, test:
Vladimir Marko72ab6842017-01-20 19:32:50 +00004637 // mirror::Class::IsErroneous(oat_file_class_status) => !preverified
4638 DCHECK(!mirror::Class::IsErroneous(oat_file_class_status) || !preverified);
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004639
Ian Rogers62d6c772013-02-27 08:32:07 -08004640 std::string error_msg;
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004641 verifier::FailureKind verifier_failure = verifier::FailureKind::kNoFailure;
jeffhaof1e6b7c2012-06-05 18:33:30 -07004642 if (!preverified) {
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004643 verifier_failure = PerformClassVerification(self, klass, log_level, &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07004644 }
Andreas Gampe884f3b82016-03-30 19:52:58 -07004645
4646 // Verification is done, grab the lock again.
4647 ObjectLock<mirror::Class> lock(self, klass);
4648
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004649 if (preverified || verifier_failure != verifier::FailureKind::kHardFailure) {
4650 if (!preverified && verifier_failure != verifier::FailureKind::kNoFailure) {
David Sehr709b0702016-10-13 09:12:37 -07004651 VLOG(class_linker) << "Soft verification failure in class "
4652 << klass->PrettyDescriptor()
4653 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4654 << " because: " << error_msg;
Ian Rogers529781d2012-07-23 17:24:29 -07004655 }
Ian Rogers1f539342012-10-03 21:09:42 -07004656 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004657 // Make sure all classes referenced by catch blocks are resolved.
Alex Light5a559862016-01-29 12:24:48 -08004658 ResolveClassExceptionHandlerTypes(klass);
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004659 if (verifier_failure == verifier::FailureKind::kNoFailure) {
Alex Lightf1f10492015-10-07 16:08:36 -07004660 // Even though there were no verifier failures we need to respect whether the super-class and
4661 // super-default-interfaces were verified or requiring runtime reverification.
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004662 if (supertype == nullptr
4663 || supertype->IsVerified()
4664 || supertype->IsVerifiedNeedsAccessChecks()) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004665 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004666 } else {
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004667 CHECK(Runtime::Current()->IsAotCompiler());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004668 CHECK_EQ(supertype->GetStatus(), ClassStatus::kRetryVerificationAtRuntime);
4669 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
Alex Lightf1f10492015-10-07 16:08:36 -07004670 // Pretend a soft failure occurred so that we don't consider the class verified below.
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004671 verifier_failure = verifier::FailureKind::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07004672 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004673 } else {
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004674 CHECK(verifier_failure == verifier::FailureKind::kSoftFailure ||
Nicolas Geoffrayd1728bf2021-01-12 14:02:29 +00004675 verifier_failure == verifier::FailureKind::kTypeChecksFailure ||
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004676 verifier_failure == verifier::FailureKind::kAccessChecksFailure);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004677 // Soft failures at compile time should be retried at runtime. Soft
4678 // failures at runtime will be handled by slow paths in the generated
4679 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004680 if (Runtime::Current()->IsAotCompiler()) {
Nicolas Geoffrayd1728bf2021-01-12 14:02:29 +00004681 if (verifier_failure == verifier::FailureKind::kSoftFailure ||
4682 verifier_failure == verifier::FailureKind::kTypeChecksFailure) {
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004683 mirror::Class::SetStatus(klass, ClassStatus::kRetryVerificationAtRuntime, self);
4684 } else {
4685 mirror::Class::SetStatus(klass, ClassStatus::kVerifiedNeedsAccessChecks, self);
4686 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004687 } else {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004688 mirror::Class::SetStatus(klass, ClassStatus::kVerified, self);
Igor Murashkindf707e42016-02-02 16:56:50 -08004689 // As this is a fake verified status, make sure the methods are _not_ marked
4690 // kAccSkipAccessChecks later.
4691 klass->SetVerificationAttempted();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07004692 }
4693 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07004694 } else {
David Sehr709b0702016-10-13 09:12:37 -07004695 VLOG(verifier) << "Verification failed on class " << klass->PrettyDescriptor()
Andreas Gampeec6e6c12015-11-05 20:39:56 -08004696 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
4697 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004698 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004699 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004700 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07004701 }
Andreas Gampe6d7abbd2017-04-24 13:19:09 -07004702 if (preverified || verifier_failure == verifier::FailureKind::kNoFailure) {
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004703 if (oat_file_class_status == ClassStatus::kVerifiedNeedsAccessChecks ||
4704 UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
Igor Murashkindf707e42016-02-02 16:56:50 -08004705 // Never skip access checks if the verification soft fail is forced.
4706 // Mark the class as having a verification attempt to avoid re-running the verifier.
4707 klass->SetVerificationAttempted();
4708 } else {
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004709 // Class is verified so we don't need to do any access check on its methods.
4710 // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
4711 // method.
4712 // Note: we're going here during compilation and at runtime. When we set the
4713 // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
4714 // in the image and is set when loading the image.
Andreas Gampecc1b5352016-12-01 16:58:38 -08004715 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Igor Murashkindf707e42016-02-02 16:56:50 -08004716 }
Andreas Gampe48498592014-09-10 19:48:05 -07004717 }
Nicolas Geoffray486dda02017-09-11 14:15:52 +01004718 // Done verifying. Notify the compiler about the verification status, in case the class
4719 // was verified implicitly (eg super class of a compiled class).
4720 if (Runtime::Current()->IsAotCompiler()) {
4721 Runtime::Current()->GetCompilerCallbacks()->UpdateClassState(
4722 ClassReference(&klass->GetDexFile(), klass->GetDexClassDefIndex()), klass->GetStatus());
4723 }
Nicolas Geoffray08025182016-10-25 17:20:18 +01004724 return verifier_failure;
Andreas Gampe48498592014-09-10 19:48:05 -07004725}
4726
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004727verifier::FailureKind ClassLinker::PerformClassVerification(Thread* self,
4728 Handle<mirror::Class> klass,
4729 verifier::HardFailLogMode log_level,
4730 std::string* error_msg) {
4731 Runtime* const runtime = Runtime::Current();
Andreas Gampea43ba3d2019-03-13 15:49:20 -07004732 return verifier::ClassVerifier::VerifyClass(self,
4733 klass.Get(),
4734 runtime->GetCompilerCallbacks(),
4735 runtime->IsAotCompiler(),
4736 log_level,
4737 Runtime::Current()->GetTargetSdkVersion(),
4738 error_msg);
Mathieu Chartier9e050df2017-08-09 10:05:47 -07004739}
4740
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07004741bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004742 ObjPtr<mirror::Class> klass,
Vladimir Marko2c64a832018-01-04 11:31:56 +00004743 ClassStatus& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004744 // If we're compiling, we can only verify the class using the oat file if
4745 // we are not compiling the image or if the class we're verifying is not part of
Andreas Gampee9934582018-01-19 21:23:04 -08004746 // the compilation unit (app - dependencies). We will let the compiler callback
4747 // tell us about the latter.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08004748 if (Runtime::Current()->IsAotCompiler()) {
Andreas Gampee9934582018-01-19 21:23:04 -08004749 CompilerCallbacks* callbacks = Runtime::Current()->GetCompilerCallbacks();
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004750 // We are compiling an app (not the image).
Andreas Gampee9934582018-01-19 21:23:04 -08004751 if (!callbacks->CanUseOatStatusForVerification(klass.Ptr())) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004752 return false;
4753 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004754 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07004755
Andreas Gampeb40d3612018-06-26 15:49:42 -07004756 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004757 // In case we run without an image there won't be a backing oat file.
Mathieu Chartier1b868492016-11-16 16:22:37 -08004758 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07004759 return false;
4760 }
4761
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004762 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01004763 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Vladimir Marko2c64a832018-01-04 11:31:56 +00004764 if (oat_file_class_status >= ClassStatus::kVerified) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004765 return true;
4766 }
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004767 if (oat_file_class_status >= ClassStatus::kVerifiedNeedsAccessChecks) {
4768 // We return that the clas has already been verified, and the caller should
4769 // check the class status to ensure we run with access checks.
4770 return true;
4771 }
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004772 // If we only verified a subset of the classes at compile time, we can end up with classes that
4773 // were resolved by the verifier.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004774 if (oat_file_class_status == ClassStatus::kResolved) {
Mathieu Chartiera079e3a2016-03-16 19:08:31 -07004775 return false;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004776 }
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01004777 // We never expect a .oat file to have kRetryVerificationAtRuntime statuses.
4778 CHECK_NE(oat_file_class_status, ClassStatus::kRetryVerificationAtRuntime)
4779 << klass->PrettyClass() << " " << dex_file.GetLocation();
4780
Vladimir Marko72ab6842017-01-20 19:32:50 +00004781 if (mirror::Class::IsErroneous(oat_file_class_status)) {
jeffhao1ac29442012-03-26 11:37:32 -07004782 // Compile time verification failed with a hard error. This is caused by invalid instructions
4783 // in the class. These errors are unrecoverable.
4784 return false;
4785 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00004786 if (oat_file_class_status == ClassStatus::kNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08004787 // Status is uninitialized if we couldn't determine the status at compile time, for example,
4788 // not loading the class.
4789 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4790 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004791 return false;
4792 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07004793 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07004794 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
David Sehr709b0702016-10-13 09:12:37 -07004795 << " " << dex_file.GetLocation() << " " << klass->PrettyClass() << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07004796 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08004797 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004798}
4799
Alex Light5a559862016-01-29 12:24:48 -08004800void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
Alex Light51a64d52015-12-17 13:55:59 -08004801 for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
Alex Light5a559862016-01-29 12:24:48 -08004802 ResolveMethodExceptionHandlerTypes(&method);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004803 }
4804}
4805
Alex Light5a559862016-01-29 12:24:48 -08004806void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004807 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
David Sehr0225f8e2018-01-31 08:52:24 +00004808 CodeItemDataAccessor accessor(method->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004809 if (!accessor.HasCodeItem()) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004810 return; // native or abstract method
4811 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004812 if (accessor.TriesSize() == 0) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004813 return; // nothing to process
4814 }
Mathieu Chartier808c7a52017-12-15 11:19:33 -08004815 const uint8_t* handlers_ptr = accessor.GetCatchHandlerData(0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004816 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004817 for (uint32_t idx = 0; idx < handlers_size; idx++) {
4818 CatchHandlerIterator iterator(handlers_ptr);
4819 for (; iterator.HasNext(); iterator.Next()) {
4820 // Ensure exception types are resolved so that they don't need resolution to be delivered,
4821 // unresolved exception types will be ignored by exception delivery
Andreas Gampea5b09a62016-11-17 15:21:22 -08004822 if (iterator.GetHandlerTypeIndex().IsValid()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07004823 ObjPtr<mirror::Class> exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004824 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08004825 DCHECK(Thread::Current()->IsExceptionPending());
4826 Thread::Current()->ClearException();
4827 }
4828 }
4829 }
4830 handlers_ptr = iterator.EndDataPointer();
4831 }
4832}
4833
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01004834ObjPtr<mirror::Class> ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4835 jstring name,
4836 jobjectArray interfaces,
4837 jobject loader,
4838 jobjectArray methods,
4839 jobjectArray throws) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004840 Thread* self = soa.Self();
Alex Lighte9f61032018-09-24 16:04:51 -07004841
4842 // This is to prevent the calls to ClassLoad and ClassPrepare which can cause java/user-supplied
4843 // code to be executed. We put it up here so we can avoid all the allocations associated with
4844 // creating the class. This can happen with (eg) jit-threads.
4845 if (!self->CanLoadClasses()) {
4846 // Make sure we don't try to load anything, potentially causing an infinite loop.
4847 ObjPtr<mirror::Throwable> pre_allocated =
4848 Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
4849 self->SetException(pre_allocated);
4850 return nullptr;
4851 }
4852
Alex Light133987d2020-03-26 19:22:12 +00004853 StackHandleScope<12> hs(self);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004854 MutableHandle<mirror::Class> temp_klass(hs.NewHandle(
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004855 AllocClass(self, GetClassRoot<mirror::Class>(this), sizeof(mirror::Class))));
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004856 if (temp_klass == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004857 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004858 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004859 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004860 DCHECK(temp_klass->GetClass() != nullptr);
4861 temp_klass->SetObjectSize(sizeof(mirror::Proxy));
Igor Murashkindf707e42016-02-02 16:56:50 -08004862 // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4863 // the methods.
Vladimir Markob68bb7a2020-03-17 10:55:25 +00004864 temp_klass->SetAccessFlagsDuringLinking(
4865 kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004866 temp_klass->SetClassLoader(soa.Decode<mirror::ClassLoader>(loader));
4867 DCHECK_EQ(temp_klass->GetPrimitiveType(), Primitive::kPrimNot);
4868 temp_klass->SetName(soa.Decode<mirror::String>(name));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004869 temp_klass->SetDexCache(GetClassRoot<mirror::Proxy>(this)->GetDexCache());
Mathieu Chartier6beced42016-11-15 15:51:31 -08004870 // Object has an empty iftable, copy it for that reason.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004871 temp_klass->SetIfTable(GetClassRoot<mirror::Object>(this)->GetIfTable());
Vladimir Marko2c64a832018-01-04 11:31:56 +00004872 mirror::Class::SetStatus(temp_klass, ClassStatus::kIdx, self);
Vladimir Marko3892e622019-03-15 15:22:18 +00004873 std::string storage;
4874 const char* descriptor = temp_klass->GetDescriptor(&storage);
4875 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004876
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004877 // Needs to be before we insert the class so that the allocator field is set.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004878 LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(temp_klass->GetClassLoader());
Mathieu Chartierd57d4542015-10-14 10:55:30 -07004879
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004880 // Insert the class before loading the fields as the field roots
4881 // (ArtField::declaring_class_) are only visited from the class
4882 // table. There can't be any suspend points between inserting the
4883 // class and setting the field arrays below.
Vladimir Marko3892e622019-03-15 15:22:18 +00004884 ObjPtr<mirror::Class> existing = InsertClass(descriptor, temp_klass.Get(), hash);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004885 CHECK(existing == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08004886
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004887 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07004888 const size_t num_fields = 2;
Mathieu Chartier951ec2c2015-09-22 08:50:05 -07004889 LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004890 temp_klass->SetSFieldsPtr(sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004891
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004892 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4893 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004894 ArtField& interfaces_sfield = sfields->At(0);
4895 interfaces_sfield.SetDexFieldIndex(0);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004896 interfaces_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004897 interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07004898
Elliott Hughes2ed52c42012-03-21 16:56:56 -07004899 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004900 ArtField& throws_sfield = sfields->At(1);
4901 throws_sfield.SetDexFieldIndex(1);
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004902 throws_sfield.SetDeclaringClass(temp_klass.Get());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07004903 throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04004904
Ian Rogers466bb252011-10-14 03:29:56 -07004905 // Proxies have 1 direct method, the constructor
Alex Lighte64300b2015-12-15 15:02:47 -08004906 const size_t num_direct_methods = 1;
Jesse Wilson95caa792011-10-12 18:14:17 -04004907
Alex Light133987d2020-03-26 19:22:12 +00004908 // The array we get passed contains all methods, including private and static
4909 // ones that aren't proxied. We need to filter those out since only interface
4910 // methods (non-private & virtual) are actually proxied.
4911 Handle<mirror::ObjectArray<mirror::Method>> h_methods =
4912 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>>(methods));
Vladimir Marko679730e2018-05-25 15:06:48 +01004913 DCHECK_EQ(h_methods->GetClass(), GetClassRoot<mirror::ObjectArray<mirror::Method>>())
David Sehr709b0702016-10-13 09:12:37 -07004914 << mirror::Class::PrettyClass(h_methods->GetClass());
Alex Light133987d2020-03-26 19:22:12 +00004915 // List of the actual virtual methods this class will have.
4916 std::vector<ArtMethod*> proxied_methods;
4917 std::vector<size_t> proxied_throws_idx;
4918 proxied_methods.reserve(h_methods->GetLength());
4919 proxied_throws_idx.reserve(h_methods->GetLength());
4920 // Filter out to only the non-private virtual methods.
4921 for (auto [mirror, idx] : ZipCount(h_methods.Iterate<mirror::Method>())) {
4922 ArtMethod* m = mirror->GetArtMethod();
4923 if (!m->IsPrivate() && !m->IsStatic()) {
4924 proxied_methods.push_back(m);
4925 proxied_throws_idx.push_back(idx);
4926 }
4927 }
4928 const size_t num_virtual_methods = proxied_methods.size();
Alex Lightbc115092020-03-27 11:25:16 -07004929 // We also need to filter out the 'throws'. The 'throws' are a Class[][] that
4930 // contains an array of all the classes each function is declared to throw.
4931 // This is used to wrap unexpected exceptions in a
4932 // UndeclaredThrowableException exception. This array is in the same order as
4933 // the methods array and like the methods array must be filtered to remove any
4934 // non-proxied methods.
Alex Light133987d2020-03-26 19:22:12 +00004935 const bool has_filtered_methods =
4936 static_cast<int32_t>(num_virtual_methods) != h_methods->GetLength();
4937 MutableHandle<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>> original_proxied_throws(
4938 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(throws)));
4939 MutableHandle<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>> proxied_throws(
4940 hs.NewHandle<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>>(
4941 (has_filtered_methods)
4942 ? mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>::Alloc(
4943 self, original_proxied_throws->GetClass(), num_virtual_methods)
4944 : original_proxied_throws.Get()));
Alex Lightbc115092020-03-27 11:25:16 -07004945 if (proxied_throws.IsNull() && !original_proxied_throws.IsNull()) {
4946 self->AssertPendingOOMException();
4947 return nullptr;
4948 }
Alex Light133987d2020-03-26 19:22:12 +00004949 if (has_filtered_methods) {
4950 for (auto [orig_idx, new_idx] : ZipCount(MakeIterationRange(proxied_throws_idx))) {
4951 DCHECK_LE(new_idx, orig_idx);
4952 proxied_throws->Set(new_idx, original_proxied_throws->Get(orig_idx));
4953 }
4954 }
Alex Lighte64300b2015-12-15 15:02:47 -08004955
4956 // Create the methods array.
4957 LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
4958 self, allocator, num_direct_methods + num_virtual_methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004959 // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
4960 // want to throw OOM in the future.
Alex Lighte64300b2015-12-15 15:02:47 -08004961 if (UNLIKELY(proxy_class_methods == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07004962 self->AssertPendingOOMException();
4963 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07004964 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004965 temp_klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
Alex Lighte64300b2015-12-15 15:02:47 -08004966
4967 // Create the single direct method.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004968 CreateProxyConstructor(temp_klass, temp_klass->GetDirectMethodUnchecked(0, image_pointer_size_));
Alex Lighte64300b2015-12-15 15:02:47 -08004969
4970 // Create virtual method using specified prototypes.
4971 // TODO These should really use the iterators.
Jesse Wilson95caa792011-10-12 18:14:17 -04004972 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004973 auto* virtual_method = temp_klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Alex Light133987d2020-03-26 19:22:12 +00004974 auto* prototype = proxied_methods[i];
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004975 CreateProxyMethod(temp_klass, prototype, virtual_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07004976 DCHECK(virtual_method->GetDeclaringClass() != nullptr);
4977 DCHECK(prototype->GetDeclaringClass() != nullptr);
Jesse Wilson95caa792011-10-12 18:14:17 -04004978 }
Ian Rogersc2b44472011-12-14 21:17:17 -08004979
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004980 // The super class is java.lang.reflect.Proxy
Vladimir Markob4eb1b12018-05-24 11:09:38 +01004981 temp_klass->SetSuperClass(GetClassRoot<mirror::Proxy>(this));
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004982 // Now effectively in the loaded state.
Vladimir Marko2c64a832018-01-04 11:31:56 +00004983 mirror::Class::SetStatus(temp_klass, ClassStatus::kLoaded, self);
Ian Rogers62d6c772013-02-27 08:32:07 -08004984 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08004985
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004986 // At this point the class is loaded. Publish a ClassLoad event.
4987 // Note: this may be a temporary class. It is a listener's responsibility to handle this.
4988 Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(temp_klass);
4989
4990 MutableHandle<mirror::Class> klass = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogersc8982582012-09-07 16:53:25 -07004991 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004992 // Must hold lock on object when resolved.
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07004993 ObjectLock<mirror::Class> resolution_lock(self, temp_klass);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07004994 // Link the fields and virtual methods, creating vtable and iftables.
4995 // The new class will replace the old one in the class table.
Mathieu Chartiere401d142015-04-22 13:56:20 -07004996 Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
Mathieu Chartier0795f232016-09-27 18:43:30 -07004997 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces)));
Vladimir Marko3892e622019-03-15 15:22:18 +00004998 if (!LinkClass(self, descriptor, temp_klass, h_interfaces, &klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00004999 mirror::Class::SetStatus(temp_klass, ClassStatus::kErrorUnresolved, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005000 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005001 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005002 }
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005003 CHECK(temp_klass->IsRetired());
5004 CHECK_NE(temp_klass.Get(), klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005005
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005006 CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
Mathieu Chartier0795f232016-09-27 18:43:30 -07005007 interfaces_sfield.SetObject<false>(
5008 klass.Get(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07005009 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005010 CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
5011 throws_sfield.SetObject<false>(
Mathieu Chartier0795f232016-09-27 18:43:30 -07005012 klass.Get(),
Alex Light133987d2020-03-26 19:22:12 +00005013 proxied_throws.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005014
Andreas Gampe6cfd4c92017-04-06 08:03:32 -07005015 Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(temp_klass, klass);
5016
Vladimir Marko305c38b2018-02-14 11:50:07 +00005017 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5018 // See also ClassLinker::EnsureInitialized().
5019 if (kBitstringSubtypeCheckEnabled) {
5020 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
5021 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(klass.Get());
5022 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck for j.l.r.Proxy is already assigned.
5023 }
5024
Vladimir Markobf121912019-06-04 13:49:05 +01005025 VisiblyInitializedCallback* callback = nullptr;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005026 {
5027 // Lock on klass is released. Lock new class object.
5028 ObjectLock<mirror::Class> initialization_lock(self, klass);
Andreas Gampe5b20b352018-10-11 19:03:20 -07005029 EnsureSkipAccessChecksMethods(klass, image_pointer_size_);
Vladimir Markobf121912019-06-04 13:49:05 +01005030 // Conservatively go through the ClassStatus::kInitialized state.
5031 callback = MarkClassInitialized(self, klass);
5032 }
5033 if (callback != nullptr) {
5034 callback->MakeVisible(self);
Ian Rogersc8982582012-09-07 16:53:25 -07005035 }
Ian Rogersc2b44472011-12-14 21:17:17 -08005036
David Srbecky346fd962020-07-27 16:51:00 +01005037 // Consistency checks.
Elliott Hughes67d92002012-03-26 15:08:51 -07005038 if (kIsDebugBuild) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005039 CHECK(klass->GetIFieldsPtr() == nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005040 CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
5041
Ian Rogersc2b44472011-12-14 21:17:17 -08005042 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005043 auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
Alex Light133987d2020-03-26 19:22:12 +00005044 CheckProxyMethod(virtual_method, proxied_methods[i]);
Ian Rogersc2b44472011-12-14 21:17:17 -08005045 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005046
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005047 StackHandleScope<1> hs2(self);
Mathieu Chartier0795f232016-09-27 18:43:30 -07005048 Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String>(name));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005049 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07005050 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07005051 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(0)), interfaces_field_name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07005052
5053 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07005054 decoded_name->ToModifiedUtf8().c_str()));
David Sehr709b0702016-10-13 09:12:37 -07005055 CHECK_EQ(ArtField::PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08005056
Narayan Kamath6b2dc312017-03-14 13:26:12 +00005057 CHECK_EQ(klass.Get()->GetProxyInterfaces(),
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -07005058 soa.Decode<mirror::ObjectArray<mirror::Class>>(interfaces));
Narayan Kamath6b2dc312017-03-14 13:26:12 +00005059 CHECK_EQ(klass.Get()->GetProxyThrows(),
Alex Light133987d2020-03-26 19:22:12 +00005060 proxied_throws.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08005061 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005062 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04005063}
5064
Mathieu Chartiere401d142015-04-22 13:56:20 -07005065void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
5066 // Create constructor for Proxy that must initialize the method.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01005067 ObjPtr<mirror::Class> proxy_class = GetClassRoot<mirror::Proxy>(this);
5068 CHECK_EQ(proxy_class->NumDirectMethods(), 21u);
Przemyslaw Szczepaniakf11cd292016-08-17 17:46:38 +01005069
Igor Murashkin9d3d7522017-02-27 10:39:49 -08005070 // Find the <init>(InvocationHandler)V method. The exact method offset varies depending
5071 // on which front-end compiler was used to build the libcore DEX files.
Alex Light6cae5ea2018-06-07 17:07:02 -07005072 ArtMethod* proxy_constructor =
5073 jni::DecodeArtMethod(WellKnownClasses::java_lang_reflect_Proxy_init);
Igor Murashkin9d3d7522017-02-27 10:39:49 -08005074 DCHECK(proxy_constructor != nullptr)
5075 << "Could not find <init> method in java.lang.reflect.Proxy";
5076
Jeff Haodb8a6642014-08-14 17:18:52 -07005077 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
5078 // code_ too)
Mathieu Chartiere401d142015-04-22 13:56:20 -07005079 DCHECK(out != nullptr);
5080 out->CopyFrom(proxy_constructor, image_pointer_size_);
Vladimir Markoba118822017-06-12 15:41:56 +01005081 // Make this constructor public and fix the class to be our Proxy version.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005082 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
Vladimir Markoba118822017-06-12 15:41:56 +01005083 // Note that the compiler calls a ResolveMethod() overload that does not handle a Proxy referrer.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005084 out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) |
5085 kAccPublic |
5086 kAccCompileDontBother);
Mathieu Chartiere401d142015-04-22 13:56:20 -07005087 out->SetDeclaringClass(klass.Get());
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005088
5089 // Set the original constructor method.
5090 out->SetDataPtrSize(proxy_constructor, image_pointer_size_);
Ian Rogersc2b44472011-12-14 21:17:17 -08005091}
5092
Mathieu Chartiere401d142015-04-22 13:56:20 -07005093void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
Ian Rogers466bb252011-10-14 03:29:56 -07005094 CHECK(constructor->IsConstructor());
Mathieu Chartiere401d142015-04-22 13:56:20 -07005095 auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
5096 CHECK_STREQ(np->GetName(), "<init>");
5097 CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07005098 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04005099}
5100
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005101void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005102 ArtMethod* out) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005103 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07005104 // as necessary
Mathieu Chartiere401d142015-04-22 13:56:20 -07005105 DCHECK(out != nullptr);
5106 out->CopyFrom(prototype, image_pointer_size_);
Ian Rogers466bb252011-10-14 03:29:56 -07005107
Alex Lighte9dd04f2016-03-16 16:09:45 -07005108 // Set class to be the concrete proxy class.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005109 out->SetDeclaringClass(klass.Get());
Alex Lighte9dd04f2016-03-16 16:09:45 -07005110 // Clear the abstract, default and conflict flags to ensure that defaults aren't picked in
5111 // preference to the invocation handler.
5112 const uint32_t kRemoveFlags = kAccAbstract | kAccDefault | kAccDefaultConflict;
5113 // Make the method final.
Mathieu Chartier201e2972017-06-05 18:34:53 -07005114 // Mark kAccCompileDontBother so that we don't take JIT samples for the method. b/62349349
5115 const uint32_t kAddFlags = kAccFinal | kAccCompileDontBother;
Alex Lighte9dd04f2016-03-16 16:09:45 -07005116 out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
5117
Vladimir Markod1ee20f2017-08-17 09:21:16 +00005118 // Set the original interface method.
5119 out->SetDataPtrSize(prototype, image_pointer_size_);
5120
Ian Rogers466bb252011-10-14 03:29:56 -07005121 // At runtime the method looks like a reference and argument saving method, clone the code
5122 // related parameters from this method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005123 out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Ian Rogersc2b44472011-12-14 21:17:17 -08005124}
Jesse Wilson95caa792011-10-12 18:14:17 -04005125
Mathieu Chartiere401d142015-04-22 13:56:20 -07005126void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
David Srbecky346fd962020-07-27 16:51:00 +01005127 // Basic consistency checks.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005128 CHECK(!prototype->IsFinal());
5129 CHECK(method->IsFinal());
Alex Light9139e002015-10-09 15:59:48 -07005130 CHECK(method->IsInvokable());
Ian Rogers19846512012-02-24 11:42:47 -08005131
5132 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
5133 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Ian Rogers19846512012-02-24 11:42:47 -08005134 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
Vladimir Marko5c3e9d12017-08-30 16:43:54 +01005135 CHECK_EQ(prototype, method->GetInterfaceMethodIfProxy(image_pointer_size_));
Jesse Wilson95caa792011-10-12 18:14:17 -04005136}
5137
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005138bool ClassLinker::CanWeInitializeClass(ObjPtr<mirror::Class> klass, bool can_init_statics,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005139 bool can_init_parents) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08005140 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005141 return true;
5142 }
5143 if (!can_init_statics) {
5144 // Check if there's a class initializer.
Mathieu Chartiere401d142015-04-22 13:56:20 -07005145 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005146 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005147 return false;
5148 }
5149 // Check if there are encoded static values needing initialization.
5150 if (klass->NumStaticFields() != 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005151 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005152 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005153 if (dex_class_def->static_values_off_ != 0) {
5154 return false;
5155 }
5156 }
Vladimir Marko889b72d2019-11-12 11:01:13 +00005157 }
5158 // If we are a class we need to initialize all interfaces with default methods when we are
5159 // initialized. Check all of them.
5160 if (!klass->IsInterface()) {
5161 size_t num_interfaces = klass->GetIfTableCount();
5162 for (size_t i = 0; i < num_interfaces; i++) {
5163 ObjPtr<mirror::Class> iface = klass->GetIfTable()->GetInterface(i);
5164 if (iface->HasDefaultMethods() && !iface->IsInitialized()) {
5165 if (!can_init_parents || !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005166 return false;
5167 }
5168 }
5169 }
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005170 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07005171 if (klass->IsInterface() || !klass->HasSuperClass()) {
5172 return true;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005173 }
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005174 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Vladimir Marko889b72d2019-11-12 11:01:13 +00005175 if (super_class->IsInitialized()) {
5176 return true;
Mathieu Chartiere401d142015-04-22 13:56:20 -07005177 }
Vladimir Marko889b72d2019-11-12 11:01:13 +00005178 return can_init_parents && CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005179}
5180
Mathieu Chartier23369542020-03-04 08:24:11 -08005181bool ClassLinker::InitializeClass(Thread* self,
5182 Handle<mirror::Class> klass,
5183 bool can_init_statics,
5184 bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005185 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
5186
5187 // Are we already initialized and therefore done?
5188 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
5189 // an initialized class will never change its state.
5190 if (klass->IsInitialized()) {
5191 return true;
5192 }
5193
5194 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005195 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005196 return false;
5197 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005198
Ian Rogers7b078e82014-09-10 14:44:24 -07005199 self->AllowThreadSuspension();
Mathieu Chartier23369542020-03-04 08:24:11 -08005200 Runtime* const runtime = Runtime::Current();
5201 const bool stats_enabled = runtime->HasStatsEnabled();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005202 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005203 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005204 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005205
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005206 // Re-check under the lock in case another thread initialized ahead of us.
5207 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005208 return true;
5209 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005210
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005211 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005212 if (klass->IsErroneous()) {
Andreas Gampe7b3063b2019-01-07 14:12:52 -08005213 ThrowEarlierClassFailure(klass.Get(), true, /* log= */ true);
Brian Carlstromb23eab12014-10-08 17:55:21 -07005214 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005215 return false;
5216 }
5217
Vladimir Marko72ab6842017-01-20 19:32:50 +00005218 CHECK(klass->IsResolved() && !klass->IsErroneousResolved())
5219 << klass->PrettyClass() << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005220
5221 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005222 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005223 if (!klass->IsVerified()) {
5224 // We failed to verify, expect either the klass to be erroneous or verification failed at
5225 // compile time.
5226 if (klass->IsErroneous()) {
Andreas Gampefc49fa02016-04-21 12:21:55 -07005227 // The class is erroneous. This may be a verifier error, or another thread attempted
5228 // verification and/or initialization and failed. We can distinguish those cases by
5229 // whether an exception is already pending.
5230 if (self->IsExceptionPending()) {
5231 // Check that it's a VerifyError.
5232 DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
David Sehr709b0702016-10-13 09:12:37 -07005233 mirror::Class::PrettyClass(self->GetException()->GetClass()));
Andreas Gampefc49fa02016-04-21 12:21:55 -07005234 } else {
5235 // Check that another thread attempted initialization.
5236 DCHECK_NE(0, klass->GetClinitThreadId());
5237 DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
5238 // Need to rethrow the previous failure now.
5239 ThrowEarlierClassFailure(klass.Get(), true);
5240 }
Brian Carlstromb23eab12014-10-08 17:55:21 -07005241 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005242 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005243 CHECK(Runtime::Current()->IsAotCompiler());
Nicolas Geoffray1715efa2020-06-05 18:34:49 +01005244 CHECK(klass->ShouldVerifyAtRuntime() || klass->IsVerifiedNeedsAccessChecks());
Vladimir Markod79b37b2018-11-02 13:06:22 +00005245 self->AssertNoPendingException();
5246 self->SetException(Runtime::Current()->GetPreAllocatedNoClassDefFoundError());
jeffhaoa9b3bf42012-06-06 17:18:39 -07005247 }
Vladimir Markod79b37b2018-11-02 13:06:22 +00005248 self->AssertPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005249 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07005250 } else {
5251 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005252 }
Andreas Gampefc49fa02016-04-21 12:21:55 -07005253
5254 // A separate thread could have moved us all the way to initialized. A "simple" example
5255 // involves a subclass of the current class being initialized at the same time (which
5256 // will implicitly initialize the superclass, if scheduled that way). b/28254258
Vladimir Marko72ab6842017-01-20 19:32:50 +00005257 DCHECK(!klass->IsErroneous()) << klass->GetStatus();
Andreas Gampefc49fa02016-04-21 12:21:55 -07005258 if (klass->IsInitialized()) {
5259 return true;
5260 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005261 }
5262
Vladimir Marko2c64a832018-01-04 11:31:56 +00005263 // If the class is ClassStatus::kInitializing, either this thread is
Brian Carlstromd1422f82011-09-28 11:37:09 -07005264 // initializing higher up the stack or another thread has beat us
5265 // to initializing and we need to wait. Either way, this
5266 // invocation of InitializeClass will not be responsible for
5267 // running <clinit> and will return.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005268 if (klass->GetStatus() == ClassStatus::kInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07005269 // Could have got an exception during verification.
5270 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005271 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005272 return false;
5273 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07005274 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07005275 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005276 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005277 return true;
5278 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005279 // No. That's fine. Wait for another thread to finish initializing.
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005280 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005281 }
5282
Jeff Haoe2e40342017-07-19 10:45:18 -07005283 // Try to get the oat class's status for this class if the oat file is present. The compiler
5284 // tries to validate superclass descriptors, and writes the result into the oat file.
5285 // Runtime correctness is guaranteed by classpath checks done on loading. If the classpath
5286 // is different at runtime than it was at compile time, the oat file is rejected. So if the
5287 // oat file is present, the classpaths must match, and the runtime time check can be skipped.
Jeff Hao0cb17282017-07-12 14:51:49 -07005288 bool has_oat_class = false;
Jeff Haoe2e40342017-07-19 10:45:18 -07005289 const OatFile::OatClass oat_class = (runtime->IsStarted() && !runtime->IsAotCompiler())
5290 ? OatFile::FindOatClass(klass->GetDexFile(), klass->GetDexClassDefIndex(), &has_oat_class)
5291 : OatFile::OatClass::Invalid();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005292 if (oat_class.GetStatus() < ClassStatus::kSuperclassValidated &&
Jeff Hao0cb17282017-07-12 14:51:49 -07005293 !ValidateSuperClassDescriptors(klass)) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005294 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005295 return false;
5296 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005297 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005298
Vladimir Marko2c64a832018-01-04 11:31:56 +00005299 CHECK_EQ(klass->GetStatus(), ClassStatus::kVerified) << klass->PrettyClass()
Andreas Gampe9510ccd2016-04-20 09:55:25 -07005300 << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005301
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005302 // From here out other threads may observe that we're initializing and so changes of state
5303 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07005304 klass->SetClinitThreadId(self->GetTid());
Vladimir Marko2c64a832018-01-04 11:31:56 +00005305 mirror::Class::SetStatus(klass, ClassStatus::kInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005306
Mathieu Chartier23369542020-03-04 08:24:11 -08005307 t0 = stats_enabled ? NanoTime() : 0u;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005308 }
5309
Andreas Gampeaf864702019-07-23 14:05:35 -07005310 uint64_t t_sub = 0;
5311
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07005312 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005313 if (!klass->IsInterface() && klass->HasSuperClass()) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005314 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005315 if (!super_class->IsInitialized()) {
5316 CHECK(!super_class->IsInterface());
5317 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005318 StackHandleScope<1> hs(self);
5319 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Mathieu Chartier23369542020-03-04 08:24:11 -08005320 uint64_t super_t0 = stats_enabled ? NanoTime() : 0u;
Ian Rogers7b078e82014-09-10 14:44:24 -07005321 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Mathieu Chartier23369542020-03-04 08:24:11 -08005322 uint64_t super_t1 = stats_enabled ? NanoTime() : 0u;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005323 if (!super_initialized) {
5324 // The super class was verified ahead of entering initializing, we should only be here if
5325 // the super class became erroneous due to initialization.
Chang Xingadbb91c2017-07-17 11:23:55 -07005326 // For the case of aot compiler, the super class might also be initializing but we don't
5327 // want to process circular dependencies in pre-compile.
5328 CHECK(self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07005329 << "Super class initialization failed for "
David Sehr709b0702016-10-13 09:12:37 -07005330 << handle_scope_super->PrettyDescriptor()
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005331 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005332 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005333 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005334 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005335 // Initialization failed because the super-class is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005336 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005337 return false;
5338 }
Andreas Gampeaf864702019-07-23 14:05:35 -07005339 t_sub = super_t1 - super_t0;
Ian Rogers1bddec32012-02-04 12:27:34 -08005340 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005341 }
5342
Alex Lighteb7c1442015-08-31 13:17:42 -07005343 if (!klass->IsInterface()) {
5344 // Initialize interfaces with default methods for the JLS.
5345 size_t num_direct_interfaces = klass->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005346 // Only setup the (expensive) handle scope if we actually need to.
5347 if (UNLIKELY(num_direct_interfaces > 0)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07005348 StackHandleScope<1> hs_iface(self);
Alex Light56a40f52015-10-14 11:07:41 -07005349 MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
5350 for (size_t i = 0; i < num_direct_interfaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005351 handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass.Get(), i));
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005352 CHECK(handle_scope_iface != nullptr) << klass->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005353 CHECK(handle_scope_iface->IsInterface());
5354 if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
5355 // We have already done this for this interface. Skip it.
5356 continue;
5357 }
5358 // We cannot just call initialize class directly because we need to ensure that ALL
5359 // interfaces with default methods are initialized. Non-default interface initialization
5360 // will not affect other non-default super-interfaces.
Mathieu Chartier23369542020-03-04 08:24:11 -08005361 // This is not very precise, misses all walking.
5362 uint64_t inf_t0 = stats_enabled ? NanoTime() : 0u;
Alex Light56a40f52015-10-14 11:07:41 -07005363 bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
5364 handle_scope_iface,
5365 can_init_statics,
5366 can_init_parents);
Mathieu Chartier23369542020-03-04 08:24:11 -08005367 uint64_t inf_t1 = stats_enabled ? NanoTime() : 0u;
Alex Light56a40f52015-10-14 11:07:41 -07005368 if (!iface_initialized) {
5369 ObjectLock<mirror::Class> lock(self, klass);
5370 // Initialization failed because one of our interfaces with default methods is erroneous.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005371 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Alex Light56a40f52015-10-14 11:07:41 -07005372 return false;
5373 }
Andreas Gampeaf864702019-07-23 14:05:35 -07005374 t_sub += inf_t1 - inf_t0;
Alex Lighteb7c1442015-08-31 13:17:42 -07005375 }
5376 }
5377 }
5378
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005379 const size_t num_static_fields = klass->NumStaticFields();
5380 if (num_static_fields > 0) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005381 const dex::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005382 CHECK(dex_class_def != nullptr);
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07005383 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005384 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005385 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005386
5387 // Eagerly fill in static fields so that the we don't have to do as many expensive
5388 // Class::FindStaticField in ResolveField.
5389 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005390 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005391 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07005392 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005393 if (resolved_field == nullptr) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01005394 // Populating cache of a dex file which defines `klass` should always be allowed.
David Brazdilf50ac102018-10-17 18:00:06 +01005395 DCHECK(!hiddenapi::ShouldDenyAccessToMember(
5396 field,
5397 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
5398 hiddenapi::AccessMethod::kNone));
Mathieu Chartierc7853442015-03-27 14:35:38 -07005399 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07005400 } else {
5401 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07005402 }
5403 }
5404
Vladimir Markoe11dd502017-12-08 14:09:45 +00005405 annotations::RuntimeEncodedStaticFieldValueIterator value_it(dex_cache,
5406 class_loader,
David Sehr9323e6e2016-09-13 08:58:35 -07005407 this,
5408 *dex_class_def);
Vladimir Markoe11dd502017-12-08 14:09:45 +00005409 const DexFile& dex_file = *dex_cache->GetDexFile();
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005410
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07005411 if (value_it.HasNext()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005412 ClassAccessor accessor(dex_file, *dex_class_def);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005413 CHECK(can_init_statics);
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005414 for (const ClassAccessor::Field& field : accessor.GetStaticFields()) {
5415 if (!value_it.HasNext()) {
5416 break;
5417 }
5418 ArtField* art_field = ResolveField(field.GetIndex(),
5419 dex_cache,
5420 class_loader,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07005421 /* is_static= */ true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005422 if (Runtime::Current()->IsActiveTransaction()) {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005423 value_it.ReadValueToField<true>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005424 } else {
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005425 value_it.ReadValueToField<false>(art_field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01005426 }
Mathieu Chartierda595be2016-08-10 13:57:39 -07005427 if (self->IsExceptionPending()) {
5428 break;
5429 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005430 value_it.Next();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005431 }
Mathieu Chartier1f1cb9f2018-06-04 09:22:46 -07005432 DCHECK(self->IsExceptionPending() || !value_it.HasNext());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005433 }
5434 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005435
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005436
Mathieu Chartierda595be2016-08-10 13:57:39 -07005437 if (!self->IsExceptionPending()) {
5438 ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
5439 if (clinit != nullptr) {
5440 CHECK(can_init_statics);
5441 JValue result;
5442 clinit->Invoke(self, nullptr, 0, &result, "V");
5443 }
5444 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005445 self->AllowThreadSuspension();
Mathieu Chartier23369542020-03-04 08:24:11 -08005446 uint64_t t1 = stats_enabled ? NanoTime() : 0u;
Elliott Hughes83df2ac2011-10-11 16:37:54 -07005447
Vladimir Markobf121912019-06-04 13:49:05 +01005448 VisiblyInitializedCallback* callback = nullptr;
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005449 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005450 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07005451 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005452
5453 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005454 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005455 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005456 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005457 } else if (Runtime::Current()->IsTransactionAborted()) {
5458 // The exception thrown when the transaction aborted has been caught and cleared
5459 // so we need to throw it again now.
David Sehr709b0702016-10-13 09:12:37 -07005460 VLOG(compiler) << "Return from class initializer of "
5461 << mirror::Class::PrettyDescriptor(klass.Get())
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01005462 << " without exception while transaction was aborted: re-throw it now.";
Mathieu Chartier23369542020-03-04 08:24:11 -08005463 runtime->ThrowTransactionAbortError(self);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005464 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01005465 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005466 } else {
Mathieu Chartier23369542020-03-04 08:24:11 -08005467 if (stats_enabled) {
5468 RuntimeStats* global_stats = runtime->GetStats();
5469 RuntimeStats* thread_stats = self->GetStats();
5470 ++global_stats->class_init_count;
5471 ++thread_stats->class_init_count;
5472 global_stats->class_init_time_ns += (t1 - t0 - t_sub);
5473 thread_stats->class_init_time_ns += (t1 - t0 - t_sub);
5474 }
Ian Rogerse6bb3b22013-08-19 21:51:45 -07005475 // Set the class as initialized except if failed to initialize static fields.
Vladimir Markobf121912019-06-04 13:49:05 +01005476 callback = MarkClassInitialized(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005477 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07005478 std::string temp;
5479 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07005480 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08005481 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005482 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005483 }
Vladimir Markobf121912019-06-04 13:49:05 +01005484 if (callback != nullptr) {
5485 callback->MakeVisible(self);
5486 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08005487 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005488}
5489
Alex Lighteb7c1442015-08-31 13:17:42 -07005490// We recursively run down the tree of interfaces. We need to do this in the order they are declared
5491// and perform the initialization only on those interfaces that contain default methods.
5492bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
5493 Handle<mirror::Class> iface,
5494 bool can_init_statics,
5495 bool can_init_parents) {
5496 CHECK(iface->IsInterface());
5497 size_t num_direct_ifaces = iface->NumDirectInterfaces();
Alex Light56a40f52015-10-14 11:07:41 -07005498 // Only create the (expensive) handle scope if we need it.
5499 if (UNLIKELY(num_direct_ifaces > 0)) {
5500 StackHandleScope<1> hs(self);
5501 MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
5502 // First we initialize all of iface's super-interfaces recursively.
5503 for (size_t i = 0; i < num_direct_ifaces; i++) {
Vladimir Marko19a4d372016-12-08 14:41:46 +00005504 ObjPtr<mirror::Class> super_iface = mirror::Class::GetDirectInterface(self, iface.Get(), i);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00005505 CHECK(super_iface != nullptr) << iface->PrettyDescriptor() << " iface #" << i;
Alex Light56a40f52015-10-14 11:07:41 -07005506 if (!super_iface->HasBeenRecursivelyInitialized()) {
5507 // Recursive step
5508 handle_super_iface.Assign(super_iface);
5509 if (!InitializeDefaultInterfaceRecursive(self,
5510 handle_super_iface,
5511 can_init_statics,
5512 can_init_parents)) {
5513 return false;
5514 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005515 }
5516 }
5517 }
5518
5519 bool result = true;
5520 // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
5521 // initialize if we don't have default methods.
5522 if (iface->HasDefaultMethods()) {
5523 result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
5524 }
5525
5526 // Mark that this interface has undergone recursive default interface initialization so we know we
5527 // can skip it on any later class initializations. We do this even if we are not a default
5528 // interface since we can still avoid the traversal. This is purely a performance optimization.
5529 if (result) {
5530 // TODO This should be done in a better way
Andreas Gampe976b2982018-03-02 17:54:22 -08005531 // Note: Use a try-lock to avoid blocking when someone else is holding the lock on this
5532 // interface. It is bad (Java) style, but not impossible. Marking the recursive
5533 // initialization is a performance optimization (to avoid another idempotent visit
5534 // for other implementing classes/interfaces), and can be revisited later.
5535 ObjectTryLock<mirror::Class> lock(self, iface);
5536 if (lock.Acquired()) {
5537 iface->SetRecursivelyInitialized();
5538 }
Alex Lighteb7c1442015-08-31 13:17:42 -07005539 }
5540 return result;
5541}
5542
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005543bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
5544 Thread* self,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005545 ObjectLock<mirror::Class>& lock)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005546 REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005547 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005548 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07005549 CHECK(!klass->IsInitialized());
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005550 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005551
5552 // When we wake up, repeat the test for init-in-progress. If
5553 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07005554 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07005555 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07005556 WrapExceptionInInitializer(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005557 mirror::Class::SetStatus(klass, ClassStatus::kErrorResolved, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005558 return false;
5559 }
5560 // Spurious wakeup? Go back to waiting.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005561 if (klass->GetStatus() == ClassStatus::kInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07005562 continue;
5563 }
Vladimir Marko2c64a832018-01-04 11:31:56 +00005564 if (klass->GetStatus() == ClassStatus::kVerified &&
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08005565 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07005566 // Compile time initialization failed.
5567 return false;
5568 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07005569 if (klass->IsErroneous()) {
5570 // The caller wants an exception, but it was thrown in a
5571 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07005572 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
David Sehr709b0702016-10-13 09:12:37 -07005573 klass->PrettyDescriptor().c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07005574 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07005575 return false;
5576 }
5577 if (klass->IsInitialized()) {
5578 return true;
5579 }
David Sehr709b0702016-10-13 09:12:37 -07005580 LOG(FATAL) << "Unexpected class status. " << klass->PrettyClass() << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08005581 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005582 }
Ian Rogers07140832014-09-30 15:43:59 -07005583 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07005584}
5585
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005586static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
5587 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005588 ArtMethod* method,
5589 ArtMethod* m)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005590 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005591 DCHECK(Thread::Current()->IsExceptionPending());
5592 DCHECK(!m->IsProxyMethod());
5593 const DexFile* dex_file = m->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005594 const dex::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
5595 const dex::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005596 dex::TypeIndex return_type_idx = proto_id.return_type_idx_;
David Sehr709b0702016-10-13 09:12:37 -07005597 std::string return_type = dex_file->PrettyType(return_type_idx);
5598 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005599 ThrowWrappedLinkageError(klass.Get(),
5600 "While checking class %s method %s signature against %s %s: "
5601 "Failed to resolve return type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005602 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5603 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005604 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005605 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005606 return_type.c_str(), class_loader.c_str());
5607}
5608
5609static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
5610 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005611 ArtMethod* method,
5612 ArtMethod* m,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005613 uint32_t index,
Andreas Gampea5b09a62016-11-17 15:21:22 -08005614 dex::TypeIndex arg_type_idx)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005615 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005616 DCHECK(Thread::Current()->IsExceptionPending());
5617 DCHECK(!m->IsProxyMethod());
5618 const DexFile* dex_file = m->GetDexFile();
David Sehr709b0702016-10-13 09:12:37 -07005619 std::string arg_type = dex_file->PrettyType(arg_type_idx);
5620 std::string class_loader = mirror::Object::PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005621 ThrowWrappedLinkageError(klass.Get(),
5622 "While checking class %s method %s signature against %s %s: "
5623 "Failed to resolve arg %u type %s with %s",
David Sehr709b0702016-10-13 09:12:37 -07005624 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5625 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005626 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005627 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005628 index, arg_type.c_str(), class_loader.c_str());
5629}
5630
5631static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
5632 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005633 ArtMethod* method,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005634 const std::string& error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005635 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005636 ThrowLinkageError(klass.Get(),
5637 "Class %s method %s resolves differently in %s %s: %s",
David Sehr709b0702016-10-13 09:12:37 -07005638 mirror::Class::PrettyDescriptor(klass.Get()).c_str(),
5639 ArtMethod::PrettyMethod(method).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005640 super_klass->IsInterface() ? "interface" : "superclass",
David Sehr709b0702016-10-13 09:12:37 -07005641 mirror::Class::PrettyDescriptor(super_klass.Get()).c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005642 error_msg.c_str());
5643}
5644
Ian Rogersb5fb2072014-12-02 17:22:02 -08005645static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005646 Handle<mirror::Class> klass,
5647 Handle<mirror::Class> super_klass,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005648 ArtMethod* method1,
5649 ArtMethod* method2)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005650 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08005651 {
5652 StackHandleScope<1> hs(self);
Vladimir Markob45528c2017-07-27 14:14:28 +01005653 Handle<mirror::Class> return_type(hs.NewHandle(method1->ResolveReturnType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005654 if (UNLIKELY(return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005655 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005656 return false;
5657 }
Vladimir Markob45528c2017-07-27 14:14:28 +01005658 ObjPtr<mirror::Class> other_return_type = method2->ResolveReturnType();
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005659 if (UNLIKELY(other_return_type == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005660 ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005661 return false;
5662 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005663 if (UNLIKELY(other_return_type != return_type.Get())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005664 ThrowSignatureMismatch(klass, super_klass, method1,
5665 StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
David Sehr709b0702016-10-13 09:12:37 -07005666 return_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005667 return_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005668 other_return_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005669 other_return_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005670 return false;
5671 }
5672 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08005673 const dex::TypeList* types1 = method1->GetParameterTypeList();
5674 const dex::TypeList* types2 = method2->GetParameterTypeList();
Ian Rogersb5fb2072014-12-02 17:22:02 -08005675 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005676 if (types2 != nullptr && types2->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005677 ThrowSignatureMismatch(klass, super_klass, method1,
5678 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005679 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005680 return false;
5681 }
5682 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005683 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005684 if (types1->Size() != 0) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005685 ThrowSignatureMismatch(klass, super_klass, method1,
5686 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005687 method2->PrettyMethod(true).c_str()));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005688 return false;
5689 }
5690 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08005691 }
5692 uint32_t num_types = types1->Size();
5693 if (UNLIKELY(num_types != types2->Size())) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005694 ThrowSignatureMismatch(klass, super_klass, method1,
5695 StringPrintf("Type list mismatch with %s",
David Sehr709b0702016-10-13 09:12:37 -07005696 method2->PrettyMethod(true).c_str()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005697 return false;
5698 }
5699 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00005700 StackHandleScope<1> hs(self);
Andreas Gampea5b09a62016-11-17 15:21:22 -08005701 dex::TypeIndex param_type_idx = types1->GetTypeItem(i).type_idx_;
Vladimir Marko862f43c2015-02-10 18:22:57 +00005702 Handle<mirror::Class> param_type(hs.NewHandle(
Vladimir Markob45528c2017-07-27 14:14:28 +01005703 method1->ResolveClassFromTypeIndex(param_type_idx)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08005704 if (UNLIKELY(param_type == nullptr)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005705 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005706 method1, i, param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005707 return false;
5708 }
Andreas Gampea5b09a62016-11-17 15:21:22 -08005709 dex::TypeIndex other_param_type_idx = types2->GetTypeItem(i).type_idx_;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005710 ObjPtr<mirror::Class> other_param_type =
Vladimir Markob45528c2017-07-27 14:14:28 +01005711 method2->ResolveClassFromTypeIndex(other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005712 if (UNLIKELY(other_param_type == nullptr)) {
5713 ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
Mathieu Chartiere401d142015-04-22 13:56:20 -07005714 method2, i, other_param_type_idx);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005715 return false;
5716 }
Vladimir Marko862f43c2015-02-10 18:22:57 +00005717 if (UNLIKELY(param_type.Get() != other_param_type)) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005718 ThrowSignatureMismatch(klass, super_klass, method1,
5719 StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
5720 i,
David Sehr709b0702016-10-13 09:12:37 -07005721 param_type->PrettyClassAndClassLoader().c_str(),
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005722 param_type.Get(),
David Sehr709b0702016-10-13 09:12:37 -07005723 other_param_type->PrettyClassAndClassLoader().c_str(),
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005724 other_param_type.Ptr()));
Ian Rogersb5fb2072014-12-02 17:22:02 -08005725 return false;
5726 }
5727 }
5728 return true;
5729}
5730
5731
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005732bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005733 if (klass->IsInterface()) {
5734 return true;
5735 }
Ian Rogers151f2212014-05-06 11:27:27 -07005736 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07005737 Thread* self = Thread::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07005738 StackHandleScope<1> hs(self);
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005739 MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005740 if (klass->HasSuperClass() &&
5741 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005742 super_klass.Assign(klass->GetSuperClass());
Mingyao Yang2cdbad72014-07-16 10:44:41 -07005743 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005744 auto* m = klass->GetVTableEntry(i, image_pointer_size_);
5745 auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
5746 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005747 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5748 klass,
5749 super_klass,
5750 m,
5751 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005752 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005753 return false;
5754 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005755 }
5756 }
5757 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07005758 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005759 super_klass.Assign(klass->GetIfTable()->GetInterface(i));
5760 if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
5761 uint32_t num_methods = super_klass->NumVirtualMethods();
Ian Rogers151f2212014-05-06 11:27:27 -07005762 for (uint32_t j = 0; j < num_methods; ++j) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005763 auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
5764 j, image_pointer_size_);
5765 auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
5766 if (m != super_m) {
Vladimir Marko942fd312017-01-16 20:52:19 +00005767 if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self,
5768 klass,
5769 super_klass,
5770 m,
5771 super_m))) {
Vladimir Markod5e5a0e2015-05-08 12:26:59 +01005772 self->AssertPendingException();
Andreas Gamped8ca52e2015-02-13 15:23:18 -08005773 return false;
5774 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005775 }
5776 }
5777 }
5778 }
5779 return true;
5780}
5781
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005782bool ClassLinker::EnsureInitialized(Thread* self,
5783 Handle<mirror::Class> c,
5784 bool can_init_fields,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005785 bool can_init_parents) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08005786 DCHECK(c != nullptr);
Igor Murashkin86083f72017-10-27 10:59:04 -07005787
Mathieu Chartier524507a2014-08-27 15:28:28 -07005788 if (c->IsInitialized()) {
Vladimir Marko8e110652019-07-30 10:14:41 +01005789 // If we've seen an initialized but not visibly initialized class
5790 // many times, request visible initialization.
5791 if (kRuntimeISA == InstructionSet::kX86 || kRuntimeISA == InstructionSet::kX86_64) {
5792 // Thanks to the x86 memory model classes skip the initialized status.
5793 DCHECK(c->IsVisiblyInitialized());
5794 } else if (UNLIKELY(!c->IsVisiblyInitialized())) {
5795 if (self->IncrementMakeVisiblyInitializedCounter()) {
5796 MakeInitializedClassesVisiblyInitialized(self, /*wait=*/ false);
5797 }
5798 }
Andreas Gampe5b20b352018-10-11 19:03:20 -07005799 DCHECK(c->WasVerificationAttempted()) << c->PrettyClassAndClassLoader();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005800 return true;
5801 }
Igor Murashkin86083f72017-10-27 10:59:04 -07005802 // SubtypeCheckInfo::Initialized must happen-before any new-instance for that type.
5803 //
5804 // Ensure the bitstring is initialized before any of the class initialization
5805 // logic occurs. Once a class initializer starts running, objects can
5806 // escape into the heap and use the subtype checking code.
5807 //
5808 // Note: A class whose SubtypeCheckInfo is at least Initialized means it
5809 // can be used as a source for the IsSubClass check, and that all ancestors
5810 // of the class are Assigned (can be used as a target for IsSubClass check)
5811 // or Overflowed (can be used as a source for IsSubClass check).
Vladimir Marko305c38b2018-02-14 11:50:07 +00005812 if (kBitstringSubtypeCheckEnabled) {
Igor Murashkin86083f72017-10-27 10:59:04 -07005813 MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
Vladimir Marko38b8b252018-01-02 19:07:06 +00005814 SubtypeCheck<ObjPtr<mirror::Class>>::EnsureInitialized(c.Get());
Igor Murashkin86083f72017-10-27 10:59:04 -07005815 // TODO: Avoid taking subtype_check_lock_ if SubtypeCheck is already initialized.
5816 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005817 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07005818 if (!success) {
5819 if (can_init_fields && can_init_parents) {
David Sehr709b0702016-10-13 09:12:37 -07005820 CHECK(self->IsExceptionPending()) << c->PrettyClass();
Mathieu Chartier524507a2014-08-27 15:28:28 -07005821 }
5822 } else {
5823 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08005824 }
5825 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07005826}
5827
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005828void ClassLinker::FixupTemporaryDeclaringClass(ObjPtr<mirror::Class> temp_class,
5829 ObjPtr<mirror::Class> new_class) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005830 DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005831 for (ArtField& field : new_class->GetIFields()) {
5832 if (field.GetDeclaringClass() == temp_class) {
5833 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005834 }
5835 }
5836
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005837 DCHECK_EQ(temp_class->NumStaticFields(), 0u);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005838 for (ArtField& field : new_class->GetSFields()) {
5839 if (field.GetDeclaringClass() == temp_class) {
5840 field.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005841 }
5842 }
5843
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005844 DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005845 DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
Alex Lighte64300b2015-12-15 15:02:47 -08005846 for (auto& method : new_class->GetMethods(image_pointer_size_)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005847 if (method.GetDeclaringClass() == temp_class) {
5848 method.SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005849 }
5850 }
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07005851
5852 // Make sure the remembered set and mod-union tables know that we updated some of the native
5853 // roots.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07005854 WriteBarrier::ForEveryFieldWrite(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005855}
5856
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005857void ClassLinker::RegisterClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005858 CHECK(class_loader->GetAllocator() == nullptr);
5859 CHECK(class_loader->GetClassTable() == nullptr);
5860 Thread* const self = Thread::Current();
5861 ClassLoaderData data;
Ian Rogers55256cb2017-12-21 17:07:11 -08005862 data.weak_root = self->GetJniEnv()->GetVm()->AddWeakGlobalRef(self, class_loader);
Mathieu Chartier5b830502016-03-02 10:30:23 -08005863 // Create and set the class table.
5864 data.class_table = new ClassTable;
5865 class_loader->SetClassTable(data.class_table);
5866 // Create and set the linear allocator.
5867 data.allocator = Runtime::Current()->CreateLinearAlloc();
5868 class_loader->SetAllocator(data.allocator);
5869 // Add to the list so that we know to free the data later.
5870 class_loaders_.push_back(data);
5871}
5872
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005873ClassTable* ClassLinker::InsertClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07005874 if (class_loader == nullptr) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005875 return boot_class_table_.get();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005876 }
Mathieu Chartier6b069532015-08-05 15:08:12 -07005877 ClassTable* class_table = class_loader->GetClassTable();
5878 if (class_table == nullptr) {
Mathieu Chartier5b830502016-03-02 10:30:23 -08005879 RegisterClassLoader(class_loader);
5880 class_table = class_loader->GetClassTable();
5881 DCHECK(class_table != nullptr);
Mathieu Chartier6b069532015-08-05 15:08:12 -07005882 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005883 return class_table;
5884}
5885
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005886ClassTable* ClassLinker::ClassTableForClassLoader(ObjPtr<mirror::ClassLoader> class_loader) {
Andreas Gampe2af99022017-04-25 08:32:59 -07005887 return class_loader == nullptr ? boot_class_table_.get() : class_loader->GetClassTable();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07005888}
5889
Mathieu Chartier28357fa2016-10-18 16:27:40 -07005890static ImTable* FindSuperImt(ObjPtr<mirror::Class> klass, PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07005891 REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005892 while (klass->HasSuperClass()) {
5893 klass = klass->GetSuperClass();
5894 if (klass->ShouldHaveImt()) {
5895 return klass->GetImt(pointer_size);
5896 }
5897 }
5898 return nullptr;
5899}
5900
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07005901bool ClassLinker::LinkClass(Thread* self,
5902 const char* descriptor,
5903 Handle<mirror::Class> klass,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005904 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005905 MutableHandle<mirror::Class>* h_new_class_out) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00005906 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005907
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005908 if (!LinkSuperClass(klass)) {
5909 return false;
5910 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005911 ArtMethod* imt_data[ImTable::kSize];
5912 // If there are any new conflicts compared to super class.
5913 bool new_conflict = false;
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005914 std::fill_n(imt_data, arraysize(imt_data), Runtime::Current()->GetImtUnimplementedMethod());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005915 if (!LinkMethods(self, klass, interfaces, &new_conflict, imt_data)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005916 return false;
5917 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005918 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005919 return false;
5920 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005921 size_t class_size;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07005922 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07005923 return false;
5924 }
5925 CreateReferenceInstanceOffsets(klass);
Vladimir Marko2c64a832018-01-04 11:31:56 +00005926 CHECK_EQ(ClassStatus::kLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005927
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005928 ImTable* imt = nullptr;
5929 if (klass->ShouldHaveImt()) {
5930 // If there are any new conflicts compared to the super class we can not make a copy. There
5931 // can be cases where both will have a conflict method at the same slot without having the same
5932 // set of conflicts. In this case, we can not share the IMT since the conflict table slow path
5933 // will possibly create a table that is incorrect for either of the classes.
5934 // Same IMT with new_conflict does not happen very often.
5935 if (!new_conflict) {
5936 ImTable* super_imt = FindSuperImt(klass.Get(), image_pointer_size_);
5937 if (super_imt != nullptr) {
5938 bool imt_equals = true;
5939 for (size_t i = 0; i < ImTable::kSize && imt_equals; ++i) {
5940 imt_equals = imt_equals && (super_imt->Get(i, image_pointer_size_) == imt_data[i]);
5941 }
5942 if (imt_equals) {
5943 imt = super_imt;
5944 }
5945 }
5946 }
5947 if (imt == nullptr) {
5948 LinearAlloc* allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
5949 imt = reinterpret_cast<ImTable*>(
5950 allocator->Alloc(self, ImTable::SizeInBytes(image_pointer_size_)));
5951 if (imt == nullptr) {
5952 return false;
5953 }
5954 imt->Populate(imt_data, image_pointer_size_);
5955 }
5956 }
5957
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005958 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
5959 // We don't need to retire this class as it has no embedded tables or it was created the
5960 // correct size during class linker initialization.
David Sehr709b0702016-10-13 09:12:37 -07005961 CHECK_EQ(klass->GetClassSize(), class_size) << klass->PrettyDescriptor();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005962
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005963 if (klass->ShouldHaveEmbeddedVTable()) {
5964 klass->PopulateEmbeddedVTable(image_pointer_size_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005965 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00005966 if (klass->ShouldHaveImt()) {
5967 klass->SetImt(imt, image_pointer_size_);
5968 }
Mingyao Yang063fc772016-08-02 11:02:54 -07005969
5970 // Update CHA info based on whether we override methods.
5971 // Have to do this before setting the class as resolved which allows
5972 // instantiation of klass.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00005973 if (LIKELY(descriptor != nullptr) && cha_ != nullptr) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07005974 cha_->UpdateAfterLoadingOf(klass);
5975 }
Nicolas Geoffray918dcea2017-07-21 07:58:14 +00005976
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005977 // This will notify waiters on klass that saw the not yet resolved
5978 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00005979 mirror::Class::SetStatus(klass, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005980 h_new_class_out->Assign(klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005981 } else {
5982 CHECK(!klass->IsResolved());
5983 // Retire the temporary class and create the correctly sized resolved class.
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07005984 StackHandleScope<1> hs(self);
Vladimir Marko3068d582019-05-28 16:39:29 +01005985 Handle<mirror::Class> h_new_class =
5986 hs.NewHandle(mirror::Class::CopyOf(klass, self, class_size, imt, image_pointer_size_));
Mathieu Chartier3ee25bb2015-08-10 10:13:02 -07005987 // Set arrays to null since we don't want to have multiple classes with the same ArtField or
5988 // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
5989 // may not see any references to the target space and clean the card for a class if another
5990 // class had the same array pointer.
Alex Lighte64300b2015-12-15 15:02:47 -08005991 klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07005992 klass->SetSFieldsPtrUnchecked(nullptr);
5993 klass->SetIFieldsPtrUnchecked(nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08005994 if (UNLIKELY(h_new_class == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07005995 self->AssertPendingOOMException();
Vladimir Marko2c64a832018-01-04 11:31:56 +00005996 mirror::Class::SetStatus(klass, ClassStatus::kErrorUnresolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07005997 return false;
5998 }
5999
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006000 CHECK_EQ(h_new_class->GetClassSize(), class_size);
6001 ObjectLock<mirror::Class> lock(self, h_new_class);
6002 FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006003
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00006004 if (LIKELY(descriptor != nullptr)) {
Mathieu Chartiereb837eb2015-07-29 17:25:41 -07006005 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko0984e482019-03-27 16:41:41 +00006006 const ObjPtr<mirror::ClassLoader> class_loader = h_new_class.Get()->GetClassLoader();
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006007 ClassTable* const table = InsertClassTableForClassLoader(class_loader);
Vladimir Marko0984e482019-03-27 16:41:41 +00006008 const ObjPtr<mirror::Class> existing =
6009 table->UpdateClass(descriptor, h_new_class.Get(), ComputeModifiedUtf8Hash(descriptor));
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07006010 if (class_loader != nullptr) {
6011 // We updated the class in the class table, perform the write barrier so that the GC knows
6012 // about the change.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -07006013 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier05aa4d32015-09-19 12:44:38 -07006014 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006015 CHECK_EQ(existing, klass.Get());
Vladimir Marko1998cd02017-01-13 13:02:58 +00006016 if (log_new_roots_) {
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07006017 new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
6018 }
6019 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006020
Mingyao Yang063fc772016-08-02 11:02:54 -07006021 // Update CHA info based on whether we override methods.
6022 // Have to do this before setting the class as resolved which allows
6023 // instantiation of klass.
Nicolas Geoffray4ac0e152019-09-18 06:14:50 +00006024 if (LIKELY(descriptor != nullptr) && cha_ != nullptr) {
Andreas Gampec1ac9ee2017-07-24 22:35:49 -07006025 cha_->UpdateAfterLoadingOf(h_new_class);
6026 }
Mingyao Yang063fc772016-08-02 11:02:54 -07006027
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006028 // This will notify waiters on temp class that saw the not yet resolved class in the
6029 // class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006030 mirror::Class::SetStatus(klass, ClassStatus::kRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006031
Vladimir Marko2c64a832018-01-04 11:31:56 +00006032 CHECK_EQ(h_new_class->GetStatus(), ClassStatus::kResolving);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006033 // This will notify waiters on new_class that saw the not yet resolved
6034 // class in the class_table_ during EnsureResolved.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006035 mirror::Class::SetStatus(h_new_class, ClassStatus::kResolved, self);
Hiroshi Yamauchi679b1cf2015-05-21 12:05:27 -07006036 // Return the new class.
6037 h_new_class_out->Assign(h_new_class.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006038 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006039 return true;
6040}
6041
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006042bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Vladimir Marko2c64a832018-01-04 11:31:56 +00006043 CHECK_EQ(ClassStatus::kIdx, klass->GetStatus());
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006044 const dex::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
Andreas Gampea5b09a62016-11-17 15:21:22 -08006045 dex::TypeIndex super_class_idx = class_def.superclass_idx_;
6046 if (super_class_idx.IsValid()) {
Roland Levillain90328ac2016-05-18 12:25:38 +01006047 // Check that a class does not inherit from itself directly.
6048 //
6049 // TODO: This is a cheap check to detect the straightforward case
6050 // of a class extending itself (b/28685551), but we should do a
6051 // proper cycle detection on loaded classes, to detect all cases
6052 // of class circularity errors (b/28830038).
6053 if (super_class_idx == class_def.class_idx_) {
6054 ThrowClassCircularityError(klass.Get(),
6055 "Class %s extends itself",
David Sehr709b0702016-10-13 09:12:37 -07006056 klass->PrettyDescriptor().c_str());
Roland Levillain90328ac2016-05-18 12:25:38 +01006057 return false;
6058 }
6059
Vladimir Marko666ee3d2017-12-11 18:37:36 +00006060 ObjPtr<mirror::Class> super_class = ResolveType(super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006061 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07006062 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006063 return false;
6064 }
Ian Rogersbe125a92012-01-11 15:19:49 -08006065 // Verify
6066 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006067 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07006068 super_class->PrettyDescriptor().c_str(),
6069 klass->PrettyDescriptor().c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08006070 return false;
6071 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07006072 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006073 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006074 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006075 const dex::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006076 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006077 for (size_t i = 0; i < interfaces->Size(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08006078 dex::TypeIndex idx = interfaces->GetTypeItem(i).type_idx_;
Vladimir Marko666ee3d2017-12-11 18:37:36 +00006079 ObjPtr<mirror::Class> interface = ResolveType(idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006080 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006081 DCHECK(Thread::Current()->IsExceptionPending());
6082 return false;
6083 }
6084 // Verify
6085 if (!klass->CanAccess(interface)) {
6086 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006087 ThrowIllegalAccessError(klass.Get(),
6088 "Interface %s implemented by class %s is inaccessible",
David Sehr709b0702016-10-13 09:12:37 -07006089 interface->PrettyDescriptor().c_str(),
6090 klass->PrettyDescriptor().c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08006091 return false;
6092 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006093 }
6094 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07006095 // Mark the class as loaded.
Vladimir Marko2c64a832018-01-04 11:31:56 +00006096 mirror::Class::SetStatus(klass, ClassStatus::kLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006097 return true;
6098}
6099
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07006100bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006101 CHECK(!klass->IsPrimitive());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006102 ObjPtr<mirror::Class> super = klass->GetSuperClass();
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006103 ObjPtr<mirror::Class> object_class = GetClassRoot<mirror::Object>(this);
6104 if (klass.Get() == object_class) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006105 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006106 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006107 return false;
6108 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006109 return true;
6110 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006111 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006112 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
David Sehr709b0702016-10-13 09:12:37 -07006113 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006114 return false;
6115 }
6116 // Verify
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006117 if (klass->IsInterface() && super != object_class) {
Vladimir Marko1fcae9f2017-11-28 14:14:19 +00006118 ThrowClassFormatError(klass.Get(), "Interfaces must have java.lang.Object as superclass");
6119 return false;
6120 }
Vladimir Markob43b2d82017-07-18 17:46:38 +01006121 if (super->IsFinal()) {
6122 ThrowVerifyError(klass.Get(),
6123 "Superclass %s of %s is declared final",
6124 super->PrettyDescriptor().c_str(),
6125 klass->PrettyDescriptor().c_str());
6126 return false;
6127 }
6128 if (super->IsInterface()) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006129 ThrowIncompatibleClassChangeError(klass.Get(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006130 "Superclass %s of %s is an interface",
David Sehr709b0702016-10-13 09:12:37 -07006131 super->PrettyDescriptor().c_str(),
Vladimir Markob43b2d82017-07-18 17:46:38 +01006132 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006133 return false;
6134 }
6135 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006136 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
David Sehr709b0702016-10-13 09:12:37 -07006137 super->PrettyDescriptor().c_str(),
6138 klass->PrettyDescriptor().c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006139 return false;
6140 }
Elliott Hughes20cde902011-10-04 17:37:27 -07006141
Brian Carlstromf3632832014-05-20 15:36:53 -07006142 // Inherit kAccClassIsFinalizable from the superclass in case this
6143 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07006144 if (super->IsFinalizable()) {
6145 klass->SetFinalizable();
6146 }
6147
Mathieu Chartiere4275c02015-08-06 15:34:15 -07006148 // Inherit class loader flag form super class.
6149 if (super->IsClassLoaderClass()) {
6150 klass->SetClassLoaderClass();
6151 }
6152
Elliott Hughes2da50362011-10-10 16:57:08 -07006153 // Inherit reference flags (if any) from the superclass.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006154 uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
Elliott Hughes2da50362011-10-10 16:57:08 -07006155 if (reference_flags != 0) {
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07006156 CHECK_EQ(klass->GetClassFlags(), 0u);
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07006157 klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
Elliott Hughes2da50362011-10-10 16:57:08 -07006158 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006159 // Disallow custom direct subclasses of java.lang.ref.Reference.
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006160 if (init_done_ && super == GetClassRoot<mirror::Reference>(this)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006161 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08006162 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
David Sehr709b0702016-10-13 09:12:37 -07006163 klass->PrettyDescriptor().c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07006164 return false;
6165 }
Elliott Hughes2da50362011-10-10 16:57:08 -07006166
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006167 if (kIsDebugBuild) {
6168 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07006169 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07006170 CHECK(super->IsResolved());
6171 super = super->GetSuperClass();
6172 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006173 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006174 return true;
6175}
6176
Vladimir Marko782fb712020-12-23 12:47:31 +00006177// A wrapper class representing the result of a method translation used for linking methods and
6178// updating superclass default methods. For each method in a classes vtable there are 4 states it
6179// could be in:
6180// 1) No translation is necessary. In this case there is no MethodTranslation object for it. This
6181// is the standard case and is true when the method is not overridable by a default method,
6182// the class defines a concrete implementation of the method, the default method implementation
6183// remains the same, or an abstract method stayed abstract.
6184// 2) The method must be translated to a different default method. We note this with
6185// CreateTranslatedMethod.
6186// 3) The method must be replaced with a conflict method. This happens when a superclass
6187// implements an interface with a default method and this class implements an unrelated
6188// interface that also defines that default method. We note this with CreateConflictingMethod.
6189// 4) The method must be replaced with an abstract miranda method. This happens when a superclass
6190// implements an interface with a default method and this class implements a subinterface of
6191// the superclass's interface which declares the default method abstract. We note this with
6192// CreateAbstractMethod.
6193//
6194// When a method translation is unnecessary (case #1), we don't put it into the
6195// default_translation maps. So an instance of MethodTranslation must be in one of #2-#4.
6196class ClassLinker::MethodTranslation {
6197 public:
6198 MethodTranslation() : translation_(nullptr), type_(Type::kInvalid) {}
6199
6200 // This slot must become a default conflict method.
6201 static MethodTranslation CreateConflictingMethod() {
6202 return MethodTranslation(Type::kConflict, /*translation=*/nullptr);
6203 }
6204
6205 // This slot must become an abstract method.
6206 static MethodTranslation CreateAbstractMethod() {
6207 return MethodTranslation(Type::kAbstract, /*translation=*/nullptr);
6208 }
6209
6210 // Use the given method as the current value for this vtable slot during translation.
6211 static MethodTranslation CreateTranslatedMethod(ArtMethod* new_method) {
6212 return MethodTranslation(Type::kTranslation, new_method);
6213 }
6214
6215 // Returns true if this is a method that must become a conflict method.
6216 bool IsInConflict() const {
6217 return type_ == Type::kConflict;
6218 }
6219
6220 // Returns true if this is a method that must become an abstract method.
6221 bool IsAbstract() const {
6222 return type_ == Type::kAbstract;
6223 }
6224
6225 // Returns true if this is a method that must become a different method.
6226 bool IsTranslation() const {
6227 return type_ == Type::kTranslation;
6228 }
6229
6230 // Get the translated version of this method.
6231 ArtMethod* GetTranslation() const {
6232 DCHECK(IsTranslation());
6233 DCHECK(translation_ != nullptr);
6234 return translation_;
6235 }
6236
6237 private:
6238 enum class Type {
6239 kInvalid,
6240 kTranslation,
6241 kConflict,
6242 kAbstract,
6243 };
6244
6245 MethodTranslation(Type type, ArtMethod* translation)
6246 : translation_(translation), type_(type) {}
6247
6248 ArtMethod* translation_;
6249 Type type_;
6250};
6251
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006252// Populate the class vtable and itable. Compute return type indices.
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006253bool ClassLinker::LinkMethods(Thread* self,
6254 Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006255 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006256 bool* out_new_conflict,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07006257 ArtMethod** out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07006258 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07006259 // A map from vtable indexes to the method they need to be updated to point to. Used because we
6260 // need to have default methods be in the virtuals array of each class but we don't set that up
6261 // until LinkInterfaceMethods.
Vladimir Marko782fb712020-12-23 12:47:31 +00006262 constexpr size_t kBufferSize = 8; // Avoid malloc/free for a few translations.
6263 std::pair<size_t, ClassLinker::MethodTranslation> buffer[kBufferSize];
6264 HashMap<size_t, ClassLinker::MethodTranslation> default_translations(buffer, kBufferSize);
Alex Lighteb7c1442015-08-31 13:17:42 -07006265 // Link virtual methods then interface methods.
6266 // We set up the interface lookup table first because we need it to determine if we need to update
6267 // any vtable entries with new default method implementations.
6268 return SetupInterfaceLookupTable(self, klass, interfaces)
6269 && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006270 && LinkInterfaceMethods(self, klass, default_translations, out_new_conflict, out_imt);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006271}
6272
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006273// Comparator for name and signature of a method, used in finding overriding methods. Implementation
6274// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
6275// caches in the implementation below.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01006276class MethodNameAndSignatureComparator final : public ValueObject {
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006277 public:
Mathieu Chartiere401d142015-04-22 13:56:20 -07006278 explicit MethodNameAndSignatureComparator(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006279 REQUIRES_SHARED(Locks::mutator_lock_) :
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006280 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
6281 name_(nullptr), name_len_(0) {
David Sehr709b0702016-10-13 09:12:37 -07006282 DCHECK(!method->IsProxyMethod()) << method->PrettyMethod();
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006283 }
6284
6285 const char* GetName() {
6286 if (name_ == nullptr) {
6287 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
6288 }
6289 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006290 }
6291
Mathieu Chartiere401d142015-04-22 13:56:20 -07006292 bool HasSameNameAndSignature(ArtMethod* other)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006293 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07006294 DCHECK(!other->IsProxyMethod()) << other->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006295 const DexFile* other_dex_file = other->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006296 const dex::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006297 if (dex_file_ == other_dex_file) {
6298 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
6299 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006300 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006301 uint32_t other_name_len;
6302 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
6303 &other_name_len);
6304 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
6305 return false;
6306 }
6307 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
6308 }
6309
6310 private:
6311 // Dex file for the method to compare against.
6312 const DexFile* const dex_file_;
6313 // MethodId for the method to compare against.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08006314 const dex::MethodId* const mid_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07006315 // Lazily computed name from the dex file's strings.
6316 const char* name_;
6317 // Lazily computed name length.
6318 uint32_t name_len_;
6319};
6320
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006321class LinkVirtualHashTable {
6322 public:
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006323 LinkVirtualHashTable(Handle<mirror::Class> klass,
6324 size_t hash_size,
6325 uint32_t* hash_table,
Andreas Gampe542451c2016-07-26 09:02:02 -07006326 PointerSize image_pointer_size)
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006327 : klass_(klass),
6328 hash_size_(hash_size),
6329 hash_table_(hash_table),
Mathieu Chartiere401d142015-04-22 13:56:20 -07006330 image_pointer_size_(image_pointer_size) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006331 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
6332 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006333
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006334 void Add(uint32_t virtual_method_index) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006335 ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
6336 virtual_method_index, image_pointer_size_);
6337 const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08006338 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006339 uint32_t index = hash % hash_size_;
6340 // Linear probe until we have an empty slot.
6341 while (hash_table_[index] != invalid_index_) {
6342 if (++index == hash_size_) {
6343 index = 0;
6344 }
6345 }
6346 hash_table_[index] = virtual_method_index;
6347 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006348
Vladimir Marko43354742021-02-03 15:37:01 +00006349 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator, uint32_t hash)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006350 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko43354742021-02-03 15:37:01 +00006351 DCHECK_EQ(hash, ComputeModifiedUtf8Hash(comparator->GetName()));
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006352 size_t index = hash % hash_size_;
6353 while (true) {
6354 const uint32_t value = hash_table_[index];
6355 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
6356 // the block and can safely assume not found.
6357 if (value == invalid_index_) {
6358 break;
6359 }
6360 if (value != removed_index_) { // This signifies not already overriden.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006361 ArtMethod* virtual_method =
6362 klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
6363 if (comparator->HasSameNameAndSignature(
6364 virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006365 hash_table_[index] = removed_index_;
6366 return value;
6367 }
6368 }
6369 if (++index == hash_size_) {
6370 index = 0;
6371 }
6372 }
6373 return GetNotFoundIndex();
6374 }
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07006375
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006376 static uint32_t GetNotFoundIndex() {
6377 return invalid_index_;
6378 }
6379
6380 private:
6381 static const uint32_t invalid_index_;
6382 static const uint32_t removed_index_;
6383
6384 Handle<mirror::Class> klass_;
6385 const size_t hash_size_;
6386 uint32_t* const hash_table_;
Andreas Gampe542451c2016-07-26 09:02:02 -07006387 const PointerSize image_pointer_size_;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006388};
6389
6390const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
6391const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
6392
Stephen Hines1ddd9132017-02-08 01:51:18 -08006393bool ClassLinker::LinkVirtualMethods(
Alex Lighteb7c1442015-08-31 13:17:42 -07006394 Thread* self,
6395 Handle<mirror::Class> klass,
Vladimir Marko782fb712020-12-23 12:47:31 +00006396 /*out*/HashMap<size_t, ClassLinker::MethodTranslation>* default_translations) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006397 const size_t num_virtual_methods = klass->NumVirtualMethods();
Alex Lighteb7c1442015-08-31 13:17:42 -07006398 if (klass->IsInterface()) {
6399 // No vtable.
6400 if (!IsUint<16>(num_virtual_methods)) {
6401 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
6402 return false;
6403 }
6404 bool has_defaults = false;
Alex Lighteb7c1442015-08-31 13:17:42 -07006405 // Assign each method an IMT index and set the default flag.
6406 for (size_t i = 0; i < num_virtual_methods; ++i) {
6407 ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6408 m->SetMethodIndex(i);
6409 if (!m->IsAbstract()) {
Vladimir Marko1c993cd2020-05-28 09:30:06 +00006410 // If the dex file does not support default methods, throw ClassFormatError.
6411 // This check is necessary to protect from odd cases, such as native default
6412 // methods, that the dex file verifier permits for old dex file versions. b/157170505
6413 // FIXME: This should be `if (!m->GetDexFile()->SupportsDefaultMethods())` but we're
6414 // currently running CTS tests for default methods with dex file version 035 which
6415 // does not support default methods. So, we limit this to native methods. b/157718952
6416 if (m->IsNative()) {
6417 DCHECK(!m->GetDexFile()->SupportsDefaultMethods());
6418 ThrowClassFormatError(klass.Get(),
6419 "Dex file does not support default method '%s'",
6420 m->PrettyMethod().c_str());
6421 return false;
6422 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006423 m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
6424 has_defaults = true;
6425 }
6426 }
6427 // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
6428 // during initialization. This is a performance optimization. We could simply traverse the
6429 // virtual_methods_ array again during initialization.
6430 if (has_defaults) {
6431 klass->SetHasDefaultMethods();
6432 }
6433 return true;
6434 } else if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006435 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
6436 const size_t max_count = num_virtual_methods + super_vtable_length;
Vladimir Marko3068d582019-05-28 16:39:29 +01006437 StackHandleScope<3> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07006438 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07006439 MutableHandle<mirror::PointerArray> vtable;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006440 if (super_class->ShouldHaveEmbeddedVTable()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006441 vtable = hs.NewHandle(AllocPointerArray(self, max_count));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006442 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006443 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006444 return false;
6445 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006446 for (size_t i = 0; i < super_vtable_length; i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006447 vtable->SetElementPtrSize(
6448 i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006449 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006450 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6451 // might give us new default methods). If no new interfaces then we can skip the rest since
6452 // the class cannot override any of the super-class's methods. This is required for
6453 // correctness since without it we might not update overridden default method vtable entries
6454 // correctly.
6455 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006456 klass->SetVTable(vtable.Get());
6457 return true;
6458 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006459 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07006460 DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
Vladimir Marko3068d582019-05-28 16:39:29 +01006461 Handle<mirror::PointerArray> super_vtable = hs.NewHandle(super_class->GetVTable());
David Sehr709b0702016-10-13 09:12:37 -07006462 CHECK(super_vtable != nullptr) << super_class->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07006463 // We might need to change vtable if we have new virtual methods or new interfaces (since that
6464 // might give us new default methods). See comment above.
6465 if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
Vladimir Marko3068d582019-05-28 16:39:29 +01006466 klass->SetVTable(super_vtable.Get());
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006467 return true;
6468 }
Vladimir Marko3068d582019-05-28 16:39:29 +01006469 vtable = hs.NewHandle(ObjPtr<mirror::PointerArray>::DownCast(
6470 mirror::Array::CopyOf(super_vtable, self, max_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006471 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006472 self->AssertPendingOOMException();
Mingyao Yang2cdbad72014-07-16 10:44:41 -07006473 return false;
6474 }
Ian Rogersa436fde2013-08-27 23:34:06 -07006475 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006476 // How the algorithm works:
6477 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
6478 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
6479 // method which has not been matched to a vtable method, and j if the virtual method at the
6480 // index overrode the super virtual method at index j.
6481 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
6482 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
6483 // the need for the initial vtable which we later shrink back down).
6484 // 3. Add non overridden methods to the end of the vtable.
6485 static constexpr size_t kMaxStackHash = 250;
Alex Lighteb7c1442015-08-31 13:17:42 -07006486 // + 1 so that even if we only have new default methods we will still be able to use this hash
6487 // table (i.e. it will never have 0 size).
6488 const size_t hash_table_size = num_virtual_methods * 3 + 1;
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006489 uint32_t* hash_table_ptr;
6490 std::unique_ptr<uint32_t[]> hash_heap_storage;
6491 if (hash_table_size <= kMaxStackHash) {
6492 hash_table_ptr = reinterpret_cast<uint32_t*>(
6493 alloca(hash_table_size * sizeof(*hash_table_ptr)));
6494 } else {
6495 hash_heap_storage.reset(new uint32_t[hash_table_size]);
6496 hash_table_ptr = hash_heap_storage.get();
6497 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006498 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006499 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006500 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006501 DCHECK(klass->GetVirtualMethodDuringLinking(
6502 i, image_pointer_size_)->GetDeclaringClass() != nullptr);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006503 hash_table.Add(i);
6504 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006505 // 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 -07006506 // the hash table.
6507 for (size_t j = 0; j < super_vtable_length; ++j) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006508 // Search the hash table to see if we are overridden by any method.
Mathieu Chartiere401d142015-04-22 13:56:20 -07006509 ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006510 if (!klass->CanAccessMember(super_method->GetDeclaringClass(),
6511 super_method->GetAccessFlags())) {
6512 // Continue on to the next method since this one is package private and canot be overridden.
6513 // Before Android 4.1, the package-private method super_method might have been incorrectly
6514 // overridden.
6515 continue;
6516 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006517 MethodNameAndSignatureComparator super_method_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07006518 super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lightc7a420c2016-10-18 14:33:18 -07006519 // We remove the method so that subsequent lookups will be faster by making the hash-map
6520 // smaller as we go on.
Vladimir Marko43354742021-02-03 15:37:01 +00006521 uint32_t hash = (j < mirror::Object::kVTableLength)
6522 ? object_virtual_method_hashes_[j]
6523 : ComputeModifiedUtf8Hash(super_method_name_comparator.GetName());
6524 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator, hash);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006525 if (hash_index != hash_table.GetNotFoundIndex()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006526 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
6527 hash_index, image_pointer_size_);
Alex Lightc7a420c2016-10-18 14:33:18 -07006528 if (super_method->IsFinal()) {
6529 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
6530 virtual_method->PrettyMethod().c_str(),
6531 super_method->GetDeclaringClassDescriptor());
6532 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006533 }
Alex Lightc7a420c2016-10-18 14:33:18 -07006534 vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
6535 virtual_method->SetMethodIndex(j);
Alex Light9139e002015-10-09 15:59:48 -07006536 } else if (super_method->IsOverridableByDefaultMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006537 // We didn't directly override this method but we might through default methods...
6538 // Check for default method update.
6539 ArtMethod* default_method = nullptr;
Alex Light9139e002015-10-09 15:59:48 -07006540 switch (FindDefaultMethodImplementation(self,
6541 super_method,
6542 klass,
6543 /*out*/&default_method)) {
6544 case DefaultMethodSearchResult::kDefaultConflict: {
6545 // A conflict was found looking for default methods. Note this (assuming it wasn't
6546 // pre-existing) in the translations map.
6547 if (UNLIKELY(!super_method->IsDefaultConflicting())) {
6548 // Don't generate another conflict method to reduce memory use as an optimization.
6549 default_translations->insert(
6550 {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
6551 }
6552 break;
6553 }
6554 case DefaultMethodSearchResult::kAbstractFound: {
6555 // No conflict but method is abstract.
6556 // We note that this vtable entry must be made abstract.
6557 if (UNLIKELY(!super_method->IsAbstract())) {
6558 default_translations->insert(
6559 {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
6560 }
6561 break;
6562 }
6563 case DefaultMethodSearchResult::kDefaultFound: {
6564 if (UNLIKELY(super_method->IsDefaultConflicting() ||
6565 default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
6566 // Found a default method implementation that is new.
6567 // TODO Refactor this add default methods to virtuals here and not in
6568 // LinkInterfaceMethods maybe.
6569 // The problem is default methods might override previously present
6570 // default-method or miranda-method vtable entries from the superclass.
6571 // Unfortunately we need these to be entries in this class's virtuals. We do not
6572 // give these entries there until LinkInterfaceMethods so we pass this map around
6573 // to let it know which vtable entries need to be updated.
6574 // Make a note that vtable entry j must be updated, store what it needs to be updated
6575 // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
6576 // then.
6577 default_translations->insert(
6578 {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
David Sehr709b0702016-10-13 09:12:37 -07006579 VLOG(class_linker) << "Method " << super_method->PrettyMethod()
6580 << " overridden by default "
6581 << default_method->PrettyMethod()
6582 << " in " << mirror::Class::PrettyClass(klass.Get());
Alex Light9139e002015-10-09 15:59:48 -07006583 }
6584 break;
6585 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006586 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006587 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006588 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006589 size_t actual_count = super_vtable_length;
Alex Lighteb7c1442015-08-31 13:17:42 -07006590 // Add the non-overridden methods at the end.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006591 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006592 ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006593 size_t method_idx = local_method->GetMethodIndexDuringLinking();
6594 if (method_idx < super_vtable_length &&
Mathieu Chartiere401d142015-04-22 13:56:20 -07006595 local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006596 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006597 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07006598 vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07006599 local_method->SetMethodIndex(actual_count);
6600 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006601 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006602 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006603 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006604 return false;
6605 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006606 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006607 CHECK_LE(actual_count, max_count);
6608 if (actual_count < max_count) {
Vladimir Marko3068d582019-05-28 16:39:29 +01006609 vtable.Assign(ObjPtr<mirror::PointerArray>::DownCast(
6610 mirror::Array::CopyOf(vtable, self, actual_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08006611 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006612 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006613 return false;
6614 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006615 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07006616 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006617 } else {
Vladimir Markob4eb1b12018-05-24 11:09:38 +01006618 CHECK_EQ(klass.Get(), GetClassRoot<mirror::Object>(this));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08006619 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006620 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
6621 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006622 return false;
6623 }
Vladimir Markobcf17522018-06-01 13:14:32 +01006624 ObjPtr<mirror::PointerArray> vtable = AllocPointerArray(self, num_virtual_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006625 if (UNLIKELY(vtable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006626 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07006627 return false;
6628 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07006629 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07006630 ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
6631 vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006632 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006633 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07006634 klass->SetVTable(vtable);
Vladimir Marko43354742021-02-03 15:37:01 +00006635 InitializeObjectVirtualMethodHashes(klass.Get(),
6636 image_pointer_size_,
6637 ArrayRef<uint32_t>(object_virtual_method_hashes_));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006638 }
6639 return true;
6640}
6641
Alex Light9139e002015-10-09 15:59:48 -07006642// Determine if the given iface has any subinterface in the given list that declares the method
6643// specified by 'target'.
6644//
6645// Arguments
6646// - self: The thread we are running on
6647// - target: A comparator that will match any method that overrides the method we are checking for
6648// - iftable: The iftable we are searching for an overriding method on.
6649// - ifstart: The index of the interface we are checking to see if anything overrides
6650// - iface: The interface we are checking to see if anything overrides.
6651// - image_pointer_size:
6652// The image pointer size.
6653//
6654// Returns
6655// - True: There is some method that matches the target comparator defined in an interface that
6656// is a subtype of iface.
6657// - False: There is no method that matches the target comparator in any interface that is a subtype
6658// of iface.
6659static bool ContainsOverridingMethodOf(Thread* self,
6660 MethodNameAndSignatureComparator& target,
6661 Handle<mirror::IfTable> iftable,
6662 size_t ifstart,
6663 Handle<mirror::Class> iface,
Andreas Gampe542451c2016-07-26 09:02:02 -07006664 PointerSize image_pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07006665 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07006666 DCHECK(self != nullptr);
Andreas Gampefa4333d2017-02-14 11:10:34 -08006667 DCHECK(iface != nullptr);
6668 DCHECK(iftable != nullptr);
Alex Light9139e002015-10-09 15:59:48 -07006669 DCHECK_GE(ifstart, 0u);
6670 DCHECK_LT(ifstart, iftable->Count());
6671 DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
6672 DCHECK(iface->IsInterface());
6673
6674 size_t iftable_count = iftable->Count();
6675 StackHandleScope<1> hs(self);
6676 MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
6677 for (size_t k = ifstart + 1; k < iftable_count; k++) {
6678 // Skip ifstart since our current interface obviously cannot override itself.
6679 current_iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006680 // Iterate through every method on this interface. The order does not matter.
6681 for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
Alex Light9139e002015-10-09 15:59:48 -07006682 if (UNLIKELY(target.HasSameNameAndSignature(
Alex Lighte64300b2015-12-15 15:02:47 -08006683 current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
Alex Light9139e002015-10-09 15:59:48 -07006684 // Check if the i'th interface is a subtype of this one.
6685 if (iface->IsAssignableFrom(current_iface.Get())) {
6686 return true;
6687 }
6688 break;
6689 }
6690 }
6691 }
6692 return false;
6693}
6694
Alex Lighteb7c1442015-08-31 13:17:42 -07006695// Find the default method implementation for 'interface_method' in 'klass'. Stores it into
Alex Light9139e002015-10-09 15:59:48 -07006696// out_default_method and returns kDefaultFound on success. If no default method was found return
6697// kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
6698// default_method conflict) it will return kDefaultConflict.
6699ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
6700 Thread* self,
6701 ArtMethod* target_method,
6702 Handle<mirror::Class> klass,
6703 /*out*/ArtMethod** out_default_method) const {
Alex Lighteb7c1442015-08-31 13:17:42 -07006704 DCHECK(self != nullptr);
6705 DCHECK(target_method != nullptr);
6706 DCHECK(out_default_method != nullptr);
Alex Lighteb7c1442015-08-31 13:17:42 -07006707
6708 *out_default_method = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07006709
6710 // We organize the interface table so that, for interface I any subinterfaces J follow it in the
6711 // table. This lets us walk the table backwards when searching for default methods. The first one
6712 // we encounter is the best candidate since it is the most specific. Once we have found it we keep
6713 // track of it and then continue checking all other interfaces, since we need to throw an error if
6714 // we encounter conflicting default method implementations (one is not a subtype of the other).
6715 //
6716 // The order of unrelated interfaces does not matter and is not defined.
6717 size_t iftable_count = klass->GetIfTableCount();
6718 if (iftable_count == 0) {
Alex Light9139e002015-10-09 15:59:48 -07006719 // No interfaces. We have already reset out to null so just return kAbstractFound.
6720 return DefaultMethodSearchResult::kAbstractFound;
Alex Lighteb7c1442015-08-31 13:17:42 -07006721 }
6722
Alex Light9139e002015-10-09 15:59:48 -07006723 StackHandleScope<3> hs(self);
6724 MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006725 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Alex Light9139e002015-10-09 15:59:48 -07006726 MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
Alex Lighteb7c1442015-08-31 13:17:42 -07006727 MethodNameAndSignatureComparator target_name_comparator(
6728 target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6729 // Iterates over the klass's iftable in reverse
Alex Light9139e002015-10-09 15:59:48 -07006730 for (size_t k = iftable_count; k != 0; ) {
6731 --k;
6732
Alex Lighteb7c1442015-08-31 13:17:42 -07006733 DCHECK_LT(k, iftable->Count());
Alex Light9139e002015-10-09 15:59:48 -07006734
6735 iface.Assign(iftable->GetInterface(k));
Alex Lighte64300b2015-12-15 15:02:47 -08006736 // Iterate through every declared method on this interface. The order does not matter.
6737 for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
6738 ArtMethod* current_method = &method_iter;
Alex Lighteb7c1442015-08-31 13:17:42 -07006739 // Skip abstract methods and methods with different names.
6740 if (current_method->IsAbstract() ||
6741 !target_name_comparator.HasSameNameAndSignature(
6742 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6743 continue;
Alex Lightd7c10c22016-03-31 10:03:07 -07006744 } else if (!current_method->IsPublic()) {
6745 // The verifier should have caught the non-public method for dex version 37. Just warn and
6746 // skip it since this is from before default-methods so we don't really need to care that it
6747 // has code.
David Sehr709b0702016-10-13 09:12:37 -07006748 LOG(WARNING) << "Interface method " << current_method->PrettyMethod()
6749 << " is not public! "
Alex Lightd7c10c22016-03-31 10:03:07 -07006750 << "This will be a fatal error in subsequent versions of android. "
6751 << "Continuing anyway.";
Alex Lighteb7c1442015-08-31 13:17:42 -07006752 }
Andreas Gampefa4333d2017-02-14 11:10:34 -08006753 if (UNLIKELY(chosen_iface != nullptr)) {
Alex Light9139e002015-10-09 15:59:48 -07006754 // We have multiple default impls of the same method. This is a potential default conflict.
6755 // We need to check if this possibly conflicting method is either a superclass of the chosen
6756 // default implementation or is overridden by a non-default interface method. In either case
6757 // there is no conflict.
6758 if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
6759 !ContainsOverridingMethodOf(self,
6760 target_name_comparator,
6761 iftable,
6762 k,
6763 iface,
6764 image_pointer_size_)) {
Nicolas Geoffray7f3e0db2016-01-28 09:29:31 +00006765 VLOG(class_linker) << "Conflicting default method implementations found: "
David Sehr709b0702016-10-13 09:12:37 -07006766 << current_method->PrettyMethod() << " and "
6767 << ArtMethod::PrettyMethod(*out_default_method) << " in class "
6768 << klass->PrettyClass() << " conflict.";
Alex Light9139e002015-10-09 15:59:48 -07006769 *out_default_method = nullptr;
6770 return DefaultMethodSearchResult::kDefaultConflict;
Alex Lighteb7c1442015-08-31 13:17:42 -07006771 } else {
6772 break; // Continue checking at the next interface.
6773 }
6774 } else {
Alex Light9139e002015-10-09 15:59:48 -07006775 // chosen_iface == null
6776 if (!ContainsOverridingMethodOf(self,
6777 target_name_comparator,
6778 iftable,
6779 k,
6780 iface,
6781 image_pointer_size_)) {
6782 // Don't set this as the chosen interface if something else is overriding it (because that
6783 // other interface would be potentially chosen instead if it was default). If the other
6784 // interface was abstract then we wouldn't select this interface as chosen anyway since
6785 // the abstract method masks it.
6786 *out_default_method = current_method;
6787 chosen_iface.Assign(iface.Get());
6788 // We should now finish traversing the graph to find if we have default methods that
6789 // conflict.
6790 } else {
David Sehr709b0702016-10-13 09:12:37 -07006791 VLOG(class_linker) << "A default method '" << current_method->PrettyMethod()
6792 << "' was "
6793 << "skipped because it was overridden by an abstract method in a "
6794 << "subinterface on class '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006795 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006796 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006797 break;
6798 }
6799 }
Alex Light9139e002015-10-09 15:59:48 -07006800 if (*out_default_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07006801 VLOG(class_linker) << "Default method '" << (*out_default_method)->PrettyMethod()
6802 << "' selected "
6803 << "as the implementation for '" << target_method->PrettyMethod()
6804 << "' in '" << klass->PrettyClass() << "'";
Alex Light9139e002015-10-09 15:59:48 -07006805 return DefaultMethodSearchResult::kDefaultFound;
6806 } else {
6807 return DefaultMethodSearchResult::kAbstractFound;
6808 }
Alex Lighteb7c1442015-08-31 13:17:42 -07006809}
6810
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006811ArtMethod* ClassLinker::AddMethodToConflictTable(ObjPtr<mirror::Class> klass,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006812 ArtMethod* conflict_method,
6813 ArtMethod* interface_method,
Nicolas Geoffray47213e42020-12-30 15:12:00 +00006814 ArtMethod* method) {
Andreas Gampe542451c2016-07-26 09:02:02 -07006815 ImtConflictTable* current_table = conflict_method->GetImtConflictTable(kRuntimePointerSize);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006816 Runtime* const runtime = Runtime::Current();
6817 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006818
6819 // Create a new entry if the existing one is the shared conflict method.
Nicolas Geoffray47213e42020-12-30 15:12:00 +00006820 ArtMethod* new_conflict_method = (conflict_method == runtime->GetImtConflictMethod())
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006821 ? runtime->CreateImtConflictMethod(linear_alloc)
6822 : conflict_method;
6823
6824 // Allocate a new table. Note that we will leak this table at the next conflict,
6825 // but that's a tradeoff compared to making the table fixed size.
6826 void* data = linear_alloc->Alloc(
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006827 Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6828 image_pointer_size_));
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006829 if (data == nullptr) {
6830 LOG(ERROR) << "Failed to allocate conflict table";
6831 return conflict_method;
6832 }
6833 ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6834 interface_method,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006835 method,
6836 image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006837
6838 // Do a fence to ensure threads see the data in the table before it is assigned
6839 // to the conflict method.
6840 // Note that there is a race in the presence of multiple threads and we may leak
6841 // memory from the LinearAlloc, but that's a tradeoff compared to using
6842 // atomic operations.
Orion Hodson27b96762018-03-13 16:06:57 +00006843 std::atomic_thread_fence(std::memory_order_release);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006844 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006845 return new_conflict_method;
6846}
6847
Vladimir Marko921094a2017-01-12 18:37:06 +00006848bool ClassLinker::AllocateIfTableMethodArrays(Thread* self,
6849 Handle<mirror::Class> klass,
6850 Handle<mirror::IfTable> iftable) {
6851 DCHECK(!klass->IsInterface());
6852 const bool has_superclass = klass->HasSuperClass();
6853 const bool extend_super_iftable = has_superclass;
6854 const size_t ifcount = klass->GetIfTableCount();
6855 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6856 for (size_t i = 0; i < ifcount; ++i) {
6857 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6858 if (num_methods > 0) {
6859 const bool is_super = i < super_ifcount;
6860 // This is an interface implemented by a super-class. Therefore we can just copy the method
6861 // array from the superclass.
6862 const bool super_interface = is_super && extend_super_iftable;
6863 ObjPtr<mirror::PointerArray> method_array;
6864 if (super_interface) {
6865 ObjPtr<mirror::IfTable> if_table = klass->GetSuperClass()->GetIfTable();
6866 DCHECK(if_table != nullptr);
6867 DCHECK(if_table->GetMethodArray(i) != nullptr);
6868 // If we are working on a super interface, try extending the existing method array.
Vladimir Marko3068d582019-05-28 16:39:29 +01006869 StackHandleScope<1u> hs(self);
6870 Handle<mirror::PointerArray> old_array = hs.NewHandle(if_table->GetMethodArray(i));
6871 method_array =
6872 ObjPtr<mirror::PointerArray>::DownCast(mirror::Object::Clone(old_array, self));
Vladimir Marko921094a2017-01-12 18:37:06 +00006873 } else {
6874 method_array = AllocPointerArray(self, num_methods);
6875 }
6876 if (UNLIKELY(method_array == nullptr)) {
6877 self->AssertPendingOOMException();
6878 return false;
6879 }
6880 iftable->SetMethodArray(i, method_array);
6881 }
6882 }
6883 return true;
6884}
6885
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006886void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6887 ArtMethod* imt_conflict_method,
6888 ArtMethod* current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006889 /*out*/bool* new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006890 /*out*/ArtMethod** imt_ref) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006891 // Place method in imt if entry is empty, place conflict otherwise.
6892 if (*imt_ref == unimplemented_method) {
6893 *imt_ref = current_method;
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006894 } else if (!(*imt_ref)->IsRuntimeMethod()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006895 // If we are not a conflict and we have the same signature and name as the imt
6896 // entry, it must be that we overwrote a superclass vtable entry.
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006897 // Note that we have checked IsRuntimeMethod, as there may be multiple different
6898 // conflict methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07006899 MethodNameAndSignatureComparator imt_comparator(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006900 (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
Alex Lighteb7c1442015-08-31 13:17:42 -07006901 if (imt_comparator.HasSameNameAndSignature(
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006902 current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
Alex Lighteb7c1442015-08-31 13:17:42 -07006903 *imt_ref = current_method;
6904 } else {
Alex Light9139e002015-10-09 15:59:48 -07006905 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006906 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006907 }
Nicolas Geoffray796d6302016-03-13 22:22:31 +00006908 } else {
6909 // Place the default conflict method. Note that there may be an existing conflict
6910 // method in the IMT, but it could be one tailored to the super class, with a
6911 // specific ImtConflictTable.
6912 *imt_ref = imt_conflict_method;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006913 *new_conflict = true;
Alex Lighteb7c1442015-08-31 13:17:42 -07006914 }
6915}
6916
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006917void ClassLinker::FillIMTAndConflictTables(ObjPtr<mirror::Class> klass) {
David Sehr709b0702016-10-13 09:12:37 -07006918 DCHECK(klass->ShouldHaveImt()) << klass->PrettyClass();
6919 DCHECK(!klass->IsTemp()) << klass->PrettyClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006920 ArtMethod* imt_data[ImTable::kSize];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006921 Runtime* const runtime = Runtime::Current();
6922 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6923 ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006924 std::fill_n(imt_data, arraysize(imt_data), unimplemented_method);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006925 if (klass->GetIfTable() != nullptr) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006926 bool new_conflict = false;
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006927 FillIMTFromIfTable(klass->GetIfTable(),
6928 unimplemented_method,
6929 conflict_method,
6930 klass,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07006931 /*create_conflict_tables=*/true,
6932 /*ignore_copied_methods=*/false,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006933 &new_conflict,
6934 &imt_data[0]);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006935 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006936 // Compare the IMT with the super class including the conflict methods. If they are equivalent,
6937 // we can just use the same pointer.
6938 ImTable* imt = nullptr;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006939 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006940 if (super_class != nullptr && super_class->ShouldHaveImt()) {
6941 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
6942 bool same = true;
6943 for (size_t i = 0; same && i < ImTable::kSize; ++i) {
6944 ArtMethod* method = imt_data[i];
6945 ArtMethod* super_method = super_imt->Get(i, image_pointer_size_);
6946 if (method != super_method) {
6947 bool is_conflict_table = method->IsRuntimeMethod() &&
6948 method != unimplemented_method &&
6949 method != conflict_method;
6950 // Verify conflict contents.
6951 bool super_conflict_table = super_method->IsRuntimeMethod() &&
6952 super_method != unimplemented_method &&
6953 super_method != conflict_method;
6954 if (!is_conflict_table || !super_conflict_table) {
6955 same = false;
6956 } else {
6957 ImtConflictTable* table1 = method->GetImtConflictTable(image_pointer_size_);
6958 ImtConflictTable* table2 = super_method->GetImtConflictTable(image_pointer_size_);
6959 same = same && table1->Equals(table2, image_pointer_size_);
6960 }
6961 }
6962 }
6963 if (same) {
6964 imt = super_imt;
6965 }
6966 }
6967 if (imt == nullptr) {
6968 imt = klass->GetImt(image_pointer_size_);
6969 DCHECK(imt != nullptr);
6970 imt->Populate(imt_data, image_pointer_size_);
6971 } else {
6972 klass->SetImt(imt, image_pointer_size_);
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006973 }
6974}
6975
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006976ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
6977 LinearAlloc* linear_alloc,
Andreas Gampe542451c2016-07-26 09:02:02 -07006978 PointerSize image_pointer_size) {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006979 void* data = linear_alloc->Alloc(Thread::Current(),
6980 ImtConflictTable::ComputeSize(count,
6981 image_pointer_size));
6982 return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
6983}
6984
6985ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
6986 return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
6987}
6988
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006989void ClassLinker::FillIMTFromIfTable(ObjPtr<mirror::IfTable> if_table,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006990 ArtMethod* unimplemented_method,
6991 ArtMethod* imt_conflict_method,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006992 ObjPtr<mirror::Class> klass,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07006993 bool create_conflict_tables,
6994 bool ignore_copied_methods,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00006995 /*out*/bool* new_conflict,
6996 /*out*/ArtMethod** imt) {
6997 uint32_t conflict_counts[ImTable::kSize] = {};
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07006998 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07006999 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007000 const size_t num_virtuals = interface->NumVirtualMethods();
7001 const size_t method_array_count = if_table->GetMethodArrayCount(i);
7002 // Virtual methods can be larger than the if table methods if there are default methods.
7003 DCHECK_GE(num_virtuals, method_array_count);
7004 if (kIsDebugBuild) {
7005 if (klass->IsInterface()) {
7006 DCHECK_EQ(method_array_count, 0u);
7007 } else {
7008 DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
7009 }
7010 }
7011 if (method_array_count == 0) {
7012 continue;
7013 }
Vladimir Marko557fece2019-03-26 14:29:41 +00007014 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007015 for (size_t j = 0; j < method_array_count; ++j) {
7016 ArtMethod* implementation_method =
7017 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7018 if (ignore_copied_methods && implementation_method->IsCopied()) {
7019 continue;
7020 }
7021 DCHECK(implementation_method != nullptr);
7022 // Miranda methods cannot be used to implement an interface method, but they are safe to put
7023 // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
7024 // or interface methods in the IMT here they will not create extra conflicts since we compare
7025 // names and signatures in SetIMTRef.
7026 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00007027 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007028
7029 // There is only any conflicts if all of the interface methods for an IMT slot don't have
7030 // the same implementation method, keep track of this to avoid creating a conflict table in
7031 // this case.
7032
7033 // Conflict table size for each IMT slot.
7034 ++conflict_counts[imt_index];
7035
7036 SetIMTRef(unimplemented_method,
7037 imt_conflict_method,
7038 implementation_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007039 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007040 /*out*/&imt[imt_index]);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007041 }
7042 }
7043
7044 if (create_conflict_tables) {
7045 // Create the conflict tables.
7046 LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007047 for (size_t i = 0; i < ImTable::kSize; ++i) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007048 size_t conflicts = conflict_counts[i];
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007049 if (imt[i] == imt_conflict_method) {
7050 ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
7051 if (new_table != nullptr) {
7052 ArtMethod* new_conflict_method =
7053 Runtime::Current()->CreateImtConflictMethod(linear_alloc);
7054 new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
7055 imt[i] = new_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007056 } else {
7057 LOG(ERROR) << "Failed to allocate conflict table";
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007058 imt[i] = imt_conflict_method;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007059 }
7060 } else {
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007061 DCHECK_NE(imt[i], imt_conflict_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007062 }
7063 }
7064
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007065 for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007066 ObjPtr<mirror::Class> interface = if_table->GetInterface(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007067 const size_t method_array_count = if_table->GetMethodArrayCount(i);
7068 // Virtual methods can be larger than the if table methods if there are default methods.
7069 if (method_array_count == 0) {
7070 continue;
7071 }
Vladimir Marko557fece2019-03-26 14:29:41 +00007072 ObjPtr<mirror::PointerArray> method_array = if_table->GetMethodArray(i);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007073 for (size_t j = 0; j < method_array_count; ++j) {
7074 ArtMethod* implementation_method =
7075 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
7076 if (ignore_copied_methods && implementation_method->IsCopied()) {
7077 continue;
7078 }
7079 DCHECK(implementation_method != nullptr);
7080 ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
David Srbeckye36e7f22018-11-14 14:21:23 +00007081 const uint32_t imt_index = interface_method->GetImtIndex();
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007082 if (!imt[imt_index]->IsRuntimeMethod() ||
7083 imt[imt_index] == unimplemented_method ||
7084 imt[imt_index] == imt_conflict_method) {
7085 continue;
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007086 }
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007087 ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
7088 const size_t num_entries = table->NumEntries(image_pointer_size_);
7089 table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
7090 table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007091 }
7092 }
7093 }
7094}
7095
Alex Lighteb7c1442015-08-31 13:17:42 -07007096// Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
7097// set.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007098static bool NotSubinterfaceOfAny(
Vladimir Marko782fb712020-12-23 12:47:31 +00007099 const HashSet<mirror::Class*>& classes,
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007100 ObjPtr<mirror::Class> val)
Alex Lighteb7c1442015-08-31 13:17:42 -07007101 REQUIRES(Roles::uninterruptible_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007102 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007103 DCHECK(val != nullptr);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007104 for (ObjPtr<mirror::Class> c : classes) {
7105 if (val->IsAssignableFrom(c)) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007106 return false;
7107 }
7108 }
7109 return true;
7110}
7111
7112// Fills in and flattens the interface inheritance hierarchy.
7113//
7114// By the end of this function all interfaces in the transitive closure of to_process are added to
7115// the iftable and every interface precedes all of its sub-interfaces in this list.
7116//
7117// all I, J: Interface | I <: J implies J precedes I
7118//
7119// (note A <: B means that A is a subtype of B)
7120//
7121// This returns the total number of items in the iftable. The iftable might be resized down after
7122// this call.
7123//
7124// We order this backwards so that we do not need to reorder superclass interfaces when new
7125// interfaces are added in subclass's interface tables.
7126//
7127// Upon entry into this function iftable is a copy of the superclass's iftable with the first
7128// super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
7129// The other entries are uninitialized. We will fill in the remaining entries in this function. The
7130// iftable must be large enough to hold all interfaces without changing its size.
Vladimir Marko782fb712020-12-23 12:47:31 +00007131static size_t FillIfTable(Thread* self,
7132 ObjPtr<mirror::Class> klass,
7133 ObjPtr<mirror::ObjectArray<mirror::Class>> interfaces,
7134 ObjPtr<mirror::IfTable> iftable,
Alex Lighteb7c1442015-08-31 13:17:42 -07007135 size_t super_ifcount,
Vladimir Marko782fb712020-12-23 12:47:31 +00007136 size_t num_interfaces)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007137 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Marko782fb712020-12-23 12:47:31 +00007138 ScopedAssertNoThreadSuspension nts(__FUNCTION__);
7139 // This is the set of all classes already in the iftable. Used to make checking
7140 // if a class has already been added quicker.
7141 constexpr size_t kBufferSize = 32; // 256 bytes on 64-bit architectures.
7142 mirror::Class* buffer[kBufferSize];
7143 HashSet<mirror::Class*> classes_in_iftable(buffer, kBufferSize);
Alex Lighteb7c1442015-08-31 13:17:42 -07007144 // The first super_ifcount elements are from the superclass. We note that they are already added.
7145 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007146 ObjPtr<mirror::Class> iface = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07007147 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
Vladimir Marko782fb712020-12-23 12:47:31 +00007148 classes_in_iftable.insert(iface.Ptr());
Alex Lighteb7c1442015-08-31 13:17:42 -07007149 }
7150 size_t filled_ifcount = super_ifcount;
Vladimir Marko782fb712020-12-23 12:47:31 +00007151 const bool have_interfaces = interfaces != nullptr;
7152 for (size_t i = 0; i != num_interfaces; ++i) {
7153 ObjPtr<mirror::Class> interface = have_interfaces
7154 ? interfaces->Get(i)
7155 : mirror::Class::GetDirectInterface(self, klass, i);
7156
Alex Lighteb7c1442015-08-31 13:17:42 -07007157 // Let us call the first filled_ifcount elements of iftable the current-iface-list.
7158 // At this point in the loop current-iface-list has the invariant that:
7159 // for every pair of interfaces I,J within it:
7160 // if index_of(I) < index_of(J) then I is not a subtype of J
7161
7162 // If we have already seen this element then all of its super-interfaces must already be in the
7163 // current-iface-list so we can skip adding it.
Vladimir Marko782fb712020-12-23 12:47:31 +00007164 if (classes_in_iftable.find(interface.Ptr()) == classes_in_iftable.end()) {
Alex Lighteb7c1442015-08-31 13:17:42 -07007165 // We haven't seen this interface so add all of its super-interfaces onto the
7166 // current-iface-list, skipping those already on it.
7167 int32_t ifcount = interface->GetIfTableCount();
7168 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007169 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007170 if (!ContainsElement(classes_in_iftable, super_interface)) {
7171 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
Vladimir Marko782fb712020-12-23 12:47:31 +00007172 classes_in_iftable.insert(super_interface.Ptr());
Alex Lighteb7c1442015-08-31 13:17:42 -07007173 iftable->SetInterface(filled_ifcount, super_interface);
7174 filled_ifcount++;
7175 }
7176 }
7177 DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
7178 // Place this interface onto the current-iface-list after all of its super-interfaces.
Vladimir Marko782fb712020-12-23 12:47:31 +00007179 classes_in_iftable.insert(interface.Ptr());
Alex Lighteb7c1442015-08-31 13:17:42 -07007180 iftable->SetInterface(filled_ifcount, interface);
7181 filled_ifcount++;
7182 } else if (kIsDebugBuild) {
7183 // Check all super-interfaces are already in the list.
7184 int32_t ifcount = interface->GetIfTableCount();
7185 for (int32_t j = 0; j < ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007186 ObjPtr<mirror::Class> super_interface = interface->GetIfTable()->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007187 DCHECK(ContainsElement(classes_in_iftable, super_interface))
David Sehr709b0702016-10-13 09:12:37 -07007188 << "Iftable does not contain " << mirror::Class::PrettyClass(super_interface)
7189 << ", a superinterface of " << interface->PrettyClass();
Alex Lighteb7c1442015-08-31 13:17:42 -07007190 }
7191 }
7192 }
7193 if (kIsDebugBuild) {
7194 // Check that the iftable is ordered correctly.
7195 for (size_t i = 0; i < filled_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007196 ObjPtr<mirror::Class> if_a = iftable->GetInterface(i);
Alex Lighteb7c1442015-08-31 13:17:42 -07007197 for (size_t j = i + 1; j < filled_ifcount; j++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007198 ObjPtr<mirror::Class> if_b = iftable->GetInterface(j);
Alex Lighteb7c1442015-08-31 13:17:42 -07007199 // !(if_a <: if_b)
7200 CHECK(!if_b->IsAssignableFrom(if_a))
David Sehr709b0702016-10-13 09:12:37 -07007201 << "Bad interface order: " << mirror::Class::PrettyClass(if_a) << " (index " << i
7202 << ") extends "
7203 << if_b->PrettyClass() << " (index " << j << ") and so should be after it in the "
Alex Lighteb7c1442015-08-31 13:17:42 -07007204 << "interface list.";
7205 }
7206 }
7207 }
7208 return filled_ifcount;
7209}
7210
Vladimir Marko782fb712020-12-23 12:47:31 +00007211bool ClassLinker::SetupInterfaceLookupTable(Thread* self,
7212 Handle<mirror::Class> klass,
Alex Lighteb7c1442015-08-31 13:17:42 -07007213 Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
7214 StackHandleScope<1> hs(self);
Mathieu Chartier6beced42016-11-15 15:51:31 -08007215 const bool has_superclass = klass->HasSuperClass();
7216 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Andreas Gampefa4333d2017-02-14 11:10:34 -08007217 const bool have_interfaces = interfaces != nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07007218 const size_t num_interfaces =
7219 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007220 if (num_interfaces == 0) {
7221 if (super_ifcount == 0) {
Mathieu Chartier6beced42016-11-15 15:51:31 -08007222 if (LIKELY(has_superclass)) {
7223 klass->SetIfTable(klass->GetSuperClass()->GetIfTable());
7224 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007225 // Class implements no interfaces.
7226 DCHECK_EQ(klass->GetIfTableCount(), 0);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007227 return true;
7228 }
Ian Rogers9bc81912012-10-11 21:43:36 -07007229 // Class implements same interfaces as parent, are any of these not marker interfaces?
7230 bool has_non_marker_interface = false;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007231 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007232 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07007233 if (super_iftable->GetMethodArrayCount(i) > 0) {
7234 has_non_marker_interface = true;
7235 break;
7236 }
7237 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007238 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07007239 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07007240 klass->SetIfTable(super_iftable);
7241 return true;
7242 }
7243 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007244 size_t ifcount = super_ifcount + num_interfaces;
Alex Lighteb7c1442015-08-31 13:17:42 -07007245 // Check that every class being implemented is an interface.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007246 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07007247 ObjPtr<mirror::Class> interface = have_interfaces
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007248 ? interfaces->GetWithoutChecks(i)
Vladimir Marko19a4d372016-12-08 14:41:46 +00007249 : mirror::Class::GetDirectInterface(self, klass.Get(), i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007250 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007251 if (UNLIKELY(!interface->IsInterface())) {
7252 std::string temp;
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07007253 ThrowIncompatibleClassChangeError(klass.Get(),
7254 "Class %s implements non-interface class %s",
David Sehr709b0702016-10-13 09:12:37 -07007255 klass->PrettyDescriptor().c_str(),
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007256 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
7257 return false;
7258 }
7259 ifcount += interface->GetIfTableCount();
7260 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007261 // Create the interface function table.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07007262 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007263 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007264 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007265 return false;
7266 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007267 // Fill in table with superclass's iftable.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007268 if (super_ifcount != 0) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007269 ObjPtr<mirror::IfTable> super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007270 for (size_t i = 0; i < super_ifcount; i++) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007271 ObjPtr<mirror::Class> super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07007272 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07007273 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007274 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007275
7276 // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
7277 // cancellation. That is it will suspend if one has a pending suspend request but otherwise
7278 // doesn't really do anything.
Ian Rogers7b078e82014-09-10 14:44:24 -07007279 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007280
Vladimir Marko782fb712020-12-23 12:47:31 +00007281 const size_t new_ifcount = FillIfTable(
7282 self, klass.Get(), interfaces.Get(), iftable.Get(), super_ifcount, num_interfaces);
Alex Lighteb7c1442015-08-31 13:17:42 -07007283
Ian Rogers7b078e82014-09-10 14:44:24 -07007284 self->AllowThreadSuspension();
Alex Lighteb7c1442015-08-31 13:17:42 -07007285
Ian Rogersb52b01a2012-01-12 17:01:38 -08007286 // Shrink iftable in case duplicates were found
Alex Lighteb7c1442015-08-31 13:17:42 -07007287 if (new_ifcount < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07007288 DCHECK_NE(num_interfaces, 0U);
Vladimir Markobcf17522018-06-01 13:14:32 +01007289 iftable.Assign(ObjPtr<mirror::IfTable>::DownCast(
Vladimir Marko3068d582019-05-28 16:39:29 +01007290 mirror::IfTable::CopyOf(iftable, self, new_ifcount * mirror::IfTable::kMax)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007291 if (UNLIKELY(iftable == nullptr)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07007292 self->AssertPendingOOMException();
Ian Rogersa436fde2013-08-27 23:34:06 -07007293 return false;
7294 }
Alex Lighteb7c1442015-08-31 13:17:42 -07007295 ifcount = new_ifcount;
Ian Rogersb52b01a2012-01-12 17:01:38 -08007296 } else {
Alex Lighteb7c1442015-08-31 13:17:42 -07007297 DCHECK_EQ(new_ifcount, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08007298 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07007299 klass->SetIfTable(iftable.Get());
Alex Lighteb7c1442015-08-31 13:17:42 -07007300 return true;
7301}
7302
Alex Light1f3925d2016-09-07 12:04:20 -07007303// Finds the method with a name/signature that matches cmp in the given lists of methods. The list
7304// of methods must be unique.
7305static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp ATTRIBUTE_UNUSED) {
7306 return nullptr;
7307}
7308
7309template <typename ... Types>
Alex Light9139e002015-10-09 15:59:48 -07007310static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
Alex Light1f3925d2016-09-07 12:04:20 -07007311 const ScopedArenaVector<ArtMethod*>& list,
7312 const Types& ... rest)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007313 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light9139e002015-10-09 15:59:48 -07007314 for (ArtMethod* method : list) {
7315 if (cmp.HasSameNameAndSignature(method)) {
7316 return method;
7317 }
7318 }
Alex Light1f3925d2016-09-07 12:04:20 -07007319 return FindSameNameAndSignature(cmp, rest...);
Alex Light9139e002015-10-09 15:59:48 -07007320}
7321
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007322namespace {
7323
Alex Light1f3925d2016-09-07 12:04:20 -07007324// Check that all vtable entries are present in this class's virtuals or are the same as a
7325// superclasses vtable entry.
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007326void CheckClassOwnsVTableEntries(Thread* self,
7327 Handle<mirror::Class> klass,
7328 PointerSize pointer_size)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07007329 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light1f3925d2016-09-07 12:04:20 -07007330 StackHandleScope<2> hs(self);
7331 Handle<mirror::PointerArray> check_vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007332 ObjPtr<mirror::Class> super_temp = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
Alex Light1f3925d2016-09-07 12:04:20 -07007333 Handle<mirror::Class> superclass(hs.NewHandle(super_temp));
Andreas Gampefa4333d2017-02-14 11:10:34 -08007334 int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
Alex Lighte64300b2015-12-15 15:02:47 -08007335 for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
7336 ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7337 CHECK(m != nullptr);
7338
Alex Lighta41a30782017-03-29 11:33:19 -07007339 if (m->GetMethodIndexDuringLinking() != i) {
7340 LOG(WARNING) << m->PrettyMethod()
7341 << " has an unexpected method index for its spot in the vtable for class"
7342 << klass->PrettyClass();
7343 }
Alex Lighte64300b2015-12-15 15:02:47 -08007344 ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
7345 auto is_same_method = [m] (const ArtMethod& meth) {
7346 return &meth == m;
7347 };
Alex Light3f980532017-03-17 15:10:32 -07007348 if (!((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
7349 std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())) {
7350 LOG(WARNING) << m->PrettyMethod() << " does not seem to be owned by current class "
7351 << klass->PrettyClass() << " or any of its superclasses!";
7352 }
Alex Lighte64300b2015-12-15 15:02:47 -08007353 }
7354}
7355
Alex Light1f3925d2016-09-07 12:04:20 -07007356// Check to make sure the vtable does not have duplicates. Duplicates could cause problems when a
7357// method is overridden in a subclass.
Andreas Gampea2fed082019-02-01 09:34:43 -08007358template <PointerSize kPointerSize>
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007359void CheckVTableHasNoDuplicates(Thread* self, Handle<mirror::Class> klass)
Alex Light1f3925d2016-09-07 12:04:20 -07007360 REQUIRES_SHARED(Locks::mutator_lock_) {
7361 StackHandleScope<1> hs(self);
7362 Handle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
7363 int32_t num_entries = vtable->GetLength();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007364
7365 // Observations:
7366 // * The older implementation was O(n^2) and got too expensive for apps with larger classes.
7367 // * Many classes do not override Object functions (e.g., equals/hashCode/toString). Thus,
7368 // for many classes outside of libcore a cross-dexfile check has to be run anyways.
7369 // * In the cross-dexfile case, with the O(n^2), in the best case O(n) cross checks would have
7370 // to be done. It is thus OK in a single-pass algorithm to read all data, anyways.
7371 // * The single-pass algorithm will trade memory for speed, but that is OK.
7372
7373 CHECK_GT(num_entries, 0);
7374
7375 auto log_fn = [&vtable, &klass](int32_t i, int32_t j) REQUIRES_SHARED(Locks::mutator_lock_) {
7376 ArtMethod* m1 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(i);
7377 ArtMethod* m2 = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(j);
7378 LOG(WARNING) << "vtable entries " << i << " and " << j << " are identical for "
7379 << klass->PrettyClass() << " in method " << m1->PrettyMethod()
7380 << " (0x" << std::hex << reinterpret_cast<uintptr_t>(m2) << ") and "
7381 << m2->PrettyMethod() << " (0x" << std::hex
7382 << reinterpret_cast<uintptr_t>(m2) << ")";
7383 };
7384 struct BaseHashType {
7385 static size_t HashCombine(size_t seed, size_t val) {
7386 return seed ^ (val + 0x9e3779b9 + (seed << 6) + (seed >> 2));
7387 }
7388 };
7389
7390 // Check assuming all entries come from the same dex file.
7391 {
7392 // Find the first interesting method and its dex file.
7393 int32_t start = 0;
7394 for (; start < num_entries; ++start) {
7395 ArtMethod* vtable_entry = vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start);
7396 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7397 // maybe).
7398 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7399 vtable_entry->GetAccessFlags())) {
7400 continue;
7401 }
7402 break;
7403 }
7404 if (start == num_entries) {
7405 return;
7406 }
7407 const DexFile* dex_file =
7408 vtable->GetElementPtrSize<ArtMethod*, kPointerSize>(start)->
7409 GetInterfaceMethodIfProxy(kPointerSize)->GetDexFile();
7410
7411 // Helper function to avoid logging if we have to run the cross-file checks.
7412 auto check_fn = [&](bool log_warn) REQUIRES_SHARED(Locks::mutator_lock_) {
7413 // Use a map to store seen entries, as the storage space is too large for a bitvector.
7414 using PairType = std::pair<uint32_t, uint16_t>;
7415 struct PairHash : BaseHashType {
7416 size_t operator()(const PairType& key) const {
7417 return BaseHashType::HashCombine(BaseHashType::HashCombine(0, key.first), key.second);
7418 }
7419 };
Vladimir Marko782fb712020-12-23 12:47:31 +00007420 HashMap<PairType, int32_t, DefaultMapEmptyFn<PairType, int32_t>, PairHash> seen;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007421 seen.reserve(2 * num_entries);
7422 bool need_slow_path = false;
7423 bool found_dup = false;
7424 for (int i = start; i < num_entries; ++i) {
7425 // Can use Unchecked here as the start loop already ensured that the arrays are correct
7426 // wrt/ kPointerSize.
7427 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7428 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7429 vtable_entry->GetAccessFlags())) {
7430 continue;
7431 }
7432 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7433 if (dex_file != m->GetDexFile()) {
7434 need_slow_path = true;
7435 break;
7436 }
7437 const dex::MethodId* m_mid = &dex_file->GetMethodId(m->GetDexMethodIndex());
7438 PairType pair = std::make_pair(m_mid->name_idx_.index_, m_mid->proto_idx_.index_);
7439 auto it = seen.find(pair);
7440 if (it != seen.end()) {
7441 found_dup = true;
7442 if (log_warn) {
7443 log_fn(it->second, i);
7444 }
7445 } else {
Vladimir Marko782fb712020-12-23 12:47:31 +00007446 seen.insert(std::make_pair(pair, i));
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007447 }
7448 }
7449 return std::make_pair(need_slow_path, found_dup);
7450 };
7451 std::pair<bool, bool> result = check_fn(/* log_warn= */ false);
7452 if (!result.first) {
7453 if (result.second) {
7454 check_fn(/* log_warn= */ true);
7455 }
7456 return;
7457 }
7458 }
7459
7460 // Need to check across dex files.
7461 struct Entry {
7462 size_t cached_hash = 0;
Vladimir Markoaa027b82021-01-06 20:34:20 +00007463 uint32_t name_len = 0;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007464 const char* name = nullptr;
7465 Signature signature = Signature::NoSignature();
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007466
Vladimir Marko782fb712020-12-23 12:47:31 +00007467 Entry() = default;
7468 Entry(const Entry& other) = default;
7469 Entry& operator=(const Entry& other) = default;
7470
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007471 Entry(const DexFile* dex_file, const dex::MethodId& mid)
Vladimir Markoaa027b82021-01-06 20:34:20 +00007472 : name_len(0), // Explicit to enforce ordering with -Werror,-Wreorder-ctor.
7473 // This call writes `name_len` and it is therefore necessary that the
7474 // initializer for `name_len` comes before it, otherwise the value
7475 // from the call would be overwritten by that initializer.
7476 name(dex_file->StringDataAndUtf16LengthByIdx(mid.name_idx_, &name_len)),
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007477 signature(dex_file->GetMethodSignature(mid)) {
Vladimir Markoaa027b82021-01-06 20:34:20 +00007478 // The `name_len` has been initialized to the UTF16 length. Calculate length in bytes.
7479 if (name[name_len] != 0) {
7480 name_len += strlen(name + name_len);
7481 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007482 }
7483
7484 bool operator==(const Entry& other) const {
Vladimir Marko782fb712020-12-23 12:47:31 +00007485 return name_len == other.name_len &&
7486 memcmp(name, other.name, name_len) == 0 &&
7487 signature == other.signature;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007488 }
7489 };
7490 struct EntryHash {
7491 size_t operator()(const Entry& key) const {
7492 return key.cached_hash;
7493 }
7494 };
Vladimir Marko782fb712020-12-23 12:47:31 +00007495 HashMap<Entry, int32_t, DefaultMapEmptyFn<Entry, int32_t>, EntryHash> map;
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007496 for (int32_t i = 0; i < num_entries; ++i) {
7497 // Can use Unchecked here as the first loop already ensured that the arrays are correct
7498 // wrt/ kPointerSize.
7499 ArtMethod* vtable_entry = vtable->GetElementPtrSizeUnchecked<ArtMethod*, kPointerSize>(i);
7500 // Don't bother if we cannot 'see' the vtable entry (i.e. it is a package-private member
7501 // maybe).
Alex Light1f3925d2016-09-07 12:04:20 -07007502 if (!klass->CanAccessMember(vtable_entry->GetDeclaringClass(),
7503 vtable_entry->GetAccessFlags())) {
7504 continue;
7505 }
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007506 ArtMethod* m = vtable_entry->GetInterfaceMethodIfProxy(kPointerSize);
7507 const DexFile* dex_file = m->GetDexFile();
7508 const dex::MethodId& mid = dex_file->GetMethodId(m->GetDexMethodIndex());
7509
7510 Entry e(dex_file, mid);
7511
7512 size_t string_hash = std::hash<std::string_view>()(std::string_view(e.name, e.name_len));
7513 size_t sig_hash = std::hash<std::string>()(e.signature.ToString());
7514 e.cached_hash = BaseHashType::HashCombine(BaseHashType::HashCombine(0u, string_hash),
7515 sig_hash);
7516
7517 auto it = map.find(e);
7518 if (it != map.end()) {
7519 log_fn(it->second, i);
7520 } else {
Vladimir Marko782fb712020-12-23 12:47:31 +00007521 map.insert(std::make_pair(e, i));
Alex Light1f3925d2016-09-07 12:04:20 -07007522 }
7523 }
7524}
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007525
7526void CheckVTableHasNoDuplicates(Thread* self,
7527 Handle<mirror::Class> klass,
7528 PointerSize pointer_size)
Andreas Gampea2fed082019-02-01 09:34:43 -08007529 REQUIRES_SHARED(Locks::mutator_lock_) {
7530 switch (pointer_size) {
7531 case PointerSize::k64:
7532 CheckVTableHasNoDuplicates<PointerSize::k64>(self, klass);
7533 break;
7534 case PointerSize::k32:
7535 CheckVTableHasNoDuplicates<PointerSize::k32>(self, klass);
7536 break;
7537 }
7538}
Alex Light1f3925d2016-09-07 12:04:20 -07007539
Orion Hodson5880c772020-07-28 20:12:08 +01007540static void CheckVTable(Thread* self, Handle<mirror::Class> klass, PointerSize pointer_size)
Alex Light1f3925d2016-09-07 12:04:20 -07007541 REQUIRES_SHARED(Locks::mutator_lock_) {
7542 CheckClassOwnsVTableEntries(self, klass, pointer_size);
7543 CheckVTableHasNoDuplicates(self, klass, pointer_size);
7544}
7545
Andreas Gampe9f3928f2019-02-04 11:19:31 -08007546} // namespace
7547
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007548void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
7549 ArtMethod* unimplemented_method,
7550 ArtMethod* imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007551 bool* new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007552 ArtMethod** imt) {
Alex Light705ad492015-09-21 11:36:30 -07007553 DCHECK(klass->HasSuperClass());
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007554 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007555 if (super_class->ShouldHaveImt()) {
7556 ImTable* super_imt = super_class->GetImt(image_pointer_size_);
7557 for (size_t i = 0; i < ImTable::kSize; ++i) {
7558 imt[i] = super_imt->Get(i, image_pointer_size_);
Alex Light705ad492015-09-21 11:36:30 -07007559 }
7560 } else {
7561 // No imt in the super class, need to reconstruct from the iftable.
Mathieu Chartier28357fa2016-10-18 16:27:40 -07007562 ObjPtr<mirror::IfTable> if_table = super_class->GetIfTable();
Mathieu Chartier6beced42016-11-15 15:51:31 -08007563 if (if_table->Count() != 0) {
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07007564 // Ignore copied methods since we will handle these in LinkInterfaceMethods.
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007565 FillIMTFromIfTable(if_table,
7566 unimplemented_method,
7567 imt_conflict_method,
7568 klass.Get(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -07007569 /*create_conflict_tables=*/false,
7570 /*ignore_copied_methods=*/true,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00007571 /*out*/new_conflict,
Mathieu Chartiercdca4762016-04-28 09:44:54 -07007572 /*out*/imt);
Alex Light705ad492015-09-21 11:36:30 -07007573 }
7574 }
7575}
7576
Vladimir Marko921094a2017-01-12 18:37:06 +00007577class ClassLinker::LinkInterfaceMethodsHelper {
7578 public:
7579 LinkInterfaceMethodsHelper(ClassLinker* class_linker,
7580 Handle<mirror::Class> klass,
7581 Thread* self,
7582 Runtime* runtime)
7583 : class_linker_(class_linker),
7584 klass_(klass),
7585 method_alignment_(ArtMethod::Alignment(class_linker->GetImagePointerSize())),
7586 method_size_(ArtMethod::Size(class_linker->GetImagePointerSize())),
7587 self_(self),
7588 stack_(runtime->GetLinearAlloc()->GetArenaPool()),
7589 allocator_(&stack_),
7590 default_conflict_methods_(allocator_.Adapter()),
7591 overriding_default_conflict_methods_(allocator_.Adapter()),
7592 miranda_methods_(allocator_.Adapter()),
7593 default_methods_(allocator_.Adapter()),
7594 overriding_default_methods_(allocator_.Adapter()),
7595 move_table_(allocator_.Adapter()) {
7596 }
7597
7598 ArtMethod* FindMethod(ArtMethod* interface_method,
7599 MethodNameAndSignatureComparator& interface_name_comparator,
7600 ArtMethod* vtable_impl)
7601 REQUIRES_SHARED(Locks::mutator_lock_);
7602
7603 ArtMethod* GetOrCreateMirandaMethod(ArtMethod* interface_method,
7604 MethodNameAndSignatureComparator& interface_name_comparator)
7605 REQUIRES_SHARED(Locks::mutator_lock_);
7606
7607 bool HasNewVirtuals() const {
7608 return !(miranda_methods_.empty() &&
7609 default_methods_.empty() &&
7610 overriding_default_methods_.empty() &&
7611 overriding_default_conflict_methods_.empty() &&
7612 default_conflict_methods_.empty());
7613 }
7614
7615 void ReallocMethods() REQUIRES_SHARED(Locks::mutator_lock_);
7616
7617 ObjPtr<mirror::PointerArray> UpdateVtable(
Vladimir Marko782fb712020-12-23 12:47:31 +00007618 const HashMap<size_t, ClassLinker::MethodTranslation>& default_translations,
Vladimir Marko3068d582019-05-28 16:39:29 +01007619 Handle<mirror::PointerArray> old_vtable) REQUIRES_SHARED(Locks::mutator_lock_);
Vladimir Marko921094a2017-01-12 18:37:06 +00007620
7621 void UpdateIfTable(Handle<mirror::IfTable> iftable) REQUIRES_SHARED(Locks::mutator_lock_);
7622
7623 void UpdateIMT(ArtMethod** out_imt);
7624
7625 void CheckNoStaleMethodsInDexCache() REQUIRES_SHARED(Locks::mutator_lock_) {
7626 if (kIsDebugBuild) {
7627 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7628 // Check that there are no stale methods are in the dex cache array.
7629 auto* resolved_methods = klass_->GetDexCache()->GetResolvedMethods();
7630 for (size_t i = 0, count = klass_->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01007631 auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_methods, i, pointer_size);
7632 ArtMethod* m = pair.object;
Vladimir Marko921094a2017-01-12 18:37:06 +00007633 CHECK(move_table_.find(m) == move_table_.end() ||
7634 // The original versions of copied methods will still be present so allow those too.
7635 // Note that if the first check passes this might fail to GetDeclaringClass().
7636 std::find_if(m->GetDeclaringClass()->GetMethods(pointer_size).begin(),
7637 m->GetDeclaringClass()->GetMethods(pointer_size).end(),
7638 [m] (ArtMethod& meth) {
7639 return &meth == m;
7640 }) != m->GetDeclaringClass()->GetMethods(pointer_size).end())
7641 << "Obsolete method " << m->PrettyMethod() << " is in dex cache!";
7642 }
7643 }
7644 }
7645
7646 void ClobberOldMethods(LengthPrefixedArray<ArtMethod>* old_methods,
7647 LengthPrefixedArray<ArtMethod>* methods) {
7648 if (kIsDebugBuild) {
7649 CHECK(methods != nullptr);
7650 // Put some random garbage in old methods to help find stale pointers.
7651 if (methods != old_methods && old_methods != nullptr) {
7652 // Need to make sure the GC is not running since it could be scanning the methods we are
7653 // about to overwrite.
7654 ScopedThreadStateChange tsc(self_, kSuspended);
7655 gc::ScopedGCCriticalSection gcs(self_,
7656 gc::kGcCauseClassLinker,
7657 gc::kCollectorTypeClassLinker);
7658 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_methods->size(),
7659 method_size_,
7660 method_alignment_);
7661 memset(old_methods, 0xFEu, old_size);
7662 }
7663 }
7664 }
7665
7666 private:
7667 size_t NumberOfNewVirtuals() const {
7668 return miranda_methods_.size() +
7669 default_methods_.size() +
7670 overriding_default_conflict_methods_.size() +
7671 overriding_default_methods_.size() +
7672 default_conflict_methods_.size();
7673 }
7674
7675 bool FillTables() REQUIRES_SHARED(Locks::mutator_lock_) {
7676 return !klass_->IsInterface();
7677 }
7678
7679 void LogNewVirtuals() const REQUIRES_SHARED(Locks::mutator_lock_) {
7680 DCHECK(!klass_->IsInterface() || (default_methods_.empty() && miranda_methods_.empty()))
7681 << "Interfaces should only have default-conflict methods appended to them.";
7682 VLOG(class_linker) << mirror::Class::PrettyClass(klass_.Get()) << ": miranda_methods="
7683 << miranda_methods_.size()
7684 << " default_methods=" << default_methods_.size()
7685 << " overriding_default_methods=" << overriding_default_methods_.size()
7686 << " default_conflict_methods=" << default_conflict_methods_.size()
7687 << " overriding_default_conflict_methods="
7688 << overriding_default_conflict_methods_.size();
7689 }
7690
7691 ClassLinker* class_linker_;
7692 Handle<mirror::Class> klass_;
7693 size_t method_alignment_;
7694 size_t method_size_;
7695 Thread* const self_;
7696
7697 // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
7698 // the virtual methods array.
7699 // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
7700 // during cross compilation.
7701 // Use the linear alloc pool since this one is in the low 4gb for the compiler.
7702 ArenaStack stack_;
7703 ScopedArenaAllocator allocator_;
7704
7705 ScopedArenaVector<ArtMethod*> default_conflict_methods_;
7706 ScopedArenaVector<ArtMethod*> overriding_default_conflict_methods_;
7707 ScopedArenaVector<ArtMethod*> miranda_methods_;
7708 ScopedArenaVector<ArtMethod*> default_methods_;
7709 ScopedArenaVector<ArtMethod*> overriding_default_methods_;
7710
7711 ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table_;
7712};
7713
7714ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::FindMethod(
7715 ArtMethod* interface_method,
7716 MethodNameAndSignatureComparator& interface_name_comparator,
7717 ArtMethod* vtable_impl) {
7718 ArtMethod* current_method = nullptr;
7719 switch (class_linker_->FindDefaultMethodImplementation(self_,
7720 interface_method,
7721 klass_,
7722 /*out*/&current_method)) {
7723 case DefaultMethodSearchResult::kDefaultConflict: {
7724 // Default method conflict.
7725 DCHECK(current_method == nullptr);
7726 ArtMethod* default_conflict_method = nullptr;
7727 if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
7728 // We can reuse the method from the superclass, don't bother adding it to virtuals.
7729 default_conflict_method = vtable_impl;
7730 } else {
7731 // See if we already have a conflict method for this method.
7732 ArtMethod* preexisting_conflict = FindSameNameAndSignature(
7733 interface_name_comparator,
7734 default_conflict_methods_,
7735 overriding_default_conflict_methods_);
7736 if (LIKELY(preexisting_conflict != nullptr)) {
7737 // We already have another conflict we can reuse.
7738 default_conflict_method = preexisting_conflict;
7739 } else {
7740 // Note that we do this even if we are an interface since we need to create this and
7741 // cannot reuse another classes.
7742 // Create a new conflict method for this to use.
7743 default_conflict_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7744 new(default_conflict_method) ArtMethod(interface_method,
7745 class_linker_->GetImagePointerSize());
7746 if (vtable_impl == nullptr) {
7747 // Save the conflict method. We need to add it to the vtable.
7748 default_conflict_methods_.push_back(default_conflict_method);
7749 } else {
7750 // Save the conflict method but it is already in the vtable.
7751 overriding_default_conflict_methods_.push_back(default_conflict_method);
7752 }
7753 }
7754 }
7755 current_method = default_conflict_method;
7756 break;
7757 } // case kDefaultConflict
7758 case DefaultMethodSearchResult::kDefaultFound: {
7759 DCHECK(current_method != nullptr);
7760 // Found a default method.
7761 if (vtable_impl != nullptr &&
7762 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
7763 // We found a default method but it was the same one we already have from our
7764 // superclass. Don't bother adding it to our vtable again.
7765 current_method = vtable_impl;
7766 } else if (LIKELY(FillTables())) {
7767 // Interfaces don't need to copy default methods since they don't have vtables.
7768 // Only record this default method if it is new to save space.
7769 // TODO It might be worthwhile to copy default methods on interfaces anyway since it
7770 // would make lookup for interface super much faster. (We would only need to scan
7771 // the iftable to find if there is a NSME or AME.)
7772 ArtMethod* old = FindSameNameAndSignature(interface_name_comparator,
7773 default_methods_,
7774 overriding_default_methods_);
7775 if (old == nullptr) {
7776 // We found a default method implementation and there were no conflicts.
7777 if (vtable_impl == nullptr) {
7778 // Save the default method. We need to add it to the vtable.
7779 default_methods_.push_back(current_method);
7780 } else {
7781 // Save the default method but it is already in the vtable.
7782 overriding_default_methods_.push_back(current_method);
7783 }
7784 } else {
7785 CHECK(old == current_method) << "Multiple default implementations selected!";
7786 }
7787 }
7788 break;
7789 } // case kDefaultFound
7790 case DefaultMethodSearchResult::kAbstractFound: {
7791 DCHECK(current_method == nullptr);
7792 // Abstract method masks all defaults.
7793 if (vtable_impl != nullptr &&
7794 vtable_impl->IsAbstract() &&
7795 !vtable_impl->IsDefaultConflicting()) {
7796 // We need to make this an abstract method but the version in the vtable already is so
7797 // don't do anything.
7798 current_method = vtable_impl;
7799 }
7800 break;
7801 } // case kAbstractFound
7802 }
7803 return current_method;
7804}
7805
7806ArtMethod* ClassLinker::LinkInterfaceMethodsHelper::GetOrCreateMirandaMethod(
7807 ArtMethod* interface_method,
7808 MethodNameAndSignatureComparator& interface_name_comparator) {
7809 // Find out if there is already a miranda method we can use.
7810 ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
7811 miranda_methods_);
7812 if (miranda_method == nullptr) {
7813 DCHECK(interface_method->IsAbstract()) << interface_method->PrettyMethod();
7814 miranda_method = reinterpret_cast<ArtMethod*>(allocator_.Alloc(method_size_));
7815 CHECK(miranda_method != nullptr);
7816 // Point the interface table at a phantom slot.
7817 new(miranda_method) ArtMethod(interface_method, class_linker_->GetImagePointerSize());
7818 miranda_methods_.push_back(miranda_method);
7819 }
7820 return miranda_method;
7821}
7822
7823void ClassLinker::LinkInterfaceMethodsHelper::ReallocMethods() {
7824 LogNewVirtuals();
7825
7826 const size_t old_method_count = klass_->NumMethods();
7827 const size_t new_method_count = old_method_count + NumberOfNewVirtuals();
7828 DCHECK_NE(old_method_count, new_method_count);
7829
7830 // Attempt to realloc to save RAM if possible.
7831 LengthPrefixedArray<ArtMethod>* old_methods = klass_->GetMethodsPtr();
7832 // The Realloced virtual methods aren't visible from the class roots, so there is no issue
7833 // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
7834 // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
7835 // CopyFrom has internal read barriers.
7836 //
7837 // TODO We should maybe move some of this into mirror::Class or at least into another method.
7838 const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
7839 method_size_,
7840 method_alignment_);
7841 const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
7842 method_size_,
7843 method_alignment_);
7844 const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
7845 auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
Nicolas Geoffray48b40cc2017-08-07 16:52:40 +01007846 class_linker_->GetAllocatorForClassLoader(klass_->GetClassLoader())->Realloc(
Vladimir Marko921094a2017-01-12 18:37:06 +00007847 self_, old_methods, old_methods_ptr_size, new_size));
7848 CHECK(methods != nullptr); // Native allocation failure aborts.
7849
7850 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7851 if (methods != old_methods) {
7852 // Maps from heap allocated miranda method to linear alloc miranda method.
7853 StrideIterator<ArtMethod> out = methods->begin(method_size_, method_alignment_);
7854 // Copy over the old methods.
7855 for (auto& m : klass_->GetMethods(pointer_size)) {
7856 move_table_.emplace(&m, &*out);
7857 // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
7858 // barriers when it copies.
7859 out->CopyFrom(&m, pointer_size);
7860 ++out;
7861 }
7862 }
7863 StrideIterator<ArtMethod> out(methods->begin(method_size_, method_alignment_) + old_method_count);
7864 // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
7865 // we want the roots of the miranda methods to get visited.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007866 for (size_t i = 0; i < miranda_methods_.size(); ++i) {
7867 ArtMethod* mir_method = miranda_methods_[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007868 ArtMethod& new_method = *out;
7869 new_method.CopyFrom(mir_method, pointer_size);
7870 new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda | kAccCopied);
7871 DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
7872 << "Miranda method should be abstract!";
7873 move_table_.emplace(mir_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007874 // Update the entry in the method array, as the array will be used for future lookups,
7875 // where thread suspension is allowed.
7876 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7877 // would not see them.
7878 miranda_methods_[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007879 ++out;
7880 }
7881 // We need to copy the default methods into our own method table since the runtime requires that
7882 // every method on a class's vtable be in that respective class's virtual method table.
7883 // NOTE This means that two classes might have the same implementation of a method from the same
7884 // interface but will have different ArtMethod*s for them. This also means we cannot compare a
7885 // default method found on a class with one found on the declaring interface directly and must
7886 // look at the declaring class to determine if they are the same.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007887 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_methods_,
7888 &overriding_default_methods_}) {
7889 for (size_t i = 0; i < methods_vec->size(); ++i) {
7890 ArtMethod* def_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007891 ArtMethod& new_method = *out;
7892 new_method.CopyFrom(def_method, pointer_size);
7893 // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been
7894 // verified yet it shouldn't have methods that are skipping access checks.
7895 // TODO This is rather arbitrary. We should maybe support classes where only some of its
7896 // methods are skip_access_checks.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007897 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007898 constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
7899 constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
7900 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7901 move_table_.emplace(def_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007902 // Update the entry in the method array, as the array will be used for future lookups,
7903 // where thread suspension is allowed.
7904 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7905 // would not see them.
7906 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007907 ++out;
7908 }
7909 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007910 for (ScopedArenaVector<ArtMethod*>* methods_vec : {&default_conflict_methods_,
7911 &overriding_default_conflict_methods_}) {
7912 for (size_t i = 0; i < methods_vec->size(); ++i) {
7913 ArtMethod* conf_method = (*methods_vec)[i];
Vladimir Marko921094a2017-01-12 18:37:06 +00007914 ArtMethod& new_method = *out;
7915 new_method.CopyFrom(conf_method, pointer_size);
7916 // This is a type of default method (there are default method impls, just a conflict) so
7917 // mark this as a default, non-abstract method, since thats what it is. Also clear the
7918 // kAccSkipAccessChecks bit since this class hasn't been verified yet it shouldn't have
7919 // methods that are skipping access checks.
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007920 // Also clear potential kAccSingleImplementation to avoid CHA trying to inline
7921 // the default method.
Vladimir Markob0a6aee2017-10-27 10:34:04 +01007922 DCHECK_EQ(new_method.GetAccessFlags() & kAccNative, 0u);
Vladimir Marko921094a2017-01-12 18:37:06 +00007923 constexpr uint32_t kSetFlags = kAccDefault | kAccDefaultConflict | kAccCopied;
Nicolas Geoffray7aca9d52018-09-07 11:13:33 +01007924 constexpr uint32_t kMaskFlags =
7925 ~(kAccAbstract | kAccSkipAccessChecks | kAccSingleImplementation);
Vladimir Marko921094a2017-01-12 18:37:06 +00007926 new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
7927 DCHECK(new_method.IsDefaultConflicting());
7928 // The actual method might or might not be marked abstract since we just copied it from a
7929 // (possibly default) interface method. We need to set it entry point to be the bridge so
7930 // that the compiler will not invoke the implementation of whatever method we copied from.
7931 EnsureThrowsInvocationError(class_linker_, &new_method);
7932 move_table_.emplace(conf_method, &new_method);
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007933 // Update the entry in the method array, as the array will be used for future lookups,
7934 // where thread suspension is allowed.
7935 // As such, the array should not contain locally allocated ArtMethod, otherwise the GC
7936 // would not see them.
7937 (*methods_vec)[i] = &new_method;
Vladimir Marko921094a2017-01-12 18:37:06 +00007938 ++out;
7939 }
7940 }
7941 methods->SetSize(new_method_count);
7942 class_linker_->UpdateClassMethods(klass_.Get(), methods);
7943}
7944
7945ObjPtr<mirror::PointerArray> ClassLinker::LinkInterfaceMethodsHelper::UpdateVtable(
Vladimir Marko782fb712020-12-23 12:47:31 +00007946 const HashMap<size_t, ClassLinker::MethodTranslation>& default_translations,
Vladimir Marko3068d582019-05-28 16:39:29 +01007947 Handle<mirror::PointerArray> old_vtable) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007948 // Update the vtable to the new method structures. We can skip this for interfaces since they
7949 // do not have vtables.
7950 const size_t old_vtable_count = old_vtable->GetLength();
7951 const size_t new_vtable_count = old_vtable_count +
7952 miranda_methods_.size() +
7953 default_methods_.size() +
7954 default_conflict_methods_.size();
7955
Vladimir Marko3068d582019-05-28 16:39:29 +01007956 ObjPtr<mirror::PointerArray> vtable = ObjPtr<mirror::PointerArray>::DownCast(
7957 mirror::Array::CopyOf(old_vtable, self_, new_vtable_count));
Vladimir Marko921094a2017-01-12 18:37:06 +00007958 if (UNLIKELY(vtable == nullptr)) {
7959 self_->AssertPendingOOMException();
7960 return nullptr;
7961 }
7962
7963 size_t vtable_pos = old_vtable_count;
7964 PointerSize pointer_size = class_linker_->GetImagePointerSize();
7965 // Update all the newly copied method's indexes so they denote their placement in the vtable.
7966 for (const ScopedArenaVector<ArtMethod*>& methods_vec : {default_methods_,
7967 default_conflict_methods_,
7968 miranda_methods_}) {
7969 // These are the functions that are not already in the vtable!
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00007970 for (ArtMethod* new_vtable_method : methods_vec) {
Vladimir Marko921094a2017-01-12 18:37:06 +00007971 // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
7972 // fields are references into the dex file the method was defined in. Since the ArtMethod
7973 // does not store that information it uses declaring_class_->dex_cache_.
7974 new_vtable_method->SetMethodIndex(0xFFFF & vtable_pos);
7975 vtable->SetElementPtrSize(vtable_pos, new_vtable_method, pointer_size);
7976 ++vtable_pos;
7977 }
7978 }
7979 DCHECK_EQ(vtable_pos, new_vtable_count);
7980
7981 // Update old vtable methods. We use the default_translations map to figure out what each
7982 // vtable entry should be updated to, if they need to be at all.
7983 for (size_t i = 0; i < old_vtable_count; ++i) {
7984 ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
7985 // Try and find what we need to change this method to.
7986 auto translation_it = default_translations.find(i);
Vladimir Marko921094a2017-01-12 18:37:06 +00007987 if (translation_it != default_translations.end()) {
7988 if (translation_it->second.IsInConflict()) {
7989 // Find which conflict method we are to use for this method.
7990 MethodNameAndSignatureComparator old_method_comparator(
7991 translated_method->GetInterfaceMethodIfProxy(pointer_size));
7992 // We only need to look through overriding_default_conflict_methods since this is an
7993 // overridden method we are fixing up here.
7994 ArtMethod* new_conflict_method = FindSameNameAndSignature(
7995 old_method_comparator, overriding_default_conflict_methods_);
7996 CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
7997 translated_method = new_conflict_method;
7998 } else if (translation_it->second.IsAbstract()) {
7999 // Find which miranda method we are to use for this method.
8000 MethodNameAndSignatureComparator old_method_comparator(
8001 translated_method->GetInterfaceMethodIfProxy(pointer_size));
8002 ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
8003 miranda_methods_);
8004 DCHECK(miranda_method != nullptr);
8005 translated_method = miranda_method;
8006 } else {
8007 // Normal default method (changed from an older default or abstract interface method).
8008 DCHECK(translation_it->second.IsTranslation());
8009 translated_method = translation_it->second.GetTranslation();
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008010 auto it = move_table_.find(translated_method);
8011 DCHECK(it != move_table_.end());
8012 translated_method = it->second;
Vladimir Marko921094a2017-01-12 18:37:06 +00008013 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008014 } else {
8015 auto it = move_table_.find(translated_method);
8016 translated_method = (it != move_table_.end()) ? it->second : nullptr;
Vladimir Marko921094a2017-01-12 18:37:06 +00008017 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008018
8019 if (translated_method != nullptr) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008020 // Make sure the new_methods index is set.
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008021 if (translated_method->GetMethodIndexDuringLinking() != i) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008022 if (kIsDebugBuild) {
8023 auto* methods = klass_->GetMethodsPtr();
8024 CHECK_LE(reinterpret_cast<uintptr_t>(&*methods->begin(method_size_, method_alignment_)),
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008025 reinterpret_cast<uintptr_t>(translated_method));
8026 CHECK_LT(reinterpret_cast<uintptr_t>(translated_method),
Vladimir Marko921094a2017-01-12 18:37:06 +00008027 reinterpret_cast<uintptr_t>(&*methods->end(method_size_, method_alignment_)));
8028 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008029 translated_method->SetMethodIndex(0xFFFF & i);
Vladimir Marko921094a2017-01-12 18:37:06 +00008030 }
Nicolas Geoffray0376a5c2017-01-12 15:15:45 +00008031 vtable->SetElementPtrSize(i, translated_method, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00008032 }
8033 }
Vladimir Markod93e3742018-07-18 10:58:13 +01008034 klass_->SetVTable(vtable);
Vladimir Marko921094a2017-01-12 18:37:06 +00008035 return vtable;
8036}
8037
8038void ClassLinker::LinkInterfaceMethodsHelper::UpdateIfTable(Handle<mirror::IfTable> iftable) {
8039 PointerSize pointer_size = class_linker_->GetImagePointerSize();
8040 const size_t ifcount = klass_->GetIfTableCount();
8041 // Go fix up all the stale iftable pointers.
8042 for (size_t i = 0; i < ifcount; ++i) {
8043 for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
Vladimir Marko557fece2019-03-26 14:29:41 +00008044 ObjPtr<mirror::PointerArray> method_array = iftable->GetMethodArray(i);
8045 ArtMethod* m = method_array->GetElementPtrSize<ArtMethod*>(j, pointer_size);
Vladimir Marko921094a2017-01-12 18:37:06 +00008046 DCHECK(m != nullptr) << klass_->PrettyClass();
8047 auto it = move_table_.find(m);
8048 if (it != move_table_.end()) {
8049 auto* new_m = it->second;
8050 DCHECK(new_m != nullptr) << klass_->PrettyClass();
8051 method_array->SetElementPtrSize(j, new_m, pointer_size);
8052 }
8053 }
8054 }
8055}
8056
8057void ClassLinker::LinkInterfaceMethodsHelper::UpdateIMT(ArtMethod** out_imt) {
8058 // Fix up IMT next.
8059 for (size_t i = 0; i < ImTable::kSize; ++i) {
8060 auto it = move_table_.find(out_imt[i]);
8061 if (it != move_table_.end()) {
8062 out_imt[i] = it->second;
8063 }
8064 }
8065}
8066
Alex Light705ad492015-09-21 11:36:30 -07008067// TODO This method needs to be split up into several smaller methods.
Alex Lighteb7c1442015-08-31 13:17:42 -07008068bool ClassLinker::LinkInterfaceMethods(
8069 Thread* self,
8070 Handle<mirror::Class> klass,
Vladimir Marko782fb712020-12-23 12:47:31 +00008071 const HashMap<size_t, ClassLinker::MethodTranslation>& default_translations,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008072 bool* out_new_conflict,
Alex Lighteb7c1442015-08-31 13:17:42 -07008073 ArtMethod** out_imt) {
8074 StackHandleScope<3> hs(self);
8075 Runtime* const runtime = Runtime::Current();
Alex Light705ad492015-09-21 11:36:30 -07008076
8077 const bool is_interface = klass->IsInterface();
Alex Lighteb7c1442015-08-31 13:17:42 -07008078 const bool has_superclass = klass->HasSuperClass();
Alex Light705ad492015-09-21 11:36:30 -07008079 const bool fill_tables = !is_interface;
Alex Lighteb7c1442015-08-31 13:17:42 -07008080 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
Alex Lighteb7c1442015-08-31 13:17:42 -07008081 const size_t ifcount = klass->GetIfTableCount();
8082
Vladimir Marko921094a2017-01-12 18:37:06 +00008083 Handle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07008084
8085 MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
8086 ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
Alex Light9139e002015-10-09 15:59:48 -07008087 ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008088 // Copy the IMT from the super class if possible.
Alex Light705ad492015-09-21 11:36:30 -07008089 const bool extend_super_iftable = has_superclass;
8090 if (has_superclass && fill_tables) {
8091 FillImtFromSuperClass(klass,
Alex Light705ad492015-09-21 11:36:30 -07008092 unimplemented_method,
8093 imt_conflict_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008094 out_new_conflict,
Mathieu Chartier49b5ced2016-04-14 10:49:19 -07008095 out_imt);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008096 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008097 // Allocate method arrays before since we don't want miss visiting miranda method roots due to
8098 // thread suspension.
Alex Light705ad492015-09-21 11:36:30 -07008099 if (fill_tables) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008100 if (!AllocateIfTableMethodArrays(self, klass, iftable)) {
8101 return false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07008102 }
8103 }
8104
Vladimir Marko921094a2017-01-12 18:37:06 +00008105 LinkInterfaceMethodsHelper helper(this, klass, self, runtime);
8106
Igor Murashkinb1d8c312015-08-04 11:18:43 -07008107 auto* old_cause = self->StartAssertNoThreadSuspension(
Mathieu Chartiere401d142015-04-22 13:56:20 -07008108 "Copying ArtMethods for LinkInterfaceMethods");
Alex Light9139e002015-10-09 15:59:48 -07008109 // Going in reverse to ensure that we will hit abstract methods that override defaults before the
8110 // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
8111 // they will already be null. This has the additional benefit that the declarer of a miranda
8112 // method will actually declare an abstract method.
Vladimir Markoba118822017-06-12 15:41:56 +01008113 for (size_t i = ifcount; i != 0u; ) {
Alex Light9139e002015-10-09 15:59:48 -07008114 --i;
Alex Light9139e002015-10-09 15:59:48 -07008115 DCHECK_LT(i, ifcount);
8116
Alex Light705ad492015-09-21 11:36:30 -07008117 size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
Mathieu Chartiere401d142015-04-22 13:56:20 -07008118 if (num_methods > 0) {
8119 StackHandleScope<2> hs2(self);
8120 const bool is_super = i < super_ifcount;
8121 const bool super_interface = is_super && extend_super_iftable;
Alex Light705ad492015-09-21 11:36:30 -07008122 // We don't actually create or fill these tables for interfaces, we just copy some methods for
8123 // conflict methods. Just set this as nullptr in those cases.
8124 Handle<mirror::PointerArray> method_array(fill_tables
8125 ? hs2.NewHandle(iftable->GetMethodArray(i))
8126 : hs2.NewHandle<mirror::PointerArray>(nullptr));
Mathieu Chartiere401d142015-04-22 13:56:20 -07008127
Alex Lighte64300b2015-12-15 15:02:47 -08008128 ArraySlice<ArtMethod> input_virtual_methods;
Mathieu Chartier9865bde2015-12-21 09:58:16 -08008129 ScopedNullHandle<mirror::PointerArray> null_handle;
8130 Handle<mirror::PointerArray> input_vtable_array(null_handle);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008131 int32_t input_array_length = 0;
Alex Lighte64300b2015-12-15 15:02:47 -08008132
Alex Light9139e002015-10-09 15:59:48 -07008133 // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
8134 // and confusing. Default methods should always look through all the superclasses
8135 // because they are the last choice of an implementation. We get around this by looking
8136 // at the super-classes iftable methods (copied into method_array previously) when we are
8137 // looking for the implementation of a super-interface method but that is rather dirty.
Alex Lighte64300b2015-12-15 15:02:47 -08008138 bool using_virtuals;
Alex Light705ad492015-09-21 11:36:30 -07008139 if (super_interface || is_interface) {
Alex Lighte64300b2015-12-15 15:02:47 -08008140 // If we are overwriting a super class interface, try to only virtual methods instead of the
Mathieu Chartiere401d142015-04-22 13:56:20 -07008141 // whole vtable.
Alex Lighte64300b2015-12-15 15:02:47 -08008142 using_virtuals = true;
Alex Lighta467a6e2020-03-23 16:07:29 -07008143 input_virtual_methods = klass->GetDeclaredVirtualMethodsSlice(image_pointer_size_);
Alex Lighte64300b2015-12-15 15:02:47 -08008144 input_array_length = input_virtual_methods.size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07008145 } else {
Alex Lighte64300b2015-12-15 15:02:47 -08008146 // For a new interface, however, we need the whole vtable in case a new
8147 // interface method is implemented in the whole superclass.
8148 using_virtuals = false;
Andreas Gampefa4333d2017-02-14 11:10:34 -08008149 DCHECK(vtable != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008150 input_vtable_array = vtable;
8151 input_array_length = input_vtable_array->GetLength();
8152 }
Alex Lighte64300b2015-12-15 15:02:47 -08008153
Alex Lighteb7c1442015-08-31 13:17:42 -07008154 // For each method in interface
Ian Rogers62d6c772013-02-27 08:32:07 -08008155 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07008156 auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07008157 MethodNameAndSignatureComparator interface_name_comparator(
Mathieu Chartiere401d142015-04-22 13:56:20 -07008158 interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
David Srbeckye36e7f22018-11-14 14:21:23 +00008159 uint32_t imt_index = interface_method->GetImtIndex();
Alex Lighteb7c1442015-08-31 13:17:42 -07008160 ArtMethod** imt_ptr = &out_imt[imt_index];
Ian Rogers9bc81912012-10-11 21:43:36 -07008161 // For each method listed in the interface's method list, find the
8162 // matching method in our class's method list. We want to favor the
8163 // subclass over the superclass, which just requires walking
8164 // back from the end of the vtable. (This only matters if the
8165 // superclass defines a private method and this class redefines
8166 // it -- otherwise it would use the same vtable slot. In .dex files
8167 // those don't end up in the virtual method table, so it shouldn't
8168 // matter which direction we go. We walk it backward anyway.)
Alex Lighteb7c1442015-08-31 13:17:42 -07008169 //
8170 // To find defaults we need to do the same but also go over interfaces.
8171 bool found_impl = false;
Alex Light9139e002015-10-09 15:59:48 -07008172 ArtMethod* vtable_impl = nullptr;
Alex Lighteb7c1442015-08-31 13:17:42 -07008173 for (int32_t k = input_array_length - 1; k >= 0; --k) {
Alex Lighte64300b2015-12-15 15:02:47 -08008174 ArtMethod* vtable_method = using_virtuals ?
8175 &input_virtual_methods[k] :
Mathieu Chartiere401d142015-04-22 13:56:20 -07008176 input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
8177 ArtMethod* vtable_method_for_name_comparison =
8178 vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
Alex Lighta467a6e2020-03-23 16:07:29 -07008179 DCHECK(!vtable_method->IsStatic()) << vtable_method->PrettyMethod();
Ian Rogers03b6eaf2014-10-28 09:34:57 -07008180 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07008181 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07008182 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Mathieu Chartier4d122c12015-06-17 14:14:36 -07008183 // Must do EndAssertNoThreadSuspension before throw since the throw can cause
8184 // allocations.
8185 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008186 ThrowIllegalAccessError(klass.Get(),
Brian Carlstromf3632832014-05-20 15:36:53 -07008187 "Method '%s' implementing interface method '%s' is not public",
David Sehr709b0702016-10-13 09:12:37 -07008188 vtable_method->PrettyMethod().c_str(),
8189 interface_method->PrettyMethod().c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07008190 return false;
Alex Light9139e002015-10-09 15:59:48 -07008191 } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
Alex Lighteb7c1442015-08-31 13:17:42 -07008192 // We might have a newer, better, default method for this, so we just skip it. If we
8193 // are still using this we will select it again when scanning for default methods. To
8194 // obviate the need to copy the method again we will make a note that we already found
8195 // a default here.
8196 // TODO This should be much cleaner.
Alex Light9139e002015-10-09 15:59:48 -07008197 vtable_impl = vtable_method;
Alex Lighteb7c1442015-08-31 13:17:42 -07008198 break;
8199 } else {
8200 found_impl = true;
Alex Light705ad492015-09-21 11:36:30 -07008201 if (LIKELY(fill_tables)) {
8202 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
8203 // Place method in imt if entry is empty, place conflict otherwise.
8204 SetIMTRef(unimplemented_method,
8205 imt_conflict_method,
Alex Light705ad492015-09-21 11:36:30 -07008206 vtable_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008207 /*out*/out_new_conflict,
Alex Light705ad492015-09-21 11:36:30 -07008208 /*out*/imt_ptr);
8209 }
Ian Rogers9bc81912012-10-11 21:43:36 -07008210 break;
8211 }
8212 }
Alex Light9139e002015-10-09 15:59:48 -07008213 }
8214 // Continue on to the next method if we are done.
8215 if (LIKELY(found_impl)) {
8216 continue;
8217 } else if (LIKELY(super_interface)) {
8218 // Don't look for a default implementation when the super-method is implemented directly
8219 // by the class.
8220 //
8221 // See if we can use the superclasses method and skip searching everything else.
8222 // Note: !found_impl && super_interface
8223 CHECK(extend_super_iftable);
8224 // If this is a super_interface method it is possible we shouldn't override it because a
8225 // superclass could have implemented it directly. We get the method the superclass used
8226 // to implement this to know if we can override it with a default method. Doing this is
8227 // safe since we know that the super_iftable is filled in so we can simply pull it from
8228 // there. We don't bother if this is not a super-classes interface since in that case we
8229 // have scanned the entire vtable anyway and would have found it.
8230 // TODO This is rather dirty but it is faster than searching through the entire vtable
8231 // every time.
8232 ArtMethod* supers_method =
8233 method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
8234 DCHECK(supers_method != nullptr);
8235 DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
Alex Light705ad492015-09-21 11:36:30 -07008236 if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
Alex Light9139e002015-10-09 15:59:48 -07008237 // The method is not overridable by a default method (i.e. it is directly implemented
8238 // in some class). Therefore move onto the next interface method.
8239 continue;
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008240 } else {
8241 // If the super-classes method is override-able by a default method we need to keep
8242 // track of it since though it is override-able it is not guaranteed to be 'overridden'.
8243 // 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 -07008244 // to the vtable twice, causing corruption (vtable entries having inconsistent and
8245 // illegal states, incorrect vtable size, and incorrect or inconsistent iftable entries)
8246 // in this class and any subclasses.
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008247 DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
David Sehr709b0702016-10-13 09:12:37 -07008248 << "vtable_impl was " << ArtMethod::PrettyMethod(vtable_impl)
8249 << " and not 'nullptr' or "
8250 << supers_method->PrettyMethod()
8251 << " as expected. IFTable appears to be corrupt!";
Alex Lightd6c2bfa2016-05-02 18:51:34 -07008252 vtable_impl = supers_method;
Alex Light9139e002015-10-09 15:59:48 -07008253 }
8254 }
8255 // If we haven't found it yet we should search through the interfaces for default methods.
Vladimir Marko921094a2017-01-12 18:37:06 +00008256 ArtMethod* current_method = helper.FindMethod(interface_method,
8257 interface_name_comparator,
8258 vtable_impl);
Alex Light705ad492015-09-21 11:36:30 -07008259 if (LIKELY(fill_tables)) {
Alex Light12771082016-01-26 16:07:41 -08008260 if (current_method == nullptr && !super_interface) {
Alex Light705ad492015-09-21 11:36:30 -07008261 // We could not find an implementation for this method and since it is a brand new
8262 // interface we searched the entire vtable (and all default methods) for an
8263 // implementation but couldn't find one. We therefore need to make a miranda method.
Vladimir Marko921094a2017-01-12 18:37:06 +00008264 current_method = helper.GetOrCreateMirandaMethod(interface_method,
8265 interface_name_comparator);
Alex Light12771082016-01-26 16:07:41 -08008266 }
8267
8268 if (current_method != nullptr) {
8269 // We found a default method implementation. Record it in the iftable and IMT.
8270 method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
8271 SetIMTRef(unimplemented_method,
8272 imt_conflict_method,
Alex Light12771082016-01-26 16:07:41 -08008273 current_method,
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00008274 /*out*/out_new_conflict,
Alex Light12771082016-01-26 16:07:41 -08008275 /*out*/imt_ptr);
Alex Light9139e002015-10-09 15:59:48 -07008276 }
8277 }
Alex Light705ad492015-09-21 11:36:30 -07008278 } // For each method in interface end.
8279 } // if (num_methods > 0)
8280 } // For each interface.
Alex Light705ad492015-09-21 11:36:30 -07008281 // TODO don't extend virtuals of interface unless necessary (when is it?).
Vladimir Marko921094a2017-01-12 18:37:06 +00008282 if (helper.HasNewVirtuals()) {
8283 LengthPrefixedArray<ArtMethod>* old_methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8284 helper.ReallocMethods(); // No return value to check. Native allocation failure aborts.
8285 LengthPrefixedArray<ArtMethod>* methods = kIsDebugBuild ? klass->GetMethodsPtr() : nullptr;
8286
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008287 // 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 -07008288 // suspension assert.
8289 self->EndAssertNoThreadSuspension(old_cause);
Mathieu Chartierd4d83b82015-06-19 20:24:45 -07008290
Alex Light705ad492015-09-21 11:36:30 -07008291 if (fill_tables) {
Vladimir Marko3068d582019-05-28 16:39:29 +01008292 vtable.Assign(helper.UpdateVtable(default_translations, vtable));
Andreas Gampefa4333d2017-02-14 11:10:34 -08008293 if (UNLIKELY(vtable == nullptr)) {
Vladimir Marko921094a2017-01-12 18:37:06 +00008294 // The helper has already called self->AssertPendingOOMException();
Alex Light705ad492015-09-21 11:36:30 -07008295 return false;
8296 }
Vladimir Marko921094a2017-01-12 18:37:06 +00008297 helper.UpdateIfTable(iftable);
8298 helper.UpdateIMT(out_imt);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008299 }
Alex Light705ad492015-09-21 11:36:30 -07008300
Vladimir Marko921094a2017-01-12 18:37:06 +00008301 helper.CheckNoStaleMethodsInDexCache();
8302 helper.ClobberOldMethods(old_methods, methods);
Mathieu Chartiere401d142015-04-22 13:56:20 -07008303 } else {
8304 self->EndAssertNoThreadSuspension(old_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008305 }
Alex Light705ad492015-09-21 11:36:30 -07008306 if (kIsDebugBuild && !is_interface) {
Orion Hodson5880c772020-07-28 20:12:08 +01008307 CheckVTable(self, klass, image_pointer_size_);
Elliott Hughes4681c802011-09-25 18:04:37 -07008308 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008309 return true;
8310}
8311
Vladimir Marko42bee502021-01-28 14:58:35 +00008312class ClassLinker::LinkFieldsHelper {
8313 public:
8314 static bool LinkFields(ClassLinker* class_linker,
8315 Thread* self,
8316 Handle<mirror::Class> klass,
8317 bool is_static,
8318 size_t* class_size)
8319 REQUIRES_SHARED(Locks::mutator_lock_);
Brian Carlstrom4873d462011-08-21 15:23:39 -07008320
Vladimir Marko42bee502021-01-28 14:58:35 +00008321 private:
8322 enum class FieldTypeOrder : uint16_t;
8323 class FieldGaps;
8324
8325 struct FieldTypeOrderAndIndex {
8326 FieldTypeOrder field_type_order;
8327 uint16_t field_index;
8328 };
8329
8330 static FieldTypeOrder FieldTypeOrderFromFirstDescriptorCharacter(char first_char);
8331
8332 template <size_t kSize>
8333 static MemberOffset AssignFieldOffset(ArtField* field, MemberOffset field_offset)
8334 REQUIRES_SHARED(Locks::mutator_lock_);
8335};
Brian Carlstrom4873d462011-08-21 15:23:39 -07008336
Vladimir Markoc7993d52021-01-27 15:20:56 +00008337// We use the following order of field types for assigning offsets.
8338// Some fields can be shuffled forward to fill gaps, see `ClassLinker::LinkFields()`.
Vladimir Marko42bee502021-01-28 14:58:35 +00008339enum class ClassLinker::LinkFieldsHelper::FieldTypeOrder : uint16_t {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008340 kReference = 0u,
8341 kLong,
8342 kDouble,
8343 kInt,
8344 kFloat,
8345 kChar,
8346 kShort,
8347 kBoolean,
8348 kByte,
8349
8350 kLast64BitType = kDouble,
8351 kLast32BitType = kFloat,
8352 kLast16BitType = kShort,
Brian Carlstromdbc05252011-09-09 01:59:59 -07008353};
8354
Vladimir Markoc7993d52021-01-27 15:20:56 +00008355ALWAYS_INLINE
Vladimir Marko42bee502021-01-28 14:58:35 +00008356ClassLinker::LinkFieldsHelper::FieldTypeOrder
8357ClassLinker::LinkFieldsHelper::FieldTypeOrderFromFirstDescriptorCharacter(char first_char) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008358 switch (first_char) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008359 case 'J':
8360 return FieldTypeOrder::kLong;
8361 case 'D':
8362 return FieldTypeOrder::kDouble;
8363 case 'I':
8364 return FieldTypeOrder::kInt;
8365 case 'F':
8366 return FieldTypeOrder::kFloat;
8367 case 'C':
8368 return FieldTypeOrder::kChar;
8369 case 'S':
8370 return FieldTypeOrder::kShort;
8371 case 'Z':
8372 return FieldTypeOrder::kBoolean;
8373 case 'B':
8374 return FieldTypeOrder::kByte;
Vladimir Marko42bee502021-01-28 14:58:35 +00008375 default:
8376 DCHECK(first_char == 'L' || first_char == '[') << first_char;
8377 return FieldTypeOrder::kReference;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008378 }
8379}
8380
8381// Gaps where we can insert fields in object layout.
Vladimir Marko42bee502021-01-28 14:58:35 +00008382class ClassLinker::LinkFieldsHelper::FieldGaps {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008383 public:
8384 template <uint32_t kSize>
8385 ALWAYS_INLINE MemberOffset AlignFieldOffset(MemberOffset field_offset) {
8386 static_assert(kSize == 2u || kSize == 4u || kSize == 8u);
8387 if (!IsAligned<kSize>(field_offset.Uint32Value())) {
8388 uint32_t gap_start = field_offset.Uint32Value();
8389 field_offset = MemberOffset(RoundUp(gap_start, kSize));
8390 AddGaps<kSize - 1u>(gap_start, field_offset.Uint32Value());
8391 }
8392 return field_offset;
8393 }
8394
8395 template <uint32_t kSize>
8396 bool HasGap() const {
8397 static_assert(kSize == 1u || kSize == 2u || kSize == 4u);
8398 return (kSize == 1u && gap1_offset_ != kNoOffset) ||
8399 (kSize <= 2u && gap2_offset_ != kNoOffset) ||
8400 gap4_offset_ != kNoOffset;
8401 }
8402
8403 template <uint32_t kSize>
8404 MemberOffset ReleaseGap() {
8405 static_assert(kSize == 1u || kSize == 2u || kSize == 4u);
8406 uint32_t result;
8407 if (kSize == 1u && gap1_offset_ != kNoOffset) {
8408 DCHECK(gap2_offset_ == kNoOffset || gap2_offset_ > gap1_offset_);
8409 DCHECK(gap4_offset_ == kNoOffset || gap4_offset_ > gap1_offset_);
8410 result = gap1_offset_;
8411 gap1_offset_ = kNoOffset;
8412 } else if (kSize <= 2u && gap2_offset_ != kNoOffset) {
8413 DCHECK(gap4_offset_ == kNoOffset || gap4_offset_ > gap2_offset_);
8414 result = gap2_offset_;
8415 gap2_offset_ = kNoOffset;
8416 if (kSize < 2u) {
8417 AddGaps<1u>(result + kSize, result + 2u);
8418 }
8419 } else {
8420 DCHECK_NE(gap4_offset_, kNoOffset);
8421 result = gap4_offset_;
8422 gap4_offset_ = kNoOffset;
8423 if (kSize < 4u) {
8424 AddGaps<kSize | 2u>(result + kSize, result + 4u);
8425 }
8426 }
8427 return MemberOffset(result);
8428 }
8429
8430 private:
8431 template <uint32_t kGapsToCheck>
8432 void AddGaps(uint32_t gap_start, uint32_t gap_end) {
8433 if ((kGapsToCheck & 1u) != 0u) {
8434 DCHECK_LT(gap_start, gap_end);
8435 DCHECK_ALIGNED(gap_end, 2u);
8436 if ((gap_start & 1u) != 0u) {
8437 DCHECK_EQ(gap1_offset_, kNoOffset);
8438 gap1_offset_ = gap_start;
8439 gap_start += 1u;
8440 if (kGapsToCheck == 1u || gap_start == gap_end) {
8441 DCHECK_EQ(gap_start, gap_end);
8442 return;
8443 }
8444 }
8445 }
8446
8447 if ((kGapsToCheck & 2u) != 0u) {
8448 DCHECK_LT(gap_start, gap_end);
8449 DCHECK_ALIGNED(gap_start, 2u);
8450 DCHECK_ALIGNED(gap_end, 4u);
8451 if ((gap_start & 2u) != 0u) {
8452 DCHECK_EQ(gap2_offset_, kNoOffset);
8453 gap2_offset_ = gap_start;
8454 gap_start += 2u;
8455 if (kGapsToCheck <= 3u || gap_start == gap_end) {
8456 DCHECK_EQ(gap_start, gap_end);
8457 return;
8458 }
8459 }
8460 }
8461
8462 if ((kGapsToCheck & 4u) != 0u) {
8463 DCHECK_LT(gap_start, gap_end);
8464 DCHECK_ALIGNED(gap_start, 4u);
8465 DCHECK_ALIGNED(gap_end, 8u);
8466 DCHECK_EQ(gap_start + 4u, gap_end);
8467 DCHECK_EQ(gap4_offset_, kNoOffset);
8468 gap4_offset_ = gap_start;
8469 return;
8470 }
8471
8472 DCHECK(false) << "Remaining gap: " << gap_start << " to " << gap_end
8473 << " after checking " << kGapsToCheck;
8474 }
8475
8476 static constexpr uint32_t kNoOffset = static_cast<uint32_t>(-1);
8477
8478 uint32_t gap4_offset_ = kNoOffset;
8479 uint32_t gap2_offset_ = kNoOffset;
8480 uint32_t gap1_offset_ = kNoOffset;
8481};
8482
8483template <size_t kSize>
Vladimir Marko42bee502021-01-28 14:58:35 +00008484ALWAYS_INLINE
8485MemberOffset ClassLinker::LinkFieldsHelper::AssignFieldOffset(ArtField* field,
8486 MemberOffset field_offset) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008487 DCHECK_ALIGNED(field_offset.Uint32Value(), kSize);
8488 DCHECK_EQ(Primitive::ComponentSize(field->GetTypeAsPrimitiveType()), kSize);
8489 field->SetOffset(field_offset);
8490 return MemberOffset(field_offset.Uint32Value() + kSize);
8491}
8492
Vladimir Marko42bee502021-01-28 14:58:35 +00008493bool ClassLinker::LinkFieldsHelper::LinkFields(ClassLinker* class_linker,
8494 Thread* self,
8495 Handle<mirror::Class> klass,
8496 bool is_static,
8497 size_t* class_size) {
Ian Rogers7b078e82014-09-10 14:44:24 -07008498 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07008499 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008500 LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
8501 klass->GetIFieldsPtr();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008502
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008503 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07008504 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008505 if (is_static) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008506 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(
8507 class_linker->GetImagePointerSize());
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008508 } else {
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008509 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008510 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07008511 CHECK(super_class->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008512 << klass->PrettyClass() << " " << super_class->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008513 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008514 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008515 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008516
David Sehr709b0702016-10-13 09:12:37 -07008517 CHECK_EQ(num_fields == 0, fields == nullptr) << klass->PrettyClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008518
Brian Carlstromdbc05252011-09-09 01:59:59 -07008519 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07008520 // minimizes disruption of C++ version such as Class and Method.
Alex Lighte64300b2015-12-15 15:02:47 -08008521 //
8522 // The overall sort order order is:
8523 // 1) All object reference fields, sorted alphabetically.
8524 // 2) All java long (64-bit) integer fields, sorted alphabetically.
8525 // 3) All java double (64-bit) floating point fields, sorted alphabetically.
8526 // 4) All java int (32-bit) integer fields, sorted alphabetically.
8527 // 5) All java float (32-bit) floating point fields, sorted alphabetically.
8528 // 6) All java char (16-bit) integer fields, sorted alphabetically.
8529 // 7) All java short (16-bit) integer fields, sorted alphabetically.
8530 // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
8531 // 9) All java byte (8-bit) integer fields, sorted alphabetically.
8532 //
Vladimir Marko42bee502021-01-28 14:58:35 +00008533 // (References are first to increase the chance of reference visiting
8534 // being able to take a fast path using a bitmap of references at the
8535 // start of the object, see `Class::reference_instance_offsets_`.)
8536 //
Vladimir Markoc7993d52021-01-27 15:20:56 +00008537 // Once the fields are sorted in this order we will attempt to fill any gaps
8538 // that might be present in the memory layout of the structure.
8539 // Note that we shall not fill gaps between the superclass fields.
8540
8541 // Collect fields and their "type order index" (see numbered points above).
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07008542 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Vladimir Markoc7993d52021-01-27 15:20:56 +00008543 "Using plain ArtField references");
Vladimir Marko42bee502021-01-28 14:58:35 +00008544 constexpr size_t kStackBufferEntries = 64; // Avoid allocations for small number of fields.
8545 FieldTypeOrderAndIndex stack_buffer[kStackBufferEntries];
8546 std::vector<FieldTypeOrderAndIndex> heap_buffer;
8547 ArrayRef<FieldTypeOrderAndIndex> sorted_fields;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008548 if (num_fields <= kStackBufferEntries) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008549 sorted_fields = ArrayRef<FieldTypeOrderAndIndex>(stack_buffer, num_fields);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008550 } else {
8551 heap_buffer.resize(num_fields);
Vladimir Marko42bee502021-01-28 14:58:35 +00008552 sorted_fields = ArrayRef<FieldTypeOrderAndIndex>(heap_buffer);
Brian Carlstromdbc05252011-09-09 01:59:59 -07008553 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008554 size_t num_reference_fields = 0;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008555 size_t primitive_fields_start = num_fields;
Vladimir Marko42bee502021-01-28 14:58:35 +00008556 DCHECK_LE(num_fields, 1u << 16);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008557 for (size_t i = 0; i != num_fields; ++i) {
8558 ArtField* field = &fields->At(i);
8559 const char* descriptor = field->GetTypeDescriptor();
Vladimir Marko42bee502021-01-28 14:58:35 +00008560 FieldTypeOrder field_type_order = FieldTypeOrderFromFirstDescriptorCharacter(descriptor[0]);
8561 uint16_t field_index = dchecked_integral_cast<uint16_t>(i);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008562 // Insert references to the start, other fields to the end.
8563 DCHECK_LT(num_reference_fields, primitive_fields_start);
Vladimir Marko42bee502021-01-28 14:58:35 +00008564 if (field_type_order == FieldTypeOrder::kReference) {
8565 sorted_fields[num_reference_fields] = { field_type_order, field_index };
Vladimir Markoc7993d52021-01-27 15:20:56 +00008566 ++num_reference_fields;
8567 } else {
8568 --primitive_fields_start;
Vladimir Marko42bee502021-01-28 14:58:35 +00008569 sorted_fields[primitive_fields_start] = { field_type_order, field_index };
Vladimir Markoc7993d52021-01-27 15:20:56 +00008570 }
8571 }
8572 DCHECK_EQ(num_reference_fields, primitive_fields_start);
Fred Shih381e4ca2014-08-25 17:24:27 -07008573
Vladimir Marko42bee502021-01-28 14:58:35 +00008574 // Reference fields are already sorted by field index (and dex field index).
Vladimir Markoc7993d52021-01-27 15:20:56 +00008575 DCHECK(std::is_sorted(
8576 sorted_fields.begin(),
8577 sorted_fields.begin() + num_reference_fields,
Vladimir Marko42bee502021-01-28 14:58:35 +00008578 [fields](const auto& lhs, const auto& rhs) REQUIRES_SHARED(Locks::mutator_lock_) {
8579 ArtField* lhs_field = &fields->At(lhs.field_index);
8580 ArtField* rhs_field = &fields->At(rhs.field_index);
8581 CHECK_EQ(lhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8582 CHECK_EQ(rhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8583 CHECK_EQ(lhs_field->GetDexFieldIndex() < rhs_field->GetDexFieldIndex(),
8584 lhs.field_index < rhs.field_index);
8585 return lhs_field->GetDexFieldIndex() < rhs_field->GetDexFieldIndex();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008586 }));
Vladimir Marko42bee502021-01-28 14:58:35 +00008587 // Primitive fields were stored in reverse order of their field index (and dex field index).
Vladimir Markoc7993d52021-01-27 15:20:56 +00008588 DCHECK(std::is_sorted(
8589 sorted_fields.begin() + primitive_fields_start,
8590 sorted_fields.end(),
Vladimir Marko42bee502021-01-28 14:58:35 +00008591 [fields](const auto& lhs, const auto& rhs) REQUIRES_SHARED(Locks::mutator_lock_) {
8592 ArtField* lhs_field = &fields->At(lhs.field_index);
8593 ArtField* rhs_field = &fields->At(rhs.field_index);
8594 CHECK_NE(lhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8595 CHECK_NE(rhs_field->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
8596 CHECK_EQ(lhs_field->GetDexFieldIndex() > rhs_field->GetDexFieldIndex(),
8597 lhs.field_index > rhs.field_index);
8598 return lhs.field_index > rhs.field_index;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008599 }));
8600 // Sort the primitive fields by the field type order, then field index.
8601 std::sort(sorted_fields.begin() + primitive_fields_start,
8602 sorted_fields.end(),
Vladimir Marko42bee502021-01-28 14:58:35 +00008603 [](const auto& lhs, const auto& rhs) {
8604 if (lhs.field_type_order != rhs.field_type_order) {
8605 return lhs.field_type_order < rhs.field_type_order;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008606 } else {
Vladimir Marko42bee502021-01-28 14:58:35 +00008607 return lhs.field_index < rhs.field_index;
Vladimir Markoc7993d52021-01-27 15:20:56 +00008608 }
8609 });
8610 // Primitive fields are now sorted by field size (descending), then type, then field index.
8611 DCHECK(std::is_sorted(
8612 sorted_fields.begin() + primitive_fields_start,
8613 sorted_fields.end(),
Vladimir Marko42bee502021-01-28 14:58:35 +00008614 [fields](const auto& lhs, const auto& rhs) REQUIRES_SHARED(Locks::mutator_lock_) {
8615 ArtField* lhs_field = &fields->At(lhs.field_index);
8616 ArtField* rhs_field = &fields->At(rhs.field_index);
8617 Primitive::Type lhs_type = lhs_field->GetTypeAsPrimitiveType();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008618 CHECK_NE(lhs_type, Primitive::kPrimNot);
Vladimir Marko42bee502021-01-28 14:58:35 +00008619 Primitive::Type rhs_type = rhs_field->GetTypeAsPrimitiveType();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008620 CHECK_NE(rhs_type, Primitive::kPrimNot);
8621 if (lhs_type != rhs_type) {
8622 size_t lhs_size = Primitive::ComponentSize(lhs_type);
8623 size_t rhs_size = Primitive::ComponentSize(rhs_type);
8624 return (lhs_size != rhs_size) ? (lhs_size > rhs_size) : (lhs_type < rhs_type);
8625 } else {
Vladimir Marko42bee502021-01-28 14:58:35 +00008626 return lhs_field->GetDexFieldIndex() < rhs_field->GetDexFieldIndex();
Vladimir Markoc7993d52021-01-27 15:20:56 +00008627 }
8628 }));
8629
8630 // Process reference fields.
8631 FieldGaps field_gaps;
8632 size_t index = 0u;
8633 if (num_reference_fields != 0u) {
8634 constexpr size_t kReferenceSize = sizeof(mirror::HeapReference<mirror::Object>);
8635 field_offset = field_gaps.AlignFieldOffset<kReferenceSize>(field_offset);
8636 for (; index != num_reference_fields; ++index) {
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 field_offset = AssignFieldOffset<kReferenceSize>(field, field_offset);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008639 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008640 }
Vladimir Markoc7993d52021-01-27 15:20:56 +00008641 // Process 64-bit fields.
Vladimir Marko42bee502021-01-28 14:58:35 +00008642 if (index != num_fields &&
8643 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast64BitType) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008644 field_offset = field_gaps.AlignFieldOffset<8u>(field_offset);
Vladimir Marko42bee502021-01-28 14:58:35 +00008645 while (index != num_fields &&
8646 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast64BitType) {
8647 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008648 field_offset = AssignFieldOffset<8u>(field, field_offset);
8649 ++index;
Mathieu Chartier55650292020-09-14 12:21:04 -07008650 }
Mathieu Chartier55650292020-09-14 12:21:04 -07008651 }
Vladimir Markoc7993d52021-01-27 15:20:56 +00008652 // Process 32-bit fields.
Vladimir Marko42bee502021-01-28 14:58:35 +00008653 if (index != num_fields &&
8654 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast32BitType) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008655 field_offset = field_gaps.AlignFieldOffset<4u>(field_offset);
8656 if (field_gaps.HasGap<4u>()) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008657 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008658 AssignFieldOffset<4u>(field, field_gaps.ReleaseGap<4u>()); // Ignore return value.
8659 ++index;
8660 DCHECK(!field_gaps.HasGap<4u>()); // There can be only one gap for a 32-bit field.
8661 }
Vladimir Marko42bee502021-01-28 14:58:35 +00008662 while (index != num_fields &&
8663 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast32BitType) {
8664 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008665 field_offset = AssignFieldOffset<4u>(field, field_offset);
8666 ++index;
8667 }
8668 }
8669 // Process 16-bit fields.
Vladimir Marko42bee502021-01-28 14:58:35 +00008670 if (index != num_fields &&
8671 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast16BitType) {
Vladimir Markoc7993d52021-01-27 15:20:56 +00008672 field_offset = field_gaps.AlignFieldOffset<2u>(field_offset);
8673 while (index != num_fields &&
Vladimir Marko42bee502021-01-28 14:58:35 +00008674 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast16BitType &&
Vladimir Markoc7993d52021-01-27 15:20:56 +00008675 field_gaps.HasGap<2u>()) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008676 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008677 AssignFieldOffset<2u>(field, field_gaps.ReleaseGap<2u>()); // Ignore return value.
8678 ++index;
8679 }
Vladimir Marko42bee502021-01-28 14:58:35 +00008680 while (index != num_fields &&
8681 sorted_fields[index].field_type_order <= FieldTypeOrder::kLast16BitType) {
8682 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008683 field_offset = AssignFieldOffset<2u>(field, field_offset);
8684 ++index;
8685 }
8686 }
8687 // Process 8-bit fields.
8688 for (; index != num_fields && field_gaps.HasGap<1u>(); ++index) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008689 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008690 AssignFieldOffset<1u>(field, field_gaps.ReleaseGap<1u>()); // Ignore return value.
8691 }
8692 for (; index != num_fields; ++index) {
Vladimir Marko42bee502021-01-28 14:58:35 +00008693 ArtField* field = &fields->At(sorted_fields[index].field_index);
Vladimir Markoc7993d52021-01-27 15:20:56 +00008694 field_offset = AssignFieldOffset<1u>(field, field_offset);
8695 }
8696
Ian Rogers7b078e82014-09-10 14:44:24 -07008697 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008698
Elliott Hughesadb460d2011-10-05 17:02:34 -07008699 // 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 +00008700 DCHECK(!class_linker->init_done_ || !klass->DescriptorEquals("Ljava/lang/ref/Reference;"));
8701 if (!is_static &&
8702 UNLIKELY(!class_linker->init_done_) &&
8703 klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07008704 // We know there are no non-reference fields in the Reference classes, and we know
8705 // that 'referent' is alphabetically last, so this is easy...
David Sehr709b0702016-10-13 09:12:37 -07008706 CHECK_EQ(num_reference_fields, num_fields) << klass->PrettyClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008707 CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
David Sehr709b0702016-10-13 09:12:37 -07008708 << klass->PrettyClass();
Elliott Hughesadb460d2011-10-05 17:02:34 -07008709 --num_reference_fields;
8710 }
8711
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008712 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008713 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008714 if (is_static) {
8715 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07008716 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07008717 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008718 klass->SetNumReferenceInstanceFields(num_reference_fields);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008719 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008720 if (num_reference_fields == 0 || super_class == nullptr) {
8721 // object has one reference field, klass, but we ignore it since we always visit the class.
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008722 // super_class is null iff the class is java.lang.Object.
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008723 if (super_class == nullptr ||
8724 (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
8725 klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008726 }
8727 }
8728 if (kIsDebugBuild) {
8729 DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
8730 size_t total_reference_instance_fields = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008731 ObjPtr<mirror::Class> cur_super = klass.Get();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008732 while (cur_super != nullptr) {
8733 total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
8734 cur_super = cur_super->GetSuperClass();
8735 }
8736 if (super_class == nullptr) {
David Sehr709b0702016-10-13 09:12:37 -07008737 CHECK_EQ(total_reference_instance_fields, 1u) << klass->PrettyDescriptor();
Mathieu Chartier66c2d2d2015-08-25 14:32:32 -07008738 } else {
8739 // Check that there is at least num_reference_fields other than Object.class.
8740 CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
David Sehr709b0702016-10-13 09:12:37 -07008741 << klass->PrettyClass();
Mathieu Chartier52a7f5c2015-08-18 18:35:52 -07008742 }
8743 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07008744 if (!klass->IsVariableSize()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07008745 std::string temp;
8746 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
8747 size_t previous_size = klass->GetObjectSize();
8748 if (previous_size != 0) {
8749 // Make sure that we didn't originally have an incorrect size.
8750 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07008751 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07008752 klass->SetObjectSize(size);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008753 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008754 }
Vladimir Marko76649e82014-11-10 18:32:59 +00008755
8756 if (kIsDebugBuild) {
8757 // Make sure that the fields array is ordered by name but all reference
8758 // offsets are at the beginning as far as alignment allows.
8759 MemberOffset start_ref_offset = is_static
Vladimir Marko42bee502021-01-28 14:58:35 +00008760 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(class_linker->image_pointer_size_)
Vladimir Marko76649e82014-11-10 18:32:59 +00008761 : klass->GetFirstReferenceInstanceFieldOffset();
8762 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
8763 num_reference_fields *
8764 sizeof(mirror::HeapReference<mirror::Object>));
8765 MemberOffset current_ref_offset = start_ref_offset;
8766 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008767 ArtField* field = &fields->At(i);
Mathieu Chartierc7853442015-03-27 14:35:38 -07008768 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
David Sehr709b0702016-10-13 09:12:37 -07008769 << " class=" << klass->PrettyClass() << " field=" << field->PrettyField()
8770 << " offset=" << field->GetOffsetDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008771 if (i != 0) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008772 ArtField* const prev_field = &fields->At(i - 1);
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00008773 // NOTE: The field names can be the same. This is not possible in the Java language
8774 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07008775 DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00008776 }
8777 Primitive::Type type = field->GetTypeAsPrimitiveType();
8778 bool is_primitive = type != Primitive::kPrimNot;
8779 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
8780 strcmp("referent", field->GetName()) == 0) {
8781 is_primitive = true; // We lied above, so we have to expect a lie here.
8782 }
8783 MemberOffset offset = field->GetOffsetDuringLinking();
8784 if (is_primitive) {
8785 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
8786 // Shuffled before references.
8787 size_t type_size = Primitive::ComponentSize(type);
8788 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
8789 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
8790 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
8791 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
8792 }
8793 } else {
8794 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
8795 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
8796 sizeof(mirror::HeapReference<mirror::Object>));
8797 }
8798 }
8799 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
8800 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008801 return true;
8802}
8803
Vladimir Marko42bee502021-01-28 14:58:35 +00008804bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
8805 CHECK(klass != nullptr);
8806 return LinkFieldsHelper::LinkFields(this, self, klass, false, nullptr);
8807}
8808
8809bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
8810 CHECK(klass != nullptr);
8811 return LinkFieldsHelper::LinkFields(this, self, klass, true, class_size);
8812}
8813
Vladimir Marko76649e82014-11-10 18:32:59 +00008814// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07008815void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008816 uint32_t reference_offsets = 0;
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008817 ObjPtr<mirror::Class> super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008818 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07008819 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008820 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008821 // Compute reference offsets unless our superclass overflowed.
8822 if (reference_offsets != mirror::Class::kClassWalkSuper) {
8823 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00008824 if (num_reference_fields != 0u) {
8825 // All of the fields that contain object references are guaranteed be grouped in memory
8826 // starting at an appropriately aligned address after super class object data.
8827 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
8828 sizeof(mirror::HeapReference<mirror::Object>));
8829 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008830 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00008831 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008832 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008833 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00008834 reference_offsets |= (0xffffffffu << start_bit) &
8835 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07008836 }
8837 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07008838 }
8839 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07008840 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008841}
8842
Vladimir Marko18090d12018-06-01 16:53:12 +01008843ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8844 ObjPtr<mirror::DexCache> dex_cache) {
8845 StackHandleScope<1> hs(Thread::Current());
8846 Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(dex_cache));
8847 return DoResolveString(string_idx, h_dex_cache);
8848}
8849
8850ObjPtr<mirror::String> ClassLinker::DoResolveString(dex::StringIndex string_idx,
8851 Handle<mirror::DexCache> dex_cache) {
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008852 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersdfb325e2013-10-30 01:00:44 -07008853 uint32_t utf16_length;
8854 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Mathieu Chartier28357fa2016-10-18 16:27:40 -07008855 ObjPtr<mirror::String> string = intern_table_->InternStrong(utf16_length, utf8_data);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008856 if (string != nullptr) {
8857 dex_cache->SetResolvedString(string_idx, string);
8858 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008859 return string;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07008860}
8861
Vladimir Marko18090d12018-06-01 16:53:12 +01008862ObjPtr<mirror::String> ClassLinker::DoLookupString(dex::StringIndex string_idx,
8863 ObjPtr<mirror::DexCache> dex_cache) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08008864 DCHECK(dex_cache != nullptr);
Vladimir Markoa64b52d2017-12-08 16:27:49 +00008865 const DexFile& dex_file = *dex_cache->GetDexFile();
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008866 uint32_t utf16_length;
8867 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Andreas Gampe8a0128a2016-11-28 07:38:35 -08008868 ObjPtr<mirror::String> string =
8869 intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008870 if (string != nullptr) {
8871 dex_cache->SetResolvedString(string_idx, string);
8872 }
Vladimir Marko28e012a2017-12-07 11:22:59 +00008873 return string;
Vladimir Markocac5a7e2016-02-22 10:39:50 +00008874}
8875
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008876ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008877 ObjPtr<mirror::Class> referrer) {
8878 return DoLookupResolvedType(type_idx, referrer->GetDexCache(), referrer->GetClassLoader());
8879}
8880
8881ObjPtr<mirror::Class> ClassLinker::DoLookupResolvedType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008882 ObjPtr<mirror::DexCache> dex_cache,
8883 ObjPtr<mirror::ClassLoader> class_loader) {
8884 const DexFile& dex_file = *dex_cache->GetDexFile();
8885 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
8886 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
8887 ObjPtr<mirror::Class> type = nullptr;
8888 if (descriptor[1] == '\0') {
8889 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
8890 // for primitive classes that aren't backed by dex files.
Vladimir Marko9186b182018-11-06 14:55:54 +00008891 type = LookupPrimitiveClass(descriptor[0]);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008892 } else {
8893 Thread* const self = Thread::Current();
8894 DCHECK(self != nullptr);
8895 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
8896 // Find the class in the loaded classes table.
Vladimir Markobcf17522018-06-01 13:14:32 +01008897 type = LookupClass(self, descriptor, hash, class_loader);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008898 }
8899 if (type != nullptr) {
8900 if (type->IsResolved()) {
8901 dex_cache->SetResolvedType(type_idx, type);
Mathieu Chartierb8901302016-09-30 10:27:43 -07008902 } else {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008903 type = nullptr;
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008904 }
Mathieu Chartierb8901302016-09-30 10:27:43 -07008905 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00008906 return type;
Mathieu Chartierb8901302016-09-30 10:27:43 -07008907}
8908
Andreas Gampeb0625e02019-05-01 12:43:31 -07008909template <typename RefType>
8910ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx, RefType referrer) {
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008911 StackHandleScope<2> hs(Thread::Current());
8912 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
8913 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
8914 return DoResolveType(type_idx, dex_cache, class_loader);
8915}
8916
Andreas Gampe4835d212018-11-21 14:55:10 -08008917// Instantiate the above.
8918template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8919 ArtField* referrer);
8920template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8921 ArtMethod* referrer);
8922template ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
8923 ObjPtr<mirror::Class> referrer);
8924
Vladimir Marko09c5ca42018-05-31 15:15:31 +01008925ObjPtr<mirror::Class> ClassLinker::DoResolveType(dex::TypeIndex type_idx,
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008926 Handle<mirror::DexCache> dex_cache,
8927 Handle<mirror::ClassLoader> class_loader) {
8928 Thread* self = Thread::Current();
8929 const char* descriptor = dex_cache->GetDexFile()->StringByTypeIdx(type_idx);
8930 ObjPtr<mirror::Class> resolved = FindClass(self, descriptor, class_loader);
8931 if (resolved != nullptr) {
8932 // TODO: we used to throw here if resolved's class loader was not the
8933 // boot class loader. This was to permit different classes with the
8934 // same name to be loaded simultaneously by different loaders
8935 dex_cache->SetResolvedType(type_idx, resolved);
8936 } else {
8937 CHECK(self->IsExceptionPending())
8938 << "Expected pending exception for failed resolution of: " << descriptor;
8939 // Convert a ClassNotFoundException to a NoClassDefFoundError.
8940 StackHandleScope<1> hs(self);
8941 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Vladimir Markob4eb1b12018-05-24 11:09:38 +01008942 if (cause->InstanceOf(GetClassRoot(ClassRoot::kJavaLangClassNotFoundException, this))) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00008943 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
8944 self->ClearException();
8945 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
8946 self->GetException()->SetCause(cause.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07008947 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008948 }
Vladimir Marko72ab6842017-01-20 19:32:50 +00008949 DCHECK((resolved == nullptr) || resolved->IsResolved())
David Sehr709b0702016-10-13 09:12:37 -07008950 << resolved->PrettyDescriptor() << " " << resolved->GetStatus();
Vladimir Marko28e012a2017-12-07 11:22:59 +00008951 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008952}
8953
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008954ArtMethod* ClassLinker::FindResolvedMethod(ObjPtr<mirror::Class> klass,
8955 ObjPtr<mirror::DexCache> dex_cache,
8956 ObjPtr<mirror::ClassLoader> class_loader,
8957 uint32_t method_idx) {
8958 // Search for the method using dex_cache and method_idx. The Class::Find*Method()
8959 // functions can optimize the search if the dex_cache is the same as the DexCache
8960 // of the class, with fall-back to name and signature search otherwise.
8961 ArtMethod* resolved = nullptr;
8962 if (klass->IsInterface()) {
8963 resolved = klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
8964 } else {
8965 resolved = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
8966 }
8967 DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008968 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01008969 hiddenapi::ShouldDenyAccessToMember(resolved,
8970 hiddenapi::AccessContext(class_loader, dex_cache),
8971 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00008972 resolved = nullptr;
8973 }
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008974 if (resolved != nullptr) {
8975 // In case of jmvti, the dex file gets verified before being registered, so first
8976 // check if it's registered before checking class tables.
8977 const DexFile& dex_file = *dex_cache->GetDexFile();
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008978 DCHECK(!IsDexFileRegistered(Thread::Current(), dex_file) ||
8979 FindClassTable(Thread::Current(), dex_cache) == ClassTableForClassLoader(class_loader))
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008980 << "DexFile referrer: " << dex_file.GetLocation()
8981 << " ClassLoader: " << DescribeLoaders(class_loader, "");
8982 // Be a good citizen and update the dex cache to speed subsequent calls.
8983 dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_);
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00008984 // Disable the following invariant check as the verifier breaks it. b/73760543
8985 // const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
8986 // DCHECK(LookupResolvedType(method_id.class_idx_, dex_cache, class_loader) != nullptr)
8987 // << "Method: " << resolved->PrettyMethod() << ", "
8988 // << "Class: " << klass->PrettyClass() << " (" << klass->GetStatus() << "), "
8989 // << "DexFile referrer: " << dex_file.GetLocation();
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00008990 }
8991 return resolved;
8992}
8993
David Brazdil4525e0b2018-04-05 16:57:32 +01008994// Returns true if `method` is either null or hidden.
8995// Does not print any warnings if it is hidden.
8996static bool CheckNoSuchMethod(ArtMethod* method,
8997 ObjPtr<mirror::DexCache> dex_cache,
8998 ObjPtr<mirror::ClassLoader> class_loader)
8999 REQUIRES_SHARED(Locks::mutator_lock_) {
9000 return method == nullptr ||
David Brazdilf50ac102018-10-17 18:00:06 +01009001 hiddenapi::ShouldDenyAccessToMember(method,
9002 hiddenapi::AccessContext(class_loader, dex_cache),
9003 hiddenapi::AccessMethod::kNone); // no warnings
David Brazdil4525e0b2018-04-05 16:57:32 +01009004}
9005
9006ArtMethod* ClassLinker::FindIncompatibleMethod(ObjPtr<mirror::Class> klass,
9007 ObjPtr<mirror::DexCache> dex_cache,
9008 ObjPtr<mirror::ClassLoader> class_loader,
9009 uint32_t method_idx) {
9010 if (klass->IsInterface()) {
9011 ArtMethod* method = klass->FindClassMethod(dex_cache, method_idx, image_pointer_size_);
9012 return CheckNoSuchMethod(method, dex_cache, class_loader) ? nullptr : method;
9013 } else {
9014 // If there was an interface method with the same signature, we would have
9015 // found it in the "copied" methods. Only DCHECK that the interface method
9016 // really does not exist.
9017 if (kIsDebugBuild) {
9018 ArtMethod* method =
9019 klass->FindInterfaceMethod(dex_cache, method_idx, image_pointer_size_);
9020 DCHECK(CheckNoSuchMethod(method, dex_cache, class_loader));
9021 }
9022 return nullptr;
9023 }
9024}
9025
Andreas Gampe42ef8ab2015-12-03 17:27:32 -08009026template <ClassLinker::ResolveMode kResolveMode>
Vladimir Marko89011192017-12-11 13:45:05 +00009027ArtMethod* ClassLinker::ResolveMethod(uint32_t method_idx,
Mathieu Chartiere401d142015-04-22 13:56:20 -07009028 Handle<mirror::DexCache> dex_cache,
9029 Handle<mirror::ClassLoader> class_loader,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07009030 ArtMethod* referrer,
9031 InvokeType type) {
Nicolas Geoffray605c5912020-04-08 15:12:39 +01009032 DCHECK(!Thread::Current()->IsExceptionPending()) << Thread::Current()->GetException()->Dump();
Andreas Gampefa4333d2017-02-14 11:10:34 -08009033 DCHECK(dex_cache != nullptr);
Vladimir Markoba118822017-06-12 15:41:56 +01009034 DCHECK(referrer == nullptr || !referrer->IsProxyMethod());
Ian Rogers08f753d2012-08-24 14:35:25 -07009035 // Check for hit in the dex cache.
Vladimir Markoba118822017-06-12 15:41:56 +01009036 PointerSize pointer_size = image_pointer_size_;
9037 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, pointer_size);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07009038 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01009039 DCHECK(resolved == nullptr || !resolved->IsRuntimeMethod());
9040 bool valid_dex_cache_method = resolved != nullptr;
Vladimir Markoba118822017-06-12 15:41:56 +01009041 if (kResolveMode == ResolveMode::kNoChecks && valid_dex_cache_method) {
9042 // We have a valid method from the DexCache and no checks to perform.
Mathieu Chartiere401d142015-04-22 13:56:20 -07009043 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009044 return resolved;
9045 }
Vladimir Marko89011192017-12-11 13:45:05 +00009046 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009047 const dex::MethodId& method_id = dex_file.GetMethodId(method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01009048 ObjPtr<mirror::Class> klass = nullptr;
9049 if (valid_dex_cache_method) {
9050 // We have a valid method from the DexCache but we need to perform ICCE and IAE checks.
9051 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009052 klass = LookupResolvedType(method_id.class_idx_, dex_cache.Get(), class_loader.Get());
Vladimir Marko6f1bd462017-12-06 17:45:03 +00009053 if (UNLIKELY(klass == nullptr)) {
Nicolas Geoffraybefa3092018-02-22 14:50:01 +00009054 // We normaly should not end up here. However the verifier currently doesn't guarantee
9055 // the invariant of having the klass in the class table. b/73760543
9056 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Nicolas Geoffray07614192020-04-28 17:31:31 +01009057 if (klass == nullptr) {
9058 // This can only happen if the current thread is not allowed to load
9059 // classes.
9060 DCHECK(!Thread::Current()->CanLoadClasses());
9061 DCHECK(Thread::Current()->IsExceptionPending());
9062 return nullptr;
9063 }
Vladimir Marko6f1bd462017-12-06 17:45:03 +00009064 }
Vladimir Markoba118822017-06-12 15:41:56 +01009065 } else {
9066 // The method was not in the DexCache, resolve the declaring class.
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009067 klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Vladimir Markoba118822017-06-12 15:41:56 +01009068 if (klass == nullptr) {
9069 DCHECK(Thread::Current()->IsExceptionPending());
9070 return nullptr;
9071 }
9072 }
9073
9074 // Check if the invoke type matches the class type.
9075 if (kResolveMode == ResolveMode::kCheckICCEAndIAE &&
Andreas Gampe98ea9d92018-10-19 14:06:15 -07009076 CheckInvokeClassMismatch</* kThrow= */ true>(
Vladimir Markoba118822017-06-12 15:41:56 +01009077 dex_cache.Get(), type, [klass]() { return klass; })) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07009078 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07009079 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009080 }
Vladimir Markoba118822017-06-12 15:41:56 +01009081
9082 if (!valid_dex_cache_method) {
Nicolas Geoffrayea179f42018-02-08 22:30:18 +00009083 resolved = FindResolvedMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009084 }
Vladimir Markoba118822017-06-12 15:41:56 +01009085
9086 // Note: We can check for IllegalAccessError only if we have a referrer.
9087 if (kResolveMode == ResolveMode::kCheckICCEAndIAE && resolved != nullptr && referrer != nullptr) {
9088 ObjPtr<mirror::Class> methods_class = resolved->GetDeclaringClass();
9089 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9090 if (!referring_class->CheckResolvedMethodAccess(methods_class,
9091 resolved,
9092 dex_cache.Get(),
9093 method_idx,
9094 type)) {
9095 DCHECK(Thread::Current()->IsExceptionPending());
9096 return nullptr;
9097 }
9098 }
9099
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07009100 // If we found a method, check for incompatible class changes.
Vladimir Markoba118822017-06-12 15:41:56 +01009101 if (LIKELY(resolved != nullptr) &&
9102 LIKELY(kResolveMode == ResolveMode::kNoChecks ||
9103 !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07009104 return resolved;
9105 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01009106 // If we had a method, or if we can find one with another lookup type,
9107 // it's an incompatible-class-change error.
9108 if (resolved == nullptr) {
David Brazdil4525e0b2018-04-05 16:57:32 +01009109 resolved = FindIncompatibleMethod(klass, dex_cache.Get(), class_loader.Get(), method_idx);
Vladimir Markoba118822017-06-12 15:41:56 +01009110 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07009111 if (resolved != nullptr) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07009112 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07009113 } else {
Vladimir Markoba118822017-06-12 15:41:56 +01009114 // We failed to find the method (using all lookup types), so throw a NoSuchMethodError.
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07009115 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
9116 const Signature signature = dex_file.GetMethodSignature(method_id);
Vladimir Markoba118822017-06-12 15:41:56 +01009117 ThrowNoSuchMethodError(type, klass, name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07009118 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08009119 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07009120 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07009121 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009122}
9123
Vladimir Marko89011192017-12-11 13:45:05 +00009124ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(uint32_t method_idx,
Jeff Hao13e748b2015-08-25 20:44:19 +00009125 Handle<mirror::DexCache> dex_cache,
9126 Handle<mirror::ClassLoader> class_loader) {
9127 ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07009128 Thread::PoisonObjectPointersIfDebug();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01009129 if (resolved != nullptr) {
9130 DCHECK(!resolved->IsRuntimeMethod());
Jeff Hao13e748b2015-08-25 20:44:19 +00009131 DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
9132 return resolved;
9133 }
9134 // Fail, get the declaring class.
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009135 const dex::MethodId& method_id = dex_cache->GetDexFile()->GetMethodId(method_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009136 ObjPtr<mirror::Class> klass = ResolveType(method_id.class_idx_, dex_cache, class_loader);
Jeff Hao13e748b2015-08-25 20:44:19 +00009137 if (klass == nullptr) {
9138 Thread::Current()->AssertPendingException();
9139 return nullptr;
9140 }
9141 if (klass->IsInterface()) {
Vladimir Markoba118822017-06-12 15:41:56 +01009142 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
9143 } else {
9144 resolved = klass->FindClassMethod(dex_cache.Get(), method_idx, image_pointer_size_);
Jeff Hao13e748b2015-08-25 20:44:19 +00009145 }
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009146 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009147 hiddenapi::ShouldDenyAccessToMember(
9148 resolved,
9149 hiddenapi::AccessContext(class_loader.Get(), dex_cache.Get()),
9150 hiddenapi::AccessMethod::kLinking)) {
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009151 resolved = nullptr;
9152 }
Jeff Hao13e748b2015-08-25 20:44:19 +00009153 return resolved;
9154}
9155
Vladimir Markof44d36c2017-03-14 14:18:46 +00009156ArtField* ClassLinker::LookupResolvedField(uint32_t field_idx,
9157 ObjPtr<mirror::DexCache> dex_cache,
9158 ObjPtr<mirror::ClassLoader> class_loader,
9159 bool is_static) {
9160 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009161 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Markof44d36c2017-03-14 14:18:46 +00009162 ObjPtr<mirror::Class> klass = dex_cache->GetResolvedType(field_id.class_idx_);
9163 if (klass == nullptr) {
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009164 klass = LookupResolvedType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Markof44d36c2017-03-14 14:18:46 +00009165 }
9166 if (klass == nullptr) {
9167 // The class has not been resolved yet, so the field is also unresolved.
9168 return nullptr;
9169 }
9170 DCHECK(klass->IsResolved());
Vladimir Markof44d36c2017-03-14 14:18:46 +00009171
David Brazdil1ab0fa82018-05-04 11:28:03 +01009172 return FindResolvedField(klass, dex_cache, class_loader, field_idx, is_static);
Vladimir Markof44d36c2017-03-14 14:18:46 +00009173}
9174
Vladimir Markoe11dd502017-12-08 14:09:45 +00009175ArtField* ClassLinker::ResolveField(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07009176 Handle<mirror::DexCache> dex_cache,
Mathieu Chartierc77f3ab2015-09-03 19:41:50 -07009177 Handle<mirror::ClassLoader> class_loader,
9178 bool is_static) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08009179 DCHECK(dex_cache != nullptr);
Nicolas Geoffrayf3688822020-03-25 15:04:03 +00009180 DCHECK(!Thread::Current()->IsExceptionPending()) << Thread::Current()->GetException()->Dump();
Mathieu Chartierc7853442015-03-27 14:35:38 -07009181 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07009182 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07009183 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009184 return resolved;
9185 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00009186 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009187 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009188 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00009189 if (klass == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08009190 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07009191 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009192 }
9193
David Brazdil1ab0fa82018-05-04 11:28:03 +01009194 resolved = FindResolvedField(klass, dex_cache.Get(), class_loader.Get(), field_idx, is_static);
Andreas Gampe58a5af82014-07-31 16:23:49 -07009195 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08009196 const char* name = dex_file.GetFieldName(field_id);
9197 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009198 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
David Brazdil8ce3bfa2018-03-12 18:01:18 +00009199 }
Ian Rogersb067ac22011-12-13 18:05:09 -08009200 return resolved;
9201}
9202
Vladimir Markoe11dd502017-12-08 14:09:45 +00009203ArtField* ClassLinker::ResolveFieldJLS(uint32_t field_idx,
Mathieu Chartierc7853442015-03-27 14:35:38 -07009204 Handle<mirror::DexCache> dex_cache,
9205 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampefa4333d2017-02-14 11:10:34 -08009206 DCHECK(dex_cache != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009207 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartiera59d9b22016-09-26 18:13:17 -07009208 Thread::PoisonObjectPointersIfDebug();
Andreas Gampe58a5af82014-07-31 16:23:49 -07009209 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08009210 return resolved;
9211 }
Vladimir Markoe11dd502017-12-08 14:09:45 +00009212 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009213 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009214 ObjPtr<mirror::Class> klass = ResolveType(field_id.class_idx_, dex_cache, class_loader);
Vladimir Marko19a4d372016-12-08 14:41:46 +00009215 if (klass == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08009216 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009217 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08009218 }
9219
David Brazdil1ab0fa82018-05-04 11:28:03 +01009220 resolved = FindResolvedFieldJLS(klass, dex_cache.Get(), class_loader.Get(), field_idx);
9221 if (resolved == nullptr) {
9222 const char* name = dex_file.GetFieldName(field_id);
9223 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Vladimir Marko19a4d372016-12-08 14:41:46 +00009224 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07009225 }
9226 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07009227}
9228
David Brazdil1ab0fa82018-05-04 11:28:03 +01009229ArtField* ClassLinker::FindResolvedField(ObjPtr<mirror::Class> klass,
9230 ObjPtr<mirror::DexCache> dex_cache,
9231 ObjPtr<mirror::ClassLoader> class_loader,
9232 uint32_t field_idx,
9233 bool is_static) {
9234 ArtField* resolved = nullptr;
9235 Thread* self = is_static ? Thread::Current() : nullptr;
9236 const DexFile& dex_file = *dex_cache->GetDexFile();
9237
9238 resolved = is_static ? mirror::Class::FindStaticField(self, klass, dex_cache, field_idx)
9239 : klass->FindInstanceField(dex_cache, field_idx);
9240
9241 if (resolved == nullptr) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009242 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009243 const char* name = dex_file.GetFieldName(field_id);
9244 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
9245 resolved = is_static ? mirror::Class::FindStaticField(self, klass, name, type)
9246 : klass->FindInstanceField(name, type);
9247 }
9248
9249 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009250 hiddenapi::ShouldDenyAccessToMember(resolved,
9251 hiddenapi::AccessContext(class_loader, dex_cache),
9252 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01009253 resolved = nullptr;
9254 }
9255
9256 if (resolved != nullptr) {
9257 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
9258 }
9259
9260 return resolved;
9261}
9262
9263ArtField* ClassLinker::FindResolvedFieldJLS(ObjPtr<mirror::Class> klass,
9264 ObjPtr<mirror::DexCache> dex_cache,
9265 ObjPtr<mirror::ClassLoader> class_loader,
9266 uint32_t field_idx) {
9267 ArtField* resolved = nullptr;
9268 Thread* self = Thread::Current();
9269 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009270 const dex::FieldId& field_id = dex_file.GetFieldId(field_idx);
David Brazdil1ab0fa82018-05-04 11:28:03 +01009271
9272 const char* name = dex_file.GetFieldName(field_id);
9273 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
9274 resolved = mirror::Class::FindField(self, klass, name, type);
9275
9276 if (resolved != nullptr &&
David Brazdilf50ac102018-10-17 18:00:06 +01009277 hiddenapi::ShouldDenyAccessToMember(resolved,
9278 hiddenapi::AccessContext(class_loader, dex_cache),
9279 hiddenapi::AccessMethod::kLinking)) {
David Brazdil1ab0fa82018-05-04 11:28:03 +01009280 resolved = nullptr;
9281 }
9282
9283 if (resolved != nullptr) {
9284 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
9285 }
9286
9287 return resolved;
9288}
9289
Vladimir Markoaf940202017-12-08 15:01:18 +00009290ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(
9291 Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01009292 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00009293 Handle<mirror::DexCache> dex_cache,
9294 Handle<mirror::ClassLoader> class_loader) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009295 DCHECK(Runtime::Current()->IsMethodHandlesEnabled());
Andreas Gampefa4333d2017-02-14 11:10:34 -08009296 DCHECK(dex_cache != nullptr);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009297
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009298 ObjPtr<mirror::MethodType> resolved = dex_cache->GetResolvedMethodType(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009299 if (resolved != nullptr) {
Vladimir Markobcf17522018-06-01 13:14:32 +01009300 return resolved;
Narayan Kamath25352fc2016-08-03 12:46:58 +01009301 }
9302
Narayan Kamath25352fc2016-08-03 12:46:58 +01009303 StackHandleScope<4> hs(self);
9304
9305 // First resolve the return type.
Vladimir Markoaf940202017-12-08 15:01:18 +00009306 const DexFile& dex_file = *dex_cache->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009307 const dex::ProtoId& proto_id = dex_file.GetProtoId(proto_idx);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009308 Handle<mirror::Class> return_type(hs.NewHandle(
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009309 ResolveType(proto_id.return_type_idx_, dex_cache, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009310 if (return_type == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009311 DCHECK(self->IsExceptionPending());
9312 return nullptr;
9313 }
9314
9315 // Then resolve the argument types.
9316 //
9317 // TODO: Is there a better way to figure out the number of method arguments
9318 // other than by looking at the shorty ?
9319 const size_t num_method_args = strlen(dex_file.StringDataByIdx(proto_id.shorty_idx_)) - 1;
9320
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009321 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Narayan Kamath25352fc2016-08-03 12:46:58 +01009322 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9323 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_method_args)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009324 if (method_params == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009325 DCHECK(self->IsExceptionPending());
9326 return nullptr;
9327 }
9328
9329 DexFileParameterIterator it(dex_file, proto_id);
9330 int32_t i = 0;
9331 MutableHandle<mirror::Class> param_class = hs.NewHandle<mirror::Class>(nullptr);
9332 for (; it.HasNext(); it.Next()) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08009333 const dex::TypeIndex type_idx = it.GetTypeIdx();
Vladimir Marko666ee3d2017-12-11 18:37:36 +00009334 param_class.Assign(ResolveType(type_idx, dex_cache, class_loader));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009335 if (param_class == nullptr) {
Narayan Kamath25352fc2016-08-03 12:46:58 +01009336 DCHECK(self->IsExceptionPending());
9337 return nullptr;
9338 }
9339
9340 method_params->Set(i++, param_class.Get());
9341 }
9342
9343 DCHECK(!it.HasNext());
9344
9345 Handle<mirror::MethodType> type = hs.NewHandle(
9346 mirror::MethodType::Create(self, return_type, method_params));
9347 dex_cache->SetResolvedMethodType(proto_idx, type.Get());
9348
9349 return type.Get();
9350}
9351
Vladimir Markoaf940202017-12-08 15:01:18 +00009352ObjPtr<mirror::MethodType> ClassLinker::ResolveMethodType(Thread* self,
Orion Hodson06d10a72018-05-14 08:53:38 +01009353 dex::ProtoIndex proto_idx,
Vladimir Markoaf940202017-12-08 15:01:18 +00009354 ArtMethod* referrer) {
Orion Hodson2e599942017-09-22 16:17:41 +01009355 StackHandleScope<2> hs(self);
Orion Hodson2e599942017-09-22 16:17:41 +01009356 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
9357 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Vladimir Markoaf940202017-12-08 15:01:18 +00009358 return ResolveMethodType(self, proto_idx, dex_cache, class_loader);
Orion Hodson2e599942017-09-22 16:17:41 +01009359}
9360
Vladimir Marko5aead702019-03-27 11:00:36 +00009361ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForField(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009362 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009363 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009364 ArtMethod* referrer) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009365 DexFile::MethodHandleType handle_type =
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009366 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
9367 mirror::MethodHandle::Kind kind;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009368 bool is_put;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009369 bool is_static;
9370 int32_t num_params;
Orion Hodsonc069a302017-01-18 09:23:12 +00009371 switch (handle_type) {
9372 case DexFile::MethodHandleType::kStaticPut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009373 kind = mirror::MethodHandle::Kind::kStaticPut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009374 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009375 is_static = true;
9376 num_params = 1;
Orion Hodson631827d2017-04-10 14:53:47 +01009377 break;
9378 }
9379 case DexFile::MethodHandleType::kStaticGet: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009380 kind = mirror::MethodHandle::Kind::kStaticGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009381 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009382 is_static = true;
9383 num_params = 0;
Orion Hodson631827d2017-04-10 14:53:47 +01009384 break;
9385 }
9386 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson82b351f2017-07-05 14:34:25 +01009387 kind = mirror::MethodHandle::Kind::kInstancePut;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009388 is_put = true;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009389 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00009390 num_params = 2;
9391 break;
9392 }
9393 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009394 kind = mirror::MethodHandle::Kind::kInstanceGet;
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009395 is_put = false;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009396 is_static = false;
Orion Hodsonc069a302017-01-18 09:23:12 +00009397 num_params = 1;
9398 break;
9399 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009400 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson82b351f2017-07-05 14:34:25 +01009401 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009402 case DexFile::MethodHandleType::kInvokeConstructor:
Orion Hodson82b351f2017-07-05 14:34:25 +01009403 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009404 case DexFile::MethodHandleType::kInvokeInterface:
9405 UNREACHABLE();
Orion Hodsonc069a302017-01-18 09:23:12 +00009406 }
9407
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009408 ArtField* target_field =
9409 ResolveField(method_handle.field_or_method_idx_, referrer, is_static);
9410 if (LIKELY(target_field != nullptr)) {
9411 ObjPtr<mirror::Class> target_class = target_field->GetDeclaringClass();
9412 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9413 if (UNLIKELY(!referring_class->CanAccessMember(target_class, target_field->GetAccessFlags()))) {
9414 ThrowIllegalAccessErrorField(referring_class, target_field);
9415 return nullptr;
9416 }
Orion Hodsonfd7b2c22018-03-15 15:38:38 +00009417 if (UNLIKELY(is_put && target_field->IsFinal())) {
9418 ThrowIllegalAccessErrorField(referring_class, target_field);
9419 return nullptr;
9420 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009421 } else {
9422 DCHECK(Thread::Current()->IsExceptionPending());
9423 return nullptr;
9424 }
9425
9426 StackHandleScope<4> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009427 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonc069a302017-01-18 09:23:12 +00009428 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9429 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009430 if (UNLIKELY(method_params == nullptr)) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009431 DCHECK(self->IsExceptionPending());
9432 return nullptr;
9433 }
9434
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009435 Handle<mirror::Class> constructor_class;
Orion Hodsonc069a302017-01-18 09:23:12 +00009436 Handle<mirror::Class> return_type;
9437 switch (handle_type) {
9438 case DexFile::MethodHandleType::kStaticPut: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009439 method_params->Set(0, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00009440 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00009441 break;
9442 }
9443 case DexFile::MethodHandleType::kStaticGet: {
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009444 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00009445 break;
9446 }
9447 case DexFile::MethodHandleType::kInstancePut: {
Orion Hodson631827d2017-04-10 14:53:47 +01009448 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009449 method_params->Set(1, target_field->ResolveType());
Vladimir Marko9186b182018-11-06 14:55:54 +00009450 return_type = hs.NewHandle(GetClassRoot(ClassRoot::kPrimitiveVoid, this));
Orion Hodsonc069a302017-01-18 09:23:12 +00009451 break;
9452 }
9453 case DexFile::MethodHandleType::kInstanceGet: {
Orion Hodson631827d2017-04-10 14:53:47 +01009454 method_params->Set(0, target_field->GetDeclaringClass());
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009455 return_type = hs.NewHandle(target_field->ResolveType());
Orion Hodsonc069a302017-01-18 09:23:12 +00009456 break;
9457 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009458 case DexFile::MethodHandleType::kInvokeStatic:
Orion Hodson631827d2017-04-10 14:53:47 +01009459 case DexFile::MethodHandleType::kInvokeInstance:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009460 case DexFile::MethodHandleType::kInvokeConstructor:
9461 case DexFile::MethodHandleType::kInvokeDirect:
Orion Hodson631827d2017-04-10 14:53:47 +01009462 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009463 UNREACHABLE();
9464 }
9465
9466 for (int32_t i = 0; i < num_params; ++i) {
9467 if (UNLIKELY(method_params->Get(i) == nullptr)) {
9468 DCHECK(self->IsExceptionPending());
9469 return nullptr;
Orion Hodsonc069a302017-01-18 09:23:12 +00009470 }
9471 }
9472
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009473 if (UNLIKELY(return_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009474 DCHECK(self->IsExceptionPending());
9475 return nullptr;
9476 }
9477
9478 Handle<mirror::MethodType>
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009479 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9480 if (UNLIKELY(method_type.IsNull())) {
Orion Hodsonc069a302017-01-18 09:23:12 +00009481 DCHECK(self->IsExceptionPending());
9482 return nullptr;
9483 }
Orion Hodson631827d2017-04-10 14:53:47 +01009484
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009485 uintptr_t target = reinterpret_cast<uintptr_t>(target_field);
9486 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9487}
9488
Vladimir Marko5aead702019-03-27 11:00:36 +00009489ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandleForMethod(
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009490 Thread* self,
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009491 const dex::MethodHandleItem& method_handle,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009492 ArtMethod* referrer) {
9493 DexFile::MethodHandleType handle_type =
9494 static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_);
9495 mirror::MethodHandle::Kind kind;
9496 uint32_t receiver_count = 0;
9497 ArtMethod* target_method = nullptr;
9498 switch (handle_type) {
9499 case DexFile::MethodHandleType::kStaticPut:
9500 case DexFile::MethodHandleType::kStaticGet:
9501 case DexFile::MethodHandleType::kInstancePut:
9502 case DexFile::MethodHandleType::kInstanceGet:
9503 UNREACHABLE();
9504 case DexFile::MethodHandleType::kInvokeStatic: {
9505 kind = mirror::MethodHandle::Kind::kInvokeStatic;
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::kStatic);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009511 break;
9512 }
9513 case DexFile::MethodHandleType::kInvokeInstance: {
9514 kind = mirror::MethodHandle::Kind::kInvokeVirtual;
9515 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009516 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9517 method_handle.field_or_method_idx_,
9518 referrer,
9519 InvokeType::kVirtual);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009520 break;
9521 }
9522 case DexFile::MethodHandleType::kInvokeConstructor: {
9523 // Constructors are currently implemented as a transform. They
9524 // are special cased later in this method.
9525 kind = mirror::MethodHandle::Kind::kInvokeTransform;
9526 receiver_count = 0;
Vladimir Markoba118822017-06-12 15:41:56 +01009527 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9528 method_handle.field_or_method_idx_,
9529 referrer,
9530 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009531 break;
9532 }
9533 case DexFile::MethodHandleType::kInvokeDirect: {
9534 kind = mirror::MethodHandle::Kind::kInvokeDirect;
9535 receiver_count = 1;
9536 StackHandleScope<2> hs(self);
9537 // A constant method handle with type kInvokeDirect can refer to
9538 // a method that is private or to a method in a super class. To
9539 // disambiguate the two options, we resolve the method ignoring
9540 // the invocation type to determine if the method is private. We
9541 // then resolve again specifying the intended invocation type to
9542 // force the appropriate checks.
Vladimir Marko89011192017-12-11 13:45:05 +00009543 target_method = ResolveMethodWithoutInvokeType(method_handle.field_or_method_idx_,
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009544 hs.NewHandle(referrer->GetDexCache()),
9545 hs.NewHandle(referrer->GetClassLoader()));
9546 if (UNLIKELY(target_method == nullptr)) {
9547 break;
9548 }
9549
9550 if (target_method->IsPrivate()) {
9551 kind = mirror::MethodHandle::Kind::kInvokeDirect;
Vladimir Markoba118822017-06-12 15:41:56 +01009552 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9553 method_handle.field_or_method_idx_,
9554 referrer,
9555 InvokeType::kDirect);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009556 } else {
9557 kind = mirror::MethodHandle::Kind::kInvokeSuper;
Vladimir Markoba118822017-06-12 15:41:56 +01009558 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9559 method_handle.field_or_method_idx_,
9560 referrer,
9561 InvokeType::kSuper);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009562 if (UNLIKELY(target_method == nullptr)) {
9563 break;
9564 }
9565 // Find the method specified in the parent in referring class
9566 // so invoke-super invokes the method in the parent of the
9567 // referrer.
9568 target_method =
9569 referrer->GetDeclaringClass()->FindVirtualMethodForVirtual(target_method,
9570 kRuntimePointerSize);
9571 }
9572 break;
9573 }
9574 case DexFile::MethodHandleType::kInvokeInterface: {
9575 kind = mirror::MethodHandle::Kind::kInvokeInterface;
9576 receiver_count = 1;
Vladimir Markoba118822017-06-12 15:41:56 +01009577 target_method = ResolveMethod<ResolveMode::kNoChecks>(self,
9578 method_handle.field_or_method_idx_,
9579 referrer,
9580 InvokeType::kInterface);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009581 break;
9582 }
Orion Hodson631827d2017-04-10 14:53:47 +01009583 }
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009584
9585 if (UNLIKELY(target_method == nullptr)) {
9586 DCHECK(Thread::Current()->IsExceptionPending());
9587 return nullptr;
9588 }
9589
9590 ObjPtr<mirror::Class> target_class = target_method->GetDeclaringClass();
9591 ObjPtr<mirror::Class> referring_class = referrer->GetDeclaringClass();
9592 uint32_t access_flags = target_method->GetAccessFlags();
9593 if (UNLIKELY(!referring_class->CanAccessMember(target_class, access_flags))) {
9594 ThrowIllegalAccessErrorMethod(referring_class, target_method);
9595 return nullptr;
9596 }
9597
9598 // Calculate the number of parameters from the method shorty. We add the
9599 // receiver count (0 or 1) and deduct one for the return value.
9600 uint32_t shorty_length;
9601 target_method->GetShorty(&shorty_length);
9602 int32_t num_params = static_cast<int32_t>(shorty_length + receiver_count - 1);
9603
Orion Hodsonecd58562018-09-24 11:27:33 +01009604 StackHandleScope<5> hs(self);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01009605 ObjPtr<mirror::Class> array_of_class = GetClassRoot<mirror::ObjectArray<mirror::Class>>(this);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009606 Handle<mirror::ObjectArray<mirror::Class>> method_params(hs.NewHandle(
9607 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, num_params)));
9608 if (method_params.Get() == nullptr) {
9609 DCHECK(self->IsExceptionPending());
9610 return nullptr;
9611 }
9612
Orion Hodsonecd58562018-09-24 11:27:33 +01009613 const DexFile* dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009614 const dex::MethodId& method_id = dex_file->GetMethodId(method_handle.field_or_method_idx_);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009615 int32_t index = 0;
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009616 if (receiver_count != 0) {
Orion Hodsonecd58562018-09-24 11:27:33 +01009617 // Insert receiver. Use the class identified in the method handle rather than the declaring
9618 // class of the resolved method which may be super class or default interface method
9619 // (b/115964401).
9620 ObjPtr<mirror::Class> receiver_class = LookupResolvedType(method_id.class_idx_, referrer);
9621 // receiver_class should have been resolved when resolving the target method.
9622 DCHECK(receiver_class != nullptr);
9623 method_params->Set(index++, receiver_class);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009624 }
Orion Hodsonecd58562018-09-24 11:27:33 +01009625
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009626 const dex::ProtoId& proto_id = dex_file->GetProtoId(method_id.proto_idx_);
Orion Hodsonecd58562018-09-24 11:27:33 +01009627 DexFileParameterIterator it(*dex_file, proto_id);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009628 while (it.HasNext()) {
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009629 DCHECK_LT(index, num_params);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009630 const dex::TypeIndex type_idx = it.GetTypeIdx();
Orion Hodsonecd58562018-09-24 11:27:33 +01009631 ObjPtr<mirror::Class> klass = ResolveType(type_idx, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009632 if (nullptr == klass) {
9633 DCHECK(self->IsExceptionPending());
9634 return nullptr;
9635 }
9636 method_params->Set(index++, klass);
9637 it.Next();
9638 }
9639
Orion Hodsonecd58562018-09-24 11:27:33 +01009640 Handle<mirror::Class> return_type =
9641 hs.NewHandle(ResolveType(proto_id.return_type_idx_, referrer));
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009642 if (UNLIKELY(return_type.IsNull())) {
9643 DCHECK(self->IsExceptionPending());
9644 return nullptr;
9645 }
9646
9647 Handle<mirror::MethodType>
9648 method_type(hs.NewHandle(mirror::MethodType::Create(self, return_type, method_params)));
9649 if (UNLIKELY(method_type.IsNull())) {
9650 DCHECK(self->IsExceptionPending());
9651 return nullptr;
9652 }
9653
9654 if (UNLIKELY(handle_type == DexFile::MethodHandleType::kInvokeConstructor)) {
9655 Handle<mirror::Class> constructor_class = hs.NewHandle(target_method->GetDeclaringClass());
9656 Handle<mirror::MethodHandlesLookup> lookup =
9657 hs.NewHandle(mirror::MethodHandlesLookup::GetDefault(self));
9658 return lookup->FindConstructor(self, constructor_class, method_type);
9659 }
9660
9661 uintptr_t target = reinterpret_cast<uintptr_t>(target_method);
9662 return mirror::MethodHandleImpl::Create(self, target, kind, method_type);
9663}
9664
Vladimir Markoaf940202017-12-08 15:01:18 +00009665ObjPtr<mirror::MethodHandle> ClassLinker::ResolveMethodHandle(Thread* self,
9666 uint32_t method_handle_idx,
9667 ArtMethod* referrer)
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009668 REQUIRES_SHARED(Locks::mutator_lock_) {
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009669 const DexFile* const dex_file = referrer->GetDexFile();
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08009670 const dex::MethodHandleItem& method_handle = dex_file->GetMethodHandle(method_handle_idx);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009671 switch (static_cast<DexFile::MethodHandleType>(method_handle.method_handle_type_)) {
9672 case DexFile::MethodHandleType::kStaticPut:
9673 case DexFile::MethodHandleType::kStaticGet:
9674 case DexFile::MethodHandleType::kInstancePut:
9675 case DexFile::MethodHandleType::kInstanceGet:
9676 return ResolveMethodHandleForField(self, method_handle, referrer);
9677 case DexFile::MethodHandleType::kInvokeStatic:
9678 case DexFile::MethodHandleType::kInvokeInstance:
9679 case DexFile::MethodHandleType::kInvokeConstructor:
9680 case DexFile::MethodHandleType::kInvokeDirect:
9681 case DexFile::MethodHandleType::kInvokeInterface:
Orion Hodsonda1cdd02018-01-31 18:08:28 +00009682 return ResolveMethodHandleForMethod(self, method_handle, referrer);
Orion Hodsonf8db2c32017-07-07 20:07:12 +01009683 }
Orion Hodsonc069a302017-01-18 09:23:12 +00009684}
9685
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009686bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
9687 return (entry_point == GetQuickResolutionStub()) ||
9688 (quick_resolution_trampoline_ == entry_point);
9689}
9690
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009691bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
9692 return (entry_point == GetQuickToInterpreterBridge()) ||
9693 (quick_to_interpreter_bridge_trampoline_ == entry_point);
9694}
9695
9696bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
9697 return (entry_point == GetQuickGenericJniStub()) ||
9698 (quick_generic_jni_trampoline_ == entry_point);
9699}
9700
David Sehra49e0532017-08-25 08:05:29 -07009701bool ClassLinker::IsJniDlsymLookupStub(const void* entry_point) const {
Vladimir Marko7dac8642019-11-06 17:09:30 +00009702 return entry_point == GetJniDlsymLookupStub() ||
9703 (jni_dlsym_lookup_trampoline_ == entry_point);
David Sehra49e0532017-08-25 08:05:29 -07009704}
9705
Vladimir Markofa458ac2020-02-12 14:08:07 +00009706bool ClassLinker::IsJniDlsymLookupCriticalStub(const void* entry_point) const {
9707 return entry_point == GetJniDlsymLookupCriticalStub() ||
9708 (jni_dlsym_lookup_critical_trampoline_ == entry_point);
9709}
9710
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009711const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
9712 return GetQuickGenericJniStub();
9713}
9714
Mathieu Chartiere401d142015-04-22 13:56:20 -07009715void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009716 if (!method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009717 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
9718 } else {
Goran Jakovljevicc16268f2017-07-27 10:03:32 +02009719 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009720 }
9721}
9722
Alex Lightdb01a092017-04-03 15:39:55 -07009723void ClassLinker::SetEntryPointsForObsoleteMethod(ArtMethod* method) const {
9724 DCHECK(method->IsObsolete());
9725 // We cannot mess with the entrypoints of native methods because they are used to determine how
9726 // large the method's quick stack frame is. Without this information we cannot walk the stacks.
9727 if (!method->IsNative()) {
9728 method->SetEntryPointFromQuickCompiledCode(GetInvokeObsoleteMethodStub());
9729 }
9730}
9731
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009732void ClassLinker::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier6b069532015-08-05 15:08:12 -07009733 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier6b069532015-08-05 15:08:12 -07009734 ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009735 os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
9736 << NumNonZygoteClasses() << "\n";
Nicolas Geoffraya90c9222018-09-07 13:19:19 +01009737 ReaderMutexLock mu2(soa.Self(), *Locks::dex_lock_);
9738 os << "Dumping registered class loaders\n";
9739 size_t class_loader_index = 0;
9740 for (const ClassLoaderData& class_loader : class_loaders_) {
9741 ObjPtr<mirror::ClassLoader> loader =
9742 ObjPtr<mirror::ClassLoader>::DownCast(soa.Self()->DecodeJObject(class_loader.weak_root));
9743 if (loader != nullptr) {
9744 os << "#" << class_loader_index++ << " " << loader->GetClass()->PrettyDescriptor() << ": [";
9745 bool saw_one_dex_file = false;
9746 for (const DexCacheData& dex_cache : dex_caches_) {
9747 if (dex_cache.IsValid() && dex_cache.class_table == class_loader.class_table) {
9748 if (saw_one_dex_file) {
9749 os << ":";
9750 }
9751 saw_one_dex_file = true;
9752 os << dex_cache.dex_file->GetLocation();
9753 }
9754 }
9755 os << "]";
9756 bool found_parent = false;
9757 if (loader->GetParent() != nullptr) {
9758 size_t parent_index = 0;
9759 for (const ClassLoaderData& class_loader2 : class_loaders_) {
9760 ObjPtr<mirror::ClassLoader> loader2 = ObjPtr<mirror::ClassLoader>::DownCast(
9761 soa.Self()->DecodeJObject(class_loader2.weak_root));
9762 if (loader2 == loader->GetParent()) {
9763 os << ", parent #" << parent_index;
9764 found_parent = true;
9765 break;
9766 }
9767 parent_index++;
9768 }
9769 if (!found_parent) {
9770 os << ", unregistered parent of type "
9771 << loader->GetParent()->GetClass()->PrettyDescriptor();
9772 }
9773 } else {
9774 os << ", no parent";
9775 }
9776 os << "\n";
9777 }
9778 }
9779 os << "Done dumping class loaders\n";
Andreas Gampe9b7f8b52019-06-07 08:59:29 -07009780 Runtime* runtime = Runtime::Current();
9781 os << "Classes initialized: " << runtime->GetStat(KIND_GLOBAL_CLASS_INIT_COUNT) << " in "
9782 << PrettyDuration(runtime->GetStat(KIND_GLOBAL_CLASS_INIT_TIME)) << "\n";
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009783}
9784
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009785class CountClassesVisitor : public ClassLoaderVisitor {
9786 public:
9787 CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
9788
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009789 void Visit(ObjPtr<mirror::ClassLoader> class_loader)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01009790 REQUIRES_SHARED(Locks::classlinker_classes_lock_, Locks::mutator_lock_) override {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009791 ClassTable* const class_table = class_loader->GetClassTable();
Mathieu Chartier6b069532015-08-05 15:08:12 -07009792 if (class_table != nullptr) {
Vladimir Markoc5798bf2016-12-09 10:20:54 +00009793 num_zygote_classes += class_table->NumZygoteClasses(class_loader);
9794 num_non_zygote_classes += class_table->NumNonZygoteClasses(class_loader);
Mathieu Chartier6b069532015-08-05 15:08:12 -07009795 }
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009796 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009797
9798 size_t num_zygote_classes;
9799 size_t num_non_zygote_classes;
9800};
9801
9802size_t ClassLinker::NumZygoteClasses() const {
9803 CountClassesVisitor visitor;
9804 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009805 return visitor.num_zygote_classes + boot_class_table_->NumZygoteClasses(nullptr);
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009806}
9807
9808size_t ClassLinker::NumNonZygoteClasses() const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -07009809 CountClassesVisitor visitor;
9810 VisitClassLoaders(&visitor);
Andreas Gampe2af99022017-04-25 08:32:59 -07009811 return visitor.num_non_zygote_classes + boot_class_table_->NumNonZygoteClasses(nullptr);
Elliott Hughescac6cc72011-11-03 20:31:21 -07009812}
9813
Ian Rogers7dfb28c2013-08-22 08:18:36 -07009814size_t ClassLinker::NumLoadedClasses() {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07009815 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08009816 // Only return non zygote classes since these are the ones which apps which care about.
Mathieu Chartiercc5ebdf2015-07-27 11:19:43 -07009817 return NumNonZygoteClasses();
Elliott Hughese27955c2011-08-26 15:21:24 -07009818}
9819
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009820pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07009821 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07009822}
9823
9824pid_t ClassLinker::GetDexLockOwner() {
Andreas Gampecc1b5352016-12-01 16:58:38 -08009825 return Locks::dex_lock_->GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07009826}
9827
Mathieu Chartier28357fa2016-10-18 16:27:40 -07009828void ClassLinker::SetClassRoot(ClassRoot class_root, ObjPtr<mirror::Class> klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009829 DCHECK(!init_done_);
9830
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009831 DCHECK(klass != nullptr);
9832 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08009833
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07009834 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07009835 DCHECK(class_roots != nullptr);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01009836 DCHECK_LT(static_cast<uint32_t>(class_root), static_cast<uint32_t>(ClassRoot::kMax));
9837 int32_t index = static_cast<int32_t>(class_root);
9838 DCHECK(class_roots->Get(index) == nullptr);
9839 class_roots->Set<false>(index, klass);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07009840}
9841
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009842ObjPtr<mirror::ClassLoader> ClassLinker::CreateWellKnownClassLoader(
9843 Thread* self,
9844 const std::vector<const DexFile*>& dex_files,
9845 Handle<mirror::Class> loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009846 Handle<mirror::ClassLoader> parent_loader,
9847 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries) {
Calin Juravle7865ac72017-06-28 11:03:12 -07009848
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009849 StackHandleScope<5> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009850
Mathieu Chartierc7853442015-03-27 14:35:38 -07009851 ArtField* dex_elements_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009852 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009853
Vladimir Marko4098a7a2017-11-06 16:00:51 +00009854 Handle<mirror::Class> dex_elements_class(hs.NewHandle(dex_elements_field->ResolveType()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009855 DCHECK(dex_elements_class != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009856 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07009857 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
Mathieu Chartier3398c782016-09-30 10:27:43 -07009858 mirror::ObjectArray<mirror::Object>::Alloc(self,
9859 dex_elements_class.Get(),
9860 dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009861 Handle<mirror::Class> h_dex_element_class =
9862 hs.NewHandle(dex_elements_class->GetComponentType());
9863
Mathieu Chartierc7853442015-03-27 14:35:38 -07009864 ArtField* element_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009865 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009866 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009867
Andreas Gampe08883de2016-11-08 13:20:52 -08009868 ArtField* cookie_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Vladimir Marko208f6702017-12-08 12:00:50 +00009869 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009870
Andreas Gampe08883de2016-11-08 13:20:52 -08009871 ArtField* file_name_field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_fileName);
Vladimir Marko208f6702017-12-08 12:00:50 +00009872 DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->LookupResolvedType());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009873
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009874 // Fill the elements array.
9875 int32_t index = 0;
9876 for (const DexFile* dex_file : dex_files) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009877 StackHandleScope<4> hs2(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009878
Calin Juravle7865ac72017-06-28 11:03:12 -07009879 // CreateWellKnownClassLoader is only used by gtests and compiler.
9880 // 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 -07009881 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
9882 self,
9883 kDexFileIndexStart + 1));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009884 DCHECK(h_long_array != nullptr);
Vladimir Marko78baed52018-10-11 10:44:58 +01009885 h_long_array->Set(kDexFileIndexStart, reinterpret_cast64<int64_t>(dex_file));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009886
Mathieu Chartier3738e982017-05-12 16:07:28 -07009887 // Note that this creates a finalizable dalvik.system.DexFile object and a corresponding
9888 // FinalizerReference which will never get cleaned up without a started runtime.
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009889 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009890 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009891 DCHECK(h_dex_file != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009892 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009893
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009894 Handle<mirror::String> h_file_name = hs2.NewHandle(
9895 mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009896 DCHECK(h_file_name != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08009897 file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
9898
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009899 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009900 DCHECK(h_element != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009901 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009902
9903 h_dex_elements->Set(index, h_element.Get());
9904 index++;
9905 }
9906 DCHECK_EQ(index, h_dex_elements->GetLength());
9907
9908 // Create DexPathList.
9909 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07009910 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampefa4333d2017-02-14 11:10:34 -08009911 DCHECK(h_dex_path_list != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009912 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009913 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe473191c2017-12-28 16:55:31 -08009914 // Create an empty List for the "nativeLibraryDirectories," required for native tests.
9915 // Note: this code is uncommon(oatdump)/testing-only, so don't add further WellKnownClasses
9916 // elements.
9917 {
9918 ArtField* native_lib_dirs = dex_elements_field->GetDeclaringClass()->
9919 FindDeclaredInstanceField("nativeLibraryDirectories", "Ljava/util/List;");
9920 DCHECK(native_lib_dirs != nullptr);
9921 ObjPtr<mirror::Class> list_class = FindSystemClass(self, "Ljava/util/ArrayList;");
9922 DCHECK(list_class != nullptr);
9923 {
9924 StackHandleScope<1> h_list_scope(self);
9925 Handle<mirror::Class> h_list_class(h_list_scope.NewHandle<mirror::Class>(list_class));
9926 bool list_init = EnsureInitialized(self, h_list_class, true, true);
9927 DCHECK(list_init);
9928 list_class = h_list_class.Get();
9929 }
9930 ObjPtr<mirror::Object> list_object = list_class->AllocObject(self);
9931 // Note: we leave the object uninitialized. This must never leak into any non-testing code, but
9932 // is fine for testing. While it violates a Java-code invariant (the elementData field is
9933 // normally never null), as long as one does not try to add elements, this will still
9934 // work.
9935 native_lib_dirs->SetObject<false>(h_dex_path_list.Get(), list_object);
9936 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009937
Calin Juravle7865ac72017-06-28 11:03:12 -07009938 // Create the class loader..
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009939 Handle<mirror::ClassLoader> h_class_loader = hs.NewHandle<mirror::ClassLoader>(
9940 ObjPtr<mirror::ClassLoader>::DownCast(loader_class->AllocObject(self)));
Calin Juravle7865ac72017-06-28 11:03:12 -07009941 DCHECK(h_class_loader != nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009942 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07009943 ArtField* path_list_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08009944 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList);
Mathieu Chartierc7853442015-03-27 14:35:38 -07009945 DCHECK(path_list_field != nullptr);
Calin Juravle7865ac72017-06-28 11:03:12 -07009946 path_list_field->SetObject<false>(h_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07009947
9948 // Make a pretend boot-classpath.
9949 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07009950 ArtField* const parent_field =
Vladimir Marko19a4d372016-12-08 14:41:46 +00009951 mirror::Class::FindField(self,
Calin Juravle7865ac72017-06-28 11:03:12 -07009952 h_class_loader->GetClass(),
Vladimir Marko19a4d372016-12-08 14:41:46 +00009953 "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07009954 "Ljava/lang/ClassLoader;");
Roland Levillainf39c9eb2015-05-26 15:02:07 +01009955 DCHECK(parent_field != nullptr);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009956 if (parent_loader.Get() == nullptr) {
9957 ScopedObjectAccessUnchecked soa(self);
9958 ObjPtr<mirror::Object> boot_loader(soa.Decode<mirror::Class>(
9959 WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self));
9960 parent_field->SetObject<false>(h_class_loader.Get(), boot_loader);
9961 } else {
9962 parent_field->SetObject<false>(h_class_loader.Get(), parent_loader.Get());
9963 }
Calin Juravle7865ac72017-06-28 11:03:12 -07009964
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009965 ArtField* shared_libraries_field =
9966 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
9967 DCHECK(shared_libraries_field != nullptr);
9968 shared_libraries_field->SetObject<false>(h_class_loader.Get(), shared_libraries.Get());
9969
9970 return h_class_loader.Get();
9971}
9972
9973jobject ClassLinker::CreateWellKnownClassLoader(Thread* self,
9974 const std::vector<const DexFile*>& dex_files,
9975 jclass loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009976 jobject parent_loader,
9977 jobject shared_libraries) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009978 CHECK(self->GetJniEnv()->IsSameObject(loader_class,
9979 WellKnownClasses::dalvik_system_PathClassLoader) ||
9980 self->GetJniEnv()->IsSameObject(loader_class,
David Brazdil1a9ac532019-03-05 11:57:13 +00009981 WellKnownClasses::dalvik_system_DelegateLastClassLoader) ||
9982 self->GetJniEnv()->IsSameObject(loader_class,
9983 WellKnownClasses::dalvik_system_InMemoryDexClassLoader));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009984
9985 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
9986 // We could move the jobject to the callers, but all call-sites do this...
9987 ScopedObjectAccessUnchecked soa(self);
9988
9989 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009990 StackHandleScope<4> hs(self);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009991
9992 Handle<mirror::Class> h_loader_class =
9993 hs.NewHandle<mirror::Class>(soa.Decode<mirror::Class>(loader_class));
Nicolas Geoffraye1672732018-11-30 01:09:49 +00009994 Handle<mirror::ClassLoader> h_parent =
9995 hs.NewHandle<mirror::ClassLoader>(soa.Decode<mirror::ClassLoader>(parent_loader));
9996 Handle<mirror::ObjectArray<mirror::ClassLoader>> h_shared_libraries =
9997 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::ClassLoader>>(shared_libraries));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +00009998
9999 ObjPtr<mirror::ClassLoader> loader = CreateWellKnownClassLoader(
10000 self,
10001 dex_files,
10002 h_loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +000010003 h_parent,
10004 h_shared_libraries);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010005
10006 // Make it a global ref and return.
10007 ScopedLocalRef<jobject> local_ref(
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000010008 soa.Env(), soa.Env()->AddLocalReference<jobject>(loader));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -070010009 return soa.Env()->NewGlobalRef(local_ref.get());
10010}
10011
Calin Juravle7865ac72017-06-28 11:03:12 -070010012jobject ClassLinker::CreatePathClassLoader(Thread* self,
10013 const std::vector<const DexFile*>& dex_files) {
10014 return CreateWellKnownClassLoader(self,
10015 dex_files,
10016 WellKnownClasses::dalvik_system_PathClassLoader,
10017 nullptr);
10018}
10019
Andreas Gampe8ac75952015-06-02 21:01:45 -070010020void ClassLinker::DropFindArrayClassCache() {
10021 std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
10022 find_array_class_cache_next_victim_ = 0;
10023}
10024
Mathieu Chartier951ec2c2015-09-22 08:50:05 -070010025void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010026 Thread* const self = Thread::Current();
Mathieu Chartier951ec2c2015-09-22 08:50:05 -070010027 for (const ClassLoaderData& data : class_loaders_) {
Mathieu Chartier4843bd52015-10-01 17:08:44 -070010028 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -070010029 ObjPtr<mirror::ClassLoader> class_loader = ObjPtr<mirror::ClassLoader>::DownCast(
10030 self->DecodeJObject(data.weak_root));
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010031 if (class_loader != nullptr) {
Vladimir Markod93e3742018-07-18 10:58:13 +010010032 visitor->Visit(class_loader);
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010033 }
10034 }
10035}
10036
Alexey Grebenkin252a4e42018-04-02 18:18:01 +030010037void ClassLinker::VisitAllocators(AllocatorVisitor* visitor) const {
10038 for (const ClassLoaderData& data : class_loaders_) {
10039 LinearAlloc* alloc = data.allocator;
10040 if (alloc != nullptr && !visitor->Visit(alloc)) {
10041 break;
10042 }
10043 }
10044}
10045
Mathieu Chartierbc5a7952016-10-17 15:46:31 -070010046void ClassLinker::InsertDexFileInToClassLoader(ObjPtr<mirror::Object> dex_file,
10047 ObjPtr<mirror::ClassLoader> class_loader) {
Mathieu Chartier00310e02015-10-17 12:46:42 -070010048 DCHECK(dex_file != nullptr);
Mathieu Chartier00310e02015-10-17 12:46:42 -070010049 Thread* const self = Thread::Current();
10050 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Markobcf17522018-06-01 13:14:32 +010010051 ClassTable* const table = ClassTableForClassLoader(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -070010052 DCHECK(table != nullptr);
Mathieu Chartierc9dbb1d2016-06-03 17:47:32 -070010053 if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
Mathieu Chartier00310e02015-10-17 12:46:42 -070010054 // It was not already inserted, perform the write barrier to let the GC know the class loader's
10055 // class table was modified.
Mathieu Chartier88ea61e2018-06-20 17:45:41 -070010056 WriteBarrier::ForEveryFieldWrite(class_loader);
Mathieu Chartier00310e02015-10-17 12:46:42 -070010057 }
10058}
10059
Mathieu Chartier951ec2c2015-09-22 08:50:05 -070010060void ClassLinker::CleanupClassLoaders() {
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010061 Thread* const self = Thread::Current();
Mathieu Chartier65975772016-08-05 10:46:36 -070010062 std::vector<ClassLoaderData> to_delete;
10063 // Do the delete outside the lock to avoid lock violation in jit code cache.
10064 {
10065 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
10066 for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
10067 const ClassLoaderData& data = *it;
10068 // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
Mathieu Chartierc4f39252016-10-05 18:32:08 -070010069 ObjPtr<mirror::ClassLoader> class_loader =
10070 ObjPtr<mirror::ClassLoader>::DownCast(self->DecodeJObject(data.weak_root));
Mathieu Chartier65975772016-08-05 10:46:36 -070010071 if (class_loader != nullptr) {
10072 ++it;
10073 } else {
10074 VLOG(class_linker) << "Freeing class loader";
10075 to_delete.push_back(data);
10076 it = class_loaders_.erase(it);
10077 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010078 }
10079 }
Mathieu Chartier65975772016-08-05 10:46:36 -070010080 for (ClassLoaderData& data : to_delete) {
Alexey Grebenkinbe4c2bd2018-02-01 19:09:59 +030010081 // CHA unloading analysis and SingleImplementaion cleanups are required.
Andreas Gampe98ea9d92018-10-19 14:06:15 -070010082 DeleteClassLoader(self, data, /*cleanup_cha=*/ true);
Mathieu Chartier65975772016-08-05 10:46:36 -070010083 }
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -070010084}
10085
Mathieu Chartier65975772016-08-05 10:46:36 -070010086class ClassLinker::FindVirtualMethodHolderVisitor : public ClassVisitor {
10087 public:
10088 FindVirtualMethodHolderVisitor(const ArtMethod* method, PointerSize pointer_size)
10089 : method_(method),
10090 pointer_size_(pointer_size) {}
10091
Roland Levillainbbc6e7e2018-08-24 16:58:47 +010010092 bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) override {
Mathieu Chartier65975772016-08-05 10:46:36 -070010093 if (klass->GetVirtualMethodsSliceUnchecked(pointer_size_).Contains(method_)) {
10094 holder_ = klass;
10095 }
10096 // Return false to stop searching if holder_ is not null.
10097 return holder_ == nullptr;
10098 }
10099
Mathieu Chartier28357fa2016-10-18 16:27:40 -070010100 ObjPtr<mirror::Class> holder_ = nullptr;
Mathieu Chartier65975772016-08-05 10:46:36 -070010101 const ArtMethod* const method_;
10102 const PointerSize pointer_size_;
10103};
10104
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010105ObjPtr<mirror::Class> ClassLinker::GetHoldingClassOfCopiedMethod(ArtMethod* method) {
Mathieu Chartier65975772016-08-05 10:46:36 -070010106 ScopedTrace trace(__FUNCTION__); // Since this function is slow, have a trace to notify people.
10107 CHECK(method->IsCopied());
10108 FindVirtualMethodHolderVisitor visitor(method, image_pointer_size_);
10109 VisitClasses(&visitor);
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010110 return visitor.holder_;
Mathieu Chartier65975772016-08-05 10:46:36 -070010111}
10112
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010113ObjPtr<mirror::IfTable> ClassLinker::AllocIfTable(Thread* self, size_t ifcount) {
10114 return ObjPtr<mirror::IfTable>::DownCast(ObjPtr<mirror::ObjectArray<mirror::Object>>(
Andreas Gampec6ea7d02017-02-01 16:46:28 -080010115 mirror::IfTable::Alloc(self,
Vladimir Markob4eb1b12018-05-24 11:09:38 +010010116 GetClassRoot<mirror::ObjectArray<mirror::Object>>(this),
Vladimir Markoa8bba7d2018-05-30 15:18:48 +010010117 ifcount * mirror::IfTable::kMax)));
Andreas Gampec6ea7d02017-02-01 16:46:28 -080010118}
10119
Vladimir Markod1f73512020-04-02 10:50:35 +010010120bool ClassLinker::IsUpdatableBootClassPathDescriptor(const char* descriptor ATTRIBUTE_UNUSED) {
10121 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10122 LOG(FATAL) << "UNREACHABLE";
10123 UNREACHABLE();
10124}
10125
Calin Juravle33787682019-07-26 14:27:18 -070010126bool ClassLinker::DenyAccessBasedOnPublicSdk(ArtMethod* art_method ATTRIBUTE_UNUSED) const
10127 REQUIRES_SHARED(Locks::mutator_lock_) {
10128 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10129 LOG(FATAL) << "UNREACHABLE";
10130 UNREACHABLE();
10131}
10132
10133bool ClassLinker::DenyAccessBasedOnPublicSdk(ArtField* art_field ATTRIBUTE_UNUSED) const
10134 REQUIRES_SHARED(Locks::mutator_lock_) {
10135 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10136 LOG(FATAL) << "UNREACHABLE";
10137 UNREACHABLE();
10138}
10139
10140bool ClassLinker::DenyAccessBasedOnPublicSdk(const char* type_descriptor ATTRIBUTE_UNUSED) const {
10141 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10142 LOG(FATAL) << "UNREACHABLE";
10143 UNREACHABLE();
10144}
10145
Calin Juravle2c2724c2021-01-14 19:54:23 -080010146void ClassLinker::SetEnablePublicSdkChecks(bool enabled ATTRIBUTE_UNUSED) {
10147 // Should not be called on ClassLinker, only on AotClassLinker that overrides this.
10148 LOG(FATAL) << "UNREACHABLE";
10149 UNREACHABLE();
10150}
10151
Roland Levillain0e840272018-08-23 19:55:30 +010010152// Instantiate ClassLinker::ResolveMethod.
Vladimir Markoba118822017-06-12 15:41:56 +010010153template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kCheckICCEAndIAE>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -080010154 uint32_t method_idx,
10155 Handle<mirror::DexCache> dex_cache,
10156 Handle<mirror::ClassLoader> class_loader,
10157 ArtMethod* referrer,
10158 InvokeType type);
Vladimir Markoba118822017-06-12 15:41:56 +010010159template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::ResolveMode::kNoChecks>(
Andreas Gampe42ef8ab2015-12-03 17:27:32 -080010160 uint32_t method_idx,
10161 Handle<mirror::DexCache> dex_cache,
10162 Handle<mirror::ClassLoader> class_loader,
10163 ArtMethod* referrer,
10164 InvokeType type);
10165
Roland Levillain0e840272018-08-23 19:55:30 +010010166// Instantiate ClassLinker::AllocClass.
Andreas Gampe98ea9d92018-10-19 14:06:15 -070010167template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ true>(
Roland Levillain0e840272018-08-23 19:55:30 +010010168 Thread* self,
10169 ObjPtr<mirror::Class> java_lang_Class,
10170 uint32_t class_size);
Andreas Gampe98ea9d92018-10-19 14:06:15 -070010171template ObjPtr<mirror::Class> ClassLinker::AllocClass</* kMovable= */ false>(
Roland Levillain0e840272018-08-23 19:55:30 +010010172 Thread* self,
10173 ObjPtr<mirror::Class> java_lang_Class,
10174 uint32_t class_size);
10175
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070010176} // namespace art