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 select
312 // 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 we
362 // already have in our list (keep them), which ones we don't (add them),
363 // 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 thread
378 currThreads.push_back(thread_sp);
380 // We don't have a native thread instance for this thread. Create it
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. Make
386 // sure the thread is ready to be displayed and shown to users before
387 // 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. This is
421 // currently done by finding the first thread in the list that has a
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 will
459 // 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
495 resume_new_threads.state = eStateSuspended;
497 const size_t num_new_threads = new_threads.size();
498 const size_t num_threads = m_threads.size();
499 for (uint32_t idx = 0; idx < num_threads; ++idx)
501 MachThread *thread = m_threads[idx].get();
502 bool handled = false;
503 for (uint32_t new_idx = 0; new_idx < num_new_threads; ++new_idx)
505 if (thread == new_threads[new_idx].get())
507 thread->ThreadWillResume(&resume_new_threads);
515 const DNBThreadResumeAction *thread_action = thread_actions.GetActionForThread (thread->ThreadID(), true);
516 // There must always be a thread action for every thread.
517 assert (thread_action);
518 bool others_stopped = false;
519 if (solo_thread == thread->ThreadID())
520 others_stopped = true;
521 thread->ThreadWillResume (thread_action, others_stopped);
525 if (new_threads.size())
527 for (uint32_t idx = 0; idx < num_new_threads; ++idx)
529 DNBLogThreadedIf (LOG_THREAD, "NativeThreadListDarwin::ProcessWillResume (pid = %4.4x) stop-id=%u, resuming newly discovered thread: 0x%8.8" PRIx64 ", thread-is-user-ready=%i)",
530 process->ProcessID(),
531 process->StopCount(),
532 new_threads[idx]->ThreadID(),
533 new_threads[idx]->IsUserReady());
539 uint32_t NativeThreadListDarwin::ProcessDidStop(NativeProcessDarwin &process) {
540 std::lock_guard<std::recursive_mutex> locker(m_threads_mutex);
542 // Update our thread list.
543 UpdateThreadList(process, true);
545 for (auto thread_sp : m_threads) {
547 thread_sp->ThreadDidStop();
549 return (uint32_t)m_threads.size();
552 //----------------------------------------------------------------------
553 // Check each thread in our thread list to see if we should notify our client
554 // of the current halt in execution.
556 // Breakpoints can have callback functions associated with them than can return
557 // true to stop, or false to continue executing the inferior.
560 // true if we should stop and notify our clients
561 // false if we should resume our child process and skip notification
562 //----------------------------------------------------------------------
563 bool NativeThreadListDarwin::ShouldStop(bool &step_more) {
564 std::lock_guard<std::recursive_mutex> locker(m_threads_mutex);
565 for (auto thread_sp : m_threads) {
566 if (thread_sp && thread_sp->ShouldStop(step_more))
576 NativeThreadListDarwin::NotifyBreakpointChanged (const DNBBreakpoint *bp)
578 PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
579 const size_t num_threads = m_threads.size();
580 for (uint32_t idx = 0; idx < num_threads; ++idx)
582 m_threads[idx]->NotifyBreakpointChanged(bp);
588 NativeThreadListDarwin::EnableHardwareBreakpoint (const DNBBreakpoint* bp) const
592 const size_t num_threads = m_threads.size();
593 for (uint32_t idx = 0; idx < num_threads; ++idx)
594 m_threads[idx]->EnableHardwareBreakpoint(bp);
596 return INVALID_NUB_HW_INDEX;
600 NativeThreadListDarwin::DisableHardwareBreakpoint (const DNBBreakpoint* bp) const
604 const size_t num_threads = m_threads.size();
605 for (uint32_t idx = 0; idx < num_threads; ++idx)
606 m_threads[idx]->DisableHardwareBreakpoint(bp);
611 // DNBWatchpointSet() -> MachProcess::CreateWatchpoint() ->
612 // MachProcess::EnableWatchpoint() ->
613 // NativeThreadListDarwin::EnableHardwareWatchpoint().
615 NativeThreadListDarwin::EnableHardwareWatchpoint (const DNBBreakpoint* wp) const
617 uint32_t hw_index = INVALID_NUB_HW_INDEX;
620 PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
621 const size_t num_threads = m_threads.size();
622 // On Mac OS X we have to prime the control registers for new threads.
623 // We do this using the control register data for the first thread, for
624 // lack of a better way of choosing.
625 bool also_set_on_task = true;
626 for (uint32_t idx = 0; idx < num_threads; ++idx)
628 if ((hw_index = m_threads[idx]->EnableHardwareWatchpoint(wp, also_set_on_task)) == INVALID_NUB_HW_INDEX)
630 // We know that idx failed for some reason. Let's rollback the
631 // transaction for [0, idx).
632 for (uint32_t i = 0; i < idx; ++i)
633 m_threads[i]->RollbackTransForHWP();
634 return INVALID_NUB_HW_INDEX;
636 also_set_on_task = false;
638 // Notify each thread to commit the pending transaction.
639 for (uint32_t idx = 0; idx < num_threads; ++idx)
640 m_threads[idx]->FinishTransForHWP();
647 NativeThreadListDarwin::DisableHardwareWatchpoint (const DNBBreakpoint* wp) const
651 PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
652 const size_t num_threads = m_threads.size();
654 // On Mac OS X we have to prime the control registers for new threads.
655 // We do this using the control register data for the first thread, for
656 // lack of a better way of choosing.
657 bool also_set_on_task = true;
658 for (uint32_t idx = 0; idx < num_threads; ++idx)
660 if (!m_threads[idx]->DisableHardwareWatchpoint(wp, also_set_on_task))
662 // We know that idx failed for some reason. Let's rollback the
663 // transaction for [0, idx).
664 for (uint32_t i = 0; i < idx; ++i)
665 m_threads[i]->RollbackTransForHWP();
668 also_set_on_task = false;
670 // Notify each thread to commit the pending transaction.
671 for (uint32_t idx = 0; idx < num_threads; ++idx)
672 m_threads[idx]->FinishTransForHWP();
680 NativeThreadListDarwin::NumSupportedHardwareWatchpoints () const
682 PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
683 const size_t num_threads = m_threads.size();
684 // Use an arbitrary thread to retrieve the number of supported hardware
687 return m_threads[0]->NumSupportedHardwareWatchpoints();
692 NativeThreadListDarwin::GetThreadIndexForThreadStoppedWithSignal (const int signo) const
694 PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
695 uint32_t should_stop = false;
696 const size_t num_threads = m_threads.size();
697 for (uint32_t idx = 0; !should_stop && idx < num_threads; ++idx)
699 if (m_threads[idx]->GetStopException().SoftSignal () == signo)