blob: 740e3b086f41669f95aed82c818712a6b98eb746 [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.
Elliott Hughes8daa0922011-09-11 13:46:25 -070054 if (Contains(Thread::Current())) {
55 Runtime::Current()->DetachCurrentThread();
56 }
Elliott Hughes6a144332012-04-03 13:07:11 -070057
58 WaitForOtherNonDaemonThreadsToExit();
Ian Rogers00f7d0e2012-07-19 15:28:27 -070059 // TODO: there's an unaddressed race here where a thread may attach during shutdown, see
60 // Thread::Init.
Elliott Hughes6a144332012-04-03 13:07:11 -070061 SuspendAllDaemonThreads();
Elliott Hughes8daa0922011-09-11 13:46:25 -070062}
63
64bool ThreadList::Contains(Thread* thread) {
65 return find(list_.begin(), list_.end(), thread) != list_.end();
66}
67
Elliott Hughesabbe07d2012-06-05 17:42:23 -070068bool ThreadList::Contains(pid_t tid) {
Mathieu Chartier02e25112013-08-14 16:14:24 -070069 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -070070 if (thread->GetTid() == tid) {
Elliott Hughesabbe07d2012-06-05 17:42:23 -070071 return true;
72 }
73 }
74 return false;
75}
76
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -070077pid_t ThreadList::GetLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -070078 return Locks::thread_list_lock_->GetExclusiveOwnerTid();
Elliott Hughesaccd83d2011-10-17 14:25:58 -070079}
80
Mathieu Chartier590fee92013-09-13 13:46:47 -070081void ThreadList::DumpNativeStacks(std::ostream& os) {
82 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
83 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -070084 os << "DUMPING THREAD " << thread->GetTid() << "\n";
Christopher Ferrisa2cee182014-04-16 19:13:59 -070085 DumpNativeStack(os, thread->GetTid(), "\t");
Mathieu Chartier590fee92013-09-13 13:46:47 -070086 os << "\n";
87 }
88}
89
Elliott Hughesc967f782012-04-16 10:23:15 -070090void ThreadList::DumpForSigQuit(std::ostream& os) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -070091 {
Ian Rogers50b35e22012-10-04 10:09:15 -070092 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -070093 DumpLocked(os);
94 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -070095 DumpUnattachedThreads(os);
96}
97
Ian Rogerscfaa4552012-11-26 21:00:08 -080098static void DumpUnattachedThread(std::ostream& os, pid_t tid) NO_THREAD_SAFETY_ANALYSIS {
99 // TODO: No thread safety analysis as DumpState with a NULL thread won't access fields, should
100 // refactor DumpState to avoid skipping analysis.
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700101 Thread::DumpState(os, NULL, tid);
102 DumpKernelStack(os, tid, " kernel: ", false);
Brian Carlstromed8b7232012-06-27 17:54:47 -0700103 // TODO: Reenable this when the native code in system_server can handle it.
104 // Currently "adb shell kill -3 `pid system_server`" will cause it to exit.
105 if (false) {
Christopher Ferrisa2cee182014-04-16 19:13:59 -0700106 DumpNativeStack(os, tid, " native: ");
Brian Carlstromed8b7232012-06-27 17:54:47 -0700107 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700108 os << "\n";
109}
110
111void ThreadList::DumpUnattachedThreads(std::ostream& os) {
112 DIR* d = opendir("/proc/self/task");
113 if (!d) {
114 return;
115 }
116
Ian Rogers50b35e22012-10-04 10:09:15 -0700117 Thread* self = Thread::Current();
Elliott Hughes4696b5b2012-10-30 10:35:10 -0700118 dirent* e;
119 while ((e = readdir(d)) != NULL) {
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700120 char* end;
Elliott Hughes4696b5b2012-10-30 10:35:10 -0700121 pid_t tid = strtol(e->d_name, &end, 10);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700122 if (!*end) {
123 bool contains;
124 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700125 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700126 contains = Contains(tid);
127 }
128 if (!contains) {
129 DumpUnattachedThread(os, tid);
130 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700131 }
132 }
133 closedir(d);
Elliott Hughesff738062012-02-03 15:00:42 -0800134}
135
136void ThreadList::DumpLocked(std::ostream& os) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700137 os << "DALVIK THREADS (" << list_.size() << "):\n";
Mathieu Chartier02e25112013-08-14 16:14:24 -0700138 for (const auto& thread : list_) {
139 thread->Dump(os);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700140 os << "\n";
141 }
142}
143
Ian Rogers50b35e22012-10-04 10:09:15 -0700144void ThreadList::AssertThreadsAreSuspended(Thread* self, Thread* ignore1, Thread* ignore2) {
145 MutexLock mu(self, *Locks::thread_list_lock_);
146 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700147 for (const auto& thread : list_) {
jeffhao725a9572012-11-13 18:20:12 -0800148 if (thread != ignore1 && thread != ignore2) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700149 CHECK(thread->IsSuspended())
150 << "\nUnsuspended thread: <<" << *thread << "\n"
151 << "self: <<" << *Thread::Current();
152 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700153 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700154}
155
Ian Rogers66aee5c2012-08-15 17:17:47 -0700156#if HAVE_TIMED_RWLOCK
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700157// Attempt to rectify locks so that we dump thread list with required locks before exiting.
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100158static void UnsafeLogFatalForThreadSuspendAllTimeout() NO_THREAD_SAFETY_ANALYSIS __attribute__((noreturn));
159static void UnsafeLogFatalForThreadSuspendAllTimeout() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700160 Runtime* runtime = Runtime::Current();
161 std::ostringstream ss;
162 ss << "Thread suspend timeout\n";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700163 runtime->GetThreadList()->DumpLocked(ss);
164 LOG(FATAL) << ss.str();
Ian Rogers719d1a32014-03-06 12:13:39 -0800165 exit(0);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700166}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700167#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700168
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800169// Unlike suspending all threads where we can wait to acquire the mutator_lock_, suspending an
170// individual thread requires polling. delay_us is the requested sleep and total_delay_us
171// accumulates the total time spent sleeping for timeouts. The first sleep is just a yield,
172// subsequently sleeps increase delay_us from 1ms to 500ms by doubling.
Ian Rogersf3d874c2014-07-17 18:52:42 -0700173static void ThreadSuspendSleep(Thread* self, useconds_t* delay_us, useconds_t* total_delay_us) {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800174 useconds_t new_delay_us = (*delay_us) * 2;
175 CHECK_GE(new_delay_us, *delay_us);
176 if (new_delay_us < 500000) { // Don't allow sleeping to be more than 0.5s.
177 *delay_us = new_delay_us;
178 }
179 if (*delay_us == 0) {
180 sched_yield();
181 // Default to 1 milliseconds (note that this gets multiplied by 2 before the first sleep).
182 *delay_us = 500;
183 } else {
184 usleep(*delay_us);
185 *total_delay_us += *delay_us;
186 }
187}
188
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700189size_t ThreadList::RunCheckpoint(Closure* checkpoint_function) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700190 Thread* self = Thread::Current();
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800191 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
192 Locks::thread_list_lock_->AssertNotHeld(self);
193 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
194 if (kDebugLocking) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700195 CHECK_NE(self->GetState(), kRunnable);
196 }
197
198 std::vector<Thread*> suspended_count_modified_threads;
199 size_t count = 0;
200 {
201 // Call a checkpoint function for each thread, threads which are suspend get their checkpoint
202 // manually called.
203 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700204 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700205 for (const auto& thread : list_) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700206 if (thread != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700207 while (true) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700208 if (thread->RequestCheckpoint(checkpoint_function)) {
Dave Allison0aded082013-11-07 13:15:11 -0800209 // This thread will run its checkpoint some time in the near future.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700210 count++;
211 break;
212 } else {
213 // We are probably suspended, try to make sure that we stay suspended.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700214 // The thread switched back to runnable.
215 if (thread->GetState() == kRunnable) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700216 // Spurious fail, try again.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700217 continue;
218 }
219 thread->ModifySuspendCount(self, +1, false);
220 suspended_count_modified_threads.push_back(thread);
221 break;
222 }
223 }
224 }
225 }
226 }
227
228 // Run the checkpoint on ourself while we wait for threads to suspend.
229 checkpoint_function->Run(self);
230
231 // Run the checkpoint on the suspended threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700232 for (const auto& thread : suspended_count_modified_threads) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700233 if (!thread->IsSuspended()) {
234 // Wait until the thread is suspended.
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800235 useconds_t total_delay_us = 0;
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700236 do {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800237 useconds_t delay_us = 100;
Ian Rogersf3d874c2014-07-17 18:52:42 -0700238 ThreadSuspendSleep(self, &delay_us, &total_delay_us);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700239 } while (!thread->IsSuspended());
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800240 // Shouldn't need to wait for longer than 1000 microseconds.
241 constexpr useconds_t kLongWaitThresholdUS = 1000;
242 if (UNLIKELY(total_delay_us > kLongWaitThresholdUS)) {
243 LOG(WARNING) << "Waited " << total_delay_us << " us for thread suspend!";
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700244 }
245 }
246 // We know for sure that the thread is suspended at this point.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700247 checkpoint_function->Run(thread);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700248 {
249 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
250 thread->ModifySuspendCount(self, -1, false);
251 }
252 }
253
Mathieu Chartier664bebf2012-11-12 16:54:11 -0800254 {
255 // Imitate ResumeAll, threads may be waiting on Thread::resume_cond_ since we raised their
256 // suspend count. Now the suspend_count_ is lowered so we must do the broadcast.
257 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
258 Thread::resume_cond_->Broadcast(self);
259 }
260
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700261 // Add one for self.
262 return count + suspended_count_modified_threads.size() + 1;
263}
264
Dave Allison39c3bfb2014-01-28 18:33:52 -0800265// Request that a checkpoint function be run on all active (non-suspended)
266// threads. Returns the number of successful requests.
267size_t ThreadList::RunCheckpointOnRunnableThreads(Closure* checkpoint_function) {
268 Thread* self = Thread::Current();
269 if (kIsDebugBuild) {
270 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
271 Locks::thread_list_lock_->AssertNotHeld(self);
272 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
273 CHECK_NE(self->GetState(), kRunnable);
274 }
275
276 size_t count = 0;
277 {
278 // Call a checkpoint function for each non-suspended thread.
279 MutexLock mu(self, *Locks::thread_list_lock_);
280 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
281 for (const auto& thread : list_) {
282 if (thread != self) {
283 if (thread->RequestCheckpoint(checkpoint_function)) {
284 // This thread will run its checkpoint some time in the near future.
285 count++;
286 }
287 }
288 }
289 }
290
291 // Return the number of threads that will run the checkpoint function.
292 return count;
293}
294
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700295void ThreadList::SuspendAll() {
296 Thread* self = Thread::Current();
297
Jeff Haoc5d824a2014-07-28 18:35:38 -0700298 if (self != nullptr) {
299 VLOG(threads) << *self << " SuspendAll starting...";
300 } else {
301 VLOG(threads) << "Thread[null] SuspendAll starting...";
302 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700303 ATRACE_BEGIN("Suspending mutator threads");
Mathieu Chartier251755c2014-07-15 18:10:25 -0700304 uint64_t start_time = NanoTime();
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700305
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800306 Locks::mutator_lock_->AssertNotHeld(self);
307 Locks::thread_list_lock_->AssertNotHeld(self);
308 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
Jeff Haoc5d824a2014-07-28 18:35:38 -0700309 if (kDebugLocking && self != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700310 CHECK_NE(self->GetState(), kRunnable);
311 }
312 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700313 MutexLock mu(self, *Locks::thread_list_lock_);
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800314 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
315 // Update global suspend all state for attaching threads.
316 ++suspend_all_count_;
317 // Increment everybody's suspend count (except our own).
318 for (const auto& thread : list_) {
319 if (thread == self) {
320 continue;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700321 }
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800322 VLOG(threads) << "requesting thread suspend: " << *thread;
323 thread->ModifySuspendCount(self, +1, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700324 }
325 }
326
Ian Rogers66aee5c2012-08-15 17:17:47 -0700327 // Block on the mutator lock until all Runnable threads release their share of access.
328#if HAVE_TIMED_RWLOCK
329 // Timeout if we wait more than 30 seconds.
Ian Rogers719d1a32014-03-06 12:13:39 -0800330 if (!Locks::mutator_lock_->ExclusiveLockWithTimeout(self, 30 * 1000, 0)) {
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100331 UnsafeLogFatalForThreadSuspendAllTimeout();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700332 }
Ian Rogers66aee5c2012-08-15 17:17:47 -0700333#else
Ian Rogers81d425b2012-09-27 16:03:43 -0700334 Locks::mutator_lock_->ExclusiveLock(self);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700335#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700336
Mathieu Chartier251755c2014-07-15 18:10:25 -0700337 uint64_t end_time = NanoTime();
338 if (end_time - start_time > kLongThreadSuspendThreshold) {
339 LOG(WARNING) << "Suspending all threads took: " << PrettyDuration(end_time - start_time);
340 }
341
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800342 if (kDebugLocking) {
343 // Debug check that all threads are suspended.
344 AssertThreadsAreSuspended(self, self);
345 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700346
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700347 ATRACE_END();
348 ATRACE_BEGIN("Mutator threads suspended");
349
Jeff Haoc5d824a2014-07-28 18:35:38 -0700350 if (self != nullptr) {
351 VLOG(threads) << *self << " SuspendAll complete";
352 } else {
353 VLOG(threads) << "Thread[null] SuspendAll complete";
354 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700355}
356
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700357void ThreadList::ResumeAll() {
358 Thread* self = Thread::Current();
359
Jeff Haoc5d824a2014-07-28 18:35:38 -0700360 if (self != nullptr) {
361 VLOG(threads) << *self << " ResumeAll starting";
362 } else {
363 VLOG(threads) << "Thread[null] ResumeAll starting";
364 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700365
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700366 ATRACE_END();
367 ATRACE_BEGIN("Resuming mutator threads");
368
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800369 if (kDebugLocking) {
370 // Debug check that all threads are suspended.
371 AssertThreadsAreSuspended(self, self);
372 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700373
Ian Rogers81d425b2012-09-27 16:03:43 -0700374 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700375 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700376 MutexLock mu(self, *Locks::thread_list_lock_);
377 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700378 // Update global suspend all state for attaching threads.
379 --suspend_all_count_;
380 // Decrement the suspend counts for all threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700381 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700382 if (thread == self) {
383 continue;
384 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700385 thread->ModifySuspendCount(self, -1, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700386 }
387
388 // Broadcast a notification to all suspended threads, some or all of
389 // which may choose to wake up. No need to wait for them.
Jeff Haoc5d824a2014-07-28 18:35:38 -0700390 if (self != nullptr) {
391 VLOG(threads) << *self << " ResumeAll waking others";
392 } else {
393 VLOG(threads) << "Thread[null] ResumeAll waking others";
394 }
Ian Rogersc604d732012-10-14 16:09:54 -0700395 Thread::resume_cond_->Broadcast(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700396 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700397 ATRACE_END();
Jeff Haoc5d824a2014-07-28 18:35:38 -0700398
399 if (self != nullptr) {
400 VLOG(threads) << *self << " ResumeAll complete";
401 } else {
402 VLOG(threads) << "Thread[null] ResumeAll complete";
403 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700404}
405
406void ThreadList::Resume(Thread* thread, bool for_debugger) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700407 Thread* self = Thread::Current();
408 DCHECK_NE(thread, self);
Brian Carlstromba32de42014-08-27 23:43:46 -0700409 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") starting..."
410 << (for_debugger ? " (debugger)" : "");
Elliott Hughes01158d72011-09-19 19:47:10 -0700411
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700412 {
413 // To check Contains.
Ian Rogers81d425b2012-09-27 16:03:43 -0700414 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700415 // To check IsSuspended.
Ian Rogers81d425b2012-09-27 16:03:43 -0700416 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
417 DCHECK(thread->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700418 if (!Contains(thread)) {
Brian Carlstromba32de42014-08-27 23:43:46 -0700419 // We only expect threads within the thread-list to have been suspended otherwise we can't
420 // stop such threads from delete-ing themselves.
421 LOG(ERROR) << "Resume(" << reinterpret_cast<void*>(thread)
422 << ") thread not within thread list";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700423 return;
424 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700425 thread->ModifySuspendCount(self, -1, for_debugger);
Elliott Hughes01158d72011-09-19 19:47:10 -0700426 }
427
428 {
Brian Carlstromba32de42014-08-27 23:43:46 -0700429 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") waking others";
Ian Rogers81d425b2012-09-27 16:03:43 -0700430 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700431 Thread::resume_cond_->Broadcast(self);
Elliott Hughes01158d72011-09-19 19:47:10 -0700432 }
433
Brian Carlstromba32de42014-08-27 23:43:46 -0700434 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") complete";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700435}
Elliott Hughes01158d72011-09-19 19:47:10 -0700436
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700437static void ThreadSuspendByPeerWarning(Thread* self, int level, const char* message, jobject peer) {
438 JNIEnvExt* env = self->GetJniEnv();
439 ScopedLocalRef<jstring>
440 scoped_name_string(env, (jstring)env->GetObjectField(peer,
441 WellKnownClasses::java_lang_Thread_name));
442 ScopedUtfChars scoped_name_chars(env, scoped_name_string.get());
443 if (scoped_name_chars.c_str() == NULL) {
444 LOG(level) << message << ": " << peer;
445 env->ExceptionClear();
446 } else {
447 LOG(level) << message << ": " << peer << ":" << scoped_name_chars.c_str();
448 }
449}
450
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700451Thread* ThreadList::SuspendThreadByPeer(jobject peer, bool request_suspension,
452 bool debug_suspension, bool* timed_out) {
453 static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
454 useconds_t total_delay_us = 0;
455 useconds_t delay_us = 0;
456 bool did_suspend_request = false;
457 *timed_out = false;
458 Thread* self = Thread::Current();
Brian Carlstromba32de42014-08-27 23:43:46 -0700459 VLOG(threads) << "SuspendThreadByPeer starting";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700460 while (true) {
461 Thread* thread;
462 {
Ian Rogersf3d874c2014-07-17 18:52:42 -0700463 // Note: this will transition to runnable and potentially suspend. We ensure only one thread
464 // is requesting another suspend, to avoid deadlock, by requiring this function be called
465 // holding Locks::thread_list_suspend_thread_lock_. Its important this thread suspend rather
466 // than request thread suspension, to avoid potential cycles in threads requesting each other
467 // suspend.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700468 ScopedObjectAccess soa(self);
469 MutexLock mu(self, *Locks::thread_list_lock_);
470 thread = Thread::FromManagedThread(soa, peer);
Brian Carlstromba32de42014-08-27 23:43:46 -0700471 if (thread == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700472 ThreadSuspendByPeerWarning(self, WARNING, "No such thread for suspend", peer);
Brian Carlstromba32de42014-08-27 23:43:46 -0700473 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700474 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700475 if (!Contains(thread)) {
476 VLOG(threads) << "SuspendThreadByPeer failed for unattached thread: "
477 << reinterpret_cast<void*>(thread);
478 return nullptr;
479 }
480 VLOG(threads) << "SuspendThreadByPeer found thread: " << *thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700481 {
482 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
483 if (request_suspension) {
484 thread->ModifySuspendCount(self, +1, debug_suspension);
485 request_suspension = false;
486 did_suspend_request = true;
487 } else {
488 // If the caller isn't requesting suspension, a suspension should have already occurred.
489 CHECK_GT(thread->GetSuspendCount(), 0);
490 }
491 // IsSuspended on the current thread will fail as the current thread is changed into
492 // Runnable above. As the suspend count is now raised if this is the current thread
493 // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
494 // to just explicitly handle the current thread in the callers to this code.
495 CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
496 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
497 // count, or else we've waited and it has self suspended) or is the current thread, we're
498 // done.
499 if (thread->IsSuspended()) {
Brian Carlstromba32de42014-08-27 23:43:46 -0700500 VLOG(threads) << "SuspendThreadByPeer thread suspended: " << *thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700501 return thread;
502 }
503 if (total_delay_us >= kTimeoutUs) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700504 ThreadSuspendByPeerWarning(self, FATAL, "Thread suspension timed out", peer);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700505 if (did_suspend_request) {
506 thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
507 }
508 *timed_out = true;
Brian Carlstromba32de42014-08-27 23:43:46 -0700509 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700510 }
511 }
512 // Release locks and come out of runnable state.
513 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700514 VLOG(threads) << "SuspendThreadByPeer sleeping to allow thread chance to suspend";
Ian Rogersf3d874c2014-07-17 18:52:42 -0700515 ThreadSuspendSleep(self, &delay_us, &total_delay_us);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700516 }
517}
518
519static void ThreadSuspendByThreadIdWarning(int level, const char* message, uint32_t thread_id) {
520 LOG(level) << StringPrintf("%s: %d", message, thread_id);
521}
522
523Thread* ThreadList::SuspendThreadByThreadId(uint32_t thread_id, bool debug_suspension,
524 bool* timed_out) {
525 static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
526 useconds_t total_delay_us = 0;
527 useconds_t delay_us = 0;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700528 *timed_out = false;
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800529 Thread* suspended_thread = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700530 Thread* self = Thread::Current();
531 CHECK_NE(thread_id, kInvalidThreadId);
Brian Carlstromba32de42014-08-27 23:43:46 -0700532 VLOG(threads) << "SuspendThreadByThreadId starting";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700533 while (true) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700534 {
Ian Rogersf3d874c2014-07-17 18:52:42 -0700535 // Note: this will transition to runnable and potentially suspend. We ensure only one thread
536 // is requesting another suspend, to avoid deadlock, by requiring this function be called
537 // holding Locks::thread_list_suspend_thread_lock_. Its important this thread suspend rather
538 // than request thread suspension, to avoid potential cycles in threads requesting each other
539 // suspend.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700540 ScopedObjectAccess soa(self);
541 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogersf3d874c2014-07-17 18:52:42 -0700542 Thread* thread = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700543 for (const auto& it : list_) {
544 if (it->GetThreadId() == thread_id) {
545 thread = it;
546 break;
547 }
548 }
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800549 if (thread == nullptr) {
550 CHECK(suspended_thread == nullptr) << "Suspended thread " << suspended_thread
551 << " no longer in thread list";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700552 // There's a race in inflating a lock and the owner giving up ownership and then dying.
553 ThreadSuspendByThreadIdWarning(WARNING, "No such thread id for suspend", thread_id);
Brian Carlstromba32de42014-08-27 23:43:46 -0700554 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700555 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700556 VLOG(threads) << "SuspendThreadByThreadId found thread: " << *thread;
557 DCHECK(Contains(thread));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700558 {
559 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800560 if (suspended_thread == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700561 thread->ModifySuspendCount(self, +1, debug_suspension);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800562 suspended_thread = thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700563 } else {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800564 CHECK_EQ(suspended_thread, thread);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700565 // If the caller isn't requesting suspension, a suspension should have already occurred.
566 CHECK_GT(thread->GetSuspendCount(), 0);
567 }
568 // IsSuspended on the current thread will fail as the current thread is changed into
569 // Runnable above. As the suspend count is now raised if this is the current thread
570 // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
571 // to just explicitly handle the current thread in the callers to this code.
572 CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
573 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
574 // count, or else we've waited and it has self suspended) or is the current thread, we're
575 // done.
576 if (thread->IsSuspended()) {
Brian Carlstromba32de42014-08-27 23:43:46 -0700577 VLOG(threads) << "SuspendThreadByThreadId thread suspended: " << *thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700578 return thread;
579 }
580 if (total_delay_us >= kTimeoutUs) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700581 ThreadSuspendByThreadIdWarning(WARNING, "Thread suspension timed out", thread_id);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800582 if (suspended_thread != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700583 thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
584 }
585 *timed_out = true;
Brian Carlstromba32de42014-08-27 23:43:46 -0700586 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700587 }
588 }
589 // Release locks and come out of runnable state.
590 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700591 VLOG(threads) << "SuspendThreadByThreadId sleeping to allow thread chance to suspend";
Ian Rogersf3d874c2014-07-17 18:52:42 -0700592 ThreadSuspendSleep(self, &delay_us, &total_delay_us);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700593 }
594}
595
596Thread* ThreadList::FindThreadByThreadId(uint32_t thin_lock_id) {
597 Thread* self = Thread::Current();
598 MutexLock mu(self, *Locks::thread_list_lock_);
599 for (const auto& thread : list_) {
600 if (thread->GetThreadId() == thin_lock_id) {
601 CHECK(thread == self || thread->IsSuspended());
602 return thread;
603 }
604 }
605 return NULL;
606}
607
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700608void ThreadList::SuspendAllForDebugger() {
609 Thread* self = Thread::Current();
610 Thread* debug_thread = Dbg::GetDebugThread();
611
612 VLOG(threads) << *self << " SuspendAllForDebugger starting...";
613
614 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700615 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700616 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700617 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700618 // Update global suspend all state for attaching threads.
619 ++suspend_all_count_;
620 ++debug_suspend_all_count_;
621 // Increment everybody's suspend count (except our own).
Mathieu Chartier02e25112013-08-14 16:14:24 -0700622 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700623 if (thread == self || thread == debug_thread) {
624 continue;
625 }
626 VLOG(threads) << "requesting thread suspend: " << *thread;
Ian Rogers01ae5802012-09-28 16:14:01 -0700627 thread->ModifySuspendCount(self, +1, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700628 }
629 }
630 }
631
Ian Rogers66aee5c2012-08-15 17:17:47 -0700632 // Block on the mutator lock until all Runnable threads release their share of access then
633 // immediately unlock again.
634#if HAVE_TIMED_RWLOCK
635 // Timeout if we wait more than 30 seconds.
Ian Rogersc604d732012-10-14 16:09:54 -0700636 if (!Locks::mutator_lock_->ExclusiveLockWithTimeout(self, 30 * 1000, 0)) {
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100637 UnsafeLogFatalForThreadSuspendAllTimeout();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700638 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -0700639 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700640 }
Ian Rogers66aee5c2012-08-15 17:17:47 -0700641#else
Ian Rogers81d425b2012-09-27 16:03:43 -0700642 Locks::mutator_lock_->ExclusiveLock(self);
643 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700644#endif
Ian Rogers50b35e22012-10-04 10:09:15 -0700645 AssertThreadsAreSuspended(self, self, debug_thread);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700646
647 VLOG(threads) << *self << " SuspendAll complete";
Elliott Hughes01158d72011-09-19 19:47:10 -0700648}
649
Elliott Hughes475fc232011-10-25 15:00:35 -0700650void ThreadList::SuspendSelfForDebugger() {
651 Thread* self = Thread::Current();
Elliott Hughes01158d72011-09-19 19:47:10 -0700652
Elliott Hughes475fc232011-10-25 15:00:35 -0700653 // The debugger thread must not suspend itself due to debugger activity!
654 Thread* debug_thread = Dbg::GetDebugThread();
655 CHECK(debug_thread != NULL);
656 CHECK(self != debug_thread);
jeffhaoa77f0f62012-12-05 17:19:31 -0800657 CHECK_NE(self->GetState(), kRunnable);
658 Locks::mutator_lock_->AssertNotHeld(self);
Elliott Hughes475fc232011-10-25 15:00:35 -0700659
jeffhaoa77f0f62012-12-05 17:19:31 -0800660 {
661 // Collisions with other suspends aren't really interesting. We want
662 // to ensure that we're the only one fiddling with the suspend count
663 // though.
664 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
665 self->ModifySuspendCount(self, +1, true);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700666 CHECK_GT(self->GetSuspendCount(), 0);
jeffhaoa77f0f62012-12-05 17:19:31 -0800667 }
Elliott Hughes475fc232011-10-25 15:00:35 -0700668
Elliott Hughes1f729aa2012-03-02 13:55:41 -0800669 VLOG(threads) << *self << " self-suspending (debugger)";
Elliott Hughes475fc232011-10-25 15:00:35 -0700670
Sebastien Hertz21e729c2014-02-18 14:16:00 +0100671 // Tell JDWP we've completed invocation and are ready to suspend.
672 DebugInvokeReq* pReq = self->GetInvokeReq();
673 DCHECK(pReq != NULL);
674 if (pReq->invoke_needed) {
675 // Clear this before signaling.
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200676 pReq->Clear();
Sebastien Hertz21e729c2014-02-18 14:16:00 +0100677
678 VLOG(jdwp) << "invoke complete, signaling";
679 MutexLock mu(self, pReq->lock);
680 pReq->cond.Signal(self);
681 }
682
Elliott Hughes475fc232011-10-25 15:00:35 -0700683 // Tell JDWP that we've completed suspension. The JDWP thread can't
684 // tell us to resume before we're fully asleep because we hold the
685 // suspend count lock.
686 Dbg::ClearWaitForEventThread();
687
jeffhaoa77f0f62012-12-05 17:19:31 -0800688 {
689 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700690 while (self->GetSuspendCount() != 0) {
jeffhaoa77f0f62012-12-05 17:19:31 -0800691 Thread::resume_cond_->Wait(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700692 if (self->GetSuspendCount() != 0) {
jeffhaoa77f0f62012-12-05 17:19:31 -0800693 // The condition was signaled but we're still suspended. This
694 // can happen if the debugger lets go while a SIGQUIT thread
695 // dump event is pending (assuming SignalCatcher was resumed for
696 // just long enough to try to grab the thread-suspend lock).
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700697 LOG(WARNING) << *self << " still suspended after undo "
Ian Rogersdd7624d2014-03-14 17:43:00 -0700698 << "(suspend count=" << self->GetSuspendCount() << ")";
jeffhaoa77f0f62012-12-05 17:19:31 -0800699 }
Elliott Hughes475fc232011-10-25 15:00:35 -0700700 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700701 CHECK_EQ(self->GetSuspendCount(), 0);
Elliott Hughes475fc232011-10-25 15:00:35 -0700702 }
jeffhaoa77f0f62012-12-05 17:19:31 -0800703
Elliott Hughes1f729aa2012-03-02 13:55:41 -0800704 VLOG(threads) << *self << " self-reviving (debugger)";
Elliott Hughes475fc232011-10-25 15:00:35 -0700705}
706
Elliott Hughes234ab152011-10-26 14:02:26 -0700707void ThreadList::UndoDebuggerSuspensions() {
708 Thread* self = Thread::Current();
709
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800710 VLOG(threads) << *self << " UndoDebuggerSuspensions starting";
Elliott Hughes234ab152011-10-26 14:02:26 -0700711
712 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700713 MutexLock mu(self, *Locks::thread_list_lock_);
714 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700715 // Update global suspend all state for attaching threads.
716 suspend_all_count_ -= debug_suspend_all_count_;
717 debug_suspend_all_count_ = 0;
718 // Update running threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700719 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700720 if (thread == self || thread->GetDebugSuspendCount() == 0) {
Elliott Hughes234ab152011-10-26 14:02:26 -0700721 continue;
722 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700723 thread->ModifySuspendCount(self, -thread->GetDebugSuspendCount(), true);
Elliott Hughes234ab152011-10-26 14:02:26 -0700724 }
725 }
726
727 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700728 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700729 Thread::resume_cond_->Broadcast(self);
Elliott Hughes234ab152011-10-26 14:02:26 -0700730 }
731
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800732 VLOG(threads) << "UndoDebuggerSuspensions(" << *self << ") complete";
Elliott Hughes234ab152011-10-26 14:02:26 -0700733}
734
Elliott Hughese52e49b2012-04-02 16:05:44 -0700735void ThreadList::WaitForOtherNonDaemonThreadsToExit() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700736 Thread* self = Thread::Current();
737 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700738 bool all_threads_are_daemons;
739 do {
Ian Rogers120f1c72012-09-28 17:17:10 -0700740 {
741 // No more threads can be born after we start to shutdown.
742 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700743 CHECK(Runtime::Current()->IsShuttingDownLocked());
Ian Rogers120f1c72012-09-28 17:17:10 -0700744 CHECK_EQ(Runtime::Current()->NumberOfThreadsBeingBorn(), 0U);
745 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700746 all_threads_are_daemons = true;
Ian Rogers120f1c72012-09-28 17:17:10 -0700747 MutexLock mu(self, *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700748 for (const auto& thread : list_) {
Anwar Ghuloum97543682013-06-14 12:58:16 -0700749 if (thread != self && !thread->IsDaemon()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700750 all_threads_are_daemons = false;
751 break;
752 }
753 }
754 if (!all_threads_are_daemons) {
755 // Wait for another thread to exit before re-checking.
Ian Rogersc604d732012-10-14 16:09:54 -0700756 thread_exit_cond_.Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700757 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700758 } while (!all_threads_are_daemons);
Elliott Hughes038a8062011-09-18 14:12:41 -0700759}
760
761void ThreadList::SuspendAllDaemonThreads() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700762 Thread* self = Thread::Current();
763 MutexLock mu(self, *Locks::thread_list_lock_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700764 { // Tell all the daemons it's time to suspend.
Ian Rogers81d425b2012-09-27 16:03:43 -0700765 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700766 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700767 // This is only run after all non-daemon threads have exited, so the remainder should all be
768 // daemons.
Ian Rogers7e762862012-10-22 15:45:08 -0700769 CHECK(thread->IsDaemon()) << *thread;
Ian Rogers81d425b2012-09-27 16:03:43 -0700770 if (thread != self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700771 thread->ModifySuspendCount(self, +1, false);
Elliott Hughese52e49b2012-04-02 16:05:44 -0700772 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700773 }
774 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700775 // Give the threads a chance to suspend, complaining if they're slow.
776 bool have_complained = false;
777 for (int i = 0; i < 10; ++i) {
778 usleep(200 * 1000);
779 bool all_suspended = true;
Mathieu Chartier02e25112013-08-14 16:14:24 -0700780 for (const auto& thread : list_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700781 if (thread != self && thread->GetState() == kRunnable) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700782 if (!have_complained) {
783 LOG(WARNING) << "daemon thread not yet suspended: " << *thread;
784 have_complained = true;
785 }
786 all_suspended = false;
787 }
788 }
789 if (all_suspended) {
790 return;
791 }
792 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700793 LOG(ERROR) << "suspend all daemons failed";
794}
795void ThreadList::Register(Thread* self) {
796 DCHECK_EQ(self, Thread::Current());
797
798 if (VLOG_IS_ON(threads)) {
799 std::ostringstream oss;
800 self->ShortDump(oss); // We don't hold the mutator_lock_ yet and so cannot call Dump.
Ian Rogers5a9ba012014-05-19 13:28:52 -0700801 LOG(INFO) << "ThreadList::Register() " << *self << "\n" << oss.str();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700802 }
803
804 // Atomically add self to the thread list and make its thread_suspend_count_ reflect ongoing
805 // SuspendAll requests.
Ian Rogers81d425b2012-09-27 16:03:43 -0700806 MutexLock mu(self, *Locks::thread_list_lock_);
807 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700808 CHECK_GE(suspend_all_count_, debug_suspend_all_count_);
Ian Rogers2966e132014-04-02 08:34:36 -0700809 // Modify suspend count in increments of 1 to maintain invariants in ModifySuspendCount. While
810 // this isn't particularly efficient the suspend counts are most commonly 0 or 1.
811 for (int delta = debug_suspend_all_count_; delta > 0; delta--) {
812 self->ModifySuspendCount(self, +1, true);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700813 }
Ian Rogers2966e132014-04-02 08:34:36 -0700814 for (int delta = suspend_all_count_ - debug_suspend_all_count_; delta > 0; delta--) {
815 self->ModifySuspendCount(self, +1, false);
Ian Rogers01ae5802012-09-28 16:14:01 -0700816 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700817 CHECK(!Contains(self));
818 list_.push_back(self);
819}
820
821void ThreadList::Unregister(Thread* self) {
822 DCHECK_EQ(self, Thread::Current());
Ian Rogers68d8b422014-07-17 11:09:10 -0700823 CHECK_NE(self->GetState(), kRunnable);
824 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700825
826 VLOG(threads) << "ThreadList::Unregister() " << *self;
827
828 // Any time-consuming destruction, plus anything that can call back into managed code or
829 // suspend and so on, must happen at this point, and not in ~Thread.
830 self->Destroy();
831
Ian Rogersdd7624d2014-03-14 17:43:00 -0700832 uint32_t thin_lock_id = self->GetThreadId();
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800833 while (self != nullptr) {
Ian Rogerscfaa4552012-11-26 21:00:08 -0800834 // Remove and delete the Thread* while holding the thread_list_lock_ and
835 // thread_suspend_count_lock_ so that the unregistering thread cannot be suspended.
Ian Rogers0878d652013-04-18 17:38:35 -0700836 // Note: deliberately not using MutexLock that could hold a stale self pointer.
837 Locks::thread_list_lock_->ExclusiveLock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700838 CHECK(Contains(self));
Ian Rogers68d8b422014-07-17 11:09:10 -0700839 Locks::thread_suspend_count_lock_->ExclusiveLock(self);
840 bool removed = false;
Ian Rogerscfaa4552012-11-26 21:00:08 -0800841 if (!self->IsSuspended()) {
842 list_.remove(self);
Ian Rogers68d8b422014-07-17 11:09:10 -0700843 removed = true;
844 }
845 Locks::thread_suspend_count_lock_->ExclusiveUnlock(self);
846 Locks::thread_list_lock_->ExclusiveUnlock(self);
847 if (removed) {
Ian Rogerscfaa4552012-11-26 21:00:08 -0800848 delete self;
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800849 self = nullptr;
Ian Rogerscfaa4552012-11-26 21:00:08 -0800850 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700851 }
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800852 // Release the thread ID after the thread is finished and deleted to avoid cases where we can
853 // temporarily have multiple threads with the same thread id. When this occurs, it causes
854 // problems in FindThreadByThreadId / SuspendThreadByThreadId.
855 ReleaseThreadId(nullptr, thin_lock_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700856
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700857 // Clear the TLS data, so that the underlying native thread is recognizably detached.
858 // (It may wish to reattach later.)
859 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, NULL), "detach self");
860
861 // Signal that a thread just detached.
Ian Rogers81d425b2012-09-27 16:03:43 -0700862 MutexLock mu(NULL, *Locks::thread_list_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700863 thread_exit_cond_.Signal(NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700864}
865
866void ThreadList::ForEach(void (*callback)(Thread*, void*), void* context) {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700867 for (const auto& thread : list_) {
868 callback(thread, context);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700869 }
870}
871
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800872void ThreadList::VisitRoots(RootCallback* callback, void* arg) const {
Ian Rogers81d425b2012-09-27 16:03:43 -0700873 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700874 for (const auto& thread : list_) {
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800875 thread->VisitRoots(callback, arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700876 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700877}
878
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800879class VerifyRootWrapperArg {
880 public:
881 VerifyRootWrapperArg(VerifyRootCallback* callback, void* arg) : callback_(callback), arg_(arg) {
882 }
883 VerifyRootCallback* const callback_;
884 void* const arg_;
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700885};
886
Mathieu Chartier815873e2014-02-13 18:02:13 -0800887static void VerifyRootWrapperCallback(mirror::Object** root, void* arg, uint32_t /*thread_id*/,
Mathieu Chartier7bf9f192014-04-04 11:09:41 -0700888 RootType root_type) {
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700889 VerifyRootWrapperArg* wrapperArg = reinterpret_cast<VerifyRootWrapperArg*>(arg);
Mathieu Chartier7bf9f192014-04-04 11:09:41 -0700890 wrapperArg->callback_(*root, wrapperArg->arg_, 0, NULL, root_type);
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700891}
892
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800893void ThreadList::VerifyRoots(VerifyRootCallback* callback, void* arg) const {
894 VerifyRootWrapperArg wrapper(callback, arg);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700895 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700896 for (const auto& thread : list_) {
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700897 thread->VisitRoots(VerifyRootWrapperCallback, &wrapper);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700898 }
899}
900
Ian Rogerscfaa4552012-11-26 21:00:08 -0800901uint32_t ThreadList::AllocThreadId(Thread* self) {
Chao-ying Fu9e369312014-05-21 11:20:52 -0700902 MutexLock mu(self, *Locks::allocated_thread_ids_lock_);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700903 for (size_t i = 0; i < allocated_ids_.size(); ++i) {
904 if (!allocated_ids_[i]) {
905 allocated_ids_.set(i);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700906 return i + 1; // Zero is reserved to mean "invalid".
Elliott Hughes8daa0922011-09-11 13:46:25 -0700907 }
908 }
909 LOG(FATAL) << "Out of internal thread ids";
910 return 0;
911}
912
Ian Rogerscfaa4552012-11-26 21:00:08 -0800913void ThreadList::ReleaseThreadId(Thread* self, uint32_t id) {
Chao-ying Fu9e369312014-05-21 11:20:52 -0700914 MutexLock mu(self, *Locks::allocated_thread_ids_lock_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700915 --id; // Zero is reserved to mean "invalid".
Elliott Hughes8daa0922011-09-11 13:46:25 -0700916 DCHECK(allocated_ids_[id]) << id;
917 allocated_ids_.reset(id);
918}
919
Elliott Hughes8daa0922011-09-11 13:46:25 -0700920} // namespace art