blob: 6a9111fad5d306488681de8f2da998b9df7abda6 [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
Ian Rogersc7dd2952014-10-21 23:31:19 -070028#include <sstream>
29
Elliott Hughes76b61672012-12-12 17:47:30 -080030#include "base/mutex.h"
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -070031#include "base/mutex-inl.h"
Sameer Abu Asala8439542013-02-14 16:06:42 -080032#include "base/timing_logger.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070033#include "debugger.h"
Ian Rogersd9c4fc92013-10-01 19:45:43 -070034#include "jni_internal.h"
35#include "lock_word.h"
36#include "monitor.h"
37#include "scoped_thread_state_change.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080038#include "thread.h"
Jeff Haoe094b872014-10-14 13:12:01 -070039#include "trace.h"
Elliott Hughesabbe07d2012-06-05 17:42:23 -070040#include "utils.h"
Ian Rogersd9c4fc92013-10-01 19:45:43 -070041#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070042
Elliott Hughes8daa0922011-09-11 13:46:25 -070043namespace art {
44
Mathieu Chartier251755c2014-07-15 18:10:25 -070045static constexpr uint64_t kLongThreadSuspendThreshold = MsToNs(5);
46
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -080047ThreadList::ThreadList()
Chao-ying Fu9e369312014-05-21 11:20:52 -070048 : suspend_all_count_(0), debug_suspend_all_count_(0),
Ian Rogersc604d732012-10-14 16:09:54 -070049 thread_exit_cond_("thread exit condition variable", *Locks::thread_list_lock_) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -070050 CHECK(Monitor::IsValidLockWord(LockWord::FromThinLockId(kMaxThreadId, 1)));
Elliott Hughes8daa0922011-09-11 13:46:25 -070051}
52
53ThreadList::~ThreadList() {
Elliott Hughese52e49b2012-04-02 16:05:44 -070054 // Detach the current thread if necessary. If we failed to start, there might not be any threads.
Elliott Hughes6a144332012-04-03 13:07:11 -070055 // We need to detach the current thread here in case there's another thread waiting to join with
56 // us.
Mathieu Chartierfec72f42014-10-09 12:57:58 -070057 bool contains = false;
58 {
59 Thread* self = Thread::Current();
60 MutexLock mu(self, *Locks::thread_list_lock_);
61 contains = Contains(self);
62 }
63 if (contains) {
Elliott Hughes8daa0922011-09-11 13:46:25 -070064 Runtime::Current()->DetachCurrentThread();
65 }
Elliott Hughes6a144332012-04-03 13:07:11 -070066
67 WaitForOtherNonDaemonThreadsToExit();
Ian Rogers00f7d0e2012-07-19 15:28:27 -070068 // TODO: there's an unaddressed race here where a thread may attach during shutdown, see
69 // Thread::Init.
Elliott Hughes6a144332012-04-03 13:07:11 -070070 SuspendAllDaemonThreads();
Elliott Hughes8daa0922011-09-11 13:46:25 -070071}
72
73bool ThreadList::Contains(Thread* thread) {
74 return find(list_.begin(), list_.end(), thread) != list_.end();
75}
76
Elliott Hughesabbe07d2012-06-05 17:42:23 -070077bool ThreadList::Contains(pid_t tid) {
Mathieu Chartier02e25112013-08-14 16:14:24 -070078 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -070079 if (thread->GetTid() == tid) {
Elliott Hughesabbe07d2012-06-05 17:42:23 -070080 return true;
81 }
82 }
83 return false;
84}
85
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -070086pid_t ThreadList::GetLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -070087 return Locks::thread_list_lock_->GetExclusiveOwnerTid();
Elliott Hughesaccd83d2011-10-17 14:25:58 -070088}
89
Mathieu Chartier590fee92013-09-13 13:46:47 -070090void ThreadList::DumpNativeStacks(std::ostream& os) {
91 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
92 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -070093 os << "DUMPING THREAD " << thread->GetTid() << "\n";
Christopher Ferrisa2cee182014-04-16 19:13:59 -070094 DumpNativeStack(os, thread->GetTid(), "\t");
Mathieu Chartier590fee92013-09-13 13:46:47 -070095 os << "\n";
96 }
97}
98
Elliott Hughesc967f782012-04-16 10:23:15 -070099void ThreadList::DumpForSigQuit(std::ostream& os) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700100 Dump(os);
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700101 DumpUnattachedThreads(os);
102}
103
Ian Rogerscfaa4552012-11-26 21:00:08 -0800104static void DumpUnattachedThread(std::ostream& os, pid_t tid) NO_THREAD_SAFETY_ANALYSIS {
105 // TODO: No thread safety analysis as DumpState with a NULL thread won't access fields, should
106 // refactor DumpState to avoid skipping analysis.
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700107 Thread::DumpState(os, NULL, tid);
108 DumpKernelStack(os, tid, " kernel: ", false);
Brian Carlstromed8b7232012-06-27 17:54:47 -0700109 // TODO: Reenable this when the native code in system_server can handle it.
110 // Currently "adb shell kill -3 `pid system_server`" will cause it to exit.
111 if (false) {
Christopher Ferrisa2cee182014-04-16 19:13:59 -0700112 DumpNativeStack(os, tid, " native: ");
Brian Carlstromed8b7232012-06-27 17:54:47 -0700113 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700114 os << "\n";
115}
116
117void ThreadList::DumpUnattachedThreads(std::ostream& os) {
118 DIR* d = opendir("/proc/self/task");
119 if (!d) {
120 return;
121 }
122
Ian Rogers50b35e22012-10-04 10:09:15 -0700123 Thread* self = Thread::Current();
Elliott Hughes4696b5b2012-10-30 10:35:10 -0700124 dirent* e;
125 while ((e = readdir(d)) != NULL) {
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700126 char* end;
Elliott Hughes4696b5b2012-10-30 10:35:10 -0700127 pid_t tid = strtol(e->d_name, &end, 10);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700128 if (!*end) {
129 bool contains;
130 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700131 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700132 contains = Contains(tid);
133 }
134 if (!contains) {
135 DumpUnattachedThread(os, tid);
136 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700137 }
138 }
139 closedir(d);
Elliott Hughesff738062012-02-03 15:00:42 -0800140}
141
Ian Rogers7b078e82014-09-10 14:44:24 -0700142// A closure used by Thread::Dump.
143class DumpCheckpoint FINAL : public Closure {
144 public:
145 explicit DumpCheckpoint(std::ostream* os) : os_(os), barrier_(0) {}
146
147 void Run(Thread* thread) OVERRIDE {
148 // Note thread and self may not be equal if thread was already suspended at the point of the
149 // request.
150 Thread* self = Thread::Current();
151 std::ostringstream local_os;
152 {
153 ScopedObjectAccess soa(self);
154 thread->Dump(local_os);
155 }
156 local_os << "\n";
157 {
158 // Use the logging lock to ensure serialization when writing to the common ostream.
159 MutexLock mu(self, *Locks::logging_lock_);
160 *os_ << local_os.str();
161 }
162 barrier_.Pass(self);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700163 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700164
165 void WaitForThreadsToRunThroughCheckpoint(size_t threads_running_checkpoint) {
166 Thread* self = Thread::Current();
167 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
Ian Rogers2156ff12014-09-13 19:20:54 -0700168 const uint32_t kWaitTimeoutMs = 10000;
169 bool timed_out = barrier_.Increment(self, threads_running_checkpoint, kWaitTimeoutMs);
170 if (timed_out) {
Nicolas Geoffraydb978712014-12-09 13:33:38 +0000171 // Avoid a recursive abort.
172 LOG((kIsDebugBuild && (gAborting == 0)) ? FATAL : ERROR)
173 << "Unexpected time out during dump checkpoint.";
Ian Rogers2156ff12014-09-13 19:20:54 -0700174 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700175 }
176
177 private:
178 // The common stream that will accumulate all the dumps.
179 std::ostream* const os_;
180 // The barrier to be passed through and for the requestor to wait upon.
181 Barrier barrier_;
182};
183
184void ThreadList::Dump(std::ostream& os) {
185 {
186 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
187 os << "DALVIK THREADS (" << list_.size() << "):\n";
188 }
189 DumpCheckpoint checkpoint(&os);
190 size_t threads_running_checkpoint = RunCheckpoint(&checkpoint);
191 checkpoint.WaitForThreadsToRunThroughCheckpoint(threads_running_checkpoint);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700192}
193
Ian Rogers50b35e22012-10-04 10:09:15 -0700194void ThreadList::AssertThreadsAreSuspended(Thread* self, Thread* ignore1, Thread* ignore2) {
195 MutexLock mu(self, *Locks::thread_list_lock_);
196 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700197 for (const auto& thread : list_) {
jeffhao725a9572012-11-13 18:20:12 -0800198 if (thread != ignore1 && thread != ignore2) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700199 CHECK(thread->IsSuspended())
200 << "\nUnsuspended thread: <<" << *thread << "\n"
201 << "self: <<" << *Thread::Current();
202 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700203 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700204}
205
Ian Rogers66aee5c2012-08-15 17:17:47 -0700206#if HAVE_TIMED_RWLOCK
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700207// Attempt to rectify locks so that we dump thread list with required locks before exiting.
Ian Rogers7b078e82014-09-10 14:44:24 -0700208static void UnsafeLogFatalForThreadSuspendAllTimeout() __attribute__((noreturn));
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100209static void UnsafeLogFatalForThreadSuspendAllTimeout() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700210 Runtime* runtime = Runtime::Current();
211 std::ostringstream ss;
212 ss << "Thread suspend timeout\n";
Mathieu Chartier5869a2c2014-10-08 14:26:23 -0700213 Locks::mutator_lock_->Dump(ss);
214 ss << "\n";
Ian Rogers7b078e82014-09-10 14:44:24 -0700215 runtime->GetThreadList()->Dump(ss);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700216 LOG(FATAL) << ss.str();
Ian Rogers719d1a32014-03-06 12:13:39 -0800217 exit(0);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700218}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700219#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700220
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800221// Unlike suspending all threads where we can wait to acquire the mutator_lock_, suspending an
222// individual thread requires polling. delay_us is the requested sleep and total_delay_us
223// accumulates the total time spent sleeping for timeouts. The first sleep is just a yield,
224// subsequently sleeps increase delay_us from 1ms to 500ms by doubling.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700225static void ThreadSuspendSleep(useconds_t* delay_us, useconds_t* total_delay_us) {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800226 useconds_t new_delay_us = (*delay_us) * 2;
227 CHECK_GE(new_delay_us, *delay_us);
228 if (new_delay_us < 500000) { // Don't allow sleeping to be more than 0.5s.
229 *delay_us = new_delay_us;
230 }
231 if (*delay_us == 0) {
232 sched_yield();
233 // Default to 1 milliseconds (note that this gets multiplied by 2 before the first sleep).
234 *delay_us = 500;
235 } else {
236 usleep(*delay_us);
237 *total_delay_us += *delay_us;
238 }
239}
240
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700241size_t ThreadList::RunCheckpoint(Closure* checkpoint_function) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700242 Thread* self = Thread::Current();
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800243 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
244 Locks::thread_list_lock_->AssertNotHeld(self);
245 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
Nicolas Geoffraydb978712014-12-09 13:33:38 +0000246 if (kDebugLocking && gAborting == 0) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700247 CHECK_NE(self->GetState(), kRunnable);
248 }
249
250 std::vector<Thread*> suspended_count_modified_threads;
251 size_t count = 0;
252 {
253 // Call a checkpoint function for each thread, threads which are suspend get their checkpoint
254 // manually called.
255 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700256 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700257 for (const auto& thread : list_) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700258 if (thread != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700259 while (true) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700260 if (thread->RequestCheckpoint(checkpoint_function)) {
Dave Allison0aded082013-11-07 13:15:11 -0800261 // This thread will run its checkpoint some time in the near future.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700262 count++;
263 break;
264 } else {
265 // We are probably suspended, try to make sure that we stay suspended.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700266 // The thread switched back to runnable.
267 if (thread->GetState() == kRunnable) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700268 // Spurious fail, try again.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700269 continue;
270 }
271 thread->ModifySuspendCount(self, +1, false);
272 suspended_count_modified_threads.push_back(thread);
273 break;
274 }
275 }
276 }
277 }
278 }
279
280 // Run the checkpoint on ourself while we wait for threads to suspend.
281 checkpoint_function->Run(self);
282
283 // Run the checkpoint on the suspended threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700284 for (const auto& thread : suspended_count_modified_threads) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700285 if (!thread->IsSuspended()) {
286 // Wait until the thread is suspended.
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800287 useconds_t total_delay_us = 0;
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700288 do {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800289 useconds_t delay_us = 100;
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700290 ThreadSuspendSleep(&delay_us, &total_delay_us);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700291 } while (!thread->IsSuspended());
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800292 // Shouldn't need to wait for longer than 1000 microseconds.
293 constexpr useconds_t kLongWaitThresholdUS = 1000;
294 if (UNLIKELY(total_delay_us > kLongWaitThresholdUS)) {
295 LOG(WARNING) << "Waited " << total_delay_us << " us for thread suspend!";
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700296 }
297 }
298 // We know for sure that the thread is suspended at this point.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700299 checkpoint_function->Run(thread);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700300 {
301 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
302 thread->ModifySuspendCount(self, -1, false);
303 }
304 }
305
Mathieu Chartier664bebf2012-11-12 16:54:11 -0800306 {
307 // Imitate ResumeAll, threads may be waiting on Thread::resume_cond_ since we raised their
308 // suspend count. Now the suspend_count_ is lowered so we must do the broadcast.
309 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
310 Thread::resume_cond_->Broadcast(self);
311 }
312
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700313 // Add one for self.
314 return count + suspended_count_modified_threads.size() + 1;
315}
316
Dave Allison39c3bfb2014-01-28 18:33:52 -0800317// Request that a checkpoint function be run on all active (non-suspended)
318// threads. Returns the number of successful requests.
319size_t ThreadList::RunCheckpointOnRunnableThreads(Closure* checkpoint_function) {
320 Thread* self = Thread::Current();
Ian Rogers7b078e82014-09-10 14:44:24 -0700321 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
322 Locks::thread_list_lock_->AssertNotHeld(self);
323 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
324 CHECK_NE(self->GetState(), kRunnable);
Dave Allison39c3bfb2014-01-28 18:33:52 -0800325
326 size_t count = 0;
327 {
328 // Call a checkpoint function for each non-suspended thread.
329 MutexLock mu(self, *Locks::thread_list_lock_);
330 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
331 for (const auto& thread : list_) {
332 if (thread != self) {
333 if (thread->RequestCheckpoint(checkpoint_function)) {
334 // This thread will run its checkpoint some time in the near future.
335 count++;
336 }
337 }
338 }
339 }
340
341 // Return the number of threads that will run the checkpoint function.
342 return count;
343}
344
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700345void ThreadList::SuspendAll() {
346 Thread* self = Thread::Current();
347
Jeff Haoc5d824a2014-07-28 18:35:38 -0700348 if (self != nullptr) {
349 VLOG(threads) << *self << " SuspendAll starting...";
350 } else {
351 VLOG(threads) << "Thread[null] SuspendAll starting...";
352 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700353 ATRACE_BEGIN("Suspending mutator threads");
Mathieu Chartier251755c2014-07-15 18:10:25 -0700354 uint64_t start_time = NanoTime();
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700355
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800356 Locks::mutator_lock_->AssertNotHeld(self);
357 Locks::thread_list_lock_->AssertNotHeld(self);
358 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
Jeff Haoc5d824a2014-07-28 18:35:38 -0700359 if (kDebugLocking && self != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700360 CHECK_NE(self->GetState(), kRunnable);
361 }
362 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700363 MutexLock mu(self, *Locks::thread_list_lock_);
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800364 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
365 // Update global suspend all state for attaching threads.
366 ++suspend_all_count_;
367 // Increment everybody's suspend count (except our own).
368 for (const auto& thread : list_) {
369 if (thread == self) {
370 continue;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700371 }
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800372 VLOG(threads) << "requesting thread suspend: " << *thread;
373 thread->ModifySuspendCount(self, +1, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700374 }
375 }
376
Ian Rogers66aee5c2012-08-15 17:17:47 -0700377 // Block on the mutator lock until all Runnable threads release their share of access.
378#if HAVE_TIMED_RWLOCK
379 // Timeout if we wait more than 30 seconds.
Ian Rogers719d1a32014-03-06 12:13:39 -0800380 if (!Locks::mutator_lock_->ExclusiveLockWithTimeout(self, 30 * 1000, 0)) {
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100381 UnsafeLogFatalForThreadSuspendAllTimeout();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700382 }
Ian Rogers66aee5c2012-08-15 17:17:47 -0700383#else
Ian Rogers81d425b2012-09-27 16:03:43 -0700384 Locks::mutator_lock_->ExclusiveLock(self);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700385#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700386
Mathieu Chartier251755c2014-07-15 18:10:25 -0700387 uint64_t end_time = NanoTime();
388 if (end_time - start_time > kLongThreadSuspendThreshold) {
389 LOG(WARNING) << "Suspending all threads took: " << PrettyDuration(end_time - start_time);
390 }
391
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800392 if (kDebugLocking) {
393 // Debug check that all threads are suspended.
394 AssertThreadsAreSuspended(self, self);
395 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700396
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700397 ATRACE_END();
398 ATRACE_BEGIN("Mutator threads suspended");
399
Jeff Haoc5d824a2014-07-28 18:35:38 -0700400 if (self != nullptr) {
401 VLOG(threads) << *self << " SuspendAll complete";
402 } else {
403 VLOG(threads) << "Thread[null] SuspendAll complete";
404 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700405}
406
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700407void ThreadList::ResumeAll() {
408 Thread* self = Thread::Current();
409
Jeff Haoc5d824a2014-07-28 18:35:38 -0700410 if (self != nullptr) {
411 VLOG(threads) << *self << " ResumeAll starting";
412 } else {
413 VLOG(threads) << "Thread[null] ResumeAll starting";
414 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700415
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700416 ATRACE_END();
417 ATRACE_BEGIN("Resuming mutator threads");
418
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800419 if (kDebugLocking) {
420 // Debug check that all threads are suspended.
421 AssertThreadsAreSuspended(self, self);
422 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700423
Ian Rogers81d425b2012-09-27 16:03:43 -0700424 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700425 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700426 MutexLock mu(self, *Locks::thread_list_lock_);
427 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700428 // Update global suspend all state for attaching threads.
429 --suspend_all_count_;
430 // Decrement the suspend counts for all threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700431 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700432 if (thread == self) {
433 continue;
434 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700435 thread->ModifySuspendCount(self, -1, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700436 }
437
438 // Broadcast a notification to all suspended threads, some or all of
439 // which may choose to wake up. No need to wait for them.
Jeff Haoc5d824a2014-07-28 18:35:38 -0700440 if (self != nullptr) {
441 VLOG(threads) << *self << " ResumeAll waking others";
442 } else {
443 VLOG(threads) << "Thread[null] ResumeAll waking others";
444 }
Ian Rogersc604d732012-10-14 16:09:54 -0700445 Thread::resume_cond_->Broadcast(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700446 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700447 ATRACE_END();
Jeff Haoc5d824a2014-07-28 18:35:38 -0700448
449 if (self != nullptr) {
450 VLOG(threads) << *self << " ResumeAll complete";
451 } else {
452 VLOG(threads) << "Thread[null] ResumeAll complete";
453 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700454}
455
456void ThreadList::Resume(Thread* thread, bool for_debugger) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700457 Thread* self = Thread::Current();
458 DCHECK_NE(thread, self);
Brian Carlstromba32de42014-08-27 23:43:46 -0700459 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") starting..."
460 << (for_debugger ? " (debugger)" : "");
Elliott Hughes01158d72011-09-19 19:47:10 -0700461
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700462 {
463 // To check Contains.
Ian Rogers81d425b2012-09-27 16:03:43 -0700464 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700465 // To check IsSuspended.
Ian Rogers81d425b2012-09-27 16:03:43 -0700466 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
467 DCHECK(thread->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700468 if (!Contains(thread)) {
Brian Carlstromba32de42014-08-27 23:43:46 -0700469 // We only expect threads within the thread-list to have been suspended otherwise we can't
470 // stop such threads from delete-ing themselves.
471 LOG(ERROR) << "Resume(" << reinterpret_cast<void*>(thread)
472 << ") thread not within thread list";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700473 return;
474 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700475 thread->ModifySuspendCount(self, -1, for_debugger);
Elliott Hughes01158d72011-09-19 19:47:10 -0700476 }
477
478 {
Brian Carlstromba32de42014-08-27 23:43:46 -0700479 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") waking others";
Ian Rogers81d425b2012-09-27 16:03:43 -0700480 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700481 Thread::resume_cond_->Broadcast(self);
Elliott Hughes01158d72011-09-19 19:47:10 -0700482 }
483
Brian Carlstromba32de42014-08-27 23:43:46 -0700484 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") complete";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700485}
Elliott Hughes01158d72011-09-19 19:47:10 -0700486
Ian Rogersc7dd2952014-10-21 23:31:19 -0700487static void ThreadSuspendByPeerWarning(Thread* self, LogSeverity severity, const char* message,
488 jobject peer) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700489 JNIEnvExt* env = self->GetJniEnv();
490 ScopedLocalRef<jstring>
491 scoped_name_string(env, (jstring)env->GetObjectField(peer,
492 WellKnownClasses::java_lang_Thread_name));
493 ScopedUtfChars scoped_name_chars(env, scoped_name_string.get());
494 if (scoped_name_chars.c_str() == NULL) {
Ian Rogersc7dd2952014-10-21 23:31:19 -0700495 LOG(severity) << message << ": " << peer;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700496 env->ExceptionClear();
497 } else {
Ian Rogersc7dd2952014-10-21 23:31:19 -0700498 LOG(severity) << message << ": " << peer << ":" << scoped_name_chars.c_str();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700499 }
500}
501
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700502Thread* ThreadList::SuspendThreadByPeer(jobject peer, bool request_suspension,
503 bool debug_suspension, bool* timed_out) {
504 static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
505 useconds_t total_delay_us = 0;
506 useconds_t delay_us = 0;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700507 *timed_out = false;
508 Thread* self = Thread::Current();
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800509 Thread* suspended_thread = nullptr;
Brian Carlstromba32de42014-08-27 23:43:46 -0700510 VLOG(threads) << "SuspendThreadByPeer starting";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700511 while (true) {
512 Thread* thread;
513 {
Ian Rogersf3d874c2014-07-17 18:52:42 -0700514 // Note: this will transition to runnable and potentially suspend. We ensure only one thread
515 // is requesting another suspend, to avoid deadlock, by requiring this function be called
516 // holding Locks::thread_list_suspend_thread_lock_. Its important this thread suspend rather
517 // than request thread suspension, to avoid potential cycles in threads requesting each other
518 // suspend.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700519 ScopedObjectAccess soa(self);
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800520 MutexLock thread_list_mu(self, *Locks::thread_list_lock_);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700521 thread = Thread::FromManagedThread(soa, peer);
Brian Carlstromba32de42014-08-27 23:43:46 -0700522 if (thread == nullptr) {
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800523 if (suspended_thread != nullptr) {
524 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
525 // If we incremented the suspend count but the thread reset its peer, we need to
526 // re-decrement it since it is shutting down and may deadlock the runtime in
527 // ThreadList::WaitForOtherNonDaemonThreadsToExit.
528 suspended_thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
529 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700530 ThreadSuspendByPeerWarning(self, WARNING, "No such thread for suspend", peer);
Brian Carlstromba32de42014-08-27 23:43:46 -0700531 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700532 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700533 if (!Contains(thread)) {
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800534 CHECK(suspended_thread == nullptr);
Brian Carlstromba32de42014-08-27 23:43:46 -0700535 VLOG(threads) << "SuspendThreadByPeer failed for unattached thread: "
536 << reinterpret_cast<void*>(thread);
537 return nullptr;
538 }
539 VLOG(threads) << "SuspendThreadByPeer found thread: " << *thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700540 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800541 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700542 if (request_suspension) {
Ian Rogers4ad5cd32014-11-11 23:08:07 -0800543 if (self->GetSuspendCount() > 0) {
544 // We hold the suspend count lock but another thread is trying to suspend us. Its not
545 // safe to try to suspend another thread in case we get a cycle. Start the loop again
546 // which will allow this thread to be suspended.
547 continue;
548 }
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800549 CHECK(suspended_thread == nullptr);
550 suspended_thread = thread;
551 suspended_thread->ModifySuspendCount(self, +1, debug_suspension);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700552 request_suspension = false;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700553 } else {
554 // If the caller isn't requesting suspension, a suspension should have already occurred.
555 CHECK_GT(thread->GetSuspendCount(), 0);
556 }
557 // IsSuspended on the current thread will fail as the current thread is changed into
558 // Runnable above. As the suspend count is now raised if this is the current thread
559 // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
560 // to just explicitly handle the current thread in the callers to this code.
561 CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
562 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
563 // count, or else we've waited and it has self suspended) or is the current thread, we're
564 // done.
565 if (thread->IsSuspended()) {
Brian Carlstromba32de42014-08-27 23:43:46 -0700566 VLOG(threads) << "SuspendThreadByPeer thread suspended: " << *thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700567 return thread;
568 }
569 if (total_delay_us >= kTimeoutUs) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700570 ThreadSuspendByPeerWarning(self, FATAL, "Thread suspension timed out", peer);
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800571 if (suspended_thread != nullptr) {
572 CHECK_EQ(suspended_thread, thread);
573 suspended_thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700574 }
575 *timed_out = true;
Brian Carlstromba32de42014-08-27 23:43:46 -0700576 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700577 }
578 }
579 // Release locks and come out of runnable state.
580 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700581 VLOG(threads) << "SuspendThreadByPeer sleeping to allow thread chance to suspend";
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700582 ThreadSuspendSleep(&delay_us, &total_delay_us);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700583 }
584}
585
Ian Rogersc7dd2952014-10-21 23:31:19 -0700586static void ThreadSuspendByThreadIdWarning(LogSeverity severity, const char* message,
587 uint32_t thread_id) {
588 LOG(severity) << StringPrintf("%s: %d", message, thread_id);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700589}
590
591Thread* ThreadList::SuspendThreadByThreadId(uint32_t thread_id, bool debug_suspension,
592 bool* timed_out) {
593 static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
594 useconds_t total_delay_us = 0;
595 useconds_t delay_us = 0;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700596 *timed_out = false;
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800597 Thread* suspended_thread = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700598 Thread* self = Thread::Current();
599 CHECK_NE(thread_id, kInvalidThreadId);
Brian Carlstromba32de42014-08-27 23:43:46 -0700600 VLOG(threads) << "SuspendThreadByThreadId starting";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700601 while (true) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700602 {
Ian Rogersf3d874c2014-07-17 18:52:42 -0700603 // Note: this will transition to runnable and potentially suspend. We ensure only one thread
604 // is requesting another suspend, to avoid deadlock, by requiring this function be called
605 // holding Locks::thread_list_suspend_thread_lock_. Its important this thread suspend rather
606 // than request thread suspension, to avoid potential cycles in threads requesting each other
607 // suspend.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700608 ScopedObjectAccess soa(self);
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800609 MutexLock thread_list_mu(self, *Locks::thread_list_lock_);
Ian Rogersf3d874c2014-07-17 18:52:42 -0700610 Thread* thread = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700611 for (const auto& it : list_) {
612 if (it->GetThreadId() == thread_id) {
613 thread = it;
614 break;
615 }
616 }
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800617 if (thread == nullptr) {
618 CHECK(suspended_thread == nullptr) << "Suspended thread " << suspended_thread
619 << " no longer in thread list";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700620 // There's a race in inflating a lock and the owner giving up ownership and then dying.
621 ThreadSuspendByThreadIdWarning(WARNING, "No such thread id for suspend", thread_id);
Brian Carlstromba32de42014-08-27 23:43:46 -0700622 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700623 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700624 VLOG(threads) << "SuspendThreadByThreadId found thread: " << *thread;
625 DCHECK(Contains(thread));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700626 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800627 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800628 if (suspended_thread == nullptr) {
Ian Rogers4ad5cd32014-11-11 23:08:07 -0800629 if (self->GetSuspendCount() > 0) {
630 // We hold the suspend count lock but another thread is trying to suspend us. Its not
631 // safe to try to suspend another thread in case we get a cycle. Start the loop again
632 // which will allow this thread to be suspended.
633 continue;
634 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700635 thread->ModifySuspendCount(self, +1, debug_suspension);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800636 suspended_thread = thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700637 } else {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800638 CHECK_EQ(suspended_thread, thread);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700639 // If the caller isn't requesting suspension, a suspension should have already occurred.
640 CHECK_GT(thread->GetSuspendCount(), 0);
641 }
642 // IsSuspended on the current thread will fail as the current thread is changed into
643 // Runnable above. As the suspend count is now raised if this is the current thread
644 // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
645 // to just explicitly handle the current thread in the callers to this code.
646 CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
647 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
648 // count, or else we've waited and it has self suspended) or is the current thread, we're
649 // done.
650 if (thread->IsSuspended()) {
Brian Carlstromba32de42014-08-27 23:43:46 -0700651 VLOG(threads) << "SuspendThreadByThreadId thread suspended: " << *thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700652 return thread;
653 }
654 if (total_delay_us >= kTimeoutUs) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700655 ThreadSuspendByThreadIdWarning(WARNING, "Thread suspension timed out", thread_id);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800656 if (suspended_thread != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700657 thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
658 }
659 *timed_out = true;
Brian Carlstromba32de42014-08-27 23:43:46 -0700660 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700661 }
662 }
663 // Release locks and come out of runnable state.
664 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700665 VLOG(threads) << "SuspendThreadByThreadId sleeping to allow thread chance to suspend";
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700666 ThreadSuspendSleep(&delay_us, &total_delay_us);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700667 }
668}
669
670Thread* ThreadList::FindThreadByThreadId(uint32_t thin_lock_id) {
671 Thread* self = Thread::Current();
672 MutexLock mu(self, *Locks::thread_list_lock_);
673 for (const auto& thread : list_) {
674 if (thread->GetThreadId() == thin_lock_id) {
675 CHECK(thread == self || thread->IsSuspended());
676 return thread;
677 }
678 }
679 return NULL;
680}
681
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700682void ThreadList::SuspendAllForDebugger() {
683 Thread* self = Thread::Current();
684 Thread* debug_thread = Dbg::GetDebugThread();
685
686 VLOG(threads) << *self << " SuspendAllForDebugger starting...";
687
688 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800689 MutexLock thread_list_mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700690 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800691 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700692 // Update global suspend all state for attaching threads.
Sebastien Hertz253fa552014-10-14 17:27:15 +0200693 DCHECK_GE(suspend_all_count_, debug_suspend_all_count_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700694 ++suspend_all_count_;
695 ++debug_suspend_all_count_;
696 // Increment everybody's suspend count (except our own).
Mathieu Chartier02e25112013-08-14 16:14:24 -0700697 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700698 if (thread == self || thread == debug_thread) {
699 continue;
700 }
701 VLOG(threads) << "requesting thread suspend: " << *thread;
Ian Rogers01ae5802012-09-28 16:14:01 -0700702 thread->ModifySuspendCount(self, +1, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700703 }
704 }
705 }
706
Ian Rogers66aee5c2012-08-15 17:17:47 -0700707 // Block on the mutator lock until all Runnable threads release their share of access then
708 // immediately unlock again.
709#if HAVE_TIMED_RWLOCK
710 // Timeout if we wait more than 30 seconds.
Ian Rogersc604d732012-10-14 16:09:54 -0700711 if (!Locks::mutator_lock_->ExclusiveLockWithTimeout(self, 30 * 1000, 0)) {
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100712 UnsafeLogFatalForThreadSuspendAllTimeout();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700713 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -0700714 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700715 }
Ian Rogers66aee5c2012-08-15 17:17:47 -0700716#else
Ian Rogers81d425b2012-09-27 16:03:43 -0700717 Locks::mutator_lock_->ExclusiveLock(self);
718 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700719#endif
Ian Rogers50b35e22012-10-04 10:09:15 -0700720 AssertThreadsAreSuspended(self, self, debug_thread);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700721
Sebastien Hertzed2be172014-08-19 15:33:43 +0200722 VLOG(threads) << *self << " SuspendAllForDebugger complete";
Elliott Hughes01158d72011-09-19 19:47:10 -0700723}
724
Elliott Hughes475fc232011-10-25 15:00:35 -0700725void ThreadList::SuspendSelfForDebugger() {
726 Thread* self = Thread::Current();
Elliott Hughes01158d72011-09-19 19:47:10 -0700727
Elliott Hughes475fc232011-10-25 15:00:35 -0700728 // The debugger thread must not suspend itself due to debugger activity!
729 Thread* debug_thread = Dbg::GetDebugThread();
730 CHECK(debug_thread != NULL);
731 CHECK(self != debug_thread);
jeffhaoa77f0f62012-12-05 17:19:31 -0800732 CHECK_NE(self->GetState(), kRunnable);
733 Locks::mutator_lock_->AssertNotHeld(self);
Elliott Hughes475fc232011-10-25 15:00:35 -0700734
jeffhaoa77f0f62012-12-05 17:19:31 -0800735 {
736 // Collisions with other suspends aren't really interesting. We want
737 // to ensure that we're the only one fiddling with the suspend count
738 // though.
739 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
740 self->ModifySuspendCount(self, +1, true);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700741 CHECK_GT(self->GetSuspendCount(), 0);
jeffhaoa77f0f62012-12-05 17:19:31 -0800742 }
Elliott Hughes475fc232011-10-25 15:00:35 -0700743
Elliott Hughes1f729aa2012-03-02 13:55:41 -0800744 VLOG(threads) << *self << " self-suspending (debugger)";
Elliott Hughes475fc232011-10-25 15:00:35 -0700745
Sebastien Hertz21e729c2014-02-18 14:16:00 +0100746 // Tell JDWP we've completed invocation and are ready to suspend.
747 DebugInvokeReq* pReq = self->GetInvokeReq();
748 DCHECK(pReq != NULL);
749 if (pReq->invoke_needed) {
750 // Clear this before signaling.
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200751 pReq->Clear();
Sebastien Hertz21e729c2014-02-18 14:16:00 +0100752
753 VLOG(jdwp) << "invoke complete, signaling";
754 MutexLock mu(self, pReq->lock);
755 pReq->cond.Signal(self);
756 }
757
Elliott Hughes475fc232011-10-25 15:00:35 -0700758 // Tell JDWP that we've completed suspension. The JDWP thread can't
759 // tell us to resume before we're fully asleep because we hold the
760 // suspend count lock.
761 Dbg::ClearWaitForEventThread();
762
jeffhaoa77f0f62012-12-05 17:19:31 -0800763 {
764 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700765 while (self->GetSuspendCount() != 0) {
jeffhaoa77f0f62012-12-05 17:19:31 -0800766 Thread::resume_cond_->Wait(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700767 if (self->GetSuspendCount() != 0) {
jeffhaoa77f0f62012-12-05 17:19:31 -0800768 // The condition was signaled but we're still suspended. This
Sebastien Hertzf272af42014-09-18 10:20:42 +0200769 // can happen when we suspend then resume all threads to
770 // update instrumentation or compute monitor info. This can
771 // also happen if the debugger lets go while a SIGQUIT thread
jeffhaoa77f0f62012-12-05 17:19:31 -0800772 // dump event is pending (assuming SignalCatcher was resumed for
773 // just long enough to try to grab the thread-suspend lock).
Sebastien Hertzf272af42014-09-18 10:20:42 +0200774 VLOG(jdwp) << *self << " still suspended after undo "
775 << "(suspend count=" << self->GetSuspendCount() << ", "
776 << "debug suspend count=" << self->GetDebugSuspendCount() << ")";
jeffhaoa77f0f62012-12-05 17:19:31 -0800777 }
Elliott Hughes475fc232011-10-25 15:00:35 -0700778 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700779 CHECK_EQ(self->GetSuspendCount(), 0);
Elliott Hughes475fc232011-10-25 15:00:35 -0700780 }
jeffhaoa77f0f62012-12-05 17:19:31 -0800781
Elliott Hughes1f729aa2012-03-02 13:55:41 -0800782 VLOG(threads) << *self << " self-reviving (debugger)";
Elliott Hughes475fc232011-10-25 15:00:35 -0700783}
784
Sebastien Hertz253fa552014-10-14 17:27:15 +0200785void ThreadList::ResumeAllForDebugger() {
786 Thread* self = Thread::Current();
787 Thread* debug_thread = Dbg::GetDebugThread();
788 bool needs_resume = false;
789
790 VLOG(threads) << *self << " ResumeAllForDebugger starting...";
791
792 // Threads can't resume if we exclusively hold the mutator lock.
793 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
794
795 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800796 MutexLock thread_list_mu(self, *Locks::thread_list_lock_);
Sebastien Hertz253fa552014-10-14 17:27:15 +0200797 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800798 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
Sebastien Hertz253fa552014-10-14 17:27:15 +0200799 // Update global suspend all state for attaching threads.
800 DCHECK_GE(suspend_all_count_, debug_suspend_all_count_);
801 needs_resume = (debug_suspend_all_count_ > 0);
802 if (needs_resume) {
803 --suspend_all_count_;
804 --debug_suspend_all_count_;
805 // Decrement everybody's suspend count (except our own).
806 for (const auto& thread : list_) {
807 if (thread == self || thread == debug_thread) {
808 continue;
809 }
810 if (thread->GetDebugSuspendCount() == 0) {
811 // This thread may have been individually resumed with ThreadReference.Resume.
812 continue;
813 }
814 VLOG(threads) << "requesting thread resume: " << *thread;
815 thread->ModifySuspendCount(self, -1, true);
816 }
817 } else {
818 // We've been asked to resume all threads without being asked to
819 // suspend them all before. Let's print a warning.
820 LOG(WARNING) << "Debugger attempted to resume all threads without "
821 << "having suspended them all before.";
822 }
823 }
824 }
825
826 if (needs_resume) {
827 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
828 Thread::resume_cond_->Broadcast(self);
829 }
830
831 VLOG(threads) << *self << " ResumeAllForDebugger complete";
832}
833
Elliott Hughes234ab152011-10-26 14:02:26 -0700834void ThreadList::UndoDebuggerSuspensions() {
835 Thread* self = Thread::Current();
836
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800837 VLOG(threads) << *self << " UndoDebuggerSuspensions starting";
Elliott Hughes234ab152011-10-26 14:02:26 -0700838
839 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700840 MutexLock mu(self, *Locks::thread_list_lock_);
841 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700842 // Update global suspend all state for attaching threads.
843 suspend_all_count_ -= debug_suspend_all_count_;
844 debug_suspend_all_count_ = 0;
845 // Update running threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700846 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700847 if (thread == self || thread->GetDebugSuspendCount() == 0) {
Elliott Hughes234ab152011-10-26 14:02:26 -0700848 continue;
849 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700850 thread->ModifySuspendCount(self, -thread->GetDebugSuspendCount(), true);
Elliott Hughes234ab152011-10-26 14:02:26 -0700851 }
852 }
853
854 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700855 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700856 Thread::resume_cond_->Broadcast(self);
Elliott Hughes234ab152011-10-26 14:02:26 -0700857 }
858
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800859 VLOG(threads) << "UndoDebuggerSuspensions(" << *self << ") complete";
Elliott Hughes234ab152011-10-26 14:02:26 -0700860}
861
Elliott Hughese52e49b2012-04-02 16:05:44 -0700862void ThreadList::WaitForOtherNonDaemonThreadsToExit() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700863 Thread* self = Thread::Current();
864 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700865 bool all_threads_are_daemons;
866 do {
Ian Rogers120f1c72012-09-28 17:17:10 -0700867 {
868 // No more threads can be born after we start to shutdown.
869 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700870 CHECK(Runtime::Current()->IsShuttingDownLocked());
Ian Rogers120f1c72012-09-28 17:17:10 -0700871 CHECK_EQ(Runtime::Current()->NumberOfThreadsBeingBorn(), 0U);
872 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700873 all_threads_are_daemons = true;
Ian Rogers120f1c72012-09-28 17:17:10 -0700874 MutexLock mu(self, *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700875 for (const auto& thread : list_) {
Anwar Ghuloum97543682013-06-14 12:58:16 -0700876 if (thread != self && !thread->IsDaemon()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700877 all_threads_are_daemons = false;
878 break;
879 }
880 }
881 if (!all_threads_are_daemons) {
882 // Wait for another thread to exit before re-checking.
Ian Rogersc604d732012-10-14 16:09:54 -0700883 thread_exit_cond_.Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700884 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700885 } while (!all_threads_are_daemons);
Elliott Hughes038a8062011-09-18 14:12:41 -0700886}
887
888void ThreadList::SuspendAllDaemonThreads() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700889 Thread* self = Thread::Current();
890 MutexLock mu(self, *Locks::thread_list_lock_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700891 { // Tell all the daemons it's time to suspend.
Ian Rogers81d425b2012-09-27 16:03:43 -0700892 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700893 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700894 // This is only run after all non-daemon threads have exited, so the remainder should all be
895 // daemons.
Ian Rogers7e762862012-10-22 15:45:08 -0700896 CHECK(thread->IsDaemon()) << *thread;
Ian Rogers81d425b2012-09-27 16:03:43 -0700897 if (thread != self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700898 thread->ModifySuspendCount(self, +1, false);
Elliott Hughese52e49b2012-04-02 16:05:44 -0700899 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700900 }
901 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700902 // Give the threads a chance to suspend, complaining if they're slow.
903 bool have_complained = false;
904 for (int i = 0; i < 10; ++i) {
905 usleep(200 * 1000);
906 bool all_suspended = true;
Mathieu Chartier02e25112013-08-14 16:14:24 -0700907 for (const auto& thread : list_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700908 if (thread != self && thread->GetState() == kRunnable) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700909 if (!have_complained) {
910 LOG(WARNING) << "daemon thread not yet suspended: " << *thread;
911 have_complained = true;
912 }
913 all_suspended = false;
914 }
915 }
916 if (all_suspended) {
917 return;
918 }
919 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700920 LOG(ERROR) << "suspend all daemons failed";
921}
922void ThreadList::Register(Thread* self) {
923 DCHECK_EQ(self, Thread::Current());
924
925 if (VLOG_IS_ON(threads)) {
926 std::ostringstream oss;
927 self->ShortDump(oss); // We don't hold the mutator_lock_ yet and so cannot call Dump.
Ian Rogers5a9ba012014-05-19 13:28:52 -0700928 LOG(INFO) << "ThreadList::Register() " << *self << "\n" << oss.str();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700929 }
930
931 // Atomically add self to the thread list and make its thread_suspend_count_ reflect ongoing
932 // SuspendAll requests.
Ian Rogers81d425b2012-09-27 16:03:43 -0700933 MutexLock mu(self, *Locks::thread_list_lock_);
934 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700935 CHECK_GE(suspend_all_count_, debug_suspend_all_count_);
Ian Rogers2966e132014-04-02 08:34:36 -0700936 // Modify suspend count in increments of 1 to maintain invariants in ModifySuspendCount. While
937 // this isn't particularly efficient the suspend counts are most commonly 0 or 1.
938 for (int delta = debug_suspend_all_count_; delta > 0; delta--) {
939 self->ModifySuspendCount(self, +1, true);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700940 }
Ian Rogers2966e132014-04-02 08:34:36 -0700941 for (int delta = suspend_all_count_ - debug_suspend_all_count_; delta > 0; delta--) {
942 self->ModifySuspendCount(self, +1, false);
Ian Rogers01ae5802012-09-28 16:14:01 -0700943 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700944 CHECK(!Contains(self));
945 list_.push_back(self);
946}
947
948void ThreadList::Unregister(Thread* self) {
949 DCHECK_EQ(self, Thread::Current());
Ian Rogers68d8b422014-07-17 11:09:10 -0700950 CHECK_NE(self->GetState(), kRunnable);
951 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700952
953 VLOG(threads) << "ThreadList::Unregister() " << *self;
954
955 // Any time-consuming destruction, plus anything that can call back into managed code or
956 // suspend and so on, must happen at this point, and not in ~Thread.
957 self->Destroy();
958
Jeff Haoe094b872014-10-14 13:12:01 -0700959 // If tracing, remember thread id and name before thread exits.
960 Trace::StoreExitingThreadInfo(self);
961
Ian Rogersdd7624d2014-03-14 17:43:00 -0700962 uint32_t thin_lock_id = self->GetThreadId();
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800963 while (self != nullptr) {
Ian Rogerscfaa4552012-11-26 21:00:08 -0800964 // Remove and delete the Thread* while holding the thread_list_lock_ and
965 // thread_suspend_count_lock_ so that the unregistering thread cannot be suspended.
Ian Rogers0878d652013-04-18 17:38:35 -0700966 // Note: deliberately not using MutexLock that could hold a stale self pointer.
967 Locks::thread_list_lock_->ExclusiveLock(self);
Ian Rogersa2af5c72014-09-15 15:17:07 -0700968 bool removed = true;
969 if (!Contains(self)) {
970 std::ostringstream os;
971 DumpNativeStack(os, GetTid(), " native: ", nullptr);
972 LOG(ERROR) << "Request to unregister unattached thread\n" << os.str();
973 } else {
974 Locks::thread_suspend_count_lock_->ExclusiveLock(self);
975 if (!self->IsSuspended()) {
976 list_.remove(self);
977 } else {
978 // We failed to remove the thread due to a suspend request, loop and try again.
979 removed = false;
980 }
981 Locks::thread_suspend_count_lock_->ExclusiveUnlock(self);
Ian Rogers68d8b422014-07-17 11:09:10 -0700982 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700983 Locks::thread_list_lock_->ExclusiveUnlock(self);
984 if (removed) {
Ian Rogerscfaa4552012-11-26 21:00:08 -0800985 delete self;
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800986 self = nullptr;
Ian Rogerscfaa4552012-11-26 21:00:08 -0800987 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700988 }
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800989 // Release the thread ID after the thread is finished and deleted to avoid cases where we can
990 // temporarily have multiple threads with the same thread id. When this occurs, it causes
991 // problems in FindThreadByThreadId / SuspendThreadByThreadId.
992 ReleaseThreadId(nullptr, thin_lock_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700993
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700994 // Clear the TLS data, so that the underlying native thread is recognizably detached.
995 // (It may wish to reattach later.)
996 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, NULL), "detach self");
997
998 // Signal that a thread just detached.
Ian Rogers81d425b2012-09-27 16:03:43 -0700999 MutexLock mu(NULL, *Locks::thread_list_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -07001000 thread_exit_cond_.Signal(NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001001}
1002
1003void ThreadList::ForEach(void (*callback)(Thread*, void*), void* context) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001004 for (const auto& thread : list_) {
1005 callback(thread, context);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001006 }
1007}
1008
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001009void ThreadList::VisitRoots(RootCallback* callback, void* arg) const {
Ian Rogers81d425b2012-09-27 16:03:43 -07001010 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001011 for (const auto& thread : list_) {
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001012 thread->VisitRoots(callback, arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001013 }
Elliott Hughes038a8062011-09-18 14:12:41 -07001014}
1015
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001016class VerifyRootWrapperArg {
1017 public:
1018 VerifyRootWrapperArg(VerifyRootCallback* callback, void* arg) : callback_(callback), arg_(arg) {
1019 }
1020 VerifyRootCallback* const callback_;
1021 void* const arg_;
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001022};
1023
Mathieu Chartier815873e2014-02-13 18:02:13 -08001024static void VerifyRootWrapperCallback(mirror::Object** root, void* arg, uint32_t /*thread_id*/,
Mathieu Chartier7bf9f192014-04-04 11:09:41 -07001025 RootType root_type) {
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001026 VerifyRootWrapperArg* wrapperArg = reinterpret_cast<VerifyRootWrapperArg*>(arg);
Mathieu Chartier7bf9f192014-04-04 11:09:41 -07001027 wrapperArg->callback_(*root, wrapperArg->arg_, 0, NULL, root_type);
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001028}
1029
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001030void ThreadList::VerifyRoots(VerifyRootCallback* callback, void* arg) const {
1031 VerifyRootWrapperArg wrapper(callback, arg);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07001032 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001033 for (const auto& thread : list_) {
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001034 thread->VisitRoots(VerifyRootWrapperCallback, &wrapper);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07001035 }
1036}
1037
Ian Rogerscfaa4552012-11-26 21:00:08 -08001038uint32_t ThreadList::AllocThreadId(Thread* self) {
Chao-ying Fu9e369312014-05-21 11:20:52 -07001039 MutexLock mu(self, *Locks::allocated_thread_ids_lock_);
Elliott Hughes8daa0922011-09-11 13:46:25 -07001040 for (size_t i = 0; i < allocated_ids_.size(); ++i) {
1041 if (!allocated_ids_[i]) {
1042 allocated_ids_.set(i);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001043 return i + 1; // Zero is reserved to mean "invalid".
Elliott Hughes8daa0922011-09-11 13:46:25 -07001044 }
1045 }
1046 LOG(FATAL) << "Out of internal thread ids";
1047 return 0;
1048}
1049
Ian Rogerscfaa4552012-11-26 21:00:08 -08001050void ThreadList::ReleaseThreadId(Thread* self, uint32_t id) {
Chao-ying Fu9e369312014-05-21 11:20:52 -07001051 MutexLock mu(self, *Locks::allocated_thread_ids_lock_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001052 --id; // Zero is reserved to mean "invalid".
Elliott Hughes8daa0922011-09-11 13:46:25 -07001053 DCHECK(allocated_ids_[id]) << id;
1054 allocated_ids_.reset(id);
1055}
1056
Elliott Hughes8daa0922011-09-11 13:46:25 -07001057} // namespace art