blob: 35411e2660656abc19c8ad19ae47be7fdf9e1b6c [file] [log] [blame]
Elliott Hughes8daa0922011-09-11 13:46: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 */
16
17#include "thread_list.h"
18
Mathieu Chartier6f365cc2014-04-23 12:42:27 -070019#define ATRACE_TAG ATRACE_TAG_DALVIK
20
21#include <cutils/trace.h>
Elliott Hughesabbe07d2012-06-05 17:42:23 -070022#include <dirent.h>
Ian Rogersd9c4fc92013-10-01 19:45:43 -070023#include <ScopedLocalRef.h>
24#include <ScopedUtfChars.h>
Elliott Hughesabbe07d2012-06-05 17:42:23 -070025#include <sys/types.h>
Elliott Hughes038a8062011-09-18 14:12:41 -070026#include <unistd.h>
27
Elliott Hughes76b61672012-12-12 17:47:30 -080028#include "base/mutex.h"
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -070029#include "base/mutex-inl.h"
Sameer Abu Asala8439542013-02-14 16:06:42 -080030#include "base/timing_logger.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070031#include "debugger.h"
Ian Rogersd9c4fc92013-10-01 19:45:43 -070032#include "jni_internal.h"
33#include "lock_word.h"
34#include "monitor.h"
35#include "scoped_thread_state_change.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080036#include "thread.h"
Elliott Hughesabbe07d2012-06-05 17:42:23 -070037#include "utils.h"
Ian Rogersd9c4fc92013-10-01 19:45:43 -070038#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070039
Elliott Hughes8daa0922011-09-11 13:46:25 -070040namespace art {
41
Mathieu Chartier251755c2014-07-15 18:10:25 -070042static constexpr uint64_t kLongThreadSuspendThreshold = MsToNs(5);
43
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -080044ThreadList::ThreadList()
Chao-ying Fu9e369312014-05-21 11:20:52 -070045 : suspend_all_count_(0), debug_suspend_all_count_(0),
Ian Rogersc604d732012-10-14 16:09:54 -070046 thread_exit_cond_("thread exit condition variable", *Locks::thread_list_lock_) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -070047 CHECK(Monitor::IsValidLockWord(LockWord::FromThinLockId(kMaxThreadId, 1)));
Elliott Hughes8daa0922011-09-11 13:46:25 -070048}
49
50ThreadList::~ThreadList() {
Elliott Hughese52e49b2012-04-02 16:05:44 -070051 // Detach the current thread if necessary. If we failed to start, there might not be any threads.
Elliott Hughes6a144332012-04-03 13:07:11 -070052 // We need to detach the current thread here in case there's another thread waiting to join with
53 // us.
Mathieu Chartierfec72f42014-10-09 12:57:58 -070054 bool contains = false;
55 {
56 Thread* self = Thread::Current();
57 MutexLock mu(self, *Locks::thread_list_lock_);
58 contains = Contains(self);
59 }
60 if (contains) {
Elliott Hughes8daa0922011-09-11 13:46:25 -070061 Runtime::Current()->DetachCurrentThread();
62 }
Elliott Hughes6a144332012-04-03 13:07:11 -070063
64 WaitForOtherNonDaemonThreadsToExit();
Ian Rogers00f7d0e2012-07-19 15:28:27 -070065 // TODO: there's an unaddressed race here where a thread may attach during shutdown, see
66 // Thread::Init.
Elliott Hughes6a144332012-04-03 13:07:11 -070067 SuspendAllDaemonThreads();
Elliott Hughes8daa0922011-09-11 13:46:25 -070068}
69
70bool ThreadList::Contains(Thread* thread) {
71 return find(list_.begin(), list_.end(), thread) != list_.end();
72}
73
Elliott Hughesabbe07d2012-06-05 17:42:23 -070074bool ThreadList::Contains(pid_t tid) {
Mathieu Chartier02e25112013-08-14 16:14:24 -070075 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -070076 if (thread->GetTid() == tid) {
Elliott Hughesabbe07d2012-06-05 17:42:23 -070077 return true;
78 }
79 }
80 return false;
81}
82
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -070083pid_t ThreadList::GetLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -070084 return Locks::thread_list_lock_->GetExclusiveOwnerTid();
Elliott Hughesaccd83d2011-10-17 14:25:58 -070085}
86
Mathieu Chartier590fee92013-09-13 13:46:47 -070087void ThreadList::DumpNativeStacks(std::ostream& os) {
88 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
89 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -070090 os << "DUMPING THREAD " << thread->GetTid() << "\n";
Christopher Ferrisa2cee182014-04-16 19:13:59 -070091 DumpNativeStack(os, thread->GetTid(), "\t");
Mathieu Chartier590fee92013-09-13 13:46:47 -070092 os << "\n";
93 }
94}
95
Elliott Hughesc967f782012-04-16 10:23:15 -070096void ThreadList::DumpForSigQuit(std::ostream& os) {
Ian Rogers7b078e82014-09-10 14:44:24 -070097 Dump(os);
Elliott Hughesabbe07d2012-06-05 17:42:23 -070098 DumpUnattachedThreads(os);
99}
100
Ian Rogerscfaa4552012-11-26 21:00:08 -0800101static void DumpUnattachedThread(std::ostream& os, pid_t tid) NO_THREAD_SAFETY_ANALYSIS {
102 // TODO: No thread safety analysis as DumpState with a NULL thread won't access fields, should
103 // refactor DumpState to avoid skipping analysis.
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700104 Thread::DumpState(os, NULL, tid);
105 DumpKernelStack(os, tid, " kernel: ", false);
Brian Carlstromed8b7232012-06-27 17:54:47 -0700106 // TODO: Reenable this when the native code in system_server can handle it.
107 // Currently "adb shell kill -3 `pid system_server`" will cause it to exit.
108 if (false) {
Christopher Ferrisa2cee182014-04-16 19:13:59 -0700109 DumpNativeStack(os, tid, " native: ");
Brian Carlstromed8b7232012-06-27 17:54:47 -0700110 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700111 os << "\n";
112}
113
114void ThreadList::DumpUnattachedThreads(std::ostream& os) {
115 DIR* d = opendir("/proc/self/task");
116 if (!d) {
117 return;
118 }
119
Ian Rogers50b35e22012-10-04 10:09:15 -0700120 Thread* self = Thread::Current();
Elliott Hughes4696b5b2012-10-30 10:35:10 -0700121 dirent* e;
122 while ((e = readdir(d)) != NULL) {
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700123 char* end;
Elliott Hughes4696b5b2012-10-30 10:35:10 -0700124 pid_t tid = strtol(e->d_name, &end, 10);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700125 if (!*end) {
126 bool contains;
127 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700128 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700129 contains = Contains(tid);
130 }
131 if (!contains) {
132 DumpUnattachedThread(os, tid);
133 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700134 }
135 }
136 closedir(d);
Elliott Hughesff738062012-02-03 15:00:42 -0800137}
138
Ian Rogers7b078e82014-09-10 14:44:24 -0700139// A closure used by Thread::Dump.
140class DumpCheckpoint FINAL : public Closure {
141 public:
142 explicit DumpCheckpoint(std::ostream* os) : os_(os), barrier_(0) {}
143
144 void Run(Thread* thread) OVERRIDE {
145 // Note thread and self may not be equal if thread was already suspended at the point of the
146 // request.
147 Thread* self = Thread::Current();
148 std::ostringstream local_os;
149 {
150 ScopedObjectAccess soa(self);
151 thread->Dump(local_os);
152 }
153 local_os << "\n";
154 {
155 // Use the logging lock to ensure serialization when writing to the common ostream.
156 MutexLock mu(self, *Locks::logging_lock_);
157 *os_ << local_os.str();
158 }
159 barrier_.Pass(self);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700160 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700161
162 void WaitForThreadsToRunThroughCheckpoint(size_t threads_running_checkpoint) {
163 Thread* self = Thread::Current();
164 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
Ian Rogers2156ff12014-09-13 19:20:54 -0700165 const uint32_t kWaitTimeoutMs = 10000;
166 bool timed_out = barrier_.Increment(self, threads_running_checkpoint, kWaitTimeoutMs);
167 if (timed_out) {
168 LOG(kIsDebugBuild ? FATAL : ERROR) << "Unexpected time out during dump checkpoint.";
169 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700170 }
171
172 private:
173 // The common stream that will accumulate all the dumps.
174 std::ostream* const os_;
175 // The barrier to be passed through and for the requestor to wait upon.
176 Barrier barrier_;
177};
178
179void ThreadList::Dump(std::ostream& os) {
180 {
181 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
182 os << "DALVIK THREADS (" << list_.size() << "):\n";
183 }
184 DumpCheckpoint checkpoint(&os);
185 size_t threads_running_checkpoint = RunCheckpoint(&checkpoint);
186 checkpoint.WaitForThreadsToRunThroughCheckpoint(threads_running_checkpoint);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700187}
188
Ian Rogers50b35e22012-10-04 10:09:15 -0700189void ThreadList::AssertThreadsAreSuspended(Thread* self, Thread* ignore1, Thread* ignore2) {
190 MutexLock mu(self, *Locks::thread_list_lock_);
191 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700192 for (const auto& thread : list_) {
jeffhao725a9572012-11-13 18:20:12 -0800193 if (thread != ignore1 && thread != ignore2) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700194 CHECK(thread->IsSuspended())
195 << "\nUnsuspended thread: <<" << *thread << "\n"
196 << "self: <<" << *Thread::Current();
197 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700198 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700199}
200
Ian Rogers66aee5c2012-08-15 17:17:47 -0700201#if HAVE_TIMED_RWLOCK
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700202// Attempt to rectify locks so that we dump thread list with required locks before exiting.
Ian Rogers7b078e82014-09-10 14:44:24 -0700203static void UnsafeLogFatalForThreadSuspendAllTimeout() __attribute__((noreturn));
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100204static void UnsafeLogFatalForThreadSuspendAllTimeout() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700205 Runtime* runtime = Runtime::Current();
206 std::ostringstream ss;
207 ss << "Thread suspend timeout\n";
Mathieu Chartier5869a2c2014-10-08 14:26:23 -0700208 Locks::mutator_lock_->Dump(ss);
209 ss << "\n";
Ian Rogers7b078e82014-09-10 14:44:24 -0700210 runtime->GetThreadList()->Dump(ss);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700211 LOG(FATAL) << ss.str();
Ian Rogers719d1a32014-03-06 12:13:39 -0800212 exit(0);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700213}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700214#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700215
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800216// Unlike suspending all threads where we can wait to acquire the mutator_lock_, suspending an
217// individual thread requires polling. delay_us is the requested sleep and total_delay_us
218// accumulates the total time spent sleeping for timeouts. The first sleep is just a yield,
219// subsequently sleeps increase delay_us from 1ms to 500ms by doubling.
Ian Rogersf3d874c2014-07-17 18:52:42 -0700220static void ThreadSuspendSleep(Thread* self, useconds_t* delay_us, useconds_t* total_delay_us) {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800221 useconds_t new_delay_us = (*delay_us) * 2;
222 CHECK_GE(new_delay_us, *delay_us);
223 if (new_delay_us < 500000) { // Don't allow sleeping to be more than 0.5s.
224 *delay_us = new_delay_us;
225 }
226 if (*delay_us == 0) {
227 sched_yield();
228 // Default to 1 milliseconds (note that this gets multiplied by 2 before the first sleep).
229 *delay_us = 500;
230 } else {
231 usleep(*delay_us);
232 *total_delay_us += *delay_us;
233 }
234}
235
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700236size_t ThreadList::RunCheckpoint(Closure* checkpoint_function) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700237 Thread* self = Thread::Current();
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800238 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
239 Locks::thread_list_lock_->AssertNotHeld(self);
240 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
241 if (kDebugLocking) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700242 CHECK_NE(self->GetState(), kRunnable);
243 }
244
245 std::vector<Thread*> suspended_count_modified_threads;
246 size_t count = 0;
247 {
248 // Call a checkpoint function for each thread, threads which are suspend get their checkpoint
249 // manually called.
250 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700251 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700252 for (const auto& thread : list_) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700253 if (thread != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700254 while (true) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700255 if (thread->RequestCheckpoint(checkpoint_function)) {
Dave Allison0aded082013-11-07 13:15:11 -0800256 // This thread will run its checkpoint some time in the near future.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700257 count++;
258 break;
259 } else {
260 // We are probably suspended, try to make sure that we stay suspended.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700261 // The thread switched back to runnable.
262 if (thread->GetState() == kRunnable) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700263 // Spurious fail, try again.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700264 continue;
265 }
266 thread->ModifySuspendCount(self, +1, false);
267 suspended_count_modified_threads.push_back(thread);
268 break;
269 }
270 }
271 }
272 }
273 }
274
275 // Run the checkpoint on ourself while we wait for threads to suspend.
276 checkpoint_function->Run(self);
277
278 // Run the checkpoint on the suspended threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700279 for (const auto& thread : suspended_count_modified_threads) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700280 if (!thread->IsSuspended()) {
281 // Wait until the thread is suspended.
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800282 useconds_t total_delay_us = 0;
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700283 do {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800284 useconds_t delay_us = 100;
Ian Rogersf3d874c2014-07-17 18:52:42 -0700285 ThreadSuspendSleep(self, &delay_us, &total_delay_us);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700286 } while (!thread->IsSuspended());
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800287 // Shouldn't need to wait for longer than 1000 microseconds.
288 constexpr useconds_t kLongWaitThresholdUS = 1000;
289 if (UNLIKELY(total_delay_us > kLongWaitThresholdUS)) {
290 LOG(WARNING) << "Waited " << total_delay_us << " us for thread suspend!";
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700291 }
292 }
293 // We know for sure that the thread is suspended at this point.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700294 checkpoint_function->Run(thread);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700295 {
296 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
297 thread->ModifySuspendCount(self, -1, false);
298 }
299 }
300
Mathieu Chartier664bebf2012-11-12 16:54:11 -0800301 {
302 // Imitate ResumeAll, threads may be waiting on Thread::resume_cond_ since we raised their
303 // suspend count. Now the suspend_count_ is lowered so we must do the broadcast.
304 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
305 Thread::resume_cond_->Broadcast(self);
306 }
307
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700308 // Add one for self.
309 return count + suspended_count_modified_threads.size() + 1;
310}
311
Dave Allison39c3bfb2014-01-28 18:33:52 -0800312// Request that a checkpoint function be run on all active (non-suspended)
313// threads. Returns the number of successful requests.
314size_t ThreadList::RunCheckpointOnRunnableThreads(Closure* checkpoint_function) {
315 Thread* self = Thread::Current();
Ian Rogers7b078e82014-09-10 14:44:24 -0700316 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
317 Locks::thread_list_lock_->AssertNotHeld(self);
318 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
319 CHECK_NE(self->GetState(), kRunnable);
Dave Allison39c3bfb2014-01-28 18:33:52 -0800320
321 size_t count = 0;
322 {
323 // Call a checkpoint function for each non-suspended thread.
324 MutexLock mu(self, *Locks::thread_list_lock_);
325 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
326 for (const auto& thread : list_) {
327 if (thread != self) {
328 if (thread->RequestCheckpoint(checkpoint_function)) {
329 // This thread will run its checkpoint some time in the near future.
330 count++;
331 }
332 }
333 }
334 }
335
336 // Return the number of threads that will run the checkpoint function.
337 return count;
338}
339
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700340void ThreadList::SuspendAll() {
341 Thread* self = Thread::Current();
342
Jeff Haoc5d824a2014-07-28 18:35:38 -0700343 if (self != nullptr) {
344 VLOG(threads) << *self << " SuspendAll starting...";
345 } else {
346 VLOG(threads) << "Thread[null] SuspendAll starting...";
347 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700348 ATRACE_BEGIN("Suspending mutator threads");
Mathieu Chartier251755c2014-07-15 18:10:25 -0700349 uint64_t start_time = NanoTime();
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700350
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800351 Locks::mutator_lock_->AssertNotHeld(self);
352 Locks::thread_list_lock_->AssertNotHeld(self);
353 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
Jeff Haoc5d824a2014-07-28 18:35:38 -0700354 if (kDebugLocking && self != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700355 CHECK_NE(self->GetState(), kRunnable);
356 }
357 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700358 MutexLock mu(self, *Locks::thread_list_lock_);
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800359 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
360 // Update global suspend all state for attaching threads.
361 ++suspend_all_count_;
362 // Increment everybody's suspend count (except our own).
363 for (const auto& thread : list_) {
364 if (thread == self) {
365 continue;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700366 }
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800367 VLOG(threads) << "requesting thread suspend: " << *thread;
368 thread->ModifySuspendCount(self, +1, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700369 }
370 }
371
Ian Rogers66aee5c2012-08-15 17:17:47 -0700372 // Block on the mutator lock until all Runnable threads release their share of access.
373#if HAVE_TIMED_RWLOCK
374 // Timeout if we wait more than 30 seconds.
Ian Rogers719d1a32014-03-06 12:13:39 -0800375 if (!Locks::mutator_lock_->ExclusiveLockWithTimeout(self, 30 * 1000, 0)) {
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100376 UnsafeLogFatalForThreadSuspendAllTimeout();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700377 }
Ian Rogers66aee5c2012-08-15 17:17:47 -0700378#else
Ian Rogers81d425b2012-09-27 16:03:43 -0700379 Locks::mutator_lock_->ExclusiveLock(self);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700380#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700381
Mathieu Chartier251755c2014-07-15 18:10:25 -0700382 uint64_t end_time = NanoTime();
383 if (end_time - start_time > kLongThreadSuspendThreshold) {
384 LOG(WARNING) << "Suspending all threads took: " << PrettyDuration(end_time - start_time);
385 }
386
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800387 if (kDebugLocking) {
388 // Debug check that all threads are suspended.
389 AssertThreadsAreSuspended(self, self);
390 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700391
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700392 ATRACE_END();
393 ATRACE_BEGIN("Mutator threads suspended");
394
Jeff Haoc5d824a2014-07-28 18:35:38 -0700395 if (self != nullptr) {
396 VLOG(threads) << *self << " SuspendAll complete";
397 } else {
398 VLOG(threads) << "Thread[null] SuspendAll complete";
399 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700400}
401
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700402void ThreadList::ResumeAll() {
403 Thread* self = Thread::Current();
404
Jeff Haoc5d824a2014-07-28 18:35:38 -0700405 if (self != nullptr) {
406 VLOG(threads) << *self << " ResumeAll starting";
407 } else {
408 VLOG(threads) << "Thread[null] ResumeAll starting";
409 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700410
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700411 ATRACE_END();
412 ATRACE_BEGIN("Resuming mutator threads");
413
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800414 if (kDebugLocking) {
415 // Debug check that all threads are suspended.
416 AssertThreadsAreSuspended(self, self);
417 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700418
Ian Rogers81d425b2012-09-27 16:03:43 -0700419 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700420 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700421 MutexLock mu(self, *Locks::thread_list_lock_);
422 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700423 // Update global suspend all state for attaching threads.
424 --suspend_all_count_;
425 // Decrement the suspend counts for all threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700426 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700427 if (thread == self) {
428 continue;
429 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700430 thread->ModifySuspendCount(self, -1, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700431 }
432
433 // Broadcast a notification to all suspended threads, some or all of
434 // which may choose to wake up. No need to wait for them.
Jeff Haoc5d824a2014-07-28 18:35:38 -0700435 if (self != nullptr) {
436 VLOG(threads) << *self << " ResumeAll waking others";
437 } else {
438 VLOG(threads) << "Thread[null] ResumeAll waking others";
439 }
Ian Rogersc604d732012-10-14 16:09:54 -0700440 Thread::resume_cond_->Broadcast(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700441 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700442 ATRACE_END();
Jeff Haoc5d824a2014-07-28 18:35:38 -0700443
444 if (self != nullptr) {
445 VLOG(threads) << *self << " ResumeAll complete";
446 } else {
447 VLOG(threads) << "Thread[null] ResumeAll complete";
448 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700449}
450
451void ThreadList::Resume(Thread* thread, bool for_debugger) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700452 Thread* self = Thread::Current();
453 DCHECK_NE(thread, self);
Brian Carlstromba32de42014-08-27 23:43:46 -0700454 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") starting..."
455 << (for_debugger ? " (debugger)" : "");
Elliott Hughes01158d72011-09-19 19:47:10 -0700456
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700457 {
458 // To check Contains.
Ian Rogers81d425b2012-09-27 16:03:43 -0700459 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700460 // To check IsSuspended.
Ian Rogers81d425b2012-09-27 16:03:43 -0700461 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
462 DCHECK(thread->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700463 if (!Contains(thread)) {
Brian Carlstromba32de42014-08-27 23:43:46 -0700464 // We only expect threads within the thread-list to have been suspended otherwise we can't
465 // stop such threads from delete-ing themselves.
466 LOG(ERROR) << "Resume(" << reinterpret_cast<void*>(thread)
467 << ") thread not within thread list";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700468 return;
469 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700470 thread->ModifySuspendCount(self, -1, for_debugger);
Elliott Hughes01158d72011-09-19 19:47:10 -0700471 }
472
473 {
Brian Carlstromba32de42014-08-27 23:43:46 -0700474 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") waking others";
Ian Rogers81d425b2012-09-27 16:03:43 -0700475 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700476 Thread::resume_cond_->Broadcast(self);
Elliott Hughes01158d72011-09-19 19:47:10 -0700477 }
478
Brian Carlstromba32de42014-08-27 23:43:46 -0700479 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") complete";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700480}
Elliott Hughes01158d72011-09-19 19:47:10 -0700481
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700482static void ThreadSuspendByPeerWarning(Thread* self, int level, const char* message, jobject peer) {
483 JNIEnvExt* env = self->GetJniEnv();
484 ScopedLocalRef<jstring>
485 scoped_name_string(env, (jstring)env->GetObjectField(peer,
486 WellKnownClasses::java_lang_Thread_name));
487 ScopedUtfChars scoped_name_chars(env, scoped_name_string.get());
488 if (scoped_name_chars.c_str() == NULL) {
489 LOG(level) << message << ": " << peer;
490 env->ExceptionClear();
491 } else {
492 LOG(level) << message << ": " << peer << ":" << scoped_name_chars.c_str();
493 }
494}
495
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700496Thread* ThreadList::SuspendThreadByPeer(jobject peer, bool request_suspension,
497 bool debug_suspension, bool* timed_out) {
498 static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
499 useconds_t total_delay_us = 0;
500 useconds_t delay_us = 0;
501 bool did_suspend_request = false;
502 *timed_out = false;
503 Thread* self = Thread::Current();
Brian Carlstromba32de42014-08-27 23:43:46 -0700504 VLOG(threads) << "SuspendThreadByPeer starting";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700505 while (true) {
506 Thread* thread;
507 {
Ian Rogersf3d874c2014-07-17 18:52:42 -0700508 // Note: this will transition to runnable and potentially suspend. We ensure only one thread
509 // is requesting another suspend, to avoid deadlock, by requiring this function be called
510 // holding Locks::thread_list_suspend_thread_lock_. Its important this thread suspend rather
511 // than request thread suspension, to avoid potential cycles in threads requesting each other
512 // suspend.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700513 ScopedObjectAccess soa(self);
514 MutexLock mu(self, *Locks::thread_list_lock_);
515 thread = Thread::FromManagedThread(soa, peer);
Brian Carlstromba32de42014-08-27 23:43:46 -0700516 if (thread == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700517 ThreadSuspendByPeerWarning(self, WARNING, "No such thread for suspend", peer);
Brian Carlstromba32de42014-08-27 23:43:46 -0700518 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700519 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700520 if (!Contains(thread)) {
521 VLOG(threads) << "SuspendThreadByPeer failed for unattached thread: "
522 << reinterpret_cast<void*>(thread);
523 return nullptr;
524 }
525 VLOG(threads) << "SuspendThreadByPeer found thread: " << *thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700526 {
527 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
528 if (request_suspension) {
529 thread->ModifySuspendCount(self, +1, debug_suspension);
530 request_suspension = false;
531 did_suspend_request = true;
532 } else {
533 // If the caller isn't requesting suspension, a suspension should have already occurred.
534 CHECK_GT(thread->GetSuspendCount(), 0);
535 }
536 // IsSuspended on the current thread will fail as the current thread is changed into
537 // Runnable above. As the suspend count is now raised if this is the current thread
538 // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
539 // to just explicitly handle the current thread in the callers to this code.
540 CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
541 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
542 // count, or else we've waited and it has self suspended) or is the current thread, we're
543 // done.
544 if (thread->IsSuspended()) {
Brian Carlstromba32de42014-08-27 23:43:46 -0700545 VLOG(threads) << "SuspendThreadByPeer thread suspended: " << *thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700546 return thread;
547 }
548 if (total_delay_us >= kTimeoutUs) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700549 ThreadSuspendByPeerWarning(self, FATAL, "Thread suspension timed out", peer);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700550 if (did_suspend_request) {
551 thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
552 }
553 *timed_out = true;
Brian Carlstromba32de42014-08-27 23:43:46 -0700554 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700555 }
556 }
557 // Release locks and come out of runnable state.
558 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700559 VLOG(threads) << "SuspendThreadByPeer sleeping to allow thread chance to suspend";
Ian Rogersf3d874c2014-07-17 18:52:42 -0700560 ThreadSuspendSleep(self, &delay_us, &total_delay_us);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700561 }
562}
563
564static void ThreadSuspendByThreadIdWarning(int level, const char* message, uint32_t thread_id) {
565 LOG(level) << StringPrintf("%s: %d", message, thread_id);
566}
567
568Thread* ThreadList::SuspendThreadByThreadId(uint32_t thread_id, bool debug_suspension,
569 bool* timed_out) {
570 static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
571 useconds_t total_delay_us = 0;
572 useconds_t delay_us = 0;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700573 *timed_out = false;
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800574 Thread* suspended_thread = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700575 Thread* self = Thread::Current();
576 CHECK_NE(thread_id, kInvalidThreadId);
Brian Carlstromba32de42014-08-27 23:43:46 -0700577 VLOG(threads) << "SuspendThreadByThreadId starting";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700578 while (true) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700579 {
Ian Rogersf3d874c2014-07-17 18:52:42 -0700580 // Note: this will transition to runnable and potentially suspend. We ensure only one thread
581 // is requesting another suspend, to avoid deadlock, by requiring this function be called
582 // holding Locks::thread_list_suspend_thread_lock_. Its important this thread suspend rather
583 // than request thread suspension, to avoid potential cycles in threads requesting each other
584 // suspend.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700585 ScopedObjectAccess soa(self);
586 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogersf3d874c2014-07-17 18:52:42 -0700587 Thread* thread = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700588 for (const auto& it : list_) {
589 if (it->GetThreadId() == thread_id) {
590 thread = it;
591 break;
592 }
593 }
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800594 if (thread == nullptr) {
595 CHECK(suspended_thread == nullptr) << "Suspended thread " << suspended_thread
596 << " no longer in thread list";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700597 // There's a race in inflating a lock and the owner giving up ownership and then dying.
598 ThreadSuspendByThreadIdWarning(WARNING, "No such thread id for suspend", thread_id);
Brian Carlstromba32de42014-08-27 23:43:46 -0700599 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700600 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700601 VLOG(threads) << "SuspendThreadByThreadId found thread: " << *thread;
602 DCHECK(Contains(thread));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700603 {
604 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800605 if (suspended_thread == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700606 thread->ModifySuspendCount(self, +1, debug_suspension);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800607 suspended_thread = thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700608 } else {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800609 CHECK_EQ(suspended_thread, thread);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700610 // If the caller isn't requesting suspension, a suspension should have already occurred.
611 CHECK_GT(thread->GetSuspendCount(), 0);
612 }
613 // IsSuspended on the current thread will fail as the current thread is changed into
614 // Runnable above. As the suspend count is now raised if this is the current thread
615 // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
616 // to just explicitly handle the current thread in the callers to this code.
617 CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
618 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
619 // count, or else we've waited and it has self suspended) or is the current thread, we're
620 // done.
621 if (thread->IsSuspended()) {
Brian Carlstromba32de42014-08-27 23:43:46 -0700622 VLOG(threads) << "SuspendThreadByThreadId thread suspended: " << *thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700623 return thread;
624 }
625 if (total_delay_us >= kTimeoutUs) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700626 ThreadSuspendByThreadIdWarning(WARNING, "Thread suspension timed out", thread_id);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800627 if (suspended_thread != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700628 thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
629 }
630 *timed_out = true;
Brian Carlstromba32de42014-08-27 23:43:46 -0700631 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700632 }
633 }
634 // Release locks and come out of runnable state.
635 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700636 VLOG(threads) << "SuspendThreadByThreadId sleeping to allow thread chance to suspend";
Ian Rogersf3d874c2014-07-17 18:52:42 -0700637 ThreadSuspendSleep(self, &delay_us, &total_delay_us);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700638 }
639}
640
641Thread* ThreadList::FindThreadByThreadId(uint32_t thin_lock_id) {
642 Thread* self = Thread::Current();
643 MutexLock mu(self, *Locks::thread_list_lock_);
644 for (const auto& thread : list_) {
645 if (thread->GetThreadId() == thin_lock_id) {
646 CHECK(thread == self || thread->IsSuspended());
647 return thread;
648 }
649 }
650 return NULL;
651}
652
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700653void ThreadList::SuspendAllForDebugger() {
654 Thread* self = Thread::Current();
655 Thread* debug_thread = Dbg::GetDebugThread();
656
657 VLOG(threads) << *self << " SuspendAllForDebugger starting...";
658
659 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700660 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700661 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700662 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700663 // Update global suspend all state for attaching threads.
664 ++suspend_all_count_;
665 ++debug_suspend_all_count_;
666 // Increment everybody's suspend count (except our own).
Mathieu Chartier02e25112013-08-14 16:14:24 -0700667 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700668 if (thread == self || thread == debug_thread) {
669 continue;
670 }
671 VLOG(threads) << "requesting thread suspend: " << *thread;
Ian Rogers01ae5802012-09-28 16:14:01 -0700672 thread->ModifySuspendCount(self, +1, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700673 }
674 }
675 }
676
Ian Rogers66aee5c2012-08-15 17:17:47 -0700677 // Block on the mutator lock until all Runnable threads release their share of access then
678 // immediately unlock again.
679#if HAVE_TIMED_RWLOCK
680 // Timeout if we wait more than 30 seconds.
Ian Rogersc604d732012-10-14 16:09:54 -0700681 if (!Locks::mutator_lock_->ExclusiveLockWithTimeout(self, 30 * 1000, 0)) {
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100682 UnsafeLogFatalForThreadSuspendAllTimeout();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700683 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -0700684 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700685 }
Ian Rogers66aee5c2012-08-15 17:17:47 -0700686#else
Ian Rogers81d425b2012-09-27 16:03:43 -0700687 Locks::mutator_lock_->ExclusiveLock(self);
688 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700689#endif
Ian Rogers50b35e22012-10-04 10:09:15 -0700690 AssertThreadsAreSuspended(self, self, debug_thread);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700691
Sebastien Hertzed2be172014-08-19 15:33:43 +0200692 VLOG(threads) << *self << " SuspendAllForDebugger complete";
Elliott Hughes01158d72011-09-19 19:47:10 -0700693}
694
Elliott Hughes475fc232011-10-25 15:00:35 -0700695void ThreadList::SuspendSelfForDebugger() {
696 Thread* self = Thread::Current();
Elliott Hughes01158d72011-09-19 19:47:10 -0700697
Elliott Hughes475fc232011-10-25 15:00:35 -0700698 // The debugger thread must not suspend itself due to debugger activity!
699 Thread* debug_thread = Dbg::GetDebugThread();
700 CHECK(debug_thread != NULL);
701 CHECK(self != debug_thread);
jeffhaoa77f0f62012-12-05 17:19:31 -0800702 CHECK_NE(self->GetState(), kRunnable);
703 Locks::mutator_lock_->AssertNotHeld(self);
Elliott Hughes475fc232011-10-25 15:00:35 -0700704
jeffhaoa77f0f62012-12-05 17:19:31 -0800705 {
706 // Collisions with other suspends aren't really interesting. We want
707 // to ensure that we're the only one fiddling with the suspend count
708 // though.
709 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
710 self->ModifySuspendCount(self, +1, true);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700711 CHECK_GT(self->GetSuspendCount(), 0);
jeffhaoa77f0f62012-12-05 17:19:31 -0800712 }
Elliott Hughes475fc232011-10-25 15:00:35 -0700713
Elliott Hughes1f729aa2012-03-02 13:55:41 -0800714 VLOG(threads) << *self << " self-suspending (debugger)";
Elliott Hughes475fc232011-10-25 15:00:35 -0700715
Sebastien Hertz21e729c2014-02-18 14:16:00 +0100716 // Tell JDWP we've completed invocation and are ready to suspend.
717 DebugInvokeReq* pReq = self->GetInvokeReq();
718 DCHECK(pReq != NULL);
719 if (pReq->invoke_needed) {
720 // Clear this before signaling.
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200721 pReq->Clear();
Sebastien Hertz21e729c2014-02-18 14:16:00 +0100722
723 VLOG(jdwp) << "invoke complete, signaling";
724 MutexLock mu(self, pReq->lock);
725 pReq->cond.Signal(self);
726 }
727
Elliott Hughes475fc232011-10-25 15:00:35 -0700728 // Tell JDWP that we've completed suspension. The JDWP thread can't
729 // tell us to resume before we're fully asleep because we hold the
730 // suspend count lock.
731 Dbg::ClearWaitForEventThread();
732
jeffhaoa77f0f62012-12-05 17:19:31 -0800733 {
734 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700735 while (self->GetSuspendCount() != 0) {
jeffhaoa77f0f62012-12-05 17:19:31 -0800736 Thread::resume_cond_->Wait(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700737 if (self->GetSuspendCount() != 0) {
jeffhaoa77f0f62012-12-05 17:19:31 -0800738 // The condition was signaled but we're still suspended. This
Sebastien Hertzf272af42014-09-18 10:20:42 +0200739 // can happen when we suspend then resume all threads to
740 // update instrumentation or compute monitor info. This can
741 // also happen if the debugger lets go while a SIGQUIT thread
jeffhaoa77f0f62012-12-05 17:19:31 -0800742 // dump event is pending (assuming SignalCatcher was resumed for
743 // just long enough to try to grab the thread-suspend lock).
Sebastien Hertzf272af42014-09-18 10:20:42 +0200744 VLOG(jdwp) << *self << " still suspended after undo "
745 << "(suspend count=" << self->GetSuspendCount() << ", "
746 << "debug suspend count=" << self->GetDebugSuspendCount() << ")";
jeffhaoa77f0f62012-12-05 17:19:31 -0800747 }
Elliott Hughes475fc232011-10-25 15:00:35 -0700748 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700749 CHECK_EQ(self->GetSuspendCount(), 0);
Elliott Hughes475fc232011-10-25 15:00:35 -0700750 }
jeffhaoa77f0f62012-12-05 17:19:31 -0800751
Elliott Hughes1f729aa2012-03-02 13:55:41 -0800752 VLOG(threads) << *self << " self-reviving (debugger)";
Elliott Hughes475fc232011-10-25 15:00:35 -0700753}
754
Elliott Hughes234ab152011-10-26 14:02:26 -0700755void ThreadList::UndoDebuggerSuspensions() {
756 Thread* self = Thread::Current();
757
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800758 VLOG(threads) << *self << " UndoDebuggerSuspensions starting";
Elliott Hughes234ab152011-10-26 14:02:26 -0700759
760 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700761 MutexLock mu(self, *Locks::thread_list_lock_);
762 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700763 // Update global suspend all state for attaching threads.
764 suspend_all_count_ -= debug_suspend_all_count_;
765 debug_suspend_all_count_ = 0;
766 // Update running threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700767 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700768 if (thread == self || thread->GetDebugSuspendCount() == 0) {
Elliott Hughes234ab152011-10-26 14:02:26 -0700769 continue;
770 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700771 thread->ModifySuspendCount(self, -thread->GetDebugSuspendCount(), true);
Elliott Hughes234ab152011-10-26 14:02:26 -0700772 }
773 }
774
775 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700776 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700777 Thread::resume_cond_->Broadcast(self);
Elliott Hughes234ab152011-10-26 14:02:26 -0700778 }
779
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800780 VLOG(threads) << "UndoDebuggerSuspensions(" << *self << ") complete";
Elliott Hughes234ab152011-10-26 14:02:26 -0700781}
782
Elliott Hughese52e49b2012-04-02 16:05:44 -0700783void ThreadList::WaitForOtherNonDaemonThreadsToExit() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700784 Thread* self = Thread::Current();
785 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700786 bool all_threads_are_daemons;
787 do {
Ian Rogers120f1c72012-09-28 17:17:10 -0700788 {
789 // No more threads can be born after we start to shutdown.
790 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700791 CHECK(Runtime::Current()->IsShuttingDownLocked());
Ian Rogers120f1c72012-09-28 17:17:10 -0700792 CHECK_EQ(Runtime::Current()->NumberOfThreadsBeingBorn(), 0U);
793 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700794 all_threads_are_daemons = true;
Ian Rogers120f1c72012-09-28 17:17:10 -0700795 MutexLock mu(self, *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700796 for (const auto& thread : list_) {
Anwar Ghuloum97543682013-06-14 12:58:16 -0700797 if (thread != self && !thread->IsDaemon()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700798 all_threads_are_daemons = false;
799 break;
800 }
801 }
802 if (!all_threads_are_daemons) {
803 // Wait for another thread to exit before re-checking.
Ian Rogersc604d732012-10-14 16:09:54 -0700804 thread_exit_cond_.Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700805 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700806 } while (!all_threads_are_daemons);
Elliott Hughes038a8062011-09-18 14:12:41 -0700807}
808
809void ThreadList::SuspendAllDaemonThreads() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700810 Thread* self = Thread::Current();
811 MutexLock mu(self, *Locks::thread_list_lock_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700812 { // Tell all the daemons it's time to suspend.
Ian Rogers81d425b2012-09-27 16:03:43 -0700813 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700814 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700815 // This is only run after all non-daemon threads have exited, so the remainder should all be
816 // daemons.
Ian Rogers7e762862012-10-22 15:45:08 -0700817 CHECK(thread->IsDaemon()) << *thread;
Ian Rogers81d425b2012-09-27 16:03:43 -0700818 if (thread != self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700819 thread->ModifySuspendCount(self, +1, false);
Elliott Hughese52e49b2012-04-02 16:05:44 -0700820 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700821 }
822 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700823 // Give the threads a chance to suspend, complaining if they're slow.
824 bool have_complained = false;
825 for (int i = 0; i < 10; ++i) {
826 usleep(200 * 1000);
827 bool all_suspended = true;
Mathieu Chartier02e25112013-08-14 16:14:24 -0700828 for (const auto& thread : list_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700829 if (thread != self && thread->GetState() == kRunnable) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700830 if (!have_complained) {
831 LOG(WARNING) << "daemon thread not yet suspended: " << *thread;
832 have_complained = true;
833 }
834 all_suspended = false;
835 }
836 }
837 if (all_suspended) {
838 return;
839 }
840 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700841 LOG(ERROR) << "suspend all daemons failed";
842}
843void ThreadList::Register(Thread* self) {
844 DCHECK_EQ(self, Thread::Current());
845
846 if (VLOG_IS_ON(threads)) {
847 std::ostringstream oss;
848 self->ShortDump(oss); // We don't hold the mutator_lock_ yet and so cannot call Dump.
Ian Rogers5a9ba012014-05-19 13:28:52 -0700849 LOG(INFO) << "ThreadList::Register() " << *self << "\n" << oss.str();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700850 }
851
852 // Atomically add self to the thread list and make its thread_suspend_count_ reflect ongoing
853 // SuspendAll requests.
Ian Rogers81d425b2012-09-27 16:03:43 -0700854 MutexLock mu(self, *Locks::thread_list_lock_);
855 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700856 CHECK_GE(suspend_all_count_, debug_suspend_all_count_);
Ian Rogers2966e132014-04-02 08:34:36 -0700857 // Modify suspend count in increments of 1 to maintain invariants in ModifySuspendCount. While
858 // this isn't particularly efficient the suspend counts are most commonly 0 or 1.
859 for (int delta = debug_suspend_all_count_; delta > 0; delta--) {
860 self->ModifySuspendCount(self, +1, true);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700861 }
Ian Rogers2966e132014-04-02 08:34:36 -0700862 for (int delta = suspend_all_count_ - debug_suspend_all_count_; delta > 0; delta--) {
863 self->ModifySuspendCount(self, +1, false);
Ian Rogers01ae5802012-09-28 16:14:01 -0700864 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700865 CHECK(!Contains(self));
866 list_.push_back(self);
867}
868
869void ThreadList::Unregister(Thread* self) {
870 DCHECK_EQ(self, Thread::Current());
Ian Rogers68d8b422014-07-17 11:09:10 -0700871 CHECK_NE(self->GetState(), kRunnable);
872 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700873
874 VLOG(threads) << "ThreadList::Unregister() " << *self;
875
876 // Any time-consuming destruction, plus anything that can call back into managed code or
877 // suspend and so on, must happen at this point, and not in ~Thread.
878 self->Destroy();
879
Ian Rogersdd7624d2014-03-14 17:43:00 -0700880 uint32_t thin_lock_id = self->GetThreadId();
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800881 while (self != nullptr) {
Ian Rogerscfaa4552012-11-26 21:00:08 -0800882 // Remove and delete the Thread* while holding the thread_list_lock_ and
883 // thread_suspend_count_lock_ so that the unregistering thread cannot be suspended.
Ian Rogers0878d652013-04-18 17:38:35 -0700884 // Note: deliberately not using MutexLock that could hold a stale self pointer.
885 Locks::thread_list_lock_->ExclusiveLock(self);
Ian Rogersa2af5c72014-09-15 15:17:07 -0700886 bool removed = true;
887 if (!Contains(self)) {
888 std::ostringstream os;
889 DumpNativeStack(os, GetTid(), " native: ", nullptr);
890 LOG(ERROR) << "Request to unregister unattached thread\n" << os.str();
891 } else {
892 Locks::thread_suspend_count_lock_->ExclusiveLock(self);
893 if (!self->IsSuspended()) {
894 list_.remove(self);
895 } else {
896 // We failed to remove the thread due to a suspend request, loop and try again.
897 removed = false;
898 }
899 Locks::thread_suspend_count_lock_->ExclusiveUnlock(self);
Ian Rogers68d8b422014-07-17 11:09:10 -0700900 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700901 Locks::thread_list_lock_->ExclusiveUnlock(self);
902 if (removed) {
Ian Rogerscfaa4552012-11-26 21:00:08 -0800903 delete self;
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800904 self = nullptr;
Ian Rogerscfaa4552012-11-26 21:00:08 -0800905 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700906 }
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800907 // Release the thread ID after the thread is finished and deleted to avoid cases where we can
908 // temporarily have multiple threads with the same thread id. When this occurs, it causes
909 // problems in FindThreadByThreadId / SuspendThreadByThreadId.
910 ReleaseThreadId(nullptr, thin_lock_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700911
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700912 // Clear the TLS data, so that the underlying native thread is recognizably detached.
913 // (It may wish to reattach later.)
914 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, NULL), "detach self");
915
916 // Signal that a thread just detached.
Ian Rogers81d425b2012-09-27 16:03:43 -0700917 MutexLock mu(NULL, *Locks::thread_list_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700918 thread_exit_cond_.Signal(NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700919}
920
921void ThreadList::ForEach(void (*callback)(Thread*, void*), void* context) {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700922 for (const auto& thread : list_) {
923 callback(thread, context);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700924 }
925}
926
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800927void ThreadList::VisitRoots(RootCallback* callback, void* arg) const {
Ian Rogers81d425b2012-09-27 16:03:43 -0700928 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700929 for (const auto& thread : list_) {
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800930 thread->VisitRoots(callback, arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700931 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700932}
933
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800934class VerifyRootWrapperArg {
935 public:
936 VerifyRootWrapperArg(VerifyRootCallback* callback, void* arg) : callback_(callback), arg_(arg) {
937 }
938 VerifyRootCallback* const callback_;
939 void* const arg_;
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700940};
941
Mathieu Chartier815873e2014-02-13 18:02:13 -0800942static void VerifyRootWrapperCallback(mirror::Object** root, void* arg, uint32_t /*thread_id*/,
Mathieu Chartier7bf9f192014-04-04 11:09:41 -0700943 RootType root_type) {
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700944 VerifyRootWrapperArg* wrapperArg = reinterpret_cast<VerifyRootWrapperArg*>(arg);
Mathieu Chartier7bf9f192014-04-04 11:09:41 -0700945 wrapperArg->callback_(*root, wrapperArg->arg_, 0, NULL, root_type);
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700946}
947
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800948void ThreadList::VerifyRoots(VerifyRootCallback* callback, void* arg) const {
949 VerifyRootWrapperArg wrapper(callback, arg);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700950 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700951 for (const auto& thread : list_) {
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700952 thread->VisitRoots(VerifyRootWrapperCallback, &wrapper);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700953 }
954}
955
Ian Rogerscfaa4552012-11-26 21:00:08 -0800956uint32_t ThreadList::AllocThreadId(Thread* self) {
Chao-ying Fu9e369312014-05-21 11:20:52 -0700957 MutexLock mu(self, *Locks::allocated_thread_ids_lock_);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700958 for (size_t i = 0; i < allocated_ids_.size(); ++i) {
959 if (!allocated_ids_[i]) {
960 allocated_ids_.set(i);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700961 return i + 1; // Zero is reserved to mean "invalid".
Elliott Hughes8daa0922011-09-11 13:46:25 -0700962 }
963 }
964 LOG(FATAL) << "Out of internal thread ids";
965 return 0;
966}
967
Ian Rogerscfaa4552012-11-26 21:00:08 -0800968void ThreadList::ReleaseThreadId(Thread* self, uint32_t id) {
Chao-ying Fu9e369312014-05-21 11:20:52 -0700969 MutexLock mu(self, *Locks::allocated_thread_ids_lock_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700970 --id; // Zero is reserved to mean "invalid".
Elliott Hughes8daa0922011-09-11 13:46:25 -0700971 DCHECK(allocated_ids_[id]) << id;
972 allocated_ids_.reset(id);
973}
974
Elliott Hughes8daa0922011-09-11 13:46:25 -0700975} // namespace art