blob: 5460249e91c86d43a693f88b9b183a6677c8b3de [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"
Jeff Haofdcbc5c2014-10-14 13:12:01 -070037#include "trace.h"
Elliott Hughesabbe07d2012-06-05 17:42:23 -070038#include "utils.h"
Ian Rogersd9c4fc92013-10-01 19:45:43 -070039#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070040
Elliott Hughes8daa0922011-09-11 13:46:25 -070041namespace art {
42
Mathieu Chartierb960cd72014-07-15 18:10:25 -070043static constexpr uint64_t kLongThreadSuspendThreshold = MsToNs(5);
44
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -080045ThreadList::ThreadList()
Chao-ying Fu9e369312014-05-21 11:20:52 -070046 : suspend_all_count_(0), debug_suspend_all_count_(0),
Ian Rogersc604d732012-10-14 16:09:54 -070047 thread_exit_cond_("thread exit condition variable", *Locks::thread_list_lock_) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -070048 CHECK(Monitor::IsValidLockWord(LockWord::FromThinLockId(kMaxThreadId, 1)));
Elliott Hughes8daa0922011-09-11 13:46:25 -070049}
50
51ThreadList::~ThreadList() {
Elliott Hughese52e49b2012-04-02 16:05:44 -070052 // Detach the current thread if necessary. If we failed to start, there might not be any threads.
Elliott Hughes6a144332012-04-03 13:07:11 -070053 // We need to detach the current thread here in case there's another thread waiting to join with
54 // us.
Mathieu Chartierb90132c2014-10-09 12:57:58 -070055 bool contains = false;
56 {
57 Thread* self = Thread::Current();
58 MutexLock mu(self, *Locks::thread_list_lock_);
59 contains = Contains(self);
60 }
61 if (contains) {
Elliott Hughes8daa0922011-09-11 13:46:25 -070062 Runtime::Current()->DetachCurrentThread();
63 }
Elliott Hughes6a144332012-04-03 13:07:11 -070064
65 WaitForOtherNonDaemonThreadsToExit();
Ian Rogers00f7d0e2012-07-19 15:28:27 -070066 // TODO: there's an unaddressed race here where a thread may attach during shutdown, see
67 // Thread::Init.
Elliott Hughes6a144332012-04-03 13:07:11 -070068 SuspendAllDaemonThreads();
Elliott Hughes8daa0922011-09-11 13:46:25 -070069}
70
71bool ThreadList::Contains(Thread* thread) {
72 return find(list_.begin(), list_.end(), thread) != list_.end();
73}
74
Elliott Hughesabbe07d2012-06-05 17:42:23 -070075bool ThreadList::Contains(pid_t tid) {
Mathieu Chartier02e25112013-08-14 16:14:24 -070076 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -070077 if (thread->GetTid() == tid) {
Elliott Hughesabbe07d2012-06-05 17:42:23 -070078 return true;
79 }
80 }
81 return false;
82}
83
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -070084pid_t ThreadList::GetLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -070085 return Locks::thread_list_lock_->GetExclusiveOwnerTid();
Elliott Hughesaccd83d2011-10-17 14:25:58 -070086}
87
Mathieu Chartier590fee92013-09-13 13:46:47 -070088void ThreadList::DumpNativeStacks(std::ostream& os) {
89 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
90 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -070091 os << "DUMPING THREAD " << thread->GetTid() << "\n";
Christopher Ferrisa2cee182014-04-16 19:13:59 -070092 DumpNativeStack(os, thread->GetTid(), "\t");
Mathieu Chartier590fee92013-09-13 13:46:47 -070093 os << "\n";
94 }
95}
96
Elliott Hughesc967f782012-04-16 10:23:15 -070097void ThreadList::DumpForSigQuit(std::ostream& os) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -070098 {
Ian Rogers50b35e22012-10-04 10:09:15 -070099 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700100 DumpLocked(os);
101 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700102 DumpUnattachedThreads(os);
103}
104
Ian Rogerscfaa4552012-11-26 21:00:08 -0800105static void DumpUnattachedThread(std::ostream& os, pid_t tid) NO_THREAD_SAFETY_ANALYSIS {
106 // TODO: No thread safety analysis as DumpState with a NULL thread won't access fields, should
107 // refactor DumpState to avoid skipping analysis.
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700108 Thread::DumpState(os, NULL, tid);
109 DumpKernelStack(os, tid, " kernel: ", false);
Brian Carlstromed8b7232012-06-27 17:54:47 -0700110 // TODO: Reenable this when the native code in system_server can handle it.
111 // Currently "adb shell kill -3 `pid system_server`" will cause it to exit.
112 if (false) {
Christopher Ferrisa2cee182014-04-16 19:13:59 -0700113 DumpNativeStack(os, tid, " native: ");
Brian Carlstromed8b7232012-06-27 17:54:47 -0700114 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700115 os << "\n";
116}
117
118void ThreadList::DumpUnattachedThreads(std::ostream& os) {
119 DIR* d = opendir("/proc/self/task");
120 if (!d) {
121 return;
122 }
123
Ian Rogers50b35e22012-10-04 10:09:15 -0700124 Thread* self = Thread::Current();
Elliott Hughes4696b5b2012-10-30 10:35:10 -0700125 dirent* e;
126 while ((e = readdir(d)) != NULL) {
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700127 char* end;
Elliott Hughes4696b5b2012-10-30 10:35:10 -0700128 pid_t tid = strtol(e->d_name, &end, 10);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700129 if (!*end) {
130 bool contains;
131 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700132 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700133 contains = Contains(tid);
134 }
135 if (!contains) {
136 DumpUnattachedThread(os, tid);
137 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700138 }
139 }
140 closedir(d);
Elliott Hughesff738062012-02-03 15:00:42 -0800141}
142
143void ThreadList::DumpLocked(std::ostream& os) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700144 os << "DALVIK THREADS (" << list_.size() << "):\n";
Mathieu Chartier02e25112013-08-14 16:14:24 -0700145 for (const auto& thread : list_) {
146 thread->Dump(os);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700147 os << "\n";
148 }
149}
150
Ian Rogers50b35e22012-10-04 10:09:15 -0700151void ThreadList::AssertThreadsAreSuspended(Thread* self, Thread* ignore1, Thread* ignore2) {
152 MutexLock mu(self, *Locks::thread_list_lock_);
153 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700154 for (const auto& thread : list_) {
jeffhao725a9572012-11-13 18:20:12 -0800155 if (thread != ignore1 && thread != ignore2) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700156 CHECK(thread->IsSuspended())
157 << "\nUnsuspended thread: <<" << *thread << "\n"
158 << "self: <<" << *Thread::Current();
159 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700160 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700161}
162
Ian Rogers66aee5c2012-08-15 17:17:47 -0700163#if HAVE_TIMED_RWLOCK
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700164// Attempt to rectify locks so that we dump thread list with required locks before exiting.
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100165static void UnsafeLogFatalForThreadSuspendAllTimeout() NO_THREAD_SAFETY_ANALYSIS __attribute__((noreturn));
166static void UnsafeLogFatalForThreadSuspendAllTimeout() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700167 Runtime* runtime = Runtime::Current();
168 std::ostringstream ss;
169 ss << "Thread suspend timeout\n";
Mathieu Chartierf924d232014-10-08 12:17:44 -0700170 Locks::mutator_lock_->Dump(ss);
171 ss << "\n";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700172 runtime->GetThreadList()->DumpLocked(ss);
173 LOG(FATAL) << ss.str();
Ian Rogers719d1a32014-03-06 12:13:39 -0800174 exit(0);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700175}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700176#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700177
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800178// Unlike suspending all threads where we can wait to acquire the mutator_lock_, suspending an
179// individual thread requires polling. delay_us is the requested sleep and total_delay_us
180// accumulates the total time spent sleeping for timeouts. The first sleep is just a yield,
181// subsequently sleeps increase delay_us from 1ms to 500ms by doubling.
Ian Rogers6093a5c2014-07-17 18:52:42 -0700182static void ThreadSuspendSleep(Thread* self, useconds_t* delay_us, useconds_t* total_delay_us) {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800183 useconds_t new_delay_us = (*delay_us) * 2;
184 CHECK_GE(new_delay_us, *delay_us);
185 if (new_delay_us < 500000) { // Don't allow sleeping to be more than 0.5s.
186 *delay_us = new_delay_us;
187 }
188 if (*delay_us == 0) {
189 sched_yield();
190 // Default to 1 milliseconds (note that this gets multiplied by 2 before the first sleep).
191 *delay_us = 500;
192 } else {
193 usleep(*delay_us);
194 *total_delay_us += *delay_us;
195 }
196}
197
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700198size_t ThreadList::RunCheckpoint(Closure* checkpoint_function) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700199 Thread* self = Thread::Current();
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800200 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
201 Locks::thread_list_lock_->AssertNotHeld(self);
202 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
203 if (kDebugLocking) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700204 CHECK_NE(self->GetState(), kRunnable);
205 }
206
207 std::vector<Thread*> suspended_count_modified_threads;
208 size_t count = 0;
209 {
210 // Call a checkpoint function for each thread, threads which are suspend get their checkpoint
211 // manually called.
212 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700213 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700214 for (const auto& thread : list_) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700215 if (thread != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700216 while (true) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700217 if (thread->RequestCheckpoint(checkpoint_function)) {
Dave Allison0aded082013-11-07 13:15:11 -0800218 // This thread will run its checkpoint some time in the near future.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700219 count++;
220 break;
221 } else {
222 // We are probably suspended, try to make sure that we stay suspended.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700223 // The thread switched back to runnable.
224 if (thread->GetState() == kRunnable) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700225 // Spurious fail, try again.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700226 continue;
227 }
228 thread->ModifySuspendCount(self, +1, false);
229 suspended_count_modified_threads.push_back(thread);
230 break;
231 }
232 }
233 }
234 }
235 }
236
237 // Run the checkpoint on ourself while we wait for threads to suspend.
238 checkpoint_function->Run(self);
239
240 // Run the checkpoint on the suspended threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700241 for (const auto& thread : suspended_count_modified_threads) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700242 if (!thread->IsSuspended()) {
243 // Wait until the thread is suspended.
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800244 useconds_t total_delay_us = 0;
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700245 do {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800246 useconds_t delay_us = 100;
Ian Rogers6093a5c2014-07-17 18:52:42 -0700247 ThreadSuspendSleep(self, &delay_us, &total_delay_us);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700248 } while (!thread->IsSuspended());
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800249 // Shouldn't need to wait for longer than 1000 microseconds.
250 constexpr useconds_t kLongWaitThresholdUS = 1000;
251 if (UNLIKELY(total_delay_us > kLongWaitThresholdUS)) {
252 LOG(WARNING) << "Waited " << total_delay_us << " us for thread suspend!";
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700253 }
254 }
255 // We know for sure that the thread is suspended at this point.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700256 checkpoint_function->Run(thread);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700257 {
258 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
259 thread->ModifySuspendCount(self, -1, false);
260 }
261 }
262
Mathieu Chartier664bebf2012-11-12 16:54:11 -0800263 {
264 // Imitate ResumeAll, threads may be waiting on Thread::resume_cond_ since we raised their
265 // suspend count. Now the suspend_count_ is lowered so we must do the broadcast.
266 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
267 Thread::resume_cond_->Broadcast(self);
268 }
269
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700270 // Add one for self.
271 return count + suspended_count_modified_threads.size() + 1;
272}
273
Dave Allison39c3bfb2014-01-28 18:33:52 -0800274// Request that a checkpoint function be run on all active (non-suspended)
275// threads. Returns the number of successful requests.
276size_t ThreadList::RunCheckpointOnRunnableThreads(Closure* checkpoint_function) {
277 Thread* self = Thread::Current();
278 if (kIsDebugBuild) {
279 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
280 Locks::thread_list_lock_->AssertNotHeld(self);
281 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
282 CHECK_NE(self->GetState(), kRunnable);
283 }
284
285 size_t count = 0;
286 {
287 // Call a checkpoint function for each non-suspended thread.
288 MutexLock mu(self, *Locks::thread_list_lock_);
289 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
290 for (const auto& thread : list_) {
291 if (thread != self) {
292 if (thread->RequestCheckpoint(checkpoint_function)) {
293 // This thread will run its checkpoint some time in the near future.
294 count++;
295 }
296 }
297 }
298 }
299
300 // Return the number of threads that will run the checkpoint function.
301 return count;
302}
303
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700304void ThreadList::SuspendAll() {
305 Thread* self = Thread::Current();
306
Jeff Haoc7c6d182014-07-28 18:35:38 -0700307 if (self != nullptr) {
308 VLOG(threads) << *self << " SuspendAll starting...";
309 } else {
310 VLOG(threads) << "Thread[null] SuspendAll starting...";
311 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700312 ATRACE_BEGIN("Suspending mutator threads");
Mathieu Chartierb960cd72014-07-15 18:10:25 -0700313 uint64_t start_time = NanoTime();
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700314
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800315 Locks::mutator_lock_->AssertNotHeld(self);
316 Locks::thread_list_lock_->AssertNotHeld(self);
317 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
Jeff Haoc7c6d182014-07-28 18:35:38 -0700318 if (kDebugLocking && self != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700319 CHECK_NE(self->GetState(), kRunnable);
320 }
321 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700322 MutexLock mu(self, *Locks::thread_list_lock_);
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800323 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
324 // Update global suspend all state for attaching threads.
325 ++suspend_all_count_;
326 // Increment everybody's suspend count (except our own).
327 for (const auto& thread : list_) {
328 if (thread == self) {
329 continue;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700330 }
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800331 VLOG(threads) << "requesting thread suspend: " << *thread;
332 thread->ModifySuspendCount(self, +1, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700333 }
334 }
335
Ian Rogers66aee5c2012-08-15 17:17:47 -0700336 // Block on the mutator lock until all Runnable threads release their share of access.
337#if HAVE_TIMED_RWLOCK
338 // Timeout if we wait more than 30 seconds.
Ian Rogers719d1a32014-03-06 12:13:39 -0800339 if (!Locks::mutator_lock_->ExclusiveLockWithTimeout(self, 30 * 1000, 0)) {
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100340 UnsafeLogFatalForThreadSuspendAllTimeout();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700341 }
Ian Rogers66aee5c2012-08-15 17:17:47 -0700342#else
Ian Rogers81d425b2012-09-27 16:03:43 -0700343 Locks::mutator_lock_->ExclusiveLock(self);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700344#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700345
Mathieu Chartierb960cd72014-07-15 18:10:25 -0700346 uint64_t end_time = NanoTime();
347 if (end_time - start_time > kLongThreadSuspendThreshold) {
348 LOG(WARNING) << "Suspending all threads took: " << PrettyDuration(end_time - start_time);
349 }
350
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800351 if (kDebugLocking) {
352 // Debug check that all threads are suspended.
353 AssertThreadsAreSuspended(self, self);
354 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700355
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700356 ATRACE_END();
357 ATRACE_BEGIN("Mutator threads suspended");
358
Jeff Haoc7c6d182014-07-28 18:35:38 -0700359 if (self != nullptr) {
360 VLOG(threads) << *self << " SuspendAll complete";
361 } else {
362 VLOG(threads) << "Thread[null] SuspendAll complete";
363 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700364}
365
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700366void ThreadList::ResumeAll() {
367 Thread* self = Thread::Current();
368
Jeff Haoc7c6d182014-07-28 18:35:38 -0700369 if (self != nullptr) {
370 VLOG(threads) << *self << " ResumeAll starting";
371 } else {
372 VLOG(threads) << "Thread[null] ResumeAll starting";
373 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700374
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700375 ATRACE_END();
376 ATRACE_BEGIN("Resuming mutator threads");
377
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800378 if (kDebugLocking) {
379 // Debug check that all threads are suspended.
380 AssertThreadsAreSuspended(self, self);
381 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700382
Ian Rogers81d425b2012-09-27 16:03:43 -0700383 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700384 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700385 MutexLock mu(self, *Locks::thread_list_lock_);
386 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700387 // Update global suspend all state for attaching threads.
388 --suspend_all_count_;
389 // Decrement the suspend counts for all threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700390 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700391 if (thread == self) {
392 continue;
393 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700394 thread->ModifySuspendCount(self, -1, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700395 }
396
397 // Broadcast a notification to all suspended threads, some or all of
398 // which may choose to wake up. No need to wait for them.
Jeff Haoc7c6d182014-07-28 18:35:38 -0700399 if (self != nullptr) {
400 VLOG(threads) << *self << " ResumeAll waking others";
401 } else {
402 VLOG(threads) << "Thread[null] ResumeAll waking others";
403 }
Ian Rogersc604d732012-10-14 16:09:54 -0700404 Thread::resume_cond_->Broadcast(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700405 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700406 ATRACE_END();
Jeff Haoc7c6d182014-07-28 18:35:38 -0700407
408 if (self != nullptr) {
409 VLOG(threads) << *self << " ResumeAll complete";
410 } else {
411 VLOG(threads) << "Thread[null] ResumeAll complete";
412 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700413}
414
415void ThreadList::Resume(Thread* thread, bool for_debugger) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700416 Thread* self = Thread::Current();
417 DCHECK_NE(thread, self);
Brian Carlstrom37c16452014-08-27 23:43:46 -0700418 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") starting..."
419 << (for_debugger ? " (debugger)" : "");
Elliott Hughes01158d72011-09-19 19:47:10 -0700420
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700421 {
422 // To check Contains.
Ian Rogers81d425b2012-09-27 16:03:43 -0700423 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700424 // To check IsSuspended.
Ian Rogers81d425b2012-09-27 16:03:43 -0700425 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
426 DCHECK(thread->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700427 if (!Contains(thread)) {
Brian Carlstrom37c16452014-08-27 23:43:46 -0700428 // We only expect threads within the thread-list to have been suspended otherwise we can't
429 // stop such threads from delete-ing themselves.
430 LOG(ERROR) << "Resume(" << reinterpret_cast<void*>(thread)
431 << ") thread not within thread list";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700432 return;
433 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700434 thread->ModifySuspendCount(self, -1, for_debugger);
Elliott Hughes01158d72011-09-19 19:47:10 -0700435 }
436
437 {
Brian Carlstrom37c16452014-08-27 23:43:46 -0700438 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") waking others";
Ian Rogers81d425b2012-09-27 16:03:43 -0700439 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700440 Thread::resume_cond_->Broadcast(self);
Elliott Hughes01158d72011-09-19 19:47:10 -0700441 }
442
Brian Carlstrom37c16452014-08-27 23:43:46 -0700443 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") complete";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700444}
Elliott Hughes01158d72011-09-19 19:47:10 -0700445
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700446static void ThreadSuspendByPeerWarning(Thread* self, int level, const char* message, jobject peer) {
447 JNIEnvExt* env = self->GetJniEnv();
448 ScopedLocalRef<jstring>
449 scoped_name_string(env, (jstring)env->GetObjectField(peer,
450 WellKnownClasses::java_lang_Thread_name));
451 ScopedUtfChars scoped_name_chars(env, scoped_name_string.get());
452 if (scoped_name_chars.c_str() == NULL) {
453 LOG(level) << message << ": " << peer;
454 env->ExceptionClear();
455 } else {
456 LOG(level) << message << ": " << peer << ":" << scoped_name_chars.c_str();
457 }
458}
459
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700460Thread* ThreadList::SuspendThreadByPeer(jobject peer, bool request_suspension,
461 bool debug_suspension, bool* timed_out) {
462 static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
463 useconds_t total_delay_us = 0;
464 useconds_t delay_us = 0;
465 bool did_suspend_request = false;
466 *timed_out = false;
467 Thread* self = Thread::Current();
Brian Carlstrom37c16452014-08-27 23:43:46 -0700468 VLOG(threads) << "SuspendThreadByPeer starting";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700469 while (true) {
470 Thread* thread;
471 {
Ian Rogers6093a5c2014-07-17 18:52:42 -0700472 // Note: this will transition to runnable and potentially suspend. We ensure only one thread
473 // is requesting another suspend, to avoid deadlock, by requiring this function be called
474 // holding Locks::thread_list_suspend_thread_lock_. Its important this thread suspend rather
475 // than request thread suspension, to avoid potential cycles in threads requesting each other
476 // suspend.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700477 ScopedObjectAccess soa(self);
478 MutexLock mu(self, *Locks::thread_list_lock_);
479 thread = Thread::FromManagedThread(soa, peer);
Brian Carlstrom37c16452014-08-27 23:43:46 -0700480 if (thread == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700481 ThreadSuspendByPeerWarning(self, WARNING, "No such thread for suspend", peer);
Brian Carlstrom37c16452014-08-27 23:43:46 -0700482 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700483 }
Brian Carlstrom37c16452014-08-27 23:43:46 -0700484 if (!Contains(thread)) {
485 VLOG(threads) << "SuspendThreadByPeer failed for unattached thread: "
486 << reinterpret_cast<void*>(thread);
487 return nullptr;
488 }
489 VLOG(threads) << "SuspendThreadByPeer found thread: " << *thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700490 {
491 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
492 if (request_suspension) {
493 thread->ModifySuspendCount(self, +1, debug_suspension);
494 request_suspension = false;
495 did_suspend_request = true;
496 } else {
497 // If the caller isn't requesting suspension, a suspension should have already occurred.
498 CHECK_GT(thread->GetSuspendCount(), 0);
499 }
500 // IsSuspended on the current thread will fail as the current thread is changed into
501 // Runnable above. As the suspend count is now raised if this is the current thread
502 // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
503 // to just explicitly handle the current thread in the callers to this code.
504 CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
505 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
506 // count, or else we've waited and it has self suspended) or is the current thread, we're
507 // done.
508 if (thread->IsSuspended()) {
Brian Carlstrom37c16452014-08-27 23:43:46 -0700509 VLOG(threads) << "SuspendThreadByPeer thread suspended: " << *thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700510 return thread;
511 }
512 if (total_delay_us >= kTimeoutUs) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700513 ThreadSuspendByPeerWarning(self, FATAL, "Thread suspension timed out", peer);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700514 if (did_suspend_request) {
515 thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
516 }
517 *timed_out = true;
Brian Carlstrom37c16452014-08-27 23:43:46 -0700518 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700519 }
520 }
521 // Release locks and come out of runnable state.
522 }
Brian Carlstrom37c16452014-08-27 23:43:46 -0700523 VLOG(threads) << "SuspendThreadByPeer sleeping to allow thread chance to suspend";
Ian Rogers6093a5c2014-07-17 18:52:42 -0700524 ThreadSuspendSleep(self, &delay_us, &total_delay_us);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700525 }
526}
527
528static void ThreadSuspendByThreadIdWarning(int level, const char* message, uint32_t thread_id) {
529 LOG(level) << StringPrintf("%s: %d", message, thread_id);
530}
531
532Thread* ThreadList::SuspendThreadByThreadId(uint32_t thread_id, bool debug_suspension,
533 bool* timed_out) {
534 static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
535 useconds_t total_delay_us = 0;
536 useconds_t delay_us = 0;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700537 *timed_out = false;
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800538 Thread* suspended_thread = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700539 Thread* self = Thread::Current();
540 CHECK_NE(thread_id, kInvalidThreadId);
Brian Carlstrom37c16452014-08-27 23:43:46 -0700541 VLOG(threads) << "SuspendThreadByThreadId starting";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700542 while (true) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700543 {
Ian Rogers6093a5c2014-07-17 18:52:42 -0700544 // Note: this will transition to runnable and potentially suspend. We ensure only one thread
545 // is requesting another suspend, to avoid deadlock, by requiring this function be called
546 // holding Locks::thread_list_suspend_thread_lock_. Its important this thread suspend rather
547 // than request thread suspension, to avoid potential cycles in threads requesting each other
548 // suspend.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700549 ScopedObjectAccess soa(self);
550 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers6093a5c2014-07-17 18:52:42 -0700551 Thread* thread = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700552 for (const auto& it : list_) {
553 if (it->GetThreadId() == thread_id) {
554 thread = it;
555 break;
556 }
557 }
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800558 if (thread == nullptr) {
559 CHECK(suspended_thread == nullptr) << "Suspended thread " << suspended_thread
560 << " no longer in thread list";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700561 // There's a race in inflating a lock and the owner giving up ownership and then dying.
562 ThreadSuspendByThreadIdWarning(WARNING, "No such thread id for suspend", thread_id);
Brian Carlstrom37c16452014-08-27 23:43:46 -0700563 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700564 }
Brian Carlstrom37c16452014-08-27 23:43:46 -0700565 VLOG(threads) << "SuspendThreadByThreadId found thread: " << *thread;
566 DCHECK(Contains(thread));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700567 {
568 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800569 if (suspended_thread == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700570 thread->ModifySuspendCount(self, +1, debug_suspension);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800571 suspended_thread = thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700572 } else {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800573 CHECK_EQ(suspended_thread, thread);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700574 // If the caller isn't requesting suspension, a suspension should have already occurred.
575 CHECK_GT(thread->GetSuspendCount(), 0);
576 }
577 // IsSuspended on the current thread will fail as the current thread is changed into
578 // Runnable above. As the suspend count is now raised if this is the current thread
579 // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
580 // to just explicitly handle the current thread in the callers to this code.
581 CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
582 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
583 // count, or else we've waited and it has self suspended) or is the current thread, we're
584 // done.
585 if (thread->IsSuspended()) {
Brian Carlstrom37c16452014-08-27 23:43:46 -0700586 VLOG(threads) << "SuspendThreadByThreadId thread suspended: " << *thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700587 return thread;
588 }
589 if (total_delay_us >= kTimeoutUs) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700590 ThreadSuspendByThreadIdWarning(WARNING, "Thread suspension timed out", thread_id);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800591 if (suspended_thread != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700592 thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
593 }
594 *timed_out = true;
Brian Carlstrom37c16452014-08-27 23:43:46 -0700595 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700596 }
597 }
598 // Release locks and come out of runnable state.
599 }
Brian Carlstrom37c16452014-08-27 23:43:46 -0700600 VLOG(threads) << "SuspendThreadByThreadId sleeping to allow thread chance to suspend";
Ian Rogers6093a5c2014-07-17 18:52:42 -0700601 ThreadSuspendSleep(self, &delay_us, &total_delay_us);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700602 }
603}
604
605Thread* ThreadList::FindThreadByThreadId(uint32_t thin_lock_id) {
606 Thread* self = Thread::Current();
607 MutexLock mu(self, *Locks::thread_list_lock_);
608 for (const auto& thread : list_) {
609 if (thread->GetThreadId() == thin_lock_id) {
610 CHECK(thread == self || thread->IsSuspended());
611 return thread;
612 }
613 }
614 return NULL;
615}
616
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700617void ThreadList::SuspendAllForDebugger() {
618 Thread* self = Thread::Current();
619 Thread* debug_thread = Dbg::GetDebugThread();
620
621 VLOG(threads) << *self << " SuspendAllForDebugger starting...";
622
623 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700624 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700625 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700626 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700627 // Update global suspend all state for attaching threads.
Sebastien Hertz4eec0262014-10-14 17:27:15 +0200628 DCHECK_GE(suspend_all_count_, debug_suspend_all_count_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700629 ++suspend_all_count_;
630 ++debug_suspend_all_count_;
631 // Increment everybody's suspend count (except our own).
Mathieu Chartier02e25112013-08-14 16:14:24 -0700632 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700633 if (thread == self || thread == debug_thread) {
634 continue;
635 }
636 VLOG(threads) << "requesting thread suspend: " << *thread;
Ian Rogers01ae5802012-09-28 16:14:01 -0700637 thread->ModifySuspendCount(self, +1, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700638 }
639 }
640 }
641
Ian Rogers66aee5c2012-08-15 17:17:47 -0700642 // Block on the mutator lock until all Runnable threads release their share of access then
643 // immediately unlock again.
644#if HAVE_TIMED_RWLOCK
645 // Timeout if we wait more than 30 seconds.
Ian Rogersc604d732012-10-14 16:09:54 -0700646 if (!Locks::mutator_lock_->ExclusiveLockWithTimeout(self, 30 * 1000, 0)) {
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100647 UnsafeLogFatalForThreadSuspendAllTimeout();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700648 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -0700649 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700650 }
Ian Rogers66aee5c2012-08-15 17:17:47 -0700651#else
Ian Rogers81d425b2012-09-27 16:03:43 -0700652 Locks::mutator_lock_->ExclusiveLock(self);
653 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700654#endif
Ian Rogers50b35e22012-10-04 10:09:15 -0700655 AssertThreadsAreSuspended(self, self, debug_thread);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700656
Sebastien Hertz59d9d662014-08-19 15:33:43 +0200657 VLOG(threads) << *self << " SuspendAllForDebugger complete";
Elliott Hughes01158d72011-09-19 19:47:10 -0700658}
659
Elliott Hughes475fc232011-10-25 15:00:35 -0700660void ThreadList::SuspendSelfForDebugger() {
661 Thread* self = Thread::Current();
Elliott Hughes01158d72011-09-19 19:47:10 -0700662
Elliott Hughes475fc232011-10-25 15:00:35 -0700663 // The debugger thread must not suspend itself due to debugger activity!
664 Thread* debug_thread = Dbg::GetDebugThread();
665 CHECK(debug_thread != NULL);
666 CHECK(self != debug_thread);
jeffhaoa77f0f62012-12-05 17:19:31 -0800667 CHECK_NE(self->GetState(), kRunnable);
668 Locks::mutator_lock_->AssertNotHeld(self);
Elliott Hughes475fc232011-10-25 15:00:35 -0700669
jeffhaoa77f0f62012-12-05 17:19:31 -0800670 {
671 // Collisions with other suspends aren't really interesting. We want
672 // to ensure that we're the only one fiddling with the suspend count
673 // though.
674 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
675 self->ModifySuspendCount(self, +1, true);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700676 CHECK_GT(self->GetSuspendCount(), 0);
jeffhaoa77f0f62012-12-05 17:19:31 -0800677 }
Elliott Hughes475fc232011-10-25 15:00:35 -0700678
Elliott Hughes1f729aa2012-03-02 13:55:41 -0800679 VLOG(threads) << *self << " self-suspending (debugger)";
Elliott Hughes475fc232011-10-25 15:00:35 -0700680
Sebastien Hertz21e729c2014-02-18 14:16:00 +0100681 // Tell JDWP we've completed invocation and are ready to suspend.
682 DebugInvokeReq* pReq = self->GetInvokeReq();
683 DCHECK(pReq != NULL);
684 if (pReq->invoke_needed) {
685 // Clear this before signaling.
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200686 pReq->Clear();
Sebastien Hertz21e729c2014-02-18 14:16:00 +0100687
688 VLOG(jdwp) << "invoke complete, signaling";
689 MutexLock mu(self, pReq->lock);
690 pReq->cond.Signal(self);
691 }
692
Elliott Hughes475fc232011-10-25 15:00:35 -0700693 // Tell JDWP that we've completed suspension. The JDWP thread can't
694 // tell us to resume before we're fully asleep because we hold the
695 // suspend count lock.
696 Dbg::ClearWaitForEventThread();
697
jeffhaoa77f0f62012-12-05 17:19:31 -0800698 {
699 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700700 while (self->GetSuspendCount() != 0) {
jeffhaoa77f0f62012-12-05 17:19:31 -0800701 Thread::resume_cond_->Wait(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700702 if (self->GetSuspendCount() != 0) {
jeffhaoa77f0f62012-12-05 17:19:31 -0800703 // The condition was signaled but we're still suspended. This
Sebastien Hertzdcfd6ca2014-09-18 10:20:42 +0200704 // can happen when we suspend then resume all threads to
705 // update instrumentation or compute monitor info. This can
706 // also happen if the debugger lets go while a SIGQUIT thread
jeffhaoa77f0f62012-12-05 17:19:31 -0800707 // dump event is pending (assuming SignalCatcher was resumed for
708 // just long enough to try to grab the thread-suspend lock).
Sebastien Hertzdcfd6ca2014-09-18 10:20:42 +0200709 VLOG(jdwp) << *self << " still suspended after undo "
710 << "(suspend count=" << self->GetSuspendCount() << ", "
711 << "debug suspend count=" << self->GetDebugSuspendCount() << ")";
jeffhaoa77f0f62012-12-05 17:19:31 -0800712 }
Elliott Hughes475fc232011-10-25 15:00:35 -0700713 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700714 CHECK_EQ(self->GetSuspendCount(), 0);
Elliott Hughes475fc232011-10-25 15:00:35 -0700715 }
jeffhaoa77f0f62012-12-05 17:19:31 -0800716
Elliott Hughes1f729aa2012-03-02 13:55:41 -0800717 VLOG(threads) << *self << " self-reviving (debugger)";
Elliott Hughes475fc232011-10-25 15:00:35 -0700718}
719
Sebastien Hertz4eec0262014-10-14 17:27:15 +0200720void ThreadList::ResumeAllForDebugger() {
721 Thread* self = Thread::Current();
722 Thread* debug_thread = Dbg::GetDebugThread();
Sebastien Hertz4eec0262014-10-14 17:27:15 +0200723
724 VLOG(threads) << *self << " ResumeAllForDebugger starting...";
725
726 // Threads can't resume if we exclusively hold the mutator lock.
727 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
728
729 {
730 MutexLock mu(self, *Locks::thread_list_lock_);
731 {
732 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
733 // Update global suspend all state for attaching threads.
734 DCHECK_GE(suspend_all_count_, debug_suspend_all_count_);
Sebastien Hertz66516ac2015-01-09 14:51:41 +0100735 if (debug_suspend_all_count_ > 0) {
Sebastien Hertz4eec0262014-10-14 17:27:15 +0200736 --suspend_all_count_;
737 --debug_suspend_all_count_;
Sebastien Hertz4eec0262014-10-14 17:27:15 +0200738 } else {
739 // We've been asked to resume all threads without being asked to
Sebastien Hertz66516ac2015-01-09 14:51:41 +0100740 // suspend them all before. That may happen if a debugger tries
741 // to resume some suspended threads (with suspend count == 1)
742 // at once with a VirtualMachine.Resume command. Let's print a
743 // warning.
Sebastien Hertz4eec0262014-10-14 17:27:15 +0200744 LOG(WARNING) << "Debugger attempted to resume all threads without "
745 << "having suspended them all before.";
746 }
Sebastien Hertz66516ac2015-01-09 14:51:41 +0100747 // Decrement everybody's suspend count (except our own).
748 for (const auto& thread : list_) {
749 if (thread == self || thread == debug_thread) {
750 continue;
751 }
752 if (thread->GetDebugSuspendCount() == 0) {
753 // This thread may have been individually resumed with ThreadReference.Resume.
754 continue;
755 }
756 VLOG(threads) << "requesting thread resume: " << *thread;
757 thread->ModifySuspendCount(self, -1, true);
758 }
Sebastien Hertz4eec0262014-10-14 17:27:15 +0200759 }
760 }
761
Sebastien Hertz66516ac2015-01-09 14:51:41 +0100762 {
Sebastien Hertz4eec0262014-10-14 17:27:15 +0200763 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
764 Thread::resume_cond_->Broadcast(self);
765 }
766
767 VLOG(threads) << *self << " ResumeAllForDebugger complete";
768}
769
Elliott Hughes234ab152011-10-26 14:02:26 -0700770void ThreadList::UndoDebuggerSuspensions() {
771 Thread* self = Thread::Current();
772
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800773 VLOG(threads) << *self << " UndoDebuggerSuspensions starting";
Elliott Hughes234ab152011-10-26 14:02:26 -0700774
775 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700776 MutexLock mu(self, *Locks::thread_list_lock_);
777 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700778 // Update global suspend all state for attaching threads.
779 suspend_all_count_ -= debug_suspend_all_count_;
780 debug_suspend_all_count_ = 0;
781 // Update running threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700782 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700783 if (thread == self || thread->GetDebugSuspendCount() == 0) {
Elliott Hughes234ab152011-10-26 14:02:26 -0700784 continue;
785 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700786 thread->ModifySuspendCount(self, -thread->GetDebugSuspendCount(), true);
Elliott Hughes234ab152011-10-26 14:02:26 -0700787 }
788 }
789
790 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700791 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700792 Thread::resume_cond_->Broadcast(self);
Elliott Hughes234ab152011-10-26 14:02:26 -0700793 }
794
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800795 VLOG(threads) << "UndoDebuggerSuspensions(" << *self << ") complete";
Elliott Hughes234ab152011-10-26 14:02:26 -0700796}
797
Elliott Hughese52e49b2012-04-02 16:05:44 -0700798void ThreadList::WaitForOtherNonDaemonThreadsToExit() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700799 Thread* self = Thread::Current();
800 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700801 bool all_threads_are_daemons;
802 do {
Ian Rogers120f1c72012-09-28 17:17:10 -0700803 {
804 // No more threads can be born after we start to shutdown.
805 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700806 CHECK(Runtime::Current()->IsShuttingDownLocked());
Ian Rogers120f1c72012-09-28 17:17:10 -0700807 CHECK_EQ(Runtime::Current()->NumberOfThreadsBeingBorn(), 0U);
808 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700809 all_threads_are_daemons = true;
Ian Rogers120f1c72012-09-28 17:17:10 -0700810 MutexLock mu(self, *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700811 for (const auto& thread : list_) {
Anwar Ghuloum97543682013-06-14 12:58:16 -0700812 if (thread != self && !thread->IsDaemon()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700813 all_threads_are_daemons = false;
814 break;
815 }
816 }
817 if (!all_threads_are_daemons) {
818 // Wait for another thread to exit before re-checking.
Ian Rogersc604d732012-10-14 16:09:54 -0700819 thread_exit_cond_.Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700820 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700821 } while (!all_threads_are_daemons);
Elliott Hughes038a8062011-09-18 14:12:41 -0700822}
823
824void ThreadList::SuspendAllDaemonThreads() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700825 Thread* self = Thread::Current();
826 MutexLock mu(self, *Locks::thread_list_lock_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700827 { // Tell all the daemons it's time to suspend.
Ian Rogers81d425b2012-09-27 16:03:43 -0700828 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700829 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700830 // This is only run after all non-daemon threads have exited, so the remainder should all be
831 // daemons.
Ian Rogers7e762862012-10-22 15:45:08 -0700832 CHECK(thread->IsDaemon()) << *thread;
Ian Rogers81d425b2012-09-27 16:03:43 -0700833 if (thread != self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700834 thread->ModifySuspendCount(self, +1, false);
Elliott Hughese52e49b2012-04-02 16:05:44 -0700835 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700836 }
837 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700838 // Give the threads a chance to suspend, complaining if they're slow.
839 bool have_complained = false;
840 for (int i = 0; i < 10; ++i) {
841 usleep(200 * 1000);
842 bool all_suspended = true;
Mathieu Chartier02e25112013-08-14 16:14:24 -0700843 for (const auto& thread : list_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700844 if (thread != self && thread->GetState() == kRunnable) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700845 if (!have_complained) {
846 LOG(WARNING) << "daemon thread not yet suspended: " << *thread;
847 have_complained = true;
848 }
849 all_suspended = false;
850 }
851 }
852 if (all_suspended) {
853 return;
854 }
855 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700856 LOG(ERROR) << "suspend all daemons failed";
857}
858void ThreadList::Register(Thread* self) {
859 DCHECK_EQ(self, Thread::Current());
860
861 if (VLOG_IS_ON(threads)) {
862 std::ostringstream oss;
863 self->ShortDump(oss); // We don't hold the mutator_lock_ yet and so cannot call Dump.
Ian Rogers5a9ba012014-05-19 13:28:52 -0700864 LOG(INFO) << "ThreadList::Register() " << *self << "\n" << oss.str();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700865 }
866
867 // Atomically add self to the thread list and make its thread_suspend_count_ reflect ongoing
868 // SuspendAll requests.
Ian Rogers81d425b2012-09-27 16:03:43 -0700869 MutexLock mu(self, *Locks::thread_list_lock_);
870 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700871 CHECK_GE(suspend_all_count_, debug_suspend_all_count_);
Ian Rogers2966e132014-04-02 08:34:36 -0700872 // Modify suspend count in increments of 1 to maintain invariants in ModifySuspendCount. While
873 // this isn't particularly efficient the suspend counts are most commonly 0 or 1.
874 for (int delta = debug_suspend_all_count_; delta > 0; delta--) {
875 self->ModifySuspendCount(self, +1, true);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700876 }
Ian Rogers2966e132014-04-02 08:34:36 -0700877 for (int delta = suspend_all_count_ - debug_suspend_all_count_; delta > 0; delta--) {
878 self->ModifySuspendCount(self, +1, false);
Ian Rogers01ae5802012-09-28 16:14:01 -0700879 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700880 CHECK(!Contains(self));
881 list_.push_back(self);
882}
883
884void ThreadList::Unregister(Thread* self) {
885 DCHECK_EQ(self, Thread::Current());
886
887 VLOG(threads) << "ThreadList::Unregister() " << *self;
888
889 // Any time-consuming destruction, plus anything that can call back into managed code or
890 // suspend and so on, must happen at this point, and not in ~Thread.
891 self->Destroy();
892
Jeff Haofdcbc5c2014-10-14 13:12:01 -0700893 // If tracing, remember thread id and name before thread exits.
894 Trace::StoreExitingThreadInfo(self);
895
Ian Rogersdd7624d2014-03-14 17:43:00 -0700896 uint32_t thin_lock_id = self->GetThreadId();
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800897 while (self != nullptr) {
Ian Rogerscfaa4552012-11-26 21:00:08 -0800898 // Remove and delete the Thread* while holding the thread_list_lock_ and
899 // thread_suspend_count_lock_ so that the unregistering thread cannot be suspended.
Ian Rogers0878d652013-04-18 17:38:35 -0700900 // Note: deliberately not using MutexLock that could hold a stale self pointer.
901 Locks::thread_list_lock_->ExclusiveLock(self);
Ian Rogerse2bcf572014-09-15 15:17:07 -0700902 if (!Contains(self)) {
903 std::ostringstream os;
904 DumpNativeStack(os, GetTid(), " native: ", nullptr);
905 LOG(ERROR) << "Request to unregister unattached thread\n" << os.str();
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800906 self = nullptr;
Ian Rogerse2bcf572014-09-15 15:17:07 -0700907 } else {
908 // Note: we don't take the thread_suspend_count_lock_ here as to be suspending a thread other
909 // than yourself you need to hold the thread_list_lock_ (see Thread::ModifySuspendCount).
910 if (!self->IsSuspended()) {
911 list_.remove(self);
912 delete self;
913 self = nullptr;
914 }
Ian Rogerscfaa4552012-11-26 21:00:08 -0800915 }
Ian Rogers0878d652013-04-18 17:38:35 -0700916 Locks::thread_list_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700917 }
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800918 // Release the thread ID after the thread is finished and deleted to avoid cases where we can
919 // temporarily have multiple threads with the same thread id. When this occurs, it causes
920 // problems in FindThreadByThreadId / SuspendThreadByThreadId.
921 ReleaseThreadId(nullptr, thin_lock_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700922
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700923 // Clear the TLS data, so that the underlying native thread is recognizably detached.
924 // (It may wish to reattach later.)
925 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, NULL), "detach self");
926
927 // Signal that a thread just detached.
Ian Rogers81d425b2012-09-27 16:03:43 -0700928 MutexLock mu(NULL, *Locks::thread_list_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700929 thread_exit_cond_.Signal(NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700930}
931
932void ThreadList::ForEach(void (*callback)(Thread*, void*), void* context) {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700933 for (const auto& thread : list_) {
934 callback(thread, context);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700935 }
936}
937
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800938void ThreadList::VisitRoots(RootCallback* callback, void* arg) const {
Ian Rogers81d425b2012-09-27 16:03:43 -0700939 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700940 for (const auto& thread : list_) {
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800941 thread->VisitRoots(callback, arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700942 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700943}
944
Ian Rogerscfaa4552012-11-26 21:00:08 -0800945uint32_t ThreadList::AllocThreadId(Thread* self) {
Chao-ying Fu9e369312014-05-21 11:20:52 -0700946 MutexLock mu(self, *Locks::allocated_thread_ids_lock_);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700947 for (size_t i = 0; i < allocated_ids_.size(); ++i) {
948 if (!allocated_ids_[i]) {
949 allocated_ids_.set(i);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700950 return i + 1; // Zero is reserved to mean "invalid".
Elliott Hughes8daa0922011-09-11 13:46:25 -0700951 }
952 }
953 LOG(FATAL) << "Out of internal thread ids";
954 return 0;
955}
956
Ian Rogerscfaa4552012-11-26 21:00:08 -0800957void ThreadList::ReleaseThreadId(Thread* self, uint32_t id) {
Chao-ying Fu9e369312014-05-21 11:20:52 -0700958 MutexLock mu(self, *Locks::allocated_thread_ids_lock_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700959 --id; // Zero is reserved to mean "invalid".
Elliott Hughes8daa0922011-09-11 13:46:25 -0700960 DCHECK(allocated_ids_[id]) << id;
961 allocated_ids_.reset(id);
962}
963
Elliott Hughes8daa0922011-09-11 13:46:25 -0700964} // namespace art