1 //===-- ThreadList.cpp ------------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 // C Includes
11 #include <stdlib.h>
12 
13 // C++ Includes
14 #include <algorithm>
15 
16 // Other libraries and framework includes
17 // Project 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"
27 
28 using namespace lldb;
29 using namespace lldb_private;
30 
31 ThreadList::ThreadList(Process *process)
32     : ThreadCollection(), m_process(process), m_stop_id(0),
33       m_selected_tid(LLDB_INVALID_THREAD_ID) {}
34 
35 ThreadList::ThreadList(const ThreadList &rhs)
36     : ThreadCollection(), m_process(rhs.m_process), m_stop_id(rhs.m_stop_id),
37       m_selected_tid() {
38   // Use the assignment operator since it uses the mutex
39   *this = rhs;
40 }
41 
42 const ThreadList &ThreadList::operator=(const ThreadList &rhs) {
43   if (this != &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 
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;
52   }
53   return *this;
54 }
55 
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.
60   Clear();
61 }
62 
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());
67   if (expr_thread_sp)
68     return expr_thread_sp;
69   else
70     return GetSelectedThread();
71 }
72 
73 void ThreadList::PushExpressionExecutionThread(lldb::tid_t tid) {
74   m_expression_tid_stack.push_back(tid);
75 }
76 
77 void ThreadList::PopExpressionExecutionThread(lldb::tid_t tid) {
78   assert(m_expression_tid_stack.back() == tid);
79   m_expression_tid_stack.pop_back();
80 }
81 
82 uint32_t ThreadList::GetStopID() const { return m_stop_id; }
83 
84 void ThreadList::SetStopID(uint32_t stop_id) { m_stop_id = stop_id; }
85 
86 uint32_t ThreadList::GetSize(bool can_update) {
87   std::lock_guard<std::recursive_mutex> guard(GetMutex());
88 
89   if (can_update)
90     m_process->UpdateThreadListIfNeeded();
91   return m_threads.size();
92 }
93 
94 ThreadSP ThreadList::GetThreadAtIndex(uint32_t idx, bool can_update) {
95   std::lock_guard<std::recursive_mutex> guard(GetMutex());
96 
97   if (can_update)
98     m_process->UpdateThreadListIfNeeded();
99 
100   ThreadSP thread_sp;
101   if (idx < m_threads.size())
102     thread_sp = m_threads[idx];
103   return thread_sp;
104 }
105 
106 ThreadSP ThreadList::FindThreadByID(lldb::tid_t tid, bool can_update) {
107   std::lock_guard<std::recursive_mutex> guard(GetMutex());
108 
109   if (can_update)
110     m_process->UpdateThreadListIfNeeded();
111 
112   ThreadSP thread_sp;
113   uint32_t idx = 0;
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];
118       break;
119     }
120   }
121   return thread_sp;
122 }
123 
124 ThreadSP ThreadList::FindThreadByProtocolID(lldb::tid_t tid, bool can_update) {
125   std::lock_guard<std::recursive_mutex> guard(GetMutex());
126 
127   if (can_update)
128     m_process->UpdateThreadListIfNeeded();
129 
130   ThreadSP thread_sp;
131   uint32_t idx = 0;
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];
136       break;
137     }
138   }
139   return thread_sp;
140 }
141 
142 ThreadSP ThreadList::RemoveThreadByID(lldb::tid_t tid, bool can_update) {
143   std::lock_guard<std::recursive_mutex> guard(GetMutex());
144 
145   if (can_update)
146     m_process->UpdateThreadListIfNeeded();
147 
148   ThreadSP thread_sp;
149   uint32_t idx = 0;
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);
155       break;
156     }
157   }
158   return thread_sp;
159 }
160 
161 ThreadSP ThreadList::RemoveThreadByProtocolID(lldb::tid_t tid,
162                                               bool can_update) {
163   std::lock_guard<std::recursive_mutex> guard(GetMutex());
164 
165   if (can_update)
166     m_process->UpdateThreadListIfNeeded();
167 
168   ThreadSP thread_sp;
169   uint32_t idx = 0;
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);
175       break;
176     }
177   }
178   return thread_sp;
179 }
180 
181 ThreadSP ThreadList::GetThreadSPForThreadPtr(Thread *thread_ptr) {
182   ThreadSP thread_sp;
183   if (thread_ptr) {
184     std::lock_guard<std::recursive_mutex> guard(GetMutex());
185 
186     uint32_t idx = 0;
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];
191         break;
192       }
193     }
194   }
195   return thread_sp;
196 }
197 
198 ThreadSP ThreadList::FindThreadByIndexID(uint32_t index_id, bool can_update) {
199   std::lock_guard<std::recursive_mutex> guard(GetMutex());
200 
201   if (can_update)
202     m_process->UpdateThreadListIfNeeded();
203 
204   ThreadSP thread_sp;
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];
209       break;
210     }
211   }
212   return thread_sp;
213 }
214 
215 bool ThreadList::ShouldStop(Event *event_ptr) {
216   // Running events should never stop, obviously...
217 
218   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
219 
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.
227 
228   collection threads_copy;
229   {
230     // Scope for locker
231     std::lock_guard<std::recursive_mutex> guard(GetMutex());
232 
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
239       // inspect.
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
246       // previous stop.
247       if (thread_sp->GetTemporaryResumeState() != eStateSuspended ||
248           thread_sp->IsStillAtLastBreakpointHit())
249         threads_copy.push_back(thread_sp);
250     }
251 
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:
255 
256     if (threads_copy.size() == 0)
257       threads_copy = m_threads;
258   }
259 
260   collection::iterator pos, end = threads_copy.end();
261 
262   if (log) {
263     log->PutCString("");
264     log->Printf("ThreadList::%s: %" PRIu64 " threads, %" PRIu64
265                 " unsuspended threads",
266                 __FUNCTION__, (uint64_t)m_threads.size(),
267                 (uint64_t)threads_copy.size());
268   }
269 
270   bool did_anybody_stop_for_a_reason = false;
271 
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)) {
276     if (log)
277       log->Printf(
278           "ThreadList::%s handling interrupt event, should stop set to true",
279           __FUNCTION__);
280 
281     should_stop = true;
282   }
283 
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.
291 
292   for (pos = threads_copy.begin(); pos != end; ++pos) {
293     ThreadSP thread_sp(*pos);
294     thread_sp->GetStopInfo();
295   }
296 
297   for (pos = threads_copy.begin(); pos != end; ++pos) {
298     ThreadSP thread_sp(*pos);
299 
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
305     // in this instance.
306     //
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.
314     //
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.
318     //
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.
322 
323     if (thread_sp->GetProcess()->GetStopID() > 1)
324       did_anybody_stop_for_a_reason = true;
325     else
326       did_anybody_stop_for_a_reason |= thread_sp->ThreadStoppedForAReason();
327 
328     const bool thread_should_stop = thread_sp->ShouldStop(event_ptr);
329     if (thread_should_stop)
330       should_stop |= true;
331   }
332 
333   if (!should_stop && !did_anybody_stop_for_a_reason) {
334     should_stop = true;
335     if (log)
336       log->Printf("ThreadList::%s we stopped but no threads had a stop reason, "
337                   "overriding should_stop and stopping.",
338                   __FUNCTION__);
339   }
340 
341   if (log)
342     log->Printf("ThreadList::%s overall should_stop = %i", __FUNCTION__,
343                 should_stop);
344 
345   if (should_stop) {
346     for (pos = threads_copy.begin(); pos != end; ++pos) {
347       ThreadSP thread_sp(*pos);
348       thread_sp->WillStop();
349     }
350   }
351 
352   return should_stop;
353 }
354 
355 Vote ThreadList::ShouldReportStop(Event *event_ptr) {
356   std::lock_guard<std::recursive_mutex> guard(GetMutex());
357 
358   Vote result = eVoteNoOpinion;
359   m_process->UpdateThreadListIfNeeded();
360   collection::iterator pos, end = m_threads.end();
361 
362   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
363 
364   if (log)
365     log->Printf("ThreadList::%s %" PRIu64 " threads", __FUNCTION__,
366                 (uint64_t)m_threads.size());
367 
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
370   // opinion.
371   for (pos = m_threads.begin(); pos != end; ++pos) {
372     ThreadSP thread_sp(*pos);
373     const Vote vote = thread_sp->ShouldReportStop(event_ptr);
374     switch (vote) {
375     case eVoteNoOpinion:
376       continue;
377 
378     case eVoteYes:
379       result = eVoteYes;
380       break;
381 
382     case eVoteNo:
383       if (result == eVoteNoOpinion) {
384         result = eVoteNo;
385       } else {
386         if (log)
387           log->Printf("ThreadList::%s thread 0x%4.4" PRIx64
388                       ": voted %s, but lost out because result was %s",
389                       __FUNCTION__, thread_sp->GetID(), GetVoteAsCString(vote),
390                       GetVoteAsCString(result));
391       }
392       break;
393     }
394   }
395   if (log)
396     log->Printf("ThreadList::%s returning %s", __FUNCTION__,
397                 GetVoteAsCString(result));
398   return result;
399 }
400 
401 void ThreadList::SetShouldReportStop(Vote vote) {
402   std::lock_guard<std::recursive_mutex> guard(GetMutex());
403 
404   m_process->UpdateThreadListIfNeeded();
405   collection::iterator pos, end = m_threads.end();
406   for (pos = m_threads.begin(); pos != end; ++pos) {
407     ThreadSP thread_sp(*pos);
408     thread_sp->SetShouldReportStop(vote);
409   }
410 }
411 
412 Vote ThreadList::ShouldReportRun(Event *event_ptr) {
413 
414   std::lock_guard<std::recursive_mutex> guard(GetMutex());
415 
416   Vote result = eVoteNoOpinion;
417   m_process->UpdateThreadListIfNeeded();
418   collection::iterator pos, end = m_threads.end();
419 
420   // Run through the threads and ask whether we should report this event.
421   // The rule is NO vote wins over everything, a YES vote wins over no opinion.
422 
423   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
424 
425   for (pos = m_threads.begin(); pos != end; ++pos) {
426     if ((*pos)->GetResumeState() != eStateSuspended) {
427       switch ((*pos)->ShouldReportRun(event_ptr)) {
428       case eVoteNoOpinion:
429         continue;
430       case eVoteYes:
431         if (result == eVoteNoOpinion)
432           result = eVoteYes;
433         break;
434       case eVoteNo:
435         if (log)
436           log->Printf("ThreadList::ShouldReportRun() thread %d (0x%4.4" PRIx64
437                       ") says don't report.",
438                       (*pos)->GetIndexID(), (*pos)->GetID());
439         result = eVoteNo;
440         break;
441       }
442     }
443   }
444   return result;
445 }
446 
447 void ThreadList::Clear() {
448   std::lock_guard<std::recursive_mutex> guard(GetMutex());
449   m_stop_id = 0;
450   m_threads.clear();
451   m_selected_tid = LLDB_INVALID_THREAD_ID;
452 }
453 
454 void ThreadList::Destroy() {
455   std::lock_guard<std::recursive_mutex> guard(GetMutex());
456   const uint32_t num_threads = m_threads.size();
457   for (uint32_t idx = 0; idx < num_threads; ++idx) {
458     m_threads[idx]->DestroyThread();
459   }
460 }
461 
462 void ThreadList::RefreshStateAfterStop() {
463   std::lock_guard<std::recursive_mutex> guard(GetMutex());
464 
465   m_process->UpdateThreadListIfNeeded();
466 
467   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
468   if (log && log->GetVerbose())
469     log->Printf("Turning off notification of new threads while single stepping "
470                 "a thread.");
471 
472   collection::iterator pos, end = m_threads.end();
473   for (pos = m_threads.begin(); pos != end; ++pos)
474     (*pos)->RefreshStateAfterStop();
475 }
476 
477 void ThreadList::DiscardThreadPlans() {
478   // You don't need to update the thread list here, because only threads
479   // that you currently know about have any thread plans.
480   std::lock_guard<std::recursive_mutex> guard(GetMutex());
481 
482   collection::iterator pos, end = m_threads.end();
483   for (pos = m_threads.begin(); pos != end; ++pos)
484     (*pos)->DiscardThreadPlans(true);
485 }
486 
487 bool ThreadList::WillResume() {
488   // Run through the threads and perform their momentary actions.
489   // But we only do this for threads that are running, user suspended
490   // threads stay where they are.
491 
492   std::lock_guard<std::recursive_mutex> guard(GetMutex());
493   m_process->UpdateThreadListIfNeeded();
494 
495   collection::iterator pos, end = m_threads.end();
496 
497   // See if any thread wants to run stopping others.  If it does, then we won't
498   // setup the other threads for resume, since they aren't going to get a chance
499   // to run.  This is necessary because the SetupForResume might add
500   // "StopOthers"
501   // plans which would then get to be part of the who-gets-to-run negotiation,
502   // but
503   // they're coming in after the fact, and the threads that are already set up
504   // should
505   // take priority.
506 
507   bool wants_solo_run = false;
508 
509   for (pos = m_threads.begin(); pos != end; ++pos) {
510     lldbassert((*pos)->GetCurrentPlan() &&
511                "thread should not have null thread plan");
512     if ((*pos)->GetResumeState() != eStateSuspended &&
513         (*pos)->GetCurrentPlan()->StopOthers()) {
514       if ((*pos)->IsOperatingSystemPluginThread() &&
515           !(*pos)->GetBackingThread())
516         continue;
517       wants_solo_run = true;
518       break;
519     }
520   }
521 
522   if (wants_solo_run) {
523     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
524     if (log && log->GetVerbose())
525       log->Printf("Turning on notification of new threads while single "
526                   "stepping a thread.");
527     m_process->StartNoticingNewThreads();
528   } else {
529     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
530     if (log && log->GetVerbose())
531       log->Printf("Turning off notification of new threads while single "
532                   "stepping a thread.");
533     m_process->StopNoticingNewThreads();
534   }
535 
536   // Give all the threads that are likely to run a last chance to set up their
537   // state before we
538   // negotiate who is actually going to get a chance to run...
539   // Don't set to resume suspended threads, and if any thread wanted to stop
540   // others, only
541   // call setup on the threads that request StopOthers...
542 
543   for (pos = m_threads.begin(); pos != end; ++pos) {
544     if ((*pos)->GetResumeState() != eStateSuspended &&
545         (!wants_solo_run || (*pos)->GetCurrentPlan()->StopOthers())) {
546       if ((*pos)->IsOperatingSystemPluginThread() &&
547           !(*pos)->GetBackingThread())
548         continue;
549       (*pos)->SetupForResume();
550     }
551   }
552 
553   // Now go through the threads and see if any thread wants to run just itself.
554   // if so then pick one and run it.
555 
556   ThreadList run_me_only_list(m_process);
557 
558   run_me_only_list.SetStopID(m_process->GetStopID());
559 
560   bool run_only_current_thread = false;
561 
562   for (pos = m_threads.begin(); pos != end; ++pos) {
563     ThreadSP thread_sp(*pos);
564     if (thread_sp->GetResumeState() != eStateSuspended &&
565         thread_sp->GetCurrentPlan()->StopOthers()) {
566       if ((*pos)->IsOperatingSystemPluginThread() &&
567           !(*pos)->GetBackingThread())
568         continue;
569 
570       // You can't say "stop others" and also want yourself to be suspended.
571       assert(thread_sp->GetCurrentPlan()->RunState() != eStateSuspended);
572 
573       if (thread_sp == GetSelectedThread()) {
574         // If the currently selected thread wants to run on its own, always let
575         // it.
576         run_only_current_thread = true;
577         run_me_only_list.Clear();
578         run_me_only_list.AddThread(thread_sp);
579         break;
580       }
581 
582       run_me_only_list.AddThread(thread_sp);
583     }
584   }
585 
586   bool need_to_resume = true;
587 
588   if (run_me_only_list.GetSize(false) == 0) {
589     // Everybody runs as they wish:
590     for (pos = m_threads.begin(); pos != end; ++pos) {
591       ThreadSP thread_sp(*pos);
592       StateType run_state;
593       if (thread_sp->GetResumeState() != eStateSuspended)
594         run_state = thread_sp->GetCurrentPlan()->RunState();
595       else
596         run_state = eStateSuspended;
597       if (!thread_sp->ShouldResume(run_state))
598         need_to_resume = false;
599     }
600   } else {
601     ThreadSP thread_to_run;
602 
603     if (run_only_current_thread) {
604       thread_to_run = GetSelectedThread();
605     } else if (run_me_only_list.GetSize(false) == 1) {
606       thread_to_run = run_me_only_list.GetThreadAtIndex(0);
607     } else {
608       int random_thread =
609           (int)((run_me_only_list.GetSize(false) * (double)rand()) /
610                 (RAND_MAX + 1.0));
611       thread_to_run = run_me_only_list.GetThreadAtIndex(random_thread);
612     }
613 
614     for (pos = m_threads.begin(); pos != end; ++pos) {
615       ThreadSP thread_sp(*pos);
616       if (thread_sp == thread_to_run) {
617         if (!thread_sp->ShouldResume(thread_sp->GetCurrentPlan()->RunState()))
618           need_to_resume = false;
619       } else
620         thread_sp->ShouldResume(eStateSuspended);
621     }
622   }
623 
624   return need_to_resume;
625 }
626 
627 void ThreadList::DidResume() {
628   std::lock_guard<std::recursive_mutex> guard(GetMutex());
629   collection::iterator pos, end = m_threads.end();
630   for (pos = m_threads.begin(); pos != end; ++pos) {
631     // Don't clear out threads that aren't going to get a chance to run, rather
632     // leave their state for the next time around.
633     ThreadSP thread_sp(*pos);
634     if (thread_sp->GetResumeState() != eStateSuspended)
635       thread_sp->DidResume();
636   }
637 }
638 
639 void ThreadList::DidStop() {
640   std::lock_guard<std::recursive_mutex> guard(GetMutex());
641   collection::iterator pos, end = m_threads.end();
642   for (pos = m_threads.begin(); pos != end; ++pos) {
643     // Notify threads that the process just stopped.
644     // Note, this currently assumes that all threads in the list
645     // stop when the process stops.  In the future we will want to support
646     // a debugging model where some threads continue to run while others
647     // are stopped.  We either need to handle that somehow here or
648     // create a special thread list containing only threads which will
649     // stop in the code that calls this method (currently
650     // Process::SetPrivateState).
651     ThreadSP thread_sp(*pos);
652     if (StateIsRunningState(thread_sp->GetState()))
653       thread_sp->DidStop();
654   }
655 }
656 
657 ThreadSP ThreadList::GetSelectedThread() {
658   std::lock_guard<std::recursive_mutex> guard(GetMutex());
659   ThreadSP thread_sp = FindThreadByID(m_selected_tid);
660   if (!thread_sp.get()) {
661     if (m_threads.size() == 0)
662       return thread_sp;
663     m_selected_tid = m_threads[0]->GetID();
664     thread_sp = m_threads[0];
665   }
666   return thread_sp;
667 }
668 
669 bool ThreadList::SetSelectedThreadByID(lldb::tid_t tid, bool notify) {
670   std::lock_guard<std::recursive_mutex> guard(GetMutex());
671   ThreadSP selected_thread_sp(FindThreadByID(tid));
672   if (selected_thread_sp) {
673     m_selected_tid = tid;
674     selected_thread_sp->SetDefaultFileAndLineToSelectedFrame();
675   } else
676     m_selected_tid = LLDB_INVALID_THREAD_ID;
677 
678   if (notify)
679     NotifySelectedThreadChanged(m_selected_tid);
680 
681   return m_selected_tid != LLDB_INVALID_THREAD_ID;
682 }
683 
684 bool ThreadList::SetSelectedThreadByIndexID(uint32_t index_id, bool notify) {
685   std::lock_guard<std::recursive_mutex> guard(GetMutex());
686   ThreadSP selected_thread_sp(FindThreadByIndexID(index_id));
687   if (selected_thread_sp.get()) {
688     m_selected_tid = selected_thread_sp->GetID();
689     selected_thread_sp->SetDefaultFileAndLineToSelectedFrame();
690   } else
691     m_selected_tid = LLDB_INVALID_THREAD_ID;
692 
693   if (notify)
694     NotifySelectedThreadChanged(m_selected_tid);
695 
696   return m_selected_tid != LLDB_INVALID_THREAD_ID;
697 }
698 
699 void ThreadList::NotifySelectedThreadChanged(lldb::tid_t tid) {
700   ThreadSP selected_thread_sp(FindThreadByID(tid));
701   if (selected_thread_sp->EventTypeHasListeners(
702           Thread::eBroadcastBitThreadSelected))
703     selected_thread_sp->BroadcastEvent(
704         Thread::eBroadcastBitThreadSelected,
705         new Thread::ThreadEventData(selected_thread_sp));
706 }
707 
708 void ThreadList::Update(ThreadList &rhs) {
709   if (this != &rhs) {
710     // Lock both mutexes to make sure neither side changes anyone on us
711     // while the assignment occurs
712     std::lock_guard<std::recursive_mutex> guard(GetMutex());
713 
714     m_process = rhs.m_process;
715     m_stop_id = rhs.m_stop_id;
716     m_threads.swap(rhs.m_threads);
717     m_selected_tid = rhs.m_selected_tid;
718 
719     // Now we look for threads that we are done with and
720     // make sure to clear them up as much as possible so
721     // anyone with a shared pointer will still have a reference,
722     // but the thread won't be of much use. Using std::weak_ptr
723     // for all backward references (such as a thread to a process)
724     // will eventually solve this issue for us, but for now, we
725     // need to work around the issue
726     collection::iterator rhs_pos, rhs_end = rhs.m_threads.end();
727     for (rhs_pos = rhs.m_threads.begin(); rhs_pos != rhs_end; ++rhs_pos) {
728       const lldb::tid_t tid = (*rhs_pos)->GetID();
729       bool thread_is_alive = false;
730       const uint32_t num_threads = m_threads.size();
731       for (uint32_t idx = 0; idx < num_threads; ++idx) {
732         ThreadSP backing_thread = m_threads[idx]->GetBackingThread();
733         if (m_threads[idx]->GetID() == tid ||
734             (backing_thread && backing_thread->GetID() == tid)) {
735           thread_is_alive = true;
736           break;
737         }
738       }
739       if (!thread_is_alive)
740         (*rhs_pos)->DestroyThread();
741     }
742   }
743 }
744 
745 void ThreadList::Flush() {
746   std::lock_guard<std::recursive_mutex> guard(GetMutex());
747   collection::iterator pos, end = m_threads.end();
748   for (pos = m_threads.begin(); pos != end; ++pos)
749     (*pos)->Flush();
750 }
751 
752 std::recursive_mutex &ThreadList::GetMutex() {
753   return m_process->m_thread_mutex;
754 }
755 
756 ThreadList::ExpressionExecutionThreadPusher::ExpressionExecutionThreadPusher(
757     lldb::ThreadSP thread_sp)
758     : m_thread_list(nullptr), m_tid(LLDB_INVALID_THREAD_ID) {
759   if (thread_sp) {
760     m_tid = thread_sp->GetID();
761     m_thread_list = &thread_sp->GetProcess()->GetThreadList();
762     m_thread_list->PushExpressionExecutionThread(m_tid);
763   }
764 }
765