blob: 54732fae0414f326ffc2585bc13a8e6ab63afb0e [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()
Chao-ying Fu9e369312014-05-21 11:20:52 -070043 : suspend_all_count_(0), debug_suspend_all_count_(0),
Ian Rogersc604d732012-10-14 16:09:54 -070044 thread_exit_cond_("thread exit condition variable", *Locks::thread_list_lock_) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -070045 CHECK(Monitor::IsValidLockWord(LockWord::FromThinLockId(kMaxThreadId, 1)));
Elliott Hughes8daa0922011-09-11 13:46:25 -070046}
47
48ThreadList::~ThreadList() {
Elliott Hughese52e49b2012-04-02 16:05:44 -070049 // Detach the current thread if necessary. If we failed to start, there might not be any threads.
Elliott Hughes6a144332012-04-03 13:07:11 -070050 // We need to detach the current thread here in case there's another thread waiting to join with
51 // us.
Elliott Hughes8daa0922011-09-11 13:46:25 -070052 if (Contains(Thread::Current())) {
53 Runtime::Current()->DetachCurrentThread();
54 }
Elliott Hughes6a144332012-04-03 13:07:11 -070055
56 WaitForOtherNonDaemonThreadsToExit();
Ian Rogers00f7d0e2012-07-19 15:28:27 -070057 // TODO: there's an unaddressed race here where a thread may attach during shutdown, see
58 // Thread::Init.
Elliott Hughes6a144332012-04-03 13:07:11 -070059 SuspendAllDaemonThreads();
Elliott Hughes8daa0922011-09-11 13:46:25 -070060}
61
62bool ThreadList::Contains(Thread* thread) {
63 return find(list_.begin(), list_.end(), thread) != list_.end();
64}
65
Elliott Hughesabbe07d2012-06-05 17:42:23 -070066bool ThreadList::Contains(pid_t tid) {
Mathieu Chartier02e25112013-08-14 16:14:24 -070067 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -070068 if (thread->GetTid() == tid) {
Elliott Hughesabbe07d2012-06-05 17:42:23 -070069 return true;
70 }
71 }
72 return false;
73}
74
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -070075pid_t ThreadList::GetLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -070076 return Locks::thread_list_lock_->GetExclusiveOwnerTid();
Elliott Hughesaccd83d2011-10-17 14:25:58 -070077}
78
Mathieu Chartier590fee92013-09-13 13:46:47 -070079void ThreadList::DumpNativeStacks(std::ostream& os) {
80 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
81 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -070082 os << "DUMPING THREAD " << thread->GetTid() << "\n";
Christopher Ferrisa2cee182014-04-16 19:13:59 -070083 DumpNativeStack(os, thread->GetTid(), "\t");
Mathieu Chartier590fee92013-09-13 13:46:47 -070084 os << "\n";
85 }
86}
87
Elliott Hughesc967f782012-04-16 10:23:15 -070088void ThreadList::DumpForSigQuit(std::ostream& os) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -070089 {
Ian Rogers50b35e22012-10-04 10:09:15 -070090 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -070091 DumpLocked(os);
92 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -070093 DumpUnattachedThreads(os);
94}
95
Ian Rogerscfaa4552012-11-26 21:00:08 -080096static void DumpUnattachedThread(std::ostream& os, pid_t tid) NO_THREAD_SAFETY_ANALYSIS {
97 // TODO: No thread safety analysis as DumpState with a NULL thread won't access fields, should
98 // refactor DumpState to avoid skipping analysis.
Elliott Hughesabbe07d2012-06-05 17:42:23 -070099 Thread::DumpState(os, NULL, tid);
100 DumpKernelStack(os, tid, " kernel: ", false);
Brian Carlstromed8b7232012-06-27 17:54:47 -0700101 // TODO: Reenable this when the native code in system_server can handle it.
102 // Currently "adb shell kill -3 `pid system_server`" will cause it to exit.
103 if (false) {
Christopher Ferrisa2cee182014-04-16 19:13:59 -0700104 DumpNativeStack(os, tid, " native: ");
Brian Carlstromed8b7232012-06-27 17:54:47 -0700105 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700106 os << "\n";
107}
108
109void ThreadList::DumpUnattachedThreads(std::ostream& os) {
110 DIR* d = opendir("/proc/self/task");
111 if (!d) {
112 return;
113 }
114
Ian Rogers50b35e22012-10-04 10:09:15 -0700115 Thread* self = Thread::Current();
Elliott Hughes4696b5b2012-10-30 10:35:10 -0700116 dirent* e;
117 while ((e = readdir(d)) != NULL) {
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700118 char* end;
Elliott Hughes4696b5b2012-10-30 10:35:10 -0700119 pid_t tid = strtol(e->d_name, &end, 10);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700120 if (!*end) {
121 bool contains;
122 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700123 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700124 contains = Contains(tid);
125 }
126 if (!contains) {
127 DumpUnattachedThread(os, tid);
128 }
Elliott Hughesabbe07d2012-06-05 17:42:23 -0700129 }
130 }
131 closedir(d);
Elliott Hughesff738062012-02-03 15:00:42 -0800132}
133
134void ThreadList::DumpLocked(std::ostream& os) {
Elliott Hughes8daa0922011-09-11 13:46:25 -0700135 os << "DALVIK THREADS (" << list_.size() << "):\n";
Mathieu Chartier02e25112013-08-14 16:14:24 -0700136 for (const auto& thread : list_) {
137 thread->Dump(os);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700138 os << "\n";
139 }
140}
141
Ian Rogers50b35e22012-10-04 10:09:15 -0700142void ThreadList::AssertThreadsAreSuspended(Thread* self, Thread* ignore1, Thread* ignore2) {
143 MutexLock mu(self, *Locks::thread_list_lock_);
144 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700145 for (const auto& thread : list_) {
jeffhao725a9572012-11-13 18:20:12 -0800146 if (thread != ignore1 && thread != ignore2) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700147 CHECK(thread->IsSuspended())
148 << "\nUnsuspended thread: <<" << *thread << "\n"
149 << "self: <<" << *Thread::Current();
150 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700151 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700152}
153
Ian Rogers66aee5c2012-08-15 17:17:47 -0700154#if HAVE_TIMED_RWLOCK
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700155// Attempt to rectify locks so that we dump thread list with required locks before exiting.
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100156static void UnsafeLogFatalForThreadSuspendAllTimeout() NO_THREAD_SAFETY_ANALYSIS __attribute__((noreturn));
157static void UnsafeLogFatalForThreadSuspendAllTimeout() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700158 Runtime* runtime = Runtime::Current();
159 std::ostringstream ss;
160 ss << "Thread suspend timeout\n";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700161 runtime->GetThreadList()->DumpLocked(ss);
162 LOG(FATAL) << ss.str();
Ian Rogers719d1a32014-03-06 12:13:39 -0800163 exit(0);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700164}
Ian Rogers66aee5c2012-08-15 17:17:47 -0700165#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700166
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800167// Unlike suspending all threads where we can wait to acquire the mutator_lock_, suspending an
168// individual thread requires polling. delay_us is the requested sleep and total_delay_us
169// accumulates the total time spent sleeping for timeouts. The first sleep is just a yield,
170// subsequently sleeps increase delay_us from 1ms to 500ms by doubling.
171static void ThreadSuspendSleep(Thread* self, useconds_t* delay_us, useconds_t* total_delay_us,
172 bool holding_locks) {
173 if (!holding_locks) {
174 for (int i = kLockLevelCount - 1; i >= 0; --i) {
175 BaseMutex* held_mutex = self->GetHeldMutex(static_cast<LockLevel>(i));
176 if (held_mutex != NULL) {
177 LOG(FATAL) << "Holding " << held_mutex->GetName() << " while sleeping for thread suspension";
178 }
179 }
180 }
181 useconds_t new_delay_us = (*delay_us) * 2;
182 CHECK_GE(new_delay_us, *delay_us);
183 if (new_delay_us < 500000) { // Don't allow sleeping to be more than 0.5s.
184 *delay_us = new_delay_us;
185 }
186 if (*delay_us == 0) {
187 sched_yield();
188 // Default to 1 milliseconds (note that this gets multiplied by 2 before the first sleep).
189 *delay_us = 500;
190 } else {
191 usleep(*delay_us);
192 *total_delay_us += *delay_us;
193 }
194}
195
Mathieu Chartier0e4627e2012-10-23 16:13:36 -0700196size_t ThreadList::RunCheckpoint(Closure* checkpoint_function) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700197 Thread* self = Thread::Current();
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800198 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
199 Locks::thread_list_lock_->AssertNotHeld(self);
200 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
201 if (kDebugLocking) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700202 CHECK_NE(self->GetState(), kRunnable);
203 }
204
205 std::vector<Thread*> suspended_count_modified_threads;
206 size_t count = 0;
207 {
208 // Call a checkpoint function for each thread, threads which are suspend get their checkpoint
209 // manually called.
210 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700211 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700212 for (const auto& thread : list_) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700213 if (thread != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700214 while (true) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700215 if (thread->RequestCheckpoint(checkpoint_function)) {
Dave Allison0aded082013-11-07 13:15:11 -0800216 // This thread will run its checkpoint some time in the near future.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700217 count++;
218 break;
219 } else {
220 // We are probably suspended, try to make sure that we stay suspended.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700221 // The thread switched back to runnable.
222 if (thread->GetState() == kRunnable) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700223 // Spurious fail, try again.
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700224 continue;
225 }
226 thread->ModifySuspendCount(self, +1, false);
227 suspended_count_modified_threads.push_back(thread);
228 break;
229 }
230 }
231 }
232 }
233 }
234
235 // Run the checkpoint on ourself while we wait for threads to suspend.
236 checkpoint_function->Run(self);
237
238 // Run the checkpoint on the suspended threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700239 for (const auto& thread : suspended_count_modified_threads) {
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700240 if (!thread->IsSuspended()) {
241 // Wait until the thread is suspended.
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800242 useconds_t total_delay_us = 0;
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700243 do {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800244 useconds_t delay_us = 100;
245 ThreadSuspendSleep(self, &delay_us, &total_delay_us, true);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700246 } while (!thread->IsSuspended());
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800247 // Shouldn't need to wait for longer than 1000 microseconds.
248 constexpr useconds_t kLongWaitThresholdUS = 1000;
249 if (UNLIKELY(total_delay_us > kLongWaitThresholdUS)) {
250 LOG(WARNING) << "Waited " << total_delay_us << " us for thread suspend!";
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700251 }
252 }
253 // We know for sure that the thread is suspended at this point.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700254 checkpoint_function->Run(thread);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700255 {
256 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
257 thread->ModifySuspendCount(self, -1, false);
258 }
259 }
260
Mathieu Chartier664bebf2012-11-12 16:54:11 -0800261 {
262 // Imitate ResumeAll, threads may be waiting on Thread::resume_cond_ since we raised their
263 // suspend count. Now the suspend_count_ is lowered so we must do the broadcast.
264 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
265 Thread::resume_cond_->Broadcast(self);
266 }
267
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700268 // Add one for self.
269 return count + suspended_count_modified_threads.size() + 1;
270}
271
Dave Allison39c3bfb2014-01-28 18:33:52 -0800272// Request that a checkpoint function be run on all active (non-suspended)
273// threads. Returns the number of successful requests.
274size_t ThreadList::RunCheckpointOnRunnableThreads(Closure* checkpoint_function) {
275 Thread* self = Thread::Current();
276 if (kIsDebugBuild) {
277 Locks::mutator_lock_->AssertNotExclusiveHeld(self);
278 Locks::thread_list_lock_->AssertNotHeld(self);
279 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
280 CHECK_NE(self->GetState(), kRunnable);
281 }
282
283 size_t count = 0;
284 {
285 // Call a checkpoint function for each non-suspended thread.
286 MutexLock mu(self, *Locks::thread_list_lock_);
287 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
288 for (const auto& thread : list_) {
289 if (thread != self) {
290 if (thread->RequestCheckpoint(checkpoint_function)) {
291 // This thread will run its checkpoint some time in the near future.
292 count++;
293 }
294 }
295 }
296 }
297
298 // Return the number of threads that will run the checkpoint function.
299 return count;
300}
301
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700302void ThreadList::SuspendAll() {
303 Thread* self = Thread::Current();
Brian Carlstrom6449c622014-02-10 23:48:36 -0800304 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700305
306 VLOG(threads) << *self << " SuspendAll starting...";
307
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700308 ATRACE_BEGIN("Suspending mutator threads");
309
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800310 Locks::mutator_lock_->AssertNotHeld(self);
311 Locks::thread_list_lock_->AssertNotHeld(self);
312 Locks::thread_suspend_count_lock_->AssertNotHeld(self);
313 if (kDebugLocking) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700314 CHECK_NE(self->GetState(), kRunnable);
315 }
316 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700317 MutexLock mu(self, *Locks::thread_list_lock_);
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800318 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
319 // Update global suspend all state for attaching threads.
320 ++suspend_all_count_;
321 // Increment everybody's suspend count (except our own).
322 for (const auto& thread : list_) {
323 if (thread == self) {
324 continue;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700325 }
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800326 VLOG(threads) << "requesting thread suspend: " << *thread;
327 thread->ModifySuspendCount(self, +1, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700328 }
329 }
330
Ian Rogers66aee5c2012-08-15 17:17:47 -0700331 // Block on the mutator lock until all Runnable threads release their share of access.
332#if HAVE_TIMED_RWLOCK
333 // Timeout if we wait more than 30 seconds.
Ian Rogers719d1a32014-03-06 12:13:39 -0800334 if (!Locks::mutator_lock_->ExclusiveLockWithTimeout(self, 30 * 1000, 0)) {
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100335 UnsafeLogFatalForThreadSuspendAllTimeout();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700336 }
Ian Rogers66aee5c2012-08-15 17:17:47 -0700337#else
Ian Rogers81d425b2012-09-27 16:03:43 -0700338 Locks::mutator_lock_->ExclusiveLock(self);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700339#endif
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700340
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800341 if (kDebugLocking) {
342 // Debug check that all threads are suspended.
343 AssertThreadsAreSuspended(self, self);
344 }
Elliott Hughes8d768a92011-09-14 16:35:25 -0700345
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700346 ATRACE_END();
347 ATRACE_BEGIN("Mutator threads suspended");
348
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800349 VLOG(threads) << *self << " SuspendAll complete";
Elliott Hughes8d768a92011-09-14 16:35:25 -0700350}
351
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700352void ThreadList::ResumeAll() {
353 Thread* self = Thread::Current();
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100354 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700355
356 VLOG(threads) << *self << " ResumeAll starting";
Ian Rogers01ae5802012-09-28 16:14:01 -0700357
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700358 ATRACE_END();
359 ATRACE_BEGIN("Resuming mutator threads");
360
Mathieu Chartier6dda8982014-03-06 11:11:48 -0800361 if (kDebugLocking) {
362 // Debug check that all threads are suspended.
363 AssertThreadsAreSuspended(self, self);
364 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700365
Ian Rogers81d425b2012-09-27 16:03:43 -0700366 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700367 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700368 MutexLock mu(self, *Locks::thread_list_lock_);
369 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700370 // Update global suspend all state for attaching threads.
371 --suspend_all_count_;
372 // Decrement the suspend counts for all threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700373 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700374 if (thread == self) {
375 continue;
376 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700377 thread->ModifySuspendCount(self, -1, false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700378 }
379
380 // Broadcast a notification to all suspended threads, some or all of
381 // which may choose to wake up. No need to wait for them.
382 VLOG(threads) << *self << " ResumeAll waking others";
Ian Rogersc604d732012-10-14 16:09:54 -0700383 Thread::resume_cond_->Broadcast(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700384 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700385 ATRACE_END();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700386 VLOG(threads) << *self << " ResumeAll complete";
387}
388
389void ThreadList::Resume(Thread* thread, bool for_debugger) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700390 Thread* self = Thread::Current();
391 DCHECK_NE(thread, self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700392 VLOG(threads) << "Resume(" << *thread << ") starting..." << (for_debugger ? " (debugger)" : "");
Elliott Hughes01158d72011-09-19 19:47:10 -0700393
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700394 {
395 // To check Contains.
Ian Rogers81d425b2012-09-27 16:03:43 -0700396 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700397 // To check IsSuspended.
Ian Rogers81d425b2012-09-27 16:03:43 -0700398 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
399 DCHECK(thread->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700400 if (!Contains(thread)) {
401 return;
402 }
Ian Rogers01ae5802012-09-28 16:14:01 -0700403 thread->ModifySuspendCount(self, -1, for_debugger);
Elliott Hughes01158d72011-09-19 19:47:10 -0700404 }
405
406 {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700407 VLOG(threads) << "Resume(" << *thread << ") waking others";
Ian Rogers81d425b2012-09-27 16:03:43 -0700408 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700409 Thread::resume_cond_->Broadcast(self);
Elliott Hughes01158d72011-09-19 19:47:10 -0700410 }
411
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700412 VLOG(threads) << "Resume(" << *thread << ") complete";
413}
Elliott Hughes01158d72011-09-19 19:47:10 -0700414
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700415static void ThreadSuspendByPeerWarning(Thread* self, int level, const char* message, jobject peer) {
416 JNIEnvExt* env = self->GetJniEnv();
417 ScopedLocalRef<jstring>
418 scoped_name_string(env, (jstring)env->GetObjectField(peer,
419 WellKnownClasses::java_lang_Thread_name));
420 ScopedUtfChars scoped_name_chars(env, scoped_name_string.get());
421 if (scoped_name_chars.c_str() == NULL) {
422 LOG(level) << message << ": " << peer;
423 env->ExceptionClear();
424 } else {
425 LOG(level) << message << ": " << peer << ":" << scoped_name_chars.c_str();
426 }
427}
428
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700429Thread* ThreadList::SuspendThreadByPeer(jobject peer, bool request_suspension,
430 bool debug_suspension, bool* timed_out) {
431 static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
432 useconds_t total_delay_us = 0;
433 useconds_t delay_us = 0;
434 bool did_suspend_request = false;
435 *timed_out = false;
436 Thread* self = Thread::Current();
437 while (true) {
438 Thread* thread;
439 {
440 ScopedObjectAccess soa(self);
441 MutexLock mu(self, *Locks::thread_list_lock_);
442 thread = Thread::FromManagedThread(soa, peer);
443 if (thread == NULL) {
444 ThreadSuspendByPeerWarning(self, WARNING, "No such thread for suspend", peer);
445 return NULL;
446 }
447 {
448 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
449 if (request_suspension) {
450 thread->ModifySuspendCount(self, +1, debug_suspension);
451 request_suspension = false;
452 did_suspend_request = true;
453 } else {
454 // If the caller isn't requesting suspension, a suspension should have already occurred.
455 CHECK_GT(thread->GetSuspendCount(), 0);
456 }
457 // IsSuspended on the current thread will fail as the current thread is changed into
458 // Runnable above. As the suspend count is now raised if this is the current thread
459 // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
460 // to just explicitly handle the current thread in the callers to this code.
461 CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
462 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
463 // count, or else we've waited and it has self suspended) or is the current thread, we're
464 // done.
465 if (thread->IsSuspended()) {
466 return thread;
467 }
468 if (total_delay_us >= kTimeoutUs) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700469 ThreadSuspendByPeerWarning(self, FATAL, "Thread suspension timed out", peer);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700470 if (did_suspend_request) {
471 thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
472 }
473 *timed_out = true;
474 return NULL;
475 }
476 }
477 // Release locks and come out of runnable state.
478 }
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800479 ThreadSuspendSleep(self, &delay_us, &total_delay_us, false);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700480 }
481}
482
483static void ThreadSuspendByThreadIdWarning(int level, const char* message, uint32_t thread_id) {
484 LOG(level) << StringPrintf("%s: %d", message, thread_id);
485}
486
487Thread* ThreadList::SuspendThreadByThreadId(uint32_t thread_id, bool debug_suspension,
488 bool* timed_out) {
489 static const useconds_t kTimeoutUs = 30 * 1000000; // 30s.
490 useconds_t total_delay_us = 0;
491 useconds_t delay_us = 0;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700492 *timed_out = false;
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800493 Thread* suspended_thread = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700494 Thread* self = Thread::Current();
495 CHECK_NE(thread_id, kInvalidThreadId);
496 while (true) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700497 {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800498 Thread* thread = NULL;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700499 ScopedObjectAccess soa(self);
500 MutexLock mu(self, *Locks::thread_list_lock_);
501 for (const auto& it : list_) {
502 if (it->GetThreadId() == thread_id) {
503 thread = it;
504 break;
505 }
506 }
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800507 if (thread == nullptr) {
508 CHECK(suspended_thread == nullptr) << "Suspended thread " << suspended_thread
509 << " no longer in thread list";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700510 // There's a race in inflating a lock and the owner giving up ownership and then dying.
511 ThreadSuspendByThreadIdWarning(WARNING, "No such thread id for suspend", thread_id);
512 return NULL;
513 }
514 {
515 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800516 if (suspended_thread == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700517 thread->ModifySuspendCount(self, +1, debug_suspension);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800518 suspended_thread = thread;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700519 } else {
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800520 CHECK_EQ(suspended_thread, thread);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700521 // If the caller isn't requesting suspension, a suspension should have already occurred.
522 CHECK_GT(thread->GetSuspendCount(), 0);
523 }
524 // IsSuspended on the current thread will fail as the current thread is changed into
525 // Runnable above. As the suspend count is now raised if this is the current thread
526 // it will self suspend on transition to Runnable, making it hard to work with. It's simpler
527 // to just explicitly handle the current thread in the callers to this code.
528 CHECK_NE(thread, self) << "Attempt to suspend the current thread for the debugger";
529 // If thread is suspended (perhaps it was already not Runnable but didn't have a suspend
530 // count, or else we've waited and it has self suspended) or is the current thread, we're
531 // done.
532 if (thread->IsSuspended()) {
533 return thread;
534 }
535 if (total_delay_us >= kTimeoutUs) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700536 ThreadSuspendByThreadIdWarning(WARNING, "Thread suspension timed out", thread_id);
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800537 if (suspended_thread != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700538 thread->ModifySuspendCount(soa.Self(), -1, debug_suspension);
539 }
540 *timed_out = true;
541 return NULL;
542 }
543 }
544 // Release locks and come out of runnable state.
545 }
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800546 ThreadSuspendSleep(self, &delay_us, &total_delay_us, false);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700547 }
548}
549
550Thread* ThreadList::FindThreadByThreadId(uint32_t thin_lock_id) {
551 Thread* self = Thread::Current();
552 MutexLock mu(self, *Locks::thread_list_lock_);
553 for (const auto& thread : list_) {
554 if (thread->GetThreadId() == thin_lock_id) {
555 CHECK(thread == self || thread->IsSuspended());
556 return thread;
557 }
558 }
559 return NULL;
560}
561
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700562void ThreadList::SuspendAllForDebugger() {
563 Thread* self = Thread::Current();
564 Thread* debug_thread = Dbg::GetDebugThread();
565
566 VLOG(threads) << *self << " SuspendAllForDebugger starting...";
567
568 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700569 MutexLock mu(self, *Locks::thread_list_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700570 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700571 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700572 // Update global suspend all state for attaching threads.
573 ++suspend_all_count_;
574 ++debug_suspend_all_count_;
575 // Increment everybody's suspend count (except our own).
Mathieu Chartier02e25112013-08-14 16:14:24 -0700576 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700577 if (thread == self || thread == debug_thread) {
578 continue;
579 }
580 VLOG(threads) << "requesting thread suspend: " << *thread;
Ian Rogers01ae5802012-09-28 16:14:01 -0700581 thread->ModifySuspendCount(self, +1, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700582 }
583 }
584 }
585
Ian Rogers66aee5c2012-08-15 17:17:47 -0700586 // Block on the mutator lock until all Runnable threads release their share of access then
587 // immediately unlock again.
588#if HAVE_TIMED_RWLOCK
589 // Timeout if we wait more than 30 seconds.
Ian Rogersc604d732012-10-14 16:09:54 -0700590 if (!Locks::mutator_lock_->ExclusiveLockWithTimeout(self, 30 * 1000, 0)) {
Sebastien Hertzbae182c2013-12-17 10:42:03 +0100591 UnsafeLogFatalForThreadSuspendAllTimeout();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700592 } else {
Ian Rogers81d425b2012-09-27 16:03:43 -0700593 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700594 }
Ian Rogers66aee5c2012-08-15 17:17:47 -0700595#else
Ian Rogers81d425b2012-09-27 16:03:43 -0700596 Locks::mutator_lock_->ExclusiveLock(self);
597 Locks::mutator_lock_->ExclusiveUnlock(self);
Ian Rogers66aee5c2012-08-15 17:17:47 -0700598#endif
Ian Rogers50b35e22012-10-04 10:09:15 -0700599 AssertThreadsAreSuspended(self, self, debug_thread);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700600
601 VLOG(threads) << *self << " SuspendAll complete";
Elliott Hughes01158d72011-09-19 19:47:10 -0700602}
603
Elliott Hughes475fc232011-10-25 15:00:35 -0700604void ThreadList::SuspendSelfForDebugger() {
605 Thread* self = Thread::Current();
Elliott Hughes01158d72011-09-19 19:47:10 -0700606
Elliott Hughes475fc232011-10-25 15:00:35 -0700607 // The debugger thread must not suspend itself due to debugger activity!
608 Thread* debug_thread = Dbg::GetDebugThread();
609 CHECK(debug_thread != NULL);
610 CHECK(self != debug_thread);
jeffhaoa77f0f62012-12-05 17:19:31 -0800611 CHECK_NE(self->GetState(), kRunnable);
612 Locks::mutator_lock_->AssertNotHeld(self);
Elliott Hughes475fc232011-10-25 15:00:35 -0700613
jeffhaoa77f0f62012-12-05 17:19:31 -0800614 {
615 // Collisions with other suspends aren't really interesting. We want
616 // to ensure that we're the only one fiddling with the suspend count
617 // though.
618 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
619 self->ModifySuspendCount(self, +1, true);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700620 CHECK_GT(self->GetSuspendCount(), 0);
jeffhaoa77f0f62012-12-05 17:19:31 -0800621 }
Elliott Hughes475fc232011-10-25 15:00:35 -0700622
Elliott Hughes1f729aa2012-03-02 13:55:41 -0800623 VLOG(threads) << *self << " self-suspending (debugger)";
Elliott Hughes475fc232011-10-25 15:00:35 -0700624
Sebastien Hertz21e729c2014-02-18 14:16:00 +0100625 // Tell JDWP we've completed invocation and are ready to suspend.
626 DebugInvokeReq* pReq = self->GetInvokeReq();
627 DCHECK(pReq != NULL);
628 if (pReq->invoke_needed) {
629 // Clear this before signaling.
Sebastien Hertzbb43b432014-04-14 11:59:08 +0200630 pReq->Clear();
Sebastien Hertz21e729c2014-02-18 14:16:00 +0100631
632 VLOG(jdwp) << "invoke complete, signaling";
633 MutexLock mu(self, pReq->lock);
634 pReq->cond.Signal(self);
635 }
636
Elliott Hughes475fc232011-10-25 15:00:35 -0700637 // Tell JDWP that we've completed suspension. The JDWP thread can't
638 // tell us to resume before we're fully asleep because we hold the
639 // suspend count lock.
640 Dbg::ClearWaitForEventThread();
641
jeffhaoa77f0f62012-12-05 17:19:31 -0800642 {
643 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700644 while (self->GetSuspendCount() != 0) {
jeffhaoa77f0f62012-12-05 17:19:31 -0800645 Thread::resume_cond_->Wait(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700646 if (self->GetSuspendCount() != 0) {
jeffhaoa77f0f62012-12-05 17:19:31 -0800647 // The condition was signaled but we're still suspended. This
648 // can happen if the debugger lets go while a SIGQUIT thread
649 // dump event is pending (assuming SignalCatcher was resumed for
650 // just long enough to try to grab the thread-suspend lock).
Brian Carlstrom4d466a82014-05-08 19:05:29 -0700651 LOG(WARNING) << *self << " still suspended after undo "
Ian Rogersdd7624d2014-03-14 17:43:00 -0700652 << "(suspend count=" << self->GetSuspendCount() << ")";
jeffhaoa77f0f62012-12-05 17:19:31 -0800653 }
Elliott Hughes475fc232011-10-25 15:00:35 -0700654 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700655 CHECK_EQ(self->GetSuspendCount(), 0);
Elliott Hughes475fc232011-10-25 15:00:35 -0700656 }
jeffhaoa77f0f62012-12-05 17:19:31 -0800657
Elliott Hughes1f729aa2012-03-02 13:55:41 -0800658 VLOG(threads) << *self << " self-reviving (debugger)";
Elliott Hughes475fc232011-10-25 15:00:35 -0700659}
660
Elliott Hughes234ab152011-10-26 14:02:26 -0700661void ThreadList::UndoDebuggerSuspensions() {
662 Thread* self = Thread::Current();
663
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800664 VLOG(threads) << *self << " UndoDebuggerSuspensions starting";
Elliott Hughes234ab152011-10-26 14:02:26 -0700665
666 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700667 MutexLock mu(self, *Locks::thread_list_lock_);
668 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700669 // Update global suspend all state for attaching threads.
670 suspend_all_count_ -= debug_suspend_all_count_;
671 debug_suspend_all_count_ = 0;
672 // Update running threads.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700673 for (const auto& thread : list_) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700674 if (thread == self || thread->GetDebugSuspendCount() == 0) {
Elliott Hughes234ab152011-10-26 14:02:26 -0700675 continue;
676 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700677 thread->ModifySuspendCount(self, -thread->GetDebugSuspendCount(), true);
Elliott Hughes234ab152011-10-26 14:02:26 -0700678 }
679 }
680
681 {
Ian Rogers81d425b2012-09-27 16:03:43 -0700682 MutexLock mu(self, *Locks::thread_suspend_count_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700683 Thread::resume_cond_->Broadcast(self);
Elliott Hughes234ab152011-10-26 14:02:26 -0700684 }
685
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800686 VLOG(threads) << "UndoDebuggerSuspensions(" << *self << ") complete";
Elliott Hughes234ab152011-10-26 14:02:26 -0700687}
688
Elliott Hughese52e49b2012-04-02 16:05:44 -0700689void ThreadList::WaitForOtherNonDaemonThreadsToExit() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700690 Thread* self = Thread::Current();
691 Locks::mutator_lock_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700692 bool all_threads_are_daemons;
693 do {
Ian Rogers120f1c72012-09-28 17:17:10 -0700694 {
695 // No more threads can be born after we start to shutdown.
696 MutexLock mu(self, *Locks::runtime_shutdown_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700697 CHECK(Runtime::Current()->IsShuttingDownLocked());
Ian Rogers120f1c72012-09-28 17:17:10 -0700698 CHECK_EQ(Runtime::Current()->NumberOfThreadsBeingBorn(), 0U);
699 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700700 all_threads_are_daemons = true;
Ian Rogers120f1c72012-09-28 17:17:10 -0700701 MutexLock mu(self, *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700702 for (const auto& thread : list_) {
Anwar Ghuloum97543682013-06-14 12:58:16 -0700703 if (thread != self && !thread->IsDaemon()) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700704 all_threads_are_daemons = false;
705 break;
706 }
707 }
708 if (!all_threads_are_daemons) {
709 // Wait for another thread to exit before re-checking.
Ian Rogersc604d732012-10-14 16:09:54 -0700710 thread_exit_cond_.Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700711 }
Brian Carlstromdf629502013-07-17 22:39:56 -0700712 } while (!all_threads_are_daemons);
Elliott Hughes038a8062011-09-18 14:12:41 -0700713}
714
715void ThreadList::SuspendAllDaemonThreads() {
Ian Rogers81d425b2012-09-27 16:03:43 -0700716 Thread* self = Thread::Current();
717 MutexLock mu(self, *Locks::thread_list_lock_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700718 { // Tell all the daemons it's time to suspend.
Ian Rogers81d425b2012-09-27 16:03:43 -0700719 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700720 for (const auto& thread : list_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700721 // This is only run after all non-daemon threads have exited, so the remainder should all be
722 // daemons.
Ian Rogers7e762862012-10-22 15:45:08 -0700723 CHECK(thread->IsDaemon()) << *thread;
Ian Rogers81d425b2012-09-27 16:03:43 -0700724 if (thread != self) {
Ian Rogers01ae5802012-09-28 16:14:01 -0700725 thread->ModifySuspendCount(self, +1, false);
Elliott Hughese52e49b2012-04-02 16:05:44 -0700726 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700727 }
728 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700729 // Give the threads a chance to suspend, complaining if they're slow.
730 bool have_complained = false;
731 for (int i = 0; i < 10; ++i) {
732 usleep(200 * 1000);
733 bool all_suspended = true;
Mathieu Chartier02e25112013-08-14 16:14:24 -0700734 for (const auto& thread : list_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700735 if (thread != self && thread->GetState() == kRunnable) {
Elliott Hughes038a8062011-09-18 14:12:41 -0700736 if (!have_complained) {
737 LOG(WARNING) << "daemon thread not yet suspended: " << *thread;
738 have_complained = true;
739 }
740 all_suspended = false;
741 }
742 }
743 if (all_suspended) {
744 return;
745 }
746 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700747 LOG(ERROR) << "suspend all daemons failed";
748}
749void ThreadList::Register(Thread* self) {
750 DCHECK_EQ(self, Thread::Current());
751
752 if (VLOG_IS_ON(threads)) {
753 std::ostringstream oss;
754 self->ShortDump(oss); // We don't hold the mutator_lock_ yet and so cannot call Dump.
Ian Rogers5a9ba012014-05-19 13:28:52 -0700755 LOG(INFO) << "ThreadList::Register() " << *self << "\n" << oss.str();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700756 }
757
758 // Atomically add self to the thread list and make its thread_suspend_count_ reflect ongoing
759 // SuspendAll requests.
Ian Rogers81d425b2012-09-27 16:03:43 -0700760 MutexLock mu(self, *Locks::thread_list_lock_);
761 MutexLock mu2(self, *Locks::thread_suspend_count_lock_);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700762 CHECK_GE(suspend_all_count_, debug_suspend_all_count_);
Ian Rogers2966e132014-04-02 08:34:36 -0700763 // Modify suspend count in increments of 1 to maintain invariants in ModifySuspendCount. While
764 // this isn't particularly efficient the suspend counts are most commonly 0 or 1.
765 for (int delta = debug_suspend_all_count_; delta > 0; delta--) {
766 self->ModifySuspendCount(self, +1, true);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700767 }
Ian Rogers2966e132014-04-02 08:34:36 -0700768 for (int delta = suspend_all_count_ - debug_suspend_all_count_; delta > 0; delta--) {
769 self->ModifySuspendCount(self, +1, false);
Ian Rogers01ae5802012-09-28 16:14:01 -0700770 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700771 CHECK(!Contains(self));
772 list_.push_back(self);
773}
774
775void ThreadList::Unregister(Thread* self) {
776 DCHECK_EQ(self, Thread::Current());
777
778 VLOG(threads) << "ThreadList::Unregister() " << *self;
779
780 // Any time-consuming destruction, plus anything that can call back into managed code or
781 // suspend and so on, must happen at this point, and not in ~Thread.
782 self->Destroy();
783
Ian Rogersdd7624d2014-03-14 17:43:00 -0700784 uint32_t thin_lock_id = self->GetThreadId();
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800785 while (self != nullptr) {
Ian Rogerscfaa4552012-11-26 21:00:08 -0800786 // Remove and delete the Thread* while holding the thread_list_lock_ and
787 // thread_suspend_count_lock_ so that the unregistering thread cannot be suspended.
Ian Rogers0878d652013-04-18 17:38:35 -0700788 // Note: deliberately not using MutexLock that could hold a stale self pointer.
789 Locks::thread_list_lock_->ExclusiveLock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700790 CHECK(Contains(self));
Ian Rogerscfaa4552012-11-26 21:00:08 -0800791 // Note: we don't take the thread_suspend_count_lock_ here as to be suspending a thread other
792 // than yourself you need to hold the thread_list_lock_ (see Thread::ModifySuspendCount).
793 if (!self->IsSuspended()) {
794 list_.remove(self);
795 delete self;
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800796 self = nullptr;
Ian Rogerscfaa4552012-11-26 21:00:08 -0800797 }
Ian Rogers0878d652013-04-18 17:38:35 -0700798 Locks::thread_list_lock_->ExclusiveUnlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700799 }
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800800 // Release the thread ID after the thread is finished and deleted to avoid cases where we can
801 // temporarily have multiple threads with the same thread id. When this occurs, it causes
802 // problems in FindThreadByThreadId / SuspendThreadByThreadId.
803 ReleaseThreadId(nullptr, thin_lock_id);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700804
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700805 // Clear the TLS data, so that the underlying native thread is recognizably detached.
806 // (It may wish to reattach later.)
807 CHECK_PTHREAD_CALL(pthread_setspecific, (Thread::pthread_key_self_, NULL), "detach self");
808
809 // Signal that a thread just detached.
Ian Rogers81d425b2012-09-27 16:03:43 -0700810 MutexLock mu(NULL, *Locks::thread_list_lock_);
Ian Rogersc604d732012-10-14 16:09:54 -0700811 thread_exit_cond_.Signal(NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700812}
813
814void ThreadList::ForEach(void (*callback)(Thread*, void*), void* context) {
Mathieu Chartier02e25112013-08-14 16:14:24 -0700815 for (const auto& thread : list_) {
816 callback(thread, context);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700817 }
818}
819
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800820void ThreadList::VisitRoots(RootCallback* callback, void* arg) const {
Ian Rogers81d425b2012-09-27 16:03:43 -0700821 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700822 for (const auto& thread : list_) {
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800823 thread->VisitRoots(callback, arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700824 }
Elliott Hughes038a8062011-09-18 14:12:41 -0700825}
826
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800827class VerifyRootWrapperArg {
828 public:
829 VerifyRootWrapperArg(VerifyRootCallback* callback, void* arg) : callback_(callback), arg_(arg) {
830 }
831 VerifyRootCallback* const callback_;
832 void* const arg_;
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700833};
834
Mathieu Chartier815873e2014-02-13 18:02:13 -0800835static void VerifyRootWrapperCallback(mirror::Object** root, void* arg, uint32_t /*thread_id*/,
Mathieu Chartier7bf9f192014-04-04 11:09:41 -0700836 RootType root_type) {
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700837 VerifyRootWrapperArg* wrapperArg = reinterpret_cast<VerifyRootWrapperArg*>(arg);
Mathieu Chartier7bf9f192014-04-04 11:09:41 -0700838 wrapperArg->callback_(*root, wrapperArg->arg_, 0, NULL, root_type);
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700839}
840
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800841void ThreadList::VerifyRoots(VerifyRootCallback* callback, void* arg) const {
842 VerifyRootWrapperArg wrapper(callback, arg);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700843 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700844 for (const auto& thread : list_) {
Mathieu Chartier423d2a32013-09-12 17:33:56 -0700845 thread->VisitRoots(VerifyRootWrapperCallback, &wrapper);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700846 }
847}
848
Ian Rogerscfaa4552012-11-26 21:00:08 -0800849uint32_t ThreadList::AllocThreadId(Thread* self) {
Chao-ying Fu9e369312014-05-21 11:20:52 -0700850 MutexLock mu(self, *Locks::allocated_thread_ids_lock_);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700851 for (size_t i = 0; i < allocated_ids_.size(); ++i) {
852 if (!allocated_ids_[i]) {
853 allocated_ids_.set(i);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700854 return i + 1; // Zero is reserved to mean "invalid".
Elliott Hughes8daa0922011-09-11 13:46:25 -0700855 }
856 }
857 LOG(FATAL) << "Out of internal thread ids";
858 return 0;
859}
860
Ian Rogerscfaa4552012-11-26 21:00:08 -0800861void ThreadList::ReleaseThreadId(Thread* self, uint32_t id) {
Chao-ying Fu9e369312014-05-21 11:20:52 -0700862 MutexLock mu(self, *Locks::allocated_thread_ids_lock_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700863 --id; // Zero is reserved to mean "invalid".
Elliott Hughes8daa0922011-09-11 13:46:25 -0700864 DCHECK(allocated_ids_[id]) << id;
865 allocated_ids_.reset(id);
866}
867
Elliott Hughes8daa0922011-09-11 13:46:25 -0700868} // namespace art