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(NULL) {
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
73 // has been created since that watchpoint was enabled. Since
74 // the POSIXBreakpointProtocol has yet to be initialized, its
75 // m_watchpoints_initialized member will be FALSE. Attempting to
76 // read the debug status register to determine if a watchpoint
77 // has been hit would result in the zeroing of that register.
78 // Since the active debug registers would have been cloned when
79 // this thread was created, simply force the m_watchpoints_initized
80 // member to TRUE and avoid resetting dr6 and dr7.
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
103 // if (StateIsStoppedState(GetState())
105 const bool force = false;
106 GetRegisterContext()->InvalidateIfNeeded(force);
110 const char *FreeBSDThread::GetInfo() { return NULL; }
112 void FreeBSDThread::SetName(const char *name) {
113 m_thread_name_valid = (name && name[0]);
114 if (m_thread_name_valid)
115 m_thread_name.assign(name);
117 m_thread_name.clear();
120 const char *FreeBSDThread::GetName() {
121 if (!m_thread_name_valid) {
122 m_thread_name.clear();
123 int pid = GetProcess()->GetID();
125 struct kinfo_proc *kp = nullptr, *nkp;
128 int ctl[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID | KERN_PROC_INC_THREAD,
132 error = sysctl(ctl, 4, kp, &len, nullptr, 0);
133 if (kp == nullptr || (error != 0 && errno == ENOMEM)) {
134 // Add extra space in case threads are added before next call.
135 len += sizeof(*kp) + len / 10;
136 nkp = (struct kinfo_proc *)realloc(kp, len);
137 if (nkp == nullptr) {
149 for (size_t i = 0; i < len / sizeof(*kp); i++) {
150 if (kp[i].ki_tid == (lwpid_t)GetID()) {
151 m_thread_name.append(kp[i].ki_tdname,
152 kp[i].ki_tdname + strlen(kp[i].ki_tdname));
157 m_thread_name_valid = true;
160 if (m_thread_name.empty())
162 return m_thread_name.c_str();
165 lldb::RegisterContextSP FreeBSDThread::GetRegisterContext() {
166 if (!m_reg_context_sp) {
167 m_posix_thread = NULL;
169 RegisterInfoInterface *reg_interface = NULL;
170 const ArchSpec &target_arch = GetProcess()->GetTarget().GetArchitecture();
172 assert(target_arch.GetTriple().getOS() == llvm::Triple::FreeBSD);
173 switch (target_arch.GetMachine()) {
174 case llvm::Triple::aarch64:
175 reg_interface = new RegisterInfoPOSIX_arm64(target_arch);
177 case llvm::Triple::arm:
178 reg_interface = new RegisterInfoPOSIX_arm(target_arch);
180 case llvm::Triple::ppc:
181 #ifndef __powerpc64__
182 reg_interface = new RegisterContextFreeBSD_powerpc32(target_arch);
185 case llvm::Triple::ppc64:
186 reg_interface = new RegisterContextFreeBSD_powerpc64(target_arch);
188 case llvm::Triple::mips64:
189 reg_interface = new RegisterContextFreeBSD_mips64(target_arch);
191 case llvm::Triple::x86:
192 reg_interface = new RegisterContextFreeBSD_i386(target_arch);
194 case llvm::Triple::x86_64:
195 reg_interface = new RegisterContextFreeBSD_x86_64(target_arch);
198 llvm_unreachable("CPU not supported");
201 switch (target_arch.GetMachine()) {
202 case llvm::Triple::aarch64: {
203 RegisterContextPOSIXProcessMonitor_arm64 *reg_ctx =
204 new RegisterContextPOSIXProcessMonitor_arm64(*this, 0, reg_interface);
205 m_posix_thread = reg_ctx;
206 m_reg_context_sp.reset(reg_ctx);
209 case llvm::Triple::arm: {
210 RegisterContextPOSIXProcessMonitor_arm *reg_ctx =
211 new RegisterContextPOSIXProcessMonitor_arm(*this, 0, reg_interface);
212 m_posix_thread = reg_ctx;
213 m_reg_context_sp.reset(reg_ctx);
216 case llvm::Triple::mips64: {
217 RegisterContextPOSIXProcessMonitor_mips64 *reg_ctx =
218 new RegisterContextPOSIXProcessMonitor_mips64(*this, 0,
220 m_posix_thread = reg_ctx;
221 m_reg_context_sp.reset(reg_ctx);
224 case llvm::Triple::ppc:
225 case llvm::Triple::ppc64: {
226 RegisterContextPOSIXProcessMonitor_powerpc *reg_ctx =
227 new RegisterContextPOSIXProcessMonitor_powerpc(*this, 0,
229 m_posix_thread = reg_ctx;
230 m_reg_context_sp.reset(reg_ctx);
233 case llvm::Triple::x86:
234 case llvm::Triple::x86_64: {
235 RegisterContextPOSIXProcessMonitor_x86_64 *reg_ctx =
236 new RegisterContextPOSIXProcessMonitor_x86_64(*this, 0,
238 m_posix_thread = reg_ctx;
239 m_reg_context_sp.reset(reg_ctx);
246 return m_reg_context_sp;
249 lldb::RegisterContextSP
250 FreeBSDThread::CreateRegisterContextForFrame(lldb_private::StackFrame *frame) {
251 lldb::RegisterContextSP reg_ctx_sp;
252 uint32_t concrete_frame_idx = 0;
254 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
255 LLDB_LOGV(log, "called");
258 concrete_frame_idx = frame->GetConcreteFrameIndex();
260 if (concrete_frame_idx == 0)
261 reg_ctx_sp = GetRegisterContext();
263 assert(GetUnwinder());
264 reg_ctx_sp = GetUnwinder()->CreateRegisterContextForFrame(frame);
270 lldb::addr_t FreeBSDThread::GetThreadPointer() {
271 ProcessMonitor &monitor = GetMonitor();
273 if (monitor.ReadThreadPointer(GetID(), addr))
276 return LLDB_INVALID_ADDRESS;
279 bool FreeBSDThread::CalculateStopInfo() {
280 SetStopInfo(m_stop_info_sp);
284 Unwind *FreeBSDThread::GetUnwinder() {
285 if (m_unwinder_ap.get() == NULL)
286 m_unwinder_ap.reset(new UnwindLLDB(*this));
288 return m_unwinder_ap.get();
291 void FreeBSDThread::DidStop() {
292 // Don't set the thread state to stopped unless we really stopped.
295 void FreeBSDThread::WillResume(lldb::StateType resume_state) {
296 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
298 log->Printf("tid %" PRIu64 " resume_state = %s", GetID(),
299 lldb_private::StateAsCString(resume_state));
300 ProcessSP process_sp(GetProcess());
301 ProcessFreeBSD *process = static_cast<ProcessFreeBSD *>(process_sp.get());
302 int signo = GetResumeSignal();
303 bool signo_valid = process->GetUnixSignals()->SignalIsValid(signo);
305 switch (resume_state) {
306 case eStateSuspended:
308 process->m_suspend_tids.push_back(GetID());
311 process->m_run_tids.push_back(GetID());
313 process->m_resume_signo = signo;
316 process->m_step_tids.push_back(GetID());
318 process->m_resume_signo = signo;
325 bool FreeBSDThread::Resume() {
326 lldb::StateType resume_state = GetResumeState();
327 ProcessMonitor &monitor = GetMonitor();
330 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
332 log->Printf("FreeBSDThread::%s (), resume_state = %s", __FUNCTION__,
333 StateAsCString(resume_state));
335 switch (resume_state) {
337 assert(false && "Unexpected state for resume!");
341 case lldb::eStateRunning:
342 SetState(resume_state);
343 status = monitor.Resume(GetID(), GetResumeSignal());
346 case lldb::eStateStepping:
347 SetState(resume_state);
348 status = monitor.SingleStep(GetID(), GetResumeSignal());
350 case lldb::eStateStopped:
351 case lldb::eStateSuspended:
359 void FreeBSDThread::Notify(const ProcessMessage &message) {
360 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
362 log->Printf("FreeBSDThread::%s () message kind = '%s' for tid %" PRIu64,
363 __FUNCTION__, message.PrintKind(), GetID());
365 switch (message.GetKind()) {
367 assert(false && "Unexpected message kind!");
370 case ProcessMessage::eExitMessage:
371 // Nothing to be done.
374 case ProcessMessage::eLimboMessage:
375 LimboNotify(message);
378 case ProcessMessage::eCrashMessage:
379 case ProcessMessage::eSignalMessage:
380 SignalNotify(message);
383 case ProcessMessage::eSignalDeliveredMessage:
384 SignalDeliveredNotify(message);
387 case ProcessMessage::eTraceMessage:
388 TraceNotify(message);
391 case ProcessMessage::eBreakpointMessage:
392 BreakNotify(message);
395 case ProcessMessage::eWatchpointMessage:
396 WatchNotify(message);
399 case ProcessMessage::eExecMessage:
405 bool FreeBSDThread::EnableHardwareWatchpoint(Watchpoint *wp) {
408 addr_t wp_addr = wp->GetLoadAddress();
409 size_t wp_size = wp->GetByteSize();
410 bool wp_read = wp->WatchpointRead();
411 bool wp_write = wp->WatchpointWrite();
412 uint32_t wp_hw_index = wp->GetHardwareIndex();
413 POSIXBreakpointProtocol *reg_ctx = GetPOSIXBreakpointProtocol();
415 wp_set = reg_ctx->SetHardwareWatchpointWithIndex(
416 wp_addr, wp_size, wp_read, wp_write, wp_hw_index);
421 bool FreeBSDThread::DisableHardwareWatchpoint(Watchpoint *wp) {
424 lldb::RegisterContextSP reg_ctx_sp = GetRegisterContext();
425 if (reg_ctx_sp.get())
426 result = reg_ctx_sp->ClearHardwareWatchpoint(wp->GetHardwareIndex());
431 uint32_t FreeBSDThread::NumSupportedHardwareWatchpoints() {
432 lldb::RegisterContextSP reg_ctx_sp = GetRegisterContext();
433 if (reg_ctx_sp.get())
434 return reg_ctx_sp->NumSupportedHardwareWatchpoints();
438 uint32_t FreeBSDThread::FindVacantWatchpointIndex() {
439 uint32_t hw_index = LLDB_INVALID_INDEX32;
440 uint32_t num_hw_wps = NumSupportedHardwareWatchpoints();
442 POSIXBreakpointProtocol *reg_ctx = GetPOSIXBreakpointProtocol();
444 for (wp_idx = 0; wp_idx < num_hw_wps; wp_idx++) {
445 if (reg_ctx->IsWatchpointVacant(wp_idx)) {
454 void FreeBSDThread::BreakNotify(const ProcessMessage &message) {
456 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
458 assert(GetRegisterContext());
459 status = GetPOSIXBreakpointProtocol()->UpdateAfterBreakpoint();
460 assert(status && "Breakpoint update failed!");
462 // With our register state restored, resolve the breakpoint object
463 // corresponding to our current PC.
464 assert(GetRegisterContext());
465 lldb::addr_t pc = GetRegisterContext()->GetPC();
467 log->Printf("FreeBSDThread::%s () PC=0x%8.8" PRIx64, __FUNCTION__, pc);
468 lldb::BreakpointSiteSP bp_site(
469 GetProcess()->GetBreakpointSiteList().FindByAddress(pc));
471 // If the breakpoint is for this thread, then we'll report the hit, but if it
472 // is for another thread,
473 // we create a stop reason with should_stop=false. If there is no breakpoint
474 // location, then report
475 // an invalid stop reason. We don't need to worry about stepping over the
476 // breakpoint here, that will
477 // be taken care of when the thread resumes and notices that there's a
478 // breakpoint under the pc.
480 lldb::break_id_t bp_id = bp_site->GetID();
481 // If we have an operating system plug-in, we might have set a thread
482 // specific breakpoint using the
483 // operating system thread ID, so we can't make any assumptions about the
484 // thread ID so we must always
485 // report the breakpoint regardless of the thread.
486 if (bp_site->ValidForThisThread(this) ||
487 GetProcess()->GetOperatingSystem() != NULL)
488 SetStopInfo(StopInfo::CreateStopReasonWithBreakpointSiteID(*this, bp_id));
490 const bool should_stop = false;
491 SetStopInfo(StopInfo::CreateStopReasonWithBreakpointSiteID(*this, bp_id,
495 SetStopInfo(StopInfoSP());
498 void FreeBSDThread::WatchNotify(const ProcessMessage &message) {
499 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
501 lldb::addr_t halt_addr = message.GetHWAddress();
504 "FreeBSDThread::%s () Hardware Watchpoint Address = 0x%8.8" PRIx64,
505 __FUNCTION__, halt_addr);
507 POSIXBreakpointProtocol *reg_ctx = GetPOSIXBreakpointProtocol();
509 uint32_t num_hw_wps = reg_ctx->NumSupportedHardwareWatchpoints();
511 for (wp_idx = 0; wp_idx < num_hw_wps; wp_idx++) {
512 if (reg_ctx->IsWatchpointHit(wp_idx)) {
513 // Clear the watchpoint hit here
514 reg_ctx->ClearWatchpointHits();
519 if (wp_idx == num_hw_wps)
522 Target &target = GetProcess()->GetTarget();
523 lldb::addr_t wp_monitor_addr = reg_ctx->GetWatchpointAddress(wp_idx);
524 const WatchpointList &wp_list = target.GetWatchpointList();
525 lldb::WatchpointSP wp_sp = wp_list.FindByAddress(wp_monitor_addr);
527 assert(wp_sp.get() && "No watchpoint found");
529 StopInfo::CreateStopReasonWithWatchpointID(*this, wp_sp->GetID()));
533 void FreeBSDThread::TraceNotify(const ProcessMessage &message) {
534 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
536 // Try to resolve the breakpoint object corresponding to the current PC.
537 assert(GetRegisterContext());
538 lldb::addr_t pc = GetRegisterContext()->GetPC();
540 log->Printf("FreeBSDThread::%s () PC=0x%8.8" PRIx64, __FUNCTION__, pc);
541 lldb::BreakpointSiteSP bp_site(
542 GetProcess()->GetBreakpointSiteList().FindByAddress(pc));
544 // If the current pc is a breakpoint site then set the StopInfo to Breakpoint.
545 // Otherwise, set the StopInfo to Watchpoint or Trace.
546 // If we have an operating system plug-in, we might have set a thread specific
547 // breakpoint using the
548 // operating system thread ID, so we can't make any assumptions about the
549 // thread ID so we must always
550 // report the breakpoint regardless of the thread.
551 if (bp_site && (bp_site->ValidForThisThread(this) ||
552 GetProcess()->GetOperatingSystem() != NULL))
553 SetStopInfo(StopInfo::CreateStopReasonWithBreakpointSiteID(
554 *this, bp_site->GetID()));
556 POSIXBreakpointProtocol *reg_ctx = GetPOSIXBreakpointProtocol();
558 uint32_t num_hw_wps = reg_ctx->NumSupportedHardwareWatchpoints();
560 for (wp_idx = 0; wp_idx < num_hw_wps; wp_idx++) {
561 if (reg_ctx->IsWatchpointHit(wp_idx)) {
562 WatchNotify(message);
567 SetStopInfo(StopInfo::CreateStopReasonToTrace(*this));
571 void FreeBSDThread::LimboNotify(const ProcessMessage &message) {
572 SetStopInfo(lldb::StopInfoSP(new POSIXLimboStopInfo(*this)));
575 void FreeBSDThread::SignalNotify(const ProcessMessage &message) {
576 int signo = message.GetSignal();
577 if (message.GetKind() == ProcessMessage::eCrashMessage) {
578 std::string stop_description = GetCrashReasonString(
579 message.GetCrashReason(), message.GetFaultAddress());
580 SetStopInfo(StopInfo::CreateStopReasonWithSignal(
581 *this, signo, stop_description.c_str()));
583 SetStopInfo(StopInfo::CreateStopReasonWithSignal(*this, signo));
587 void FreeBSDThread::SignalDeliveredNotify(const ProcessMessage &message) {
588 int signo = message.GetSignal();
589 SetStopInfo(StopInfo::CreateStopReasonWithSignal(*this, signo));
592 unsigned FreeBSDThread::GetRegisterIndexFromOffset(unsigned offset) {
593 unsigned reg = LLDB_INVALID_REGNUM;
594 ArchSpec arch = HostInfo::GetArchitecture();
596 switch (arch.GetMachine()) {
598 llvm_unreachable("CPU type not supported!");
601 case llvm::Triple::aarch64:
602 case llvm::Triple::arm:
603 case llvm::Triple::mips64:
604 case llvm::Triple::ppc:
605 case llvm::Triple::ppc64:
606 case llvm::Triple::x86:
607 case llvm::Triple::x86_64: {
608 POSIXBreakpointProtocol *reg_ctx = GetPOSIXBreakpointProtocol();
609 reg = reg_ctx->GetRegisterIndexFromOffset(offset);
615 void FreeBSDThread::ExecNotify(const ProcessMessage &message) {
616 SetStopInfo(StopInfo::CreateStopReasonWithExec(*this));
619 const char *FreeBSDThread::GetRegisterName(unsigned reg) {
620 const char *name = nullptr;
621 ArchSpec arch = HostInfo::GetArchitecture();
623 switch (arch.GetMachine()) {
625 assert(false && "CPU type not supported!");
628 case llvm::Triple::aarch64:
629 case llvm::Triple::arm:
630 case llvm::Triple::mips64:
631 case llvm::Triple::ppc:
632 case llvm::Triple::ppc64:
633 case llvm::Triple::x86:
634 case llvm::Triple::x86_64:
635 name = GetRegisterContext()->GetRegisterName(reg);
641 const char *FreeBSDThread::GetRegisterNameFromOffset(unsigned offset) {
642 return GetRegisterName(GetRegisterIndexFromOffset(offset));