blob: 646830acc6112f0d3faa0818f8b22602fbf6527d [file] [log] [blame]
Elliott Hughes8daa0922011-09-11 13:46:25 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "thread_list.h"
18
Mathieu Chartier6f365cc2014-04-23 12:42:27 -070019#define ATRACE_TAG ATRACE_TAG_DALVIK
20
21#include <cutils/trace.h>
Elliott Hughesabbe07d2012-06-05 17:42:23 -070022#include <dirent.h>
Ian Rogersd9c4fc92013-10-01 19:45:43 -070023#include <ScopedLocalRef.h>
24#include <ScopedUtfChars.h>
Elliott Hughesabbe07d2012-06-05 17:42:23 -070025#include <sys/types.h>
Elliott Hughes038a8062011-09-18 14:12:41 -070026#include <unistd.h>
27
Elliott Hughes76b61672012-12-12 17:47:30 -080028#include "base/mutex.h"
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -070029#include "base/mutex-inl.h"
Sameer Abu Asala8439542013-02-14 16:06:42 -080030#include "base/timing_logger.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070031#include "debugger.h"
Ian Rogersd9c4fc92013-10-01 19:45:43 -070032#include "jni_internal.h"
33#include "lock_word.h"
34#include "monitor.h"
35#include "scoped_thread_state_change.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080036#include "thread.h"
Jeff Haoe094b872014-10-14 13:12:01 -070037#include "trace.h"
Elliott Hughesabbe07d2012-06-05 17:42:23 -070038#include "utils.h"
Ian Rogersd9c4fc92013-10-01 19:45:43 -070039#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070040
Elliott Hughes8daa0922011-09-11 13:46:25 -070041namespace art {
42
Mathieu Chartier251755c2014-07-15 18:10:25 -070043static constexpr uint64_t kLongThreadSuspendThreshold = MsToNs(5);
44
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -080045ThreadList::ThreadList()
Chao-ying Fu9e369312014-05-21 11:20:52 -070046 : suspend_all_count_(0), debug_suspend_all_count_(0),
Ian Rogersc604d732012-10-14 16:09:54 -070047 thread_exit_cond_("thread exit condition variable", *Locks::thread_list_lock_) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -070048 CHECK(Monitor::IsValidLockWord(LockWord::FromThinLockId(kMaxThreadId, 1)));
Elliott Hughes8daa0922011-09-11 13:46:25 -070049}
50
51ThreadList::~ThreadList() {
Elliott Hughese52e49b2012-04-02 16:05:44 -070052 // Detach the current thread if necessary. If we failed to start, there might not be any threads.
Elliott Hughes6a144332012-04-03 13:07:11 -070053 // We need to detach the current thread here in case there's another thread waiting to join with
54 // us.
Mathieu Chartierfec72f42014-10-09 12:57:58 -070055 bool contains = false;
56 {
57 Thread* self = Thread::Current();
58 MutexLock mu(self, *Locks::thread_list_lock_);
59 contains = Contains(self);
60 }
61 if (contains) {
Elliott Hughes8daa0922011-09-11 13:46:25 -070062 Runtime::Current()->DetachCurrentThread();
63 }
Elliott Hughes6a144332012-04-03 13:07:11 -070064
65 WaitForOtherNonDaemonThreadsToExit();
Ian Rogers00f7d0e2012-07-19 15:28:27 -070066 // TODO: there's an unaddressed race here where a thread may attach during shutdown, see
67 // Thread::Init.
Elliott Hughes6a144332012-04-03 13:07:11 -070068 SuspendAllDaemonThreads();
Elliott Hughes8daa0922011-09-11 13:46:25 -070069}
70
71bool ThreadList::Contains(Thread* thread) {
72 return find(list_.begin(), list_.end(), thread) != list_.end();
73}
74
Elliott Hughesabbe07d2012-06-05 17:42:23 -070075bool ThreadList::Contains(pid_t tid) {
Mathieu Chartier02e25112013-08-14 16:14:24 -070076 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -070077 if (thread->GetTid() == tid) {
Elliott Hughesabbe07d2012-06-05 17:42:23 -070078 return true;
79 }
80 }
81 return false;
82}
83
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -070084pid_t ThreadList::GetLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -070085 return Locks::thread_list_lock_->GetExclusiveOwnerTid();
Elliott Hughesaccd83d2011-10-17 14:25:58 -070086}
87
Mathieu Chartier590fee92013-09-13 13:46:47 -070088void ThreadList::DumpNativeStacks(std::ostream& os) {
89 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
90 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -070091 os << "DUMPING THREAD " << thread->GetTid() << "\n";
Christopher Ferrisa2cee182014-04-16 19:13:59 -070092 DumpNativeStack(os, thread->GetTid(), "\t");
Mathieu Chartier590fee92013-09-13 13:46:47 -070093 os << "\n";
94 }
95}
96
Elliott Hughesc967f782012-04-16 10:23:15 -070097void ThreadList::DumpForSigQuit(std::ostream& os) {
Ian Rogers7b078e82014-09-10 14:44:24 -070098 Dump(os);
Elliott Hughesabbe07d2012-06-05 17:42:23 -070099 DumpUnattachedThreads(os);
100}
101
Ian Rogerscfaa4552012-11-26 21:00:08 -0800102static void DumpUnattachedThread(std::ostream& os, pid_t tid) NO_THREAD_SAFETY_ANALYSIS {
103 // TODO: No thread safety analysis as DumpState with a NULL thread won't access fields, should
104 // refactor DumpState to avoid skipping analysis.
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700105 Thread::DumpState(os, NULL, tid);
106 DumpKernelStack(os, tid, " kernel: ", false);
Brian Carlstromed8b7232012-06-27 17:54:47 -0700107 // TODO: Reenable this when the native code in system_server can handle it.
108 // Currently "adb shell kill -3 `pid system_server`" will cause it to exit.
109 if (false) {
Christopher Ferrisa2cee182014-04-16 19:13:59 -0700110 DumpNativeStack(os, tid, " native: ");
Brian Carlstromed8b7232012-06-27 17:54:47 -0700111 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700112 os << "\n";
113}
114
115void ThreadList::DumpUnattachedThreads(std::ostream& os) {
116 DIR* d = opendir("/proc/self/task");
117 if (!d) {
118 return;
119 }
120
Ian Rogers50b35e22012-10-04 10:09:15 -0700121 Thread* self = Thread::Current();
Elliott Hughes4696b5b2012-10-30 10:35:10 -0700122 dirent* e;
123 while ((e = readdir(d)) != NULL) {
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700124 char* end;
Elliott Hughes4696b5b2012-10-30 10:35:10 -0700125 pid_t tid = strtol(e->d_name, &end, 10);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700126 if (!*end) {
127 bool contains;
128 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700129 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700130 contains = Contains(tid);
131 }
132 if (!contains) {
133 DumpUnattachedThread(os, tid);
134 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700135 }
136 }
137 closedir(d);
Elliott Hughesff738062012-02-03 15:00:42 -0800138}
139
Ian Rogers7b078e82014-09-10 14:44:24 -0700140// A closure used by Thread::Dump.
141class DumpCheckpoint FINAL : public Closure {
142 public:
143 explicit DumpCheckpoint(std::ostream* os) : os_(os), barrier_(0) {}
144
145 void Run(Thread* thread) OVERRIDE {
146 // Note thread and self may not be equal if thread was already suspended at the point of the
147 // request.
148 Thread* self = Thread::Current();
149 std::ostringstream local_os;
150 {
151 ScopedObjectAccess soa(self);
152 thread->Dump(local_os);
153 }
154 local_os << "\n";
155 {
156 // Use the logging lock to ensure serialization when writing to the common ostream.
157 MutexLock mu(self, *Locks::logging_lock_);
158 *os_ << local_os.str();
159 }
160 barrier_.Pass(self);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700161 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700162
163 void WaitForThreadsToRunThroughCheckpoint(size_t threads_running_checkpoint) {
164 Thread* self = Thread::Current();
165 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
Ian Rogers2156ff12014-09-13 19:20:54 -0700166 const uint32_t kWaitTimeoutMs = 10000;
167 bool timed_out = barrier_.Increment(self, threads_running_checkpoint, kWaitTimeoutMs);
168 if (timed_out) {
169 LOG(kIsDebugBuild ? FATAL : ERROR) << "Unexpected time out during dump checkpoint.";
170 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700171 }
172
173 private:
174 // The common stream that will accumulate all the dumps.
175 std::ostream* const os_;
176 // The barrier to be passed through and for the requestor to wait upon.
177 Barrier barrier_;
178};
179
180void ThreadList::Dump(std::ostream& os) {
181 {
182 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
183 os << "DALVIK THREADS (" << list_.size() << "):\n";
184 }
185 DumpCheckpoint checkpoint(&os);
186 size_t threads_running_checkpoint = RunCheckpoint(&checkpoint);
187 checkpoint.WaitForThreadsToRunThroughCheckpoint(threads_running_checkpoint);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700188}
189
Ian Rogers50b35e22012-10-04 10:09:15 -0700190void ThreadList::AssertThreadsAreSuspended(Thread* self, Thread* ignore1, Thread* ignore2) {
191 MutexLock mu(self, *Locks::thread_list_lock_);
192 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700193 for (const auto& thread : list_) {
jeffhao725a9572012-11-13 18:20:12 -0800194 if (thread != ignore1 && thread != ignore2) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700195 CHECK(thread->IsSuspended())
196 << "\nUnsuspended thread: <<" << *thread << "\n"
197 << "self: <<" << *Thread::Current();
198 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700199 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700200}
201
Ian Rogers66aee5c2012-08-15 17:17:47 -0700202#if HAVE_TIMED_RWLOCK
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700203// Attempt to rectify locks so that we dump thread list with required locks before exiting.
Ian Rogers7b078e82014-09-10 14:44:24 -0700204static void UnsafeLogFatalForThreadSuspendAllTimeout() __attribute__((noreturn));
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100205static void UnsafeLogFatalForThreadSuspendAllTimeout() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700206 Runtime* runtime = Runtime::Current();
207 std::ostringstream ss;
208 ss << "Thread suspend timeout\n";
Mathieu Chartier5869a2c2014-10-08 14:26:23 -0700209 Locks::mutator_lock_->Dump(ss);
210 ss << "\n";
Ian Rogers7b078e82014-09-10 14:44:24 -0700211 runtime->GetThreadList()->Dump(ss);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700212 LOG(FATAL) << ss.str();
Ian Rogers719d1a32014-03-06 12:13:39 -0800213 exit(0);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700214}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700215#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700216
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800217// Unlike suspending all threads where we can wait to acquire the mutator_lock_, suspending an
218// individual thread requires polling. delay_us is the requested sleep and total_delay_us
219// accumulates the total time spent sleeping for timeouts. The first sleep is just a yield,
220// subsequently sleeps increase delay_us from 1ms to 500ms by doubling.
Ian Rogersf3d874c2014-07-17 18:52:42 -0700221static void ThreadSuspendSleep(Thread* self, useconds_t* delay_us, useconds_t* total_delay_us) {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800222 useconds_t new_delay_us = (*delay_us) * 2;
223 CHECK_GE(new_delay_us, *delay_us);
224 if (new_delay_us < 500000) { // Don't allow sleeping to be more than 0.5s.
225 *delay_us = new_delay_us;
226 }
227 if (*delay_us == 0) {
228 sched_yield();
229 // Default to 1 milliseconds (note that this gets multiplied by 2 before the first sleep).
230 *delay_us = 500;
231 } else {
232 usleep(*delay_us);
233 *total_delay_us += *delay_us;
234 }
235}
236
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700237size_t ThreadList::RunCheckpoint(Closure* checkpoint_function) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700238 Thread* self = Thread::Current();
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800239 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
240 Locks::thread_list_lock_->AssertNotHeld(self);
241 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
242 if (kDebugLocking) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700243 CHECK_NE(self->GetState(), kRunnable);
244 }
245
246 std::vector<Thread*> suspended_count_modified_threads;
247 size_t count = 0;
248 {
249 // Call a checkpoint function for each thread, threads which are suspend get their checkpoint
250 // manually called.
251 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700252 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700253 for (const auto& thread : list_) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700254 if (thread != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700255 while (true) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700256 if (thread->RequestCheckpoint(checkpoint_function)) {
Dave Allison0aded082013-11-07 13:15:11 -0800257 // This thread will run its checkpoint some time in the near future.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700258 count++;
259 break;
260 } else {
261 // We are probably suspended, try to make sure that we stay suspended.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700262 // The thread switched back to runnable.
263 if (thread->GetState() == kRunnable) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700264 // Spurious fail, try again.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700265 continue;
266 }
267 thread->ModifySuspendCount(self, +1, false);
268 suspended_count_modified_threads.push_back(thread);
269 break;
270 }
271 }
272 }
273 }
274 }
275
276 // Run the checkpoint on ourself while we wait for threads to suspend.
277 checkpoint_function->Run(self);
278
279 // Run the checkpoint on the suspended threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700280 for (const auto& thread : suspended_count_modified_threads) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700281 if (!thread->IsSuspended()) {
282 // Wait until the thread is suspended.
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800283 useconds_t total_delay_us = 0;
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700284 do {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800285 useconds_t delay_us = 100;
Ian Rogersf3d874c2014-07-17 18:52:42 -0700286 ThreadSuspendSleep(self, &delay_us, &total_delay_us);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700287 } while (!thread->IsSuspended());
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800288 // Shouldn't need to wait for longer than 1000 microseconds.
289 constexpr useconds_t kLongWaitThresholdUS = 1000;
290 if (UNLIKELY(total_delay_us > kLongWaitThresholdUS)) {
291 LOG(WARNING) << "Waited " << total_delay_us << " us for thread suspend!";
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700292 }
293 }
294 // We know for sure that the thread is suspended at this point.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700295 checkpoint_function->Run(thread);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700296 {
297 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
298 thread->ModifySuspendCount(self, -1, false);
299 }
300 }
301
Mathieu Chartier664bebf2012-11-12 16:54:11 -0800302 {
303 // Imitate ResumeAll, threads may be waiting on Thread::resume_cond_ since we raised their
304 // suspend count. Now the suspend_count_ is lowered so we must do the broadcast.
305 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
306 Thread::resume_cond_->Broadcast(self);
307 }
308
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700309 // Add one for self.
310 return count + suspended_count_modified_threads.size() + 1;
311}
312
Dave Allison39c3bfb2014-01-28 18:33:52 -0800313// Request that a checkpoint function be run on all active (non-suspended)
314// threads. Returns the number of successful requests.
315size_t ThreadList::RunCheckpointOnRunnableThreads(Closure* checkpoint_function) {
316 Thread* self = Thread::Current();
Ian Rogers7b078e82014-09-10 14:44:24 -0700317 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
318 Locks::thread_list_lock_->AssertNotHeld(self);
319 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
320 CHECK_NE(self->GetState(), kRunnable);
Dave Allison39c3bfb2014-01-28 18:33:52 -0800321
322 size_t count = 0;
323 {
324 // Call a checkpoint function for each non-suspended thread.
325 MutexLock mu(self, *Locks::thread_list_lock_);
326 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
327 for (const auto& thread : list_) {
328 if (thread != self) {
329 if (thread->RequestCheckpoint(checkpoint_function)) {
330 // This thread will run its checkpoint some time in the near future.
331 count++;
332 }
333 }
334 }
335 }
336
337 // Return the number of threads that will run the checkpoint function.
338 return count;
339}
340
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700341void ThreadList::SuspendAll() {
342 Thread* self = Thread::Current();
343
Jeff Haoc5d824a2014-07-28 18:35:38 -0700344 if (self != nullptr) {
345 VLOG(threads) << *self << " SuspendAll starting...";
346 } else {
347 VLOG(threads) << "Thread[null] SuspendAll starting...";
348 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700349 ATRACE_BEGIN("Suspending mutator threads");
Mathieu Chartier251755c2014-07-15 18:10:25 -0700350 uint64_t start_time = NanoTime();
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700351
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800352 Locks::mutator_lock_->AssertNotHeld(self);
353 Locks::thread_list_lock_->AssertNotHeld(self);
354 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
Jeff Haoc5d824a2014-07-28 18:35:38 -0700355 if (kDebugLocking && self != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700356 CHECK_NE(self->GetState(), kRunnable);
357 }
358 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700359 MutexLock mu(self, *Locks::thread_list_lock_);
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800360 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
361 // Update global suspend all state for attaching threads.
362 ++suspend_all_count_;
363 // Increment everybody's suspend count (except our own).
364 for (const auto& thread : list_) {
365 if (thread == self) {
366 continue;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700367 }
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800368 VLOG(threads) << "requesting thread suspend: " << *thread;
369 thread->ModifySuspendCount(self, +1, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700370 }
371 }
372
Ian Rogers66aee5c2012-08-15 17:17:47 -0700373 // Block on the mutator lock until all Runnable threads release their share of access.
374#if HAVE_TIMED_RWLOCK
375 // Timeout if we wait more than 30 seconds.
Ian Rogers719d1a32014-03-06 12:13:39 -0800376 if (!Locks::mutator_lock_->ExclusiveLockWithTimeout(self, 30 * 1000, 0)) {
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100377 UnsafeLogFatalForThreadSuspendAllTimeout();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700378 }
Ian Rogers66aee5c2012-08-15 17:17:47 -0700379#else
Ian Rogers81d425b2012-09-27 16:03:43 -0700380 Locks::mutator_lock_->ExclusiveLock(self);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700381#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700382
Mathieu Chartier251755c2014-07-15 18:10:25 -0700383 uint64_t end_time = NanoTime();
384 if (end_time - start_time > kLongThreadSuspendThreshold) {
385 LOG(WARNING) << "Suspending all threads took: " << PrettyDuration(end_time - start_time);
386 }
387
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800388 if (kDebugLocking) {
389 // Debug check that all threads are suspended.
390 AssertThreadsAreSuspended(self, self);
391 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700392
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700393 ATRACE_END();
394 ATRACE_BEGIN("Mutator threads suspended");
395
Jeff Haoc5d824a2014-07-28 18:35:38 -0700396 if (self != nullptr) {
397 VLOG(threads) << *self << " SuspendAll complete";
398 } else {
399 VLOG(threads) << "Thread[null] SuspendAll complete";
400 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700401}
402
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700403void ThreadList::ResumeAll() {
404 Thread* self = Thread::Current();
405
Jeff Haoc5d824a2014-07-28 18:35:38 -0700406 if (self != nullptr) {
407 VLOG(threads) << *self << " ResumeAll starting";
408 } else {
409 VLOG(threads) << "Thread[null] ResumeAll starting";
410 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700411
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700412 ATRACE_END();
413 ATRACE_BEGIN("Resuming mutator threads");
414
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800415 if (kDebugLocking) {
416 // Debug check that all threads are suspended.
417 AssertThreadsAreSuspended(self, self);
418 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700419
Ian Rogers81d425b2012-09-27 16:03:43 -0700420 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700421 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700422 MutexLock mu(self, *Locks::thread_list_lock_);
423 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700424 // Update global suspend all state for attaching threads.
425 --suspend_all_count_;
426 // Decrement the suspend counts for all threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700427 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700428 if (thread == self) {
429 continue;
430 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700431 thread->ModifySuspendCount(self, -1, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700432 }
433
434 // Broadcast a notification to all suspended threads, some or all of
435 // which may choose to wake up. No need to wait for them.
Jeff Haoc5d824a2014-07-28 18:35:38 -0700436 if (self != nullptr) {
437 VLOG(threads) << *self << " ResumeAll waking others";
438 } else {
439 VLOG(threads) << "Thread[null] ResumeAll waking others";
440 }
Ian Rogersc604d732012-10-14 16:09:54 -0700441 Thread::resume_cond_->Broadcast(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700442 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700443 ATRACE_END();
Jeff Haoc5d824a2014-07-28 18:35:38 -0700444
445 if (self != nullptr) {
446 VLOG(threads) << *self << " ResumeAll complete";
447 } else {
448 VLOG(threads) << "Thread[null] ResumeAll complete";
449 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700450}
451
452void ThreadList::Resume(Thread* thread, bool for_debugger) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700453 Thread* self = Thread::Current();
454 DCHECK_NE(thread, self);
Brian Carlstromba32de42014-08-27 23:43:46 -0700455 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") starting..."
456 << (for_debugger ? " (debugger)" : "");
Elliott Hughes01158d72011-09-19 19:47:10 -0700457
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700458 {
459 // To check Contains.
Ian Rogers81d425b2012-09-27 16:03:43 -0700460 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700461 // To check IsSuspended.
Ian Rogers81d425b2012-09-27 16:03:43 -0700462 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
463 DCHECK(thread->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700464 if (!Contains(thread)) {
Brian Carlstromba32de42014-08-27 23:43:46 -0700465 // We only expect threads within the thread-list to have been suspended otherwise we can't
466 // stop such threads from delete-ing themselves.
467 LOG(ERROR) << "Resume(" << reinterpret_cast<void*>(thread)
468 << ") thread not within thread list";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700469 return;
470 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700471 thread->ModifySuspendCount(self, -1, for_debugger);
Elliott Hughes01158d72011-09-19 19:47:10 -0700472 }
473
474 {
Brian Carlstromba32de42014-08-27 23:43:46 -0700475 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") waking others";
Ian Rogers81d425b2012-09-27 16:03:43 -0700476 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700477 Thread::resume_cond_->Broadcast(self);
Elliott Hughes01158d72011-09-19 19:47:10 -0700478 }
479
Brian Carlstromba32de42014-08-27 23:43:46 -0700480 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") complete";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700481}
Elliott Hughes01158d72011-09-19 19:47:10 -0700482
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700483static void ThreadSuspendByPeerWarning(Thread* self, int level, const char* message, jobject peer) {
484 JNIEnvExt* env = self->GetJniEnv();
485 ScopedLocalRef<jstring>
486 scoped_name_string(env, (jstring)env->GetObjectField(peer,
487 WellKnownClasses::java_lang_Thread_name));
488 ScopedUtfChars scoped_name_chars(env, scoped_name_string.get());
489 if (scoped_name_chars.c_str() == NULL) {
490 LOG(level) << message << ": " << peer;
491 env->ExceptionClear();
492 } else {
493 LOG(level) << message << ": " << peer << ":" << scoped_name_chars.c_str();
494 }
495}
496
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700497Thread* ThreadList::SuspendThreadByPeer(jobject peer, bool request_suspension,
498 bool debug_suspension, bool* timed_out) {
499 static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
500 useconds_t total_delay_us = 0;
501 useconds_t delay_us = 0;
502 bool did_suspend_request = false;
503 *timed_out = false;
504 Thread* self = Thread::Current();
Brian Carlstromba32de42014-08-27 23:43:46 -0700505 VLOG(threads) << "SuspendThreadByPeer starting";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700506 while (true) {
507 Thread* thread;
508 {
Ian Rogersf3d874c2014-07-17 18:52:42 -0700509 // Note: this will transition to runnable and potentially suspend. We ensure only one thread
510 // is requesting another suspend, to avoid deadlock, by requiring this function be called
511 // holding Locks::thread_list_suspend_thread_lock_. Its important this thread suspend rather
512 // than request thread suspension, to avoid potential cycles in threads requesting each other
513 // suspend.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700514 ScopedObjectAccess soa(self);
515 MutexLock mu(self, *Locks::thread_list_lock_);
516 thread = Thread::FromManagedThread(soa, peer);
Brian Carlstromba32de42014-08-27 23:43:46 -0700517 if (thread == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700518 ThreadSuspendByPeerWarning(self, WARNING, "No such thread for suspend", peer);
Brian Carlstromba32de42014-08-27 23:43:46 -0700519 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700520 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700521 if (!Contains(thread)) {
522 VLOG(threads) << "SuspendThreadByPeer failed for unattached thread: "
523 << reinterpret_cast<void*>(thread);
524 return nullptr;
525 }
526 VLOG(threads) << "SuspendThreadByPeer found thread: " << *thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700527 {
528 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
529 if (request_suspension) {
530 thread->ModifySuspendCount(self, +1, debug_suspension);
531 request_suspension = false;
532 did_suspend_request = true;
533 } else {
534 // If the caller isn't requesting suspension, a suspension should have already occurred.
535 CHECK_GT(thread->GetSuspendCount(), 0);
536 }
537 // IsSuspended on the current thread will fail as the current thread is changed into
538 // Runnable above. As the suspend count is now raised if this is the current thread
539 // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
540 // to just explicitly handle the current thread in the callers to this code.
541 CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
542 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
543 // count, or else we've waited and it has self suspended) or is the current thread, we're
544 // done.
545 if (thread->IsSuspended()) {
Brian Carlstromba32de42014-08-27 23:43:46 -0700546 VLOG(threads) << "SuspendThreadByPeer thread suspended: " << *thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700547 return thread;
548 }
549 if (total_delay_us >= kTimeoutUs) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700550 ThreadSuspendByPeerWarning(self, FATAL, "Thread suspension timed out", peer);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700551 if (did_suspend_request) {
552 thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
553 }
554 *timed_out = true;
Brian Carlstromba32de42014-08-27 23:43:46 -0700555 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700556 }
557 }
558 // Release locks and come out of runnable state.
559 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700560 VLOG(threads) << "SuspendThreadByPeer sleeping to allow thread chance to suspend";
Ian Rogersf3d874c2014-07-17 18:52:42 -0700561 ThreadSuspendSleep(self, &delay_us, &total_delay_us);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700562 }
563}
564
565static void ThreadSuspendByThreadIdWarning(int level, const char* message, uint32_t thread_id) {
566 LOG(level) << StringPrintf("%s: %d", message, thread_id);
567}
568
569Thread* ThreadList::SuspendThreadByThreadId(uint32_t thread_id, bool debug_suspension,
570 bool* timed_out) {
571 static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
572 useconds_t total_delay_us = 0;
573 useconds_t delay_us = 0;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700574 *timed_out = false;
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800575 Thread* suspended_thread = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700576 Thread* self = Thread::Current();
577 CHECK_NE(thread_id, kInvalidThreadId);
Brian Carlstromba32de42014-08-27 23:43:46 -0700578 VLOG(threads) << "SuspendThreadByThreadId starting";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700579 while (true) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700580 {
Ian Rogersf3d874c2014-07-17 18:52:42 -0700581 // Note: this will transition to runnable and potentially suspend. We ensure only one thread
582 // is requesting another suspend, to avoid deadlock, by requiring this function be called
583 // holding Locks::thread_list_suspend_thread_lock_. Its important this thread suspend rather
584 // than request thread suspension, to avoid potential cycles in threads requesting each other
585 // suspend.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700586 ScopedObjectAccess soa(self);
587 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogersf3d874c2014-07-17 18:52:42 -0700588 Thread* thread = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700589 for (const auto& it : list_) {
590 if (it->GetThreadId() == thread_id) {
591 thread = it;
592 break;
593 }
594 }
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800595 if (thread == nullptr) {
596 CHECK(suspended_thread == nullptr) << "Suspended thread " << suspended_thread
597 << " no longer in thread list";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700598 // There's a race in inflating a lock and the owner giving up ownership and then dying.
599 ThreadSuspendByThreadIdWarning(WARNING, "No such thread id for suspend", thread_id);
Brian Carlstromba32de42014-08-27 23:43:46 -0700600 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700601 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700602 VLOG(threads) << "SuspendThreadByThreadId found thread: " << *thread;
603 DCHECK(Contains(thread));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700604 {
605 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800606 if (suspended_thread == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700607 thread->ModifySuspendCount(self, +1, debug_suspension);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800608 suspended_thread = thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700609 } else {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800610 CHECK_EQ(suspended_thread, thread);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700611 // If the caller isn't requesting suspension, a suspension should have already occurred.
612 CHECK_GT(thread->GetSuspendCount(), 0);
613 }
614 // IsSuspended on the current thread will fail as the current thread is changed into
615 // Runnable above. As the suspend count is now raised if this is the current thread
616 // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
617 // to just explicitly handle the current thread in the callers to this code.
618 CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
619 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
620 // count, or else we've waited and it has self suspended) or is the current thread, we're
621 // done.
622 if (thread->IsSuspended()) {
Brian Carlstromba32de42014-08-27 23:43:46 -0700623 VLOG(threads) << "SuspendThreadByThreadId thread suspended: " << *thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700624 return thread;
625 }
626 if (total_delay_us >= kTimeoutUs) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700627 ThreadSuspendByThreadIdWarning(WARNING, "Thread suspension timed out", thread_id);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800628 if (suspended_thread != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700629 thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
630 }
631 *timed_out = true;
Brian Carlstromba32de42014-08-27 23:43:46 -0700632 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700633 }
634 }
635 // Release locks and come out of runnable state.
636 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700637 VLOG(threads) << "SuspendThreadByThreadId sleeping to allow thread chance to suspend";
Ian Rogersf3d874c2014-07-17 18:52:42 -0700638 ThreadSuspendSleep(self, &delay_us, &total_delay_us);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700639 }
640}
641
642Thread* ThreadList::FindThreadByThreadId(uint32_t thin_lock_id) {
643 Thread* self = Thread::Current();
644 MutexLock mu(self, *Locks::thread_list_lock_);
645 for (const auto& thread : list_) {
646 if (thread->GetThreadId() == thin_lock_id) {
647 CHECK(thread == self || thread->IsSuspended());
648 return thread;
649 }
650 }
651 return NULL;
652}
653
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700654void ThreadList::SuspendAllForDebugger() {
655 Thread* self = Thread::Current();
656 Thread* debug_thread = Dbg::GetDebugThread();
657
658 VLOG(threads) << *self << " SuspendAllForDebugger starting...";
659
660 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700661 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700662 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700663 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700664 // Update global suspend all state for attaching threads.
665 ++suspend_all_count_;
666 ++debug_suspend_all_count_;
667 // Increment everybody's suspend count (except our own).
Mathieu Chartier02e25112013-08-14 16:14:24 -0700668 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700669 if (thread == self || thread == debug_thread) {
670 continue;
671 }
672 VLOG(threads) << "requesting thread suspend: " << *thread;
Ian Rogers01ae5802012-09-28 16:14:01 -0700673 thread->ModifySuspendCount(self, +1, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700674 }
675 }
676 }
677
Ian Rogers66aee5c2012-08-15 17:17:47 -0700678 // Block on the mutator lock until all Runnable threads release their share of access then
679 // immediately unlock again.
680#if HAVE_TIMED_RWLOCK
681 // Timeout if we wait more than 30 seconds.
Ian Rogersc604d732012-10-14 16:09:54 -0700682 if (!Locks::mutator_lock_->ExclusiveLockWithTimeout(self, 30 * 1000, 0)) {
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100683 UnsafeLogFatalForThreadSuspendAllTimeout();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700684 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -0700685 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700686 }
Ian Rogers66aee5c2012-08-15 17:17:47 -0700687#else
Ian Rogers81d425b2012-09-27 16:03:43 -0700688 Locks::mutator_lock_->ExclusiveLock(self);
689 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700690#endif
Ian Rogers50b35e22012-10-04 10:09:15 -0700691 AssertThreadsAreSuspended(self, self, debug_thread);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700692
Sebastien Hertzed2be172014-08-19 15:33:43 +0200693 VLOG(threads) << *self << " SuspendAllForDebugger complete";
Elliott Hughes01158d72011-09-19 19:47:10 -0700694}
695
Elliott Hughes475fc232011-10-25 15:00:35 -0700696void ThreadList::SuspendSelfForDebugger() {
697 Thread* self = Thread::Current();
Elliott Hughes01158d72011-09-19 19:47:10 -0700698
Elliott Hughes475fc232011-10-25 15:00:35 -0700699 // The debugger thread must not suspend itself due to debugger activity!
700 Thread* debug_thread = Dbg::GetDebugThread();
701 CHECK(debug_thread != NULL);
702 CHECK(self != debug_thread);
jeffhaoa77f0f62012-12-05 17:19:31 -0800703 CHECK_NE(self->GetState(), kRunnable);
704 Locks::mutator_lock_->AssertNotHeld(self);
Elliott Hughes475fc232011-10-25 15:00:35 -0700705
jeffhaoa77f0f62012-12-05 17:19:31 -0800706 {
707 // Collisions with other suspends aren't really interesting. We want
708 // to ensure that we're the only one fiddling with the suspend count
709 // though.
710 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
711 self->ModifySuspendCount(self, +1, true);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700712 CHECK_GT(self->GetSuspendCount(), 0);
jeffhaoa77f0f62012-12-05 17:19:31 -0800713 }
Elliott Hughes475fc232011-10-25 15:00:35 -0700714
Elliott Hughes1f729aa2012-03-02 13:55:41 -0800715 VLOG(threads) << *self << " self-suspending (debugger)";
Elliott Hughes475fc232011-10-25 15:00:35 -0700716
Sebastien Hertz21e729c2014-02-18 14:16:00 +0100717 // Tell JDWP we've completed invocation and are ready to suspend.
718 DebugInvokeReq* pReq = self->GetInvokeReq();
719 DCHECK(pReq != NULL);
720 if (pReq->invoke_needed) {
721 // Clear this before signaling.
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200722 pReq->Clear();
Sebastien Hertz21e729c2014-02-18 14:16:00 +0100723
724 VLOG(jdwp) << "invoke complete, signaling";
725 MutexLock mu(self, pReq->lock);
726 pReq->cond.Signal(self);
727 }
728
Elliott Hughes475fc232011-10-25 15:00:35 -0700729 // Tell JDWP that we've completed suspension. The JDWP thread can't
730 // tell us to resume before we're fully asleep because we hold the
731 // suspend count lock.
732 Dbg::ClearWaitForEventThread();
733
jeffhaoa77f0f62012-12-05 17:19:31 -0800734 {
735 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700736 while (self->GetSuspendCount() != 0) {
jeffhaoa77f0f62012-12-05 17:19:31 -0800737 Thread::resume_cond_->Wait(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700738 if (self->GetSuspendCount() != 0) {
jeffhaoa77f0f62012-12-05 17:19:31 -0800739 // The condition was signaled but we're still suspended. This
Sebastien Hertzf272af42014-09-18 10:20:42 +0200740 // can happen when we suspend then resume all threads to
741 // update instrumentation or compute monitor info. This can
742 // also happen if the debugger lets go while a SIGQUIT thread
jeffhaoa77f0f62012-12-05 17:19:31 -0800743 // dump event is pending (assuming SignalCatcher was resumed for
744 // just long enough to try to grab the thread-suspend lock).
Sebastien Hertzf272af42014-09-18 10:20:42 +0200745 VLOG(jdwp) << *self << " still suspended after undo "
746 << "(suspend count=" << self->GetSuspendCount() << ", "
747 << "debug suspend count=" << self->GetDebugSuspendCount() << ")";
jeffhaoa77f0f62012-12-05 17:19:31 -0800748 }
Elliott Hughes475fc232011-10-25 15:00:35 -0700749 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700750 CHECK_EQ(self->GetSuspendCount(), 0);
Elliott Hughes475fc232011-10-25 15:00:35 -0700751 }
jeffhaoa77f0f62012-12-05 17:19:31 -0800752
Elliott Hughes1f729aa2012-03-02 13:55:41 -0800753 VLOG(threads) << *self << " self-reviving (debugger)";
Elliott Hughes475fc232011-10-25 15:00:35 -0700754}
755
Elliott Hughes234ab152011-10-26 14:02:26 -0700756void ThreadList::UndoDebuggerSuspensions() {
757 Thread* self = Thread::Current();
758
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800759 VLOG(threads) << *self << " UndoDebuggerSuspensions starting";
Elliott Hughes234ab152011-10-26 14:02:26 -0700760
761 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700762 MutexLock mu(self, *Locks::thread_list_lock_);
763 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700764 // Update global suspend all state for attaching threads.
765 suspend_all_count_ -= debug_suspend_all_count_;
766 debug_suspend_all_count_ = 0;
767 // Update running threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700768 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700769 if (thread == self || thread->GetDebugSuspendCount() == 0) {
Elliott Hughes234ab152011-10-26 14:02:26 -0700770 continue;
771 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700772 thread->ModifySuspendCount(self, -thread->GetDebugSuspendCount(), true);
Elliott Hughes234ab152011-10-26 14:02:26 -0700773 }
774 }
775
776 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700777 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700778 Thread::resume_cond_->Broadcast(self);
Elliott Hughes234ab152011-10-26 14:02:26 -0700779 }
780
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800781 VLOG(threads) << "UndoDebuggerSuspensions(" << *self << ") complete";
Elliott Hughes234ab152011-10-26 14:02:26 -0700782}
783
Elliott Hughese52e49b2012-04-02 16:05:44 -0700784void ThreadList::WaitForOtherNonDaemonThreadsToExit() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700785 Thread* self = Thread::Current();
786 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700787 bool all_threads_are_daemons;
788 do {
Ian Rogers120f1c72012-09-28 17:17:10 -0700789 {
790 // No more threads can be born after we start to shutdown.
791 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700792 CHECK(Runtime::Current()->IsShuttingDownLocked());
Ian Rogers120f1c72012-09-28 17:17:10 -0700793 CHECK_EQ(Runtime::Current()->NumberOfThreadsBeingBorn(), 0U);
794 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700795 all_threads_are_daemons = true;
Ian Rogers120f1c72012-09-28 17:17:10 -0700796 MutexLock mu(self, *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700797 for (const auto& thread : list_) {
Anwar Ghuloum97543682013-06-14 12:58:16 -0700798 if (thread != self && !thread->IsDaemon()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700799 all_threads_are_daemons = false;
800 break;
801 }
802 }
803 if (!all_threads_are_daemons) {
804 // Wait for another thread to exit before re-checking.
Ian Rogersc604d732012-10-14 16:09:54 -0700805 thread_exit_cond_.Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700806 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700807 } while (!all_threads_are_daemons);
Elliott Hughes038a8062011-09-18 14:12:41 -0700808}
809
810void ThreadList::SuspendAllDaemonThreads() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700811 Thread* self = Thread::Current();
812 MutexLock mu(self, *Locks::thread_list_lock_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700813 { // Tell all the daemons it's time to suspend.
Ian Rogers81d425b2012-09-27 16:03:43 -0700814 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700815 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700816 // This is only run after all non-daemon threads have exited, so the remainder should all be
817 // daemons.
Ian Rogers7e762862012-10-22 15:45:08 -0700818 CHECK(thread->IsDaemon()) << *thread;
Ian Rogers81d425b2012-09-27 16:03:43 -0700819 if (thread != self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700820 thread->ModifySuspendCount(self, +1, false);
Elliott Hughese52e49b2012-04-02 16:05:44 -0700821 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700822 }
823 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700824 // Give the threads a chance to suspend, complaining if they're slow.
825 bool have_complained = false;
826 for (int i = 0; i < 10; ++i) {
827 usleep(200 * 1000);
828 bool all_suspended = true;
Mathieu Chartier02e25112013-08-14 16:14:24 -0700829 for (const auto& thread : list_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700830 if (thread != self && thread->GetState() == kRunnable) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700831 if (!have_complained) {
832 LOG(WARNING) << "daemon thread not yet suspended: " << *thread;
833 have_complained = true;
834 }
835 all_suspended = false;
836 }
837 }
838 if (all_suspended) {
839 return;
840 }
841 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700842 LOG(ERROR) << "suspend all daemons failed";
843}
844void ThreadList::Register(Thread* self) {
845 DCHECK_EQ(self, Thread::Current());
846
847 if (VLOG_IS_ON(threads)) {
848 std::ostringstream oss;
849 self->ShortDump(oss); // We don't hold the mutator_lock_ yet and so cannot call Dump.
Ian Rogers5a9ba012014-05-19 13:28:52 -0700850 LOG(INFO) << "ThreadList::Register() " << *self << "\n" << oss.str();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700851 }
852
853 // Atomically add self to the thread list and make its thread_suspend_count_ reflect ongoing
854 // SuspendAll requests.
Ian Rogers81d425b2012-09-27 16:03:43 -0700855 MutexLock mu(self, *Locks::thread_list_lock_);
856 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700857 CHECK_GE(suspend_all_count_, debug_suspend_all_count_);
Ian Rogers2966e132014-04-02 08:34:36 -0700858 // Modify suspend count in increments of 1 to maintain invariants in ModifySuspendCount. While
859 // this isn't particularly efficient the suspend counts are most commonly 0 or 1.
860 for (int delta = debug_suspend_all_count_; delta > 0; delta--) {
861 self->ModifySuspendCount(self, +1, true);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700862 }
Ian Rogers2966e132014-04-02 08:34:36 -0700863 for (int delta = suspend_all_count_ - debug_suspend_all_count_; delta > 0; delta--) {
864 self->ModifySuspendCount(self, +1, false);
Ian Rogers01ae5802012-09-28 16:14:01 -0700865 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700866 CHECK(!Contains(self));
867 list_.push_back(self);
868}
869
870void ThreadList::Unregister(Thread* self) {
871 DCHECK_EQ(self, Thread::Current());
Ian Rogers68d8b422014-07-17 11:09:10 -0700872 CHECK_NE(self->GetState(), kRunnable);
873 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700874
875 VLOG(threads) << "ThreadList::Unregister() " << *self;
876
877 // Any time-consuming destruction, plus anything that can call back into managed code or
878 // suspend and so on, must happen at this point, and not in ~Thread.
879 self->Destroy();
880
Jeff Haoe094b872014-10-14 13:12:01 -0700881 // If tracing, remember thread id and name before thread exits.
882 Trace::StoreExitingThreadInfo(self);
883
Ian Rogersdd7624d2014-03-14 17:43:00 -0700884 uint32_t thin_lock_id = self->GetThreadId();
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800885 while (self != nullptr) {
Ian Rogerscfaa4552012-11-26 21:00:08 -0800886 // Remove and delete the Thread* while holding the thread_list_lock_ and
887 // thread_suspend_count_lock_ so that the unregistering thread cannot be suspended.
Ian Rogers0878d652013-04-18 17:38:35 -0700888 // Note: deliberately not using MutexLock that could hold a stale self pointer.
889 Locks::thread_list_lock_->ExclusiveLock(self);
Ian Rogersa2af5c72014-09-15 15:17:07 -0700890 bool removed = true;
891 if (!Contains(self)) {
892 std::ostringstream os;
893 DumpNativeStack(os, GetTid(), " native: ", nullptr);
894 LOG(ERROR) << "Request to unregister unattached thread\n" << os.str();
895 } else {
896 Locks::thread_suspend_count_lock_->ExclusiveLock(self);
897 if (!self->IsSuspended()) {
898 list_.remove(self);
899 } else {
900 // We failed to remove the thread due to a suspend request, loop and try again.
901 removed = false;
902 }
903 Locks::thread_suspend_count_lock_->ExclusiveUnlock(self);
Ian Rogers68d8b422014-07-17 11:09:10 -0700904 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700905 Locks::thread_list_lock_->ExclusiveUnlock(self);
906 if (removed) {
Ian Rogerscfaa4552012-11-26 21:00:08 -0800907 delete self;
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800908 self = nullptr;
Ian Rogerscfaa4552012-11-26 21:00:08 -0800909 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700910 }
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800911 // Release the thread ID after the thread is finished and deleted to avoid cases where we can
912 // temporarily have multiple threads with the same thread id. When this occurs, it causes
913 // problems in FindThreadByThreadId / SuspendThreadByThreadId.
914 ReleaseThreadId(nullptr, thin_lock_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700915
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700916 // Clear the TLS data, so that the underlying native thread is recognizably detached.
917 // (It may wish to reattach later.)
918 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, NULL), "detach self");
919
920 // Signal that a thread just detached.
Ian Rogers81d425b2012-09-27 16:03:43 -0700921 MutexLock mu(NULL, *Locks::thread_list_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700922 thread_exit_cond_.Signal(NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700923}
924
925void ThreadList::ForEach(void (*callback)(Thread*, void*), void* context) {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700926 for (const auto& thread : list_) {
927 callback(thread, context);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700928 }
929}
930
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800931void ThreadList::VisitRoots(RootCallback* callback, void* arg) const {
Ian Rogers81d425b2012-09-27 16:03:43 -0700932 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700933 for (const auto& thread : list_) {
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800934 thread->VisitRoots(callback, arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700935 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700936}
937
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800938class VerifyRootWrapperArg {
939 public:
940 VerifyRootWrapperArg(VerifyRootCallback* callback, void* arg) : callback_(callback), arg_(arg) {
941 }
942 VerifyRootCallback* const callback_;
943 void* const arg_;
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700944};
945
Mathieu Chartier815873e2014-02-13 18:02:13 -0800946static void VerifyRootWrapperCallback(mirror::Object** root, void* arg, uint32_t /*thread_id*/,
Mathieu Chartier7bf9f192014-04-04 11:09:41 -0700947 RootType root_type) {
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700948 VerifyRootWrapperArg* wrapperArg = reinterpret_cast<VerifyRootWrapperArg*>(arg);
Mathieu Chartier7bf9f192014-04-04 11:09:41 -0700949 wrapperArg->callback_(*root, wrapperArg->arg_, 0, NULL, root_type);
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700950}
951
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800952void ThreadList::VerifyRoots(VerifyRootCallback* callback, void* arg) const {
953 VerifyRootWrapperArg wrapper(callback, arg);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700954 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700955 for (const auto& thread : list_) {
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700956 thread->VisitRoots(VerifyRootWrapperCallback, &wrapper);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700957 }
958}
959
Ian Rogerscfaa4552012-11-26 21:00:08 -0800960uint32_t ThreadList::AllocThreadId(Thread* self) {
Chao-ying Fu9e369312014-05-21 11:20:52 -0700961 MutexLock mu(self, *Locks::allocated_thread_ids_lock_);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700962 for (size_t i = 0; i < allocated_ids_.size(); ++i) {
963 if (!allocated_ids_[i]) {
964 allocated_ids_.set(i);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700965 return i + 1; // Zero is reserved to mean "invalid".
Elliott Hughes8daa0922011-09-11 13:46:25 -0700966 }
967 }
968 LOG(FATAL) << "Out of internal thread ids";
969 return 0;
970}
971
Ian Rogerscfaa4552012-11-26 21:00:08 -0800972void ThreadList::ReleaseThreadId(Thread* self, uint32_t id) {
Chao-ying Fu9e369312014-05-21 11:20:52 -0700973 MutexLock mu(self, *Locks::allocated_thread_ids_lock_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700974 --id; // Zero is reserved to mean "invalid".
Elliott Hughes8daa0922011-09-11 13:46:25 -0700975 DCHECK(allocated_ids_[id]) << id;
976 allocated_ids_.reset(id);
977}
978
Elliott Hughes8daa0922011-09-11 13:46:25 -0700979} // namespace art