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/Log.h"
19 #include "lldb/Core/State.h"
20 #include "lldb/Target/RegisterContext.h"
21 #include "lldb/Target/ThreadList.h"
22 #include "lldb/Target/Thread.h"
23 #include "lldb/Target/ThreadPlan.h"
24 #include "lldb/Target/Process.h"
25 #include "lldb/Utility/ConvertEnum.h"
26 #include "lldb/Utility/LLDBAssert.h"
29 using namespace lldb_private;
31 ThreadList::ThreadList (Process *process) :
35 m_selected_tid (LLDB_INVALID_THREAD_ID)
39 ThreadList::ThreadList (const ThreadList &rhs) :
41 m_process (rhs.m_process),
42 m_stop_id (rhs.m_stop_id),
45 // Use the assignment operator since it uses the mutex
50 ThreadList::operator = (const ThreadList& rhs)
54 // Lock both mutexes to make sure neither side changes anyone on us
55 // while the assignment occurs
56 std::lock_guard<std::recursive_mutex> guard(GetMutex());
58 m_process = rhs.m_process;
59 m_stop_id = rhs.m_stop_id;
60 m_threads = rhs.m_threads;
61 m_selected_tid = rhs.m_selected_tid;
67 ThreadList::~ThreadList()
69 // Clear the thread list. Clear will take the mutex lock
70 // which will ensure that if anyone is using the list
71 // they won't get it removed while using it.
76 ThreadList::GetExpressionExecutionThread()
78 if (m_expression_tid_stack.empty())
79 return GetSelectedThread();
80 ThreadSP expr_thread_sp = FindThreadByID(m_expression_tid_stack.back());
82 return expr_thread_sp;
84 return GetSelectedThread();
88 ThreadList::PushExpressionExecutionThread(lldb::tid_t tid)
90 m_expression_tid_stack.push_back(tid);
94 ThreadList::PopExpressionExecutionThread(lldb::tid_t tid)
96 assert(m_expression_tid_stack.back() == tid);
97 m_expression_tid_stack.pop_back();
101 ThreadList::GetStopID () const
107 ThreadList::SetStopID (uint32_t stop_id)
113 ThreadList::GetSize (bool can_update)
115 std::lock_guard<std::recursive_mutex> guard(GetMutex());
118 m_process->UpdateThreadListIfNeeded();
119 return m_threads.size();
123 ThreadList::GetThreadAtIndex (uint32_t idx, bool can_update)
125 std::lock_guard<std::recursive_mutex> guard(GetMutex());
128 m_process->UpdateThreadListIfNeeded();
131 if (idx < m_threads.size())
132 thread_sp = m_threads[idx];
137 ThreadList::FindThreadByID (lldb::tid_t tid, bool can_update)
139 std::lock_guard<std::recursive_mutex> guard(GetMutex());
142 m_process->UpdateThreadListIfNeeded();
146 const uint32_t num_threads = m_threads.size();
147 for (idx = 0; idx < num_threads; ++idx)
149 if (m_threads[idx]->GetID() == tid)
151 thread_sp = m_threads[idx];
159 ThreadList::FindThreadByProtocolID (lldb::tid_t tid, bool can_update)
161 std::lock_guard<std::recursive_mutex> guard(GetMutex());
164 m_process->UpdateThreadListIfNeeded();
168 const uint32_t num_threads = m_threads.size();
169 for (idx = 0; idx < num_threads; ++idx)
171 if (m_threads[idx]->GetProtocolID() == tid)
173 thread_sp = m_threads[idx];
182 ThreadList::RemoveThreadByID (lldb::tid_t tid, bool can_update)
184 std::lock_guard<std::recursive_mutex> guard(GetMutex());
187 m_process->UpdateThreadListIfNeeded();
191 const uint32_t num_threads = m_threads.size();
192 for (idx = 0; idx < num_threads; ++idx)
194 if (m_threads[idx]->GetID() == tid)
196 thread_sp = m_threads[idx];
197 m_threads.erase(m_threads.begin()+idx);
205 ThreadList::RemoveThreadByProtocolID (lldb::tid_t tid, bool can_update)
207 std::lock_guard<std::recursive_mutex> guard(GetMutex());
210 m_process->UpdateThreadListIfNeeded();
214 const uint32_t num_threads = m_threads.size();
215 for (idx = 0; idx < num_threads; ++idx)
217 if (m_threads[idx]->GetProtocolID() == tid)
219 thread_sp = m_threads[idx];
220 m_threads.erase(m_threads.begin()+idx);
228 ThreadList::GetThreadSPForThreadPtr (Thread *thread_ptr)
233 std::lock_guard<std::recursive_mutex> guard(GetMutex());
236 const uint32_t num_threads = m_threads.size();
237 for (idx = 0; idx < num_threads; ++idx)
239 if (m_threads[idx].get() == thread_ptr)
241 thread_sp = m_threads[idx];
252 ThreadList::FindThreadByIndexID (uint32_t index_id, bool can_update)
254 std::lock_guard<std::recursive_mutex> guard(GetMutex());
257 m_process->UpdateThreadListIfNeeded();
260 const uint32_t num_threads = m_threads.size();
261 for (uint32_t idx = 0; idx < num_threads; ++idx)
263 if (m_threads[idx]->GetIndexID() == index_id)
265 thread_sp = m_threads[idx];
273 ThreadList::ShouldStop (Event *event_ptr)
275 // Running events should never stop, obviously...
277 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
279 // The ShouldStop method of the threads can do a whole lot of work,
280 // figuring out whether the thread plan conditions are met. So we don't want
281 // to keep the ThreadList locked the whole time we are doing this.
282 // FIXME: It is possible that running code could cause new threads
283 // to be created. If that happens, we will miss asking them whether
284 // they should stop. This is not a big deal since we haven't had
285 // a chance to hang any interesting operations on those threads yet.
287 collection threads_copy;
290 std::lock_guard<std::recursive_mutex> guard(GetMutex());
292 m_process->UpdateThreadListIfNeeded();
293 for (lldb::ThreadSP thread_sp : m_threads)
295 // This is an optimization... If we didn't let a thread run in between the previous stop and this
296 // one, we shouldn't have to consult it for ShouldStop. So just leave it off the list we are going to
298 // On Linux, if a thread-specific conditional breakpoint was hit, it won't necessarily be the thread
299 // that hit the breakpoint itself that evaluates the conditional expression, so the thread that hit
300 // the breakpoint could still be asked to stop, even though it hasn't been allowed to run since the
302 if (thread_sp->GetTemporaryResumeState () != eStateSuspended || thread_sp->IsStillAtLastBreakpointHit())
303 threads_copy.push_back(thread_sp);
306 // It is possible the threads we were allowing to run all exited and then maybe the user interrupted
307 // or something, then fall back on looking at all threads:
309 if (threads_copy.size() == 0)
310 threads_copy = m_threads;
313 collection::iterator pos, end = threads_copy.end();
318 log->Printf ("ThreadList::%s: %" PRIu64 " threads, %" PRIu64 " unsuspended threads",
320 (uint64_t)m_threads.size(),
321 (uint64_t)threads_copy.size());
324 bool did_anybody_stop_for_a_reason = false;
326 // If the event is an Interrupt event, then we're going to stop no matter what. Otherwise, presume we won't stop.
327 bool should_stop = false;
328 if (Process::ProcessEventData::GetInterruptedFromEvent(event_ptr))
331 log->Printf("ThreadList::%s handling interrupt event, should stop set to true", __FUNCTION__);
336 // Now we run through all the threads and get their stop info's. We want to make sure to do this first before
337 // we start running the ShouldStop, because one thread's ShouldStop could destroy information (like deleting a
338 // thread specific breakpoint another thread had stopped at) which could lead us to compute the StopInfo incorrectly.
339 // We don't need to use it here, we just want to make sure it gets computed.
341 for (pos = threads_copy.begin(); pos != end; ++pos)
343 ThreadSP thread_sp(*pos);
344 thread_sp->GetStopInfo();
347 for (pos = threads_copy.begin(); pos != end; ++pos)
349 ThreadSP thread_sp(*pos);
351 // We should never get a stop for which no thread had a stop reason, but sometimes we do see this -
352 // for instance when we first connect to a remote stub. In that case we should stop, since we can't figure out
353 // the right thing to do and stopping gives the user control over what to do in this instance.
355 // Note, this causes a problem when you have a thread specific breakpoint, and a bunch of threads hit the breakpoint,
356 // but not the thread which we are waiting for. All the threads that are not "supposed" to hit the breakpoint
357 // are marked as having no stop reason, which is right, they should not show a stop reason. But that triggers this
358 // code and causes us to stop seemingly for no reason.
360 // Since the only way we ever saw this error was on first attach, I'm only going to trigger set did_anybody_stop_for_a_reason
361 // to true unless this is the first stop.
363 // If this becomes a problem, we'll have to have another StopReason like "StopInfoHidden" which will look invalid
364 // everywhere but at this check.
366 if (thread_sp->GetProcess()->GetStopID() > 1)
367 did_anybody_stop_for_a_reason = true;
369 did_anybody_stop_for_a_reason |= thread_sp->ThreadStoppedForAReason();
371 const bool thread_should_stop = thread_sp->ShouldStop(event_ptr);
372 if (thread_should_stop)
376 if (!should_stop && !did_anybody_stop_for_a_reason)
380 log->Printf ("ThreadList::%s we stopped but no threads had a stop reason, overriding should_stop and stopping.", __FUNCTION__);
384 log->Printf ("ThreadList::%s overall should_stop = %i", __FUNCTION__, should_stop);
388 for (pos = threads_copy.begin(); pos != end; ++pos)
390 ThreadSP thread_sp(*pos);
391 thread_sp->WillStop ();
399 ThreadList::ShouldReportStop (Event *event_ptr)
401 std::lock_guard<std::recursive_mutex> guard(GetMutex());
403 Vote result = eVoteNoOpinion;
404 m_process->UpdateThreadListIfNeeded();
405 collection::iterator pos, end = m_threads.end();
407 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
410 log->Printf ("ThreadList::%s %" PRIu64 " threads", __FUNCTION__, (uint64_t)m_threads.size());
412 // Run through the threads and ask whether we should report this event.
413 // For stopping, a YES vote wins over everything. A NO vote wins over NO opinion.
414 for (pos = m_threads.begin(); pos != end; ++pos)
416 ThreadSP thread_sp(*pos);
417 const Vote vote = thread_sp->ShouldReportStop (event_ptr);
428 if (result == eVoteNoOpinion)
435 log->Printf ("ThreadList::%s thread 0x%4.4" PRIx64 ": voted %s, but lost out because result was %s",
438 GetVoteAsCString (vote),
439 GetVoteAsCString (result));
445 log->Printf ("ThreadList::%s returning %s", __FUNCTION__, GetVoteAsCString (result));
450 ThreadList::SetShouldReportStop (Vote vote)
452 std::lock_guard<std::recursive_mutex> guard(GetMutex());
454 m_process->UpdateThreadListIfNeeded();
455 collection::iterator pos, end = m_threads.end();
456 for (pos = m_threads.begin(); pos != end; ++pos)
458 ThreadSP thread_sp(*pos);
459 thread_sp->SetShouldReportStop (vote);
464 ThreadList::ShouldReportRun (Event *event_ptr)
467 std::lock_guard<std::recursive_mutex> guard(GetMutex());
469 Vote result = eVoteNoOpinion;
470 m_process->UpdateThreadListIfNeeded();
471 collection::iterator pos, end = m_threads.end();
473 // Run through the threads and ask whether we should report this event.
474 // The rule is NO vote wins over everything, a YES vote wins over no opinion.
476 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
478 for (pos = m_threads.begin(); pos != end; ++pos)
480 if ((*pos)->GetResumeState () != eStateSuspended)
482 switch ((*pos)->ShouldReportRun (event_ptr))
487 if (result == eVoteNoOpinion)
492 log->Printf ("ThreadList::ShouldReportRun() thread %d (0x%4.4" PRIx64 ") says don't report.",
493 (*pos)->GetIndexID(),
506 std::lock_guard<std::recursive_mutex> guard(GetMutex());
509 m_selected_tid = LLDB_INVALID_THREAD_ID;
513 ThreadList::Destroy()
515 std::lock_guard<std::recursive_mutex> guard(GetMutex());
516 const uint32_t num_threads = m_threads.size();
517 for (uint32_t idx = 0; idx < num_threads; ++idx)
519 m_threads[idx]->DestroyThread();
524 ThreadList::RefreshStateAfterStop ()
526 std::lock_guard<std::recursive_mutex> guard(GetMutex());
528 m_process->UpdateThreadListIfNeeded();
530 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
531 if (log && log->GetVerbose())
532 log->Printf ("Turning off notification of new threads while single stepping a thread.");
534 collection::iterator pos, end = m_threads.end();
535 for (pos = m_threads.begin(); pos != end; ++pos)
536 (*pos)->RefreshStateAfterStop ();
540 ThreadList::DiscardThreadPlans ()
542 // You don't need to update the thread list here, because only threads
543 // that you currently know about have any thread plans.
544 std::lock_guard<std::recursive_mutex> guard(GetMutex());
546 collection::iterator pos, end = m_threads.end();
547 for (pos = m_threads.begin(); pos != end; ++pos)
548 (*pos)->DiscardThreadPlans (true);
553 ThreadList::WillResume ()
555 // Run through the threads and perform their momentary actions.
556 // But we only do this for threads that are running, user suspended
557 // threads stay where they are.
559 std::lock_guard<std::recursive_mutex> guard(GetMutex());
560 m_process->UpdateThreadListIfNeeded();
562 collection::iterator pos, end = m_threads.end();
564 // See if any thread wants to run stopping others. If it does, then we won't
565 // setup the other threads for resume, since they aren't going to get a chance
566 // to run. This is necessary because the SetupForResume might add "StopOthers"
567 // plans which would then get to be part of the who-gets-to-run negotiation, but
568 // they're coming in after the fact, and the threads that are already set up should
571 bool wants_solo_run = false;
573 for (pos = m_threads.begin(); pos != end; ++pos)
575 lldbassert((*pos)->GetCurrentPlan() && "thread should not have null thread plan");
576 if ((*pos)->GetResumeState() != eStateSuspended &&
577 (*pos)->GetCurrentPlan()->StopOthers())
579 if ((*pos)->IsOperatingSystemPluginThread() && !(*pos)->GetBackingThread())
581 wants_solo_run = true;
588 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
589 if (log && log->GetVerbose())
590 log->Printf ("Turning on notification of new threads while single stepping a thread.");
591 m_process->StartNoticingNewThreads();
595 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
596 if (log && log->GetVerbose())
597 log->Printf ("Turning off notification of new threads while single stepping a thread.");
598 m_process->StopNoticingNewThreads();
601 // Give all the threads that are likely to run a last chance to set up their state before we
602 // negotiate who is actually going to get a chance to run...
603 // Don't set to resume suspended threads, and if any thread wanted to stop others, only
604 // call setup on the threads that request StopOthers...
606 for (pos = m_threads.begin(); pos != end; ++pos)
608 if ((*pos)->GetResumeState() != eStateSuspended
609 && (!wants_solo_run || (*pos)->GetCurrentPlan()->StopOthers()))
611 if ((*pos)->IsOperatingSystemPluginThread() && !(*pos)->GetBackingThread())
613 (*pos)->SetupForResume ();
617 // Now go through the threads and see if any thread wants to run just itself.
618 // if so then pick one and run it.
620 ThreadList run_me_only_list (m_process);
622 run_me_only_list.SetStopID(m_process->GetStopID());
624 bool run_only_current_thread = false;
626 for (pos = m_threads.begin(); pos != end; ++pos)
628 ThreadSP thread_sp(*pos);
629 if (thread_sp->GetResumeState() != eStateSuspended &&
630 thread_sp->GetCurrentPlan()->StopOthers())
632 if ((*pos)->IsOperatingSystemPluginThread() && !(*pos)->GetBackingThread())
635 // You can't say "stop others" and also want yourself to be suspended.
636 assert (thread_sp->GetCurrentPlan()->RunState() != eStateSuspended);
638 if (thread_sp == GetSelectedThread())
640 // If the currently selected thread wants to run on its own, always let it.
641 run_only_current_thread = true;
642 run_me_only_list.Clear();
643 run_me_only_list.AddThread (thread_sp);
647 run_me_only_list.AddThread (thread_sp);
652 bool need_to_resume = true;
654 if (run_me_only_list.GetSize (false) == 0)
656 // Everybody runs as they wish:
657 for (pos = m_threads.begin(); pos != end; ++pos)
659 ThreadSP thread_sp(*pos);
661 if (thread_sp->GetResumeState() != eStateSuspended)
662 run_state = thread_sp->GetCurrentPlan()->RunState();
664 run_state = eStateSuspended;
665 if (!thread_sp->ShouldResume(run_state))
666 need_to_resume = false;
671 ThreadSP thread_to_run;
673 if (run_only_current_thread)
675 thread_to_run = GetSelectedThread();
677 else if (run_me_only_list.GetSize (false) == 1)
679 thread_to_run = run_me_only_list.GetThreadAtIndex (0);
683 int random_thread = (int)
684 ((run_me_only_list.GetSize (false) * (double) rand ()) / (RAND_MAX + 1.0));
685 thread_to_run = run_me_only_list.GetThreadAtIndex (random_thread);
688 for (pos = m_threads.begin(); pos != end; ++pos)
690 ThreadSP thread_sp(*pos);
691 if (thread_sp == thread_to_run)
693 if (!thread_sp->ShouldResume(thread_sp->GetCurrentPlan()->RunState()))
694 need_to_resume = false;
697 thread_sp->ShouldResume (eStateSuspended);
701 return need_to_resume;
705 ThreadList::DidResume ()
707 std::lock_guard<std::recursive_mutex> guard(GetMutex());
708 collection::iterator pos, end = m_threads.end();
709 for (pos = m_threads.begin(); pos != end; ++pos)
711 // Don't clear out threads that aren't going to get a chance to run, rather
712 // leave their state for the next time around.
713 ThreadSP thread_sp(*pos);
714 if (thread_sp->GetResumeState() != eStateSuspended)
715 thread_sp->DidResume ();
720 ThreadList::DidStop ()
722 std::lock_guard<std::recursive_mutex> guard(GetMutex());
723 collection::iterator pos, end = m_threads.end();
724 for (pos = m_threads.begin(); pos != end; ++pos)
726 // Notify threads that the process just stopped.
727 // Note, this currently assumes that all threads in the list
728 // stop when the process stops. In the future we will want to support
729 // a debugging model where some threads continue to run while others
730 // are stopped. We either need to handle that somehow here or
731 // create a special thread list containing only threads which will
732 // stop in the code that calls this method (currently
733 // Process::SetPrivateState).
734 ThreadSP thread_sp(*pos);
735 if (StateIsRunningState(thread_sp->GetState()))
736 thread_sp->DidStop ();
741 ThreadList::GetSelectedThread ()
743 std::lock_guard<std::recursive_mutex> guard(GetMutex());
744 ThreadSP thread_sp = FindThreadByID(m_selected_tid);
745 if (!thread_sp.get())
747 if (m_threads.size() == 0)
749 m_selected_tid = m_threads[0]->GetID();
750 thread_sp = m_threads[0];
756 ThreadList::SetSelectedThreadByID (lldb::tid_t tid, bool notify)
758 std::lock_guard<std::recursive_mutex> guard(GetMutex());
759 ThreadSP selected_thread_sp(FindThreadByID(tid));
760 if (selected_thread_sp)
762 m_selected_tid = tid;
763 selected_thread_sp->SetDefaultFileAndLineToSelectedFrame();
766 m_selected_tid = LLDB_INVALID_THREAD_ID;
769 NotifySelectedThreadChanged(m_selected_tid);
771 return m_selected_tid != LLDB_INVALID_THREAD_ID;
775 ThreadList::SetSelectedThreadByIndexID (uint32_t index_id, bool notify)
777 std::lock_guard<std::recursive_mutex> guard(GetMutex());
778 ThreadSP selected_thread_sp (FindThreadByIndexID(index_id));
779 if (selected_thread_sp.get())
781 m_selected_tid = selected_thread_sp->GetID();
782 selected_thread_sp->SetDefaultFileAndLineToSelectedFrame();
785 m_selected_tid = LLDB_INVALID_THREAD_ID;
788 NotifySelectedThreadChanged(m_selected_tid);
790 return m_selected_tid != LLDB_INVALID_THREAD_ID;
794 ThreadList::NotifySelectedThreadChanged (lldb::tid_t tid)
796 ThreadSP selected_thread_sp (FindThreadByID(tid));
797 if (selected_thread_sp->EventTypeHasListeners(Thread::eBroadcastBitThreadSelected))
798 selected_thread_sp->BroadcastEvent(Thread::eBroadcastBitThreadSelected,
799 new Thread::ThreadEventData(selected_thread_sp));
803 ThreadList::Update (ThreadList &rhs)
807 // Lock both mutexes to make sure neither side changes anyone on us
808 // while the assignment occurs
809 std::lock_guard<std::recursive_mutex> guard(GetMutex());
811 m_process = rhs.m_process;
812 m_stop_id = rhs.m_stop_id;
813 m_threads.swap(rhs.m_threads);
814 m_selected_tid = rhs.m_selected_tid;
817 // Now we look for threads that we are done with and
818 // make sure to clear them up as much as possible so
819 // anyone with a shared pointer will still have a reference,
820 // but the thread won't be of much use. Using std::weak_ptr
821 // for all backward references (such as a thread to a process)
822 // will eventually solve this issue for us, but for now, we
823 // need to work around the issue
824 collection::iterator rhs_pos, rhs_end = rhs.m_threads.end();
825 for (rhs_pos = rhs.m_threads.begin(); rhs_pos != rhs_end; ++rhs_pos)
827 const lldb::tid_t tid = (*rhs_pos)->GetID();
828 bool thread_is_alive = false;
829 const uint32_t num_threads = m_threads.size();
830 for (uint32_t idx = 0; idx < num_threads; ++idx)
832 ThreadSP backing_thread = m_threads[idx]->GetBackingThread();
833 if (m_threads[idx]->GetID() == tid || (backing_thread && backing_thread->GetID() == tid))
835 thread_is_alive = true;
839 if (!thread_is_alive)
840 (*rhs_pos)->DestroyThread();
848 std::lock_guard<std::recursive_mutex> guard(GetMutex());
849 collection::iterator pos, end = m_threads.end();
850 for (pos = m_threads.begin(); pos != end; ++pos)
854 std::recursive_mutex &
855 ThreadList::GetMutex()
857 return m_process->m_thread_mutex;
860 ThreadList::ExpressionExecutionThreadPusher::ExpressionExecutionThreadPusher (lldb::ThreadSP thread_sp) :
861 m_thread_list(nullptr),
862 m_tid(LLDB_INVALID_THREAD_ID)
866 m_tid = thread_sp->GetID();
867 m_thread_list = &thread_sp->GetProcess()->GetThreadList();
868 m_thread_list->PushExpressionExecutionThread(m_tid);