blob: 968e89d1dacf8124444feee224652407e01b2724 [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
Mathieu Chartier70a596d2014-12-17 14:56:47 -080030#include "base/histogram-inl.h"
Elliott Hughes76b61672012-12-12 17:47:30 -080031#include "base/mutex.h"
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -070032#include "base/mutex-inl.h"
Sameer Abu Asala8439542013-02-14 16:06:42 -080033#include "base/timing_logger.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070034#include "debugger.h"
Ian Rogersd9c4fc92013-10-01 19:45:43 -070035#include "jni_internal.h"
36#include "lock_word.h"
37#include "monitor.h"
38#include "scoped_thread_state_change.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080039#include "thread.h"
Jeff Haoe094b872014-10-14 13:12:01 -070040#include "trace.h"
Elliott Hughesabbe07d2012-06-05 17:42:23 -070041#include "utils.h"
Ian Rogersd9c4fc92013-10-01 19:45:43 -070042#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070043
Elliott Hughes8daa0922011-09-11 13:46:25 -070044namespace art {
45
Mathieu Chartier251755c2014-07-15 18:10:25 -070046static constexpr uint64_t kLongThreadSuspendThreshold = MsToNs(5);
47
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -080048ThreadList::ThreadList()
Chao-ying Fu9e369312014-05-21 11:20:52 -070049 : suspend_all_count_(0), debug_suspend_all_count_(0),
Mathieu Chartier70a596d2014-12-17 14:56:47 -080050 thread_exit_cond_("thread exit condition variable", *Locks::thread_list_lock_),
51 suspend_all_historam_("suspend all histogram", 16, 64) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -070052 CHECK(Monitor::IsValidLockWord(LockWord::FromThinLockId(kMaxThreadId, 1)));
Elliott Hughes8daa0922011-09-11 13:46:25 -070053}
54
55ThreadList::~ThreadList() {
Elliott Hughese52e49b2012-04-02 16:05:44 -070056 // Detach the current thread if necessary. If we failed to start, there might not be any threads.
Elliott Hughes6a144332012-04-03 13:07:11 -070057 // We need to detach the current thread here in case there's another thread waiting to join with
58 // us.
Mathieu Chartierfec72f42014-10-09 12:57:58 -070059 bool contains = false;
60 {
61 Thread* self = Thread::Current();
62 MutexLock mu(self, *Locks::thread_list_lock_);
63 contains = Contains(self);
64 }
65 if (contains) {
Elliott Hughes8daa0922011-09-11 13:46:25 -070066 Runtime::Current()->DetachCurrentThread();
67 }
Elliott Hughes6a144332012-04-03 13:07:11 -070068
69 WaitForOtherNonDaemonThreadsToExit();
Ian Rogers00f7d0e2012-07-19 15:28:27 -070070 // TODO: there's an unaddressed race here where a thread may attach during shutdown, see
71 // Thread::Init.
Elliott Hughes6a144332012-04-03 13:07:11 -070072 SuspendAllDaemonThreads();
Elliott Hughes8daa0922011-09-11 13:46:25 -070073}
74
75bool ThreadList::Contains(Thread* thread) {
76 return find(list_.begin(), list_.end(), thread) != list_.end();
77}
78
Elliott Hughesabbe07d2012-06-05 17:42:23 -070079bool ThreadList::Contains(pid_t tid) {
Mathieu Chartier02e25112013-08-14 16:14:24 -070080 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -070081 if (thread->GetTid() == tid) {
Elliott Hughesabbe07d2012-06-05 17:42:23 -070082 return true;
83 }
84 }
85 return false;
86}
87
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -070088pid_t ThreadList::GetLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -070089 return Locks::thread_list_lock_->GetExclusiveOwnerTid();
Elliott Hughesaccd83d2011-10-17 14:25:58 -070090}
91
Mathieu Chartier590fee92013-09-13 13:46:47 -070092void ThreadList::DumpNativeStacks(std::ostream& os) {
93 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
94 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -070095 os << "DUMPING THREAD " << thread->GetTid() << "\n";
Christopher Ferrisa2cee182014-04-16 19:13:59 -070096 DumpNativeStack(os, thread->GetTid(), "\t");
Mathieu Chartier590fee92013-09-13 13:46:47 -070097 os << "\n";
98 }
99}
100
Elliott Hughesc967f782012-04-16 10:23:15 -0700101void ThreadList::DumpForSigQuit(std::ostream& os) {
Mathieu Chartier70a596d2014-12-17 14:56:47 -0800102 {
103 ScopedObjectAccess soa(Thread::Current());
104 Histogram<uint64_t>::CumulativeData data;
105 suspend_all_historam_.CreateHistogram(&data);
106 suspend_all_historam_.PrintConfidenceIntervals(os, 0.99, data); // Dump time to suspend.
107 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700108 Dump(os);
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700109 DumpUnattachedThreads(os);
110}
111
Ian Rogerscfaa4552012-11-26 21:00:08 -0800112static void DumpUnattachedThread(std::ostream& os, pid_t tid) NO_THREAD_SAFETY_ANALYSIS {
113 // TODO: No thread safety analysis as DumpState with a NULL thread won't access fields, should
114 // refactor DumpState to avoid skipping analysis.
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700115 Thread::DumpState(os, NULL, tid);
116 DumpKernelStack(os, tid, " kernel: ", false);
Brian Carlstromed8b7232012-06-27 17:54:47 -0700117 // TODO: Reenable this when the native code in system_server can handle it.
118 // Currently "adb shell kill -3 `pid system_server`" will cause it to exit.
119 if (false) {
Christopher Ferrisa2cee182014-04-16 19:13:59 -0700120 DumpNativeStack(os, tid, " native: ");
Brian Carlstromed8b7232012-06-27 17:54:47 -0700121 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700122 os << "\n";
123}
124
125void ThreadList::DumpUnattachedThreads(std::ostream& os) {
126 DIR* d = opendir("/proc/self/task");
127 if (!d) {
128 return;
129 }
130
Ian Rogers50b35e22012-10-04 10:09:15 -0700131 Thread* self = Thread::Current();
Elliott Hughes4696b5b2012-10-30 10:35:10 -0700132 dirent* e;
133 while ((e = readdir(d)) != NULL) {
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700134 char* end;
Elliott Hughes4696b5b2012-10-30 10:35:10 -0700135 pid_t tid = strtol(e->d_name, &end, 10);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700136 if (!*end) {
137 bool contains;
138 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700139 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700140 contains = Contains(tid);
141 }
142 if (!contains) {
143 DumpUnattachedThread(os, tid);
144 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700145 }
146 }
147 closedir(d);
Elliott Hughesff738062012-02-03 15:00:42 -0800148}
149
Ian Rogers7b078e82014-09-10 14:44:24 -0700150// A closure used by Thread::Dump.
151class DumpCheckpoint FINAL : public Closure {
152 public:
153 explicit DumpCheckpoint(std::ostream* os) : os_(os), barrier_(0) {}
154
155 void Run(Thread* thread) OVERRIDE {
156 // Note thread and self may not be equal if thread was already suspended at the point of the
157 // request.
158 Thread* self = Thread::Current();
159 std::ostringstream local_os;
160 {
161 ScopedObjectAccess soa(self);
162 thread->Dump(local_os);
163 }
164 local_os << "\n";
165 {
166 // Use the logging lock to ensure serialization when writing to the common ostream.
167 MutexLock mu(self, *Locks::logging_lock_);
168 *os_ << local_os.str();
169 }
170 barrier_.Pass(self);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700171 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700172
173 void WaitForThreadsToRunThroughCheckpoint(size_t threads_running_checkpoint) {
174 Thread* self = Thread::Current();
175 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
Ian Rogers2156ff12014-09-13 19:20:54 -0700176 const uint32_t kWaitTimeoutMs = 10000;
177 bool timed_out = barrier_.Increment(self, threads_running_checkpoint, kWaitTimeoutMs);
178 if (timed_out) {
Nicolas Geoffraydb978712014-12-09 13:33:38 +0000179 // Avoid a recursive abort.
180 LOG((kIsDebugBuild && (gAborting == 0)) ? FATAL : ERROR)
181 << "Unexpected time out during dump checkpoint.";
Ian Rogers2156ff12014-09-13 19:20:54 -0700182 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700183 }
184
185 private:
186 // The common stream that will accumulate all the dumps.
187 std::ostream* const os_;
188 // The barrier to be passed through and for the requestor to wait upon.
189 Barrier barrier_;
190};
191
192void ThreadList::Dump(std::ostream& os) {
193 {
194 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
195 os << "DALVIK THREADS (" << list_.size() << "):\n";
196 }
197 DumpCheckpoint checkpoint(&os);
198 size_t threads_running_checkpoint = RunCheckpoint(&checkpoint);
199 checkpoint.WaitForThreadsToRunThroughCheckpoint(threads_running_checkpoint);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700200}
201
Ian Rogers50b35e22012-10-04 10:09:15 -0700202void ThreadList::AssertThreadsAreSuspended(Thread* self, Thread* ignore1, Thread* ignore2) {
203 MutexLock mu(self, *Locks::thread_list_lock_);
204 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700205 for (const auto& thread : list_) {
jeffhao725a9572012-11-13 18:20:12 -0800206 if (thread != ignore1 && thread != ignore2) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700207 CHECK(thread->IsSuspended())
208 << "\nUnsuspended thread: <<" << *thread << "\n"
209 << "self: <<" << *Thread::Current();
210 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700211 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700212}
213
Ian Rogers66aee5c2012-08-15 17:17:47 -0700214#if HAVE_TIMED_RWLOCK
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700215// Attempt to rectify locks so that we dump thread list with required locks before exiting.
Ian Rogers7b078e82014-09-10 14:44:24 -0700216static void UnsafeLogFatalForThreadSuspendAllTimeout() __attribute__((noreturn));
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100217static void UnsafeLogFatalForThreadSuspendAllTimeout() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700218 Runtime* runtime = Runtime::Current();
219 std::ostringstream ss;
220 ss << "Thread suspend timeout\n";
Mathieu Chartier5869a2c2014-10-08 14:26:23 -0700221 Locks::mutator_lock_->Dump(ss);
222 ss << "\n";
Ian Rogers7b078e82014-09-10 14:44:24 -0700223 runtime->GetThreadList()->Dump(ss);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700224 LOG(FATAL) << ss.str();
Ian Rogers719d1a32014-03-06 12:13:39 -0800225 exit(0);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700226}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700227#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700228
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800229// Unlike suspending all threads where we can wait to acquire the mutator_lock_, suspending an
230// individual thread requires polling. delay_us is the requested sleep and total_delay_us
231// accumulates the total time spent sleeping for timeouts. The first sleep is just a yield,
232// subsequently sleeps increase delay_us from 1ms to 500ms by doubling.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700233static void ThreadSuspendSleep(useconds_t* delay_us, useconds_t* total_delay_us) {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800234 useconds_t new_delay_us = (*delay_us) * 2;
235 CHECK_GE(new_delay_us, *delay_us);
236 if (new_delay_us < 500000) { // Don't allow sleeping to be more than 0.5s.
237 *delay_us = new_delay_us;
238 }
239 if (*delay_us == 0) {
240 sched_yield();
241 // Default to 1 milliseconds (note that this gets multiplied by 2 before the first sleep).
242 *delay_us = 500;
243 } else {
244 usleep(*delay_us);
245 *total_delay_us += *delay_us;
246 }
247}
248
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700249size_t ThreadList::RunCheckpoint(Closure* checkpoint_function) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700250 Thread* self = Thread::Current();
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800251 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
252 Locks::thread_list_lock_->AssertNotHeld(self);
253 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
Nicolas Geoffraydb978712014-12-09 13:33:38 +0000254 if (kDebugLocking && gAborting == 0) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700255 CHECK_NE(self->GetState(), kRunnable);
256 }
257
258 std::vector<Thread*> suspended_count_modified_threads;
259 size_t count = 0;
260 {
261 // Call a checkpoint function for each thread, threads which are suspend get their checkpoint
262 // manually called.
263 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700264 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700265 for (const auto& thread : list_) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700266 if (thread != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700267 while (true) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700268 if (thread->RequestCheckpoint(checkpoint_function)) {
Dave Allison0aded082013-11-07 13:15:11 -0800269 // This thread will run its checkpoint some time in the near future.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700270 count++;
271 break;
272 } else {
273 // We are probably suspended, try to make sure that we stay suspended.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700274 // The thread switched back to runnable.
275 if (thread->GetState() == kRunnable) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700276 // Spurious fail, try again.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700277 continue;
278 }
279 thread->ModifySuspendCount(self, +1, false);
280 suspended_count_modified_threads.push_back(thread);
281 break;
282 }
283 }
284 }
285 }
286 }
287
288 // Run the checkpoint on ourself while we wait for threads to suspend.
289 checkpoint_function->Run(self);
290
291 // Run the checkpoint on the suspended threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700292 for (const auto& thread : suspended_count_modified_threads) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700293 if (!thread->IsSuspended()) {
294 // Wait until the thread is suspended.
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800295 useconds_t total_delay_us = 0;
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700296 do {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800297 useconds_t delay_us = 100;
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700298 ThreadSuspendSleep(&delay_us, &total_delay_us);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700299 } while (!thread->IsSuspended());
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800300 // Shouldn't need to wait for longer than 1000 microseconds.
301 constexpr useconds_t kLongWaitThresholdUS = 1000;
302 if (UNLIKELY(total_delay_us > kLongWaitThresholdUS)) {
303 LOG(WARNING) << "Waited " << total_delay_us << " us for thread suspend!";
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700304 }
305 }
306 // We know for sure that the thread is suspended at this point.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700307 checkpoint_function->Run(thread);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700308 {
309 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
310 thread->ModifySuspendCount(self, -1, false);
311 }
312 }
313
Mathieu Chartier664bebf2012-11-12 16:54:11 -0800314 {
315 // Imitate ResumeAll, threads may be waiting on Thread::resume_cond_ since we raised their
316 // suspend count. Now the suspend_count_ is lowered so we must do the broadcast.
317 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
318 Thread::resume_cond_->Broadcast(self);
319 }
320
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700321 // Add one for self.
322 return count + suspended_count_modified_threads.size() + 1;
323}
324
Dave Allison39c3bfb2014-01-28 18:33:52 -0800325// Request that a checkpoint function be run on all active (non-suspended)
326// threads. Returns the number of successful requests.
327size_t ThreadList::RunCheckpointOnRunnableThreads(Closure* checkpoint_function) {
328 Thread* self = Thread::Current();
Ian Rogers7b078e82014-09-10 14:44:24 -0700329 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
330 Locks::thread_list_lock_->AssertNotHeld(self);
331 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
332 CHECK_NE(self->GetState(), kRunnable);
Dave Allison39c3bfb2014-01-28 18:33:52 -0800333
334 size_t count = 0;
335 {
336 // Call a checkpoint function for each non-suspended thread.
337 MutexLock mu(self, *Locks::thread_list_lock_);
338 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
339 for (const auto& thread : list_) {
340 if (thread != self) {
341 if (thread->RequestCheckpoint(checkpoint_function)) {
342 // This thread will run its checkpoint some time in the near future.
343 count++;
344 }
345 }
346 }
347 }
348
349 // Return the number of threads that will run the checkpoint function.
350 return count;
351}
352
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700353void ThreadList::SuspendAll() {
354 Thread* self = Thread::Current();
355
Jeff Haoc5d824a2014-07-28 18:35:38 -0700356 if (self != nullptr) {
357 VLOG(threads) << *self << " SuspendAll starting...";
358 } else {
359 VLOG(threads) << "Thread[null] SuspendAll starting...";
360 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700361 ATRACE_BEGIN("Suspending mutator threads");
Mathieu Chartier70a596d2014-12-17 14:56:47 -0800362 const uint64_t start_time = NanoTime();
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700363
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800364 Locks::mutator_lock_->AssertNotHeld(self);
365 Locks::thread_list_lock_->AssertNotHeld(self);
366 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
Jeff Haoc5d824a2014-07-28 18:35:38 -0700367 if (kDebugLocking && self != nullptr) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700368 CHECK_NE(self->GetState(), kRunnable);
369 }
370 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700371 MutexLock mu(self, *Locks::thread_list_lock_);
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800372 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
373 // Update global suspend all state for attaching threads.
374 ++suspend_all_count_;
375 // Increment everybody's suspend count (except our own).
376 for (const auto& thread : list_) {
377 if (thread == self) {
378 continue;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700379 }
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800380 VLOG(threads) << "requesting thread suspend: " << *thread;
381 thread->ModifySuspendCount(self, +1, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700382 }
383 }
384
Ian Rogers66aee5c2012-08-15 17:17:47 -0700385 // Block on the mutator lock until all Runnable threads release their share of access.
386#if HAVE_TIMED_RWLOCK
387 // Timeout if we wait more than 30 seconds.
Ian Rogers719d1a32014-03-06 12:13:39 -0800388 if (!Locks::mutator_lock_->ExclusiveLockWithTimeout(self, 30 * 1000, 0)) {
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100389 UnsafeLogFatalForThreadSuspendAllTimeout();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700390 }
Ian Rogers66aee5c2012-08-15 17:17:47 -0700391#else
Ian Rogers81d425b2012-09-27 16:03:43 -0700392 Locks::mutator_lock_->ExclusiveLock(self);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700393#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700394
Mathieu Chartier70a596d2014-12-17 14:56:47 -0800395 const uint64_t end_time = NanoTime();
396 const uint64_t suspend_time = end_time - start_time;
397 suspend_all_historam_.AdjustAndAddValue(suspend_time);
398 if (suspend_time > kLongThreadSuspendThreshold) {
399 LOG(WARNING) << "Suspending all threads took: " << PrettyDuration(suspend_time);
Mathieu Chartier251755c2014-07-15 18:10:25 -0700400 }
401
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800402 if (kDebugLocking) {
403 // Debug check that all threads are suspended.
404 AssertThreadsAreSuspended(self, self);
405 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700406
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700407 ATRACE_END();
408 ATRACE_BEGIN("Mutator threads suspended");
409
Jeff Haoc5d824a2014-07-28 18:35:38 -0700410 if (self != nullptr) {
411 VLOG(threads) << *self << " SuspendAll complete";
412 } else {
413 VLOG(threads) << "Thread[null] SuspendAll complete";
414 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700415}
416
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700417void ThreadList::ResumeAll() {
418 Thread* self = Thread::Current();
419
Jeff Haoc5d824a2014-07-28 18:35:38 -0700420 if (self != nullptr) {
421 VLOG(threads) << *self << " ResumeAll starting";
422 } else {
423 VLOG(threads) << "Thread[null] ResumeAll starting";
424 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700425
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700426 ATRACE_END();
427 ATRACE_BEGIN("Resuming mutator threads");
428
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800429 if (kDebugLocking) {
430 // Debug check that all threads are suspended.
431 AssertThreadsAreSuspended(self, self);
432 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700433
Ian Rogers81d425b2012-09-27 16:03:43 -0700434 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700435 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700436 MutexLock mu(self, *Locks::thread_list_lock_);
437 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700438 // Update global suspend all state for attaching threads.
439 --suspend_all_count_;
440 // Decrement the suspend counts for all threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700441 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700442 if (thread == self) {
443 continue;
444 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700445 thread->ModifySuspendCount(self, -1, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700446 }
447
448 // Broadcast a notification to all suspended threads, some or all of
449 // which may choose to wake up. No need to wait for them.
Jeff Haoc5d824a2014-07-28 18:35:38 -0700450 if (self != nullptr) {
451 VLOG(threads) << *self << " ResumeAll waking others";
452 } else {
453 VLOG(threads) << "Thread[null] ResumeAll waking others";
454 }
Ian Rogersc604d732012-10-14 16:09:54 -0700455 Thread::resume_cond_->Broadcast(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700456 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700457 ATRACE_END();
Jeff Haoc5d824a2014-07-28 18:35:38 -0700458
459 if (self != nullptr) {
460 VLOG(threads) << *self << " ResumeAll complete";
461 } else {
462 VLOG(threads) << "Thread[null] ResumeAll complete";
463 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700464}
465
466void ThreadList::Resume(Thread* thread, bool for_debugger) {
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800467 // This assumes there was an ATRACE_BEGIN when we suspended the thread.
468 ATRACE_END();
469
Ian Rogers81d425b2012-09-27 16:03:43 -0700470 Thread* self = Thread::Current();
471 DCHECK_NE(thread, self);
Brian Carlstromba32de42014-08-27 23:43:46 -0700472 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") starting..."
473 << (for_debugger ? " (debugger)" : "");
Elliott Hughes01158d72011-09-19 19:47:10 -0700474
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700475 {
476 // To check Contains.
Ian Rogers81d425b2012-09-27 16:03:43 -0700477 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700478 // To check IsSuspended.
Ian Rogers81d425b2012-09-27 16:03:43 -0700479 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
480 DCHECK(thread->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700481 if (!Contains(thread)) {
Brian Carlstromba32de42014-08-27 23:43:46 -0700482 // We only expect threads within the thread-list to have been suspended otherwise we can't
483 // stop such threads from delete-ing themselves.
484 LOG(ERROR) << "Resume(" << reinterpret_cast<void*>(thread)
485 << ") thread not within thread list";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700486 return;
487 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700488 thread->ModifySuspendCount(self, -1, for_debugger);
Elliott Hughes01158d72011-09-19 19:47:10 -0700489 }
490
491 {
Brian Carlstromba32de42014-08-27 23:43:46 -0700492 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") waking others";
Ian Rogers81d425b2012-09-27 16:03:43 -0700493 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700494 Thread::resume_cond_->Broadcast(self);
Elliott Hughes01158d72011-09-19 19:47:10 -0700495 }
496
Brian Carlstromba32de42014-08-27 23:43:46 -0700497 VLOG(threads) << "Resume(" << reinterpret_cast<void*>(thread) << ") complete";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700498}
Elliott Hughes01158d72011-09-19 19:47:10 -0700499
Ian Rogersc7dd2952014-10-21 23:31:19 -0700500static void ThreadSuspendByPeerWarning(Thread* self, LogSeverity severity, const char* message,
501 jobject peer) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700502 JNIEnvExt* env = self->GetJniEnv();
503 ScopedLocalRef<jstring>
504 scoped_name_string(env, (jstring)env->GetObjectField(peer,
505 WellKnownClasses::java_lang_Thread_name));
506 ScopedUtfChars scoped_name_chars(env, scoped_name_string.get());
507 if (scoped_name_chars.c_str() == NULL) {
Ian Rogersc7dd2952014-10-21 23:31:19 -0700508 LOG(severity) << message << ": " << peer;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700509 env->ExceptionClear();
510 } else {
Ian Rogersc7dd2952014-10-21 23:31:19 -0700511 LOG(severity) << message << ": " << peer << ":" << scoped_name_chars.c_str();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700512 }
513}
514
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700515Thread* ThreadList::SuspendThreadByPeer(jobject peer, bool request_suspension,
516 bool debug_suspension, bool* timed_out) {
517 static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
518 useconds_t total_delay_us = 0;
519 useconds_t delay_us = 0;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700520 *timed_out = false;
521 Thread* self = Thread::Current();
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800522 Thread* suspended_thread = nullptr;
Brian Carlstromba32de42014-08-27 23:43:46 -0700523 VLOG(threads) << "SuspendThreadByPeer starting";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700524 while (true) {
525 Thread* thread;
526 {
Ian Rogersf3d874c2014-07-17 18:52:42 -0700527 // Note: this will transition to runnable and potentially suspend. We ensure only one thread
528 // is requesting another suspend, to avoid deadlock, by requiring this function be called
529 // holding Locks::thread_list_suspend_thread_lock_. Its important this thread suspend rather
530 // than request thread suspension, to avoid potential cycles in threads requesting each other
531 // suspend.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700532 ScopedObjectAccess soa(self);
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800533 MutexLock thread_list_mu(self, *Locks::thread_list_lock_);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700534 thread = Thread::FromManagedThread(soa, peer);
Brian Carlstromba32de42014-08-27 23:43:46 -0700535 if (thread == nullptr) {
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800536 if (suspended_thread != nullptr) {
537 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
538 // If we incremented the suspend count but the thread reset its peer, we need to
539 // re-decrement it since it is shutting down and may deadlock the runtime in
540 // ThreadList::WaitForOtherNonDaemonThreadsToExit.
541 suspended_thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
542 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700543 ThreadSuspendByPeerWarning(self, WARNING, "No such thread for suspend", peer);
Brian Carlstromba32de42014-08-27 23:43:46 -0700544 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700545 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700546 if (!Contains(thread)) {
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800547 CHECK(suspended_thread == nullptr);
Brian Carlstromba32de42014-08-27 23:43:46 -0700548 VLOG(threads) << "SuspendThreadByPeer failed for unattached thread: "
549 << reinterpret_cast<void*>(thread);
550 return nullptr;
551 }
552 VLOG(threads) << "SuspendThreadByPeer found thread: " << *thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700553 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800554 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700555 if (request_suspension) {
Ian Rogers4ad5cd32014-11-11 23:08:07 -0800556 if (self->GetSuspendCount() > 0) {
557 // We hold the suspend count lock but another thread is trying to suspend us. Its not
558 // safe to try to suspend another thread in case we get a cycle. Start the loop again
559 // which will allow this thread to be suspended.
560 continue;
561 }
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800562 CHECK(suspended_thread == nullptr);
563 suspended_thread = thread;
564 suspended_thread->ModifySuspendCount(self, +1, debug_suspension);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700565 request_suspension = false;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700566 } else {
567 // If the caller isn't requesting suspension, a suspension should have already occurred.
568 CHECK_GT(thread->GetSuspendCount(), 0);
569 }
570 // IsSuspended on the current thread will fail as the current thread is changed into
571 // Runnable above. As the suspend count is now raised if this is the current thread
572 // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
573 // to just explicitly handle the current thread in the callers to this code.
574 CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
575 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
576 // count, or else we've waited and it has self suspended) or is the current thread, we're
577 // done.
578 if (thread->IsSuspended()) {
Brian Carlstromba32de42014-08-27 23:43:46 -0700579 VLOG(threads) << "SuspendThreadByPeer thread suspended: " << *thread;
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800580 if (ATRACE_ENABLED()) {
581 std::string name;
582 thread->GetThreadName(name);
583 ATRACE_BEGIN(StringPrintf("SuspendThreadByPeer suspended %s for peer=%p", name.c_str(),
584 peer).c_str());
585 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700586 return thread;
587 }
588 if (total_delay_us >= kTimeoutUs) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700589 ThreadSuspendByPeerWarning(self, FATAL, "Thread suspension timed out", peer);
Mathieu Chartier82a800d2014-12-15 15:59:49 -0800590 if (suspended_thread != nullptr) {
591 CHECK_EQ(suspended_thread, thread);
592 suspended_thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700593 }
594 *timed_out = true;
Brian Carlstromba32de42014-08-27 23:43:46 -0700595 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700596 }
597 }
598 // Release locks and come out of runnable state.
599 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700600 VLOG(threads) << "SuspendThreadByPeer sleeping to allow thread chance to suspend";
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700601 ThreadSuspendSleep(&delay_us, &total_delay_us);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700602 }
603}
604
Ian Rogersc7dd2952014-10-21 23:31:19 -0700605static void ThreadSuspendByThreadIdWarning(LogSeverity severity, const char* message,
606 uint32_t thread_id) {
607 LOG(severity) << StringPrintf("%s: %d", message, thread_id);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700608}
609
610Thread* ThreadList::SuspendThreadByThreadId(uint32_t thread_id, bool debug_suspension,
611 bool* timed_out) {
612 static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
613 useconds_t total_delay_us = 0;
614 useconds_t delay_us = 0;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700615 *timed_out = false;
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800616 Thread* suspended_thread = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700617 Thread* self = Thread::Current();
618 CHECK_NE(thread_id, kInvalidThreadId);
Brian Carlstromba32de42014-08-27 23:43:46 -0700619 VLOG(threads) << "SuspendThreadByThreadId starting";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700620 while (true) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700621 {
Ian Rogersf3d874c2014-07-17 18:52:42 -0700622 // Note: this will transition to runnable and potentially suspend. We ensure only one thread
623 // is requesting another suspend, to avoid deadlock, by requiring this function be called
624 // holding Locks::thread_list_suspend_thread_lock_. Its important this thread suspend rather
625 // than request thread suspension, to avoid potential cycles in threads requesting each other
626 // suspend.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700627 ScopedObjectAccess soa(self);
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800628 MutexLock thread_list_mu(self, *Locks::thread_list_lock_);
Ian Rogersf3d874c2014-07-17 18:52:42 -0700629 Thread* thread = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700630 for (const auto& it : list_) {
631 if (it->GetThreadId() == thread_id) {
632 thread = it;
633 break;
634 }
635 }
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800636 if (thread == nullptr) {
637 CHECK(suspended_thread == nullptr) << "Suspended thread " << suspended_thread
638 << " no longer in thread list";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700639 // There's a race in inflating a lock and the owner giving up ownership and then dying.
640 ThreadSuspendByThreadIdWarning(WARNING, "No such thread id for suspend", thread_id);
Brian Carlstromba32de42014-08-27 23:43:46 -0700641 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700642 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700643 VLOG(threads) << "SuspendThreadByThreadId found thread: " << *thread;
644 DCHECK(Contains(thread));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700645 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800646 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800647 if (suspended_thread == nullptr) {
Ian Rogers4ad5cd32014-11-11 23:08:07 -0800648 if (self->GetSuspendCount() > 0) {
649 // We hold the suspend count lock but another thread is trying to suspend us. Its not
650 // safe to try to suspend another thread in case we get a cycle. Start the loop again
651 // which will allow this thread to be suspended.
652 continue;
653 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700654 thread->ModifySuspendCount(self, +1, debug_suspension);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800655 suspended_thread = thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700656 } else {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800657 CHECK_EQ(suspended_thread, thread);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700658 // If the caller isn't requesting suspension, a suspension should have already occurred.
659 CHECK_GT(thread->GetSuspendCount(), 0);
660 }
661 // IsSuspended on the current thread will fail as the current thread is changed into
662 // Runnable above. As the suspend count is now raised if this is the current thread
663 // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
664 // to just explicitly handle the current thread in the callers to this code.
665 CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
666 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
667 // count, or else we've waited and it has self suspended) or is the current thread, we're
668 // done.
669 if (thread->IsSuspended()) {
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800670 if (ATRACE_ENABLED()) {
671 std::string name;
672 thread->GetThreadName(name);
673 ATRACE_BEGIN(StringPrintf("SuspendThreadByThreadId suspended %s id=%d",
674 name.c_str(), thread_id).c_str());
675 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700676 VLOG(threads) << "SuspendThreadByThreadId thread suspended: " << *thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700677 return thread;
678 }
679 if (total_delay_us >= kTimeoutUs) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700680 ThreadSuspendByThreadIdWarning(WARNING, "Thread suspension timed out", thread_id);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800681 if (suspended_thread != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700682 thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
683 }
684 *timed_out = true;
Brian Carlstromba32de42014-08-27 23:43:46 -0700685 return nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700686 }
687 }
688 // Release locks and come out of runnable state.
689 }
Brian Carlstromba32de42014-08-27 23:43:46 -0700690 VLOG(threads) << "SuspendThreadByThreadId sleeping to allow thread chance to suspend";
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700691 ThreadSuspendSleep(&delay_us, &total_delay_us);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700692 }
693}
694
695Thread* ThreadList::FindThreadByThreadId(uint32_t thin_lock_id) {
696 Thread* self = Thread::Current();
697 MutexLock mu(self, *Locks::thread_list_lock_);
698 for (const auto& thread : list_) {
699 if (thread->GetThreadId() == thin_lock_id) {
700 CHECK(thread == self || thread->IsSuspended());
701 return thread;
702 }
703 }
704 return NULL;
705}
706
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700707void ThreadList::SuspendAllForDebugger() {
708 Thread* self = Thread::Current();
709 Thread* debug_thread = Dbg::GetDebugThread();
710
711 VLOG(threads) << *self << " SuspendAllForDebugger starting...";
712
713 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800714 MutexLock thread_list_mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700715 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800716 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700717 // Update global suspend all state for attaching threads.
Sebastien Hertz253fa552014-10-14 17:27:15 +0200718 DCHECK_GE(suspend_all_count_, debug_suspend_all_count_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700719 ++suspend_all_count_;
720 ++debug_suspend_all_count_;
721 // Increment everybody's suspend count (except our own).
Mathieu Chartier02e25112013-08-14 16:14:24 -0700722 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700723 if (thread == self || thread == debug_thread) {
724 continue;
725 }
726 VLOG(threads) << "requesting thread suspend: " << *thread;
Ian Rogers01ae5802012-09-28 16:14:01 -0700727 thread->ModifySuspendCount(self, +1, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700728 }
729 }
730 }
731
Ian Rogers66aee5c2012-08-15 17:17:47 -0700732 // Block on the mutator lock until all Runnable threads release their share of access then
733 // immediately unlock again.
734#if HAVE_TIMED_RWLOCK
735 // Timeout if we wait more than 30 seconds.
Ian Rogersc604d732012-10-14 16:09:54 -0700736 if (!Locks::mutator_lock_->ExclusiveLockWithTimeout(self, 30 * 1000, 0)) {
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100737 UnsafeLogFatalForThreadSuspendAllTimeout();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700738 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -0700739 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700740 }
Ian Rogers66aee5c2012-08-15 17:17:47 -0700741#else
Ian Rogers81d425b2012-09-27 16:03:43 -0700742 Locks::mutator_lock_->ExclusiveLock(self);
743 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700744#endif
Ian Rogers50b35e22012-10-04 10:09:15 -0700745 AssertThreadsAreSuspended(self, self, debug_thread);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700746
Sebastien Hertzed2be172014-08-19 15:33:43 +0200747 VLOG(threads) << *self << " SuspendAllForDebugger complete";
Elliott Hughes01158d72011-09-19 19:47:10 -0700748}
749
Elliott Hughes475fc232011-10-25 15:00:35 -0700750void ThreadList::SuspendSelfForDebugger() {
751 Thread* self = Thread::Current();
Elliott Hughes01158d72011-09-19 19:47:10 -0700752
Elliott Hughes475fc232011-10-25 15:00:35 -0700753 // The debugger thread must not suspend itself due to debugger activity!
754 Thread* debug_thread = Dbg::GetDebugThread();
755 CHECK(debug_thread != NULL);
756 CHECK(self != debug_thread);
jeffhaoa77f0f62012-12-05 17:19:31 -0800757 CHECK_NE(self->GetState(), kRunnable);
758 Locks::mutator_lock_->AssertNotHeld(self);
Elliott Hughes475fc232011-10-25 15:00:35 -0700759
jeffhaoa77f0f62012-12-05 17:19:31 -0800760 {
761 // Collisions with other suspends aren't really interesting. We want
762 // to ensure that we're the only one fiddling with the suspend count
763 // though.
764 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
765 self->ModifySuspendCount(self, +1, true);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700766 CHECK_GT(self->GetSuspendCount(), 0);
jeffhaoa77f0f62012-12-05 17:19:31 -0800767 }
Elliott Hughes475fc232011-10-25 15:00:35 -0700768
Elliott Hughes1f729aa2012-03-02 13:55:41 -0800769 VLOG(threads) << *self << " self-suspending (debugger)";
Elliott Hughes475fc232011-10-25 15:00:35 -0700770
Sebastien Hertz21e729c2014-02-18 14:16:00 +0100771 // Tell JDWP we've completed invocation and are ready to suspend.
772 DebugInvokeReq* pReq = self->GetInvokeReq();
773 DCHECK(pReq != NULL);
774 if (pReq->invoke_needed) {
775 // Clear this before signaling.
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200776 pReq->Clear();
Sebastien Hertz21e729c2014-02-18 14:16:00 +0100777
778 VLOG(jdwp) << "invoke complete, signaling";
779 MutexLock mu(self, pReq->lock);
780 pReq->cond.Signal(self);
781 }
782
Elliott Hughes475fc232011-10-25 15:00:35 -0700783 // Tell JDWP that we've completed suspension. The JDWP thread can't
784 // tell us to resume before we're fully asleep because we hold the
785 // suspend count lock.
786 Dbg::ClearWaitForEventThread();
787
jeffhaoa77f0f62012-12-05 17:19:31 -0800788 {
789 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700790 while (self->GetSuspendCount() != 0) {
jeffhaoa77f0f62012-12-05 17:19:31 -0800791 Thread::resume_cond_->Wait(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700792 if (self->GetSuspendCount() != 0) {
jeffhaoa77f0f62012-12-05 17:19:31 -0800793 // The condition was signaled but we're still suspended. This
Sebastien Hertzf272af42014-09-18 10:20:42 +0200794 // can happen when we suspend then resume all threads to
795 // update instrumentation or compute monitor info. This can
796 // also happen if the debugger lets go while a SIGQUIT thread
jeffhaoa77f0f62012-12-05 17:19:31 -0800797 // dump event is pending (assuming SignalCatcher was resumed for
798 // just long enough to try to grab the thread-suspend lock).
Sebastien Hertzf272af42014-09-18 10:20:42 +0200799 VLOG(jdwp) << *self << " still suspended after undo "
800 << "(suspend count=" << self->GetSuspendCount() << ", "
801 << "debug suspend count=" << self->GetDebugSuspendCount() << ")";
jeffhaoa77f0f62012-12-05 17:19:31 -0800802 }
Elliott Hughes475fc232011-10-25 15:00:35 -0700803 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700804 CHECK_EQ(self->GetSuspendCount(), 0);
Elliott Hughes475fc232011-10-25 15:00:35 -0700805 }
jeffhaoa77f0f62012-12-05 17:19:31 -0800806
Elliott Hughes1f729aa2012-03-02 13:55:41 -0800807 VLOG(threads) << *self << " self-reviving (debugger)";
Elliott Hughes475fc232011-10-25 15:00:35 -0700808}
809
Sebastien Hertz253fa552014-10-14 17:27:15 +0200810void ThreadList::ResumeAllForDebugger() {
811 Thread* self = Thread::Current();
812 Thread* debug_thread = Dbg::GetDebugThread();
813 bool needs_resume = false;
814
815 VLOG(threads) << *self << " ResumeAllForDebugger starting...";
816
817 // Threads can't resume if we exclusively hold the mutator lock.
818 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
819
820 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800821 MutexLock thread_list_mu(self, *Locks::thread_list_lock_);
Sebastien Hertz253fa552014-10-14 17:27:15 +0200822 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800823 MutexLock suspend_count_mu(self, *Locks::thread_suspend_count_lock_);
Sebastien Hertz253fa552014-10-14 17:27:15 +0200824 // Update global suspend all state for attaching threads.
825 DCHECK_GE(suspend_all_count_, debug_suspend_all_count_);
826 needs_resume = (debug_suspend_all_count_ > 0);
827 if (needs_resume) {
828 --suspend_all_count_;
829 --debug_suspend_all_count_;
830 // Decrement everybody's suspend count (except our own).
831 for (const auto& thread : list_) {
832 if (thread == self || thread == debug_thread) {
833 continue;
834 }
835 if (thread->GetDebugSuspendCount() == 0) {
836 // This thread may have been individually resumed with ThreadReference.Resume.
837 continue;
838 }
839 VLOG(threads) << "requesting thread resume: " << *thread;
840 thread->ModifySuspendCount(self, -1, true);
841 }
842 } else {
843 // We've been asked to resume all threads without being asked to
844 // suspend them all before. Let's print a warning.
845 LOG(WARNING) << "Debugger attempted to resume all threads without "
846 << "having suspended them all before.";
847 }
848 }
849 }
850
851 if (needs_resume) {
852 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
853 Thread::resume_cond_->Broadcast(self);
854 }
855
856 VLOG(threads) << *self << " ResumeAllForDebugger complete";
857}
858
Elliott Hughes234ab152011-10-26 14:02:26 -0700859void ThreadList::UndoDebuggerSuspensions() {
860 Thread* self = Thread::Current();
861
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800862 VLOG(threads) << *self << " UndoDebuggerSuspensions starting";
Elliott Hughes234ab152011-10-26 14:02:26 -0700863
864 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700865 MutexLock mu(self, *Locks::thread_list_lock_);
866 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700867 // Update global suspend all state for attaching threads.
868 suspend_all_count_ -= debug_suspend_all_count_;
869 debug_suspend_all_count_ = 0;
870 // Update running threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700871 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700872 if (thread == self || thread->GetDebugSuspendCount() == 0) {
Elliott Hughes234ab152011-10-26 14:02:26 -0700873 continue;
874 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700875 thread->ModifySuspendCount(self, -thread->GetDebugSuspendCount(), true);
Elliott Hughes234ab152011-10-26 14:02:26 -0700876 }
877 }
878
879 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700880 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700881 Thread::resume_cond_->Broadcast(self);
Elliott Hughes234ab152011-10-26 14:02:26 -0700882 }
883
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800884 VLOG(threads) << "UndoDebuggerSuspensions(" << *self << ") complete";
Elliott Hughes234ab152011-10-26 14:02:26 -0700885}
886
Elliott Hughese52e49b2012-04-02 16:05:44 -0700887void ThreadList::WaitForOtherNonDaemonThreadsToExit() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700888 Thread* self = Thread::Current();
889 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700890 bool all_threads_are_daemons;
891 do {
Ian Rogers120f1c72012-09-28 17:17:10 -0700892 {
893 // No more threads can be born after we start to shutdown.
894 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700895 CHECK(Runtime::Current()->IsShuttingDownLocked());
Ian Rogers120f1c72012-09-28 17:17:10 -0700896 CHECK_EQ(Runtime::Current()->NumberOfThreadsBeingBorn(), 0U);
897 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700898 all_threads_are_daemons = true;
Ian Rogers120f1c72012-09-28 17:17:10 -0700899 MutexLock mu(self, *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700900 for (const auto& thread : list_) {
Anwar Ghuloum97543682013-06-14 12:58:16 -0700901 if (thread != self && !thread->IsDaemon()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700902 all_threads_are_daemons = false;
903 break;
904 }
905 }
906 if (!all_threads_are_daemons) {
907 // Wait for another thread to exit before re-checking.
Ian Rogersc604d732012-10-14 16:09:54 -0700908 thread_exit_cond_.Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700909 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700910 } while (!all_threads_are_daemons);
Elliott Hughes038a8062011-09-18 14:12:41 -0700911}
912
913void ThreadList::SuspendAllDaemonThreads() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700914 Thread* self = Thread::Current();
915 MutexLock mu(self, *Locks::thread_list_lock_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700916 { // Tell all the daemons it's time to suspend.
Ian Rogers81d425b2012-09-27 16:03:43 -0700917 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700918 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700919 // This is only run after all non-daemon threads have exited, so the remainder should all be
920 // daemons.
Ian Rogers7e762862012-10-22 15:45:08 -0700921 CHECK(thread->IsDaemon()) << *thread;
Ian Rogers81d425b2012-09-27 16:03:43 -0700922 if (thread != self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700923 thread->ModifySuspendCount(self, +1, false);
Elliott Hughese52e49b2012-04-02 16:05:44 -0700924 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700925 }
926 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700927 // Give the threads a chance to suspend, complaining if they're slow.
928 bool have_complained = false;
929 for (int i = 0; i < 10; ++i) {
930 usleep(200 * 1000);
931 bool all_suspended = true;
Mathieu Chartier02e25112013-08-14 16:14:24 -0700932 for (const auto& thread : list_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700933 if (thread != self && thread->GetState() == kRunnable) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700934 if (!have_complained) {
935 LOG(WARNING) << "daemon thread not yet suspended: " << *thread;
936 have_complained = true;
937 }
938 all_suspended = false;
939 }
940 }
941 if (all_suspended) {
942 return;
943 }
944 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700945 LOG(ERROR) << "suspend all daemons failed";
946}
947void ThreadList::Register(Thread* self) {
948 DCHECK_EQ(self, Thread::Current());
949
950 if (VLOG_IS_ON(threads)) {
951 std::ostringstream oss;
952 self->ShortDump(oss); // We don't hold the mutator_lock_ yet and so cannot call Dump.
Ian Rogers5a9ba012014-05-19 13:28:52 -0700953 LOG(INFO) << "ThreadList::Register() " << *self << "\n" << oss.str();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700954 }
955
956 // Atomically add self to the thread list and make its thread_suspend_count_ reflect ongoing
957 // SuspendAll requests.
Ian Rogers81d425b2012-09-27 16:03:43 -0700958 MutexLock mu(self, *Locks::thread_list_lock_);
959 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700960 CHECK_GE(suspend_all_count_, debug_suspend_all_count_);
Ian Rogers2966e132014-04-02 08:34:36 -0700961 // Modify suspend count in increments of 1 to maintain invariants in ModifySuspendCount. While
962 // this isn't particularly efficient the suspend counts are most commonly 0 or 1.
963 for (int delta = debug_suspend_all_count_; delta > 0; delta--) {
964 self->ModifySuspendCount(self, +1, true);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700965 }
Ian Rogers2966e132014-04-02 08:34:36 -0700966 for (int delta = suspend_all_count_ - debug_suspend_all_count_; delta > 0; delta--) {
967 self->ModifySuspendCount(self, +1, false);
Ian Rogers01ae5802012-09-28 16:14:01 -0700968 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700969 CHECK(!Contains(self));
970 list_.push_back(self);
971}
972
973void ThreadList::Unregister(Thread* self) {
974 DCHECK_EQ(self, Thread::Current());
Ian Rogers68d8b422014-07-17 11:09:10 -0700975 CHECK_NE(self->GetState(), kRunnable);
976 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700977
978 VLOG(threads) << "ThreadList::Unregister() " << *self;
979
980 // Any time-consuming destruction, plus anything that can call back into managed code or
981 // suspend and so on, must happen at this point, and not in ~Thread.
982 self->Destroy();
983
Jeff Haoe094b872014-10-14 13:12:01 -0700984 // If tracing, remember thread id and name before thread exits.
985 Trace::StoreExitingThreadInfo(self);
986
Ian Rogersdd7624d2014-03-14 17:43:00 -0700987 uint32_t thin_lock_id = self->GetThreadId();
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800988 while (self != nullptr) {
Ian Rogerscfaa4552012-11-26 21:00:08 -0800989 // Remove and delete the Thread* while holding the thread_list_lock_ and
990 // thread_suspend_count_lock_ so that the unregistering thread cannot be suspended.
Ian Rogers0878d652013-04-18 17:38:35 -0700991 // Note: deliberately not using MutexLock that could hold a stale self pointer.
992 Locks::thread_list_lock_->ExclusiveLock(self);
Ian Rogersa2af5c72014-09-15 15:17:07 -0700993 bool removed = true;
994 if (!Contains(self)) {
995 std::ostringstream os;
996 DumpNativeStack(os, GetTid(), " native: ", nullptr);
997 LOG(ERROR) << "Request to unregister unattached thread\n" << os.str();
998 } else {
999 Locks::thread_suspend_count_lock_->ExclusiveLock(self);
1000 if (!self->IsSuspended()) {
1001 list_.remove(self);
1002 } else {
1003 // We failed to remove the thread due to a suspend request, loop and try again.
1004 removed = false;
1005 }
1006 Locks::thread_suspend_count_lock_->ExclusiveUnlock(self);
Ian Rogers68d8b422014-07-17 11:09:10 -07001007 }
Ian Rogers68d8b422014-07-17 11:09:10 -07001008 Locks::thread_list_lock_->ExclusiveUnlock(self);
1009 if (removed) {
Ian Rogerscfaa4552012-11-26 21:00:08 -08001010 delete self;
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -08001011 self = nullptr;
Ian Rogerscfaa4552012-11-26 21:00:08 -08001012 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001013 }
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -08001014 // Release the thread ID after the thread is finished and deleted to avoid cases where we can
1015 // temporarily have multiple threads with the same thread id. When this occurs, it causes
1016 // problems in FindThreadByThreadId / SuspendThreadByThreadId.
1017 ReleaseThreadId(nullptr, thin_lock_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001018
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001019 // Clear the TLS data, so that the underlying native thread is recognizably detached.
1020 // (It may wish to reattach later.)
1021 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, NULL), "detach self");
1022
1023 // Signal that a thread just detached.
Ian Rogers81d425b2012-09-27 16:03:43 -07001024 MutexLock mu(NULL, *Locks::thread_list_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -07001025 thread_exit_cond_.Signal(NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001026}
1027
1028void ThreadList::ForEach(void (*callback)(Thread*, void*), void* context) {
Mathieu Chartier02e25112013-08-14 16:14:24 -07001029 for (const auto& thread : list_) {
1030 callback(thread, context);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001031 }
1032}
1033
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001034void ThreadList::VisitRoots(RootCallback* callback, void* arg) const {
Ian Rogers81d425b2012-09-27 16:03:43 -07001035 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001036 for (const auto& thread : list_) {
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001037 thread->VisitRoots(callback, arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001038 }
Elliott Hughes038a8062011-09-18 14:12:41 -07001039}
1040
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001041class VerifyRootWrapperArg {
1042 public:
1043 VerifyRootWrapperArg(VerifyRootCallback* callback, void* arg) : callback_(callback), arg_(arg) {
1044 }
1045 VerifyRootCallback* const callback_;
1046 void* const arg_;
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001047};
1048
Mathieu Chartier815873e2014-02-13 18:02:13 -08001049static void VerifyRootWrapperCallback(mirror::Object** root, void* arg, uint32_t /*thread_id*/,
Mathieu Chartier7bf9f192014-04-04 11:09:41 -07001050 RootType root_type) {
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001051 VerifyRootWrapperArg* wrapperArg = reinterpret_cast<VerifyRootWrapperArg*>(arg);
Mathieu Chartier7bf9f192014-04-04 11:09:41 -07001052 wrapperArg->callback_(*root, wrapperArg->arg_, 0, NULL, root_type);
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001053}
1054
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001055void ThreadList::VerifyRoots(VerifyRootCallback* callback, void* arg) const {
1056 VerifyRootWrapperArg wrapper(callback, arg);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07001057 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001058 for (const auto& thread : list_) {
Mathieu Chartier423d2a32013-09-12 17:33:56 -07001059 thread->VisitRoots(VerifyRootWrapperCallback, &wrapper);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -07001060 }
1061}
1062
Ian Rogerscfaa4552012-11-26 21:00:08 -08001063uint32_t ThreadList::AllocThreadId(Thread* self) {
Chao-ying Fu9e369312014-05-21 11:20:52 -07001064 MutexLock mu(self, *Locks::allocated_thread_ids_lock_);
Elliott Hughes8daa0922011-09-11 13:46:25 -07001065 for (size_t i = 0; i < allocated_ids_.size(); ++i) {
1066 if (!allocated_ids_[i]) {
1067 allocated_ids_.set(i);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001068 return i + 1; // Zero is reserved to mean "invalid".
Elliott Hughes8daa0922011-09-11 13:46:25 -07001069 }
1070 }
1071 LOG(FATAL) << "Out of internal thread ids";
1072 return 0;
1073}
1074
Ian Rogerscfaa4552012-11-26 21:00:08 -08001075void ThreadList::ReleaseThreadId(Thread* self, uint32_t id) {
Chao-ying Fu9e369312014-05-21 11:20:52 -07001076 MutexLock mu(self, *Locks::allocated_thread_ids_lock_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001077 --id; // Zero is reserved to mean "invalid".
Elliott Hughes8daa0922011-09-11 13:46:25 -07001078 DCHECK(allocated_ids_[id]) << id;
1079 allocated_ids_.reset(id);
1080}
1081
Elliott Hughes8daa0922011-09-11 13:46:25 -07001082} // namespace art