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