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     Log *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     Log *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 lldb::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     for (pos = m_threads.begin(); pos != end; ++pos)
320     {
321         ThreadSP thread_sp(*pos);
322         if (thread_sp->GetResumeState () != eStateSuspended)
323 
324         switch (thread_sp->ShouldReportRun (event_ptr))
325         {
326             case eVoteNoOpinion:
327                 continue;
328             case eVoteYes:
329                 if (result == eVoteNoOpinion)
330                     result = eVoteYes;
331                 break;
332             case eVoteNo:
333                 result = eVoteNo;
334                 break;
335         }
336     }
337     return result;
338 }
339 
340 void
341 ThreadList::Clear()
342 {
343     m_stop_id = 0;
344     m_threads.clear();
345     m_selected_tid = LLDB_INVALID_THREAD_ID;
346 }
347 
348 void
349 ThreadList::RefreshStateAfterStop ()
350 {
351     Mutex::Locker locker(m_threads_mutex);
352 
353     m_process->UpdateThreadListIfNeeded();
354 
355     collection::iterator pos, end = m_threads.end();
356     for (pos = m_threads.begin(); pos != end; ++pos)
357         (*pos)->RefreshStateAfterStop ();
358 }
359 
360 void
361 ThreadList::DiscardThreadPlans ()
362 {
363     // You don't need to update the thread list here, because only threads
364     // that you currently know about have any thread plans.
365     Mutex::Locker locker(m_threads_mutex);
366 
367     collection::iterator pos, end = m_threads.end();
368     for (pos = m_threads.begin(); pos != end; ++pos)
369         (*pos)->DiscardThreadPlans (true);
370 
371 }
372 
373 bool
374 ThreadList::WillResume ()
375 {
376     // Run through the threads and perform their momentary actions.
377     // But we only do this for threads that are running, user suspended
378     // threads stay where they are.
379     bool success = true;
380 
381     Mutex::Locker locker(m_threads_mutex);
382     m_process->UpdateThreadListIfNeeded();
383 
384     collection::iterator pos, end = m_threads.end();
385 
386     // See if any thread wants to run stopping others.  If it does, then we won't
387     // setup the other threads for resume, since they aren't going to get a chance
388     // to run.  This is necessary because the SetupForResume might add "StopOthers"
389     // plans which would then get to be part of the who-gets-to-run negotiation, but
390     // they're coming in after the fact, and the threads that are already set up should
391     // take priority.
392 
393     bool wants_solo_run = false;
394 
395     for (pos = m_threads.begin(); pos != end; ++pos)
396     {
397         if ((*pos)->GetResumeState() != eStateSuspended &&
398                  (*pos)->GetCurrentPlan()->StopOthers())
399         {
400             wants_solo_run = true;
401             break;
402         }
403     }
404 
405 
406     // Give all the threads that are likely to run a last chance to set up their state before we
407     // negotiate who is actually going to get a chance to run...
408     // Don't set to resume suspended threads, and if any thread wanted to stop others, only
409     // call setup on the threads that request StopOthers...
410 
411     for (pos = m_threads.begin(); pos != end; ++pos)
412     {
413         if ((*pos)->GetResumeState() != eStateSuspended
414             && (!wants_solo_run || (*pos)->GetCurrentPlan()->StopOthers()))
415         {
416             (*pos)->SetupForResume ();
417         }
418     }
419 
420     // Now go through the threads and see if any thread wants to run just itself.
421     // if so then pick one and run it.
422 
423     ThreadList run_me_only_list (m_process);
424 
425     run_me_only_list.SetStopID(m_process->GetStopID());
426 
427     ThreadSP immediate_thread_sp;
428     bool run_only_current_thread = false;
429 
430     for (pos = m_threads.begin(); pos != end; ++pos)
431     {
432         ThreadSP thread_sp(*pos);
433         if (thread_sp->GetResumeState() != eStateSuspended &&
434                  thread_sp->GetCurrentPlan()->StopOthers())
435         {
436             // You can't say "stop others" and also want yourself to be suspended.
437             assert (thread_sp->GetCurrentPlan()->RunState() != eStateSuspended);
438 
439             if (thread_sp == GetSelectedThread())
440             {
441                 run_only_current_thread = true;
442                 run_me_only_list.Clear();
443                 run_me_only_list.AddThread (thread_sp);
444                 break;
445             }
446 
447             run_me_only_list.AddThread (thread_sp);
448         }
449 
450     }
451 
452     if (immediate_thread_sp)
453     {
454         for (pos = m_threads.begin(); pos != end; ++pos)
455         {
456             ThreadSP thread_sp(*pos);
457             if (thread_sp.get() == immediate_thread_sp.get())
458                 thread_sp->WillResume(thread_sp->GetCurrentPlan()->RunState());
459             else
460                 thread_sp->WillResume (eStateSuspended);
461         }
462     }
463     else if (run_me_only_list.GetSize (false) == 0)
464     {
465         // Everybody runs as they wish:
466         for (pos = m_threads.begin(); pos != end; ++pos)
467         {
468             ThreadSP thread_sp(*pos);
469             thread_sp->WillResume(thread_sp->GetCurrentPlan()->RunState());
470         }
471     }
472     else
473     {
474         ThreadSP thread_to_run;
475 
476         if (run_only_current_thread)
477         {
478             thread_to_run = GetSelectedThread();
479         }
480         else if (run_me_only_list.GetSize (false) == 1)
481         {
482             thread_to_run = run_me_only_list.GetThreadAtIndex (0);
483         }
484         else
485         {
486             int random_thread = (int)
487                     ((run_me_only_list.GetSize (false) * (double) rand ()) / (RAND_MAX + 1.0));
488             thread_to_run = run_me_only_list.GetThreadAtIndex (random_thread);
489         }
490 
491         for (pos = m_threads.begin(); pos != end; ++pos)
492         {
493             ThreadSP thread_sp(*pos);
494             if (thread_sp == thread_to_run)
495                 thread_sp->WillResume(thread_sp->GetCurrentPlan()->RunState());
496             else
497                 thread_sp->WillResume (eStateSuspended);
498         }
499     }
500 
501     return success;
502 }
503 
504 void
505 ThreadList::DidResume ()
506 {
507     collection::iterator pos, end = m_threads.end();
508     for (pos = m_threads.begin(); pos != end; ++pos)
509     {
510         // Don't clear out threads that aren't going to get a chance to run, rather
511         // leave their state for the next time around.
512         ThreadSP thread_sp(*pos);
513         if (thread_sp->GetResumeState() != eStateSuspended)
514             thread_sp->DidResume ();
515     }
516 }
517 
518 ThreadSP
519 ThreadList::GetSelectedThread ()
520 {
521     Mutex::Locker locker(m_threads_mutex);
522     return FindThreadByID(m_selected_tid);
523 }
524 
525 bool
526 ThreadList::SetSelectedThreadByID (lldb::tid_t tid)
527 {
528     Mutex::Locker locker(m_threads_mutex);
529     if  (FindThreadByID(tid).get())
530         m_selected_tid = tid;
531     else
532         m_selected_tid = LLDB_INVALID_THREAD_ID;
533 
534     return m_selected_tid != LLDB_INVALID_THREAD_ID;
535 }
536 
537 bool
538 ThreadList::SetSelectedThreadByIndexID (uint32_t index_id)
539 {
540     Mutex::Locker locker(m_threads_mutex);
541     ThreadSP thread_sp (FindThreadByIndexID(index_id));
542     if  (thread_sp.get())
543         m_selected_tid = thread_sp->GetID();
544     else
545         m_selected_tid = LLDB_INVALID_THREAD_ID;
546 
547     return m_selected_tid != LLDB_INVALID_THREAD_ID;
548 }
549 
550