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/Process.h"
21 #include "lldb/Target/RegisterContext.h"
22 #include "lldb/Target/Thread.h"
23 #include "lldb/Target/ThreadList.h"
24 #include "lldb/Target/ThreadPlan.h"
25 #include "lldb/Utility/ConvertEnum.h"
26 #include "lldb/Utility/LLDBAssert.h"
29 using namespace lldb_private;
31 ThreadList::ThreadList(Process *process)
32 : ThreadCollection(), m_process(process), m_stop_id(0),
33 m_selected_tid(LLDB_INVALID_THREAD_ID) {}
35 ThreadList::ThreadList(const ThreadList &rhs)
36 : ThreadCollection(), m_process(rhs.m_process), m_stop_id(rhs.m_stop_id),
38 // Use the assignment operator since it uses the mutex
42 const ThreadList &ThreadList::operator=(const ThreadList &rhs) {
44 // Lock both mutexes to make sure neither side changes anyone on us
45 // while the assignment occurs
46 std::lock_guard<std::recursive_mutex> guard(GetMutex());
47 std::lock_guard<std::recursive_mutex> rhs_guard(rhs.GetMutex());
49 m_process = rhs.m_process;
50 m_stop_id = rhs.m_stop_id;
51 m_threads = rhs.m_threads;
52 m_selected_tid = rhs.m_selected_tid;
57 ThreadList::~ThreadList() {
58 // Clear the thread list. Clear will take the mutex lock
59 // which will ensure that if anyone is using the list
60 // they won't get it removed while using it.
64 lldb::ThreadSP ThreadList::GetExpressionExecutionThread() {
65 if (m_expression_tid_stack.empty())
66 return GetSelectedThread();
67 ThreadSP expr_thread_sp = FindThreadByID(m_expression_tid_stack.back());
69 return expr_thread_sp;
71 return GetSelectedThread();
74 void ThreadList::PushExpressionExecutionThread(lldb::tid_t tid) {
75 m_expression_tid_stack.push_back(tid);
78 void ThreadList::PopExpressionExecutionThread(lldb::tid_t tid) {
79 assert(m_expression_tid_stack.back() == tid);
80 m_expression_tid_stack.pop_back();
83 uint32_t ThreadList::GetStopID() const { return m_stop_id; }
85 void ThreadList::SetStopID(uint32_t stop_id) { m_stop_id = stop_id; }
87 uint32_t ThreadList::GetSize(bool can_update) {
88 std::lock_guard<std::recursive_mutex> guard(GetMutex());
91 m_process->UpdateThreadListIfNeeded();
92 return m_threads.size();
95 ThreadSP ThreadList::GetThreadAtIndex(uint32_t idx, bool can_update) {
96 std::lock_guard<std::recursive_mutex> guard(GetMutex());
99 m_process->UpdateThreadListIfNeeded();
102 if (idx < m_threads.size())
103 thread_sp = m_threads[idx];
107 ThreadSP ThreadList::FindThreadByID(lldb::tid_t tid, bool can_update) {
108 std::lock_guard<std::recursive_mutex> guard(GetMutex());
111 m_process->UpdateThreadListIfNeeded();
115 const uint32_t num_threads = m_threads.size();
116 for (idx = 0; idx < num_threads; ++idx) {
117 if (m_threads[idx]->GetID() == tid) {
118 thread_sp = m_threads[idx];
125 ThreadSP ThreadList::FindThreadByProtocolID(lldb::tid_t tid, bool can_update) {
126 std::lock_guard<std::recursive_mutex> guard(GetMutex());
129 m_process->UpdateThreadListIfNeeded();
133 const uint32_t num_threads = m_threads.size();
134 for (idx = 0; idx < num_threads; ++idx) {
135 if (m_threads[idx]->GetProtocolID() == tid) {
136 thread_sp = m_threads[idx];
143 ThreadSP ThreadList::RemoveThreadByID(lldb::tid_t tid, bool can_update) {
144 std::lock_guard<std::recursive_mutex> guard(GetMutex());
147 m_process->UpdateThreadListIfNeeded();
151 const uint32_t num_threads = m_threads.size();
152 for (idx = 0; idx < num_threads; ++idx) {
153 if (m_threads[idx]->GetID() == tid) {
154 thread_sp = m_threads[idx];
155 m_threads.erase(m_threads.begin() + idx);
162 ThreadSP ThreadList::RemoveThreadByProtocolID(lldb::tid_t tid,
164 std::lock_guard<std::recursive_mutex> guard(GetMutex());
167 m_process->UpdateThreadListIfNeeded();
171 const uint32_t num_threads = m_threads.size();
172 for (idx = 0; idx < num_threads; ++idx) {
173 if (m_threads[idx]->GetProtocolID() == tid) {
174 thread_sp = m_threads[idx];
175 m_threads.erase(m_threads.begin() + idx);
182 ThreadSP ThreadList::GetThreadSPForThreadPtr(Thread *thread_ptr) {
185 std::lock_guard<std::recursive_mutex> guard(GetMutex());
188 const uint32_t num_threads = m_threads.size();
189 for (idx = 0; idx < num_threads; ++idx) {
190 if (m_threads[idx].get() == thread_ptr) {
191 thread_sp = m_threads[idx];
199 ThreadSP ThreadList::FindThreadByIndexID(uint32_t index_id, bool can_update) {
200 std::lock_guard<std::recursive_mutex> guard(GetMutex());
203 m_process->UpdateThreadListIfNeeded();
206 const uint32_t num_threads = m_threads.size();
207 for (uint32_t idx = 0; idx < num_threads; ++idx) {
208 if (m_threads[idx]->GetIndexID() == index_id) {
209 thread_sp = m_threads[idx];
216 bool ThreadList::ShouldStop(Event *event_ptr) {
217 // Running events should never stop, obviously...
219 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
221 // The ShouldStop method of the threads can do a whole lot of work,
222 // figuring out whether the thread plan conditions are met. So we don't want
223 // to keep the ThreadList locked the whole time we are doing this.
224 // FIXME: It is possible that running code could cause new threads
225 // to be created. If that happens, we will miss asking them whether
226 // they should stop. This is not a big deal since we haven't had
227 // a chance to hang any interesting operations on those threads yet.
229 collection threads_copy;
232 std::lock_guard<std::recursive_mutex> guard(GetMutex());
234 m_process->UpdateThreadListIfNeeded();
235 for (lldb::ThreadSP thread_sp : m_threads) {
236 // This is an optimization... If we didn't let a thread run in between
237 // the previous stop and this
238 // one, we shouldn't have to consult it for ShouldStop. So just leave it
239 // off the list we are going to
241 // On Linux, if a thread-specific conditional breakpoint was hit, it won't
242 // necessarily be the thread
243 // that hit the breakpoint itself that evaluates the conditional
244 // expression, so the thread that hit
245 // the breakpoint could still be asked to stop, even though it hasn't been
246 // allowed to run since the
248 if (thread_sp->GetTemporaryResumeState() != eStateSuspended ||
249 thread_sp->IsStillAtLastBreakpointHit())
250 threads_copy.push_back(thread_sp);
253 // It is possible the threads we were allowing to run all exited and then
254 // maybe the user interrupted
255 // or something, then fall back on looking at all threads:
257 if (threads_copy.size() == 0)
258 threads_copy = m_threads;
261 collection::iterator pos, end = threads_copy.end();
265 log->Printf("ThreadList::%s: %" PRIu64 " threads, %" PRIu64
266 " unsuspended threads",
267 __FUNCTION__, (uint64_t)m_threads.size(),
268 (uint64_t)threads_copy.size());
271 bool did_anybody_stop_for_a_reason = false;
273 // If the event is an Interrupt event, then we're going to stop no matter
274 // what. Otherwise, presume we won't stop.
275 bool should_stop = false;
276 if (Process::ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
279 "ThreadList::%s handling interrupt event, should stop set to true",
285 // Now we run through all the threads and get their stop info's. We want to
286 // make sure to do this first before
287 // we start running the ShouldStop, because one thread's ShouldStop could
288 // destroy information (like deleting a
289 // thread specific breakpoint another thread had stopped at) which could lead
290 // us to compute the StopInfo incorrectly.
291 // We don't need to use it here, we just want to make sure it gets computed.
293 for (pos = threads_copy.begin(); pos != end; ++pos) {
294 ThreadSP thread_sp(*pos);
295 thread_sp->GetStopInfo();
298 for (pos = threads_copy.begin(); pos != end; ++pos) {
299 ThreadSP thread_sp(*pos);
301 // We should never get a stop for which no thread had a stop reason, but
302 // sometimes we do see this -
303 // for instance when we first connect to a remote stub. In that case we
304 // should stop, since we can't figure out
305 // the right thing to do and stopping gives the user control over what to do
308 // Note, this causes a problem when you have a thread specific breakpoint,
309 // and a bunch of threads hit the breakpoint,
310 // but not the thread which we are waiting for. All the threads that are
311 // not "supposed" to hit the breakpoint
312 // are marked as having no stop reason, which is right, they should not show
313 // a stop reason. But that triggers this
314 // code and causes us to stop seemingly for no reason.
316 // Since the only way we ever saw this error was on first attach, I'm only
317 // going to trigger set did_anybody_stop_for_a_reason
318 // to true unless this is the first stop.
320 // If this becomes a problem, we'll have to have another StopReason like
321 // "StopInfoHidden" which will look invalid
322 // everywhere but at this check.
324 if (thread_sp->GetProcess()->GetStopID() > 1)
325 did_anybody_stop_for_a_reason = true;
327 did_anybody_stop_for_a_reason |= thread_sp->ThreadStoppedForAReason();
329 const bool thread_should_stop = thread_sp->ShouldStop(event_ptr);
330 if (thread_should_stop)
334 if (!should_stop && !did_anybody_stop_for_a_reason) {
337 log->Printf("ThreadList::%s we stopped but no threads had a stop reason, "
338 "overriding should_stop and stopping.",
343 log->Printf("ThreadList::%s overall should_stop = %i", __FUNCTION__,
347 for (pos = threads_copy.begin(); pos != end; ++pos) {
348 ThreadSP thread_sp(*pos);
349 thread_sp->WillStop();
356 Vote ThreadList::ShouldReportStop(Event *event_ptr) {
357 std::lock_guard<std::recursive_mutex> guard(GetMutex());
359 Vote result = eVoteNoOpinion;
360 m_process->UpdateThreadListIfNeeded();
361 collection::iterator pos, end = m_threads.end();
363 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
366 log->Printf("ThreadList::%s %" PRIu64 " threads", __FUNCTION__,
367 (uint64_t)m_threads.size());
369 // Run through the threads and ask whether we should report this event.
370 // For stopping, a YES vote wins over everything. A NO vote wins over NO
372 for (pos = m_threads.begin(); pos != end; ++pos) {
373 ThreadSP thread_sp(*pos);
374 const Vote vote = thread_sp->ShouldReportStop(event_ptr);
384 if (result == eVoteNoOpinion) {
388 log->Printf("ThreadList::%s thread 0x%4.4" PRIx64
389 ": voted %s, but lost out because result was %s",
390 __FUNCTION__, thread_sp->GetID(), GetVoteAsCString(vote),
391 GetVoteAsCString(result));
397 log->Printf("ThreadList::%s returning %s", __FUNCTION__,
398 GetVoteAsCString(result));
402 void ThreadList::SetShouldReportStop(Vote vote) {
403 std::lock_guard<std::recursive_mutex> guard(GetMutex());
405 m_process->UpdateThreadListIfNeeded();
406 collection::iterator pos, end = m_threads.end();
407 for (pos = m_threads.begin(); pos != end; ++pos) {
408 ThreadSP thread_sp(*pos);
409 thread_sp->SetShouldReportStop(vote);
413 Vote ThreadList::ShouldReportRun(Event *event_ptr) {
415 std::lock_guard<std::recursive_mutex> guard(GetMutex());
417 Vote result = eVoteNoOpinion;
418 m_process->UpdateThreadListIfNeeded();
419 collection::iterator pos, end = m_threads.end();
421 // Run through the threads and ask whether we should report this event.
422 // The rule is NO vote wins over everything, a YES vote wins over no opinion.
424 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
426 for (pos = m_threads.begin(); pos != end; ++pos) {
427 if ((*pos)->GetResumeState() != eStateSuspended) {
428 switch ((*pos)->ShouldReportRun(event_ptr)) {
432 if (result == eVoteNoOpinion)
437 log->Printf("ThreadList::ShouldReportRun() thread %d (0x%4.4" PRIx64
438 ") says don't report.",
439 (*pos)->GetIndexID(), (*pos)->GetID());
448 void ThreadList::Clear() {
449 std::lock_guard<std::recursive_mutex> guard(GetMutex());
452 m_selected_tid = LLDB_INVALID_THREAD_ID;
455 void ThreadList::Destroy() {
456 std::lock_guard<std::recursive_mutex> guard(GetMutex());
457 const uint32_t num_threads = m_threads.size();
458 for (uint32_t idx = 0; idx < num_threads; ++idx) {
459 m_threads[idx]->DestroyThread();
463 void ThreadList::RefreshStateAfterStop() {
464 std::lock_guard<std::recursive_mutex> guard(GetMutex());
466 m_process->UpdateThreadListIfNeeded();
468 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
469 if (log && log->GetVerbose())
470 log->Printf("Turning off notification of new threads while single stepping "
473 collection::iterator pos, end = m_threads.end();
474 for (pos = m_threads.begin(); pos != end; ++pos)
475 (*pos)->RefreshStateAfterStop();
478 void ThreadList::DiscardThreadPlans() {
479 // You don't need to update the thread list here, because only threads
480 // that you currently know about have any thread plans.
481 std::lock_guard<std::recursive_mutex> guard(GetMutex());
483 collection::iterator pos, end = m_threads.end();
484 for (pos = m_threads.begin(); pos != end; ++pos)
485 (*pos)->DiscardThreadPlans(true);
488 bool ThreadList::WillResume() {
489 // Run through the threads and perform their momentary actions.
490 // But we only do this for threads that are running, user suspended
491 // threads stay where they are.
493 std::lock_guard<std::recursive_mutex> guard(GetMutex());
494 m_process->UpdateThreadListIfNeeded();
496 collection::iterator pos, end = m_threads.end();
498 // See if any thread wants to run stopping others. If it does, then we won't
499 // setup the other threads for resume, since they aren't going to get a chance
500 // to run. This is necessary because the SetupForResume might add
502 // plans which would then get to be part of the who-gets-to-run negotiation,
504 // they're coming in after the fact, and the threads that are already set up
508 bool wants_solo_run = false;
510 for (pos = m_threads.begin(); pos != end; ++pos) {
511 lldbassert((*pos)->GetCurrentPlan() &&
512 "thread should not have null thread plan");
513 if ((*pos)->GetResumeState() != eStateSuspended &&
514 (*pos)->GetCurrentPlan()->StopOthers()) {
515 if ((*pos)->IsOperatingSystemPluginThread() &&
516 !(*pos)->GetBackingThread())
518 wants_solo_run = true;
523 if (wants_solo_run) {
524 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
525 if (log && log->GetVerbose())
526 log->Printf("Turning on notification of new threads while single "
527 "stepping a thread.");
528 m_process->StartNoticingNewThreads();
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 "
533 "stepping a thread.");
534 m_process->StopNoticingNewThreads();
537 // Give all the threads that are likely to run a last chance to set up their
539 // negotiate who is actually going to get a chance to run...
540 // Don't set to resume suspended threads, and if any thread wanted to stop
542 // call setup on the threads that request StopOthers...
544 for (pos = m_threads.begin(); pos != end; ++pos) {
545 if ((*pos)->GetResumeState() != eStateSuspended &&
546 (!wants_solo_run || (*pos)->GetCurrentPlan()->StopOthers())) {
547 if ((*pos)->IsOperatingSystemPluginThread() &&
548 !(*pos)->GetBackingThread())
550 (*pos)->SetupForResume();
554 // Now go through the threads and see if any thread wants to run just itself.
555 // if so then pick one and run it.
557 ThreadList run_me_only_list(m_process);
559 run_me_only_list.SetStopID(m_process->GetStopID());
561 bool run_only_current_thread = false;
563 for (pos = m_threads.begin(); pos != end; ++pos) {
564 ThreadSP thread_sp(*pos);
565 if (thread_sp->GetResumeState() != eStateSuspended &&
566 thread_sp->GetCurrentPlan()->StopOthers()) {
567 if ((*pos)->IsOperatingSystemPluginThread() &&
568 !(*pos)->GetBackingThread())
571 // You can't say "stop others" and also want yourself to be suspended.
572 assert(thread_sp->GetCurrentPlan()->RunState() != eStateSuspended);
574 if (thread_sp == GetSelectedThread()) {
575 // If the currently selected thread wants to run on its own, always let
577 run_only_current_thread = true;
578 run_me_only_list.Clear();
579 run_me_only_list.AddThread(thread_sp);
583 run_me_only_list.AddThread(thread_sp);
587 bool need_to_resume = true;
589 if (run_me_only_list.GetSize(false) == 0) {
590 // Everybody runs as they wish:
591 for (pos = m_threads.begin(); pos != end; ++pos) {
592 ThreadSP thread_sp(*pos);
594 if (thread_sp->GetResumeState() != eStateSuspended)
595 run_state = thread_sp->GetCurrentPlan()->RunState();
597 run_state = eStateSuspended;
598 if (!thread_sp->ShouldResume(run_state))
599 need_to_resume = false;
602 ThreadSP thread_to_run;
604 if (run_only_current_thread) {
605 thread_to_run = GetSelectedThread();
606 } else if (run_me_only_list.GetSize(false) == 1) {
607 thread_to_run = run_me_only_list.GetThreadAtIndex(0);
610 (int)((run_me_only_list.GetSize(false) * (double)rand()) /
612 thread_to_run = run_me_only_list.GetThreadAtIndex(random_thread);
615 for (pos = m_threads.begin(); pos != end; ++pos) {
616 ThreadSP thread_sp(*pos);
617 if (thread_sp == thread_to_run) {
618 if (!thread_sp->ShouldResume(thread_sp->GetCurrentPlan()->RunState()))
619 need_to_resume = false;
621 thread_sp->ShouldResume(eStateSuspended);
625 return need_to_resume;
628 void ThreadList::DidResume() {
629 std::lock_guard<std::recursive_mutex> guard(GetMutex());
630 collection::iterator pos, end = m_threads.end();
631 for (pos = m_threads.begin(); pos != end; ++pos) {
632 // Don't clear out threads that aren't going to get a chance to run, rather
633 // leave their state for the next time around.
634 ThreadSP thread_sp(*pos);
635 if (thread_sp->GetResumeState() != eStateSuspended)
636 thread_sp->DidResume();
640 void ThreadList::DidStop() {
641 std::lock_guard<std::recursive_mutex> guard(GetMutex());
642 collection::iterator pos, end = m_threads.end();
643 for (pos = m_threads.begin(); pos != end; ++pos) {
644 // Notify threads that the process just stopped.
645 // Note, this currently assumes that all threads in the list
646 // stop when the process stops. In the future we will want to support
647 // a debugging model where some threads continue to run while others
648 // are stopped. We either need to handle that somehow here or
649 // create a special thread list containing only threads which will
650 // stop in the code that calls this method (currently
651 // Process::SetPrivateState).
652 ThreadSP thread_sp(*pos);
653 if (StateIsRunningState(thread_sp->GetState()))
654 thread_sp->DidStop();
658 ThreadSP ThreadList::GetSelectedThread() {
659 std::lock_guard<std::recursive_mutex> guard(GetMutex());
660 ThreadSP thread_sp = FindThreadByID(m_selected_tid);
661 if (!thread_sp.get()) {
662 if (m_threads.size() == 0)
664 m_selected_tid = m_threads[0]->GetID();
665 thread_sp = m_threads[0];
670 bool ThreadList::SetSelectedThreadByID(lldb::tid_t tid, bool notify) {
671 std::lock_guard<std::recursive_mutex> guard(GetMutex());
672 ThreadSP selected_thread_sp(FindThreadByID(tid));
673 if (selected_thread_sp) {
674 m_selected_tid = tid;
675 selected_thread_sp->SetDefaultFileAndLineToSelectedFrame();
677 m_selected_tid = LLDB_INVALID_THREAD_ID;
680 NotifySelectedThreadChanged(m_selected_tid);
682 return m_selected_tid != LLDB_INVALID_THREAD_ID;
685 bool ThreadList::SetSelectedThreadByIndexID(uint32_t index_id, bool notify) {
686 std::lock_guard<std::recursive_mutex> guard(GetMutex());
687 ThreadSP selected_thread_sp(FindThreadByIndexID(index_id));
688 if (selected_thread_sp.get()) {
689 m_selected_tid = selected_thread_sp->GetID();
690 selected_thread_sp->SetDefaultFileAndLineToSelectedFrame();
692 m_selected_tid = LLDB_INVALID_THREAD_ID;
695 NotifySelectedThreadChanged(m_selected_tid);
697 return m_selected_tid != LLDB_INVALID_THREAD_ID;
700 void ThreadList::NotifySelectedThreadChanged(lldb::tid_t tid) {
701 ThreadSP selected_thread_sp(FindThreadByID(tid));
702 if (selected_thread_sp->EventTypeHasListeners(
703 Thread::eBroadcastBitThreadSelected))
704 selected_thread_sp->BroadcastEvent(
705 Thread::eBroadcastBitThreadSelected,
706 new Thread::ThreadEventData(selected_thread_sp));
709 void ThreadList::Update(ThreadList &rhs) {
711 // Lock both mutexes to make sure neither side changes anyone on us
712 // while the assignment occurs
713 std::lock_guard<std::recursive_mutex> guard(GetMutex());
715 m_process = rhs.m_process;
716 m_stop_id = rhs.m_stop_id;
717 m_threads.swap(rhs.m_threads);
718 m_selected_tid = rhs.m_selected_tid;
720 // Now we look for threads that we are done with and
721 // make sure to clear them up as much as possible so
722 // anyone with a shared pointer will still have a reference,
723 // but the thread won't be of much use. Using std::weak_ptr
724 // for all backward references (such as a thread to a process)
725 // will eventually solve this issue for us, but for now, we
726 // need to work around the issue
727 collection::iterator rhs_pos, rhs_end = rhs.m_threads.end();
728 for (rhs_pos = rhs.m_threads.begin(); rhs_pos != rhs_end; ++rhs_pos) {
729 const lldb::tid_t tid = (*rhs_pos)->GetID();
730 bool thread_is_alive = false;
731 const uint32_t num_threads = m_threads.size();
732 for (uint32_t idx = 0; idx < num_threads; ++idx) {
733 ThreadSP backing_thread = m_threads[idx]->GetBackingThread();
734 if (m_threads[idx]->GetID() == tid ||
735 (backing_thread && backing_thread->GetID() == tid)) {
736 thread_is_alive = true;
740 if (!thread_is_alive)
741 (*rhs_pos)->DestroyThread();
746 void ThreadList::Flush() {
747 std::lock_guard<std::recursive_mutex> guard(GetMutex());
748 collection::iterator pos, end = m_threads.end();
749 for (pos = m_threads.begin(); pos != end; ++pos)
753 std::recursive_mutex &ThreadList::GetMutex() const {
754 return m_process->m_thread_mutex;
757 ThreadList::ExpressionExecutionThreadPusher::ExpressionExecutionThreadPusher(
758 lldb::ThreadSP thread_sp)
759 : m_thread_list(nullptr), m_tid(LLDB_INVALID_THREAD_ID) {
761 m_tid = thread_sp->GetID();
762 m_thread_list = &thread_sp->GetProcess()->GetThreadList();
763 m_thread_list->PushExpressionExecutionThread(m_tid);