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