blob: 3cc2a2892d0a657d9ff08a8623edcf8767e5b3a3 [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 Rogers7b078e82014-09-10 14:44:24 -070091 Dump(os);
Elliott Hughesabbe07d2012-06-05 17:42:23 -070092 DumpUnattachedThreads(os);
93}
94
Ian Rogerscfaa4552012-11-26 21:00:08 -080095static void DumpUnattachedThread(std::ostream& os, pid_t tid) NO_THREAD_SAFETY_ANALYSIS {
96 // TODO: No thread safety analysis as DumpState with a NULL thread won't access fields, should
97 // refactor DumpState to avoid skipping analysis.
Elliott Hughesabbe07d2012-06-05 17:42:23 -070098 Thread::DumpState(os, NULL, tid);
99 DumpKernelStack(os, tid, " kernel: ", false);
Brian Carlstromed8b7232012-06-27 17:54:47 -0700100 // TODO: Reenable this when the native code in system_server can handle it.
101 // Currently "adb shell kill -3 `pid system_server`" will cause it to exit.
102 if (false) {
Christopher Ferrisa2cee182014-04-16 19:13:59 -0700103 DumpNativeStack(os, tid, " native: ");
Brian Carlstromed8b7232012-06-27 17:54:47 -0700104 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700105 os << "\n";
106}
107
108void ThreadList::DumpUnattachedThreads(std::ostream& os) {
109 DIR* d = opendir("/proc/self/task");
110 if (!d) {
111 return;
112 }
113
Ian Rogers50b35e22012-10-04 10:09:15 -0700114 Thread* self = Thread::Current();
Elliott Hughes4696b5b2012-10-30 10:35:10 -0700115 dirent* e;
116 while ((e = readdir(d)) != NULL) {
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700117 char* end;
Elliott Hughes4696b5b2012-10-30 10:35:10 -0700118 pid_t tid = strtol(e->d_name, &end, 10);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700119 if (!*end) {
120 bool contains;
121 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700122 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700123 contains = Contains(tid);
124 }
125 if (!contains) {
126 DumpUnattachedThread(os, tid);
127 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700128 }
129 }
130 closedir(d);
Elliott Hughesff738062012-02-03 15:00:42 -0800131}
132
Ian Rogers7b078e82014-09-10 14:44:24 -0700133// A closure used by Thread::Dump.
134class DumpCheckpoint FINAL : public Closure {
135 public:
136 explicit DumpCheckpoint(std::ostream* os) : os_(os), barrier_(0) {}
137
138 void Run(Thread* thread) OVERRIDE {
139 // Note thread and self may not be equal if thread was already suspended at the point of the
140 // request.
141 Thread* self = Thread::Current();
142 std::ostringstream local_os;
143 {
144 ScopedObjectAccess soa(self);
145 thread->Dump(local_os);
146 }
147 local_os << "\n";
148 {
149 // Use the logging lock to ensure serialization when writing to the common ostream.
150 MutexLock mu(self, *Locks::logging_lock_);
151 *os_ << local_os.str();
152 }
153 barrier_.Pass(self);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700154 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700155
156 void WaitForThreadsToRunThroughCheckpoint(size_t threads_running_checkpoint) {
157 Thread* self = Thread::Current();
158 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
159 barrier_.Increment(self, threads_running_checkpoint);
160 }
161
162 private:
163 // The common stream that will accumulate all the dumps.
164 std::ostream* const os_;
165 // The barrier to be passed through and for the requestor to wait upon.
166 Barrier barrier_;
167};
168
169void ThreadList::Dump(std::ostream& os) {
170 {
171 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
172 os << "DALVIK THREADS (" << list_.size() << "):\n";
173 }
174 DumpCheckpoint checkpoint(&os);
175 size_t threads_running_checkpoint = RunCheckpoint(&checkpoint);
176 checkpoint.WaitForThreadsToRunThroughCheckpoint(threads_running_checkpoint);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700177}
178
Ian Rogers50b35e22012-10-04 10:09:15 -0700179void ThreadList::AssertThreadsAreSuspended(Thread* self, Thread* ignore1, Thread* ignore2) {
180 MutexLock mu(self, *Locks::thread_list_lock_);
181 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700182 for (const auto& thread : list_) {
jeffhao725a9572012-11-13 18:20:12 -0800183 if (thread != ignore1 && thread != ignore2) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700184 CHECK(thread->IsSuspended())
185 << "\nUnsuspended thread: <<" << *thread << "\n"
186 << "self: <<" << *Thread::Current();
187 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700188 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700189}
190
Ian Rogers66aee5c2012-08-15 17:17:47 -0700191#if HAVE_TIMED_RWLOCK
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700192// Attempt to rectify locks so that we dump thread list with required locks before exiting.
Ian Rogers7b078e82014-09-10 14:44:24 -0700193static void UnsafeLogFatalForThreadSuspendAllTimeout() __attribute__((noreturn));
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100194static void UnsafeLogFatalForThreadSuspendAllTimeout() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700195 Runtime* runtime = Runtime::Current();
196 std::ostringstream ss;
197 ss << "Thread suspend timeout\n";
Ian Rogers7b078e82014-09-10 14:44:24 -0700198 runtime->GetThreadList()->Dump(ss);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700199 LOG(FATAL) << ss.str();
Ian Rogers719d1a32014-03-06 12:13:39 -0800200 exit(0);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700201}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700202#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700203
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800204// Unlike suspending all threads where we can wait to acquire the mutator_lock_, suspending an
205// individual thread requires polling. delay_us is the requested sleep and total_delay_us
206// accumulates the total time spent sleeping for timeouts. The first sleep is just a yield,
207// subsequently sleeps increase delay_us from 1ms to 500ms by doubling.
Ian Rogersf3d874c2014-07-17 18:52:42 -0700208static void ThreadSuspendSleep(Thread* self, useconds_t* delay_us, useconds_t* total_delay_us) {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800209 useconds_t new_delay_us = (*delay_us) * 2;
210 CHECK_GE(new_delay_us, *delay_us);
211 if (new_delay_us < 500000) { // Don't allow sleeping to be more than 0.5s.
212 *delay_us = new_delay_us;
213 }
214 if (*delay_us == 0) {
215 sched_yield();
216 // Default to 1 milliseconds (note that this gets multiplied by 2 before the first sleep).
217 *delay_us = 500;
218 } else {
219 usleep(*delay_us);
220 *total_delay_us += *delay_us;
221 }
222}
223
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700224size_t ThreadList::RunCheckpoint(Closure* checkpoint_function) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700225 Thread* self = Thread::Current();
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800226 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
227 Locks::thread_list_lock_->AssertNotHeld(self);
228 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
229 if (kDebugLocking) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700230 CHECK_NE(self->GetState(), kRunnable);
231 }
232
233 std::vector<Thread*> suspended_count_modified_threads;
234 size_t count = 0;
235 {
236 // Call a checkpoint function for each thread, threads which are suspend get their checkpoint
237 // manually called.
238 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700239 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700240 for (const auto& thread : list_) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700241 if (thread != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700242 while (true) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700243 if (thread->RequestCheckpoint(checkpoint_function)) {
Dave Allison0aded082013-11-07 13:15:11 -0800244 // This thread will run its checkpoint some time in the near future.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700245 count++;
246 break;
247 } else {
248 // We are probably suspended, try to make sure that we stay suspended.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700249 // The thread switched back to runnable.
250 if (thread->GetState() == kRunnable) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700251 // Spurious fail, try again.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700252 continue;
253 }
254 thread->ModifySuspendCount(self, +1, false);
255 suspended_count_modified_threads.push_back(thread);
256 break;
257 }
258 }
259 }
260 }
261 }
262
263 // Run the checkpoint on ourself while we wait for threads to suspend.
264 checkpoint_function->Run(self);
265
266 // Run the checkpoint on the suspended threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700267 for (const auto& thread : suspended_count_modified_threads) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700268 if (!thread->IsSuspended()) {
269 // Wait until the thread is suspended.
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800270 useconds_t total_delay_us = 0;
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700271 do {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800272 useconds_t delay_us = 100;
Ian Rogersf3d874c2014-07-17 18:52:42 -0700273 ThreadSuspendSleep(self, &delay_us, &total_delay_us);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700274 } while (!thread->IsSuspended());
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800275 // Shouldn't need to wait for longer than 1000 microseconds.
276 constexpr useconds_t kLongWaitThresholdUS = 1000;
277 if (UNLIKELY(total_delay_us > kLongWaitThresholdUS)) {
278 LOG(WARNING) << "Waited " << total_delay_us << " us for thread suspend!";
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700279 }
280 }
281 // We know for sure that the thread is suspended at this point.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700282 checkpoint_function->Run(thread);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700283 {
284 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
285 thread->ModifySuspendCount(self, -1, false);
286 }
287 }
288
Mathieu Chartier664bebf2012-11-12 16:54:11 -0800289 {
290 // Imitate ResumeAll, threads may be waiting on Thread::resume_cond_ since we raised their
291 // suspend count. Now the suspend_count_ is lowered so we must do the broadcast.
292 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
293 Thread::resume_cond_->Broadcast(self);
294 }
295
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700296 // Add one for self.
297 return count + suspended_count_modified_threads.size() + 1;
298}
299
Dave Allison39c3bfb2014-01-28 18:33:52 -0800300// Request that a checkpoint function be run on all active (non-suspended)
301// threads. Returns the number of successful requests.
302size_t ThreadList::RunCheckpointOnRunnableThreads(Closure* checkpoint_function) {
303 Thread* self = Thread::Current();
Ian Rogers7b078e82014-09-10 14:44:24 -0700304 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
305 Locks::thread_list_lock_->AssertNotHeld(self);
306 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
307 CHECK_NE(self->GetState(), kRunnable);
Dave Allison39c3bfb2014-01-28 18:33:52 -0800308
309 size_t count = 0;
310 {
311 // Call a checkpoint function for each non-suspended thread.
312 MutexLock mu(self, *Locks::thread_list_lock_);
313 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
314 for (const auto& thread : list_) {
315 if (thread != self) {
316 if (thread->RequestCheckpoint(checkpoint_function)) {
317 // This thread will run its checkpoint some time in the near future.
318 count++;
319 }
320 }
321 }
322 }
323
324 // Return the number of threads that will run the checkpoint function.
325 return count;
326}
327
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700328void ThreadList::SuspendAll() {
329 Thread* self = Thread::Current();
330
Jeff Haoc5d824a2014-07-28 18:35:38 -0700331 if (self != nullptr) {
332 VLOG(threads) << *self << " SuspendAll starting...";
333 } else {
334 VLOG(threads) << "Thread[null] SuspendAll starting...";
335 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700336 ATRACE_BEGIN("Suspending mutator threads");
Mathieu Chartier251755c2014-07-15 18:10:25 -0700337 uint64_t start_time = NanoTime();
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700338
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800339 Locks::mutator_lock_->AssertNotHeld(self);
340 Locks::thread_list_lock_->AssertNotHeld(self);
341 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
Jeff Haoc5d824a2014-07-28 18:35:38 -0700342 if (kDebugLocking && self != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700343 CHECK_NE(self->GetState(), kRunnable);
344 }
345 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700346 MutexLock mu(self, *Locks::thread_list_lock_);
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800347 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
348 // Update global suspend all state for attaching threads.
349 ++suspend_all_count_;
350 // Increment everybody's suspend count (except our own).
351 for (const auto& thread : list_) {
352 if (thread == self) {
353 continue;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700354 }
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800355 VLOG(threads) << "requesting thread suspend: " << *thread;
356 thread->ModifySuspendCount(self, +1, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700357 }
358 }
359
Ian Rogers66aee5c2012-08-15 17:17:47 -0700360 // Block on the mutator lock until all Runnable threads release their share of access.
361#if HAVE_TIMED_RWLOCK
362 // Timeout if we wait more than 30 seconds.
Ian Rogers719d1a32014-03-06 12:13:39 -0800363 if (!Locks::mutator_lock_->ExclusiveLockWithTimeout(self, 30 * 1000, 0)) {
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100364 UnsafeLogFatalForThreadSuspendAllTimeout();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700365 }
Ian Rogers66aee5c2012-08-15 17:17:47 -0700366#else
Ian Rogers81d425b2012-09-27 16:03:43 -0700367 Locks::mutator_lock_->ExclusiveLock(self);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700368#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700369
Mathieu Chartier251755c2014-07-15 18:10:25 -0700370 uint64_t end_time = NanoTime();
371 if (end_time - start_time > kLongThreadSuspendThreshold) {
372 LOG(WARNING) << "Suspending all threads took: " << PrettyDuration(end_time - start_time);
373 }
374
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800375 if (kDebugLocking) {
376 // Debug check that all threads are suspended.
377 AssertThreadsAreSuspended(self, self);
378 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700379
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700380 ATRACE_END();
381 ATRACE_BEGIN("Mutator threads suspended");
382
Jeff Haoc5d824a2014-07-28 18:35:38 -0700383 if (self != nullptr) {
384 VLOG(threads) << *self << " SuspendAll complete";
385 } else {
386 VLOG(threads) << "Thread[null] SuspendAll complete";
387 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700388}
389
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700390void ThreadList::ResumeAll() {
391 Thread* self = Thread::Current();
392
Jeff Haoc5d824a2014-07-28 18:35:38 -0700393 if (self != nullptr) {
394 VLOG(threads) << *self << " ResumeAll starting";
395 } else {
396 VLOG(threads) << "Thread[null] ResumeAll starting";
397 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700398
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700399 ATRACE_END();
400 ATRACE_BEGIN("Resuming mutator threads");
401
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800402 if (kDebugLocking) {
403 // Debug check that all threads are suspended.
404 AssertThreadsAreSuspended(self, self);
405 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700406
Ian Rogers81d425b2012-09-27 16:03:43 -0700407 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700408 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700409 MutexLock mu(self, *Locks::thread_list_lock_);
410 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700411 // Update global suspend all state for attaching threads.
412 --suspend_all_count_;
413 // Decrement the suspend counts for all threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700414 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700415 if (thread == self) {
416 continue;
417 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700418 thread->ModifySuspendCount(self, -1, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700419 }
420
421 // Broadcast a notification to all suspended threads, some or all of
422 // which may choose to wake up. No need to wait for them.
Jeff Haoc5d824a2014-07-28 18:35:38 -0700423 if (self != nullptr) {
424 VLOG(threads) << *self << " ResumeAll waking others";
425 } else {
426 VLOG(threads) << "Thread[null] ResumeAll waking others";
427 }
Ian Rogersc604d732012-10-14 16:09:54 -0700428 Thread::resume_cond_->Broadcast(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700429 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700430 ATRACE_END();
Jeff Haoc5d824a2014-07-28 18:35:38 -0700431
432 if (self != nullptr) {
433 VLOG(threads) << *self << " ResumeAll complete";
434 } else {
435 VLOG(threads) << "Thread[null] ResumeAll complete";
436 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700437}
438
439void ThreadList::Resume(Thread* thread, bool for_debugger) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700440 Thread* self = Thread::Current();
441 DCHECK_NE(thread, self);
Brian Carlstromba32de42014-08-27 23:43:46 -0700442 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") starting..."
443 << (for_debugger ? " (debugger)" : "");
Elliott Hughes01158d72011-09-19 19:47:10 -0700444
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700445 {
446 // To check Contains.
Ian Rogers81d425b2012-09-27 16:03:43 -0700447 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700448 // To check IsSuspended.
Ian Rogers81d425b2012-09-27 16:03:43 -0700449 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
450 DCHECK(thread->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700451 if (!Contains(thread)) {
Brian Carlstromba32de42014-08-27 23:43:46 -0700452 // We only expect threads within the thread-list to have been suspended otherwise we can't
453 // stop such threads from delete-ing themselves.
454 LOG(ERROR) << "Resume(" << reinterpret_cast<void*>(thread)
455 << ") thread not within thread list";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700456 return;
457 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700458 thread->ModifySuspendCount(self, -1, for_debugger);
Elliott Hughes01158d72011-09-19 19:47:10 -0700459 }
460
461 {
Brian Carlstromba32de42014-08-27 23:43:46 -0700462 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") waking others";
Ian Rogers81d425b2012-09-27 16:03:43 -0700463 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700464 Thread::resume_cond_->Broadcast(self);
Elliott Hughes01158d72011-09-19 19:47:10 -0700465 }
466
Brian Carlstromba32de42014-08-27 23:43:46 -0700467 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") complete";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700468}
Elliott Hughes01158d72011-09-19 19:47:10 -0700469
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700470static void ThreadSuspendByPeerWarning(Thread* self, int level, const char* message, jobject peer) {
471 JNIEnvExt* env = self->GetJniEnv();
472 ScopedLocalRef<jstring>
473 scoped_name_string(env, (jstring)env->GetObjectField(peer,
474 WellKnownClasses::java_lang_Thread_name));
475 ScopedUtfChars scoped_name_chars(env, scoped_name_string.get());
476 if (scoped_name_chars.c_str() == NULL) {
477 LOG(level) << message << ": " << peer;
478 env->ExceptionClear();
479 } else {
480 LOG(level) << message << ": " << peer << ":" << scoped_name_chars.c_str();
481 }
482}
483
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700484Thread* ThreadList::SuspendThreadByPeer(jobject peer, bool request_suspension,
485 bool debug_suspension, bool* timed_out) {
486 static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
487 useconds_t total_delay_us = 0;
488 useconds_t delay_us = 0;
489 bool did_suspend_request = false;
490 *timed_out = false;
491 Thread* self = Thread::Current();
Brian Carlstromba32de42014-08-27 23:43:46 -0700492 VLOG(threads) << "SuspendThreadByPeer starting";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700493 while (true) {
494 Thread* thread;
495 {
Ian Rogersf3d874c2014-07-17 18:52:42 -0700496 // Note: this will transition to runnable and potentially suspend. We ensure only one thread
497 // is requesting another suspend, to avoid deadlock, by requiring this function be called
498 // holding Locks::thread_list_suspend_thread_lock_. Its important this thread suspend rather
499 // than request thread suspension, to avoid potential cycles in threads requesting each other
500 // suspend.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700501 ScopedObjectAccess soa(self);
502 MutexLock mu(self, *Locks::thread_list_lock_);
503 thread = Thread::FromManagedThread(soa, peer);
Brian Carlstromba32de42014-08-27 23:43:46 -0700504 if (thread == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700505 ThreadSuspendByPeerWarning(self, WARNING, "No such thread for suspend", peer);
Brian Carlstromba32de42014-08-27 23:43:46 -0700506 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700507 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700508 if (!Contains(thread)) {
509 VLOG(threads) << "SuspendThreadByPeer failed for unattached thread: "
510 << reinterpret_cast<void*>(thread);
511 return nullptr;
512 }
513 VLOG(threads) << "SuspendThreadByPeer found thread: " << *thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700514 {
515 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
516 if (request_suspension) {
517 thread->ModifySuspendCount(self, +1, debug_suspension);
518 request_suspension = false;
519 did_suspend_request = true;
520 } else {
521 // If the caller isn't requesting suspension, a suspension should have already occurred.
522 CHECK_GT(thread->GetSuspendCount(), 0);
523 }
524 // IsSuspended on the current thread will fail as the current thread is changed into
525 // Runnable above. As the suspend count is now raised if this is the current thread
526 // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
527 // to just explicitly handle the current thread in the callers to this code.
528 CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
529 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
530 // count, or else we've waited and it has self suspended) or is the current thread, we're
531 // done.
532 if (thread->IsSuspended()) {
Brian Carlstromba32de42014-08-27 23:43:46 -0700533 VLOG(threads) << "SuspendThreadByPeer thread suspended: " << *thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700534 return thread;
535 }
536 if (total_delay_us >= kTimeoutUs) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700537 ThreadSuspendByPeerWarning(self, FATAL, "Thread suspension timed out", peer);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700538 if (did_suspend_request) {
539 thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
540 }
541 *timed_out = true;
Brian Carlstromba32de42014-08-27 23:43:46 -0700542 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700543 }
544 }
545 // Release locks and come out of runnable state.
546 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700547 VLOG(threads) << "SuspendThreadByPeer sleeping to allow thread chance to suspend";
Ian Rogersf3d874c2014-07-17 18:52:42 -0700548 ThreadSuspendSleep(self, &delay_us, &total_delay_us);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700549 }
550}
551
552static void ThreadSuspendByThreadIdWarning(int level, const char* message, uint32_t thread_id) {
553 LOG(level) << StringPrintf("%s: %d", message, thread_id);
554}
555
556Thread* ThreadList::SuspendThreadByThreadId(uint32_t thread_id, bool debug_suspension,
557 bool* timed_out) {
558 static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
559 useconds_t total_delay_us = 0;
560 useconds_t delay_us = 0;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700561 *timed_out = false;
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800562 Thread* suspended_thread = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700563 Thread* self = Thread::Current();
564 CHECK_NE(thread_id, kInvalidThreadId);
Brian Carlstromba32de42014-08-27 23:43:46 -0700565 VLOG(threads) << "SuspendThreadByThreadId starting";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700566 while (true) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700567 {
Ian Rogersf3d874c2014-07-17 18:52:42 -0700568 // Note: this will transition to runnable and potentially suspend. We ensure only one thread
569 // is requesting another suspend, to avoid deadlock, by requiring this function be called
570 // holding Locks::thread_list_suspend_thread_lock_. Its important this thread suspend rather
571 // than request thread suspension, to avoid potential cycles in threads requesting each other
572 // suspend.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700573 ScopedObjectAccess soa(self);
574 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogersf3d874c2014-07-17 18:52:42 -0700575 Thread* thread = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700576 for (const auto& it : list_) {
577 if (it->GetThreadId() == thread_id) {
578 thread = it;
579 break;
580 }
581 }
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800582 if (thread == nullptr) {
583 CHECK(suspended_thread == nullptr) << "Suspended thread " << suspended_thread
584 << " no longer in thread list";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700585 // There's a race in inflating a lock and the owner giving up ownership and then dying.
586 ThreadSuspendByThreadIdWarning(WARNING, "No such thread id for suspend", thread_id);
Brian Carlstromba32de42014-08-27 23:43:46 -0700587 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700588 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700589 VLOG(threads) << "SuspendThreadByThreadId found thread: " << *thread;
590 DCHECK(Contains(thread));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700591 {
592 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800593 if (suspended_thread == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700594 thread->ModifySuspendCount(self, +1, debug_suspension);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800595 suspended_thread = thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700596 } else {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800597 CHECK_EQ(suspended_thread, thread);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700598 // If the caller isn't requesting suspension, a suspension should have already occurred.
599 CHECK_GT(thread->GetSuspendCount(), 0);
600 }
601 // IsSuspended on the current thread will fail as the current thread is changed into
602 // Runnable above. As the suspend count is now raised if this is the current thread
603 // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
604 // to just explicitly handle the current thread in the callers to this code.
605 CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
606 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
607 // count, or else we've waited and it has self suspended) or is the current thread, we're
608 // done.
609 if (thread->IsSuspended()) {
Brian Carlstromba32de42014-08-27 23:43:46 -0700610 VLOG(threads) << "SuspendThreadByThreadId thread suspended: " << *thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700611 return thread;
612 }
613 if (total_delay_us >= kTimeoutUs) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700614 ThreadSuspendByThreadIdWarning(WARNING, "Thread suspension timed out", thread_id);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800615 if (suspended_thread != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700616 thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
617 }
618 *timed_out = true;
Brian Carlstromba32de42014-08-27 23:43:46 -0700619 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700620 }
621 }
622 // Release locks and come out of runnable state.
623 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700624 VLOG(threads) << "SuspendThreadByThreadId sleeping to allow thread chance to suspend";
Ian Rogersf3d874c2014-07-17 18:52:42 -0700625 ThreadSuspendSleep(self, &delay_us, &total_delay_us);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700626 }
627}
628
629Thread* ThreadList::FindThreadByThreadId(uint32_t thin_lock_id) {
630 Thread* self = Thread::Current();
631 MutexLock mu(self, *Locks::thread_list_lock_);
632 for (const auto& thread : list_) {
633 if (thread->GetThreadId() == thin_lock_id) {
634 CHECK(thread == self || thread->IsSuspended());
635 return thread;
636 }
637 }
638 return NULL;
639}
640
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700641void ThreadList::SuspendAllForDebugger() {
642 Thread* self = Thread::Current();
643 Thread* debug_thread = Dbg::GetDebugThread();
644
645 VLOG(threads) << *self << " SuspendAllForDebugger starting...";
646
647 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700648 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700649 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700650 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700651 // Update global suspend all state for attaching threads.
652 ++suspend_all_count_;
653 ++debug_suspend_all_count_;
654 // Increment everybody's suspend count (except our own).
Mathieu Chartier02e25112013-08-14 16:14:24 -0700655 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700656 if (thread == self || thread == debug_thread) {
657 continue;
658 }
659 VLOG(threads) << "requesting thread suspend: " << *thread;
Ian Rogers01ae5802012-09-28 16:14:01 -0700660 thread->ModifySuspendCount(self, +1, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700661 }
662 }
663 }
664
Ian Rogers66aee5c2012-08-15 17:17:47 -0700665 // Block on the mutator lock until all Runnable threads release their share of access then
666 // immediately unlock again.
667#if HAVE_TIMED_RWLOCK
668 // Timeout if we wait more than 30 seconds.
Ian Rogersc604d732012-10-14 16:09:54 -0700669 if (!Locks::mutator_lock_->ExclusiveLockWithTimeout(self, 30 * 1000, 0)) {
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100670 UnsafeLogFatalForThreadSuspendAllTimeout();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700671 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -0700672 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700673 }
Ian Rogers66aee5c2012-08-15 17:17:47 -0700674#else
Ian Rogers81d425b2012-09-27 16:03:43 -0700675 Locks::mutator_lock_->ExclusiveLock(self);
676 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700677#endif
Ian Rogers50b35e22012-10-04 10:09:15 -0700678 AssertThreadsAreSuspended(self, self, debug_thread);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700679
Sebastien Hertzed2be172014-08-19 15:33:43 +0200680 VLOG(threads) << *self << " SuspendAllForDebugger complete";
Elliott Hughes01158d72011-09-19 19:47:10 -0700681}
682
Elliott Hughes475fc232011-10-25 15:00:35 -0700683void ThreadList::SuspendSelfForDebugger() {
684 Thread* self = Thread::Current();
Elliott Hughes01158d72011-09-19 19:47:10 -0700685
Elliott Hughes475fc232011-10-25 15:00:35 -0700686 // The debugger thread must not suspend itself due to debugger activity!
687 Thread* debug_thread = Dbg::GetDebugThread();
688 CHECK(debug_thread != NULL);
689 CHECK(self != debug_thread);
jeffhaoa77f0f62012-12-05 17:19:31 -0800690 CHECK_NE(self->GetState(), kRunnable);
691 Locks::mutator_lock_->AssertNotHeld(self);
Elliott Hughes475fc232011-10-25 15:00:35 -0700692
jeffhaoa77f0f62012-12-05 17:19:31 -0800693 {
694 // Collisions with other suspends aren't really interesting. We want
695 // to ensure that we're the only one fiddling with the suspend count
696 // though.
697 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
698 self->ModifySuspendCount(self, +1, true);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700699 CHECK_GT(self->GetSuspendCount(), 0);
jeffhaoa77f0f62012-12-05 17:19:31 -0800700 }
Elliott Hughes475fc232011-10-25 15:00:35 -0700701
Elliott Hughes1f729aa2012-03-02 13:55:41 -0800702 VLOG(threads) << *self << " self-suspending (debugger)";
Elliott Hughes475fc232011-10-25 15:00:35 -0700703
Sebastien Hertz21e729c2014-02-18 14:16:00 +0100704 // Tell JDWP we've completed invocation and are ready to suspend.
705 DebugInvokeReq* pReq = self->GetInvokeReq();
706 DCHECK(pReq != NULL);
707 if (pReq->invoke_needed) {
708 // Clear this before signaling.
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200709 pReq->Clear();
Sebastien Hertz21e729c2014-02-18 14:16:00 +0100710
711 VLOG(jdwp) << "invoke complete, signaling";
712 MutexLock mu(self, pReq->lock);
713 pReq->cond.Signal(self);
714 }
715
Elliott Hughes475fc232011-10-25 15:00:35 -0700716 // Tell JDWP that we've completed suspension. The JDWP thread can't
717 // tell us to resume before we're fully asleep because we hold the
718 // suspend count lock.
719 Dbg::ClearWaitForEventThread();
720
jeffhaoa77f0f62012-12-05 17:19:31 -0800721 {
722 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700723 while (self->GetSuspendCount() != 0) {
jeffhaoa77f0f62012-12-05 17:19:31 -0800724 Thread::resume_cond_->Wait(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700725 if (self->GetSuspendCount() != 0) {
jeffhaoa77f0f62012-12-05 17:19:31 -0800726 // The condition was signaled but we're still suspended. This
727 // can happen if the debugger lets go while a SIGQUIT thread
728 // dump event is pending (assuming SignalCatcher was resumed for
729 // just long enough to try to grab the thread-suspend lock).
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700730 LOG(WARNING) << *self << " still suspended after undo "
Ian Rogersdd7624d2014-03-14 17:43:00 -0700731 << "(suspend count=" << self->GetSuspendCount() << ")";
jeffhaoa77f0f62012-12-05 17:19:31 -0800732 }
Elliott Hughes475fc232011-10-25 15:00:35 -0700733 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700734 CHECK_EQ(self->GetSuspendCount(), 0);
Elliott Hughes475fc232011-10-25 15:00:35 -0700735 }
jeffhaoa77f0f62012-12-05 17:19:31 -0800736
Elliott Hughes1f729aa2012-03-02 13:55:41 -0800737 VLOG(threads) << *self << " self-reviving (debugger)";
Elliott Hughes475fc232011-10-25 15:00:35 -0700738}
739
Elliott Hughes234ab152011-10-26 14:02:26 -0700740void ThreadList::UndoDebuggerSuspensions() {
741 Thread* self = Thread::Current();
742
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800743 VLOG(threads) << *self << " UndoDebuggerSuspensions starting";
Elliott Hughes234ab152011-10-26 14:02:26 -0700744
745 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700746 MutexLock mu(self, *Locks::thread_list_lock_);
747 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700748 // Update global suspend all state for attaching threads.
749 suspend_all_count_ -= debug_suspend_all_count_;
750 debug_suspend_all_count_ = 0;
751 // Update running threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700752 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700753 if (thread == self || thread->GetDebugSuspendCount() == 0) {
Elliott Hughes234ab152011-10-26 14:02:26 -0700754 continue;
755 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700756 thread->ModifySuspendCount(self, -thread->GetDebugSuspendCount(), true);
Elliott Hughes234ab152011-10-26 14:02:26 -0700757 }
758 }
759
760 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700761 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700762 Thread::resume_cond_->Broadcast(self);
Elliott Hughes234ab152011-10-26 14:02:26 -0700763 }
764
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800765 VLOG(threads) << "UndoDebuggerSuspensions(" << *self << ") complete";
Elliott Hughes234ab152011-10-26 14:02:26 -0700766}
767
Elliott Hughese52e49b2012-04-02 16:05:44 -0700768void ThreadList::WaitForOtherNonDaemonThreadsToExit() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700769 Thread* self = Thread::Current();
770 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700771 bool all_threads_are_daemons;
772 do {
Ian Rogers120f1c72012-09-28 17:17:10 -0700773 {
774 // No more threads can be born after we start to shutdown.
775 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700776 CHECK(Runtime::Current()->IsShuttingDownLocked());
Ian Rogers120f1c72012-09-28 17:17:10 -0700777 CHECK_EQ(Runtime::Current()->NumberOfThreadsBeingBorn(), 0U);
778 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700779 all_threads_are_daemons = true;
Ian Rogers120f1c72012-09-28 17:17:10 -0700780 MutexLock mu(self, *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700781 for (const auto& thread : list_) {
Anwar Ghuloum97543682013-06-14 12:58:16 -0700782 if (thread != self && !thread->IsDaemon()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700783 all_threads_are_daemons = false;
784 break;
785 }
786 }
787 if (!all_threads_are_daemons) {
788 // Wait for another thread to exit before re-checking.
Ian Rogersc604d732012-10-14 16:09:54 -0700789 thread_exit_cond_.Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700790 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700791 } while (!all_threads_are_daemons);
Elliott Hughes038a8062011-09-18 14:12:41 -0700792}
793
794void ThreadList::SuspendAllDaemonThreads() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700795 Thread* self = Thread::Current();
796 MutexLock mu(self, *Locks::thread_list_lock_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700797 { // Tell all the daemons it's time to suspend.
Ian Rogers81d425b2012-09-27 16:03:43 -0700798 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700799 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700800 // This is only run after all non-daemon threads have exited, so the remainder should all be
801 // daemons.
Ian Rogers7e762862012-10-22 15:45:08 -0700802 CHECK(thread->IsDaemon()) << *thread;
Ian Rogers81d425b2012-09-27 16:03:43 -0700803 if (thread != self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700804 thread->ModifySuspendCount(self, +1, false);
Elliott Hughese52e49b2012-04-02 16:05:44 -0700805 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700806 }
807 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700808 // Give the threads a chance to suspend, complaining if they're slow.
809 bool have_complained = false;
810 for (int i = 0; i < 10; ++i) {
811 usleep(200 * 1000);
812 bool all_suspended = true;
Mathieu Chartier02e25112013-08-14 16:14:24 -0700813 for (const auto& thread : list_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700814 if (thread != self && thread->GetState() == kRunnable) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700815 if (!have_complained) {
816 LOG(WARNING) << "daemon thread not yet suspended: " << *thread;
817 have_complained = true;
818 }
819 all_suspended = false;
820 }
821 }
822 if (all_suspended) {
823 return;
824 }
825 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700826 LOG(ERROR) << "suspend all daemons failed";
827}
828void ThreadList::Register(Thread* self) {
829 DCHECK_EQ(self, Thread::Current());
830
831 if (VLOG_IS_ON(threads)) {
832 std::ostringstream oss;
833 self->ShortDump(oss); // We don't hold the mutator_lock_ yet and so cannot call Dump.
Ian Rogers5a9ba012014-05-19 13:28:52 -0700834 LOG(INFO) << "ThreadList::Register() " << *self << "\n" << oss.str();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700835 }
836
837 // Atomically add self to the thread list and make its thread_suspend_count_ reflect ongoing
838 // SuspendAll requests.
Ian Rogers81d425b2012-09-27 16:03:43 -0700839 MutexLock mu(self, *Locks::thread_list_lock_);
840 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700841 CHECK_GE(suspend_all_count_, debug_suspend_all_count_);
Ian Rogers2966e132014-04-02 08:34:36 -0700842 // Modify suspend count in increments of 1 to maintain invariants in ModifySuspendCount. While
843 // this isn't particularly efficient the suspend counts are most commonly 0 or 1.
844 for (int delta = debug_suspend_all_count_; delta > 0; delta--) {
845 self->ModifySuspendCount(self, +1, true);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700846 }
Ian Rogers2966e132014-04-02 08:34:36 -0700847 for (int delta = suspend_all_count_ - debug_suspend_all_count_; delta > 0; delta--) {
848 self->ModifySuspendCount(self, +1, false);
Ian Rogers01ae5802012-09-28 16:14:01 -0700849 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700850 CHECK(!Contains(self));
851 list_.push_back(self);
852}
853
854void ThreadList::Unregister(Thread* self) {
855 DCHECK_EQ(self, Thread::Current());
Ian Rogers68d8b422014-07-17 11:09:10 -0700856 CHECK_NE(self->GetState(), kRunnable);
857 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700858
859 VLOG(threads) << "ThreadList::Unregister() " << *self;
860
861 // Any time-consuming destruction, plus anything that can call back into managed code or
862 // suspend and so on, must happen at this point, and not in ~Thread.
863 self->Destroy();
864
Ian Rogersdd7624d2014-03-14 17:43:00 -0700865 uint32_t thin_lock_id = self->GetThreadId();
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800866 while (self != nullptr) {
Ian Rogerscfaa4552012-11-26 21:00:08 -0800867 // Remove and delete the Thread* while holding the thread_list_lock_ and
868 // thread_suspend_count_lock_ so that the unregistering thread cannot be suspended.
Ian Rogers0878d652013-04-18 17:38:35 -0700869 // Note: deliberately not using MutexLock that could hold a stale self pointer.
870 Locks::thread_list_lock_->ExclusiveLock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700871 CHECK(Contains(self));
Ian Rogers68d8b422014-07-17 11:09:10 -0700872 Locks::thread_suspend_count_lock_->ExclusiveLock(self);
873 bool removed = false;
Ian Rogerscfaa4552012-11-26 21:00:08 -0800874 if (!self->IsSuspended()) {
875 list_.remove(self);
Ian Rogers68d8b422014-07-17 11:09:10 -0700876 removed = true;
877 }
878 Locks::thread_suspend_count_lock_->ExclusiveUnlock(self);
879 Locks::thread_list_lock_->ExclusiveUnlock(self);
880 if (removed) {
Ian Rogerscfaa4552012-11-26 21:00:08 -0800881 delete self;
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800882 self = nullptr;
Ian Rogerscfaa4552012-11-26 21:00:08 -0800883 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700884 }
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800885 // Release the thread ID after the thread is finished and deleted to avoid cases where we can
886 // temporarily have multiple threads with the same thread id. When this occurs, it causes
887 // problems in FindThreadByThreadId / SuspendThreadByThreadId.
888 ReleaseThreadId(nullptr, thin_lock_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700889
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700890 // Clear the TLS data, so that the underlying native thread is recognizably detached.
891 // (It may wish to reattach later.)
892 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, NULL), "detach self");
893
894 // Signal that a thread just detached.
Ian Rogers81d425b2012-09-27 16:03:43 -0700895 MutexLock mu(NULL, *Locks::thread_list_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700896 thread_exit_cond_.Signal(NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700897}
898
899void ThreadList::ForEach(void (*callback)(Thread*, void*), void* context) {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700900 for (const auto& thread : list_) {
901 callback(thread, context);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700902 }
903}
904
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800905void ThreadList::VisitRoots(RootCallback* callback, void* arg) const {
Ian Rogers81d425b2012-09-27 16:03:43 -0700906 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700907 for (const auto& thread : list_) {
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800908 thread->VisitRoots(callback, arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700909 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700910}
911
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800912class VerifyRootWrapperArg {
913 public:
914 VerifyRootWrapperArg(VerifyRootCallback* callback, void* arg) : callback_(callback), arg_(arg) {
915 }
916 VerifyRootCallback* const callback_;
917 void* const arg_;
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700918};
919
Mathieu Chartier815873e2014-02-13 18:02:13 -0800920static void VerifyRootWrapperCallback(mirror::Object** root, void* arg, uint32_t /*thread_id*/,
Mathieu Chartier7bf9f192014-04-04 11:09:41 -0700921 RootType root_type) {
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700922 VerifyRootWrapperArg* wrapperArg = reinterpret_cast<VerifyRootWrapperArg*>(arg);
Mathieu Chartier7bf9f192014-04-04 11:09:41 -0700923 wrapperArg->callback_(*root, wrapperArg->arg_, 0, NULL, root_type);
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700924}
925
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800926void ThreadList::VerifyRoots(VerifyRootCallback* callback, void* arg) const {
927 VerifyRootWrapperArg wrapper(callback, arg);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700928 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700929 for (const auto& thread : list_) {
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700930 thread->VisitRoots(VerifyRootWrapperCallback, &wrapper);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700931 }
932}
933
Ian Rogerscfaa4552012-11-26 21:00:08 -0800934uint32_t ThreadList::AllocThreadId(Thread* self) {
Chao-ying Fu9e369312014-05-21 11:20:52 -0700935 MutexLock mu(self, *Locks::allocated_thread_ids_lock_);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700936 for (size_t i = 0; i < allocated_ids_.size(); ++i) {
937 if (!allocated_ids_[i]) {
938 allocated_ids_.set(i);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700939 return i + 1; // Zero is reserved to mean "invalid".
Elliott Hughes8daa0922011-09-11 13:46:25 -0700940 }
941 }
942 LOG(FATAL) << "Out of internal thread ids";
943 return 0;
944}
945
Ian Rogerscfaa4552012-11-26 21:00:08 -0800946void ThreadList::ReleaseThreadId(Thread* self, uint32_t id) {
Chao-ying Fu9e369312014-05-21 11:20:52 -0700947 MutexLock mu(self, *Locks::allocated_thread_ids_lock_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700948 --id; // Zero is reserved to mean "invalid".
Elliott Hughes8daa0922011-09-11 13:46:25 -0700949 DCHECK(allocated_ids_[id]) << id;
950 allocated_ids_.reset(id);
951}
952
Elliott Hughes8daa0922011-09-11 13:46:25 -0700953} // namespace art