blob: 4eb580bb50e6183fb02cd435f2812480d5604741 [file] [log] [blame]
Elliott Hughes8daa0922011-09-11 13:46:25 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "thread_list.h"
18
Mathieu Chartier6f365cc2014-04-23 12:42:27 -070019#define ATRACE_TAG ATRACE_TAG_DALVIK
20
21#include <cutils/trace.h>
Elliott Hughesabbe07d2012-06-05 17:42:23 -070022#include <dirent.h>
Ian Rogersd9c4fc92013-10-01 19:45:43 -070023#include <ScopedLocalRef.h>
24#include <ScopedUtfChars.h>
Elliott Hughesabbe07d2012-06-05 17:42:23 -070025#include <sys/types.h>
Elliott Hughes038a8062011-09-18 14:12:41 -070026#include <unistd.h>
27
Elliott Hughes76b61672012-12-12 17:47:30 -080028#include "base/mutex.h"
Hiroshi Yamauchi967a0ad2013-09-10 16:24:21 -070029#include "base/mutex-inl.h"
Sameer Abu Asala8439542013-02-14 16:06:42 -080030#include "base/timing_logger.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070031#include "debugger.h"
Ian Rogersd9c4fc92013-10-01 19:45:43 -070032#include "jni_internal.h"
33#include "lock_word.h"
34#include "monitor.h"
35#include "scoped_thread_state_change.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080036#include "thread.h"
Elliott Hughesabbe07d2012-06-05 17:42:23 -070037#include "utils.h"
Ian Rogersd9c4fc92013-10-01 19:45:43 -070038#include "well_known_classes.h"
Elliott Hughes475fc232011-10-25 15:00:35 -070039
Elliott Hughes8daa0922011-09-11 13:46:25 -070040namespace art {
41
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -080042ThreadList::ThreadList()
Elliott Hughese52e49b2012-04-02 16:05:44 -070043 : allocated_ids_lock_("allocated thread ids lock"),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070044 suspend_all_count_(0), debug_suspend_all_count_(0),
Ian Rogersc604d732012-10-14 16:09:54 -070045 thread_exit_cond_("thread exit condition variable", *Locks::thread_list_lock_) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -070046 CHECK(Monitor::IsValidLockWord(LockWord::FromThinLockId(kMaxThreadId, 1)));
Elliott Hughes8daa0922011-09-11 13:46:25 -070047}
48
49ThreadList::~ThreadList() {
Elliott Hughese52e49b2012-04-02 16:05:44 -070050 // Detach the current thread if necessary. If we failed to start, there might not be any threads.
Elliott Hughes6a144332012-04-03 13:07:11 -070051 // We need to detach the current thread here in case there's another thread waiting to join with
52 // us.
Elliott Hughes8daa0922011-09-11 13:46:25 -070053 if (Contains(Thread::Current())) {
54 Runtime::Current()->DetachCurrentThread();
55 }
Elliott Hughes6a144332012-04-03 13:07:11 -070056
57 WaitForOtherNonDaemonThreadsToExit();
Ian Rogers00f7d0e2012-07-19 15:28:27 -070058 // TODO: there's an unaddressed race here where a thread may attach during shutdown, see
59 // Thread::Init.
Elliott Hughes6a144332012-04-03 13:07:11 -070060 SuspendAllDaemonThreads();
Elliott Hughes8daa0922011-09-11 13:46:25 -070061}
62
63bool ThreadList::Contains(Thread* thread) {
64 return find(list_.begin(), list_.end(), thread) != list_.end();
65}
66
Elliott Hughesabbe07d2012-06-05 17:42:23 -070067bool ThreadList::Contains(pid_t tid) {
Mathieu Chartier02e25112013-08-14 16:14:24 -070068 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -070069 if (thread->GetTid() == tid) {
Elliott Hughesabbe07d2012-06-05 17:42:23 -070070 return true;
71 }
72 }
73 return false;
74}
75
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -070076pid_t ThreadList::GetLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -070077 return Locks::thread_list_lock_->GetExclusiveOwnerTid();
Elliott Hughesaccd83d2011-10-17 14:25:58 -070078}
79
Mathieu Chartier590fee92013-09-13 13:46:47 -070080void ThreadList::DumpNativeStacks(std::ostream& os) {
81 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
82 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -070083 os << "DUMPING THREAD " << thread->GetTid() << "\n";
Christopher Ferrisa2cee182014-04-16 19:13:59 -070084 DumpNativeStack(os, thread->GetTid(), "\t");
Mathieu Chartier590fee92013-09-13 13:46:47 -070085 os << "\n";
86 }
87}
88
Elliott Hughesc967f782012-04-16 10:23:15 -070089void ThreadList::DumpForSigQuit(std::ostream& os) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -070090 {
Ian Rogers50b35e22012-10-04 10:09:15 -070091 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -070092 DumpLocked(os);
93 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -070094 DumpUnattachedThreads(os);
95}
96
Ian Rogerscfaa4552012-11-26 21:00:08 -080097static void DumpUnattachedThread(std::ostream& os, pid_t tid) NO_THREAD_SAFETY_ANALYSIS {
98 // TODO: No thread safety analysis as DumpState with a NULL thread won't access fields, should
99 // refactor DumpState to avoid skipping analysis.
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700100 Thread::DumpState(os, NULL, tid);
101 DumpKernelStack(os, tid, " kernel: ", false);
Brian Carlstromed8b7232012-06-27 17:54:47 -0700102 // TODO: Reenable this when the native code in system_server can handle it.
103 // Currently "adb shell kill -3 `pid system_server`" will cause it to exit.
104 if (false) {
Christopher Ferrisa2cee182014-04-16 19:13:59 -0700105 DumpNativeStack(os, tid, " native: ");
Brian Carlstromed8b7232012-06-27 17:54:47 -0700106 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700107 os << "\n";
108}
109
110void ThreadList::DumpUnattachedThreads(std::ostream& os) {
111 DIR* d = opendir("/proc/self/task");
112 if (!d) {
113 return;
114 }
115
Ian Rogers50b35e22012-10-04 10:09:15 -0700116 Thread* self = Thread::Current();
Elliott Hughes4696b5b2012-10-30 10:35:10 -0700117 dirent* e;
118 while ((e = readdir(d)) != NULL) {
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700119 char* end;
Elliott Hughes4696b5b2012-10-30 10:35:10 -0700120 pid_t tid = strtol(e->d_name, &end, 10);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700121 if (!*end) {
122 bool contains;
123 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700124 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700125 contains = Contains(tid);
126 }
127 if (!contains) {
128 DumpUnattachedThread(os, tid);
129 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700130 }
131 }
132 closedir(d);
Elliott Hughesff738062012-02-03 15:00:42 -0800133}
134
135void ThreadList::DumpLocked(std::ostream& os) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700136 os << "DALVIK THREADS (" << list_.size() << "):\n";
Mathieu Chartier02e25112013-08-14 16:14:24 -0700137 for (const auto& thread : list_) {
138 thread->Dump(os);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700139 os << "\n";
140 }
141}
142
Ian Rogers50b35e22012-10-04 10:09:15 -0700143void ThreadList::AssertThreadsAreSuspended(Thread* self, Thread* ignore1, Thread* ignore2) {
144 MutexLock mu(self, *Locks::thread_list_lock_);
145 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700146 for (const auto& thread : list_) {
jeffhao725a9572012-11-13 18:20:12 -0800147 if (thread != ignore1 && thread != ignore2) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700148 CHECK(thread->IsSuspended())
149 << "\nUnsuspended thread: <<" << *thread << "\n"
150 << "self: <<" << *Thread::Current();
151 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700152 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700153}
154
Ian Rogers66aee5c2012-08-15 17:17:47 -0700155#if HAVE_TIMED_RWLOCK
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700156// Attempt to rectify locks so that we dump thread list with required locks before exiting.
Ian Rogers719d1a32014-03-06 12:13:39 -0800157static void UnsafeLogFatalForThreadSuspendAllTimeout(Thread* self) NO_THREAD_SAFETY_ANALYSIS __attribute__((noreturn));
158static void UnsafeLogFatalForThreadSuspendAllTimeout(Thread* self) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700159 Runtime* runtime = Runtime::Current();
160 std::ostringstream ss;
161 ss << "Thread suspend timeout\n";
162 runtime->DumpLockHolders(ss);
163 ss << "\n";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700164 runtime->GetThreadList()->DumpLocked(ss);
165 LOG(FATAL) << ss.str();
Ian Rogers719d1a32014-03-06 12:13:39 -0800166 exit(0);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700167}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700168#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700169
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800170// Unlike suspending all threads where we can wait to acquire the mutator_lock_, suspending an
171// individual thread requires polling. delay_us is the requested sleep and total_delay_us
172// accumulates the total time spent sleeping for timeouts. The first sleep is just a yield,
173// subsequently sleeps increase delay_us from 1ms to 500ms by doubling.
174static void ThreadSuspendSleep(Thread* self, useconds_t* delay_us, useconds_t* total_delay_us,
175 bool holding_locks) {
176 if (!holding_locks) {
177 for (int i = kLockLevelCount - 1; i >= 0; --i) {
178 BaseMutex* held_mutex = self->GetHeldMutex(static_cast<LockLevel>(i));
179 if (held_mutex != NULL) {
180 LOG(FATAL) << "Holding " << held_mutex->GetName() << " while sleeping for thread suspension";
181 }
182 }
183 }
184 useconds_t new_delay_us = (*delay_us) * 2;
185 CHECK_GE(new_delay_us, *delay_us);
186 if (new_delay_us < 500000) { // Don't allow sleeping to be more than 0.5s.
187 *delay_us = new_delay_us;
188 }
189 if (*delay_us == 0) {
190 sched_yield();
191 // Default to 1 milliseconds (note that this gets multiplied by 2 before the first sleep).
192 *delay_us = 500;
193 } else {
194 usleep(*delay_us);
195 *total_delay_us += *delay_us;
196 }
197}
198
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700199size_t ThreadList::RunCheckpoint(Closure* checkpoint_function) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700200 Thread* self = Thread::Current();
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800201 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
202 Locks::thread_list_lock_->AssertNotHeld(self);
203 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
204 if (kDebugLocking) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700205 CHECK_NE(self->GetState(), kRunnable);
206 }
207
208 std::vector<Thread*> suspended_count_modified_threads;
209 size_t count = 0;
210 {
211 // Call a checkpoint function for each thread, threads which are suspend get their checkpoint
212 // manually called.
213 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700214 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700215 for (const auto& thread : list_) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700216 if (thread != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700217 while (true) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700218 if (thread->RequestCheckpoint(checkpoint_function)) {
Dave Allison0aded082013-11-07 13:15:11 -0800219 // This thread will run its checkpoint some time in the near future.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700220 count++;
221 break;
222 } else {
223 // We are probably suspended, try to make sure that we stay suspended.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700224 // The thread switched back to runnable.
225 if (thread->GetState() == kRunnable) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700226 // Spurious fail, try again.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700227 continue;
228 }
229 thread->ModifySuspendCount(self, +1, false);
230 suspended_count_modified_threads.push_back(thread);
231 break;
232 }
233 }
234 }
235 }
236 }
237
238 // Run the checkpoint on ourself while we wait for threads to suspend.
239 checkpoint_function->Run(self);
240
241 // Run the checkpoint on the suspended threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700242 for (const auto& thread : suspended_count_modified_threads) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700243 if (!thread->IsSuspended()) {
244 // Wait until the thread is suspended.
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800245 useconds_t total_delay_us = 0;
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700246 do {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800247 useconds_t delay_us = 100;
248 ThreadSuspendSleep(self, &delay_us, &total_delay_us, true);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700249 } while (!thread->IsSuspended());
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800250 // Shouldn't need to wait for longer than 1000 microseconds.
251 constexpr useconds_t kLongWaitThresholdUS = 1000;
252 if (UNLIKELY(total_delay_us > kLongWaitThresholdUS)) {
253 LOG(WARNING) << "Waited " << total_delay_us << " us for thread suspend!";
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700254 }
255 }
256 // We know for sure that the thread is suspended at this point.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700257 checkpoint_function->Run(thread);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700258 {
259 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
260 thread->ModifySuspendCount(self, -1, false);
261 }
262 }
263
Mathieu Chartier664bebf2012-11-12 16:54:11 -0800264 {
265 // Imitate ResumeAll, threads may be waiting on Thread::resume_cond_ since we raised their
266 // suspend count. Now the suspend_count_ is lowered so we must do the broadcast.
267 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
268 Thread::resume_cond_->Broadcast(self);
269 }
270
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700271 // Add one for self.
272 return count + suspended_count_modified_threads.size() + 1;
273}
274
Dave Allison39c3bfb2014-01-28 18:33:52 -0800275// Request that a checkpoint function be run on all active (non-suspended)
276// threads. Returns the number of successful requests.
277size_t ThreadList::RunCheckpointOnRunnableThreads(Closure* checkpoint_function) {
278 Thread* self = Thread::Current();
279 if (kIsDebugBuild) {
280 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
281 Locks::thread_list_lock_->AssertNotHeld(self);
282 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
283 CHECK_NE(self->GetState(), kRunnable);
284 }
285
286 size_t count = 0;
287 {
288 // Call a checkpoint function for each non-suspended thread.
289 MutexLock mu(self, *Locks::thread_list_lock_);
290 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
291 for (const auto& thread : list_) {
292 if (thread != self) {
293 if (thread->RequestCheckpoint(checkpoint_function)) {
294 // This thread will run its checkpoint some time in the near future.
295 count++;
296 }
297 }
298 }
299 }
300
301 // Return the number of threads that will run the checkpoint function.
302 return count;
303}
304
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700305void ThreadList::SuspendAll() {
306 Thread* self = Thread::Current();
Brian Carlstrom6449c622014-02-10 23:48:36 -0800307 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700308
309 VLOG(threads) << *self << " SuspendAll starting...";
310
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700311 ATRACE_BEGIN("Suspending mutator threads");
312
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800313 Locks::mutator_lock_->AssertNotHeld(self);
314 Locks::thread_list_lock_->AssertNotHeld(self);
315 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
316 if (kDebugLocking) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700317 CHECK_NE(self->GetState(), kRunnable);
318 }
319 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700320 MutexLock mu(self, *Locks::thread_list_lock_);
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800321 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
322 // Update global suspend all state for attaching threads.
323 ++suspend_all_count_;
324 // Increment everybody's suspend count (except our own).
325 for (const auto& thread : list_) {
326 if (thread == self) {
327 continue;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700328 }
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800329 VLOG(threads) << "requesting thread suspend: " << *thread;
330 thread->ModifySuspendCount(self, +1, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700331 }
332 }
333
Ian Rogers66aee5c2012-08-15 17:17:47 -0700334 // Block on the mutator lock until all Runnable threads release their share of access.
335#if HAVE_TIMED_RWLOCK
336 // Timeout if we wait more than 30 seconds.
Ian Rogers719d1a32014-03-06 12:13:39 -0800337 if (!Locks::mutator_lock_->ExclusiveLockWithTimeout(self, 30 * 1000, 0)) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700338 UnsafeLogFatalForThreadSuspendAllTimeout(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700339 }
Ian Rogers66aee5c2012-08-15 17:17:47 -0700340#else
Ian Rogers81d425b2012-09-27 16:03:43 -0700341 Locks::mutator_lock_->ExclusiveLock(self);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700342#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700343
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800344 if (kDebugLocking) {
345 // Debug check that all threads are suspended.
346 AssertThreadsAreSuspended(self, self);
347 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700348
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700349 ATRACE_END();
350 ATRACE_BEGIN("Mutator threads suspended");
351
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800352 VLOG(threads) << *self << " SuspendAll complete";
Elliott Hughes8d768a92011-09-14 16:35:25 -0700353}
354
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700355void ThreadList::ResumeAll() {
356 Thread* self = Thread::Current();
357
358 VLOG(threads) << *self << " ResumeAll starting";
Ian Rogers01ae5802012-09-28 16:14:01 -0700359
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700360 ATRACE_END();
361 ATRACE_BEGIN("Resuming mutator threads");
362
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800363 if (kDebugLocking) {
364 // Debug check that all threads are suspended.
365 AssertThreadsAreSuspended(self, self);
366 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700367
Ian Rogers81d425b2012-09-27 16:03:43 -0700368 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700369 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700370 MutexLock mu(self, *Locks::thread_list_lock_);
371 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700372 // Update global suspend all state for attaching threads.
373 --suspend_all_count_;
374 // Decrement the suspend counts for all threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700375 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700376 if (thread == self) {
377 continue;
378 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700379 thread->ModifySuspendCount(self, -1, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700380 }
381
382 // Broadcast a notification to all suspended threads, some or all of
383 // which may choose to wake up. No need to wait for them.
384 VLOG(threads) << *self << " ResumeAll waking others";
Ian Rogersc604d732012-10-14 16:09:54 -0700385 Thread::resume_cond_->Broadcast(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700386 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700387 ATRACE_END();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700388 VLOG(threads) << *self << " ResumeAll complete";
389}
390
391void ThreadList::Resume(Thread* thread, bool for_debugger) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700392 Thread* self = Thread::Current();
393 DCHECK_NE(thread, self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700394 VLOG(threads) << "Resume(" << *thread << ") starting..." << (for_debugger ? " (debugger)" : "");
Elliott Hughes01158d72011-09-19 19:47:10 -0700395
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700396 {
397 // To check Contains.
Ian Rogers81d425b2012-09-27 16:03:43 -0700398 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700399 // To check IsSuspended.
Ian Rogers81d425b2012-09-27 16:03:43 -0700400 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
401 DCHECK(thread->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700402 if (!Contains(thread)) {
403 return;
404 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700405 thread->ModifySuspendCount(self, -1, for_debugger);
Elliott Hughes01158d72011-09-19 19:47:10 -0700406 }
407
408 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700409 VLOG(threads) << "Resume(" << *thread << ") waking others";
Ian Rogers81d425b2012-09-27 16:03:43 -0700410 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700411 Thread::resume_cond_->Broadcast(self);
Elliott Hughes01158d72011-09-19 19:47:10 -0700412 }
413
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700414 VLOG(threads) << "Resume(" << *thread << ") complete";
415}
Elliott Hughes01158d72011-09-19 19:47:10 -0700416
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700417static void ThreadSuspendByPeerWarning(Thread* self, int level, const char* message, jobject peer) {
418 JNIEnvExt* env = self->GetJniEnv();
419 ScopedLocalRef<jstring>
420 scoped_name_string(env, (jstring)env->GetObjectField(peer,
421 WellKnownClasses::java_lang_Thread_name));
422 ScopedUtfChars scoped_name_chars(env, scoped_name_string.get());
423 if (scoped_name_chars.c_str() == NULL) {
424 LOG(level) << message << ": " << peer;
425 env->ExceptionClear();
426 } else {
427 LOG(level) << message << ": " << peer << ":" << scoped_name_chars.c_str();
428 }
429}
430
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700431Thread* ThreadList::SuspendThreadByPeer(jobject peer, bool request_suspension,
432 bool debug_suspension, bool* timed_out) {
433 static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
434 useconds_t total_delay_us = 0;
435 useconds_t delay_us = 0;
436 bool did_suspend_request = false;
437 *timed_out = false;
438 Thread* self = Thread::Current();
439 while (true) {
440 Thread* thread;
441 {
442 ScopedObjectAccess soa(self);
443 MutexLock mu(self, *Locks::thread_list_lock_);
444 thread = Thread::FromManagedThread(soa, peer);
445 if (thread == NULL) {
446 ThreadSuspendByPeerWarning(self, WARNING, "No such thread for suspend", peer);
447 return NULL;
448 }
449 {
450 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
451 if (request_suspension) {
452 thread->ModifySuspendCount(self, +1, debug_suspension);
453 request_suspension = false;
454 did_suspend_request = true;
455 } else {
456 // If the caller isn't requesting suspension, a suspension should have already occurred.
457 CHECK_GT(thread->GetSuspendCount(), 0);
458 }
459 // IsSuspended on the current thread will fail as the current thread is changed into
460 // Runnable above. As the suspend count is now raised if this is the current thread
461 // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
462 // to just explicitly handle the current thread in the callers to this code.
463 CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
464 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
465 // count, or else we've waited and it has self suspended) or is the current thread, we're
466 // done.
467 if (thread->IsSuspended()) {
468 return thread;
469 }
470 if (total_delay_us >= kTimeoutUs) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700471 ThreadSuspendByPeerWarning(self, FATAL, "Thread suspension timed out", peer);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700472 if (did_suspend_request) {
473 thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
474 }
475 *timed_out = true;
476 return NULL;
477 }
478 }
479 // Release locks and come out of runnable state.
480 }
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800481 ThreadSuspendSleep(self, &delay_us, &total_delay_us, false);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700482 }
483}
484
485static void ThreadSuspendByThreadIdWarning(int level, const char* message, uint32_t thread_id) {
486 LOG(level) << StringPrintf("%s: %d", message, thread_id);
487}
488
489Thread* ThreadList::SuspendThreadByThreadId(uint32_t thread_id, bool debug_suspension,
490 bool* timed_out) {
491 static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
492 useconds_t total_delay_us = 0;
493 useconds_t delay_us = 0;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700494 *timed_out = false;
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800495 Thread* suspended_thread = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700496 Thread* self = Thread::Current();
497 CHECK_NE(thread_id, kInvalidThreadId);
498 while (true) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700499 {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800500 Thread* thread = NULL;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700501 ScopedObjectAccess soa(self);
502 MutexLock mu(self, *Locks::thread_list_lock_);
503 for (const auto& it : list_) {
504 if (it->GetThreadId() == thread_id) {
505 thread = it;
506 break;
507 }
508 }
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800509 if (thread == nullptr) {
510 CHECK(suspended_thread == nullptr) << "Suspended thread " << suspended_thread
511 << " no longer in thread list";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700512 // There's a race in inflating a lock and the owner giving up ownership and then dying.
513 ThreadSuspendByThreadIdWarning(WARNING, "No such thread id for suspend", thread_id);
514 return NULL;
515 }
516 {
517 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800518 if (suspended_thread == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700519 thread->ModifySuspendCount(self, +1, debug_suspension);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800520 suspended_thread = thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700521 } else {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800522 CHECK_EQ(suspended_thread, thread);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700523 // If the caller isn't requesting suspension, a suspension should have already occurred.
524 CHECK_GT(thread->GetSuspendCount(), 0);
525 }
526 // IsSuspended on the current thread will fail as the current thread is changed into
527 // Runnable above. As the suspend count is now raised if this is the current thread
528 // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
529 // to just explicitly handle the current thread in the callers to this code.
530 CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
531 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
532 // count, or else we've waited and it has self suspended) or is the current thread, we're
533 // done.
534 if (thread->IsSuspended()) {
535 return thread;
536 }
537 if (total_delay_us >= kTimeoutUs) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700538 ThreadSuspendByThreadIdWarning(WARNING, "Thread suspension timed out", thread_id);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800539 if (suspended_thread != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700540 thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
541 }
542 *timed_out = true;
543 return NULL;
544 }
545 }
546 // Release locks and come out of runnable state.
547 }
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800548 ThreadSuspendSleep(self, &delay_us, &total_delay_us, false);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700549 }
550}
551
552Thread* ThreadList::FindThreadByThreadId(uint32_t thin_lock_id) {
553 Thread* self = Thread::Current();
554 MutexLock mu(self, *Locks::thread_list_lock_);
555 for (const auto& thread : list_) {
556 if (thread->GetThreadId() == thin_lock_id) {
557 CHECK(thread == self || thread->IsSuspended());
558 return thread;
559 }
560 }
561 return NULL;
562}
563
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700564void ThreadList::SuspendAllForDebugger() {
565 Thread* self = Thread::Current();
566 Thread* debug_thread = Dbg::GetDebugThread();
567
568 VLOG(threads) << *self << " SuspendAllForDebugger starting...";
569
570 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700571 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700572 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700573 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700574 // Update global suspend all state for attaching threads.
575 ++suspend_all_count_;
576 ++debug_suspend_all_count_;
577 // Increment everybody's suspend count (except our own).
Mathieu Chartier02e25112013-08-14 16:14:24 -0700578 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700579 if (thread == self || thread == debug_thread) {
580 continue;
581 }
582 VLOG(threads) << "requesting thread suspend: " << *thread;
Ian Rogers01ae5802012-09-28 16:14:01 -0700583 thread->ModifySuspendCount(self, +1, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700584 }
585 }
586 }
587
Ian Rogers66aee5c2012-08-15 17:17:47 -0700588 // Block on the mutator lock until all Runnable threads release their share of access then
589 // immediately unlock again.
590#if HAVE_TIMED_RWLOCK
591 // Timeout if we wait more than 30 seconds.
Ian Rogersc604d732012-10-14 16:09:54 -0700592 if (!Locks::mutator_lock_->ExclusiveLockWithTimeout(self, 30 * 1000, 0)) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700593 UnsafeLogFatalForThreadSuspendAllTimeout(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700594 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -0700595 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700596 }
Ian Rogers66aee5c2012-08-15 17:17:47 -0700597#else
Ian Rogers81d425b2012-09-27 16:03:43 -0700598 Locks::mutator_lock_->ExclusiveLock(self);
599 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700600#endif
Ian Rogers50b35e22012-10-04 10:09:15 -0700601 AssertThreadsAreSuspended(self, self, debug_thread);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700602
603 VLOG(threads) << *self << " SuspendAll complete";
Elliott Hughes01158d72011-09-19 19:47:10 -0700604}
605
Elliott Hughes475fc232011-10-25 15:00:35 -0700606void ThreadList::SuspendSelfForDebugger() {
607 Thread* self = Thread::Current();
Elliott Hughes01158d72011-09-19 19:47:10 -0700608
Elliott Hughes475fc232011-10-25 15:00:35 -0700609 // The debugger thread must not suspend itself due to debugger activity!
610 Thread* debug_thread = Dbg::GetDebugThread();
611 CHECK(debug_thread != NULL);
612 CHECK(self != debug_thread);
jeffhaoa77f0f62012-12-05 17:19:31 -0800613 CHECK_NE(self->GetState(), kRunnable);
614 Locks::mutator_lock_->AssertNotHeld(self);
Elliott Hughes475fc232011-10-25 15:00:35 -0700615
jeffhaoa77f0f62012-12-05 17:19:31 -0800616 {
617 // Collisions with other suspends aren't really interesting. We want
618 // to ensure that we're the only one fiddling with the suspend count
619 // though.
620 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
621 self->ModifySuspendCount(self, +1, true);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700622 CHECK_GT(self->GetSuspendCount(), 0);
jeffhaoa77f0f62012-12-05 17:19:31 -0800623 }
Elliott Hughes475fc232011-10-25 15:00:35 -0700624
Elliott Hughes1f729aa2012-03-02 13:55:41 -0800625 VLOG(threads) << *self << " self-suspending (debugger)";
Elliott Hughes475fc232011-10-25 15:00:35 -0700626
Sebastien Hertz21e729c2014-02-18 14:16:00 +0100627 // Tell JDWP we've completed invocation and are ready to suspend.
628 DebugInvokeReq* pReq = self->GetInvokeReq();
629 DCHECK(pReq != NULL);
630 if (pReq->invoke_needed) {
631 // Clear this before signaling.
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200632 pReq->Clear();
Sebastien Hertz21e729c2014-02-18 14:16:00 +0100633
634 VLOG(jdwp) << "invoke complete, signaling";
635 MutexLock mu(self, pReq->lock);
636 pReq->cond.Signal(self);
637 }
638
Elliott Hughes475fc232011-10-25 15:00:35 -0700639 // Tell JDWP that we've completed suspension. The JDWP thread can't
640 // tell us to resume before we're fully asleep because we hold the
641 // suspend count lock.
642 Dbg::ClearWaitForEventThread();
643
jeffhaoa77f0f62012-12-05 17:19:31 -0800644 {
645 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700646 while (self->GetSuspendCount() != 0) {
jeffhaoa77f0f62012-12-05 17:19:31 -0800647 Thread::resume_cond_->Wait(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700648 if (self->GetSuspendCount() != 0) {
jeffhaoa77f0f62012-12-05 17:19:31 -0800649 // The condition was signaled but we're still suspended. This
650 // can happen if the debugger lets go while a SIGQUIT thread
651 // dump event is pending (assuming SignalCatcher was resumed for
652 // just long enough to try to grab the thread-suspend lock).
653 LOG(DEBUG) << *self << " still suspended after undo "
Ian Rogersdd7624d2014-03-14 17:43:00 -0700654 << "(suspend count=" << self->GetSuspendCount() << ")";
jeffhaoa77f0f62012-12-05 17:19:31 -0800655 }
Elliott Hughes475fc232011-10-25 15:00:35 -0700656 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700657 CHECK_EQ(self->GetSuspendCount(), 0);
Elliott Hughes475fc232011-10-25 15:00:35 -0700658 }
jeffhaoa77f0f62012-12-05 17:19:31 -0800659
Elliott Hughes1f729aa2012-03-02 13:55:41 -0800660 VLOG(threads) << *self << " self-reviving (debugger)";
Elliott Hughes475fc232011-10-25 15:00:35 -0700661}
662
Elliott Hughes234ab152011-10-26 14:02:26 -0700663void ThreadList::UndoDebuggerSuspensions() {
664 Thread* self = Thread::Current();
665
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800666 VLOG(threads) << *self << " UndoDebuggerSuspensions starting";
Elliott Hughes234ab152011-10-26 14:02:26 -0700667
668 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700669 MutexLock mu(self, *Locks::thread_list_lock_);
670 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700671 // Update global suspend all state for attaching threads.
672 suspend_all_count_ -= debug_suspend_all_count_;
673 debug_suspend_all_count_ = 0;
674 // Update running threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700675 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700676 if (thread == self || thread->GetDebugSuspendCount() == 0) {
Elliott Hughes234ab152011-10-26 14:02:26 -0700677 continue;
678 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700679 thread->ModifySuspendCount(self, -thread->GetDebugSuspendCount(), true);
Elliott Hughes234ab152011-10-26 14:02:26 -0700680 }
681 }
682
683 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700684 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700685 Thread::resume_cond_->Broadcast(self);
Elliott Hughes234ab152011-10-26 14:02:26 -0700686 }
687
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800688 VLOG(threads) << "UndoDebuggerSuspensions(" << *self << ") complete";
Elliott Hughes234ab152011-10-26 14:02:26 -0700689}
690
Elliott Hughese52e49b2012-04-02 16:05:44 -0700691void ThreadList::WaitForOtherNonDaemonThreadsToExit() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700692 Thread* self = Thread::Current();
693 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700694 bool all_threads_are_daemons;
695 do {
Ian Rogers120f1c72012-09-28 17:17:10 -0700696 {
697 // No more threads can be born after we start to shutdown.
698 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700699 CHECK(Runtime::Current()->IsShuttingDownLocked());
Ian Rogers120f1c72012-09-28 17:17:10 -0700700 CHECK_EQ(Runtime::Current()->NumberOfThreadsBeingBorn(), 0U);
701 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700702 all_threads_are_daemons = true;
Ian Rogers120f1c72012-09-28 17:17:10 -0700703 MutexLock mu(self, *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700704 for (const auto& thread : list_) {
Anwar Ghuloum97543682013-06-14 12:58:16 -0700705 if (thread != self && !thread->IsDaemon()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700706 all_threads_are_daemons = false;
707 break;
708 }
709 }
710 if (!all_threads_are_daemons) {
711 // Wait for another thread to exit before re-checking.
Ian Rogersc604d732012-10-14 16:09:54 -0700712 thread_exit_cond_.Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700713 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700714 } while (!all_threads_are_daemons);
Elliott Hughes038a8062011-09-18 14:12:41 -0700715}
716
717void ThreadList::SuspendAllDaemonThreads() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700718 Thread* self = Thread::Current();
719 MutexLock mu(self, *Locks::thread_list_lock_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700720 { // Tell all the daemons it's time to suspend.
Ian Rogers81d425b2012-09-27 16:03:43 -0700721 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700722 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700723 // This is only run after all non-daemon threads have exited, so the remainder should all be
724 // daemons.
Ian Rogers7e762862012-10-22 15:45:08 -0700725 CHECK(thread->IsDaemon()) << *thread;
Ian Rogers81d425b2012-09-27 16:03:43 -0700726 if (thread != self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700727 thread->ModifySuspendCount(self, +1, false);
Elliott Hughese52e49b2012-04-02 16:05:44 -0700728 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700729 }
730 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700731 // Give the threads a chance to suspend, complaining if they're slow.
732 bool have_complained = false;
733 for (int i = 0; i < 10; ++i) {
734 usleep(200 * 1000);
735 bool all_suspended = true;
Mathieu Chartier02e25112013-08-14 16:14:24 -0700736 for (const auto& thread : list_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700737 if (thread != self && thread->GetState() == kRunnable) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700738 if (!have_complained) {
739 LOG(WARNING) << "daemon thread not yet suspended: " << *thread;
740 have_complained = true;
741 }
742 all_suspended = false;
743 }
744 }
745 if (all_suspended) {
746 return;
747 }
748 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700749 LOG(ERROR) << "suspend all daemons failed";
750}
751void ThreadList::Register(Thread* self) {
752 DCHECK_EQ(self, Thread::Current());
753
754 if (VLOG_IS_ON(threads)) {
755 std::ostringstream oss;
756 self->ShortDump(oss); // We don't hold the mutator_lock_ yet and so cannot call Dump.
757 LOG(INFO) << "ThreadList::Register() " << *self << "\n" << oss;
758 }
759
760 // Atomically add self to the thread list and make its thread_suspend_count_ reflect ongoing
761 // SuspendAll requests.
Ian Rogers81d425b2012-09-27 16:03:43 -0700762 MutexLock mu(self, *Locks::thread_list_lock_);
763 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700764 CHECK_GE(suspend_all_count_, debug_suspend_all_count_);
Ian Rogers2966e132014-04-02 08:34:36 -0700765 // Modify suspend count in increments of 1 to maintain invariants in ModifySuspendCount. While
766 // this isn't particularly efficient the suspend counts are most commonly 0 or 1.
767 for (int delta = debug_suspend_all_count_; delta > 0; delta--) {
768 self->ModifySuspendCount(self, +1, true);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700769 }
Ian Rogers2966e132014-04-02 08:34:36 -0700770 for (int delta = suspend_all_count_ - debug_suspend_all_count_; delta > 0; delta--) {
771 self->ModifySuspendCount(self, +1, false);
Ian Rogers01ae5802012-09-28 16:14:01 -0700772 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700773 CHECK(!Contains(self));
774 list_.push_back(self);
775}
776
777void ThreadList::Unregister(Thread* self) {
778 DCHECK_EQ(self, Thread::Current());
779
780 VLOG(threads) << "ThreadList::Unregister() " << *self;
781
782 // Any time-consuming destruction, plus anything that can call back into managed code or
783 // suspend and so on, must happen at this point, and not in ~Thread.
784 self->Destroy();
785
Ian Rogersdd7624d2014-03-14 17:43:00 -0700786 uint32_t thin_lock_id = self->GetThreadId();
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800787 while (self != nullptr) {
Ian Rogerscfaa4552012-11-26 21:00:08 -0800788 // Remove and delete the Thread* while holding the thread_list_lock_ and
789 // thread_suspend_count_lock_ so that the unregistering thread cannot be suspended.
Ian Rogers0878d652013-04-18 17:38:35 -0700790 // Note: deliberately not using MutexLock that could hold a stale self pointer.
791 Locks::thread_list_lock_->ExclusiveLock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700792 CHECK(Contains(self));
Ian Rogerscfaa4552012-11-26 21:00:08 -0800793 // Note: we don't take the thread_suspend_count_lock_ here as to be suspending a thread other
794 // than yourself you need to hold the thread_list_lock_ (see Thread::ModifySuspendCount).
795 if (!self->IsSuspended()) {
796 list_.remove(self);
797 delete self;
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800798 self = nullptr;
Ian Rogerscfaa4552012-11-26 21:00:08 -0800799 }
Ian Rogers0878d652013-04-18 17:38:35 -0700800 Locks::thread_list_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700801 }
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800802 // Release the thread ID after the thread is finished and deleted to avoid cases where we can
803 // temporarily have multiple threads with the same thread id. When this occurs, it causes
804 // problems in FindThreadByThreadId / SuspendThreadByThreadId.
805 ReleaseThreadId(nullptr, thin_lock_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700806
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700807 // Clear the TLS data, so that the underlying native thread is recognizably detached.
808 // (It may wish to reattach later.)
809 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, NULL), "detach self");
810
811 // Signal that a thread just detached.
Ian Rogers81d425b2012-09-27 16:03:43 -0700812 MutexLock mu(NULL, *Locks::thread_list_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700813 thread_exit_cond_.Signal(NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700814}
815
816void ThreadList::ForEach(void (*callback)(Thread*, void*), void* context) {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700817 for (const auto& thread : list_) {
818 callback(thread, context);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700819 }
820}
821
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800822void ThreadList::VisitRoots(RootCallback* callback, void* arg) const {
Ian Rogers81d425b2012-09-27 16:03:43 -0700823 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700824 for (const auto& thread : list_) {
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800825 thread->VisitRoots(callback, arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700826 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700827}
828
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800829class VerifyRootWrapperArg {
830 public:
831 VerifyRootWrapperArg(VerifyRootCallback* callback, void* arg) : callback_(callback), arg_(arg) {
832 }
833 VerifyRootCallback* const callback_;
834 void* const arg_;
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700835};
836
Mathieu Chartier815873e2014-02-13 18:02:13 -0800837static void VerifyRootWrapperCallback(mirror::Object** root, void* arg, uint32_t /*thread_id*/,
Mathieu Chartier7bf9f192014-04-04 11:09:41 -0700838 RootType root_type) {
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700839 VerifyRootWrapperArg* wrapperArg = reinterpret_cast<VerifyRootWrapperArg*>(arg);
Mathieu Chartier7bf9f192014-04-04 11:09:41 -0700840 wrapperArg->callback_(*root, wrapperArg->arg_, 0, NULL, root_type);
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700841}
842
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800843void ThreadList::VerifyRoots(VerifyRootCallback* callback, void* arg) const {
844 VerifyRootWrapperArg wrapper(callback, arg);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700845 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700846 for (const auto& thread : list_) {
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700847 thread->VisitRoots(VerifyRootWrapperCallback, &wrapper);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700848 }
849}
850
Ian Rogerscfaa4552012-11-26 21:00:08 -0800851uint32_t ThreadList::AllocThreadId(Thread* self) {
852 MutexLock mu(self, allocated_ids_lock_);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700853 for (size_t i = 0; i < allocated_ids_.size(); ++i) {
854 if (!allocated_ids_[i]) {
855 allocated_ids_.set(i);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700856 return i + 1; // Zero is reserved to mean "invalid".
Elliott Hughes8daa0922011-09-11 13:46:25 -0700857 }
858 }
859 LOG(FATAL) << "Out of internal thread ids";
860 return 0;
861}
862
Ian Rogerscfaa4552012-11-26 21:00:08 -0800863void ThreadList::ReleaseThreadId(Thread* self, uint32_t id) {
864 MutexLock mu(self, allocated_ids_lock_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700865 --id; // Zero is reserved to mean "invalid".
Elliott Hughes8daa0922011-09-11 13:46:25 -0700866 DCHECK(allocated_ids_[id]) << id;
867 allocated_ids_.reset(id);
868}
869
Elliott Hughes8daa0922011-09-11 13:46:25 -0700870} // namespace art