1 //===-- NativeThreadListDarwin.cpp ------------------------------------*- C++
4 // The LLVM Compiler Infrastructure
6 // This file is distributed under the University of Illinois Open Source
7 // License. See LICENSE.TXT for details.
9 //===----------------------------------------------------------------------===//
11 // Created by Greg Clayton on 6/19/07.
13 //===----------------------------------------------------------------------===//
15 #include "NativeThreadListDarwin.h"
19 #include <mach/vm_map.h>
20 #include <sys/sysctl.h>
23 #include "lldb/Utility/Log.h"
24 #include "lldb/Utility/Status.h"
25 #include "lldb/Utility/Stream.h"
26 #include "lldb/lldb-enumerations.h"
28 #include "NativeProcessDarwin.h"
29 #include "NativeThreadDarwin.h"
32 using namespace lldb_private;
33 using namespace lldb_private::process_darwin;
35 NativeThreadListDarwin::NativeThreadListDarwin()
36 : m_threads(), m_threads_mutex(), m_is_64_bit(false) {}
38 NativeThreadListDarwin::~NativeThreadListDarwin() {}
40 // These methods will be accessed directly from NativeThreadDarwin
43 NativeThreadListDarwin::GetState(nub_thread_t tid)
45 MachThreadSP thread_sp (GetThreadByID (tid));
47 return thread_sp->GetState();
52 NativeThreadListDarwin::GetName (nub_thread_t tid)
54 MachThreadSP thread_sp (GetThreadByID (tid));
56 return thread_sp->GetName();
61 // TODO: figure out if we need to add this to NativeThreadDarwin yet.
64 NativeThreadListDarwin::GetRequestedQoS (nub_thread_t tid, nub_addr_t tsd, uint64_t dti_qos_class_index)
66 MachThreadSP thread_sp (GetThreadByID (tid));
68 return thread_sp->GetRequestedQoS(tsd, dti_qos_class_index);
69 return ThreadInfo::QoS();
73 NativeThreadListDarwin::GetPThreadT (nub_thread_t tid)
75 MachThreadSP thread_sp (GetThreadByID (tid));
77 return thread_sp->GetPThreadT();
78 return INVALID_NUB_ADDRESS;
82 NativeThreadListDarwin::GetDispatchQueueT (nub_thread_t tid)
84 MachThreadSP thread_sp (GetThreadByID (tid));
86 return thread_sp->GetDispatchQueueT();
87 return INVALID_NUB_ADDRESS;
91 NativeThreadListDarwin::GetTSDAddressForThread (nub_thread_t tid, uint64_t plo_pthread_tsd_base_address_offset, uint64_t plo_pthread_tsd_base_offset, uint64_t plo_pthread_tsd_entry_size)
93 MachThreadSP thread_sp (GetThreadByID (tid));
95 return thread_sp->GetTSDAddressForThread(plo_pthread_tsd_base_address_offset, plo_pthread_tsd_base_offset, plo_pthread_tsd_entry_size);
96 return INVALID_NUB_ADDRESS;
100 // TODO implement these
103 NativeThreadListDarwin::SetCurrentThread(nub_thread_t tid)
105 MachThreadSP thread_sp (GetThreadByID (tid));
108 m_current_thread = thread_sp;
111 return INVALID_NUB_THREAD;
116 NativeThreadListDarwin::GetThreadStoppedReason(nub_thread_t tid, struct DNBThreadStopInfo *stop_info) const
118 MachThreadSP thread_sp (GetThreadByID (tid));
120 return thread_sp->GetStopException().GetStopInfo(stop_info);
125 NativeThreadListDarwin::GetIdentifierInfo (nub_thread_t tid, thread_identifier_info_data_t *ident_info)
127 thread_t mach_port_number = GetMachPortNumberByThreadID (tid);
129 mach_msg_type_number_t count = THREAD_IDENTIFIER_INFO_COUNT;
130 return ::thread_info (mach_port_number, THREAD_IDENTIFIER_INFO, (thread_info_t)ident_info, &count) == KERN_SUCCESS;
134 NativeThreadListDarwin::DumpThreadStoppedReason (nub_thread_t tid) const
136 MachThreadSP thread_sp (GetThreadByID (tid));
138 thread_sp->GetStopException().DumpStopReason();
142 NativeThreadListDarwin::GetThreadInfo (nub_thread_t tid) const
144 MachThreadSP thread_sp (GetThreadByID (tid));
146 return thread_sp->GetBasicInfoAsString();
153 NativeThreadListDarwin::GetThreadByID(lldb::tid_t tid) const {
154 std::lock_guard<std::recursive_mutex> locker(m_threads_mutex);
155 for (auto thread_sp : m_threads) {
156 if (thread_sp && (thread_sp->GetID() == tid))
159 return NativeThreadDarwinSP();
162 NativeThreadDarwinSP NativeThreadListDarwin::GetThreadByMachPortNumber(
163 ::thread_t mach_port_number) const {
164 std::lock_guard<std::recursive_mutex> locker(m_threads_mutex);
165 for (auto thread_sp : m_threads) {
166 if (thread_sp && (thread_sp->GetMachPortNumber() == mach_port_number))
169 return NativeThreadDarwinSP();
172 lldb::tid_t NativeThreadListDarwin::GetThreadIDByMachPortNumber(
173 ::thread_t mach_port_number) const {
174 std::lock_guard<std::recursive_mutex> locker(m_threads_mutex);
175 for (auto thread_sp : m_threads) {
176 if (thread_sp && (thread_sp->GetMachPortNumber() == mach_port_number))
177 return thread_sp->GetID();
179 return LLDB_INVALID_THREAD_ID;
185 NativeThreadListDarwin::GetMachPortNumberByThreadID (nub_thread_t globally_unique_id) const
187 PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
188 MachThreadSP thread_sp;
189 const size_t num_threads = m_threads.size();
190 for (size_t idx = 0; idx < num_threads; ++idx)
192 if (m_threads[idx]->ThreadID() == globally_unique_id)
194 return m_threads[idx]->MachPortNumber();
201 NativeThreadListDarwin::GetRegisterValue (nub_thread_t tid, uint32_t set, uint32_t reg, DNBRegisterValue *reg_value ) const
203 MachThreadSP thread_sp (GetThreadByID (tid));
205 return thread_sp->GetRegisterValue(set, reg, reg_value);
211 NativeThreadListDarwin::SetRegisterValue (nub_thread_t tid, uint32_t set, uint32_t reg, const DNBRegisterValue *reg_value ) const
213 MachThreadSP thread_sp (GetThreadByID (tid));
215 return thread_sp->SetRegisterValue(set, reg, reg_value);
221 NativeThreadListDarwin::GetRegisterContext (nub_thread_t tid, void *buf, size_t buf_len)
223 MachThreadSP thread_sp (GetThreadByID (tid));
225 return thread_sp->GetRegisterContext (buf, buf_len);
230 NativeThreadListDarwin::SetRegisterContext (nub_thread_t tid, const void *buf, size_t buf_len)
232 MachThreadSP thread_sp (GetThreadByID (tid));
234 return thread_sp->SetRegisterContext (buf, buf_len);
239 NativeThreadListDarwin::SaveRegisterState (nub_thread_t tid)
241 MachThreadSP thread_sp (GetThreadByID (tid));
243 return thread_sp->SaveRegisterState ();
248 NativeThreadListDarwin::RestoreRegisterState (nub_thread_t tid, uint32_t save_id)
250 MachThreadSP thread_sp (GetThreadByID (tid));
252 return thread_sp->RestoreRegisterState (save_id);
257 size_t NativeThreadListDarwin::GetNumberOfThreads() const {
258 std::lock_guard<std::recursive_mutex> locker(m_threads_mutex);
259 return static_cast<size_t>(m_threads.size());
265 NativeThreadListDarwin::ThreadIDAtIndex (nub_size_t idx) const
267 PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
268 if (idx < m_threads.size())
269 return m_threads[idx]->ThreadID();
270 return INVALID_NUB_THREAD;
274 NativeThreadListDarwin::CurrentThreadID ( )
276 MachThreadSP thread_sp;
277 CurrentThread(thread_sp);
279 return thread_sp->ThreadID();
280 return INVALID_NUB_THREAD;
285 bool NativeThreadListDarwin::NotifyException(MachException::Data &exc) {
286 auto thread_sp = GetThreadByMachPortNumber(exc.thread_port);
288 thread_sp->NotifyException(exc);
294 void NativeThreadListDarwin::Clear() {
295 std::lock_guard<std::recursive_mutex> locker(m_threads_mutex);
299 uint32_t NativeThreadListDarwin::UpdateThreadList(NativeProcessDarwin &process,
301 collection *new_threads) {
302 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD));
304 std::lock_guard<std::recursive_mutex> locker(m_threads_mutex);
306 log->Printf("NativeThreadListDarwin::%s() (pid = %" PRIu64 ", update = "
307 "%u) process stop count = %u",
308 __FUNCTION__, process.GetID(), update, process.GetStopID());
310 if (process.GetStopID() == 0) {
311 // On our first stop, we'll record details like 32/64 bitness and
312 // select the proper architecture implementation.
314 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, (int)process.GetID()};
316 struct kinfo_proc processInfo;
317 size_t bufsize = sizeof(processInfo);
318 if ((sysctl(mib, (unsigned)(sizeof(mib) / sizeof(int)), &processInfo,
319 &bufsize, NULL, 0) == 0) &&
321 if (processInfo.kp_proc.p_flag & P_LP64)
325 // TODO implement architecture selection and abstraction.
327 #if defined(__i386__) || defined(__x86_64__)
329 DNBArchProtocol::SetArchitecture(CPU_TYPE_X86_64);
331 DNBArchProtocol::SetArchitecture(CPU_TYPE_I386);
332 #elif defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
334 DNBArchProtocol::SetArchitecture(CPU_TYPE_ARM64);
336 DNBArchProtocol::SetArchitecture(CPU_TYPE_ARM);
341 if (m_threads.empty() || update) {
342 thread_array_t thread_list = nullptr;
343 mach_msg_type_number_t thread_list_count = 0;
344 task_t task = process.GetTask();
347 auto mach_err = ::task_threads(task, &thread_list, &thread_list_count);
348 error.SetError(mach_err, eErrorTypeMachKernel);
351 log->Printf("::task_threads(task = 0x%4.4x, thread_list => %p, "
352 "thread_list_count => %u) failed: %u (%s)",
353 task, thread_list, thread_list_count, error.GetError(),
358 if (thread_list_count > 0) {
359 collection currThreads;
361 // Iterator through the current thread list and see which threads
362 // we already have in our list (keep them), which ones we don't
363 // (add them), and which ones are not around anymore (remove them).
364 for (idx = 0; idx < thread_list_count; ++idx) {
365 // Get the Mach thread port.
366 const ::thread_t mach_port_num = thread_list[idx];
368 // Get the unique thread id for the mach port number.
369 uint64_t unique_thread_id =
370 NativeThreadDarwin::GetGloballyUniqueThreadIDForMachPortID(
373 // Retrieve the thread if it exists.
374 auto thread_sp = GetThreadByID(unique_thread_id);
376 // We are already tracking it. Keep the existing native
378 currThreads.push_back(thread_sp);
380 // We don't have a native thread instance for this thread.
382 thread_sp.reset(new NativeThreadDarwin(
383 &process, m_is_64_bit, unique_thread_id, mach_port_num));
385 // Add the new thread regardless of its is user ready state.
386 // Make sure the thread is ready to be displayed and shown
387 // to users before we add this thread to our list...
388 if (thread_sp->IsUserReady()) {
390 new_threads->push_back(thread_sp);
392 currThreads.push_back(thread_sp);
397 m_threads.swap(currThreads);
398 m_current_thread.reset();
400 // Free the vm memory given to us by ::task_threads()
401 vm_size_t thread_list_size =
402 (vm_size_t)(thread_list_count * sizeof(::thread_t));
403 ::vm_deallocate(::mach_task_self(), (vm_address_t)thread_list,
407 return static_cast<uint32_t>(m_threads.size());
414 NativeThreadListDarwin::CurrentThread (MachThreadSP& thread_sp)
416 // locker will keep a mutex locked until it goes out of scope
417 PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
418 if (m_current_thread.get() == NULL)
420 // Figure out which thread is going to be our current thread.
421 // This is currently done by finding the first thread in the list
422 // that has a valid exception.
423 const size_t num_threads = m_threads.size();
424 for (uint32_t idx = 0; idx < num_threads; ++idx)
426 if (m_threads[idx]->GetStopException().IsValid())
428 m_current_thread = m_threads[idx];
433 thread_sp = m_current_thread;
438 void NativeThreadListDarwin::Dump(Stream &stream) const {
441 std::lock_guard<std::recursive_mutex> locker(m_threads_mutex);
442 for (auto thread_sp : m_threads) {
444 // Handle newlines between thread entries.
448 stream.PutChar('\n');
449 thread_sp->Dump(stream);
454 void NativeThreadListDarwin::ProcessWillResume(
455 NativeProcessDarwin &process, const ResumeActionList &thread_actions) {
456 std::lock_guard<std::recursive_mutex> locker(m_threads_mutex);
458 // Update our thread list, because sometimes libdispatch or the kernel
459 // will spawn threads while a task is suspended.
460 NativeThreadListDarwin::collection new_threads;
462 // TODO implement this.
464 // First figure out if we were planning on running only one thread, and if
465 // so, force that thread to resume.
467 thread_t solo_thread = THREAD_NULL;
468 if ((thread_actions.GetSize() > 0) &&
469 (thread_actions.NumActionsWithState(eStateStepping) +
470 thread_actions.NumActionsWithState (eStateRunning) == 1))
472 run_one_thread = true;
473 const DNBThreadResumeAction *action_ptr = thread_actions.GetFirst();
474 size_t num_actions = thread_actions.GetSize();
475 for (size_t i = 0; i < num_actions; i++, action_ptr++)
477 if (action_ptr->state == eStateStepping || action_ptr->state == eStateRunning)
479 solo_thread = action_ptr->tid;
485 run_one_thread = false;
488 UpdateThreadList(process, true, &new_threads);
491 DNBThreadResumeAction resume_new_threads = { -1U, eStateRunning, 0, INVALID_NUB_ADDRESS };
492 // If we are planning to run only one thread, any new threads should be suspended.
494 resume_new_threads.state = eStateSuspended;
496 const size_t num_new_threads = new_threads.size();
497 const size_t num_threads = m_threads.size();
498 for (uint32_t idx = 0; idx < num_threads; ++idx)
500 MachThread *thread = m_threads[idx].get();
501 bool handled = false;
502 for (uint32_t new_idx = 0; new_idx < num_new_threads; ++new_idx)
504 if (thread == new_threads[new_idx].get())
506 thread->ThreadWillResume(&resume_new_threads);
514 const DNBThreadResumeAction *thread_action = thread_actions.GetActionForThread (thread->ThreadID(), true);
515 // There must always be a thread action for every thread.
516 assert (thread_action);
517 bool others_stopped = false;
518 if (solo_thread == thread->ThreadID())
519 others_stopped = true;
520 thread->ThreadWillResume (thread_action, others_stopped);
524 if (new_threads.size())
526 for (uint32_t idx = 0; idx < num_new_threads; ++idx)
528 DNBLogThreadedIf (LOG_THREAD, "NativeThreadListDarwin::ProcessWillResume (pid = %4.4x) stop-id=%u, resuming newly discovered thread: 0x%8.8" PRIx64 ", thread-is-user-ready=%i)",
529 process->ProcessID(),
530 process->StopCount(),
531 new_threads[idx]->ThreadID(),
532 new_threads[idx]->IsUserReady());
538 uint32_t NativeThreadListDarwin::ProcessDidStop(NativeProcessDarwin &process) {
539 std::lock_guard<std::recursive_mutex> locker(m_threads_mutex);
541 // Update our thread list.
542 UpdateThreadList(process, true);
544 for (auto thread_sp : m_threads) {
546 thread_sp->ThreadDidStop();
548 return (uint32_t)m_threads.size();
551 //----------------------------------------------------------------------
552 // Check each thread in our thread list to see if we should notify our
553 // client of the current halt in execution.
555 // Breakpoints can have callback functions associated with them than
556 // can return true to stop, or false to continue executing the inferior.
559 // true if we should stop and notify our clients
560 // false if we should resume our child process and skip notification
561 //----------------------------------------------------------------------
562 bool NativeThreadListDarwin::ShouldStop(bool &step_more) {
563 std::lock_guard<std::recursive_mutex> locker(m_threads_mutex);
564 for (auto thread_sp : m_threads) {
565 if (thread_sp && thread_sp->ShouldStop(step_more))
575 NativeThreadListDarwin::NotifyBreakpointChanged (const DNBBreakpoint *bp)
577 PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
578 const size_t num_threads = m_threads.size();
579 for (uint32_t idx = 0; idx < num_threads; ++idx)
581 m_threads[idx]->NotifyBreakpointChanged(bp);
587 NativeThreadListDarwin::EnableHardwareBreakpoint (const DNBBreakpoint* bp) const
591 const size_t num_threads = m_threads.size();
592 for (uint32_t idx = 0; idx < num_threads; ++idx)
593 m_threads[idx]->EnableHardwareBreakpoint(bp);
595 return INVALID_NUB_HW_INDEX;
599 NativeThreadListDarwin::DisableHardwareBreakpoint (const DNBBreakpoint* bp) const
603 const size_t num_threads = m_threads.size();
604 for (uint32_t idx = 0; idx < num_threads; ++idx)
605 m_threads[idx]->DisableHardwareBreakpoint(bp);
610 // DNBWatchpointSet() -> MachProcess::CreateWatchpoint() -> MachProcess::EnableWatchpoint()
611 // -> NativeThreadListDarwin::EnableHardwareWatchpoint().
613 NativeThreadListDarwin::EnableHardwareWatchpoint (const DNBBreakpoint* wp) const
615 uint32_t hw_index = INVALID_NUB_HW_INDEX;
618 PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
619 const size_t num_threads = m_threads.size();
620 // On Mac OS X we have to prime the control registers for new threads. We do this
621 // using the control register data for the first thread, for lack of a better way of choosing.
622 bool also_set_on_task = true;
623 for (uint32_t idx = 0; idx < num_threads; ++idx)
625 if ((hw_index = m_threads[idx]->EnableHardwareWatchpoint(wp, also_set_on_task)) == INVALID_NUB_HW_INDEX)
627 // We know that idx failed for some reason. Let's rollback the transaction for [0, idx).
628 for (uint32_t i = 0; i < idx; ++i)
629 m_threads[i]->RollbackTransForHWP();
630 return INVALID_NUB_HW_INDEX;
632 also_set_on_task = false;
634 // Notify each thread to commit the pending transaction.
635 for (uint32_t idx = 0; idx < num_threads; ++idx)
636 m_threads[idx]->FinishTransForHWP();
643 NativeThreadListDarwin::DisableHardwareWatchpoint (const DNBBreakpoint* wp) const
647 PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
648 const size_t num_threads = m_threads.size();
650 // On Mac OS X we have to prime the control registers for new threads. We do this
651 // using the control register data for the first thread, for lack of a better way of choosing.
652 bool also_set_on_task = true;
653 for (uint32_t idx = 0; idx < num_threads; ++idx)
655 if (!m_threads[idx]->DisableHardwareWatchpoint(wp, also_set_on_task))
657 // We know that idx failed for some reason. Let's rollback the transaction for [0, idx).
658 for (uint32_t i = 0; i < idx; ++i)
659 m_threads[i]->RollbackTransForHWP();
662 also_set_on_task = false;
664 // Notify each thread to commit the pending transaction.
665 for (uint32_t idx = 0; idx < num_threads; ++idx)
666 m_threads[idx]->FinishTransForHWP();
674 NativeThreadListDarwin::NumSupportedHardwareWatchpoints () const
676 PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
677 const size_t num_threads = m_threads.size();
678 // Use an arbitrary thread to retrieve the number of supported hardware watchpoints.
680 return m_threads[0]->NumSupportedHardwareWatchpoints();
685 NativeThreadListDarwin::GetThreadIndexForThreadStoppedWithSignal (const int signo) const
687 PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
688 uint32_t should_stop = false;
689 const size_t num_threads = m_threads.size();
690 for (uint32_t idx = 0; !should_stop && idx < num_threads; ++idx)
692 if (m_threads[idx]->GetStopException().SoftSignal () == signo)