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