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/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"
27 
28 using namespace lldb;
29 using namespace lldb_private;
30 
31 ThreadList::ThreadList (Process *process) :
32     ThreadCollection(),
33     m_process (process),
34     m_stop_id (0),
35     m_selected_tid (LLDB_INVALID_THREAD_ID)
36 {
37 }
38 
39 ThreadList::ThreadList (const ThreadList &rhs) :
40     ThreadCollection(),
41     m_process (rhs.m_process),
42     m_stop_id (rhs.m_stop_id),
43     m_selected_tid ()
44 {
45     // Use the assignment operator since it uses the mutex
46     *this = rhs;
47 }
48 
49 const ThreadList&
50 ThreadList::operator = (const ThreadList& rhs)
51 {
52     if (this != &rhs)
53     {
54         // Lock both mutexes to make sure neither side changes anyone on us
55         // while the assignment occurs
56         Mutex::Locker locker(GetMutex());
57         m_process = rhs.m_process;
58         m_stop_id = rhs.m_stop_id;
59         m_threads = rhs.m_threads;
60         m_selected_tid = rhs.m_selected_tid;
61     }
62     return *this;
63 }
64 
65 
66 ThreadList::~ThreadList()
67 {
68     // Clear the thread list. Clear will take the mutex lock
69     // which will ensure that if anyone is using the list
70     // they won't get it removed while using it.
71     Clear();
72 }
73 
74 lldb::ThreadSP
75 ThreadList::GetExpressionExecutionThread()
76 {
77     if (m_expression_tid_stack.empty())
78         return GetSelectedThread();
79     ThreadSP expr_thread_sp = FindThreadByID(m_expression_tid_stack.back());
80     if (expr_thread_sp)
81         return expr_thread_sp;
82     else
83         return GetSelectedThread();
84 }
85 
86 void
87 ThreadList::PushExpressionExecutionThread(lldb::tid_t tid)
88 {
89     m_expression_tid_stack.push_back(tid);
90 }
91 
92 void
93 ThreadList::PopExpressionExecutionThread(lldb::tid_t tid)
94 {
95     assert(m_expression_tid_stack.back() == tid);
96     m_expression_tid_stack.pop_back();
97 }
98 
99 uint32_t
100 ThreadList::GetStopID () const
101 {
102     return m_stop_id;
103 }
104 
105 void
106 ThreadList::SetStopID (uint32_t stop_id)
107 {
108     m_stop_id = stop_id;
109 }
110 
111 uint32_t
112 ThreadList::GetSize (bool can_update)
113 {
114     Mutex::Locker locker(GetMutex());
115     if (can_update)
116         m_process->UpdateThreadListIfNeeded();
117     return m_threads.size();
118 }
119 
120 ThreadSP
121 ThreadList::GetThreadAtIndex (uint32_t idx, bool can_update)
122 {
123     Mutex::Locker locker(GetMutex());
124     if (can_update)
125         m_process->UpdateThreadListIfNeeded();
126 
127     ThreadSP thread_sp;
128     if (idx < m_threads.size())
129         thread_sp = m_threads[idx];
130     return thread_sp;
131 }
132 
133 ThreadSP
134 ThreadList::FindThreadByID (lldb::tid_t tid, bool can_update)
135 {
136     Mutex::Locker locker(GetMutex());
137 
138     if (can_update)
139         m_process->UpdateThreadListIfNeeded();
140 
141     ThreadSP thread_sp;
142     uint32_t idx = 0;
143     const uint32_t num_threads = m_threads.size();
144     for (idx = 0; idx < num_threads; ++idx)
145     {
146         if (m_threads[idx]->GetID() == tid)
147         {
148             thread_sp = m_threads[idx];
149             break;
150         }
151     }
152     return thread_sp;
153 }
154 
155 ThreadSP
156 ThreadList::FindThreadByProtocolID (lldb::tid_t tid, bool can_update)
157 {
158     Mutex::Locker locker(GetMutex());
159 
160     if (can_update)
161         m_process->UpdateThreadListIfNeeded();
162 
163     ThreadSP thread_sp;
164     uint32_t idx = 0;
165     const uint32_t num_threads = m_threads.size();
166     for (idx = 0; idx < num_threads; ++idx)
167     {
168         if (m_threads[idx]->GetProtocolID() == tid)
169         {
170             thread_sp = m_threads[idx];
171             break;
172         }
173     }
174     return thread_sp;
175 }
176 
177 
178 ThreadSP
179 ThreadList::RemoveThreadByID (lldb::tid_t tid, bool can_update)
180 {
181     Mutex::Locker locker(GetMutex());
182 
183     if (can_update)
184         m_process->UpdateThreadListIfNeeded();
185 
186     ThreadSP thread_sp;
187     uint32_t idx = 0;
188     const uint32_t num_threads = m_threads.size();
189     for (idx = 0; idx < num_threads; ++idx)
190     {
191         if (m_threads[idx]->GetID() == tid)
192         {
193             thread_sp = m_threads[idx];
194             m_threads.erase(m_threads.begin()+idx);
195             break;
196         }
197     }
198     return thread_sp;
199 }
200 
201 ThreadSP
202 ThreadList::RemoveThreadByProtocolID (lldb::tid_t tid, bool can_update)
203 {
204     Mutex::Locker locker(GetMutex());
205 
206     if (can_update)
207         m_process->UpdateThreadListIfNeeded();
208 
209     ThreadSP thread_sp;
210     uint32_t idx = 0;
211     const uint32_t num_threads = m_threads.size();
212     for (idx = 0; idx < num_threads; ++idx)
213     {
214         if (m_threads[idx]->GetProtocolID() == tid)
215         {
216             thread_sp = m_threads[idx];
217             m_threads.erase(m_threads.begin()+idx);
218             break;
219         }
220     }
221     return thread_sp;
222 }
223 
224 ThreadSP
225 ThreadList::GetThreadSPForThreadPtr (Thread *thread_ptr)
226 {
227     ThreadSP thread_sp;
228     if (thread_ptr)
229     {
230         Mutex::Locker locker(GetMutex());
231 
232         uint32_t idx = 0;
233         const uint32_t num_threads = m_threads.size();
234         for (idx = 0; idx < num_threads; ++idx)
235         {
236             if (m_threads[idx].get() == thread_ptr)
237             {
238                 thread_sp = m_threads[idx];
239                 break;
240             }
241         }
242     }
243     return thread_sp;
244 }
245 
246 
247 
248 ThreadSP
249 ThreadList::FindThreadByIndexID (uint32_t index_id, bool can_update)
250 {
251     Mutex::Locker locker(GetMutex());
252 
253     if (can_update)
254         m_process->UpdateThreadListIfNeeded();
255 
256     ThreadSP thread_sp;
257     const uint32_t num_threads = m_threads.size();
258     for (uint32_t idx = 0; idx < num_threads; ++idx)
259     {
260         if (m_threads[idx]->GetIndexID() == index_id)
261         {
262             thread_sp = m_threads[idx];
263             break;
264         }
265     }
266     return thread_sp;
267 }
268 
269 bool
270 ThreadList::ShouldStop (Event *event_ptr)
271 {
272     // Running events should never stop, obviously...
273 
274     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
275 
276     // The ShouldStop method of the threads can do a whole lot of work,
277     // figuring out whether the thread plan conditions are met.  So we don't want
278     // to keep the ThreadList locked the whole time we are doing this.
279     // FIXME: It is possible that running code could cause new threads
280     // to be created.  If that happens, we will miss asking them whether
281     // they should stop.  This is not a big deal since we haven't had
282     // a chance to hang any interesting operations on those threads yet.
283 
284     collection threads_copy;
285     {
286         // Scope for locker
287         Mutex::Locker locker(GetMutex());
288 
289         m_process->UpdateThreadListIfNeeded();
290         for (lldb::ThreadSP thread_sp : m_threads)
291         {
292             // This is an optimization...  If we didn't let a thread run in between the previous stop and this
293             // one, we shouldn't have to consult it for ShouldStop.  So just leave it off the list we are going to
294             // inspect.
295             // On Linux, if a thread-specific conditional breakpoint was hit, it won't necessarily be the thread
296             // that hit the breakpoint itself that evaluates the conditional expression, so the thread that hit
297             // the breakpoint could still be asked to stop, even though it hasn't been allowed to run since the
298             // previous stop.
299             if (thread_sp->GetTemporaryResumeState () != eStateSuspended || thread_sp->IsStillAtLastBreakpointHit())
300                 threads_copy.push_back(thread_sp);
301         }
302 
303         // It is possible the threads we were allowing to run all exited and then maybe the user interrupted
304         // or something, then fall back on looking at all threads:
305 
306         if (threads_copy.size() == 0)
307             threads_copy = m_threads;
308     }
309 
310     collection::iterator pos, end = threads_copy.end();
311 
312     if (log)
313     {
314         log->PutCString("");
315         log->Printf ("ThreadList::%s: %" PRIu64 " threads, %" PRIu64 " unsuspended threads",
316                      __FUNCTION__,
317                      (uint64_t)m_threads.size(),
318                      (uint64_t)threads_copy.size());
319     }
320 
321     bool did_anybody_stop_for_a_reason = false;
322 
323     // If the event is an Interrupt event, then we're going to stop no matter what.  Otherwise, presume we won't stop.
324     bool should_stop = false;
325     if (Process::ProcessEventData::GetInterruptedFromEvent(event_ptr))
326     {
327         if (log)
328             log->Printf("ThreadList::%s handling interrupt event, should stop set to true", __FUNCTION__);
329 
330         should_stop = true;
331     }
332 
333     // Now we run through all the threads and get their stop info's.  We want to make sure to do this first before
334     // we start running the ShouldStop, because one thread's ShouldStop could destroy information (like deleting a
335     // thread specific breakpoint another thread had stopped at) which could lead us to compute the StopInfo incorrectly.
336     // We don't need to use it here, we just want to make sure it gets computed.
337 
338     for (pos = threads_copy.begin(); pos != end; ++pos)
339     {
340         ThreadSP thread_sp(*pos);
341         thread_sp->GetStopInfo();
342     }
343 
344     for (pos = threads_copy.begin(); pos != end; ++pos)
345     {
346         ThreadSP thread_sp(*pos);
347 
348         // We should never get a stop for which no thread had a stop reason, but sometimes we do see this -
349         // for instance when we first connect to a remote stub.  In that case we should stop, since we can't figure out
350         // the right thing to do and stopping gives the user control over what to do in this instance.
351         //
352         // Note, this causes a problem when you have a thread specific breakpoint, and a bunch of threads hit the breakpoint,
353         // but not the thread which we are waiting for.  All the threads that are not "supposed" to hit the breakpoint
354         // are marked as having no stop reason, which is right, they should not show a stop reason.  But that triggers this
355         // code and causes us to stop seemingly for no reason.
356         //
357         // 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
358         // to true unless this is the first stop.
359         //
360         // If this becomes a problem, we'll have to have another StopReason like "StopInfoHidden" which will look invalid
361         // everywhere but at this check.
362 
363         if (thread_sp->GetProcess()->GetStopID() > 1)
364             did_anybody_stop_for_a_reason = true;
365         else
366             did_anybody_stop_for_a_reason |= thread_sp->ThreadStoppedForAReason();
367 
368         const bool thread_should_stop = thread_sp->ShouldStop(event_ptr);
369         if (thread_should_stop)
370             should_stop |= true;
371     }
372 
373     if (!should_stop && !did_anybody_stop_for_a_reason)
374     {
375         should_stop = true;
376         if (log)
377             log->Printf ("ThreadList::%s we stopped but no threads had a stop reason, overriding should_stop and stopping.", __FUNCTION__);
378     }
379 
380     if (log)
381         log->Printf ("ThreadList::%s overall should_stop = %i", __FUNCTION__, should_stop);
382 
383     if (should_stop)
384     {
385         for (pos = threads_copy.begin(); pos != end; ++pos)
386         {
387             ThreadSP thread_sp(*pos);
388             thread_sp->WillStop ();
389         }
390     }
391 
392     return should_stop;
393 }
394 
395 Vote
396 ThreadList::ShouldReportStop (Event *event_ptr)
397 {
398     Mutex::Locker locker(GetMutex());
399 
400     Vote result = eVoteNoOpinion;
401     m_process->UpdateThreadListIfNeeded();
402     collection::iterator pos, end = m_threads.end();
403 
404     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
405 
406     if (log)
407         log->Printf ("ThreadList::%s %" PRIu64 " threads", __FUNCTION__, (uint64_t)m_threads.size());
408 
409     // Run through the threads and ask whether we should report this event.
410     // For stopping, a YES vote wins over everything.  A NO vote wins over NO opinion.
411     for (pos = m_threads.begin(); pos != end; ++pos)
412     {
413         ThreadSP thread_sp(*pos);
414         const Vote vote = thread_sp->ShouldReportStop (event_ptr);
415         switch (vote)
416         {
417         case eVoteNoOpinion:
418             continue;
419 
420         case eVoteYes:
421             result = eVoteYes;
422             break;
423 
424         case eVoteNo:
425             if (result == eVoteNoOpinion)
426             {
427                 result = eVoteNo;
428             }
429             else
430             {
431                 if (log)
432                     log->Printf ("ThreadList::%s thread 0x%4.4" PRIx64 ": voted %s, but lost out because result was %s",
433                                  __FUNCTION__,
434                                  thread_sp->GetID (),
435                                  GetVoteAsCString (vote),
436                                  GetVoteAsCString (result));
437             }
438             break;
439         }
440     }
441     if (log)
442         log->Printf ("ThreadList::%s returning %s", __FUNCTION__, GetVoteAsCString (result));
443     return result;
444 }
445 
446 void
447 ThreadList::SetShouldReportStop (Vote vote)
448 {
449     Mutex::Locker locker(GetMutex());
450     m_process->UpdateThreadListIfNeeded();
451     collection::iterator pos, end = m_threads.end();
452     for (pos = m_threads.begin(); pos != end; ++pos)
453     {
454         ThreadSP thread_sp(*pos);
455         thread_sp->SetShouldReportStop (vote);
456     }
457 }
458 
459 Vote
460 ThreadList::ShouldReportRun (Event *event_ptr)
461 {
462 
463     Mutex::Locker locker(GetMutex());
464 
465     Vote result = eVoteNoOpinion;
466     m_process->UpdateThreadListIfNeeded();
467     collection::iterator pos, end = m_threads.end();
468 
469     // Run through the threads and ask whether we should report this event.
470     // The rule is NO vote wins over everything, a YES vote wins over no opinion.
471 
472     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
473 
474     for (pos = m_threads.begin(); pos != end; ++pos)
475     {
476         if ((*pos)->GetResumeState () != eStateSuspended)
477         {
478             switch ((*pos)->ShouldReportRun (event_ptr))
479             {
480                 case eVoteNoOpinion:
481                     continue;
482                 case eVoteYes:
483                     if (result == eVoteNoOpinion)
484                         result = eVoteYes;
485                     break;
486                 case eVoteNo:
487                     if (log)
488                         log->Printf ("ThreadList::ShouldReportRun() thread %d (0x%4.4" PRIx64 ") says don't report.",
489                                      (*pos)->GetIndexID(),
490                                      (*pos)->GetID());
491                     result = eVoteNo;
492                     break;
493             }
494         }
495     }
496     return result;
497 }
498 
499 void
500 ThreadList::Clear()
501 {
502     Mutex::Locker locker(GetMutex());
503     m_stop_id = 0;
504     m_threads.clear();
505     m_selected_tid = LLDB_INVALID_THREAD_ID;
506 }
507 
508 void
509 ThreadList::Destroy()
510 {
511     Mutex::Locker locker(GetMutex());
512     const uint32_t num_threads = m_threads.size();
513     for (uint32_t idx = 0; idx < num_threads; ++idx)
514     {
515         m_threads[idx]->DestroyThread();
516     }
517 }
518 
519 void
520 ThreadList::RefreshStateAfterStop ()
521 {
522     Mutex::Locker locker(GetMutex());
523 
524     m_process->UpdateThreadListIfNeeded();
525 
526     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
527     if (log && log->GetVerbose())
528         log->Printf ("Turning off notification of new threads while single stepping a thread.");
529 
530     collection::iterator pos, end = m_threads.end();
531     for (pos = m_threads.begin(); pos != end; ++pos)
532         (*pos)->RefreshStateAfterStop ();
533 }
534 
535 void
536 ThreadList::DiscardThreadPlans ()
537 {
538     // You don't need to update the thread list here, because only threads
539     // that you currently know about have any thread plans.
540     Mutex::Locker locker(GetMutex());
541 
542     collection::iterator pos, end = m_threads.end();
543     for (pos = m_threads.begin(); pos != end; ++pos)
544         (*pos)->DiscardThreadPlans (true);
545 
546 }
547 
548 bool
549 ThreadList::WillResume ()
550 {
551     // Run through the threads and perform their momentary actions.
552     // But we only do this for threads that are running, user suspended
553     // threads stay where they are.
554 
555     Mutex::Locker locker(GetMutex());
556     m_process->UpdateThreadListIfNeeded();
557 
558     collection::iterator pos, end = m_threads.end();
559 
560     // See if any thread wants to run stopping others.  If it does, then we won't
561     // setup the other threads for resume, since they aren't going to get a chance
562     // to run.  This is necessary because the SetupForResume might add "StopOthers"
563     // plans which would then get to be part of the who-gets-to-run negotiation, but
564     // they're coming in after the fact, and the threads that are already set up should
565     // take priority.
566 
567     bool wants_solo_run = false;
568 
569     for (pos = m_threads.begin(); pos != end; ++pos)
570     {
571         lldbassert((*pos)->GetCurrentPlan() && "thread should not have null thread plan");
572         if ((*pos)->GetResumeState() != eStateSuspended &&
573                  (*pos)->GetCurrentPlan()->StopOthers())
574         {
575             if ((*pos)->IsOperatingSystemPluginThread() && !(*pos)->GetBackingThread())
576                 continue;
577             wants_solo_run = true;
578             break;
579         }
580     }
581 
582     if (wants_solo_run)
583     {
584         Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
585         if (log && log->GetVerbose())
586             log->Printf ("Turning on notification of new threads while single stepping a thread.");
587         m_process->StartNoticingNewThreads();
588     }
589     else
590     {
591         Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
592         if (log && log->GetVerbose())
593             log->Printf ("Turning off notification of new threads while single stepping a thread.");
594         m_process->StopNoticingNewThreads();
595     }
596 
597     // Give all the threads that are likely to run a last chance to set up their state before we
598     // negotiate who is actually going to get a chance to run...
599     // Don't set to resume suspended threads, and if any thread wanted to stop others, only
600     // call setup on the threads that request StopOthers...
601 
602     for (pos = m_threads.begin(); pos != end; ++pos)
603     {
604         if ((*pos)->GetResumeState() != eStateSuspended
605             && (!wants_solo_run || (*pos)->GetCurrentPlan()->StopOthers()))
606         {
607             if ((*pos)->IsOperatingSystemPluginThread() && !(*pos)->GetBackingThread())
608                 continue;
609             (*pos)->SetupForResume ();
610         }
611     }
612 
613     // Now go through the threads and see if any thread wants to run just itself.
614     // if so then pick one and run it.
615 
616     ThreadList run_me_only_list (m_process);
617 
618     run_me_only_list.SetStopID(m_process->GetStopID());
619 
620     bool run_only_current_thread = false;
621 
622     for (pos = m_threads.begin(); pos != end; ++pos)
623     {
624         ThreadSP thread_sp(*pos);
625         if (thread_sp->GetResumeState() != eStateSuspended &&
626                  thread_sp->GetCurrentPlan()->StopOthers())
627         {
628             if ((*pos)->IsOperatingSystemPluginThread() && !(*pos)->GetBackingThread())
629                 continue;
630 
631             // You can't say "stop others" and also want yourself to be suspended.
632             assert (thread_sp->GetCurrentPlan()->RunState() != eStateSuspended);
633 
634             if (thread_sp == GetSelectedThread())
635             {
636                 // If the currently selected thread wants to run on its own, always let it.
637                 run_only_current_thread = true;
638                 run_me_only_list.Clear();
639                 run_me_only_list.AddThread (thread_sp);
640                 break;
641             }
642 
643             run_me_only_list.AddThread (thread_sp);
644         }
645 
646     }
647 
648     bool need_to_resume = true;
649 
650     if (run_me_only_list.GetSize (false) == 0)
651     {
652         // Everybody runs as they wish:
653         for (pos = m_threads.begin(); pos != end; ++pos)
654         {
655             ThreadSP thread_sp(*pos);
656             StateType run_state;
657             if (thread_sp->GetResumeState() != eStateSuspended)
658                 run_state = thread_sp->GetCurrentPlan()->RunState();
659             else
660                 run_state = eStateSuspended;
661             if (!thread_sp->ShouldResume(run_state))
662                 need_to_resume = false;
663         }
664     }
665     else
666     {
667         ThreadSP thread_to_run;
668 
669         if (run_only_current_thread)
670         {
671             thread_to_run = GetSelectedThread();
672         }
673         else if (run_me_only_list.GetSize (false) == 1)
674         {
675             thread_to_run = run_me_only_list.GetThreadAtIndex (0);
676         }
677         else
678         {
679             int random_thread = (int)
680                     ((run_me_only_list.GetSize (false) * (double) rand ()) / (RAND_MAX + 1.0));
681             thread_to_run = run_me_only_list.GetThreadAtIndex (random_thread);
682         }
683 
684         for (pos = m_threads.begin(); pos != end; ++pos)
685         {
686             ThreadSP thread_sp(*pos);
687             if (thread_sp == thread_to_run)
688             {
689                 if (!thread_sp->ShouldResume(thread_sp->GetCurrentPlan()->RunState()))
690                     need_to_resume = false;
691             }
692             else
693                 thread_sp->ShouldResume (eStateSuspended);
694         }
695     }
696 
697     return need_to_resume;
698 }
699 
700 void
701 ThreadList::DidResume ()
702 {
703     Mutex::Locker locker(GetMutex());
704     collection::iterator pos, end = m_threads.end();
705     for (pos = m_threads.begin(); pos != end; ++pos)
706     {
707         // Don't clear out threads that aren't going to get a chance to run, rather
708         // leave their state for the next time around.
709         ThreadSP thread_sp(*pos);
710         if (thread_sp->GetResumeState() != eStateSuspended)
711             thread_sp->DidResume ();
712     }
713 }
714 
715 void
716 ThreadList::DidStop ()
717 {
718     Mutex::Locker locker(GetMutex());
719     collection::iterator pos, end = m_threads.end();
720     for (pos = m_threads.begin(); pos != end; ++pos)
721     {
722         // Notify threads that the process just stopped.
723         // Note, this currently assumes that all threads in the list
724         // stop when the process stops.  In the future we will want to support
725         // a debugging model where some threads continue to run while others
726         // are stopped.  We either need to handle that somehow here or
727         // create a special thread list containing only threads which will
728         // stop in the code that calls this method (currently
729         // Process::SetPrivateState).
730         ThreadSP thread_sp(*pos);
731         if (StateIsRunningState(thread_sp->GetState()))
732             thread_sp->DidStop ();
733     }
734 }
735 
736 ThreadSP
737 ThreadList::GetSelectedThread ()
738 {
739     Mutex::Locker locker(GetMutex());
740     ThreadSP thread_sp = FindThreadByID(m_selected_tid);
741     if (!thread_sp.get())
742     {
743         if (m_threads.size() == 0)
744             return thread_sp;
745         m_selected_tid = m_threads[0]->GetID();
746         thread_sp = m_threads[0];
747     }
748     return thread_sp;
749 }
750 
751 bool
752 ThreadList::SetSelectedThreadByID (lldb::tid_t tid, bool notify)
753 {
754     Mutex::Locker locker(GetMutex());
755     ThreadSP selected_thread_sp(FindThreadByID(tid));
756     if  (selected_thread_sp)
757     {
758         m_selected_tid = tid;
759         selected_thread_sp->SetDefaultFileAndLineToSelectedFrame();
760     }
761     else
762         m_selected_tid = LLDB_INVALID_THREAD_ID;
763 
764     if (notify)
765         NotifySelectedThreadChanged(m_selected_tid);
766 
767     return m_selected_tid != LLDB_INVALID_THREAD_ID;
768 }
769 
770 bool
771 ThreadList::SetSelectedThreadByIndexID (uint32_t index_id, bool notify)
772 {
773     Mutex::Locker locker(GetMutex());
774     ThreadSP selected_thread_sp (FindThreadByIndexID(index_id));
775     if  (selected_thread_sp.get())
776     {
777         m_selected_tid = selected_thread_sp->GetID();
778         selected_thread_sp->SetDefaultFileAndLineToSelectedFrame();
779     }
780     else
781         m_selected_tid = LLDB_INVALID_THREAD_ID;
782 
783     if (notify)
784         NotifySelectedThreadChanged(m_selected_tid);
785 
786     return m_selected_tid != LLDB_INVALID_THREAD_ID;
787 }
788 
789 void
790 ThreadList::NotifySelectedThreadChanged (lldb::tid_t tid)
791 {
792     ThreadSP selected_thread_sp (FindThreadByID(tid));
793     if (selected_thread_sp->EventTypeHasListeners(Thread::eBroadcastBitThreadSelected))
794         selected_thread_sp->BroadcastEvent(Thread::eBroadcastBitThreadSelected,
795                                            new Thread::ThreadEventData(selected_thread_sp));
796 }
797 
798 void
799 ThreadList::Update (ThreadList &rhs)
800 {
801     if (this != &rhs)
802     {
803         // Lock both mutexes to make sure neither side changes anyone on us
804         // while the assignment occurs
805         Mutex::Locker locker(GetMutex());
806         m_process = rhs.m_process;
807         m_stop_id = rhs.m_stop_id;
808         m_threads.swap(rhs.m_threads);
809         m_selected_tid = rhs.m_selected_tid;
810 
811 
812         // Now we look for threads that we are done with and
813         // make sure to clear them up as much as possible so
814         // anyone with a shared pointer will still have a reference,
815         // but the thread won't be of much use. Using std::weak_ptr
816         // for all backward references (such as a thread to a process)
817         // will eventually solve this issue for us, but for now, we
818         // need to work around the issue
819         collection::iterator rhs_pos, rhs_end = rhs.m_threads.end();
820         for (rhs_pos = rhs.m_threads.begin(); rhs_pos != rhs_end; ++rhs_pos)
821         {
822             const lldb::tid_t tid = (*rhs_pos)->GetID();
823             bool thread_is_alive = false;
824             const uint32_t num_threads = m_threads.size();
825             for (uint32_t idx = 0; idx < num_threads; ++idx)
826             {
827                 ThreadSP backing_thread = m_threads[idx]->GetBackingThread();
828                 if (m_threads[idx]->GetID() == tid || (backing_thread && backing_thread->GetID() == tid))
829                 {
830                     thread_is_alive = true;
831                     break;
832                 }
833             }
834             if (!thread_is_alive)
835                 (*rhs_pos)->DestroyThread();
836         }
837     }
838 }
839 
840 void
841 ThreadList::Flush ()
842 {
843     Mutex::Locker locker(GetMutex());
844     collection::iterator pos, end = m_threads.end();
845     for (pos = m_threads.begin(); pos != end; ++pos)
846         (*pos)->Flush ();
847 }
848 
849 Mutex &
850 ThreadList::GetMutex ()
851 {
852     return m_process->m_thread_mutex;
853 }
854 
855 ThreadList::ExpressionExecutionThreadPusher::ExpressionExecutionThreadPusher (lldb::ThreadSP thread_sp) :
856     m_thread_list(nullptr),
857     m_tid(LLDB_INVALID_THREAD_ID)
858 {
859     if (thread_sp)
860     {
861         m_tid = thread_sp->GetID();
862         m_thread_list = &thread_sp->GetProcess()->GetThreadList();
863         m_thread_list->PushExpressionExecutionThread(m_tid);
864     }
865 }
866 
867 
868