1 //===-- ThreadList.cpp ------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
16 // Other libraries and framework includes
18 #include "lldb/Core/State.h"
19 #include "lldb/Target/Process.h"
20 #include "lldb/Target/RegisterContext.h"
21 #include "lldb/Target/Thread.h"
22 #include "lldb/Target/ThreadList.h"
23 #include "lldb/Target/ThreadPlan.h"
24 #include "lldb/Utility/LLDBAssert.h"
25 #include "lldb/Utility/Log.h"
28 using namespace lldb_private;
30 ThreadList::ThreadList(Process *process)
31 : ThreadCollection(), m_process(process), m_stop_id(0),
32 m_selected_tid(LLDB_INVALID_THREAD_ID) {}
34 ThreadList::ThreadList(const ThreadList &rhs)
35 : ThreadCollection(), m_process(rhs.m_process), m_stop_id(rhs.m_stop_id),
37 // Use the assignment operator since it uses the mutex
41 const ThreadList &ThreadList::operator=(const ThreadList &rhs) {
43 // Lock both mutexes to make sure neither side changes anyone on us
44 // while the assignment occurs
45 std::lock_guard<std::recursive_mutex> guard(GetMutex());
46 std::lock_guard<std::recursive_mutex> rhs_guard(rhs.GetMutex());
48 m_process = rhs.m_process;
49 m_stop_id = rhs.m_stop_id;
50 m_threads = rhs.m_threads;
51 m_selected_tid = rhs.m_selected_tid;
56 ThreadList::~ThreadList() {
57 // Clear the thread list. Clear will take the mutex lock
58 // which will ensure that if anyone is using the list
59 // they won't get it removed while using it.
63 lldb::ThreadSP ThreadList::GetExpressionExecutionThread() {
64 if (m_expression_tid_stack.empty())
65 return GetSelectedThread();
66 ThreadSP expr_thread_sp = FindThreadByID(m_expression_tid_stack.back());
68 return expr_thread_sp;
70 return GetSelectedThread();
73 void ThreadList::PushExpressionExecutionThread(lldb::tid_t tid) {
74 m_expression_tid_stack.push_back(tid);
77 void ThreadList::PopExpressionExecutionThread(lldb::tid_t tid) {
78 assert(m_expression_tid_stack.back() == tid);
79 m_expression_tid_stack.pop_back();
82 uint32_t ThreadList::GetStopID() const { return m_stop_id; }
84 void ThreadList::SetStopID(uint32_t stop_id) { m_stop_id = stop_id; }
86 uint32_t ThreadList::GetSize(bool can_update) {
87 std::lock_guard<std::recursive_mutex> guard(GetMutex());
90 m_process->UpdateThreadListIfNeeded();
91 return m_threads.size();
94 ThreadSP ThreadList::GetThreadAtIndex(uint32_t idx, bool can_update) {
95 std::lock_guard<std::recursive_mutex> guard(GetMutex());
98 m_process->UpdateThreadListIfNeeded();
101 if (idx < m_threads.size())
102 thread_sp = m_threads[idx];
106 ThreadSP ThreadList::FindThreadByID(lldb::tid_t tid, bool can_update) {
107 std::lock_guard<std::recursive_mutex> guard(GetMutex());
110 m_process->UpdateThreadListIfNeeded();
114 const uint32_t num_threads = m_threads.size();
115 for (idx = 0; idx < num_threads; ++idx) {
116 if (m_threads[idx]->GetID() == tid) {
117 thread_sp = m_threads[idx];
124 ThreadSP ThreadList::FindThreadByProtocolID(lldb::tid_t tid, bool can_update) {
125 std::lock_guard<std::recursive_mutex> guard(GetMutex());
128 m_process->UpdateThreadListIfNeeded();
132 const uint32_t num_threads = m_threads.size();
133 for (idx = 0; idx < num_threads; ++idx) {
134 if (m_threads[idx]->GetProtocolID() == tid) {
135 thread_sp = m_threads[idx];
142 ThreadSP ThreadList::RemoveThreadByID(lldb::tid_t tid, bool can_update) {
143 std::lock_guard<std::recursive_mutex> guard(GetMutex());
146 m_process->UpdateThreadListIfNeeded();
150 const uint32_t num_threads = m_threads.size();
151 for (idx = 0; idx < num_threads; ++idx) {
152 if (m_threads[idx]->GetID() == tid) {
153 thread_sp = m_threads[idx];
154 m_threads.erase(m_threads.begin() + idx);
161 ThreadSP ThreadList::RemoveThreadByProtocolID(lldb::tid_t tid,
163 std::lock_guard<std::recursive_mutex> guard(GetMutex());
166 m_process->UpdateThreadListIfNeeded();
170 const uint32_t num_threads = m_threads.size();
171 for (idx = 0; idx < num_threads; ++idx) {
172 if (m_threads[idx]->GetProtocolID() == tid) {
173 thread_sp = m_threads[idx];
174 m_threads.erase(m_threads.begin() + idx);
181 ThreadSP ThreadList::GetThreadSPForThreadPtr(Thread *thread_ptr) {
184 std::lock_guard<std::recursive_mutex> guard(GetMutex());
187 const uint32_t num_threads = m_threads.size();
188 for (idx = 0; idx < num_threads; ++idx) {
189 if (m_threads[idx].get() == thread_ptr) {
190 thread_sp = m_threads[idx];
198 ThreadSP ThreadList::FindThreadByIndexID(uint32_t index_id, bool can_update) {
199 std::lock_guard<std::recursive_mutex> guard(GetMutex());
202 m_process->UpdateThreadListIfNeeded();
205 const uint32_t num_threads = m_threads.size();
206 for (uint32_t idx = 0; idx < num_threads; ++idx) {
207 if (m_threads[idx]->GetIndexID() == index_id) {
208 thread_sp = m_threads[idx];
215 bool ThreadList::ShouldStop(Event *event_ptr) {
216 // Running events should never stop, obviously...
218 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
220 // The ShouldStop method of the threads can do a whole lot of work,
221 // figuring out whether the thread plan conditions are met. So we don't want
222 // to keep the ThreadList locked the whole time we are doing this.
223 // FIXME: It is possible that running code could cause new threads
224 // to be created. If that happens, we will miss asking them whether
225 // they should stop. This is not a big deal since we haven't had
226 // a chance to hang any interesting operations on those threads yet.
228 collection threads_copy;
231 std::lock_guard<std::recursive_mutex> guard(GetMutex());
233 m_process->UpdateThreadListIfNeeded();
234 for (lldb::ThreadSP thread_sp : m_threads) {
235 // This is an optimization... If we didn't let a thread run in between
236 // the previous stop and this
237 // one, we shouldn't have to consult it for ShouldStop. So just leave it
238 // off the list we are going to
240 // On Linux, if a thread-specific conditional breakpoint was hit, it won't
241 // necessarily be the thread
242 // that hit the breakpoint itself that evaluates the conditional
243 // expression, so the thread that hit
244 // the breakpoint could still be asked to stop, even though it hasn't been
245 // allowed to run since the
247 if (thread_sp->GetTemporaryResumeState() != eStateSuspended ||
248 thread_sp->IsStillAtLastBreakpointHit())
249 threads_copy.push_back(thread_sp);
252 // It is possible the threads we were allowing to run all exited and then
253 // maybe the user interrupted
254 // or something, then fall back on looking at all threads:
256 if (threads_copy.size() == 0)
257 threads_copy = m_threads;
260 collection::iterator pos, end = threads_copy.end();
264 log->Printf("ThreadList::%s: %" PRIu64 " threads, %" PRIu64
265 " unsuspended threads",
266 __FUNCTION__, (uint64_t)m_threads.size(),
267 (uint64_t)threads_copy.size());
270 bool did_anybody_stop_for_a_reason = false;
272 // If the event is an Interrupt event, then we're going to stop no matter
273 // what. Otherwise, presume we won't stop.
274 bool should_stop = false;
275 if (Process::ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
278 "ThreadList::%s handling interrupt event, should stop set to true",
284 // Now we run through all the threads and get their stop info's. We want to
285 // make sure to do this first before
286 // we start running the ShouldStop, because one thread's ShouldStop could
287 // destroy information (like deleting a
288 // thread specific breakpoint another thread had stopped at) which could lead
289 // us to compute the StopInfo incorrectly.
290 // We don't need to use it here, we just want to make sure it gets computed.
292 for (pos = threads_copy.begin(); pos != end; ++pos) {
293 ThreadSP thread_sp(*pos);
294 thread_sp->GetStopInfo();
297 for (pos = threads_copy.begin(); pos != end; ++pos) {
298 ThreadSP thread_sp(*pos);
300 // We should never get a stop for which no thread had a stop reason, but
301 // sometimes we do see this -
302 // for instance when we first connect to a remote stub. In that case we
303 // should stop, since we can't figure out
304 // the right thing to do and stopping gives the user control over what to do
307 // Note, this causes a problem when you have a thread specific breakpoint,
308 // and a bunch of threads hit the breakpoint,
309 // but not the thread which we are waiting for. All the threads that are
310 // not "supposed" to hit the breakpoint
311 // are marked as having no stop reason, which is right, they should not show
312 // a stop reason. But that triggers this
313 // code and causes us to stop seemingly for no reason.
315 // Since the only way we ever saw this error was on first attach, I'm only
316 // going to trigger set did_anybody_stop_for_a_reason
317 // to true unless this is the first stop.
319 // If this becomes a problem, we'll have to have another StopReason like
320 // "StopInfoHidden" which will look invalid
321 // everywhere but at this check.
323 if (thread_sp->GetProcess()->GetStopID() > 1)
324 did_anybody_stop_for_a_reason = true;
326 did_anybody_stop_for_a_reason |= thread_sp->ThreadStoppedForAReason();
328 const bool thread_should_stop = thread_sp->ShouldStop(event_ptr);
329 if (thread_should_stop)
333 if (!should_stop && !did_anybody_stop_for_a_reason) {
336 log->Printf("ThreadList::%s we stopped but no threads had a stop reason, "
337 "overriding should_stop and stopping.",
342 log->Printf("ThreadList::%s overall should_stop = %i", __FUNCTION__,
346 for (pos = threads_copy.begin(); pos != end; ++pos) {
347 ThreadSP thread_sp(*pos);
348 thread_sp->WillStop();
355 Vote ThreadList::ShouldReportStop(Event *event_ptr) {
356 std::lock_guard<std::recursive_mutex> guard(GetMutex());
358 Vote result = eVoteNoOpinion;
359 m_process->UpdateThreadListIfNeeded();
360 collection::iterator pos, end = m_threads.end();
362 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
365 log->Printf("ThreadList::%s %" PRIu64 " threads", __FUNCTION__,
366 (uint64_t)m_threads.size());
368 // Run through the threads and ask whether we should report this event.
369 // For stopping, a YES vote wins over everything. A NO vote wins over NO
371 for (pos = m_threads.begin(); pos != end; ++pos) {
372 ThreadSP thread_sp(*pos);
373 const Vote vote = thread_sp->ShouldReportStop(event_ptr);
383 if (result == eVoteNoOpinion) {
387 "Thread {0:x} voted {1}, but lost out because result was {2}",
388 thread_sp->GetID(), vote, result);
393 LLDB_LOG(log, "Returning {0}", result);
397 void ThreadList::SetShouldReportStop(Vote vote) {
398 std::lock_guard<std::recursive_mutex> guard(GetMutex());
400 m_process->UpdateThreadListIfNeeded();
401 collection::iterator pos, end = m_threads.end();
402 for (pos = m_threads.begin(); pos != end; ++pos) {
403 ThreadSP thread_sp(*pos);
404 thread_sp->SetShouldReportStop(vote);
408 Vote ThreadList::ShouldReportRun(Event *event_ptr) {
410 std::lock_guard<std::recursive_mutex> guard(GetMutex());
412 Vote result = eVoteNoOpinion;
413 m_process->UpdateThreadListIfNeeded();
414 collection::iterator pos, end = m_threads.end();
416 // Run through the threads and ask whether we should report this event.
417 // The rule is NO vote wins over everything, a YES vote wins over no opinion.
419 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
421 for (pos = m_threads.begin(); pos != end; ++pos) {
422 if ((*pos)->GetResumeState() != eStateSuspended) {
423 switch ((*pos)->ShouldReportRun(event_ptr)) {
427 if (result == eVoteNoOpinion)
432 log->Printf("ThreadList::ShouldReportRun() thread %d (0x%4.4" PRIx64
433 ") says don't report.",
434 (*pos)->GetIndexID(), (*pos)->GetID());
443 void ThreadList::Clear() {
444 std::lock_guard<std::recursive_mutex> guard(GetMutex());
447 m_selected_tid = LLDB_INVALID_THREAD_ID;
450 void ThreadList::Destroy() {
451 std::lock_guard<std::recursive_mutex> guard(GetMutex());
452 const uint32_t num_threads = m_threads.size();
453 for (uint32_t idx = 0; idx < num_threads; ++idx) {
454 m_threads[idx]->DestroyThread();
458 void ThreadList::RefreshStateAfterStop() {
459 std::lock_guard<std::recursive_mutex> guard(GetMutex());
461 m_process->UpdateThreadListIfNeeded();
463 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
464 if (log && log->GetVerbose())
465 log->Printf("Turning off notification of new threads while single stepping "
468 collection::iterator pos, end = m_threads.end();
469 for (pos = m_threads.begin(); pos != end; ++pos)
470 (*pos)->RefreshStateAfterStop();
473 void ThreadList::DiscardThreadPlans() {
474 // You don't need to update the thread list here, because only threads
475 // that you currently know about have any thread plans.
476 std::lock_guard<std::recursive_mutex> guard(GetMutex());
478 collection::iterator pos, end = m_threads.end();
479 for (pos = m_threads.begin(); pos != end; ++pos)
480 (*pos)->DiscardThreadPlans(true);
483 bool ThreadList::WillResume() {
484 // Run through the threads and perform their momentary actions.
485 // But we only do this for threads that are running, user suspended
486 // threads stay where they are.
488 std::lock_guard<std::recursive_mutex> guard(GetMutex());
489 m_process->UpdateThreadListIfNeeded();
491 collection::iterator pos, end = m_threads.end();
493 // See if any thread wants to run stopping others. If it does, then we won't
494 // setup the other threads for resume, since they aren't going to get a chance
495 // to run. This is necessary because the SetupForResume might add
497 // plans which would then get to be part of the who-gets-to-run negotiation,
499 // they're coming in after the fact, and the threads that are already set up
503 bool wants_solo_run = false;
505 for (pos = m_threads.begin(); pos != end; ++pos) {
506 lldbassert((*pos)->GetCurrentPlan() &&
507 "thread should not have null thread plan");
508 if ((*pos)->GetResumeState() != eStateSuspended &&
509 (*pos)->GetCurrentPlan()->StopOthers()) {
510 if ((*pos)->IsOperatingSystemPluginThread() &&
511 !(*pos)->GetBackingThread())
513 wants_solo_run = true;
518 if (wants_solo_run) {
519 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
520 if (log && log->GetVerbose())
521 log->Printf("Turning on notification of new threads while single "
522 "stepping a thread.");
523 m_process->StartNoticingNewThreads();
525 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
526 if (log && log->GetVerbose())
527 log->Printf("Turning off notification of new threads while single "
528 "stepping a thread.");
529 m_process->StopNoticingNewThreads();
532 // Give all the threads that are likely to run a last chance to set up their
534 // negotiate who is actually going to get a chance to run...
535 // Don't set to resume suspended threads, and if any thread wanted to stop
537 // call setup on the threads that request StopOthers...
539 for (pos = m_threads.begin(); pos != end; ++pos) {
540 if ((*pos)->GetResumeState() != eStateSuspended &&
541 (!wants_solo_run || (*pos)->GetCurrentPlan()->StopOthers())) {
542 if ((*pos)->IsOperatingSystemPluginThread() &&
543 !(*pos)->GetBackingThread())
545 (*pos)->SetupForResume();
549 // Now go through the threads and see if any thread wants to run just itself.
550 // if so then pick one and run it.
552 ThreadList run_me_only_list(m_process);
554 run_me_only_list.SetStopID(m_process->GetStopID());
556 bool run_only_current_thread = false;
558 for (pos = m_threads.begin(); pos != end; ++pos) {
559 ThreadSP thread_sp(*pos);
560 if (thread_sp->GetResumeState() != eStateSuspended &&
561 thread_sp->GetCurrentPlan()->StopOthers()) {
562 if ((*pos)->IsOperatingSystemPluginThread() &&
563 !(*pos)->GetBackingThread())
566 // You can't say "stop others" and also want yourself to be suspended.
567 assert(thread_sp->GetCurrentPlan()->RunState() != eStateSuspended);
569 if (thread_sp == GetSelectedThread()) {
570 // If the currently selected thread wants to run on its own, always let
572 run_only_current_thread = true;
573 run_me_only_list.Clear();
574 run_me_only_list.AddThread(thread_sp);
578 run_me_only_list.AddThread(thread_sp);
582 bool need_to_resume = true;
584 if (run_me_only_list.GetSize(false) == 0) {
585 // Everybody runs as they wish:
586 for (pos = m_threads.begin(); pos != end; ++pos) {
587 ThreadSP thread_sp(*pos);
589 if (thread_sp->GetResumeState() != eStateSuspended)
590 run_state = thread_sp->GetCurrentPlan()->RunState();
592 run_state = eStateSuspended;
593 if (!thread_sp->ShouldResume(run_state))
594 need_to_resume = false;
597 ThreadSP thread_to_run;
599 if (run_only_current_thread) {
600 thread_to_run = GetSelectedThread();
601 } else if (run_me_only_list.GetSize(false) == 1) {
602 thread_to_run = run_me_only_list.GetThreadAtIndex(0);
605 (int)((run_me_only_list.GetSize(false) * (double)rand()) /
607 thread_to_run = run_me_only_list.GetThreadAtIndex(random_thread);
610 for (pos = m_threads.begin(); pos != end; ++pos) {
611 ThreadSP thread_sp(*pos);
612 if (thread_sp == thread_to_run) {
613 if (!thread_sp->ShouldResume(thread_sp->GetCurrentPlan()->RunState()))
614 need_to_resume = false;
616 thread_sp->ShouldResume(eStateSuspended);
620 return need_to_resume;
623 void ThreadList::DidResume() {
624 std::lock_guard<std::recursive_mutex> guard(GetMutex());
625 collection::iterator pos, end = m_threads.end();
626 for (pos = m_threads.begin(); pos != end; ++pos) {
627 // Don't clear out threads that aren't going to get a chance to run, rather
628 // leave their state for the next time around.
629 ThreadSP thread_sp(*pos);
630 if (thread_sp->GetResumeState() != eStateSuspended)
631 thread_sp->DidResume();
635 void ThreadList::DidStop() {
636 std::lock_guard<std::recursive_mutex> guard(GetMutex());
637 collection::iterator pos, end = m_threads.end();
638 for (pos = m_threads.begin(); pos != end; ++pos) {
639 // Notify threads that the process just stopped.
640 // Note, this currently assumes that all threads in the list
641 // stop when the process stops. In the future we will want to support
642 // a debugging model where some threads continue to run while others
643 // are stopped. We either need to handle that somehow here or
644 // create a special thread list containing only threads which will
645 // stop in the code that calls this method (currently
646 // Process::SetPrivateState).
647 ThreadSP thread_sp(*pos);
648 if (StateIsRunningState(thread_sp->GetState()))
649 thread_sp->DidStop();
653 ThreadSP ThreadList::GetSelectedThread() {
654 std::lock_guard<std::recursive_mutex> guard(GetMutex());
655 ThreadSP thread_sp = FindThreadByID(m_selected_tid);
656 if (!thread_sp.get()) {
657 if (m_threads.size() == 0)
659 m_selected_tid = m_threads[0]->GetID();
660 thread_sp = m_threads[0];
665 bool ThreadList::SetSelectedThreadByID(lldb::tid_t tid, bool notify) {
666 std::lock_guard<std::recursive_mutex> guard(GetMutex());
667 ThreadSP selected_thread_sp(FindThreadByID(tid));
668 if (selected_thread_sp) {
669 m_selected_tid = tid;
670 selected_thread_sp->SetDefaultFileAndLineToSelectedFrame();
672 m_selected_tid = LLDB_INVALID_THREAD_ID;
675 NotifySelectedThreadChanged(m_selected_tid);
677 return m_selected_tid != LLDB_INVALID_THREAD_ID;
680 bool ThreadList::SetSelectedThreadByIndexID(uint32_t index_id, bool notify) {
681 std::lock_guard<std::recursive_mutex> guard(GetMutex());
682 ThreadSP selected_thread_sp(FindThreadByIndexID(index_id));
683 if (selected_thread_sp.get()) {
684 m_selected_tid = selected_thread_sp->GetID();
685 selected_thread_sp->SetDefaultFileAndLineToSelectedFrame();
687 m_selected_tid = LLDB_INVALID_THREAD_ID;
690 NotifySelectedThreadChanged(m_selected_tid);
692 return m_selected_tid != LLDB_INVALID_THREAD_ID;
695 void ThreadList::NotifySelectedThreadChanged(lldb::tid_t tid) {
696 ThreadSP selected_thread_sp(FindThreadByID(tid));
697 if (selected_thread_sp->EventTypeHasListeners(
698 Thread::eBroadcastBitThreadSelected))
699 selected_thread_sp->BroadcastEvent(
700 Thread::eBroadcastBitThreadSelected,
701 new Thread::ThreadEventData(selected_thread_sp));
704 void ThreadList::Update(ThreadList &rhs) {
706 // Lock both mutexes to make sure neither side changes anyone on us
707 // while the assignment occurs
708 std::lock_guard<std::recursive_mutex> guard(GetMutex());
710 m_process = rhs.m_process;
711 m_stop_id = rhs.m_stop_id;
712 m_threads.swap(rhs.m_threads);
713 m_selected_tid = rhs.m_selected_tid;
715 // Now we look for threads that we are done with and
716 // make sure to clear them up as much as possible so
717 // anyone with a shared pointer will still have a reference,
718 // but the thread won't be of much use. Using std::weak_ptr
719 // for all backward references (such as a thread to a process)
720 // will eventually solve this issue for us, but for now, we
721 // need to work around the issue
722 collection::iterator rhs_pos, rhs_end = rhs.m_threads.end();
723 for (rhs_pos = rhs.m_threads.begin(); rhs_pos != rhs_end; ++rhs_pos) {
724 const lldb::tid_t tid = (*rhs_pos)->GetID();
725 bool thread_is_alive = false;
726 const uint32_t num_threads = m_threads.size();
727 for (uint32_t idx = 0; idx < num_threads; ++idx) {
728 ThreadSP backing_thread = m_threads[idx]->GetBackingThread();
729 if (m_threads[idx]->GetID() == tid ||
730 (backing_thread && backing_thread->GetID() == tid)) {
731 thread_is_alive = true;
735 if (!thread_is_alive)
736 (*rhs_pos)->DestroyThread();
741 void ThreadList::Flush() {
742 std::lock_guard<std::recursive_mutex> guard(GetMutex());
743 collection::iterator pos, end = m_threads.end();
744 for (pos = m_threads.begin(); pos != end; ++pos)
748 std::recursive_mutex &ThreadList::GetMutex() const {
749 return m_process->m_thread_mutex;
752 ThreadList::ExpressionExecutionThreadPusher::ExpressionExecutionThreadPusher(
753 lldb::ThreadSP thread_sp)
754 : m_thread_list(nullptr), m_tid(LLDB_INVALID_THREAD_ID) {
756 m_tid = thread_sp->GetID();
757 m_thread_list = &thread_sp->GetProcess()->GetThreadList();
758 m_thread_list->PushExpressionExecutionThread(m_tid);