blob: 78ba26dec0ce4e228214bc093a0d23884e3a1b59 [file] [log] [blame]
Elliott Hughes8d768a92011-09-14 16:35:25 -07001/*
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 Shapirob5573532011-07-12 18:22:59 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "thread.h"
Carl Shapirob5573532011-07-12 18:22:59 -070018
Hans Boehm81dc7ab2019-04-19 17:34:31 -070019#include <limits.h> // for INT_MAX
Ian Rogersb033c752011-07-20 12:22:35 -070020#include <pthread.h>
Elliott Hughes2acf36d2012-04-17 13:30:13 -070021#include <signal.h>
Hans Boehm30bc7772022-01-28 15:07:02 -080022#include <stdlib.h>
Brian Carlstromdbf05b72011-12-15 00:55:24 -080023#include <sys/resource.h>
24#include <sys/time.h>
Elliott Hughesa0957642011-09-02 14:27:33 -070025
Evgenii Stepanov9b7656d2018-08-21 15:18:49 -070026#if __has_feature(hwaddress_sanitizer)
27#include <sanitizer/hwasan_interface.h>
28#else
29#define __hwasan_tag_pointer(p, t) (p)
30#endif
31
Carl Shapirob5573532011-07-12 18:22:59 -070032#include <algorithm>
Hans Boehm30bc7772022-01-28 15:07:02 -080033#include <atomic>
Elliott Hughesdcc24742011-09-07 14:02:44 -070034#include <bitset>
Elliott Hugheseb4f6142011-07-15 17:43:51 -070035#include <cerrno>
Elliott Hughesa0957642011-09-02 14:27:33 -070036#include <iostream>
Carl Shapirob5573532011-07-12 18:22:59 -070037#include <list>
Ian Rogersc7dd2952014-10-21 23:31:19 -070038#include <sstream>
Carl Shapirob5573532011-07-12 18:22:59 -070039
Andreas Gampe43e72432019-05-14 16:15:24 -070040#include "android-base/file.h"
Andreas Gampe46ee31b2016-12-14 10:11:49 -080041#include "android-base/stringprintf.h"
Evan Chengd57c51e2018-01-26 15:43:08 +080042#include "android-base/strings.h"
Andreas Gampe46ee31b2016-12-14 10:11:49 -080043
Mathieu Chartiera62b4532017-04-26 13:16:25 -070044#include "arch/context-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070045#include "arch/context.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070046#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070047#include "art_method-inl.h"
Charles Mungeraa31f492018-11-01 18:57:38 +000048#include "base/atomic.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010049#include "base/bit_utils.h"
Vladimir Marko78baed52018-10-11 10:44:58 +010050#include "base/casts.h"
David Sehr891a50e2017-10-27 17:01:07 -070051#include "base/file_utils.h"
Evgenii Stepanov1e133742015-05-20 12:30:59 -070052#include "base/memory_tool.h"
Elliott Hughes76b61672012-12-12 17:47:30 -080053#include "base/mutex.h"
Alex Light184f0752018-07-13 11:18:22 -070054#include "base/stl_util.h"
Steven Morelande431e272017-07-18 16:53:49 -070055#include "base/systrace.h"
Hans Boehmca834382020-08-26 21:41:13 -070056#include "base/time_utils.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080057#include "base/timing_logger.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070058#include "base/to_str.h"
David Sehrc431b9d2018-03-02 12:01:51 -080059#include "base/utils.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080060#include "class_linker-inl.h"
Vladimir Marko5868ada2020-05-12 11:50:34 +010061#include "class_root-inl.h"
Elliott Hughes46e251b2012-05-22 15:10:45 -070062#include "debugger.h"
David Sehrb2ec9f52018-02-21 13:20:31 -080063#include "dex/descriptors_names.h"
David Sehr9e734c72018-01-04 17:56:19 -080064#include "dex/dex_file-inl.h"
65#include "dex/dex_file_annotations.h"
66#include "dex/dex_file_types.h"
Ian Rogers7655f292013-07-29 11:07:13 -070067#include "entrypoints/entrypoint_utils.h"
Mathieu Chartierd8891782014-03-02 13:28:37 -080068#include "entrypoints/quick/quick_alloc_entrypoints.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070069#include "gc/accounting/card_table-inl.h"
Roland Levillain1fbd4522016-03-22 15:52:22 +000070#include "gc/accounting/heap_bitmap-inl.h"
Ian Rogerse63db272014-07-15 15:36:11 -070071#include "gc/allocator/rosalloc.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070072#include "gc/heap.h"
Mathieu Chartierd5f3f322016-03-21 14:05:56 -070073#include "gc/space/space-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070074#include "gc_root.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070075#include "handle_scope-inl.h"
Mathieu Chartierc56057e2014-05-04 13:18:58 -070076#include "indirect_reference_table-inl.h"
Andreas Gamped77abd92019-01-02 16:10:20 -080077#include "instrumentation.h"
Steven Morelande431e272017-07-18 16:53:49 -070078#include "interpreter/interpreter.h"
Vladimir Marko6ec2a1b2018-05-22 15:33:48 +010079#include "interpreter/shadow_frame-inl.h"
Andreas Gampe36a296f2017-06-13 14:11:11 -070080#include "java_frame_root_info.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010081#include "jni/java_vm_ext.h"
82#include "jni/jni_internal.h"
Andreas Gampe70f5fd02018-10-24 19:58:37 -070083#include "mirror/class-alloc-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070084#include "mirror/class_loader.h"
Andreas Gampe52ecb652018-10-24 15:18:21 -070085#include "mirror/object_array-alloc-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080086#include "mirror/object_array-inl.h"
87#include "mirror/stack_trace_element.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070088#include "monitor.h"
Andreas Gampe93104952017-12-13 17:13:15 -080089#include "monitor_objects_stack_visitor.h"
Andreas Gampe5dd44d02016-08-02 17:20:03 -070090#include "native_stack_dump.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -070091#include "nativehelper/scoped_local_ref.h"
92#include "nativehelper/scoped_utf_chars.h"
Nicolas Geoffray013d1ee2019-12-04 16:18:15 +000093#include "nterp_helpers.h"
Mingyao Yangf711f2c2016-05-23 12:29:39 -070094#include "nth_caller_visitor.h"
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +010095#include "oat_quick_method_header.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070096#include "obj_ptr-inl.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070097#include "object_lock.h"
Orion Hodson119733d2019-01-30 15:14:41 +000098#include "palette/palette.h"
Vladimir Marko7624d252014-05-02 14:40:15 +010099#include "quick/quick_method_frame_info.h"
Steven Morelande431e272017-07-18 16:53:49 -0700100#include "quick_exception_handler.h"
Andreas Gampe202f85a2017-02-06 10:23:26 -0800101#include "read_barrier-inl.h"
Jesse Wilson9a6bae82011-11-14 14:57:30 -0500102#include "reflection.h"
Alex Light55eccdf2019-10-07 13:51:13 +0000103#include "reflective_handle_scope-inl.h"
David Srbecky28f6cff2018-10-16 15:07:28 +0100104#include "runtime-inl.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700105#include "runtime.h"
Andreas Gampeac30fa22017-01-18 21:02:36 -0800106#include "runtime_callbacks.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -0700107#include "scoped_thread_state_change-inl.h"
Calin Juravle2c2724c2021-01-14 19:54:23 -0800108#include "scoped_disable_public_sdk_checker.h"
Elliott Hughes68e76522011-10-05 13:22:16 -0700109#include "stack.h"
Nicolas Geoffray6bc43742015-10-12 18:11:10 +0100110#include "stack_map.h"
Ian Rogers22d5e732014-07-15 22:23:51 -0700111#include "thread-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -0700112#include "thread_list.h"
Mathieu Chartier12d625f2015-03-13 11:33:37 -0700113#include "verifier/method_verifier.h"
Andreas Gampe90b936d2017-01-31 08:58:55 -0800114#include "verify_object.h"
Elliott Hugheseac76672012-05-24 21:56:51 -0700115#include "well_known_classes.h"
Carl Shapirob5573532011-07-12 18:22:59 -0700116
Yu Lieac44242015-06-29 10:50:03 +0800117#if ART_USE_FUTEXES
118#include "linux/futex.h"
119#include "sys/syscall.h"
120#ifndef SYS_futex
121#define SYS_futex __NR_futex
122#endif
123#endif // ART_USE_FUTEXES
124
Eric Holkf1e1dd12020-08-21 15:38:12 -0700125#pragma clang diagnostic push
126#pragma clang diagnostic error "-Wconversion"
127
Carl Shapirob5573532011-07-12 18:22:59 -0700128namespace art {
129
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800130using android::base::StringAppendV;
131using android::base::StringPrintf;
132
Mingyao Yangf711f2c2016-05-23 12:29:39 -0700133extern "C" NO_RETURN void artDeoptimize(Thread* self);
134
Ian Rogers0878d652013-04-18 17:38:35 -0700135bool Thread::is_started_ = false;
Carl Shapirob5573532011-07-12 18:22:59 -0700136pthread_key_t Thread::pthread_key_self_;
Dave Allison0aded082013-11-07 13:15:11 -0800137ConditionVariable* Thread::resume_cond_ = nullptr;
Dave Allison648d7112014-07-25 16:15:27 -0700138const size_t Thread::kStackOverflowImplicitCheckSize = GetStackOverflowReservedBytes(kRuntimeISA);
Calin Juravleb2771b42016-04-07 17:09:25 +0100139bool (*Thread::is_sensitive_thread_hook_)() = nullptr;
Calin Juravle97cbc922016-04-15 16:16:35 +0100140Thread* Thread::jit_sensitive_thread_ = nullptr;
Andreas Gampe82372002019-07-24 15:42:09 -0700141#ifndef __BIONIC__
142thread_local Thread* Thread::self_tls_ = nullptr;
143#endif
Calin Juravleb2771b42016-04-07 17:09:25 +0100144
Mathieu Chartierb0026b42016-03-31 15:05:45 -0700145static constexpr bool kVerifyImageObjectsMarked = kIsDebugBuild;
Carl Shapirob5573532011-07-12 18:22:59 -0700146
Evgenii Stepanov1e133742015-05-20 12:30:59 -0700147// For implicit overflow checks we reserve an extra piece of memory at the bottom
148// of the stack (lowest memory). The higher portion of the memory
149// is protected against reads and the lower is available for use while
150// throwing the StackOverflow exception.
151constexpr size_t kStackOverflowProtectedSize = 4 * kMemoryToolStackGuardSizeScale * KB;
152
Elliott Hughes7dc51662012-05-16 14:48:43 -0700153static const char* kThreadNameDuringStartup = "<native thread without managed peer>";
154
Ian Rogers5d76c432011-10-31 21:42:49 -0700155void Thread::InitCardTable() {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700156 tlsPtr_.card_table = Runtime::Current()->GetHeap()->GetCardTable()->GetBiasedBegin();
Ian Rogers5d76c432011-10-31 21:42:49 -0700157}
158
Elliott Hughes3ea0f422012-04-16 17:01:43 -0700159static void UnimplementedEntryPoint() {
160 UNIMPLEMENTED(FATAL);
161}
162
Vladimir Markoce2a3442021-11-24 15:10:26 +0000163void InitEntryPoints(JniEntryPoints* jpoints,
164 QuickEntryPoints* qpoints,
165 bool monitor_jni_entry_exit);
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700166void UpdateReadBarrierEntrypoints(QuickEntryPoints* qpoints, bool is_active);
Mathieu Chartierfe814e82016-11-09 14:32:49 -0800167
168void Thread::SetIsGcMarkingAndUpdateEntrypoints(bool is_marking) {
169 CHECK(kUseReadBarrier);
170 tls32_.is_gc_marking = is_marking;
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700171 UpdateReadBarrierEntrypoints(&tlsPtr_.quick_entrypoints, /* is_active= */ is_marking);
Mathieu Chartierfe814e82016-11-09 14:32:49 -0800172}
Ian Rogers7655f292013-07-29 11:07:13 -0700173
Ian Rogers848871b2013-08-05 10:56:33 -0700174void Thread::InitTlsEntryPoints() {
Mathieu Chartier3a0cd342018-12-13 13:45:17 -0800175 ScopedTrace trace("InitTlsEntryPoints");
Elliott Hughes3ea0f422012-04-16 17:01:43 -0700176 // Insert a placeholder so we can easily tell if we call an unimplemented entry point.
Andreas Gampe3cfa4d02015-10-06 17:04:01 -0700177 uintptr_t* begin = reinterpret_cast<uintptr_t*>(&tlsPtr_.jni_entrypoints);
Mathieu Chartier5ace2012016-11-30 10:15:41 -0800178 uintptr_t* end = reinterpret_cast<uintptr_t*>(
179 reinterpret_cast<uint8_t*>(&tlsPtr_.quick_entrypoints) + sizeof(tlsPtr_.quick_entrypoints));
Ian Rogers7655f292013-07-29 11:07:13 -0700180 for (uintptr_t* it = begin; it != end; ++it) {
181 *it = reinterpret_cast<uintptr_t>(UnimplementedEntryPoint);
182 }
Vladimir Markoce2a3442021-11-24 15:10:26 +0000183 bool monitor_jni_entry_exit = false;
184 PaletteShouldReportJniInvocations(&monitor_jni_entry_exit);
185 if (monitor_jni_entry_exit) {
186 AtomicSetFlag(ThreadFlag::kMonitorJniEntryExit);
187 }
188 InitEntryPoints(&tlsPtr_.jni_entrypoints, &tlsPtr_.quick_entrypoints, monitor_jni_entry_exit);
Elliott Hughesc0f09332012-03-26 13:27:06 -0700189}
190
Lokesh Gidra7e678d32020-04-28 16:17:49 -0700191void Thread::ResetQuickAllocEntryPointsForThread() {
192 ResetQuickAllocEntryPoints(&tlsPtr_.quick_entrypoints);
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700193}
194
Sebastien Hertz07474662015-08-25 15:12:33 +0000195class DeoptimizationContextRecord {
Sebastien Hertzf7958692015-06-09 14:09:14 +0200196 public:
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100197 DeoptimizationContextRecord(const JValue& ret_val,
198 bool is_reference,
199 bool from_code,
Mathieu Chartierf5769e12017-01-10 15:54:41 -0800200 ObjPtr<mirror::Throwable> pending_exception,
Mingyao Yang2ee17902017-08-30 11:37:08 -0700201 DeoptimizationMethodType method_type,
Sebastien Hertz07474662015-08-25 15:12:33 +0000202 DeoptimizationContextRecord* link)
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100203 : ret_val_(ret_val),
204 is_reference_(is_reference),
205 from_code_(from_code),
Mathieu Chartierf5769e12017-01-10 15:54:41 -0800206 pending_exception_(pending_exception.Ptr()),
Mingyao Yang2ee17902017-08-30 11:37:08 -0700207 deopt_method_type_(method_type),
Sebastien Hertz07474662015-08-25 15:12:33 +0000208 link_(link) {}
Sebastien Hertzf7958692015-06-09 14:09:14 +0200209
210 JValue GetReturnValue() const { return ret_val_; }
211 bool IsReference() const { return is_reference_; }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100212 bool GetFromCode() const { return from_code_; }
Mathieu Chartierf5769e12017-01-10 15:54:41 -0800213 ObjPtr<mirror::Throwable> GetPendingException() const { return pending_exception_; }
Sebastien Hertz07474662015-08-25 15:12:33 +0000214 DeoptimizationContextRecord* GetLink() const { return link_; }
215 mirror::Object** GetReturnValueAsGCRoot() {
Sebastien Hertzf7958692015-06-09 14:09:14 +0200216 DCHECK(is_reference_);
217 return ret_val_.GetGCRoot();
218 }
Sebastien Hertz07474662015-08-25 15:12:33 +0000219 mirror::Object** GetPendingExceptionAsGCRoot() {
220 return reinterpret_cast<mirror::Object**>(&pending_exception_);
221 }
Mingyao Yang2ee17902017-08-30 11:37:08 -0700222 DeoptimizationMethodType GetDeoptimizationMethodType() const {
223 return deopt_method_type_;
224 }
Sebastien Hertzf7958692015-06-09 14:09:14 +0200225
226 private:
Sebastien Hertz07474662015-08-25 15:12:33 +0000227 // The value returned by the method at the top of the stack before deoptimization.
Sebastien Hertzf7958692015-06-09 14:09:14 +0200228 JValue ret_val_;
Sebastien Hertz54b62482015-08-20 12:07:57 +0200229
Sebastien Hertz07474662015-08-25 15:12:33 +0000230 // Indicates whether the returned value is a reference. If so, the GC will visit it.
231 const bool is_reference_;
232
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100233 // Whether the context was created from an explicit deoptimization in the code.
234 const bool from_code_;
235
Sebastien Hertz07474662015-08-25 15:12:33 +0000236 // The exception that was pending before deoptimization (or null if there was no pending
237 // exception).
238 mirror::Throwable* pending_exception_;
239
Mingyao Yang2ee17902017-08-30 11:37:08 -0700240 // Whether the context was created for an (idempotent) runtime method.
241 const DeoptimizationMethodType deopt_method_type_;
242
Sebastien Hertz07474662015-08-25 15:12:33 +0000243 // A link to the previous DeoptimizationContextRecord.
244 DeoptimizationContextRecord* const link_;
245
246 DISALLOW_COPY_AND_ASSIGN(DeoptimizationContextRecord);
Sebastien Hertzf7958692015-06-09 14:09:14 +0200247};
248
249class StackedShadowFrameRecord {
250 public:
251 StackedShadowFrameRecord(ShadowFrame* shadow_frame,
252 StackedShadowFrameType type,
253 StackedShadowFrameRecord* link)
254 : shadow_frame_(shadow_frame),
255 type_(type),
256 link_(link) {}
257
258 ShadowFrame* GetShadowFrame() const { return shadow_frame_; }
259 StackedShadowFrameType GetType() const { return type_; }
260 StackedShadowFrameRecord* GetLink() const { return link_; }
261
262 private:
263 ShadowFrame* const shadow_frame_;
264 const StackedShadowFrameType type_;
265 StackedShadowFrameRecord* const link_;
266
267 DISALLOW_COPY_AND_ASSIGN(StackedShadowFrameRecord);
268};
269
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100270void Thread::PushDeoptimizationContext(const JValue& return_value,
271 bool is_reference,
Mingyao Yang2ee17902017-08-30 11:37:08 -0700272 ObjPtr<mirror::Throwable> exception,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100273 bool from_code,
Mingyao Yang2ee17902017-08-30 11:37:08 -0700274 DeoptimizationMethodType method_type) {
Sebastien Hertz07474662015-08-25 15:12:33 +0000275 DeoptimizationContextRecord* record = new DeoptimizationContextRecord(
276 return_value,
277 is_reference,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100278 from_code,
Sebastien Hertz07474662015-08-25 15:12:33 +0000279 exception,
Mingyao Yang2ee17902017-08-30 11:37:08 -0700280 method_type,
Sebastien Hertz07474662015-08-25 15:12:33 +0000281 tlsPtr_.deoptimization_context_stack);
282 tlsPtr_.deoptimization_context_stack = record;
buzbee3ea4ec52011-08-22 17:37:19 -0700283}
284
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100285void Thread::PopDeoptimizationContext(JValue* result,
Mathieu Chartierf5769e12017-01-10 15:54:41 -0800286 ObjPtr<mirror::Throwable>* exception,
Mingyao Yang2ee17902017-08-30 11:37:08 -0700287 bool* from_code,
288 DeoptimizationMethodType* method_type) {
Sebastien Hertz07474662015-08-25 15:12:33 +0000289 AssertHasDeoptimizationContext();
290 DeoptimizationContextRecord* record = tlsPtr_.deoptimization_context_stack;
291 tlsPtr_.deoptimization_context_stack = record->GetLink();
292 result->SetJ(record->GetReturnValue().GetJ());
293 *exception = record->GetPendingException();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100294 *from_code = record->GetFromCode();
Mingyao Yang2ee17902017-08-30 11:37:08 -0700295 *method_type = record->GetDeoptimizationMethodType();
Mingyao Yang1f2d3ba2015-05-18 12:12:50 -0700296 delete record;
Sebastien Hertz07474662015-08-25 15:12:33 +0000297}
298
299void Thread::AssertHasDeoptimizationContext() {
300 CHECK(tlsPtr_.deoptimization_context_stack != nullptr)
301 << "No deoptimization context for thread " << *this;
Ian Rogers306057f2012-11-26 12:45:53 -0800302}
303
Charles Mungeraa31f492018-11-01 18:57:38 +0000304enum {
305 kPermitAvailable = 0, // Incrementing consumes the permit
306 kNoPermit = 1, // Incrementing marks as waiter waiting
307 kNoPermitWaiterWaiting = 2
308};
309
310void Thread::Park(bool is_absolute, int64_t time) {
311 DCHECK(this == Thread::Current());
312#if ART_USE_FUTEXES
313 // Consume the permit, or mark as waiting. This cannot cause park_state to go
314 // outside of its valid range (0, 1, 2), because in all cases where 2 is
315 // assigned it is set back to 1 before returning, and this method cannot run
316 // concurrently with itself since it operates on the current thread.
317 int old_state = tls32_.park_state_.fetch_add(1, std::memory_order_relaxed);
318 if (old_state == kNoPermit) {
319 // no permit was available. block thread until later.
Charles Munger5cc0e752018-11-09 12:30:46 -0800320 Runtime::Current()->GetRuntimeCallbacks()->ThreadParkStart(is_absolute, time);
Charles Munger5cc0e752018-11-09 12:30:46 -0800321 bool timed_out = false;
Charles Mungeraa31f492018-11-01 18:57:38 +0000322 if (!is_absolute && time == 0) {
323 // Thread.getState() is documented to return waiting for untimed parks.
324 ScopedThreadSuspension sts(this, ThreadState::kWaiting);
325 DCHECK_EQ(NumberOfHeldMutexes(), 0u);
Charles Mungered19c672019-02-21 15:32:32 -0800326 int result = futex(tls32_.park_state_.Address(),
Charles Mungeraa31f492018-11-01 18:57:38 +0000327 FUTEX_WAIT_PRIVATE,
328 /* sleep if val = */ kNoPermitWaiterWaiting,
329 /* timeout */ nullptr,
330 nullptr,
331 0);
Charles Mungered19c672019-02-21 15:32:32 -0800332 // This errno check must happen before the scope is closed, to ensure that
333 // no destructors (such as ScopedThreadSuspension) overwrite errno.
334 if (result == -1) {
335 switch (errno) {
336 case EAGAIN:
337 FALLTHROUGH_INTENDED;
338 case EINTR: break; // park() is allowed to spuriously return
339 default: PLOG(FATAL) << "Failed to park";
340 }
341 }
Charles Mungeraa31f492018-11-01 18:57:38 +0000342 } else if (time > 0) {
343 // Only actually suspend and futex_wait if we're going to wait for some
344 // positive amount of time - the kernel will reject negative times with
345 // EINVAL, and a zero time will just noop.
346
347 // Thread.getState() is documented to return timed wait for timed parks.
348 ScopedThreadSuspension sts(this, ThreadState::kTimedWaiting);
349 DCHECK_EQ(NumberOfHeldMutexes(), 0u);
350 timespec timespec;
Charles Mungered19c672019-02-21 15:32:32 -0800351 int result = 0;
Charles Mungeraa31f492018-11-01 18:57:38 +0000352 if (is_absolute) {
353 // Time is millis when scheduled for an absolute time
354 timespec.tv_nsec = (time % 1000) * 1000000;
Hans Boehm33701432020-08-19 15:05:03 -0700355 timespec.tv_sec = SaturatedTimeT(time / 1000);
Charles Mungeraa31f492018-11-01 18:57:38 +0000356 // This odd looking pattern is recommended by futex documentation to
357 // wait until an absolute deadline, with otherwise identical behavior to
358 // FUTEX_WAIT_PRIVATE. This also allows parkUntil() to return at the
359 // correct time when the system clock changes.
360 result = futex(tls32_.park_state_.Address(),
361 FUTEX_WAIT_BITSET_PRIVATE | FUTEX_CLOCK_REALTIME,
362 /* sleep if val = */ kNoPermitWaiterWaiting,
363 &timespec,
364 nullptr,
Eric Holkf1e1dd12020-08-21 15:38:12 -0700365 static_cast<int>(FUTEX_BITSET_MATCH_ANY));
Charles Mungeraa31f492018-11-01 18:57:38 +0000366 } else {
367 // Time is nanos when scheduled for a relative time
Hans Boehm33701432020-08-19 15:05:03 -0700368 timespec.tv_sec = SaturatedTimeT(time / 1000000000);
Charles Mungeraa31f492018-11-01 18:57:38 +0000369 timespec.tv_nsec = time % 1000000000;
370 result = futex(tls32_.park_state_.Address(),
371 FUTEX_WAIT_PRIVATE,
372 /* sleep if val = */ kNoPermitWaiterWaiting,
373 &timespec,
374 nullptr,
375 0);
376 }
Charles Mungered19c672019-02-21 15:32:32 -0800377 // This errno check must happen before the scope is closed, to ensure that
378 // no destructors (such as ScopedThreadSuspension) overwrite errno.
379 if (result == -1) {
380 switch (errno) {
381 case ETIMEDOUT:
382 timed_out = true;
383 FALLTHROUGH_INTENDED;
384 case EAGAIN:
385 case EINTR: break; // park() is allowed to spuriously return
386 default: PLOG(FATAL) << "Failed to park";
387 }
Charles Mungeraa31f492018-11-01 18:57:38 +0000388 }
389 }
390 // Mark as no longer waiting, and consume permit if there is one.
391 tls32_.park_state_.store(kNoPermit, std::memory_order_relaxed);
392 // TODO: Call to signal jvmti here
Charles Munger5cc0e752018-11-09 12:30:46 -0800393 Runtime::Current()->GetRuntimeCallbacks()->ThreadParkFinished(timed_out);
Charles Mungeraa31f492018-11-01 18:57:38 +0000394 } else {
395 // the fetch_add has consumed the permit. immediately return.
396 DCHECK_EQ(old_state, kPermitAvailable);
397 }
398#else
399 #pragma clang diagnostic push
400 #pragma clang diagnostic warning "-W#warnings"
401 #warning "LockSupport.park/unpark implemented as noops without FUTEX support."
402 #pragma clang diagnostic pop
403 UNUSED(is_absolute, time);
404 UNIMPLEMENTED(WARNING);
405 sched_yield();
406#endif
407}
408
409void Thread::Unpark() {
410#if ART_USE_FUTEXES
411 // Set permit available; will be consumed either by fetch_add (when the thread
412 // tries to park) or store (when the parked thread is woken up)
413 if (tls32_.park_state_.exchange(kPermitAvailable, std::memory_order_relaxed)
414 == kNoPermitWaiterWaiting) {
415 int result = futex(tls32_.park_state_.Address(),
416 FUTEX_WAKE_PRIVATE,
417 /* number of waiters = */ 1,
418 nullptr,
419 nullptr,
420 0);
421 if (result == -1) {
422 PLOG(FATAL) << "Failed to unpark";
423 }
424 }
425#else
426 UNIMPLEMENTED(WARNING);
427#endif
428}
429
Mingyao Yang1f2d3ba2015-05-18 12:12:50 -0700430void Thread::PushStackedShadowFrame(ShadowFrame* sf, StackedShadowFrameType type) {
431 StackedShadowFrameRecord* record = new StackedShadowFrameRecord(
432 sf, type, tlsPtr_.stacked_shadow_frame_record);
433 tlsPtr_.stacked_shadow_frame_record = record;
Ian Rogers306057f2012-11-26 12:45:53 -0800434}
435
Andreas Gampe639bdd12015-06-03 11:22:45 -0700436ShadowFrame* Thread::PopStackedShadowFrame(StackedShadowFrameType type, bool must_be_present) {
Mingyao Yang1f2d3ba2015-05-18 12:12:50 -0700437 StackedShadowFrameRecord* record = tlsPtr_.stacked_shadow_frame_record;
Andreas Gampe639bdd12015-06-03 11:22:45 -0700438 if (must_be_present) {
439 DCHECK(record != nullptr);
Andreas Gampe639bdd12015-06-03 11:22:45 -0700440 } else {
441 if (record == nullptr || record->GetType() != type) {
442 return nullptr;
443 }
444 }
Mingyao Yang1f2d3ba2015-05-18 12:12:50 -0700445 tlsPtr_.stacked_shadow_frame_record = record->GetLink();
446 ShadowFrame* shadow_frame = record->GetShadowFrame();
447 delete record;
448 return shadow_frame;
Andreas Gampe2a0d4ec2014-06-02 22:05:22 -0700449}
450
Mingyao Yang99170c62015-07-06 11:10:37 -0700451class FrameIdToShadowFrame {
452 public:
453 static FrameIdToShadowFrame* Create(size_t frame_id,
454 ShadowFrame* shadow_frame,
455 FrameIdToShadowFrame* next,
456 size_t num_vregs) {
457 // Append a bool array at the end to keep track of what vregs are updated by the debugger.
458 uint8_t* memory = new uint8_t[sizeof(FrameIdToShadowFrame) + sizeof(bool) * num_vregs];
459 return new (memory) FrameIdToShadowFrame(frame_id, shadow_frame, next);
460 }
461
462 static void Delete(FrameIdToShadowFrame* f) {
463 uint8_t* memory = reinterpret_cast<uint8_t*>(f);
464 delete[] memory;
465 }
466
467 size_t GetFrameId() const { return frame_id_; }
468 ShadowFrame* GetShadowFrame() const { return shadow_frame_; }
469 FrameIdToShadowFrame* GetNext() const { return next_; }
470 void SetNext(FrameIdToShadowFrame* next) { next_ = next; }
471 bool* GetUpdatedVRegFlags() {
472 return updated_vreg_flags_;
473 }
474
475 private:
476 FrameIdToShadowFrame(size_t frame_id,
477 ShadowFrame* shadow_frame,
478 FrameIdToShadowFrame* next)
479 : frame_id_(frame_id),
480 shadow_frame_(shadow_frame),
481 next_(next) {}
482
483 const size_t frame_id_;
484 ShadowFrame* const shadow_frame_;
485 FrameIdToShadowFrame* next_;
486 bool updated_vreg_flags_[0];
487
488 DISALLOW_COPY_AND_ASSIGN(FrameIdToShadowFrame);
489};
490
491static FrameIdToShadowFrame* FindFrameIdToShadowFrame(FrameIdToShadowFrame* head,
492 size_t frame_id) {
493 FrameIdToShadowFrame* found = nullptr;
494 for (FrameIdToShadowFrame* record = head; record != nullptr; record = record->GetNext()) {
495 if (record->GetFrameId() == frame_id) {
496 if (kIsDebugBuild) {
David Srbecky346fd962020-07-27 16:51:00 +0100497 // Check we have at most one record for this frame.
Mingyao Yang99170c62015-07-06 11:10:37 -0700498 CHECK(found == nullptr) << "Multiple records for the frame " << frame_id;
499 found = record;
500 } else {
501 return record;
502 }
503 }
504 }
505 return found;
506}
507
508ShadowFrame* Thread::FindDebuggerShadowFrame(size_t frame_id) {
509 FrameIdToShadowFrame* record = FindFrameIdToShadowFrame(
510 tlsPtr_.frame_id_to_shadow_frame, frame_id);
511 if (record != nullptr) {
512 return record->GetShadowFrame();
513 }
514 return nullptr;
515}
516
517// Must only be called when FindDebuggerShadowFrame(frame_id) returns non-nullptr.
518bool* Thread::GetUpdatedVRegFlags(size_t frame_id) {
519 FrameIdToShadowFrame* record = FindFrameIdToShadowFrame(
520 tlsPtr_.frame_id_to_shadow_frame, frame_id);
521 CHECK(record != nullptr);
522 return record->GetUpdatedVRegFlags();
523}
524
525ShadowFrame* Thread::FindOrCreateDebuggerShadowFrame(size_t frame_id,
526 uint32_t num_vregs,
527 ArtMethod* method,
528 uint32_t dex_pc) {
529 ShadowFrame* shadow_frame = FindDebuggerShadowFrame(frame_id);
530 if (shadow_frame != nullptr) {
531 return shadow_frame;
532 }
David Sehr709b0702016-10-13 09:12:37 -0700533 VLOG(deopt) << "Create pre-deopted ShadowFrame for " << ArtMethod::PrettyMethod(method);
Mingyao Yang99170c62015-07-06 11:10:37 -0700534 shadow_frame = ShadowFrame::CreateDeoptimizedFrame(num_vregs, nullptr, method, dex_pc);
535 FrameIdToShadowFrame* record = FrameIdToShadowFrame::Create(frame_id,
536 shadow_frame,
537 tlsPtr_.frame_id_to_shadow_frame,
538 num_vregs);
539 for (uint32_t i = 0; i < num_vregs; i++) {
540 // Do this to clear all references for root visitors.
541 shadow_frame->SetVRegReference(i, nullptr);
542 // This flag will be changed to true if the debugger modifies the value.
543 record->GetUpdatedVRegFlags()[i] = false;
544 }
545 tlsPtr_.frame_id_to_shadow_frame = record;
546 return shadow_frame;
547}
548
Alex Light184f0752018-07-13 11:18:22 -0700549TLSData* Thread::GetCustomTLS(const char* key) {
550 MutexLock mu(Thread::Current(), *Locks::custom_tls_lock_);
551 auto it = custom_tls_.find(key);
552 return (it != custom_tls_.end()) ? it->second.get() : nullptr;
553}
554
555void Thread::SetCustomTLS(const char* key, TLSData* data) {
556 // We will swap the old data (which might be nullptr) with this and then delete it outside of the
557 // custom_tls_lock_.
558 std::unique_ptr<TLSData> old_data(data);
559 {
560 MutexLock mu(Thread::Current(), *Locks::custom_tls_lock_);
561 custom_tls_.GetOrCreate(key, []() { return std::unique_ptr<TLSData>(); }).swap(old_data);
562 }
563}
564
Mingyao Yang99170c62015-07-06 11:10:37 -0700565void Thread::RemoveDebuggerShadowFrameMapping(size_t frame_id) {
566 FrameIdToShadowFrame* head = tlsPtr_.frame_id_to_shadow_frame;
567 if (head->GetFrameId() == frame_id) {
568 tlsPtr_.frame_id_to_shadow_frame = head->GetNext();
569 FrameIdToShadowFrame::Delete(head);
570 return;
571 }
572 FrameIdToShadowFrame* prev = head;
573 for (FrameIdToShadowFrame* record = head->GetNext();
574 record != nullptr;
575 prev = record, record = record->GetNext()) {
576 if (record->GetFrameId() == frame_id) {
577 prev->SetNext(record->GetNext());
578 FrameIdToShadowFrame::Delete(record);
579 return;
580 }
581 }
582 LOG(FATAL) << "No shadow frame for frame " << frame_id;
583 UNREACHABLE();
584}
585
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700586void Thread::InitTid() {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700587 tls32_.tid = ::art::GetTid();
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700588}
589
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700590void Thread::InitAfterFork() {
Elliott Hughes8029cbe2012-05-22 09:13:08 -0700591 // One thread (us) survived the fork, but we have a new tid so we need to
592 // update the value stashed in this Thread*.
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700593 InitTid();
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700594}
595
Alex Light4847a072019-12-12 16:13:47 -0800596void Thread::DeleteJPeer(JNIEnv* env) {
597 // Make sure nothing can observe both opeer and jpeer set at the same time.
598 jobject old_jpeer = tlsPtr_.jpeer;
599 CHECK(old_jpeer != nullptr);
600 tlsPtr_.jpeer = nullptr;
601 env->DeleteGlobalRef(old_jpeer);
602}
603
Brian Carlstrom78128a62011-09-15 17:21:19 -0700604void* Thread::CreateCallback(void* arg) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700605 Thread* self = reinterpret_cast<Thread*>(arg);
Ian Rogers120f1c72012-09-28 17:17:10 -0700606 Runtime* runtime = Runtime::Current();
Dave Allison0aded082013-11-07 13:15:11 -0800607 if (runtime == nullptr) {
Ian Rogers120f1c72012-09-28 17:17:10 -0700608 LOG(ERROR) << "Thread attaching to non-existent runtime: " << *self;
Dave Allison0aded082013-11-07 13:15:11 -0800609 return nullptr;
Ian Rogers120f1c72012-09-28 17:17:10 -0700610 }
611 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700612 // TODO: pass self to MutexLock - requires self to equal Thread::Current(), which is only true
613 // after self->Init().
Dave Allison0aded082013-11-07 13:15:11 -0800614 MutexLock mu(nullptr, *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700615 // Check that if we got here we cannot be shutting down (as shutdown should never have started
616 // while threads are being born).
Mathieu Chartier590fee92013-09-13 13:46:47 -0700617 CHECK(!runtime->IsShuttingDownLocked());
Andreas Gampe449357d2015-06-01 22:29:51 -0700618 // Note: given that the JNIEnv is created in the parent thread, the only failure point here is
619 // a mess in InitStackHwm. We do not have a reasonable way to recover from that, so abort
620 // the runtime in such a case. In case this ever changes, we need to make sure here to
621 // delete the tmp_jni_env, as we own it at this point.
622 CHECK(self->Init(runtime->GetThreadList(), runtime->GetJavaVM(), self->tlsPtr_.tmp_jni_env));
623 self->tlsPtr_.tmp_jni_env = nullptr;
Ian Rogers120f1c72012-09-28 17:17:10 -0700624 Runtime::Current()->EndThreadBirth();
625 }
Elliott Hughes47179f72011-10-27 16:44:39 -0700626 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700627 ScopedObjectAccess soa(self);
Jeff Hao848f70a2014-01-15 13:49:50 -0800628 self->InitStringEntryPoints();
Ian Rogerscfaa4552012-11-26 21:00:08 -0800629
630 // Copy peer into self, deleting global reference when done.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700631 CHECK(self->tlsPtr_.jpeer != nullptr);
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700632 self->tlsPtr_.opeer = soa.Decode<mirror::Object>(self->tlsPtr_.jpeer).Ptr();
Alex Light4847a072019-12-12 16:13:47 -0800633 // Make sure nothing can observe both opeer and jpeer set at the same time.
634 self->DeleteJPeer(self->GetJniEnv());
Andreas Gampe08883de2016-11-08 13:20:52 -0800635 self->SetThreadName(self->GetThreadName()->ToModifiedUtf8().c_str());
Narayan Kamatha0b34512014-10-07 12:51:26 +0100636
Andreas Gampe08883de2016-11-08 13:20:52 -0800637 ArtField* priorityField = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_priority);
Narayan Kamatha0b34512014-10-07 12:51:26 +0100638 self->SetNativePriority(priorityField->GetInt(self->tlsPtr_.opeer));
Andreas Gampe04bbb5b2017-01-19 17:49:03 +0000639
Andreas Gampeac30fa22017-01-18 21:02:36 -0800640 runtime->GetRuntimeCallbacks()->ThreadStart(self);
Ian Rogers365c1022012-06-22 15:05:28 -0700641
Charles Mungeraa31f492018-11-01 18:57:38 +0000642 // Unpark ourselves if the java peer was unparked before it started (see
643 // b/28845097#comment49 for more information)
644
645 ArtField* unparkedField = jni::DecodeArtField(
646 WellKnownClasses::java_lang_Thread_unparkedBeforeStart);
647 bool should_unpark = false;
648 {
649 // Hold the lock here, so that if another thread calls unpark before the thread starts
650 // we don't observe the unparkedBeforeStart field before the unparker writes to it,
651 // which could cause a lost unpark.
652 art::MutexLock mu(soa.Self(), *art::Locks::thread_list_lock_);
653 should_unpark = unparkedField->GetBoolean(self->tlsPtr_.opeer) == JNI_TRUE;
654 }
655 if (should_unpark) {
656 self->Unpark();
657 }
Ian Rogers365c1022012-06-22 15:05:28 -0700658 // Invoke the 'run' method of our java.lang.Thread.
Mathieu Chartierf5769e12017-01-10 15:54:41 -0800659 ObjPtr<mirror::Object> receiver = self->tlsPtr_.opeer;
Ian Rogers365c1022012-06-22 15:05:28 -0700660 jmethodID mid = WellKnownClasses::java_lang_Thread_run;
Jeff Hao39b6c242015-05-19 20:30:23 -0700661 ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(receiver));
662 InvokeVirtualOrInterfaceWithJValues(soa, ref.get(), mid, nullptr);
Elliott Hughes47179f72011-10-27 16:44:39 -0700663 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700664 // Detach and delete self.
665 Runtime::Current()->GetThreadList()->Unregister(self);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700666
Dave Allison0aded082013-11-07 13:15:11 -0800667 return nullptr;
Carl Shapirob5573532011-07-12 18:22:59 -0700668}
669
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -0700670Thread* Thread::FromManagedThread(const ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartierf5769e12017-01-10 15:54:41 -0800671 ObjPtr<mirror::Object> thread_peer) {
Andreas Gampe08883de2016-11-08 13:20:52 -0800672 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_nativePeer);
Vladimir Marko78baed52018-10-11 10:44:58 +0100673 Thread* result = reinterpret_cast64<Thread*>(f->GetLong(thread_peer));
David Srbecky346fd962020-07-27 16:51:00 +0100674 // Check that if we have a result it is either suspended or we hold the thread_list_lock_
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700675 // to stop it from going away.
Ian Rogers81d425b2012-09-27 16:03:43 -0700676 if (kIsDebugBuild) {
677 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
Dave Allison0aded082013-11-07 13:15:11 -0800678 if (result != nullptr && !result->IsSuspended()) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700679 Locks::thread_list_lock_->AssertHeld(soa.Self());
680 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700681 }
682 return result;
Elliott Hughes761928d2011-11-16 18:33:03 -0800683}
684
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -0700685Thread* Thread::FromManagedThread(const ScopedObjectAccessAlreadyRunnable& soa,
686 jobject java_thread) {
Vladimir Markobcf17522018-06-01 13:14:32 +0100687 return FromManagedThread(soa, soa.Decode<mirror::Object>(java_thread));
Elliott Hughes01158d72011-09-19 19:47:10 -0700688}
689
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700690static size_t FixStackSize(size_t stack_size) {
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700691 // A stack size of zero means "use the default".
Elliott Hughesd369bb72011-09-12 14:41:14 -0700692 if (stack_size == 0) {
693 stack_size = Runtime::Current()->GetDefaultStackSize();
694 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700695
Brian Carlstrom6414a972012-04-14 14:20:04 -0700696 // Dalvik used the bionic pthread default stack size for native threads,
697 // so include that here to support apps that expect large native stacks.
698 stack_size += 1 * MB;
699
Andreas Gampe7a55ce02018-06-19 10:07:18 -0700700 // Under sanitization, frames of the interpreter may become bigger, both for C code as
701 // well as the ShadowFrame. Ensure a larger minimum size. Otherwise initialization
702 // of all core classes cannot be done in all test circumstances.
703 if (kMemoryToolIsAvailable) {
704 stack_size = std::max(2 * MB, stack_size);
705 }
706
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700707 // It's not possible to request a stack smaller than the system-defined PTHREAD_STACK_MIN.
708 if (stack_size < PTHREAD_STACK_MIN) {
709 stack_size = PTHREAD_STACK_MIN;
710 }
711
Nicolas Geoffray541ca322022-01-20 09:03:04 +0000712 if (Runtime::Current()->GetImplicitStackOverflowChecks()) {
Dave Allisonf9439142014-03-27 15:10:22 -0700713 // If we are going to use implicit stack checks, allocate space for the protected
714 // region at the bottom of the stack.
Dave Allisonb090a182014-08-14 17:02:48 +0000715 stack_size += Thread::kStackOverflowImplicitCheckSize +
716 GetStackOverflowReservedBytes(kRuntimeISA);
Nicolas Geoffray541ca322022-01-20 09:03:04 +0000717 } else {
718 // It's likely that callers are trying to ensure they have at least a certain amount of
719 // stack space, so we should add our reserved space on top of what they requested, rather
720 // than implicitly take it away from them.
721 stack_size += GetStackOverflowReservedBytes(kRuntimeISA);
Dave Allisonf9439142014-03-27 15:10:22 -0700722 }
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700723
724 // Some systems require the stack size to be a multiple of the system page size, so round up.
725 stack_size = RoundUp(stack_size, kPageSize);
726
727 return stack_size;
728}
729
Evgenii Stepanov84a4ab82016-05-13 14:01:41 -0700730// Return the nearest page-aligned address below the current stack top.
731NO_INLINE
732static uint8_t* FindStackTop() {
733 return reinterpret_cast<uint8_t*>(
734 AlignDown(__builtin_frame_address(0), kPageSize));
735}
736
Dave Allisonf9439142014-03-27 15:10:22 -0700737// Install a protected region in the stack. This is used to trigger a SIGSEGV if a stack
Dave Allison648d7112014-07-25 16:15:27 -0700738// overflow is detected. It is located right below the stack_begin_.
Evgenii Stepanov4abf4512015-07-13 10:41:57 -0700739ATTRIBUTE_NO_SANITIZE_ADDRESS
Dave Allison648d7112014-07-25 16:15:27 -0700740void Thread::InstallImplicitProtection() {
Ian Rogers13735952014-10-08 12:43:28 -0700741 uint8_t* pregion = tlsPtr_.stack_begin - kStackOverflowProtectedSize;
Evgenii Stepanov84a4ab82016-05-13 14:01:41 -0700742 // Page containing current top of stack.
743 uint8_t* stack_top = FindStackTop();
Dave Allisonf9439142014-03-27 15:10:22 -0700744
Andreas Gampe2c2d2a02016-03-17 21:27:19 -0700745 // Try to directly protect the stack.
746 VLOG(threads) << "installing stack protected region at " << std::hex <<
747 static_cast<void*>(pregion) << " to " <<
748 static_cast<void*>(pregion + kStackOverflowProtectedSize - 1);
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700749 if (ProtectStack(/* fatal_on_error= */ false)) {
Andreas Gampe2c2d2a02016-03-17 21:27:19 -0700750 // Tell the kernel that we won't be needing these pages any more.
751 // NB. madvise will probably write zeroes into the memory (on linux it does).
Eric Holkf1e1dd12020-08-21 15:38:12 -0700752 size_t unwanted_size =
753 reinterpret_cast<uintptr_t>(stack_top) - reinterpret_cast<uintptr_t>(pregion) - kPageSize;
Andreas Gampe2c2d2a02016-03-17 21:27:19 -0700754 madvise(pregion, unwanted_size, MADV_DONTNEED);
755 return;
756 }
757
758 // There is a little complexity here that deserves a special mention. On some
759 // architectures, the stack is created using a VM_GROWSDOWN flag
760 // to prevent memory being allocated when it's not needed. This flag makes the
761 // kernel only allocate memory for the stack by growing down in memory. Because we
762 // want to put an mprotected region far away from that at the stack top, we need
763 // to make sure the pages for the stack are mapped in before we call mprotect.
764 //
765 // The failed mprotect in UnprotectStack is an indication of a thread with VM_GROWSDOWN
766 // with a non-mapped stack (usually only the main thread).
767 //
768 // We map in the stack by reading every page from the stack bottom (highest address)
769 // to the stack top. (We then madvise this away.) This must be done by reading from the
Andreas Gampe6c63f862017-06-28 17:20:15 -0700770 // current stack pointer downwards.
Andreas Gampe2c2d2a02016-03-17 21:27:19 -0700771 //
Andreas Gampe6c63f862017-06-28 17:20:15 -0700772 // Accesses too far below the current machine register corresponding to the stack pointer (e.g.,
773 // ESP on x86[-32], SP on ARM) might cause a SIGSEGV (at least on x86 with newer kernels). We
774 // thus have to move the stack pointer. We do this portably by using a recursive function with a
775 // large stack frame size.
Andreas Gampe2c2d2a02016-03-17 21:27:19 -0700776
Andreas Gampe6c63f862017-06-28 17:20:15 -0700777 // (Defensively) first remove the protection on the protected region as we'll want to read
Andreas Gampe2c2d2a02016-03-17 21:27:19 -0700778 // and write it. Ignore errors.
Dave Allison648d7112014-07-25 16:15:27 -0700779 UnprotectStack();
Dave Allison69dfe512014-07-11 17:11:58 +0000780
Andreas Gampe2c2d2a02016-03-17 21:27:19 -0700781 VLOG(threads) << "Need to map in stack for thread at " << std::hex <<
782 static_cast<void*>(pregion);
Dave Allison69dfe512014-07-11 17:11:58 +0000783
Andreas Gampe6c63f862017-06-28 17:20:15 -0700784 struct RecurseDownStack {
785 // This function has an intentionally large stack size.
786#pragma GCC diagnostic push
787#pragma GCC diagnostic ignored "-Wframe-larger-than="
788 NO_INLINE
789 static void Touch(uintptr_t target) {
790 volatile size_t zero = 0;
791 // Use a large local volatile array to ensure a large frame size. Do not use anything close
792 // to a full page for ASAN. It would be nice to ensure the frame size is at most a page, but
793 // there is no pragma support for this.
Andreas Gampe6f1c7512017-07-05 19:18:31 -0700794 // Note: for ASAN we need to shrink the array a bit, as there's other overhead.
795 constexpr size_t kAsanMultiplier =
796#ifdef ADDRESS_SANITIZER
797 2u;
798#else
799 1u;
800#endif
Stephen Hines469016b2020-01-22 17:50:41 -0800801 // Keep space uninitialized as it can overflow the stack otherwise (should Clang actually
802 // auto-initialize this local variable).
803 volatile char space[kPageSize - (kAsanMultiplier * 256)] __attribute__((uninitialized));
Andreas Gampee383d232018-06-19 12:29:51 -0700804 char sink ATTRIBUTE_UNUSED = space[zero]; // NOLINT
Evgenii Stepanov9b7656d2018-08-21 15:18:49 -0700805 // Remove tag from the pointer. Nop in non-hwasan builds.
806 uintptr_t addr = reinterpret_cast<uintptr_t>(__hwasan_tag_pointer(space, 0));
807 if (addr >= target + kPageSize) {
Andreas Gampe6c63f862017-06-28 17:20:15 -0700808 Touch(target);
809 }
810 zero *= 2; // Try to avoid tail recursion.
811 }
812#pragma GCC diagnostic pop
813 };
814 RecurseDownStack::Touch(reinterpret_cast<uintptr_t>(pregion));
Dave Allison69dfe512014-07-11 17:11:58 +0000815
Andreas Gampe2c2d2a02016-03-17 21:27:19 -0700816 VLOG(threads) << "(again) installing stack protected region at " << std::hex <<
Dave Allisonf9439142014-03-27 15:10:22 -0700817 static_cast<void*>(pregion) << " to " <<
818 static_cast<void*>(pregion + kStackOverflowProtectedSize - 1);
819
Dave Allison648d7112014-07-25 16:15:27 -0700820 // Protect the bottom of the stack to prevent read/write to it.
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700821 ProtectStack(/* fatal_on_error= */ true);
Dave Allison5cd33752014-04-15 15:57:58 -0700822
823 // Tell the kernel that we won't be needing these pages any more.
Dave Allison69dfe512014-07-11 17:11:58 +0000824 // NB. madvise will probably write zeroes into the memory (on linux it does).
Eric Holkf1e1dd12020-08-21 15:38:12 -0700825 size_t unwanted_size =
826 reinterpret_cast<uintptr_t>(stack_top) - reinterpret_cast<uintptr_t>(pregion) - kPageSize;
Dave Allison648d7112014-07-25 16:15:27 -0700827 madvise(pregion, unwanted_size, MADV_DONTNEED);
Dave Allisonf9439142014-03-27 15:10:22 -0700828}
829
Ian Rogers120f1c72012-09-28 17:17:10 -0700830void Thread::CreateNativeThread(JNIEnv* env, jobject java_peer, size_t stack_size, bool is_daemon) {
Dave Allison0aded082013-11-07 13:15:11 -0800831 CHECK(java_peer != nullptr);
Ian Rogers55256cb2017-12-21 17:07:11 -0800832 Thread* self = static_cast<JNIEnvExt*>(env)->GetSelf();
Andreas Gampe56623832015-07-09 21:53:15 -0700833
834 if (VLOG_IS_ON(threads)) {
835 ScopedObjectAccess soa(env);
836
Andreas Gampe08883de2016-11-08 13:20:52 -0800837 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_name);
Mathieu Chartier3398c782016-09-30 10:27:43 -0700838 ObjPtr<mirror::String> java_name =
839 f->GetObject(soa.Decode<mirror::Object>(java_peer))->AsString();
Andreas Gampe56623832015-07-09 21:53:15 -0700840 std::string thread_name;
841 if (java_name != nullptr) {
842 thread_name = java_name->ToModifiedUtf8();
843 } else {
844 thread_name = "(Unnamed)";
845 }
846
847 VLOG(threads) << "Creating native thread for " << thread_name;
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700848 self->Dump(LOG_STREAM(INFO));
Andreas Gampe56623832015-07-09 21:53:15 -0700849 }
850
Ian Rogers120f1c72012-09-28 17:17:10 -0700851 Runtime* runtime = Runtime::Current();
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700852
Ian Rogers120f1c72012-09-28 17:17:10 -0700853 // Atomically start the birth of the thread ensuring the runtime isn't shutting down.
854 bool thread_start_during_shutdown = false;
Elliott Hughes47179f72011-10-27 16:44:39 -0700855 {
Ian Rogers120f1c72012-09-28 17:17:10 -0700856 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700857 if (runtime->IsShuttingDownLocked()) {
Ian Rogers120f1c72012-09-28 17:17:10 -0700858 thread_start_during_shutdown = true;
859 } else {
860 runtime->StartThreadBirth();
861 }
Elliott Hughes47179f72011-10-27 16:44:39 -0700862 }
Ian Rogers120f1c72012-09-28 17:17:10 -0700863 if (thread_start_during_shutdown) {
864 ScopedLocalRef<jclass> error_class(env, env->FindClass("java/lang/InternalError"));
865 env->ThrowNew(error_class.get(), "Thread starting during runtime shutdown");
866 return;
867 }
868
869 Thread* child_thread = new Thread(is_daemon);
870 // Use global JNI ref to hold peer live while child thread starts.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700871 child_thread->tlsPtr_.jpeer = env->NewGlobalRef(java_peer);
Ian Rogers120f1c72012-09-28 17:17:10 -0700872 stack_size = FixStackSize(stack_size);
873
Roland Levillain2ae376f2018-01-30 11:35:11 +0000874 // Thread.start is synchronized, so we know that nativePeer is 0, and know that we're not racing
875 // to assign it.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800876 env->SetLongField(java_peer, WellKnownClasses::java_lang_Thread_nativePeer,
877 reinterpret_cast<jlong>(child_thread));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700878
Andreas Gampe449357d2015-06-01 22:29:51 -0700879 // Try to allocate a JNIEnvExt for the thread. We do this here as we might be out of memory and
880 // do not have a good way to report this on the child's side.
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100881 std::string error_msg;
Andreas Gampe449357d2015-06-01 22:29:51 -0700882 std::unique_ptr<JNIEnvExt> child_jni_env_ext(
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100883 JNIEnvExt::Create(child_thread, Runtime::Current()->GetJavaVM(), &error_msg));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700884
Andreas Gampe449357d2015-06-01 22:29:51 -0700885 int pthread_create_result = 0;
886 if (child_jni_env_ext.get() != nullptr) {
887 pthread_t new_pthread;
888 pthread_attr_t attr;
889 child_thread->tlsPtr_.tmp_jni_env = child_jni_env_ext.get();
890 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
891 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED),
892 "PTHREAD_CREATE_DETACHED");
893 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
894 pthread_create_result = pthread_create(&new_pthread,
895 &attr,
896 Thread::CreateCallback,
897 child_thread);
898 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
899
900 if (pthread_create_result == 0) {
901 // pthread_create started the new thread. The child is now responsible for managing the
902 // JNIEnvExt we created.
903 // Note: we can't check for tmp_jni_env == nullptr, as that would require synchronization
904 // between the threads.
Andreas Gampeafaf7f82018-10-16 11:32:38 -0700905 child_jni_env_ext.release(); // NOLINT pthreads API.
Andreas Gampe449357d2015-06-01 22:29:51 -0700906 return;
Ian Rogers120f1c72012-09-28 17:17:10 -0700907 }
Andreas Gampe449357d2015-06-01 22:29:51 -0700908 }
909
910 // Either JNIEnvExt::Create or pthread_create(3) failed, so clean up.
911 {
912 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
913 runtime->EndThreadBirth();
914 }
Alex Light4847a072019-12-12 16:13:47 -0800915 // Manually delete the global reference since Thread::Init will not have been run. Make sure
916 // nothing can observe both opeer and jpeer set at the same time.
917 child_thread->DeleteJPeer(env);
Andreas Gampe449357d2015-06-01 22:29:51 -0700918 delete child_thread;
919 child_thread = nullptr;
920 // TODO: remove from thread group?
921 env->SetLongField(java_peer, WellKnownClasses::java_lang_Thread_nativePeer, 0);
922 {
923 std::string msg(child_jni_env_ext.get() == nullptr ?
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100924 StringPrintf("Could not allocate JNI Env: %s", error_msg.c_str()) :
Andreas Gampe449357d2015-06-01 22:29:51 -0700925 StringPrintf("pthread_create (%s stack) failed: %s",
926 PrettySize(stack_size).c_str(), strerror(pthread_create_result)));
927 ScopedObjectAccess soa(env);
928 soa.Self()->ThrowOutOfMemoryError(msg.c_str());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700929 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700930}
931
Andreas Gampe449357d2015-06-01 22:29:51 -0700932bool Thread::Init(ThreadList* thread_list, JavaVMExt* java_vm, JNIEnvExt* jni_env_ext) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700933 // This function does all the initialization that must be run by the native thread it applies to.
934 // (When we create a new thread from managed code, we allocate the Thread* in Thread::Create so
935 // we can handshake with the corresponding native thread when it's ready.) Check this native
936 // thread hasn't been through here already...
Dave Allison0aded082013-11-07 13:15:11 -0800937 CHECK(Thread::Current() == nullptr);
Ian Rogersf4d4da12014-11-11 16:10:33 -0800938
939 // Set pthread_self_ ahead of pthread_setspecific, that makes Thread::Current function, this
940 // avoids pthread_self_ ever being invalid when discovered from Thread::Current().
941 tlsPtr_.pthread_self = pthread_self();
942 CHECK(is_started_);
943
Mathieu Chartier3a0cd342018-12-13 13:45:17 -0800944 ScopedTrace trace("Thread::Init");
945
Elliott Hughesd8af1592012-04-16 20:40:15 -0700946 SetUpAlternateSignalStack();
Ian Rogersf4d4da12014-11-11 16:10:33 -0800947 if (!InitStackHwm()) {
948 return false;
949 }
Elliott Hughes93e74e82011-09-13 11:07:03 -0700950 InitCpu();
Ian Rogers848871b2013-08-05 10:56:33 -0700951 InitTlsEntryPoints();
Dave Allisonb373e092014-02-20 16:06:36 -0800952 RemoveSuspendTrigger();
Ian Rogers5d76c432011-10-31 21:42:49 -0700953 InitCardTable();
Ian Rogers01ae5802012-09-28 16:14:01 -0700954 InitTid();
Ian Rogersf4d4da12014-11-11 16:10:33 -0800955
Andreas Gampea47a6e82019-07-24 09:46:16 -0700956#ifdef __BIONIC__
Andreas Gampe4382f1e2015-08-05 01:08:53 +0000957 __get_tls()[TLS_SLOT_ART_THREAD_SELF] = this;
958#else
Ian Rogers120f1c72012-09-28 17:17:10 -0700959 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach self");
Andreas Gampe82372002019-07-24 15:42:09 -0700960 Thread::self_tls_ = this;
Andreas Gampe4382f1e2015-08-05 01:08:53 +0000961#endif
Ian Rogers120f1c72012-09-28 17:17:10 -0700962 DCHECK_EQ(Thread::Current(), this);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700963
Ian Rogersdd7624d2014-03-14 17:43:00 -0700964 tls32_.thin_lock_thread_id = thread_list->AllocThreadId(this);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700965
Andreas Gampe449357d2015-06-01 22:29:51 -0700966 if (jni_env_ext != nullptr) {
Ian Rogers55256cb2017-12-21 17:07:11 -0800967 DCHECK_EQ(jni_env_ext->GetVm(), java_vm);
968 DCHECK_EQ(jni_env_ext->GetSelf(), this);
Andreas Gampe449357d2015-06-01 22:29:51 -0700969 tlsPtr_.jni_env = jni_env_ext;
970 } else {
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100971 std::string error_msg;
972 tlsPtr_.jni_env = JNIEnvExt::Create(this, java_vm, &error_msg);
Andreas Gampe449357d2015-06-01 22:29:51 -0700973 if (tlsPtr_.jni_env == nullptr) {
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100974 LOG(ERROR) << "Failed to create JNIEnvExt: " << error_msg;
Andreas Gampe449357d2015-06-01 22:29:51 -0700975 return false;
976 }
Andreas Gampe3f5881f2015-04-08 10:26:16 -0700977 }
978
Mathieu Chartier3a0cd342018-12-13 13:45:17 -0800979 ScopedTrace trace3("ThreadList::Register");
Ian Rogers120f1c72012-09-28 17:17:10 -0700980 thread_list->Register(this);
Ian Rogersf4d4da12014-11-11 16:10:33 -0800981 return true;
Elliott Hughes93e74e82011-09-13 11:07:03 -0700982}
983
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800984template <typename PeerAction>
985Thread* Thread::Attach(const char* thread_name, bool as_daemon, PeerAction peer_action) {
Ian Rogers120f1c72012-09-28 17:17:10 -0700986 Runtime* runtime = Runtime::Current();
Mathieu Chartier3a0cd342018-12-13 13:45:17 -0800987 ScopedTrace trace("Thread::Attach");
Dave Allison0aded082013-11-07 13:15:11 -0800988 if (runtime == nullptr) {
Kazuhiro Inaba9ff12512017-12-04 16:26:38 +0900989 LOG(ERROR) << "Thread attaching to non-existent runtime: " <<
990 ((thread_name != nullptr) ? thread_name : "(Unnamed)");
Dave Allison0aded082013-11-07 13:15:11 -0800991 return nullptr;
Ian Rogers120f1c72012-09-28 17:17:10 -0700992 }
Ian Rogersf4d4da12014-11-11 16:10:33 -0800993 Thread* self;
Ian Rogers120f1c72012-09-28 17:17:10 -0700994 {
Mathieu Chartier3a0cd342018-12-13 13:45:17 -0800995 ScopedTrace trace2("Thread birth");
Dave Allison0aded082013-11-07 13:15:11 -0800996 MutexLock mu(nullptr, *Locks::runtime_shutdown_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700997 if (runtime->IsShuttingDownLocked()) {
Kazuhiro Inaba9ff12512017-12-04 16:26:38 +0900998 LOG(WARNING) << "Thread attaching while runtime is shutting down: " <<
999 ((thread_name != nullptr) ? thread_name : "(Unnamed)");
Dave Allison0aded082013-11-07 13:15:11 -08001000 return nullptr;
Ian Rogers120f1c72012-09-28 17:17:10 -07001001 } else {
1002 Runtime::Current()->StartThreadBirth();
1003 self = new Thread(as_daemon);
Ian Rogersf4d4da12014-11-11 16:10:33 -08001004 bool init_success = self->Init(runtime->GetThreadList(), runtime->GetJavaVM());
Ian Rogers120f1c72012-09-28 17:17:10 -07001005 Runtime::Current()->EndThreadBirth();
Ian Rogersf4d4da12014-11-11 16:10:33 -08001006 if (!init_success) {
1007 delete self;
1008 return nullptr;
1009 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001010 }
1011 }
Elliott Hughes93e74e82011-09-13 11:07:03 -07001012
Jeff Hao848f70a2014-01-15 13:49:50 -08001013 self->InitStringEntryPoints();
1014
Vladimir Markoddf4fd32021-11-22 16:31:57 +00001015 CHECK_NE(self->GetState(), ThreadState::kRunnable);
1016 self->SetState(ThreadState::kNative);
Elliott Hughes93e74e82011-09-13 11:07:03 -07001017
Andreas Gampe732b0ac2017-01-18 15:23:39 -08001018 // Run the action that is acting on the peer.
1019 if (!peer_action(self)) {
1020 runtime->GetThreadList()->Unregister(self);
1021 // Unregister deletes self, no need to do this here.
1022 return nullptr;
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001023 }
Elliott Hughescac6cc72011-11-03 20:31:21 -07001024
Andreas Gampe56623832015-07-09 21:53:15 -07001025 if (VLOG_IS_ON(threads)) {
1026 if (thread_name != nullptr) {
1027 VLOG(threads) << "Attaching thread " << thread_name;
1028 } else {
1029 VLOG(threads) << "Attaching unnamed thread.";
1030 }
1031 ScopedObjectAccess soa(self);
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001032 self->Dump(LOG_STREAM(INFO));
Andreas Gampe56623832015-07-09 21:53:15 -07001033 }
1034
Daniel Mihalyidfafeef2014-10-20 11:47:56 +02001035 {
1036 ScopedObjectAccess soa(self);
Andreas Gampeac30fa22017-01-18 21:02:36 -08001037 runtime->GetRuntimeCallbacks()->ThreadStart(self);
Daniel Mihalyidfafeef2014-10-20 11:47:56 +02001038 }
1039
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001040 return self;
1041}
1042
Andreas Gampe732b0ac2017-01-18 15:23:39 -08001043Thread* Thread::Attach(const char* thread_name,
1044 bool as_daemon,
1045 jobject thread_group,
1046 bool create_peer) {
1047 auto create_peer_action = [&](Thread* self) {
1048 // If we're the main thread, ClassLinker won't be created until after we're attached,
1049 // so that thread needs a two-stage attach. Regular threads don't need this hack.
1050 // In the compiler, all threads need this hack, because no-one's going to be getting
1051 // a native peer!
1052 if (create_peer) {
1053 self->CreatePeer(thread_name, as_daemon, thread_group);
1054 if (self->IsExceptionPending()) {
Roland Levillain2ae376f2018-01-30 11:35:11 +00001055 // We cannot keep the exception around, as we're deleting self. Try to be helpful and log
Vladimir Marko1b3fb622021-02-08 10:54:38 +00001056 // the failure but do not dump the exception details. If we fail to allocate the peer, we
1057 // usually also fail to allocate an exception object and throw a pre-allocated OOME without
1058 // any useful information. If we do manage to allocate the exception object, the memory
1059 // information in the message could have been collected too late and therefore misleading.
Andreas Gampe732b0ac2017-01-18 15:23:39 -08001060 {
1061 ScopedObjectAccess soa(self);
Vladimir Marko1b3fb622021-02-08 10:54:38 +00001062 LOG(ERROR) << "Exception creating thread peer: "
1063 << ((thread_name != nullptr) ? thread_name : "<null>");
Andreas Gampe732b0ac2017-01-18 15:23:39 -08001064 self->ClearException();
1065 }
1066 return false;
1067 }
1068 } else {
1069 // These aren't necessary, but they improve diagnostics for unit tests & command-line tools.
1070 if (thread_name != nullptr) {
Hans Boehm30bc7772022-01-28 15:07:02 -08001071 self->SetCachedThreadName(thread_name);
Andreas Gampe732b0ac2017-01-18 15:23:39 -08001072 ::art::SetThreadName(thread_name);
Ian Rogers55256cb2017-12-21 17:07:11 -08001073 } else if (self->GetJniEnv()->IsCheckJniEnabled()) {
Andreas Gampe732b0ac2017-01-18 15:23:39 -08001074 LOG(WARNING) << *Thread::Current() << " attached without supplying a name";
1075 }
1076 }
1077 return true;
1078 };
1079 return Attach(thread_name, as_daemon, create_peer_action);
1080}
1081
1082Thread* Thread::Attach(const char* thread_name, bool as_daemon, jobject thread_peer) {
1083 auto set_peer_action = [&](Thread* self) {
1084 // Install the given peer.
1085 {
1086 DCHECK(self == Thread::Current());
1087 ScopedObjectAccess soa(self);
1088 self->tlsPtr_.opeer = soa.Decode<mirror::Object>(thread_peer).Ptr();
1089 }
1090 self->GetJniEnv()->SetLongField(thread_peer,
1091 WellKnownClasses::java_lang_Thread_nativePeer,
Vladimir Marko78baed52018-10-11 10:44:58 +01001092 reinterpret_cast64<jlong>(self));
Andreas Gampe732b0ac2017-01-18 15:23:39 -08001093 return true;
1094 };
1095 return Attach(thread_name, as_daemon, set_peer_action);
1096}
1097
Ian Rogers365c1022012-06-22 15:05:28 -07001098void Thread::CreatePeer(const char* name, bool as_daemon, jobject thread_group) {
1099 Runtime* runtime = Runtime::Current();
1100 CHECK(runtime->IsStarted());
Ian Rogersdd7624d2014-03-14 17:43:00 -07001101 JNIEnv* env = tlsPtr_.jni_env;
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001102
Dave Allison0aded082013-11-07 13:15:11 -08001103 if (thread_group == nullptr) {
Ian Rogers365c1022012-06-22 15:05:28 -07001104 thread_group = runtime->GetMainThreadGroup();
Elliott Hughes462c9442012-03-23 18:47:50 -07001105 }
Elliott Hughes726079d2011-10-07 18:43:44 -07001106 ScopedLocalRef<jobject> thread_name(env, env->NewStringUTF(name));
Mathieu Chartiere07fd172014-11-10 16:58:19 -08001107 // Add missing null check in case of OOM b/18297817
Vladimir Marko44512052014-11-12 15:41:57 +00001108 if (name != nullptr && thread_name.get() == nullptr) {
Mathieu Chartiere07fd172014-11-10 16:58:19 -08001109 CHECK(IsExceptionPending());
1110 return;
1111 }
Elliott Hughes8daa0922011-09-11 13:46:25 -07001112 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001113 jboolean thread_is_daemon = as_daemon;
1114
Elliott Hugheseac76672012-05-24 21:56:51 -07001115 ScopedLocalRef<jobject> peer(env, env->AllocObject(WellKnownClasses::java_lang_Thread));
Dave Allison0aded082013-11-07 13:15:11 -08001116 if (peer.get() == nullptr) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001117 CHECK(IsExceptionPending());
1118 return;
Ian Rogers5d4bdc22011-11-02 22:15:43 -07001119 }
Ian Rogerscfaa4552012-11-26 21:00:08 -08001120 {
1121 ScopedObjectAccess soa(this);
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07001122 tlsPtr_.opeer = soa.Decode<mirror::Object>(peer.get()).Ptr();
Ian Rogerscfaa4552012-11-26 21:00:08 -08001123 }
Elliott Hugheseac76672012-05-24 21:56:51 -07001124 env->CallNonvirtualVoidMethod(peer.get(),
1125 WellKnownClasses::java_lang_Thread,
1126 WellKnownClasses::java_lang_Thread_init,
Ian Rogers365c1022012-06-22 15:05:28 -07001127 thread_group, thread_name.get(), thread_priority, thread_is_daemon);
Andreas Gampe4b1d4ec2015-10-01 16:47:26 -07001128 if (IsExceptionPending()) {
1129 return;
1130 }
Elliott Hughesd369bb72011-09-12 14:41:14 -07001131
Ian Rogers120f1c72012-09-28 17:17:10 -07001132 Thread* self = this;
1133 DCHECK_EQ(self, Thread::Current());
Vladimir Marko78baed52018-10-11 10:44:58 +01001134 env->SetLongField(peer.get(),
1135 WellKnownClasses::java_lang_Thread_nativePeer,
1136 reinterpret_cast64<jlong>(self));
Ian Rogers120f1c72012-09-28 17:17:10 -07001137
1138 ScopedObjectAccess soa(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001139 StackHandleScope<1> hs(self);
Andreas Gampe08883de2016-11-08 13:20:52 -08001140 MutableHandle<mirror::String> peer_thread_name(hs.NewHandle(GetThreadName()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001141 if (peer_thread_name == nullptr) {
Brian Carlstrom00fae582011-10-28 01:16:28 -07001142 // The Thread constructor should have set the Thread.name to a
1143 // non-null value. However, because we can run without code
1144 // available (in the compiler, in tests), we manually assign the
1145 // fields the constructor should have set.
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001146 if (runtime->IsActiveTransaction()) {
Andreas Gampebad529d2017-02-13 18:52:10 -08001147 InitPeer<true>(soa,
1148 tlsPtr_.opeer,
1149 thread_is_daemon,
1150 thread_group,
1151 thread_name.get(),
1152 thread_priority);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001153 } else {
Andreas Gampebad529d2017-02-13 18:52:10 -08001154 InitPeer<false>(soa,
1155 tlsPtr_.opeer,
1156 thread_is_daemon,
1157 thread_group,
1158 thread_name.get(),
1159 thread_priority);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001160 }
Andreas Gampe08883de2016-11-08 13:20:52 -08001161 peer_thread_name.Assign(GetThreadName());
Brian Carlstrom00fae582011-10-28 01:16:28 -07001162 }
Elliott Hughes225f5a12012-06-11 11:23:48 -07001163 // 'thread_name' may have been null, so don't trust 'peer_thread_name' to be non-null.
Andreas Gampefa4333d2017-02-14 11:10:34 -08001164 if (peer_thread_name != nullptr) {
Elliott Hughes899e7892012-01-24 14:57:32 -08001165 SetThreadName(peer_thread_name->ToModifiedUtf8().c_str());
Brian Carlstrom00fae582011-10-28 01:16:28 -07001166 }
Carl Shapiro61e019d2011-07-14 16:53:09 -07001167}
1168
Andreas Gampebad529d2017-02-13 18:52:10 -08001169jobject Thread::CreateCompileTimePeer(JNIEnv* env,
1170 const char* name,
1171 bool as_daemon,
1172 jobject thread_group) {
1173 Runtime* runtime = Runtime::Current();
1174 CHECK(!runtime->IsStarted());
1175
1176 if (thread_group == nullptr) {
1177 thread_group = runtime->GetMainThreadGroup();
1178 }
1179 ScopedLocalRef<jobject> thread_name(env, env->NewStringUTF(name));
1180 // Add missing null check in case of OOM b/18297817
1181 if (name != nullptr && thread_name.get() == nullptr) {
1182 CHECK(Thread::Current()->IsExceptionPending());
1183 return nullptr;
1184 }
Andreas Gampea1e5b972019-03-18 16:54:25 -07001185 jint thread_priority = kNormThreadPriority; // Always normalize to NORM priority.
Andreas Gampebad529d2017-02-13 18:52:10 -08001186 jboolean thread_is_daemon = as_daemon;
1187
1188 ScopedLocalRef<jobject> peer(env, env->AllocObject(WellKnownClasses::java_lang_Thread));
1189 if (peer.get() == nullptr) {
1190 CHECK(Thread::Current()->IsExceptionPending());
1191 return nullptr;
1192 }
1193
1194 // We cannot call Thread.init, as it will recursively ask for currentThread.
1195
1196 // The Thread constructor should have set the Thread.name to a
1197 // non-null value. However, because we can run without code
1198 // available (in the compiler, in tests), we manually assign the
1199 // fields the constructor should have set.
1200 ScopedObjectAccessUnchecked soa(Thread::Current());
1201 if (runtime->IsActiveTransaction()) {
1202 InitPeer<true>(soa,
1203 soa.Decode<mirror::Object>(peer.get()),
1204 thread_is_daemon,
1205 thread_group,
1206 thread_name.get(),
1207 thread_priority);
1208 } else {
1209 InitPeer<false>(soa,
1210 soa.Decode<mirror::Object>(peer.get()),
1211 thread_is_daemon,
1212 thread_group,
1213 thread_name.get(),
1214 thread_priority);
1215 }
1216
1217 return peer.release();
1218}
1219
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001220template<bool kTransactionActive>
Andreas Gampebad529d2017-02-13 18:52:10 -08001221void Thread::InitPeer(ScopedObjectAccessAlreadyRunnable& soa,
1222 ObjPtr<mirror::Object> peer,
1223 jboolean thread_is_daemon,
1224 jobject thread_group,
1225 jobject thread_name,
1226 jint thread_priority) {
Andreas Gampe08883de2016-11-08 13:20:52 -08001227 jni::DecodeArtField(WellKnownClasses::java_lang_Thread_daemon)->
Andreas Gampebad529d2017-02-13 18:52:10 -08001228 SetBoolean<kTransactionActive>(peer, thread_is_daemon);
Andreas Gampe08883de2016-11-08 13:20:52 -08001229 jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group)->
Andreas Gampebad529d2017-02-13 18:52:10 -08001230 SetObject<kTransactionActive>(peer, soa.Decode<mirror::Object>(thread_group));
Andreas Gampe08883de2016-11-08 13:20:52 -08001231 jni::DecodeArtField(WellKnownClasses::java_lang_Thread_name)->
Andreas Gampebad529d2017-02-13 18:52:10 -08001232 SetObject<kTransactionActive>(peer, soa.Decode<mirror::Object>(thread_name));
Andreas Gampe08883de2016-11-08 13:20:52 -08001233 jni::DecodeArtField(WellKnownClasses::java_lang_Thread_priority)->
Andreas Gampebad529d2017-02-13 18:52:10 -08001234 SetInt<kTransactionActive>(peer, thread_priority);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001235}
1236
Hans Boehm30bc7772022-01-28 15:07:02 -08001237void Thread::SetCachedThreadName(const char* name) {
1238 DCHECK(name != kThreadNameDuringStartup);
1239 const char* old_name = tlsPtr_.name.exchange(name == nullptr ? nullptr : strdup(name));
1240 if (old_name != nullptr && old_name != kThreadNameDuringStartup) {
1241 // Deallocate it, carefully. Note that the load has to be ordered wrt the store of the xchg.
1242 for (uint32_t i = 0; UNLIKELY(tls32_.num_name_readers.load(std::memory_order_seq_cst) != 0);
1243 ++i) {
1244 static constexpr uint32_t kNumSpins = 1000;
1245 // Ugly, but keeps us from having to do anything on the reader side.
1246 if (i > kNumSpins) {
1247 usleep(500);
1248 }
1249 }
1250 // We saw the reader count drop to zero since we replaced the name; old one is now safe to
1251 // deallocate.
1252 free(const_cast<char *>(old_name));
1253 }
1254}
1255
Elliott Hughes899e7892012-01-24 14:57:32 -08001256void Thread::SetThreadName(const char* name) {
Hans Boehm30bc7772022-01-28 15:07:02 -08001257 SetCachedThreadName(name);
Elliott Hughes899e7892012-01-24 14:57:32 -08001258 ::art::SetThreadName(name);
1259 Dbg::DdmSendThreadNotification(this, CHUNK_TYPE("THNM"));
1260}
1261
Andreas Gampe9186ced2016-12-12 14:28:21 -08001262static void GetThreadStack(pthread_t thread,
1263 void** stack_base,
1264 size_t* stack_size,
1265 size_t* guard_size) {
1266#if defined(__APPLE__)
1267 *stack_size = pthread_get_stacksize_np(thread);
1268 void* stack_addr = pthread_get_stackaddr_np(thread);
1269
1270 // Check whether stack_addr is the base or end of the stack.
1271 // (On Mac OS 10.7, it's the end.)
1272 int stack_variable;
1273 if (stack_addr > &stack_variable) {
1274 *stack_base = reinterpret_cast<uint8_t*>(stack_addr) - *stack_size;
1275 } else {
1276 *stack_base = stack_addr;
1277 }
1278
1279 // This is wrong, but there doesn't seem to be a way to get the actual value on the Mac.
1280 pthread_attr_t attributes;
1281 CHECK_PTHREAD_CALL(pthread_attr_init, (&attributes), __FUNCTION__);
1282 CHECK_PTHREAD_CALL(pthread_attr_getguardsize, (&attributes, guard_size), __FUNCTION__);
1283 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
1284#else
1285 pthread_attr_t attributes;
1286 CHECK_PTHREAD_CALL(pthread_getattr_np, (thread, &attributes), __FUNCTION__);
1287 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, stack_base, stack_size), __FUNCTION__);
1288 CHECK_PTHREAD_CALL(pthread_attr_getguardsize, (&attributes, guard_size), __FUNCTION__);
1289 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
1290
1291#if defined(__GLIBC__)
1292 // If we're the main thread, check whether we were run with an unlimited stack. In that case,
1293 // glibc will have reported a 2GB stack for our 32-bit process, and our stack overflow detection
1294 // will be broken because we'll die long before we get close to 2GB.
Eric Holkf1e1dd12020-08-21 15:38:12 -07001295 bool is_main_thread = (::art::GetTid() == static_cast<uint32_t>(getpid()));
Andreas Gampe9186ced2016-12-12 14:28:21 -08001296 if (is_main_thread) {
1297 rlimit stack_limit;
1298 if (getrlimit(RLIMIT_STACK, &stack_limit) == -1) {
1299 PLOG(FATAL) << "getrlimit(RLIMIT_STACK) failed";
1300 }
1301 if (stack_limit.rlim_cur == RLIM_INFINITY) {
1302 size_t old_stack_size = *stack_size;
1303
1304 // Use the kernel default limit as our size, and adjust the base to match.
1305 *stack_size = 8 * MB;
1306 *stack_base = reinterpret_cast<uint8_t*>(*stack_base) + (old_stack_size - *stack_size);
1307
1308 VLOG(threads) << "Limiting unlimited stack (reported as " << PrettySize(old_stack_size) << ")"
1309 << " to " << PrettySize(*stack_size)
1310 << " with base " << *stack_base;
1311 }
1312 }
1313#endif
1314
1315#endif
1316}
1317
Ian Rogersf4d4da12014-11-11 16:10:33 -08001318bool Thread::InitStackHwm() {
Mathieu Chartier3a0cd342018-12-13 13:45:17 -08001319 ScopedTrace trace("InitStackHwm");
Ian Rogersdd7624d2014-03-14 17:43:00 -07001320 void* read_stack_base;
1321 size_t read_stack_size;
Elliott Hughes6d3fc562014-08-27 11:47:01 -07001322 size_t read_guard_size;
1323 GetThreadStack(tlsPtr_.pthread_self, &read_stack_base, &read_stack_size, &read_guard_size);
Elliott Hughes36ecb782012-04-17 16:55:45 -07001324
Ian Rogers13735952014-10-08 12:43:28 -07001325 tlsPtr_.stack_begin = reinterpret_cast<uint8_t*>(read_stack_base);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001326 tlsPtr_.stack_size = read_stack_size;
Elliott Hughes36ecb782012-04-17 16:55:45 -07001327
Dave Allison648d7112014-07-25 16:15:27 -07001328 // The minimum stack size we can cope with is the overflow reserved bytes (typically
1329 // 8K) + the protected region size (4K) + another page (4K). Typically this will
1330 // be 8+4+4 = 16K. The thread won't be able to do much with this stack even the GC takes
1331 // between 8K and 12K.
1332 uint32_t min_stack = GetStackOverflowReservedBytes(kRuntimeISA) + kStackOverflowProtectedSize
1333 + 4 * KB;
1334 if (read_stack_size <= min_stack) {
Ian Rogersf4d4da12014-11-11 16:10:33 -08001335 // Note, as we know the stack is small, avoid operations that could use a lot of stack.
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001336 LogHelper::LogLineLowStack(__PRETTY_FUNCTION__,
1337 __LINE__,
1338 ::android::base::ERROR,
1339 "Attempt to attach a thread with a too-small stack");
Ian Rogersf4d4da12014-11-11 16:10:33 -08001340 return false;
Elliott Hughesbe759c62011-09-08 19:38:21 -07001341 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -07001342
Vladimir Markob8f2f632015-01-02 14:23:26 +00001343 // This is included in the SIGQUIT output, but it's useful here for thread debugging.
1344 VLOG(threads) << StringPrintf("Native stack is at %p (%s with %s guard)",
1345 read_stack_base,
1346 PrettySize(read_stack_size).c_str(),
1347 PrettySize(read_guard_size).c_str());
1348
Ian Rogers932746a2011-09-22 18:57:50 -07001349 // Set stack_end_ to the bottom of the stack saving space of stack overflows
Mathieu Chartier8e219ae2014-08-19 14:29:46 -07001350
1351 Runtime* runtime = Runtime::Current();
Nicolas Geoffray541ca322022-01-20 09:03:04 +00001352 bool implicit_stack_check =
1353 runtime->GetImplicitStackOverflowChecks() && !runtime->IsAotCompiler();
Andreas Gampe7df12cb2016-06-10 20:38:55 -07001354
Dave Allisonb090a182014-08-14 17:02:48 +00001355 ResetDefaultStackEnd();
Dave Allisonf9439142014-03-27 15:10:22 -07001356
1357 // Install the protected region if we are doing implicit overflow checks.
Roland Levillain05e34f42018-05-24 13:19:05 +00001358 if (implicit_stack_check) {
Dave Allison648d7112014-07-25 16:15:27 -07001359 // The thread might have protected region at the bottom. We need
1360 // to install our own region so we need to move the limits
1361 // of the stack to make room for it.
Dave Allison216cf232014-08-18 15:49:51 -07001362
Elliott Hughes6d3fc562014-08-27 11:47:01 -07001363 tlsPtr_.stack_begin += read_guard_size + kStackOverflowProtectedSize;
1364 tlsPtr_.stack_end += read_guard_size + kStackOverflowProtectedSize;
Vladimir Markocedec9d2021-02-08 16:16:13 +00001365 tlsPtr_.stack_size -= read_guard_size + kStackOverflowProtectedSize;
Dave Allison648d7112014-07-25 16:15:27 -07001366
1367 InstallImplicitProtection();
Dave Allisonf9439142014-03-27 15:10:22 -07001368 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -07001369
David Srbecky346fd962020-07-27 16:51:00 +01001370 // Consistency check.
Andreas Gampeb87c03f2016-06-10 20:34:55 -07001371 CHECK_GT(FindStackTop(), reinterpret_cast<void*>(tlsPtr_.stack_end));
Ian Rogersf4d4da12014-11-11 16:10:33 -08001372
1373 return true;
Elliott Hughesbe759c62011-09-08 19:38:21 -07001374}
1375
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001376void Thread::ShortDump(std::ostream& os) const {
1377 os << "Thread[";
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001378 if (GetThreadId() != 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001379 // If we're in kStarting, we won't have a thin lock id or tid yet.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001380 os << GetThreadId()
Mathieu Chartierb28412e2015-04-24 15:28:36 -07001381 << ",tid=" << GetTid() << ',';
Elliott Hughese0918552011-10-28 17:18:29 -07001382 }
Hans Boehm30bc7772022-01-28 15:07:02 -08001383 tls32_.num_name_readers.fetch_add(1, std::memory_order_seq_cst);
1384 const char* name = tlsPtr_.name.load();
Ian Rogers474b6da2012-09-25 00:20:38 -07001385 os << GetState()
Mathieu Chartierb28412e2015-04-24 15:28:36 -07001386 << ",Thread*=" << this
1387 << ",peer=" << tlsPtr_.opeer
Hans Boehm30bc7772022-01-28 15:07:02 -08001388 << ",\"" << (name == nullptr ? "null" : name) << "\""
Mathieu Chartierb28412e2015-04-24 15:28:36 -07001389 << "]";
Hans Boehm30bc7772022-01-28 15:07:02 -08001390 tls32_.num_name_readers.fetch_sub(1 /* at least memory_order_release */);
Elliott Hughesa0957642011-09-02 14:27:33 -07001391}
1392
Nicolas Geoffray6ee49712018-03-30 14:39:05 +00001393void Thread::Dump(std::ostream& os, bool dump_native_stack, BacktraceMap* backtrace_map,
1394 bool force_dump_stack) const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001395 DumpState(os);
Nicolas Geoffray6ee49712018-03-30 14:39:05 +00001396 DumpStack(os, dump_native_stack, backtrace_map, force_dump_stack);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001397}
1398
Vladimir Marko4617d582019-03-28 13:48:31 +00001399ObjPtr<mirror::String> Thread::GetThreadName() const {
Andreas Gampe08883de2016-11-08 13:20:52 -08001400 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_name);
Mathieu Chartier3398c782016-09-30 10:27:43 -07001401 if (tlsPtr_.opeer == nullptr) {
1402 return nullptr;
1403 }
1404 ObjPtr<mirror::Object> name = f->GetObject(tlsPtr_.opeer);
1405 return name == nullptr ? nullptr : name->AsString();
Elliott Hughesfc861622011-10-17 17:57:47 -07001406}
1407
Elliott Hughesffb465f2012-03-01 18:46:05 -08001408void Thread::GetThreadName(std::string& name) const {
Hans Boehm30bc7772022-01-28 15:07:02 -08001409 tls32_.num_name_readers.fetch_add(1, std::memory_order_seq_cst);
1410 // The store part of the increment has to be ordered with respect to the following load.
1411 name.assign(tlsPtr_.name.load(std::memory_order_seq_cst));
1412 tls32_.num_name_readers.fetch_sub(1 /* at least memory_order_release */);
Elliott Hughesffb465f2012-03-01 18:46:05 -08001413}
1414
Jeff Hao57dac6e2013-08-15 16:36:24 -07001415uint64_t Thread::GetCpuMicroTime() const {
Elliott Hughes0a18df82015-01-09 15:16:16 -08001416#if defined(__linux__)
Jeff Hao57dac6e2013-08-15 16:36:24 -07001417 clockid_t cpu_clock_id;
Ian Rogersdd7624d2014-03-14 17:43:00 -07001418 pthread_getcpuclockid(tlsPtr_.pthread_self, &cpu_clock_id);
Jeff Hao57dac6e2013-08-15 16:36:24 -07001419 timespec now;
1420 clock_gettime(cpu_clock_id, &now);
Eric Holkf1e1dd12020-08-21 15:38:12 -07001421 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000) +
1422 static_cast<uint64_t>(now.tv_nsec) / UINT64_C(1000);
Elliott Hughes0a18df82015-01-09 15:16:16 -08001423#else // __APPLE__
Jeff Hao57dac6e2013-08-15 16:36:24 -07001424 UNIMPLEMENTED(WARNING);
1425 return -1;
1426#endif
1427}
1428
Ian Rogers01ae5802012-09-28 16:14:01 -07001429// Attempt to rectify locks so that we dump thread list with required locks before exiting.
1430static void UnsafeLogFatalForSuspendCount(Thread* self, Thread* thread) NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers120f1c72012-09-28 17:17:10 -07001431 LOG(ERROR) << *thread << " suspend count already zero.";
Ian Rogers01ae5802012-09-28 16:14:01 -07001432 Locks::thread_suspend_count_lock_->Unlock(self);
1433 if (!Locks::mutator_lock_->IsSharedHeld(self)) {
1434 Locks::mutator_lock_->SharedTryLock(self);
1435 if (!Locks::mutator_lock_->IsSharedHeld(self)) {
1436 LOG(WARNING) << "Dumping thread list without holding mutator_lock_";
1437 }
1438 }
1439 if (!Locks::thread_list_lock_->IsExclusiveHeld(self)) {
1440 Locks::thread_list_lock_->TryLock(self);
1441 if (!Locks::thread_list_lock_->IsExclusiveHeld(self)) {
1442 LOG(WARNING) << "Dumping thread list without holding thread_list_lock_";
1443 }
1444 }
1445 std::ostringstream ss;
Ian Rogers7b078e82014-09-10 14:44:24 -07001446 Runtime::Current()->GetThreadList()->Dump(ss);
Ian Rogers120f1c72012-09-28 17:17:10 -07001447 LOG(FATAL) << ss.str();
Ian Rogers01ae5802012-09-28 16:14:01 -07001448}
1449
Hiroshi Yamauchi02e7f1a2016-10-03 15:32:01 -07001450bool Thread::ModifySuspendCountInternal(Thread* self,
1451 int delta,
1452 AtomicInteger* suspend_barrier,
Alex Light46f93402017-06-29 11:59:50 -07001453 SuspendReason reason) {
Ian Rogers2966e132014-04-02 08:34:36 -07001454 if (kIsDebugBuild) {
Alex Light72e27b02020-07-27 12:59:58 -07001455 DCHECK(delta == -1 || delta == +1)
1456 << reason << " " << delta << " " << this;
Ian Rogers2966e132014-04-02 08:34:36 -07001457 Locks::thread_suspend_count_lock_->AssertHeld(self);
1458 if (this != self && !IsSuspended()) {
1459 Locks::thread_list_lock_->AssertHeld(self);
1460 }
Ian Rogerscfaa4552012-11-26 21:00:08 -08001461 }
Alex Light88fd7202017-06-30 08:31:59 -07001462 // User code suspensions need to be checked more closely since they originate from code outside of
1463 // the runtime's control.
1464 if (UNLIKELY(reason == SuspendReason::kForUserCode)) {
1465 Locks::user_code_suspension_lock_->AssertHeld(self);
1466 if (UNLIKELY(delta + tls32_.user_code_suspend_count < 0)) {
1467 LOG(ERROR) << "attempting to modify suspend count in an illegal way.";
1468 return false;
1469 }
1470 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07001471 if (UNLIKELY(delta < 0 && tls32_.suspend_count <= 0)) {
Ian Rogers01ae5802012-09-28 16:14:01 -07001472 UnsafeLogFatalForSuspendCount(self, this);
Yu Lieac44242015-06-29 10:50:03 +08001473 return false;
1474 }
1475
Hiroshi Yamauchi02e7f1a2016-10-03 15:32:01 -07001476 if (kUseReadBarrier && delta > 0 && this != self && tlsPtr_.flip_function != nullptr) {
1477 // Force retry of a suspend request if it's in the middle of a thread flip to avoid a
1478 // deadlock. b/31683379.
1479 return false;
1480 }
1481
Vladimir Markoddf4fd32021-11-22 16:31:57 +00001482 uint32_t flags = enum_cast<uint32_t>(ThreadFlag::kSuspendRequest);
Yu Lieac44242015-06-29 10:50:03 +08001483 if (delta > 0 && suspend_barrier != nullptr) {
1484 uint32_t available_barrier = kMaxSuspendBarriers;
1485 for (uint32_t i = 0; i < kMaxSuspendBarriers; ++i) {
1486 if (tlsPtr_.active_suspend_barriers[i] == nullptr) {
1487 available_barrier = i;
1488 break;
1489 }
1490 }
1491 if (available_barrier == kMaxSuspendBarriers) {
1492 // No barrier spaces available, we can't add another.
1493 return false;
1494 }
1495 tlsPtr_.active_suspend_barriers[available_barrier] = suspend_barrier;
Vladimir Markoddf4fd32021-11-22 16:31:57 +00001496 flags |= enum_cast<uint32_t>(ThreadFlag::kActiveSuspendBarrier);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001497 }
Ian Rogers01ae5802012-09-28 16:14:01 -07001498
Ian Rogersdd7624d2014-03-14 17:43:00 -07001499 tls32_.suspend_count += delta;
Alex Light46f93402017-06-29 11:59:50 -07001500 switch (reason) {
Alex Light88fd7202017-06-30 08:31:59 -07001501 case SuspendReason::kForUserCode:
1502 tls32_.user_code_suspend_count += delta;
1503 break;
Alex Light46f93402017-06-29 11:59:50 -07001504 case SuspendReason::kInternal:
1505 break;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001506 }
Ian Rogers01ae5802012-09-28 16:14:01 -07001507
Ian Rogersdd7624d2014-03-14 17:43:00 -07001508 if (tls32_.suspend_count == 0) {
Vladimir Markoddf4fd32021-11-22 16:31:57 +00001509 AtomicClearFlag(ThreadFlag::kSuspendRequest);
Ian Rogers474b6da2012-09-25 00:20:38 -07001510 } else {
Yu Lieac44242015-06-29 10:50:03 +08001511 // Two bits might be set simultaneously.
Vladimir Markoddf4fd32021-11-22 16:31:57 +00001512 tls32_.state_and_flags.fetch_or(flags, std::memory_order_seq_cst);
Dave Allisonb373e092014-02-20 16:06:36 -08001513 TriggerSuspend();
Ian Rogers474b6da2012-09-25 00:20:38 -07001514 }
Yu Lieac44242015-06-29 10:50:03 +08001515 return true;
1516}
1517
1518bool Thread::PassActiveSuspendBarriers(Thread* self) {
1519 // Grab the suspend_count lock and copy the current set of
1520 // barriers. Then clear the list and the flag. The ModifySuspendCount
1521 // function requires the lock so we prevent a race between setting
1522 // the kActiveSuspendBarrier flag and clearing it.
1523 AtomicInteger* pass_barriers[kMaxSuspendBarriers];
1524 {
1525 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Vladimir Markoddf4fd32021-11-22 16:31:57 +00001526 if (!ReadFlag(ThreadFlag::kActiveSuspendBarrier)) {
Yu Lieac44242015-06-29 10:50:03 +08001527 // quick exit test: the barriers have already been claimed - this is
1528 // possible as there may be a race to claim and it doesn't matter
1529 // who wins.
1530 // All of the callers of this function (except the SuspendAllInternal)
1531 // will first test the kActiveSuspendBarrier flag without lock. Here
1532 // double-check whether the barrier has been passed with the
1533 // suspend_count lock.
1534 return false;
1535 }
1536
1537 for (uint32_t i = 0; i < kMaxSuspendBarriers; ++i) {
1538 pass_barriers[i] = tlsPtr_.active_suspend_barriers[i];
1539 tlsPtr_.active_suspend_barriers[i] = nullptr;
1540 }
Vladimir Markoddf4fd32021-11-22 16:31:57 +00001541 AtomicClearFlag(ThreadFlag::kActiveSuspendBarrier);
Yu Lieac44242015-06-29 10:50:03 +08001542 }
1543
1544 uint32_t barrier_count = 0;
1545 for (uint32_t i = 0; i < kMaxSuspendBarriers; i++) {
1546 AtomicInteger* pending_threads = pass_barriers[i];
1547 if (pending_threads != nullptr) {
1548 bool done = false;
1549 do {
Orion Hodson88591fe2018-03-06 13:35:43 +00001550 int32_t cur_val = pending_threads->load(std::memory_order_relaxed);
Yu Lieac44242015-06-29 10:50:03 +08001551 CHECK_GT(cur_val, 0) << "Unexpected value for PassActiveSuspendBarriers(): " << cur_val;
1552 // Reduce value by 1.
Orion Hodson4557b382018-01-03 11:47:54 +00001553 done = pending_threads->CompareAndSetWeakRelaxed(cur_val, cur_val - 1);
Yu Lieac44242015-06-29 10:50:03 +08001554#if ART_USE_FUTEXES
1555 if (done && (cur_val - 1) == 0) { // Weak CAS may fail spuriously.
Hans Boehm81dc7ab2019-04-19 17:34:31 -07001556 futex(pending_threads->Address(), FUTEX_WAKE_PRIVATE, INT_MAX, nullptr, nullptr, 0);
Yu Lieac44242015-06-29 10:50:03 +08001557 }
1558#endif
1559 } while (!done);
1560 ++barrier_count;
1561 }
1562 }
1563 CHECK_GT(barrier_count, 0U);
1564 return true;
1565}
1566
1567void Thread::ClearSuspendBarrier(AtomicInteger* target) {
Vladimir Markoddf4fd32021-11-22 16:31:57 +00001568 CHECK(ReadFlag(ThreadFlag::kActiveSuspendBarrier));
Yu Lieac44242015-06-29 10:50:03 +08001569 bool clear_flag = true;
1570 for (uint32_t i = 0; i < kMaxSuspendBarriers; ++i) {
1571 AtomicInteger* ptr = tlsPtr_.active_suspend_barriers[i];
1572 if (ptr == target) {
1573 tlsPtr_.active_suspend_barriers[i] = nullptr;
1574 } else if (ptr != nullptr) {
1575 clear_flag = false;
1576 }
1577 }
1578 if (LIKELY(clear_flag)) {
Vladimir Markoddf4fd32021-11-22 16:31:57 +00001579 AtomicClearFlag(ThreadFlag::kActiveSuspendBarrier);
Yu Lieac44242015-06-29 10:50:03 +08001580 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001581}
1582
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001583void Thread::RunCheckpointFunction() {
Vladimir Marko9c0f7642021-12-06 16:17:52 +00001584 // If this thread is suspended and another thread is running the checkpoint on its behalf,
1585 // we may have a pending flip function that we need to run for the sake of those checkpoints
1586 // that need to walk the stack. We should not see the flip function flags when the thread
1587 // is running the checkpoint on its own.
1588 StateAndFlags state_and_flags = GetStateAndFlags(std::memory_order_relaxed);
1589 if (UNLIKELY(state_and_flags.IsAnyOfFlagsSet(FlipFunctionFlags()))) {
1590 DCHECK(IsSuspended());
1591 Thread* self = Thread::Current();
1592 DCHECK(self != this);
1593 if (state_and_flags.IsFlagSet(ThreadFlag::kPendingFlipFunction)) {
1594 EnsureFlipFunctionStarted(self);
1595 state_and_flags = GetStateAndFlags(std::memory_order_relaxed);
1596 DCHECK(!state_and_flags.IsFlagSet(ThreadFlag::kPendingFlipFunction));
1597 }
1598 if (state_and_flags.IsFlagSet(ThreadFlag::kRunningFlipFunction)) {
1599 WaitForFlipFunction(self);
1600 }
1601 }
1602
Alex Lightdf00a1e2017-11-01 09:29:53 -07001603 // Grab the suspend_count lock, get the next checkpoint and update all the checkpoint fields. If
1604 // there are no more checkpoints we will also clear the kCheckpointRequest flag.
1605 Closure* checkpoint;
1606 {
1607 MutexLock mu(this, *Locks::thread_suspend_count_lock_);
1608 checkpoint = tlsPtr_.checkpoint_function;
1609 if (!checkpoint_overflow_.empty()) {
1610 // Overflow list not empty, copy the first one out and continue.
1611 tlsPtr_.checkpoint_function = checkpoint_overflow_.front();
1612 checkpoint_overflow_.pop_front();
1613 } else {
1614 // No overflow checkpoints. Clear the kCheckpointRequest flag
1615 tlsPtr_.checkpoint_function = nullptr;
Vladimir Markoddf4fd32021-11-22 16:31:57 +00001616 AtomicClearFlag(ThreadFlag::kCheckpointRequest);
Dave Allison0aded082013-11-07 13:15:11 -08001617 }
Alex Lightdf00a1e2017-11-01 09:29:53 -07001618 }
1619 // Outside the lock, run the checkpoint function.
1620 ScopedTrace trace("Run checkpoint function");
1621 CHECK(checkpoint != nullptr) << "Checkpoint flag set without pending checkpoint";
1622 checkpoint->Run(this);
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001623}
1624
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07001625void Thread::RunEmptyCheckpoint() {
Vladimir Marko9c0f7642021-12-06 16:17:52 +00001626 // Note: Empty checkpoint does not access the thread's stack,
1627 // so we do not need to check for the flip function.
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07001628 DCHECK_EQ(Thread::Current(), this);
Vladimir Markoddf4fd32021-11-22 16:31:57 +00001629 AtomicClearFlag(ThreadFlag::kEmptyCheckpointRequest);
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07001630 Runtime::Current()->GetThreadList()->EmptyCheckpointBarrier()->Pass(this);
1631}
1632
Mathieu Chartier0e4627e2012-10-23 16:13:36 -07001633bool Thread::RequestCheckpoint(Closure* function) {
Vladimir Marko9c0f7642021-12-06 16:17:52 +00001634 StateAndFlags old_state_and_flags = GetStateAndFlags(std::memory_order_relaxed);
Vladimir Markoddf4fd32021-11-22 16:31:57 +00001635 if (old_state_and_flags.GetState() != ThreadState::kRunnable) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001636 return false; // Fail, thread is suspended and so can't run a checkpoint.
1637 }
Dave Allison0aded082013-11-07 13:15:11 -08001638
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001639 // We must be runnable to request a checkpoint.
Vladimir Markoddf4fd32021-11-22 16:31:57 +00001640 DCHECK_EQ(old_state_and_flags.GetState(), ThreadState::kRunnable);
1641 StateAndFlags new_state_and_flags = old_state_and_flags;
1642 new_state_and_flags.SetFlag(ThreadFlag::kCheckpointRequest);
1643 bool success = tls32_.state_and_flags.CompareAndSetStrongSequentiallyConsistent(
1644 old_state_and_flags.GetValue(), new_state_and_flags.GetValue());
Mathieu Chartier952e1e32016-06-13 14:04:02 -07001645 if (success) {
1646 // Succeeded setting checkpoint flag, now insert the actual checkpoint.
1647 if (tlsPtr_.checkpoint_function == nullptr) {
1648 tlsPtr_.checkpoint_function = function;
1649 } else {
1650 checkpoint_overflow_.push_back(function);
1651 }
Vladimir Markoddf4fd32021-11-22 16:31:57 +00001652 CHECK(ReadFlag(ThreadFlag::kCheckpointRequest));
Dave Allisonb373e092014-02-20 16:06:36 -08001653 TriggerSuspend();
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001654 }
Ian Rogers8c1b5f72014-07-09 22:02:36 -07001655 return success;
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001656}
1657
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07001658bool Thread::RequestEmptyCheckpoint() {
Vladimir Marko9c0f7642021-12-06 16:17:52 +00001659 StateAndFlags old_state_and_flags = GetStateAndFlags(std::memory_order_relaxed);
Vladimir Markoddf4fd32021-11-22 16:31:57 +00001660 if (old_state_and_flags.GetState() != ThreadState::kRunnable) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07001661 // If it's not runnable, we don't need to do anything because it won't be in the middle of a
1662 // heap access (eg. the read barrier).
1663 return false;
1664 }
1665
1666 // We must be runnable to request a checkpoint.
Vladimir Markoddf4fd32021-11-22 16:31:57 +00001667 DCHECK_EQ(old_state_and_flags.GetState(), ThreadState::kRunnable);
1668 StateAndFlags new_state_and_flags = old_state_and_flags;
1669 new_state_and_flags.SetFlag(ThreadFlag::kEmptyCheckpointRequest);
1670 bool success = tls32_.state_and_flags.CompareAndSetStrongSequentiallyConsistent(
1671 old_state_and_flags.GetValue(), new_state_and_flags.GetValue());
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07001672 if (success) {
1673 TriggerSuspend();
1674 }
1675 return success;
1676}
1677
Andreas Gampee9f67122016-10-27 19:21:23 -07001678class BarrierClosure : public Closure {
1679 public:
1680 explicit BarrierClosure(Closure* wrapped) : wrapped_(wrapped), barrier_(0) {}
1681
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001682 void Run(Thread* self) override {
Andreas Gampee9f67122016-10-27 19:21:23 -07001683 wrapped_->Run(self);
1684 barrier_.Pass(self);
1685 }
1686
Alex Light318afe62018-03-22 16:50:10 -07001687 void Wait(Thread* self, ThreadState suspend_state) {
1688 if (suspend_state != ThreadState::kRunnable) {
1689 barrier_.Increment<Barrier::kDisallowHoldingLocks>(self, 1);
1690 } else {
1691 barrier_.Increment<Barrier::kAllowHoldingLocks>(self, 1);
1692 }
Andreas Gampee9f67122016-10-27 19:21:23 -07001693 }
1694
1695 private:
1696 Closure* wrapped_;
1697 Barrier barrier_;
1698};
1699
Alex Lightb1e31a82017-10-04 16:57:36 -07001700// RequestSynchronousCheckpoint releases the thread_list_lock_ as a part of its execution.
Alex Light318afe62018-03-22 16:50:10 -07001701bool Thread::RequestSynchronousCheckpoint(Closure* function, ThreadState suspend_state) {
Alex Lightb1e31a82017-10-04 16:57:36 -07001702 Thread* self = Thread::Current();
Andreas Gampee9f67122016-10-27 19:21:23 -07001703 if (this == Thread::Current()) {
Alex Lightb1e31a82017-10-04 16:57:36 -07001704 Locks::thread_list_lock_->AssertExclusiveHeld(self);
1705 // Unlock the tll before running so that the state is the same regardless of thread.
1706 Locks::thread_list_lock_->ExclusiveUnlock(self);
Andreas Gampee9f67122016-10-27 19:21:23 -07001707 // Asked to run on this thread. Just run.
1708 function->Run(this);
Andreas Gampe28c4a232017-06-21 21:21:31 -07001709 return true;
Andreas Gampee9f67122016-10-27 19:21:23 -07001710 }
Andreas Gampee9f67122016-10-27 19:21:23 -07001711
1712 // The current thread is not this thread.
1713
Andreas Gampe28c4a232017-06-21 21:21:31 -07001714 if (GetState() == ThreadState::kTerminated) {
Alex Lightb1e31a82017-10-04 16:57:36 -07001715 Locks::thread_list_lock_->ExclusiveUnlock(self);
Andreas Gampe28c4a232017-06-21 21:21:31 -07001716 return false;
1717 }
1718
Andreas Gampe28c4a232017-06-21 21:21:31 -07001719 struct ScopedThreadListLockUnlock {
1720 explicit ScopedThreadListLockUnlock(Thread* self_in) RELEASE(*Locks::thread_list_lock_)
1721 : self_thread(self_in) {
1722 Locks::thread_list_lock_->AssertHeld(self_thread);
1723 Locks::thread_list_lock_->Unlock(self_thread);
1724 }
1725
1726 ~ScopedThreadListLockUnlock() ACQUIRE(*Locks::thread_list_lock_) {
1727 Locks::thread_list_lock_->AssertNotHeld(self_thread);
1728 Locks::thread_list_lock_->Lock(self_thread);
1729 }
1730
1731 Thread* self_thread;
1732 };
1733
Andreas Gampee9f67122016-10-27 19:21:23 -07001734 for (;;) {
Alex Lightb1e31a82017-10-04 16:57:36 -07001735 Locks::thread_list_lock_->AssertExclusiveHeld(self);
Andreas Gampee9f67122016-10-27 19:21:23 -07001736 // If this thread is runnable, try to schedule a checkpoint. Do some gymnastics to not hold the
1737 // suspend-count lock for too long.
1738 if (GetState() == ThreadState::kRunnable) {
1739 BarrierClosure barrier_closure(function);
1740 bool installed = false;
1741 {
1742 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
1743 installed = RequestCheckpoint(&barrier_closure);
1744 }
1745 if (installed) {
Alex Lightb1e31a82017-10-04 16:57:36 -07001746 // Relinquish the thread-list lock. We should not wait holding any locks. We cannot
1747 // reacquire it since we don't know if 'this' hasn't been deleted yet.
1748 Locks::thread_list_lock_->ExclusiveUnlock(self);
Alex Light318afe62018-03-22 16:50:10 -07001749 ScopedThreadStateChange sts(self, suspend_state);
1750 barrier_closure.Wait(self, suspend_state);
Andreas Gampe28c4a232017-06-21 21:21:31 -07001751 return true;
Andreas Gampee9f67122016-10-27 19:21:23 -07001752 }
1753 // Fall-through.
1754 }
1755
1756 // This thread is not runnable, make sure we stay suspended, then run the checkpoint.
1757 // Note: ModifySuspendCountInternal also expects the thread_list_lock to be held in
1758 // certain situations.
1759 {
Andreas Gampee9f67122016-10-27 19:21:23 -07001760 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
1761
Alex Light46f93402017-06-29 11:59:50 -07001762 if (!ModifySuspendCount(self, +1, nullptr, SuspendReason::kInternal)) {
Andreas Gampee9f67122016-10-27 19:21:23 -07001763 // Just retry the loop.
1764 sched_yield();
1765 continue;
1766 }
1767 }
1768
Andreas Gampe28c4a232017-06-21 21:21:31 -07001769 {
Alex Lightb1e31a82017-10-04 16:57:36 -07001770 // Release for the wait. The suspension will keep us from being deleted. Reacquire after so
1771 // that we can call ModifySuspendCount without racing against ThreadList::Unregister.
Andreas Gampe28c4a232017-06-21 21:21:31 -07001772 ScopedThreadListLockUnlock stllu(self);
Andreas Gampe117f9b32017-06-23 13:33:50 -07001773 {
Alex Light318afe62018-03-22 16:50:10 -07001774 ScopedThreadStateChange sts(self, suspend_state);
Andreas Gampe117f9b32017-06-23 13:33:50 -07001775 while (GetState() == ThreadState::kRunnable) {
1776 // We became runnable again. Wait till the suspend triggered in ModifySuspendCount
1777 // moves us to suspended.
1778 sched_yield();
1779 }
Andreas Gampe28c4a232017-06-21 21:21:31 -07001780 }
1781
1782 function->Run(this);
Andreas Gampee9f67122016-10-27 19:21:23 -07001783 }
1784
Andreas Gampee9f67122016-10-27 19:21:23 -07001785 {
Andreas Gampee9f67122016-10-27 19:21:23 -07001786 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
1787
1788 DCHECK_NE(GetState(), ThreadState::kRunnable);
Alex Light46f93402017-06-29 11:59:50 -07001789 bool updated = ModifySuspendCount(self, -1, nullptr, SuspendReason::kInternal);
Sebastien Hertz1c8f4ff2017-04-14 15:05:12 +02001790 DCHECK(updated);
Andreas Gampee9f67122016-10-27 19:21:23 -07001791 }
1792
Andreas Gampe117f9b32017-06-23 13:33:50 -07001793 {
1794 // Imitate ResumeAll, the thread may be waiting on Thread::resume_cond_ since we raised its
1795 // suspend count. Now the suspend_count_ is lowered so we must do the broadcast.
1796 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
1797 Thread::resume_cond_->Broadcast(self);
1798 }
1799
Alex Lightb1e31a82017-10-04 16:57:36 -07001800 // Release the thread_list_lock_ to be consistent with the barrier-closure path.
1801 Locks::thread_list_lock_->ExclusiveUnlock(self);
1802
Andreas Gampe28c4a232017-06-21 21:21:31 -07001803 return true; // We're done, break out of the loop.
Andreas Gampee9f67122016-10-27 19:21:23 -07001804 }
1805}
1806
Vladimir Marko9c0f7642021-12-06 16:17:52 +00001807void Thread::SetFlipFunction(Closure* function) {
1808 // This is called with all threads suspended, except for the calling thread.
1809 DCHECK(IsSuspended() || Thread::Current() == this);
1810 DCHECK(function != nullptr);
1811 DCHECK(tlsPtr_.flip_function == nullptr);
1812 tlsPtr_.flip_function = function;
1813 DCHECK(!GetStateAndFlags(std::memory_order_relaxed).IsAnyOfFlagsSet(FlipFunctionFlags()));
1814 AtomicSetFlag(ThreadFlag::kPendingFlipFunction, std::memory_order_release);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001815}
1816
Vladimir Marko9c0f7642021-12-06 16:17:52 +00001817void Thread::EnsureFlipFunctionStarted(Thread* self) {
1818 while (true) {
1819 StateAndFlags old_state_and_flags = GetStateAndFlags(std::memory_order_relaxed);
1820 if (!old_state_and_flags.IsFlagSet(ThreadFlag::kPendingFlipFunction)) {
1821 return;
1822 }
1823 DCHECK(!old_state_and_flags.IsFlagSet(ThreadFlag::kRunningFlipFunction));
1824 StateAndFlags new_state_and_flags =
1825 old_state_and_flags.WithFlag(ThreadFlag::kRunningFlipFunction)
1826 .WithoutFlag(ThreadFlag::kPendingFlipFunction);
1827 if (tls32_.state_and_flags.CompareAndSetWeakAcquire(old_state_and_flags.GetValue(),
1828 new_state_and_flags.GetValue())) {
1829 RunFlipFunction(self, /*notify=*/ true);
1830 DCHECK(!GetStateAndFlags(std::memory_order_relaxed).IsAnyOfFlagsSet(FlipFunctionFlags()));
1831 return;
1832 }
1833 }
1834}
1835
1836void Thread::RunFlipFunction(Thread* self, bool notify) {
1837 // This function is called for suspended threads and by the thread running
1838 // `ThreadList::FlipThreadRoots()` after we've successfully set the flag
1839 // `ThreadFlag::kRunningFlipFunction`. This flag is not set if the thread is
1840 // running the flip function right after transitioning to Runnable as
1841 // no other thread may run checkpoints on a thread that's actually Runnable.
1842 DCHECK_EQ(notify, ReadFlag(ThreadFlag::kRunningFlipFunction));
1843
1844 Closure* flip_function = tlsPtr_.flip_function;
1845 tlsPtr_.flip_function = nullptr;
1846 DCHECK(flip_function != nullptr);
1847 flip_function->Run(this);
1848
1849 if (notify) {
1850 // Clear the `ThreadFlag::kRunningFlipFunction` and `ThreadFlag::kWaitingForFlipFunction`.
1851 // Check if the latter was actually set, indicating that there is at least one waiting thread.
1852 constexpr uint32_t kFlagsToClear = enum_cast<uint32_t>(ThreadFlag::kRunningFlipFunction) |
1853 enum_cast<uint32_t>(ThreadFlag::kWaitingForFlipFunction);
1854 StateAndFlags old_state_and_flags(
1855 tls32_.state_and_flags.fetch_and(~kFlagsToClear, std::memory_order_release));
1856 if (old_state_and_flags.IsFlagSet(ThreadFlag::kWaitingForFlipFunction)) {
1857 // Notify all threads that are waiting for completion (at least one).
1858 // TODO: Should we create a separate mutex and condition variable instead
1859 // of piggy-backing on the `thread_suspend_count_lock_` and `resume_cond_`?
1860 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
1861 resume_cond_->Broadcast(self);
1862 }
1863 }
1864}
1865
1866void Thread::WaitForFlipFunction(Thread* self) {
1867 // Another thread is running the flip function. Wait for it to complete.
1868 // Check the flag while holding the mutex so that we do not miss the broadcast.
1869 // Repeat the check after waiting to guard against spurious wakeups (and because
1870 // we share the `thread_suspend_count_lock_` and `resume_cond_` with other code).
1871 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
1872 while (true) {
1873 StateAndFlags old_state_and_flags = GetStateAndFlags(std::memory_order_acquire);
1874 DCHECK(!old_state_and_flags.IsFlagSet(ThreadFlag::kPendingFlipFunction));
1875 if (!old_state_and_flags.IsFlagSet(ThreadFlag::kRunningFlipFunction)) {
1876 DCHECK(!old_state_and_flags.IsAnyOfFlagsSet(FlipFunctionFlags()));
1877 break;
1878 }
1879 if (!old_state_and_flags.IsFlagSet(ThreadFlag::kWaitingForFlipFunction)) {
1880 // Mark that there is a waiting thread.
1881 StateAndFlags new_state_and_flags =
1882 old_state_and_flags.WithFlag(ThreadFlag::kWaitingForFlipFunction);
1883 if (!tls32_.state_and_flags.CompareAndSetWeakRelaxed(old_state_and_flags.GetValue(),
1884 new_state_and_flags.GetValue())) {
1885 continue; // Retry.
1886 }
1887 }
1888 resume_cond_->Wait(self);
1889 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001890}
1891
Vladimir Markoe45883e2022-01-11 12:38:35 +00001892void Thread::FullSuspendCheck(bool implicit) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001893 ScopedTrace trace(__FUNCTION__);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001894 VLOG(threads) << this << " self-suspending";
1895 // Make thread appear suspended to other threads, release mutator_lock_.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07001896 // Transition to suspended and back to runnable, re-acquire share on mutator_lock_.
Vladimir Markoddf4fd32021-11-22 16:31:57 +00001897 ScopedThreadSuspension(this, ThreadState::kSuspended); // NOLINT
Vladimir Markoe45883e2022-01-11 12:38:35 +00001898 if (implicit) {
1899 // For implicit suspend check we want to `madvise()` away
1900 // the alternate signal stack to avoid wasting memory.
1901 MadviseAwayAlternateSignalStack();
1902 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001903 VLOG(threads) << this << " self-reviving";
1904}
1905
Andreas Gampe9186ced2016-12-12 14:28:21 -08001906static std::string GetSchedulerGroupName(pid_t tid) {
1907 // /proc/<pid>/cgroup looks like this:
1908 // 2:devices:/
1909 // 1:cpuacct,cpu:/
1910 // We want the third field from the line whose second field contains the "cpu" token.
1911 std::string cgroup_file;
Andreas Gampe43e72432019-05-14 16:15:24 -07001912 if (!android::base::ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid),
1913 &cgroup_file)) {
Andreas Gampe9186ced2016-12-12 14:28:21 -08001914 return "";
1915 }
1916 std::vector<std::string> cgroup_lines;
1917 Split(cgroup_file, '\n', &cgroup_lines);
1918 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
1919 std::vector<std::string> cgroup_fields;
1920 Split(cgroup_lines[i], ':', &cgroup_fields);
1921 std::vector<std::string> cgroups;
1922 Split(cgroup_fields[1], ',', &cgroups);
1923 for (size_t j = 0; j < cgroups.size(); ++j) {
1924 if (cgroups[j] == "cpu") {
1925 return cgroup_fields[2].substr(1); // Skip the leading slash.
1926 }
1927 }
1928 }
1929 return "";
1930}
1931
Elliott Hughesabbe07d2012-06-05 17:42:23 -07001932void Thread::DumpState(std::ostream& os, const Thread* thread, pid_t tid) {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001933 std::string group_name;
1934 int priority;
1935 bool is_daemon = false;
Ian Rogers81d425b2012-09-27 16:03:43 -07001936 Thread* self = Thread::Current();
Elliott Hughesdcc24742011-09-07 14:02:44 -07001937
Mathieu Chartierc7a966d2014-04-10 18:06:32 -07001938 // Don't do this if we are aborting since the GC may have all the threads suspended. This will
1939 // cause ScopedObjectAccessUnchecked to deadlock.
Nicolas Geoffraydb978712014-12-09 13:33:38 +00001940 if (gAborting == 0 && self != nullptr && thread != nullptr && thread->tlsPtr_.opeer != nullptr) {
Ian Rogerscfaa4552012-11-26 21:00:08 -08001941 ScopedObjectAccessUnchecked soa(self);
Andreas Gampe08883de2016-11-08 13:20:52 -08001942 priority = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_priority)
Ian Rogersdd7624d2014-03-14 17:43:00 -07001943 ->GetInt(thread->tlsPtr_.opeer);
Andreas Gampe08883de2016-11-08 13:20:52 -08001944 is_daemon = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_daemon)
Ian Rogersdd7624d2014-03-14 17:43:00 -07001945 ->GetBoolean(thread->tlsPtr_.opeer);
Elliott Hughesd369bb72011-09-12 14:41:14 -07001946
Mathieu Chartier3398c782016-09-30 10:27:43 -07001947 ObjPtr<mirror::Object> thread_group =
Andreas Gampe08883de2016-11-08 13:20:52 -08001948 jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group)
1949 ->GetObject(thread->tlsPtr_.opeer);
Ian Rogers120f1c72012-09-28 17:17:10 -07001950
Dave Allison0aded082013-11-07 13:15:11 -08001951 if (thread_group != nullptr) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001952 ArtField* group_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001953 jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_name);
Mathieu Chartier3398c782016-09-30 10:27:43 -07001954 ObjPtr<mirror::String> group_name_string =
1955 group_name_field->GetObject(thread_group)->AsString();
Dave Allison0aded082013-11-07 13:15:11 -08001956 group_name = (group_name_string != nullptr) ? group_name_string->ToModifiedUtf8() : "<null>";
Elliott Hughesd369bb72011-09-12 14:41:14 -07001957 }
Nicolas Geoffrayfa595882019-08-06 17:40:09 +01001958 } else if (thread != nullptr) {
1959 priority = thread->GetNativePriority();
Elliott Hughesd369bb72011-09-12 14:41:14 -07001960 } else {
Orion Hodsonc5323fe2021-02-04 21:20:30 +00001961 palette_status_t status = PaletteSchedGetPriority(tid, &priority);
1962 CHECK(status == PALETTE_STATUS_OK || status == PALETTE_STATUS_CHECK_ERRNO);
Elliott Hughesdcc24742011-09-07 14:02:44 -07001963 }
Elliott Hughesd92bec42011-09-02 17:04:36 -07001964
Elliott Hughesabbe07d2012-06-05 17:42:23 -07001965 std::string scheduler_group_name(GetSchedulerGroupName(tid));
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001966 if (scheduler_group_name.empty()) {
1967 scheduler_group_name = "default";
Elliott Hughesd92bec42011-09-02 17:04:36 -07001968 }
1969
Dave Allison0aded082013-11-07 13:15:11 -08001970 if (thread != nullptr) {
Hans Boehm30bc7772022-01-28 15:07:02 -08001971 thread->tls32_.num_name_readers.fetch_add(1, std::memory_order_seq_cst);
1972 os << '"' << thread->tlsPtr_.name.load() << '"';
1973 thread->tls32_.num_name_readers.fetch_sub(1 /* at least memory_order_release */);
Elliott Hughesabbe07d2012-06-05 17:42:23 -07001974 if (is_daemon) {
1975 os << " daemon";
1976 }
1977 os << " prio=" << priority
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001978 << " tid=" << thread->GetThreadId()
Elliott Hughes80537bb2013-01-04 16:37:26 -08001979 << " " << thread->GetState();
1980 if (thread->IsStillStarting()) {
1981 os << " (still starting up)";
1982 }
1983 os << "\n";
Elliott Hughesabbe07d2012-06-05 17:42:23 -07001984 } else {
Elliott Hughes289be852012-06-12 13:57:20 -07001985 os << '"' << ::art::GetThreadName(tid) << '"'
Elliott Hughesabbe07d2012-06-05 17:42:23 -07001986 << " prio=" << priority
Elliott Hughesabbe07d2012-06-05 17:42:23 -07001987 << " (not attached)\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -07001988 }
Elliott Hughesd92bec42011-09-02 17:04:36 -07001989
Dave Allison0aded082013-11-07 13:15:11 -08001990 if (thread != nullptr) {
Andreas Gampe7d42cdd2019-05-31 16:54:46 -07001991 auto suspend_log_fn = [&]() REQUIRES(Locks::thread_suspend_count_lock_) {
Vladimir Marko9c0f7642021-12-06 16:17:52 +00001992 StateAndFlags state_and_flags = thread->GetStateAndFlags(std::memory_order_relaxed);
Vladimir Markoddf4fd32021-11-22 16:31:57 +00001993 static_assert(
1994 static_cast<std::underlying_type_t<ThreadState>>(ThreadState::kRunnable) == 0u);
1995 state_and_flags.SetState(ThreadState::kRunnable); // Clear state bits.
Andreas Gampe7d42cdd2019-05-31 16:54:46 -07001996 os << " | group=\"" << group_name << "\""
1997 << " sCount=" << thread->tls32_.suspend_count
Alex Lighta462fa62020-07-27 12:58:33 -07001998 << " ucsCount=" << thread->tls32_.user_code_suspend_count
Vladimir Markoddf4fd32021-11-22 16:31:57 +00001999 << " flags=" << state_and_flags.GetValue()
Andreas Gampe7d42cdd2019-05-31 16:54:46 -07002000 << " obj=" << reinterpret_cast<void*>(thread->tlsPtr_.opeer)
2001 << " self=" << reinterpret_cast<const void*>(thread) << "\n";
2002 };
2003 if (Locks::thread_suspend_count_lock_->IsExclusiveHeld(self)) {
2004 Locks::thread_suspend_count_lock_->AssertExclusiveHeld(self); // For annotalysis.
2005 suspend_log_fn();
2006 } else {
2007 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
2008 suspend_log_fn();
2009 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -07002010 }
Elliott Hughes0d39c122012-06-06 16:41:17 -07002011
Elliott Hughesabbe07d2012-06-05 17:42:23 -07002012 os << " | sysTid=" << tid
Eric Holkf1e1dd12020-08-21 15:38:12 -07002013 << " nice=" << getpriority(PRIO_PROCESS, static_cast<id_t>(tid))
Elliott Hughes0d39c122012-06-06 16:41:17 -07002014 << " cgrp=" << scheduler_group_name;
Dave Allison0aded082013-11-07 13:15:11 -08002015 if (thread != nullptr) {
Elliott Hughes0d39c122012-06-06 16:41:17 -07002016 int policy;
2017 sched_param sp;
Brian Carlstrom640a1042017-03-20 15:03:42 -07002018#if !defined(__APPLE__)
2019 // b/36445592 Don't use pthread_getschedparam since pthread may have exited.
2020 policy = sched_getscheduler(tid);
2021 if (policy == -1) {
2022 PLOG(WARNING) << "sched_getscheduler(" << tid << ")";
2023 }
2024 int sched_getparam_result = sched_getparam(tid, &sp);
2025 if (sched_getparam_result == -1) {
2026 PLOG(WARNING) << "sched_getparam(" << tid << ", &sp)";
2027 sp.sched_priority = -1;
2028 }
2029#else
Ian Rogersdd7624d2014-03-14 17:43:00 -07002030 CHECK_PTHREAD_CALL(pthread_getschedparam, (thread->tlsPtr_.pthread_self, &policy, &sp),
2031 __FUNCTION__);
Brian Carlstrom640a1042017-03-20 15:03:42 -07002032#endif
Elliott Hughes0d39c122012-06-06 16:41:17 -07002033 os << " sched=" << policy << "/" << sp.sched_priority
Ian Rogersdd7624d2014-03-14 17:43:00 -07002034 << " handle=" << reinterpret_cast<void*>(thread->tlsPtr_.pthread_self);
Elliott Hughes0d39c122012-06-06 16:41:17 -07002035 }
2036 os << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -07002037
2038 // Grab the scheduler stats for this thread.
2039 std::string scheduler_stats;
Andreas Gampe43e72432019-05-14 16:15:24 -07002040 if (android::base::ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", tid),
2041 &scheduler_stats)
Evan Chengd57c51e2018-01-26 15:43:08 +08002042 && !scheduler_stats.empty()) {
2043 scheduler_stats = android::base::Trim(scheduler_stats); // Lose the trailing '\n'.
Elliott Hughesd92bec42011-09-02 17:04:36 -07002044 } else {
2045 scheduler_stats = "0 0 0";
2046 }
2047
Elliott Hughesba0b9c52012-09-20 11:25:12 -07002048 char native_thread_state = '?';
Elliott Hughesd92bec42011-09-02 17:04:36 -07002049 int utime = 0;
2050 int stime = 0;
2051 int task_cpu = 0;
Brian Carlstrom29212012013-09-12 22:18:30 -07002052 GetTaskStats(tid, &native_thread_state, &utime, &stime, &task_cpu);
Elliott Hughesd92bec42011-09-02 17:04:36 -07002053
Elliott Hughesba0b9c52012-09-20 11:25:12 -07002054 os << " | state=" << native_thread_state
2055 << " schedstat=( " << scheduler_stats << " )"
Elliott Hughesd92bec42011-09-02 17:04:36 -07002056 << " utm=" << utime
2057 << " stm=" << stime
Elliott Hughesabbe07d2012-06-05 17:42:23 -07002058 << " core=" << task_cpu
2059 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
Dave Allison0aded082013-11-07 13:15:11 -08002060 if (thread != nullptr) {
Ian Rogersdd7624d2014-03-14 17:43:00 -07002061 os << " | stack=" << reinterpret_cast<void*>(thread->tlsPtr_.stack_begin) << "-"
2062 << reinterpret_cast<void*>(thread->tlsPtr_.stack_end) << " stackSize="
2063 << PrettySize(thread->tlsPtr_.stack_size) << "\n";
Mathieu Chartier9db911e2014-06-04 11:23:58 -07002064 // Dump the held mutexes.
2065 os << " | held mutexes=";
2066 for (size_t i = 0; i < kLockLevelCount; ++i) {
2067 if (i != kMonitorLock) {
2068 BaseMutex* mutex = thread->GetHeldMutex(static_cast<LockLevel>(i));
2069 if (mutex != nullptr) {
2070 os << " \"" << mutex->GetName() << "\"";
2071 if (mutex->IsReaderWriterMutex()) {
2072 ReaderWriterMutex* rw_mutex = down_cast<ReaderWriterMutex*>(mutex);
Hans Boehm0882af22017-08-31 15:21:57 -07002073 if (rw_mutex->GetExclusiveOwnerTid() == tid) {
Mathieu Chartier9db911e2014-06-04 11:23:58 -07002074 os << "(exclusive held)";
2075 } else {
Mathieu Chartier9db911e2014-06-04 11:23:58 -07002076 os << "(shared held)";
2077 }
2078 }
2079 }
2080 }
2081 }
2082 os << "\n";
Elliott Hughesabbe07d2012-06-05 17:42:23 -07002083 }
2084}
2085
2086void Thread::DumpState(std::ostream& os) const {
2087 Thread::DumpState(os, this, GetTid());
Elliott Hughesd92bec42011-09-02 17:04:36 -07002088}
2089
Andreas Gampe93104952017-12-13 17:13:15 -08002090struct StackDumpVisitor : public MonitorObjectsStackVisitor {
Hiroshi Yamauchi02f365f2017-02-03 15:06:00 -08002091 StackDumpVisitor(std::ostream& os_in,
2092 Thread* thread_in,
2093 Context* context,
Andreas Gampe93104952017-12-13 17:13:15 -08002094 bool can_allocate,
Hiroshi Yamauchi02f365f2017-02-03 15:06:00 -08002095 bool check_suspended = true,
Andreas Gampe93104952017-12-13 17:13:15 -08002096 bool dump_locks = true)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002097 REQUIRES_SHARED(Locks::mutator_lock_)
Andreas Gampe93104952017-12-13 17:13:15 -08002098 : MonitorObjectsStackVisitor(thread_in,
2099 context,
2100 check_suspended,
2101 can_allocate && dump_locks),
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002102 os(os_in),
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002103 last_method(nullptr),
2104 last_line_number(0),
Andreas Gampe93104952017-12-13 17:13:15 -08002105 repetition_count(0) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07002106
Ian Rogersbdb03912011-09-14 00:55:44 -07002107 virtual ~StackDumpVisitor() {
Elliott Hughese85d2e92012-05-01 14:02:10 -07002108 if (frame_count == 0) {
2109 os << " (no managed stack frames)\n";
2110 }
Elliott Hughesd369bb72011-09-12 14:41:14 -07002111 }
2112
Andreas Gampe93104952017-12-13 17:13:15 -08002113 static constexpr size_t kMaxRepetition = 3u;
2114
2115 VisitMethodResult StartMethod(ArtMethod* m, size_t frame_nr ATTRIBUTE_UNUSED)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002116 override
Andreas Gampe93104952017-12-13 17:13:15 -08002117 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe542451c2016-07-26 09:02:02 -07002118 m = m->GetInterfaceMethodIfProxy(kRuntimePointerSize);
Vladimir Marko813a8632018-11-29 16:17:01 +00002119 ObjPtr<mirror::DexCache> dex_cache = m->GetDexCache();
Ian Rogersb861dc02011-11-14 17:00:05 -08002120 int line_number = -1;
Daniel Jin35782d42022-01-19 14:58:15 -08002121 uint32_t dex_pc = GetDexPc(false);
Dave Allison0aded082013-11-07 13:15:11 -08002122 if (dex_cache != nullptr) { // be tolerant of bad input
David Sehr9323e6e2016-09-13 08:58:35 -07002123 const DexFile* dex_file = dex_cache->GetDexFile();
Daniel Jin35782d42022-01-19 14:58:15 -08002124 line_number = annotations::GetLineNumFromPC(dex_file, m, dex_pc);
Ian Rogersb861dc02011-11-14 17:00:05 -08002125 }
Ian Rogers28ad40d2011-10-27 15:19:26 -07002126 if (line_number == last_line_number && last_method == m) {
Dave Allison0aded082013-11-07 13:15:11 -08002127 ++repetition_count;
Elliott Hughesd369bb72011-09-12 14:41:14 -07002128 } else {
Ian Rogers28ad40d2011-10-27 15:19:26 -07002129 if (repetition_count >= kMaxRepetition) {
2130 os << " ... repeated " << (repetition_count - kMaxRepetition) << " times\n";
2131 }
2132 repetition_count = 0;
2133 last_line_number = line_number;
2134 last_method = m;
Elliott Hughesd369bb72011-09-12 14:41:14 -07002135 }
Andreas Gampe93104952017-12-13 17:13:15 -08002136
2137 if (repetition_count >= kMaxRepetition) {
2138 // Skip visiting=printing anything.
2139 return VisitMethodResult::kSkipMethod;
Ian Rogers28ad40d2011-10-27 15:19:26 -07002140 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -07002141
Andreas Gampe93104952017-12-13 17:13:15 -08002142 os << " at " << m->PrettyMethod(false);
2143 if (m->IsNative()) {
2144 os << "(Native method)";
2145 } else {
2146 const char* source_file(m->GetDeclaringClassSourceFile());
Daniel Jin35782d42022-01-19 14:58:15 -08002147 if (line_number == -1) {
2148 // If we failed to map to a line number, use
2149 // the dex pc as the line number and leave source file null
2150 source_file = nullptr;
2151 line_number = static_cast<int32_t>(dex_pc);
2152 }
Andreas Gampe93104952017-12-13 17:13:15 -08002153 os << "(" << (source_file != nullptr ? source_file : "unavailable")
2154 << ":" << line_number << ")";
2155 }
2156 os << "\n";
2157 // Go and visit locks.
2158 return VisitMethodResult::kContinueMethod;
Elliott Hughesd369bb72011-09-12 14:41:14 -07002159 }
Elliott Hughes4993bbc2013-01-10 15:41:25 -08002160
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002161 VisitMethodResult EndMethod(ArtMethod* m ATTRIBUTE_UNUSED) override {
Andreas Gampe93104952017-12-13 17:13:15 -08002162 return VisitMethodResult::kContinueMethod;
2163 }
2164
Vladimir Markof52d92f2019-03-29 12:33:02 +00002165 void VisitWaitingObject(ObjPtr<mirror::Object> obj, ThreadState state ATTRIBUTE_UNUSED)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002166 override
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002167 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe93104952017-12-13 17:13:15 -08002168 PrintObject(obj, " - waiting on ", ThreadList::kInvalidThreadId);
2169 }
Vladimir Markof52d92f2019-03-29 12:33:02 +00002170 void VisitSleepingObject(ObjPtr<mirror::Object> obj)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002171 override
Andreas Gampe93104952017-12-13 17:13:15 -08002172 REQUIRES_SHARED(Locks::mutator_lock_) {
2173 PrintObject(obj, " - sleeping on ", ThreadList::kInvalidThreadId);
2174 }
Vladimir Markof52d92f2019-03-29 12:33:02 +00002175 void VisitBlockedOnObject(ObjPtr<mirror::Object> obj,
Andreas Gampe93104952017-12-13 17:13:15 -08002176 ThreadState state,
2177 uint32_t owner_tid)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002178 override
Andreas Gampe93104952017-12-13 17:13:15 -08002179 REQUIRES_SHARED(Locks::mutator_lock_) {
2180 const char* msg;
2181 switch (state) {
Vladimir Markoddf4fd32021-11-22 16:31:57 +00002182 case ThreadState::kBlocked:
Andreas Gampe93104952017-12-13 17:13:15 -08002183 msg = " - waiting to lock ";
2184 break;
2185
Vladimir Markoddf4fd32021-11-22 16:31:57 +00002186 case ThreadState::kWaitingForLockInflation:
Andreas Gampe93104952017-12-13 17:13:15 -08002187 msg = " - waiting for lock inflation of ";
2188 break;
2189
2190 default:
2191 LOG(FATAL) << "Unreachable";
2192 UNREACHABLE();
2193 }
2194 PrintObject(obj, msg, owner_tid);
2195 }
Vladimir Markof52d92f2019-03-29 12:33:02 +00002196 void VisitLockedObject(ObjPtr<mirror::Object> obj)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002197 override
Andreas Gampe93104952017-12-13 17:13:15 -08002198 REQUIRES_SHARED(Locks::mutator_lock_) {
2199 PrintObject(obj, " - locked ", ThreadList::kInvalidThreadId);
2200 }
2201
Vladimir Markof52d92f2019-03-29 12:33:02 +00002202 void PrintObject(ObjPtr<mirror::Object> obj,
Andreas Gampe93104952017-12-13 17:13:15 -08002203 const char* msg,
2204 uint32_t owner_tid) REQUIRES_SHARED(Locks::mutator_lock_) {
2205 if (obj == nullptr) {
2206 os << msg << "an unknown object";
Ian Rogersd803bc72014-04-01 15:33:03 -07002207 } else {
Andreas Gampe93104952017-12-13 17:13:15 -08002208 if ((obj->GetLockWord(true).GetState() == LockWord::kThinLocked) &&
Ian Rogersd803bc72014-04-01 15:33:03 -07002209 Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) {
2210 // Getting the identity hashcode here would result in lock inflation and suspension of the
2211 // current thread, which isn't safe if this is the only runnable thread.
Andreas Gampe93104952017-12-13 17:13:15 -08002212 os << msg << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
Vladimir Markof52d92f2019-03-29 12:33:02 +00002213 reinterpret_cast<intptr_t>(obj.Ptr()),
Andreas Gampe93104952017-12-13 17:13:15 -08002214 obj->PrettyTypeOf().c_str());
Ian Rogersd803bc72014-04-01 15:33:03 -07002215 } else {
Andreas Gampe93104952017-12-13 17:13:15 -08002216 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
2217 // Call PrettyTypeOf before IdentityHashCode since IdentityHashCode can cause thread
2218 // suspension and move pretty_object.
2219 const std::string pretty_type(obj->PrettyTypeOf());
2220 os << msg << StringPrintf("<0x%08x> (a %s)", obj->IdentityHashCode(), pretty_type.c_str());
Ian Rogersd803bc72014-04-01 15:33:03 -07002221 }
2222 }
Andreas Gampe93104952017-12-13 17:13:15 -08002223 if (owner_tid != ThreadList::kInvalidThreadId) {
2224 os << " held by thread " << owner_tid;
2225 }
Ian Rogersd803bc72014-04-01 15:33:03 -07002226 os << "\n";
Elliott Hughes4993bbc2013-01-10 15:41:25 -08002227 }
2228
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002229 std::ostream& os;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002230 ArtMethod* last_method;
Ian Rogers28ad40d2011-10-27 15:19:26 -07002231 int last_line_number;
Andreas Gampe93104952017-12-13 17:13:15 -08002232 size_t repetition_count;
Elliott Hughesd369bb72011-09-12 14:41:14 -07002233};
2234
Ian Rogers33e95662013-05-20 20:29:14 -07002235static bool ShouldShowNativeStack(const Thread* thread)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002236 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesaef701d2013-04-05 18:15:40 -07002237 ThreadState state = thread->GetState();
2238
2239 // In native code somewhere in the VM (one of the kWaitingFor* states)? That's interesting.
Vladimir Markoddf4fd32021-11-22 16:31:57 +00002240 if (state > ThreadState::kWaiting && state < ThreadState::kStarting) {
Elliott Hughesaef701d2013-04-05 18:15:40 -07002241 return true;
2242 }
2243
2244 // In an Object.wait variant or Thread.sleep? That's not interesting.
Vladimir Markoddf4fd32021-11-22 16:31:57 +00002245 if (state == ThreadState::kTimedWaiting ||
2246 state == ThreadState::kSleeping ||
2247 state == ThreadState::kWaiting) {
Elliott Hughesaef701d2013-04-05 18:15:40 -07002248 return false;
2249 }
2250
Christopher Ferris2366f4e2014-09-19 17:23:59 -07002251 // Threads with no managed stack frames should be shown.
Vladimir Markoe7441632017-11-29 13:00:56 +00002252 if (!thread->HasManagedStack()) {
Christopher Ferris2366f4e2014-09-19 17:23:59 -07002253 return true;
2254 }
2255
Elliott Hughesaef701d2013-04-05 18:15:40 -07002256 // In some other native method? That's interesting.
2257 // We don't just check kNative because native methods will be in state kSuspended if they're
2258 // calling back into the VM, or kBlocked if they're blocked on a monitor, or one of the
2259 // thread-startup states if it's early enough in their life cycle (http://b/7432159).
Mathieu Chartiere401d142015-04-22 13:56:20 -07002260 ArtMethod* current_method = thread->GetCurrentMethod(nullptr);
Dave Allison0aded082013-11-07 13:15:11 -08002261 return current_method != nullptr && current_method->IsNative();
Elliott Hughesaef701d2013-04-05 18:15:40 -07002262}
2263
Hiroshi Yamauchi02f365f2017-02-03 15:06:00 -08002264void Thread::DumpJavaStack(std::ostream& os, bool check_suspended, bool dump_locks) const {
Andreas Gampe986c6fb2014-10-02 21:00:06 -07002265 // Dumping the Java stack involves the verifier for locks. The verifier operates under the
2266 // assumption that there is no exception pending on entry. Thus, stash any pending exception.
Mathieu Chartierbef89c92015-01-09 09:46:49 -08002267 // Thread::Current() instead of this in case a thread is dumping the stack of another suspended
2268 // thread.
Alex Lightb7c640d2019-03-20 15:52:13 -07002269 ScopedExceptionStorage ses(Thread::Current());
Andreas Gampe986c6fb2014-10-02 21:00:06 -07002270
Ian Rogers700a4022014-05-19 16:49:03 -07002271 std::unique_ptr<Context> context(Context::Create());
Mathieu Chartierc751fdc2014-03-30 15:25:44 -07002272 StackDumpVisitor dumper(os, const_cast<Thread*>(this), context.get(),
Hiroshi Yamauchi02f365f2017-02-03 15:06:00 -08002273 !tls32_.throwing_OutOfMemoryError, check_suspended, dump_locks);
Mathieu Chartierc751fdc2014-03-30 15:25:44 -07002274 dumper.WalkStack();
2275}
2276
Nicolas Geoffray6ee49712018-03-30 14:39:05 +00002277void Thread::DumpStack(std::ostream& os,
2278 bool dump_native_stack,
2279 BacktraceMap* backtrace_map,
2280 bool force_dump_stack) const {
Jeff Haoed1790e2013-04-12 09:58:14 -07002281 // TODO: we call this code when dying but may not have suspended the thread ourself. The
2282 // IsSuspended check is therefore racy with the use for dumping (normally we inhibit
2283 // the race with the thread_suspend_count_lock_).
Ian Rogerseef2e542014-06-24 22:48:01 -07002284 bool dump_for_abort = (gAborting > 0);
2285 bool safe_to_dump = (this == Thread::Current() || IsSuspended());
2286 if (!kIsDebugBuild) {
2287 // We always want to dump the stack for an abort, however, there is no point dumping another
2288 // thread's stack in debug builds where we'll hit the not suspended check in the stack walk.
2289 safe_to_dump = (safe_to_dump || dump_for_abort);
2290 }
Hiroshi Yamauchi13c16352017-01-31 10:15:08 -08002291 if (safe_to_dump || force_dump_stack) {
Ian Rogersf08e4732013-04-09 09:45:49 -07002292 // If we're currently in native code, dump that stack before dumping the managed stack.
Nicolas Geoffray6ee49712018-03-30 14:39:05 +00002293 if (dump_native_stack && (dump_for_abort || force_dump_stack || ShouldShowNativeStack(this))) {
Hiroshi Yamauchi02f365f2017-02-03 15:06:00 -08002294 ArtMethod* method =
2295 GetCurrentMethod(nullptr,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002296 /*check_suspended=*/ !force_dump_stack,
2297 /*abort_on_error=*/ !(dump_for_abort || force_dump_stack));
Christopher Ferris6cff48f2014-01-26 21:36:13 -08002298 DumpNativeStack(os, GetTid(), backtrace_map, " native: ", method);
Ian Rogersf08e4732013-04-09 09:45:49 -07002299 }
Hiroshi Yamauchi02f365f2017-02-03 15:06:00 -08002300 DumpJavaStack(os,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002301 /*check_suspended=*/ !force_dump_stack,
2302 /*dump_locks=*/ !force_dump_stack);
Ian Rogersf08e4732013-04-09 09:45:49 -07002303 } else {
2304 os << "Not able to dump stack of thread that isn't suspended";
Elliott Hughesffb465f2012-03-01 18:46:05 -08002305 }
Elliott Hughese27955c2011-08-26 15:21:24 -07002306}
2307
Elliott Hughesbe759c62011-09-08 19:38:21 -07002308void Thread::ThreadExitCallback(void* arg) {
2309 Thread* self = reinterpret_cast<Thread*>(arg);
Ian Rogersdd7624d2014-03-14 17:43:00 -07002310 if (self->tls32_.thread_exit_check_count == 0) {
2311 LOG(WARNING) << "Native thread exiting without having called DetachCurrentThread (maybe it's "
2312 "going to use a pthread_key_create destructor?): " << *self;
Ian Rogers0878d652013-04-18 17:38:35 -07002313 CHECK(is_started_);
Andreas Gampea47a6e82019-07-24 09:46:16 -07002314#ifdef __BIONIC__
Andreas Gampe4382f1e2015-08-05 01:08:53 +00002315 __get_tls()[TLS_SLOT_ART_THREAD_SELF] = self;
2316#else
Elliott Hughes6a607ad2012-07-13 20:40:00 -07002317 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, self), "reattach self");
Andreas Gampe82372002019-07-24 15:42:09 -07002318 Thread::self_tls_ = self;
Andreas Gampe4382f1e2015-08-05 01:08:53 +00002319#endif
Ian Rogersdd7624d2014-03-14 17:43:00 -07002320 self->tls32_.thread_exit_check_count = 1;
Elliott Hughes6a607ad2012-07-13 20:40:00 -07002321 } else {
2322 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
2323 }
Carl Shapirob5573532011-07-12 18:22:59 -07002324}
2325
Elliott Hughesbe759c62011-09-08 19:38:21 -07002326void Thread::Startup() {
Ian Rogers0878d652013-04-18 17:38:35 -07002327 CHECK(!is_started_);
2328 is_started_ = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002329 {
Brian Carlstrom6d69f592013-07-16 17:18:16 -07002330 // MutexLock to keep annotalysis happy.
2331 //
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002332 // Note we use null for the thread because Thread::Current can
Brian Carlstrom6d69f592013-07-16 17:18:16 -07002333 // return garbage since (is_started_ == true) and
2334 // Thread::pthread_key_self_ is not yet initialized.
2335 // This was seen on glibc.
Dave Allison0aded082013-11-07 13:15:11 -08002336 MutexLock mu(nullptr, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -07002337 resume_cond_ = new ConditionVariable("Thread resumption condition variable",
2338 *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002339 }
2340
Carl Shapirob5573532011-07-12 18:22:59 -07002341 // Allocate a TLS slot.
Ian Rogersf4d4da12014-11-11 16:10:33 -08002342 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback),
2343 "self key");
Carl Shapirob5573532011-07-12 18:22:59 -07002344
2345 // Double-check the TLS slot allocation.
Dave Allison0aded082013-11-07 13:15:11 -08002346 if (pthread_getspecific(pthread_key_self_) != nullptr) {
2347 LOG(FATAL) << "Newly-created pthread TLS slot is not nullptr";
Carl Shapirob5573532011-07-12 18:22:59 -07002348 }
Andreas Gampe82372002019-07-24 15:42:09 -07002349#ifndef __BIONIC__
2350 CHECK(Thread::self_tls_ == nullptr);
2351#endif
Elliott Hughes038a8062011-09-18 14:12:41 -07002352}
Carl Shapirob5573532011-07-12 18:22:59 -07002353
Elliott Hughes038a8062011-09-18 14:12:41 -07002354void Thread::FinishStartup() {
Ian Rogers365c1022012-06-22 15:05:28 -07002355 Runtime* runtime = Runtime::Current();
2356 CHECK(runtime->IsStarted());
Brian Carlstromb82b6872011-10-26 17:18:07 -07002357
Elliott Hughes01158d72011-09-19 19:47:10 -07002358 // Finish attaching the main thread.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002359 ScopedObjectAccess soa(Thread::Current());
Vladimir Markodcfcce42018-06-27 10:00:28 +00002360 soa.Self()->CreatePeer("main", false, runtime->GetMainThreadGroup());
2361 soa.Self()->AssertNoPendingException();
Jesse Wilson9a6bae82011-11-14 14:57:30 -05002362
Vladimir Markodcfcce42018-06-27 10:00:28 +00002363 runtime->RunRootClinits(soa.Self());
Andreas Gampe21cf95d2017-04-17 20:19:14 -07002364
2365 // The thread counts as started from now on. We need to add it to the ThreadGroup. For regular
2366 // threads, this is done in Thread.start() on the Java side.
Vladimir Markodcfcce42018-06-27 10:00:28 +00002367 soa.Self()->NotifyThreadGroup(soa, runtime->GetMainThreadGroup());
2368 soa.Self()->AssertNoPendingException();
Carl Shapirob5573532011-07-12 18:22:59 -07002369}
2370
Elliott Hughesc1674ed2011-08-25 18:09:09 -07002371void Thread::Shutdown() {
Ian Rogers0878d652013-04-18 17:38:35 -07002372 CHECK(is_started_);
2373 is_started_ = false;
Elliott Hughes8d768a92011-09-14 16:35:25 -07002374 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Ian Rogers33e95662013-05-20 20:29:14 -07002375 MutexLock mu(Thread::Current(), *Locks::thread_suspend_count_lock_);
Dave Allison0aded082013-11-07 13:15:11 -08002376 if (resume_cond_ != nullptr) {
Ian Rogers0878d652013-04-18 17:38:35 -07002377 delete resume_cond_;
Dave Allison0aded082013-11-07 13:15:11 -08002378 resume_cond_ = nullptr;
Ian Rogers0878d652013-04-18 17:38:35 -07002379 }
Elliott Hughesc1674ed2011-08-25 18:09:09 -07002380}
2381
Andreas Gampe56776012018-01-26 17:40:55 -08002382void Thread::NotifyThreadGroup(ScopedObjectAccessAlreadyRunnable& soa, jobject thread_group) {
2383 ScopedLocalRef<jobject> thread_jobject(
2384 soa.Env(), soa.Env()->AddLocalReference<jobject>(Thread::Current()->GetPeer()));
2385 ScopedLocalRef<jobject> thread_group_jobject_scoped(
2386 soa.Env(), nullptr);
2387 jobject thread_group_jobject = thread_group;
2388 if (thread_group == nullptr || kIsDebugBuild) {
2389 // There is always a group set. Retrieve it.
2390 thread_group_jobject_scoped.reset(
2391 soa.Env()->GetObjectField(thread_jobject.get(),
2392 WellKnownClasses::java_lang_Thread_group));
2393 thread_group_jobject = thread_group_jobject_scoped.get();
2394 if (kIsDebugBuild && thread_group != nullptr) {
2395 CHECK(soa.Env()->IsSameObject(thread_group, thread_group_jobject));
2396 }
2397 }
2398 soa.Env()->CallNonvirtualVoidMethod(thread_group_jobject,
2399 WellKnownClasses::java_lang_ThreadGroup,
2400 WellKnownClasses::java_lang_ThreadGroup_add,
2401 thread_jobject.get());
2402}
2403
Calin Juravleccd56952016-12-15 17:57:38 +00002404Thread::Thread(bool daemon)
2405 : tls32_(daemon),
2406 wait_monitor_(nullptr),
Alex Lightcea42152018-09-18 22:51:55 +00002407 is_runtime_thread_(false) {
Charles Mungerc665d632018-11-06 16:20:13 +00002408 wait_mutex_ = new Mutex("a thread wait mutex", LockLevel::kThreadWaitLock);
Ian Rogersdd7624d2014-03-14 17:43:00 -07002409 wait_cond_ = new ConditionVariable("a thread wait condition variable", *wait_mutex_);
Vladimir Marko23cf32f2021-11-15 13:38:02 +00002410 tlsPtr_.mutator_lock = Locks::mutator_lock_;
2411 DCHECK(tlsPtr_.mutator_lock != nullptr);
Nicolas Geoffraye91e7952020-01-23 10:15:56 +00002412 tlsPtr_.instrumentation_stack =
2413 new std::map<uintptr_t, instrumentation::InstrumentationStackFrame>;
Hans Boehm30bc7772022-01-28 15:07:02 -08002414 tlsPtr_.name.store(kThreadNameDuringStartup, std::memory_order_relaxed);
Ian Rogersdd7624d2014-03-14 17:43:00 -07002415
Roland Levillain33d69032015-06-18 18:20:59 +01002416 static_assert((sizeof(Thread) % 4) == 0U,
2417 "art::Thread has a size which is not a multiple of 4.");
Vladimir Marko9c0f7642021-12-06 16:17:52 +00002418 DCHECK_EQ(GetStateAndFlags(std::memory_order_relaxed).GetValue(), 0u);
2419 StateAndFlags state_and_flags = StateAndFlags(0u).WithState(ThreadState::kNative);
Vladimir Markoddf4fd32021-11-22 16:31:57 +00002420 tls32_.state_and_flags.store(state_and_flags.GetValue(), std::memory_order_relaxed);
Orion Hodson88591fe2018-03-06 13:35:43 +00002421 tls32_.interrupted.store(false, std::memory_order_relaxed);
Charles Mungeraa31f492018-11-01 18:57:38 +00002422 // Initialize with no permit; if the java Thread was unparked before being
2423 // started, it will unpark itself before calling into java code.
2424 tls32_.park_state_.store(kNoPermit, std::memory_order_relaxed);
Ian Rogersdd7624d2014-03-14 17:43:00 -07002425 memset(&tlsPtr_.held_mutexes[0], 0, sizeof(tlsPtr_.held_mutexes));
Mathieu Chartier0651d412014-04-29 14:37:57 -07002426 std::fill(tlsPtr_.rosalloc_runs,
Hiroshi Yamauchi7ed9c562016-02-02 15:22:09 -08002427 tlsPtr_.rosalloc_runs + kNumRosAllocThreadLocalSizeBracketsInThread,
Mathieu Chartier73d1e172014-04-11 17:53:48 -07002428 gc::allocator::RosAlloc::GetDedicatedFullRun());
Mathieu Chartier952e1e32016-06-13 14:04:02 -07002429 tlsPtr_.checkpoint_function = nullptr;
Yu Lieac44242015-06-29 10:50:03 +08002430 for (uint32_t i = 0; i < kMaxSuspendBarriers; ++i) {
2431 tlsPtr_.active_suspend_barriers[i] = nullptr;
2432 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002433 tlsPtr_.flip_function = nullptr;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002434 tlsPtr_.thread_local_mark_stack = nullptr;
Hiroshi Yamauchiee235822016-08-19 17:03:27 -07002435 tls32_.is_transitioning_to_runnable = false;
Mathieu Chartierc4bf6672020-01-13 13:07:16 -08002436 ResetTlab();
David Srbecky28f6cff2018-10-16 15:07:28 +01002437}
2438
Alex Lighte9f61032018-09-24 16:04:51 -07002439bool Thread::CanLoadClasses() const {
2440 return !IsRuntimeThread() || !Runtime::Current()->IsJavaDebuggable();
2441}
2442
Elliott Hughes7dc51662012-05-16 14:48:43 -07002443bool Thread::IsStillStarting() const {
2444 // You might think you can check whether the state is kStarting, but for much of thread startup,
Elliott Hughes80537bb2013-01-04 16:37:26 -08002445 // the thread is in kNative; it might also be in kVmWait.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002446 // You might think you can check whether the peer is null, but the peer is actually created and
Elliott Hughes7dc51662012-05-16 14:48:43 -07002447 // assigned fairly early on, and needs to be.
2448 // It turns out that the last thing to change is the thread name; that's a good proxy for "has
2449 // this thread _ever_ entered kRunnable".
Ian Rogersdd7624d2014-03-14 17:43:00 -07002450 return (tlsPtr_.jpeer == nullptr && tlsPtr_.opeer == nullptr) ||
Hans Boehm30bc7772022-01-28 15:07:02 -08002451 (tlsPtr_.name.load() == kThreadNameDuringStartup);
Elliott Hughes7dc51662012-05-16 14:48:43 -07002452}
2453
Andreas Gamped9efea62014-07-21 22:56:08 -07002454void Thread::AssertPendingException() const {
Mathieu Chartiera61894d2015-04-23 16:32:54 -07002455 CHECK(IsExceptionPending()) << "Pending exception expected.";
2456}
2457
2458void Thread::AssertPendingOOMException() const {
2459 AssertPendingException();
2460 auto* e = GetException();
2461 CHECK_EQ(e->GetClass(), DecodeJObject(WellKnownClasses::java_lang_OutOfMemoryError)->AsClass())
2462 << e->Dump();
Andreas Gamped9efea62014-07-21 22:56:08 -07002463}
2464
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002465void Thread::AssertNoPendingException() const {
2466 if (UNLIKELY(IsExceptionPending())) {
2467 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierf5769e12017-01-10 15:54:41 -08002468 LOG(FATAL) << "No pending exception expected: " << GetException()->Dump();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002469 }
2470}
2471
Mathieu Chartier8d7672e2014-02-25 10:57:16 -08002472void Thread::AssertNoPendingExceptionForNewException(const char* msg) const {
2473 if (UNLIKELY(IsExceptionPending())) {
2474 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc114b5f2014-07-21 08:55:01 -07002475 LOG(FATAL) << "Throwing new exception '" << msg << "' with unexpected pending exception: "
Mathieu Chartierf5769e12017-01-10 15:54:41 -08002476 << GetException()->Dump();
Mathieu Chartier8d7672e2014-02-25 10:57:16 -08002477 }
2478}
2479
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002480class MonitorExitVisitor : public SingleRootVisitor {
2481 public:
2482 explicit MonitorExitVisitor(Thread* self) : self_(self) { }
2483
2484 // NO_THREAD_SAFETY_ANALYSIS due to MonitorExit.
2485 void VisitRoot(mirror::Object* entered_monitor, const RootInfo& info ATTRIBUTE_UNUSED)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002486 override NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002487 if (self_->HoldsLock(entered_monitor)) {
2488 LOG(WARNING) << "Calling MonitorExit on object "
David Sehr709b0702016-10-13 09:12:37 -07002489 << entered_monitor << " (" << entered_monitor->PrettyTypeOf() << ")"
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002490 << " left locked by native thread "
2491 << *Thread::Current() << " which is detaching";
2492 entered_monitor->MonitorExit(self_);
2493 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002494 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002495
2496 private:
2497 Thread* const self_;
2498};
Elliott Hughes02b48d12011-09-07 17:15:51 -07002499
Elliott Hughesc0f09332012-03-26 13:27:06 -07002500void Thread::Destroy() {
Ian Rogers120f1c72012-09-28 17:17:10 -07002501 Thread* self = this;
2502 DCHECK_EQ(self, Thread::Current());
Elliott Hughes02b48d12011-09-07 17:15:51 -07002503
Ian Rogers68d8b422014-07-17 11:09:10 -07002504 if (tlsPtr_.jni_env != nullptr) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002505 {
2506 ScopedObjectAccess soa(self);
2507 MonitorExitVisitor visitor(self);
2508 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Ian Rogers55256cb2017-12-21 17:07:11 -08002509 tlsPtr_.jni_env->monitors_.VisitRoots(&visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002510 }
Ian Rogers68d8b422014-07-17 11:09:10 -07002511 // Release locally held global references which releasing may require the mutator lock.
2512 if (tlsPtr_.jpeer != nullptr) {
2513 // If pthread_create fails we don't have a jni env here.
2514 tlsPtr_.jni_env->DeleteGlobalRef(tlsPtr_.jpeer);
2515 tlsPtr_.jpeer = nullptr;
2516 }
2517 if (tlsPtr_.class_loader_override != nullptr) {
2518 tlsPtr_.jni_env->DeleteGlobalRef(tlsPtr_.class_loader_override);
2519 tlsPtr_.class_loader_override = nullptr;
2520 }
2521 }
2522
Ian Rogersdd7624d2014-03-14 17:43:00 -07002523 if (tlsPtr_.opeer != nullptr) {
Ian Rogerscfaa4552012-11-26 21:00:08 -08002524 ScopedObjectAccess soa(self);
Ian Rogers120f1c72012-09-28 17:17:10 -07002525 // We may need to call user-supplied managed code, do this before final clean-up.
Ian Rogerscfaa4552012-11-26 21:00:08 -08002526 HandleUncaughtExceptions(soa);
Alex Lightdf132402017-09-29 12:54:33 -07002527 RemoveFromThreadGroup(soa);
Alex Light8c5e2da2017-07-11 10:32:20 -07002528 Runtime* runtime = Runtime::Current();
2529 if (runtime != nullptr) {
2530 runtime->GetRuntimeCallbacks()->ThreadDeath(self);
2531 }
Elliott Hughes534da072012-03-27 15:17:42 -07002532
Anwar Ghuloum3c50a4b2013-06-21 13:05:23 -07002533 // this.nativePeer = 0;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002534 if (Runtime::Current()->IsActiveTransaction()) {
Andreas Gampe08883de2016-11-08 13:20:52 -08002535 jni::DecodeArtField(WellKnownClasses::java_lang_Thread_nativePeer)
Ian Rogersdd7624d2014-03-14 17:43:00 -07002536 ->SetLong<true>(tlsPtr_.opeer, 0);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002537 } else {
Andreas Gampe08883de2016-11-08 13:20:52 -08002538 jni::DecodeArtField(WellKnownClasses::java_lang_Thread_nativePeer)
Ian Rogersdd7624d2014-03-14 17:43:00 -07002539 ->SetLong<false>(tlsPtr_.opeer, 0);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002540 }
Elliott Hughes02b48d12011-09-07 17:15:51 -07002541
Ian Rogerscfaa4552012-11-26 21:00:08 -08002542 // Thread.join() is implemented as an Object.wait() on the Thread.lock object. Signal anyone
2543 // who is waiting.
Mathieu Chartier3398c782016-09-30 10:27:43 -07002544 ObjPtr<mirror::Object> lock =
Andreas Gampe08883de2016-11-08 13:20:52 -08002545 jni::DecodeArtField(WellKnownClasses::java_lang_Thread_lock)->GetObject(tlsPtr_.opeer);
Elliott Hughes038a8062011-09-18 14:12:41 -07002546 // (This conditional is only needed for tests, where Thread.lock won't have been set.)
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002547 if (lock != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002548 StackHandleScope<1> hs(self);
2549 Handle<mirror::Object> h_obj(hs.NewHandle(lock));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002550 ObjectLock<mirror::Object> locker(self, h_obj);
Yevgeny Rouban63e8a682014-04-16 18:26:09 +07002551 locker.NotifyAll();
Elliott Hughes5f791332011-09-15 17:45:30 -07002552 }
Ian Rogers68d8b422014-07-17 11:09:10 -07002553 tlsPtr_.opeer = nullptr;
Elliott Hughes5f791332011-09-15 17:45:30 -07002554 }
Ian Rogers120f1c72012-09-28 17:17:10 -07002555
Hiroshi Yamauchia1b94c62014-12-17 15:49:56 -08002556 {
2557 ScopedObjectAccess soa(self);
2558 Runtime::Current()->GetHeap()->RevokeThreadLocalBuffers(this);
Lokesh Gidra93170312019-12-04 13:46:11 -08002559 }
2560 // Mark-stack revocation must be performed at the very end. No
2561 // checkpoint/flip-function or read-barrier should be called after this.
2562 if (kUseReadBarrier) {
2563 Runtime::Current()->GetHeap()->ConcurrentCopyingCollector()->RevokeThreadLocalMarkStack(this);
Hiroshi Yamauchia1b94c62014-12-17 15:49:56 -08002564 }
Elliott Hughesc0f09332012-03-26 13:27:06 -07002565}
Elliott Hughes02b48d12011-09-07 17:15:51 -07002566
Elliott Hughesc0f09332012-03-26 13:27:06 -07002567Thread::~Thread() {
Ian Rogers68d8b422014-07-17 11:09:10 -07002568 CHECK(tlsPtr_.class_loader_override == nullptr);
2569 CHECK(tlsPtr_.jpeer == nullptr);
2570 CHECK(tlsPtr_.opeer == nullptr);
Ian Rogersdd7624d2014-03-14 17:43:00 -07002571 bool initialized = (tlsPtr_.jni_env != nullptr); // Did Thread::Init run?
Alexei Zavjalov1efa0a92014-02-04 02:08:31 +07002572 if (initialized) {
Ian Rogersdd7624d2014-03-14 17:43:00 -07002573 delete tlsPtr_.jni_env;
2574 tlsPtr_.jni_env = nullptr;
Alexei Zavjalov1efa0a92014-02-04 02:08:31 +07002575 }
Vladimir Markoddf4fd32021-11-22 16:31:57 +00002576 CHECK_NE(GetState(), ThreadState::kRunnable);
2577 CHECK(!ReadFlag(ThreadFlag::kCheckpointRequest));
2578 CHECK(!ReadFlag(ThreadFlag::kEmptyCheckpointRequest));
Mathieu Chartier952e1e32016-06-13 14:04:02 -07002579 CHECK(tlsPtr_.checkpoint_function == nullptr);
2580 CHECK_EQ(checkpoint_overflow_.size(), 0u);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002581 CHECK(tlsPtr_.flip_function == nullptr);
Hiroshi Yamauchiee235822016-08-19 17:03:27 -07002582 CHECK_EQ(tls32_.is_transitioning_to_runnable, false);
Dave Allison0aded082013-11-07 13:15:11 -08002583
Sebastien Hertz07474662015-08-25 15:12:33 +00002584 // Make sure we processed all deoptimization requests.
2585 CHECK(tlsPtr_.deoptimization_context_stack == nullptr) << "Missed deoptimization";
Mingyao Yang99170c62015-07-06 11:10:37 -07002586 CHECK(tlsPtr_.frame_id_to_shadow_frame == nullptr) <<
2587 "Not all deoptimized frames have been consumed by the debugger.";
Sebastien Hertz07474662015-08-25 15:12:33 +00002588
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002589 // We may be deleting a still born thread.
Vladimir Markoddf4fd32021-11-22 16:31:57 +00002590 SetStateUnsafe(ThreadState::kTerminated);
Elliott Hughes85d15452011-09-16 17:33:01 -07002591
2592 delete wait_cond_;
2593 delete wait_mutex_;
2594
Ian Rogersdd7624d2014-03-14 17:43:00 -07002595 if (tlsPtr_.long_jump_context != nullptr) {
2596 delete tlsPtr_.long_jump_context;
Ian Rogersc928de92013-02-27 14:30:44 -08002597 }
Elliott Hughes475fc232011-10-25 15:00:35 -07002598
Alexei Zavjalov1efa0a92014-02-04 02:08:31 +07002599 if (initialized) {
2600 CleanupCpu();
2601 }
2602
Ian Rogersdd7624d2014-03-14 17:43:00 -07002603 delete tlsPtr_.instrumentation_stack;
Hans Boehm30bc7772022-01-28 15:07:02 -08002604 SetCachedThreadName(nullptr); // Deallocate name.
Nicolas Geoffray340dafa2016-11-18 16:03:10 +00002605 delete tlsPtr_.deps_or_stack_trace_sample.stack_trace_sample;
Elliott Hughesd8af1592012-04-16 20:40:15 -07002606
Ian Rogers68d8b422014-07-17 11:09:10 -07002607 Runtime::Current()->GetHeap()->AssertThreadLocalBuffersAreRevoked(this);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07002608
Elliott Hughesd8af1592012-04-16 20:40:15 -07002609 TearDownAlternateSignalStack();
Elliott Hughesc1674ed2011-08-25 18:09:09 -07002610}
2611
Andreas Gampe513061a2017-06-01 09:17:34 -07002612void Thread::HandleUncaughtExceptions(ScopedObjectAccessAlreadyRunnable& soa) {
Elliott Hughesaccd83d2011-10-17 14:25:58 -07002613 if (!IsExceptionPending()) {
2614 return;
2615 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002616 ScopedLocalRef<jobject> peer(tlsPtr_.jni_env, soa.AddLocalReference<jobject>(tlsPtr_.opeer));
Vladimir Markoddf4fd32021-11-22 16:31:57 +00002617 ScopedThreadStateChange tsc(this, ThreadState::kNative);
Ian Rogers120f1c72012-09-28 17:17:10 -07002618
Elliott Hughesaccd83d2011-10-17 14:25:58 -07002619 // Get and clear the exception.
Ian Rogersdd7624d2014-03-14 17:43:00 -07002620 ScopedLocalRef<jthrowable> exception(tlsPtr_.jni_env, tlsPtr_.jni_env->ExceptionOccurred());
2621 tlsPtr_.jni_env->ExceptionClear();
Elliott Hughesaccd83d2011-10-17 14:25:58 -07002622
Tobias Thierer5cbe65d2016-07-22 18:37:59 +01002623 // Call the Thread instance's dispatchUncaughtException(Throwable)
2624 tlsPtr_.jni_env->CallVoidMethod(peer.get(),
2625 WellKnownClasses::java_lang_Thread_dispatchUncaughtException,
2626 exception.get());
Elliott Hughesaccd83d2011-10-17 14:25:58 -07002627
Tobias Thierer5cbe65d2016-07-22 18:37:59 +01002628 // If the dispatchUncaughtException threw, clear that exception too.
Ian Rogersdd7624d2014-03-14 17:43:00 -07002629 tlsPtr_.jni_env->ExceptionClear();
Elliott Hughesaccd83d2011-10-17 14:25:58 -07002630}
2631
Andreas Gampe513061a2017-06-01 09:17:34 -07002632void Thread::RemoveFromThreadGroup(ScopedObjectAccessAlreadyRunnable& soa) {
Brian Carlstrom4514d3c2011-10-21 17:01:31 -07002633 // this.group.removeThread(this);
2634 // group can be null if we're in the compiler or a test.
Andreas Gampe08883de2016-11-08 13:20:52 -08002635 ObjPtr<mirror::Object> ogroup = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group)
Ian Rogersdd7624d2014-03-14 17:43:00 -07002636 ->GetObject(tlsPtr_.opeer);
Dave Allison0aded082013-11-07 13:15:11 -08002637 if (ogroup != nullptr) {
Ian Rogerscfaa4552012-11-26 21:00:08 -08002638 ScopedLocalRef<jobject> group(soa.Env(), soa.AddLocalReference<jobject>(ogroup));
Ian Rogersdd7624d2014-03-14 17:43:00 -07002639 ScopedLocalRef<jobject> peer(soa.Env(), soa.AddLocalReference<jobject>(tlsPtr_.opeer));
Vladimir Markoddf4fd32021-11-22 16:31:57 +00002640 ScopedThreadStateChange tsc(soa.Self(), ThreadState::kNative);
Ian Rogersdd7624d2014-03-14 17:43:00 -07002641 tlsPtr_.jni_env->CallVoidMethod(group.get(),
2642 WellKnownClasses::java_lang_ThreadGroup_removeThread,
2643 peer.get());
Brian Carlstrom4514d3c2011-10-21 17:01:31 -07002644 }
2645}
2646
Vladimir Markocedec9d2021-02-08 16:16:13 +00002647template <bool kPointsToStack>
2648class JniTransitionReferenceVisitor : public StackVisitor {
2649 public:
2650 JniTransitionReferenceVisitor(Thread* thread, void* obj) REQUIRES_SHARED(Locks::mutator_lock_)
2651 : StackVisitor(thread, /*context=*/ nullptr, StackVisitor::StackWalkKind::kSkipInlinedFrames),
2652 obj_(obj),
2653 found_(false) {}
2654
2655 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
2656 ArtMethod* m = GetMethod();
2657 if (!m->IsNative() || m->IsCriticalNative()) {
2658 return true;
2659 }
2660 if (kPointsToStack) {
2661 uint8_t* sp = reinterpret_cast<uint8_t*>(GetCurrentQuickFrame());
2662 size_t frame_size = GetCurrentQuickFrameInfo().FrameSizeInBytes();
2663 uint32_t* current_vreg = reinterpret_cast<uint32_t*>(sp + frame_size + sizeof(ArtMethod*));
2664 if (!m->IsStatic()) {
2665 if (current_vreg == obj_) {
2666 found_ = true;
2667 return false;
2668 }
2669 current_vreg += 1u;
2670 }
Jared Duke968c8132021-11-02 16:47:54 -07002671 uint32_t shorty_length;
2672 const char* shorty = m->GetShorty(&shorty_length);
2673 for (size_t i = 1; i != shorty_length; ++i) {
Vladimir Markocedec9d2021-02-08 16:16:13 +00002674 switch (shorty[i]) {
2675 case 'D':
2676 case 'J':
2677 current_vreg += 2u;
2678 break;
2679 case 'L':
2680 if (current_vreg == obj_) {
2681 found_ = true;
2682 return false;
2683 }
2684 FALLTHROUGH_INTENDED;
2685 default:
2686 current_vreg += 1u;
2687 break;
2688 }
2689 }
2690 // Continue only if the object is somewhere higher on the stack.
2691 return obj_ >= current_vreg;
2692 } else { // if (kPointsToStack)
2693 if (m->IsStatic() && obj_ == m->GetDeclaringClassAddressWithoutBarrier()) {
2694 found_ = true;
2695 return false;
2696 }
Ian Rogersa8cd9f42011-08-19 16:43:41 -07002697 return true;
2698 }
2699 }
Vladimir Markocedec9d2021-02-08 16:16:13 +00002700
2701 bool Found() const {
2702 return found_;
2703 }
2704
2705 private:
2706 void* obj_;
2707 bool found_;
2708};
2709
2710bool Thread::IsJniTransitionReference(jobject obj) const {
2711 DCHECK(obj != nullptr);
2712 // We need a non-const pointer for stack walk even if we're not modifying the thread state.
2713 Thread* thread = const_cast<Thread*>(this);
2714 uint8_t* raw_obj = reinterpret_cast<uint8_t*>(obj);
2715 if (static_cast<size_t>(raw_obj - tlsPtr_.stack_begin) < tlsPtr_.stack_size) {
2716 JniTransitionReferenceVisitor</*kPointsToStack=*/ true> visitor(thread, raw_obj);
2717 visitor.WalkStack();
2718 return visitor.Found();
2719 } else {
2720 JniTransitionReferenceVisitor</*kPointsToStack=*/ false> visitor(thread, raw_obj);
2721 visitor.WalkStack();
2722 return visitor.Found();
2723 }
TDYa12728f1a142012-03-15 21:51:52 -07002724}
2725
Eric Holkf1e1dd12020-08-21 15:38:12 -07002726void Thread::HandleScopeVisitRoots(RootVisitor* visitor, uint32_t thread_id) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07002727 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(
2728 visitor, RootInfo(kRootNativeStack, thread_id));
Mathieu Chartiere8a3c572016-10-11 16:52:17 -07002729 for (BaseHandleScope* cur = tlsPtr_.top_handle_scope; cur; cur = cur->GetLink()) {
2730 cur->VisitRoots(buffered_visitor);
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07002731 }
2732}
2733
Mathieu Chartierc4f39252016-10-05 18:32:08 -07002734ObjPtr<mirror::Object> Thread::DecodeJObject(jobject obj) const {
Dave Allison0aded082013-11-07 13:15:11 -08002735 if (obj == nullptr) {
2736 return nullptr;
Ian Rogers408f79a2011-08-23 18:22:33 -07002737 }
2738 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
Andreas Gampedc061d02016-10-24 13:19:37 -07002739 IndirectRefKind kind = IndirectReferenceTable::GetIndirectRefKind(ref);
Mathieu Chartier8778c522016-10-04 19:06:30 -07002740 ObjPtr<mirror::Object> result;
Ian Rogersc0542af2014-09-03 16:16:56 -07002741 bool expect_null = false;
Ian Rogers4f6ad8a2013-03-18 15:27:28 -07002742 // The "kinds" below are sorted by the frequency we expect to encounter them.
2743 if (kind == kLocal) {
Ian Rogers55256cb2017-12-21 17:07:11 -08002744 IndirectReferenceTable& locals = tlsPtr_.jni_env->locals_;
Hiroshi Yamauchi196851b2014-05-29 12:16:04 -07002745 // Local references do not need a read barrier.
2746 result = locals.Get<kWithoutReadBarrier>(ref);
Vladimir Markocedec9d2021-02-08 16:16:13 +00002747 } else if (kind == kJniTransitionOrInvalid) {
2748 // The `jclass` for a static method points to the CompressedReference<> in the
2749 // `ArtMethod::declaring_class_`. Other `jobject` arguments point to spilled stack
2750 // references but a StackReference<> is just a subclass of CompressedReference<>.
2751 DCHECK(IsJniTransitionReference(obj));
2752 result = reinterpret_cast<mirror::CompressedReference<mirror::Object>*>(obj)->AsMirrorPtr();
Vladimir Marko17491ac2020-12-01 12:02:29 +00002753 VerifyObject(result);
Ian Rogers4f6ad8a2013-03-18 15:27:28 -07002754 } else if (kind == kGlobal) {
Ian Rogers55256cb2017-12-21 17:07:11 -08002755 result = tlsPtr_.jni_env->vm_->DecodeGlobal(ref);
Ian Rogers4f6ad8a2013-03-18 15:27:28 -07002756 } else {
2757 DCHECK_EQ(kind, kWeakGlobal);
Ian Rogers55256cb2017-12-21 17:07:11 -08002758 result = tlsPtr_.jni_env->vm_->DecodeWeakGlobal(const_cast<Thread*>(this), ref);
Ian Rogersc0542af2014-09-03 16:16:56 -07002759 if (Runtime::Current()->IsClearedJniWeakGlobal(result)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002760 // This is a special case where it's okay to return null.
Ian Rogersc0542af2014-09-03 16:16:56 -07002761 expect_null = true;
2762 result = nullptr;
Ian Rogers4f6ad8a2013-03-18 15:27:28 -07002763 }
Ian Rogers408f79a2011-08-23 18:22:33 -07002764 }
2765
Vladimir Marko17491ac2020-12-01 12:02:29 +00002766 DCHECK(expect_null || result != nullptr)
2767 << "use of deleted " << ToStr<IndirectRefKind>(kind).c_str()
2768 << " " << static_cast<const void*>(obj);
Mathieu Chartierc4f39252016-10-05 18:32:08 -07002769 return result;
Ian Rogers408f79a2011-08-23 18:22:33 -07002770}
2771
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08002772bool Thread::IsJWeakCleared(jweak obj) const {
2773 CHECK(obj != nullptr);
2774 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
Andreas Gampedc061d02016-10-24 13:19:37 -07002775 IndirectRefKind kind = IndirectReferenceTable::GetIndirectRefKind(ref);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08002776 CHECK_EQ(kind, kWeakGlobal);
Ian Rogers55256cb2017-12-21 17:07:11 -08002777 return tlsPtr_.jni_env->vm_->IsWeakGlobalCleared(const_cast<Thread*>(this), ref);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08002778}
2779
Ian Rogers81d425b2012-09-27 16:03:43 -07002780// Implements java.lang.Thread.interrupted.
2781bool Thread::Interrupted() {
Nicolas Geoffray365719c2017-03-08 13:11:50 +00002782 DCHECK_EQ(Thread::Current(), this);
2783 // No other thread can concurrently reset the interrupted flag.
Orion Hodson88591fe2018-03-06 13:35:43 +00002784 bool interrupted = tls32_.interrupted.load(std::memory_order_seq_cst);
Nicolas Geoffray365719c2017-03-08 13:11:50 +00002785 if (interrupted) {
Orion Hodson88591fe2018-03-06 13:35:43 +00002786 tls32_.interrupted.store(false, std::memory_order_seq_cst);
Nicolas Geoffray365719c2017-03-08 13:11:50 +00002787 }
Ian Rogers81d425b2012-09-27 16:03:43 -07002788 return interrupted;
2789}
2790
2791// Implements java.lang.Thread.isInterrupted.
2792bool Thread::IsInterrupted() {
Orion Hodson88591fe2018-03-06 13:35:43 +00002793 return tls32_.interrupted.load(std::memory_order_seq_cst);
Ian Rogers81d425b2012-09-27 16:03:43 -07002794}
2795
Ian Rogersdd7624d2014-03-14 17:43:00 -07002796void Thread::Interrupt(Thread* self) {
Charles Mungeraa31f492018-11-01 18:57:38 +00002797 {
2798 MutexLock mu(self, *wait_mutex_);
2799 if (tls32_.interrupted.load(std::memory_order_seq_cst)) {
2800 return;
2801 }
2802 tls32_.interrupted.store(true, std::memory_order_seq_cst);
2803 NotifyLocked(self);
Ian Rogers81d425b2012-09-27 16:03:43 -07002804 }
Charles Mungeraa31f492018-11-01 18:57:38 +00002805 Unpark();
Ian Rogers81d425b2012-09-27 16:03:43 -07002806}
2807
2808void Thread::Notify() {
Ian Rogersc604d732012-10-14 16:09:54 -07002809 Thread* self = Thread::Current();
2810 MutexLock mu(self, *wait_mutex_);
2811 NotifyLocked(self);
Ian Rogers81d425b2012-09-27 16:03:43 -07002812}
2813
Ian Rogersc604d732012-10-14 16:09:54 -07002814void Thread::NotifyLocked(Thread* self) {
Dave Allison0aded082013-11-07 13:15:11 -08002815 if (wait_monitor_ != nullptr) {
Ian Rogersc604d732012-10-14 16:09:54 -07002816 wait_cond_->Signal(self);
Ian Rogers81d425b2012-09-27 16:03:43 -07002817 }
2818}
2819
Ian Rogers68d8b422014-07-17 11:09:10 -07002820void Thread::SetClassLoaderOverride(jobject class_loader_override) {
2821 if (tlsPtr_.class_loader_override != nullptr) {
2822 GetJniEnv()->DeleteGlobalRef(tlsPtr_.class_loader_override);
2823 }
2824 tlsPtr_.class_loader_override = GetJniEnv()->NewGlobalRef(class_loader_override);
2825}
2826
Mathieu Chartier65b8bb22017-02-01 11:03:50 -08002827using ArtMethodDexPcPair = std::pair<ArtMethod*, uint32_t>;
2828
2829// Counts the stack trace depth and also fetches the first max_saved_frames frames.
2830class FetchStackTraceVisitor : public StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07002831 public:
Mathieu Chartier65b8bb22017-02-01 11:03:50 -08002832 explicit FetchStackTraceVisitor(Thread* thread,
2833 ArtMethodDexPcPair* saved_frames = nullptr,
2834 size_t max_saved_frames = 0)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002835 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002836 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
Mathieu Chartier65b8bb22017-02-01 11:03:50 -08002837 saved_frames_(saved_frames),
2838 max_saved_frames_(max_saved_frames) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07002839
Andreas Gampefa6a1b02018-09-07 08:11:55 -07002840 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughes29f27422011-09-18 16:02:18 -07002841 // We want to skip frames up to and including the exception's constructor.
Ian Rogers90865722011-09-19 11:11:44 -07002842 // Note we also skip the frame if it doesn't have a method (namely the callee
2843 // save frame)
Mathieu Chartiere401d142015-04-22 13:56:20 -07002844 ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002845 if (skipping_ && !m->IsRuntimeMethod() &&
Vladimir Markoadbceb72018-05-29 14:34:14 +01002846 !GetClassRoot<mirror::Throwable>()->IsAssignableFrom(m->GetDeclaringClass())) {
Elliott Hughes29f27422011-09-18 16:02:18 -07002847 skipping_ = false;
2848 }
2849 if (!skipping_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002850 if (!m->IsRuntimeMethod()) { // Ignore runtime frames (in particular callee save).
Mathieu Chartier65b8bb22017-02-01 11:03:50 -08002851 if (depth_ < max_saved_frames_) {
2852 saved_frames_[depth_].first = m;
Andreas Gampee2abbc62017-09-15 11:59:26 -07002853 saved_frames_[depth_].second = m->IsProxyMethod() ? dex::kDexNoIndex : GetDexPc();
Mathieu Chartier65b8bb22017-02-01 11:03:50 -08002854 }
Ian Rogers6b0870d2011-12-15 19:38:12 -08002855 ++depth_;
2856 }
Elliott Hughes29f27422011-09-18 16:02:18 -07002857 } else {
2858 ++skip_depth_;
2859 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002860 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002861 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07002862
Mathieu Chartier65b8bb22017-02-01 11:03:50 -08002863 uint32_t GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -07002864 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07002865 }
2866
Mathieu Chartier65b8bb22017-02-01 11:03:50 -08002867 uint32_t GetSkipDepth() const {
Elliott Hughes29f27422011-09-18 16:02:18 -07002868 return skip_depth_;
2869 }
2870
Shih-wei Liao9b576b42011-08-29 01:45:07 -07002871 private:
Mathieu Chartier65b8bb22017-02-01 11:03:50 -08002872 uint32_t depth_ = 0;
2873 uint32_t skip_depth_ = 0;
2874 bool skipping_ = true;
2875 ArtMethodDexPcPair* saved_frames_;
2876 const size_t max_saved_frames_;
Sebastien Hertz26f72862015-09-15 09:52:07 +02002877
Mathieu Chartier65b8bb22017-02-01 11:03:50 -08002878 DISALLOW_COPY_AND_ASSIGN(FetchStackTraceVisitor);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07002879};
2880
Ian Rogers0399dde2012-06-06 17:09:28 -07002881class BuildInternalStackTraceVisitor : public StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07002882 public:
Eric Holkf1e1dd12020-08-21 15:38:12 -07002883 BuildInternalStackTraceVisitor(Thread* self, Thread* thread, uint32_t skip_depth)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002884 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2885 self_(self),
2886 skip_depth_(skip_depth),
Mathieu Chartiere401d142015-04-22 13:56:20 -07002887 pointer_size_(Runtime::Current()->GetClassLinker()->GetImagePointerSize()) {}
Ian Rogers283ed0d2012-02-16 15:25:09 -08002888
Eric Holkf1e1dd12020-08-21 15:38:12 -07002889 bool Init(uint32_t depth) REQUIRES_SHARED(Locks::mutator_lock_) ACQUIRE(Roles::uninterruptible_) {
Mathieu Chartier910e8272015-09-30 09:24:22 -07002890 // Allocate method trace as an object array where the first element is a pointer array that
2891 // contains the ArtMethod pointers and dex PCs. The rest of the elements are the declaring
2892 // class of the ArtMethod pointers.
2893 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2894 StackHandleScope<1> hs(self_);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002895 ObjPtr<mirror::Class> array_class =
2896 GetClassRoot<mirror::ObjectArray<mirror::Object>>(class_linker);
Mathieu Chartier910e8272015-09-30 09:24:22 -07002897 // The first element is the methods and dex pc array, the other elements are declaring classes
2898 // for the methods to ensure classes in the stack trace don't get unloaded.
2899 Handle<mirror::ObjectArray<mirror::Object>> trace(
Eric Holkf1e1dd12020-08-21 15:38:12 -07002900 hs.NewHandle(mirror::ObjectArray<mirror::Object>::Alloc(
2901 hs.Self(), array_class, static_cast<int32_t>(depth) + 1)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002902 if (trace == nullptr) {
Mathieu Chartier910e8272015-09-30 09:24:22 -07002903 // Acquire uninterruptible_ in all paths.
2904 self_->StartAssertNoThreadSuspension("Building internal stack trace");
Mathieu Chartier566fc922015-09-29 10:21:55 -07002905 self_->AssertPendingOOMException();
2906 return false;
2907 }
Mathieu Chartierf5769e12017-01-10 15:54:41 -08002908 ObjPtr<mirror::PointerArray> methods_and_pcs =
2909 class_linker->AllocPointerArray(self_, depth * 2);
Mathieu Chartier910e8272015-09-30 09:24:22 -07002910 const char* last_no_suspend_cause =
2911 self_->StartAssertNoThreadSuspension("Building internal stack trace");
2912 if (methods_and_pcs == nullptr) {
2913 self_->AssertPendingOOMException();
2914 return false;
2915 }
Vladimir Markod34b73b2020-05-05 10:07:59 +01002916 trace->Set</*kTransactionActive=*/ false, /*kCheckTransaction=*/ false>(0, methods_and_pcs);
Mathieu Chartier910e8272015-09-30 09:24:22 -07002917 trace_ = trace.Get();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002918 // If We are called from native, use non-transactional mode.
Dave Allison0aded082013-11-07 13:15:11 -08002919 CHECK(last_no_suspend_cause == nullptr) << last_no_suspend_cause;
Ian Rogers283ed0d2012-02-16 15:25:09 -08002920 return true;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07002921 }
2922
Mathieu Chartier4e2cb092015-07-22 16:17:51 -07002923 virtual ~BuildInternalStackTraceVisitor() RELEASE(Roles::uninterruptible_) {
2924 self_->EndAssertNoThreadSuspension(nullptr);
Ian Rogers0399dde2012-06-06 17:09:28 -07002925 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07002926
Andreas Gampefa6a1b02018-09-07 08:11:55 -07002927 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002928 if (trace_ == nullptr) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002929 return true; // We're probably trying to fillInStackTrace for an OutOfMemoryError.
Elliott Hughes726079d2011-10-07 18:43:44 -07002930 }
Elliott Hughes29f27422011-09-18 16:02:18 -07002931 if (skip_depth_ > 0) {
2932 skip_depth_--;
Elliott Hughes530fa002012-03-12 11:44:49 -07002933 return true;
Elliott Hughes29f27422011-09-18 16:02:18 -07002934 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002935 ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002936 if (m->IsRuntimeMethod()) {
2937 return true; // Ignore runtime frames (in particular callee save).
Ian Rogers6b0870d2011-12-15 19:38:12 -08002938 }
Andreas Gampee2abbc62017-09-15 11:59:26 -07002939 AddFrame(m, m->IsProxyMethod() ? dex::kDexNoIndex : GetDexPc());
Mathieu Chartier65b8bb22017-02-01 11:03:50 -08002940 return true;
2941 }
2942
2943 void AddFrame(ArtMethod* method, uint32_t dex_pc) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod34b73b2020-05-05 10:07:59 +01002944 ObjPtr<mirror::PointerArray> methods_and_pcs = GetTraceMethodsAndPCs();
2945 methods_and_pcs->SetElementPtrSize</*kTransactionActive=*/ false, /*kCheckTransaction=*/ false>(
2946 count_, method, pointer_size_);
2947 methods_and_pcs->SetElementPtrSize</*kTransactionActive=*/ false, /*kCheckTransaction=*/ false>(
Eric Holkf1e1dd12020-08-21 15:38:12 -07002948 static_cast<uint32_t>(methods_and_pcs->GetLength()) / 2 + count_, dex_pc, pointer_size_);
Mathieu Chartier910e8272015-09-30 09:24:22 -07002949 // Save the declaring class of the method to ensure that the declaring classes of the methods
2950 // do not get unloaded while the stack trace is live.
Vladimir Markod34b73b2020-05-05 10:07:59 +01002951 trace_->Set</*kTransactionActive=*/ false, /*kCheckTransaction=*/ false>(
Eric Holkf1e1dd12020-08-21 15:38:12 -07002952 static_cast<int32_t>(count_) + 1, method->GetDeclaringClass());
Ian Rogersaaa20802011-09-11 21:47:37 -07002953 ++count_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07002954 }
2955
Mathieu Chartierf5769e12017-01-10 15:54:41 -08002956 ObjPtr<mirror::PointerArray> GetTraceMethodsAndPCs() const REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod7e9bbf2019-03-28 13:18:57 +00002957 return ObjPtr<mirror::PointerArray>::DownCast(trace_->Get(0));
Mathieu Chartier910e8272015-09-30 09:24:22 -07002958 }
2959
2960 mirror::ObjectArray<mirror::Object>* GetInternalStackTrace() const {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002961 return trace_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07002962 }
2963
2964 private:
Ian Rogers1f539342012-10-03 21:09:42 -07002965 Thread* const self_;
Elliott Hughes29f27422011-09-18 16:02:18 -07002966 // How many more frames to skip.
Eric Holkf1e1dd12020-08-21 15:38:12 -07002967 uint32_t skip_depth_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002968 // Current position down stack trace.
Mathieu Chartier65b8bb22017-02-01 11:03:50 -08002969 uint32_t count_ = 0;
Mathieu Chartier910e8272015-09-30 09:24:22 -07002970 // An object array where the first element is a pointer array that contains the ArtMethod
Vladimir Markod34b73b2020-05-05 10:07:59 +01002971 // pointers on the stack and dex PCs. The rest of the elements are the declaring class of
2972 // the ArtMethod pointers. trace_[i+1] contains the declaring class of the ArtMethod of the
2973 // i'th frame. We're initializing a newly allocated trace, so we do not need to record that
2974 // under a transaction. If the transaction is aborted, the whole trace shall be unreachable.
Mathieu Chartier65b8bb22017-02-01 11:03:50 -08002975 mirror::ObjectArray<mirror::Object>* trace_ = nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002976 // For cross compilation.
Andreas Gampe542451c2016-07-26 09:02:02 -07002977 const PointerSize pointer_size_;
Sebastien Hertz26f72862015-09-15 09:52:07 +02002978
2979 DISALLOW_COPY_AND_ASSIGN(BuildInternalStackTraceVisitor);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07002980};
2981
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07002982jobject Thread::CreateInternalStackTrace(const ScopedObjectAccessAlreadyRunnable& soa) const {
Mathieu Chartier65b8bb22017-02-01 11:03:50 -08002983 // Compute depth of stack, save frames if possible to avoid needing to recompute many.
2984 constexpr size_t kMaxSavedFrames = 256;
2985 std::unique_ptr<ArtMethodDexPcPair[]> saved_frames(new ArtMethodDexPcPair[kMaxSavedFrames]);
2986 FetchStackTraceVisitor count_visitor(const_cast<Thread*>(this),
2987 &saved_frames[0],
2988 kMaxSavedFrames);
Ian Rogers0399dde2012-06-06 17:09:28 -07002989 count_visitor.WalkStack();
Mathieu Chartier65b8bb22017-02-01 11:03:50 -08002990 const uint32_t depth = count_visitor.GetDepth();
2991 const uint32_t skip_depth = count_visitor.GetSkipDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07002992
Ian Rogers1f539342012-10-03 21:09:42 -07002993 // Build internal stack trace.
Vladimir Markod34b73b2020-05-05 10:07:59 +01002994 BuildInternalStackTraceVisitor build_trace_visitor(
2995 soa.Self(), const_cast<Thread*>(this), skip_depth);
Ian Rogers1f539342012-10-03 21:09:42 -07002996 if (!build_trace_visitor.Init(depth)) {
Dave Allison0aded082013-11-07 13:15:11 -08002997 return nullptr; // Allocation failed.
Ian Rogers283ed0d2012-02-16 15:25:09 -08002998 }
Mathieu Chartier65b8bb22017-02-01 11:03:50 -08002999 // If we saved all of the frames we don't even need to do the actual stack walk. This is faster
3000 // than doing the stack walk twice.
3001 if (depth < kMaxSavedFrames) {
3002 for (size_t i = 0; i < depth; ++i) {
3003 build_trace_visitor.AddFrame(saved_frames[i].first, saved_frames[i].second);
3004 }
3005 } else {
3006 build_trace_visitor.WalkStack();
3007 }
3008
Mathieu Chartier910e8272015-09-30 09:24:22 -07003009 mirror::ObjectArray<mirror::Object>* trace = build_trace_visitor.GetInternalStackTrace();
Ian Rogers7a22fa62013-01-23 12:16:16 -08003010 if (kIsDebugBuild) {
Mathieu Chartierf5769e12017-01-10 15:54:41 -08003011 ObjPtr<mirror::PointerArray> trace_methods = build_trace_visitor.GetTraceMethodsAndPCs();
Mathieu Chartier910e8272015-09-30 09:24:22 -07003012 // Second half of trace_methods is dex PCs.
3013 for (uint32_t i = 0; i < static_cast<uint32_t>(trace_methods->GetLength() / 2); ++i) {
3014 auto* method = trace_methods->GetElementPtrSize<ArtMethod*>(
Mathieu Chartiere401d142015-04-22 13:56:20 -07003015 i, Runtime::Current()->GetClassLinker()->GetImagePointerSize());
3016 CHECK(method != nullptr);
Ian Rogers7a22fa62013-01-23 12:16:16 -08003017 }
3018 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003019 return soa.AddLocalReference<jobject>(trace);
Ian Rogersaaa20802011-09-11 21:47:37 -07003020}
3021
Mathieu Chartierf5769e12017-01-10 15:54:41 -08003022bool Thread::IsExceptionThrownByCurrentMethod(ObjPtr<mirror::Throwable> exception) const {
Mathieu Chartier65b8bb22017-02-01 11:03:50 -08003023 // Only count the depth since we do not pass a stack frame array as an argument.
3024 FetchStackTraceVisitor count_visitor(const_cast<Thread*>(this));
Nicolas Geoffray7642cfc2015-02-26 10:56:09 +00003025 count_visitor.WalkStack();
Mathieu Chartier65b8bb22017-02-01 11:03:50 -08003026 return count_visitor.GetDepth() == static_cast<uint32_t>(exception->GetStackDepth());
Nicolas Geoffray7642cfc2015-02-26 10:56:09 +00003027}
3028
Andreas Gampeb6f309e2017-12-11 20:45:41 -08003029static ObjPtr<mirror::StackTraceElement> CreateStackTraceElement(
3030 const ScopedObjectAccessAlreadyRunnable& soa,
3031 ArtMethod* method,
3032 uint32_t dex_pc) REQUIRES_SHARED(Locks::mutator_lock_) {
3033 int32_t line_number;
3034 StackHandleScope<3> hs(soa.Self());
3035 auto class_name_object(hs.NewHandle<mirror::String>(nullptr));
3036 auto source_name_object(hs.NewHandle<mirror::String>(nullptr));
3037 if (method->IsProxyMethod()) {
3038 line_number = -1;
3039 class_name_object.Assign(method->GetDeclaringClass()->GetName());
3040 // source_name_object intentionally left null for proxy methods
3041 } else {
3042 line_number = method->GetLineNumFromDexPC(dex_pc);
3043 // Allocate element, potentially triggering GC
3044 // TODO: reuse class_name_object via Class::name_?
3045 const char* descriptor = method->GetDeclaringClassDescriptor();
3046 CHECK(descriptor != nullptr);
3047 std::string class_name(PrettyDescriptor(descriptor));
3048 class_name_object.Assign(
3049 mirror::String::AllocFromModifiedUtf8(soa.Self(), class_name.c_str()));
3050 if (class_name_object == nullptr) {
3051 soa.Self()->AssertPendingOOMException();
3052 return nullptr;
3053 }
3054 const char* source_file = method->GetDeclaringClassSourceFile();
3055 if (line_number == -1) {
3056 // Make the line_number field of StackTraceElement hold the dex pc.
3057 // source_name_object is intentionally left null if we failed to map the dex pc to
3058 // a line number (most probably because there is no debug info). See b/30183883.
Eric Holkf1e1dd12020-08-21 15:38:12 -07003059 line_number = static_cast<int32_t>(dex_pc);
Andreas Gampeb6f309e2017-12-11 20:45:41 -08003060 } else {
3061 if (source_file != nullptr) {
3062 source_name_object.Assign(mirror::String::AllocFromModifiedUtf8(soa.Self(), source_file));
3063 if (source_name_object == nullptr) {
3064 soa.Self()->AssertPendingOOMException();
3065 return nullptr;
3066 }
3067 }
3068 }
3069 }
3070 const char* method_name = method->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetName();
3071 CHECK(method_name != nullptr);
3072 Handle<mirror::String> method_name_object(
3073 hs.NewHandle(mirror::String::AllocFromModifiedUtf8(soa.Self(), method_name)));
3074 if (method_name_object == nullptr) {
3075 return nullptr;
3076 }
3077 return mirror::StackTraceElement::Alloc(soa.Self(),
3078 class_name_object,
3079 method_name_object,
3080 source_name_object,
3081 line_number);
3082}
3083
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07003084jobjectArray Thread::InternalStackTraceToStackTraceElementArray(
Mathieu Chartier910e8272015-09-30 09:24:22 -07003085 const ScopedObjectAccessAlreadyRunnable& soa,
3086 jobject internal,
3087 jobjectArray output_array,
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07003088 int* stack_depth) {
Mathieu Chartier910e8272015-09-30 09:24:22 -07003089 // Decode the internal stack trace into the depth, method trace and PC trace.
3090 // Subtract one for the methods and PC trace.
Mathieu Chartier0795f232016-09-27 18:43:30 -07003091 int32_t depth = soa.Decode<mirror::Array>(internal)->GetLength() - 1;
Mathieu Chartier910e8272015-09-30 09:24:22 -07003092 DCHECK_GE(depth, 0);
Ian Rogersaaa20802011-09-11 21:47:37 -07003093
Mathieu Chartier910e8272015-09-30 09:24:22 -07003094 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Ian Rogersaaa20802011-09-11 21:47:37 -07003095
Elliott Hughes01158d72011-09-19 19:47:10 -07003096 jobjectArray result;
Mathieu Chartier530825b2013-09-25 17:56:49 -07003097
Dave Allison0aded082013-11-07 13:15:11 -08003098 if (output_array != nullptr) {
Elliott Hughes01158d72011-09-19 19:47:10 -07003099 // Reuse the array we were given.
3100 result = output_array;
Elliott Hughes01158d72011-09-19 19:47:10 -07003101 // ...adjusting the number of frames we'll write to not exceed the array length.
Mathieu Chartier530825b2013-09-25 17:56:49 -07003102 const int32_t traces_length =
Mathieu Chartier0795f232016-09-27 18:43:30 -07003103 soa.Decode<mirror::ObjectArray<mirror::StackTraceElement>>(result)->GetLength();
Mathieu Chartier530825b2013-09-25 17:56:49 -07003104 depth = std::min(depth, traces_length);
Elliott Hughes01158d72011-09-19 19:47:10 -07003105 } else {
3106 // Create java_trace array and place in local reference table
Vladimir Markobcf17522018-06-01 13:14:32 +01003107 ObjPtr<mirror::ObjectArray<mirror::StackTraceElement>> java_traces =
Eric Holkf1e1dd12020-08-21 15:38:12 -07003108 class_linker->AllocStackTraceElementArray(soa.Self(), static_cast<size_t>(depth));
Dave Allison0aded082013-11-07 13:15:11 -08003109 if (java_traces == nullptr) {
3110 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07003111 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003112 result = soa.AddLocalReference<jobjectArray>(java_traces);
Elliott Hughes01158d72011-09-19 19:47:10 -07003113 }
3114
Dave Allison0aded082013-11-07 13:15:11 -08003115 if (stack_depth != nullptr) {
Elliott Hughes01158d72011-09-19 19:47:10 -07003116 *stack_depth = depth;
3117 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07003118
Eric Holkf1e1dd12020-08-21 15:38:12 -07003119 for (uint32_t i = 0; i < static_cast<uint32_t>(depth); ++i) {
Mathieu Chartierf5769e12017-01-10 15:54:41 -08003120 ObjPtr<mirror::ObjectArray<mirror::Object>> decoded_traces =
Mathieu Chartier0795f232016-09-27 18:43:30 -07003121 soa.Decode<mirror::Object>(internal)->AsObjectArray<mirror::Object>();
Mathieu Chartier910e8272015-09-30 09:24:22 -07003122 // Methods and dex PC trace is element 0.
3123 DCHECK(decoded_traces->Get(0)->IsIntArray() || decoded_traces->Get(0)->IsLongArray());
Vladimir Marko0984e482019-03-27 16:41:41 +00003124 const ObjPtr<mirror::PointerArray> method_trace =
Vladimir Markod7e9bbf2019-03-28 13:18:57 +00003125 ObjPtr<mirror::PointerArray>::DownCast(decoded_traces->Get(0));
Ian Rogersaaa20802011-09-11 21:47:37 -07003126 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
Andreas Gampe542451c2016-07-26 09:02:02 -07003127 ArtMethod* method = method_trace->GetElementPtrSize<ArtMethod*>(i, kRuntimePointerSize);
Mathieu Chartiere401d142015-04-22 13:56:20 -07003128 uint32_t dex_pc = method_trace->GetElementPtrSize<uint32_t>(
Eric Holkf1e1dd12020-08-21 15:38:12 -07003129 i + static_cast<uint32_t>(method_trace->GetLength()) / 2, kRuntimePointerSize);
Vladimir Marko0984e482019-03-27 16:41:41 +00003130 const ObjPtr<mirror::StackTraceElement> obj = CreateStackTraceElement(soa, method, dex_pc);
Dave Allison0aded082013-11-07 13:15:11 -08003131 if (obj == nullptr) {
3132 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07003133 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003134 // We are called from native: use non-transactional mode.
Eric Holkf1e1dd12020-08-21 15:38:12 -07003135 soa.Decode<mirror::ObjectArray<mirror::StackTraceElement>>(result)->Set<false>(
3136 static_cast<int32_t>(i), obj);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07003137 }
Ian Rogersaaa20802011-09-11 21:47:37 -07003138 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07003139}
3140
Andreas Gampefb6b0b12017-12-11 20:47:56 -08003141jobjectArray Thread::CreateAnnotatedStackTrace(const ScopedObjectAccessAlreadyRunnable& soa) const {
3142 // This code allocates. Do not allow it to operate with a pending exception.
3143 if (IsExceptionPending()) {
3144 return nullptr;
3145 }
3146
Andreas Gampefb6b0b12017-12-11 20:47:56 -08003147 class CollectFramesAndLocksStackVisitor : public MonitorObjectsStackVisitor {
3148 public:
3149 CollectFramesAndLocksStackVisitor(const ScopedObjectAccessAlreadyRunnable& soaa_in,
3150 Thread* self,
3151 Context* context)
3152 : MonitorObjectsStackVisitor(self, context),
3153 wait_jobject_(soaa_in.Env(), nullptr),
3154 block_jobject_(soaa_in.Env(), nullptr),
3155 soaa_(soaa_in) {}
3156
3157 protected:
3158 VisitMethodResult StartMethod(ArtMethod* m, size_t frame_nr ATTRIBUTE_UNUSED)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01003159 override
Andreas Gampefb6b0b12017-12-11 20:47:56 -08003160 REQUIRES_SHARED(Locks::mutator_lock_) {
3161 ObjPtr<mirror::StackTraceElement> obj = CreateStackTraceElement(
3162 soaa_, m, GetDexPc(/* abort on error */ false));
3163 if (obj == nullptr) {
3164 return VisitMethodResult::kEndStackWalk;
3165 }
3166 stack_trace_elements_.emplace_back(soaa_.Env(), soaa_.AddLocalReference<jobject>(obj.Ptr()));
3167 return VisitMethodResult::kContinueMethod;
3168 }
3169
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01003170 VisitMethodResult EndMethod(ArtMethod* m ATTRIBUTE_UNUSED) override {
Andreas Gampefb6b0b12017-12-11 20:47:56 -08003171 lock_objects_.push_back({});
3172 lock_objects_[lock_objects_.size() - 1].swap(frame_lock_objects_);
3173
3174 DCHECK_EQ(lock_objects_.size(), stack_trace_elements_.size());
3175
3176 return VisitMethodResult::kContinueMethod;
3177 }
3178
Vladimir Markof52d92f2019-03-29 12:33:02 +00003179 void VisitWaitingObject(ObjPtr<mirror::Object> obj, ThreadState state ATTRIBUTE_UNUSED)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01003180 override
Andreas Gampefb6b0b12017-12-11 20:47:56 -08003181 REQUIRES_SHARED(Locks::mutator_lock_) {
3182 wait_jobject_.reset(soaa_.AddLocalReference<jobject>(obj));
3183 }
Vladimir Markof52d92f2019-03-29 12:33:02 +00003184 void VisitSleepingObject(ObjPtr<mirror::Object> obj)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01003185 override
Andreas Gampefb6b0b12017-12-11 20:47:56 -08003186 REQUIRES_SHARED(Locks::mutator_lock_) {
3187 wait_jobject_.reset(soaa_.AddLocalReference<jobject>(obj));
3188 }
Vladimir Markof52d92f2019-03-29 12:33:02 +00003189 void VisitBlockedOnObject(ObjPtr<mirror::Object> obj,
Andreas Gampefb6b0b12017-12-11 20:47:56 -08003190 ThreadState state ATTRIBUTE_UNUSED,
3191 uint32_t owner_tid ATTRIBUTE_UNUSED)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01003192 override
Andreas Gampefb6b0b12017-12-11 20:47:56 -08003193 REQUIRES_SHARED(Locks::mutator_lock_) {
3194 block_jobject_.reset(soaa_.AddLocalReference<jobject>(obj));
3195 }
Vladimir Markof52d92f2019-03-29 12:33:02 +00003196 void VisitLockedObject(ObjPtr<mirror::Object> obj)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01003197 override
Andreas Gampefb6b0b12017-12-11 20:47:56 -08003198 REQUIRES_SHARED(Locks::mutator_lock_) {
3199 frame_lock_objects_.emplace_back(soaa_.Env(), soaa_.AddLocalReference<jobject>(obj));
3200 }
3201
3202 public:
3203 std::vector<ScopedLocalRef<jobject>> stack_trace_elements_;
3204 ScopedLocalRef<jobject> wait_jobject_;
3205 ScopedLocalRef<jobject> block_jobject_;
3206 std::vector<std::vector<ScopedLocalRef<jobject>>> lock_objects_;
3207
3208 private:
3209 const ScopedObjectAccessAlreadyRunnable& soaa_;
3210
3211 std::vector<ScopedLocalRef<jobject>> frame_lock_objects_;
3212 };
3213
3214 std::unique_ptr<Context> context(Context::Create());
3215 CollectFramesAndLocksStackVisitor dumper(soa, const_cast<Thread*>(this), context.get());
3216 dumper.WalkStack();
3217
3218 // There should not be a pending exception. Otherwise, return with it pending.
3219 if (IsExceptionPending()) {
3220 return nullptr;
3221 }
3222
3223 // Now go and create Java arrays.
3224
3225 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
3226
3227 StackHandleScope<6> hs(soa.Self());
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003228 Handle<mirror::Class> h_aste_array_class = hs.NewHandle(class_linker->FindSystemClass(
Andreas Gampefb6b0b12017-12-11 20:47:56 -08003229 soa.Self(),
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003230 "[Ldalvik/system/AnnotatedStackTraceElement;"));
3231 if (h_aste_array_class == nullptr) {
Andreas Gampefb6b0b12017-12-11 20:47:56 -08003232 return nullptr;
3233 }
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003234 Handle<mirror::Class> h_aste_class = hs.NewHandle(h_aste_array_class->GetComponentType());
Andreas Gampefb6b0b12017-12-11 20:47:56 -08003235
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003236 Handle<mirror::Class> h_o_array_class =
3237 hs.NewHandle(GetClassRoot<mirror::ObjectArray<mirror::Object>>(class_linker));
3238 DCHECK(h_o_array_class != nullptr); // Class roots must be already initialized.
Andreas Gampefb6b0b12017-12-11 20:47:56 -08003239
Vladimir Markoc4b1c0c2018-03-29 17:07:17 +01003240
3241 // Make sure the AnnotatedStackTraceElement.class is initialized, b/76208924 .
3242 class_linker->EnsureInitialized(soa.Self(),
3243 h_aste_class,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003244 /* can_init_fields= */ true,
3245 /* can_init_parents= */ true);
Vladimir Markoc4b1c0c2018-03-29 17:07:17 +01003246 if (soa.Self()->IsExceptionPending()) {
3247 // This should not fail in a healthy runtime.
3248 return nullptr;
3249 }
3250
Vladimir Markoe300c4e2021-06-08 16:00:05 +01003251 ArtField* stack_trace_element_field =
3252 h_aste_class->FindDeclaredInstanceField("stackTraceElement", "Ljava/lang/StackTraceElement;");
Andreas Gampefb6b0b12017-12-11 20:47:56 -08003253 DCHECK(stack_trace_element_field != nullptr);
Vladimir Markoe300c4e2021-06-08 16:00:05 +01003254 ArtField* held_locks_field =
3255 h_aste_class->FindDeclaredInstanceField("heldLocks", "[Ljava/lang/Object;");
Andreas Gampefb6b0b12017-12-11 20:47:56 -08003256 DCHECK(held_locks_field != nullptr);
Vladimir Markoe300c4e2021-06-08 16:00:05 +01003257 ArtField* blocked_on_field =
3258 h_aste_class->FindDeclaredInstanceField("blockedOn", "Ljava/lang/Object;");
Andreas Gampefb6b0b12017-12-11 20:47:56 -08003259 DCHECK(blocked_on_field != nullptr);
3260
Eric Holkf1e1dd12020-08-21 15:38:12 -07003261 int32_t length = static_cast<int32_t>(dumper.stack_trace_elements_.size());
Andreas Gampefb6b0b12017-12-11 20:47:56 -08003262 ObjPtr<mirror::ObjectArray<mirror::Object>> array =
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003263 mirror::ObjectArray<mirror::Object>::Alloc(soa.Self(), h_aste_array_class.Get(), length);
Andreas Gampefb6b0b12017-12-11 20:47:56 -08003264 if (array == nullptr) {
3265 soa.Self()->AssertPendingOOMException();
3266 return nullptr;
3267 }
3268
3269 ScopedLocalRef<jobjectArray> result(soa.Env(), soa.Env()->AddLocalReference<jobjectArray>(array));
3270
3271 MutableHandle<mirror::Object> handle(hs.NewHandle<mirror::Object>(nullptr));
3272 MutableHandle<mirror::ObjectArray<mirror::Object>> handle2(
3273 hs.NewHandle<mirror::ObjectArray<mirror::Object>>(nullptr));
Eric Holkf1e1dd12020-08-21 15:38:12 -07003274 for (size_t i = 0; i != static_cast<size_t>(length); ++i) {
Andreas Gampefb6b0b12017-12-11 20:47:56 -08003275 handle.Assign(h_aste_class->AllocObject(soa.Self()));
3276 if (handle == nullptr) {
3277 soa.Self()->AssertPendingOOMException();
3278 return nullptr;
3279 }
3280
3281 // Set stack trace element.
3282 stack_trace_element_field->SetObject<false>(
3283 handle.Get(), soa.Decode<mirror::Object>(dumper.stack_trace_elements_[i].get()));
3284
3285 // Create locked-on array.
3286 if (!dumper.lock_objects_[i].empty()) {
Eric Holkf1e1dd12020-08-21 15:38:12 -07003287 handle2.Assign(mirror::ObjectArray<mirror::Object>::Alloc(
3288 soa.Self(), h_o_array_class.Get(), static_cast<int32_t>(dumper.lock_objects_[i].size())));
Andreas Gampefb6b0b12017-12-11 20:47:56 -08003289 if (handle2 == nullptr) {
3290 soa.Self()->AssertPendingOOMException();
3291 return nullptr;
3292 }
3293 int32_t j = 0;
3294 for (auto& scoped_local : dumper.lock_objects_[i]) {
3295 if (scoped_local == nullptr) {
3296 continue;
3297 }
3298 handle2->Set(j, soa.Decode<mirror::Object>(scoped_local.get()));
3299 DCHECK(!soa.Self()->IsExceptionPending());
3300 j++;
3301 }
3302 held_locks_field->SetObject<false>(handle.Get(), handle2.Get());
3303 }
3304
3305 // Set blocked-on object.
3306 if (i == 0) {
3307 if (dumper.block_jobject_ != nullptr) {
3308 blocked_on_field->SetObject<false>(
3309 handle.Get(), soa.Decode<mirror::Object>(dumper.block_jobject_.get()));
3310 }
3311 }
3312
3313 ScopedLocalRef<jobject> elem(soa.Env(), soa.AddLocalReference<jobject>(handle.Get()));
Eric Holkf1e1dd12020-08-21 15:38:12 -07003314 soa.Env()->SetObjectArrayElement(result.get(), static_cast<jsize>(i), elem.get());
Andreas Gampefb6b0b12017-12-11 20:47:56 -08003315 DCHECK(!soa.Self()->IsExceptionPending());
3316 }
3317
3318 return result.release();
3319}
3320
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00003321void Thread::ThrowNewExceptionF(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughesa5b897e2011-08-16 11:33:06 -07003322 va_list args;
3323 va_start(args, fmt);
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00003324 ThrowNewExceptionV(exception_class_descriptor, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07003325 va_end(args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003326}
3327
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00003328void Thread::ThrowNewExceptionV(const char* exception_class_descriptor,
Ian Rogers62d6c772013-02-27 08:32:07 -08003329 const char* fmt, va_list ap) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003330 std::string msg;
3331 StringAppendV(&msg, fmt, ap);
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00003332 ThrowNewException(exception_class_descriptor, msg.c_str());
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07003333}
Elliott Hughes37f7a402011-08-22 18:56:01 -07003334
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00003335void Thread::ThrowNewException(const char* exception_class_descriptor,
Ian Rogers62d6c772013-02-27 08:32:07 -08003336 const char* msg) {
Mathieu Chartier8d7672e2014-02-25 10:57:16 -08003337 // Callers should either clear or call ThrowNewWrappedException.
3338 AssertNoPendingExceptionForNewException(msg);
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00003339 ThrowNewWrappedException(exception_class_descriptor, msg);
Elliott Hughesa4f94742012-05-29 16:28:38 -07003340}
3341
Mathieu Chartierf5769e12017-01-10 15:54:41 -08003342static ObjPtr<mirror::ClassLoader> GetCurrentClassLoader(Thread* self)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003343 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003344 ArtMethod* method = self->GetCurrentMethod(nullptr);
Nicolas Geoffrayee077032015-03-09 14:56:37 +00003345 return method != nullptr
3346 ? method->GetDeclaringClass()->GetClassLoader()
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003347 : nullptr;
3348}
3349
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00003350void Thread::ThrowNewWrappedException(const char* exception_class_descriptor,
Ian Rogers62d6c772013-02-27 08:32:07 -08003351 const char* msg) {
3352 DCHECK_EQ(this, Thread::Current());
Ian Rogers53b8b092014-03-13 23:45:53 -07003353 ScopedObjectAccessUnchecked soa(this);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003354 StackHandleScope<3> hs(soa.Self());
Calin Juravle2c2724c2021-01-14 19:54:23 -08003355
3356 // Disable public sdk checks if we need to throw exceptions.
3357 // The checks are only used in AOT compilation and may block (exception) class
3358 // initialization if it needs access to private fields (e.g. serialVersionUID).
3359 //
3360 // Since throwing an exception will EnsureInitialization and the public sdk may
3361 // block that, disable the checks. It's ok to do so, because the thrown exceptions
3362 // are not part of the application code that needs to verified.
3363 ScopedDisablePublicSdkChecker sdpsc;
3364
Nicolas Geoffrayee077032015-03-09 14:56:37 +00003365 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(GetCurrentClassLoader(soa.Self())));
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003366 ScopedLocalRef<jobject> cause(GetJniEnv(), soa.AddLocalReference<jobject>(GetException()));
Ian Rogers62d6c772013-02-27 08:32:07 -08003367 ClearException();
3368 Runtime* runtime = Runtime::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003369 auto* cl = runtime->GetClassLinker();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003370 Handle<mirror::Class> exception_class(
Mathieu Chartiere401d142015-04-22 13:56:20 -07003371 hs.NewHandle(cl->FindClass(this, exception_class_descriptor, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003372 if (UNLIKELY(exception_class == nullptr)) {
Elliott Hughes30646832011-10-13 16:59:46 -07003373 CHECK(IsExceptionPending());
Ian Rogers62d6c772013-02-27 08:32:07 -08003374 LOG(ERROR) << "No exception class " << PrettyDescriptor(exception_class_descriptor);
Elliott Hughes30646832011-10-13 16:59:46 -07003375 return;
3376 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003377
Ian Rogers7b078e82014-09-10 14:44:24 -07003378 if (UNLIKELY(!runtime->GetClassLinker()->EnsureInitialized(soa.Self(), exception_class, true,
3379 true))) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003380 DCHECK(IsExceptionPending());
3381 return;
3382 }
Santiago Aboy Solanes6cdabe12022-02-18 15:27:43 +00003383 DCHECK_IMPLIES(runtime->IsStarted(), exception_class->IsThrowableClass());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003384 Handle<mirror::Throwable> exception(
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07003385 hs.NewHandle(ObjPtr<mirror::Throwable>::DownCast(exception_class->AllocObject(this))));
Ian Rogers62d6c772013-02-27 08:32:07 -08003386
Mathieu Chartier590fee92013-09-13 13:46:47 -07003387 // If we couldn't allocate the exception, throw the pre-allocated out of memory exception.
Andreas Gampefa4333d2017-02-14 11:10:34 -08003388 if (exception == nullptr) {
Roland Levillain7b0e8442018-04-11 18:27:47 +01003389 Dump(LOG_STREAM(WARNING)); // The pre-allocated OOME has no stack, so help out and log one.
3390 SetException(Runtime::Current()->GetPreAllocatedOutOfMemoryErrorWhenThrowingException());
Mathieu Chartier590fee92013-09-13 13:46:47 -07003391 return;
3392 }
3393
Ian Rogers62d6c772013-02-27 08:32:07 -08003394 // Choose an appropriate constructor and set up the arguments.
3395 const char* signature;
Ian Rogers53b8b092014-03-13 23:45:53 -07003396 ScopedLocalRef<jstring> msg_string(GetJniEnv(), nullptr);
Dave Allison0aded082013-11-07 13:15:11 -08003397 if (msg != nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003398 // Ensure we remember this and the method over the String allocation.
Ian Rogers53b8b092014-03-13 23:45:53 -07003399 msg_string.reset(
3400 soa.AddLocalReference<jstring>(mirror::String::AllocFromModifiedUtf8(this, msg)));
Dave Allison0aded082013-11-07 13:15:11 -08003401 if (UNLIKELY(msg_string.get() == nullptr)) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003402 CHECK(IsExceptionPending()); // OOME.
3403 return;
Brian Carlstromebd1fd22011-12-07 15:46:26 -08003404 }
Dave Allison0aded082013-11-07 13:15:11 -08003405 if (cause.get() == nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003406 signature = "(Ljava/lang/String;)V";
3407 } else {
3408 signature = "(Ljava/lang/String;Ljava/lang/Throwable;)V";
3409 }
3410 } else {
Dave Allison0aded082013-11-07 13:15:11 -08003411 if (cause.get() == nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003412 signature = "()V";
3413 } else {
3414 signature = "(Ljava/lang/Throwable;)V";
3415 }
Brian Carlstromebd1fd22011-12-07 15:46:26 -08003416 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003417 ArtMethod* exception_init_method =
Vladimir Markoba118822017-06-12 15:41:56 +01003418 exception_class->FindConstructor(signature, cl->GetImagePointerSize());
Ian Rogers62d6c772013-02-27 08:32:07 -08003419
Dave Allison0aded082013-11-07 13:15:11 -08003420 CHECK(exception_init_method != nullptr) << "No <init>" << signature << " in "
Ian Rogers62d6c772013-02-27 08:32:07 -08003421 << PrettyDescriptor(exception_class_descriptor);
3422
3423 if (UNLIKELY(!runtime->IsStarted())) {
3424 // Something is trying to throw an exception without a started runtime, which is the common
3425 // case in the compiler. We won't be able to invoke the constructor of the exception, so set
3426 // the exception fields directly.
Dave Allison0aded082013-11-07 13:15:11 -08003427 if (msg != nullptr) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07003428 exception->SetDetailMessage(DecodeJObject(msg_string.get())->AsString());
Ian Rogers62d6c772013-02-27 08:32:07 -08003429 }
Dave Allison0aded082013-11-07 13:15:11 -08003430 if (cause.get() != nullptr) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07003431 exception->SetCause(DecodeJObject(cause.get())->AsThrowable());
Ian Rogers62d6c772013-02-27 08:32:07 -08003432 }
Vladimir Markod34b73b2020-05-05 10:07:59 +01003433 ScopedLocalRef<jobject> trace(GetJniEnv(), CreateInternalStackTrace(soa));
Ian Rogersc45b8b52014-05-03 01:39:59 -07003434 if (trace.get() != nullptr) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07003435 exception->SetStackState(DecodeJObject(trace.get()).Ptr());
Ian Rogersc45b8b52014-05-03 01:39:59 -07003436 }
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003437 SetException(exception.Get());
Ian Rogers62d6c772013-02-27 08:32:07 -08003438 } else {
Ian Rogers53b8b092014-03-13 23:45:53 -07003439 jvalue jv_args[2];
3440 size_t i = 0;
3441
Dave Allison0aded082013-11-07 13:15:11 -08003442 if (msg != nullptr) {
Ian Rogers53b8b092014-03-13 23:45:53 -07003443 jv_args[i].l = msg_string.get();
3444 ++i;
Ian Rogers62d6c772013-02-27 08:32:07 -08003445 }
Dave Allison0aded082013-11-07 13:15:11 -08003446 if (cause.get() != nullptr) {
Ian Rogers53b8b092014-03-13 23:45:53 -07003447 jv_args[i].l = cause.get();
3448 ++i;
Ian Rogers62d6c772013-02-27 08:32:07 -08003449 }
Jeff Hao39b6c242015-05-19 20:30:23 -07003450 ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(exception.Get()));
Alex Light01fbfbe2019-06-27 10:47:04 -07003451 InvokeWithJValues(soa, ref.get(), exception_init_method, jv_args);
Ian Rogers62d6c772013-02-27 08:32:07 -08003452 if (LIKELY(!IsExceptionPending())) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003453 SetException(exception.Get());
Ian Rogers62d6c772013-02-27 08:32:07 -08003454 }
Elliott Hughes30646832011-10-13 16:59:46 -07003455 }
Elliott Hughesa5b897e2011-08-16 11:33:06 -07003456}
3457
Elliott Hughes2ced6a52011-10-16 18:44:48 -07003458void Thread::ThrowOutOfMemoryError(const char* msg) {
Wei Li8991ad02018-09-13 16:43:39 +08003459 LOG(WARNING) << "Throwing OutOfMemoryError "
3460 << '"' << msg << '"'
3461 << " (VmSize " << GetProcessStatus("VmSize")
3462 << (tls32_.throwing_OutOfMemoryError ? ", recursive case)" : ")");
Ioannis Ilkosdbba2f02022-02-08 20:08:44 +00003463 ScopedTrace trace("OutOfMemoryError");
Ian Rogersdd7624d2014-03-14 17:43:00 -07003464 if (!tls32_.throwing_OutOfMemoryError) {
3465 tls32_.throwing_OutOfMemoryError = true;
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00003466 ThrowNewException("Ljava/lang/OutOfMemoryError;", msg);
Ian Rogersdd7624d2014-03-14 17:43:00 -07003467 tls32_.throwing_OutOfMemoryError = false;
Elliott Hughes418dfe72011-10-06 18:56:27 -07003468 } else {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07003469 Dump(LOG_STREAM(WARNING)); // The pre-allocated OOME has no stack, so help out and log one.
Roland Levillain7b0e8442018-04-11 18:27:47 +01003470 SetException(Runtime::Current()->GetPreAllocatedOutOfMemoryErrorWhenThrowingOOME());
Elliott Hughes418dfe72011-10-06 18:56:27 -07003471 }
Elliott Hughes79082e32011-08-25 12:07:32 -07003472}
3473
Elliott Hughes498508c2011-10-17 14:58:22 -07003474Thread* Thread::CurrentFromGdb() {
Elliott Hughesaccd83d2011-10-17 14:25:58 -07003475 return Thread::Current();
3476}
3477
3478void Thread::DumpFromGdb() const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003479 std::ostringstream ss;
3480 Dump(ss);
Elliott Hughes95572412011-12-13 18:14:20 -08003481 std::string str(ss.str());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003482 // log to stderr for debugging command line processes
3483 std::cerr << str;
Bilyan Borisovbb661c02016-04-04 16:27:32 +01003484#ifdef ART_TARGET_ANDROID
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003485 // log to logcat for debugging frameworks processes
3486 LOG(INFO) << str;
3487#endif
Elliott Hughesaccd83d2011-10-17 14:25:58 -07003488}
3489
Ian Rogersdd7624d2014-03-14 17:43:00 -07003490// Explicitly instantiate 32 and 64bit thread offset dumping support.
Andreas Gampe542451c2016-07-26 09:02:02 -07003491template
3492void Thread::DumpThreadOffset<PointerSize::k32>(std::ostream& os, uint32_t offset);
3493template
3494void Thread::DumpThreadOffset<PointerSize::k64>(std::ostream& os, uint32_t offset);
Elliott Hughes98e20172012-04-24 15:38:13 -07003495
Andreas Gampe542451c2016-07-26 09:02:02 -07003496template<PointerSize ptr_size>
Ian Rogersdd7624d2014-03-14 17:43:00 -07003497void Thread::DumpThreadOffset(std::ostream& os, uint32_t offset) {
3498#define DO_THREAD_OFFSET(x, y) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07003499 if (offset == (x).Uint32Value()) { \
3500 os << (y); \
Brian Carlstromf69863b2013-07-17 21:53:13 -07003501 return; \
3502 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07003503 DO_THREAD_OFFSET(ThreadFlagsOffset<ptr_size>(), "state_and_flags")
3504 DO_THREAD_OFFSET(CardTableOffset<ptr_size>(), "card_table")
3505 DO_THREAD_OFFSET(ExceptionOffset<ptr_size>(), "exception")
3506 DO_THREAD_OFFSET(PeerOffset<ptr_size>(), "peer");
3507 DO_THREAD_OFFSET(JniEnvOffset<ptr_size>(), "jni_env")
3508 DO_THREAD_OFFSET(SelfOffset<ptr_size>(), "self")
3509 DO_THREAD_OFFSET(StackEndOffset<ptr_size>(), "stack_end")
3510 DO_THREAD_OFFSET(ThinLockIdOffset<ptr_size>(), "thin_lock_thread_id")
Roland Levillain97c46462017-05-11 14:04:03 +01003511 DO_THREAD_OFFSET(IsGcMarkingOffset<ptr_size>(), "is_gc_marking")
Ian Rogersdd7624d2014-03-14 17:43:00 -07003512 DO_THREAD_OFFSET(TopOfManagedStackOffset<ptr_size>(), "top_quick_frame_method")
Ian Rogersdd7624d2014-03-14 17:43:00 -07003513 DO_THREAD_OFFSET(TopShadowFrameOffset<ptr_size>(), "top_shadow_frame")
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003514 DO_THREAD_OFFSET(TopHandleScopeOffset<ptr_size>(), "top_handle_scope")
Ian Rogersdd7624d2014-03-14 17:43:00 -07003515 DO_THREAD_OFFSET(ThreadSuspendTriggerOffset<ptr_size>(), "suspend_trigger")
Elliott Hughes28fa76d2012-04-09 17:31:46 -07003516#undef DO_THREAD_OFFSET
Elliott Hughes98e20172012-04-24 15:38:13 -07003517
Ian Rogersdd7624d2014-03-14 17:43:00 -07003518#define JNI_ENTRY_POINT_INFO(x) \
3519 if (JNI_ENTRYPOINT_OFFSET(ptr_size, x).Uint32Value() == offset) { \
3520 os << #x; \
3521 return; \
3522 }
3523 JNI_ENTRY_POINT_INFO(pDlsymLookup)
Vladimir Markofa458ac2020-02-12 14:08:07 +00003524 JNI_ENTRY_POINT_INFO(pDlsymLookupCritical)
Ian Rogersdd7624d2014-03-14 17:43:00 -07003525#undef JNI_ENTRY_POINT_INFO
3526
Ian Rogersdd7624d2014-03-14 17:43:00 -07003527#define QUICK_ENTRY_POINT_INFO(x) \
3528 if (QUICK_ENTRYPOINT_OFFSET(ptr_size, x).Uint32Value() == offset) { \
3529 os << #x; \
3530 return; \
3531 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07003532 QUICK_ENTRY_POINT_INFO(pAllocArrayResolved)
Nicolas Geoffrayb048cb72017-01-23 22:50:24 +00003533 QUICK_ENTRY_POINT_INFO(pAllocArrayResolved8)
3534 QUICK_ENTRY_POINT_INFO(pAllocArrayResolved16)
3535 QUICK_ENTRY_POINT_INFO(pAllocArrayResolved32)
3536 QUICK_ENTRY_POINT_INFO(pAllocArrayResolved64)
Ian Rogersdd7624d2014-03-14 17:43:00 -07003537 QUICK_ENTRY_POINT_INFO(pAllocObjectResolved)
3538 QUICK_ENTRY_POINT_INFO(pAllocObjectInitialized)
Nicolas Geoffray0d3998b2017-01-12 15:35:12 +00003539 QUICK_ENTRY_POINT_INFO(pAllocObjectWithChecks)
Alex Lightd109e302018-06-27 10:25:41 -07003540 QUICK_ENTRY_POINT_INFO(pAllocStringObject)
Jeff Hao848f70a2014-01-15 13:49:50 -08003541 QUICK_ENTRY_POINT_INFO(pAllocStringFromBytes)
3542 QUICK_ENTRY_POINT_INFO(pAllocStringFromChars)
3543 QUICK_ENTRY_POINT_INFO(pAllocStringFromString)
Ian Rogersdd7624d2014-03-14 17:43:00 -07003544 QUICK_ENTRY_POINT_INFO(pInstanceofNonTrivial)
Mathieu Chartierb99f4d62016-11-07 16:17:26 -08003545 QUICK_ENTRY_POINT_INFO(pCheckInstanceOf)
Ian Rogersdd7624d2014-03-14 17:43:00 -07003546 QUICK_ENTRY_POINT_INFO(pInitializeStaticStorage)
Vladimir Marko9d479252018-07-24 11:35:20 +01003547 QUICK_ENTRY_POINT_INFO(pResolveTypeAndVerifyAccess)
3548 QUICK_ENTRY_POINT_INFO(pResolveType)
Ian Rogersdd7624d2014-03-14 17:43:00 -07003549 QUICK_ENTRY_POINT_INFO(pResolveString)
Fred Shih37f05ef2014-07-16 18:38:08 -07003550 QUICK_ENTRY_POINT_INFO(pSet8Instance)
3551 QUICK_ENTRY_POINT_INFO(pSet8Static)
3552 QUICK_ENTRY_POINT_INFO(pSet16Instance)
3553 QUICK_ENTRY_POINT_INFO(pSet16Static)
Ian Rogersdd7624d2014-03-14 17:43:00 -07003554 QUICK_ENTRY_POINT_INFO(pSet32Instance)
3555 QUICK_ENTRY_POINT_INFO(pSet32Static)
3556 QUICK_ENTRY_POINT_INFO(pSet64Instance)
3557 QUICK_ENTRY_POINT_INFO(pSet64Static)
3558 QUICK_ENTRY_POINT_INFO(pSetObjInstance)
3559 QUICK_ENTRY_POINT_INFO(pSetObjStatic)
Fred Shih37f05ef2014-07-16 18:38:08 -07003560 QUICK_ENTRY_POINT_INFO(pGetByteInstance)
3561 QUICK_ENTRY_POINT_INFO(pGetBooleanInstance)
3562 QUICK_ENTRY_POINT_INFO(pGetByteStatic)
3563 QUICK_ENTRY_POINT_INFO(pGetBooleanStatic)
3564 QUICK_ENTRY_POINT_INFO(pGetShortInstance)
3565 QUICK_ENTRY_POINT_INFO(pGetCharInstance)
3566 QUICK_ENTRY_POINT_INFO(pGetShortStatic)
3567 QUICK_ENTRY_POINT_INFO(pGetCharStatic)
Ian Rogersdd7624d2014-03-14 17:43:00 -07003568 QUICK_ENTRY_POINT_INFO(pGet32Instance)
3569 QUICK_ENTRY_POINT_INFO(pGet32Static)
3570 QUICK_ENTRY_POINT_INFO(pGet64Instance)
3571 QUICK_ENTRY_POINT_INFO(pGet64Static)
3572 QUICK_ENTRY_POINT_INFO(pGetObjInstance)
3573 QUICK_ENTRY_POINT_INFO(pGetObjStatic)
Ian Rogersdd7624d2014-03-14 17:43:00 -07003574 QUICK_ENTRY_POINT_INFO(pAputObject)
Ian Rogersdd7624d2014-03-14 17:43:00 -07003575 QUICK_ENTRY_POINT_INFO(pJniMethodStart)
Ian Rogersdd7624d2014-03-14 17:43:00 -07003576 QUICK_ENTRY_POINT_INFO(pJniMethodEnd)
Vladimir Marko46a89102021-10-21 13:05:46 +00003577 QUICK_ENTRY_POINT_INFO(pJniDecodeReferenceResult)
Vladimir Marko4d527152021-11-23 12:07:04 +00003578 QUICK_ENTRY_POINT_INFO(pJniLockObject)
3579 QUICK_ENTRY_POINT_INFO(pJniUnlockObject)
Ian Rogersdd7624d2014-03-14 17:43:00 -07003580 QUICK_ENTRY_POINT_INFO(pQuickGenericJniTrampoline)
3581 QUICK_ENTRY_POINT_INFO(pLockObject)
3582 QUICK_ENTRY_POINT_INFO(pUnlockObject)
3583 QUICK_ENTRY_POINT_INFO(pCmpgDouble)
3584 QUICK_ENTRY_POINT_INFO(pCmpgFloat)
3585 QUICK_ENTRY_POINT_INFO(pCmplDouble)
3586 QUICK_ENTRY_POINT_INFO(pCmplFloat)
Mark Mendella4f12202015-08-06 15:23:34 -04003587 QUICK_ENTRY_POINT_INFO(pCos)
3588 QUICK_ENTRY_POINT_INFO(pSin)
3589 QUICK_ENTRY_POINT_INFO(pAcos)
3590 QUICK_ENTRY_POINT_INFO(pAsin)
3591 QUICK_ENTRY_POINT_INFO(pAtan)
3592 QUICK_ENTRY_POINT_INFO(pAtan2)
3593 QUICK_ENTRY_POINT_INFO(pCbrt)
3594 QUICK_ENTRY_POINT_INFO(pCosh)
3595 QUICK_ENTRY_POINT_INFO(pExp)
3596 QUICK_ENTRY_POINT_INFO(pExpm1)
3597 QUICK_ENTRY_POINT_INFO(pHypot)
3598 QUICK_ENTRY_POINT_INFO(pLog)
3599 QUICK_ENTRY_POINT_INFO(pLog10)
3600 QUICK_ENTRY_POINT_INFO(pNextAfter)
3601 QUICK_ENTRY_POINT_INFO(pSinh)
3602 QUICK_ENTRY_POINT_INFO(pTan)
3603 QUICK_ENTRY_POINT_INFO(pTanh)
Ian Rogersdd7624d2014-03-14 17:43:00 -07003604 QUICK_ENTRY_POINT_INFO(pFmod)
Ian Rogersdd7624d2014-03-14 17:43:00 -07003605 QUICK_ENTRY_POINT_INFO(pL2d)
3606 QUICK_ENTRY_POINT_INFO(pFmodf)
3607 QUICK_ENTRY_POINT_INFO(pL2f)
3608 QUICK_ENTRY_POINT_INFO(pD2iz)
3609 QUICK_ENTRY_POINT_INFO(pF2iz)
3610 QUICK_ENTRY_POINT_INFO(pIdivmod)
3611 QUICK_ENTRY_POINT_INFO(pD2l)
3612 QUICK_ENTRY_POINT_INFO(pF2l)
3613 QUICK_ENTRY_POINT_INFO(pLdiv)
3614 QUICK_ENTRY_POINT_INFO(pLmod)
3615 QUICK_ENTRY_POINT_INFO(pLmul)
3616 QUICK_ENTRY_POINT_INFO(pShlLong)
3617 QUICK_ENTRY_POINT_INFO(pShrLong)
3618 QUICK_ENTRY_POINT_INFO(pUshrLong)
3619 QUICK_ENTRY_POINT_INFO(pIndexOf)
Ian Rogersdd7624d2014-03-14 17:43:00 -07003620 QUICK_ENTRY_POINT_INFO(pStringCompareTo)
3621 QUICK_ENTRY_POINT_INFO(pMemcpy)
3622 QUICK_ENTRY_POINT_INFO(pQuickImtConflictTrampoline)
3623 QUICK_ENTRY_POINT_INFO(pQuickResolutionTrampoline)
3624 QUICK_ENTRY_POINT_INFO(pQuickToInterpreterBridge)
3625 QUICK_ENTRY_POINT_INFO(pInvokeDirectTrampolineWithAccessCheck)
3626 QUICK_ENTRY_POINT_INFO(pInvokeInterfaceTrampolineWithAccessCheck)
3627 QUICK_ENTRY_POINT_INFO(pInvokeStaticTrampolineWithAccessCheck)
3628 QUICK_ENTRY_POINT_INFO(pInvokeSuperTrampolineWithAccessCheck)
3629 QUICK_ENTRY_POINT_INFO(pInvokeVirtualTrampolineWithAccessCheck)
Orion Hodsonac141392017-01-13 11:53:47 +00003630 QUICK_ENTRY_POINT_INFO(pInvokePolymorphic)
Ian Rogersdd7624d2014-03-14 17:43:00 -07003631 QUICK_ENTRY_POINT_INFO(pTestSuspend)
3632 QUICK_ENTRY_POINT_INFO(pDeliverException)
3633 QUICK_ENTRY_POINT_INFO(pThrowArrayBounds)
3634 QUICK_ENTRY_POINT_INFO(pThrowDivZero)
Ian Rogersdd7624d2014-03-14 17:43:00 -07003635 QUICK_ENTRY_POINT_INFO(pThrowNullPointer)
3636 QUICK_ENTRY_POINT_INFO(pThrowStackOverflow)
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07003637 QUICK_ENTRY_POINT_INFO(pDeoptimize)
Douglas Leungd9cb8ae2014-07-09 14:28:35 -07003638 QUICK_ENTRY_POINT_INFO(pA64Load)
3639 QUICK_ENTRY_POINT_INFO(pA64Store)
Jeff Hao848f70a2014-01-15 13:49:50 -08003640 QUICK_ENTRY_POINT_INFO(pNewEmptyString)
3641 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_B)
3642 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BI)
3643 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BII)
3644 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BIII)
3645 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BIIString)
3646 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BString)
3647 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BIICharset)
3648 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BCharset)
3649 QUICK_ENTRY_POINT_INFO(pNewStringFromChars_C)
3650 QUICK_ENTRY_POINT_INFO(pNewStringFromChars_CII)
3651 QUICK_ENTRY_POINT_INFO(pNewStringFromChars_IIC)
3652 QUICK_ENTRY_POINT_INFO(pNewStringFromCodePoints)
3653 QUICK_ENTRY_POINT_INFO(pNewStringFromString)
3654 QUICK_ENTRY_POINT_INFO(pNewStringFromStringBuffer)
3655 QUICK_ENTRY_POINT_INFO(pNewStringFromStringBuilder)
Vladimir Marko8439e452021-11-25 15:36:29 +00003656 QUICK_ENTRY_POINT_INFO(pJniReadBarrier)
Roland Levillain02b75802016-07-13 11:54:35 +01003657 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg00)
3658 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg01)
3659 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg02)
3660 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg03)
3661 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg04)
3662 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg05)
3663 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg06)
3664 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg07)
3665 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg08)
3666 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg09)
3667 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg10)
3668 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg11)
3669 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg12)
3670 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg13)
3671 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg14)
3672 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg15)
3673 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg16)
3674 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg17)
3675 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg18)
3676 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg19)
3677 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg20)
3678 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg21)
3679 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg22)
3680 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg23)
3681 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg24)
3682 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg25)
3683 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg26)
3684 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg27)
3685 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg28)
3686 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg29)
Man Cao1aee9002015-07-14 22:31:42 -07003687 QUICK_ENTRY_POINT_INFO(pReadBarrierSlow)
Roland Levillain0d5a2812015-11-13 10:07:31 +00003688 QUICK_ENTRY_POINT_INFO(pReadBarrierForRootSlow)
Ian Rogersdd7624d2014-03-14 17:43:00 -07003689#undef QUICK_ENTRY_POINT_INFO
3690
Elliott Hughes98e20172012-04-24 15:38:13 -07003691 os << offset;
Elliott Hughes28fa76d2012-04-09 17:31:46 -07003692}
3693
jeffhao94d6df42012-11-26 16:02:12 -08003694void Thread::QuickDeliverException() {
Ian Rogers62d6c772013-02-27 08:32:07 -08003695 // Get exception from thread.
Mathieu Chartierf5769e12017-01-10 15:54:41 -08003696 ObjPtr<mirror::Throwable> exception = GetException();
Dave Allison0aded082013-11-07 13:15:11 -08003697 CHECK(exception != nullptr);
Mingyao Yangf711f2c2016-05-23 12:29:39 -07003698 if (exception == GetDeoptimizationException()) {
3699 artDeoptimize(this);
3700 UNREACHABLE();
3701 }
3702
Roland Levillaina78f5b62017-09-29 13:50:44 +01003703 ReadBarrier::MaybeAssertToSpaceInvariant(exception.Ptr());
Roland Levillainb77b6982017-06-08 18:03:48 +01003704
Mythri Alleab474882022-01-17 16:43:04 +00003705 // This is a real exception: let the instrumentation know about it. Exception throw listener
3706 // could set a breakpoint or install listeners that might require a deoptimization. Hence the
3707 // deoptimization check needs to happen after calling the listener.
Mingyao Yangf711f2c2016-05-23 12:29:39 -07003708 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Alex Light6e1607e2017-08-23 10:06:18 -07003709 if (instrumentation->HasExceptionThrownListeners() &&
Mingyao Yangf711f2c2016-05-23 12:29:39 -07003710 IsExceptionThrownByCurrentMethod(exception)) {
3711 // Instrumentation may cause GC so keep the exception object safe.
3712 StackHandleScope<1> hs(this);
Mathieu Chartierf5769e12017-01-10 15:54:41 -08003713 HandleWrapperObjPtr<mirror::Throwable> h_exception(hs.NewHandleWrapper(&exception));
Vladimir Marko19711d42019-04-12 14:05:34 +01003714 instrumentation->ExceptionThrownEvent(this, exception);
Mingyao Yangf711f2c2016-05-23 12:29:39 -07003715 }
Alex Light0aa7a5a2018-10-10 15:58:14 +00003716 // Does instrumentation need to deoptimize the stack or otherwise go to interpreter for something?
3717 // Note: we do this *after* reporting the exception to instrumentation in case it now requires
3718 // deoptimization. It may happen if a debugger is attached and requests new events (single-step,
3719 // breakpoint, ...) when the exception is reported.
Alex Lightbe1f8d02018-10-15 11:44:42 -07003720 //
3721 // Note we need to check for both force_frame_pop and force_retry_instruction. The first is
3722 // expected to happen fairly regularly but the second can only happen if we are using
3723 // instrumentation trampolines (for example with DDMS tracing). That forces us to do deopt later
3724 // and see every frame being popped. We don't need to handle it any differently.
Alex Light0aa7a5a2018-10-10 15:58:14 +00003725 ShadowFrame* cf;
David Srbecky1cbac5c2019-07-18 20:05:32 +01003726 bool force_deopt = false;
3727 if (Runtime::Current()->AreNonStandardExitsEnabled() || kIsDebugBuild) {
Alex Light0aa7a5a2018-10-10 15:58:14 +00003728 NthCallerVisitor visitor(this, 0, false);
3729 visitor.WalkStack();
3730 cf = visitor.GetCurrentShadowFrame();
3731 if (cf == nullptr) {
3732 cf = FindDebuggerShadowFrame(visitor.GetFrameId());
3733 }
Alex Lightbe1f8d02018-10-15 11:44:42 -07003734 bool force_frame_pop = cf != nullptr && cf->GetForcePopFrame();
3735 bool force_retry_instr = cf != nullptr && cf->GetForceRetryInstruction();
Alex Light0aa7a5a2018-10-10 15:58:14 +00003736 if (kIsDebugBuild && force_frame_pop) {
David Srbecky1cbac5c2019-07-18 20:05:32 +01003737 DCHECK(Runtime::Current()->AreNonStandardExitsEnabled());
Alex Light0aa7a5a2018-10-10 15:58:14 +00003738 NthCallerVisitor penultimate_visitor(this, 1, false);
3739 penultimate_visitor.WalkStack();
3740 ShadowFrame* penultimate_frame = penultimate_visitor.GetCurrentShadowFrame();
3741 if (penultimate_frame == nullptr) {
3742 penultimate_frame = FindDebuggerShadowFrame(penultimate_visitor.GetFrameId());
3743 }
Alex Light0aa7a5a2018-10-10 15:58:14 +00003744 }
David Srbecky1cbac5c2019-07-18 20:05:32 +01003745 if (force_retry_instr) {
3746 DCHECK(Runtime::Current()->AreNonStandardExitsEnabled());
3747 }
Alex Lightbe1f8d02018-10-15 11:44:42 -07003748 force_deopt = force_frame_pop || force_retry_instr;
Alex Light0aa7a5a2018-10-10 15:58:14 +00003749 }
Alex Light3dacdd62019-03-12 15:45:47 +00003750 if (Dbg::IsForcedInterpreterNeededForException(this) || force_deopt || IsForceInterpreter()) {
Mingyao Yangf711f2c2016-05-23 12:29:39 -07003751 NthCallerVisitor visitor(this, 0, false);
3752 visitor.WalkStack();
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003753 if (Runtime::Current()->IsAsyncDeoptimizeable(visitor.caller_pc)) {
Mingyao Yang2ee17902017-08-30 11:37:08 -07003754 // method_type shouldn't matter due to exception handling.
3755 const DeoptimizationMethodType method_type = DeoptimizationMethodType::kDefault;
Sebastien Hertz520633b2015-09-08 17:03:36 +02003756 // Save the exception into the deoptimization context so it can be restored
3757 // before entering the interpreter.
Alex Lightbe1f8d02018-10-15 11:44:42 -07003758 if (force_deopt) {
Alex Light0aa7a5a2018-10-10 15:58:14 +00003759 VLOG(deopt) << "Deopting " << cf->GetMethod()->PrettyMethod() << " for frame-pop";
3760 DCHECK(Runtime::Current()->AreNonStandardExitsEnabled());
3761 // Get rid of the exception since we are doing a framepop instead.
Alex Lightbe1f8d02018-10-15 11:44:42 -07003762 LOG(WARNING) << "Suppressing pending exception for retry-instruction/frame-pop: "
3763 << exception->Dump();
Alex Light0aa7a5a2018-10-10 15:58:14 +00003764 ClearException();
3765 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01003766 PushDeoptimizationContext(
Mingyao Yang2ee17902017-08-30 11:37:08 -07003767 JValue(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003768 /* is_reference= */ false,
Alex Lightbe1f8d02018-10-15 11:44:42 -07003769 (force_deopt ? nullptr : exception),
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003770 /* from_code= */ false,
Mingyao Yang2ee17902017-08-30 11:37:08 -07003771 method_type);
Mingyao Yangf711f2c2016-05-23 12:29:39 -07003772 artDeoptimize(this);
3773 UNREACHABLE();
Nicolas Geoffraye91e7952020-01-23 10:15:56 +00003774 } else if (visitor.caller != nullptr) {
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003775 LOG(WARNING) << "Got a deoptimization request on un-deoptimizable method "
3776 << visitor.caller->PrettyMethod();
Sebastien Hertz520633b2015-09-08 17:03:36 +02003777 }
3778 }
Mingyao Yangf711f2c2016-05-23 12:29:39 -07003779
Ian Rogers28ad40d2011-10-27 15:19:26 -07003780 // Don't leave exception visible while we try to find the handler, which may cause class
Elliott Hughesd07986f2011-12-06 18:27:45 -08003781 // resolution.
Ian Rogers28ad40d2011-10-27 15:19:26 -07003782 ClearException();
Mingyao Yangf711f2c2016-05-23 12:29:39 -07003783 QuickExceptionHandler exception_handler(this, false);
3784 exception_handler.FindCatch(exception);
Roland Levillainb77b6982017-06-08 18:03:48 +01003785 if (exception_handler.GetClearException()) {
3786 // Exception was cleared as part of delivery.
3787 DCHECK(!IsExceptionPending());
3788 } else {
3789 // Exception was put back with a throw location.
3790 DCHECK(IsExceptionPending());
Roland Levillaina78f5b62017-09-29 13:50:44 +01003791 // Check the to-space invariant on the re-installed exception (if applicable).
3792 ReadBarrier::MaybeAssertToSpaceInvariant(GetException());
Roland Levillainb77b6982017-06-08 18:03:48 +01003793 }
Sebastien Hertzfd3077e2014-04-23 10:32:43 +02003794 exception_handler.DoLongJump();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07003795}
3796
Ian Rogersbdb03912011-09-14 00:55:44 -07003797Context* Thread::GetLongJumpContext() {
Ian Rogersdd7624d2014-03-14 17:43:00 -07003798 Context* result = tlsPtr_.long_jump_context;
Dave Allison0aded082013-11-07 13:15:11 -08003799 if (result == nullptr) {
Ian Rogersbdb03912011-09-14 00:55:44 -07003800 result = Context::Create();
Ian Rogers0399dde2012-06-06 17:09:28 -07003801 } else {
Ian Rogersdd7624d2014-03-14 17:43:00 -07003802 tlsPtr_.long_jump_context = nullptr; // Avoid context being shared.
Mathieu Chartier67022432012-11-29 18:04:50 -08003803 result->Reset();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07003804 }
Ian Rogersbdb03912011-09-14 00:55:44 -07003805 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07003806}
3807
Andreas Gampec7d878d2018-11-19 18:42:06 +00003808ArtMethod* Thread::GetCurrentMethod(uint32_t* dex_pc_out,
Hiroshi Yamauchi02f365f2017-02-03 15:06:00 -08003809 bool check_suspended,
3810 bool abort_on_error) const {
Andreas Gampe1b5c5c82018-09-27 10:42:18 -07003811 // Note: this visitor may return with a method set, but dex_pc_ being DexFile:kDexNoIndex. This is
3812 // so we don't abort in a special situation (thinlocked monitor) when dumping the Java
3813 // stack.
Andreas Gampec7d878d2018-11-19 18:42:06 +00003814 ArtMethod* method = nullptr;
3815 uint32_t dex_pc = dex::kDexNoIndex;
3816 StackVisitor::WalkStack(
3817 [&](const StackVisitor* visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
3818 ArtMethod* m = visitor->GetMethod();
3819 if (m->IsRuntimeMethod()) {
3820 // Continue if this is a runtime method.
3821 return true;
3822 }
3823 method = m;
3824 dex_pc = visitor->GetDexPc(abort_on_error);
3825 return false;
3826 },
3827 const_cast<Thread*>(this),
3828 /* context= */ nullptr,
3829 StackVisitor::StackWalkKind::kIncludeInlinedFrames,
3830 check_suspended);
3831
3832 if (dex_pc_out != nullptr) {
3833 *dex_pc_out = dex_pc;
Elliott Hughes9fd66f52011-10-16 12:13:26 -07003834 }
Andreas Gampec7d878d2018-11-19 18:42:06 +00003835 return method;
jeffhao33dc7712011-11-09 17:54:24 -08003836}
3837
Mathieu Chartierf5769e12017-01-10 15:54:41 -08003838bool Thread::HoldsLock(ObjPtr<mirror::Object> object) const {
3839 return object != nullptr && object->GetLockOwnerThreadId() == GetThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -07003840}
3841
Roland Levillainad0777d2018-02-12 20:00:18 +00003842extern std::vector<StackReference<mirror::Object>*> GetProxyReferenceArguments(ArtMethod** sp)
Roland Levillainfa854e42018-02-07 13:09:55 +00003843 REQUIRES_SHARED(Locks::mutator_lock_);
3844
Ian Rogers40e3bac2012-11-20 00:09:14 -08003845// RootVisitor parameters are: (const Object* obj, size_t vreg, const StackVisitor* visitor).
Andreas Gampe585da952016-12-02 14:52:29 -08003846template <typename RootVisitor, bool kPrecise = false>
Ian Rogers0399dde2012-06-06 17:09:28 -07003847class ReferenceMapVisitor : public StackVisitor {
Ian Rogersd6b1f612011-09-27 13:38:14 -07003848 public:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07003849 ReferenceMapVisitor(Thread* thread, Context* context, RootVisitor& visitor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003850 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01003851 // We are visiting the references in compiled frames, so we do not need
3852 // to know the inlined frames.
3853 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kSkipInlinedFrames),
3854 visitor_(visitor) {}
Ian Rogersd6b1f612011-09-27 13:38:14 -07003855
Andreas Gampefa6a1b02018-09-07 08:11:55 -07003856 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -07003857 if (false) {
David Sehr709b0702016-10-13 09:12:37 -07003858 LOG(INFO) << "Visiting stack roots in " << ArtMethod::PrettyMethod(GetMethod())
Sebastien Hertz714f1752014-04-28 15:03:08 +02003859 << StringPrintf("@ PC:%04x", GetDexPc());
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -07003860 }
Ian Rogers0399dde2012-06-06 17:09:28 -07003861 ShadowFrame* shadow_frame = GetCurrentShadowFrame();
Dave Allison0aded082013-11-07 13:15:11 -08003862 if (shadow_frame != nullptr) {
Sebastien Hertz714f1752014-04-28 15:03:08 +02003863 VisitShadowFrame(shadow_frame);
Nicolas Geoffray013d1ee2019-12-04 16:18:15 +00003864 } else if (GetCurrentOatQuickMethodHeader()->IsNterpMethodHeader()) {
3865 VisitNterpFrame();
Sebastien Hertz714f1752014-04-28 15:03:08 +02003866 } else {
3867 VisitQuickFrame();
3868 }
3869 return true;
3870 }
3871
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003872 void VisitShadowFrame(ShadowFrame* shadow_frame) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003873 ArtMethod* m = shadow_frame->GetMethod();
Mathieu Chartier10e5ea92015-08-13 12:56:31 -07003874 VisitDeclaringClass(m);
Hiroshi Yamauchi92d1a662014-05-15 21:43:59 -07003875 DCHECK(m != nullptr);
Sebastien Hertz714f1752014-04-28 15:03:08 +02003876 size_t num_regs = shadow_frame->NumberOfVRegs();
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +01003877 // handle scope for JNI or References for interpreter.
3878 for (size_t reg = 0; reg < num_regs; ++reg) {
3879 mirror::Object* ref = shadow_frame->GetVRegReference(reg);
3880 if (ref != nullptr) {
3881 mirror::Object* new_ref = ref;
3882 visitor_(&new_ref, reg, this);
3883 if (new_ref != ref) {
3884 shadow_frame->SetVRegReference(reg, new_ref);
TDYa127ce4cc0d2012-11-18 16:59:53 -08003885 }
3886 }
Sebastien Hertz714f1752014-04-28 15:03:08 +02003887 }
Andreas Gampe03ec9302015-08-27 17:41:47 -07003888 // Mark lock count map required for structured locking checks.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003889 shadow_frame->GetLockCountData().VisitMonitors(visitor_, /* vreg= */ -1, this);
Sebastien Hertz714f1752014-04-28 15:03:08 +02003890 }
3891
3892 private:
Mathieu Chartier10e5ea92015-08-13 12:56:31 -07003893 // Visiting the declaring class is necessary so that we don't unload the class of a method that
Mathieu Chartierd5f3f322016-03-21 14:05:56 -07003894 // is executing. We need to ensure that the code stays mapped. NO_THREAD_SAFETY_ANALYSIS since
3895 // the threads do not all hold the heap bitmap lock for parallel GC.
3896 void VisitDeclaringClass(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003897 REQUIRES_SHARED(Locks::mutator_lock_)
Mathieu Chartierd5f3f322016-03-21 14:05:56 -07003898 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierf5769e12017-01-10 15:54:41 -08003899 ObjPtr<mirror::Class> klass = method->GetDeclaringClassUnchecked<kWithoutReadBarrier>();
Mathieu Chartier10e5ea92015-08-13 12:56:31 -07003900 // klass can be null for runtime methods.
3901 if (klass != nullptr) {
Mathieu Chartierd5f3f322016-03-21 14:05:56 -07003902 if (kVerifyImageObjectsMarked) {
3903 gc::Heap* const heap = Runtime::Current()->GetHeap();
3904 gc::space::ContinuousSpace* space = heap->FindContinuousSpaceFromObject(klass,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003905 /*fail_ok=*/true);
Mathieu Chartierd5f3f322016-03-21 14:05:56 -07003906 if (space != nullptr && space->IsImageSpace()) {
3907 bool failed = false;
Mathieu Chartierf5769e12017-01-10 15:54:41 -08003908 if (!space->GetLiveBitmap()->Test(klass.Ptr())) {
Mathieu Chartierd5f3f322016-03-21 14:05:56 -07003909 failed = true;
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07003910 LOG(FATAL_WITHOUT_ABORT) << "Unmarked object in image " << *space;
Mathieu Chartierf5769e12017-01-10 15:54:41 -08003911 } else if (!heap->GetLiveBitmap()->Test(klass.Ptr())) {
Mathieu Chartierd5f3f322016-03-21 14:05:56 -07003912 failed = true;
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07003913 LOG(FATAL_WITHOUT_ABORT) << "Unmarked object in image through live bitmap " << *space;
Mathieu Chartierd5f3f322016-03-21 14:05:56 -07003914 }
3915 if (failed) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07003916 GetThread()->Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
3917 space->AsImageSpace()->DumpSections(LOG_STREAM(FATAL_WITHOUT_ABORT));
3918 LOG(FATAL_WITHOUT_ABORT) << "Method@" << method->GetDexMethodIndex() << ":" << method
Mathieu Chartierf5769e12017-01-10 15:54:41 -08003919 << " klass@" << klass.Ptr();
Mathieu Chartierd5f3f322016-03-21 14:05:56 -07003920 // Pretty info last in case it crashes.
David Sehr709b0702016-10-13 09:12:37 -07003921 LOG(FATAL) << "Method " << method->PrettyMethod() << " klass "
3922 << klass->PrettyClass();
Mathieu Chartierd5f3f322016-03-21 14:05:56 -07003923 }
3924 }
3925 }
Mathieu Chartierf5769e12017-01-10 15:54:41 -08003926 mirror::Object* new_ref = klass.Ptr();
Alex Light0054aa52019-09-10 16:46:48 -07003927 visitor_(&new_ref, /* vreg= */ JavaFrameRootInfo::kMethodDeclaringClass, this);
Mathieu Chartier10e5ea92015-08-13 12:56:31 -07003928 if (new_ref != klass) {
Mathieu Chartierf5769e12017-01-10 15:54:41 -08003929 method->CASDeclaringClass(klass.Ptr(), new_ref->AsClass());
Mathieu Chartier10e5ea92015-08-13 12:56:31 -07003930 }
3931 }
3932 }
3933
Nicolas Geoffray013d1ee2019-12-04 16:18:15 +00003934 void VisitNterpFrame() REQUIRES_SHARED(Locks::mutator_lock_) {
3935 ArtMethod** cur_quick_frame = GetCurrentQuickFrame();
3936 StackReference<mirror::Object>* vreg_ref_base =
3937 reinterpret_cast<StackReference<mirror::Object>*>(NterpGetReferenceArray(cur_quick_frame));
3938 StackReference<mirror::Object>* vreg_int_base =
3939 reinterpret_cast<StackReference<mirror::Object>*>(NterpGetRegistersArray(cur_quick_frame));
3940 CodeItemDataAccessor accessor((*cur_quick_frame)->DexInstructionData());
3941 const uint16_t num_regs = accessor.RegistersSize();
3942 // An nterp frame has two arrays: a dex register array and a reference array
3943 // that shadows the dex register array but only containing references
3944 // (non-reference dex registers have nulls). See nterp_helpers.cc.
3945 for (size_t reg = 0; reg < num_regs; ++reg) {
3946 StackReference<mirror::Object>* ref_addr = vreg_ref_base + reg;
3947 mirror::Object* ref = ref_addr->AsMirrorPtr();
3948 if (ref != nullptr) {
3949 mirror::Object* new_ref = ref;
3950 visitor_(&new_ref, reg, this);
3951 if (new_ref != ref) {
3952 ref_addr->Assign(new_ref);
3953 StackReference<mirror::Object>* int_addr = vreg_int_base + reg;
3954 int_addr->Assign(new_ref);
3955 }
3956 }
3957 }
3958 }
3959
Andreas Gampe585da952016-12-02 14:52:29 -08003960 template <typename T>
3961 ALWAYS_INLINE
3962 inline void VisitQuickFrameWithVregCallback() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier10e5ea92015-08-13 12:56:31 -07003963 ArtMethod** cur_quick_frame = GetCurrentQuickFrame();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003964 DCHECK(cur_quick_frame != nullptr);
Mathieu Chartier10e5ea92015-08-13 12:56:31 -07003965 ArtMethod* m = *cur_quick_frame;
3966 VisitDeclaringClass(m);
Andreas Gampecf4035a2014-05-28 22:43:01 -07003967
Vladimir Markocedec9d2021-02-08 16:16:13 +00003968 if (m->IsNative()) {
3969 // TODO: Spill the `this` reference in the AOT-compiled String.charAt()
3970 // slow-path for throwing SIOOBE, so that we can remove this carve-out.
3971 if (UNLIKELY(m->IsIntrinsic()) &&
3972 m->GetIntrinsic() == enum_cast<uint32_t>(Intrinsics::kStringCharAt)) {
3973 // The String.charAt() method is AOT-compiled with an intrinsic implementation
3974 // instead of a JNI stub. It has a slow path that constructs a runtime frame
3975 // for throwing SIOOBE and in that path we do not get the `this` pointer
3976 // spilled on the stack, so there is nothing to visit. We can distinguish
3977 // this from the GenericJni path by checking that the PC is in the boot image
3978 // (PC shall be known thanks to the runtime frame for throwing SIOOBE).
3979 // Note that JIT does not emit that intrinic implementation.
3980 const void* pc = reinterpret_cast<const void*>(GetCurrentQuickFramePc());
3981 if (pc != 0u && Runtime::Current()->GetHeap()->IsInBootImageOatFile(pc)) {
3982 return;
3983 }
3984 }
3985 // Native methods spill their arguments to the reserved vregs in the caller's frame
3986 // and use pointers to these stack references as jobject, jclass, jarray, etc.
3987 // Note: We can come here for a @CriticalNative method when it needs to resolve the
3988 // target native function but there would be no references to visit below.
3989 const size_t frame_size = GetCurrentQuickFrameInfo().FrameSizeInBytes();
3990 const size_t method_pointer_size = static_cast<size_t>(kRuntimePointerSize);
3991 uint32_t* current_vreg = reinterpret_cast<uint32_t*>(
3992 reinterpret_cast<uint8_t*>(cur_quick_frame) + frame_size + method_pointer_size);
3993 auto visit = [&]() REQUIRES_SHARED(Locks::mutator_lock_) {
3994 auto* ref_addr = reinterpret_cast<StackReference<mirror::Object>*>(current_vreg);
3995 mirror::Object* ref = ref_addr->AsMirrorPtr();
3996 if (ref != nullptr) {
3997 mirror::Object* new_ref = ref;
3998 visitor_(&new_ref, /* vreg= */ JavaFrameRootInfo::kNativeReferenceArgument, this);
3999 if (ref != new_ref) {
4000 ref_addr->Assign(new_ref);
4001 }
4002 }
4003 };
4004 const char* shorty = m->GetShorty();
4005 if (!m->IsStatic()) {
4006 visit();
4007 current_vreg += 1u;
4008 }
4009 for (shorty += 1u; *shorty != 0; ++shorty) {
4010 switch (*shorty) {
4011 case 'D':
4012 case 'J':
4013 current_vreg += 2u;
4014 break;
4015 case 'L':
4016 visit();
4017 FALLTHROUGH_INTENDED;
4018 default:
4019 current_vreg += 1u;
4020 break;
4021 }
4022 }
4023 } else if (!m->IsRuntimeMethod() && (!m->IsProxyMethod() || m->IsConstructor())) {
4024 // Process register map (which native, runtime and proxy methods don't have)
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +01004025 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01004026 DCHECK(method_header->IsOptimized());
Vladimir Marko78baed52018-10-11 10:44:58 +01004027 StackReference<mirror::Object>* vreg_base =
4028 reinterpret_cast<StackReference<mirror::Object>*>(cur_quick_frame);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01004029 uintptr_t native_pc_offset = method_header->NativeQuickPcOffset(GetCurrentQuickFramePc());
David Srbecky0d4567f2019-05-30 22:45:40 +01004030 CodeInfo code_info = kPrecise
4031 ? CodeInfo(method_header) // We will need dex register maps.
4032 : CodeInfo::DecodeGcMasksOnly(method_header);
David Srbecky052f8ca2018-04-26 15:42:54 +01004033 StackMap map = code_info.GetStackMapForNativePcOffset(native_pc_offset);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01004034 DCHECK(map.IsValid());
Andreas Gampe585da952016-12-02 14:52:29 -08004035
David Srbecky052f8ca2018-04-26 15:42:54 +01004036 T vreg_info(m, code_info, map, visitor_);
Andreas Gampe585da952016-12-02 14:52:29 -08004037
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01004038 // Visit stack entries that hold pointers.
David Srbecky052f8ca2018-04-26 15:42:54 +01004039 BitMemoryRegion stack_mask = code_info.GetStackMaskOf(map);
David Srbecky4b59d102018-05-29 21:46:10 +00004040 for (size_t i = 0; i < stack_mask.size_in_bits(); ++i) {
David Srbecky45aa5982016-03-18 02:15:09 +00004041 if (stack_mask.LoadBit(i)) {
Roland Levillainfa854e42018-02-07 13:09:55 +00004042 StackReference<mirror::Object>* ref_addr = vreg_base + i;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01004043 mirror::Object* ref = ref_addr->AsMirrorPtr();
4044 if (ref != nullptr) {
4045 mirror::Object* new_ref = ref;
Andreas Gampe585da952016-12-02 14:52:29 -08004046 vreg_info.VisitStack(&new_ref, i, this);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01004047 if (ref != new_ref) {
4048 ref_addr->Assign(new_ref);
David Srbeckya2d29a32018-08-03 11:06:38 +01004049 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01004050 }
4051 }
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01004052 }
4053 // Visit callee-save registers that hold pointers.
David Srbecky052f8ca2018-04-26 15:42:54 +01004054 uint32_t register_mask = code_info.GetRegisterMaskOf(map);
Eric Holkf1e1dd12020-08-21 15:38:12 -07004055 for (uint32_t i = 0; i < BitSizeOf<uint32_t>(); ++i) {
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01004056 if (register_mask & (1 << i)) {
4057 mirror::Object** ref_addr = reinterpret_cast<mirror::Object**>(GetGPRAddress(i));
Hiroshi Yamauchieb1680f2016-09-12 12:10:08 -07004058 if (kIsDebugBuild && ref_addr == nullptr) {
4059 std::string thread_name;
4060 GetThread()->GetThreadName(thread_name);
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07004061 LOG(FATAL_WITHOUT_ABORT) << "On thread " << thread_name;
Hiroshi Yamauchieb1680f2016-09-12 12:10:08 -07004062 DescribeStack(GetThread());
4063 LOG(FATAL) << "Found an unsaved callee-save register " << i << " (null GPRAddress) "
4064 << "set in register_mask=" << register_mask << " at " << DescribeLocation();
4065 }
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01004066 if (*ref_addr != nullptr) {
Andreas Gampe585da952016-12-02 14:52:29 -08004067 vreg_info.VisitRegister(ref_addr, i, this);
Shih-wei Liao4f894e32011-09-27 21:33:19 -07004068 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07004069 }
4070 }
Roland Levillainad0777d2018-02-12 20:00:18 +00004071 } else if (!m->IsRuntimeMethod() && m->IsProxyMethod()) {
4072 // If this is a proxy method, visit its reference arguments.
4073 DCHECK(!m->IsStatic());
Roland Levillainfa854e42018-02-07 13:09:55 +00004074 DCHECK(!m->IsNative());
Roland Levillainad0777d2018-02-12 20:00:18 +00004075 std::vector<StackReference<mirror::Object>*> ref_addrs =
4076 GetProxyReferenceArguments(cur_quick_frame);
4077 for (StackReference<mirror::Object>* ref_addr : ref_addrs) {
4078 mirror::Object* ref = ref_addr->AsMirrorPtr();
4079 if (ref != nullptr) {
4080 mirror::Object* new_ref = ref;
Alex Light0054aa52019-09-10 16:46:48 -07004081 visitor_(&new_ref, /* vreg= */ JavaFrameRootInfo::kProxyReferenceArgument, this);
Roland Levillainad0777d2018-02-12 20:00:18 +00004082 if (ref != new_ref) {
4083 ref_addr->Assign(new_ref);
4084 }
Roland Levillainfa854e42018-02-07 13:09:55 +00004085 }
4086 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07004087 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07004088 }
4089
Andreas Gampe585da952016-12-02 14:52:29 -08004090 void VisitQuickFrame() REQUIRES_SHARED(Locks::mutator_lock_) {
4091 if (kPrecise) {
4092 VisitQuickFramePrecise();
4093 } else {
4094 VisitQuickFrameNonPrecise();
4095 }
4096 }
4097
4098 void VisitQuickFrameNonPrecise() REQUIRES_SHARED(Locks::mutator_lock_) {
4099 struct UndefinedVRegInfo {
4100 UndefinedVRegInfo(ArtMethod* method ATTRIBUTE_UNUSED,
4101 const CodeInfo& code_info ATTRIBUTE_UNUSED,
Andreas Gampe585da952016-12-02 14:52:29 -08004102 const StackMap& map ATTRIBUTE_UNUSED,
4103 RootVisitor& _visitor)
4104 : visitor(_visitor) {
4105 }
4106
4107 ALWAYS_INLINE
4108 void VisitStack(mirror::Object** ref,
4109 size_t stack_index ATTRIBUTE_UNUSED,
4110 const StackVisitor* stack_visitor)
4111 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light0054aa52019-09-10 16:46:48 -07004112 visitor(ref, JavaFrameRootInfo::kImpreciseVreg, stack_visitor);
Andreas Gampe585da952016-12-02 14:52:29 -08004113 }
4114
4115 ALWAYS_INLINE
4116 void VisitRegister(mirror::Object** ref,
4117 size_t register_index ATTRIBUTE_UNUSED,
4118 const StackVisitor* stack_visitor)
4119 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light0054aa52019-09-10 16:46:48 -07004120 visitor(ref, JavaFrameRootInfo::kImpreciseVreg, stack_visitor);
Andreas Gampe585da952016-12-02 14:52:29 -08004121 }
4122
4123 RootVisitor& visitor;
4124 };
4125 VisitQuickFrameWithVregCallback<UndefinedVRegInfo>();
4126 }
4127
4128 void VisitQuickFramePrecise() REQUIRES_SHARED(Locks::mutator_lock_) {
4129 struct StackMapVRegInfo {
4130 StackMapVRegInfo(ArtMethod* method,
4131 const CodeInfo& _code_info,
Andreas Gampe585da952016-12-02 14:52:29 -08004132 const StackMap& map,
4133 RootVisitor& _visitor)
David Sehr0225f8e2018-01-31 08:52:24 +00004134 : number_of_dex_registers(method->DexInstructionData().RegistersSize()),
Andreas Gampe585da952016-12-02 14:52:29 -08004135 code_info(_code_info),
David Srbeckyfd89b072018-06-03 12:00:22 +01004136 dex_register_map(code_info.GetDexRegisterMapOf(map)),
Andreas Gampe585da952016-12-02 14:52:29 -08004137 visitor(_visitor) {
Artem Serov2808be82018-12-20 19:15:11 +00004138 DCHECK_EQ(dex_register_map.size(), number_of_dex_registers);
Andreas Gampe585da952016-12-02 14:52:29 -08004139 }
4140
4141 // TODO: If necessary, we should consider caching a reverse map instead of the linear
4142 // lookups for each location.
4143 void FindWithType(const size_t index,
4144 const DexRegisterLocation::Kind kind,
4145 mirror::Object** ref,
4146 const StackVisitor* stack_visitor)
4147 REQUIRES_SHARED(Locks::mutator_lock_) {
4148 bool found = false;
4149 for (size_t dex_reg = 0; dex_reg != number_of_dex_registers; ++dex_reg) {
David Srbeckye1402122018-06-13 18:20:45 +01004150 DexRegisterLocation location = dex_register_map[dex_reg];
Andreas Gampe585da952016-12-02 14:52:29 -08004151 if (location.GetKind() == kind && static_cast<size_t>(location.GetValue()) == index) {
4152 visitor(ref, dex_reg, stack_visitor);
4153 found = true;
4154 }
4155 }
4156
4157 if (!found) {
Alex Light0054aa52019-09-10 16:46:48 -07004158 // If nothing found, report with unknown.
4159 visitor(ref, JavaFrameRootInfo::kUnknownVreg, stack_visitor);
Andreas Gampe585da952016-12-02 14:52:29 -08004160 }
4161 }
4162
4163 void VisitStack(mirror::Object** ref, size_t stack_index, const StackVisitor* stack_visitor)
4164 REQUIRES_SHARED(Locks::mutator_lock_) {
4165 const size_t stack_offset = stack_index * kFrameSlotSize;
4166 FindWithType(stack_offset,
4167 DexRegisterLocation::Kind::kInStack,
4168 ref,
4169 stack_visitor);
4170 }
4171
4172 void VisitRegister(mirror::Object** ref,
4173 size_t register_index,
4174 const StackVisitor* stack_visitor)
4175 REQUIRES_SHARED(Locks::mutator_lock_) {
4176 FindWithType(register_index,
4177 DexRegisterLocation::Kind::kInRegister,
4178 ref,
4179 stack_visitor);
4180 }
4181
4182 size_t number_of_dex_registers;
4183 const CodeInfo& code_info;
Andreas Gampe585da952016-12-02 14:52:29 -08004184 DexRegisterMap dex_register_map;
4185 RootVisitor& visitor;
4186 };
4187 VisitQuickFrameWithVregCallback<StackMapVRegInfo>();
4188 }
4189
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07004190 // Visitor for when we visit a root.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07004191 RootVisitor& visitor_;
Ian Rogersd6b1f612011-09-27 13:38:14 -07004192};
4193
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07004194class RootCallbackVisitor {
4195 public:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07004196 RootCallbackVisitor(RootVisitor* visitor, uint32_t tid) : visitor_(visitor), tid_(tid) {}
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07004197
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07004198 void operator()(mirror::Object** obj, size_t vreg, const StackVisitor* stack_visitor) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004199 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07004200 visitor_->VisitRoot(obj, JavaFrameRootInfo(tid_, stack_visitor, vreg));
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07004201 }
4202
4203 private:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07004204 RootVisitor* const visitor_;
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08004205 const uint32_t tid_;
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07004206};
4207
Alex Light55eccdf2019-10-07 13:51:13 +00004208void Thread::VisitReflectiveTargets(ReflectiveValueVisitor* visitor) {
4209 for (BaseReflectiveHandleScope* brhs = GetTopReflectiveHandleScope();
4210 brhs != nullptr;
4211 brhs = brhs->GetLink()) {
4212 brhs->VisitTargets(visitor);
4213 }
4214}
4215
Yi Kong29997592021-08-27 17:31:20 +08004216// FIXME: clang-r433403 reports the below function exceeds frame size limit.
4217// http://b/197647048
4218#pragma GCC diagnostic push
4219#pragma GCC diagnostic ignored "-Wframe-larger-than="
Andreas Gampe585da952016-12-02 14:52:29 -08004220template <bool kPrecise>
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07004221void Thread::VisitRoots(RootVisitor* visitor) {
Eric Holkf1e1dd12020-08-21 15:38:12 -07004222 const uint32_t thread_id = GetThreadId();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07004223 visitor->VisitRootIfNonNull(&tlsPtr_.opeer, RootInfo(kRootThreadObject, thread_id));
Sebastien Hertzfd3077e2014-04-23 10:32:43 +02004224 if (tlsPtr_.exception != nullptr && tlsPtr_.exception != GetDeoptimizationException()) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07004225 visitor->VisitRoot(reinterpret_cast<mirror::Object**>(&tlsPtr_.exception),
Sebastien Hertz07474662015-08-25 15:12:33 +00004226 RootInfo(kRootNativeStack, thread_id));
Elliott Hughesd369bb72011-09-12 14:41:14 -07004227 }
Alex Light848574c2017-09-25 16:59:39 -07004228 if (tlsPtr_.async_exception != nullptr) {
4229 visitor->VisitRoot(reinterpret_cast<mirror::Object**>(&tlsPtr_.async_exception),
4230 RootInfo(kRootNativeStack, thread_id));
4231 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07004232 visitor->VisitRootIfNonNull(&tlsPtr_.monitor_enter_object, RootInfo(kRootNativeStack, thread_id));
Ian Rogers55256cb2017-12-21 17:07:11 -08004233 tlsPtr_.jni_env->VisitJniLocalRoots(visitor, RootInfo(kRootJNILocal, thread_id));
4234 tlsPtr_.jni_env->VisitMonitorRoots(visitor, RootInfo(kRootJNIMonitor, thread_id));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07004235 HandleScopeVisitRoots(visitor, thread_id);
Sebastien Hertz07474662015-08-25 15:12:33 +00004236 // Visit roots for deoptimization.
Mingyao Yang1f2d3ba2015-05-18 12:12:50 -07004237 if (tlsPtr_.stacked_shadow_frame_record != nullptr) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07004238 RootCallbackVisitor visitor_to_callback(visitor, thread_id);
Andreas Gampe585da952016-12-02 14:52:29 -08004239 ReferenceMapVisitor<RootCallbackVisitor, kPrecise> mapper(this, nullptr, visitor_to_callback);
Mingyao Yang1f2d3ba2015-05-18 12:12:50 -07004240 for (StackedShadowFrameRecord* record = tlsPtr_.stacked_shadow_frame_record;
4241 record != nullptr;
4242 record = record->GetLink()) {
4243 for (ShadowFrame* shadow_frame = record->GetShadowFrame();
4244 shadow_frame != nullptr;
4245 shadow_frame = shadow_frame->GetLink()) {
4246 mapper.VisitShadowFrame(shadow_frame);
4247 }
Sebastien Hertz714f1752014-04-28 15:03:08 +02004248 }
4249 }
Mingyao Yang99170c62015-07-06 11:10:37 -07004250 for (DeoptimizationContextRecord* record = tlsPtr_.deoptimization_context_stack;
4251 record != nullptr;
4252 record = record->GetLink()) {
4253 if (record->IsReference()) {
4254 visitor->VisitRootIfNonNull(record->GetReturnValueAsGCRoot(),
Sebastien Hertz07474662015-08-25 15:12:33 +00004255 RootInfo(kRootThreadObject, thread_id));
Andreas Gampe2a0d4ec2014-06-02 22:05:22 -07004256 }
Mingyao Yang99170c62015-07-06 11:10:37 -07004257 visitor->VisitRootIfNonNull(record->GetPendingExceptionAsGCRoot(),
4258 RootInfo(kRootThreadObject, thread_id));
4259 }
4260 if (tlsPtr_.frame_id_to_shadow_frame != nullptr) {
4261 RootCallbackVisitor visitor_to_callback(visitor, thread_id);
Andreas Gampe585da952016-12-02 14:52:29 -08004262 ReferenceMapVisitor<RootCallbackVisitor, kPrecise> mapper(this, nullptr, visitor_to_callback);
Mingyao Yang99170c62015-07-06 11:10:37 -07004263 for (FrameIdToShadowFrame* record = tlsPtr_.frame_id_to_shadow_frame;
4264 record != nullptr;
4265 record = record->GetNext()) {
4266 mapper.VisitShadowFrame(record->GetShadowFrame());
4267 }
Andreas Gampe2a0d4ec2014-06-02 22:05:22 -07004268 }
Mathieu Chartierd0ad2ee2015-03-31 14:59:59 -07004269 for (auto* verifier = tlsPtr_.method_verifier; verifier != nullptr; verifier = verifier->link_) {
4270 verifier->VisitRoots(visitor, RootInfo(kRootNativeStack, thread_id));
Mathieu Chartier12d625f2015-03-13 11:33:37 -07004271 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07004272 // Visit roots on this thread's stack
Mathieu Chartiera62b4532017-04-26 13:16:25 -07004273 RuntimeContextType context;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07004274 RootCallbackVisitor visitor_to_callback(visitor, thread_id);
Mathieu Chartiera62b4532017-04-26 13:16:25 -07004275 ReferenceMapVisitor<RootCallbackVisitor, kPrecise> mapper(this, &context, visitor_to_callback);
Andreas Gampe585da952016-12-02 14:52:29 -08004276 mapper.template WalkStack<StackVisitor::CountTransitions::kNo>(false);
Nicolas Geoffraye91e7952020-01-23 10:15:56 +00004277 for (auto& entry : *GetInstrumentationStack()) {
4278 visitor->VisitRootIfNonNull(&entry.second.this_object_, RootInfo(kRootVMInternal, thread_id));
Ian Rogers62d6c772013-02-27 08:32:07 -08004279 }
Nicolas Geoffraye3f775b2019-12-04 14:41:52 +00004280}
Yi Kong29997592021-08-27 17:31:20 +08004281#pragma GCC diagnostic pop
Nicolas Geoffraye3f775b2019-12-04 14:41:52 +00004282
David Srbeckybe2b1092022-02-19 23:13:27 +00004283static void SweepCacheEntry(IsMarkedVisitor* visitor, const Instruction* inst, size_t* value)
4284 REQUIRES_SHARED(Locks::mutator_lock_) {
4285 if (inst == nullptr) {
4286 return;
Hans Boehm3d2f1482022-01-17 01:32:55 +00004287 }
David Srbeckybe2b1092022-02-19 23:13:27 +00004288 using Opcode = Instruction::Code;
4289 Opcode opcode = inst->Opcode();
4290 switch (opcode) {
4291 case Opcode::NEW_INSTANCE:
4292 case Opcode::CHECK_CAST:
4293 case Opcode::INSTANCE_OF:
4294 case Opcode::NEW_ARRAY:
4295 case Opcode::CONST_CLASS: {
4296 mirror::Class* cls = reinterpret_cast<mirror::Class*>(*value);
4297 if (cls == nullptr || cls == Runtime::GetWeakClassSentinel()) {
4298 // Entry got deleted in a previous sweep.
4299 return;
4300 }
4301 Runtime::ProcessWeakClass(
4302 reinterpret_cast<GcRoot<mirror::Class>*>(value),
4303 visitor,
4304 Runtime::GetWeakClassSentinel());
4305 return;
4306 }
4307 case Opcode::CONST_STRING:
4308 case Opcode::CONST_STRING_JUMBO: {
4309 mirror::Object* object = reinterpret_cast<mirror::Object*>(*value);
4310 mirror::Object* new_object = visitor->IsMarked(object);
4311 // We know the string is marked because it's a strongly-interned string that
4312 // is always alive (see b/117621117 for trying to make those strings weak).
4313 // The IsMarked implementation of the CMS collector returns
4314 // null for newly allocated objects, but we know those haven't moved. Therefore,
4315 // only update the entry if we get a different non-null string.
4316 if (new_object != nullptr && new_object != object) {
4317 *value = reinterpret_cast<size_t>(new_object);
4318 }
4319 return;
4320 }
4321 default:
4322 // The following opcode ranges store non-reference values.
4323 if ((Opcode::IGET <= opcode && opcode <= Opcode::SPUT_SHORT) ||
4324 (Opcode::INVOKE_VIRTUAL <= opcode && opcode <= Opcode::INVOKE_INTERFACE_RANGE)) {
4325 return; // Nothing to do for the GC.
4326 }
4327 // New opcode is using the cache. We need to explicitly handle it in this method.
4328 DCHECK(false) << "Unhandled opcode " << inst->Opcode();
4329 }
4330};
4331
4332void Thread::SweepInterpreterCaches(IsMarkedVisitor* visitor) {
4333 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
4334 Runtime::Current()->GetThreadList()->ForEach([visitor](Thread* thread) {
4335 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
4336 for (InterpreterCache::Entry& entry : thread->GetInterpreterCache()->GetArray()) {
4337 SweepCacheEntry(visitor, reinterpret_cast<const Instruction*>(entry.first), &entry.second);
4338 }
4339 });
Elliott Hughes410c0c82011-09-01 17:58:25 -07004340}
4341
Yi Kong29997592021-08-27 17:31:20 +08004342// FIXME: clang-r433403 reports the below function exceeds frame size limit.
4343// http://b/197647048
4344#pragma GCC diagnostic push
4345#pragma GCC diagnostic ignored "-Wframe-larger-than="
Andreas Gampe585da952016-12-02 14:52:29 -08004346void Thread::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
4347 if ((flags & VisitRootFlags::kVisitRootFlagPrecise) != 0) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -07004348 VisitRoots</* kPrecise= */ true>(visitor);
Andreas Gampe585da952016-12-02 14:52:29 -08004349 } else {
Andreas Gampe98ea9d92018-10-19 14:06:15 -07004350 VisitRoots</* kPrecise= */ false>(visitor);
Andreas Gampe585da952016-12-02 14:52:29 -08004351 }
4352}
Yi Kong29997592021-08-27 17:31:20 +08004353#pragma GCC diagnostic pop
Andreas Gampe585da952016-12-02 14:52:29 -08004354
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07004355class VerifyRootVisitor : public SingleRootVisitor {
4356 public:
4357 void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004358 override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07004359 VerifyObject(root);
4360 }
4361};
jeffhao25045522012-03-13 19:34:37 -07004362
Ian Rogers04d7aa92013-03-16 14:29:17 -07004363void Thread::VerifyStackImpl() {
Andreas Gamped4901292017-05-30 18:41:34 -07004364 if (Runtime::Current()->GetHeap()->IsObjectValidationEnabled()) {
4365 VerifyRootVisitor visitor;
4366 std::unique_ptr<Context> context(Context::Create());
4367 RootCallbackVisitor visitor_to_callback(&visitor, GetThreadId());
4368 ReferenceMapVisitor<RootCallbackVisitor> mapper(this, context.get(), visitor_to_callback);
4369 mapper.WalkStack();
4370 }
jeffhao25045522012-03-13 19:34:37 -07004371}
jeffhao25045522012-03-13 19:34:37 -07004372
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004373// Set the stack end to that to be used during a stack overflow
4374void Thread::SetStackEndForStackOverflow() {
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07004375 // During stack overflow we allow use of the full stack.
Ian Rogersdd7624d2014-03-14 17:43:00 -07004376 if (tlsPtr_.stack_end == tlsPtr_.stack_begin) {
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07004377 // However, we seem to have already extended to use the full stack.
4378 LOG(ERROR) << "Need to increase kStackOverflowReservedBytes (currently "
Andreas Gampe7ea6f792014-07-14 16:21:44 -07004379 << GetStackOverflowReservedBytes(kRuntimeISA) << ")?";
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07004380 DumpStack(LOG_STREAM(ERROR));
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07004381 LOG(FATAL) << "Recursive stack overflow.";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004382 }
4383
Ian Rogersdd7624d2014-03-14 17:43:00 -07004384 tlsPtr_.stack_end = tlsPtr_.stack_begin;
Dave Allison648d7112014-07-25 16:15:27 -07004385
4386 // Remove the stack overflow protection if is it set up.
Nicolas Geoffray541ca322022-01-20 09:03:04 +00004387 bool implicit_stack_check = Runtime::Current()->GetImplicitStackOverflowChecks();
Dave Allison648d7112014-07-25 16:15:27 -07004388 if (implicit_stack_check) {
4389 if (!UnprotectStack()) {
4390 LOG(ERROR) << "Unable to remove stack protection for stack overflow";
4391 }
4392 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004393}
4394
Mathieu Chartier6bc77742017-04-18 17:46:23 -07004395void Thread::SetTlab(uint8_t* start, uint8_t* end, uint8_t* limit) {
Mathieu Chartier692fafd2013-11-29 17:24:40 -08004396 DCHECK_LE(start, end);
Mathieu Chartier6bc77742017-04-18 17:46:23 -07004397 DCHECK_LE(end, limit);
Ian Rogersdd7624d2014-03-14 17:43:00 -07004398 tlsPtr_.thread_local_start = start;
4399 tlsPtr_.thread_local_pos = tlsPtr_.thread_local_start;
4400 tlsPtr_.thread_local_end = end;
Mathieu Chartier6bc77742017-04-18 17:46:23 -07004401 tlsPtr_.thread_local_limit = limit;
Ian Rogersdd7624d2014-03-14 17:43:00 -07004402 tlsPtr_.thread_local_objects = 0;
Mathieu Chartier692fafd2013-11-29 17:24:40 -08004403}
4404
Mathieu Chartierc4bf6672020-01-13 13:07:16 -08004405void Thread::ResetTlab() {
Wessam Hassaneinb5a10be2020-11-11 16:42:52 -08004406 gc::Heap* const heap = Runtime::Current()->GetHeap();
4407 if (heap->GetHeapSampler().IsEnabled()) {
4408 // Note: We always ResetTlab before SetTlab, therefore we can do the sample
4409 // offset adjustment here.
4410 heap->AdjustSampleOffset(GetTlabPosOffset());
4411 VLOG(heap) << "JHP: ResetTlab, Tid: " << GetTid()
4412 << " adjustment = "
4413 << (tlsPtr_.thread_local_pos - tlsPtr_.thread_local_start);
4414 }
Mathieu Chartierc4bf6672020-01-13 13:07:16 -08004415 SetTlab(nullptr, nullptr, nullptr);
4416}
4417
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07004418bool Thread::HasTlab() const {
Mathieu Chartierc4bf6672020-01-13 13:07:16 -08004419 const bool has_tlab = tlsPtr_.thread_local_pos != nullptr;
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07004420 if (has_tlab) {
Ian Rogersdd7624d2014-03-14 17:43:00 -07004421 DCHECK(tlsPtr_.thread_local_start != nullptr && tlsPtr_.thread_local_end != nullptr);
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07004422 } else {
Ian Rogersdd7624d2014-03-14 17:43:00 -07004423 DCHECK(tlsPtr_.thread_local_start == nullptr && tlsPtr_.thread_local_end == nullptr);
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07004424 }
4425 return has_tlab;
4426}
4427
Elliott Hughes330304d2011-08-12 14:28:05 -07004428std::ostream& operator<<(std::ostream& os, const Thread& thread) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004429 thread.ShortDump(os);
Elliott Hughes330304d2011-08-12 14:28:05 -07004430 return os;
4431}
4432
Andreas Gampe2c2d2a02016-03-17 21:27:19 -07004433bool Thread::ProtectStack(bool fatal_on_error) {
Dave Allison648d7112014-07-25 16:15:27 -07004434 void* pregion = tlsPtr_.stack_begin - kStackOverflowProtectedSize;
4435 VLOG(threads) << "Protecting stack at " << pregion;
4436 if (mprotect(pregion, kStackOverflowProtectedSize, PROT_NONE) == -1) {
Andreas Gampe2c2d2a02016-03-17 21:27:19 -07004437 if (fatal_on_error) {
4438 LOG(FATAL) << "Unable to create protected region in stack for implicit overflow check. "
4439 "Reason: "
4440 << strerror(errno) << " size: " << kStackOverflowProtectedSize;
4441 }
4442 return false;
Dave Allison648d7112014-07-25 16:15:27 -07004443 }
Andreas Gampe2c2d2a02016-03-17 21:27:19 -07004444 return true;
Dave Allison648d7112014-07-25 16:15:27 -07004445}
4446
4447bool Thread::UnprotectStack() {
4448 void* pregion = tlsPtr_.stack_begin - kStackOverflowProtectedSize;
4449 VLOG(threads) << "Unprotecting stack at " << pregion;
4450 return mprotect(pregion, kStackOverflowProtectedSize, PROT_READ|PROT_WRITE) == 0;
4451}
4452
Mathieu Chartierd0ad2ee2015-03-31 14:59:59 -07004453void Thread::PushVerifier(verifier::MethodVerifier* verifier) {
4454 verifier->link_ = tlsPtr_.method_verifier;
Mathieu Chartier12d625f2015-03-13 11:33:37 -07004455 tlsPtr_.method_verifier = verifier;
4456}
4457
Mathieu Chartierd0ad2ee2015-03-31 14:59:59 -07004458void Thread::PopVerifier(verifier::MethodVerifier* verifier) {
Mathieu Chartier12d625f2015-03-13 11:33:37 -07004459 CHECK_EQ(tlsPtr_.method_verifier, verifier);
Mathieu Chartierd0ad2ee2015-03-31 14:59:59 -07004460 tlsPtr_.method_verifier = verifier->link_;
Mathieu Chartier12d625f2015-03-13 11:33:37 -07004461}
4462
Mathieu Chartier14c3bf92015-07-13 14:35:43 -07004463size_t Thread::NumberOfHeldMutexes() const {
4464 size_t count = 0;
4465 for (BaseMutex* mu : tlsPtr_.held_mutexes) {
Mathieu Chartier90ef3db2015-08-04 15:19:41 -07004466 count += mu != nullptr ? 1 : 0;
Mathieu Chartier14c3bf92015-07-13 14:35:43 -07004467 }
4468 return count;
4469}
4470
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00004471void Thread::DeoptimizeWithDeoptimizationException(JValue* result) {
4472 DCHECK_EQ(GetException(), Thread::GetDeoptimizationException());
4473 ClearException();
4474 ShadowFrame* shadow_frame =
4475 PopStackedShadowFrame(StackedShadowFrameType::kDeoptimizationShadowFrame);
Mathieu Chartierf5769e12017-01-10 15:54:41 -08004476 ObjPtr<mirror::Throwable> pending_exception;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00004477 bool from_code = false;
Mingyao Yang2ee17902017-08-30 11:37:08 -07004478 DeoptimizationMethodType method_type;
4479 PopDeoptimizationContext(result, &pending_exception, &from_code, &method_type);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00004480 SetTopOfStack(nullptr);
4481 SetTopOfShadowStack(shadow_frame);
4482
4483 // Restore the exception that was pending before deoptimization then interpret the
4484 // deoptimized frames.
4485 if (pending_exception != nullptr) {
4486 SetException(pending_exception);
4487 }
Mingyao Yang2ee17902017-08-30 11:37:08 -07004488 interpreter::EnterInterpreterFromDeoptimize(this,
4489 shadow_frame,
4490 result,
4491 from_code,
4492 method_type);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00004493}
4494
Alex Light848574c2017-09-25 16:59:39 -07004495void Thread::SetAsyncException(ObjPtr<mirror::Throwable> new_exception) {
4496 CHECK(new_exception != nullptr);
David Srbeckyd3883902019-02-26 17:29:32 +00004497 Runtime::Current()->SetAsyncExceptionsThrown();
Alex Light848574c2017-09-25 16:59:39 -07004498 if (kIsDebugBuild) {
4499 // Make sure we are in a checkpoint.
4500 MutexLock mu(Thread::Current(), *Locks::thread_suspend_count_lock_);
4501 CHECK(this == Thread::Current() || GetSuspendCount() >= 1)
4502 << "It doesn't look like this was called in a checkpoint! this: "
4503 << this << " count: " << GetSuspendCount();
4504 }
4505 tlsPtr_.async_exception = new_exception.Ptr();
4506}
4507
4508bool Thread::ObserveAsyncException() {
4509 DCHECK(this == Thread::Current());
4510 if (tlsPtr_.async_exception != nullptr) {
4511 if (tlsPtr_.exception != nullptr) {
4512 LOG(WARNING) << "Overwriting pending exception with async exception. Pending exception is: "
4513 << tlsPtr_.exception->Dump();
4514 LOG(WARNING) << "Async exception is " << tlsPtr_.async_exception->Dump();
4515 }
4516 tlsPtr_.exception = tlsPtr_.async_exception;
4517 tlsPtr_.async_exception = nullptr;
4518 return true;
4519 } else {
4520 return IsExceptionPending();
4521 }
4522}
4523
Mathieu Chartier0795f232016-09-27 18:43:30 -07004524void Thread::SetException(ObjPtr<mirror::Throwable> new_exception) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07004525 CHECK(new_exception != nullptr);
4526 // TODO: DCHECK(!IsExceptionPending());
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07004527 tlsPtr_.exception = new_exception.Ptr();
Mathieu Chartiere42888f2016-04-14 10:49:19 -07004528}
4529
Andreas Gampe2c19f5b2016-11-28 08:10:18 -08004530bool Thread::IsAotCompiler() {
4531 return Runtime::Current()->IsAotCompiler();
4532}
4533
Andreas Gampe202f85a2017-02-06 10:23:26 -08004534mirror::Object* Thread::GetPeerFromOtherThread() const {
Nicolas Geoffrayffc8cad2017-02-10 10:59:22 +00004535 DCHECK(tlsPtr_.jpeer == nullptr);
4536 mirror::Object* peer = tlsPtr_.opeer;
Andreas Gampe202f85a2017-02-06 10:23:26 -08004537 if (kUseReadBarrier && Current()->GetIsGcMarking()) {
4538 // We may call Thread::Dump() in the middle of the CC thread flip and this thread's stack
4539 // may have not been flipped yet and peer may be a from-space (stale) ref. So explicitly
4540 // mark/forward it here.
4541 peer = art::ReadBarrier::Mark(peer);
4542 }
4543 return peer;
4544}
4545
Mathieu Chartier3768ade2017-05-02 14:04:39 -07004546void Thread::SetReadBarrierEntrypoints() {
4547 // Make sure entrypoints aren't null.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07004548 UpdateReadBarrierEntrypoints(&tlsPtr_.quick_entrypoints, /* is_active=*/ true);
Mathieu Chartier3768ade2017-05-02 14:04:39 -07004549}
4550
David Srbecky912f36c2018-09-08 12:22:58 +01004551void Thread::ClearAllInterpreterCaches() {
4552 static struct ClearInterpreterCacheClosure : Closure {
Yi Kong39402542019-03-24 02:47:16 -07004553 void Run(Thread* thread) override {
Hans Boehm3d2f1482022-01-17 01:32:55 +00004554 thread->GetInterpreterCache()->Clear(thread);
David Srbecky912f36c2018-09-08 12:22:58 +01004555 }
4556 } closure;
4557 Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
4558}
4559
Orion Hodson119733d2019-01-30 15:14:41 +00004560
Andreas Gampee5d23982019-01-08 10:34:26 -08004561void Thread::ReleaseLongJumpContextInternal() {
4562 // Each QuickExceptionHandler gets a long jump context and uses
4563 // it for doing the long jump, after finding catch blocks/doing deoptimization.
4564 // Both finding catch blocks and deoptimization can trigger another
4565 // exception such as a result of class loading. So there can be nested
4566 // cases of exception handling and multiple contexts being used.
4567 // ReleaseLongJumpContext tries to save the context in tlsPtr_.long_jump_context
4568 // for reuse so there is no need to always allocate a new one each time when
4569 // getting a context. Since we only keep one context for reuse, delete the
4570 // existing one since the passed in context is yet to be used for longjump.
4571 delete tlsPtr_.long_jump_context;
4572}
4573
Orion Hodson119733d2019-01-30 15:14:41 +00004574void Thread::SetNativePriority(int new_priority) {
Orion Hodsonc5323fe2021-02-04 21:20:30 +00004575 palette_status_t status = PaletteSchedSetPriority(GetTid(), new_priority);
4576 CHECK(status == PALETTE_STATUS_OK || status == PALETTE_STATUS_CHECK_ERRNO);
Orion Hodson119733d2019-01-30 15:14:41 +00004577}
4578
Nicolas Geoffrayfa595882019-08-06 17:40:09 +01004579int Thread::GetNativePriority() const {
Orion Hodson119733d2019-01-30 15:14:41 +00004580 int priority = 0;
Orion Hodsonc5323fe2021-02-04 21:20:30 +00004581 palette_status_t status = PaletteSchedGetPriority(GetTid(), &priority);
4582 CHECK(status == PALETTE_STATUS_OK || status == PALETTE_STATUS_CHECK_ERRNO);
Orion Hodson119733d2019-01-30 15:14:41 +00004583 return priority;
4584}
4585
Alex Lighte0b2ce42019-02-21 19:23:42 +00004586bool Thread::IsSystemDaemon() const {
4587 if (GetPeer() == nullptr) {
4588 return false;
4589 }
4590 return jni::DecodeArtField(
4591 WellKnownClasses::java_lang_Thread_systemDaemon)->GetBoolean(GetPeer());
4592}
4593
Hans Boehm9d27fbc2021-05-21 09:23:38 -07004594std::string Thread::StateAndFlagsAsHexString() const {
4595 std::stringstream result_stream;
Vladimir Marko9c0f7642021-12-06 16:17:52 +00004596 result_stream << std::hex << GetStateAndFlags(std::memory_order_relaxed).GetValue();
Hans Boehm9d27fbc2021-05-21 09:23:38 -07004597 return result_stream.str();
4598}
4599
Alex Lightb7c640d2019-03-20 15:52:13 -07004600ScopedExceptionStorage::ScopedExceptionStorage(art::Thread* self)
4601 : self_(self), hs_(self_), excp_(hs_.NewHandle<art::mirror::Throwable>(self_->GetException())) {
4602 self_->ClearException();
4603}
4604
Alex Light79d6c802019-06-27 15:50:11 +00004605void ScopedExceptionStorage::SuppressOldException(const char* message) {
4606 CHECK(self_->IsExceptionPending()) << *self_;
4607 ObjPtr<mirror::Throwable> old_suppressed(excp_.Get());
4608 excp_.Assign(self_->GetException());
4609 LOG(WARNING) << message << "Suppressing old exception: " << old_suppressed->Dump();
4610 self_->ClearException();
4611}
4612
Alex Lightb7c640d2019-03-20 15:52:13 -07004613ScopedExceptionStorage::~ScopedExceptionStorage() {
Alex Light79d6c802019-06-27 15:50:11 +00004614 CHECK(!self_->IsExceptionPending()) << *self_;
Alex Lightb7c640d2019-03-20 15:52:13 -07004615 if (!excp_.IsNull()) {
4616 self_->SetException(excp_.Get());
4617 }
4618}
4619
Elliott Hughes8daa0922011-09-11 13:46:25 -07004620} // namespace art
Eric Holkf1e1dd12020-08-21 15:38:12 -07004621
4622#pragma clang diagnostic pop // -Wconversion