1 //===-- FreeBSDThread.cpp ---------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
12 #include <pthread_np.h>
14 #include <sys/sysctl.h>
15 #include <sys/types.h>
18 #include "lldb/Target/UnixSignals.h"
19 #include "lldb/Utility/State.h"
21 #include "FreeBSDThread.h"
22 #include "POSIXStopInfo.h"
23 #include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
24 #include "Plugins/Process/Utility/RegisterContextFreeBSD_i386.h"
25 #include "Plugins/Process/Utility/RegisterContextFreeBSD_mips64.h"
26 #include "Plugins/Process/Utility/RegisterContextFreeBSD_powerpc.h"
27 #include "Plugins/Process/Utility/RegisterContextFreeBSD_x86_64.h"
28 #include "Plugins/Process/Utility/RegisterInfoPOSIX_arm.h"
29 #include "Plugins/Process/Utility/RegisterInfoPOSIX_arm64.h"
30 #include "Plugins/Process/Utility/UnwindLLDB.h"
31 #include "ProcessFreeBSD.h"
32 #include "ProcessMonitor.h"
33 #include "RegisterContextPOSIXProcessMonitor_arm.h"
34 #include "RegisterContextPOSIXProcessMonitor_arm64.h"
35 #include "RegisterContextPOSIXProcessMonitor_mips64.h"
36 #include "RegisterContextPOSIXProcessMonitor_powerpc.h"
37 #include "RegisterContextPOSIXProcessMonitor_x86.h"
38 #include "lldb/Breakpoint/BreakpointLocation.h"
39 #include "lldb/Breakpoint/Watchpoint.h"
40 #include "lldb/Core/Debugger.h"
41 #include "lldb/Host/Host.h"
42 #include "lldb/Host/HostInfo.h"
43 #include "lldb/Host/HostNativeThread.h"
44 #include "lldb/Target/Process.h"
45 #include "lldb/Target/StopInfo.h"
46 #include "lldb/Target/Target.h"
47 #include "lldb/Target/ThreadSpec.h"
48 #include "lldb/Utility/State.h"
49 #include "llvm/ADT/SmallString.h"
52 using namespace lldb_private;
54 FreeBSDThread::FreeBSDThread(Process &process, lldb::tid_t tid)
55 : Thread(process, tid), m_frame_ap(), m_breakpoint(),
56 m_thread_name_valid(false), m_thread_name(), m_posix_thread(nullptr) {
57 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
58 LLDB_LOGV(log, "tid = {0}", tid);
60 // Set the current watchpoints for this thread.
61 Target &target = GetProcess()->GetTarget();
62 const WatchpointList &wp_list = target.GetWatchpointList();
63 size_t wp_size = wp_list.GetSize();
65 for (uint32_t wp_idx = 0; wp_idx < wp_size; wp_idx++) {
66 lldb::WatchpointSP wp = wp_list.GetByIndex(wp_idx);
67 if (wp.get() && wp->IsEnabled()) {
68 // This watchpoint as been enabled; obviously this "new" thread has been
69 // created since that watchpoint was enabled. Since the
70 // POSIXBreakpointProtocol has yet to be initialized, its
71 // m_watchpoints_initialized member will be FALSE. Attempting to read
72 // the debug status register to determine if a watchpoint has been hit
73 // would result in the zeroing of that register. Since the active debug
74 // registers would have been cloned when this thread was created, simply
75 // force the m_watchpoints_initized member to TRUE and avoid resetting
77 GetPOSIXBreakpointProtocol()->ForceWatchpointsInitialized();
82 FreeBSDThread::~FreeBSDThread() { DestroyThread(); }
84 ProcessMonitor &FreeBSDThread::GetMonitor() {
85 ProcessSP base = GetProcess();
86 ProcessFreeBSD &process = static_cast<ProcessFreeBSD &>(*base);
87 return process.GetMonitor();
90 void FreeBSDThread::RefreshStateAfterStop() {
91 // Invalidate all registers in our register context. We don't set "force" to
92 // true because the stop reply packet might have had some register values
93 // that were expedited and these will already be copied into the register
94 // context by the time this function gets called. The KDPRegisterContext
95 // class has been made smart enough to detect when it needs to invalidate
96 // which registers are valid by putting hooks in the register read and
97 // register supply functions where they check the process stop ID and do the
98 // right thing. if (StateIsStoppedState(GetState())
100 const bool force = false;
101 GetRegisterContext()->InvalidateIfNeeded(force);
105 const char *FreeBSDThread::GetInfo() { return nullptr; }
107 void FreeBSDThread::SetName(const char *name) {
108 m_thread_name_valid = (name && name[0]);
109 if (m_thread_name_valid)
110 m_thread_name.assign(name);
112 m_thread_name.clear();
115 const char *FreeBSDThread::GetName() {
116 if (!m_thread_name_valid) {
117 m_thread_name.clear();
118 int pid = GetProcess()->GetID();
120 struct kinfo_proc *kp = nullptr, *nkp;
123 int ctl[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID | KERN_PROC_INC_THREAD,
127 error = sysctl(ctl, 4, kp, &len, nullptr, 0);
128 if (kp == nullptr || (error != 0 && errno == ENOMEM)) {
129 // Add extra space in case threads are added before next call.
130 len += sizeof(*kp) + len / 10;
131 nkp = (struct kinfo_proc *)realloc(kp, len);
132 if (nkp == nullptr) {
144 for (size_t i = 0; i < len / sizeof(*kp); i++) {
145 if (kp[i].ki_tid == (lwpid_t)GetID()) {
146 m_thread_name.append(kp[i].ki_tdname,
147 kp[i].ki_tdname + strlen(kp[i].ki_tdname));
152 m_thread_name_valid = true;
155 if (m_thread_name.empty())
157 return m_thread_name.c_str();
160 lldb::RegisterContextSP FreeBSDThread::GetRegisterContext() {
161 if (!m_reg_context_sp) {
162 m_posix_thread = nullptr;
164 RegisterInfoInterface *reg_interface = nullptr;
165 const ArchSpec &target_arch = GetProcess()->GetTarget().GetArchitecture();
167 switch (target_arch.GetMachine()) {
168 case llvm::Triple::aarch64:
169 reg_interface = new RegisterInfoPOSIX_arm64(target_arch);
171 case llvm::Triple::arm:
172 reg_interface = new RegisterInfoPOSIX_arm(target_arch);
174 case llvm::Triple::ppc:
175 #ifndef __powerpc64__
176 reg_interface = new RegisterContextFreeBSD_powerpc32(target_arch);
179 case llvm::Triple::ppc64:
180 reg_interface = new RegisterContextFreeBSD_powerpc64(target_arch);
182 case llvm::Triple::mips64:
183 reg_interface = new RegisterContextFreeBSD_mips64(target_arch);
185 case llvm::Triple::x86:
186 reg_interface = new RegisterContextFreeBSD_i386(target_arch);
188 case llvm::Triple::x86_64:
189 reg_interface = new RegisterContextFreeBSD_x86_64(target_arch);
192 llvm_unreachable("CPU not supported");
195 switch (target_arch.GetMachine()) {
196 case llvm::Triple::aarch64: {
197 RegisterContextPOSIXProcessMonitor_arm64 *reg_ctx =
198 new RegisterContextPOSIXProcessMonitor_arm64(*this, 0, reg_interface);
199 m_posix_thread = reg_ctx;
200 m_reg_context_sp.reset(reg_ctx);
203 case llvm::Triple::arm: {
204 RegisterContextPOSIXProcessMonitor_arm *reg_ctx =
205 new RegisterContextPOSIXProcessMonitor_arm(*this, 0, reg_interface);
206 m_posix_thread = reg_ctx;
207 m_reg_context_sp.reset(reg_ctx);
210 case llvm::Triple::mips64: {
211 RegisterContextPOSIXProcessMonitor_mips64 *reg_ctx =
212 new RegisterContextPOSIXProcessMonitor_mips64(*this, 0,
214 m_posix_thread = reg_ctx;
215 m_reg_context_sp.reset(reg_ctx);
218 case llvm::Triple::ppc:
219 case llvm::Triple::ppc64: {
220 RegisterContextPOSIXProcessMonitor_powerpc *reg_ctx =
221 new RegisterContextPOSIXProcessMonitor_powerpc(*this, 0,
223 m_posix_thread = reg_ctx;
224 m_reg_context_sp.reset(reg_ctx);
227 case llvm::Triple::x86:
228 case llvm::Triple::x86_64: {
229 RegisterContextPOSIXProcessMonitor_x86_64 *reg_ctx =
230 new RegisterContextPOSIXProcessMonitor_x86_64(*this, 0,
232 m_posix_thread = reg_ctx;
233 m_reg_context_sp.reset(reg_ctx);
240 return m_reg_context_sp;
243 lldb::RegisterContextSP
244 FreeBSDThread::CreateRegisterContextForFrame(lldb_private::StackFrame *frame) {
245 lldb::RegisterContextSP reg_ctx_sp;
246 uint32_t concrete_frame_idx = 0;
248 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
249 LLDB_LOGV(log, "called");
252 concrete_frame_idx = frame->GetConcreteFrameIndex();
254 if (concrete_frame_idx == 0)
255 reg_ctx_sp = GetRegisterContext();
257 assert(GetUnwinder());
258 reg_ctx_sp = GetUnwinder()->CreateRegisterContextForFrame(frame);
264 lldb::addr_t FreeBSDThread::GetThreadPointer() {
265 ProcessMonitor &monitor = GetMonitor();
267 if (monitor.ReadThreadPointer(GetID(), addr))
270 return LLDB_INVALID_ADDRESS;
273 bool FreeBSDThread::CalculateStopInfo() {
274 SetStopInfo(m_stop_info_sp);
278 Unwind *FreeBSDThread::GetUnwinder() {
280 m_unwinder_ap.reset(new UnwindLLDB(*this));
282 return m_unwinder_ap.get();
285 void FreeBSDThread::DidStop() {
286 // Don't set the thread state to stopped unless we really stopped.
289 void FreeBSDThread::WillResume(lldb::StateType resume_state) {
290 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
292 log->Printf("tid %" PRIu64 " resume_state = %s", GetID(),
293 lldb_private::StateAsCString(resume_state));
294 ProcessSP process_sp(GetProcess());
295 ProcessFreeBSD *process = static_cast<ProcessFreeBSD *>(process_sp.get());
296 int signo = GetResumeSignal();
297 bool signo_valid = process->GetUnixSignals()->SignalIsValid(signo);
299 switch (resume_state) {
300 case eStateSuspended:
302 process->m_suspend_tids.push_back(GetID());
305 process->m_run_tids.push_back(GetID());
307 process->m_resume_signo = signo;
310 process->m_step_tids.push_back(GetID());
312 process->m_resume_signo = signo;
319 bool FreeBSDThread::Resume() {
320 lldb::StateType resume_state = GetResumeState();
321 ProcessMonitor &monitor = GetMonitor();
324 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
326 log->Printf("FreeBSDThread::%s (), resume_state = %s", __FUNCTION__,
327 StateAsCString(resume_state));
329 switch (resume_state) {
331 assert(false && "Unexpected state for resume!");
335 case lldb::eStateRunning:
336 SetState(resume_state);
337 status = monitor.Resume(GetID(), GetResumeSignal());
340 case lldb::eStateStepping:
341 SetState(resume_state);
342 status = monitor.SingleStep(GetID(), GetResumeSignal());
344 case lldb::eStateStopped:
345 case lldb::eStateSuspended:
353 void FreeBSDThread::Notify(const ProcessMessage &message) {
354 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
356 log->Printf("FreeBSDThread::%s () message kind = '%s' for tid %" PRIu64,
357 __FUNCTION__, message.PrintKind(), GetID());
359 switch (message.GetKind()) {
361 assert(false && "Unexpected message kind!");
364 case ProcessMessage::eExitMessage:
365 // Nothing to be done.
368 case ProcessMessage::eLimboMessage:
369 LimboNotify(message);
372 case ProcessMessage::eCrashMessage:
373 case ProcessMessage::eSignalMessage:
374 SignalNotify(message);
377 case ProcessMessage::eSignalDeliveredMessage:
378 SignalDeliveredNotify(message);
381 case ProcessMessage::eTraceMessage:
382 TraceNotify(message);
385 case ProcessMessage::eBreakpointMessage:
386 BreakNotify(message);
389 case ProcessMessage::eWatchpointMessage:
390 WatchNotify(message);
393 case ProcessMessage::eExecMessage:
399 bool FreeBSDThread::EnableHardwareWatchpoint(Watchpoint *wp) {
402 addr_t wp_addr = wp->GetLoadAddress();
403 size_t wp_size = wp->GetByteSize();
404 bool wp_read = wp->WatchpointRead();
405 bool wp_write = wp->WatchpointWrite();
406 uint32_t wp_hw_index = wp->GetHardwareIndex();
407 POSIXBreakpointProtocol *reg_ctx = GetPOSIXBreakpointProtocol();
409 wp_set = reg_ctx->SetHardwareWatchpointWithIndex(
410 wp_addr, wp_size, wp_read, wp_write, wp_hw_index);
415 bool FreeBSDThread::DisableHardwareWatchpoint(Watchpoint *wp) {
418 lldb::RegisterContextSP reg_ctx_sp = GetRegisterContext();
419 if (reg_ctx_sp.get())
420 result = reg_ctx_sp->ClearHardwareWatchpoint(wp->GetHardwareIndex());
425 uint32_t FreeBSDThread::NumSupportedHardwareWatchpoints() {
426 lldb::RegisterContextSP reg_ctx_sp = GetRegisterContext();
427 if (reg_ctx_sp.get())
428 return reg_ctx_sp->NumSupportedHardwareWatchpoints();
432 uint32_t FreeBSDThread::FindVacantWatchpointIndex() {
433 uint32_t hw_index = LLDB_INVALID_INDEX32;
434 uint32_t num_hw_wps = NumSupportedHardwareWatchpoints();
436 POSIXBreakpointProtocol *reg_ctx = GetPOSIXBreakpointProtocol();
438 for (wp_idx = 0; wp_idx < num_hw_wps; wp_idx++) {
439 if (reg_ctx->IsWatchpointVacant(wp_idx)) {
448 void FreeBSDThread::BreakNotify(const ProcessMessage &message) {
450 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
452 assert(GetRegisterContext());
453 status = GetPOSIXBreakpointProtocol()->UpdateAfterBreakpoint();
454 assert(status && "Breakpoint update failed!");
456 // With our register state restored, resolve the breakpoint object
457 // corresponding to our current PC.
458 assert(GetRegisterContext());
459 lldb::addr_t pc = GetRegisterContext()->GetPC();
461 log->Printf("FreeBSDThread::%s () PC=0x%8.8" PRIx64, __FUNCTION__, pc);
462 lldb::BreakpointSiteSP bp_site(
463 GetProcess()->GetBreakpointSiteList().FindByAddress(pc));
465 // If the breakpoint is for this thread, then we'll report the hit, but if it
466 // is for another thread, we create a stop reason with should_stop=false. If
467 // there is no breakpoint location, then report an invalid stop reason. We
468 // don't need to worry about stepping over the breakpoint here, that will be
469 // taken care of when the thread resumes and notices that there's a
470 // breakpoint under the pc.
472 lldb::break_id_t bp_id = bp_site->GetID();
473 // If we have an operating system plug-in, we might have set a thread
474 // specific breakpoint using the operating system thread ID, so we can't
475 // make any assumptions about the thread ID so we must always report the
476 // breakpoint regardless of the thread.
477 if (bp_site->ValidForThisThread(this) ||
478 GetProcess()->GetOperatingSystem() != nullptr)
479 SetStopInfo(StopInfo::CreateStopReasonWithBreakpointSiteID(*this, bp_id));
481 const bool should_stop = false;
482 SetStopInfo(StopInfo::CreateStopReasonWithBreakpointSiteID(*this, bp_id,
486 SetStopInfo(StopInfoSP());
489 void FreeBSDThread::WatchNotify(const ProcessMessage &message) {
490 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
492 lldb::addr_t halt_addr = message.GetHWAddress();
495 "FreeBSDThread::%s () Hardware Watchpoint Address = 0x%8.8" PRIx64,
496 __FUNCTION__, halt_addr);
498 POSIXBreakpointProtocol *reg_ctx = GetPOSIXBreakpointProtocol();
500 uint32_t num_hw_wps = reg_ctx->NumSupportedHardwareWatchpoints();
502 for (wp_idx = 0; wp_idx < num_hw_wps; wp_idx++) {
503 if (reg_ctx->IsWatchpointHit(wp_idx)) {
504 // Clear the watchpoint hit here
505 reg_ctx->ClearWatchpointHits();
510 if (wp_idx == num_hw_wps)
513 Target &target = GetProcess()->GetTarget();
514 lldb::addr_t wp_monitor_addr = reg_ctx->GetWatchpointAddress(wp_idx);
515 const WatchpointList &wp_list = target.GetWatchpointList();
516 lldb::WatchpointSP wp_sp = wp_list.FindByAddress(wp_monitor_addr);
518 assert(wp_sp.get() && "No watchpoint found");
520 StopInfo::CreateStopReasonWithWatchpointID(*this, wp_sp->GetID()));
524 void FreeBSDThread::TraceNotify(const ProcessMessage &message) {
525 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
527 // Try to resolve the breakpoint object corresponding to the current PC.
528 assert(GetRegisterContext());
529 lldb::addr_t pc = GetRegisterContext()->GetPC();
531 log->Printf("FreeBSDThread::%s () PC=0x%8.8" PRIx64, __FUNCTION__, pc);
532 lldb::BreakpointSiteSP bp_site(
533 GetProcess()->GetBreakpointSiteList().FindByAddress(pc));
535 // If the current pc is a breakpoint site then set the StopInfo to
536 // Breakpoint. Otherwise, set the StopInfo to Watchpoint or Trace. If we have
537 // an operating system plug-in, we might have set a thread specific
538 // breakpoint using the operating system thread ID, so we can't make any
539 // assumptions about the thread ID so we must always report the breakpoint
540 // regardless of the thread.
541 if (bp_site && (bp_site->ValidForThisThread(this) ||
542 GetProcess()->GetOperatingSystem() != nullptr))
543 SetStopInfo(StopInfo::CreateStopReasonWithBreakpointSiteID(
544 *this, bp_site->GetID()));
546 POSIXBreakpointProtocol *reg_ctx = GetPOSIXBreakpointProtocol();
548 uint32_t num_hw_wps = reg_ctx->NumSupportedHardwareWatchpoints();
550 for (wp_idx = 0; wp_idx < num_hw_wps; wp_idx++) {
551 if (reg_ctx->IsWatchpointHit(wp_idx)) {
552 WatchNotify(message);
557 SetStopInfo(StopInfo::CreateStopReasonToTrace(*this));
561 void FreeBSDThread::LimboNotify(const ProcessMessage &message) {
562 SetStopInfo(lldb::StopInfoSP(new POSIXLimboStopInfo(*this)));
565 void FreeBSDThread::SignalNotify(const ProcessMessage &message) {
566 int signo = message.GetSignal();
567 if (message.GetKind() == ProcessMessage::eCrashMessage) {
568 std::string stop_description = GetCrashReasonString(
569 message.GetCrashReason(), message.GetFaultAddress());
570 SetStopInfo(StopInfo::CreateStopReasonWithSignal(
571 *this, signo, stop_description.c_str()));
573 SetStopInfo(StopInfo::CreateStopReasonWithSignal(*this, signo));
577 void FreeBSDThread::SignalDeliveredNotify(const ProcessMessage &message) {
578 int signo = message.GetSignal();
579 SetStopInfo(StopInfo::CreateStopReasonWithSignal(*this, signo));
582 unsigned FreeBSDThread::GetRegisterIndexFromOffset(unsigned offset) {
583 unsigned reg = LLDB_INVALID_REGNUM;
584 ArchSpec arch = HostInfo::GetArchitecture();
586 switch (arch.GetMachine()) {
588 llvm_unreachable("CPU type not supported!");
591 case llvm::Triple::aarch64:
592 case llvm::Triple::arm:
593 case llvm::Triple::mips64:
594 case llvm::Triple::ppc:
595 case llvm::Triple::ppc64:
596 case llvm::Triple::x86:
597 case llvm::Triple::x86_64: {
598 POSIXBreakpointProtocol *reg_ctx = GetPOSIXBreakpointProtocol();
599 reg = reg_ctx->GetRegisterIndexFromOffset(offset);
605 void FreeBSDThread::ExecNotify(const ProcessMessage &message) {
606 SetStopInfo(StopInfo::CreateStopReasonWithExec(*this));
609 const char *FreeBSDThread::GetRegisterName(unsigned reg) {
610 const char *name = nullptr;
611 ArchSpec arch = HostInfo::GetArchitecture();
613 switch (arch.GetMachine()) {
615 assert(false && "CPU type not supported!");
618 case llvm::Triple::aarch64:
619 case llvm::Triple::arm:
620 case llvm::Triple::mips64:
621 case llvm::Triple::ppc:
622 case llvm::Triple::ppc64:
623 case llvm::Triple::x86:
624 case llvm::Triple::x86_64:
625 name = GetRegisterContext()->GetRegisterName(reg);
631 const char *FreeBSDThread::GetRegisterNameFromOffset(unsigned offset) {
632 return GetRegisterName(GetRegisterIndexFromOffset(offset));