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::GetThreadSPForThreadPtr (Thread *thread_ptr)
132 {
133     ThreadSP thread_sp;
134     if (thread_ptr)
135     {
136         Mutex::Locker locker(m_threads_mutex);
137 
138         uint32_t idx = 0;
139         const uint32_t num_threads = m_threads.size();
140         for (idx = 0; idx < num_threads; ++idx)
141         {
142             if (m_threads[idx].get() == thread_ptr)
143             {
144                 thread_sp = m_threads[idx];
145                 break;
146             }
147         }
148     }
149     return thread_sp;
150 }
151 
152 
153 
154 ThreadSP
155 ThreadList::FindThreadByIndexID (uint32_t index_id, bool can_update)
156 {
157     Mutex::Locker locker(m_threads_mutex);
158 
159     if (can_update)
160         m_process->UpdateThreadListIfNeeded();
161 
162     ThreadSP thread_sp;
163     const uint32_t num_threads = m_threads.size();
164     for (uint32_t idx = 0; idx < num_threads; ++idx)
165     {
166         if (m_threads[idx]->GetIndexID() == index_id)
167         {
168             thread_sp = m_threads[idx];
169             break;
170         }
171     }
172     return thread_sp;
173 }
174 
175 bool
176 ThreadList::ShouldStop (Event *event_ptr)
177 {
178     bool should_stop = false;
179     // Running events should never stop, obviously...
180 
181     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
182 
183     // The ShouldStop method of the threads can do a whole lot of work,
184     // running breakpoint commands & conditions, etc.  So we don't want
185     // to keep the ThreadList locked the whole time we are doing this.
186     // FIXME: It is possible that running code could cause new threads
187     // to be created.  If that happens we will miss asking them whether
188     // then should stop.  This is not a big deal, since we haven't had
189     // a chance to hang any interesting operations on those threads yet.
190 
191     collection threads_copy;
192     {
193         // Scope for locker
194         Mutex::Locker locker(m_threads_mutex);
195 
196         m_process->UpdateThreadListIfNeeded();
197         threads_copy = m_threads;
198     }
199 
200     collection::iterator pos, end = threads_copy.end();
201 
202     if (log)
203     {
204         log->PutCString("");
205         log->Printf ("ThreadList::%s: %llu threads", __FUNCTION__, (uint64_t)m_threads.size());
206     }
207 
208     for (pos = threads_copy.begin(); pos != end; ++pos)
209     {
210         ThreadSP thread_sp(*pos);
211 
212         const bool thread_should_stop = thread_sp->ShouldStop(event_ptr);
213         if (thread_should_stop)
214             should_stop |= true;
215     }
216 
217     if (log)
218         log->Printf ("ThreadList::%s overall should_stop = %i", __FUNCTION__, should_stop);
219 
220     if (should_stop)
221     {
222         for (pos = threads_copy.begin(); pos != end; ++pos)
223         {
224             ThreadSP thread_sp(*pos);
225             thread_sp->WillStop ();
226         }
227     }
228 
229     return should_stop;
230 }
231 
232 Vote
233 ThreadList::ShouldReportStop (Event *event_ptr)
234 {
235     Mutex::Locker locker(m_threads_mutex);
236 
237     Vote result = eVoteNoOpinion;
238     m_process->UpdateThreadListIfNeeded();
239     collection::iterator pos, end = m_threads.end();
240 
241     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
242 
243     if (log)
244         log->Printf ("ThreadList::%s %llu threads", __FUNCTION__, (uint64_t)m_threads.size());
245 
246     // Run through the threads and ask whether we should report this event.
247     // For stopping, a YES vote wins over everything.  A NO vote wins over NO opinion.
248     for (pos = m_threads.begin(); pos != end; ++pos)
249     {
250         ThreadSP thread_sp(*pos);
251         const Vote vote = thread_sp->ShouldReportStop (event_ptr);
252         switch (vote)
253         {
254         case eVoteNoOpinion:
255             continue;
256 
257         case eVoteYes:
258             result = eVoteYes;
259             break;
260 
261         case eVoteNo:
262             if (result == eVoteNoOpinion)
263             {
264                 result = eVoteNo;
265             }
266             else
267             {
268                 if (log)
269                     log->Printf ("ThreadList::%s thread 0x%4.4llx: voted %s, but lost out because result was %s",
270                                  __FUNCTION__,
271                                  thread_sp->GetID (),
272                                  GetVoteAsCString (vote),
273                                  GetVoteAsCString (result));
274             }
275             break;
276         }
277     }
278     if (log)
279         log->Printf ("ThreadList::%s returning %s", __FUNCTION__, GetVoteAsCString (result));
280     return result;
281 }
282 
283 Vote
284 ThreadList::ShouldReportRun (Event *event_ptr)
285 {
286 
287     Mutex::Locker locker(m_threads_mutex);
288 
289     Vote result = eVoteNoOpinion;
290     m_process->UpdateThreadListIfNeeded();
291     collection::iterator pos, end = m_threads.end();
292 
293     // Run through the threads and ask whether we should report this event.
294     // The rule is NO vote wins over everything, a YES vote wins over no opinion.
295 
296     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
297 
298     for (pos = m_threads.begin(); pos != end; ++pos)
299     {
300         if ((*pos)->GetResumeState () != eStateSuspended)
301         {
302             switch ((*pos)->ShouldReportRun (event_ptr))
303             {
304                 case eVoteNoOpinion:
305                     continue;
306                 case eVoteYes:
307                     if (result == eVoteNoOpinion)
308                         result = eVoteYes;
309                     break;
310                 case eVoteNo:
311                     if (log)
312                         log->Printf ("ThreadList::ShouldReportRun() thread %d (0x%4.4llx) says don't report.",
313                                      (*pos)->GetIndexID(),
314                                      (*pos)->GetID());
315                     result = eVoteNo;
316                     break;
317             }
318         }
319     }
320     return result;
321 }
322 
323 void
324 ThreadList::Clear()
325 {
326     Mutex::Locker locker(m_threads_mutex);
327     m_stop_id = 0;
328     m_threads.clear();
329     m_selected_tid = LLDB_INVALID_THREAD_ID;
330 }
331 
332 void
333 ThreadList::Destroy()
334 {
335     Mutex::Locker locker(m_threads_mutex);
336     const uint32_t num_threads = m_threads.size();
337     for (uint32_t idx = 0; idx < num_threads; ++idx)
338     {
339         m_threads[idx]->DestroyThread();
340     }
341 }
342 
343 void
344 ThreadList::RefreshStateAfterStop ()
345 {
346     Mutex::Locker locker(m_threads_mutex);
347 
348     m_process->UpdateThreadListIfNeeded();
349 
350     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
351     if (log && log->GetVerbose())
352         log->Printf ("Turning off notification of new threads while single stepping a thread.");
353 
354     collection::iterator pos, end = m_threads.end();
355     for (pos = m_threads.begin(); pos != end; ++pos)
356         (*pos)->RefreshStateAfterStop ();
357 }
358 
359 void
360 ThreadList::DiscardThreadPlans ()
361 {
362     // You don't need to update the thread list here, because only threads
363     // that you currently know about have any thread plans.
364     Mutex::Locker locker(m_threads_mutex);
365 
366     collection::iterator pos, end = m_threads.end();
367     for (pos = m_threads.begin(); pos != end; ++pos)
368         (*pos)->DiscardThreadPlans (true);
369 
370 }
371 
372 bool
373 ThreadList::WillResume ()
374 {
375     // Run through the threads and perform their momentary actions.
376     // But we only do this for threads that are running, user suspended
377     // threads stay where they are.
378 
379     Mutex::Locker locker(m_threads_mutex);
380     m_process->UpdateThreadListIfNeeded();
381 
382     collection::iterator pos, end = m_threads.end();
383 
384     // See if any thread wants to run stopping others.  If it does, then we won't
385     // setup the other threads for resume, since they aren't going to get a chance
386     // to run.  This is necessary because the SetupForResume might add "StopOthers"
387     // plans which would then get to be part of the who-gets-to-run negotiation, but
388     // they're coming in after the fact, and the threads that are already set up should
389     // take priority.
390 
391     bool wants_solo_run = false;
392 
393     for (pos = m_threads.begin(); pos != end; ++pos)
394     {
395         if ((*pos)->GetResumeState() != eStateSuspended &&
396                  (*pos)->GetCurrentPlan()->StopOthers())
397         {
398             wants_solo_run = true;
399             break;
400         }
401     }
402 
403     if (wants_solo_run)
404     {
405         LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
406         if (log && log->GetVerbose())
407             log->Printf ("Turning on notification of new threads while single stepping a thread.");
408         m_process->StartNoticingNewThreads();
409     }
410     else
411     {
412         LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
413         if (log && log->GetVerbose())
414             log->Printf ("Turning off notification of new threads while single stepping a thread.");
415         m_process->StopNoticingNewThreads();
416     }
417 
418     // Give all the threads that are likely to run a last chance to set up their state before we
419     // negotiate who is actually going to get a chance to run...
420     // Don't set to resume suspended threads, and if any thread wanted to stop others, only
421     // call setup on the threads that request StopOthers...
422 
423     for (pos = m_threads.begin(); pos != end; ++pos)
424     {
425         if ((*pos)->GetResumeState() != eStateSuspended
426             && (!wants_solo_run || (*pos)->GetCurrentPlan()->StopOthers()))
427         {
428             (*pos)->SetupForResume ();
429         }
430     }
431 
432     // Now go through the threads and see if any thread wants to run just itself.
433     // if so then pick one and run it.
434 
435     ThreadList run_me_only_list (m_process);
436 
437     run_me_only_list.SetStopID(m_process->GetStopID());
438 
439     ThreadSP immediate_thread_sp;
440     bool run_only_current_thread = false;
441 
442     for (pos = m_threads.begin(); pos != end; ++pos)
443     {
444         ThreadSP thread_sp(*pos);
445         if (thread_sp->GetResumeState() != eStateSuspended &&
446                  thread_sp->GetCurrentPlan()->StopOthers())
447         {
448             // You can't say "stop others" and also want yourself to be suspended.
449             assert (thread_sp->GetCurrentPlan()->RunState() != eStateSuspended);
450 
451             if (thread_sp == GetSelectedThread())
452             {
453                 run_only_current_thread = true;
454                 run_me_only_list.Clear();
455                 run_me_only_list.AddThread (thread_sp);
456                 break;
457             }
458 
459             run_me_only_list.AddThread (thread_sp);
460         }
461 
462     }
463 
464     bool need_to_resume = true;
465 
466     if (immediate_thread_sp)
467     {
468         for (pos = m_threads.begin(); pos != end; ++pos)
469         {
470             ThreadSP thread_sp(*pos);
471             if (thread_sp.get() == immediate_thread_sp.get())
472                 thread_sp->WillResume(thread_sp->GetCurrentPlan()->RunState());
473             else
474                 thread_sp->WillResume (eStateSuspended);
475         }
476     }
477     else if (run_me_only_list.GetSize (false) == 0)
478     {
479         // Everybody runs as they wish:
480         for (pos = m_threads.begin(); pos != end; ++pos)
481         {
482             ThreadSP thread_sp(*pos);
483             StateType run_state;
484             if (thread_sp->GetResumeState() != eStateSuspended)
485                 run_state = thread_sp->GetCurrentPlan()->RunState();
486             else
487                 run_state = eStateSuspended;
488             if (!thread_sp->WillResume(run_state))
489                 need_to_resume = false;
490         }
491     }
492     else
493     {
494         ThreadSP thread_to_run;
495 
496         if (run_only_current_thread)
497         {
498             thread_to_run = GetSelectedThread();
499         }
500         else if (run_me_only_list.GetSize (false) == 1)
501         {
502             thread_to_run = run_me_only_list.GetThreadAtIndex (0);
503         }
504         else
505         {
506             int random_thread = (int)
507                     ((run_me_only_list.GetSize (false) * (double) rand ()) / (RAND_MAX + 1.0));
508             thread_to_run = run_me_only_list.GetThreadAtIndex (random_thread);
509         }
510 
511         for (pos = m_threads.begin(); pos != end; ++pos)
512         {
513             ThreadSP thread_sp(*pos);
514             if (thread_sp == thread_to_run)
515             {
516                 if (!thread_sp->WillResume(thread_sp->GetCurrentPlan()->RunState()))
517                     need_to_resume = false;
518             }
519             else
520                 thread_sp->WillResume (eStateSuspended);
521         }
522     }
523 
524     return need_to_resume;
525 }
526 
527 void
528 ThreadList::DidResume ()
529 {
530     Mutex::Locker locker(m_threads_mutex);
531     collection::iterator pos, end = m_threads.end();
532     for (pos = m_threads.begin(); pos != end; ++pos)
533     {
534         // Don't clear out threads that aren't going to get a chance to run, rather
535         // leave their state for the next time around.
536         ThreadSP thread_sp(*pos);
537         if (thread_sp->GetResumeState() != eStateSuspended)
538             thread_sp->DidResume ();
539     }
540 }
541 
542 ThreadSP
543 ThreadList::GetSelectedThread ()
544 {
545     Mutex::Locker locker(m_threads_mutex);
546     ThreadSP thread_sp = FindThreadByID(m_selected_tid);
547     if (!thread_sp.get())
548     {
549         if (m_threads.size() == 0)
550             return thread_sp;
551         m_selected_tid = m_threads[0]->GetID();
552         thread_sp = m_threads[0];
553     }
554     return thread_sp;
555 }
556 
557 bool
558 ThreadList::SetSelectedThreadByID (lldb::tid_t tid)
559 {
560     Mutex::Locker locker(m_threads_mutex);
561     ThreadSP selected_thread_sp(FindThreadByID(tid));
562     if  (selected_thread_sp)
563     {
564         m_selected_tid = tid;
565         selected_thread_sp->SetDefaultFileAndLineToSelectedFrame();
566     }
567     else
568         m_selected_tid = LLDB_INVALID_THREAD_ID;
569 
570     return m_selected_tid != LLDB_INVALID_THREAD_ID;
571 }
572 
573 bool
574 ThreadList::SetSelectedThreadByIndexID (uint32_t index_id)
575 {
576     Mutex::Locker locker(m_threads_mutex);
577     ThreadSP selected_thread_sp (FindThreadByIndexID(index_id));
578     if  (selected_thread_sp.get())
579     {
580         m_selected_tid = selected_thread_sp->GetID();
581         selected_thread_sp->SetDefaultFileAndLineToSelectedFrame();
582     }
583     else
584         m_selected_tid = LLDB_INVALID_THREAD_ID;
585 
586     return m_selected_tid != LLDB_INVALID_THREAD_ID;
587 }
588 
589 void
590 ThreadList::Update (ThreadList &rhs)
591 {
592     if (this != &rhs)
593     {
594         // Lock both mutexes to make sure neither side changes anyone on us
595         // while the assignement occurs
596         Mutex::Locker locker_lhs(m_threads_mutex);
597         Mutex::Locker locker_rhs(rhs.m_threads_mutex);
598         m_process = rhs.m_process;
599         m_stop_id = rhs.m_stop_id;
600         m_threads.swap(rhs.m_threads);
601         m_selected_tid = rhs.m_selected_tid;
602 
603 
604         // Now we look for threads that we are done with and
605         // make sure to clear them up as much as possible so
606         // anyone with a shared pointer will still have a reference,
607         // but the thread won't be of much use. Using std::weak_ptr
608         // for all backward references (such as a thread to a process)
609         // will eventually solve this issue for us, but for now, we
610         // need to work around the issue
611         collection::iterator rhs_pos, rhs_end = rhs.m_threads.end();
612         for (rhs_pos = rhs.m_threads.begin(); rhs_pos != rhs_end; ++rhs_pos)
613         {
614             const lldb::tid_t tid = (*rhs_pos)->GetID();
615             bool thread_is_alive = false;
616             const uint32_t num_threads = m_threads.size();
617             for (uint32_t idx = 0; idx < num_threads; ++idx)
618             {
619                 if (m_threads[idx]->GetID() == tid)
620                 {
621                     thread_is_alive = true;
622                     break;
623                 }
624             }
625             if (!thread_is_alive)
626                 (*rhs_pos)->DestroyThread();
627         }
628     }
629 }
630 
631 void
632 ThreadList::Flush ()
633 {
634     Mutex::Locker locker(m_threads_mutex);
635     collection::iterator pos, end = m_threads.end();
636     for (pos = m_threads.begin(); pos != end; ++pos)
637         (*pos)->Flush ();
638 }
639 
640