1 //===-- MachThreadList.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 //
10 //  Created by Greg Clayton on 6/19/07.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "MachThreadList.h"
15 
16 #include <inttypes.h>
17 #include <sys/sysctl.h>
18 
19 #include "DNBLog.h"
20 #include "DNBThreadResumeActions.h"
21 #include "MachProcess.h"
22 
23 MachThreadList::MachThreadList() :
24     m_threads(),
25     m_threads_mutex(PTHREAD_MUTEX_RECURSIVE)
26 {
27 }
28 
29 MachThreadList::~MachThreadList()
30 {
31 }
32 
33 nub_state_t
34 MachThreadList::GetState(nub_thread_t tid)
35 {
36     MachThreadSP thread_sp (GetThreadByID (tid));
37     if (thread_sp)
38         return thread_sp->GetState();
39     return eStateInvalid;
40 }
41 
42 const char *
43 MachThreadList::GetName (nub_thread_t tid)
44 {
45     MachThreadSP thread_sp (GetThreadByID (tid));
46     if (thread_sp)
47         return thread_sp->GetName();
48     return NULL;
49 }
50 
51 nub_thread_t
52 MachThreadList::SetCurrentThread(nub_thread_t tid)
53 {
54     MachThreadSP thread_sp (GetThreadByID (tid));
55     if (thread_sp)
56     {
57         m_current_thread = thread_sp;
58         return tid;
59     }
60     return INVALID_NUB_THREAD;
61 }
62 
63 
64 bool
65 MachThreadList::GetThreadStoppedReason(nub_thread_t tid, struct DNBThreadStopInfo *stop_info) const
66 {
67     MachThreadSP thread_sp (GetThreadByID (tid));
68     if (thread_sp)
69         return thread_sp->GetStopException().GetStopInfo(stop_info);
70     return false;
71 }
72 
73 bool
74 MachThreadList::GetIdentifierInfo (nub_thread_t tid, thread_identifier_info_data_t *ident_info)
75 {
76     thread_t mach_port_number = GetMachPortNumberByThreadID (tid);
77 
78     mach_msg_type_number_t count = THREAD_IDENTIFIER_INFO_COUNT;
79     return ::thread_info (mach_port_number, THREAD_IDENTIFIER_INFO, (thread_info_t)ident_info, &count) == KERN_SUCCESS;
80 }
81 
82 void
83 MachThreadList::DumpThreadStoppedReason (nub_thread_t tid) const
84 {
85     MachThreadSP thread_sp (GetThreadByID (tid));
86     if (thread_sp)
87         thread_sp->GetStopException().DumpStopReason();
88 }
89 
90 const char *
91 MachThreadList::GetThreadInfo (nub_thread_t tid) const
92 {
93     MachThreadSP thread_sp (GetThreadByID (tid));
94     if (thread_sp)
95         return thread_sp->GetBasicInfoAsString();
96     return NULL;
97 }
98 
99 MachThreadSP
100 MachThreadList::GetThreadByID (nub_thread_t tid) const
101 {
102     PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
103     MachThreadSP thread_sp;
104     const size_t num_threads = m_threads.size();
105     for (size_t idx = 0; idx < num_threads; ++idx)
106     {
107         if (m_threads[idx]->ThreadID() == tid)
108         {
109             thread_sp = m_threads[idx];
110             break;
111         }
112     }
113     return thread_sp;
114 }
115 
116 MachThreadSP
117 MachThreadList::GetThreadByMachPortNumber (thread_t mach_port_number) const
118 {
119     PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
120     MachThreadSP thread_sp;
121     const size_t num_threads = m_threads.size();
122     for (size_t idx = 0; idx < num_threads; ++idx)
123     {
124         if (m_threads[idx]->MachPortNumber() == mach_port_number)
125         {
126             thread_sp = m_threads[idx];
127             break;
128         }
129     }
130     return thread_sp;
131 }
132 
133 nub_thread_t
134 MachThreadList::GetThreadIDByMachPortNumber (thread_t mach_port_number) const
135 {
136     PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
137     MachThreadSP thread_sp;
138     const size_t num_threads = m_threads.size();
139     for (size_t idx = 0; idx < num_threads; ++idx)
140     {
141         if (m_threads[idx]->MachPortNumber() == mach_port_number)
142         {
143             return m_threads[idx]->ThreadID();
144         }
145     }
146     return INVALID_NUB_THREAD;
147 }
148 
149 thread_t
150 MachThreadList::GetMachPortNumberByThreadID (nub_thread_t globally_unique_id) const
151 {
152     PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
153     MachThreadSP thread_sp;
154     const size_t num_threads = m_threads.size();
155     for (size_t idx = 0; idx < num_threads; ++idx)
156     {
157         if (m_threads[idx]->ThreadID() == globally_unique_id)
158         {
159             return m_threads[idx]->MachPortNumber();
160         }
161     }
162     return 0;
163 }
164 
165 bool
166 MachThreadList::GetRegisterValue (nub_thread_t tid, uint32_t reg_set_idx, uint32_t reg_idx, DNBRegisterValue *reg_value ) const
167 {
168     MachThreadSP thread_sp (GetThreadByID (tid));
169     if (thread_sp)
170         return thread_sp->GetRegisterValue(reg_set_idx, reg_idx, reg_value);
171 
172     return false;
173 }
174 
175 bool
176 MachThreadList::SetRegisterValue (nub_thread_t tid, uint32_t reg_set_idx, uint32_t reg_idx, const DNBRegisterValue *reg_value ) const
177 {
178     MachThreadSP thread_sp (GetThreadByID (tid));
179     if (thread_sp)
180         return thread_sp->SetRegisterValue(reg_set_idx, reg_idx, reg_value);
181 
182     return false;
183 }
184 
185 nub_size_t
186 MachThreadList::GetRegisterContext (nub_thread_t tid, void *buf, size_t buf_len)
187 {
188     MachThreadSP thread_sp (GetThreadByID (tid));
189     if (thread_sp)
190         return thread_sp->GetRegisterContext (buf, buf_len);
191     return 0;
192 }
193 
194 nub_size_t
195 MachThreadList::SetRegisterContext (nub_thread_t tid, const void *buf, size_t buf_len)
196 {
197     MachThreadSP thread_sp (GetThreadByID (tid));
198     if (thread_sp)
199         return thread_sp->SetRegisterContext (buf, buf_len);
200     return 0;
201 }
202 
203 uint32_t
204 MachThreadList::SaveRegisterState (nub_thread_t tid)
205 {
206     MachThreadSP thread_sp (GetThreadByID (tid));
207     if (thread_sp)
208         return thread_sp->SaveRegisterState ();
209     return 0;
210 }
211 
212 bool
213 MachThreadList::RestoreRegisterState (nub_thread_t tid, uint32_t save_id)
214 {
215     MachThreadSP thread_sp (GetThreadByID (tid));
216     if (thread_sp)
217         return thread_sp->RestoreRegisterState (save_id);
218     return 0;
219 }
220 
221 
222 nub_size_t
223 MachThreadList::NumThreads () const
224 {
225     PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
226     return m_threads.size();
227 }
228 
229 nub_thread_t
230 MachThreadList::ThreadIDAtIndex (nub_size_t idx) const
231 {
232     PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
233     if (idx < m_threads.size())
234         return m_threads[idx]->ThreadID();
235     return INVALID_NUB_THREAD;
236 }
237 
238 nub_thread_t
239 MachThreadList::CurrentThreadID ( )
240 {
241     MachThreadSP thread_sp;
242     CurrentThread(thread_sp);
243     if (thread_sp.get())
244         return thread_sp->ThreadID();
245     return INVALID_NUB_THREAD;
246 }
247 
248 bool
249 MachThreadList::NotifyException(MachException::Data& exc)
250 {
251     MachThreadSP thread_sp (GetThreadByMachPortNumber (exc.thread_port));
252     if (thread_sp)
253     {
254         thread_sp->NotifyException(exc);
255         return true;
256     }
257     return false;
258 }
259 
260 void
261 MachThreadList::Clear()
262 {
263     PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
264     m_threads.clear();
265 }
266 
267 uint32_t
268 MachThreadList::UpdateThreadList(MachProcess *process, bool update, MachThreadList::collection *new_threads)
269 {
270     // locker will keep a mutex locked until it goes out of scope
271     DNBLogThreadedIf (LOG_THREAD, "MachThreadList::UpdateThreadList (pid = %4.4x, update = %u) process stop count = %u", process->ProcessID(), update, process->StopCount());
272     PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
273 
274     if (process->StopCount() == 0)
275     {
276         int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, process->ProcessID() };
277         struct kinfo_proc processInfo;
278         size_t bufsize = sizeof(processInfo);
279         bool is_64_bit = false;
280         if (sysctl(mib, (unsigned)(sizeof(mib)/sizeof(int)), &processInfo, &bufsize, NULL, 0) == 0 && bufsize > 0)
281         {
282             if (processInfo.kp_proc.p_flag & P_LP64)
283                 is_64_bit = true;
284         }
285 #if defined (__i386__) || defined (__x86_64__)
286         if (is_64_bit)
287             DNBArchProtocol::SetArchitecture(CPU_TYPE_X86_64);
288         else
289             DNBArchProtocol::SetArchitecture(CPU_TYPE_I386);
290 #elif defined (__arm__) || defined (__arm64__)
291         if (is_64_bit)
292             DNBArchProtocol::SetArchitecture(CPU_TYPE_ARM64);
293         else
294             DNBArchProtocol::SetArchitecture(CPU_TYPE_ARM);
295 #endif
296     }
297 
298     if (m_threads.empty() || update)
299     {
300         thread_array_t thread_list = NULL;
301         mach_msg_type_number_t thread_list_count = 0;
302         task_t task = process->Task().TaskPort();
303         DNBError err(::task_threads (task, &thread_list, &thread_list_count), DNBError::MachKernel);
304 
305         if (DNBLogCheckLogBit(LOG_THREAD) || err.Fail())
306             err.LogThreaded("::task_threads ( task = 0x%4.4x, thread_list => %p, thread_list_count => %u )", task, thread_list, thread_list_count);
307 
308         if (err.Error() == KERN_SUCCESS && thread_list_count > 0)
309         {
310             MachThreadList::collection currThreads;
311             size_t idx;
312             // Iterator through the current thread list and see which threads
313             // we already have in our list (keep them), which ones we don't
314             // (add them), and which ones are not around anymore (remove them).
315             for (idx = 0; idx < thread_list_count; ++idx)
316             {
317                 const thread_t mach_port_num = thread_list[idx];
318 
319                 uint64_t unique_thread_id = MachThread::GetGloballyUniqueThreadIDForMachPortID (mach_port_num);
320                 MachThreadSP thread_sp (GetThreadByID (unique_thread_id));
321                 if (thread_sp)
322                 {
323                     // Keep the existing thread class
324                     currThreads.push_back(thread_sp);
325                 }
326                 else
327                 {
328                     // We don't have this thread, lets add it.
329                     thread_sp.reset(new MachThread(process, unique_thread_id, mach_port_num));
330 
331                     // Add the new thread regardless of its is user ready state...
332                     // Make sure the thread is ready to be displayed and shown to users
333                     // before we add this thread to our list...
334                     if (thread_sp->IsUserReady())
335                     {
336                         if (new_threads)
337                             new_threads->push_back(thread_sp);
338 
339                         currThreads.push_back(thread_sp);
340                     }
341                 }
342             }
343 
344             m_threads.swap(currThreads);
345             m_current_thread.reset();
346 
347             // Free the vm memory given to us by ::task_threads()
348             vm_size_t thread_list_size = (vm_size_t) (thread_list_count * sizeof (thread_t));
349             ::vm_deallocate (::mach_task_self(),
350                              (vm_address_t)thread_list,
351                              thread_list_size);
352         }
353     }
354     return m_threads.size();
355 }
356 
357 
358 void
359 MachThreadList::CurrentThread (MachThreadSP& thread_sp)
360 {
361     // locker will keep a mutex locked until it goes out of scope
362     PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
363     if (m_current_thread.get() == NULL)
364     {
365         // Figure out which thread is going to be our current thread.
366         // This is currently done by finding the first thread in the list
367         // that has a valid exception.
368         const uint32_t num_threads = m_threads.size();
369         for (uint32_t idx = 0; idx < num_threads; ++idx)
370         {
371             if (m_threads[idx]->GetStopException().IsValid())
372             {
373                 m_current_thread = m_threads[idx];
374                 break;
375             }
376         }
377     }
378     thread_sp = m_current_thread;
379 }
380 
381 void
382 MachThreadList::Dump() const
383 {
384     PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
385     const uint32_t num_threads = m_threads.size();
386     for (uint32_t idx = 0; idx < num_threads; ++idx)
387     {
388         m_threads[idx]->Dump(idx);
389     }
390 }
391 
392 
393 void
394 MachThreadList::ProcessWillResume(MachProcess *process, const DNBThreadResumeActions &thread_actions)
395 {
396     PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
397 
398     // Update our thread list, because sometimes libdispatch or the kernel
399     // will spawn threads while a task is suspended.
400     MachThreadList::collection new_threads;
401 
402     // First figure out if we were planning on running only one thread, and if so force that thread to resume.
403     bool run_one_thread;
404     nub_thread_t solo_thread = INVALID_NUB_THREAD;
405     if (thread_actions.GetSize() > 0
406         && thread_actions.NumActionsWithState(eStateStepping) + thread_actions.NumActionsWithState (eStateRunning) == 1)
407     {
408         run_one_thread = true;
409         const DNBThreadResumeAction *action_ptr = thread_actions.GetFirst();
410         size_t num_actions = thread_actions.GetSize();
411         for (size_t i = 0; i < num_actions; i++, action_ptr++)
412         {
413             if (action_ptr->state == eStateStepping || action_ptr->state == eStateRunning)
414             {
415                 solo_thread = action_ptr->tid;
416                 break;
417             }
418         }
419     }
420     else
421         run_one_thread = false;
422 
423     UpdateThreadList(process, true, &new_threads);
424 
425     DNBThreadResumeAction resume_new_threads = { -1U, eStateRunning, 0, INVALID_NUB_ADDRESS };
426     // If we are planning to run only one thread, any new threads should be suspended.
427     if (run_one_thread)
428         resume_new_threads.state = eStateSuspended;
429 
430     const uint32_t num_new_threads = new_threads.size();
431     const uint32_t num_threads = m_threads.size();
432     for (uint32_t idx = 0; idx < num_threads; ++idx)
433     {
434         MachThread *thread = m_threads[idx].get();
435         bool handled = false;
436         for (uint32_t new_idx = 0; new_idx < num_new_threads; ++new_idx)
437         {
438             if (thread == new_threads[new_idx].get())
439             {
440                 thread->ThreadWillResume(&resume_new_threads);
441                 handled = true;
442                 break;
443             }
444         }
445 
446         if (!handled)
447         {
448             const DNBThreadResumeAction *thread_action = thread_actions.GetActionForThread (thread->ThreadID(), true);
449             // There must always be a thread action for every thread.
450             assert (thread_action);
451             bool others_stopped = false;
452             if (solo_thread == thread->ThreadID())
453                 others_stopped = true;
454             thread->ThreadWillResume (thread_action, others_stopped);
455         }
456     }
457 
458     if (new_threads.size())
459     {
460         for (uint32_t idx = 0; idx < num_new_threads; ++idx)
461         {
462             DNBLogThreadedIf (LOG_THREAD, "MachThreadList::ProcessWillResume (pid = %4.4x) stop-id=%u, resuming newly discovered thread: 0x%8.8" PRIx64 ", thread-is-user-ready=%i)",
463                               process->ProcessID(),
464                               process->StopCount(),
465                               new_threads[idx]->ThreadID(),
466                               new_threads[idx]->IsUserReady());
467         }
468     }
469 }
470 
471 uint32_t
472 MachThreadList::ProcessDidStop(MachProcess *process)
473 {
474     PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
475     // Update our thread list
476     const uint32_t num_threads = UpdateThreadList(process, true);
477     for (uint32_t idx = 0; idx < num_threads; ++idx)
478     {
479         m_threads[idx]->ThreadDidStop();
480     }
481     return num_threads;
482 }
483 
484 //----------------------------------------------------------------------
485 // Check each thread in our thread list to see if we should notify our
486 // client of the current halt in execution.
487 //
488 // Breakpoints can have callback functions associated with them than
489 // can return true to stop, or false to continue executing the inferior.
490 //
491 // RETURNS
492 //    true if we should stop and notify our clients
493 //    false if we should resume our child process and skip notification
494 //----------------------------------------------------------------------
495 bool
496 MachThreadList::ShouldStop(bool &step_more)
497 {
498     PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
499     uint32_t should_stop = false;
500     const uint32_t num_threads = m_threads.size();
501     for (uint32_t idx = 0; !should_stop && idx < num_threads; ++idx)
502     {
503         should_stop = m_threads[idx]->ShouldStop(step_more);
504     }
505     return should_stop;
506 }
507 
508 
509 void
510 MachThreadList::NotifyBreakpointChanged (const DNBBreakpoint *bp)
511 {
512     PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
513     const uint32_t num_threads = m_threads.size();
514     for (uint32_t idx = 0; idx < num_threads; ++idx)
515     {
516         m_threads[idx]->NotifyBreakpointChanged(bp);
517     }
518 }
519 
520 
521 uint32_t
522 MachThreadList::EnableHardwareBreakpoint (const DNBBreakpoint* bp) const
523 {
524     if (bp != NULL)
525     {
526         const uint32_t num_threads = m_threads.size();
527         for (uint32_t idx = 0; idx < num_threads; ++idx)
528             m_threads[idx]->EnableHardwareBreakpoint(bp);
529     }
530     return INVALID_NUB_HW_INDEX;
531 }
532 
533 bool
534 MachThreadList::DisableHardwareBreakpoint (const DNBBreakpoint* bp) const
535 {
536     if (bp != NULL)
537     {
538         const uint32_t num_threads = m_threads.size();
539         for (uint32_t idx = 0; idx < num_threads; ++idx)
540             m_threads[idx]->DisableHardwareBreakpoint(bp);
541     }
542     return false;
543 }
544 
545 // DNBWatchpointSet() -> MachProcess::CreateWatchpoint() -> MachProcess::EnableWatchpoint()
546 // -> MachThreadList::EnableHardwareWatchpoint().
547 uint32_t
548 MachThreadList::EnableHardwareWatchpoint (const DNBBreakpoint* wp) const
549 {
550     uint32_t hw_index = INVALID_NUB_HW_INDEX;
551     if (wp != NULL)
552     {
553         PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
554         const uint32_t num_threads = m_threads.size();
555         // On Mac OS X we have to prime the control registers for new threads.  We do this
556         // using the control register data for the first thread, for lack of a better way of choosing.
557         bool also_set_on_task = true;
558         for (uint32_t idx = 0; idx < num_threads; ++idx)
559         {
560             if ((hw_index = m_threads[idx]->EnableHardwareWatchpoint(wp, also_set_on_task)) == INVALID_NUB_HW_INDEX)
561             {
562                 // We know that idx failed for some reason.  Let's rollback the transaction for [0, idx).
563                 for (uint32_t i = 0; i < idx; ++i)
564                     m_threads[i]->RollbackTransForHWP();
565                 return INVALID_NUB_HW_INDEX;
566             }
567             also_set_on_task = false;
568         }
569         // Notify each thread to commit the pending transaction.
570         for (uint32_t idx = 0; idx < num_threads; ++idx)
571             m_threads[idx]->FinishTransForHWP();
572 
573     }
574     return hw_index;
575 }
576 
577 bool
578 MachThreadList::DisableHardwareWatchpoint (const DNBBreakpoint* wp) const
579 {
580     if (wp != NULL)
581     {
582         PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
583         const uint32_t num_threads = m_threads.size();
584 
585         // On Mac OS X we have to prime the control registers for new threads.  We do this
586         // using the control register data for the first thread, for lack of a better way of choosing.
587         bool also_set_on_task = true;
588         for (uint32_t idx = 0; idx < num_threads; ++idx)
589         {
590             if (!m_threads[idx]->DisableHardwareWatchpoint(wp, also_set_on_task))
591             {
592                 // We know that idx failed for some reason.  Let's rollback the transaction for [0, idx).
593                 for (uint32_t i = 0; i < idx; ++i)
594                     m_threads[i]->RollbackTransForHWP();
595                 return false;
596             }
597             also_set_on_task = false;
598         }
599         // Notify each thread to commit the pending transaction.
600         for (uint32_t idx = 0; idx < num_threads; ++idx)
601             m_threads[idx]->FinishTransForHWP();
602 
603         return true;
604     }
605     return false;
606 }
607 
608 uint32_t
609 MachThreadList::NumSupportedHardwareWatchpoints () const
610 {
611     PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
612     const uint32_t num_threads = m_threads.size();
613     // Use an arbitrary thread to retrieve the number of supported hardware watchpoints.
614     if (num_threads)
615         return m_threads[0]->NumSupportedHardwareWatchpoints();
616     return 0;
617 }
618 
619 uint32_t
620 MachThreadList::GetThreadIndexForThreadStoppedWithSignal (const int signo) const
621 {
622     PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
623     uint32_t should_stop = false;
624     const uint32_t num_threads = m_threads.size();
625     for (uint32_t idx = 0; !should_stop && idx < num_threads; ++idx)
626     {
627         if (m_threads[idx]->GetStopException().SoftSignal () == signo)
628             return idx;
629     }
630     return UINT32_MAX;
631 }
632 
633