blob: b71c41e48e04edd90ae3847d61e66fef5d02e964 [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>
Brian Carlstromdbf05b72011-12-15 00:55:24 -080022#include <sys/resource.h>
23#include <sys/time.h>
Elliott Hughesa0957642011-09-02 14:27:33 -070024
Evgenii Stepanov9b7656d2018-08-21 15:18:49 -070025#if __has_feature(hwaddress_sanitizer)
26#include <sanitizer/hwasan_interface.h>
27#else
28#define __hwasan_tag_pointer(p, t) (p)
29#endif
30
Carl Shapirob5573532011-07-12 18:22:59 -070031#include <algorithm>
Elliott Hughesdcc24742011-09-07 14:02:44 -070032#include <bitset>
Elliott Hugheseb4f6142011-07-15 17:43:51 -070033#include <cerrno>
Elliott Hughesa0957642011-09-02 14:27:33 -070034#include <iostream>
Carl Shapirob5573532011-07-12 18:22:59 -070035#include <list>
Ian Rogersc7dd2952014-10-21 23:31:19 -070036#include <sstream>
Carl Shapirob5573532011-07-12 18:22:59 -070037
Andreas Gampe43e72432019-05-14 16:15:24 -070038#include "android-base/file.h"
Andreas Gampe46ee31b2016-12-14 10:11:49 -080039#include "android-base/stringprintf.h"
Evan Chengd57c51e2018-01-26 15:43:08 +080040#include "android-base/strings.h"
Andreas Gampe46ee31b2016-12-14 10:11:49 -080041
Mathieu Chartiera62b4532017-04-26 13:16:25 -070042#include "arch/context-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070043#include "arch/context.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070044#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070045#include "art_method-inl.h"
Charles Mungeraa31f492018-11-01 18:57:38 +000046#include "base/atomic.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010047#include "base/bit_utils.h"
Vladimir Marko78baed52018-10-11 10:44:58 +010048#include "base/casts.h"
Andreas Gampee5d23982019-01-08 10:34:26 -080049#include "arch/context.h"
David Sehr891a50e2017-10-27 17:01:07 -070050#include "base/file_utils.h"
Evgenii Stepanov1e133742015-05-20 12:30:59 -070051#include "base/memory_tool.h"
Elliott Hughes76b61672012-12-12 17:47:30 -080052#include "base/mutex.h"
Alex Light184f0752018-07-13 11:18:22 -070053#include "base/stl_util.h"
Steven Morelande431e272017-07-18 16:53:49 -070054#include "base/systrace.h"
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -080055#include "base/timing_logger.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070056#include "base/to_str.h"
David Sehrc431b9d2018-03-02 12:01:51 -080057#include "base/utils.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080058#include "class_linker-inl.h"
Vladimir Marko5868ada2020-05-12 11:50:34 +010059#include "class_root-inl.h"
Ulyana Trafimoviche886d682020-07-16 15:09:38 +000060#include "code_simulator.h"
61#include "code_simulator_container.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"
David Srbecky28f6cff2018-10-16 15:07:28 +010079#include "interpreter/mterp/mterp.h"
Vladimir Marko6ec2a1b2018-05-22 15:33:48 +010080#include "interpreter/shadow_frame-inl.h"
Andreas Gampe36a296f2017-06-13 14:11:11 -070081#include "java_frame_root_info.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010082#include "jni/java_vm_ext.h"
83#include "jni/jni_internal.h"
Andreas Gampe70f5fd02018-10-24 19:58:37 -070084#include "mirror/class-alloc-inl.h"
Steven Morelande431e272017-07-18 16:53:49 -070085#include "mirror/class_loader.h"
Andreas Gampe52ecb652018-10-24 15:18:21 -070086#include "mirror/object_array-alloc-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080087#include "mirror/object_array-inl.h"
88#include "mirror/stack_trace_element.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070089#include "monitor.h"
Andreas Gampe93104952017-12-13 17:13:15 -080090#include "monitor_objects_stack_visitor.h"
Andreas Gampe5dd44d02016-08-02 17:20:03 -070091#include "native_stack_dump.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -070092#include "nativehelper/scoped_local_ref.h"
93#include "nativehelper/scoped_utf_chars.h"
Nicolas Geoffray013d1ee2019-12-04 16:18:15 +000094#include "nterp_helpers.h"
Mingyao Yangf711f2c2016-05-23 12:29:39 -070095#include "nth_caller_visitor.h"
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +010096#include "oat_quick_method_header.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070097#include "obj_ptr-inl.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070098#include "object_lock.h"
Orion Hodson119733d2019-01-30 15:14:41 +000099#include "palette/palette.h"
Vladimir Marko7624d252014-05-02 14:40:15 +0100100#include "quick/quick_method_frame_info.h"
Steven Morelande431e272017-07-18 16:53:49 -0700101#include "quick_exception_handler.h"
Andreas Gampe202f85a2017-02-06 10:23:26 -0800102#include "read_barrier-inl.h"
Jesse Wilson9a6bae82011-11-14 14:57:30 -0500103#include "reflection.h"
Alex Light55eccdf2019-10-07 13:51:13 +0000104#include "reflective_handle_scope-inl.h"
David Srbecky28f6cff2018-10-16 15:07:28 +0100105#include "runtime-inl.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700106#include "runtime.h"
Andreas Gampeac30fa22017-01-18 21:02:36 -0800107#include "runtime_callbacks.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -0700108#include "scoped_thread_state_change-inl.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
Carl Shapirob5573532011-07-12 18:22:59 -0700125namespace art {
126
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800127using android::base::StringAppendV;
128using android::base::StringPrintf;
129
Mingyao Yangf711f2c2016-05-23 12:29:39 -0700130extern "C" NO_RETURN void artDeoptimize(Thread* self);
131
Ian Rogers0878d652013-04-18 17:38:35 -0700132bool Thread::is_started_ = false;
Carl Shapirob5573532011-07-12 18:22:59 -0700133pthread_key_t Thread::pthread_key_self_;
Dave Allison0aded082013-11-07 13:15:11 -0800134ConditionVariable* Thread::resume_cond_ = nullptr;
Dave Allison648d7112014-07-25 16:15:27 -0700135const size_t Thread::kStackOverflowImplicitCheckSize = GetStackOverflowReservedBytes(kRuntimeISA);
Calin Juravleb2771b42016-04-07 17:09:25 +0100136bool (*Thread::is_sensitive_thread_hook_)() = nullptr;
Calin Juravle97cbc922016-04-15 16:16:35 +0100137Thread* Thread::jit_sensitive_thread_ = nullptr;
Andreas Gampe82372002019-07-24 15:42:09 -0700138#ifndef __BIONIC__
139thread_local Thread* Thread::self_tls_ = nullptr;
140#endif
Calin Juravleb2771b42016-04-07 17:09:25 +0100141
Mathieu Chartierb0026b42016-03-31 15:05:45 -0700142static constexpr bool kVerifyImageObjectsMarked = kIsDebugBuild;
Carl Shapirob5573532011-07-12 18:22:59 -0700143
Evgenii Stepanov1e133742015-05-20 12:30:59 -0700144// For implicit overflow checks we reserve an extra piece of memory at the bottom
145// of the stack (lowest memory). The higher portion of the memory
146// is protected against reads and the lower is available for use while
147// throwing the StackOverflow exception.
148constexpr size_t kStackOverflowProtectedSize = 4 * kMemoryToolStackGuardSizeScale * KB;
149
Elliott Hughes7dc51662012-05-16 14:48:43 -0700150static const char* kThreadNameDuringStartup = "<native thread without managed peer>";
151
Ian Rogers5d76c432011-10-31 21:42:49 -0700152void Thread::InitCardTable() {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700153 tlsPtr_.card_table = Runtime::Current()->GetHeap()->GetCardTable()->GetBiasedBegin();
Ian Rogers5d76c432011-10-31 21:42:49 -0700154}
155
Elliott Hughes3ea0f422012-04-16 17:01:43 -0700156static void UnimplementedEntryPoint() {
157 UNIMPLEMENTED(FATAL);
158}
159
Andreas Gampe3cfa4d02015-10-06 17:04:01 -0700160void InitEntryPoints(JniEntryPoints* jpoints, QuickEntryPoints* qpoints);
Mathieu Chartier3768ade2017-05-02 14:04:39 -0700161void UpdateReadBarrierEntrypoints(QuickEntryPoints* qpoints, bool is_active);
Mathieu Chartierfe814e82016-11-09 14:32:49 -0800162
163void Thread::SetIsGcMarkingAndUpdateEntrypoints(bool is_marking) {
164 CHECK(kUseReadBarrier);
165 tls32_.is_gc_marking = is_marking;
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700166 UpdateReadBarrierEntrypoints(&tlsPtr_.quick_entrypoints, /* is_active= */ is_marking);
Mathieu Chartierfe814e82016-11-09 14:32:49 -0800167}
Ian Rogers7655f292013-07-29 11:07:13 -0700168
Ulyana Trafimoviche886d682020-07-16 15:09:38 +0000169void Thread::InitSimulator() {
170 tlsPtr_.simulator = new CodeSimulatorContainer(Runtime::Current()->GetSimulateISA());
171}
172
173CodeSimulatorContainer* Thread::GetSimulator() {
174 DCHECK(tlsPtr_.simulator != nullptr);
175 return tlsPtr_.simulator;
176}
177
Ian Rogers848871b2013-08-05 10:56:33 -0700178void Thread::InitTlsEntryPoints() {
Mathieu Chartier3a0cd342018-12-13 13:45:17 -0800179 ScopedTrace trace("InitTlsEntryPoints");
Elliott Hughes3ea0f422012-04-16 17:01:43 -0700180 // Insert a placeholder so we can easily tell if we call an unimplemented entry point.
Andreas Gampe3cfa4d02015-10-06 17:04:01 -0700181 uintptr_t* begin = reinterpret_cast<uintptr_t*>(&tlsPtr_.jni_entrypoints);
Mathieu Chartier5ace2012016-11-30 10:15:41 -0800182 uintptr_t* end = reinterpret_cast<uintptr_t*>(
183 reinterpret_cast<uint8_t*>(&tlsPtr_.quick_entrypoints) + sizeof(tlsPtr_.quick_entrypoints));
Ian Rogers7655f292013-07-29 11:07:13 -0700184 for (uintptr_t* it = begin; it != end; ++it) {
185 *it = reinterpret_cast<uintptr_t>(UnimplementedEntryPoint);
186 }
Andreas Gampe3cfa4d02015-10-06 17:04:01 -0700187 InitEntryPoints(&tlsPtr_.jni_entrypoints, &tlsPtr_.quick_entrypoints);
Ulyana Trafimoviche886d682020-07-16 15:09:38 +0000188
189 // Initialize entry points for simulator because some entry points are not needed in normal run,
190 // but required in simulator mode.
191 if (Runtime::SimulatorMode()) {
192 CodeSimulatorContainer *simulator = GetSimulator();
193 DCHECK(simulator->CanSimulate());
194 simulator->Get()->InitEntryPoints(&tlsPtr_.quick_entrypoints);
195 }
Elliott Hughesc0f09332012-03-26 13:27:06 -0700196}
197
Lokesh Gidra7e678d32020-04-28 16:17:49 -0700198void Thread::ResetQuickAllocEntryPointsForThread() {
199 ResetQuickAllocEntryPoints(&tlsPtr_.quick_entrypoints);
Hiroshi Yamauchi3b4c1892013-09-12 21:33:12 -0700200}
201
Sebastien Hertz07474662015-08-25 15:12:33 +0000202class DeoptimizationContextRecord {
Sebastien Hertzf7958692015-06-09 14:09:14 +0200203 public:
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100204 DeoptimizationContextRecord(const JValue& ret_val,
205 bool is_reference,
206 bool from_code,
Mathieu Chartierf5769e12017-01-10 15:54:41 -0800207 ObjPtr<mirror::Throwable> pending_exception,
Mingyao Yang2ee17902017-08-30 11:37:08 -0700208 DeoptimizationMethodType method_type,
Sebastien Hertz07474662015-08-25 15:12:33 +0000209 DeoptimizationContextRecord* link)
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100210 : ret_val_(ret_val),
211 is_reference_(is_reference),
212 from_code_(from_code),
Mathieu Chartierf5769e12017-01-10 15:54:41 -0800213 pending_exception_(pending_exception.Ptr()),
Mingyao Yang2ee17902017-08-30 11:37:08 -0700214 deopt_method_type_(method_type),
Sebastien Hertz07474662015-08-25 15:12:33 +0000215 link_(link) {}
Sebastien Hertzf7958692015-06-09 14:09:14 +0200216
217 JValue GetReturnValue() const { return ret_val_; }
218 bool IsReference() const { return is_reference_; }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100219 bool GetFromCode() const { return from_code_; }
Mathieu Chartierf5769e12017-01-10 15:54:41 -0800220 ObjPtr<mirror::Throwable> GetPendingException() const { return pending_exception_; }
Sebastien Hertz07474662015-08-25 15:12:33 +0000221 DeoptimizationContextRecord* GetLink() const { return link_; }
222 mirror::Object** GetReturnValueAsGCRoot() {
Sebastien Hertzf7958692015-06-09 14:09:14 +0200223 DCHECK(is_reference_);
224 return ret_val_.GetGCRoot();
225 }
Sebastien Hertz07474662015-08-25 15:12:33 +0000226 mirror::Object** GetPendingExceptionAsGCRoot() {
227 return reinterpret_cast<mirror::Object**>(&pending_exception_);
228 }
Mingyao Yang2ee17902017-08-30 11:37:08 -0700229 DeoptimizationMethodType GetDeoptimizationMethodType() const {
230 return deopt_method_type_;
231 }
Sebastien Hertzf7958692015-06-09 14:09:14 +0200232
233 private:
Sebastien Hertz07474662015-08-25 15:12:33 +0000234 // The value returned by the method at the top of the stack before deoptimization.
Sebastien Hertzf7958692015-06-09 14:09:14 +0200235 JValue ret_val_;
Sebastien Hertz54b62482015-08-20 12:07:57 +0200236
Sebastien Hertz07474662015-08-25 15:12:33 +0000237 // Indicates whether the returned value is a reference. If so, the GC will visit it.
238 const bool is_reference_;
239
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100240 // Whether the context was created from an explicit deoptimization in the code.
241 const bool from_code_;
242
Sebastien Hertz07474662015-08-25 15:12:33 +0000243 // The exception that was pending before deoptimization (or null if there was no pending
244 // exception).
245 mirror::Throwable* pending_exception_;
246
Mingyao Yang2ee17902017-08-30 11:37:08 -0700247 // Whether the context was created for an (idempotent) runtime method.
248 const DeoptimizationMethodType deopt_method_type_;
249
Sebastien Hertz07474662015-08-25 15:12:33 +0000250 // A link to the previous DeoptimizationContextRecord.
251 DeoptimizationContextRecord* const link_;
252
253 DISALLOW_COPY_AND_ASSIGN(DeoptimizationContextRecord);
Sebastien Hertzf7958692015-06-09 14:09:14 +0200254};
255
256class StackedShadowFrameRecord {
257 public:
258 StackedShadowFrameRecord(ShadowFrame* shadow_frame,
259 StackedShadowFrameType type,
260 StackedShadowFrameRecord* link)
261 : shadow_frame_(shadow_frame),
262 type_(type),
263 link_(link) {}
264
265 ShadowFrame* GetShadowFrame() const { return shadow_frame_; }
266 StackedShadowFrameType GetType() const { return type_; }
267 StackedShadowFrameRecord* GetLink() const { return link_; }
268
269 private:
270 ShadowFrame* const shadow_frame_;
271 const StackedShadowFrameType type_;
272 StackedShadowFrameRecord* const link_;
273
274 DISALLOW_COPY_AND_ASSIGN(StackedShadowFrameRecord);
275};
276
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100277void Thread::PushDeoptimizationContext(const JValue& return_value,
278 bool is_reference,
Mingyao Yang2ee17902017-08-30 11:37:08 -0700279 ObjPtr<mirror::Throwable> exception,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100280 bool from_code,
Mingyao Yang2ee17902017-08-30 11:37:08 -0700281 DeoptimizationMethodType method_type) {
Sebastien Hertz07474662015-08-25 15:12:33 +0000282 DeoptimizationContextRecord* record = new DeoptimizationContextRecord(
283 return_value,
284 is_reference,
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100285 from_code,
Sebastien Hertz07474662015-08-25 15:12:33 +0000286 exception,
Mingyao Yang2ee17902017-08-30 11:37:08 -0700287 method_type,
Sebastien Hertz07474662015-08-25 15:12:33 +0000288 tlsPtr_.deoptimization_context_stack);
289 tlsPtr_.deoptimization_context_stack = record;
buzbee3ea4ec52011-08-22 17:37:19 -0700290}
291
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100292void Thread::PopDeoptimizationContext(JValue* result,
Mathieu Chartierf5769e12017-01-10 15:54:41 -0800293 ObjPtr<mirror::Throwable>* exception,
Mingyao Yang2ee17902017-08-30 11:37:08 -0700294 bool* from_code,
295 DeoptimizationMethodType* method_type) {
Sebastien Hertz07474662015-08-25 15:12:33 +0000296 AssertHasDeoptimizationContext();
297 DeoptimizationContextRecord* record = tlsPtr_.deoptimization_context_stack;
298 tlsPtr_.deoptimization_context_stack = record->GetLink();
299 result->SetJ(record->GetReturnValue().GetJ());
300 *exception = record->GetPendingException();
Nicolas Geoffray73be1e82015-09-17 15:22:56 +0100301 *from_code = record->GetFromCode();
Mingyao Yang2ee17902017-08-30 11:37:08 -0700302 *method_type = record->GetDeoptimizationMethodType();
Mingyao Yang1f2d3ba2015-05-18 12:12:50 -0700303 delete record;
Sebastien Hertz07474662015-08-25 15:12:33 +0000304}
305
306void Thread::AssertHasDeoptimizationContext() {
307 CHECK(tlsPtr_.deoptimization_context_stack != nullptr)
308 << "No deoptimization context for thread " << *this;
Ian Rogers306057f2012-11-26 12:45:53 -0800309}
310
Charles Mungeraa31f492018-11-01 18:57:38 +0000311enum {
312 kPermitAvailable = 0, // Incrementing consumes the permit
313 kNoPermit = 1, // Incrementing marks as waiter waiting
314 kNoPermitWaiterWaiting = 2
315};
316
317void Thread::Park(bool is_absolute, int64_t time) {
318 DCHECK(this == Thread::Current());
319#if ART_USE_FUTEXES
320 // Consume the permit, or mark as waiting. This cannot cause park_state to go
321 // outside of its valid range (0, 1, 2), because in all cases where 2 is
322 // assigned it is set back to 1 before returning, and this method cannot run
323 // concurrently with itself since it operates on the current thread.
324 int old_state = tls32_.park_state_.fetch_add(1, std::memory_order_relaxed);
325 if (old_state == kNoPermit) {
326 // no permit was available. block thread until later.
Charles Munger5cc0e752018-11-09 12:30:46 -0800327 Runtime::Current()->GetRuntimeCallbacks()->ThreadParkStart(is_absolute, time);
Charles Munger5cc0e752018-11-09 12:30:46 -0800328 bool timed_out = false;
Charles Mungeraa31f492018-11-01 18:57:38 +0000329 if (!is_absolute && time == 0) {
330 // Thread.getState() is documented to return waiting for untimed parks.
331 ScopedThreadSuspension sts(this, ThreadState::kWaiting);
332 DCHECK_EQ(NumberOfHeldMutexes(), 0u);
Charles Mungered19c672019-02-21 15:32:32 -0800333 int result = futex(tls32_.park_state_.Address(),
Charles Mungeraa31f492018-11-01 18:57:38 +0000334 FUTEX_WAIT_PRIVATE,
335 /* sleep if val = */ kNoPermitWaiterWaiting,
336 /* timeout */ nullptr,
337 nullptr,
338 0);
Charles Mungered19c672019-02-21 15:32:32 -0800339 // This errno check must happen before the scope is closed, to ensure that
340 // no destructors (such as ScopedThreadSuspension) overwrite errno.
341 if (result == -1) {
342 switch (errno) {
343 case EAGAIN:
344 FALLTHROUGH_INTENDED;
345 case EINTR: break; // park() is allowed to spuriously return
346 default: PLOG(FATAL) << "Failed to park";
347 }
348 }
Charles Mungeraa31f492018-11-01 18:57:38 +0000349 } else if (time > 0) {
350 // Only actually suspend and futex_wait if we're going to wait for some
351 // positive amount of time - the kernel will reject negative times with
352 // EINVAL, and a zero time will just noop.
353
354 // Thread.getState() is documented to return timed wait for timed parks.
355 ScopedThreadSuspension sts(this, ThreadState::kTimedWaiting);
356 DCHECK_EQ(NumberOfHeldMutexes(), 0u);
357 timespec timespec;
Charles Mungered19c672019-02-21 15:32:32 -0800358 int result = 0;
Charles Mungeraa31f492018-11-01 18:57:38 +0000359 if (is_absolute) {
360 // Time is millis when scheduled for an absolute time
361 timespec.tv_nsec = (time % 1000) * 1000000;
362 timespec.tv_sec = time / 1000;
363 // This odd looking pattern is recommended by futex documentation to
364 // wait until an absolute deadline, with otherwise identical behavior to
365 // FUTEX_WAIT_PRIVATE. This also allows parkUntil() to return at the
366 // correct time when the system clock changes.
367 result = futex(tls32_.park_state_.Address(),
368 FUTEX_WAIT_BITSET_PRIVATE | FUTEX_CLOCK_REALTIME,
369 /* sleep if val = */ kNoPermitWaiterWaiting,
370 &timespec,
371 nullptr,
372 FUTEX_BITSET_MATCH_ANY);
373 } else {
374 // Time is nanos when scheduled for a relative time
375 timespec.tv_sec = time / 1000000000;
376 timespec.tv_nsec = time % 1000000000;
377 result = futex(tls32_.park_state_.Address(),
378 FUTEX_WAIT_PRIVATE,
379 /* sleep if val = */ kNoPermitWaiterWaiting,
380 &timespec,
381 nullptr,
382 0);
383 }
Charles Mungered19c672019-02-21 15:32:32 -0800384 // This errno check must happen before the scope is closed, to ensure that
385 // no destructors (such as ScopedThreadSuspension) overwrite errno.
386 if (result == -1) {
387 switch (errno) {
388 case ETIMEDOUT:
389 timed_out = true;
390 FALLTHROUGH_INTENDED;
391 case EAGAIN:
392 case EINTR: break; // park() is allowed to spuriously return
393 default: PLOG(FATAL) << "Failed to park";
394 }
Charles Mungeraa31f492018-11-01 18:57:38 +0000395 }
396 }
397 // Mark as no longer waiting, and consume permit if there is one.
398 tls32_.park_state_.store(kNoPermit, std::memory_order_relaxed);
399 // TODO: Call to signal jvmti here
Charles Munger5cc0e752018-11-09 12:30:46 -0800400 Runtime::Current()->GetRuntimeCallbacks()->ThreadParkFinished(timed_out);
Charles Mungeraa31f492018-11-01 18:57:38 +0000401 } else {
402 // the fetch_add has consumed the permit. immediately return.
403 DCHECK_EQ(old_state, kPermitAvailable);
404 }
405#else
406 #pragma clang diagnostic push
407 #pragma clang diagnostic warning "-W#warnings"
408 #warning "LockSupport.park/unpark implemented as noops without FUTEX support."
409 #pragma clang diagnostic pop
410 UNUSED(is_absolute, time);
411 UNIMPLEMENTED(WARNING);
412 sched_yield();
413#endif
414}
415
416void Thread::Unpark() {
417#if ART_USE_FUTEXES
418 // Set permit available; will be consumed either by fetch_add (when the thread
419 // tries to park) or store (when the parked thread is woken up)
420 if (tls32_.park_state_.exchange(kPermitAvailable, std::memory_order_relaxed)
421 == kNoPermitWaiterWaiting) {
422 int result = futex(tls32_.park_state_.Address(),
423 FUTEX_WAKE_PRIVATE,
424 /* number of waiters = */ 1,
425 nullptr,
426 nullptr,
427 0);
428 if (result == -1) {
429 PLOG(FATAL) << "Failed to unpark";
430 }
431 }
432#else
433 UNIMPLEMENTED(WARNING);
434#endif
435}
436
Mingyao Yang1f2d3ba2015-05-18 12:12:50 -0700437void Thread::PushStackedShadowFrame(ShadowFrame* sf, StackedShadowFrameType type) {
438 StackedShadowFrameRecord* record = new StackedShadowFrameRecord(
439 sf, type, tlsPtr_.stacked_shadow_frame_record);
440 tlsPtr_.stacked_shadow_frame_record = record;
Ian Rogers306057f2012-11-26 12:45:53 -0800441}
442
Andreas Gampe639bdd12015-06-03 11:22:45 -0700443ShadowFrame* Thread::PopStackedShadowFrame(StackedShadowFrameType type, bool must_be_present) {
Mingyao Yang1f2d3ba2015-05-18 12:12:50 -0700444 StackedShadowFrameRecord* record = tlsPtr_.stacked_shadow_frame_record;
Andreas Gampe639bdd12015-06-03 11:22:45 -0700445 if (must_be_present) {
446 DCHECK(record != nullptr);
Andreas Gampe639bdd12015-06-03 11:22:45 -0700447 } else {
448 if (record == nullptr || record->GetType() != type) {
449 return nullptr;
450 }
451 }
Mingyao Yang1f2d3ba2015-05-18 12:12:50 -0700452 tlsPtr_.stacked_shadow_frame_record = record->GetLink();
453 ShadowFrame* shadow_frame = record->GetShadowFrame();
454 delete record;
455 return shadow_frame;
Andreas Gampe2a0d4ec2014-06-02 22:05:22 -0700456}
457
Mingyao Yang99170c62015-07-06 11:10:37 -0700458class FrameIdToShadowFrame {
459 public:
460 static FrameIdToShadowFrame* Create(size_t frame_id,
461 ShadowFrame* shadow_frame,
462 FrameIdToShadowFrame* next,
463 size_t num_vregs) {
464 // Append a bool array at the end to keep track of what vregs are updated by the debugger.
465 uint8_t* memory = new uint8_t[sizeof(FrameIdToShadowFrame) + sizeof(bool) * num_vregs];
466 return new (memory) FrameIdToShadowFrame(frame_id, shadow_frame, next);
467 }
468
469 static void Delete(FrameIdToShadowFrame* f) {
470 uint8_t* memory = reinterpret_cast<uint8_t*>(f);
471 delete[] memory;
472 }
473
474 size_t GetFrameId() const { return frame_id_; }
475 ShadowFrame* GetShadowFrame() const { return shadow_frame_; }
476 FrameIdToShadowFrame* GetNext() const { return next_; }
477 void SetNext(FrameIdToShadowFrame* next) { next_ = next; }
478 bool* GetUpdatedVRegFlags() {
479 return updated_vreg_flags_;
480 }
481
482 private:
483 FrameIdToShadowFrame(size_t frame_id,
484 ShadowFrame* shadow_frame,
485 FrameIdToShadowFrame* next)
486 : frame_id_(frame_id),
487 shadow_frame_(shadow_frame),
488 next_(next) {}
489
490 const size_t frame_id_;
491 ShadowFrame* const shadow_frame_;
492 FrameIdToShadowFrame* next_;
493 bool updated_vreg_flags_[0];
494
495 DISALLOW_COPY_AND_ASSIGN(FrameIdToShadowFrame);
496};
497
498static FrameIdToShadowFrame* FindFrameIdToShadowFrame(FrameIdToShadowFrame* head,
499 size_t frame_id) {
500 FrameIdToShadowFrame* found = nullptr;
501 for (FrameIdToShadowFrame* record = head; record != nullptr; record = record->GetNext()) {
502 if (record->GetFrameId() == frame_id) {
503 if (kIsDebugBuild) {
504 // Sanity check we have at most one record for this frame.
505 CHECK(found == nullptr) << "Multiple records for the frame " << frame_id;
506 found = record;
507 } else {
508 return record;
509 }
510 }
511 }
512 return found;
513}
514
515ShadowFrame* Thread::FindDebuggerShadowFrame(size_t frame_id) {
516 FrameIdToShadowFrame* record = FindFrameIdToShadowFrame(
517 tlsPtr_.frame_id_to_shadow_frame, frame_id);
518 if (record != nullptr) {
519 return record->GetShadowFrame();
520 }
521 return nullptr;
522}
523
524// Must only be called when FindDebuggerShadowFrame(frame_id) returns non-nullptr.
525bool* Thread::GetUpdatedVRegFlags(size_t frame_id) {
526 FrameIdToShadowFrame* record = FindFrameIdToShadowFrame(
527 tlsPtr_.frame_id_to_shadow_frame, frame_id);
528 CHECK(record != nullptr);
529 return record->GetUpdatedVRegFlags();
530}
531
532ShadowFrame* Thread::FindOrCreateDebuggerShadowFrame(size_t frame_id,
533 uint32_t num_vregs,
534 ArtMethod* method,
535 uint32_t dex_pc) {
536 ShadowFrame* shadow_frame = FindDebuggerShadowFrame(frame_id);
537 if (shadow_frame != nullptr) {
538 return shadow_frame;
539 }
David Sehr709b0702016-10-13 09:12:37 -0700540 VLOG(deopt) << "Create pre-deopted ShadowFrame for " << ArtMethod::PrettyMethod(method);
Mingyao Yang99170c62015-07-06 11:10:37 -0700541 shadow_frame = ShadowFrame::CreateDeoptimizedFrame(num_vregs, nullptr, method, dex_pc);
542 FrameIdToShadowFrame* record = FrameIdToShadowFrame::Create(frame_id,
543 shadow_frame,
544 tlsPtr_.frame_id_to_shadow_frame,
545 num_vregs);
546 for (uint32_t i = 0; i < num_vregs; i++) {
547 // Do this to clear all references for root visitors.
548 shadow_frame->SetVRegReference(i, nullptr);
549 // This flag will be changed to true if the debugger modifies the value.
550 record->GetUpdatedVRegFlags()[i] = false;
551 }
552 tlsPtr_.frame_id_to_shadow_frame = record;
553 return shadow_frame;
554}
555
Alex Light184f0752018-07-13 11:18:22 -0700556TLSData* Thread::GetCustomTLS(const char* key) {
557 MutexLock mu(Thread::Current(), *Locks::custom_tls_lock_);
558 auto it = custom_tls_.find(key);
559 return (it != custom_tls_.end()) ? it->second.get() : nullptr;
560}
561
562void Thread::SetCustomTLS(const char* key, TLSData* data) {
563 // We will swap the old data (which might be nullptr) with this and then delete it outside of the
564 // custom_tls_lock_.
565 std::unique_ptr<TLSData> old_data(data);
566 {
567 MutexLock mu(Thread::Current(), *Locks::custom_tls_lock_);
568 custom_tls_.GetOrCreate(key, []() { return std::unique_ptr<TLSData>(); }).swap(old_data);
569 }
570}
571
Mingyao Yang99170c62015-07-06 11:10:37 -0700572void Thread::RemoveDebuggerShadowFrameMapping(size_t frame_id) {
573 FrameIdToShadowFrame* head = tlsPtr_.frame_id_to_shadow_frame;
574 if (head->GetFrameId() == frame_id) {
575 tlsPtr_.frame_id_to_shadow_frame = head->GetNext();
576 FrameIdToShadowFrame::Delete(head);
577 return;
578 }
579 FrameIdToShadowFrame* prev = head;
580 for (FrameIdToShadowFrame* record = head->GetNext();
581 record != nullptr;
582 prev = record, record = record->GetNext()) {
583 if (record->GetFrameId() == frame_id) {
584 prev->SetNext(record->GetNext());
585 FrameIdToShadowFrame::Delete(record);
586 return;
587 }
588 }
589 LOG(FATAL) << "No shadow frame for frame " << frame_id;
590 UNREACHABLE();
591}
592
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700593void Thread::InitTid() {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700594 tls32_.tid = ::art::GetTid();
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700595}
596
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700597void Thread::InitAfterFork() {
Elliott Hughes8029cbe2012-05-22 09:13:08 -0700598 // One thread (us) survived the fork, but we have a new tid so we need to
599 // update the value stashed in this Thread*.
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700600 InitTid();
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700601}
602
Alex Light4847a072019-12-12 16:13:47 -0800603void Thread::DeleteJPeer(JNIEnv* env) {
604 // Make sure nothing can observe both opeer and jpeer set at the same time.
605 jobject old_jpeer = tlsPtr_.jpeer;
606 CHECK(old_jpeer != nullptr);
607 tlsPtr_.jpeer = nullptr;
608 env->DeleteGlobalRef(old_jpeer);
609}
610
Brian Carlstrom78128a62011-09-15 17:21:19 -0700611void* Thread::CreateCallback(void* arg) {
Elliott Hughes93e74e82011-09-13 11:07:03 -0700612 Thread* self = reinterpret_cast<Thread*>(arg);
Ian Rogers120f1c72012-09-28 17:17:10 -0700613 Runtime* runtime = Runtime::Current();
Dave Allison0aded082013-11-07 13:15:11 -0800614 if (runtime == nullptr) {
Ian Rogers120f1c72012-09-28 17:17:10 -0700615 LOG(ERROR) << "Thread attaching to non-existent runtime: " << *self;
Dave Allison0aded082013-11-07 13:15:11 -0800616 return nullptr;
Ian Rogers120f1c72012-09-28 17:17:10 -0700617 }
618 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700619 // TODO: pass self to MutexLock - requires self to equal Thread::Current(), which is only true
620 // after self->Init().
Dave Allison0aded082013-11-07 13:15:11 -0800621 MutexLock mu(nullptr, *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -0700622 // Check that if we got here we cannot be shutting down (as shutdown should never have started
623 // while threads are being born).
Mathieu Chartier590fee92013-09-13 13:46:47 -0700624 CHECK(!runtime->IsShuttingDownLocked());
Andreas Gampe449357d2015-06-01 22:29:51 -0700625 // Note: given that the JNIEnv is created in the parent thread, the only failure point here is
626 // a mess in InitStackHwm. We do not have a reasonable way to recover from that, so abort
627 // the runtime in such a case. In case this ever changes, we need to make sure here to
628 // delete the tmp_jni_env, as we own it at this point.
629 CHECK(self->Init(runtime->GetThreadList(), runtime->GetJavaVM(), self->tlsPtr_.tmp_jni_env));
630 self->tlsPtr_.tmp_jni_env = nullptr;
Ian Rogers120f1c72012-09-28 17:17:10 -0700631 Runtime::Current()->EndThreadBirth();
632 }
Elliott Hughes47179f72011-10-27 16:44:39 -0700633 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700634 ScopedObjectAccess soa(self);
Jeff Hao848f70a2014-01-15 13:49:50 -0800635 self->InitStringEntryPoints();
Ian Rogerscfaa4552012-11-26 21:00:08 -0800636
637 // Copy peer into self, deleting global reference when done.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700638 CHECK(self->tlsPtr_.jpeer != nullptr);
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700639 self->tlsPtr_.opeer = soa.Decode<mirror::Object>(self->tlsPtr_.jpeer).Ptr();
Alex Light4847a072019-12-12 16:13:47 -0800640 // Make sure nothing can observe both opeer and jpeer set at the same time.
641 self->DeleteJPeer(self->GetJniEnv());
Andreas Gampe08883de2016-11-08 13:20:52 -0800642 self->SetThreadName(self->GetThreadName()->ToModifiedUtf8().c_str());
Narayan Kamatha0b34512014-10-07 12:51:26 +0100643
Andreas Gampe08883de2016-11-08 13:20:52 -0800644 ArtField* priorityField = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_priority);
Narayan Kamatha0b34512014-10-07 12:51:26 +0100645 self->SetNativePriority(priorityField->GetInt(self->tlsPtr_.opeer));
Andreas Gampe04bbb5b2017-01-19 17:49:03 +0000646
Andreas Gampeac30fa22017-01-18 21:02:36 -0800647 runtime->GetRuntimeCallbacks()->ThreadStart(self);
Ian Rogers365c1022012-06-22 15:05:28 -0700648
Charles Mungeraa31f492018-11-01 18:57:38 +0000649 // Unpark ourselves if the java peer was unparked before it started (see
650 // b/28845097#comment49 for more information)
651
652 ArtField* unparkedField = jni::DecodeArtField(
653 WellKnownClasses::java_lang_Thread_unparkedBeforeStart);
654 bool should_unpark = false;
655 {
656 // Hold the lock here, so that if another thread calls unpark before the thread starts
657 // we don't observe the unparkedBeforeStart field before the unparker writes to it,
658 // which could cause a lost unpark.
659 art::MutexLock mu(soa.Self(), *art::Locks::thread_list_lock_);
660 should_unpark = unparkedField->GetBoolean(self->tlsPtr_.opeer) == JNI_TRUE;
661 }
662 if (should_unpark) {
663 self->Unpark();
664 }
Ian Rogers365c1022012-06-22 15:05:28 -0700665 // Invoke the 'run' method of our java.lang.Thread.
Mathieu Chartierf5769e12017-01-10 15:54:41 -0800666 ObjPtr<mirror::Object> receiver = self->tlsPtr_.opeer;
Ian Rogers365c1022012-06-22 15:05:28 -0700667 jmethodID mid = WellKnownClasses::java_lang_Thread_run;
Jeff Hao39b6c242015-05-19 20:30:23 -0700668 ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(receiver));
669 InvokeVirtualOrInterfaceWithJValues(soa, ref.get(), mid, nullptr);
Elliott Hughes47179f72011-10-27 16:44:39 -0700670 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700671 // Detach and delete self.
672 Runtime::Current()->GetThreadList()->Unregister(self);
Elliott Hughes93e74e82011-09-13 11:07:03 -0700673
Dave Allison0aded082013-11-07 13:15:11 -0800674 return nullptr;
Carl Shapirob5573532011-07-12 18:22:59 -0700675}
676
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -0700677Thread* Thread::FromManagedThread(const ScopedObjectAccessAlreadyRunnable& soa,
Mathieu Chartierf5769e12017-01-10 15:54:41 -0800678 ObjPtr<mirror::Object> thread_peer) {
Andreas Gampe08883de2016-11-08 13:20:52 -0800679 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_nativePeer);
Vladimir Marko78baed52018-10-11 10:44:58 +0100680 Thread* result = reinterpret_cast64<Thread*>(f->GetLong(thread_peer));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700681 // Sanity check that if we have a result it is either suspended or we hold the thread_list_lock_
682 // to stop it from going away.
Ian Rogers81d425b2012-09-27 16:03:43 -0700683 if (kIsDebugBuild) {
684 MutexLock mu(soa.Self(), *Locks::thread_suspend_count_lock_);
Dave Allison0aded082013-11-07 13:15:11 -0800685 if (result != nullptr && !result->IsSuspended()) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700686 Locks::thread_list_lock_->AssertHeld(soa.Self());
687 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700688 }
689 return result;
Elliott Hughes761928d2011-11-16 18:33:03 -0800690}
691
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -0700692Thread* Thread::FromManagedThread(const ScopedObjectAccessAlreadyRunnable& soa,
693 jobject java_thread) {
Vladimir Markobcf17522018-06-01 13:14:32 +0100694 return FromManagedThread(soa, soa.Decode<mirror::Object>(java_thread));
Elliott Hughes01158d72011-09-19 19:47:10 -0700695}
696
Elliott Hughesab7b9dc2012-03-27 13:16:29 -0700697static size_t FixStackSize(size_t stack_size) {
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700698 // A stack size of zero means "use the default".
Elliott Hughesd369bb72011-09-12 14:41:14 -0700699 if (stack_size == 0) {
700 stack_size = Runtime::Current()->GetDefaultStackSize();
701 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700702
Brian Carlstrom6414a972012-04-14 14:20:04 -0700703 // Dalvik used the bionic pthread default stack size for native threads,
704 // so include that here to support apps that expect large native stacks.
705 stack_size += 1 * MB;
706
Andreas Gampe7a55ce02018-06-19 10:07:18 -0700707 // Under sanitization, frames of the interpreter may become bigger, both for C code as
708 // well as the ShadowFrame. Ensure a larger minimum size. Otherwise initialization
709 // of all core classes cannot be done in all test circumstances.
710 if (kMemoryToolIsAvailable) {
711 stack_size = std::max(2 * MB, stack_size);
712 }
713
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700714 // It's not possible to request a stack smaller than the system-defined PTHREAD_STACK_MIN.
715 if (stack_size < PTHREAD_STACK_MIN) {
716 stack_size = PTHREAD_STACK_MIN;
717 }
718
Dave Allisonf9439142014-03-27 15:10:22 -0700719 if (Runtime::Current()->ExplicitStackOverflowChecks()) {
720 // It's likely that callers are trying to ensure they have at least a certain amount of
721 // stack space, so we should add our reserved space on top of what they requested, rather
722 // than implicitly take it away from them.
Andreas Gampe7ea6f792014-07-14 16:21:44 -0700723 stack_size += GetStackOverflowReservedBytes(kRuntimeISA);
Dave Allisonf9439142014-03-27 15:10:22 -0700724 } else {
725 // If we are going to use implicit stack checks, allocate space for the protected
726 // region at the bottom of the stack.
Dave Allisonb090a182014-08-14 17:02:48 +0000727 stack_size += Thread::kStackOverflowImplicitCheckSize +
728 GetStackOverflowReservedBytes(kRuntimeISA);
Dave Allisonf9439142014-03-27 15:10:22 -0700729 }
Elliott Hughes7502e2a2011-10-02 13:24:37 -0700730
731 // Some systems require the stack size to be a multiple of the system page size, so round up.
732 stack_size = RoundUp(stack_size, kPageSize);
733
734 return stack_size;
735}
736
Evgenii Stepanov84a4ab82016-05-13 14:01:41 -0700737// Return the nearest page-aligned address below the current stack top.
738NO_INLINE
739static uint8_t* FindStackTop() {
740 return reinterpret_cast<uint8_t*>(
741 AlignDown(__builtin_frame_address(0), kPageSize));
742}
743
Dave Allisonf9439142014-03-27 15:10:22 -0700744// Install a protected region in the stack. This is used to trigger a SIGSEGV if a stack
Dave Allison648d7112014-07-25 16:15:27 -0700745// overflow is detected. It is located right below the stack_begin_.
Evgenii Stepanov4abf4512015-07-13 10:41:57 -0700746ATTRIBUTE_NO_SANITIZE_ADDRESS
Dave Allison648d7112014-07-25 16:15:27 -0700747void Thread::InstallImplicitProtection() {
Ian Rogers13735952014-10-08 12:43:28 -0700748 uint8_t* pregion = tlsPtr_.stack_begin - kStackOverflowProtectedSize;
Evgenii Stepanov84a4ab82016-05-13 14:01:41 -0700749 // Page containing current top of stack.
750 uint8_t* stack_top = FindStackTop();
Dave Allisonf9439142014-03-27 15:10:22 -0700751
Andreas Gampe2c2d2a02016-03-17 21:27:19 -0700752 // Try to directly protect the stack.
753 VLOG(threads) << "installing stack protected region at " << std::hex <<
754 static_cast<void*>(pregion) << " to " <<
755 static_cast<void*>(pregion + kStackOverflowProtectedSize - 1);
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700756 if (ProtectStack(/* fatal_on_error= */ false)) {
Andreas Gampe2c2d2a02016-03-17 21:27:19 -0700757 // Tell the kernel that we won't be needing these pages any more.
758 // NB. madvise will probably write zeroes into the memory (on linux it does).
759 uint32_t unwanted_size = stack_top - pregion - kPageSize;
760 madvise(pregion, unwanted_size, MADV_DONTNEED);
761 return;
762 }
763
764 // There is a little complexity here that deserves a special mention. On some
765 // architectures, the stack is created using a VM_GROWSDOWN flag
766 // to prevent memory being allocated when it's not needed. This flag makes the
767 // kernel only allocate memory for the stack by growing down in memory. Because we
768 // want to put an mprotected region far away from that at the stack top, we need
769 // to make sure the pages for the stack are mapped in before we call mprotect.
770 //
771 // The failed mprotect in UnprotectStack is an indication of a thread with VM_GROWSDOWN
772 // with a non-mapped stack (usually only the main thread).
773 //
774 // We map in the stack by reading every page from the stack bottom (highest address)
775 // to the stack top. (We then madvise this away.) This must be done by reading from the
Andreas Gampe6c63f862017-06-28 17:20:15 -0700776 // current stack pointer downwards.
Andreas Gampe2c2d2a02016-03-17 21:27:19 -0700777 //
Andreas Gampe6c63f862017-06-28 17:20:15 -0700778 // Accesses too far below the current machine register corresponding to the stack pointer (e.g.,
779 // ESP on x86[-32], SP on ARM) might cause a SIGSEGV (at least on x86 with newer kernels). We
780 // thus have to move the stack pointer. We do this portably by using a recursive function with a
781 // large stack frame size.
Andreas Gampe2c2d2a02016-03-17 21:27:19 -0700782
Andreas Gampe6c63f862017-06-28 17:20:15 -0700783 // (Defensively) first remove the protection on the protected region as we'll want to read
Andreas Gampe2c2d2a02016-03-17 21:27:19 -0700784 // and write it. Ignore errors.
Dave Allison648d7112014-07-25 16:15:27 -0700785 UnprotectStack();
Dave Allison69dfe512014-07-11 17:11:58 +0000786
Andreas Gampe2c2d2a02016-03-17 21:27:19 -0700787 VLOG(threads) << "Need to map in stack for thread at " << std::hex <<
788 static_cast<void*>(pregion);
Dave Allison69dfe512014-07-11 17:11:58 +0000789
Andreas Gampe6c63f862017-06-28 17:20:15 -0700790 struct RecurseDownStack {
791 // This function has an intentionally large stack size.
792#pragma GCC diagnostic push
793#pragma GCC diagnostic ignored "-Wframe-larger-than="
794 NO_INLINE
795 static void Touch(uintptr_t target) {
796 volatile size_t zero = 0;
797 // Use a large local volatile array to ensure a large frame size. Do not use anything close
798 // to a full page for ASAN. It would be nice to ensure the frame size is at most a page, but
799 // there is no pragma support for this.
Andreas Gampe6f1c7512017-07-05 19:18:31 -0700800 // Note: for ASAN we need to shrink the array a bit, as there's other overhead.
801 constexpr size_t kAsanMultiplier =
802#ifdef ADDRESS_SANITIZER
803 2u;
804#else
805 1u;
806#endif
Stephen Hines469016b2020-01-22 17:50:41 -0800807 // Keep space uninitialized as it can overflow the stack otherwise (should Clang actually
808 // auto-initialize this local variable).
809 volatile char space[kPageSize - (kAsanMultiplier * 256)] __attribute__((uninitialized));
Andreas Gampee383d232018-06-19 12:29:51 -0700810 char sink ATTRIBUTE_UNUSED = space[zero]; // NOLINT
Evgenii Stepanov9b7656d2018-08-21 15:18:49 -0700811 // Remove tag from the pointer. Nop in non-hwasan builds.
812 uintptr_t addr = reinterpret_cast<uintptr_t>(__hwasan_tag_pointer(space, 0));
813 if (addr >= target + kPageSize) {
Andreas Gampe6c63f862017-06-28 17:20:15 -0700814 Touch(target);
815 }
816 zero *= 2; // Try to avoid tail recursion.
817 }
818#pragma GCC diagnostic pop
819 };
820 RecurseDownStack::Touch(reinterpret_cast<uintptr_t>(pregion));
Dave Allison69dfe512014-07-11 17:11:58 +0000821
Andreas Gampe2c2d2a02016-03-17 21:27:19 -0700822 VLOG(threads) << "(again) installing stack protected region at " << std::hex <<
Dave Allisonf9439142014-03-27 15:10:22 -0700823 static_cast<void*>(pregion) << " to " <<
824 static_cast<void*>(pregion + kStackOverflowProtectedSize - 1);
825
Dave Allison648d7112014-07-25 16:15:27 -0700826 // Protect the bottom of the stack to prevent read/write to it.
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700827 ProtectStack(/* fatal_on_error= */ true);
Dave Allison5cd33752014-04-15 15:57:58 -0700828
829 // Tell the kernel that we won't be needing these pages any more.
Dave Allison69dfe512014-07-11 17:11:58 +0000830 // NB. madvise will probably write zeroes into the memory (on linux it does).
Dave Allison648d7112014-07-25 16:15:27 -0700831 uint32_t unwanted_size = stack_top - pregion - kPageSize;
832 madvise(pregion, unwanted_size, MADV_DONTNEED);
Dave Allisonf9439142014-03-27 15:10:22 -0700833}
834
Ian Rogers120f1c72012-09-28 17:17:10 -0700835void Thread::CreateNativeThread(JNIEnv* env, jobject java_peer, size_t stack_size, bool is_daemon) {
Dave Allison0aded082013-11-07 13:15:11 -0800836 CHECK(java_peer != nullptr);
Ian Rogers55256cb2017-12-21 17:07:11 -0800837 Thread* self = static_cast<JNIEnvExt*>(env)->GetSelf();
Andreas Gampe56623832015-07-09 21:53:15 -0700838
839 if (VLOG_IS_ON(threads)) {
840 ScopedObjectAccess soa(env);
841
Andreas Gampe08883de2016-11-08 13:20:52 -0800842 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_name);
Mathieu Chartier3398c782016-09-30 10:27:43 -0700843 ObjPtr<mirror::String> java_name =
844 f->GetObject(soa.Decode<mirror::Object>(java_peer))->AsString();
Andreas Gampe56623832015-07-09 21:53:15 -0700845 std::string thread_name;
846 if (java_name != nullptr) {
847 thread_name = java_name->ToModifiedUtf8();
848 } else {
849 thread_name = "(Unnamed)";
850 }
851
852 VLOG(threads) << "Creating native thread for " << thread_name;
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700853 self->Dump(LOG_STREAM(INFO));
Andreas Gampe56623832015-07-09 21:53:15 -0700854 }
855
Ian Rogers120f1c72012-09-28 17:17:10 -0700856 Runtime* runtime = Runtime::Current();
Mathieu Chartierdbe6f462012-09-25 16:54:50 -0700857
Ian Rogers120f1c72012-09-28 17:17:10 -0700858 // Atomically start the birth of the thread ensuring the runtime isn't shutting down.
859 bool thread_start_during_shutdown = false;
Elliott Hughes47179f72011-10-27 16:44:39 -0700860 {
Ian Rogers120f1c72012-09-28 17:17:10 -0700861 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700862 if (runtime->IsShuttingDownLocked()) {
Ian Rogers120f1c72012-09-28 17:17:10 -0700863 thread_start_during_shutdown = true;
864 } else {
865 runtime->StartThreadBirth();
866 }
Elliott Hughes47179f72011-10-27 16:44:39 -0700867 }
Ian Rogers120f1c72012-09-28 17:17:10 -0700868 if (thread_start_during_shutdown) {
869 ScopedLocalRef<jclass> error_class(env, env->FindClass("java/lang/InternalError"));
870 env->ThrowNew(error_class.get(), "Thread starting during runtime shutdown");
871 return;
872 }
873
874 Thread* child_thread = new Thread(is_daemon);
875 // Use global JNI ref to hold peer live while child thread starts.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700876 child_thread->tlsPtr_.jpeer = env->NewGlobalRef(java_peer);
Ian Rogers120f1c72012-09-28 17:17:10 -0700877 stack_size = FixStackSize(stack_size);
878
Roland Levillain2ae376f2018-01-30 11:35:11 +0000879 // Thread.start is synchronized, so we know that nativePeer is 0, and know that we're not racing
880 // to assign it.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800881 env->SetLongField(java_peer, WellKnownClasses::java_lang_Thread_nativePeer,
882 reinterpret_cast<jlong>(child_thread));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700883
Andreas Gampe449357d2015-06-01 22:29:51 -0700884 // Try to allocate a JNIEnvExt for the thread. We do this here as we might be out of memory and
885 // do not have a good way to report this on the child's side.
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100886 std::string error_msg;
Andreas Gampe449357d2015-06-01 22:29:51 -0700887 std::unique_ptr<JNIEnvExt> child_jni_env_ext(
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100888 JNIEnvExt::Create(child_thread, Runtime::Current()->GetJavaVM(), &error_msg));
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700889
Andreas Gampe449357d2015-06-01 22:29:51 -0700890 int pthread_create_result = 0;
891 if (child_jni_env_ext.get() != nullptr) {
892 pthread_t new_pthread;
893 pthread_attr_t attr;
894 child_thread->tlsPtr_.tmp_jni_env = child_jni_env_ext.get();
895 CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), "new thread");
896 CHECK_PTHREAD_CALL(pthread_attr_setdetachstate, (&attr, PTHREAD_CREATE_DETACHED),
897 "PTHREAD_CREATE_DETACHED");
898 CHECK_PTHREAD_CALL(pthread_attr_setstacksize, (&attr, stack_size), stack_size);
899 pthread_create_result = pthread_create(&new_pthread,
900 &attr,
901 Thread::CreateCallback,
902 child_thread);
903 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), "new thread");
904
905 if (pthread_create_result == 0) {
906 // pthread_create started the new thread. The child is now responsible for managing the
907 // JNIEnvExt we created.
908 // Note: we can't check for tmp_jni_env == nullptr, as that would require synchronization
909 // between the threads.
Andreas Gampeafaf7f82018-10-16 11:32:38 -0700910 child_jni_env_ext.release(); // NOLINT pthreads API.
Andreas Gampe449357d2015-06-01 22:29:51 -0700911 return;
Ian Rogers120f1c72012-09-28 17:17:10 -0700912 }
Andreas Gampe449357d2015-06-01 22:29:51 -0700913 }
914
915 // Either JNIEnvExt::Create or pthread_create(3) failed, so clean up.
916 {
917 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
918 runtime->EndThreadBirth();
919 }
Alex Light4847a072019-12-12 16:13:47 -0800920 // Manually delete the global reference since Thread::Init will not have been run. Make sure
921 // nothing can observe both opeer and jpeer set at the same time.
922 child_thread->DeleteJPeer(env);
Andreas Gampe449357d2015-06-01 22:29:51 -0700923 delete child_thread;
924 child_thread = nullptr;
925 // TODO: remove from thread group?
926 env->SetLongField(java_peer, WellKnownClasses::java_lang_Thread_nativePeer, 0);
927 {
928 std::string msg(child_jni_env_ext.get() == nullptr ?
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100929 StringPrintf("Could not allocate JNI Env: %s", error_msg.c_str()) :
Andreas Gampe449357d2015-06-01 22:29:51 -0700930 StringPrintf("pthread_create (%s stack) failed: %s",
931 PrettySize(stack_size).c_str(), strerror(pthread_create_result)));
932 ScopedObjectAccess soa(env);
933 soa.Self()->ThrowOutOfMemoryError(msg.c_str());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700934 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700935}
936
Andreas Gampe449357d2015-06-01 22:29:51 -0700937bool Thread::Init(ThreadList* thread_list, JavaVMExt* java_vm, JNIEnvExt* jni_env_ext) {
Elliott Hughes462c9442012-03-23 18:47:50 -0700938 // This function does all the initialization that must be run by the native thread it applies to.
939 // (When we create a new thread from managed code, we allocate the Thread* in Thread::Create so
940 // we can handshake with the corresponding native thread when it's ready.) Check this native
941 // thread hasn't been through here already...
Dave Allison0aded082013-11-07 13:15:11 -0800942 CHECK(Thread::Current() == nullptr);
Ian Rogersf4d4da12014-11-11 16:10:33 -0800943
944 // Set pthread_self_ ahead of pthread_setspecific, that makes Thread::Current function, this
945 // avoids pthread_self_ ever being invalid when discovered from Thread::Current().
946 tlsPtr_.pthread_self = pthread_self();
947 CHECK(is_started_);
948
Mathieu Chartier3a0cd342018-12-13 13:45:17 -0800949 ScopedTrace trace("Thread::Init");
950
Elliott Hughesd8af1592012-04-16 20:40:15 -0700951 SetUpAlternateSignalStack();
Ian Rogersf4d4da12014-11-11 16:10:33 -0800952 if (!InitStackHwm()) {
953 return false;
954 }
Elliott Hughes93e74e82011-09-13 11:07:03 -0700955 InitCpu();
Ulyana Trafimoviche886d682020-07-16 15:09:38 +0000956 if (Runtime::SimulatorMode()) {
957 InitSimulator();
958 }
Ian Rogers848871b2013-08-05 10:56:33 -0700959 InitTlsEntryPoints();
Dave Allisonb373e092014-02-20 16:06:36 -0800960 RemoveSuspendTrigger();
Ian Rogers5d76c432011-10-31 21:42:49 -0700961 InitCardTable();
Ian Rogers01ae5802012-09-28 16:14:01 -0700962 InitTid();
Mathieu Chartier3a0cd342018-12-13 13:45:17 -0800963 {
964 ScopedTrace trace2("InitInterpreterTls");
965 interpreter::InitInterpreterTls(this);
966 }
Ian Rogersf4d4da12014-11-11 16:10:33 -0800967
Andreas Gampea47a6e82019-07-24 09:46:16 -0700968#ifdef __BIONIC__
Andreas Gampe4382f1e2015-08-05 01:08:53 +0000969 __get_tls()[TLS_SLOT_ART_THREAD_SELF] = this;
970#else
Ian Rogers120f1c72012-09-28 17:17:10 -0700971 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, this), "attach self");
Andreas Gampe82372002019-07-24 15:42:09 -0700972 Thread::self_tls_ = this;
Andreas Gampe4382f1e2015-08-05 01:08:53 +0000973#endif
Ian Rogers120f1c72012-09-28 17:17:10 -0700974 DCHECK_EQ(Thread::Current(), this);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700975
Ian Rogersdd7624d2014-03-14 17:43:00 -0700976 tls32_.thin_lock_thread_id = thread_list->AllocThreadId(this);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700977
Andreas Gampe449357d2015-06-01 22:29:51 -0700978 if (jni_env_ext != nullptr) {
Ian Rogers55256cb2017-12-21 17:07:11 -0800979 DCHECK_EQ(jni_env_ext->GetVm(), java_vm);
980 DCHECK_EQ(jni_env_ext->GetSelf(), this);
Andreas Gampe449357d2015-06-01 22:29:51 -0700981 tlsPtr_.jni_env = jni_env_ext;
982 } else {
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100983 std::string error_msg;
984 tlsPtr_.jni_env = JNIEnvExt::Create(this, java_vm, &error_msg);
Andreas Gampe449357d2015-06-01 22:29:51 -0700985 if (tlsPtr_.jni_env == nullptr) {
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100986 LOG(ERROR) << "Failed to create JNIEnvExt: " << error_msg;
Andreas Gampe449357d2015-06-01 22:29:51 -0700987 return false;
988 }
Andreas Gampe3f5881f2015-04-08 10:26:16 -0700989 }
990
Mathieu Chartier3a0cd342018-12-13 13:45:17 -0800991 ScopedTrace trace3("ThreadList::Register");
Ian Rogers120f1c72012-09-28 17:17:10 -0700992 thread_list->Register(this);
Ian Rogersf4d4da12014-11-11 16:10:33 -0800993 return true;
Elliott Hughes93e74e82011-09-13 11:07:03 -0700994}
995
Andreas Gampe732b0ac2017-01-18 15:23:39 -0800996template <typename PeerAction>
997Thread* Thread::Attach(const char* thread_name, bool as_daemon, PeerAction peer_action) {
Ian Rogers120f1c72012-09-28 17:17:10 -0700998 Runtime* runtime = Runtime::Current();
Mathieu Chartier3a0cd342018-12-13 13:45:17 -0800999 ScopedTrace trace("Thread::Attach");
Dave Allison0aded082013-11-07 13:15:11 -08001000 if (runtime == nullptr) {
Kazuhiro Inaba9ff12512017-12-04 16:26:38 +09001001 LOG(ERROR) << "Thread attaching to non-existent runtime: " <<
1002 ((thread_name != nullptr) ? thread_name : "(Unnamed)");
Dave Allison0aded082013-11-07 13:15:11 -08001003 return nullptr;
Ian Rogers120f1c72012-09-28 17:17:10 -07001004 }
Ian Rogersf4d4da12014-11-11 16:10:33 -08001005 Thread* self;
Ian Rogers120f1c72012-09-28 17:17:10 -07001006 {
Mathieu Chartier3a0cd342018-12-13 13:45:17 -08001007 ScopedTrace trace2("Thread birth");
Dave Allison0aded082013-11-07 13:15:11 -08001008 MutexLock mu(nullptr, *Locks::runtime_shutdown_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001009 if (runtime->IsShuttingDownLocked()) {
Kazuhiro Inaba9ff12512017-12-04 16:26:38 +09001010 LOG(WARNING) << "Thread attaching while runtime is shutting down: " <<
1011 ((thread_name != nullptr) ? thread_name : "(Unnamed)");
Dave Allison0aded082013-11-07 13:15:11 -08001012 return nullptr;
Ian Rogers120f1c72012-09-28 17:17:10 -07001013 } else {
1014 Runtime::Current()->StartThreadBirth();
1015 self = new Thread(as_daemon);
Ian Rogersf4d4da12014-11-11 16:10:33 -08001016 bool init_success = self->Init(runtime->GetThreadList(), runtime->GetJavaVM());
Ian Rogers120f1c72012-09-28 17:17:10 -07001017 Runtime::Current()->EndThreadBirth();
Ian Rogersf4d4da12014-11-11 16:10:33 -08001018 if (!init_success) {
1019 delete self;
1020 return nullptr;
1021 }
Ian Rogers120f1c72012-09-28 17:17:10 -07001022 }
1023 }
Elliott Hughes93e74e82011-09-13 11:07:03 -07001024
Jeff Hao848f70a2014-01-15 13:49:50 -08001025 self->InitStringEntryPoints();
1026
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001027 CHECK_NE(self->GetState(), kRunnable);
1028 self->SetState(kNative);
Elliott Hughes93e74e82011-09-13 11:07:03 -07001029
Andreas Gampe732b0ac2017-01-18 15:23:39 -08001030 // Run the action that is acting on the peer.
1031 if (!peer_action(self)) {
1032 runtime->GetThreadList()->Unregister(self);
1033 // Unregister deletes self, no need to do this here.
1034 return nullptr;
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001035 }
Elliott Hughescac6cc72011-11-03 20:31:21 -07001036
Andreas Gampe56623832015-07-09 21:53:15 -07001037 if (VLOG_IS_ON(threads)) {
1038 if (thread_name != nullptr) {
1039 VLOG(threads) << "Attaching thread " << thread_name;
1040 } else {
1041 VLOG(threads) << "Attaching unnamed thread.";
1042 }
1043 ScopedObjectAccess soa(self);
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001044 self->Dump(LOG_STREAM(INFO));
Andreas Gampe56623832015-07-09 21:53:15 -07001045 }
1046
Daniel Mihalyidfafeef2014-10-20 11:47:56 +02001047 {
1048 ScopedObjectAccess soa(self);
Andreas Gampeac30fa22017-01-18 21:02:36 -08001049 runtime->GetRuntimeCallbacks()->ThreadStart(self);
Daniel Mihalyidfafeef2014-10-20 11:47:56 +02001050 }
1051
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001052 return self;
1053}
1054
Andreas Gampe732b0ac2017-01-18 15:23:39 -08001055Thread* Thread::Attach(const char* thread_name,
1056 bool as_daemon,
1057 jobject thread_group,
1058 bool create_peer) {
1059 auto create_peer_action = [&](Thread* self) {
1060 // If we're the main thread, ClassLinker won't be created until after we're attached,
1061 // so that thread needs a two-stage attach. Regular threads don't need this hack.
1062 // In the compiler, all threads need this hack, because no-one's going to be getting
1063 // a native peer!
1064 if (create_peer) {
1065 self->CreatePeer(thread_name, as_daemon, thread_group);
1066 if (self->IsExceptionPending()) {
Roland Levillain2ae376f2018-01-30 11:35:11 +00001067 // We cannot keep the exception around, as we're deleting self. Try to be helpful and log
1068 // it.
Andreas Gampe732b0ac2017-01-18 15:23:39 -08001069 {
1070 ScopedObjectAccess soa(self);
1071 LOG(ERROR) << "Exception creating thread peer:";
1072 LOG(ERROR) << self->GetException()->Dump();
1073 self->ClearException();
1074 }
1075 return false;
1076 }
1077 } else {
1078 // These aren't necessary, but they improve diagnostics for unit tests & command-line tools.
1079 if (thread_name != nullptr) {
1080 self->tlsPtr_.name->assign(thread_name);
1081 ::art::SetThreadName(thread_name);
Ian Rogers55256cb2017-12-21 17:07:11 -08001082 } else if (self->GetJniEnv()->IsCheckJniEnabled()) {
Andreas Gampe732b0ac2017-01-18 15:23:39 -08001083 LOG(WARNING) << *Thread::Current() << " attached without supplying a name";
1084 }
1085 }
1086 return true;
1087 };
1088 return Attach(thread_name, as_daemon, create_peer_action);
1089}
1090
1091Thread* Thread::Attach(const char* thread_name, bool as_daemon, jobject thread_peer) {
1092 auto set_peer_action = [&](Thread* self) {
1093 // Install the given peer.
1094 {
1095 DCHECK(self == Thread::Current());
1096 ScopedObjectAccess soa(self);
1097 self->tlsPtr_.opeer = soa.Decode<mirror::Object>(thread_peer).Ptr();
1098 }
1099 self->GetJniEnv()->SetLongField(thread_peer,
1100 WellKnownClasses::java_lang_Thread_nativePeer,
Vladimir Marko78baed52018-10-11 10:44:58 +01001101 reinterpret_cast64<jlong>(self));
Andreas Gampe732b0ac2017-01-18 15:23:39 -08001102 return true;
1103 };
1104 return Attach(thread_name, as_daemon, set_peer_action);
1105}
1106
Ian Rogers365c1022012-06-22 15:05:28 -07001107void Thread::CreatePeer(const char* name, bool as_daemon, jobject thread_group) {
1108 Runtime* runtime = Runtime::Current();
1109 CHECK(runtime->IsStarted());
Ian Rogersdd7624d2014-03-14 17:43:00 -07001110 JNIEnv* env = tlsPtr_.jni_env;
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001111
Dave Allison0aded082013-11-07 13:15:11 -08001112 if (thread_group == nullptr) {
Ian Rogers365c1022012-06-22 15:05:28 -07001113 thread_group = runtime->GetMainThreadGroup();
Elliott Hughes462c9442012-03-23 18:47:50 -07001114 }
Elliott Hughes726079d2011-10-07 18:43:44 -07001115 ScopedLocalRef<jobject> thread_name(env, env->NewStringUTF(name));
Mathieu Chartiere07fd172014-11-10 16:58:19 -08001116 // Add missing null check in case of OOM b/18297817
Vladimir Marko44512052014-11-12 15:41:57 +00001117 if (name != nullptr && thread_name.get() == nullptr) {
Mathieu Chartiere07fd172014-11-10 16:58:19 -08001118 CHECK(IsExceptionPending());
1119 return;
1120 }
Elliott Hughes8daa0922011-09-11 13:46:25 -07001121 jint thread_priority = GetNativePriority();
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001122 jboolean thread_is_daemon = as_daemon;
1123
Elliott Hugheseac76672012-05-24 21:56:51 -07001124 ScopedLocalRef<jobject> peer(env, env->AllocObject(WellKnownClasses::java_lang_Thread));
Dave Allison0aded082013-11-07 13:15:11 -08001125 if (peer.get() == nullptr) {
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07001126 CHECK(IsExceptionPending());
1127 return;
Ian Rogers5d4bdc22011-11-02 22:15:43 -07001128 }
Ian Rogerscfaa4552012-11-26 21:00:08 -08001129 {
1130 ScopedObjectAccess soa(this);
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07001131 tlsPtr_.opeer = soa.Decode<mirror::Object>(peer.get()).Ptr();
Ian Rogerscfaa4552012-11-26 21:00:08 -08001132 }
Elliott Hugheseac76672012-05-24 21:56:51 -07001133 env->CallNonvirtualVoidMethod(peer.get(),
1134 WellKnownClasses::java_lang_Thread,
1135 WellKnownClasses::java_lang_Thread_init,
Ian Rogers365c1022012-06-22 15:05:28 -07001136 thread_group, thread_name.get(), thread_priority, thread_is_daemon);
Andreas Gampe4b1d4ec2015-10-01 16:47:26 -07001137 if (IsExceptionPending()) {
1138 return;
1139 }
Elliott Hughesd369bb72011-09-12 14:41:14 -07001140
Ian Rogers120f1c72012-09-28 17:17:10 -07001141 Thread* self = this;
1142 DCHECK_EQ(self, Thread::Current());
Vladimir Marko78baed52018-10-11 10:44:58 +01001143 env->SetLongField(peer.get(),
1144 WellKnownClasses::java_lang_Thread_nativePeer,
1145 reinterpret_cast64<jlong>(self));
Ian Rogers120f1c72012-09-28 17:17:10 -07001146
1147 ScopedObjectAccess soa(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001148 StackHandleScope<1> hs(self);
Andreas Gampe08883de2016-11-08 13:20:52 -08001149 MutableHandle<mirror::String> peer_thread_name(hs.NewHandle(GetThreadName()));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001150 if (peer_thread_name == nullptr) {
Brian Carlstrom00fae582011-10-28 01:16:28 -07001151 // The Thread constructor should have set the Thread.name to a
1152 // non-null value. However, because we can run without code
1153 // available (in the compiler, in tests), we manually assign the
1154 // fields the constructor should have set.
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001155 if (runtime->IsActiveTransaction()) {
Andreas Gampebad529d2017-02-13 18:52:10 -08001156 InitPeer<true>(soa,
1157 tlsPtr_.opeer,
1158 thread_is_daemon,
1159 thread_group,
1160 thread_name.get(),
1161 thread_priority);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001162 } else {
Andreas Gampebad529d2017-02-13 18:52:10 -08001163 InitPeer<false>(soa,
1164 tlsPtr_.opeer,
1165 thread_is_daemon,
1166 thread_group,
1167 thread_name.get(),
1168 thread_priority);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001169 }
Andreas Gampe08883de2016-11-08 13:20:52 -08001170 peer_thread_name.Assign(GetThreadName());
Brian Carlstrom00fae582011-10-28 01:16:28 -07001171 }
Elliott Hughes225f5a12012-06-11 11:23:48 -07001172 // 'thread_name' may have been null, so don't trust 'peer_thread_name' to be non-null.
Andreas Gampefa4333d2017-02-14 11:10:34 -08001173 if (peer_thread_name != nullptr) {
Elliott Hughes899e7892012-01-24 14:57:32 -08001174 SetThreadName(peer_thread_name->ToModifiedUtf8().c_str());
Brian Carlstrom00fae582011-10-28 01:16:28 -07001175 }
Carl Shapiro61e019d2011-07-14 16:53:09 -07001176}
1177
Andreas Gampebad529d2017-02-13 18:52:10 -08001178jobject Thread::CreateCompileTimePeer(JNIEnv* env,
1179 const char* name,
1180 bool as_daemon,
1181 jobject thread_group) {
1182 Runtime* runtime = Runtime::Current();
1183 CHECK(!runtime->IsStarted());
1184
1185 if (thread_group == nullptr) {
1186 thread_group = runtime->GetMainThreadGroup();
1187 }
1188 ScopedLocalRef<jobject> thread_name(env, env->NewStringUTF(name));
1189 // Add missing null check in case of OOM b/18297817
1190 if (name != nullptr && thread_name.get() == nullptr) {
1191 CHECK(Thread::Current()->IsExceptionPending());
1192 return nullptr;
1193 }
Andreas Gampea1e5b972019-03-18 16:54:25 -07001194 jint thread_priority = kNormThreadPriority; // Always normalize to NORM priority.
Andreas Gampebad529d2017-02-13 18:52:10 -08001195 jboolean thread_is_daemon = as_daemon;
1196
1197 ScopedLocalRef<jobject> peer(env, env->AllocObject(WellKnownClasses::java_lang_Thread));
1198 if (peer.get() == nullptr) {
1199 CHECK(Thread::Current()->IsExceptionPending());
1200 return nullptr;
1201 }
1202
1203 // We cannot call Thread.init, as it will recursively ask for currentThread.
1204
1205 // The Thread constructor should have set the Thread.name to a
1206 // non-null value. However, because we can run without code
1207 // available (in the compiler, in tests), we manually assign the
1208 // fields the constructor should have set.
1209 ScopedObjectAccessUnchecked soa(Thread::Current());
1210 if (runtime->IsActiveTransaction()) {
1211 InitPeer<true>(soa,
1212 soa.Decode<mirror::Object>(peer.get()),
1213 thread_is_daemon,
1214 thread_group,
1215 thread_name.get(),
1216 thread_priority);
1217 } else {
1218 InitPeer<false>(soa,
1219 soa.Decode<mirror::Object>(peer.get()),
1220 thread_is_daemon,
1221 thread_group,
1222 thread_name.get(),
1223 thread_priority);
1224 }
1225
1226 return peer.release();
1227}
1228
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001229template<bool kTransactionActive>
Andreas Gampebad529d2017-02-13 18:52:10 -08001230void Thread::InitPeer(ScopedObjectAccessAlreadyRunnable& soa,
1231 ObjPtr<mirror::Object> peer,
1232 jboolean thread_is_daemon,
1233 jobject thread_group,
1234 jobject thread_name,
1235 jint thread_priority) {
Andreas Gampe08883de2016-11-08 13:20:52 -08001236 jni::DecodeArtField(WellKnownClasses::java_lang_Thread_daemon)->
Andreas Gampebad529d2017-02-13 18:52:10 -08001237 SetBoolean<kTransactionActive>(peer, thread_is_daemon);
Andreas Gampe08883de2016-11-08 13:20:52 -08001238 jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group)->
Andreas Gampebad529d2017-02-13 18:52:10 -08001239 SetObject<kTransactionActive>(peer, soa.Decode<mirror::Object>(thread_group));
Andreas Gampe08883de2016-11-08 13:20:52 -08001240 jni::DecodeArtField(WellKnownClasses::java_lang_Thread_name)->
Andreas Gampebad529d2017-02-13 18:52:10 -08001241 SetObject<kTransactionActive>(peer, soa.Decode<mirror::Object>(thread_name));
Andreas Gampe08883de2016-11-08 13:20:52 -08001242 jni::DecodeArtField(WellKnownClasses::java_lang_Thread_priority)->
Andreas Gampebad529d2017-02-13 18:52:10 -08001243 SetInt<kTransactionActive>(peer, thread_priority);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001244}
1245
Elliott Hughes899e7892012-01-24 14:57:32 -08001246void Thread::SetThreadName(const char* name) {
Ian Rogersdd7624d2014-03-14 17:43:00 -07001247 tlsPtr_.name->assign(name);
Elliott Hughes899e7892012-01-24 14:57:32 -08001248 ::art::SetThreadName(name);
1249 Dbg::DdmSendThreadNotification(this, CHUNK_TYPE("THNM"));
1250}
1251
Andreas Gampe9186ced2016-12-12 14:28:21 -08001252static void GetThreadStack(pthread_t thread,
1253 void** stack_base,
1254 size_t* stack_size,
1255 size_t* guard_size) {
1256#if defined(__APPLE__)
1257 *stack_size = pthread_get_stacksize_np(thread);
1258 void* stack_addr = pthread_get_stackaddr_np(thread);
1259
1260 // Check whether stack_addr is the base or end of the stack.
1261 // (On Mac OS 10.7, it's the end.)
1262 int stack_variable;
1263 if (stack_addr > &stack_variable) {
1264 *stack_base = reinterpret_cast<uint8_t*>(stack_addr) - *stack_size;
1265 } else {
1266 *stack_base = stack_addr;
1267 }
1268
1269 // This is wrong, but there doesn't seem to be a way to get the actual value on the Mac.
1270 pthread_attr_t attributes;
1271 CHECK_PTHREAD_CALL(pthread_attr_init, (&attributes), __FUNCTION__);
1272 CHECK_PTHREAD_CALL(pthread_attr_getguardsize, (&attributes, guard_size), __FUNCTION__);
1273 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
1274#else
1275 pthread_attr_t attributes;
1276 CHECK_PTHREAD_CALL(pthread_getattr_np, (thread, &attributes), __FUNCTION__);
1277 CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, stack_base, stack_size), __FUNCTION__);
1278 CHECK_PTHREAD_CALL(pthread_attr_getguardsize, (&attributes, guard_size), __FUNCTION__);
1279 CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
1280
1281#if defined(__GLIBC__)
1282 // If we're the main thread, check whether we were run with an unlimited stack. In that case,
1283 // glibc will have reported a 2GB stack for our 32-bit process, and our stack overflow detection
1284 // will be broken because we'll die long before we get close to 2GB.
1285 bool is_main_thread = (::art::GetTid() == getpid());
1286 if (is_main_thread) {
1287 rlimit stack_limit;
1288 if (getrlimit(RLIMIT_STACK, &stack_limit) == -1) {
1289 PLOG(FATAL) << "getrlimit(RLIMIT_STACK) failed";
1290 }
1291 if (stack_limit.rlim_cur == RLIM_INFINITY) {
1292 size_t old_stack_size = *stack_size;
1293
1294 // Use the kernel default limit as our size, and adjust the base to match.
1295 *stack_size = 8 * MB;
1296 *stack_base = reinterpret_cast<uint8_t*>(*stack_base) + (old_stack_size - *stack_size);
1297
1298 VLOG(threads) << "Limiting unlimited stack (reported as " << PrettySize(old_stack_size) << ")"
1299 << " to " << PrettySize(*stack_size)
1300 << " with base " << *stack_base;
1301 }
1302 }
1303#endif
1304
1305#endif
1306}
1307
Ian Rogersf4d4da12014-11-11 16:10:33 -08001308bool Thread::InitStackHwm() {
Mathieu Chartier3a0cd342018-12-13 13:45:17 -08001309 ScopedTrace trace("InitStackHwm");
Ian Rogersdd7624d2014-03-14 17:43:00 -07001310 void* read_stack_base;
1311 size_t read_stack_size;
Elliott Hughes6d3fc562014-08-27 11:47:01 -07001312 size_t read_guard_size;
1313 GetThreadStack(tlsPtr_.pthread_self, &read_stack_base, &read_stack_size, &read_guard_size);
Elliott Hughes36ecb782012-04-17 16:55:45 -07001314
Ian Rogers13735952014-10-08 12:43:28 -07001315 tlsPtr_.stack_begin = reinterpret_cast<uint8_t*>(read_stack_base);
Ian Rogersdd7624d2014-03-14 17:43:00 -07001316 tlsPtr_.stack_size = read_stack_size;
Elliott Hughes36ecb782012-04-17 16:55:45 -07001317
Dave Allison648d7112014-07-25 16:15:27 -07001318 // The minimum stack size we can cope with is the overflow reserved bytes (typically
1319 // 8K) + the protected region size (4K) + another page (4K). Typically this will
1320 // be 8+4+4 = 16K. The thread won't be able to do much with this stack even the GC takes
1321 // between 8K and 12K.
1322 uint32_t min_stack = GetStackOverflowReservedBytes(kRuntimeISA) + kStackOverflowProtectedSize
1323 + 4 * KB;
1324 if (read_stack_size <= min_stack) {
Ian Rogersf4d4da12014-11-11 16:10:33 -08001325 // Note, as we know the stack is small, avoid operations that could use a lot of stack.
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001326 LogHelper::LogLineLowStack(__PRETTY_FUNCTION__,
1327 __LINE__,
1328 ::android::base::ERROR,
1329 "Attempt to attach a thread with a too-small stack");
Ian Rogersf4d4da12014-11-11 16:10:33 -08001330 return false;
Elliott Hughesbe759c62011-09-08 19:38:21 -07001331 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -07001332
Vladimir Markob8f2f632015-01-02 14:23:26 +00001333 // This is included in the SIGQUIT output, but it's useful here for thread debugging.
1334 VLOG(threads) << StringPrintf("Native stack is at %p (%s with %s guard)",
1335 read_stack_base,
1336 PrettySize(read_stack_size).c_str(),
1337 PrettySize(read_guard_size).c_str());
1338
Ian Rogers932746a2011-09-22 18:57:50 -07001339 // Set stack_end_ to the bottom of the stack saving space of stack overflows
Mathieu Chartier8e219ae2014-08-19 14:29:46 -07001340
1341 Runtime* runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001342 bool implicit_stack_check = !runtime->ExplicitStackOverflowChecks() && !runtime->IsAotCompiler();
Andreas Gampe7df12cb2016-06-10 20:38:55 -07001343
Dave Allisonb090a182014-08-14 17:02:48 +00001344 ResetDefaultStackEnd();
Dave Allisonf9439142014-03-27 15:10:22 -07001345
1346 // Install the protected region if we are doing implicit overflow checks.
Roland Levillain05e34f42018-05-24 13:19:05 +00001347 if (implicit_stack_check) {
Dave Allison648d7112014-07-25 16:15:27 -07001348 // The thread might have protected region at the bottom. We need
1349 // to install our own region so we need to move the limits
1350 // of the stack to make room for it.
Dave Allison216cf232014-08-18 15:49:51 -07001351
Elliott Hughes6d3fc562014-08-27 11:47:01 -07001352 tlsPtr_.stack_begin += read_guard_size + kStackOverflowProtectedSize;
1353 tlsPtr_.stack_end += read_guard_size + kStackOverflowProtectedSize;
1354 tlsPtr_.stack_size -= read_guard_size;
Dave Allison648d7112014-07-25 16:15:27 -07001355
1356 InstallImplicitProtection();
Dave Allisonf9439142014-03-27 15:10:22 -07001357 }
Elliott Hughes449b4bd2011-09-09 12:01:38 -07001358
1359 // Sanity check.
Andreas Gampeb87c03f2016-06-10 20:34:55 -07001360 CHECK_GT(FindStackTop(), reinterpret_cast<void*>(tlsPtr_.stack_end));
Ian Rogersf4d4da12014-11-11 16:10:33 -08001361
1362 return true;
Elliott Hughesbe759c62011-09-08 19:38:21 -07001363}
1364
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001365void Thread::ShortDump(std::ostream& os) const {
1366 os << "Thread[";
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001367 if (GetThreadId() != 0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001368 // If we're in kStarting, we won't have a thin lock id or tid yet.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001369 os << GetThreadId()
Mathieu Chartierb28412e2015-04-24 15:28:36 -07001370 << ",tid=" << GetTid() << ',';
Elliott Hughese0918552011-10-28 17:18:29 -07001371 }
Ian Rogers474b6da2012-09-25 00:20:38 -07001372 os << GetState()
Mathieu Chartierb28412e2015-04-24 15:28:36 -07001373 << ",Thread*=" << this
1374 << ",peer=" << tlsPtr_.opeer
1375 << ",\"" << (tlsPtr_.name != nullptr ? *tlsPtr_.name : "null") << "\""
1376 << "]";
Elliott Hughesa0957642011-09-02 14:27:33 -07001377}
1378
Nicolas Geoffray6ee49712018-03-30 14:39:05 +00001379void Thread::Dump(std::ostream& os, bool dump_native_stack, BacktraceMap* backtrace_map,
1380 bool force_dump_stack) const {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001381 DumpState(os);
Nicolas Geoffray6ee49712018-03-30 14:39:05 +00001382 DumpStack(os, dump_native_stack, backtrace_map, force_dump_stack);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001383}
1384
Vladimir Marko4617d582019-03-28 13:48:31 +00001385ObjPtr<mirror::String> Thread::GetThreadName() const {
Andreas Gampe08883de2016-11-08 13:20:52 -08001386 ArtField* f = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_name);
Mathieu Chartier3398c782016-09-30 10:27:43 -07001387 if (tlsPtr_.opeer == nullptr) {
1388 return nullptr;
1389 }
1390 ObjPtr<mirror::Object> name = f->GetObject(tlsPtr_.opeer);
1391 return name == nullptr ? nullptr : name->AsString();
Elliott Hughesfc861622011-10-17 17:57:47 -07001392}
1393
Elliott Hughesffb465f2012-03-01 18:46:05 -08001394void Thread::GetThreadName(std::string& name) const {
Ian Rogersdd7624d2014-03-14 17:43:00 -07001395 name.assign(*tlsPtr_.name);
Elliott Hughesffb465f2012-03-01 18:46:05 -08001396}
1397
Jeff Hao57dac6e2013-08-15 16:36:24 -07001398uint64_t Thread::GetCpuMicroTime() const {
Elliott Hughes0a18df82015-01-09 15:16:16 -08001399#if defined(__linux__)
Jeff Hao57dac6e2013-08-15 16:36:24 -07001400 clockid_t cpu_clock_id;
Ian Rogersdd7624d2014-03-14 17:43:00 -07001401 pthread_getcpuclockid(tlsPtr_.pthread_self, &cpu_clock_id);
Jeff Hao57dac6e2013-08-15 16:36:24 -07001402 timespec now;
1403 clock_gettime(cpu_clock_id, &now);
Ian Rogers0f678472014-03-10 16:18:37 -07001404 return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000) + now.tv_nsec / UINT64_C(1000);
Elliott Hughes0a18df82015-01-09 15:16:16 -08001405#else // __APPLE__
Jeff Hao57dac6e2013-08-15 16:36:24 -07001406 UNIMPLEMENTED(WARNING);
1407 return -1;
1408#endif
1409}
1410
Ian Rogers01ae5802012-09-28 16:14:01 -07001411// Attempt to rectify locks so that we dump thread list with required locks before exiting.
1412static void UnsafeLogFatalForSuspendCount(Thread* self, Thread* thread) NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers120f1c72012-09-28 17:17:10 -07001413 LOG(ERROR) << *thread << " suspend count already zero.";
Ian Rogers01ae5802012-09-28 16:14:01 -07001414 Locks::thread_suspend_count_lock_->Unlock(self);
1415 if (!Locks::mutator_lock_->IsSharedHeld(self)) {
1416 Locks::mutator_lock_->SharedTryLock(self);
1417 if (!Locks::mutator_lock_->IsSharedHeld(self)) {
1418 LOG(WARNING) << "Dumping thread list without holding mutator_lock_";
1419 }
1420 }
1421 if (!Locks::thread_list_lock_->IsExclusiveHeld(self)) {
1422 Locks::thread_list_lock_->TryLock(self);
1423 if (!Locks::thread_list_lock_->IsExclusiveHeld(self)) {
1424 LOG(WARNING) << "Dumping thread list without holding thread_list_lock_";
1425 }
1426 }
1427 std::ostringstream ss;
Ian Rogers7b078e82014-09-10 14:44:24 -07001428 Runtime::Current()->GetThreadList()->Dump(ss);
Ian Rogers120f1c72012-09-28 17:17:10 -07001429 LOG(FATAL) << ss.str();
Ian Rogers01ae5802012-09-28 16:14:01 -07001430}
1431
Hiroshi Yamauchi02e7f1a2016-10-03 15:32:01 -07001432bool Thread::ModifySuspendCountInternal(Thread* self,
1433 int delta,
1434 AtomicInteger* suspend_barrier,
Alex Light46f93402017-06-29 11:59:50 -07001435 SuspendReason reason) {
Ian Rogers2966e132014-04-02 08:34:36 -07001436 if (kIsDebugBuild) {
1437 DCHECK(delta == -1 || delta == +1 || delta == -tls32_.debug_suspend_count)
Alex Light46f93402017-06-29 11:59:50 -07001438 << reason << " " << delta << " " << tls32_.debug_suspend_count << " " << this;
Ian Rogers2966e132014-04-02 08:34:36 -07001439 DCHECK_GE(tls32_.suspend_count, tls32_.debug_suspend_count) << this;
1440 Locks::thread_suspend_count_lock_->AssertHeld(self);
1441 if (this != self && !IsSuspended()) {
1442 Locks::thread_list_lock_->AssertHeld(self);
1443 }
Ian Rogerscfaa4552012-11-26 21:00:08 -08001444 }
Alex Light88fd7202017-06-30 08:31:59 -07001445 // User code suspensions need to be checked more closely since they originate from code outside of
1446 // the runtime's control.
1447 if (UNLIKELY(reason == SuspendReason::kForUserCode)) {
1448 Locks::user_code_suspension_lock_->AssertHeld(self);
1449 if (UNLIKELY(delta + tls32_.user_code_suspend_count < 0)) {
1450 LOG(ERROR) << "attempting to modify suspend count in an illegal way.";
1451 return false;
1452 }
1453 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07001454 if (UNLIKELY(delta < 0 && tls32_.suspend_count <= 0)) {
Ian Rogers01ae5802012-09-28 16:14:01 -07001455 UnsafeLogFatalForSuspendCount(self, this);
Yu Lieac44242015-06-29 10:50:03 +08001456 return false;
1457 }
1458
Hiroshi Yamauchi02e7f1a2016-10-03 15:32:01 -07001459 if (kUseReadBarrier && delta > 0 && this != self && tlsPtr_.flip_function != nullptr) {
1460 // Force retry of a suspend request if it's in the middle of a thread flip to avoid a
1461 // deadlock. b/31683379.
1462 return false;
1463 }
1464
Yu Lieac44242015-06-29 10:50:03 +08001465 uint16_t flags = kSuspendRequest;
1466 if (delta > 0 && suspend_barrier != nullptr) {
1467 uint32_t available_barrier = kMaxSuspendBarriers;
1468 for (uint32_t i = 0; i < kMaxSuspendBarriers; ++i) {
1469 if (tlsPtr_.active_suspend_barriers[i] == nullptr) {
1470 available_barrier = i;
1471 break;
1472 }
1473 }
1474 if (available_barrier == kMaxSuspendBarriers) {
1475 // No barrier spaces available, we can't add another.
1476 return false;
1477 }
1478 tlsPtr_.active_suspend_barriers[available_barrier] = suspend_barrier;
1479 flags |= kActiveSuspendBarrier;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001480 }
Ian Rogers01ae5802012-09-28 16:14:01 -07001481
Ian Rogersdd7624d2014-03-14 17:43:00 -07001482 tls32_.suspend_count += delta;
Alex Light46f93402017-06-29 11:59:50 -07001483 switch (reason) {
Alex Light88fd7202017-06-30 08:31:59 -07001484 case SuspendReason::kForUserCode:
1485 tls32_.user_code_suspend_count += delta;
1486 break;
Alex Light46f93402017-06-29 11:59:50 -07001487 case SuspendReason::kInternal:
1488 break;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001489 }
Ian Rogers01ae5802012-09-28 16:14:01 -07001490
Ian Rogersdd7624d2014-03-14 17:43:00 -07001491 if (tls32_.suspend_count == 0) {
Ian Rogers474b6da2012-09-25 00:20:38 -07001492 AtomicClearFlag(kSuspendRequest);
1493 } else {
Yu Lieac44242015-06-29 10:50:03 +08001494 // Two bits might be set simultaneously.
Orion Hodson88591fe2018-03-06 13:35:43 +00001495 tls32_.state_and_flags.as_atomic_int.fetch_or(flags, std::memory_order_seq_cst);
Dave Allisonb373e092014-02-20 16:06:36 -08001496 TriggerSuspend();
Ian Rogers474b6da2012-09-25 00:20:38 -07001497 }
Yu Lieac44242015-06-29 10:50:03 +08001498 return true;
1499}
1500
1501bool Thread::PassActiveSuspendBarriers(Thread* self) {
1502 // Grab the suspend_count lock and copy the current set of
1503 // barriers. Then clear the list and the flag. The ModifySuspendCount
1504 // function requires the lock so we prevent a race between setting
1505 // the kActiveSuspendBarrier flag and clearing it.
1506 AtomicInteger* pass_barriers[kMaxSuspendBarriers];
1507 {
1508 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
1509 if (!ReadFlag(kActiveSuspendBarrier)) {
1510 // quick exit test: the barriers have already been claimed - this is
1511 // possible as there may be a race to claim and it doesn't matter
1512 // who wins.
1513 // All of the callers of this function (except the SuspendAllInternal)
1514 // will first test the kActiveSuspendBarrier flag without lock. Here
1515 // double-check whether the barrier has been passed with the
1516 // suspend_count lock.
1517 return false;
1518 }
1519
1520 for (uint32_t i = 0; i < kMaxSuspendBarriers; ++i) {
1521 pass_barriers[i] = tlsPtr_.active_suspend_barriers[i];
1522 tlsPtr_.active_suspend_barriers[i] = nullptr;
1523 }
1524 AtomicClearFlag(kActiveSuspendBarrier);
1525 }
1526
1527 uint32_t barrier_count = 0;
1528 for (uint32_t i = 0; i < kMaxSuspendBarriers; i++) {
1529 AtomicInteger* pending_threads = pass_barriers[i];
1530 if (pending_threads != nullptr) {
1531 bool done = false;
1532 do {
Orion Hodson88591fe2018-03-06 13:35:43 +00001533 int32_t cur_val = pending_threads->load(std::memory_order_relaxed);
Yu Lieac44242015-06-29 10:50:03 +08001534 CHECK_GT(cur_val, 0) << "Unexpected value for PassActiveSuspendBarriers(): " << cur_val;
1535 // Reduce value by 1.
Orion Hodson4557b382018-01-03 11:47:54 +00001536 done = pending_threads->CompareAndSetWeakRelaxed(cur_val, cur_val - 1);
Yu Lieac44242015-06-29 10:50:03 +08001537#if ART_USE_FUTEXES
1538 if (done && (cur_val - 1) == 0) { // Weak CAS may fail spuriously.
Hans Boehm81dc7ab2019-04-19 17:34:31 -07001539 futex(pending_threads->Address(), FUTEX_WAKE_PRIVATE, INT_MAX, nullptr, nullptr, 0);
Yu Lieac44242015-06-29 10:50:03 +08001540 }
1541#endif
1542 } while (!done);
1543 ++barrier_count;
1544 }
1545 }
1546 CHECK_GT(barrier_count, 0U);
1547 return true;
1548}
1549
1550void Thread::ClearSuspendBarrier(AtomicInteger* target) {
1551 CHECK(ReadFlag(kActiveSuspendBarrier));
1552 bool clear_flag = true;
1553 for (uint32_t i = 0; i < kMaxSuspendBarriers; ++i) {
1554 AtomicInteger* ptr = tlsPtr_.active_suspend_barriers[i];
1555 if (ptr == target) {
1556 tlsPtr_.active_suspend_barriers[i] = nullptr;
1557 } else if (ptr != nullptr) {
1558 clear_flag = false;
1559 }
1560 }
1561 if (LIKELY(clear_flag)) {
1562 AtomicClearFlag(kActiveSuspendBarrier);
1563 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001564}
1565
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001566void Thread::RunCheckpointFunction() {
Alex Lightdf00a1e2017-11-01 09:29:53 -07001567 // Grab the suspend_count lock, get the next checkpoint and update all the checkpoint fields. If
1568 // there are no more checkpoints we will also clear the kCheckpointRequest flag.
1569 Closure* checkpoint;
1570 {
1571 MutexLock mu(this, *Locks::thread_suspend_count_lock_);
1572 checkpoint = tlsPtr_.checkpoint_function;
1573 if (!checkpoint_overflow_.empty()) {
1574 // Overflow list not empty, copy the first one out and continue.
1575 tlsPtr_.checkpoint_function = checkpoint_overflow_.front();
1576 checkpoint_overflow_.pop_front();
1577 } else {
1578 // No overflow checkpoints. Clear the kCheckpointRequest flag
1579 tlsPtr_.checkpoint_function = nullptr;
1580 AtomicClearFlag(kCheckpointRequest);
Dave Allison0aded082013-11-07 13:15:11 -08001581 }
Alex Lightdf00a1e2017-11-01 09:29:53 -07001582 }
1583 // Outside the lock, run the checkpoint function.
1584 ScopedTrace trace("Run checkpoint function");
1585 CHECK(checkpoint != nullptr) << "Checkpoint flag set without pending checkpoint";
1586 checkpoint->Run(this);
Mathieu Chartier752a0e62013-06-27 11:03:27 -07001587}
1588
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07001589void Thread::RunEmptyCheckpoint() {
1590 DCHECK_EQ(Thread::Current(), this);
1591 AtomicClearFlag(kEmptyCheckpointRequest);
1592 Runtime::Current()->GetThreadList()->EmptyCheckpointBarrier()->Pass(this);
1593}
1594
Mathieu Chartier0e4627e2012-10-23 16:13:36 -07001595bool Thread::RequestCheckpoint(Closure* function) {
Chris Dearman59cde532013-12-04 18:53:49 -08001596 union StateAndFlags old_state_and_flags;
Ian Rogersdd7624d2014-03-14 17:43:00 -07001597 old_state_and_flags.as_int = tls32_.state_and_flags.as_int;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001598 if (old_state_and_flags.as_struct.state != kRunnable) {
1599 return false; // Fail, thread is suspended and so can't run a checkpoint.
1600 }
Dave Allison0aded082013-11-07 13:15:11 -08001601
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001602 // We must be runnable to request a checkpoint.
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -08001603 DCHECK_EQ(old_state_and_flags.as_struct.state, kRunnable);
Chris Dearman59cde532013-12-04 18:53:49 -08001604 union StateAndFlags new_state_and_flags;
1605 new_state_and_flags.as_int = old_state_and_flags.as_int;
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001606 new_state_and_flags.as_struct.flags |= kCheckpointRequest;
Orion Hodson4557b382018-01-03 11:47:54 +00001607 bool success = tls32_.state_and_flags.as_atomic_int.CompareAndSetStrongSequentiallyConsistent(
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001608 old_state_and_flags.as_int, new_state_and_flags.as_int);
Mathieu Chartier952e1e32016-06-13 14:04:02 -07001609 if (success) {
1610 // Succeeded setting checkpoint flag, now insert the actual checkpoint.
1611 if (tlsPtr_.checkpoint_function == nullptr) {
1612 tlsPtr_.checkpoint_function = function;
1613 } else {
1614 checkpoint_overflow_.push_back(function);
1615 }
Dave Allison0aded082013-11-07 13:15:11 -08001616 CHECK_EQ(ReadFlag(kCheckpointRequest), true);
Dave Allisonb373e092014-02-20 16:06:36 -08001617 TriggerSuspend();
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001618 }
Ian Rogers8c1b5f72014-07-09 22:02:36 -07001619 return success;
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001620}
1621
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07001622bool Thread::RequestEmptyCheckpoint() {
1623 union StateAndFlags old_state_and_flags;
1624 old_state_and_flags.as_int = tls32_.state_and_flags.as_int;
1625 if (old_state_and_flags.as_struct.state != kRunnable) {
1626 // If it's not runnable, we don't need to do anything because it won't be in the middle of a
1627 // heap access (eg. the read barrier).
1628 return false;
1629 }
1630
1631 // We must be runnable to request a checkpoint.
1632 DCHECK_EQ(old_state_and_flags.as_struct.state, kRunnable);
1633 union StateAndFlags new_state_and_flags;
1634 new_state_and_flags.as_int = old_state_and_flags.as_int;
1635 new_state_and_flags.as_struct.flags |= kEmptyCheckpointRequest;
Orion Hodson4557b382018-01-03 11:47:54 +00001636 bool success = tls32_.state_and_flags.as_atomic_int.CompareAndSetStrongSequentiallyConsistent(
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07001637 old_state_and_flags.as_int, new_state_and_flags.as_int);
1638 if (success) {
1639 TriggerSuspend();
1640 }
1641 return success;
1642}
1643
Andreas Gampee9f67122016-10-27 19:21:23 -07001644class BarrierClosure : public Closure {
1645 public:
1646 explicit BarrierClosure(Closure* wrapped) : wrapped_(wrapped), barrier_(0) {}
1647
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001648 void Run(Thread* self) override {
Andreas Gampee9f67122016-10-27 19:21:23 -07001649 wrapped_->Run(self);
1650 barrier_.Pass(self);
1651 }
1652
Alex Light318afe62018-03-22 16:50:10 -07001653 void Wait(Thread* self, ThreadState suspend_state) {
1654 if (suspend_state != ThreadState::kRunnable) {
1655 barrier_.Increment<Barrier::kDisallowHoldingLocks>(self, 1);
1656 } else {
1657 barrier_.Increment<Barrier::kAllowHoldingLocks>(self, 1);
1658 }
Andreas Gampee9f67122016-10-27 19:21:23 -07001659 }
1660
1661 private:
1662 Closure* wrapped_;
1663 Barrier barrier_;
1664};
1665
Alex Lightb1e31a82017-10-04 16:57:36 -07001666// RequestSynchronousCheckpoint releases the thread_list_lock_ as a part of its execution.
Alex Light318afe62018-03-22 16:50:10 -07001667bool Thread::RequestSynchronousCheckpoint(Closure* function, ThreadState suspend_state) {
Alex Lightb1e31a82017-10-04 16:57:36 -07001668 Thread* self = Thread::Current();
Andreas Gampee9f67122016-10-27 19:21:23 -07001669 if (this == Thread::Current()) {
Alex Lightb1e31a82017-10-04 16:57:36 -07001670 Locks::thread_list_lock_->AssertExclusiveHeld(self);
1671 // Unlock the tll before running so that the state is the same regardless of thread.
1672 Locks::thread_list_lock_->ExclusiveUnlock(self);
Andreas Gampee9f67122016-10-27 19:21:23 -07001673 // Asked to run on this thread. Just run.
1674 function->Run(this);
Andreas Gampe28c4a232017-06-21 21:21:31 -07001675 return true;
Andreas Gampee9f67122016-10-27 19:21:23 -07001676 }
Andreas Gampee9f67122016-10-27 19:21:23 -07001677
1678 // The current thread is not this thread.
1679
Andreas Gampe28c4a232017-06-21 21:21:31 -07001680 if (GetState() == ThreadState::kTerminated) {
Alex Lightb1e31a82017-10-04 16:57:36 -07001681 Locks::thread_list_lock_->ExclusiveUnlock(self);
Andreas Gampe28c4a232017-06-21 21:21:31 -07001682 return false;
1683 }
1684
Andreas Gampe28c4a232017-06-21 21:21:31 -07001685 struct ScopedThreadListLockUnlock {
1686 explicit ScopedThreadListLockUnlock(Thread* self_in) RELEASE(*Locks::thread_list_lock_)
1687 : self_thread(self_in) {
1688 Locks::thread_list_lock_->AssertHeld(self_thread);
1689 Locks::thread_list_lock_->Unlock(self_thread);
1690 }
1691
1692 ~ScopedThreadListLockUnlock() ACQUIRE(*Locks::thread_list_lock_) {
1693 Locks::thread_list_lock_->AssertNotHeld(self_thread);
1694 Locks::thread_list_lock_->Lock(self_thread);
1695 }
1696
1697 Thread* self_thread;
1698 };
1699
Andreas Gampee9f67122016-10-27 19:21:23 -07001700 for (;;) {
Alex Lightb1e31a82017-10-04 16:57:36 -07001701 Locks::thread_list_lock_->AssertExclusiveHeld(self);
Andreas Gampee9f67122016-10-27 19:21:23 -07001702 // If this thread is runnable, try to schedule a checkpoint. Do some gymnastics to not hold the
1703 // suspend-count lock for too long.
1704 if (GetState() == ThreadState::kRunnable) {
1705 BarrierClosure barrier_closure(function);
1706 bool installed = false;
1707 {
1708 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
1709 installed = RequestCheckpoint(&barrier_closure);
1710 }
1711 if (installed) {
Alex Lightb1e31a82017-10-04 16:57:36 -07001712 // Relinquish the thread-list lock. We should not wait holding any locks. We cannot
1713 // reacquire it since we don't know if 'this' hasn't been deleted yet.
1714 Locks::thread_list_lock_->ExclusiveUnlock(self);
Alex Light318afe62018-03-22 16:50:10 -07001715 ScopedThreadStateChange sts(self, suspend_state);
1716 barrier_closure.Wait(self, suspend_state);
Andreas Gampe28c4a232017-06-21 21:21:31 -07001717 return true;
Andreas Gampee9f67122016-10-27 19:21:23 -07001718 }
1719 // Fall-through.
1720 }
1721
1722 // This thread is not runnable, make sure we stay suspended, then run the checkpoint.
1723 // Note: ModifySuspendCountInternal also expects the thread_list_lock to be held in
1724 // certain situations.
1725 {
Andreas Gampee9f67122016-10-27 19:21:23 -07001726 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
1727
Alex Light46f93402017-06-29 11:59:50 -07001728 if (!ModifySuspendCount(self, +1, nullptr, SuspendReason::kInternal)) {
Andreas Gampee9f67122016-10-27 19:21:23 -07001729 // Just retry the loop.
1730 sched_yield();
1731 continue;
1732 }
1733 }
1734
Andreas Gampe28c4a232017-06-21 21:21:31 -07001735 {
Alex Lightb1e31a82017-10-04 16:57:36 -07001736 // Release for the wait. The suspension will keep us from being deleted. Reacquire after so
1737 // that we can call ModifySuspendCount without racing against ThreadList::Unregister.
Andreas Gampe28c4a232017-06-21 21:21:31 -07001738 ScopedThreadListLockUnlock stllu(self);
Andreas Gampe117f9b32017-06-23 13:33:50 -07001739 {
Alex Light318afe62018-03-22 16:50:10 -07001740 ScopedThreadStateChange sts(self, suspend_state);
Andreas Gampe117f9b32017-06-23 13:33:50 -07001741 while (GetState() == ThreadState::kRunnable) {
1742 // We became runnable again. Wait till the suspend triggered in ModifySuspendCount
1743 // moves us to suspended.
1744 sched_yield();
1745 }
Andreas Gampe28c4a232017-06-21 21:21:31 -07001746 }
1747
1748 function->Run(this);
Andreas Gampee9f67122016-10-27 19:21:23 -07001749 }
1750
Andreas Gampee9f67122016-10-27 19:21:23 -07001751 {
Andreas Gampee9f67122016-10-27 19:21:23 -07001752 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
1753
1754 DCHECK_NE(GetState(), ThreadState::kRunnable);
Alex Light46f93402017-06-29 11:59:50 -07001755 bool updated = ModifySuspendCount(self, -1, nullptr, SuspendReason::kInternal);
Sebastien Hertz1c8f4ff2017-04-14 15:05:12 +02001756 DCHECK(updated);
Andreas Gampee9f67122016-10-27 19:21:23 -07001757 }
1758
Andreas Gampe117f9b32017-06-23 13:33:50 -07001759 {
1760 // Imitate ResumeAll, the thread may be waiting on Thread::resume_cond_ since we raised its
1761 // suspend count. Now the suspend_count_ is lowered so we must do the broadcast.
1762 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
1763 Thread::resume_cond_->Broadcast(self);
1764 }
1765
Alex Lightb1e31a82017-10-04 16:57:36 -07001766 // Release the thread_list_lock_ to be consistent with the barrier-closure path.
1767 Locks::thread_list_lock_->ExclusiveUnlock(self);
1768
Andreas Gampe28c4a232017-06-21 21:21:31 -07001769 return true; // We're done, break out of the loop.
Andreas Gampee9f67122016-10-27 19:21:23 -07001770 }
1771}
1772
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001773Closure* Thread::GetFlipFunction() {
1774 Atomic<Closure*>* atomic_func = reinterpret_cast<Atomic<Closure*>*>(&tlsPtr_.flip_function);
1775 Closure* func;
1776 do {
Orion Hodson88591fe2018-03-06 13:35:43 +00001777 func = atomic_func->load(std::memory_order_relaxed);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001778 if (func == nullptr) {
1779 return nullptr;
1780 }
Orion Hodson4557b382018-01-03 11:47:54 +00001781 } while (!atomic_func->CompareAndSetWeakSequentiallyConsistent(func, nullptr));
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001782 DCHECK(func != nullptr);
1783 return func;
1784}
1785
1786void Thread::SetFlipFunction(Closure* function) {
1787 CHECK(function != nullptr);
1788 Atomic<Closure*>* atomic_func = reinterpret_cast<Atomic<Closure*>*>(&tlsPtr_.flip_function);
Orion Hodson88591fe2018-03-06 13:35:43 +00001789 atomic_func->store(function, std::memory_order_seq_cst);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001790}
1791
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001792void Thread::FullSuspendCheck() {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001793 ScopedTrace trace(__FUNCTION__);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001794 VLOG(threads) << this << " self-suspending";
1795 // Make thread appear suspended to other threads, release mutator_lock_.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07001796 // Transition to suspended and back to runnable, re-acquire share on mutator_lock_.
Andreas Gampe896583e2018-06-15 13:31:58 -07001797 ScopedThreadSuspension(this, kSuspended); // NOLINT
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001798 VLOG(threads) << this << " self-reviving";
1799}
1800
Andreas Gampe9186ced2016-12-12 14:28:21 -08001801static std::string GetSchedulerGroupName(pid_t tid) {
1802 // /proc/<pid>/cgroup looks like this:
1803 // 2:devices:/
1804 // 1:cpuacct,cpu:/
1805 // We want the third field from the line whose second field contains the "cpu" token.
1806 std::string cgroup_file;
Andreas Gampe43e72432019-05-14 16:15:24 -07001807 if (!android::base::ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid),
1808 &cgroup_file)) {
Andreas Gampe9186ced2016-12-12 14:28:21 -08001809 return "";
1810 }
1811 std::vector<std::string> cgroup_lines;
1812 Split(cgroup_file, '\n', &cgroup_lines);
1813 for (size_t i = 0; i < cgroup_lines.size(); ++i) {
1814 std::vector<std::string> cgroup_fields;
1815 Split(cgroup_lines[i], ':', &cgroup_fields);
1816 std::vector<std::string> cgroups;
1817 Split(cgroup_fields[1], ',', &cgroups);
1818 for (size_t j = 0; j < cgroups.size(); ++j) {
1819 if (cgroups[j] == "cpu") {
1820 return cgroup_fields[2].substr(1); // Skip the leading slash.
1821 }
1822 }
1823 }
1824 return "";
1825}
1826
1827
Elliott Hughesabbe07d2012-06-05 17:42:23 -07001828void Thread::DumpState(std::ostream& os, const Thread* thread, pid_t tid) {
Elliott Hughesd369bb72011-09-12 14:41:14 -07001829 std::string group_name;
1830 int priority;
1831 bool is_daemon = false;
Ian Rogers81d425b2012-09-27 16:03:43 -07001832 Thread* self = Thread::Current();
Elliott Hughesdcc24742011-09-07 14:02:44 -07001833
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001834 // If flip_function is not null, it means we have run a checkpoint
1835 // before the thread wakes up to execute the flip function and the
1836 // thread roots haven't been forwarded. So the following access to
1837 // the roots (opeer or methods in the frames) would be bad. Run it
1838 // here. TODO: clean up.
1839 if (thread != nullptr) {
1840 ScopedObjectAccessUnchecked soa(self);
1841 Thread* this_thread = const_cast<Thread*>(thread);
1842 Closure* flip_func = this_thread->GetFlipFunction();
1843 if (flip_func != nullptr) {
1844 flip_func->Run(this_thread);
1845 }
1846 }
1847
Mathieu Chartierc7a966d2014-04-10 18:06:32 -07001848 // Don't do this if we are aborting since the GC may have all the threads suspended. This will
1849 // cause ScopedObjectAccessUnchecked to deadlock.
Nicolas Geoffraydb978712014-12-09 13:33:38 +00001850 if (gAborting == 0 && self != nullptr && thread != nullptr && thread->tlsPtr_.opeer != nullptr) {
Ian Rogerscfaa4552012-11-26 21:00:08 -08001851 ScopedObjectAccessUnchecked soa(self);
Andreas Gampe08883de2016-11-08 13:20:52 -08001852 priority = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_priority)
Ian Rogersdd7624d2014-03-14 17:43:00 -07001853 ->GetInt(thread->tlsPtr_.opeer);
Andreas Gampe08883de2016-11-08 13:20:52 -08001854 is_daemon = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_daemon)
Ian Rogersdd7624d2014-03-14 17:43:00 -07001855 ->GetBoolean(thread->tlsPtr_.opeer);
Elliott Hughesd369bb72011-09-12 14:41:14 -07001856
Mathieu Chartier3398c782016-09-30 10:27:43 -07001857 ObjPtr<mirror::Object> thread_group =
Andreas Gampe08883de2016-11-08 13:20:52 -08001858 jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group)
1859 ->GetObject(thread->tlsPtr_.opeer);
Ian Rogers120f1c72012-09-28 17:17:10 -07001860
Dave Allison0aded082013-11-07 13:15:11 -08001861 if (thread_group != nullptr) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001862 ArtField* group_name_field =
Andreas Gampe08883de2016-11-08 13:20:52 -08001863 jni::DecodeArtField(WellKnownClasses::java_lang_ThreadGroup_name);
Mathieu Chartier3398c782016-09-30 10:27:43 -07001864 ObjPtr<mirror::String> group_name_string =
1865 group_name_field->GetObject(thread_group)->AsString();
Dave Allison0aded082013-11-07 13:15:11 -08001866 group_name = (group_name_string != nullptr) ? group_name_string->ToModifiedUtf8() : "<null>";
Elliott Hughesd369bb72011-09-12 14:41:14 -07001867 }
Nicolas Geoffrayfa595882019-08-06 17:40:09 +01001868 } else if (thread != nullptr) {
1869 priority = thread->GetNativePriority();
Elliott Hughesd369bb72011-09-12 14:41:14 -07001870 } else {
Nicolas Geoffrayfa595882019-08-06 17:40:09 +01001871 PaletteStatus status = PaletteSchedGetPriority(tid, &priority);
1872 CHECK(status == PaletteStatus::kOkay || status == PaletteStatus::kCheckErrno);
Elliott Hughesdcc24742011-09-07 14:02:44 -07001873 }
Elliott Hughesd92bec42011-09-02 17:04:36 -07001874
Elliott Hughesabbe07d2012-06-05 17:42:23 -07001875 std::string scheduler_group_name(GetSchedulerGroupName(tid));
Elliott Hughes1bac54f2012-03-16 12:48:31 -07001876 if (scheduler_group_name.empty()) {
1877 scheduler_group_name = "default";
Elliott Hughesd92bec42011-09-02 17:04:36 -07001878 }
1879
Dave Allison0aded082013-11-07 13:15:11 -08001880 if (thread != nullptr) {
Ian Rogersdd7624d2014-03-14 17:43:00 -07001881 os << '"' << *thread->tlsPtr_.name << '"';
Elliott Hughesabbe07d2012-06-05 17:42:23 -07001882 if (is_daemon) {
1883 os << " daemon";
1884 }
1885 os << " prio=" << priority
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001886 << " tid=" << thread->GetThreadId()
Elliott Hughes80537bb2013-01-04 16:37:26 -08001887 << " " << thread->GetState();
1888 if (thread->IsStillStarting()) {
1889 os << " (still starting up)";
1890 }
1891 os << "\n";
Elliott Hughesabbe07d2012-06-05 17:42:23 -07001892 } else {
Elliott Hughes289be852012-06-12 13:57:20 -07001893 os << '"' << ::art::GetThreadName(tid) << '"'
Elliott Hughesabbe07d2012-06-05 17:42:23 -07001894 << " prio=" << priority
Elliott Hughesabbe07d2012-06-05 17:42:23 -07001895 << " (not attached)\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -07001896 }
Elliott Hughesd92bec42011-09-02 17:04:36 -07001897
Dave Allison0aded082013-11-07 13:15:11 -08001898 if (thread != nullptr) {
Andreas Gampe7d42cdd2019-05-31 16:54:46 -07001899 auto suspend_log_fn = [&]() REQUIRES(Locks::thread_suspend_count_lock_) {
1900 os << " | group=\"" << group_name << "\""
1901 << " sCount=" << thread->tls32_.suspend_count
1902 << " dsCount=" << thread->tls32_.debug_suspend_count
1903 << " flags=" << thread->tls32_.state_and_flags.as_struct.flags
1904 << " obj=" << reinterpret_cast<void*>(thread->tlsPtr_.opeer)
1905 << " self=" << reinterpret_cast<const void*>(thread) << "\n";
1906 };
1907 if (Locks::thread_suspend_count_lock_->IsExclusiveHeld(self)) {
1908 Locks::thread_suspend_count_lock_->AssertExclusiveHeld(self); // For annotalysis.
1909 suspend_log_fn();
1910 } else {
1911 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
1912 suspend_log_fn();
1913 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -07001914 }
Elliott Hughes0d39c122012-06-06 16:41:17 -07001915
Elliott Hughesabbe07d2012-06-05 17:42:23 -07001916 os << " | sysTid=" << tid
1917 << " nice=" << getpriority(PRIO_PROCESS, tid)
Elliott Hughes0d39c122012-06-06 16:41:17 -07001918 << " cgrp=" << scheduler_group_name;
Dave Allison0aded082013-11-07 13:15:11 -08001919 if (thread != nullptr) {
Elliott Hughes0d39c122012-06-06 16:41:17 -07001920 int policy;
1921 sched_param sp;
Brian Carlstrom640a1042017-03-20 15:03:42 -07001922#if !defined(__APPLE__)
1923 // b/36445592 Don't use pthread_getschedparam since pthread may have exited.
1924 policy = sched_getscheduler(tid);
1925 if (policy == -1) {
1926 PLOG(WARNING) << "sched_getscheduler(" << tid << ")";
1927 }
1928 int sched_getparam_result = sched_getparam(tid, &sp);
1929 if (sched_getparam_result == -1) {
1930 PLOG(WARNING) << "sched_getparam(" << tid << ", &sp)";
1931 sp.sched_priority = -1;
1932 }
1933#else
Ian Rogersdd7624d2014-03-14 17:43:00 -07001934 CHECK_PTHREAD_CALL(pthread_getschedparam, (thread->tlsPtr_.pthread_self, &policy, &sp),
1935 __FUNCTION__);
Brian Carlstrom640a1042017-03-20 15:03:42 -07001936#endif
Elliott Hughes0d39c122012-06-06 16:41:17 -07001937 os << " sched=" << policy << "/" << sp.sched_priority
Ian Rogersdd7624d2014-03-14 17:43:00 -07001938 << " handle=" << reinterpret_cast<void*>(thread->tlsPtr_.pthread_self);
Elliott Hughes0d39c122012-06-06 16:41:17 -07001939 }
1940 os << "\n";
Elliott Hughesd92bec42011-09-02 17:04:36 -07001941
1942 // Grab the scheduler stats for this thread.
1943 std::string scheduler_stats;
Andreas Gampe43e72432019-05-14 16:15:24 -07001944 if (android::base::ReadFileToString(StringPrintf("/proc/self/task/%d/schedstat", tid),
1945 &scheduler_stats)
Evan Chengd57c51e2018-01-26 15:43:08 +08001946 && !scheduler_stats.empty()) {
1947 scheduler_stats = android::base::Trim(scheduler_stats); // Lose the trailing '\n'.
Elliott Hughesd92bec42011-09-02 17:04:36 -07001948 } else {
1949 scheduler_stats = "0 0 0";
1950 }
1951
Elliott Hughesba0b9c52012-09-20 11:25:12 -07001952 char native_thread_state = '?';
Elliott Hughesd92bec42011-09-02 17:04:36 -07001953 int utime = 0;
1954 int stime = 0;
1955 int task_cpu = 0;
Brian Carlstrom29212012013-09-12 22:18:30 -07001956 GetTaskStats(tid, &native_thread_state, &utime, &stime, &task_cpu);
Elliott Hughesd92bec42011-09-02 17:04:36 -07001957
Elliott Hughesba0b9c52012-09-20 11:25:12 -07001958 os << " | state=" << native_thread_state
1959 << " schedstat=( " << scheduler_stats << " )"
Elliott Hughesd92bec42011-09-02 17:04:36 -07001960 << " utm=" << utime
1961 << " stm=" << stime
Elliott Hughesabbe07d2012-06-05 17:42:23 -07001962 << " core=" << task_cpu
1963 << " HZ=" << sysconf(_SC_CLK_TCK) << "\n";
Dave Allison0aded082013-11-07 13:15:11 -08001964 if (thread != nullptr) {
Ian Rogersdd7624d2014-03-14 17:43:00 -07001965 os << " | stack=" << reinterpret_cast<void*>(thread->tlsPtr_.stack_begin) << "-"
1966 << reinterpret_cast<void*>(thread->tlsPtr_.stack_end) << " stackSize="
1967 << PrettySize(thread->tlsPtr_.stack_size) << "\n";
Mathieu Chartier9db911e2014-06-04 11:23:58 -07001968 // Dump the held mutexes.
1969 os << " | held mutexes=";
1970 for (size_t i = 0; i < kLockLevelCount; ++i) {
1971 if (i != kMonitorLock) {
1972 BaseMutex* mutex = thread->GetHeldMutex(static_cast<LockLevel>(i));
1973 if (mutex != nullptr) {
1974 os << " \"" << mutex->GetName() << "\"";
1975 if (mutex->IsReaderWriterMutex()) {
1976 ReaderWriterMutex* rw_mutex = down_cast<ReaderWriterMutex*>(mutex);
Hans Boehm0882af22017-08-31 15:21:57 -07001977 if (rw_mutex->GetExclusiveOwnerTid() == tid) {
Mathieu Chartier9db911e2014-06-04 11:23:58 -07001978 os << "(exclusive held)";
1979 } else {
Mathieu Chartier9db911e2014-06-04 11:23:58 -07001980 os << "(shared held)";
1981 }
1982 }
1983 }
1984 }
1985 }
1986 os << "\n";
Elliott Hughesabbe07d2012-06-05 17:42:23 -07001987 }
1988}
1989
1990void Thread::DumpState(std::ostream& os) const {
1991 Thread::DumpState(os, this, GetTid());
Elliott Hughesd92bec42011-09-02 17:04:36 -07001992}
1993
Andreas Gampe93104952017-12-13 17:13:15 -08001994struct StackDumpVisitor : public MonitorObjectsStackVisitor {
Hiroshi Yamauchi02f365f2017-02-03 15:06:00 -08001995 StackDumpVisitor(std::ostream& os_in,
1996 Thread* thread_in,
1997 Context* context,
Andreas Gampe93104952017-12-13 17:13:15 -08001998 bool can_allocate,
Hiroshi Yamauchi02f365f2017-02-03 15:06:00 -08001999 bool check_suspended = true,
Andreas Gampe93104952017-12-13 17:13:15 -08002000 bool dump_locks = true)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002001 REQUIRES_SHARED(Locks::mutator_lock_)
Andreas Gampe93104952017-12-13 17:13:15 -08002002 : MonitorObjectsStackVisitor(thread_in,
2003 context,
2004 check_suspended,
2005 can_allocate && dump_locks),
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002006 os(os_in),
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002007 last_method(nullptr),
2008 last_line_number(0),
Andreas Gampe93104952017-12-13 17:13:15 -08002009 repetition_count(0) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07002010
Ian Rogersbdb03912011-09-14 00:55:44 -07002011 virtual ~StackDumpVisitor() {
Elliott Hughese85d2e92012-05-01 14:02:10 -07002012 if (frame_count == 0) {
2013 os << " (no managed stack frames)\n";
2014 }
Elliott Hughesd369bb72011-09-12 14:41:14 -07002015 }
2016
Andreas Gampe93104952017-12-13 17:13:15 -08002017 static constexpr size_t kMaxRepetition = 3u;
2018
2019 VisitMethodResult StartMethod(ArtMethod* m, size_t frame_nr ATTRIBUTE_UNUSED)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002020 override
Andreas Gampe93104952017-12-13 17:13:15 -08002021 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe542451c2016-07-26 09:02:02 -07002022 m = m->GetInterfaceMethodIfProxy(kRuntimePointerSize);
Vladimir Marko813a8632018-11-29 16:17:01 +00002023 ObjPtr<mirror::DexCache> dex_cache = m->GetDexCache();
Ian Rogersb861dc02011-11-14 17:00:05 -08002024 int line_number = -1;
Dave Allison0aded082013-11-07 13:15:11 -08002025 if (dex_cache != nullptr) { // be tolerant of bad input
David Sehr9323e6e2016-09-13 08:58:35 -07002026 const DexFile* dex_file = dex_cache->GetDexFile();
2027 line_number = annotations::GetLineNumFromPC(dex_file, m, GetDexPc(false));
Ian Rogersb861dc02011-11-14 17:00:05 -08002028 }
Ian Rogers28ad40d2011-10-27 15:19:26 -07002029 if (line_number == last_line_number && last_method == m) {
Dave Allison0aded082013-11-07 13:15:11 -08002030 ++repetition_count;
Elliott Hughesd369bb72011-09-12 14:41:14 -07002031 } else {
Ian Rogers28ad40d2011-10-27 15:19:26 -07002032 if (repetition_count >= kMaxRepetition) {
2033 os << " ... repeated " << (repetition_count - kMaxRepetition) << " times\n";
2034 }
2035 repetition_count = 0;
2036 last_line_number = line_number;
2037 last_method = m;
Elliott Hughesd369bb72011-09-12 14:41:14 -07002038 }
Andreas Gampe93104952017-12-13 17:13:15 -08002039
2040 if (repetition_count >= kMaxRepetition) {
2041 // Skip visiting=printing anything.
2042 return VisitMethodResult::kSkipMethod;
Ian Rogers28ad40d2011-10-27 15:19:26 -07002043 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -07002044
Andreas Gampe93104952017-12-13 17:13:15 -08002045 os << " at " << m->PrettyMethod(false);
2046 if (m->IsNative()) {
2047 os << "(Native method)";
2048 } else {
2049 const char* source_file(m->GetDeclaringClassSourceFile());
2050 os << "(" << (source_file != nullptr ? source_file : "unavailable")
2051 << ":" << line_number << ")";
2052 }
2053 os << "\n";
2054 // Go and visit locks.
2055 return VisitMethodResult::kContinueMethod;
Elliott Hughesd369bb72011-09-12 14:41:14 -07002056 }
Elliott Hughes4993bbc2013-01-10 15:41:25 -08002057
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002058 VisitMethodResult EndMethod(ArtMethod* m ATTRIBUTE_UNUSED) override {
Andreas Gampe93104952017-12-13 17:13:15 -08002059 return VisitMethodResult::kContinueMethod;
2060 }
2061
Vladimir Markof52d92f2019-03-29 12:33:02 +00002062 void VisitWaitingObject(ObjPtr<mirror::Object> obj, ThreadState state ATTRIBUTE_UNUSED)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002063 override
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002064 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe93104952017-12-13 17:13:15 -08002065 PrintObject(obj, " - waiting on ", ThreadList::kInvalidThreadId);
2066 }
Vladimir Markof52d92f2019-03-29 12:33:02 +00002067 void VisitSleepingObject(ObjPtr<mirror::Object> obj)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002068 override
Andreas Gampe93104952017-12-13 17:13:15 -08002069 REQUIRES_SHARED(Locks::mutator_lock_) {
2070 PrintObject(obj, " - sleeping on ", ThreadList::kInvalidThreadId);
2071 }
Vladimir Markof52d92f2019-03-29 12:33:02 +00002072 void VisitBlockedOnObject(ObjPtr<mirror::Object> obj,
Andreas Gampe93104952017-12-13 17:13:15 -08002073 ThreadState state,
2074 uint32_t owner_tid)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002075 override
Andreas Gampe93104952017-12-13 17:13:15 -08002076 REQUIRES_SHARED(Locks::mutator_lock_) {
2077 const char* msg;
2078 switch (state) {
2079 case kBlocked:
2080 msg = " - waiting to lock ";
2081 break;
2082
2083 case kWaitingForLockInflation:
2084 msg = " - waiting for lock inflation of ";
2085 break;
2086
2087 default:
2088 LOG(FATAL) << "Unreachable";
2089 UNREACHABLE();
2090 }
2091 PrintObject(obj, msg, owner_tid);
2092 }
Vladimir Markof52d92f2019-03-29 12:33:02 +00002093 void VisitLockedObject(ObjPtr<mirror::Object> obj)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002094 override
Andreas Gampe93104952017-12-13 17:13:15 -08002095 REQUIRES_SHARED(Locks::mutator_lock_) {
2096 PrintObject(obj, " - locked ", ThreadList::kInvalidThreadId);
2097 }
2098
Vladimir Markof52d92f2019-03-29 12:33:02 +00002099 void PrintObject(ObjPtr<mirror::Object> obj,
Andreas Gampe93104952017-12-13 17:13:15 -08002100 const char* msg,
2101 uint32_t owner_tid) REQUIRES_SHARED(Locks::mutator_lock_) {
2102 if (obj == nullptr) {
2103 os << msg << "an unknown object";
Ian Rogersd803bc72014-04-01 15:33:03 -07002104 } else {
Andreas Gampe93104952017-12-13 17:13:15 -08002105 if ((obj->GetLockWord(true).GetState() == LockWord::kThinLocked) &&
Ian Rogersd803bc72014-04-01 15:33:03 -07002106 Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) {
2107 // Getting the identity hashcode here would result in lock inflation and suspension of the
2108 // current thread, which isn't safe if this is the only runnable thread.
Andreas Gampe93104952017-12-13 17:13:15 -08002109 os << msg << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
Vladimir Markof52d92f2019-03-29 12:33:02 +00002110 reinterpret_cast<intptr_t>(obj.Ptr()),
Andreas Gampe93104952017-12-13 17:13:15 -08002111 obj->PrettyTypeOf().c_str());
Ian Rogersd803bc72014-04-01 15:33:03 -07002112 } else {
Andreas Gampe93104952017-12-13 17:13:15 -08002113 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
2114 // Call PrettyTypeOf before IdentityHashCode since IdentityHashCode can cause thread
2115 // suspension and move pretty_object.
2116 const std::string pretty_type(obj->PrettyTypeOf());
2117 os << msg << StringPrintf("<0x%08x> (a %s)", obj->IdentityHashCode(), pretty_type.c_str());
Ian Rogersd803bc72014-04-01 15:33:03 -07002118 }
2119 }
Andreas Gampe93104952017-12-13 17:13:15 -08002120 if (owner_tid != ThreadList::kInvalidThreadId) {
2121 os << " held by thread " << owner_tid;
2122 }
Ian Rogersd803bc72014-04-01 15:33:03 -07002123 os << "\n";
Elliott Hughes4993bbc2013-01-10 15:41:25 -08002124 }
2125
Elliott Hughes08fc03a2012-06-26 17:34:00 -07002126 std::ostream& os;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002127 ArtMethod* last_method;
Ian Rogers28ad40d2011-10-27 15:19:26 -07002128 int last_line_number;
Andreas Gampe93104952017-12-13 17:13:15 -08002129 size_t repetition_count;
Elliott Hughesd369bb72011-09-12 14:41:14 -07002130};
2131
Ian Rogers33e95662013-05-20 20:29:14 -07002132static bool ShouldShowNativeStack(const Thread* thread)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002133 REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughesaef701d2013-04-05 18:15:40 -07002134 ThreadState state = thread->GetState();
2135
2136 // In native code somewhere in the VM (one of the kWaitingFor* states)? That's interesting.
2137 if (state > kWaiting && state < kStarting) {
2138 return true;
2139 }
2140
2141 // In an Object.wait variant or Thread.sleep? That's not interesting.
2142 if (state == kTimedWaiting || state == kSleeping || state == kWaiting) {
2143 return false;
2144 }
2145
Christopher Ferris2366f4e2014-09-19 17:23:59 -07002146 // Threads with no managed stack frames should be shown.
Vladimir Markoe7441632017-11-29 13:00:56 +00002147 if (!thread->HasManagedStack()) {
Christopher Ferris2366f4e2014-09-19 17:23:59 -07002148 return true;
2149 }
2150
Elliott Hughesaef701d2013-04-05 18:15:40 -07002151 // In some other native method? That's interesting.
2152 // We don't just check kNative because native methods will be in state kSuspended if they're
2153 // calling back into the VM, or kBlocked if they're blocked on a monitor, or one of the
2154 // thread-startup states if it's early enough in their life cycle (http://b/7432159).
Mathieu Chartiere401d142015-04-22 13:56:20 -07002155 ArtMethod* current_method = thread->GetCurrentMethod(nullptr);
Dave Allison0aded082013-11-07 13:15:11 -08002156 return current_method != nullptr && current_method->IsNative();
Elliott Hughesaef701d2013-04-05 18:15:40 -07002157}
2158
Hiroshi Yamauchi02f365f2017-02-03 15:06:00 -08002159void Thread::DumpJavaStack(std::ostream& os, bool check_suspended, bool dump_locks) const {
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002160 // If flip_function is not null, it means we have run a checkpoint
2161 // before the thread wakes up to execute the flip function and the
2162 // thread roots haven't been forwarded. So the following access to
2163 // the roots (locks or methods in the frames) would be bad. Run it
2164 // here. TODO: clean up.
2165 {
2166 Thread* this_thread = const_cast<Thread*>(this);
2167 Closure* flip_func = this_thread->GetFlipFunction();
2168 if (flip_func != nullptr) {
2169 flip_func->Run(this_thread);
2170 }
2171 }
2172
Andreas Gampe986c6fb2014-10-02 21:00:06 -07002173 // Dumping the Java stack involves the verifier for locks. The verifier operates under the
2174 // assumption that there is no exception pending on entry. Thus, stash any pending exception.
Mathieu Chartierbef89c92015-01-09 09:46:49 -08002175 // Thread::Current() instead of this in case a thread is dumping the stack of another suspended
2176 // thread.
Alex Lightb7c640d2019-03-20 15:52:13 -07002177 ScopedExceptionStorage ses(Thread::Current());
Andreas Gampe986c6fb2014-10-02 21:00:06 -07002178
Ian Rogers700a4022014-05-19 16:49:03 -07002179 std::unique_ptr<Context> context(Context::Create());
Mathieu Chartierc751fdc2014-03-30 15:25:44 -07002180 StackDumpVisitor dumper(os, const_cast<Thread*>(this), context.get(),
Hiroshi Yamauchi02f365f2017-02-03 15:06:00 -08002181 !tls32_.throwing_OutOfMemoryError, check_suspended, dump_locks);
Mathieu Chartierc751fdc2014-03-30 15:25:44 -07002182 dumper.WalkStack();
2183}
2184
Nicolas Geoffray6ee49712018-03-30 14:39:05 +00002185void Thread::DumpStack(std::ostream& os,
2186 bool dump_native_stack,
2187 BacktraceMap* backtrace_map,
2188 bool force_dump_stack) const {
Jeff Haoed1790e2013-04-12 09:58:14 -07002189 // TODO: we call this code when dying but may not have suspended the thread ourself. The
2190 // IsSuspended check is therefore racy with the use for dumping (normally we inhibit
2191 // the race with the thread_suspend_count_lock_).
Ian Rogerseef2e542014-06-24 22:48:01 -07002192 bool dump_for_abort = (gAborting > 0);
2193 bool safe_to_dump = (this == Thread::Current() || IsSuspended());
2194 if (!kIsDebugBuild) {
2195 // We always want to dump the stack for an abort, however, there is no point dumping another
2196 // thread's stack in debug builds where we'll hit the not suspended check in the stack walk.
2197 safe_to_dump = (safe_to_dump || dump_for_abort);
2198 }
Hiroshi Yamauchi13c16352017-01-31 10:15:08 -08002199 if (safe_to_dump || force_dump_stack) {
Ian Rogersf08e4732013-04-09 09:45:49 -07002200 // If we're currently in native code, dump that stack before dumping the managed stack.
Nicolas Geoffray6ee49712018-03-30 14:39:05 +00002201 if (dump_native_stack && (dump_for_abort || force_dump_stack || ShouldShowNativeStack(this))) {
Hiroshi Yamauchi02f365f2017-02-03 15:06:00 -08002202 ArtMethod* method =
2203 GetCurrentMethod(nullptr,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002204 /*check_suspended=*/ !force_dump_stack,
2205 /*abort_on_error=*/ !(dump_for_abort || force_dump_stack));
Christopher Ferris6cff48f2014-01-26 21:36:13 -08002206 DumpNativeStack(os, GetTid(), backtrace_map, " native: ", method);
Ian Rogersf08e4732013-04-09 09:45:49 -07002207 }
Hiroshi Yamauchi02f365f2017-02-03 15:06:00 -08002208 DumpJavaStack(os,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07002209 /*check_suspended=*/ !force_dump_stack,
2210 /*dump_locks=*/ !force_dump_stack);
Ian Rogersf08e4732013-04-09 09:45:49 -07002211 } else {
2212 os << "Not able to dump stack of thread that isn't suspended";
Elliott Hughesffb465f2012-03-01 18:46:05 -08002213 }
Elliott Hughese27955c2011-08-26 15:21:24 -07002214}
2215
Elliott Hughesbe759c62011-09-08 19:38:21 -07002216void Thread::ThreadExitCallback(void* arg) {
2217 Thread* self = reinterpret_cast<Thread*>(arg);
Ian Rogersdd7624d2014-03-14 17:43:00 -07002218 if (self->tls32_.thread_exit_check_count == 0) {
2219 LOG(WARNING) << "Native thread exiting without having called DetachCurrentThread (maybe it's "
2220 "going to use a pthread_key_create destructor?): " << *self;
Ian Rogers0878d652013-04-18 17:38:35 -07002221 CHECK(is_started_);
Andreas Gampea47a6e82019-07-24 09:46:16 -07002222#ifdef __BIONIC__
Andreas Gampe4382f1e2015-08-05 01:08:53 +00002223 __get_tls()[TLS_SLOT_ART_THREAD_SELF] = self;
2224#else
Elliott Hughes6a607ad2012-07-13 20:40:00 -07002225 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, self), "reattach self");
Andreas Gampe82372002019-07-24 15:42:09 -07002226 Thread::self_tls_ = self;
Andreas Gampe4382f1e2015-08-05 01:08:53 +00002227#endif
Ian Rogersdd7624d2014-03-14 17:43:00 -07002228 self->tls32_.thread_exit_check_count = 1;
Elliott Hughes6a607ad2012-07-13 20:40:00 -07002229 } else {
2230 LOG(FATAL) << "Native thread exited without calling DetachCurrentThread: " << *self;
2231 }
Carl Shapirob5573532011-07-12 18:22:59 -07002232}
2233
Elliott Hughesbe759c62011-09-08 19:38:21 -07002234void Thread::Startup() {
Ian Rogers0878d652013-04-18 17:38:35 -07002235 CHECK(!is_started_);
2236 is_started_ = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002237 {
Brian Carlstrom6d69f592013-07-16 17:18:16 -07002238 // MutexLock to keep annotalysis happy.
2239 //
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002240 // Note we use null for the thread because Thread::Current can
Brian Carlstrom6d69f592013-07-16 17:18:16 -07002241 // return garbage since (is_started_ == true) and
2242 // Thread::pthread_key_self_ is not yet initialized.
2243 // This was seen on glibc.
Dave Allison0aded082013-11-07 13:15:11 -08002244 MutexLock mu(nullptr, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -07002245 resume_cond_ = new ConditionVariable("Thread resumption condition variable",
2246 *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002247 }
2248
Carl Shapirob5573532011-07-12 18:22:59 -07002249 // Allocate a TLS slot.
Ian Rogersf4d4da12014-11-11 16:10:33 -08002250 CHECK_PTHREAD_CALL(pthread_key_create, (&Thread::pthread_key_self_, Thread::ThreadExitCallback),
2251 "self key");
Carl Shapirob5573532011-07-12 18:22:59 -07002252
2253 // Double-check the TLS slot allocation.
Dave Allison0aded082013-11-07 13:15:11 -08002254 if (pthread_getspecific(pthread_key_self_) != nullptr) {
2255 LOG(FATAL) << "Newly-created pthread TLS slot is not nullptr";
Carl Shapirob5573532011-07-12 18:22:59 -07002256 }
Andreas Gampe82372002019-07-24 15:42:09 -07002257#ifndef __BIONIC__
2258 CHECK(Thread::self_tls_ == nullptr);
2259#endif
Elliott Hughes038a8062011-09-18 14:12:41 -07002260}
Carl Shapirob5573532011-07-12 18:22:59 -07002261
Elliott Hughes038a8062011-09-18 14:12:41 -07002262void Thread::FinishStartup() {
Ian Rogers365c1022012-06-22 15:05:28 -07002263 Runtime* runtime = Runtime::Current();
2264 CHECK(runtime->IsStarted());
Brian Carlstromb82b6872011-10-26 17:18:07 -07002265
Elliott Hughes01158d72011-09-19 19:47:10 -07002266 // Finish attaching the main thread.
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002267 ScopedObjectAccess soa(Thread::Current());
Vladimir Markodcfcce42018-06-27 10:00:28 +00002268 soa.Self()->CreatePeer("main", false, runtime->GetMainThreadGroup());
2269 soa.Self()->AssertNoPendingException();
Jesse Wilson9a6bae82011-11-14 14:57:30 -05002270
Vladimir Markodcfcce42018-06-27 10:00:28 +00002271 runtime->RunRootClinits(soa.Self());
Andreas Gampe21cf95d2017-04-17 20:19:14 -07002272
2273 // The thread counts as started from now on. We need to add it to the ThreadGroup. For regular
2274 // threads, this is done in Thread.start() on the Java side.
Vladimir Markodcfcce42018-06-27 10:00:28 +00002275 soa.Self()->NotifyThreadGroup(soa, runtime->GetMainThreadGroup());
2276 soa.Self()->AssertNoPendingException();
Carl Shapirob5573532011-07-12 18:22:59 -07002277}
2278
Elliott Hughesc1674ed2011-08-25 18:09:09 -07002279void Thread::Shutdown() {
Ian Rogers0878d652013-04-18 17:38:35 -07002280 CHECK(is_started_);
2281 is_started_ = false;
Elliott Hughes8d768a92011-09-14 16:35:25 -07002282 CHECK_PTHREAD_CALL(pthread_key_delete, (Thread::pthread_key_self_), "self key");
Ian Rogers33e95662013-05-20 20:29:14 -07002283 MutexLock mu(Thread::Current(), *Locks::thread_suspend_count_lock_);
Dave Allison0aded082013-11-07 13:15:11 -08002284 if (resume_cond_ != nullptr) {
Ian Rogers0878d652013-04-18 17:38:35 -07002285 delete resume_cond_;
Dave Allison0aded082013-11-07 13:15:11 -08002286 resume_cond_ = nullptr;
Ian Rogers0878d652013-04-18 17:38:35 -07002287 }
Elliott Hughesc1674ed2011-08-25 18:09:09 -07002288}
2289
Andreas Gampe56776012018-01-26 17:40:55 -08002290void Thread::NotifyThreadGroup(ScopedObjectAccessAlreadyRunnable& soa, jobject thread_group) {
2291 ScopedLocalRef<jobject> thread_jobject(
2292 soa.Env(), soa.Env()->AddLocalReference<jobject>(Thread::Current()->GetPeer()));
2293 ScopedLocalRef<jobject> thread_group_jobject_scoped(
2294 soa.Env(), nullptr);
2295 jobject thread_group_jobject = thread_group;
2296 if (thread_group == nullptr || kIsDebugBuild) {
2297 // There is always a group set. Retrieve it.
2298 thread_group_jobject_scoped.reset(
2299 soa.Env()->GetObjectField(thread_jobject.get(),
2300 WellKnownClasses::java_lang_Thread_group));
2301 thread_group_jobject = thread_group_jobject_scoped.get();
2302 if (kIsDebugBuild && thread_group != nullptr) {
2303 CHECK(soa.Env()->IsSameObject(thread_group, thread_group_jobject));
2304 }
2305 }
2306 soa.Env()->CallNonvirtualVoidMethod(thread_group_jobject,
2307 WellKnownClasses::java_lang_ThreadGroup,
2308 WellKnownClasses::java_lang_ThreadGroup_add,
2309 thread_jobject.get());
2310}
2311
Calin Juravleccd56952016-12-15 17:57:38 +00002312Thread::Thread(bool daemon)
2313 : tls32_(daemon),
2314 wait_monitor_(nullptr),
Alex Lightcea42152018-09-18 22:51:55 +00002315 is_runtime_thread_(false) {
Charles Mungerc665d632018-11-06 16:20:13 +00002316 wait_mutex_ = new Mutex("a thread wait mutex", LockLevel::kThreadWaitLock);
Ian Rogersdd7624d2014-03-14 17:43:00 -07002317 wait_cond_ = new ConditionVariable("a thread wait condition variable", *wait_mutex_);
Nicolas Geoffraye91e7952020-01-23 10:15:56 +00002318 tlsPtr_.instrumentation_stack =
2319 new std::map<uintptr_t, instrumentation::InstrumentationStackFrame>;
Ian Rogersdd7624d2014-03-14 17:43:00 -07002320 tlsPtr_.name = new std::string(kThreadNameDuringStartup);
2321
Roland Levillain33d69032015-06-18 18:20:59 +01002322 static_assert((sizeof(Thread) % 4) == 0U,
2323 "art::Thread has a size which is not a multiple of 4.");
Ian Rogersdd7624d2014-03-14 17:43:00 -07002324 tls32_.state_and_flags.as_struct.flags = 0;
2325 tls32_.state_and_flags.as_struct.state = kNative;
Orion Hodson88591fe2018-03-06 13:35:43 +00002326 tls32_.interrupted.store(false, std::memory_order_relaxed);
Charles Mungeraa31f492018-11-01 18:57:38 +00002327 // Initialize with no permit; if the java Thread was unparked before being
2328 // started, it will unpark itself before calling into java code.
2329 tls32_.park_state_.store(kNoPermit, std::memory_order_relaxed);
Ian Rogersdd7624d2014-03-14 17:43:00 -07002330 memset(&tlsPtr_.held_mutexes[0], 0, sizeof(tlsPtr_.held_mutexes));
Mathieu Chartier0651d412014-04-29 14:37:57 -07002331 std::fill(tlsPtr_.rosalloc_runs,
Hiroshi Yamauchi7ed9c562016-02-02 15:22:09 -08002332 tlsPtr_.rosalloc_runs + kNumRosAllocThreadLocalSizeBracketsInThread,
Mathieu Chartier73d1e172014-04-11 17:53:48 -07002333 gc::allocator::RosAlloc::GetDedicatedFullRun());
Mathieu Chartier952e1e32016-06-13 14:04:02 -07002334 tlsPtr_.checkpoint_function = nullptr;
Yu Lieac44242015-06-29 10:50:03 +08002335 for (uint32_t i = 0; i < kMaxSuspendBarriers; ++i) {
2336 tlsPtr_.active_suspend_barriers[i] = nullptr;
2337 }
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002338 tlsPtr_.flip_function = nullptr;
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07002339 tlsPtr_.thread_local_mark_stack = nullptr;
Hiroshi Yamauchiee235822016-08-19 17:03:27 -07002340 tls32_.is_transitioning_to_runnable = false;
David Srbecky28f6cff2018-10-16 15:07:28 +01002341 tls32_.use_mterp = false;
Mathieu Chartierc4bf6672020-01-13 13:07:16 -08002342 ResetTlab();
David Srbecky28f6cff2018-10-16 15:07:28 +01002343}
2344
2345void Thread::NotifyInTheadList() {
2346 tls32_.use_mterp = interpreter::CanUseMterp();
Elliott Hughesdcc24742011-09-07 14:02:44 -07002347}
2348
Alex Lighte9f61032018-09-24 16:04:51 -07002349bool Thread::CanLoadClasses() const {
2350 return !IsRuntimeThread() || !Runtime::Current()->IsJavaDebuggable();
2351}
2352
Elliott Hughes7dc51662012-05-16 14:48:43 -07002353bool Thread::IsStillStarting() const {
2354 // You might think you can check whether the state is kStarting, but for much of thread startup,
Elliott Hughes80537bb2013-01-04 16:37:26 -08002355 // the thread is in kNative; it might also be in kVmWait.
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002356 // 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 -07002357 // assigned fairly early on, and needs to be.
2358 // It turns out that the last thing to change is the thread name; that's a good proxy for "has
2359 // this thread _ever_ entered kRunnable".
Ian Rogersdd7624d2014-03-14 17:43:00 -07002360 return (tlsPtr_.jpeer == nullptr && tlsPtr_.opeer == nullptr) ||
2361 (*tlsPtr_.name == kThreadNameDuringStartup);
Elliott Hughes7dc51662012-05-16 14:48:43 -07002362}
2363
Andreas Gamped9efea62014-07-21 22:56:08 -07002364void Thread::AssertPendingException() const {
Mathieu Chartiera61894d2015-04-23 16:32:54 -07002365 CHECK(IsExceptionPending()) << "Pending exception expected.";
2366}
2367
2368void Thread::AssertPendingOOMException() const {
2369 AssertPendingException();
2370 auto* e = GetException();
2371 CHECK_EQ(e->GetClass(), DecodeJObject(WellKnownClasses::java_lang_OutOfMemoryError)->AsClass())
2372 << e->Dump();
Andreas Gamped9efea62014-07-21 22:56:08 -07002373}
2374
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002375void Thread::AssertNoPendingException() const {
2376 if (UNLIKELY(IsExceptionPending())) {
2377 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierf5769e12017-01-10 15:54:41 -08002378 LOG(FATAL) << "No pending exception expected: " << GetException()->Dump();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002379 }
2380}
2381
Mathieu Chartier8d7672e2014-02-25 10:57:16 -08002382void Thread::AssertNoPendingExceptionForNewException(const char* msg) const {
2383 if (UNLIKELY(IsExceptionPending())) {
2384 ScopedObjectAccess soa(Thread::Current());
Ian Rogersc114b5f2014-07-21 08:55:01 -07002385 LOG(FATAL) << "Throwing new exception '" << msg << "' with unexpected pending exception: "
Mathieu Chartierf5769e12017-01-10 15:54:41 -08002386 << GetException()->Dump();
Mathieu Chartier8d7672e2014-02-25 10:57:16 -08002387 }
2388}
2389
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002390class MonitorExitVisitor : public SingleRootVisitor {
2391 public:
2392 explicit MonitorExitVisitor(Thread* self) : self_(self) { }
2393
2394 // NO_THREAD_SAFETY_ANALYSIS due to MonitorExit.
2395 void VisitRoot(mirror::Object* entered_monitor, const RootInfo& info ATTRIBUTE_UNUSED)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01002396 override NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002397 if (self_->HoldsLock(entered_monitor)) {
2398 LOG(WARNING) << "Calling MonitorExit on object "
David Sehr709b0702016-10-13 09:12:37 -07002399 << entered_monitor << " (" << entered_monitor->PrettyTypeOf() << ")"
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002400 << " left locked by native thread "
2401 << *Thread::Current() << " which is detaching";
2402 entered_monitor->MonitorExit(self_);
2403 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002404 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002405
2406 private:
2407 Thread* const self_;
2408};
Elliott Hughes02b48d12011-09-07 17:15:51 -07002409
Elliott Hughesc0f09332012-03-26 13:27:06 -07002410void Thread::Destroy() {
Ian Rogers120f1c72012-09-28 17:17:10 -07002411 Thread* self = this;
2412 DCHECK_EQ(self, Thread::Current());
Elliott Hughes02b48d12011-09-07 17:15:51 -07002413
Ian Rogers68d8b422014-07-17 11:09:10 -07002414 if (tlsPtr_.jni_env != nullptr) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002415 {
2416 ScopedObjectAccess soa(self);
2417 MonitorExitVisitor visitor(self);
2418 // On thread detach, all monitors entered with JNI MonitorEnter are automatically exited.
Ian Rogers55256cb2017-12-21 17:07:11 -08002419 tlsPtr_.jni_env->monitors_.VisitRoots(&visitor, RootInfo(kRootVMInternal));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07002420 }
Ian Rogers68d8b422014-07-17 11:09:10 -07002421 // Release locally held global references which releasing may require the mutator lock.
2422 if (tlsPtr_.jpeer != nullptr) {
2423 // If pthread_create fails we don't have a jni env here.
2424 tlsPtr_.jni_env->DeleteGlobalRef(tlsPtr_.jpeer);
2425 tlsPtr_.jpeer = nullptr;
2426 }
2427 if (tlsPtr_.class_loader_override != nullptr) {
2428 tlsPtr_.jni_env->DeleteGlobalRef(tlsPtr_.class_loader_override);
2429 tlsPtr_.class_loader_override = nullptr;
2430 }
2431 }
2432
Ian Rogersdd7624d2014-03-14 17:43:00 -07002433 if (tlsPtr_.opeer != nullptr) {
Ian Rogerscfaa4552012-11-26 21:00:08 -08002434 ScopedObjectAccess soa(self);
Ian Rogers120f1c72012-09-28 17:17:10 -07002435 // We may need to call user-supplied managed code, do this before final clean-up.
Ian Rogerscfaa4552012-11-26 21:00:08 -08002436 HandleUncaughtExceptions(soa);
Alex Lightdf132402017-09-29 12:54:33 -07002437 RemoveFromThreadGroup(soa);
Alex Light8c5e2da2017-07-11 10:32:20 -07002438 Runtime* runtime = Runtime::Current();
2439 if (runtime != nullptr) {
2440 runtime->GetRuntimeCallbacks()->ThreadDeath(self);
2441 }
Elliott Hughes534da072012-03-27 15:17:42 -07002442
Anwar Ghuloum3c50a4b2013-06-21 13:05:23 -07002443 // this.nativePeer = 0;
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002444 if (Runtime::Current()->IsActiveTransaction()) {
Andreas Gampe08883de2016-11-08 13:20:52 -08002445 jni::DecodeArtField(WellKnownClasses::java_lang_Thread_nativePeer)
Ian Rogersdd7624d2014-03-14 17:43:00 -07002446 ->SetLong<true>(tlsPtr_.opeer, 0);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002447 } else {
Andreas Gampe08883de2016-11-08 13:20:52 -08002448 jni::DecodeArtField(WellKnownClasses::java_lang_Thread_nativePeer)
Ian Rogersdd7624d2014-03-14 17:43:00 -07002449 ->SetLong<false>(tlsPtr_.opeer, 0);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002450 }
Elliott Hughes02b48d12011-09-07 17:15:51 -07002451
Ian Rogerscfaa4552012-11-26 21:00:08 -08002452 // Thread.join() is implemented as an Object.wait() on the Thread.lock object. Signal anyone
2453 // who is waiting.
Mathieu Chartier3398c782016-09-30 10:27:43 -07002454 ObjPtr<mirror::Object> lock =
Andreas Gampe08883de2016-11-08 13:20:52 -08002455 jni::DecodeArtField(WellKnownClasses::java_lang_Thread_lock)->GetObject(tlsPtr_.opeer);
Elliott Hughes038a8062011-09-18 14:12:41 -07002456 // (This conditional is only needed for tests, where Thread.lock won't have been set.)
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002457 if (lock != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002458 StackHandleScope<1> hs(self);
2459 Handle<mirror::Object> h_obj(hs.NewHandle(lock));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002460 ObjectLock<mirror::Object> locker(self, h_obj);
Yevgeny Rouban63e8a682014-04-16 18:26:09 +07002461 locker.NotifyAll();
Elliott Hughes5f791332011-09-15 17:45:30 -07002462 }
Ian Rogers68d8b422014-07-17 11:09:10 -07002463 tlsPtr_.opeer = nullptr;
Elliott Hughes5f791332011-09-15 17:45:30 -07002464 }
Ian Rogers120f1c72012-09-28 17:17:10 -07002465
Hiroshi Yamauchia1b94c62014-12-17 15:49:56 -08002466 {
2467 ScopedObjectAccess soa(self);
2468 Runtime::Current()->GetHeap()->RevokeThreadLocalBuffers(this);
Lokesh Gidra93170312019-12-04 13:46:11 -08002469 }
2470 // Mark-stack revocation must be performed at the very end. No
2471 // checkpoint/flip-function or read-barrier should be called after this.
2472 if (kUseReadBarrier) {
2473 Runtime::Current()->GetHeap()->ConcurrentCopyingCollector()->RevokeThreadLocalMarkStack(this);
Hiroshi Yamauchia1b94c62014-12-17 15:49:56 -08002474 }
Elliott Hughesc0f09332012-03-26 13:27:06 -07002475}
Elliott Hughes02b48d12011-09-07 17:15:51 -07002476
Elliott Hughesc0f09332012-03-26 13:27:06 -07002477Thread::~Thread() {
Ian Rogers68d8b422014-07-17 11:09:10 -07002478 CHECK(tlsPtr_.class_loader_override == nullptr);
2479 CHECK(tlsPtr_.jpeer == nullptr);
2480 CHECK(tlsPtr_.opeer == nullptr);
Ian Rogersdd7624d2014-03-14 17:43:00 -07002481 bool initialized = (tlsPtr_.jni_env != nullptr); // Did Thread::Init run?
Alexei Zavjalov1efa0a92014-02-04 02:08:31 +07002482 if (initialized) {
Ian Rogersdd7624d2014-03-14 17:43:00 -07002483 delete tlsPtr_.jni_env;
2484 tlsPtr_.jni_env = nullptr;
Alexei Zavjalov1efa0a92014-02-04 02:08:31 +07002485 }
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002486 CHECK_NE(GetState(), kRunnable);
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07002487 CHECK(!ReadFlag(kCheckpointRequest));
2488 CHECK(!ReadFlag(kEmptyCheckpointRequest));
Mathieu Chartier952e1e32016-06-13 14:04:02 -07002489 CHECK(tlsPtr_.checkpoint_function == nullptr);
2490 CHECK_EQ(checkpoint_overflow_.size(), 0u);
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08002491 CHECK(tlsPtr_.flip_function == nullptr);
Hiroshi Yamauchiee235822016-08-19 17:03:27 -07002492 CHECK_EQ(tls32_.is_transitioning_to_runnable, false);
Dave Allison0aded082013-11-07 13:15:11 -08002493
Sebastien Hertz07474662015-08-25 15:12:33 +00002494 // Make sure we processed all deoptimization requests.
2495 CHECK(tlsPtr_.deoptimization_context_stack == nullptr) << "Missed deoptimization";
Mingyao Yang99170c62015-07-06 11:10:37 -07002496 CHECK(tlsPtr_.frame_id_to_shadow_frame == nullptr) <<
2497 "Not all deoptimized frames have been consumed by the debugger.";
Sebastien Hertz07474662015-08-25 15:12:33 +00002498
Mathieu Chartierdbe6f462012-09-25 16:54:50 -07002499 // We may be deleting a still born thread.
2500 SetStateUnsafe(kTerminated);
Elliott Hughes85d15452011-09-16 17:33:01 -07002501
2502 delete wait_cond_;
2503 delete wait_mutex_;
2504
Ian Rogersdd7624d2014-03-14 17:43:00 -07002505 if (tlsPtr_.long_jump_context != nullptr) {
2506 delete tlsPtr_.long_jump_context;
Ian Rogersc928de92013-02-27 14:30:44 -08002507 }
Elliott Hughes475fc232011-10-25 15:00:35 -07002508
Alexei Zavjalov1efa0a92014-02-04 02:08:31 +07002509 if (initialized) {
2510 CleanupCpu();
2511 }
2512
Ulyana Trafimoviche886d682020-07-16 15:09:38 +00002513 if (tlsPtr_.simulator != nullptr) {
2514 delete tlsPtr_.simulator;
2515 }
2516
Ian Rogersdd7624d2014-03-14 17:43:00 -07002517 delete tlsPtr_.instrumentation_stack;
2518 delete tlsPtr_.name;
Nicolas Geoffray340dafa2016-11-18 16:03:10 +00002519 delete tlsPtr_.deps_or_stack_trace_sample.stack_trace_sample;
Elliott Hughesd8af1592012-04-16 20:40:15 -07002520
Ian Rogers68d8b422014-07-17 11:09:10 -07002521 Runtime::Current()->GetHeap()->AssertThreadLocalBuffersAreRevoked(this);
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -07002522
Elliott Hughesd8af1592012-04-16 20:40:15 -07002523 TearDownAlternateSignalStack();
Elliott Hughesc1674ed2011-08-25 18:09:09 -07002524}
2525
Andreas Gampe513061a2017-06-01 09:17:34 -07002526void Thread::HandleUncaughtExceptions(ScopedObjectAccessAlreadyRunnable& soa) {
Elliott Hughesaccd83d2011-10-17 14:25:58 -07002527 if (!IsExceptionPending()) {
2528 return;
2529 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07002530 ScopedLocalRef<jobject> peer(tlsPtr_.jni_env, soa.AddLocalReference<jobject>(tlsPtr_.opeer));
Ian Rogerscfaa4552012-11-26 21:00:08 -08002531 ScopedThreadStateChange tsc(this, kNative);
Ian Rogers120f1c72012-09-28 17:17:10 -07002532
Elliott Hughesaccd83d2011-10-17 14:25:58 -07002533 // Get and clear the exception.
Ian Rogersdd7624d2014-03-14 17:43:00 -07002534 ScopedLocalRef<jthrowable> exception(tlsPtr_.jni_env, tlsPtr_.jni_env->ExceptionOccurred());
2535 tlsPtr_.jni_env->ExceptionClear();
Elliott Hughesaccd83d2011-10-17 14:25:58 -07002536
Tobias Thierer5cbe65d2016-07-22 18:37:59 +01002537 // Call the Thread instance's dispatchUncaughtException(Throwable)
2538 tlsPtr_.jni_env->CallVoidMethod(peer.get(),
2539 WellKnownClasses::java_lang_Thread_dispatchUncaughtException,
2540 exception.get());
Elliott Hughesaccd83d2011-10-17 14:25:58 -07002541
Tobias Thierer5cbe65d2016-07-22 18:37:59 +01002542 // If the dispatchUncaughtException threw, clear that exception too.
Ian Rogersdd7624d2014-03-14 17:43:00 -07002543 tlsPtr_.jni_env->ExceptionClear();
Elliott Hughesaccd83d2011-10-17 14:25:58 -07002544}
2545
Andreas Gampe513061a2017-06-01 09:17:34 -07002546void Thread::RemoveFromThreadGroup(ScopedObjectAccessAlreadyRunnable& soa) {
Brian Carlstrom4514d3c2011-10-21 17:01:31 -07002547 // this.group.removeThread(this);
2548 // group can be null if we're in the compiler or a test.
Andreas Gampe08883de2016-11-08 13:20:52 -08002549 ObjPtr<mirror::Object> ogroup = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_group)
Ian Rogersdd7624d2014-03-14 17:43:00 -07002550 ->GetObject(tlsPtr_.opeer);
Dave Allison0aded082013-11-07 13:15:11 -08002551 if (ogroup != nullptr) {
Ian Rogerscfaa4552012-11-26 21:00:08 -08002552 ScopedLocalRef<jobject> group(soa.Env(), soa.AddLocalReference<jobject>(ogroup));
Ian Rogersdd7624d2014-03-14 17:43:00 -07002553 ScopedLocalRef<jobject> peer(soa.Env(), soa.AddLocalReference<jobject>(tlsPtr_.opeer));
Ian Rogerscfaa4552012-11-26 21:00:08 -08002554 ScopedThreadStateChange tsc(soa.Self(), kNative);
Ian Rogersdd7624d2014-03-14 17:43:00 -07002555 tlsPtr_.jni_env->CallVoidMethod(group.get(),
2556 WellKnownClasses::java_lang_ThreadGroup_removeThread,
2557 peer.get());
Brian Carlstrom4514d3c2011-10-21 17:01:31 -07002558 }
2559}
2560
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002561bool Thread::HandleScopeContains(jobject obj) const {
2562 StackReference<mirror::Object>* hs_entry =
Ian Rogersef7d42f2014-01-06 12:55:46 -08002563 reinterpret_cast<StackReference<mirror::Object>*>(obj);
Mathieu Chartiere8a3c572016-10-11 16:52:17 -07002564 for (BaseHandleScope* cur = tlsPtr_.top_handle_scope; cur!= nullptr; cur = cur->GetLink()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002565 if (cur->Contains(hs_entry)) {
Ian Rogersa8cd9f42011-08-19 16:43:41 -07002566 return true;
2567 }
2568 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002569 // JNI code invoked from portable code uses shadow frames rather than the handle scope.
2570 return tlsPtr_.managed_stack.ShadowFramesContain(hs_entry);
TDYa12728f1a142012-03-15 21:51:52 -07002571}
2572
Hans Boehm0882af22017-08-31 15:21:57 -07002573void Thread::HandleScopeVisitRoots(RootVisitor* visitor, pid_t thread_id) {
Mathieu Chartier4809d0a2015-04-07 10:39:04 -07002574 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(
2575 visitor, RootInfo(kRootNativeStack, thread_id));
Mathieu Chartiere8a3c572016-10-11 16:52:17 -07002576 for (BaseHandleScope* cur = tlsPtr_.top_handle_scope; cur; cur = cur->GetLink()) {
2577 cur->VisitRoots(buffered_visitor);
Shih-wei Liao8dfc9d52011-09-28 18:06:15 -07002578 }
2579}
2580
Mathieu Chartierc4f39252016-10-05 18:32:08 -07002581ObjPtr<mirror::Object> Thread::DecodeJObject(jobject obj) const {
Dave Allison0aded082013-11-07 13:15:11 -08002582 if (obj == nullptr) {
2583 return nullptr;
Ian Rogers408f79a2011-08-23 18:22:33 -07002584 }
2585 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
Andreas Gampedc061d02016-10-24 13:19:37 -07002586 IndirectRefKind kind = IndirectReferenceTable::GetIndirectRefKind(ref);
Mathieu Chartier8778c522016-10-04 19:06:30 -07002587 ObjPtr<mirror::Object> result;
Ian Rogersc0542af2014-09-03 16:16:56 -07002588 bool expect_null = false;
Ian Rogers4f6ad8a2013-03-18 15:27:28 -07002589 // The "kinds" below are sorted by the frequency we expect to encounter them.
2590 if (kind == kLocal) {
Ian Rogers55256cb2017-12-21 17:07:11 -08002591 IndirectReferenceTable& locals = tlsPtr_.jni_env->locals_;
Hiroshi Yamauchi196851b2014-05-29 12:16:04 -07002592 // Local references do not need a read barrier.
2593 result = locals.Get<kWithoutReadBarrier>(ref);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002594 } else if (kind == kHandleScopeOrInvalid) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002595 // TODO: make stack indirect reference table lookup more efficient.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002596 // Check if this is a local reference in the handle scope.
2597 if (LIKELY(HandleScopeContains(obj))) {
2598 // Read from handle scope.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002599 result = reinterpret_cast<StackReference<mirror::Object>*>(obj)->AsMirrorPtr();
Mathieu Chartier9d156d52016-10-06 17:44:26 -07002600 VerifyObject(result);
Ian Rogers408f79a2011-08-23 18:22:33 -07002601 } else {
Ian Rogers55256cb2017-12-21 17:07:11 -08002602 tlsPtr_.jni_env->vm_->JniAbortF(nullptr, "use of invalid jobject %p", obj);
Ian Rogersc0542af2014-09-03 16:16:56 -07002603 expect_null = true;
2604 result = nullptr;
Ian Rogers408f79a2011-08-23 18:22:33 -07002605 }
Ian Rogers4f6ad8a2013-03-18 15:27:28 -07002606 } else if (kind == kGlobal) {
Ian Rogers55256cb2017-12-21 17:07:11 -08002607 result = tlsPtr_.jni_env->vm_->DecodeGlobal(ref);
Ian Rogers4f6ad8a2013-03-18 15:27:28 -07002608 } else {
2609 DCHECK_EQ(kind, kWeakGlobal);
Ian Rogers55256cb2017-12-21 17:07:11 -08002610 result = tlsPtr_.jni_env->vm_->DecodeWeakGlobal(const_cast<Thread*>(this), ref);
Ian Rogersc0542af2014-09-03 16:16:56 -07002611 if (Runtime::Current()->IsClearedJniWeakGlobal(result)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002612 // This is a special case where it's okay to return null.
Ian Rogersc0542af2014-09-03 16:16:56 -07002613 expect_null = true;
2614 result = nullptr;
Ian Rogers4f6ad8a2013-03-18 15:27:28 -07002615 }
Ian Rogers408f79a2011-08-23 18:22:33 -07002616 }
2617
Ian Rogersc0542af2014-09-03 16:16:56 -07002618 if (UNLIKELY(!expect_null && result == nullptr)) {
Ian Rogers55256cb2017-12-21 17:07:11 -08002619 tlsPtr_.jni_env->vm_->JniAbortF(nullptr, "use of deleted %s %p",
Ian Rogers68d8b422014-07-17 11:09:10 -07002620 ToStr<IndirectRefKind>(kind).c_str(), obj);
Ian Rogers408f79a2011-08-23 18:22:33 -07002621 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -07002622 return result;
Ian Rogers408f79a2011-08-23 18:22:33 -07002623}
2624
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08002625bool Thread::IsJWeakCleared(jweak obj) const {
2626 CHECK(obj != nullptr);
2627 IndirectRef ref = reinterpret_cast<IndirectRef>(obj);
Andreas Gampedc061d02016-10-24 13:19:37 -07002628 IndirectRefKind kind = IndirectReferenceTable::GetIndirectRefKind(ref);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08002629 CHECK_EQ(kind, kWeakGlobal);
Ian Rogers55256cb2017-12-21 17:07:11 -08002630 return tlsPtr_.jni_env->vm_->IsWeakGlobalCleared(const_cast<Thread*>(this), ref);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08002631}
2632
Ian Rogers81d425b2012-09-27 16:03:43 -07002633// Implements java.lang.Thread.interrupted.
2634bool Thread::Interrupted() {
Nicolas Geoffray365719c2017-03-08 13:11:50 +00002635 DCHECK_EQ(Thread::Current(), this);
2636 // No other thread can concurrently reset the interrupted flag.
Orion Hodson88591fe2018-03-06 13:35:43 +00002637 bool interrupted = tls32_.interrupted.load(std::memory_order_seq_cst);
Nicolas Geoffray365719c2017-03-08 13:11:50 +00002638 if (interrupted) {
Orion Hodson88591fe2018-03-06 13:35:43 +00002639 tls32_.interrupted.store(false, std::memory_order_seq_cst);
Nicolas Geoffray365719c2017-03-08 13:11:50 +00002640 }
Ian Rogers81d425b2012-09-27 16:03:43 -07002641 return interrupted;
2642}
2643
2644// Implements java.lang.Thread.isInterrupted.
2645bool Thread::IsInterrupted() {
Orion Hodson88591fe2018-03-06 13:35:43 +00002646 return tls32_.interrupted.load(std::memory_order_seq_cst);
Ian Rogers81d425b2012-09-27 16:03:43 -07002647}
2648
Ian Rogersdd7624d2014-03-14 17:43:00 -07002649void Thread::Interrupt(Thread* self) {
Charles Mungeraa31f492018-11-01 18:57:38 +00002650 {
2651 MutexLock mu(self, *wait_mutex_);
2652 if (tls32_.interrupted.load(std::memory_order_seq_cst)) {
2653 return;
2654 }
2655 tls32_.interrupted.store(true, std::memory_order_seq_cst);
2656 NotifyLocked(self);
Ian Rogers81d425b2012-09-27 16:03:43 -07002657 }
Charles Mungeraa31f492018-11-01 18:57:38 +00002658 Unpark();
Ian Rogers81d425b2012-09-27 16:03:43 -07002659}
2660
2661void Thread::Notify() {
Ian Rogersc604d732012-10-14 16:09:54 -07002662 Thread* self = Thread::Current();
2663 MutexLock mu(self, *wait_mutex_);
2664 NotifyLocked(self);
Ian Rogers81d425b2012-09-27 16:03:43 -07002665}
2666
Ian Rogersc604d732012-10-14 16:09:54 -07002667void Thread::NotifyLocked(Thread* self) {
Dave Allison0aded082013-11-07 13:15:11 -08002668 if (wait_monitor_ != nullptr) {
Ian Rogersc604d732012-10-14 16:09:54 -07002669 wait_cond_->Signal(self);
Ian Rogers81d425b2012-09-27 16:03:43 -07002670 }
2671}
2672
Ian Rogers68d8b422014-07-17 11:09:10 -07002673void Thread::SetClassLoaderOverride(jobject class_loader_override) {
2674 if (tlsPtr_.class_loader_override != nullptr) {
2675 GetJniEnv()->DeleteGlobalRef(tlsPtr_.class_loader_override);
2676 }
2677 tlsPtr_.class_loader_override = GetJniEnv()->NewGlobalRef(class_loader_override);
2678}
2679
Mathieu Chartier65b8bb22017-02-01 11:03:50 -08002680using ArtMethodDexPcPair = std::pair<ArtMethod*, uint32_t>;
2681
2682// Counts the stack trace depth and also fetches the first max_saved_frames frames.
2683class FetchStackTraceVisitor : public StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07002684 public:
Mathieu Chartier65b8bb22017-02-01 11:03:50 -08002685 explicit FetchStackTraceVisitor(Thread* thread,
2686 ArtMethodDexPcPair* saved_frames = nullptr,
2687 size_t max_saved_frames = 0)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002688 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002689 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
Mathieu Chartier65b8bb22017-02-01 11:03:50 -08002690 saved_frames_(saved_frames),
2691 max_saved_frames_(max_saved_frames) {}
Elliott Hughesd369bb72011-09-12 14:41:14 -07002692
Andreas Gampefa6a1b02018-09-07 08:11:55 -07002693 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
Elliott Hughes29f27422011-09-18 16:02:18 -07002694 // We want to skip frames up to and including the exception's constructor.
Ian Rogers90865722011-09-19 11:11:44 -07002695 // Note we also skip the frame if it doesn't have a method (namely the callee
2696 // save frame)
Mathieu Chartiere401d142015-04-22 13:56:20 -07002697 ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002698 if (skipping_ && !m->IsRuntimeMethod() &&
Vladimir Markoadbceb72018-05-29 14:34:14 +01002699 !GetClassRoot<mirror::Throwable>()->IsAssignableFrom(m->GetDeclaringClass())) {
Elliott Hughes29f27422011-09-18 16:02:18 -07002700 skipping_ = false;
2701 }
2702 if (!skipping_) {
Ian Rogers0399dde2012-06-06 17:09:28 -07002703 if (!m->IsRuntimeMethod()) { // Ignore runtime frames (in particular callee save).
Mathieu Chartier65b8bb22017-02-01 11:03:50 -08002704 if (depth_ < max_saved_frames_) {
2705 saved_frames_[depth_].first = m;
Andreas Gampee2abbc62017-09-15 11:59:26 -07002706 saved_frames_[depth_].second = m->IsProxyMethod() ? dex::kDexNoIndex : GetDexPc();
Mathieu Chartier65b8bb22017-02-01 11:03:50 -08002707 }
Ian Rogers6b0870d2011-12-15 19:38:12 -08002708 ++depth_;
2709 }
Elliott Hughes29f27422011-09-18 16:02:18 -07002710 } else {
2711 ++skip_depth_;
2712 }
Elliott Hughes530fa002012-03-12 11:44:49 -07002713 return true;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002714 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07002715
Mathieu Chartier65b8bb22017-02-01 11:03:50 -08002716 uint32_t GetDepth() const {
Ian Rogersaaa20802011-09-11 21:47:37 -07002717 return depth_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07002718 }
2719
Mathieu Chartier65b8bb22017-02-01 11:03:50 -08002720 uint32_t GetSkipDepth() const {
Elliott Hughes29f27422011-09-18 16:02:18 -07002721 return skip_depth_;
2722 }
2723
Shih-wei Liao9b576b42011-08-29 01:45:07 -07002724 private:
Mathieu Chartier65b8bb22017-02-01 11:03:50 -08002725 uint32_t depth_ = 0;
2726 uint32_t skip_depth_ = 0;
2727 bool skipping_ = true;
2728 ArtMethodDexPcPair* saved_frames_;
2729 const size_t max_saved_frames_;
Sebastien Hertz26f72862015-09-15 09:52:07 +02002730
Mathieu Chartier65b8bb22017-02-01 11:03:50 -08002731 DISALLOW_COPY_AND_ASSIGN(FetchStackTraceVisitor);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07002732};
2733
Ian Rogers0399dde2012-06-06 17:09:28 -07002734class BuildInternalStackTraceVisitor : public StackVisitor {
Shih-wei Liao9b576b42011-08-29 01:45:07 -07002735 public:
Roland Levillain3887c462015-08-12 18:15:42 +01002736 BuildInternalStackTraceVisitor(Thread* self, Thread* thread, int skip_depth)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01002737 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
2738 self_(self),
2739 skip_depth_(skip_depth),
Mathieu Chartiere401d142015-04-22 13:56:20 -07002740 pointer_size_(Runtime::Current()->GetClassLinker()->GetImagePointerSize()) {}
Ian Rogers283ed0d2012-02-16 15:25:09 -08002741
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002742 bool Init(int depth) REQUIRES_SHARED(Locks::mutator_lock_) ACQUIRE(Roles::uninterruptible_) {
Mathieu Chartier910e8272015-09-30 09:24:22 -07002743 // Allocate method trace as an object array where the first element is a pointer array that
2744 // contains the ArtMethod pointers and dex PCs. The rest of the elements are the declaring
2745 // class of the ArtMethod pointers.
2746 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2747 StackHandleScope<1> hs(self_);
Vladimir Markob4eb1b12018-05-24 11:09:38 +01002748 ObjPtr<mirror::Class> array_class =
2749 GetClassRoot<mirror::ObjectArray<mirror::Object>>(class_linker);
Mathieu Chartier910e8272015-09-30 09:24:22 -07002750 // The first element is the methods and dex pc array, the other elements are declaring classes
2751 // for the methods to ensure classes in the stack trace don't get unloaded.
2752 Handle<mirror::ObjectArray<mirror::Object>> trace(
2753 hs.NewHandle(
2754 mirror::ObjectArray<mirror::Object>::Alloc(hs.Self(), array_class, depth + 1)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08002755 if (trace == nullptr) {
Mathieu Chartier910e8272015-09-30 09:24:22 -07002756 // Acquire uninterruptible_ in all paths.
2757 self_->StartAssertNoThreadSuspension("Building internal stack trace");
Mathieu Chartier566fc922015-09-29 10:21:55 -07002758 self_->AssertPendingOOMException();
2759 return false;
2760 }
Mathieu Chartierf5769e12017-01-10 15:54:41 -08002761 ObjPtr<mirror::PointerArray> methods_and_pcs =
2762 class_linker->AllocPointerArray(self_, depth * 2);
Mathieu Chartier910e8272015-09-30 09:24:22 -07002763 const char* last_no_suspend_cause =
2764 self_->StartAssertNoThreadSuspension("Building internal stack trace");
2765 if (methods_and_pcs == nullptr) {
2766 self_->AssertPendingOOMException();
2767 return false;
2768 }
Vladimir Markod34b73b2020-05-05 10:07:59 +01002769 trace->Set</*kTransactionActive=*/ false, /*kCheckTransaction=*/ false>(0, methods_and_pcs);
Mathieu Chartier910e8272015-09-30 09:24:22 -07002770 trace_ = trace.Get();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002771 // If We are called from native, use non-transactional mode.
Dave Allison0aded082013-11-07 13:15:11 -08002772 CHECK(last_no_suspend_cause == nullptr) << last_no_suspend_cause;
Ian Rogers283ed0d2012-02-16 15:25:09 -08002773 return true;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07002774 }
2775
Mathieu Chartier4e2cb092015-07-22 16:17:51 -07002776 virtual ~BuildInternalStackTraceVisitor() RELEASE(Roles::uninterruptible_) {
2777 self_->EndAssertNoThreadSuspension(nullptr);
Ian Rogers0399dde2012-06-06 17:09:28 -07002778 }
Shih-wei Liao9b576b42011-08-29 01:45:07 -07002779
Andreas Gampefa6a1b02018-09-07 08:11:55 -07002780 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002781 if (trace_ == nullptr) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002782 return true; // We're probably trying to fillInStackTrace for an OutOfMemoryError.
Elliott Hughes726079d2011-10-07 18:43:44 -07002783 }
Elliott Hughes29f27422011-09-18 16:02:18 -07002784 if (skip_depth_ > 0) {
2785 skip_depth_--;
Elliott Hughes530fa002012-03-12 11:44:49 -07002786 return true;
Elliott Hughes29f27422011-09-18 16:02:18 -07002787 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002788 ArtMethod* m = GetMethod();
Ian Rogers0399dde2012-06-06 17:09:28 -07002789 if (m->IsRuntimeMethod()) {
2790 return true; // Ignore runtime frames (in particular callee save).
Ian Rogers6b0870d2011-12-15 19:38:12 -08002791 }
Andreas Gampee2abbc62017-09-15 11:59:26 -07002792 AddFrame(m, m->IsProxyMethod() ? dex::kDexNoIndex : GetDexPc());
Mathieu Chartier65b8bb22017-02-01 11:03:50 -08002793 return true;
2794 }
2795
2796 void AddFrame(ArtMethod* method, uint32_t dex_pc) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod34b73b2020-05-05 10:07:59 +01002797 ObjPtr<mirror::PointerArray> methods_and_pcs = GetTraceMethodsAndPCs();
2798 methods_and_pcs->SetElementPtrSize</*kTransactionActive=*/ false, /*kCheckTransaction=*/ false>(
2799 count_, method, pointer_size_);
2800 methods_and_pcs->SetElementPtrSize</*kTransactionActive=*/ false, /*kCheckTransaction=*/ false>(
2801 methods_and_pcs->GetLength() / 2 + count_, dex_pc, pointer_size_);
Mathieu Chartier910e8272015-09-30 09:24:22 -07002802 // Save the declaring class of the method to ensure that the declaring classes of the methods
2803 // do not get unloaded while the stack trace is live.
Vladimir Markod34b73b2020-05-05 10:07:59 +01002804 trace_->Set</*kTransactionActive=*/ false, /*kCheckTransaction=*/ false>(
2805 count_ + 1, method->GetDeclaringClass());
Ian Rogersaaa20802011-09-11 21:47:37 -07002806 ++count_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07002807 }
2808
Mathieu Chartierf5769e12017-01-10 15:54:41 -08002809 ObjPtr<mirror::PointerArray> GetTraceMethodsAndPCs() const REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markod7e9bbf2019-03-28 13:18:57 +00002810 return ObjPtr<mirror::PointerArray>::DownCast(trace_->Get(0));
Mathieu Chartier910e8272015-09-30 09:24:22 -07002811 }
2812
2813 mirror::ObjectArray<mirror::Object>* GetInternalStackTrace() const {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002814 return trace_;
Shih-wei Liao9b576b42011-08-29 01:45:07 -07002815 }
2816
2817 private:
Ian Rogers1f539342012-10-03 21:09:42 -07002818 Thread* const self_;
Elliott Hughes29f27422011-09-18 16:02:18 -07002819 // How many more frames to skip.
2820 int32_t skip_depth_;
Ian Rogers0399dde2012-06-06 17:09:28 -07002821 // Current position down stack trace.
Mathieu Chartier65b8bb22017-02-01 11:03:50 -08002822 uint32_t count_ = 0;
Mathieu Chartier910e8272015-09-30 09:24:22 -07002823 // An object array where the first element is a pointer array that contains the ArtMethod
Vladimir Markod34b73b2020-05-05 10:07:59 +01002824 // pointers on the stack and dex PCs. The rest of the elements are the declaring class of
2825 // the ArtMethod pointers. trace_[i+1] contains the declaring class of the ArtMethod of the
2826 // i'th frame. We're initializing a newly allocated trace, so we do not need to record that
2827 // under a transaction. If the transaction is aborted, the whole trace shall be unreachable.
Mathieu Chartier65b8bb22017-02-01 11:03:50 -08002828 mirror::ObjectArray<mirror::Object>* trace_ = nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002829 // For cross compilation.
Andreas Gampe542451c2016-07-26 09:02:02 -07002830 const PointerSize pointer_size_;
Sebastien Hertz26f72862015-09-15 09:52:07 +02002831
2832 DISALLOW_COPY_AND_ASSIGN(BuildInternalStackTraceVisitor);
Shih-wei Liao9b576b42011-08-29 01:45:07 -07002833};
2834
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07002835jobject Thread::CreateInternalStackTrace(const ScopedObjectAccessAlreadyRunnable& soa) const {
Mathieu Chartier65b8bb22017-02-01 11:03:50 -08002836 // Compute depth of stack, save frames if possible to avoid needing to recompute many.
2837 constexpr size_t kMaxSavedFrames = 256;
2838 std::unique_ptr<ArtMethodDexPcPair[]> saved_frames(new ArtMethodDexPcPair[kMaxSavedFrames]);
2839 FetchStackTraceVisitor count_visitor(const_cast<Thread*>(this),
2840 &saved_frames[0],
2841 kMaxSavedFrames);
Ian Rogers0399dde2012-06-06 17:09:28 -07002842 count_visitor.WalkStack();
Mathieu Chartier65b8bb22017-02-01 11:03:50 -08002843 const uint32_t depth = count_visitor.GetDepth();
2844 const uint32_t skip_depth = count_visitor.GetSkipDepth();
Shih-wei Liao44175362011-08-28 16:59:17 -07002845
Ian Rogers1f539342012-10-03 21:09:42 -07002846 // Build internal stack trace.
Vladimir Markod34b73b2020-05-05 10:07:59 +01002847 BuildInternalStackTraceVisitor build_trace_visitor(
2848 soa.Self(), const_cast<Thread*>(this), skip_depth);
Ian Rogers1f539342012-10-03 21:09:42 -07002849 if (!build_trace_visitor.Init(depth)) {
Dave Allison0aded082013-11-07 13:15:11 -08002850 return nullptr; // Allocation failed.
Ian Rogers283ed0d2012-02-16 15:25:09 -08002851 }
Mathieu Chartier65b8bb22017-02-01 11:03:50 -08002852 // If we saved all of the frames we don't even need to do the actual stack walk. This is faster
2853 // than doing the stack walk twice.
2854 if (depth < kMaxSavedFrames) {
2855 for (size_t i = 0; i < depth; ++i) {
2856 build_trace_visitor.AddFrame(saved_frames[i].first, saved_frames[i].second);
2857 }
2858 } else {
2859 build_trace_visitor.WalkStack();
2860 }
2861
Mathieu Chartier910e8272015-09-30 09:24:22 -07002862 mirror::ObjectArray<mirror::Object>* trace = build_trace_visitor.GetInternalStackTrace();
Ian Rogers7a22fa62013-01-23 12:16:16 -08002863 if (kIsDebugBuild) {
Mathieu Chartierf5769e12017-01-10 15:54:41 -08002864 ObjPtr<mirror::PointerArray> trace_methods = build_trace_visitor.GetTraceMethodsAndPCs();
Mathieu Chartier910e8272015-09-30 09:24:22 -07002865 // Second half of trace_methods is dex PCs.
2866 for (uint32_t i = 0; i < static_cast<uint32_t>(trace_methods->GetLength() / 2); ++i) {
2867 auto* method = trace_methods->GetElementPtrSize<ArtMethod*>(
Mathieu Chartiere401d142015-04-22 13:56:20 -07002868 i, Runtime::Current()->GetClassLinker()->GetImagePointerSize());
2869 CHECK(method != nullptr);
Ian Rogers7a22fa62013-01-23 12:16:16 -08002870 }
2871 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002872 return soa.AddLocalReference<jobject>(trace);
Ian Rogersaaa20802011-09-11 21:47:37 -07002873}
2874
Mathieu Chartierf5769e12017-01-10 15:54:41 -08002875bool Thread::IsExceptionThrownByCurrentMethod(ObjPtr<mirror::Throwable> exception) const {
Mathieu Chartier65b8bb22017-02-01 11:03:50 -08002876 // Only count the depth since we do not pass a stack frame array as an argument.
2877 FetchStackTraceVisitor count_visitor(const_cast<Thread*>(this));
Nicolas Geoffray7642cfc2015-02-26 10:56:09 +00002878 count_visitor.WalkStack();
Mathieu Chartier65b8bb22017-02-01 11:03:50 -08002879 return count_visitor.GetDepth() == static_cast<uint32_t>(exception->GetStackDepth());
Nicolas Geoffray7642cfc2015-02-26 10:56:09 +00002880}
2881
Andreas Gampeb6f309e2017-12-11 20:45:41 -08002882static ObjPtr<mirror::StackTraceElement> CreateStackTraceElement(
2883 const ScopedObjectAccessAlreadyRunnable& soa,
2884 ArtMethod* method,
2885 uint32_t dex_pc) REQUIRES_SHARED(Locks::mutator_lock_) {
2886 int32_t line_number;
2887 StackHandleScope<3> hs(soa.Self());
2888 auto class_name_object(hs.NewHandle<mirror::String>(nullptr));
2889 auto source_name_object(hs.NewHandle<mirror::String>(nullptr));
2890 if (method->IsProxyMethod()) {
2891 line_number = -1;
2892 class_name_object.Assign(method->GetDeclaringClass()->GetName());
2893 // source_name_object intentionally left null for proxy methods
2894 } else {
2895 line_number = method->GetLineNumFromDexPC(dex_pc);
2896 // Allocate element, potentially triggering GC
2897 // TODO: reuse class_name_object via Class::name_?
2898 const char* descriptor = method->GetDeclaringClassDescriptor();
2899 CHECK(descriptor != nullptr);
2900 std::string class_name(PrettyDescriptor(descriptor));
2901 class_name_object.Assign(
2902 mirror::String::AllocFromModifiedUtf8(soa.Self(), class_name.c_str()));
2903 if (class_name_object == nullptr) {
2904 soa.Self()->AssertPendingOOMException();
2905 return nullptr;
2906 }
2907 const char* source_file = method->GetDeclaringClassSourceFile();
2908 if (line_number == -1) {
2909 // Make the line_number field of StackTraceElement hold the dex pc.
2910 // source_name_object is intentionally left null if we failed to map the dex pc to
2911 // a line number (most probably because there is no debug info). See b/30183883.
2912 line_number = dex_pc;
2913 } else {
2914 if (source_file != nullptr) {
2915 source_name_object.Assign(mirror::String::AllocFromModifiedUtf8(soa.Self(), source_file));
2916 if (source_name_object == nullptr) {
2917 soa.Self()->AssertPendingOOMException();
2918 return nullptr;
2919 }
2920 }
2921 }
2922 }
2923 const char* method_name = method->GetInterfaceMethodIfProxy(kRuntimePointerSize)->GetName();
2924 CHECK(method_name != nullptr);
2925 Handle<mirror::String> method_name_object(
2926 hs.NewHandle(mirror::String::AllocFromModifiedUtf8(soa.Self(), method_name)));
2927 if (method_name_object == nullptr) {
2928 return nullptr;
2929 }
2930 return mirror::StackTraceElement::Alloc(soa.Self(),
2931 class_name_object,
2932 method_name_object,
2933 source_name_object,
2934 line_number);
2935}
2936
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07002937jobjectArray Thread::InternalStackTraceToStackTraceElementArray(
Mathieu Chartier910e8272015-09-30 09:24:22 -07002938 const ScopedObjectAccessAlreadyRunnable& soa,
2939 jobject internal,
2940 jobjectArray output_array,
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07002941 int* stack_depth) {
Mathieu Chartier910e8272015-09-30 09:24:22 -07002942 // Decode the internal stack trace into the depth, method trace and PC trace.
2943 // Subtract one for the methods and PC trace.
Mathieu Chartier0795f232016-09-27 18:43:30 -07002944 int32_t depth = soa.Decode<mirror::Array>(internal)->GetLength() - 1;
Mathieu Chartier910e8272015-09-30 09:24:22 -07002945 DCHECK_GE(depth, 0);
Ian Rogersaaa20802011-09-11 21:47:37 -07002946
Mathieu Chartier910e8272015-09-30 09:24:22 -07002947 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Ian Rogersaaa20802011-09-11 21:47:37 -07002948
Elliott Hughes01158d72011-09-19 19:47:10 -07002949 jobjectArray result;
Mathieu Chartier530825b2013-09-25 17:56:49 -07002950
Dave Allison0aded082013-11-07 13:15:11 -08002951 if (output_array != nullptr) {
Elliott Hughes01158d72011-09-19 19:47:10 -07002952 // Reuse the array we were given.
2953 result = output_array;
Elliott Hughes01158d72011-09-19 19:47:10 -07002954 // ...adjusting the number of frames we'll write to not exceed the array length.
Mathieu Chartier530825b2013-09-25 17:56:49 -07002955 const int32_t traces_length =
Mathieu Chartier0795f232016-09-27 18:43:30 -07002956 soa.Decode<mirror::ObjectArray<mirror::StackTraceElement>>(result)->GetLength();
Mathieu Chartier530825b2013-09-25 17:56:49 -07002957 depth = std::min(depth, traces_length);
Elliott Hughes01158d72011-09-19 19:47:10 -07002958 } else {
2959 // Create java_trace array and place in local reference table
Vladimir Markobcf17522018-06-01 13:14:32 +01002960 ObjPtr<mirror::ObjectArray<mirror::StackTraceElement>> java_traces =
Mathieu Chartier910e8272015-09-30 09:24:22 -07002961 class_linker->AllocStackTraceElementArray(soa.Self(), depth);
Dave Allison0aded082013-11-07 13:15:11 -08002962 if (java_traces == nullptr) {
2963 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07002964 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07002965 result = soa.AddLocalReference<jobjectArray>(java_traces);
Elliott Hughes01158d72011-09-19 19:47:10 -07002966 }
2967
Dave Allison0aded082013-11-07 13:15:11 -08002968 if (stack_depth != nullptr) {
Elliott Hughes01158d72011-09-19 19:47:10 -07002969 *stack_depth = depth;
2970 }
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002971
Shih-wei Liao9b576b42011-08-29 01:45:07 -07002972 for (int32_t i = 0; i < depth; ++i) {
Mathieu Chartierf5769e12017-01-10 15:54:41 -08002973 ObjPtr<mirror::ObjectArray<mirror::Object>> decoded_traces =
Mathieu Chartier0795f232016-09-27 18:43:30 -07002974 soa.Decode<mirror::Object>(internal)->AsObjectArray<mirror::Object>();
Mathieu Chartier910e8272015-09-30 09:24:22 -07002975 // Methods and dex PC trace is element 0.
2976 DCHECK(decoded_traces->Get(0)->IsIntArray() || decoded_traces->Get(0)->IsLongArray());
Vladimir Marko0984e482019-03-27 16:41:41 +00002977 const ObjPtr<mirror::PointerArray> method_trace =
Vladimir Markod7e9bbf2019-03-28 13:18:57 +00002978 ObjPtr<mirror::PointerArray>::DownCast(decoded_traces->Get(0));
Ian Rogersaaa20802011-09-11 21:47:37 -07002979 // Prepare parameters for StackTraceElement(String cls, String method, String file, int line)
Andreas Gampe542451c2016-07-26 09:02:02 -07002980 ArtMethod* method = method_trace->GetElementPtrSize<ArtMethod*>(i, kRuntimePointerSize);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002981 uint32_t dex_pc = method_trace->GetElementPtrSize<uint32_t>(
Andreas Gampe542451c2016-07-26 09:02:02 -07002982 i + method_trace->GetLength() / 2, kRuntimePointerSize);
Vladimir Marko0984e482019-03-27 16:41:41 +00002983 const ObjPtr<mirror::StackTraceElement> obj = CreateStackTraceElement(soa, method, dex_pc);
Dave Allison0aded082013-11-07 13:15:11 -08002984 if (obj == nullptr) {
2985 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07002986 }
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01002987 // We are called from native: use non-transactional mode.
Mathieu Chartier0795f232016-09-27 18:43:30 -07002988 soa.Decode<mirror::ObjectArray<mirror::StackTraceElement>>(result)->Set<false>(i, obj);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002989 }
Ian Rogersaaa20802011-09-11 21:47:37 -07002990 return result;
Shih-wei Liao55df06b2011-08-26 14:39:27 -07002991}
2992
Andreas Gampefb6b0b12017-12-11 20:47:56 -08002993jobjectArray Thread::CreateAnnotatedStackTrace(const ScopedObjectAccessAlreadyRunnable& soa) const {
2994 // This code allocates. Do not allow it to operate with a pending exception.
2995 if (IsExceptionPending()) {
2996 return nullptr;
2997 }
2998
2999 // If flip_function is not null, it means we have run a checkpoint
3000 // before the thread wakes up to execute the flip function and the
3001 // thread roots haven't been forwarded. So the following access to
3002 // the roots (locks or methods in the frames) would be bad. Run it
3003 // here. TODO: clean up.
3004 // Note: copied from DumpJavaStack.
3005 {
3006 Thread* this_thread = const_cast<Thread*>(this);
3007 Closure* flip_func = this_thread->GetFlipFunction();
3008 if (flip_func != nullptr) {
3009 flip_func->Run(this_thread);
3010 }
3011 }
3012
3013 class CollectFramesAndLocksStackVisitor : public MonitorObjectsStackVisitor {
3014 public:
3015 CollectFramesAndLocksStackVisitor(const ScopedObjectAccessAlreadyRunnable& soaa_in,
3016 Thread* self,
3017 Context* context)
3018 : MonitorObjectsStackVisitor(self, context),
3019 wait_jobject_(soaa_in.Env(), nullptr),
3020 block_jobject_(soaa_in.Env(), nullptr),
3021 soaa_(soaa_in) {}
3022
3023 protected:
3024 VisitMethodResult StartMethod(ArtMethod* m, size_t frame_nr ATTRIBUTE_UNUSED)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01003025 override
Andreas Gampefb6b0b12017-12-11 20:47:56 -08003026 REQUIRES_SHARED(Locks::mutator_lock_) {
3027 ObjPtr<mirror::StackTraceElement> obj = CreateStackTraceElement(
3028 soaa_, m, GetDexPc(/* abort on error */ false));
3029 if (obj == nullptr) {
3030 return VisitMethodResult::kEndStackWalk;
3031 }
3032 stack_trace_elements_.emplace_back(soaa_.Env(), soaa_.AddLocalReference<jobject>(obj.Ptr()));
3033 return VisitMethodResult::kContinueMethod;
3034 }
3035
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01003036 VisitMethodResult EndMethod(ArtMethod* m ATTRIBUTE_UNUSED) override {
Andreas Gampefb6b0b12017-12-11 20:47:56 -08003037 lock_objects_.push_back({});
3038 lock_objects_[lock_objects_.size() - 1].swap(frame_lock_objects_);
3039
3040 DCHECK_EQ(lock_objects_.size(), stack_trace_elements_.size());
3041
3042 return VisitMethodResult::kContinueMethod;
3043 }
3044
Vladimir Markof52d92f2019-03-29 12:33:02 +00003045 void VisitWaitingObject(ObjPtr<mirror::Object> obj, ThreadState state ATTRIBUTE_UNUSED)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01003046 override
Andreas Gampefb6b0b12017-12-11 20:47:56 -08003047 REQUIRES_SHARED(Locks::mutator_lock_) {
3048 wait_jobject_.reset(soaa_.AddLocalReference<jobject>(obj));
3049 }
Vladimir Markof52d92f2019-03-29 12:33:02 +00003050 void VisitSleepingObject(ObjPtr<mirror::Object> obj)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01003051 override
Andreas Gampefb6b0b12017-12-11 20:47:56 -08003052 REQUIRES_SHARED(Locks::mutator_lock_) {
3053 wait_jobject_.reset(soaa_.AddLocalReference<jobject>(obj));
3054 }
Vladimir Markof52d92f2019-03-29 12:33:02 +00003055 void VisitBlockedOnObject(ObjPtr<mirror::Object> obj,
Andreas Gampefb6b0b12017-12-11 20:47:56 -08003056 ThreadState state ATTRIBUTE_UNUSED,
3057 uint32_t owner_tid ATTRIBUTE_UNUSED)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01003058 override
Andreas Gampefb6b0b12017-12-11 20:47:56 -08003059 REQUIRES_SHARED(Locks::mutator_lock_) {
3060 block_jobject_.reset(soaa_.AddLocalReference<jobject>(obj));
3061 }
Vladimir Markof52d92f2019-03-29 12:33:02 +00003062 void VisitLockedObject(ObjPtr<mirror::Object> obj)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01003063 override
Andreas Gampefb6b0b12017-12-11 20:47:56 -08003064 REQUIRES_SHARED(Locks::mutator_lock_) {
3065 frame_lock_objects_.emplace_back(soaa_.Env(), soaa_.AddLocalReference<jobject>(obj));
3066 }
3067
3068 public:
3069 std::vector<ScopedLocalRef<jobject>> stack_trace_elements_;
3070 ScopedLocalRef<jobject> wait_jobject_;
3071 ScopedLocalRef<jobject> block_jobject_;
3072 std::vector<std::vector<ScopedLocalRef<jobject>>> lock_objects_;
3073
3074 private:
3075 const ScopedObjectAccessAlreadyRunnable& soaa_;
3076
3077 std::vector<ScopedLocalRef<jobject>> frame_lock_objects_;
3078 };
3079
3080 std::unique_ptr<Context> context(Context::Create());
3081 CollectFramesAndLocksStackVisitor dumper(soa, const_cast<Thread*>(this), context.get());
3082 dumper.WalkStack();
3083
3084 // There should not be a pending exception. Otherwise, return with it pending.
3085 if (IsExceptionPending()) {
3086 return nullptr;
3087 }
3088
3089 // Now go and create Java arrays.
3090
3091 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
3092
3093 StackHandleScope<6> hs(soa.Self());
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003094 Handle<mirror::Class> h_aste_array_class = hs.NewHandle(class_linker->FindSystemClass(
Andreas Gampefb6b0b12017-12-11 20:47:56 -08003095 soa.Self(),
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003096 "[Ldalvik/system/AnnotatedStackTraceElement;"));
3097 if (h_aste_array_class == nullptr) {
Andreas Gampefb6b0b12017-12-11 20:47:56 -08003098 return nullptr;
3099 }
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003100 Handle<mirror::Class> h_aste_class = hs.NewHandle(h_aste_array_class->GetComponentType());
Andreas Gampefb6b0b12017-12-11 20:47:56 -08003101
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003102 Handle<mirror::Class> h_o_array_class =
3103 hs.NewHandle(GetClassRoot<mirror::ObjectArray<mirror::Object>>(class_linker));
3104 DCHECK(h_o_array_class != nullptr); // Class roots must be already initialized.
Andreas Gampefb6b0b12017-12-11 20:47:56 -08003105
Vladimir Markoc4b1c0c2018-03-29 17:07:17 +01003106
3107 // Make sure the AnnotatedStackTraceElement.class is initialized, b/76208924 .
3108 class_linker->EnsureInitialized(soa.Self(),
3109 h_aste_class,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003110 /* can_init_fields= */ true,
3111 /* can_init_parents= */ true);
Vladimir Markoc4b1c0c2018-03-29 17:07:17 +01003112 if (soa.Self()->IsExceptionPending()) {
3113 // This should not fail in a healthy runtime.
3114 return nullptr;
3115 }
3116
Andreas Gampefb6b0b12017-12-11 20:47:56 -08003117 ArtField* stack_trace_element_field = h_aste_class->FindField(
3118 soa.Self(), h_aste_class.Get(), "stackTraceElement", "Ljava/lang/StackTraceElement;");
3119 DCHECK(stack_trace_element_field != nullptr);
3120 ArtField* held_locks_field = h_aste_class->FindField(
3121 soa.Self(), h_aste_class.Get(), "heldLocks", "[Ljava/lang/Object;");
3122 DCHECK(held_locks_field != nullptr);
3123 ArtField* blocked_on_field = h_aste_class->FindField(
3124 soa.Self(), h_aste_class.Get(), "blockedOn", "Ljava/lang/Object;");
3125 DCHECK(blocked_on_field != nullptr);
3126
3127 size_t length = dumper.stack_trace_elements_.size();
3128 ObjPtr<mirror::ObjectArray<mirror::Object>> array =
Vladimir Markoa8bba7d2018-05-30 15:18:48 +01003129 mirror::ObjectArray<mirror::Object>::Alloc(soa.Self(), h_aste_array_class.Get(), length);
Andreas Gampefb6b0b12017-12-11 20:47:56 -08003130 if (array == nullptr) {
3131 soa.Self()->AssertPendingOOMException();
3132 return nullptr;
3133 }
3134
3135 ScopedLocalRef<jobjectArray> result(soa.Env(), soa.Env()->AddLocalReference<jobjectArray>(array));
3136
3137 MutableHandle<mirror::Object> handle(hs.NewHandle<mirror::Object>(nullptr));
3138 MutableHandle<mirror::ObjectArray<mirror::Object>> handle2(
3139 hs.NewHandle<mirror::ObjectArray<mirror::Object>>(nullptr));
3140 for (size_t i = 0; i != length; ++i) {
3141 handle.Assign(h_aste_class->AllocObject(soa.Self()));
3142 if (handle == nullptr) {
3143 soa.Self()->AssertPendingOOMException();
3144 return nullptr;
3145 }
3146
3147 // Set stack trace element.
3148 stack_trace_element_field->SetObject<false>(
3149 handle.Get(), soa.Decode<mirror::Object>(dumper.stack_trace_elements_[i].get()));
3150
3151 // Create locked-on array.
3152 if (!dumper.lock_objects_[i].empty()) {
3153 handle2.Assign(mirror::ObjectArray<mirror::Object>::Alloc(soa.Self(),
3154 h_o_array_class.Get(),
3155 dumper.lock_objects_[i].size()));
3156 if (handle2 == nullptr) {
3157 soa.Self()->AssertPendingOOMException();
3158 return nullptr;
3159 }
3160 int32_t j = 0;
3161 for (auto& scoped_local : dumper.lock_objects_[i]) {
3162 if (scoped_local == nullptr) {
3163 continue;
3164 }
3165 handle2->Set(j, soa.Decode<mirror::Object>(scoped_local.get()));
3166 DCHECK(!soa.Self()->IsExceptionPending());
3167 j++;
3168 }
3169 held_locks_field->SetObject<false>(handle.Get(), handle2.Get());
3170 }
3171
3172 // Set blocked-on object.
3173 if (i == 0) {
3174 if (dumper.block_jobject_ != nullptr) {
3175 blocked_on_field->SetObject<false>(
3176 handle.Get(), soa.Decode<mirror::Object>(dumper.block_jobject_.get()));
3177 }
3178 }
3179
3180 ScopedLocalRef<jobject> elem(soa.Env(), soa.AddLocalReference<jobject>(handle.Get()));
3181 soa.Env()->SetObjectArrayElement(result.get(), i, elem.get());
3182 DCHECK(!soa.Self()->IsExceptionPending());
3183 }
3184
3185 return result.release();
3186}
3187
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00003188void Thread::ThrowNewExceptionF(const char* exception_class_descriptor, const char* fmt, ...) {
Elliott Hughesa5b897e2011-08-16 11:33:06 -07003189 va_list args;
3190 va_start(args, fmt);
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00003191 ThrowNewExceptionV(exception_class_descriptor, fmt, args);
Elliott Hughesa5b897e2011-08-16 11:33:06 -07003192 va_end(args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003193}
3194
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00003195void Thread::ThrowNewExceptionV(const char* exception_class_descriptor,
Ian Rogers62d6c772013-02-27 08:32:07 -08003196 const char* fmt, va_list ap) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003197 std::string msg;
3198 StringAppendV(&msg, fmt, ap);
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00003199 ThrowNewException(exception_class_descriptor, msg.c_str());
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07003200}
Elliott Hughes37f7a402011-08-22 18:56:01 -07003201
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00003202void Thread::ThrowNewException(const char* exception_class_descriptor,
Ian Rogers62d6c772013-02-27 08:32:07 -08003203 const char* msg) {
Mathieu Chartier8d7672e2014-02-25 10:57:16 -08003204 // Callers should either clear or call ThrowNewWrappedException.
3205 AssertNoPendingExceptionForNewException(msg);
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00003206 ThrowNewWrappedException(exception_class_descriptor, msg);
Elliott Hughesa4f94742012-05-29 16:28:38 -07003207}
3208
Mathieu Chartierf5769e12017-01-10 15:54:41 -08003209static ObjPtr<mirror::ClassLoader> GetCurrentClassLoader(Thread* self)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003210 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003211 ArtMethod* method = self->GetCurrentMethod(nullptr);
Nicolas Geoffrayee077032015-03-09 14:56:37 +00003212 return method != nullptr
3213 ? method->GetDeclaringClass()->GetClassLoader()
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003214 : nullptr;
3215}
3216
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00003217void Thread::ThrowNewWrappedException(const char* exception_class_descriptor,
Ian Rogers62d6c772013-02-27 08:32:07 -08003218 const char* msg) {
3219 DCHECK_EQ(this, Thread::Current());
Ian Rogers53b8b092014-03-13 23:45:53 -07003220 ScopedObjectAccessUnchecked soa(this);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003221 StackHandleScope<3> hs(soa.Self());
Nicolas Geoffrayee077032015-03-09 14:56:37 +00003222 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(GetCurrentClassLoader(soa.Self())));
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003223 ScopedLocalRef<jobject> cause(GetJniEnv(), soa.AddLocalReference<jobject>(GetException()));
Ian Rogers62d6c772013-02-27 08:32:07 -08003224 ClearException();
3225 Runtime* runtime = Runtime::Current();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003226 auto* cl = runtime->GetClassLinker();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003227 Handle<mirror::Class> exception_class(
Mathieu Chartiere401d142015-04-22 13:56:20 -07003228 hs.NewHandle(cl->FindClass(this, exception_class_descriptor, class_loader)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08003229 if (UNLIKELY(exception_class == nullptr)) {
Elliott Hughes30646832011-10-13 16:59:46 -07003230 CHECK(IsExceptionPending());
Ian Rogers62d6c772013-02-27 08:32:07 -08003231 LOG(ERROR) << "No exception class " << PrettyDescriptor(exception_class_descriptor);
Elliott Hughes30646832011-10-13 16:59:46 -07003232 return;
3233 }
Ian Rogers62d6c772013-02-27 08:32:07 -08003234
Ian Rogers7b078e82014-09-10 14:44:24 -07003235 if (UNLIKELY(!runtime->GetClassLinker()->EnsureInitialized(soa.Self(), exception_class, true,
3236 true))) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003237 DCHECK(IsExceptionPending());
3238 return;
3239 }
3240 DCHECK(!runtime->IsStarted() || exception_class->IsThrowableClass());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003241 Handle<mirror::Throwable> exception(
Mathieu Chartier28bd2e42016-10-04 13:54:57 -07003242 hs.NewHandle(ObjPtr<mirror::Throwable>::DownCast(exception_class->AllocObject(this))));
Ian Rogers62d6c772013-02-27 08:32:07 -08003243
Mathieu Chartier590fee92013-09-13 13:46:47 -07003244 // If we couldn't allocate the exception, throw the pre-allocated out of memory exception.
Andreas Gampefa4333d2017-02-14 11:10:34 -08003245 if (exception == nullptr) {
Roland Levillain7b0e8442018-04-11 18:27:47 +01003246 Dump(LOG_STREAM(WARNING)); // The pre-allocated OOME has no stack, so help out and log one.
3247 SetException(Runtime::Current()->GetPreAllocatedOutOfMemoryErrorWhenThrowingException());
Mathieu Chartier590fee92013-09-13 13:46:47 -07003248 return;
3249 }
3250
Ian Rogers62d6c772013-02-27 08:32:07 -08003251 // Choose an appropriate constructor and set up the arguments.
3252 const char* signature;
Ian Rogers53b8b092014-03-13 23:45:53 -07003253 ScopedLocalRef<jstring> msg_string(GetJniEnv(), nullptr);
Dave Allison0aded082013-11-07 13:15:11 -08003254 if (msg != nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003255 // Ensure we remember this and the method over the String allocation.
Ian Rogers53b8b092014-03-13 23:45:53 -07003256 msg_string.reset(
3257 soa.AddLocalReference<jstring>(mirror::String::AllocFromModifiedUtf8(this, msg)));
Dave Allison0aded082013-11-07 13:15:11 -08003258 if (UNLIKELY(msg_string.get() == nullptr)) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003259 CHECK(IsExceptionPending()); // OOME.
3260 return;
Brian Carlstromebd1fd22011-12-07 15:46:26 -08003261 }
Dave Allison0aded082013-11-07 13:15:11 -08003262 if (cause.get() == nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003263 signature = "(Ljava/lang/String;)V";
3264 } else {
3265 signature = "(Ljava/lang/String;Ljava/lang/Throwable;)V";
3266 }
3267 } else {
Dave Allison0aded082013-11-07 13:15:11 -08003268 if (cause.get() == nullptr) {
Ian Rogers62d6c772013-02-27 08:32:07 -08003269 signature = "()V";
3270 } else {
3271 signature = "(Ljava/lang/Throwable;)V";
3272 }
Brian Carlstromebd1fd22011-12-07 15:46:26 -08003273 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07003274 ArtMethod* exception_init_method =
Vladimir Markoba118822017-06-12 15:41:56 +01003275 exception_class->FindConstructor(signature, cl->GetImagePointerSize());
Ian Rogers62d6c772013-02-27 08:32:07 -08003276
Dave Allison0aded082013-11-07 13:15:11 -08003277 CHECK(exception_init_method != nullptr) << "No <init>" << signature << " in "
Ian Rogers62d6c772013-02-27 08:32:07 -08003278 << PrettyDescriptor(exception_class_descriptor);
3279
3280 if (UNLIKELY(!runtime->IsStarted())) {
3281 // Something is trying to throw an exception without a started runtime, which is the common
3282 // case in the compiler. We won't be able to invoke the constructor of the exception, so set
3283 // the exception fields directly.
Dave Allison0aded082013-11-07 13:15:11 -08003284 if (msg != nullptr) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07003285 exception->SetDetailMessage(DecodeJObject(msg_string.get())->AsString());
Ian Rogers62d6c772013-02-27 08:32:07 -08003286 }
Dave Allison0aded082013-11-07 13:15:11 -08003287 if (cause.get() != nullptr) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07003288 exception->SetCause(DecodeJObject(cause.get())->AsThrowable());
Ian Rogers62d6c772013-02-27 08:32:07 -08003289 }
Vladimir Markod34b73b2020-05-05 10:07:59 +01003290 ScopedLocalRef<jobject> trace(GetJniEnv(), CreateInternalStackTrace(soa));
Ian Rogersc45b8b52014-05-03 01:39:59 -07003291 if (trace.get() != nullptr) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07003292 exception->SetStackState(DecodeJObject(trace.get()).Ptr());
Ian Rogersc45b8b52014-05-03 01:39:59 -07003293 }
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003294 SetException(exception.Get());
Ian Rogers62d6c772013-02-27 08:32:07 -08003295 } else {
Ian Rogers53b8b092014-03-13 23:45:53 -07003296 jvalue jv_args[2];
3297 size_t i = 0;
3298
Dave Allison0aded082013-11-07 13:15:11 -08003299 if (msg != nullptr) {
Ian Rogers53b8b092014-03-13 23:45:53 -07003300 jv_args[i].l = msg_string.get();
3301 ++i;
Ian Rogers62d6c772013-02-27 08:32:07 -08003302 }
Dave Allison0aded082013-11-07 13:15:11 -08003303 if (cause.get() != nullptr) {
Ian Rogers53b8b092014-03-13 23:45:53 -07003304 jv_args[i].l = cause.get();
3305 ++i;
Ian Rogers62d6c772013-02-27 08:32:07 -08003306 }
Jeff Hao39b6c242015-05-19 20:30:23 -07003307 ScopedLocalRef<jobject> ref(soa.Env(), soa.AddLocalReference<jobject>(exception.Get()));
Alex Light01fbfbe2019-06-27 10:47:04 -07003308 InvokeWithJValues(soa, ref.get(), exception_init_method, jv_args);
Ian Rogers62d6c772013-02-27 08:32:07 -08003309 if (LIKELY(!IsExceptionPending())) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003310 SetException(exception.Get());
Ian Rogers62d6c772013-02-27 08:32:07 -08003311 }
Elliott Hughes30646832011-10-13 16:59:46 -07003312 }
Elliott Hughesa5b897e2011-08-16 11:33:06 -07003313}
3314
Elliott Hughes2ced6a52011-10-16 18:44:48 -07003315void Thread::ThrowOutOfMemoryError(const char* msg) {
Wei Li8991ad02018-09-13 16:43:39 +08003316 LOG(WARNING) << "Throwing OutOfMemoryError "
3317 << '"' << msg << '"'
3318 << " (VmSize " << GetProcessStatus("VmSize")
3319 << (tls32_.throwing_OutOfMemoryError ? ", recursive case)" : ")");
Ian Rogersdd7624d2014-03-14 17:43:00 -07003320 if (!tls32_.throwing_OutOfMemoryError) {
3321 tls32_.throwing_OutOfMemoryError = true;
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00003322 ThrowNewException("Ljava/lang/OutOfMemoryError;", msg);
Ian Rogersdd7624d2014-03-14 17:43:00 -07003323 tls32_.throwing_OutOfMemoryError = false;
Elliott Hughes418dfe72011-10-06 18:56:27 -07003324 } else {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07003325 Dump(LOG_STREAM(WARNING)); // The pre-allocated OOME has no stack, so help out and log one.
Roland Levillain7b0e8442018-04-11 18:27:47 +01003326 SetException(Runtime::Current()->GetPreAllocatedOutOfMemoryErrorWhenThrowingOOME());
Elliott Hughes418dfe72011-10-06 18:56:27 -07003327 }
Elliott Hughes79082e32011-08-25 12:07:32 -07003328}
3329
Elliott Hughes498508c2011-10-17 14:58:22 -07003330Thread* Thread::CurrentFromGdb() {
Elliott Hughesaccd83d2011-10-17 14:25:58 -07003331 return Thread::Current();
3332}
3333
3334void Thread::DumpFromGdb() const {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003335 std::ostringstream ss;
3336 Dump(ss);
Elliott Hughes95572412011-12-13 18:14:20 -08003337 std::string str(ss.str());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003338 // log to stderr for debugging command line processes
3339 std::cerr << str;
Bilyan Borisovbb661c02016-04-04 16:27:32 +01003340#ifdef ART_TARGET_ANDROID
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003341 // log to logcat for debugging frameworks processes
3342 LOG(INFO) << str;
3343#endif
Elliott Hughesaccd83d2011-10-17 14:25:58 -07003344}
3345
Ian Rogersdd7624d2014-03-14 17:43:00 -07003346// Explicitly instantiate 32 and 64bit thread offset dumping support.
Andreas Gampe542451c2016-07-26 09:02:02 -07003347template
3348void Thread::DumpThreadOffset<PointerSize::k32>(std::ostream& os, uint32_t offset);
3349template
3350void Thread::DumpThreadOffset<PointerSize::k64>(std::ostream& os, uint32_t offset);
Elliott Hughes98e20172012-04-24 15:38:13 -07003351
Andreas Gampe542451c2016-07-26 09:02:02 -07003352template<PointerSize ptr_size>
Ian Rogersdd7624d2014-03-14 17:43:00 -07003353void Thread::DumpThreadOffset(std::ostream& os, uint32_t offset) {
3354#define DO_THREAD_OFFSET(x, y) \
Chih-Hung Hsiehfba39972016-05-11 11:26:48 -07003355 if (offset == (x).Uint32Value()) { \
3356 os << (y); \
Brian Carlstromf69863b2013-07-17 21:53:13 -07003357 return; \
3358 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07003359 DO_THREAD_OFFSET(ThreadFlagsOffset<ptr_size>(), "state_and_flags")
3360 DO_THREAD_OFFSET(CardTableOffset<ptr_size>(), "card_table")
3361 DO_THREAD_OFFSET(ExceptionOffset<ptr_size>(), "exception")
3362 DO_THREAD_OFFSET(PeerOffset<ptr_size>(), "peer");
3363 DO_THREAD_OFFSET(JniEnvOffset<ptr_size>(), "jni_env")
3364 DO_THREAD_OFFSET(SelfOffset<ptr_size>(), "self")
3365 DO_THREAD_OFFSET(StackEndOffset<ptr_size>(), "stack_end")
3366 DO_THREAD_OFFSET(ThinLockIdOffset<ptr_size>(), "thin_lock_thread_id")
Roland Levillain97c46462017-05-11 14:04:03 +01003367 DO_THREAD_OFFSET(IsGcMarkingOffset<ptr_size>(), "is_gc_marking")
Ian Rogersdd7624d2014-03-14 17:43:00 -07003368 DO_THREAD_OFFSET(TopOfManagedStackOffset<ptr_size>(), "top_quick_frame_method")
Ian Rogersdd7624d2014-03-14 17:43:00 -07003369 DO_THREAD_OFFSET(TopShadowFrameOffset<ptr_size>(), "top_shadow_frame")
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003370 DO_THREAD_OFFSET(TopHandleScopeOffset<ptr_size>(), "top_handle_scope")
Ian Rogersdd7624d2014-03-14 17:43:00 -07003371 DO_THREAD_OFFSET(ThreadSuspendTriggerOffset<ptr_size>(), "suspend_trigger")
Elliott Hughes28fa76d2012-04-09 17:31:46 -07003372#undef DO_THREAD_OFFSET
Elliott Hughes98e20172012-04-24 15:38:13 -07003373
Ian Rogersdd7624d2014-03-14 17:43:00 -07003374#define JNI_ENTRY_POINT_INFO(x) \
3375 if (JNI_ENTRYPOINT_OFFSET(ptr_size, x).Uint32Value() == offset) { \
3376 os << #x; \
3377 return; \
3378 }
3379 JNI_ENTRY_POINT_INFO(pDlsymLookup)
Vladimir Markofa458ac2020-02-12 14:08:07 +00003380 JNI_ENTRY_POINT_INFO(pDlsymLookupCritical)
Ian Rogersdd7624d2014-03-14 17:43:00 -07003381#undef JNI_ENTRY_POINT_INFO
3382
Ian Rogersdd7624d2014-03-14 17:43:00 -07003383#define QUICK_ENTRY_POINT_INFO(x) \
3384 if (QUICK_ENTRYPOINT_OFFSET(ptr_size, x).Uint32Value() == offset) { \
3385 os << #x; \
3386 return; \
3387 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07003388 QUICK_ENTRY_POINT_INFO(pAllocArrayResolved)
Nicolas Geoffrayb048cb72017-01-23 22:50:24 +00003389 QUICK_ENTRY_POINT_INFO(pAllocArrayResolved8)
3390 QUICK_ENTRY_POINT_INFO(pAllocArrayResolved16)
3391 QUICK_ENTRY_POINT_INFO(pAllocArrayResolved32)
3392 QUICK_ENTRY_POINT_INFO(pAllocArrayResolved64)
Ian Rogersdd7624d2014-03-14 17:43:00 -07003393 QUICK_ENTRY_POINT_INFO(pAllocObjectResolved)
3394 QUICK_ENTRY_POINT_INFO(pAllocObjectInitialized)
Nicolas Geoffray0d3998b2017-01-12 15:35:12 +00003395 QUICK_ENTRY_POINT_INFO(pAllocObjectWithChecks)
Alex Lightd109e302018-06-27 10:25:41 -07003396 QUICK_ENTRY_POINT_INFO(pAllocStringObject)
Jeff Hao848f70a2014-01-15 13:49:50 -08003397 QUICK_ENTRY_POINT_INFO(pAllocStringFromBytes)
3398 QUICK_ENTRY_POINT_INFO(pAllocStringFromChars)
3399 QUICK_ENTRY_POINT_INFO(pAllocStringFromString)
Ian Rogersdd7624d2014-03-14 17:43:00 -07003400 QUICK_ENTRY_POINT_INFO(pInstanceofNonTrivial)
Mathieu Chartierb99f4d62016-11-07 16:17:26 -08003401 QUICK_ENTRY_POINT_INFO(pCheckInstanceOf)
Ian Rogersdd7624d2014-03-14 17:43:00 -07003402 QUICK_ENTRY_POINT_INFO(pInitializeStaticStorage)
Vladimir Marko9d479252018-07-24 11:35:20 +01003403 QUICK_ENTRY_POINT_INFO(pResolveTypeAndVerifyAccess)
3404 QUICK_ENTRY_POINT_INFO(pResolveType)
Ian Rogersdd7624d2014-03-14 17:43:00 -07003405 QUICK_ENTRY_POINT_INFO(pResolveString)
Fred Shih37f05ef2014-07-16 18:38:08 -07003406 QUICK_ENTRY_POINT_INFO(pSet8Instance)
3407 QUICK_ENTRY_POINT_INFO(pSet8Static)
3408 QUICK_ENTRY_POINT_INFO(pSet16Instance)
3409 QUICK_ENTRY_POINT_INFO(pSet16Static)
Ian Rogersdd7624d2014-03-14 17:43:00 -07003410 QUICK_ENTRY_POINT_INFO(pSet32Instance)
3411 QUICK_ENTRY_POINT_INFO(pSet32Static)
3412 QUICK_ENTRY_POINT_INFO(pSet64Instance)
3413 QUICK_ENTRY_POINT_INFO(pSet64Static)
3414 QUICK_ENTRY_POINT_INFO(pSetObjInstance)
3415 QUICK_ENTRY_POINT_INFO(pSetObjStatic)
Fred Shih37f05ef2014-07-16 18:38:08 -07003416 QUICK_ENTRY_POINT_INFO(pGetByteInstance)
3417 QUICK_ENTRY_POINT_INFO(pGetBooleanInstance)
3418 QUICK_ENTRY_POINT_INFO(pGetByteStatic)
3419 QUICK_ENTRY_POINT_INFO(pGetBooleanStatic)
3420 QUICK_ENTRY_POINT_INFO(pGetShortInstance)
3421 QUICK_ENTRY_POINT_INFO(pGetCharInstance)
3422 QUICK_ENTRY_POINT_INFO(pGetShortStatic)
3423 QUICK_ENTRY_POINT_INFO(pGetCharStatic)
Ian Rogersdd7624d2014-03-14 17:43:00 -07003424 QUICK_ENTRY_POINT_INFO(pGet32Instance)
3425 QUICK_ENTRY_POINT_INFO(pGet32Static)
3426 QUICK_ENTRY_POINT_INFO(pGet64Instance)
3427 QUICK_ENTRY_POINT_INFO(pGet64Static)
3428 QUICK_ENTRY_POINT_INFO(pGetObjInstance)
3429 QUICK_ENTRY_POINT_INFO(pGetObjStatic)
Ian Rogersdd7624d2014-03-14 17:43:00 -07003430 QUICK_ENTRY_POINT_INFO(pAputObject)
Ian Rogersdd7624d2014-03-14 17:43:00 -07003431 QUICK_ENTRY_POINT_INFO(pJniMethodStart)
3432 QUICK_ENTRY_POINT_INFO(pJniMethodStartSynchronized)
3433 QUICK_ENTRY_POINT_INFO(pJniMethodEnd)
3434 QUICK_ENTRY_POINT_INFO(pJniMethodEndSynchronized)
3435 QUICK_ENTRY_POINT_INFO(pJniMethodEndWithReference)
3436 QUICK_ENTRY_POINT_INFO(pJniMethodEndWithReferenceSynchronized)
3437 QUICK_ENTRY_POINT_INFO(pQuickGenericJniTrampoline)
3438 QUICK_ENTRY_POINT_INFO(pLockObject)
3439 QUICK_ENTRY_POINT_INFO(pUnlockObject)
3440 QUICK_ENTRY_POINT_INFO(pCmpgDouble)
3441 QUICK_ENTRY_POINT_INFO(pCmpgFloat)
3442 QUICK_ENTRY_POINT_INFO(pCmplDouble)
3443 QUICK_ENTRY_POINT_INFO(pCmplFloat)
Mark Mendella4f12202015-08-06 15:23:34 -04003444 QUICK_ENTRY_POINT_INFO(pCos)
3445 QUICK_ENTRY_POINT_INFO(pSin)
3446 QUICK_ENTRY_POINT_INFO(pAcos)
3447 QUICK_ENTRY_POINT_INFO(pAsin)
3448 QUICK_ENTRY_POINT_INFO(pAtan)
3449 QUICK_ENTRY_POINT_INFO(pAtan2)
3450 QUICK_ENTRY_POINT_INFO(pCbrt)
3451 QUICK_ENTRY_POINT_INFO(pCosh)
3452 QUICK_ENTRY_POINT_INFO(pExp)
3453 QUICK_ENTRY_POINT_INFO(pExpm1)
3454 QUICK_ENTRY_POINT_INFO(pHypot)
3455 QUICK_ENTRY_POINT_INFO(pLog)
3456 QUICK_ENTRY_POINT_INFO(pLog10)
3457 QUICK_ENTRY_POINT_INFO(pNextAfter)
3458 QUICK_ENTRY_POINT_INFO(pSinh)
3459 QUICK_ENTRY_POINT_INFO(pTan)
3460 QUICK_ENTRY_POINT_INFO(pTanh)
Ian Rogersdd7624d2014-03-14 17:43:00 -07003461 QUICK_ENTRY_POINT_INFO(pFmod)
Ian Rogersdd7624d2014-03-14 17:43:00 -07003462 QUICK_ENTRY_POINT_INFO(pL2d)
3463 QUICK_ENTRY_POINT_INFO(pFmodf)
3464 QUICK_ENTRY_POINT_INFO(pL2f)
3465 QUICK_ENTRY_POINT_INFO(pD2iz)
3466 QUICK_ENTRY_POINT_INFO(pF2iz)
3467 QUICK_ENTRY_POINT_INFO(pIdivmod)
3468 QUICK_ENTRY_POINT_INFO(pD2l)
3469 QUICK_ENTRY_POINT_INFO(pF2l)
3470 QUICK_ENTRY_POINT_INFO(pLdiv)
3471 QUICK_ENTRY_POINT_INFO(pLmod)
3472 QUICK_ENTRY_POINT_INFO(pLmul)
3473 QUICK_ENTRY_POINT_INFO(pShlLong)
3474 QUICK_ENTRY_POINT_INFO(pShrLong)
3475 QUICK_ENTRY_POINT_INFO(pUshrLong)
3476 QUICK_ENTRY_POINT_INFO(pIndexOf)
Ian Rogersdd7624d2014-03-14 17:43:00 -07003477 QUICK_ENTRY_POINT_INFO(pStringCompareTo)
3478 QUICK_ENTRY_POINT_INFO(pMemcpy)
3479 QUICK_ENTRY_POINT_INFO(pQuickImtConflictTrampoline)
3480 QUICK_ENTRY_POINT_INFO(pQuickResolutionTrampoline)
3481 QUICK_ENTRY_POINT_INFO(pQuickToInterpreterBridge)
3482 QUICK_ENTRY_POINT_INFO(pInvokeDirectTrampolineWithAccessCheck)
3483 QUICK_ENTRY_POINT_INFO(pInvokeInterfaceTrampolineWithAccessCheck)
3484 QUICK_ENTRY_POINT_INFO(pInvokeStaticTrampolineWithAccessCheck)
3485 QUICK_ENTRY_POINT_INFO(pInvokeSuperTrampolineWithAccessCheck)
3486 QUICK_ENTRY_POINT_INFO(pInvokeVirtualTrampolineWithAccessCheck)
Orion Hodsonac141392017-01-13 11:53:47 +00003487 QUICK_ENTRY_POINT_INFO(pInvokePolymorphic)
Ian Rogersdd7624d2014-03-14 17:43:00 -07003488 QUICK_ENTRY_POINT_INFO(pTestSuspend)
3489 QUICK_ENTRY_POINT_INFO(pDeliverException)
3490 QUICK_ENTRY_POINT_INFO(pThrowArrayBounds)
3491 QUICK_ENTRY_POINT_INFO(pThrowDivZero)
Ian Rogersdd7624d2014-03-14 17:43:00 -07003492 QUICK_ENTRY_POINT_INFO(pThrowNullPointer)
3493 QUICK_ENTRY_POINT_INFO(pThrowStackOverflow)
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07003494 QUICK_ENTRY_POINT_INFO(pDeoptimize)
Douglas Leungd9cb8ae2014-07-09 14:28:35 -07003495 QUICK_ENTRY_POINT_INFO(pA64Load)
3496 QUICK_ENTRY_POINT_INFO(pA64Store)
Jeff Hao848f70a2014-01-15 13:49:50 -08003497 QUICK_ENTRY_POINT_INFO(pNewEmptyString)
3498 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_B)
3499 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BI)
3500 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BII)
3501 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BIII)
3502 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BIIString)
3503 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BString)
3504 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BIICharset)
3505 QUICK_ENTRY_POINT_INFO(pNewStringFromBytes_BCharset)
3506 QUICK_ENTRY_POINT_INFO(pNewStringFromChars_C)
3507 QUICK_ENTRY_POINT_INFO(pNewStringFromChars_CII)
3508 QUICK_ENTRY_POINT_INFO(pNewStringFromChars_IIC)
3509 QUICK_ENTRY_POINT_INFO(pNewStringFromCodePoints)
3510 QUICK_ENTRY_POINT_INFO(pNewStringFromString)
3511 QUICK_ENTRY_POINT_INFO(pNewStringFromStringBuffer)
3512 QUICK_ENTRY_POINT_INFO(pNewStringFromStringBuilder)
Hiroshi Yamauchi1cc71eb2015-05-07 10:47:27 -07003513 QUICK_ENTRY_POINT_INFO(pReadBarrierJni)
Roland Levillain02b75802016-07-13 11:54:35 +01003514 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg00)
3515 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg01)
3516 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg02)
3517 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg03)
3518 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg04)
3519 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg05)
3520 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg06)
3521 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg07)
3522 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg08)
3523 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg09)
3524 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg10)
3525 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg11)
3526 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg12)
3527 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg13)
3528 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg14)
3529 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg15)
3530 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg16)
3531 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg17)
3532 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg18)
3533 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg19)
3534 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg20)
3535 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg21)
3536 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg22)
3537 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg23)
3538 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg24)
3539 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg25)
3540 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg26)
3541 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg27)
3542 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg28)
3543 QUICK_ENTRY_POINT_INFO(pReadBarrierMarkReg29)
Man Cao1aee9002015-07-14 22:31:42 -07003544 QUICK_ENTRY_POINT_INFO(pReadBarrierSlow)
Roland Levillain0d5a2812015-11-13 10:07:31 +00003545 QUICK_ENTRY_POINT_INFO(pReadBarrierForRootSlow)
Igor Murashkin9d4b6da2016-07-29 09:51:58 -07003546
3547 QUICK_ENTRY_POINT_INFO(pJniMethodFastStart)
3548 QUICK_ENTRY_POINT_INFO(pJniMethodFastEnd)
Ian Rogersdd7624d2014-03-14 17:43:00 -07003549#undef QUICK_ENTRY_POINT_INFO
3550
Elliott Hughes98e20172012-04-24 15:38:13 -07003551 os << offset;
Elliott Hughes28fa76d2012-04-09 17:31:46 -07003552}
3553
jeffhao94d6df42012-11-26 16:02:12 -08003554void Thread::QuickDeliverException() {
Ian Rogers62d6c772013-02-27 08:32:07 -08003555 // Get exception from thread.
Mathieu Chartierf5769e12017-01-10 15:54:41 -08003556 ObjPtr<mirror::Throwable> exception = GetException();
Dave Allison0aded082013-11-07 13:15:11 -08003557 CHECK(exception != nullptr);
Mingyao Yangf711f2c2016-05-23 12:29:39 -07003558 if (exception == GetDeoptimizationException()) {
3559 artDeoptimize(this);
3560 UNREACHABLE();
3561 }
3562
Roland Levillaina78f5b62017-09-29 13:50:44 +01003563 ReadBarrier::MaybeAssertToSpaceInvariant(exception.Ptr());
Roland Levillainb77b6982017-06-08 18:03:48 +01003564
Mingyao Yangf711f2c2016-05-23 12:29:39 -07003565 // This is a real exception: let the instrumentation know about it.
3566 instrumentation::Instrumentation* instrumentation = Runtime::Current()->GetInstrumentation();
Alex Light6e1607e2017-08-23 10:06:18 -07003567 if (instrumentation->HasExceptionThrownListeners() &&
Mingyao Yangf711f2c2016-05-23 12:29:39 -07003568 IsExceptionThrownByCurrentMethod(exception)) {
3569 // Instrumentation may cause GC so keep the exception object safe.
3570 StackHandleScope<1> hs(this);
Mathieu Chartierf5769e12017-01-10 15:54:41 -08003571 HandleWrapperObjPtr<mirror::Throwable> h_exception(hs.NewHandleWrapper(&exception));
Vladimir Marko19711d42019-04-12 14:05:34 +01003572 instrumentation->ExceptionThrownEvent(this, exception);
Mingyao Yangf711f2c2016-05-23 12:29:39 -07003573 }
Alex Light0aa7a5a2018-10-10 15:58:14 +00003574 // Does instrumentation need to deoptimize the stack or otherwise go to interpreter for something?
3575 // Note: we do this *after* reporting the exception to instrumentation in case it now requires
3576 // deoptimization. It may happen if a debugger is attached and requests new events (single-step,
3577 // breakpoint, ...) when the exception is reported.
Alex Lightbe1f8d02018-10-15 11:44:42 -07003578 //
3579 // Note we need to check for both force_frame_pop and force_retry_instruction. The first is
3580 // expected to happen fairly regularly but the second can only happen if we are using
3581 // instrumentation trampolines (for example with DDMS tracing). That forces us to do deopt later
3582 // and see every frame being popped. We don't need to handle it any differently.
Alex Light0aa7a5a2018-10-10 15:58:14 +00003583 ShadowFrame* cf;
David Srbecky1cbac5c2019-07-18 20:05:32 +01003584 bool force_deopt = false;
3585 if (Runtime::Current()->AreNonStandardExitsEnabled() || kIsDebugBuild) {
Alex Light0aa7a5a2018-10-10 15:58:14 +00003586 NthCallerVisitor visitor(this, 0, false);
3587 visitor.WalkStack();
3588 cf = visitor.GetCurrentShadowFrame();
3589 if (cf == nullptr) {
3590 cf = FindDebuggerShadowFrame(visitor.GetFrameId());
3591 }
Alex Lightbe1f8d02018-10-15 11:44:42 -07003592 bool force_frame_pop = cf != nullptr && cf->GetForcePopFrame();
3593 bool force_retry_instr = cf != nullptr && cf->GetForceRetryInstruction();
Alex Light0aa7a5a2018-10-10 15:58:14 +00003594 if (kIsDebugBuild && force_frame_pop) {
David Srbecky1cbac5c2019-07-18 20:05:32 +01003595 DCHECK(Runtime::Current()->AreNonStandardExitsEnabled());
Alex Light0aa7a5a2018-10-10 15:58:14 +00003596 NthCallerVisitor penultimate_visitor(this, 1, false);
3597 penultimate_visitor.WalkStack();
3598 ShadowFrame* penultimate_frame = penultimate_visitor.GetCurrentShadowFrame();
3599 if (penultimate_frame == nullptr) {
3600 penultimate_frame = FindDebuggerShadowFrame(penultimate_visitor.GetFrameId());
3601 }
Alex Light0aa7a5a2018-10-10 15:58:14 +00003602 }
David Srbecky1cbac5c2019-07-18 20:05:32 +01003603 if (force_retry_instr) {
3604 DCHECK(Runtime::Current()->AreNonStandardExitsEnabled());
3605 }
Alex Lightbe1f8d02018-10-15 11:44:42 -07003606 force_deopt = force_frame_pop || force_retry_instr;
Alex Light0aa7a5a2018-10-10 15:58:14 +00003607 }
Alex Light3dacdd62019-03-12 15:45:47 +00003608 if (Dbg::IsForcedInterpreterNeededForException(this) || force_deopt || IsForceInterpreter()) {
Mingyao Yangf711f2c2016-05-23 12:29:39 -07003609 NthCallerVisitor visitor(this, 0, false);
3610 visitor.WalkStack();
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003611 if (Runtime::Current()->IsAsyncDeoptimizeable(visitor.caller_pc)) {
Mingyao Yang2ee17902017-08-30 11:37:08 -07003612 // method_type shouldn't matter due to exception handling.
3613 const DeoptimizationMethodType method_type = DeoptimizationMethodType::kDefault;
Sebastien Hertz520633b2015-09-08 17:03:36 +02003614 // Save the exception into the deoptimization context so it can be restored
3615 // before entering the interpreter.
Alex Lightbe1f8d02018-10-15 11:44:42 -07003616 if (force_deopt) {
Alex Light0aa7a5a2018-10-10 15:58:14 +00003617 VLOG(deopt) << "Deopting " << cf->GetMethod()->PrettyMethod() << " for frame-pop";
3618 DCHECK(Runtime::Current()->AreNonStandardExitsEnabled());
3619 // Get rid of the exception since we are doing a framepop instead.
Alex Lightbe1f8d02018-10-15 11:44:42 -07003620 LOG(WARNING) << "Suppressing pending exception for retry-instruction/frame-pop: "
3621 << exception->Dump();
Alex Light0aa7a5a2018-10-10 15:58:14 +00003622 ClearException();
3623 }
Nicolas Geoffray73be1e82015-09-17 15:22:56 +01003624 PushDeoptimizationContext(
Mingyao Yang2ee17902017-08-30 11:37:08 -07003625 JValue(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003626 /* is_reference= */ false,
Alex Lightbe1f8d02018-10-15 11:44:42 -07003627 (force_deopt ? nullptr : exception),
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003628 /* from_code= */ false,
Mingyao Yang2ee17902017-08-30 11:37:08 -07003629 method_type);
Mingyao Yangf711f2c2016-05-23 12:29:39 -07003630 artDeoptimize(this);
3631 UNREACHABLE();
Nicolas Geoffraye91e7952020-01-23 10:15:56 +00003632 } else if (visitor.caller != nullptr) {
Nicolas Geoffray433b79a2017-01-30 20:54:45 +00003633 LOG(WARNING) << "Got a deoptimization request on un-deoptimizable method "
3634 << visitor.caller->PrettyMethod();
Sebastien Hertz520633b2015-09-08 17:03:36 +02003635 }
3636 }
Mingyao Yangf711f2c2016-05-23 12:29:39 -07003637
Ian Rogers28ad40d2011-10-27 15:19:26 -07003638 // Don't leave exception visible while we try to find the handler, which may cause class
Elliott Hughesd07986f2011-12-06 18:27:45 -08003639 // resolution.
Ian Rogers28ad40d2011-10-27 15:19:26 -07003640 ClearException();
Mingyao Yangf711f2c2016-05-23 12:29:39 -07003641 QuickExceptionHandler exception_handler(this, false);
3642 exception_handler.FindCatch(exception);
Roland Levillainb77b6982017-06-08 18:03:48 +01003643 if (exception_handler.GetClearException()) {
3644 // Exception was cleared as part of delivery.
3645 DCHECK(!IsExceptionPending());
3646 } else {
3647 // Exception was put back with a throw location.
3648 DCHECK(IsExceptionPending());
Roland Levillaina78f5b62017-09-29 13:50:44 +01003649 // Check the to-space invariant on the re-installed exception (if applicable).
3650 ReadBarrier::MaybeAssertToSpaceInvariant(GetException());
Roland Levillainb77b6982017-06-08 18:03:48 +01003651 }
Sebastien Hertzfd3077e2014-04-23 10:32:43 +02003652 exception_handler.DoLongJump();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07003653}
3654
Ian Rogersbdb03912011-09-14 00:55:44 -07003655Context* Thread::GetLongJumpContext() {
Ian Rogersdd7624d2014-03-14 17:43:00 -07003656 Context* result = tlsPtr_.long_jump_context;
Dave Allison0aded082013-11-07 13:15:11 -08003657 if (result == nullptr) {
Ian Rogersbdb03912011-09-14 00:55:44 -07003658 result = Context::Create();
Ian Rogers0399dde2012-06-06 17:09:28 -07003659 } else {
Ian Rogersdd7624d2014-03-14 17:43:00 -07003660 tlsPtr_.long_jump_context = nullptr; // Avoid context being shared.
Mathieu Chartier67022432012-11-29 18:04:50 -08003661 result->Reset();
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07003662 }
Ian Rogersbdb03912011-09-14 00:55:44 -07003663 return result;
Shih-wei Liao1a18c8c2011-08-14 17:47:36 -07003664}
3665
Andreas Gampec7d878d2018-11-19 18:42:06 +00003666ArtMethod* Thread::GetCurrentMethod(uint32_t* dex_pc_out,
Hiroshi Yamauchi02f365f2017-02-03 15:06:00 -08003667 bool check_suspended,
3668 bool abort_on_error) const {
Andreas Gampe1b5c5c82018-09-27 10:42:18 -07003669 // Note: this visitor may return with a method set, but dex_pc_ being DexFile:kDexNoIndex. This is
3670 // so we don't abort in a special situation (thinlocked monitor) when dumping the Java
3671 // stack.
Andreas Gampec7d878d2018-11-19 18:42:06 +00003672 ArtMethod* method = nullptr;
3673 uint32_t dex_pc = dex::kDexNoIndex;
3674 StackVisitor::WalkStack(
3675 [&](const StackVisitor* visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
3676 ArtMethod* m = visitor->GetMethod();
3677 if (m->IsRuntimeMethod()) {
3678 // Continue if this is a runtime method.
3679 return true;
3680 }
3681 method = m;
3682 dex_pc = visitor->GetDexPc(abort_on_error);
3683 return false;
3684 },
3685 const_cast<Thread*>(this),
3686 /* context= */ nullptr,
3687 StackVisitor::StackWalkKind::kIncludeInlinedFrames,
3688 check_suspended);
3689
3690 if (dex_pc_out != nullptr) {
3691 *dex_pc_out = dex_pc;
Elliott Hughes9fd66f52011-10-16 12:13:26 -07003692 }
Andreas Gampec7d878d2018-11-19 18:42:06 +00003693 return method;
jeffhao33dc7712011-11-09 17:54:24 -08003694}
3695
Mathieu Chartierf5769e12017-01-10 15:54:41 -08003696bool Thread::HoldsLock(ObjPtr<mirror::Object> object) const {
3697 return object != nullptr && object->GetLockOwnerThreadId() == GetThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -07003698}
3699
Roland Levillainad0777d2018-02-12 20:00:18 +00003700extern std::vector<StackReference<mirror::Object>*> GetProxyReferenceArguments(ArtMethod** sp)
Roland Levillainfa854e42018-02-07 13:09:55 +00003701 REQUIRES_SHARED(Locks::mutator_lock_);
3702
Ian Rogers40e3bac2012-11-20 00:09:14 -08003703// RootVisitor parameters are: (const Object* obj, size_t vreg, const StackVisitor* visitor).
Andreas Gampe585da952016-12-02 14:52:29 -08003704template <typename RootVisitor, bool kPrecise = false>
Ian Rogers0399dde2012-06-06 17:09:28 -07003705class ReferenceMapVisitor : public StackVisitor {
Ian Rogersd6b1f612011-09-27 13:38:14 -07003706 public:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07003707 ReferenceMapVisitor(Thread* thread, Context* context, RootVisitor& visitor)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003708 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffray8e5bd182015-05-06 11:34:34 +01003709 // We are visiting the references in compiled frames, so we do not need
3710 // to know the inlined frames.
3711 : StackVisitor(thread, context, StackVisitor::StackWalkKind::kSkipInlinedFrames),
3712 visitor_(visitor) {}
Ian Rogersd6b1f612011-09-27 13:38:14 -07003713
Andreas Gampefa6a1b02018-09-07 08:11:55 -07003714 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -07003715 if (false) {
David Sehr709b0702016-10-13 09:12:37 -07003716 LOG(INFO) << "Visiting stack roots in " << ArtMethod::PrettyMethod(GetMethod())
Sebastien Hertz714f1752014-04-28 15:03:08 +02003717 << StringPrintf("@ PC:%04x", GetDexPc());
Brian Carlstrom6a4be3a2011-10-20 16:34:03 -07003718 }
Ian Rogers0399dde2012-06-06 17:09:28 -07003719 ShadowFrame* shadow_frame = GetCurrentShadowFrame();
Dave Allison0aded082013-11-07 13:15:11 -08003720 if (shadow_frame != nullptr) {
Sebastien Hertz714f1752014-04-28 15:03:08 +02003721 VisitShadowFrame(shadow_frame);
Nicolas Geoffray013d1ee2019-12-04 16:18:15 +00003722 } else if (GetCurrentOatQuickMethodHeader()->IsNterpMethodHeader()) {
3723 VisitNterpFrame();
Sebastien Hertz714f1752014-04-28 15:03:08 +02003724 } else {
3725 VisitQuickFrame();
3726 }
3727 return true;
3728 }
3729
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003730 void VisitShadowFrame(ShadowFrame* shadow_frame) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07003731 ArtMethod* m = shadow_frame->GetMethod();
Mathieu Chartier10e5ea92015-08-13 12:56:31 -07003732 VisitDeclaringClass(m);
Hiroshi Yamauchi92d1a662014-05-15 21:43:59 -07003733 DCHECK(m != nullptr);
Sebastien Hertz714f1752014-04-28 15:03:08 +02003734 size_t num_regs = shadow_frame->NumberOfVRegs();
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +01003735 // handle scope for JNI or References for interpreter.
3736 for (size_t reg = 0; reg < num_regs; ++reg) {
3737 mirror::Object* ref = shadow_frame->GetVRegReference(reg);
3738 if (ref != nullptr) {
3739 mirror::Object* new_ref = ref;
3740 visitor_(&new_ref, reg, this);
3741 if (new_ref != ref) {
3742 shadow_frame->SetVRegReference(reg, new_ref);
TDYa127ce4cc0d2012-11-18 16:59:53 -08003743 }
3744 }
Sebastien Hertz714f1752014-04-28 15:03:08 +02003745 }
Andreas Gampe03ec9302015-08-27 17:41:47 -07003746 // Mark lock count map required for structured locking checks.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003747 shadow_frame->GetLockCountData().VisitMonitors(visitor_, /* vreg= */ -1, this);
Sebastien Hertz714f1752014-04-28 15:03:08 +02003748 }
3749
3750 private:
Mathieu Chartier10e5ea92015-08-13 12:56:31 -07003751 // 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 -07003752 // is executing. We need to ensure that the code stays mapped. NO_THREAD_SAFETY_ANALYSIS since
3753 // the threads do not all hold the heap bitmap lock for parallel GC.
3754 void VisitDeclaringClass(ArtMethod* method)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07003755 REQUIRES_SHARED(Locks::mutator_lock_)
Mathieu Chartierd5f3f322016-03-21 14:05:56 -07003756 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierf5769e12017-01-10 15:54:41 -08003757 ObjPtr<mirror::Class> klass = method->GetDeclaringClassUnchecked<kWithoutReadBarrier>();
Mathieu Chartier10e5ea92015-08-13 12:56:31 -07003758 // klass can be null for runtime methods.
3759 if (klass != nullptr) {
Mathieu Chartierd5f3f322016-03-21 14:05:56 -07003760 if (kVerifyImageObjectsMarked) {
3761 gc::Heap* const heap = Runtime::Current()->GetHeap();
3762 gc::space::ContinuousSpace* space = heap->FindContinuousSpaceFromObject(klass,
Andreas Gampe98ea9d92018-10-19 14:06:15 -07003763 /*fail_ok=*/true);
Mathieu Chartierd5f3f322016-03-21 14:05:56 -07003764 if (space != nullptr && space->IsImageSpace()) {
3765 bool failed = false;
Mathieu Chartierf5769e12017-01-10 15:54:41 -08003766 if (!space->GetLiveBitmap()->Test(klass.Ptr())) {
Mathieu Chartierd5f3f322016-03-21 14:05:56 -07003767 failed = true;
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07003768 LOG(FATAL_WITHOUT_ABORT) << "Unmarked object in image " << *space;
Mathieu Chartierf5769e12017-01-10 15:54:41 -08003769 } else if (!heap->GetLiveBitmap()->Test(klass.Ptr())) {
Mathieu Chartierd5f3f322016-03-21 14:05:56 -07003770 failed = true;
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07003771 LOG(FATAL_WITHOUT_ABORT) << "Unmarked object in image through live bitmap " << *space;
Mathieu Chartierd5f3f322016-03-21 14:05:56 -07003772 }
3773 if (failed) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07003774 GetThread()->Dump(LOG_STREAM(FATAL_WITHOUT_ABORT));
3775 space->AsImageSpace()->DumpSections(LOG_STREAM(FATAL_WITHOUT_ABORT));
3776 LOG(FATAL_WITHOUT_ABORT) << "Method@" << method->GetDexMethodIndex() << ":" << method
Mathieu Chartierf5769e12017-01-10 15:54:41 -08003777 << " klass@" << klass.Ptr();
Mathieu Chartierd5f3f322016-03-21 14:05:56 -07003778 // Pretty info last in case it crashes.
David Sehr709b0702016-10-13 09:12:37 -07003779 LOG(FATAL) << "Method " << method->PrettyMethod() << " klass "
3780 << klass->PrettyClass();
Mathieu Chartierd5f3f322016-03-21 14:05:56 -07003781 }
3782 }
3783 }
Mathieu Chartierf5769e12017-01-10 15:54:41 -08003784 mirror::Object* new_ref = klass.Ptr();
Alex Light0054aa52019-09-10 16:46:48 -07003785 visitor_(&new_ref, /* vreg= */ JavaFrameRootInfo::kMethodDeclaringClass, this);
Mathieu Chartier10e5ea92015-08-13 12:56:31 -07003786 if (new_ref != klass) {
Mathieu Chartierf5769e12017-01-10 15:54:41 -08003787 method->CASDeclaringClass(klass.Ptr(), new_ref->AsClass());
Mathieu Chartier10e5ea92015-08-13 12:56:31 -07003788 }
3789 }
3790 }
3791
Nicolas Geoffray013d1ee2019-12-04 16:18:15 +00003792 void VisitNterpFrame() REQUIRES_SHARED(Locks::mutator_lock_) {
3793 ArtMethod** cur_quick_frame = GetCurrentQuickFrame();
3794 StackReference<mirror::Object>* vreg_ref_base =
3795 reinterpret_cast<StackReference<mirror::Object>*>(NterpGetReferenceArray(cur_quick_frame));
3796 StackReference<mirror::Object>* vreg_int_base =
3797 reinterpret_cast<StackReference<mirror::Object>*>(NterpGetRegistersArray(cur_quick_frame));
3798 CodeItemDataAccessor accessor((*cur_quick_frame)->DexInstructionData());
3799 const uint16_t num_regs = accessor.RegistersSize();
3800 // An nterp frame has two arrays: a dex register array and a reference array
3801 // that shadows the dex register array but only containing references
3802 // (non-reference dex registers have nulls). See nterp_helpers.cc.
3803 for (size_t reg = 0; reg < num_regs; ++reg) {
3804 StackReference<mirror::Object>* ref_addr = vreg_ref_base + reg;
3805 mirror::Object* ref = ref_addr->AsMirrorPtr();
3806 if (ref != nullptr) {
3807 mirror::Object* new_ref = ref;
3808 visitor_(&new_ref, reg, this);
3809 if (new_ref != ref) {
3810 ref_addr->Assign(new_ref);
3811 StackReference<mirror::Object>* int_addr = vreg_int_base + reg;
3812 int_addr->Assign(new_ref);
3813 }
3814 }
3815 }
3816 }
3817
Andreas Gampe585da952016-12-02 14:52:29 -08003818 template <typename T>
3819 ALWAYS_INLINE
3820 inline void VisitQuickFrameWithVregCallback() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier10e5ea92015-08-13 12:56:31 -07003821 ArtMethod** cur_quick_frame = GetCurrentQuickFrame();
Mathieu Chartiere401d142015-04-22 13:56:20 -07003822 DCHECK(cur_quick_frame != nullptr);
Mathieu Chartier10e5ea92015-08-13 12:56:31 -07003823 ArtMethod* m = *cur_quick_frame;
3824 VisitDeclaringClass(m);
Andreas Gampecf4035a2014-05-28 22:43:01 -07003825
Sebastien Hertz714f1752014-04-28 15:03:08 +02003826 // Process register map (which native and runtime methods don't have)
Jeff Hao84949432016-05-13 14:46:28 -07003827 if (!m->IsNative() && !m->IsRuntimeMethod() && (!m->IsProxyMethod() || m->IsConstructor())) {
Nicolas Geoffray524e7ea2015-10-16 17:13:34 +01003828 const OatQuickMethodHeader* method_header = GetCurrentOatQuickMethodHeader();
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01003829 DCHECK(method_header->IsOptimized());
Vladimir Marko78baed52018-10-11 10:44:58 +01003830 StackReference<mirror::Object>* vreg_base =
3831 reinterpret_cast<StackReference<mirror::Object>*>(cur_quick_frame);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01003832 uintptr_t native_pc_offset = method_header->NativeQuickPcOffset(GetCurrentQuickFramePc());
David Srbecky0d4567f2019-05-30 22:45:40 +01003833 CodeInfo code_info = kPrecise
3834 ? CodeInfo(method_header) // We will need dex register maps.
3835 : CodeInfo::DecodeGcMasksOnly(method_header);
David Srbecky052f8ca2018-04-26 15:42:54 +01003836 StackMap map = code_info.GetStackMapForNativePcOffset(native_pc_offset);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01003837 DCHECK(map.IsValid());
Andreas Gampe585da952016-12-02 14:52:29 -08003838
David Srbecky052f8ca2018-04-26 15:42:54 +01003839 T vreg_info(m, code_info, map, visitor_);
Andreas Gampe585da952016-12-02 14:52:29 -08003840
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01003841 // Visit stack entries that hold pointers.
David Srbecky052f8ca2018-04-26 15:42:54 +01003842 BitMemoryRegion stack_mask = code_info.GetStackMaskOf(map);
David Srbecky4b59d102018-05-29 21:46:10 +00003843 for (size_t i = 0; i < stack_mask.size_in_bits(); ++i) {
David Srbecky45aa5982016-03-18 02:15:09 +00003844 if (stack_mask.LoadBit(i)) {
Roland Levillainfa854e42018-02-07 13:09:55 +00003845 StackReference<mirror::Object>* ref_addr = vreg_base + i;
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01003846 mirror::Object* ref = ref_addr->AsMirrorPtr();
3847 if (ref != nullptr) {
3848 mirror::Object* new_ref = ref;
Andreas Gampe585da952016-12-02 14:52:29 -08003849 vreg_info.VisitStack(&new_ref, i, this);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01003850 if (ref != new_ref) {
3851 ref_addr->Assign(new_ref);
David Srbeckya2d29a32018-08-03 11:06:38 +01003852 }
Nicolas Geoffray39468442014-09-02 15:17:15 +01003853 }
3854 }
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01003855 }
3856 // Visit callee-save registers that hold pointers.
David Srbecky052f8ca2018-04-26 15:42:54 +01003857 uint32_t register_mask = code_info.GetRegisterMaskOf(map);
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01003858 for (size_t i = 0; i < BitSizeOf<uint32_t>(); ++i) {
3859 if (register_mask & (1 << i)) {
3860 mirror::Object** ref_addr = reinterpret_cast<mirror::Object**>(GetGPRAddress(i));
Hiroshi Yamauchieb1680f2016-09-12 12:10:08 -07003861 if (kIsDebugBuild && ref_addr == nullptr) {
3862 std::string thread_name;
3863 GetThread()->GetThreadName(thread_name);
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07003864 LOG(FATAL_WITHOUT_ABORT) << "On thread " << thread_name;
Hiroshi Yamauchieb1680f2016-09-12 12:10:08 -07003865 DescribeStack(GetThread());
3866 LOG(FATAL) << "Found an unsaved callee-save register " << i << " (null GPRAddress) "
3867 << "set in register_mask=" << register_mask << " at " << DescribeLocation();
3868 }
Vladimir Marko9d07e3d2016-03-31 12:02:28 +01003869 if (*ref_addr != nullptr) {
Andreas Gampe585da952016-12-02 14:52:29 -08003870 vreg_info.VisitRegister(ref_addr, i, this);
Shih-wei Liao4f894e32011-09-27 21:33:19 -07003871 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07003872 }
3873 }
Roland Levillainad0777d2018-02-12 20:00:18 +00003874 } else if (!m->IsRuntimeMethod() && m->IsProxyMethod()) {
3875 // If this is a proxy method, visit its reference arguments.
3876 DCHECK(!m->IsStatic());
Roland Levillainfa854e42018-02-07 13:09:55 +00003877 DCHECK(!m->IsNative());
Roland Levillainad0777d2018-02-12 20:00:18 +00003878 std::vector<StackReference<mirror::Object>*> ref_addrs =
3879 GetProxyReferenceArguments(cur_quick_frame);
3880 for (StackReference<mirror::Object>* ref_addr : ref_addrs) {
3881 mirror::Object* ref = ref_addr->AsMirrorPtr();
3882 if (ref != nullptr) {
3883 mirror::Object* new_ref = ref;
Alex Light0054aa52019-09-10 16:46:48 -07003884 visitor_(&new_ref, /* vreg= */ JavaFrameRootInfo::kProxyReferenceArgument, this);
Roland Levillainad0777d2018-02-12 20:00:18 +00003885 if (ref != new_ref) {
3886 ref_addr->Assign(new_ref);
3887 }
Roland Levillainfa854e42018-02-07 13:09:55 +00003888 }
3889 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07003890 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07003891 }
3892
Andreas Gampe585da952016-12-02 14:52:29 -08003893 void VisitQuickFrame() REQUIRES_SHARED(Locks::mutator_lock_) {
3894 if (kPrecise) {
3895 VisitQuickFramePrecise();
3896 } else {
3897 VisitQuickFrameNonPrecise();
3898 }
3899 }
3900
3901 void VisitQuickFrameNonPrecise() REQUIRES_SHARED(Locks::mutator_lock_) {
3902 struct UndefinedVRegInfo {
3903 UndefinedVRegInfo(ArtMethod* method ATTRIBUTE_UNUSED,
3904 const CodeInfo& code_info ATTRIBUTE_UNUSED,
Andreas Gampe585da952016-12-02 14:52:29 -08003905 const StackMap& map ATTRIBUTE_UNUSED,
3906 RootVisitor& _visitor)
3907 : visitor(_visitor) {
3908 }
3909
3910 ALWAYS_INLINE
3911 void VisitStack(mirror::Object** ref,
3912 size_t stack_index ATTRIBUTE_UNUSED,
3913 const StackVisitor* stack_visitor)
3914 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light0054aa52019-09-10 16:46:48 -07003915 visitor(ref, JavaFrameRootInfo::kImpreciseVreg, stack_visitor);
Andreas Gampe585da952016-12-02 14:52:29 -08003916 }
3917
3918 ALWAYS_INLINE
3919 void VisitRegister(mirror::Object** ref,
3920 size_t register_index ATTRIBUTE_UNUSED,
3921 const StackVisitor* stack_visitor)
3922 REQUIRES_SHARED(Locks::mutator_lock_) {
Alex Light0054aa52019-09-10 16:46:48 -07003923 visitor(ref, JavaFrameRootInfo::kImpreciseVreg, stack_visitor);
Andreas Gampe585da952016-12-02 14:52:29 -08003924 }
3925
3926 RootVisitor& visitor;
3927 };
3928 VisitQuickFrameWithVregCallback<UndefinedVRegInfo>();
3929 }
3930
3931 void VisitQuickFramePrecise() REQUIRES_SHARED(Locks::mutator_lock_) {
3932 struct StackMapVRegInfo {
3933 StackMapVRegInfo(ArtMethod* method,
3934 const CodeInfo& _code_info,
Andreas Gampe585da952016-12-02 14:52:29 -08003935 const StackMap& map,
3936 RootVisitor& _visitor)
David Sehr0225f8e2018-01-31 08:52:24 +00003937 : number_of_dex_registers(method->DexInstructionData().RegistersSize()),
Andreas Gampe585da952016-12-02 14:52:29 -08003938 code_info(_code_info),
David Srbeckyfd89b072018-06-03 12:00:22 +01003939 dex_register_map(code_info.GetDexRegisterMapOf(map)),
Andreas Gampe585da952016-12-02 14:52:29 -08003940 visitor(_visitor) {
Artem Serov2808be82018-12-20 19:15:11 +00003941 DCHECK_EQ(dex_register_map.size(), number_of_dex_registers);
Andreas Gampe585da952016-12-02 14:52:29 -08003942 }
3943
3944 // TODO: If necessary, we should consider caching a reverse map instead of the linear
3945 // lookups for each location.
3946 void FindWithType(const size_t index,
3947 const DexRegisterLocation::Kind kind,
3948 mirror::Object** ref,
3949 const StackVisitor* stack_visitor)
3950 REQUIRES_SHARED(Locks::mutator_lock_) {
3951 bool found = false;
3952 for (size_t dex_reg = 0; dex_reg != number_of_dex_registers; ++dex_reg) {
David Srbeckye1402122018-06-13 18:20:45 +01003953 DexRegisterLocation location = dex_register_map[dex_reg];
Andreas Gampe585da952016-12-02 14:52:29 -08003954 if (location.GetKind() == kind && static_cast<size_t>(location.GetValue()) == index) {
3955 visitor(ref, dex_reg, stack_visitor);
3956 found = true;
3957 }
3958 }
3959
3960 if (!found) {
Alex Light0054aa52019-09-10 16:46:48 -07003961 // If nothing found, report with unknown.
3962 visitor(ref, JavaFrameRootInfo::kUnknownVreg, stack_visitor);
Andreas Gampe585da952016-12-02 14:52:29 -08003963 }
3964 }
3965
3966 void VisitStack(mirror::Object** ref, size_t stack_index, const StackVisitor* stack_visitor)
3967 REQUIRES_SHARED(Locks::mutator_lock_) {
3968 const size_t stack_offset = stack_index * kFrameSlotSize;
3969 FindWithType(stack_offset,
3970 DexRegisterLocation::Kind::kInStack,
3971 ref,
3972 stack_visitor);
3973 }
3974
3975 void VisitRegister(mirror::Object** ref,
3976 size_t register_index,
3977 const StackVisitor* stack_visitor)
3978 REQUIRES_SHARED(Locks::mutator_lock_) {
3979 FindWithType(register_index,
3980 DexRegisterLocation::Kind::kInRegister,
3981 ref,
3982 stack_visitor);
3983 }
3984
3985 size_t number_of_dex_registers;
3986 const CodeInfo& code_info;
Andreas Gampe585da952016-12-02 14:52:29 -08003987 DexRegisterMap dex_register_map;
3988 RootVisitor& visitor;
3989 };
3990 VisitQuickFrameWithVregCallback<StackMapVRegInfo>();
3991 }
3992
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07003993 // Visitor for when we visit a root.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07003994 RootVisitor& visitor_;
Ian Rogersd6b1f612011-09-27 13:38:14 -07003995};
3996
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07003997class RootCallbackVisitor {
3998 public:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07003999 RootCallbackVisitor(RootVisitor* visitor, uint32_t tid) : visitor_(visitor), tid_(tid) {}
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07004000
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07004001 void operator()(mirror::Object** obj, size_t vreg, const StackVisitor* stack_visitor) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07004002 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07004003 visitor_->VisitRoot(obj, JavaFrameRootInfo(tid_, stack_visitor, vreg));
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07004004 }
4005
4006 private:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07004007 RootVisitor* const visitor_;
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08004008 const uint32_t tid_;
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07004009};
4010
Alex Light55eccdf2019-10-07 13:51:13 +00004011void Thread::VisitReflectiveTargets(ReflectiveValueVisitor* visitor) {
4012 for (BaseReflectiveHandleScope* brhs = GetTopReflectiveHandleScope();
4013 brhs != nullptr;
4014 brhs = brhs->GetLink()) {
4015 brhs->VisitTargets(visitor);
4016 }
4017}
4018
Andreas Gampe585da952016-12-02 14:52:29 -08004019template <bool kPrecise>
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07004020void Thread::VisitRoots(RootVisitor* visitor) {
Hans Boehm0882af22017-08-31 15:21:57 -07004021 const pid_t thread_id = GetThreadId();
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07004022 visitor->VisitRootIfNonNull(&tlsPtr_.opeer, RootInfo(kRootThreadObject, thread_id));
Sebastien Hertzfd3077e2014-04-23 10:32:43 +02004023 if (tlsPtr_.exception != nullptr && tlsPtr_.exception != GetDeoptimizationException()) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07004024 visitor->VisitRoot(reinterpret_cast<mirror::Object**>(&tlsPtr_.exception),
Sebastien Hertz07474662015-08-25 15:12:33 +00004025 RootInfo(kRootNativeStack, thread_id));
Elliott Hughesd369bb72011-09-12 14:41:14 -07004026 }
Alex Light848574c2017-09-25 16:59:39 -07004027 if (tlsPtr_.async_exception != nullptr) {
4028 visitor->VisitRoot(reinterpret_cast<mirror::Object**>(&tlsPtr_.async_exception),
4029 RootInfo(kRootNativeStack, thread_id));
4030 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07004031 visitor->VisitRootIfNonNull(&tlsPtr_.monitor_enter_object, RootInfo(kRootNativeStack, thread_id));
Ian Rogers55256cb2017-12-21 17:07:11 -08004032 tlsPtr_.jni_env->VisitJniLocalRoots(visitor, RootInfo(kRootJNILocal, thread_id));
4033 tlsPtr_.jni_env->VisitMonitorRoots(visitor, RootInfo(kRootJNIMonitor, thread_id));
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07004034 HandleScopeVisitRoots(visitor, thread_id);
Sebastien Hertz07474662015-08-25 15:12:33 +00004035 // Visit roots for deoptimization.
Mingyao Yang1f2d3ba2015-05-18 12:12:50 -07004036 if (tlsPtr_.stacked_shadow_frame_record != nullptr) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07004037 RootCallbackVisitor visitor_to_callback(visitor, thread_id);
Andreas Gampe585da952016-12-02 14:52:29 -08004038 ReferenceMapVisitor<RootCallbackVisitor, kPrecise> mapper(this, nullptr, visitor_to_callback);
Mingyao Yang1f2d3ba2015-05-18 12:12:50 -07004039 for (StackedShadowFrameRecord* record = tlsPtr_.stacked_shadow_frame_record;
4040 record != nullptr;
4041 record = record->GetLink()) {
4042 for (ShadowFrame* shadow_frame = record->GetShadowFrame();
4043 shadow_frame != nullptr;
4044 shadow_frame = shadow_frame->GetLink()) {
4045 mapper.VisitShadowFrame(shadow_frame);
4046 }
Sebastien Hertz714f1752014-04-28 15:03:08 +02004047 }
4048 }
Mingyao Yang99170c62015-07-06 11:10:37 -07004049 for (DeoptimizationContextRecord* record = tlsPtr_.deoptimization_context_stack;
4050 record != nullptr;
4051 record = record->GetLink()) {
4052 if (record->IsReference()) {
4053 visitor->VisitRootIfNonNull(record->GetReturnValueAsGCRoot(),
Sebastien Hertz07474662015-08-25 15:12:33 +00004054 RootInfo(kRootThreadObject, thread_id));
Andreas Gampe2a0d4ec2014-06-02 22:05:22 -07004055 }
Mingyao Yang99170c62015-07-06 11:10:37 -07004056 visitor->VisitRootIfNonNull(record->GetPendingExceptionAsGCRoot(),
4057 RootInfo(kRootThreadObject, thread_id));
4058 }
4059 if (tlsPtr_.frame_id_to_shadow_frame != nullptr) {
4060 RootCallbackVisitor visitor_to_callback(visitor, thread_id);
Andreas Gampe585da952016-12-02 14:52:29 -08004061 ReferenceMapVisitor<RootCallbackVisitor, kPrecise> mapper(this, nullptr, visitor_to_callback);
Mingyao Yang99170c62015-07-06 11:10:37 -07004062 for (FrameIdToShadowFrame* record = tlsPtr_.frame_id_to_shadow_frame;
4063 record != nullptr;
4064 record = record->GetNext()) {
4065 mapper.VisitShadowFrame(record->GetShadowFrame());
4066 }
Andreas Gampe2a0d4ec2014-06-02 22:05:22 -07004067 }
Mathieu Chartierd0ad2ee2015-03-31 14:59:59 -07004068 for (auto* verifier = tlsPtr_.method_verifier; verifier != nullptr; verifier = verifier->link_) {
4069 verifier->VisitRoots(visitor, RootInfo(kRootNativeStack, thread_id));
Mathieu Chartier12d625f2015-03-13 11:33:37 -07004070 }
Ian Rogersd6b1f612011-09-27 13:38:14 -07004071 // Visit roots on this thread's stack
Mathieu Chartiera62b4532017-04-26 13:16:25 -07004072 RuntimeContextType context;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07004073 RootCallbackVisitor visitor_to_callback(visitor, thread_id);
Mathieu Chartiera62b4532017-04-26 13:16:25 -07004074 ReferenceMapVisitor<RootCallbackVisitor, kPrecise> mapper(this, &context, visitor_to_callback);
Andreas Gampe585da952016-12-02 14:52:29 -08004075 mapper.template WalkStack<StackVisitor::CountTransitions::kNo>(false);
Nicolas Geoffraye91e7952020-01-23 10:15:56 +00004076 for (auto& entry : *GetInstrumentationStack()) {
4077 visitor->VisitRootIfNonNull(&entry.second.this_object_, RootInfo(kRootVMInternal, thread_id));
Ian Rogers62d6c772013-02-27 08:32:07 -08004078 }
Nicolas Geoffraye3f775b2019-12-04 14:41:52 +00004079}
4080
4081void Thread::SweepInterpreterCache(IsMarkedVisitor* visitor) {
Nicolas Geoffraya00b54b2019-12-03 14:36:42 +00004082 for (InterpreterCache::Entry& entry : GetInterpreterCache()->GetArray()) {
4083 const Instruction* inst = reinterpret_cast<const Instruction*>(entry.first);
Nicolas Geoffraye3f775b2019-12-04 14:41:52 +00004084 if (inst != nullptr) {
4085 if (inst->Opcode() == Instruction::NEW_INSTANCE ||
4086 inst->Opcode() == Instruction::CHECK_CAST ||
4087 inst->Opcode() == Instruction::INSTANCE_OF ||
4088 inst->Opcode() == Instruction::NEW_ARRAY ||
4089 inst->Opcode() == Instruction::CONST_CLASS) {
4090 mirror::Class* cls = reinterpret_cast<mirror::Class*>(entry.second);
4091 if (cls == nullptr || cls == Runtime::GetWeakClassSentinel()) {
4092 // Entry got deleted in a previous sweep.
4093 continue;
4094 }
4095 Runtime::ProcessWeakClass(
4096 reinterpret_cast<GcRoot<mirror::Class>*>(&entry.second),
4097 visitor,
4098 Runtime::GetWeakClassSentinel());
4099 } else if (inst->Opcode() == Instruction::CONST_STRING ||
4100 inst->Opcode() == Instruction::CONST_STRING_JUMBO) {
4101 mirror::Object* object = reinterpret_cast<mirror::Object*>(entry.second);
4102 mirror::Object* new_object = visitor->IsMarked(object);
4103 // We know the string is marked because it's a strongly-interned string that
4104 // is always alive (see b/117621117 for trying to make those strings weak).
4105 // The IsMarked implementation of the CMS collector returns
4106 // null for newly allocated objects, but we know those haven't moved. Therefore,
4107 // only update the entry if we get a different non-null string.
4108 if (new_object != nullptr && new_object != object) {
4109 entry.second = reinterpret_cast<size_t>(new_object);
4110 }
4111 }
Nicolas Geoffraya00b54b2019-12-03 14:36:42 +00004112 }
4113 }
Elliott Hughes410c0c82011-09-01 17:58:25 -07004114}
4115
Andreas Gampe585da952016-12-02 14:52:29 -08004116void Thread::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
4117 if ((flags & VisitRootFlags::kVisitRootFlagPrecise) != 0) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -07004118 VisitRoots</* kPrecise= */ true>(visitor);
Andreas Gampe585da952016-12-02 14:52:29 -08004119 } else {
Andreas Gampe98ea9d92018-10-19 14:06:15 -07004120 VisitRoots</* kPrecise= */ false>(visitor);
Andreas Gampe585da952016-12-02 14:52:29 -08004121 }
4122}
4123
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07004124class VerifyRootVisitor : public SingleRootVisitor {
4125 public:
4126 void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01004127 override REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07004128 VerifyObject(root);
4129 }
4130};
jeffhao25045522012-03-13 19:34:37 -07004131
Ian Rogers04d7aa92013-03-16 14:29:17 -07004132void Thread::VerifyStackImpl() {
Andreas Gamped4901292017-05-30 18:41:34 -07004133 if (Runtime::Current()->GetHeap()->IsObjectValidationEnabled()) {
4134 VerifyRootVisitor visitor;
4135 std::unique_ptr<Context> context(Context::Create());
4136 RootCallbackVisitor visitor_to_callback(&visitor, GetThreadId());
4137 ReferenceMapVisitor<RootCallbackVisitor> mapper(this, context.get(), visitor_to_callback);
4138 mapper.WalkStack();
4139 }
jeffhao25045522012-03-13 19:34:37 -07004140}
jeffhao25045522012-03-13 19:34:37 -07004141
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004142// Set the stack end to that to be used during a stack overflow
4143void Thread::SetStackEndForStackOverflow() {
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07004144 // During stack overflow we allow use of the full stack.
Ian Rogersdd7624d2014-03-14 17:43:00 -07004145 if (tlsPtr_.stack_end == tlsPtr_.stack_begin) {
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07004146 // However, we seem to have already extended to use the full stack.
4147 LOG(ERROR) << "Need to increase kStackOverflowReservedBytes (currently "
Andreas Gampe7ea6f792014-07-14 16:21:44 -07004148 << GetStackOverflowReservedBytes(kRuntimeISA) << ")?";
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07004149 DumpStack(LOG_STREAM(ERROR));
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07004150 LOG(FATAL) << "Recursive stack overflow.";
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004151 }
4152
Ian Rogersdd7624d2014-03-14 17:43:00 -07004153 tlsPtr_.stack_end = tlsPtr_.stack_begin;
Dave Allison648d7112014-07-25 16:15:27 -07004154
4155 // Remove the stack overflow protection if is it set up.
4156 bool implicit_stack_check = !Runtime::Current()->ExplicitStackOverflowChecks();
4157 if (implicit_stack_check) {
4158 if (!UnprotectStack()) {
4159 LOG(ERROR) << "Unable to remove stack protection for stack overflow";
4160 }
4161 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004162}
4163
Mathieu Chartier6bc77742017-04-18 17:46:23 -07004164void Thread::SetTlab(uint8_t* start, uint8_t* end, uint8_t* limit) {
Mathieu Chartier692fafd2013-11-29 17:24:40 -08004165 DCHECK_LE(start, end);
Mathieu Chartier6bc77742017-04-18 17:46:23 -07004166 DCHECK_LE(end, limit);
Ian Rogersdd7624d2014-03-14 17:43:00 -07004167 tlsPtr_.thread_local_start = start;
4168 tlsPtr_.thread_local_pos = tlsPtr_.thread_local_start;
4169 tlsPtr_.thread_local_end = end;
Mathieu Chartier6bc77742017-04-18 17:46:23 -07004170 tlsPtr_.thread_local_limit = limit;
Ian Rogersdd7624d2014-03-14 17:43:00 -07004171 tlsPtr_.thread_local_objects = 0;
Mathieu Chartier692fafd2013-11-29 17:24:40 -08004172}
4173
Mathieu Chartierc4bf6672020-01-13 13:07:16 -08004174void Thread::ResetTlab() {
4175 SetTlab(nullptr, nullptr, nullptr);
4176}
4177
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07004178bool Thread::HasTlab() const {
Mathieu Chartierc4bf6672020-01-13 13:07:16 -08004179 const bool has_tlab = tlsPtr_.thread_local_pos != nullptr;
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07004180 if (has_tlab) {
Ian Rogersdd7624d2014-03-14 17:43:00 -07004181 DCHECK(tlsPtr_.thread_local_start != nullptr && tlsPtr_.thread_local_end != nullptr);
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07004182 } else {
Ian Rogersdd7624d2014-03-14 17:43:00 -07004183 DCHECK(tlsPtr_.thread_local_start == nullptr && tlsPtr_.thread_local_end == nullptr);
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07004184 }
4185 return has_tlab;
4186}
4187
Elliott Hughes330304d2011-08-12 14:28:05 -07004188std::ostream& operator<<(std::ostream& os, const Thread& thread) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004189 thread.ShortDump(os);
Elliott Hughes330304d2011-08-12 14:28:05 -07004190 return os;
4191}
4192
Andreas Gampe2c2d2a02016-03-17 21:27:19 -07004193bool Thread::ProtectStack(bool fatal_on_error) {
Dave Allison648d7112014-07-25 16:15:27 -07004194 void* pregion = tlsPtr_.stack_begin - kStackOverflowProtectedSize;
4195 VLOG(threads) << "Protecting stack at " << pregion;
4196 if (mprotect(pregion, kStackOverflowProtectedSize, PROT_NONE) == -1) {
Andreas Gampe2c2d2a02016-03-17 21:27:19 -07004197 if (fatal_on_error) {
4198 LOG(FATAL) << "Unable to create protected region in stack for implicit overflow check. "
4199 "Reason: "
4200 << strerror(errno) << " size: " << kStackOverflowProtectedSize;
4201 }
4202 return false;
Dave Allison648d7112014-07-25 16:15:27 -07004203 }
Andreas Gampe2c2d2a02016-03-17 21:27:19 -07004204 return true;
Dave Allison648d7112014-07-25 16:15:27 -07004205}
4206
4207bool Thread::UnprotectStack() {
4208 void* pregion = tlsPtr_.stack_begin - kStackOverflowProtectedSize;
4209 VLOG(threads) << "Unprotecting stack at " << pregion;
4210 return mprotect(pregion, kStackOverflowProtectedSize, PROT_READ|PROT_WRITE) == 0;
4211}
4212
Mathieu Chartierd0ad2ee2015-03-31 14:59:59 -07004213void Thread::PushVerifier(verifier::MethodVerifier* verifier) {
4214 verifier->link_ = tlsPtr_.method_verifier;
Mathieu Chartier12d625f2015-03-13 11:33:37 -07004215 tlsPtr_.method_verifier = verifier;
4216}
4217
Mathieu Chartierd0ad2ee2015-03-31 14:59:59 -07004218void Thread::PopVerifier(verifier::MethodVerifier* verifier) {
Mathieu Chartier12d625f2015-03-13 11:33:37 -07004219 CHECK_EQ(tlsPtr_.method_verifier, verifier);
Mathieu Chartierd0ad2ee2015-03-31 14:59:59 -07004220 tlsPtr_.method_verifier = verifier->link_;
Mathieu Chartier12d625f2015-03-13 11:33:37 -07004221}
4222
Mathieu Chartier14c3bf92015-07-13 14:35:43 -07004223size_t Thread::NumberOfHeldMutexes() const {
4224 size_t count = 0;
4225 for (BaseMutex* mu : tlsPtr_.held_mutexes) {
Mathieu Chartier90ef3db2015-08-04 15:19:41 -07004226 count += mu != nullptr ? 1 : 0;
Mathieu Chartier14c3bf92015-07-13 14:35:43 -07004227 }
4228 return count;
4229}
4230
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00004231void Thread::DeoptimizeWithDeoptimizationException(JValue* result) {
4232 DCHECK_EQ(GetException(), Thread::GetDeoptimizationException());
4233 ClearException();
4234 ShadowFrame* shadow_frame =
4235 PopStackedShadowFrame(StackedShadowFrameType::kDeoptimizationShadowFrame);
Mathieu Chartierf5769e12017-01-10 15:54:41 -08004236 ObjPtr<mirror::Throwable> pending_exception;
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00004237 bool from_code = false;
Mingyao Yang2ee17902017-08-30 11:37:08 -07004238 DeoptimizationMethodType method_type;
4239 PopDeoptimizationContext(result, &pending_exception, &from_code, &method_type);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00004240 SetTopOfStack(nullptr);
4241 SetTopOfShadowStack(shadow_frame);
4242
4243 // Restore the exception that was pending before deoptimization then interpret the
4244 // deoptimized frames.
4245 if (pending_exception != nullptr) {
4246 SetException(pending_exception);
4247 }
Mingyao Yang2ee17902017-08-30 11:37:08 -07004248 interpreter::EnterInterpreterFromDeoptimize(this,
4249 shadow_frame,
4250 result,
4251 from_code,
4252 method_type);
Nicolas Geoffrayb331feb2016-02-05 16:51:53 +00004253}
4254
Alex Light848574c2017-09-25 16:59:39 -07004255void Thread::SetAsyncException(ObjPtr<mirror::Throwable> new_exception) {
4256 CHECK(new_exception != nullptr);
David Srbeckyd3883902019-02-26 17:29:32 +00004257 Runtime::Current()->SetAsyncExceptionsThrown();
Alex Light848574c2017-09-25 16:59:39 -07004258 if (kIsDebugBuild) {
4259 // Make sure we are in a checkpoint.
4260 MutexLock mu(Thread::Current(), *Locks::thread_suspend_count_lock_);
4261 CHECK(this == Thread::Current() || GetSuspendCount() >= 1)
4262 << "It doesn't look like this was called in a checkpoint! this: "
4263 << this << " count: " << GetSuspendCount();
4264 }
4265 tlsPtr_.async_exception = new_exception.Ptr();
4266}
4267
4268bool Thread::ObserveAsyncException() {
4269 DCHECK(this == Thread::Current());
4270 if (tlsPtr_.async_exception != nullptr) {
4271 if (tlsPtr_.exception != nullptr) {
4272 LOG(WARNING) << "Overwriting pending exception with async exception. Pending exception is: "
4273 << tlsPtr_.exception->Dump();
4274 LOG(WARNING) << "Async exception is " << tlsPtr_.async_exception->Dump();
4275 }
4276 tlsPtr_.exception = tlsPtr_.async_exception;
4277 tlsPtr_.async_exception = nullptr;
4278 return true;
4279 } else {
4280 return IsExceptionPending();
4281 }
4282}
4283
Mathieu Chartier0795f232016-09-27 18:43:30 -07004284void Thread::SetException(ObjPtr<mirror::Throwable> new_exception) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07004285 CHECK(new_exception != nullptr);
4286 // TODO: DCHECK(!IsExceptionPending());
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07004287 tlsPtr_.exception = new_exception.Ptr();
Mathieu Chartiere42888f2016-04-14 10:49:19 -07004288}
4289
Andreas Gampe2c19f5b2016-11-28 08:10:18 -08004290bool Thread::IsAotCompiler() {
4291 return Runtime::Current()->IsAotCompiler();
4292}
4293
Andreas Gampe202f85a2017-02-06 10:23:26 -08004294mirror::Object* Thread::GetPeerFromOtherThread() const {
Nicolas Geoffrayffc8cad2017-02-10 10:59:22 +00004295 DCHECK(tlsPtr_.jpeer == nullptr);
4296 mirror::Object* peer = tlsPtr_.opeer;
Andreas Gampe202f85a2017-02-06 10:23:26 -08004297 if (kUseReadBarrier && Current()->GetIsGcMarking()) {
4298 // We may call Thread::Dump() in the middle of the CC thread flip and this thread's stack
4299 // may have not been flipped yet and peer may be a from-space (stale) ref. So explicitly
4300 // mark/forward it here.
4301 peer = art::ReadBarrier::Mark(peer);
4302 }
4303 return peer;
4304}
4305
Mathieu Chartier3768ade2017-05-02 14:04:39 -07004306void Thread::SetReadBarrierEntrypoints() {
4307 // Make sure entrypoints aren't null.
Andreas Gampe98ea9d92018-10-19 14:06:15 -07004308 UpdateReadBarrierEntrypoints(&tlsPtr_.quick_entrypoints, /* is_active=*/ true);
Mathieu Chartier3768ade2017-05-02 14:04:39 -07004309}
4310
David Srbecky912f36c2018-09-08 12:22:58 +01004311void Thread::ClearAllInterpreterCaches() {
4312 static struct ClearInterpreterCacheClosure : Closure {
Yi Kong39402542019-03-24 02:47:16 -07004313 void Run(Thread* thread) override {
David Srbecky912f36c2018-09-08 12:22:58 +01004314 thread->GetInterpreterCache()->Clear(thread);
4315 }
4316 } closure;
4317 Runtime::Current()->GetThreadList()->RunCheckpoint(&closure);
4318}
4319
Orion Hodson119733d2019-01-30 15:14:41 +00004320
Andreas Gampee5d23982019-01-08 10:34:26 -08004321void Thread::ReleaseLongJumpContextInternal() {
4322 // Each QuickExceptionHandler gets a long jump context and uses
4323 // it for doing the long jump, after finding catch blocks/doing deoptimization.
4324 // Both finding catch blocks and deoptimization can trigger another
4325 // exception such as a result of class loading. So there can be nested
4326 // cases of exception handling and multiple contexts being used.
4327 // ReleaseLongJumpContext tries to save the context in tlsPtr_.long_jump_context
4328 // for reuse so there is no need to always allocate a new one each time when
4329 // getting a context. Since we only keep one context for reuse, delete the
4330 // existing one since the passed in context is yet to be used for longjump.
4331 delete tlsPtr_.long_jump_context;
4332}
4333
Orion Hodson119733d2019-01-30 15:14:41 +00004334void Thread::SetNativePriority(int new_priority) {
Nicolas Geoffrayfa595882019-08-06 17:40:09 +01004335 PaletteStatus status = PaletteSchedSetPriority(GetTid(), new_priority);
Orion Hodson119733d2019-01-30 15:14:41 +00004336 CHECK(status == PaletteStatus::kOkay || status == PaletteStatus::kCheckErrno);
4337}
4338
Nicolas Geoffrayfa595882019-08-06 17:40:09 +01004339int Thread::GetNativePriority() const {
Orion Hodson119733d2019-01-30 15:14:41 +00004340 int priority = 0;
Nicolas Geoffrayfa595882019-08-06 17:40:09 +01004341 PaletteStatus status = PaletteSchedGetPriority(GetTid(), &priority);
Orion Hodson119733d2019-01-30 15:14:41 +00004342 CHECK(status == PaletteStatus::kOkay || status == PaletteStatus::kCheckErrno);
4343 return priority;
4344}
4345
Alex Lighte0b2ce42019-02-21 19:23:42 +00004346bool Thread::IsSystemDaemon() const {
4347 if (GetPeer() == nullptr) {
4348 return false;
4349 }
4350 return jni::DecodeArtField(
4351 WellKnownClasses::java_lang_Thread_systemDaemon)->GetBoolean(GetPeer());
4352}
4353
Alex Lightb7c640d2019-03-20 15:52:13 -07004354ScopedExceptionStorage::ScopedExceptionStorage(art::Thread* self)
4355 : self_(self), hs_(self_), excp_(hs_.NewHandle<art::mirror::Throwable>(self_->GetException())) {
4356 self_->ClearException();
4357}
4358
Alex Light79d6c802019-06-27 15:50:11 +00004359void ScopedExceptionStorage::SuppressOldException(const char* message) {
4360 CHECK(self_->IsExceptionPending()) << *self_;
4361 ObjPtr<mirror::Throwable> old_suppressed(excp_.Get());
4362 excp_.Assign(self_->GetException());
4363 LOG(WARNING) << message << "Suppressing old exception: " << old_suppressed->Dump();
4364 self_->ClearException();
4365}
4366
Alex Lightb7c640d2019-03-20 15:52:13 -07004367ScopedExceptionStorage::~ScopedExceptionStorage() {
Alex Light79d6c802019-06-27 15:50:11 +00004368 CHECK(!self_->IsExceptionPending()) << *self_;
Alex Lightb7c640d2019-03-20 15:52:13 -07004369 if (!excp_.IsNull()) {
4370 self_->SetException(excp_.Get());
4371 }
4372}
4373
Elliott Hughes8daa0922011-09-11 13:46:25 -07004374} // namespace art