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/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"
26 
27 using namespace lldb;
28 using namespace lldb_private;
29 
30 ThreadList::ThreadList(Process *process)
31     : ThreadCollection(), m_process(process), m_stop_id(0),
32       m_selected_tid(LLDB_INVALID_THREAD_ID) {}
33 
34 ThreadList::ThreadList(const ThreadList &rhs)
35     : ThreadCollection(), m_process(rhs.m_process), m_stop_id(rhs.m_stop_id),
36       m_selected_tid() {
37   // Use the assignment operator since it uses the mutex
38   *this = rhs;
39 }
40 
41 const ThreadList &ThreadList::operator=(const ThreadList &rhs) {
42   if (this != &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());
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::GetBackingThread(const ThreadSP &real_thread) {
199   std::lock_guard<std::recursive_mutex> guard(GetMutex());
200 
201   ThreadSP thread_sp;
202   const uint32_t num_threads = m_threads.size();
203   for (uint32_t idx = 0; idx < num_threads; ++idx) {
204     if (m_threads[idx]->GetBackingThread() == real_thread) {
205       thread_sp = m_threads[idx];
206       break;
207     }
208   }
209   return thread_sp;
210 }
211 
212 ThreadSP ThreadList::FindThreadByIndexID(uint32_t index_id, bool can_update) {
213   std::lock_guard<std::recursive_mutex> guard(GetMutex());
214 
215   if (can_update)
216     m_process->UpdateThreadListIfNeeded();
217 
218   ThreadSP thread_sp;
219   const uint32_t num_threads = m_threads.size();
220   for (uint32_t idx = 0; idx < num_threads; ++idx) {
221     if (m_threads[idx]->GetIndexID() == index_id) {
222       thread_sp = m_threads[idx];
223       break;
224     }
225   }
226   return thread_sp;
227 }
228 
229 bool ThreadList::ShouldStop(Event *event_ptr) {
230   // Running events should never stop, obviously...
231 
232   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
233 
234   // The ShouldStop method of the threads can do a whole lot of work,
235   // figuring out whether the thread plan conditions are met.  So we don't want
236   // to keep the ThreadList locked the whole time we are doing this.
237   // FIXME: It is possible that running code could cause new threads
238   // to be created.  If that happens, we will miss asking them whether
239   // they should stop.  This is not a big deal since we haven't had
240   // a chance to hang any interesting operations on those threads yet.
241 
242   collection threads_copy;
243   {
244     // Scope for locker
245     std::lock_guard<std::recursive_mutex> guard(GetMutex());
246 
247     m_process->UpdateThreadListIfNeeded();
248     for (lldb::ThreadSP thread_sp : m_threads) {
249       // This is an optimization...  If we didn't let a thread run in between
250       // the previous stop and this
251       // one, we shouldn't have to consult it for ShouldStop.  So just leave it
252       // off the list we are going to
253       // inspect.
254       // On Linux, if a thread-specific conditional breakpoint was hit, it won't
255       // necessarily be the thread
256       // that hit the breakpoint itself that evaluates the conditional
257       // expression, so the thread that hit
258       // the breakpoint could still be asked to stop, even though it hasn't been
259       // allowed to run since the
260       // previous stop.
261       if (thread_sp->GetTemporaryResumeState() != eStateSuspended ||
262           thread_sp->IsStillAtLastBreakpointHit())
263         threads_copy.push_back(thread_sp);
264     }
265 
266     // It is possible the threads we were allowing to run all exited and then
267     // maybe the user interrupted
268     // or something, then fall back on looking at all threads:
269 
270     if (threads_copy.size() == 0)
271       threads_copy = m_threads;
272   }
273 
274   collection::iterator pos, end = threads_copy.end();
275 
276   if (log) {
277     log->PutCString("");
278     log->Printf("ThreadList::%s: %" PRIu64 " threads, %" PRIu64
279                 " unsuspended threads",
280                 __FUNCTION__, (uint64_t)m_threads.size(),
281                 (uint64_t)threads_copy.size());
282   }
283 
284   bool did_anybody_stop_for_a_reason = false;
285 
286   // If the event is an Interrupt event, then we're going to stop no matter
287   // what.  Otherwise, presume we won't stop.
288   bool should_stop = false;
289   if (Process::ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
290     if (log)
291       log->Printf(
292           "ThreadList::%s handling interrupt event, should stop set to true",
293           __FUNCTION__);
294 
295     should_stop = true;
296   }
297 
298   // Now we run through all the threads and get their stop info's.  We want to
299   // make sure to do this first before
300   // we start running the ShouldStop, because one thread's ShouldStop could
301   // destroy information (like deleting a
302   // thread specific breakpoint another thread had stopped at) which could lead
303   // us to compute the StopInfo incorrectly.
304   // We don't need to use it here, we just want to make sure it gets computed.
305 
306   for (pos = threads_copy.begin(); pos != end; ++pos) {
307     ThreadSP thread_sp(*pos);
308     thread_sp->GetStopInfo();
309   }
310 
311   for (pos = threads_copy.begin(); pos != end; ++pos) {
312     ThreadSP thread_sp(*pos);
313 
314     // We should never get a stop for which no thread had a stop reason, but
315     // sometimes we do see this -
316     // for instance when we first connect to a remote stub.  In that case we
317     // should stop, since we can't figure out
318     // the right thing to do and stopping gives the user control over what to do
319     // in this instance.
320     //
321     // Note, this causes a problem when you have a thread specific breakpoint,
322     // and a bunch of threads hit the breakpoint,
323     // but not the thread which we are waiting for.  All the threads that are
324     // not "supposed" to hit the breakpoint
325     // are marked as having no stop reason, which is right, they should not show
326     // a stop reason.  But that triggers this
327     // code and causes us to stop seemingly for no reason.
328     //
329     // Since the only way we ever saw this error was on first attach, I'm only
330     // going to trigger set did_anybody_stop_for_a_reason
331     // to true unless this is the first stop.
332     //
333     // If this becomes a problem, we'll have to have another StopReason like
334     // "StopInfoHidden" which will look invalid
335     // everywhere but at this check.
336 
337     if (thread_sp->GetProcess()->GetStopID() > 1)
338       did_anybody_stop_for_a_reason = true;
339     else
340       did_anybody_stop_for_a_reason |= thread_sp->ThreadStoppedForAReason();
341 
342     const bool thread_should_stop = thread_sp->ShouldStop(event_ptr);
343     if (thread_should_stop)
344       should_stop |= true;
345   }
346 
347   if (!should_stop && !did_anybody_stop_for_a_reason) {
348     should_stop = true;
349     if (log)
350       log->Printf("ThreadList::%s we stopped but no threads had a stop reason, "
351                   "overriding should_stop and stopping.",
352                   __FUNCTION__);
353   }
354 
355   if (log)
356     log->Printf("ThreadList::%s overall should_stop = %i", __FUNCTION__,
357                 should_stop);
358 
359   if (should_stop) {
360     for (pos = threads_copy.begin(); pos != end; ++pos) {
361       ThreadSP thread_sp(*pos);
362       thread_sp->WillStop();
363     }
364   }
365 
366   return should_stop;
367 }
368 
369 Vote ThreadList::ShouldReportStop(Event *event_ptr) {
370   std::lock_guard<std::recursive_mutex> guard(GetMutex());
371 
372   Vote result = eVoteNoOpinion;
373   m_process->UpdateThreadListIfNeeded();
374   collection::iterator pos, end = m_threads.end();
375 
376   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
377 
378   if (log)
379     log->Printf("ThreadList::%s %" PRIu64 " threads", __FUNCTION__,
380                 (uint64_t)m_threads.size());
381 
382   // Run through the threads and ask whether we should report this event.
383   // For stopping, a YES vote wins over everything.  A NO vote wins over NO
384   // opinion.
385   for (pos = m_threads.begin(); pos != end; ++pos) {
386     ThreadSP thread_sp(*pos);
387     const Vote vote = thread_sp->ShouldReportStop(event_ptr);
388     switch (vote) {
389     case eVoteNoOpinion:
390       continue;
391 
392     case eVoteYes:
393       result = eVoteYes;
394       break;
395 
396     case eVoteNo:
397       if (result == eVoteNoOpinion) {
398         result = eVoteNo;
399       } else {
400         LLDB_LOG(log,
401           "Thread {0:x} voted {1}, but lost out because result was {2}",
402           thread_sp->GetID(), vote, result);
403       }
404       break;
405     }
406   }
407   LLDB_LOG(log, "Returning {0}", result);
408   return result;
409 }
410 
411 void ThreadList::SetShouldReportStop(Vote vote) {
412   std::lock_guard<std::recursive_mutex> guard(GetMutex());
413 
414   m_process->UpdateThreadListIfNeeded();
415   collection::iterator pos, end = m_threads.end();
416   for (pos = m_threads.begin(); pos != end; ++pos) {
417     ThreadSP thread_sp(*pos);
418     thread_sp->SetShouldReportStop(vote);
419   }
420 }
421 
422 Vote ThreadList::ShouldReportRun(Event *event_ptr) {
423 
424   std::lock_guard<std::recursive_mutex> guard(GetMutex());
425 
426   Vote result = eVoteNoOpinion;
427   m_process->UpdateThreadListIfNeeded();
428   collection::iterator pos, end = m_threads.end();
429 
430   // Run through the threads and ask whether we should report this event.
431   // The rule is NO vote wins over everything, a YES vote wins over no opinion.
432 
433   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
434 
435   for (pos = m_threads.begin(); pos != end; ++pos) {
436     if ((*pos)->GetResumeState() != eStateSuspended) {
437       switch ((*pos)->ShouldReportRun(event_ptr)) {
438       case eVoteNoOpinion:
439         continue;
440       case eVoteYes:
441         if (result == eVoteNoOpinion)
442           result = eVoteYes;
443         break;
444       case eVoteNo:
445         if (log)
446           log->Printf("ThreadList::ShouldReportRun() thread %d (0x%4.4" PRIx64
447                       ") says don't report.",
448                       (*pos)->GetIndexID(), (*pos)->GetID());
449         result = eVoteNo;
450         break;
451       }
452     }
453   }
454   return result;
455 }
456 
457 void ThreadList::Clear() {
458   std::lock_guard<std::recursive_mutex> guard(GetMutex());
459   m_stop_id = 0;
460   m_threads.clear();
461   m_selected_tid = LLDB_INVALID_THREAD_ID;
462 }
463 
464 void ThreadList::Destroy() {
465   std::lock_guard<std::recursive_mutex> guard(GetMutex());
466   const uint32_t num_threads = m_threads.size();
467   for (uint32_t idx = 0; idx < num_threads; ++idx) {
468     m_threads[idx]->DestroyThread();
469   }
470 }
471 
472 void ThreadList::RefreshStateAfterStop() {
473   std::lock_guard<std::recursive_mutex> guard(GetMutex());
474 
475   m_process->UpdateThreadListIfNeeded();
476 
477   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
478   if (log && log->GetVerbose())
479     log->Printf("Turning off notification of new threads while single stepping "
480                 "a thread.");
481 
482   collection::iterator pos, end = m_threads.end();
483   for (pos = m_threads.begin(); pos != end; ++pos)
484     (*pos)->RefreshStateAfterStop();
485 }
486 
487 void ThreadList::DiscardThreadPlans() {
488   // You don't need to update the thread list here, because only threads
489   // that you currently know about have any thread plans.
490   std::lock_guard<std::recursive_mutex> guard(GetMutex());
491 
492   collection::iterator pos, end = m_threads.end();
493   for (pos = m_threads.begin(); pos != end; ++pos)
494     (*pos)->DiscardThreadPlans(true);
495 }
496 
497 bool ThreadList::WillResume() {
498   // Run through the threads and perform their momentary actions.
499   // But we only do this for threads that are running, user suspended
500   // threads stay where they are.
501 
502   std::lock_guard<std::recursive_mutex> guard(GetMutex());
503   m_process->UpdateThreadListIfNeeded();
504 
505   collection::iterator pos, end = m_threads.end();
506 
507   // See if any thread wants to run stopping others.  If it does, then we won't
508   // setup the other threads for resume, since they aren't going to get a chance
509   // to run.  This is necessary because the SetupForResume might add
510   // "StopOthers"
511   // plans which would then get to be part of the who-gets-to-run negotiation,
512   // but
513   // they're coming in after the fact, and the threads that are already set up
514   // should
515   // take priority.
516 
517   bool wants_solo_run = false;
518 
519   for (pos = m_threads.begin(); pos != end; ++pos) {
520     lldbassert((*pos)->GetCurrentPlan() &&
521                "thread should not have null thread plan");
522     if ((*pos)->GetResumeState() != eStateSuspended &&
523         (*pos)->GetCurrentPlan()->StopOthers()) {
524       if ((*pos)->IsOperatingSystemPluginThread() &&
525           !(*pos)->GetBackingThread())
526         continue;
527       wants_solo_run = true;
528       break;
529     }
530   }
531 
532   if (wants_solo_run) {
533     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
534     if (log && log->GetVerbose())
535       log->Printf("Turning on notification of new threads while single "
536                   "stepping a thread.");
537     m_process->StartNoticingNewThreads();
538   } else {
539     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
540     if (log && log->GetVerbose())
541       log->Printf("Turning off notification of new threads while single "
542                   "stepping a thread.");
543     m_process->StopNoticingNewThreads();
544   }
545 
546   // Give all the threads that are likely to run a last chance to set up their
547   // state before we
548   // negotiate who is actually going to get a chance to run...
549   // Don't set to resume suspended threads, and if any thread wanted to stop
550   // others, only
551   // call setup on the threads that request StopOthers...
552 
553   for (pos = m_threads.begin(); pos != end; ++pos) {
554     if ((*pos)->GetResumeState() != eStateSuspended &&
555         (!wants_solo_run || (*pos)->GetCurrentPlan()->StopOthers())) {
556       if ((*pos)->IsOperatingSystemPluginThread() &&
557           !(*pos)->GetBackingThread())
558         continue;
559       (*pos)->SetupForResume();
560     }
561   }
562 
563   // Now go through the threads and see if any thread wants to run just itself.
564   // if so then pick one and run it.
565 
566   ThreadList run_me_only_list(m_process);
567 
568   run_me_only_list.SetStopID(m_process->GetStopID());
569 
570   bool run_only_current_thread = false;
571 
572   for (pos = m_threads.begin(); pos != end; ++pos) {
573     ThreadSP thread_sp(*pos);
574     if (thread_sp->GetResumeState() != eStateSuspended &&
575         thread_sp->GetCurrentPlan()->StopOthers()) {
576       if ((*pos)->IsOperatingSystemPluginThread() &&
577           !(*pos)->GetBackingThread())
578         continue;
579 
580       // You can't say "stop others" and also want yourself to be suspended.
581       assert(thread_sp->GetCurrentPlan()->RunState() != eStateSuspended);
582 
583       if (thread_sp == GetSelectedThread()) {
584         // If the currently selected thread wants to run on its own, always let
585         // it.
586         run_only_current_thread = true;
587         run_me_only_list.Clear();
588         run_me_only_list.AddThread(thread_sp);
589         break;
590       }
591 
592       run_me_only_list.AddThread(thread_sp);
593     }
594   }
595 
596   bool need_to_resume = true;
597 
598   if (run_me_only_list.GetSize(false) == 0) {
599     // Everybody runs as they wish:
600     for (pos = m_threads.begin(); pos != end; ++pos) {
601       ThreadSP thread_sp(*pos);
602       StateType run_state;
603       if (thread_sp->GetResumeState() != eStateSuspended)
604         run_state = thread_sp->GetCurrentPlan()->RunState();
605       else
606         run_state = eStateSuspended;
607       if (!thread_sp->ShouldResume(run_state))
608         need_to_resume = false;
609     }
610   } else {
611     ThreadSP thread_to_run;
612 
613     if (run_only_current_thread) {
614       thread_to_run = GetSelectedThread();
615     } else if (run_me_only_list.GetSize(false) == 1) {
616       thread_to_run = run_me_only_list.GetThreadAtIndex(0);
617     } else {
618       int random_thread =
619           (int)((run_me_only_list.GetSize(false) * (double)rand()) /
620                 (RAND_MAX + 1.0));
621       thread_to_run = run_me_only_list.GetThreadAtIndex(random_thread);
622     }
623 
624     for (pos = m_threads.begin(); pos != end; ++pos) {
625       ThreadSP thread_sp(*pos);
626       if (thread_sp == thread_to_run) {
627         if (!thread_sp->ShouldResume(thread_sp->GetCurrentPlan()->RunState()))
628           need_to_resume = false;
629       } else
630         thread_sp->ShouldResume(eStateSuspended);
631     }
632   }
633 
634   return need_to_resume;
635 }
636 
637 void ThreadList::DidResume() {
638   std::lock_guard<std::recursive_mutex> guard(GetMutex());
639   collection::iterator pos, end = m_threads.end();
640   for (pos = m_threads.begin(); pos != end; ++pos) {
641     // Don't clear out threads that aren't going to get a chance to run, rather
642     // leave their state for the next time around.
643     ThreadSP thread_sp(*pos);
644     if (thread_sp->GetResumeState() != eStateSuspended)
645       thread_sp->DidResume();
646   }
647 }
648 
649 void ThreadList::DidStop() {
650   std::lock_guard<std::recursive_mutex> guard(GetMutex());
651   collection::iterator pos, end = m_threads.end();
652   for (pos = m_threads.begin(); pos != end; ++pos) {
653     // Notify threads that the process just stopped.
654     // Note, this currently assumes that all threads in the list
655     // stop when the process stops.  In the future we will want to support
656     // a debugging model where some threads continue to run while others
657     // are stopped.  We either need to handle that somehow here or
658     // create a special thread list containing only threads which will
659     // stop in the code that calls this method (currently
660     // Process::SetPrivateState).
661     ThreadSP thread_sp(*pos);
662     if (StateIsRunningState(thread_sp->GetState()))
663       thread_sp->DidStop();
664   }
665 }
666 
667 ThreadSP ThreadList::GetSelectedThread() {
668   std::lock_guard<std::recursive_mutex> guard(GetMutex());
669   ThreadSP thread_sp = FindThreadByID(m_selected_tid);
670   if (!thread_sp.get()) {
671     if (m_threads.size() == 0)
672       return thread_sp;
673     m_selected_tid = m_threads[0]->GetID();
674     thread_sp = m_threads[0];
675   }
676   return thread_sp;
677 }
678 
679 bool ThreadList::SetSelectedThreadByID(lldb::tid_t tid, bool notify) {
680   std::lock_guard<std::recursive_mutex> guard(GetMutex());
681   ThreadSP selected_thread_sp(FindThreadByID(tid));
682   if (selected_thread_sp) {
683     m_selected_tid = tid;
684     selected_thread_sp->SetDefaultFileAndLineToSelectedFrame();
685   } else
686     m_selected_tid = LLDB_INVALID_THREAD_ID;
687 
688   if (notify)
689     NotifySelectedThreadChanged(m_selected_tid);
690 
691   return m_selected_tid != LLDB_INVALID_THREAD_ID;
692 }
693 
694 bool ThreadList::SetSelectedThreadByIndexID(uint32_t index_id, bool notify) {
695   std::lock_guard<std::recursive_mutex> guard(GetMutex());
696   ThreadSP selected_thread_sp(FindThreadByIndexID(index_id));
697   if (selected_thread_sp.get()) {
698     m_selected_tid = selected_thread_sp->GetID();
699     selected_thread_sp->SetDefaultFileAndLineToSelectedFrame();
700   } else
701     m_selected_tid = LLDB_INVALID_THREAD_ID;
702 
703   if (notify)
704     NotifySelectedThreadChanged(m_selected_tid);
705 
706   return m_selected_tid != LLDB_INVALID_THREAD_ID;
707 }
708 
709 void ThreadList::NotifySelectedThreadChanged(lldb::tid_t tid) {
710   ThreadSP selected_thread_sp(FindThreadByID(tid));
711   if (selected_thread_sp->EventTypeHasListeners(
712           Thread::eBroadcastBitThreadSelected))
713     selected_thread_sp->BroadcastEvent(
714         Thread::eBroadcastBitThreadSelected,
715         new Thread::ThreadEventData(selected_thread_sp));
716 }
717 
718 void ThreadList::Update(ThreadList &rhs) {
719   if (this != &rhs) {
720     // Lock both mutexes to make sure neither side changes anyone on us
721     // while the assignment occurs
722     std::lock_guard<std::recursive_mutex> guard(GetMutex());
723 
724     m_process = rhs.m_process;
725     m_stop_id = rhs.m_stop_id;
726     m_threads.swap(rhs.m_threads);
727     m_selected_tid = rhs.m_selected_tid;
728 
729     // Now we look for threads that we are done with and
730     // make sure to clear them up as much as possible so
731     // anyone with a shared pointer will still have a reference,
732     // but the thread won't be of much use. Using std::weak_ptr
733     // for all backward references (such as a thread to a process)
734     // will eventually solve this issue for us, but for now, we
735     // need to work around the issue
736     collection::iterator rhs_pos, rhs_end = rhs.m_threads.end();
737     for (rhs_pos = rhs.m_threads.begin(); rhs_pos != rhs_end; ++rhs_pos) {
738       const lldb::tid_t tid = (*rhs_pos)->GetID();
739       bool thread_is_alive = false;
740       const uint32_t num_threads = m_threads.size();
741       for (uint32_t idx = 0; idx < num_threads; ++idx) {
742         ThreadSP backing_thread = m_threads[idx]->GetBackingThread();
743         if (m_threads[idx]->GetID() == tid ||
744             (backing_thread && backing_thread->GetID() == tid)) {
745           thread_is_alive = true;
746           break;
747         }
748       }
749       if (!thread_is_alive)
750         (*rhs_pos)->DestroyThread();
751     }
752   }
753 }
754 
755 void ThreadList::Flush() {
756   std::lock_guard<std::recursive_mutex> guard(GetMutex());
757   collection::iterator pos, end = m_threads.end();
758   for (pos = m_threads.begin(); pos != end; ++pos)
759     (*pos)->Flush();
760 }
761 
762 std::recursive_mutex &ThreadList::GetMutex() const {
763   return m_process->m_thread_mutex;
764 }
765 
766 ThreadList::ExpressionExecutionThreadPusher::ExpressionExecutionThreadPusher(
767     lldb::ThreadSP thread_sp)
768     : m_thread_list(nullptr), m_tid(LLDB_INVALID_THREAD_ID) {
769   if (thread_sp) {
770     m_tid = thread_sp->GetID();
771     m_thread_list = &thread_sp->GetProcess()->GetThreadList();
772     m_thread_list->PushExpressionExecutionThread(m_tid);
773   }
774 }
775