blob: b48fcd4f52138132a3e479f4eeb4b55b2d79e2b9 [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 Chartierb960cd72014-07-15 18:10:25 -070042static constexpr uint64_t kLongThreadSuspendThreshold = MsToNs(5);
43
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -080044ThreadList::ThreadList()
Chao-ying Fu9e369312014-05-21 11:20:52 -070045 : suspend_all_count_(0), debug_suspend_all_count_(0),
Ian Rogersc604d732012-10-14 16:09:54 -070046 thread_exit_cond_("thread exit condition variable", *Locks::thread_list_lock_) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -070047 CHECK(Monitor::IsValidLockWord(LockWord::FromThinLockId(kMaxThreadId, 1)));
Elliott Hughes8daa0922011-09-11 13:46:25 -070048}
49
50ThreadList::~ThreadList() {
Elliott Hughese52e49b2012-04-02 16:05:44 -070051 // Detach the current thread if necessary. If we failed to start, there might not be any threads.
Elliott Hughes6a144332012-04-03 13:07:11 -070052 // We need to detach the current thread here in case there's another thread waiting to join with
53 // us.
Mathieu Chartierb90132c2014-10-09 12:57:58 -070054 bool contains = false;
55 {
56 Thread* self = Thread::Current();
57 MutexLock mu(self, *Locks::thread_list_lock_);
58 contains = Contains(self);
59 }
60 if (contains) {
Elliott Hughes8daa0922011-09-11 13:46:25 -070061 Runtime::Current()->DetachCurrentThread();
62 }
Elliott Hughes6a144332012-04-03 13:07:11 -070063
64 WaitForOtherNonDaemonThreadsToExit();
Ian Rogers00f7d0e2012-07-19 15:28:27 -070065 // TODO: there's an unaddressed race here where a thread may attach during shutdown, see
66 // Thread::Init.
Elliott Hughes6a144332012-04-03 13:07:11 -070067 SuspendAllDaemonThreads();
Elliott Hughes8daa0922011-09-11 13:46:25 -070068}
69
70bool ThreadList::Contains(Thread* thread) {
71 return find(list_.begin(), list_.end(), thread) != list_.end();
72}
73
Elliott Hughesabbe07d2012-06-05 17:42:23 -070074bool ThreadList::Contains(pid_t tid) {
Mathieu Chartier02e25112013-08-14 16:14:24 -070075 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -070076 if (thread->GetTid() == tid) {
Elliott Hughesabbe07d2012-06-05 17:42:23 -070077 return true;
78 }
79 }
80 return false;
81}
82
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -070083pid_t ThreadList::GetLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -070084 return Locks::thread_list_lock_->GetExclusiveOwnerTid();
Elliott Hughesaccd83d2011-10-17 14:25:58 -070085}
86
Mathieu Chartier590fee92013-09-13 13:46:47 -070087void ThreadList::DumpNativeStacks(std::ostream& os) {
88 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
89 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -070090 os << "DUMPING THREAD " << thread->GetTid() << "\n";
Christopher Ferrisa2cee182014-04-16 19:13:59 -070091 DumpNativeStack(os, thread->GetTid(), "\t");
Mathieu Chartier590fee92013-09-13 13:46:47 -070092 os << "\n";
93 }
94}
95
Elliott Hughesc967f782012-04-16 10:23:15 -070096void ThreadList::DumpForSigQuit(std::ostream& os) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -070097 {
Ian Rogers50b35e22012-10-04 10:09:15 -070098 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -070099 DumpLocked(os);
100 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700101 DumpUnattachedThreads(os);
102}
103
Ian Rogerscfaa4552012-11-26 21:00:08 -0800104static void DumpUnattachedThread(std::ostream& os, pid_t tid) NO_THREAD_SAFETY_ANALYSIS {
105 // TODO: No thread safety analysis as DumpState with a NULL thread won't access fields, should
106 // refactor DumpState to avoid skipping analysis.
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700107 Thread::DumpState(os, NULL, tid);
108 DumpKernelStack(os, tid, " kernel: ", false);
Brian Carlstromed8b7232012-06-27 17:54:47 -0700109 // TODO: Reenable this when the native code in system_server can handle it.
110 // Currently "adb shell kill -3 `pid system_server`" will cause it to exit.
111 if (false) {
Christopher Ferrisa2cee182014-04-16 19:13:59 -0700112 DumpNativeStack(os, tid, " native: ");
Brian Carlstromed8b7232012-06-27 17:54:47 -0700113 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700114 os << "\n";
115}
116
117void ThreadList::DumpUnattachedThreads(std::ostream& os) {
118 DIR* d = opendir("/proc/self/task");
119 if (!d) {
120 return;
121 }
122
Ian Rogers50b35e22012-10-04 10:09:15 -0700123 Thread* self = Thread::Current();
Elliott Hughes4696b5b2012-10-30 10:35:10 -0700124 dirent* e;
125 while ((e = readdir(d)) != NULL) {
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700126 char* end;
Elliott Hughes4696b5b2012-10-30 10:35:10 -0700127 pid_t tid = strtol(e->d_name, &end, 10);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700128 if (!*end) {
129 bool contains;
130 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700131 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700132 contains = Contains(tid);
133 }
134 if (!contains) {
135 DumpUnattachedThread(os, tid);
136 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700137 }
138 }
139 closedir(d);
Elliott Hughesff738062012-02-03 15:00:42 -0800140}
141
142void ThreadList::DumpLocked(std::ostream& os) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700143 os << "DALVIK THREADS (" << list_.size() << "):\n";
Mathieu Chartier02e25112013-08-14 16:14:24 -0700144 for (const auto& thread : list_) {
145 thread->Dump(os);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700146 os << "\n";
147 }
148}
149
Ian Rogers50b35e22012-10-04 10:09:15 -0700150void ThreadList::AssertThreadsAreSuspended(Thread* self, Thread* ignore1, Thread* ignore2) {
151 MutexLock mu(self, *Locks::thread_list_lock_);
152 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700153 for (const auto& thread : list_) {
jeffhao725a9572012-11-13 18:20:12 -0800154 if (thread != ignore1 && thread != ignore2) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700155 CHECK(thread->IsSuspended())
156 << "\nUnsuspended thread: <<" << *thread << "\n"
157 << "self: <<" << *Thread::Current();
158 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700159 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700160}
161
Ian Rogers66aee5c2012-08-15 17:17:47 -0700162#if HAVE_TIMED_RWLOCK
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700163// Attempt to rectify locks so that we dump thread list with required locks before exiting.
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100164static void UnsafeLogFatalForThreadSuspendAllTimeout() NO_THREAD_SAFETY_ANALYSIS __attribute__((noreturn));
165static void UnsafeLogFatalForThreadSuspendAllTimeout() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700166 Runtime* runtime = Runtime::Current();
167 std::ostringstream ss;
168 ss << "Thread suspend timeout\n";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700169 runtime->GetThreadList()->DumpLocked(ss);
170 LOG(FATAL) << ss.str();
Ian Rogers719d1a32014-03-06 12:13:39 -0800171 exit(0);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700172}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700173#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700174
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800175// Unlike suspending all threads where we can wait to acquire the mutator_lock_, suspending an
176// individual thread requires polling. delay_us is the requested sleep and total_delay_us
177// accumulates the total time spent sleeping for timeouts. The first sleep is just a yield,
178// subsequently sleeps increase delay_us from 1ms to 500ms by doubling.
Ian Rogers6093a5c2014-07-17 18:52:42 -0700179static void ThreadSuspendSleep(Thread* self, useconds_t* delay_us, useconds_t* total_delay_us) {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800180 useconds_t new_delay_us = (*delay_us) * 2;
181 CHECK_GE(new_delay_us, *delay_us);
182 if (new_delay_us < 500000) { // Don't allow sleeping to be more than 0.5s.
183 *delay_us = new_delay_us;
184 }
185 if (*delay_us == 0) {
186 sched_yield();
187 // Default to 1 milliseconds (note that this gets multiplied by 2 before the first sleep).
188 *delay_us = 500;
189 } else {
190 usleep(*delay_us);
191 *total_delay_us += *delay_us;
192 }
193}
194
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700195size_t ThreadList::RunCheckpoint(Closure* checkpoint_function) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700196 Thread* self = Thread::Current();
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800197 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
198 Locks::thread_list_lock_->AssertNotHeld(self);
199 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
200 if (kDebugLocking) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700201 CHECK_NE(self->GetState(), kRunnable);
202 }
203
204 std::vector<Thread*> suspended_count_modified_threads;
205 size_t count = 0;
206 {
207 // Call a checkpoint function for each thread, threads which are suspend get their checkpoint
208 // manually called.
209 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700210 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700211 for (const auto& thread : list_) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700212 if (thread != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700213 while (true) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700214 if (thread->RequestCheckpoint(checkpoint_function)) {
Dave Allison0aded082013-11-07 13:15:11 -0800215 // This thread will run its checkpoint some time in the near future.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700216 count++;
217 break;
218 } else {
219 // We are probably suspended, try to make sure that we stay suspended.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700220 // The thread switched back to runnable.
221 if (thread->GetState() == kRunnable) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700222 // Spurious fail, try again.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700223 continue;
224 }
225 thread->ModifySuspendCount(self, +1, false);
226 suspended_count_modified_threads.push_back(thread);
227 break;
228 }
229 }
230 }
231 }
232 }
233
234 // Run the checkpoint on ourself while we wait for threads to suspend.
235 checkpoint_function->Run(self);
236
237 // Run the checkpoint on the suspended threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700238 for (const auto& thread : suspended_count_modified_threads) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700239 if (!thread->IsSuspended()) {
240 // Wait until the thread is suspended.
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800241 useconds_t total_delay_us = 0;
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700242 do {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800243 useconds_t delay_us = 100;
Ian Rogers6093a5c2014-07-17 18:52:42 -0700244 ThreadSuspendSleep(self, &delay_us, &total_delay_us);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700245 } while (!thread->IsSuspended());
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800246 // Shouldn't need to wait for longer than 1000 microseconds.
247 constexpr useconds_t kLongWaitThresholdUS = 1000;
248 if (UNLIKELY(total_delay_us > kLongWaitThresholdUS)) {
249 LOG(WARNING) << "Waited " << total_delay_us << " us for thread suspend!";
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700250 }
251 }
252 // We know for sure that the thread is suspended at this point.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700253 checkpoint_function->Run(thread);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700254 {
255 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
256 thread->ModifySuspendCount(self, -1, false);
257 }
258 }
259
Mathieu Chartier664bebf2012-11-12 16:54:11 -0800260 {
261 // Imitate ResumeAll, threads may be waiting on Thread::resume_cond_ since we raised their
262 // suspend count. Now the suspend_count_ is lowered so we must do the broadcast.
263 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
264 Thread::resume_cond_->Broadcast(self);
265 }
266
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700267 // Add one for self.
268 return count + suspended_count_modified_threads.size() + 1;
269}
270
Dave Allison39c3bfb2014-01-28 18:33:52 -0800271// Request that a checkpoint function be run on all active (non-suspended)
272// threads. Returns the number of successful requests.
273size_t ThreadList::RunCheckpointOnRunnableThreads(Closure* checkpoint_function) {
274 Thread* self = Thread::Current();
275 if (kIsDebugBuild) {
276 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
277 Locks::thread_list_lock_->AssertNotHeld(self);
278 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
279 CHECK_NE(self->GetState(), kRunnable);
280 }
281
282 size_t count = 0;
283 {
284 // Call a checkpoint function for each non-suspended thread.
285 MutexLock mu(self, *Locks::thread_list_lock_);
286 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
287 for (const auto& thread : list_) {
288 if (thread != self) {
289 if (thread->RequestCheckpoint(checkpoint_function)) {
290 // This thread will run its checkpoint some time in the near future.
291 count++;
292 }
293 }
294 }
295 }
296
297 // Return the number of threads that will run the checkpoint function.
298 return count;
299}
300
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700301void ThreadList::SuspendAll() {
302 Thread* self = Thread::Current();
303
Jeff Haoc7c6d182014-07-28 18:35:38 -0700304 if (self != nullptr) {
305 VLOG(threads) << *self << " SuspendAll starting...";
306 } else {
307 VLOG(threads) << "Thread[null] SuspendAll starting...";
308 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700309 ATRACE_BEGIN("Suspending mutator threads");
Mathieu Chartierb960cd72014-07-15 18:10:25 -0700310 uint64_t start_time = NanoTime();
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700311
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800312 Locks::mutator_lock_->AssertNotHeld(self);
313 Locks::thread_list_lock_->AssertNotHeld(self);
314 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
Jeff Haoc7c6d182014-07-28 18:35:38 -0700315 if (kDebugLocking && self != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700316 CHECK_NE(self->GetState(), kRunnable);
317 }
318 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700319 MutexLock mu(self, *Locks::thread_list_lock_);
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800320 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
321 // Update global suspend all state for attaching threads.
322 ++suspend_all_count_;
323 // Increment everybody's suspend count (except our own).
324 for (const auto& thread : list_) {
325 if (thread == self) {
326 continue;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700327 }
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800328 VLOG(threads) << "requesting thread suspend: " << *thread;
329 thread->ModifySuspendCount(self, +1, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700330 }
331 }
332
Ian Rogers66aee5c2012-08-15 17:17:47 -0700333 // Block on the mutator lock until all Runnable threads release their share of access.
334#if HAVE_TIMED_RWLOCK
335 // Timeout if we wait more than 30 seconds.
Ian Rogers719d1a32014-03-06 12:13:39 -0800336 if (!Locks::mutator_lock_->ExclusiveLockWithTimeout(self, 30 * 1000, 0)) {
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100337 UnsafeLogFatalForThreadSuspendAllTimeout();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700338 }
Ian Rogers66aee5c2012-08-15 17:17:47 -0700339#else
Ian Rogers81d425b2012-09-27 16:03:43 -0700340 Locks::mutator_lock_->ExclusiveLock(self);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700341#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700342
Mathieu Chartierb960cd72014-07-15 18:10:25 -0700343 uint64_t end_time = NanoTime();
344 if (end_time - start_time > kLongThreadSuspendThreshold) {
345 LOG(WARNING) << "Suspending all threads took: " << PrettyDuration(end_time - start_time);
346 }
347
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800348 if (kDebugLocking) {
349 // Debug check that all threads are suspended.
350 AssertThreadsAreSuspended(self, self);
351 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700352
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700353 ATRACE_END();
354 ATRACE_BEGIN("Mutator threads suspended");
355
Jeff Haoc7c6d182014-07-28 18:35:38 -0700356 if (self != nullptr) {
357 VLOG(threads) << *self << " SuspendAll complete";
358 } else {
359 VLOG(threads) << "Thread[null] SuspendAll complete";
360 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700361}
362
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700363void ThreadList::ResumeAll() {
364 Thread* self = Thread::Current();
365
Jeff Haoc7c6d182014-07-28 18:35:38 -0700366 if (self != nullptr) {
367 VLOG(threads) << *self << " ResumeAll starting";
368 } else {
369 VLOG(threads) << "Thread[null] ResumeAll starting";
370 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700371
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700372 ATRACE_END();
373 ATRACE_BEGIN("Resuming mutator threads");
374
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800375 if (kDebugLocking) {
376 // Debug check that all threads are suspended.
377 AssertThreadsAreSuspended(self, self);
378 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700379
Ian Rogers81d425b2012-09-27 16:03:43 -0700380 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700381 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700382 MutexLock mu(self, *Locks::thread_list_lock_);
383 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700384 // Update global suspend all state for attaching threads.
385 --suspend_all_count_;
386 // Decrement the suspend counts for all threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700387 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700388 if (thread == self) {
389 continue;
390 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700391 thread->ModifySuspendCount(self, -1, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700392 }
393
394 // Broadcast a notification to all suspended threads, some or all of
395 // which may choose to wake up. No need to wait for them.
Jeff Haoc7c6d182014-07-28 18:35:38 -0700396 if (self != nullptr) {
397 VLOG(threads) << *self << " ResumeAll waking others";
398 } else {
399 VLOG(threads) << "Thread[null] ResumeAll waking others";
400 }
Ian Rogersc604d732012-10-14 16:09:54 -0700401 Thread::resume_cond_->Broadcast(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700402 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700403 ATRACE_END();
Jeff Haoc7c6d182014-07-28 18:35:38 -0700404
405 if (self != nullptr) {
406 VLOG(threads) << *self << " ResumeAll complete";
407 } else {
408 VLOG(threads) << "Thread[null] ResumeAll complete";
409 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700410}
411
412void ThreadList::Resume(Thread* thread, bool for_debugger) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700413 Thread* self = Thread::Current();
414 DCHECK_NE(thread, self);
Brian Carlstrom37c16452014-08-27 23:43:46 -0700415 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") starting..."
416 << (for_debugger ? " (debugger)" : "");
Elliott Hughes01158d72011-09-19 19:47:10 -0700417
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700418 {
419 // To check Contains.
Ian Rogers81d425b2012-09-27 16:03:43 -0700420 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700421 // To check IsSuspended.
Ian Rogers81d425b2012-09-27 16:03:43 -0700422 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
423 DCHECK(thread->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700424 if (!Contains(thread)) {
Brian Carlstrom37c16452014-08-27 23:43:46 -0700425 // We only expect threads within the thread-list to have been suspended otherwise we can't
426 // stop such threads from delete-ing themselves.
427 LOG(ERROR) << "Resume(" << reinterpret_cast<void*>(thread)
428 << ") thread not within thread list";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700429 return;
430 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700431 thread->ModifySuspendCount(self, -1, for_debugger);
Elliott Hughes01158d72011-09-19 19:47:10 -0700432 }
433
434 {
Brian Carlstrom37c16452014-08-27 23:43:46 -0700435 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") waking others";
Ian Rogers81d425b2012-09-27 16:03:43 -0700436 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700437 Thread::resume_cond_->Broadcast(self);
Elliott Hughes01158d72011-09-19 19:47:10 -0700438 }
439
Brian Carlstrom37c16452014-08-27 23:43:46 -0700440 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") complete";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700441}
Elliott Hughes01158d72011-09-19 19:47:10 -0700442
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700443static void ThreadSuspendByPeerWarning(Thread* self, int level, const char* message, jobject peer) {
444 JNIEnvExt* env = self->GetJniEnv();
445 ScopedLocalRef<jstring>
446 scoped_name_string(env, (jstring)env->GetObjectField(peer,
447 WellKnownClasses::java_lang_Thread_name));
448 ScopedUtfChars scoped_name_chars(env, scoped_name_string.get());
449 if (scoped_name_chars.c_str() == NULL) {
450 LOG(level) << message << ": " << peer;
451 env->ExceptionClear();
452 } else {
453 LOG(level) << message << ": " << peer << ":" << scoped_name_chars.c_str();
454 }
455}
456
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700457Thread* ThreadList::SuspendThreadByPeer(jobject peer, bool request_suspension,
458 bool debug_suspension, bool* timed_out) {
459 static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
460 useconds_t total_delay_us = 0;
461 useconds_t delay_us = 0;
462 bool did_suspend_request = false;
463 *timed_out = false;
464 Thread* self = Thread::Current();
Brian Carlstrom37c16452014-08-27 23:43:46 -0700465 VLOG(threads) << "SuspendThreadByPeer starting";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700466 while (true) {
467 Thread* thread;
468 {
Ian Rogers6093a5c2014-07-17 18:52:42 -0700469 // Note: this will transition to runnable and potentially suspend. We ensure only one thread
470 // is requesting another suspend, to avoid deadlock, by requiring this function be called
471 // holding Locks::thread_list_suspend_thread_lock_. Its important this thread suspend rather
472 // than request thread suspension, to avoid potential cycles in threads requesting each other
473 // suspend.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700474 ScopedObjectAccess soa(self);
475 MutexLock mu(self, *Locks::thread_list_lock_);
476 thread = Thread::FromManagedThread(soa, peer);
Brian Carlstrom37c16452014-08-27 23:43:46 -0700477 if (thread == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700478 ThreadSuspendByPeerWarning(self, WARNING, "No such thread for suspend", peer);
Brian Carlstrom37c16452014-08-27 23:43:46 -0700479 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700480 }
Brian Carlstrom37c16452014-08-27 23:43:46 -0700481 if (!Contains(thread)) {
482 VLOG(threads) << "SuspendThreadByPeer failed for unattached thread: "
483 << reinterpret_cast<void*>(thread);
484 return nullptr;
485 }
486 VLOG(threads) << "SuspendThreadByPeer found thread: " << *thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700487 {
488 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
489 if (request_suspension) {
490 thread->ModifySuspendCount(self, +1, debug_suspension);
491 request_suspension = false;
492 did_suspend_request = true;
493 } else {
494 // If the caller isn't requesting suspension, a suspension should have already occurred.
495 CHECK_GT(thread->GetSuspendCount(), 0);
496 }
497 // IsSuspended on the current thread will fail as the current thread is changed into
498 // Runnable above. As the suspend count is now raised if this is the current thread
499 // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
500 // to just explicitly handle the current thread in the callers to this code.
501 CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
502 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
503 // count, or else we've waited and it has self suspended) or is the current thread, we're
504 // done.
505 if (thread->IsSuspended()) {
Brian Carlstrom37c16452014-08-27 23:43:46 -0700506 VLOG(threads) << "SuspendThreadByPeer thread suspended: " << *thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700507 return thread;
508 }
509 if (total_delay_us >= kTimeoutUs) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700510 ThreadSuspendByPeerWarning(self, FATAL, "Thread suspension timed out", peer);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700511 if (did_suspend_request) {
512 thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
513 }
514 *timed_out = true;
Brian Carlstrom37c16452014-08-27 23:43:46 -0700515 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700516 }
517 }
518 // Release locks and come out of runnable state.
519 }
Brian Carlstrom37c16452014-08-27 23:43:46 -0700520 VLOG(threads) << "SuspendThreadByPeer sleeping to allow thread chance to suspend";
Ian Rogers6093a5c2014-07-17 18:52:42 -0700521 ThreadSuspendSleep(self, &delay_us, &total_delay_us);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700522 }
523}
524
525static void ThreadSuspendByThreadIdWarning(int level, const char* message, uint32_t thread_id) {
526 LOG(level) << StringPrintf("%s: %d", message, thread_id);
527}
528
529Thread* ThreadList::SuspendThreadByThreadId(uint32_t thread_id, bool debug_suspension,
530 bool* timed_out) {
531 static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
532 useconds_t total_delay_us = 0;
533 useconds_t delay_us = 0;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700534 *timed_out = false;
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800535 Thread* suspended_thread = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700536 Thread* self = Thread::Current();
537 CHECK_NE(thread_id, kInvalidThreadId);
Brian Carlstrom37c16452014-08-27 23:43:46 -0700538 VLOG(threads) << "SuspendThreadByThreadId starting";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700539 while (true) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700540 {
Ian Rogers6093a5c2014-07-17 18:52:42 -0700541 // Note: this will transition to runnable and potentially suspend. We ensure only one thread
542 // is requesting another suspend, to avoid deadlock, by requiring this function be called
543 // holding Locks::thread_list_suspend_thread_lock_. Its important this thread suspend rather
544 // than request thread suspension, to avoid potential cycles in threads requesting each other
545 // suspend.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700546 ScopedObjectAccess soa(self);
547 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers6093a5c2014-07-17 18:52:42 -0700548 Thread* thread = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700549 for (const auto& it : list_) {
550 if (it->GetThreadId() == thread_id) {
551 thread = it;
552 break;
553 }
554 }
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800555 if (thread == nullptr) {
556 CHECK(suspended_thread == nullptr) << "Suspended thread " << suspended_thread
557 << " no longer in thread list";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700558 // There's a race in inflating a lock and the owner giving up ownership and then dying.
559 ThreadSuspendByThreadIdWarning(WARNING, "No such thread id for suspend", thread_id);
Brian Carlstrom37c16452014-08-27 23:43:46 -0700560 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700561 }
Brian Carlstrom37c16452014-08-27 23:43:46 -0700562 VLOG(threads) << "SuspendThreadByThreadId found thread: " << *thread;
563 DCHECK(Contains(thread));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700564 {
565 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800566 if (suspended_thread == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700567 thread->ModifySuspendCount(self, +1, debug_suspension);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800568 suspended_thread = thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700569 } else {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800570 CHECK_EQ(suspended_thread, thread);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700571 // If the caller isn't requesting suspension, a suspension should have already occurred.
572 CHECK_GT(thread->GetSuspendCount(), 0);
573 }
574 // IsSuspended on the current thread will fail as the current thread is changed into
575 // Runnable above. As the suspend count is now raised if this is the current thread
576 // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
577 // to just explicitly handle the current thread in the callers to this code.
578 CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
579 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
580 // count, or else we've waited and it has self suspended) or is the current thread, we're
581 // done.
582 if (thread->IsSuspended()) {
Brian Carlstrom37c16452014-08-27 23:43:46 -0700583 VLOG(threads) << "SuspendThreadByThreadId thread suspended: " << *thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700584 return thread;
585 }
586 if (total_delay_us >= kTimeoutUs) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700587 ThreadSuspendByThreadIdWarning(WARNING, "Thread suspension timed out", thread_id);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800588 if (suspended_thread != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700589 thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
590 }
591 *timed_out = true;
Brian Carlstrom37c16452014-08-27 23:43:46 -0700592 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700593 }
594 }
595 // Release locks and come out of runnable state.
596 }
Brian Carlstrom37c16452014-08-27 23:43:46 -0700597 VLOG(threads) << "SuspendThreadByThreadId sleeping to allow thread chance to suspend";
Ian Rogers6093a5c2014-07-17 18:52:42 -0700598 ThreadSuspendSleep(self, &delay_us, &total_delay_us);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700599 }
600}
601
602Thread* ThreadList::FindThreadByThreadId(uint32_t thin_lock_id) {
603 Thread* self = Thread::Current();
604 MutexLock mu(self, *Locks::thread_list_lock_);
605 for (const auto& thread : list_) {
606 if (thread->GetThreadId() == thin_lock_id) {
607 CHECK(thread == self || thread->IsSuspended());
608 return thread;
609 }
610 }
611 return NULL;
612}
613
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700614void ThreadList::SuspendAllForDebugger() {
615 Thread* self = Thread::Current();
616 Thread* debug_thread = Dbg::GetDebugThread();
617
618 VLOG(threads) << *self << " SuspendAllForDebugger starting...";
619
620 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700621 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700622 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700623 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700624 // Update global suspend all state for attaching threads.
625 ++suspend_all_count_;
626 ++debug_suspend_all_count_;
627 // Increment everybody's suspend count (except our own).
Mathieu Chartier02e25112013-08-14 16:14:24 -0700628 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700629 if (thread == self || thread == debug_thread) {
630 continue;
631 }
632 VLOG(threads) << "requesting thread suspend: " << *thread;
Ian Rogers01ae5802012-09-28 16:14:01 -0700633 thread->ModifySuspendCount(self, +1, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700634 }
635 }
636 }
637
Ian Rogers66aee5c2012-08-15 17:17:47 -0700638 // Block on the mutator lock until all Runnable threads release their share of access then
639 // immediately unlock again.
640#if HAVE_TIMED_RWLOCK
641 // Timeout if we wait more than 30 seconds.
Ian Rogersc604d732012-10-14 16:09:54 -0700642 if (!Locks::mutator_lock_->ExclusiveLockWithTimeout(self, 30 * 1000, 0)) {
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100643 UnsafeLogFatalForThreadSuspendAllTimeout();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700644 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -0700645 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700646 }
Ian Rogers66aee5c2012-08-15 17:17:47 -0700647#else
Ian Rogers81d425b2012-09-27 16:03:43 -0700648 Locks::mutator_lock_->ExclusiveLock(self);
649 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700650#endif
Ian Rogers50b35e22012-10-04 10:09:15 -0700651 AssertThreadsAreSuspended(self, self, debug_thread);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700652
Sebastien Hertz59d9d662014-08-19 15:33:43 +0200653 VLOG(threads) << *self << " SuspendAllForDebugger complete";
Elliott Hughes01158d72011-09-19 19:47:10 -0700654}
655
Elliott Hughes475fc232011-10-25 15:00:35 -0700656void ThreadList::SuspendSelfForDebugger() {
657 Thread* self = Thread::Current();
Elliott Hughes01158d72011-09-19 19:47:10 -0700658
Elliott Hughes475fc232011-10-25 15:00:35 -0700659 // The debugger thread must not suspend itself due to debugger activity!
660 Thread* debug_thread = Dbg::GetDebugThread();
661 CHECK(debug_thread != NULL);
662 CHECK(self != debug_thread);
jeffhaoa77f0f62012-12-05 17:19:31 -0800663 CHECK_NE(self->GetState(), kRunnable);
664 Locks::mutator_lock_->AssertNotHeld(self);
Elliott Hughes475fc232011-10-25 15:00:35 -0700665
jeffhaoa77f0f62012-12-05 17:19:31 -0800666 {
667 // Collisions with other suspends aren't really interesting. We want
668 // to ensure that we're the only one fiddling with the suspend count
669 // though.
670 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
671 self->ModifySuspendCount(self, +1, true);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700672 CHECK_GT(self->GetSuspendCount(), 0);
jeffhaoa77f0f62012-12-05 17:19:31 -0800673 }
Elliott Hughes475fc232011-10-25 15:00:35 -0700674
Elliott Hughes1f729aa2012-03-02 13:55:41 -0800675 VLOG(threads) << *self << " self-suspending (debugger)";
Elliott Hughes475fc232011-10-25 15:00:35 -0700676
Sebastien Hertz21e729c2014-02-18 14:16:00 +0100677 // Tell JDWP we've completed invocation and are ready to suspend.
678 DebugInvokeReq* pReq = self->GetInvokeReq();
679 DCHECK(pReq != NULL);
680 if (pReq->invoke_needed) {
681 // Clear this before signaling.
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200682 pReq->Clear();
Sebastien Hertz21e729c2014-02-18 14:16:00 +0100683
684 VLOG(jdwp) << "invoke complete, signaling";
685 MutexLock mu(self, pReq->lock);
686 pReq->cond.Signal(self);
687 }
688
Elliott Hughes475fc232011-10-25 15:00:35 -0700689 // Tell JDWP that we've completed suspension. The JDWP thread can't
690 // tell us to resume before we're fully asleep because we hold the
691 // suspend count lock.
692 Dbg::ClearWaitForEventThread();
693
jeffhaoa77f0f62012-12-05 17:19:31 -0800694 {
695 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700696 while (self->GetSuspendCount() != 0) {
jeffhaoa77f0f62012-12-05 17:19:31 -0800697 Thread::resume_cond_->Wait(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700698 if (self->GetSuspendCount() != 0) {
jeffhaoa77f0f62012-12-05 17:19:31 -0800699 // The condition was signaled but we're still suspended. This
Sebastien Hertzdcfd6ca2014-09-18 10:20:42 +0200700 // can happen when we suspend then resume all threads to
701 // update instrumentation or compute monitor info. This can
702 // also happen if the debugger lets go while a SIGQUIT thread
jeffhaoa77f0f62012-12-05 17:19:31 -0800703 // dump event is pending (assuming SignalCatcher was resumed for
704 // just long enough to try to grab the thread-suspend lock).
Sebastien Hertzdcfd6ca2014-09-18 10:20:42 +0200705 VLOG(jdwp) << *self << " still suspended after undo "
706 << "(suspend count=" << self->GetSuspendCount() << ", "
707 << "debug suspend count=" << self->GetDebugSuspendCount() << ")";
jeffhaoa77f0f62012-12-05 17:19:31 -0800708 }
Elliott Hughes475fc232011-10-25 15:00:35 -0700709 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700710 CHECK_EQ(self->GetSuspendCount(), 0);
Elliott Hughes475fc232011-10-25 15:00:35 -0700711 }
jeffhaoa77f0f62012-12-05 17:19:31 -0800712
Elliott Hughes1f729aa2012-03-02 13:55:41 -0800713 VLOG(threads) << *self << " self-reviving (debugger)";
Elliott Hughes475fc232011-10-25 15:00:35 -0700714}
715
Elliott Hughes234ab152011-10-26 14:02:26 -0700716void ThreadList::UndoDebuggerSuspensions() {
717 Thread* self = Thread::Current();
718
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800719 VLOG(threads) << *self << " UndoDebuggerSuspensions starting";
Elliott Hughes234ab152011-10-26 14:02:26 -0700720
721 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700722 MutexLock mu(self, *Locks::thread_list_lock_);
723 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700724 // Update global suspend all state for attaching threads.
725 suspend_all_count_ -= debug_suspend_all_count_;
726 debug_suspend_all_count_ = 0;
727 // Update running threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700728 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700729 if (thread == self || thread->GetDebugSuspendCount() == 0) {
Elliott Hughes234ab152011-10-26 14:02:26 -0700730 continue;
731 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700732 thread->ModifySuspendCount(self, -thread->GetDebugSuspendCount(), true);
Elliott Hughes234ab152011-10-26 14:02:26 -0700733 }
734 }
735
736 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700737 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700738 Thread::resume_cond_->Broadcast(self);
Elliott Hughes234ab152011-10-26 14:02:26 -0700739 }
740
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800741 VLOG(threads) << "UndoDebuggerSuspensions(" << *self << ") complete";
Elliott Hughes234ab152011-10-26 14:02:26 -0700742}
743
Elliott Hughese52e49b2012-04-02 16:05:44 -0700744void ThreadList::WaitForOtherNonDaemonThreadsToExit() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700745 Thread* self = Thread::Current();
746 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700747 bool all_threads_are_daemons;
748 do {
Ian Rogers120f1c72012-09-28 17:17:10 -0700749 {
750 // No more threads can be born after we start to shutdown.
751 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700752 CHECK(Runtime::Current()->IsShuttingDownLocked());
Ian Rogers120f1c72012-09-28 17:17:10 -0700753 CHECK_EQ(Runtime::Current()->NumberOfThreadsBeingBorn(), 0U);
754 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700755 all_threads_are_daemons = true;
Ian Rogers120f1c72012-09-28 17:17:10 -0700756 MutexLock mu(self, *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700757 for (const auto& thread : list_) {
Anwar Ghuloum97543682013-06-14 12:58:16 -0700758 if (thread != self && !thread->IsDaemon()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700759 all_threads_are_daemons = false;
760 break;
761 }
762 }
763 if (!all_threads_are_daemons) {
764 // Wait for another thread to exit before re-checking.
Ian Rogersc604d732012-10-14 16:09:54 -0700765 thread_exit_cond_.Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700766 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700767 } while (!all_threads_are_daemons);
Elliott Hughes038a8062011-09-18 14:12:41 -0700768}
769
770void ThreadList::SuspendAllDaemonThreads() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700771 Thread* self = Thread::Current();
772 MutexLock mu(self, *Locks::thread_list_lock_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700773 { // Tell all the daemons it's time to suspend.
Ian Rogers81d425b2012-09-27 16:03:43 -0700774 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700775 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700776 // This is only run after all non-daemon threads have exited, so the remainder should all be
777 // daemons.
Ian Rogers7e762862012-10-22 15:45:08 -0700778 CHECK(thread->IsDaemon()) << *thread;
Ian Rogers81d425b2012-09-27 16:03:43 -0700779 if (thread != self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700780 thread->ModifySuspendCount(self, +1, false);
Elliott Hughese52e49b2012-04-02 16:05:44 -0700781 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700782 }
783 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700784 // Give the threads a chance to suspend, complaining if they're slow.
785 bool have_complained = false;
786 for (int i = 0; i < 10; ++i) {
787 usleep(200 * 1000);
788 bool all_suspended = true;
Mathieu Chartier02e25112013-08-14 16:14:24 -0700789 for (const auto& thread : list_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700790 if (thread != self && thread->GetState() == kRunnable) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700791 if (!have_complained) {
792 LOG(WARNING) << "daemon thread not yet suspended: " << *thread;
793 have_complained = true;
794 }
795 all_suspended = false;
796 }
797 }
798 if (all_suspended) {
799 return;
800 }
801 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700802 LOG(ERROR) << "suspend all daemons failed";
803}
804void ThreadList::Register(Thread* self) {
805 DCHECK_EQ(self, Thread::Current());
806
807 if (VLOG_IS_ON(threads)) {
808 std::ostringstream oss;
809 self->ShortDump(oss); // We don't hold the mutator_lock_ yet and so cannot call Dump.
Ian Rogers5a9ba012014-05-19 13:28:52 -0700810 LOG(INFO) << "ThreadList::Register() " << *self << "\n" << oss.str();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700811 }
812
813 // Atomically add self to the thread list and make its thread_suspend_count_ reflect ongoing
814 // SuspendAll requests.
Ian Rogers81d425b2012-09-27 16:03:43 -0700815 MutexLock mu(self, *Locks::thread_list_lock_);
816 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700817 CHECK_GE(suspend_all_count_, debug_suspend_all_count_);
Ian Rogers2966e132014-04-02 08:34:36 -0700818 // Modify suspend count in increments of 1 to maintain invariants in ModifySuspendCount. While
819 // this isn't particularly efficient the suspend counts are most commonly 0 or 1.
820 for (int delta = debug_suspend_all_count_; delta > 0; delta--) {
821 self->ModifySuspendCount(self, +1, true);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700822 }
Ian Rogers2966e132014-04-02 08:34:36 -0700823 for (int delta = suspend_all_count_ - debug_suspend_all_count_; delta > 0; delta--) {
824 self->ModifySuspendCount(self, +1, false);
Ian Rogers01ae5802012-09-28 16:14:01 -0700825 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700826 CHECK(!Contains(self));
827 list_.push_back(self);
828}
829
830void ThreadList::Unregister(Thread* self) {
831 DCHECK_EQ(self, Thread::Current());
832
833 VLOG(threads) << "ThreadList::Unregister() " << *self;
834
835 // Any time-consuming destruction, plus anything that can call back into managed code or
836 // suspend and so on, must happen at this point, and not in ~Thread.
837 self->Destroy();
838
Ian Rogersdd7624d2014-03-14 17:43:00 -0700839 uint32_t thin_lock_id = self->GetThreadId();
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800840 while (self != nullptr) {
Ian Rogerscfaa4552012-11-26 21:00:08 -0800841 // Remove and delete the Thread* while holding the thread_list_lock_ and
842 // thread_suspend_count_lock_ so that the unregistering thread cannot be suspended.
Ian Rogers0878d652013-04-18 17:38:35 -0700843 // Note: deliberately not using MutexLock that could hold a stale self pointer.
844 Locks::thread_list_lock_->ExclusiveLock(self);
Ian Rogerse2bcf572014-09-15 15:17:07 -0700845 if (!Contains(self)) {
846 std::ostringstream os;
847 DumpNativeStack(os, GetTid(), " native: ", nullptr);
848 LOG(ERROR) << "Request to unregister unattached thread\n" << os.str();
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800849 self = nullptr;
Ian Rogerse2bcf572014-09-15 15:17:07 -0700850 } else {
851 // Note: we don't take the thread_suspend_count_lock_ here as to be suspending a thread other
852 // than yourself you need to hold the thread_list_lock_ (see Thread::ModifySuspendCount).
853 if (!self->IsSuspended()) {
854 list_.remove(self);
855 delete self;
856 self = nullptr;
857 }
Ian Rogerscfaa4552012-11-26 21:00:08 -0800858 }
Ian Rogers0878d652013-04-18 17:38:35 -0700859 Locks::thread_list_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700860 }
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800861 // Release the thread ID after the thread is finished and deleted to avoid cases where we can
862 // temporarily have multiple threads with the same thread id. When this occurs, it causes
863 // problems in FindThreadByThreadId / SuspendThreadByThreadId.
864 ReleaseThreadId(nullptr, thin_lock_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700865
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700866 // Clear the TLS data, so that the underlying native thread is recognizably detached.
867 // (It may wish to reattach later.)
868 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, NULL), "detach self");
869
870 // Signal that a thread just detached.
Ian Rogers81d425b2012-09-27 16:03:43 -0700871 MutexLock mu(NULL, *Locks::thread_list_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700872 thread_exit_cond_.Signal(NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700873}
874
875void ThreadList::ForEach(void (*callback)(Thread*, void*), void* context) {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700876 for (const auto& thread : list_) {
877 callback(thread, context);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700878 }
879}
880
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800881void ThreadList::VisitRoots(RootCallback* callback, void* arg) const {
Ian Rogers81d425b2012-09-27 16:03:43 -0700882 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700883 for (const auto& thread : list_) {
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800884 thread->VisitRoots(callback, arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700885 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700886}
887
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800888class VerifyRootWrapperArg {
889 public:
890 VerifyRootWrapperArg(VerifyRootCallback* callback, void* arg) : callback_(callback), arg_(arg) {
891 }
892 VerifyRootCallback* const callback_;
893 void* const arg_;
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700894};
895
Mathieu Chartier815873e2014-02-13 18:02:13 -0800896static void VerifyRootWrapperCallback(mirror::Object** root, void* arg, uint32_t /*thread_id*/,
Mathieu Chartier7bf9f192014-04-04 11:09:41 -0700897 RootType root_type) {
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700898 VerifyRootWrapperArg* wrapperArg = reinterpret_cast<VerifyRootWrapperArg*>(arg);
Mathieu Chartier7bf9f192014-04-04 11:09:41 -0700899 wrapperArg->callback_(*root, wrapperArg->arg_, 0, NULL, root_type);
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700900}
901
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800902void ThreadList::VerifyRoots(VerifyRootCallback* callback, void* arg) const {
903 VerifyRootWrapperArg wrapper(callback, arg);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700904 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700905 for (const auto& thread : list_) {
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700906 thread->VisitRoots(VerifyRootWrapperCallback, &wrapper);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700907 }
908}
909
Ian Rogerscfaa4552012-11-26 21:00:08 -0800910uint32_t ThreadList::AllocThreadId(Thread* self) {
Chao-ying Fu9e369312014-05-21 11:20:52 -0700911 MutexLock mu(self, *Locks::allocated_thread_ids_lock_);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700912 for (size_t i = 0; i < allocated_ids_.size(); ++i) {
913 if (!allocated_ids_[i]) {
914 allocated_ids_.set(i);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700915 return i + 1; // Zero is reserved to mean "invalid".
Elliott Hughes8daa0922011-09-11 13:46:25 -0700916 }
917 }
918 LOG(FATAL) << "Out of internal thread ids";
919 return 0;
920}
921
Ian Rogerscfaa4552012-11-26 21:00:08 -0800922void ThreadList::ReleaseThreadId(Thread* self, uint32_t id) {
Chao-ying Fu9e369312014-05-21 11:20:52 -0700923 MutexLock mu(self, *Locks::allocated_thread_ids_lock_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700924 --id; // Zero is reserved to mean "invalid".
Elliott Hughes8daa0922011-09-11 13:46:25 -0700925 DCHECK(allocated_ids_[id]) << id;
926 allocated_ids_.reset(id);
927}
928
Elliott Hughes8daa0922011-09-11 13:46:25 -0700929} // namespace art