blob: dd3f11cb9e00439b484a792cedabaea952476b35 [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
Elliott Hughesabbe07d2012-06-05 17:42:23 -070019#include <dirent.h>
Ian Rogersd9c4fc92013-10-01 19:45:43 -070020#include <ScopedLocalRef.h>
21#include <ScopedUtfChars.h>
Elliott Hughesabbe07d2012-06-05 17:42:23 -070022#include <sys/types.h>
Elliott Hughes038a8062011-09-18 14:12:41 -070023#include <unistd.h>
24
Elliott Hughes76b61672012-12-12 17:47:30 -080025#include "base/mutex.h"
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -070026#include "base/mutex-inl.h"
Sameer Abu Asala8439542013-02-14 16:06:42 -080027#include "base/timing_logger.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070028#include "debugger.h"
Ian Rogersd9c4fc92013-10-01 19:45:43 -070029#include "jni_internal.h"
30#include "lock_word.h"
31#include "monitor.h"
32#include "scoped_thread_state_change.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080033#include "thread.h"
Elliott Hughesabbe07d2012-06-05 17:42:23 -070034#include "utils.h"
Ian Rogersd9c4fc92013-10-01 19:45:43 -070035#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070036
Elliott Hughes8daa0922011-09-11 13:46:25 -070037namespace art {
38
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -080039ThreadList::ThreadList()
Elliott Hughese52e49b2012-04-02 16:05:44 -070040 : allocated_ids_lock_("allocated thread ids lock"),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070041 suspend_all_count_(0), debug_suspend_all_count_(0),
Ian Rogersc604d732012-10-14 16:09:54 -070042 thread_exit_cond_("thread exit condition variable", *Locks::thread_list_lock_) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -070043 CHECK(Monitor::IsValidLockWord(LockWord::FromThinLockId(kMaxThreadId, 1)));
Elliott Hughes8daa0922011-09-11 13:46:25 -070044}
45
46ThreadList::~ThreadList() {
Elliott Hughese52e49b2012-04-02 16:05:44 -070047 // Detach the current thread if necessary. If we failed to start, there might not be any threads.
Elliott Hughes6a144332012-04-03 13:07:11 -070048 // We need to detach the current thread here in case there's another thread waiting to join with
49 // us.
Elliott Hughes8daa0922011-09-11 13:46:25 -070050 if (Contains(Thread::Current())) {
51 Runtime::Current()->DetachCurrentThread();
52 }
Elliott Hughes6a144332012-04-03 13:07:11 -070053
54 WaitForOtherNonDaemonThreadsToExit();
Ian Rogers00f7d0e2012-07-19 15:28:27 -070055 // TODO: there's an unaddressed race here where a thread may attach during shutdown, see
56 // Thread::Init.
Elliott Hughes6a144332012-04-03 13:07:11 -070057 SuspendAllDaemonThreads();
Elliott Hughes8daa0922011-09-11 13:46:25 -070058}
59
60bool ThreadList::Contains(Thread* thread) {
61 return find(list_.begin(), list_.end(), thread) != list_.end();
62}
63
Elliott Hughesabbe07d2012-06-05 17:42:23 -070064bool ThreadList::Contains(pid_t tid) {
Mathieu Chartier02e25112013-08-14 16:14:24 -070065 for (const auto& thread : list_) {
66 if (thread->tid_ == tid) {
Elliott Hughesabbe07d2012-06-05 17:42:23 -070067 return true;
68 }
69 }
70 return false;
71}
72
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -070073pid_t ThreadList::GetLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -070074 return Locks::thread_list_lock_->GetExclusiveOwnerTid();
Elliott Hughesaccd83d2011-10-17 14:25:58 -070075}
76
Mathieu Chartier590fee92013-09-13 13:46:47 -070077void ThreadList::DumpNativeStacks(std::ostream& os) {
78 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
79 for (const auto& thread : list_) {
80 os << "DUMPING THREAD " << thread->tid_ << "\n";
81 DumpNativeStack(os, thread->tid_, "\t", true);
82 os << "\n";
83 }
84}
85
Elliott Hughesc967f782012-04-16 10:23:15 -070086void ThreadList::DumpForSigQuit(std::ostream& os) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -070087 {
Ian Rogers50b35e22012-10-04 10:09:15 -070088 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -070089 DumpLocked(os);
90 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -070091 DumpUnattachedThreads(os);
92}
93
Ian Rogerscfaa4552012-11-26 21:00:08 -080094static void DumpUnattachedThread(std::ostream& os, pid_t tid) NO_THREAD_SAFETY_ANALYSIS {
95 // TODO: No thread safety analysis as DumpState with a NULL thread won't access fields, should
96 // refactor DumpState to avoid skipping analysis.
Elliott Hughesabbe07d2012-06-05 17:42:23 -070097 Thread::DumpState(os, NULL, tid);
98 DumpKernelStack(os, tid, " kernel: ", false);
Brian Carlstromed8b7232012-06-27 17:54:47 -070099 // TODO: Reenable this when the native code in system_server can handle it.
100 // Currently "adb shell kill -3 `pid system_server`" will cause it to exit.
101 if (false) {
102 DumpNativeStack(os, tid, " native: ", false);
103 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700104 os << "\n";
105}
106
107void ThreadList::DumpUnattachedThreads(std::ostream& os) {
108 DIR* d = opendir("/proc/self/task");
109 if (!d) {
110 return;
111 }
112
Ian Rogers50b35e22012-10-04 10:09:15 -0700113 Thread* self = Thread::Current();
Elliott Hughes4696b5b2012-10-30 10:35:10 -0700114 dirent* e;
115 while ((e = readdir(d)) != NULL) {
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700116 char* end;
Elliott Hughes4696b5b2012-10-30 10:35:10 -0700117 pid_t tid = strtol(e->d_name, &end, 10);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700118 if (!*end) {
119 bool contains;
120 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700121 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700122 contains = Contains(tid);
123 }
124 if (!contains) {
125 DumpUnattachedThread(os, tid);
126 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700127 }
128 }
129 closedir(d);
Elliott Hughesff738062012-02-03 15:00:42 -0800130}
131
132void ThreadList::DumpLocked(std::ostream& os) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700133 os << "DALVIK THREADS (" << list_.size() << "):\n";
Mathieu Chartier02e25112013-08-14 16:14:24 -0700134 for (const auto& thread : list_) {
135 thread->Dump(os);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700136 os << "\n";
137 }
138}
139
Ian Rogers50b35e22012-10-04 10:09:15 -0700140void ThreadList::AssertThreadsAreSuspended(Thread* self, Thread* ignore1, Thread* ignore2) {
141 MutexLock mu(self, *Locks::thread_list_lock_);
142 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700143 for (const auto& thread : list_) {
jeffhao725a9572012-11-13 18:20:12 -0800144 if (thread != ignore1 && thread != ignore2) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700145 CHECK(thread->IsSuspended())
146 << "\nUnsuspended thread: <<" << *thread << "\n"
147 << "self: <<" << *Thread::Current();
148 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700149 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700150}
151
Ian Rogers66aee5c2012-08-15 17:17:47 -0700152#if HAVE_TIMED_RWLOCK
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700153// Attempt to rectify locks so that we dump thread list with required locks before exiting.
Ian Rogers81d425b2012-09-27 16:03:43 -0700154static void UnsafeLogFatalForThreadSuspendAllTimeout(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700155 Runtime* runtime = Runtime::Current();
156 std::ostringstream ss;
157 ss << "Thread suspend timeout\n";
158 runtime->DumpLockHolders(ss);
159 ss << "\n";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700160 runtime->GetThreadList()->DumpLocked(ss);
161 LOG(FATAL) << ss.str();
162}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700163#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700164
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700165size_t ThreadList::RunCheckpoint(Closure* checkpoint_function) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700166 Thread* self = Thread::Current();
167 if (kIsDebugBuild) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800168 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700169 Locks::thread_list_lock_->AssertNotHeld(self);
170 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
171 CHECK_NE(self->GetState(), kRunnable);
172 }
173
174 std::vector<Thread*> suspended_count_modified_threads;
175 size_t count = 0;
176 {
177 // Call a checkpoint function for each thread, threads which are suspend get their checkpoint
178 // manually called.
179 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700180 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700181 for (const auto& thread : list_) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700182 if (thread != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700183 while (true) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700184 if (thread->RequestCheckpoint(checkpoint_function)) {
185 // This thread will run it's checkpoint some time in the near future.
186 count++;
187 break;
188 } else {
189 // We are probably suspended, try to make sure that we stay suspended.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700190 // The thread switched back to runnable.
191 if (thread->GetState() == kRunnable) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700192 // Spurious fail, try again.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700193 continue;
194 }
195 thread->ModifySuspendCount(self, +1, false);
196 suspended_count_modified_threads.push_back(thread);
197 break;
198 }
199 }
200 }
201 }
202 }
203
204 // Run the checkpoint on ourself while we wait for threads to suspend.
205 checkpoint_function->Run(self);
206
207 // Run the checkpoint on the suspended threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700208 for (const auto& thread : suspended_count_modified_threads) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700209 if (!thread->IsSuspended()) {
210 // Wait until the thread is suspended.
211 uint64_t start = NanoTime();
212 do {
213 // Sleep for 100us.
214 usleep(100);
215 } while (!thread->IsSuspended());
216 uint64_t end = NanoTime();
217 // Shouldn't need to wait for longer than 1 millisecond.
218 const uint64_t threshold = 1;
219 if (NsToMs(end - start) > threshold) {
Sameer Abu Asala8439542013-02-14 16:06:42 -0800220 LOG(INFO) << "Warning: waited longer than " << threshold
221 << " ms for thread suspend\n";
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700222 }
223 }
224 // We know for sure that the thread is suspended at this point.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700225 checkpoint_function->Run(thread);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700226 {
227 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
228 thread->ModifySuspendCount(self, -1, false);
229 }
230 }
231
Mathieu Chartier664bebf2012-11-12 16:54:11 -0800232 {
233 // Imitate ResumeAll, threads may be waiting on Thread::resume_cond_ since we raised their
234 // suspend count. Now the suspend_count_ is lowered so we must do the broadcast.
235 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
236 Thread::resume_cond_->Broadcast(self);
237 }
238
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700239 // Add one for self.
240 return count + suspended_count_modified_threads.size() + 1;
241}
242
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700243void ThreadList::SuspendAll() {
244 Thread* self = Thread::Current();
245
246 VLOG(threads) << *self << " SuspendAll starting...";
247
248 if (kIsDebugBuild) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700249 Locks::mutator_lock_->AssertNotHeld(self);
250 Locks::thread_list_lock_->AssertNotHeld(self);
251 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700252 CHECK_NE(self->GetState(), kRunnable);
253 }
254 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700255 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700256 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700257 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700258 // Update global suspend all state for attaching threads.
259 ++suspend_all_count_;
260 // Increment everybody's suspend count (except our own).
Mathieu Chartier02e25112013-08-14 16:14:24 -0700261 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700262 if (thread == self) {
263 continue;
264 }
265 VLOG(threads) << "requesting thread suspend: " << *thread;
Ian Rogers01ae5802012-09-28 16:14:01 -0700266 thread->ModifySuspendCount(self, +1, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700267 }
268 }
269 }
270
Ian Rogers66aee5c2012-08-15 17:17:47 -0700271 // Block on the mutator lock until all Runnable threads release their share of access.
272#if HAVE_TIMED_RWLOCK
273 // Timeout if we wait more than 30 seconds.
Ian Rogersc604d732012-10-14 16:09:54 -0700274 if (UNLIKELY(!Locks::mutator_lock_->ExclusiveLockWithTimeout(self, 30 * 1000, 0))) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700275 UnsafeLogFatalForThreadSuspendAllTimeout(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700276 }
Ian Rogers66aee5c2012-08-15 17:17:47 -0700277#else
Ian Rogers81d425b2012-09-27 16:03:43 -0700278 Locks::mutator_lock_->ExclusiveLock(self);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700279#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700280
281 // Debug check that all threads are suspended.
Ian Rogers50b35e22012-10-04 10:09:15 -0700282 AssertThreadsAreSuspended(self, self);
Elliott Hughes8d768a92011-09-14 16:35:25 -0700283
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800284 VLOG(threads) << *self << " SuspendAll complete";
Elliott Hughes8d768a92011-09-14 16:35:25 -0700285}
286
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700287void ThreadList::ResumeAll() {
288 Thread* self = Thread::Current();
289
290 VLOG(threads) << *self << " ResumeAll starting";
Ian Rogers01ae5802012-09-28 16:14:01 -0700291
292 // Debug check that all threads are suspended.
Ian Rogers50b35e22012-10-04 10:09:15 -0700293 AssertThreadsAreSuspended(self, self);
Ian Rogers01ae5802012-09-28 16:14:01 -0700294
Ian Rogers81d425b2012-09-27 16:03:43 -0700295 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700296 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700297 MutexLock mu(self, *Locks::thread_list_lock_);
298 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700299 // Update global suspend all state for attaching threads.
300 --suspend_all_count_;
301 // Decrement the suspend counts for all threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700302 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700303 if (thread == self) {
304 continue;
305 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700306 thread->ModifySuspendCount(self, -1, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700307 }
308
309 // Broadcast a notification to all suspended threads, some or all of
310 // which may choose to wake up. No need to wait for them.
311 VLOG(threads) << *self << " ResumeAll waking others";
Ian Rogersc604d732012-10-14 16:09:54 -0700312 Thread::resume_cond_->Broadcast(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700313 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700314 VLOG(threads) << *self << " ResumeAll complete";
315}
316
317void ThreadList::Resume(Thread* thread, bool for_debugger) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700318 Thread* self = Thread::Current();
319 DCHECK_NE(thread, self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700320 VLOG(threads) << "Resume(" << *thread << ") starting..." << (for_debugger ? " (debugger)" : "");
Elliott Hughes01158d72011-09-19 19:47:10 -0700321
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700322 {
323 // To check Contains.
Ian Rogers81d425b2012-09-27 16:03:43 -0700324 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700325 // To check IsSuspended.
Ian Rogers81d425b2012-09-27 16:03:43 -0700326 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
327 DCHECK(thread->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700328 if (!Contains(thread)) {
329 return;
330 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700331 thread->ModifySuspendCount(self, -1, for_debugger);
Elliott Hughes01158d72011-09-19 19:47:10 -0700332 }
333
334 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700335 VLOG(threads) << "Resume(" << *thread << ") waking others";
Ian Rogers81d425b2012-09-27 16:03:43 -0700336 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700337 Thread::resume_cond_->Broadcast(self);
Elliott Hughes01158d72011-09-19 19:47:10 -0700338 }
339
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700340 VLOG(threads) << "Resume(" << *thread << ") complete";
341}
Elliott Hughes01158d72011-09-19 19:47:10 -0700342
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700343static void ThreadSuspendByPeerWarning(Thread* self, int level, const char* message, jobject peer) {
344 JNIEnvExt* env = self->GetJniEnv();
345 ScopedLocalRef<jstring>
346 scoped_name_string(env, (jstring)env->GetObjectField(peer,
347 WellKnownClasses::java_lang_Thread_name));
348 ScopedUtfChars scoped_name_chars(env, scoped_name_string.get());
349 if (scoped_name_chars.c_str() == NULL) {
350 LOG(level) << message << ": " << peer;
351 env->ExceptionClear();
352 } else {
353 LOG(level) << message << ": " << peer << ":" << scoped_name_chars.c_str();
354 }
355}
356
357// Unlike suspending all threads where we can wait to acquire the mutator_lock_, suspending an
358// individual thread requires polling. delay_us is the requested sleep and total_delay_us
359// accumulates the total time spent sleeping for timeouts. The first sleep is just a yield,
360// subsequently sleeps increase delay_us from 1ms to 500ms by doubling.
361static void ThreadSuspendSleep(Thread* self, useconds_t* delay_us, useconds_t* total_delay_us) {
362 for (int i = kLockLevelCount - 1; i >= 0; --i) {
363 BaseMutex* held_mutex = self->GetHeldMutex(static_cast<LockLevel>(i));
364 if (held_mutex != NULL) {
365 LOG(FATAL) << "Holding " << held_mutex->GetName() << " while sleeping for thread suspension";
366 }
367 }
368 {
369 useconds_t new_delay_us = (*delay_us) * 2;
370 CHECK_GE(new_delay_us, *delay_us);
371 if (new_delay_us < 500000) { // Don't allow sleeping to be more than 0.5s.
372 *delay_us = new_delay_us;
373 }
374 }
375 if ((*delay_us) == 0) {
376 sched_yield();
377 // Default to 1 milliseconds (note that this gets multiplied by 2 before the first sleep).
378 (*delay_us) = 500;
379 } else {
380 usleep(*delay_us);
381 (*total_delay_us) += (*delay_us);
382 }
383}
384
385Thread* ThreadList::SuspendThreadByPeer(jobject peer, bool request_suspension,
386 bool debug_suspension, bool* timed_out) {
387 static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
388 useconds_t total_delay_us = 0;
389 useconds_t delay_us = 0;
390 bool did_suspend_request = false;
391 *timed_out = false;
392 Thread* self = Thread::Current();
393 while (true) {
394 Thread* thread;
395 {
396 ScopedObjectAccess soa(self);
397 MutexLock mu(self, *Locks::thread_list_lock_);
398 thread = Thread::FromManagedThread(soa, peer);
399 if (thread == NULL) {
400 ThreadSuspendByPeerWarning(self, WARNING, "No such thread for suspend", peer);
401 return NULL;
402 }
403 {
404 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
405 if (request_suspension) {
406 thread->ModifySuspendCount(self, +1, debug_suspension);
407 request_suspension = false;
408 did_suspend_request = true;
409 } else {
410 // If the caller isn't requesting suspension, a suspension should have already occurred.
411 CHECK_GT(thread->GetSuspendCount(), 0);
412 }
413 // IsSuspended on the current thread will fail as the current thread is changed into
414 // Runnable above. As the suspend count is now raised if this is the current thread
415 // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
416 // to just explicitly handle the current thread in the callers to this code.
417 CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
418 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
419 // count, or else we've waited and it has self suspended) or is the current thread, we're
420 // done.
421 if (thread->IsSuspended()) {
422 return thread;
423 }
424 if (total_delay_us >= kTimeoutUs) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700425 ThreadSuspendByPeerWarning(self, FATAL, "Thread suspension timed out", peer);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700426 if (did_suspend_request) {
427 thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
428 }
429 *timed_out = true;
430 return NULL;
431 }
432 }
433 // Release locks and come out of runnable state.
434 }
435 ThreadSuspendSleep(self, &delay_us, &total_delay_us);
436 }
437}
438
439static void ThreadSuspendByThreadIdWarning(int level, const char* message, uint32_t thread_id) {
440 LOG(level) << StringPrintf("%s: %d", message, thread_id);
441}
442
443Thread* ThreadList::SuspendThreadByThreadId(uint32_t thread_id, bool debug_suspension,
444 bool* timed_out) {
445 static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
446 useconds_t total_delay_us = 0;
447 useconds_t delay_us = 0;
448 bool did_suspend_request = false;
449 *timed_out = false;
450 Thread* self = Thread::Current();
451 CHECK_NE(thread_id, kInvalidThreadId);
452 while (true) {
453 Thread* thread = NULL;
454 {
455 ScopedObjectAccess soa(self);
456 MutexLock mu(self, *Locks::thread_list_lock_);
457 for (const auto& it : list_) {
458 if (it->GetThreadId() == thread_id) {
459 thread = it;
460 break;
461 }
462 }
463 if (thread == NULL) {
464 // There's a race in inflating a lock and the owner giving up ownership and then dying.
465 ThreadSuspendByThreadIdWarning(WARNING, "No such thread id for suspend", thread_id);
466 return NULL;
467 }
468 {
469 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
470 if (!did_suspend_request) {
471 thread->ModifySuspendCount(self, +1, debug_suspension);
472 did_suspend_request = true;
473 } else {
474 // If the caller isn't requesting suspension, a suspension should have already occurred.
475 CHECK_GT(thread->GetSuspendCount(), 0);
476 }
477 // IsSuspended on the current thread will fail as the current thread is changed into
478 // Runnable above. As the suspend count is now raised if this is the current thread
479 // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
480 // to just explicitly handle the current thread in the callers to this code.
481 CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
482 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
483 // count, or else we've waited and it has self suspended) or is the current thread, we're
484 // done.
485 if (thread->IsSuspended()) {
486 return thread;
487 }
488 if (total_delay_us >= kTimeoutUs) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700489 ThreadSuspendByThreadIdWarning(WARNING, "Thread suspension timed out", thread_id);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700490 if (did_suspend_request) {
491 thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
492 }
493 *timed_out = true;
494 return NULL;
495 }
496 }
497 // Release locks and come out of runnable state.
498 }
499 ThreadSuspendSleep(self, &delay_us, &total_delay_us);
500 }
501}
502
503Thread* ThreadList::FindThreadByThreadId(uint32_t thin_lock_id) {
504 Thread* self = Thread::Current();
505 MutexLock mu(self, *Locks::thread_list_lock_);
506 for (const auto& thread : list_) {
507 if (thread->GetThreadId() == thin_lock_id) {
508 CHECK(thread == self || thread->IsSuspended());
509 return thread;
510 }
511 }
512 return NULL;
513}
514
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700515void ThreadList::SuspendAllForDebugger() {
516 Thread* self = Thread::Current();
517 Thread* debug_thread = Dbg::GetDebugThread();
518
519 VLOG(threads) << *self << " SuspendAllForDebugger starting...";
520
521 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700522 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700523 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700524 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700525 // Update global suspend all state for attaching threads.
526 ++suspend_all_count_;
527 ++debug_suspend_all_count_;
528 // Increment everybody's suspend count (except our own).
Mathieu Chartier02e25112013-08-14 16:14:24 -0700529 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700530 if (thread == self || thread == debug_thread) {
531 continue;
532 }
533 VLOG(threads) << "requesting thread suspend: " << *thread;
Ian Rogers01ae5802012-09-28 16:14:01 -0700534 thread->ModifySuspendCount(self, +1, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700535 }
536 }
537 }
538
Ian Rogers66aee5c2012-08-15 17:17:47 -0700539 // Block on the mutator lock until all Runnable threads release their share of access then
540 // immediately unlock again.
541#if HAVE_TIMED_RWLOCK
542 // Timeout if we wait more than 30 seconds.
Ian Rogersc604d732012-10-14 16:09:54 -0700543 if (!Locks::mutator_lock_->ExclusiveLockWithTimeout(self, 30 * 1000, 0)) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700544 UnsafeLogFatalForThreadSuspendAllTimeout(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700545 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -0700546 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700547 }
Ian Rogers66aee5c2012-08-15 17:17:47 -0700548#else
Ian Rogers81d425b2012-09-27 16:03:43 -0700549 Locks::mutator_lock_->ExclusiveLock(self);
550 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700551#endif
Ian Rogers50b35e22012-10-04 10:09:15 -0700552 AssertThreadsAreSuspended(self, self, debug_thread);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700553
554 VLOG(threads) << *self << " SuspendAll complete";
Elliott Hughes01158d72011-09-19 19:47:10 -0700555}
556
Elliott Hughes475fc232011-10-25 15:00:35 -0700557void ThreadList::SuspendSelfForDebugger() {
558 Thread* self = Thread::Current();
Elliott Hughes01158d72011-09-19 19:47:10 -0700559
Elliott Hughes475fc232011-10-25 15:00:35 -0700560 // The debugger thread must not suspend itself due to debugger activity!
561 Thread* debug_thread = Dbg::GetDebugThread();
562 CHECK(debug_thread != NULL);
563 CHECK(self != debug_thread);
jeffhaoa77f0f62012-12-05 17:19:31 -0800564 CHECK_NE(self->GetState(), kRunnable);
565 Locks::mutator_lock_->AssertNotHeld(self);
Elliott Hughes475fc232011-10-25 15:00:35 -0700566
jeffhaoa77f0f62012-12-05 17:19:31 -0800567 {
568 // Collisions with other suspends aren't really interesting. We want
569 // to ensure that we're the only one fiddling with the suspend count
570 // though.
571 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
572 self->ModifySuspendCount(self, +1, true);
573 CHECK_GT(self->suspend_count_, 0);
574 }
Elliott Hughes475fc232011-10-25 15:00:35 -0700575
Elliott Hughes1f729aa2012-03-02 13:55:41 -0800576 VLOG(threads) << *self << " self-suspending (debugger)";
Elliott Hughes475fc232011-10-25 15:00:35 -0700577
578 // Tell JDWP that we've completed suspension. The JDWP thread can't
579 // tell us to resume before we're fully asleep because we hold the
580 // suspend count lock.
581 Dbg::ClearWaitForEventThread();
582
jeffhaoa77f0f62012-12-05 17:19:31 -0800583 {
584 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
585 while (self->suspend_count_ != 0) {
586 Thread::resume_cond_->Wait(self);
587 if (self->suspend_count_ != 0) {
588 // The condition was signaled but we're still suspended. This
589 // can happen if the debugger lets go while a SIGQUIT thread
590 // dump event is pending (assuming SignalCatcher was resumed for
591 // just long enough to try to grab the thread-suspend lock).
592 LOG(DEBUG) << *self << " still suspended after undo "
593 << "(suspend count=" << self->suspend_count_ << ")";
594 }
Elliott Hughes475fc232011-10-25 15:00:35 -0700595 }
jeffhaoa77f0f62012-12-05 17:19:31 -0800596 CHECK_EQ(self->suspend_count_, 0);
Elliott Hughes475fc232011-10-25 15:00:35 -0700597 }
jeffhaoa77f0f62012-12-05 17:19:31 -0800598
Elliott Hughes1f729aa2012-03-02 13:55:41 -0800599 VLOG(threads) << *self << " self-reviving (debugger)";
Elliott Hughes475fc232011-10-25 15:00:35 -0700600}
601
Elliott Hughes234ab152011-10-26 14:02:26 -0700602void ThreadList::UndoDebuggerSuspensions() {
603 Thread* self = Thread::Current();
604
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800605 VLOG(threads) << *self << " UndoDebuggerSuspensions starting";
Elliott Hughes234ab152011-10-26 14:02:26 -0700606
607 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700608 MutexLock mu(self, *Locks::thread_list_lock_);
609 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700610 // Update global suspend all state for attaching threads.
611 suspend_all_count_ -= debug_suspend_all_count_;
612 debug_suspend_all_count_ = 0;
613 // Update running threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700614 for (const auto& thread : list_) {
Elliott Hughes234ab152011-10-26 14:02:26 -0700615 if (thread == self || thread->debug_suspend_count_ == 0) {
616 continue;
617 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700618 thread->ModifySuspendCount(self, -thread->debug_suspend_count_, true);
Elliott Hughes234ab152011-10-26 14:02:26 -0700619 }
620 }
621
622 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700623 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700624 Thread::resume_cond_->Broadcast(self);
Elliott Hughes234ab152011-10-26 14:02:26 -0700625 }
626
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800627 VLOG(threads) << "UndoDebuggerSuspensions(" << *self << ") complete";
Elliott Hughes234ab152011-10-26 14:02:26 -0700628}
629
Elliott Hughese52e49b2012-04-02 16:05:44 -0700630void ThreadList::WaitForOtherNonDaemonThreadsToExit() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700631 Thread* self = Thread::Current();
632 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700633 bool all_threads_are_daemons;
634 do {
Ian Rogers120f1c72012-09-28 17:17:10 -0700635 {
636 // No more threads can be born after we start to shutdown.
637 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700638 CHECK(Runtime::Current()->IsShuttingDownLocked());
Ian Rogers120f1c72012-09-28 17:17:10 -0700639 CHECK_EQ(Runtime::Current()->NumberOfThreadsBeingBorn(), 0U);
640 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700641 all_threads_are_daemons = true;
Ian Rogers120f1c72012-09-28 17:17:10 -0700642 MutexLock mu(self, *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700643 for (const auto& thread : list_) {
Anwar Ghuloum97543682013-06-14 12:58:16 -0700644 if (thread != self && !thread->IsDaemon()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700645 all_threads_are_daemons = false;
646 break;
647 }
648 }
649 if (!all_threads_are_daemons) {
650 // Wait for another thread to exit before re-checking.
Ian Rogersc604d732012-10-14 16:09:54 -0700651 thread_exit_cond_.Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700652 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700653 } while (!all_threads_are_daemons);
Elliott Hughes038a8062011-09-18 14:12:41 -0700654}
655
656void ThreadList::SuspendAllDaemonThreads() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700657 Thread* self = Thread::Current();
658 MutexLock mu(self, *Locks::thread_list_lock_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700659 { // Tell all the daemons it's time to suspend.
Ian Rogers81d425b2012-09-27 16:03:43 -0700660 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700661 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700662 // This is only run after all non-daemon threads have exited, so the remainder should all be
663 // daemons.
Ian Rogers7e762862012-10-22 15:45:08 -0700664 CHECK(thread->IsDaemon()) << *thread;
Ian Rogers81d425b2012-09-27 16:03:43 -0700665 if (thread != self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700666 thread->ModifySuspendCount(self, +1, false);
Elliott Hughese52e49b2012-04-02 16:05:44 -0700667 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700668 }
669 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700670 // Give the threads a chance to suspend, complaining if they're slow.
671 bool have_complained = false;
672 for (int i = 0; i < 10; ++i) {
673 usleep(200 * 1000);
674 bool all_suspended = true;
Mathieu Chartier02e25112013-08-14 16:14:24 -0700675 for (const auto& thread : list_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700676 if (thread != self && thread->GetState() == kRunnable) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700677 if (!have_complained) {
678 LOG(WARNING) << "daemon thread not yet suspended: " << *thread;
679 have_complained = true;
680 }
681 all_suspended = false;
682 }
683 }
684 if (all_suspended) {
685 return;
686 }
687 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700688 LOG(ERROR) << "suspend all daemons failed";
689}
690void ThreadList::Register(Thread* self) {
691 DCHECK_EQ(self, Thread::Current());
692
693 if (VLOG_IS_ON(threads)) {
694 std::ostringstream oss;
695 self->ShortDump(oss); // We don't hold the mutator_lock_ yet and so cannot call Dump.
696 LOG(INFO) << "ThreadList::Register() " << *self << "\n" << oss;
697 }
698
699 // Atomically add self to the thread list and make its thread_suspend_count_ reflect ongoing
700 // SuspendAll requests.
Ian Rogers81d425b2012-09-27 16:03:43 -0700701 MutexLock mu(self, *Locks::thread_list_lock_);
702 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700703 self->suspend_count_ = suspend_all_count_;
704 self->debug_suspend_count_ = debug_suspend_all_count_;
Ian Rogers01ae5802012-09-28 16:14:01 -0700705 if (self->suspend_count_ > 0) {
706 self->AtomicSetFlag(kSuspendRequest);
707 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700708 CHECK(!Contains(self));
709 list_.push_back(self);
710}
711
712void ThreadList::Unregister(Thread* self) {
713 DCHECK_EQ(self, Thread::Current());
714
715 VLOG(threads) << "ThreadList::Unregister() " << *self;
716
717 // Any time-consuming destruction, plus anything that can call back into managed code or
718 // suspend and so on, must happen at this point, and not in ~Thread.
719 self->Destroy();
720
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700721 uint32_t thin_lock_id = self->thin_lock_thread_id_;
722 self->thin_lock_thread_id_ = 0;
Ian Rogerscfaa4552012-11-26 21:00:08 -0800723 ReleaseThreadId(self, thin_lock_id);
724 while (self != NULL) {
725 // Remove and delete the Thread* while holding the thread_list_lock_ and
726 // thread_suspend_count_lock_ so that the unregistering thread cannot be suspended.
Ian Rogers0878d652013-04-18 17:38:35 -0700727 // Note: deliberately not using MutexLock that could hold a stale self pointer.
728 Locks::thread_list_lock_->ExclusiveLock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700729 CHECK(Contains(self));
Ian Rogerscfaa4552012-11-26 21:00:08 -0800730 // Note: we don't take the thread_suspend_count_lock_ here as to be suspending a thread other
731 // than yourself you need to hold the thread_list_lock_ (see Thread::ModifySuspendCount).
732 if (!self->IsSuspended()) {
733 list_.remove(self);
734 delete self;
735 self = NULL;
736 }
Ian Rogers0878d652013-04-18 17:38:35 -0700737 Locks::thread_list_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700738 }
739
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700740 // Clear the TLS data, so that the underlying native thread is recognizably detached.
741 // (It may wish to reattach later.)
742 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, NULL), "detach self");
743
744 // Signal that a thread just detached.
Ian Rogers81d425b2012-09-27 16:03:43 -0700745 MutexLock mu(NULL, *Locks::thread_list_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700746 thread_exit_cond_.Signal(NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700747}
748
749void ThreadList::ForEach(void (*callback)(Thread*, void*), void* context) {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700750 for (const auto& thread : list_) {
751 callback(thread, context);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700752 }
753}
754
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800755void ThreadList::VisitRoots(RootVisitor* visitor, void* arg) const {
Ian Rogers81d425b2012-09-27 16:03:43 -0700756 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700757 for (const auto& thread : list_) {
758 thread->VisitRoots(visitor, arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700759 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700760}
761
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700762struct VerifyRootWrapperArg {
763 VerifyRootVisitor* visitor;
764 void* arg;
765};
766
767static mirror::Object* VerifyRootWrapperCallback(mirror::Object* root, void* arg) {
768 VerifyRootWrapperArg* wrapperArg = reinterpret_cast<VerifyRootWrapperArg*>(arg);
769 wrapperArg->visitor(root, wrapperArg->arg, 0, NULL);
770 return root;
771}
772
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800773void ThreadList::VerifyRoots(VerifyRootVisitor* visitor, void* arg) const {
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700774 VerifyRootWrapperArg wrapper;
775 wrapper.visitor = visitor;
776 wrapper.arg = arg;
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700777 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700778 for (const auto& thread : list_) {
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700779 thread->VisitRoots(VerifyRootWrapperCallback, &wrapper);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700780 }
781}
782
Ian Rogerscfaa4552012-11-26 21:00:08 -0800783uint32_t ThreadList::AllocThreadId(Thread* self) {
784 MutexLock mu(self, allocated_ids_lock_);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700785 for (size_t i = 0; i < allocated_ids_.size(); ++i) {
786 if (!allocated_ids_[i]) {
787 allocated_ids_.set(i);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700788 return i + 1; // Zero is reserved to mean "invalid".
Elliott Hughes8daa0922011-09-11 13:46:25 -0700789 }
790 }
791 LOG(FATAL) << "Out of internal thread ids";
792 return 0;
793}
794
Ian Rogerscfaa4552012-11-26 21:00:08 -0800795void ThreadList::ReleaseThreadId(Thread* self, uint32_t id) {
796 MutexLock mu(self, allocated_ids_lock_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700797 --id; // Zero is reserved to mean "invalid".
Elliott Hughes8daa0922011-09-11 13:46:25 -0700798 DCHECK(allocated_ids_[id]) << id;
799 allocated_ids_.reset(id);
800}
801
Elliott Hughes8daa0922011-09-11 13:46:25 -0700802} // namespace art