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