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 //===----------------------------------------------------------------------===//
13 #include <pthread_np.h>
15 #include <sys/sysctl.h>
16 #include <sys/types.h>
20 // Other libraries and framework includes
21 #include "lldb/Core/State.h"
22 #include "lldb/Target/UnixSignals.h"
25 #include "FreeBSDThread.h"
26 #include "POSIXStopInfo.h"
27 #include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
28 #include "Plugins/Process/Utility/RegisterContextFreeBSD_i386.h"
29 #include "Plugins/Process/Utility/RegisterContextFreeBSD_mips64.h"
30 #include "Plugins/Process/Utility/RegisterContextFreeBSD_powerpc.h"
31 #include "Plugins/Process/Utility/RegisterContextFreeBSD_x86_64.h"
32 #include "Plugins/Process/Utility/RegisterInfoPOSIX_arm.h"
33 #include "Plugins/Process/Utility/RegisterInfoPOSIX_arm64.h"
34 #include "Plugins/Process/Utility/UnwindLLDB.h"
35 #include "ProcessFreeBSD.h"
36 #include "ProcessMonitor.h"
37 #include "RegisterContextPOSIXProcessMonitor_arm.h"
38 #include "RegisterContextPOSIXProcessMonitor_arm64.h"
39 #include "RegisterContextPOSIXProcessMonitor_mips64.h"
40 #include "RegisterContextPOSIXProcessMonitor_powerpc.h"
41 #include "RegisterContextPOSIXProcessMonitor_x86.h"
42 #include "lldb/Breakpoint/BreakpointLocation.h"
43 #include "lldb/Breakpoint/Watchpoint.h"
44 #include "lldb/Core/Debugger.h"
45 #include "lldb/Core/State.h"
46 #include "lldb/Host/Host.h"
47 #include "lldb/Host/HostInfo.h"
48 #include "lldb/Host/HostNativeThread.h"
49 #include "lldb/Target/Process.h"
50 #include "lldb/Target/StopInfo.h"
51 #include "lldb/Target/Target.h"
52 #include "lldb/Target/ThreadSpec.h"
53 #include "llvm/ADT/SmallString.h"
56 using namespace lldb_private;
58 FreeBSDThread::FreeBSDThread(Process &process, lldb::tid_t tid)
59 : Thread(process, tid), m_frame_ap(), m_breakpoint(),
60 m_thread_name_valid(false), m_thread_name(), m_posix_thread(nullptr) {
61 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
62 LLDB_LOGV(log, "tid = {0}", tid);
64 // Set the current watchpoints for this thread.
65 Target &target = GetProcess()->GetTarget();
66 const WatchpointList &wp_list = target.GetWatchpointList();
67 size_t wp_size = wp_list.GetSize();
69 for (uint32_t wp_idx = 0; wp_idx < wp_size; wp_idx++) {
70 lldb::WatchpointSP wp = wp_list.GetByIndex(wp_idx);
71 if (wp.get() && wp->IsEnabled()) {
72 // This watchpoint as been enabled; obviously this "new" thread has been
73 // created since that watchpoint was enabled. Since the
74 // POSIXBreakpointProtocol has yet to be initialized, its
75 // m_watchpoints_initialized member will be FALSE. Attempting to read
76 // the debug status register to determine if a watchpoint has been hit
77 // would result in the zeroing of that register. Since the active debug
78 // registers would have been cloned when this thread was created, simply
79 // force the m_watchpoints_initized member to TRUE and avoid resetting
81 GetPOSIXBreakpointProtocol()->ForceWatchpointsInitialized();
86 FreeBSDThread::~FreeBSDThread() { DestroyThread(); }
88 ProcessMonitor &FreeBSDThread::GetMonitor() {
89 ProcessSP base = GetProcess();
90 ProcessFreeBSD &process = static_cast<ProcessFreeBSD &>(*base);
91 return process.GetMonitor();
94 void FreeBSDThread::RefreshStateAfterStop() {
95 // Invalidate all registers in our register context. We don't set "force" to
96 // true because the stop reply packet might have had some register values
97 // that were expedited and these will already be copied into the register
98 // context by the time this function gets called. The KDPRegisterContext
99 // class has been made smart enough to detect when it needs to invalidate
100 // which registers are valid by putting hooks in the register read and
101 // register supply functions where they check the process stop ID and do the
102 // right thing. if (StateIsStoppedState(GetState())
104 const bool force = false;
105 GetRegisterContext()->InvalidateIfNeeded(force);
109 const char *FreeBSDThread::GetInfo() { return nullptr; }
111 void FreeBSDThread::SetName(const char *name) {
112 m_thread_name_valid = (name && name[0]);
113 if (m_thread_name_valid)
114 m_thread_name.assign(name);
116 m_thread_name.clear();
119 const char *FreeBSDThread::GetName() {
120 if (!m_thread_name_valid) {
121 m_thread_name.clear();
122 int pid = GetProcess()->GetID();
124 struct kinfo_proc *kp = nullptr, *nkp;
127 int ctl[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID | KERN_PROC_INC_THREAD,
131 error = sysctl(ctl, 4, kp, &len, nullptr, 0);
132 if (kp == nullptr || (error != 0 && errno == ENOMEM)) {
133 // Add extra space in case threads are added before next call.
134 len += sizeof(*kp) + len / 10;
135 nkp = (struct kinfo_proc *)realloc(kp, len);
136 if (nkp == nullptr) {
148 for (size_t i = 0; i < len / sizeof(*kp); i++) {
149 if (kp[i].ki_tid == (lwpid_t)GetID()) {
150 m_thread_name.append(kp[i].ki_tdname,
151 kp[i].ki_tdname + strlen(kp[i].ki_tdname));
156 m_thread_name_valid = true;
159 if (m_thread_name.empty())
161 return m_thread_name.c_str();
164 lldb::RegisterContextSP FreeBSDThread::GetRegisterContext() {
165 if (!m_reg_context_sp) {
166 m_posix_thread = nullptr;
168 RegisterInfoInterface *reg_interface = nullptr;
169 const ArchSpec &target_arch = GetProcess()->GetTarget().GetArchitecture();
171 switch (target_arch.GetMachine()) {
172 case llvm::Triple::aarch64:
173 reg_interface = new RegisterInfoPOSIX_arm64(target_arch);
175 case llvm::Triple::arm:
176 reg_interface = new RegisterInfoPOSIX_arm(target_arch);
178 case llvm::Triple::ppc:
179 #ifndef __powerpc64__
180 reg_interface = new RegisterContextFreeBSD_powerpc32(target_arch);
183 case llvm::Triple::ppc64:
184 reg_interface = new RegisterContextFreeBSD_powerpc64(target_arch);
186 case llvm::Triple::mips64:
187 reg_interface = new RegisterContextFreeBSD_mips64(target_arch);
189 case llvm::Triple::x86:
190 reg_interface = new RegisterContextFreeBSD_i386(target_arch);
192 case llvm::Triple::x86_64:
193 reg_interface = new RegisterContextFreeBSD_x86_64(target_arch);
196 llvm_unreachable("CPU not supported");
199 switch (target_arch.GetMachine()) {
200 case llvm::Triple::aarch64: {
201 RegisterContextPOSIXProcessMonitor_arm64 *reg_ctx =
202 new RegisterContextPOSIXProcessMonitor_arm64(*this, 0, reg_interface);
203 m_posix_thread = reg_ctx;
204 m_reg_context_sp.reset(reg_ctx);
207 case llvm::Triple::arm: {
208 RegisterContextPOSIXProcessMonitor_arm *reg_ctx =
209 new RegisterContextPOSIXProcessMonitor_arm(*this, 0, reg_interface);
210 m_posix_thread = reg_ctx;
211 m_reg_context_sp.reset(reg_ctx);
214 case llvm::Triple::mips64: {
215 RegisterContextPOSIXProcessMonitor_mips64 *reg_ctx =
216 new RegisterContextPOSIXProcessMonitor_mips64(*this, 0,
218 m_posix_thread = reg_ctx;
219 m_reg_context_sp.reset(reg_ctx);
222 case llvm::Triple::ppc:
223 case llvm::Triple::ppc64: {
224 RegisterContextPOSIXProcessMonitor_powerpc *reg_ctx =
225 new RegisterContextPOSIXProcessMonitor_powerpc(*this, 0,
227 m_posix_thread = reg_ctx;
228 m_reg_context_sp.reset(reg_ctx);
231 case llvm::Triple::x86:
232 case llvm::Triple::x86_64: {
233 RegisterContextPOSIXProcessMonitor_x86_64 *reg_ctx =
234 new RegisterContextPOSIXProcessMonitor_x86_64(*this, 0,
236 m_posix_thread = reg_ctx;
237 m_reg_context_sp.reset(reg_ctx);
244 return m_reg_context_sp;
247 lldb::RegisterContextSP
248 FreeBSDThread::CreateRegisterContextForFrame(lldb_private::StackFrame *frame) {
249 lldb::RegisterContextSP reg_ctx_sp;
250 uint32_t concrete_frame_idx = 0;
252 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
253 LLDB_LOGV(log, "called");
256 concrete_frame_idx = frame->GetConcreteFrameIndex();
258 if (concrete_frame_idx == 0)
259 reg_ctx_sp = GetRegisterContext();
261 assert(GetUnwinder());
262 reg_ctx_sp = GetUnwinder()->CreateRegisterContextForFrame(frame);
268 lldb::addr_t FreeBSDThread::GetThreadPointer() {
269 ProcessMonitor &monitor = GetMonitor();
271 if (monitor.ReadThreadPointer(GetID(), addr))
274 return LLDB_INVALID_ADDRESS;
277 bool FreeBSDThread::CalculateStopInfo() {
278 SetStopInfo(m_stop_info_sp);
282 Unwind *FreeBSDThread::GetUnwinder() {
284 m_unwinder_ap.reset(new UnwindLLDB(*this));
286 return m_unwinder_ap.get();
289 void FreeBSDThread::DidStop() {
290 // Don't set the thread state to stopped unless we really stopped.
293 void FreeBSDThread::WillResume(lldb::StateType resume_state) {
294 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
296 log->Printf("tid %" PRIu64 " resume_state = %s", GetID(),
297 lldb_private::StateAsCString(resume_state));
298 ProcessSP process_sp(GetProcess());
299 ProcessFreeBSD *process = static_cast<ProcessFreeBSD *>(process_sp.get());
300 int signo = GetResumeSignal();
301 bool signo_valid = process->GetUnixSignals()->SignalIsValid(signo);
303 switch (resume_state) {
304 case eStateSuspended:
306 process->m_suspend_tids.push_back(GetID());
309 process->m_run_tids.push_back(GetID());
311 process->m_resume_signo = signo;
314 process->m_step_tids.push_back(GetID());
316 process->m_resume_signo = signo;
323 bool FreeBSDThread::Resume() {
324 lldb::StateType resume_state = GetResumeState();
325 ProcessMonitor &monitor = GetMonitor();
328 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
330 log->Printf("FreeBSDThread::%s (), resume_state = %s", __FUNCTION__,
331 StateAsCString(resume_state));
333 switch (resume_state) {
335 assert(false && "Unexpected state for resume!");
339 case lldb::eStateRunning:
340 SetState(resume_state);
341 status = monitor.Resume(GetID(), GetResumeSignal());
344 case lldb::eStateStepping:
345 SetState(resume_state);
346 status = monitor.SingleStep(GetID(), GetResumeSignal());
348 case lldb::eStateStopped:
349 case lldb::eStateSuspended:
357 void FreeBSDThread::Notify(const ProcessMessage &message) {
358 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
360 log->Printf("FreeBSDThread::%s () message kind = '%s' for tid %" PRIu64,
361 __FUNCTION__, message.PrintKind(), GetID());
363 switch (message.GetKind()) {
365 assert(false && "Unexpected message kind!");
368 case ProcessMessage::eExitMessage:
369 // Nothing to be done.
372 case ProcessMessage::eLimboMessage:
373 LimboNotify(message);
376 case ProcessMessage::eCrashMessage:
377 case ProcessMessage::eSignalMessage:
378 SignalNotify(message);
381 case ProcessMessage::eSignalDeliveredMessage:
382 SignalDeliveredNotify(message);
385 case ProcessMessage::eTraceMessage:
386 TraceNotify(message);
389 case ProcessMessage::eBreakpointMessage:
390 BreakNotify(message);
393 case ProcessMessage::eWatchpointMessage:
394 WatchNotify(message);
397 case ProcessMessage::eExecMessage:
403 bool FreeBSDThread::EnableHardwareWatchpoint(Watchpoint *wp) {
406 addr_t wp_addr = wp->GetLoadAddress();
407 size_t wp_size = wp->GetByteSize();
408 bool wp_read = wp->WatchpointRead();
409 bool wp_write = wp->WatchpointWrite();
410 uint32_t wp_hw_index = wp->GetHardwareIndex();
411 POSIXBreakpointProtocol *reg_ctx = GetPOSIXBreakpointProtocol();
413 wp_set = reg_ctx->SetHardwareWatchpointWithIndex(
414 wp_addr, wp_size, wp_read, wp_write, wp_hw_index);
419 bool FreeBSDThread::DisableHardwareWatchpoint(Watchpoint *wp) {
422 lldb::RegisterContextSP reg_ctx_sp = GetRegisterContext();
423 if (reg_ctx_sp.get())
424 result = reg_ctx_sp->ClearHardwareWatchpoint(wp->GetHardwareIndex());
429 uint32_t FreeBSDThread::NumSupportedHardwareWatchpoints() {
430 lldb::RegisterContextSP reg_ctx_sp = GetRegisterContext();
431 if (reg_ctx_sp.get())
432 return reg_ctx_sp->NumSupportedHardwareWatchpoints();
436 uint32_t FreeBSDThread::FindVacantWatchpointIndex() {
437 uint32_t hw_index = LLDB_INVALID_INDEX32;
438 uint32_t num_hw_wps = NumSupportedHardwareWatchpoints();
440 POSIXBreakpointProtocol *reg_ctx = GetPOSIXBreakpointProtocol();
442 for (wp_idx = 0; wp_idx < num_hw_wps; wp_idx++) {
443 if (reg_ctx->IsWatchpointVacant(wp_idx)) {
452 void FreeBSDThread::BreakNotify(const ProcessMessage &message) {
454 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
456 assert(GetRegisterContext());
457 status = GetPOSIXBreakpointProtocol()->UpdateAfterBreakpoint();
458 assert(status && "Breakpoint update failed!");
460 // With our register state restored, resolve the breakpoint object
461 // corresponding to our current PC.
462 assert(GetRegisterContext());
463 lldb::addr_t pc = GetRegisterContext()->GetPC();
465 log->Printf("FreeBSDThread::%s () PC=0x%8.8" PRIx64, __FUNCTION__, pc);
466 lldb::BreakpointSiteSP bp_site(
467 GetProcess()->GetBreakpointSiteList().FindByAddress(pc));
469 // If the breakpoint is for this thread, then we'll report the hit, but if it
470 // is for another thread, we create a stop reason with should_stop=false. If
471 // there is no breakpoint location, then report an invalid stop reason. We
472 // don't need to worry about stepping over the breakpoint here, that will be
473 // taken care of when the thread resumes and notices that there's a
474 // breakpoint under the pc.
476 lldb::break_id_t bp_id = bp_site->GetID();
477 // If we have an operating system plug-in, we might have set a thread
478 // specific breakpoint using the operating system thread ID, so we can't
479 // make any assumptions about the thread ID so we must always report the
480 // breakpoint regardless of the thread.
481 if (bp_site->ValidForThisThread(this) ||
482 GetProcess()->GetOperatingSystem() != nullptr)
483 SetStopInfo(StopInfo::CreateStopReasonWithBreakpointSiteID(*this, bp_id));
485 const bool should_stop = false;
486 SetStopInfo(StopInfo::CreateStopReasonWithBreakpointSiteID(*this, bp_id,
490 SetStopInfo(StopInfoSP());
493 void FreeBSDThread::WatchNotify(const ProcessMessage &message) {
494 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
496 lldb::addr_t halt_addr = message.GetHWAddress();
499 "FreeBSDThread::%s () Hardware Watchpoint Address = 0x%8.8" PRIx64,
500 __FUNCTION__, halt_addr);
502 POSIXBreakpointProtocol *reg_ctx = GetPOSIXBreakpointProtocol();
504 uint32_t num_hw_wps = reg_ctx->NumSupportedHardwareWatchpoints();
506 for (wp_idx = 0; wp_idx < num_hw_wps; wp_idx++) {
507 if (reg_ctx->IsWatchpointHit(wp_idx)) {
508 // Clear the watchpoint hit here
509 reg_ctx->ClearWatchpointHits();
514 if (wp_idx == num_hw_wps)
517 Target &target = GetProcess()->GetTarget();
518 lldb::addr_t wp_monitor_addr = reg_ctx->GetWatchpointAddress(wp_idx);
519 const WatchpointList &wp_list = target.GetWatchpointList();
520 lldb::WatchpointSP wp_sp = wp_list.FindByAddress(wp_monitor_addr);
522 assert(wp_sp.get() && "No watchpoint found");
524 StopInfo::CreateStopReasonWithWatchpointID(*this, wp_sp->GetID()));
528 void FreeBSDThread::TraceNotify(const ProcessMessage &message) {
529 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
531 // Try to resolve the breakpoint object corresponding to the current PC.
532 assert(GetRegisterContext());
533 lldb::addr_t pc = GetRegisterContext()->GetPC();
535 log->Printf("FreeBSDThread::%s () PC=0x%8.8" PRIx64, __FUNCTION__, pc);
536 lldb::BreakpointSiteSP bp_site(
537 GetProcess()->GetBreakpointSiteList().FindByAddress(pc));
539 // If the current pc is a breakpoint site then set the StopInfo to
540 // Breakpoint. Otherwise, set the StopInfo to Watchpoint or Trace. If we have
541 // an operating system plug-in, we might have set a thread specific
542 // breakpoint using the operating system thread ID, so we can't make any
543 // assumptions about the thread ID so we must always report the breakpoint
544 // regardless of the thread.
545 if (bp_site && (bp_site->ValidForThisThread(this) ||
546 GetProcess()->GetOperatingSystem() != nullptr))
547 SetStopInfo(StopInfo::CreateStopReasonWithBreakpointSiteID(
548 *this, bp_site->GetID()));
550 POSIXBreakpointProtocol *reg_ctx = GetPOSIXBreakpointProtocol();
552 uint32_t num_hw_wps = reg_ctx->NumSupportedHardwareWatchpoints();
554 for (wp_idx = 0; wp_idx < num_hw_wps; wp_idx++) {
555 if (reg_ctx->IsWatchpointHit(wp_idx)) {
556 WatchNotify(message);
561 SetStopInfo(StopInfo::CreateStopReasonToTrace(*this));
565 void FreeBSDThread::LimboNotify(const ProcessMessage &message) {
566 SetStopInfo(lldb::StopInfoSP(new POSIXLimboStopInfo(*this)));
569 void FreeBSDThread::SignalNotify(const ProcessMessage &message) {
570 int signo = message.GetSignal();
571 if (message.GetKind() == ProcessMessage::eCrashMessage) {
572 std::string stop_description = GetCrashReasonString(
573 message.GetCrashReason(), message.GetFaultAddress());
574 SetStopInfo(StopInfo::CreateStopReasonWithSignal(
575 *this, signo, stop_description.c_str()));
577 SetStopInfo(StopInfo::CreateStopReasonWithSignal(*this, signo));
581 void FreeBSDThread::SignalDeliveredNotify(const ProcessMessage &message) {
582 int signo = message.GetSignal();
583 SetStopInfo(StopInfo::CreateStopReasonWithSignal(*this, signo));
586 unsigned FreeBSDThread::GetRegisterIndexFromOffset(unsigned offset) {
587 unsigned reg = LLDB_INVALID_REGNUM;
588 ArchSpec arch = HostInfo::GetArchitecture();
590 switch (arch.GetMachine()) {
592 llvm_unreachable("CPU type not supported!");
595 case llvm::Triple::aarch64:
596 case llvm::Triple::arm:
597 case llvm::Triple::mips64:
598 case llvm::Triple::ppc:
599 case llvm::Triple::ppc64:
600 case llvm::Triple::x86:
601 case llvm::Triple::x86_64: {
602 POSIXBreakpointProtocol *reg_ctx = GetPOSIXBreakpointProtocol();
603 reg = reg_ctx->GetRegisterIndexFromOffset(offset);
609 void FreeBSDThread::ExecNotify(const ProcessMessage &message) {
610 SetStopInfo(StopInfo::CreateStopReasonWithExec(*this));
613 const char *FreeBSDThread::GetRegisterName(unsigned reg) {
614 const char *name = nullptr;
615 ArchSpec arch = HostInfo::GetArchitecture();
617 switch (arch.GetMachine()) {
619 assert(false && "CPU type not supported!");
622 case llvm::Triple::aarch64:
623 case llvm::Triple::arm:
624 case llvm::Triple::mips64:
625 case llvm::Triple::ppc:
626 case llvm::Triple::ppc64:
627 case llvm::Triple::x86:
628 case llvm::Triple::x86_64:
629 name = GetRegisterContext()->GetRegisterName(reg);
635 const char *FreeBSDThread::GetRegisterNameFromOffset(unsigned offset) {
636 return GetRegisterName(GetRegisterIndexFromOffset(offset));