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 #include <stdlib.h>
10 
11 #include <algorithm>
12 
13 #include "lldb/Core/Log.h"
14 #include "lldb/Target/RegisterContext.h"
15 #include "lldb/Target/ThreadList.h"
16 #include "lldb/Target/Thread.h"
17 #include "lldb/Target/ThreadPlan.h"
18 #include "lldb/Target/Process.h"
19 
20 using namespace lldb;
21 using namespace lldb_private;
22 
23 ThreadList::ThreadList (Process *process) :
24     m_process (process),
25     m_stop_id (0),
26     m_threads(),
27     m_threads_mutex (Mutex::eMutexTypeRecursive),
28     m_selected_tid (LLDB_INVALID_THREAD_ID)
29 {
30 }
31 
32 ThreadList::ThreadList (const ThreadList &rhs) :
33     m_process (),
34     m_stop_id (),
35     m_threads (),
36     m_threads_mutex (Mutex::eMutexTypeRecursive),
37     m_selected_tid ()
38 {
39     // Use the assignment operator since it uses the mutex
40     *this = rhs;
41 }
42 
43 const ThreadList&
44 ThreadList::operator = (const ThreadList& rhs)
45 {
46     if (this != &rhs)
47     {
48         // Lock both mutexes to make sure neither side changes anyone on us
49         // while the assignement occurs
50         Mutex::Locker locker_lhs(m_threads_mutex);
51         Mutex::Locker locker_rhs(rhs.m_threads_mutex);
52         m_process = rhs.m_process;
53         m_stop_id = rhs.m_stop_id;
54         m_threads = rhs.m_threads;
55         m_selected_tid = rhs.m_selected_tid;
56     }
57     return *this;
58 }
59 
60 
61 ThreadList::~ThreadList()
62 {
63 }
64 
65 
66 uint32_t
67 ThreadList::GetStopID () const
68 {
69     return m_stop_id;
70 }
71 
72 void
73 ThreadList::SetStopID (uint32_t stop_id)
74 {
75     m_stop_id = stop_id;
76 }
77 
78 
79 void
80 ThreadList::AddThread (const ThreadSP &thread_sp)
81 {
82     Mutex::Locker locker(m_threads_mutex);
83     m_threads.push_back(thread_sp);
84 }
85 
86 uint32_t
87 ThreadList::GetSize (bool can_update)
88 {
89     Mutex::Locker locker(m_threads_mutex);
90     if (can_update)
91         m_process->UpdateThreadListIfNeeded();
92     return m_threads.size();
93 }
94 
95 ThreadSP
96 ThreadList::GetThreadAtIndex (uint32_t idx, bool can_update)
97 {
98     Mutex::Locker locker(m_threads_mutex);
99     if (can_update)
100         m_process->UpdateThreadListIfNeeded();
101 
102     ThreadSP thread_sp;
103     if (idx < m_threads.size())
104         thread_sp = m_threads[idx];
105     return thread_sp;
106 }
107 
108 ThreadSP
109 ThreadList::FindThreadByID (lldb::tid_t tid, bool can_update)
110 {
111     Mutex::Locker locker(m_threads_mutex);
112 
113     if (can_update)
114         m_process->UpdateThreadListIfNeeded();
115 
116     ThreadSP thread_sp;
117     uint32_t idx = 0;
118     const uint32_t num_threads = m_threads.size();
119     for (idx = 0; idx < num_threads; ++idx)
120     {
121         if (m_threads[idx]->GetID() == tid)
122         {
123             thread_sp = m_threads[idx];
124             break;
125         }
126     }
127     return thread_sp;
128 }
129 
130 ThreadSP
131 ThreadList::RemoveThreadByID (lldb::tid_t tid, bool can_update)
132 {
133     Mutex::Locker locker(m_threads_mutex);
134 
135     if (can_update)
136         m_process->UpdateThreadListIfNeeded();
137 
138     ThreadSP thread_sp;
139     uint32_t idx = 0;
140     const uint32_t num_threads = m_threads.size();
141     for (idx = 0; idx < num_threads; ++idx)
142     {
143         if (m_threads[idx]->GetID() == tid)
144         {
145             thread_sp = m_threads[idx];
146             m_threads.erase(m_threads.begin()+idx);
147             break;
148         }
149     }
150     return thread_sp;
151 }
152 
153 ThreadSP
154 ThreadList::GetThreadSPForThreadPtr (Thread *thread_ptr)
155 {
156     ThreadSP thread_sp;
157     if (thread_ptr)
158     {
159         Mutex::Locker locker(m_threads_mutex);
160 
161         uint32_t idx = 0;
162         const uint32_t num_threads = m_threads.size();
163         for (idx = 0; idx < num_threads; ++idx)
164         {
165             if (m_threads[idx].get() == thread_ptr)
166             {
167                 thread_sp = m_threads[idx];
168                 break;
169             }
170         }
171     }
172     return thread_sp;
173 }
174 
175 
176 
177 ThreadSP
178 ThreadList::FindThreadByIndexID (uint32_t index_id, bool can_update)
179 {
180     Mutex::Locker locker(m_threads_mutex);
181 
182     if (can_update)
183         m_process->UpdateThreadListIfNeeded();
184 
185     ThreadSP thread_sp;
186     const uint32_t num_threads = m_threads.size();
187     for (uint32_t idx = 0; idx < num_threads; ++idx)
188     {
189         if (m_threads[idx]->GetIndexID() == index_id)
190         {
191             thread_sp = m_threads[idx];
192             break;
193         }
194     }
195     return thread_sp;
196 }
197 
198 bool
199 ThreadList::ShouldStop (Event *event_ptr)
200 {
201     // Running events should never stop, obviously...
202 
203     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
204 
205     // The ShouldStop method of the threads can do a whole lot of work,
206     // running breakpoint commands & conditions, etc.  So we don't want
207     // to keep the ThreadList locked the whole time we are doing this.
208     // FIXME: It is possible that running code could cause new threads
209     // to be created.  If that happens we will miss asking them whether
210     // then should stop.  This is not a big deal, since we haven't had
211     // a chance to hang any interesting operations on those threads yet.
212 
213     collection threads_copy;
214     {
215         // Scope for locker
216         Mutex::Locker locker(m_threads_mutex);
217 
218         m_process->UpdateThreadListIfNeeded();
219         threads_copy = m_threads;
220     }
221 
222     collection::iterator pos, end = threads_copy.end();
223 
224     if (log)
225     {
226         log->PutCString("");
227         log->Printf ("ThreadList::%s: %" PRIu64 " threads", __FUNCTION__, (uint64_t)m_threads.size());
228     }
229 
230     bool did_anybody_stop_for_a_reason = false;
231     bool should_stop = false;
232 
233     for (pos = threads_copy.begin(); pos != end; ++pos)
234     {
235         ThreadSP thread_sp(*pos);
236 
237         did_anybody_stop_for_a_reason |= thread_sp->ThreadStoppedForAReason();
238 
239         const bool thread_should_stop = thread_sp->ShouldStop(event_ptr);
240         if (thread_should_stop)
241             should_stop |= true;
242     }
243 
244     // We should never get a stop for which no thread had a stop reason, but sometimes we do see this -
245     // for instance when we first connect to a remote stub.  In that case we should stop, since we can't figure out
246     // the right thing to do and stopping gives the user control over what to do in this instance.
247 
248     if (!should_stop && !did_anybody_stop_for_a_reason)
249     {
250         should_stop = true;
251         if (log)
252             log->Printf ("ThreadList::%s we stopped but no threads had a stop reason, overriding should_stop and stopping.", __FUNCTION__);
253     }
254 
255     if (log)
256         log->Printf ("ThreadList::%s overall should_stop = %i", __FUNCTION__, should_stop);
257 
258     if (should_stop)
259     {
260         for (pos = threads_copy.begin(); pos != end; ++pos)
261         {
262             ThreadSP thread_sp(*pos);
263             thread_sp->WillStop ();
264         }
265     }
266 
267     return should_stop;
268 }
269 
270 Vote
271 ThreadList::ShouldReportStop (Event *event_ptr)
272 {
273     Mutex::Locker locker(m_threads_mutex);
274 
275     Vote result = eVoteNoOpinion;
276     m_process->UpdateThreadListIfNeeded();
277     collection::iterator pos, end = m_threads.end();
278 
279     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
280 
281     if (log)
282         log->Printf ("ThreadList::%s %" PRIu64 " threads", __FUNCTION__, (uint64_t)m_threads.size());
283 
284     // Run through the threads and ask whether we should report this event.
285     // For stopping, a YES vote wins over everything.  A NO vote wins over NO opinion.
286     for (pos = m_threads.begin(); pos != end; ++pos)
287     {
288         ThreadSP thread_sp(*pos);
289         const Vote vote = thread_sp->ShouldReportStop (event_ptr);
290         switch (vote)
291         {
292         case eVoteNoOpinion:
293             continue;
294 
295         case eVoteYes:
296             result = eVoteYes;
297             break;
298 
299         case eVoteNo:
300             if (result == eVoteNoOpinion)
301             {
302                 result = eVoteNo;
303             }
304             else
305             {
306                 if (log)
307                     log->Printf ("ThreadList::%s thread 0x%4.4" PRIx64 ": voted %s, but lost out because result was %s",
308                                  __FUNCTION__,
309                                  thread_sp->GetID (),
310                                  GetVoteAsCString (vote),
311                                  GetVoteAsCString (result));
312             }
313             break;
314         }
315     }
316     if (log)
317         log->Printf ("ThreadList::%s returning %s", __FUNCTION__, GetVoteAsCString (result));
318     return result;
319 }
320 
321 Vote
322 ThreadList::ShouldReportRun (Event *event_ptr)
323 {
324 
325     Mutex::Locker locker(m_threads_mutex);
326 
327     Vote result = eVoteNoOpinion;
328     m_process->UpdateThreadListIfNeeded();
329     collection::iterator pos, end = m_threads.end();
330 
331     // Run through the threads and ask whether we should report this event.
332     // The rule is NO vote wins over everything, a YES vote wins over no opinion.
333 
334     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
335 
336     for (pos = m_threads.begin(); pos != end; ++pos)
337     {
338         if ((*pos)->GetResumeState () != eStateSuspended)
339         {
340             switch ((*pos)->ShouldReportRun (event_ptr))
341             {
342                 case eVoteNoOpinion:
343                     continue;
344                 case eVoteYes:
345                     if (result == eVoteNoOpinion)
346                         result = eVoteYes;
347                     break;
348                 case eVoteNo:
349                     if (log)
350                         log->Printf ("ThreadList::ShouldReportRun() thread %d (0x%4.4" PRIx64 ") says don't report.",
351                                      (*pos)->GetIndexID(),
352                                      (*pos)->GetID());
353                     result = eVoteNo;
354                     break;
355             }
356         }
357     }
358     return result;
359 }
360 
361 void
362 ThreadList::Clear()
363 {
364     Mutex::Locker locker(m_threads_mutex);
365     m_stop_id = 0;
366     m_threads.clear();
367     m_selected_tid = LLDB_INVALID_THREAD_ID;
368 }
369 
370 void
371 ThreadList::Destroy()
372 {
373     Mutex::Locker locker(m_threads_mutex);
374     const uint32_t num_threads = m_threads.size();
375     for (uint32_t idx = 0; idx < num_threads; ++idx)
376     {
377         m_threads[idx]->DestroyThread();
378     }
379 }
380 
381 void
382 ThreadList::RefreshStateAfterStop ()
383 {
384     Mutex::Locker locker(m_threads_mutex);
385 
386     m_process->UpdateThreadListIfNeeded();
387 
388     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
389     if (log && log->GetVerbose())
390         log->Printf ("Turning off notification of new threads while single stepping a thread.");
391 
392     collection::iterator pos, end = m_threads.end();
393     for (pos = m_threads.begin(); pos != end; ++pos)
394         (*pos)->RefreshStateAfterStop ();
395 }
396 
397 void
398 ThreadList::DiscardThreadPlans ()
399 {
400     // You don't need to update the thread list here, because only threads
401     // that you currently know about have any thread plans.
402     Mutex::Locker locker(m_threads_mutex);
403 
404     collection::iterator pos, end = m_threads.end();
405     for (pos = m_threads.begin(); pos != end; ++pos)
406         (*pos)->DiscardThreadPlans (true);
407 
408 }
409 
410 bool
411 ThreadList::WillResume ()
412 {
413     // Run through the threads and perform their momentary actions.
414     // But we only do this for threads that are running, user suspended
415     // threads stay where they are.
416 
417     Mutex::Locker locker(m_threads_mutex);
418     m_process->UpdateThreadListIfNeeded();
419 
420     collection::iterator pos, end = m_threads.end();
421 
422     // See if any thread wants to run stopping others.  If it does, then we won't
423     // setup the other threads for resume, since they aren't going to get a chance
424     // to run.  This is necessary because the SetupForResume might add "StopOthers"
425     // plans which would then get to be part of the who-gets-to-run negotiation, but
426     // they're coming in after the fact, and the threads that are already set up should
427     // take priority.
428 
429     bool wants_solo_run = false;
430 
431     for (pos = m_threads.begin(); pos != end; ++pos)
432     {
433         if ((*pos)->GetResumeState() != eStateSuspended &&
434                  (*pos)->GetCurrentPlan()->StopOthers())
435         {
436             wants_solo_run = true;
437             break;
438         }
439     }
440 
441     if (wants_solo_run)
442     {
443         Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
444         if (log && log->GetVerbose())
445             log->Printf ("Turning on notification of new threads while single stepping a thread.");
446         m_process->StartNoticingNewThreads();
447     }
448     else
449     {
450         Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
451         if (log && log->GetVerbose())
452             log->Printf ("Turning off notification of new threads while single stepping a thread.");
453         m_process->StopNoticingNewThreads();
454     }
455 
456     // Give all the threads that are likely to run a last chance to set up their state before we
457     // negotiate who is actually going to get a chance to run...
458     // Don't set to resume suspended threads, and if any thread wanted to stop others, only
459     // call setup on the threads that request StopOthers...
460 
461     for (pos = m_threads.begin(); pos != end; ++pos)
462     {
463         if ((*pos)->GetResumeState() != eStateSuspended
464             && (!wants_solo_run || (*pos)->GetCurrentPlan()->StopOthers()))
465         {
466             (*pos)->SetupForResume ();
467         }
468     }
469 
470     // Now go through the threads and see if any thread wants to run just itself.
471     // if so then pick one and run it.
472 
473     ThreadList run_me_only_list (m_process);
474 
475     run_me_only_list.SetStopID(m_process->GetStopID());
476 
477     ThreadSP immediate_thread_sp;
478     bool run_only_current_thread = false;
479 
480     for (pos = m_threads.begin(); pos != end; ++pos)
481     {
482         ThreadSP thread_sp(*pos);
483         if (thread_sp->GetResumeState() != eStateSuspended &&
484                  thread_sp->GetCurrentPlan()->StopOthers())
485         {
486             // You can't say "stop others" and also want yourself to be suspended.
487             assert (thread_sp->GetCurrentPlan()->RunState() != eStateSuspended);
488 
489             if (thread_sp == GetSelectedThread())
490             {
491                 run_only_current_thread = true;
492                 run_me_only_list.Clear();
493                 run_me_only_list.AddThread (thread_sp);
494                 break;
495             }
496 
497             run_me_only_list.AddThread (thread_sp);
498         }
499 
500     }
501 
502     bool need_to_resume = true;
503 
504     if (immediate_thread_sp)
505     {
506         for (pos = m_threads.begin(); pos != end; ++pos)
507         {
508             ThreadSP thread_sp(*pos);
509             if (thread_sp.get() == immediate_thread_sp.get())
510                 thread_sp->WillResume(thread_sp->GetCurrentPlan()->RunState());
511             else
512                 thread_sp->WillResume (eStateSuspended);
513         }
514     }
515     else if (run_me_only_list.GetSize (false) == 0)
516     {
517         // Everybody runs as they wish:
518         for (pos = m_threads.begin(); pos != end; ++pos)
519         {
520             ThreadSP thread_sp(*pos);
521             StateType run_state;
522             if (thread_sp->GetResumeState() != eStateSuspended)
523                 run_state = thread_sp->GetCurrentPlan()->RunState();
524             else
525                 run_state = eStateSuspended;
526             if (!thread_sp->WillResume(run_state))
527                 need_to_resume = false;
528         }
529     }
530     else
531     {
532         ThreadSP thread_to_run;
533 
534         if (run_only_current_thread)
535         {
536             thread_to_run = GetSelectedThread();
537         }
538         else if (run_me_only_list.GetSize (false) == 1)
539         {
540             thread_to_run = run_me_only_list.GetThreadAtIndex (0);
541         }
542         else
543         {
544             int random_thread = (int)
545                     ((run_me_only_list.GetSize (false) * (double) rand ()) / (RAND_MAX + 1.0));
546             thread_to_run = run_me_only_list.GetThreadAtIndex (random_thread);
547         }
548 
549         for (pos = m_threads.begin(); pos != end; ++pos)
550         {
551             ThreadSP thread_sp(*pos);
552             if (thread_sp == thread_to_run)
553             {
554                 if (!thread_sp->WillResume(thread_sp->GetCurrentPlan()->RunState()))
555                     need_to_resume = false;
556             }
557             else
558                 thread_sp->WillResume (eStateSuspended);
559         }
560     }
561 
562     return need_to_resume;
563 }
564 
565 void
566 ThreadList::DidResume ()
567 {
568     Mutex::Locker locker(m_threads_mutex);
569     collection::iterator pos, end = m_threads.end();
570     for (pos = m_threads.begin(); pos != end; ++pos)
571     {
572         // Don't clear out threads that aren't going to get a chance to run, rather
573         // leave their state for the next time around.
574         ThreadSP thread_sp(*pos);
575         if (thread_sp->GetResumeState() != eStateSuspended)
576             thread_sp->DidResume ();
577     }
578 }
579 
580 ThreadSP
581 ThreadList::GetSelectedThread ()
582 {
583     Mutex::Locker locker(m_threads_mutex);
584     ThreadSP thread_sp = FindThreadByID(m_selected_tid);
585     if (!thread_sp.get())
586     {
587         if (m_threads.size() == 0)
588             return thread_sp;
589         m_selected_tid = m_threads[0]->GetID();
590         thread_sp = m_threads[0];
591     }
592     return thread_sp;
593 }
594 
595 bool
596 ThreadList::SetSelectedThreadByID (lldb::tid_t tid, bool notify)
597 {
598     Mutex::Locker locker(m_threads_mutex);
599     ThreadSP selected_thread_sp(FindThreadByID(tid));
600     if  (selected_thread_sp)
601     {
602         m_selected_tid = tid;
603         selected_thread_sp->SetDefaultFileAndLineToSelectedFrame();
604     }
605     else
606         m_selected_tid = LLDB_INVALID_THREAD_ID;
607 
608     if (notify)
609         NotifySelectedThreadChanged(m_selected_tid);
610 
611     return m_selected_tid != LLDB_INVALID_THREAD_ID;
612 }
613 
614 bool
615 ThreadList::SetSelectedThreadByIndexID (uint32_t index_id, bool notify)
616 {
617     Mutex::Locker locker(m_threads_mutex);
618     ThreadSP selected_thread_sp (FindThreadByIndexID(index_id));
619     if  (selected_thread_sp.get())
620     {
621         m_selected_tid = selected_thread_sp->GetID();
622         selected_thread_sp->SetDefaultFileAndLineToSelectedFrame();
623     }
624     else
625         m_selected_tid = LLDB_INVALID_THREAD_ID;
626 
627     if (notify)
628         NotifySelectedThreadChanged(m_selected_tid);
629 
630     return m_selected_tid != LLDB_INVALID_THREAD_ID;
631 }
632 
633 void
634 ThreadList::NotifySelectedThreadChanged (lldb::tid_t tid)
635 {
636     ThreadSP selected_thread_sp (FindThreadByID(tid));
637     if (selected_thread_sp->EventTypeHasListeners(Thread::eBroadcastBitThreadSelected))
638         selected_thread_sp->BroadcastEvent(Thread::eBroadcastBitThreadSelected,
639                                            new Thread::ThreadEventData(selected_thread_sp));
640 }
641 
642 void
643 ThreadList::Update (ThreadList &rhs)
644 {
645     if (this != &rhs)
646     {
647         // Lock both mutexes to make sure neither side changes anyone on us
648         // while the assignement occurs
649         Mutex::Locker locker_lhs(m_threads_mutex);
650         Mutex::Locker locker_rhs(rhs.m_threads_mutex);
651         m_process = rhs.m_process;
652         m_stop_id = rhs.m_stop_id;
653         m_threads.swap(rhs.m_threads);
654         m_selected_tid = rhs.m_selected_tid;
655 
656 
657         // Now we look for threads that we are done with and
658         // make sure to clear them up as much as possible so
659         // anyone with a shared pointer will still have a reference,
660         // but the thread won't be of much use. Using std::weak_ptr
661         // for all backward references (such as a thread to a process)
662         // will eventually solve this issue for us, but for now, we
663         // need to work around the issue
664         collection::iterator rhs_pos, rhs_end = rhs.m_threads.end();
665         for (rhs_pos = rhs.m_threads.begin(); rhs_pos != rhs_end; ++rhs_pos)
666         {
667             const lldb::tid_t tid = (*rhs_pos)->GetID();
668             bool thread_is_alive = false;
669             const uint32_t num_threads = m_threads.size();
670             for (uint32_t idx = 0; idx < num_threads; ++idx)
671             {
672                 if (m_threads[idx]->GetID() == tid)
673                 {
674                     thread_is_alive = true;
675                     break;
676                 }
677             }
678             if (!thread_is_alive)
679                 (*rhs_pos)->DestroyThread();
680         }
681     }
682 }
683 
684 void
685 ThreadList::Flush ()
686 {
687     Mutex::Locker locker(m_threads_mutex);
688     collection::iterator pos, end = m_threads.end();
689     for (pos = m_threads.begin(); pos != end; ++pos)
690         (*pos)->Flush ();
691 }
692 
693