1 //===-- NativeThreadListDarwin.cpp ------------------------------------*- C++
4 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5 // See https://llvm.org/LICENSE.txt for license information.
6 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
8 //===----------------------------------------------------------------------===//
10 // Created by Greg Clayton on 6/19/07.
12 //===----------------------------------------------------------------------===//
14 #include "NativeThreadListDarwin.h"
18 #include <mach/vm_map.h>
19 #include <sys/sysctl.h>
22 #include "lldb/Utility/Log.h"
23 #include "lldb/Utility/Status.h"
24 #include "lldb/Utility/Stream.h"
25 #include "lldb/lldb-enumerations.h"
27 #include "NativeProcessDarwin.h"
28 #include "NativeThreadDarwin.h"
31 using namespace lldb_private;
32 using namespace lldb_private::process_darwin;
34 NativeThreadListDarwin::NativeThreadListDarwin()
35 : m_threads(), m_threads_mutex(), m_is_64_bit(false) {}
37 NativeThreadListDarwin::~NativeThreadListDarwin() {}
39 // These methods will be accessed directly from NativeThreadDarwin
42 NativeThreadListDarwin::GetState(nub_thread_t tid)
44 MachThreadSP thread_sp (GetThreadByID (tid));
46 return thread_sp->GetState();
51 NativeThreadListDarwin::GetName (nub_thread_t tid)
53 MachThreadSP thread_sp (GetThreadByID (tid));
55 return thread_sp->GetName();
60 // TODO: figure out if we need to add this to NativeThreadDarwin yet.
63 NativeThreadListDarwin::GetRequestedQoS (nub_thread_t tid, nub_addr_t tsd, uint64_t dti_qos_class_index)
65 MachThreadSP thread_sp (GetThreadByID (tid));
67 return thread_sp->GetRequestedQoS(tsd, dti_qos_class_index);
68 return ThreadInfo::QoS();
72 NativeThreadListDarwin::GetPThreadT (nub_thread_t tid)
74 MachThreadSP thread_sp (GetThreadByID (tid));
76 return thread_sp->GetPThreadT();
77 return INVALID_NUB_ADDRESS;
81 NativeThreadListDarwin::GetDispatchQueueT (nub_thread_t tid)
83 MachThreadSP thread_sp (GetThreadByID (tid));
85 return thread_sp->GetDispatchQueueT();
86 return INVALID_NUB_ADDRESS;
90 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)
92 MachThreadSP thread_sp (GetThreadByID (tid));
94 return thread_sp->GetTSDAddressForThread(plo_pthread_tsd_base_address_offset, plo_pthread_tsd_base_offset, plo_pthread_tsd_entry_size);
95 return INVALID_NUB_ADDRESS;
99 // TODO implement these
102 NativeThreadListDarwin::SetCurrentThread(nub_thread_t tid)
104 MachThreadSP thread_sp (GetThreadByID (tid));
107 m_current_thread = thread_sp;
110 return INVALID_NUB_THREAD;
115 NativeThreadListDarwin::GetThreadStoppedReason(nub_thread_t tid, struct DNBThreadStopInfo *stop_info) const
117 MachThreadSP thread_sp (GetThreadByID (tid));
119 return thread_sp->GetStopException().GetStopInfo(stop_info);
124 NativeThreadListDarwin::GetIdentifierInfo (nub_thread_t tid, thread_identifier_info_data_t *ident_info)
126 thread_t mach_port_number = GetMachPortNumberByThreadID (tid);
128 mach_msg_type_number_t count = THREAD_IDENTIFIER_INFO_COUNT;
129 return ::thread_info (mach_port_number, THREAD_IDENTIFIER_INFO, (thread_info_t)ident_info, &count) == KERN_SUCCESS;
133 NativeThreadListDarwin::DumpThreadStoppedReason (nub_thread_t tid) const
135 MachThreadSP thread_sp (GetThreadByID (tid));
137 thread_sp->GetStopException().DumpStopReason();
141 NativeThreadListDarwin::GetThreadInfo (nub_thread_t tid) const
143 MachThreadSP thread_sp (GetThreadByID (tid));
145 return thread_sp->GetBasicInfoAsString();
152 NativeThreadListDarwin::GetThreadByID(lldb::tid_t tid) const {
153 std::lock_guard<std::recursive_mutex> locker(m_threads_mutex);
154 for (auto thread_sp : m_threads) {
155 if (thread_sp && (thread_sp->GetID() == tid))
158 return NativeThreadDarwinSP();
161 NativeThreadDarwinSP NativeThreadListDarwin::GetThreadByMachPortNumber(
162 ::thread_t mach_port_number) const {
163 std::lock_guard<std::recursive_mutex> locker(m_threads_mutex);
164 for (auto thread_sp : m_threads) {
165 if (thread_sp && (thread_sp->GetMachPortNumber() == mach_port_number))
168 return NativeThreadDarwinSP();
171 lldb::tid_t NativeThreadListDarwin::GetThreadIDByMachPortNumber(
172 ::thread_t mach_port_number) const {
173 std::lock_guard<std::recursive_mutex> locker(m_threads_mutex);
174 for (auto thread_sp : m_threads) {
175 if (thread_sp && (thread_sp->GetMachPortNumber() == mach_port_number))
176 return thread_sp->GetID();
178 return LLDB_INVALID_THREAD_ID;
184 NativeThreadListDarwin::GetMachPortNumberByThreadID (nub_thread_t globally_unique_id) const
186 PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
187 MachThreadSP thread_sp;
188 const size_t num_threads = m_threads.size();
189 for (size_t idx = 0; idx < num_threads; ++idx)
191 if (m_threads[idx]->ThreadID() == globally_unique_id)
193 return m_threads[idx]->MachPortNumber();
200 NativeThreadListDarwin::GetRegisterValue (nub_thread_t tid, uint32_t set, uint32_t reg, DNBRegisterValue *reg_value ) const
202 MachThreadSP thread_sp (GetThreadByID (tid));
204 return thread_sp->GetRegisterValue(set, reg, reg_value);
210 NativeThreadListDarwin::SetRegisterValue (nub_thread_t tid, uint32_t set, uint32_t reg, const DNBRegisterValue *reg_value ) const
212 MachThreadSP thread_sp (GetThreadByID (tid));
214 return thread_sp->SetRegisterValue(set, reg, reg_value);
220 NativeThreadListDarwin::GetRegisterContext (nub_thread_t tid, void *buf, size_t buf_len)
222 MachThreadSP thread_sp (GetThreadByID (tid));
224 return thread_sp->GetRegisterContext (buf, buf_len);
229 NativeThreadListDarwin::SetRegisterContext (nub_thread_t tid, const void *buf, size_t buf_len)
231 MachThreadSP thread_sp (GetThreadByID (tid));
233 return thread_sp->SetRegisterContext (buf, buf_len);
238 NativeThreadListDarwin::SaveRegisterState (nub_thread_t tid)
240 MachThreadSP thread_sp (GetThreadByID (tid));
242 return thread_sp->SaveRegisterState ();
247 NativeThreadListDarwin::RestoreRegisterState (nub_thread_t tid, uint32_t save_id)
249 MachThreadSP thread_sp (GetThreadByID (tid));
251 return thread_sp->RestoreRegisterState (save_id);
256 size_t NativeThreadListDarwin::GetNumberOfThreads() const {
257 std::lock_guard<std::recursive_mutex> locker(m_threads_mutex);
258 return static_cast<size_t>(m_threads.size());
264 NativeThreadListDarwin::ThreadIDAtIndex (nub_size_t idx) const
266 PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
267 if (idx < m_threads.size())
268 return m_threads[idx]->ThreadID();
269 return INVALID_NUB_THREAD;
273 NativeThreadListDarwin::CurrentThreadID ( )
275 MachThreadSP thread_sp;
276 CurrentThread(thread_sp);
278 return thread_sp->ThreadID();
279 return INVALID_NUB_THREAD;
284 bool NativeThreadListDarwin::NotifyException(MachException::Data &exc) {
285 auto thread_sp = GetThreadByMachPortNumber(exc.thread_port);
287 thread_sp->NotifyException(exc);
293 void NativeThreadListDarwin::Clear() {
294 std::lock_guard<std::recursive_mutex> locker(m_threads_mutex);
298 uint32_t NativeThreadListDarwin::UpdateThreadList(NativeProcessDarwin &process,
300 collection *new_threads) {
301 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD));
303 std::lock_guard<std::recursive_mutex> locker(m_threads_mutex);
305 log->Printf("NativeThreadListDarwin::%s() (pid = %" PRIu64 ", update = "
306 "%u) process stop count = %u",
307 __FUNCTION__, process.GetID(), update, process.GetStopID());
309 if (process.GetStopID() == 0) {
310 // On our first stop, we'll record details like 32/64 bitness and select
311 // the proper architecture implementation.
313 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, (int)process.GetID()};
315 struct kinfo_proc processInfo;
316 size_t bufsize = sizeof(processInfo);
317 if ((sysctl(mib, (unsigned)(sizeof(mib) / sizeof(int)), &processInfo,
318 &bufsize, NULL, 0) == 0) &&
320 if (processInfo.kp_proc.p_flag & P_LP64)
324 // TODO implement architecture selection and abstraction.
326 #if defined(__i386__) || defined(__x86_64__)
328 DNBArchProtocol::SetArchitecture(CPU_TYPE_X86_64);
330 DNBArchProtocol::SetArchitecture(CPU_TYPE_I386);
331 #elif defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
333 DNBArchProtocol::SetArchitecture(CPU_TYPE_ARM64);
335 DNBArchProtocol::SetArchitecture(CPU_TYPE_ARM);
340 if (m_threads.empty() || update) {
341 thread_array_t thread_list = nullptr;
342 mach_msg_type_number_t thread_list_count = 0;
343 task_t task = process.GetTask();
346 auto mach_err = ::task_threads(task, &thread_list, &thread_list_count);
347 error.SetError(mach_err, eErrorTypeMachKernel);
350 log->Printf("::task_threads(task = 0x%4.4x, thread_list => %p, "
351 "thread_list_count => %u) failed: %u (%s)",
352 task, thread_list, thread_list_count, error.GetError(),
357 if (thread_list_count > 0) {
358 collection currThreads;
360 // Iterator through the current thread list and see which threads we
361 // already have in our list (keep them), which ones we don't (add them),
362 // and which ones are not around anymore (remove them).
363 for (idx = 0; idx < thread_list_count; ++idx) {
364 // Get the Mach thread port.
365 const ::thread_t mach_port_num = thread_list[idx];
367 // Get the unique thread id for the mach port number.
368 uint64_t unique_thread_id =
369 NativeThreadDarwin::GetGloballyUniqueThreadIDForMachPortID(
372 // Retrieve the thread if it exists.
373 auto thread_sp = GetThreadByID(unique_thread_id);
375 // We are already tracking it. Keep the existing native thread
377 currThreads.push_back(thread_sp);
379 // We don't have a native thread instance for this thread. Create it
381 thread_sp.reset(new NativeThreadDarwin(
382 &process, m_is_64_bit, unique_thread_id, mach_port_num));
384 // Add the new thread regardless of its is user ready state. Make
385 // sure the thread is ready to be displayed and shown to users before
386 // we add this thread to our list...
387 if (thread_sp->IsUserReady()) {
389 new_threads->push_back(thread_sp);
391 currThreads.push_back(thread_sp);
396 m_threads.swap(currThreads);
397 m_current_thread.reset();
399 // Free the vm memory given to us by ::task_threads()
400 vm_size_t thread_list_size =
401 (vm_size_t)(thread_list_count * sizeof(::thread_t));
402 ::vm_deallocate(::mach_task_self(), (vm_address_t)thread_list,
406 return static_cast<uint32_t>(m_threads.size());
413 NativeThreadListDarwin::CurrentThread (MachThreadSP& thread_sp)
415 // locker will keep a mutex locked until it goes out of scope
416 PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
417 if (m_current_thread.get() == NULL)
419 // Figure out which thread is going to be our current thread. This is
420 // currently done by finding the first thread in the list that has a
422 const size_t num_threads = m_threads.size();
423 for (uint32_t idx = 0; idx < num_threads; ++idx)
425 if (m_threads[idx]->GetStopException().IsValid())
427 m_current_thread = m_threads[idx];
432 thread_sp = m_current_thread;
437 void NativeThreadListDarwin::Dump(Stream &stream) const {
440 std::lock_guard<std::recursive_mutex> locker(m_threads_mutex);
441 for (auto thread_sp : m_threads) {
443 // Handle newlines between thread entries.
447 stream.PutChar('\n');
448 thread_sp->Dump(stream);
453 void NativeThreadListDarwin::ProcessWillResume(
454 NativeProcessDarwin &process, const ResumeActionList &thread_actions) {
455 std::lock_guard<std::recursive_mutex> locker(m_threads_mutex);
457 // Update our thread list, because sometimes libdispatch or the kernel will
458 // spawn threads while a task is suspended.
459 NativeThreadListDarwin::collection new_threads;
461 // TODO implement this.
463 // First figure out if we were planning on running only one thread, and if
464 // so, force that thread to resume.
466 thread_t solo_thread = THREAD_NULL;
467 if ((thread_actions.GetSize() > 0) &&
468 (thread_actions.NumActionsWithState(eStateStepping) +
469 thread_actions.NumActionsWithState (eStateRunning) == 1))
471 run_one_thread = true;
472 const DNBThreadResumeAction *action_ptr = thread_actions.GetFirst();
473 size_t num_actions = thread_actions.GetSize();
474 for (size_t i = 0; i < num_actions; i++, action_ptr++)
476 if (action_ptr->state == eStateStepping || action_ptr->state == eStateRunning)
478 solo_thread = action_ptr->tid;
484 run_one_thread = false;
487 UpdateThreadList(process, true, &new_threads);
490 DNBThreadResumeAction resume_new_threads = { -1U, eStateRunning, 0, INVALID_NUB_ADDRESS };
491 // If we are planning to run only one thread, any new threads should be
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 // Check each thread in our thread list to see if we should notify our client
552 // of the current halt in execution.
554 // Breakpoints can have callback functions associated with them than can return
555 // true to stop, or false to continue executing the inferior.
558 // true if we should stop and notify our clients
559 // false if we should resume our child process and skip notification
560 bool NativeThreadListDarwin::ShouldStop(bool &step_more) {
561 std::lock_guard<std::recursive_mutex> locker(m_threads_mutex);
562 for (auto thread_sp : m_threads) {
563 if (thread_sp && thread_sp->ShouldStop(step_more))
573 NativeThreadListDarwin::NotifyBreakpointChanged (const DNBBreakpoint *bp)
575 PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
576 const size_t num_threads = m_threads.size();
577 for (uint32_t idx = 0; idx < num_threads; ++idx)
579 m_threads[idx]->NotifyBreakpointChanged(bp);
585 NativeThreadListDarwin::EnableHardwareBreakpoint (const DNBBreakpoint* bp) const
589 const size_t num_threads = m_threads.size();
590 for (uint32_t idx = 0; idx < num_threads; ++idx)
591 m_threads[idx]->EnableHardwareBreakpoint(bp);
593 return INVALID_NUB_HW_INDEX;
597 NativeThreadListDarwin::DisableHardwareBreakpoint (const DNBBreakpoint* bp) const
601 const size_t num_threads = m_threads.size();
602 for (uint32_t idx = 0; idx < num_threads; ++idx)
603 m_threads[idx]->DisableHardwareBreakpoint(bp);
608 // DNBWatchpointSet() -> MachProcess::CreateWatchpoint() ->
609 // MachProcess::EnableWatchpoint() ->
610 // NativeThreadListDarwin::EnableHardwareWatchpoint().
612 NativeThreadListDarwin::EnableHardwareWatchpoint (const DNBBreakpoint* wp) const
614 uint32_t hw_index = INVALID_NUB_HW_INDEX;
617 PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
618 const size_t num_threads = m_threads.size();
619 // On Mac OS X we have to prime the control registers for new threads.
620 // We do this using the control register data for the first thread, for
621 // 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
628 // transaction for [0, idx).
629 for (uint32_t i = 0; i < idx; ++i)
630 m_threads[i]->RollbackTransForHWP();
631 return INVALID_NUB_HW_INDEX;
633 also_set_on_task = false;
635 // Notify each thread to commit the pending transaction.
636 for (uint32_t idx = 0; idx < num_threads; ++idx)
637 m_threads[idx]->FinishTransForHWP();
644 NativeThreadListDarwin::DisableHardwareWatchpoint (const DNBBreakpoint* wp) const
648 PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
649 const size_t num_threads = m_threads.size();
651 // On Mac OS X we have to prime the control registers for new threads.
652 // We do this using the control register data for the first thread, for
653 // lack of a better way of choosing.
654 bool also_set_on_task = true;
655 for (uint32_t idx = 0; idx < num_threads; ++idx)
657 if (!m_threads[idx]->DisableHardwareWatchpoint(wp, also_set_on_task))
659 // We know that idx failed for some reason. Let's rollback the
660 // transaction for [0, idx).
661 for (uint32_t i = 0; i < idx; ++i)
662 m_threads[i]->RollbackTransForHWP();
665 also_set_on_task = false;
667 // Notify each thread to commit the pending transaction.
668 for (uint32_t idx = 0; idx < num_threads; ++idx)
669 m_threads[idx]->FinishTransForHWP();
677 NativeThreadListDarwin::NumSupportedHardwareWatchpoints () const
679 PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
680 const size_t num_threads = m_threads.size();
681 // Use an arbitrary thread to retrieve the number of supported hardware
684 return m_threads[0]->NumSupportedHardwareWatchpoints();
689 NativeThreadListDarwin::GetThreadIndexForThreadStoppedWithSignal (const int signo) const
691 PTHREAD_MUTEX_LOCKER (locker, m_threads_mutex);
692 uint32_t should_stop = false;
693 const size_t num_threads = m_threads.size();
694 for (uint32_t idx = 0; !should_stop && idx < num_threads; ++idx)
696 if (m_threads[idx]->GetStopException().SoftSignal () == signo)