1 //===-- ProcessFreeBSD.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 //===----------------------------------------------------------------------===//
14 #include <pthread_np.h>
16 #include <sys/sysctl.h>
17 #include <sys/types.h>
19 #include <machine/elf.h>
23 #include <unordered_map>
25 // Other libraries and framework includes
26 #include "lldb/Core/PluginManager.h"
27 #include "lldb/Core/RegisterValue.h"
28 #include "lldb/Core/State.h"
29 #include "lldb/Host/Host.h"
30 #include "lldb/Symbol/ObjectFile.h"
31 #include "lldb/Target/DynamicLoader.h"
32 #include "lldb/Target/Target.h"
34 #include "FreeBSDThread.h"
35 #include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
36 #include "Plugins/Process/Utility/FreeBSDSignals.h"
37 #include "Plugins/Process/Utility/InferiorCallPOSIX.h"
38 #include "ProcessFreeBSD.h"
39 #include "ProcessMonitor.h"
41 // Other libraries and framework includes
42 #include "lldb/Breakpoint/BreakpointLocation.h"
43 #include "lldb/Breakpoint/Watchpoint.h"
44 #include "lldb/Core/Module.h"
45 #include "lldb/Core/ModuleSpec.h"
46 #include "lldb/Core/PluginManager.h"
47 #include "lldb/Core/State.h"
48 #include "lldb/Host/Host.h"
49 #include "lldb/Symbol/ObjectFile.h"
50 #include "lldb/Target/DynamicLoader.h"
51 #include "lldb/Target/Platform.h"
52 #include "lldb/Target/Target.h"
53 #include "lldb/Utility/DataBufferHeap.h"
54 #include "lldb/Utility/FileSpec.h"
56 #include "lldb/Host/posix/Fcntl.h"
58 #include "llvm/Support/FileSystem.h"
59 #include "llvm/Support/Threading.h"
62 using namespace lldb_private;
65 UnixSignalsSP &GetFreeBSDSignals() {
66 static UnixSignalsSP s_freebsd_signals_sp(new FreeBSDSignals());
67 return s_freebsd_signals_sp;
71 //------------------------------------------------------------------------------
75 ProcessFreeBSD::CreateInstance(lldb::TargetSP target_sp,
76 lldb::ListenerSP listener_sp,
77 const FileSpec *crash_file_path) {
78 lldb::ProcessSP process_sp;
79 if (crash_file_path == NULL)
81 new ProcessFreeBSD(target_sp, listener_sp, GetFreeBSDSignals()));
85 void ProcessFreeBSD::Initialize() {
86 static llvm::once_flag g_once_flag;
88 llvm::call_once(g_once_flag, []() {
89 PluginManager::RegisterPlugin(GetPluginNameStatic(),
90 GetPluginDescriptionStatic(), CreateInstance);
94 lldb_private::ConstString ProcessFreeBSD::GetPluginNameStatic() {
95 static ConstString g_name("freebsd");
99 const char *ProcessFreeBSD::GetPluginDescriptionStatic() {
100 return "Process plugin for FreeBSD";
103 //------------------------------------------------------------------------------
104 // ProcessInterface protocol.
106 lldb_private::ConstString ProcessFreeBSD::GetPluginName() {
107 return GetPluginNameStatic();
110 uint32_t ProcessFreeBSD::GetPluginVersion() { return 1; }
112 void ProcessFreeBSD::Terminate() {}
114 Status ProcessFreeBSD::DoDetach(bool keep_stopped) {
117 error.SetErrorString("Detaching with keep_stopped true is not currently "
118 "supported on FreeBSD.");
122 error = m_monitor->Detach(GetID());
125 SetPrivateState(eStateDetached);
130 Status ProcessFreeBSD::DoResume() {
131 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
133 SetPrivateState(eStateRunning);
135 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
136 bool do_step = false;
137 bool software_single_step = !SupportHardwareSingleStepping();
139 for (tid_collection::const_iterator t_pos = m_run_tids.begin(),
140 t_end = m_run_tids.end();
141 t_pos != t_end; ++t_pos) {
142 m_monitor->ThreadSuspend(*t_pos, false);
144 for (tid_collection::const_iterator t_pos = m_step_tids.begin(),
145 t_end = m_step_tids.end();
146 t_pos != t_end; ++t_pos) {
147 m_monitor->ThreadSuspend(*t_pos, false);
149 if (software_single_step) {
150 Status error = SetupSoftwareSingleStepping(*t_pos);
155 for (tid_collection::const_iterator t_pos = m_suspend_tids.begin(),
156 t_end = m_suspend_tids.end();
157 t_pos != t_end; ++t_pos) {
158 m_monitor->ThreadSuspend(*t_pos, true);
159 // XXX Cannot PT_CONTINUE properly with suspended threads.
164 log->Printf("process %" PRIu64 " resuming (%s)", GetID(),
165 do_step ? "step" : "continue");
166 if (do_step && !software_single_step)
167 m_monitor->SingleStep(GetID(), m_resume_signo);
169 m_monitor->Resume(GetID(), m_resume_signo);
174 bool ProcessFreeBSD::UpdateThreadList(ThreadList &old_thread_list,
175 ThreadList &new_thread_list) {
176 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
178 log->Printf("ProcessFreeBSD::%s (pid = %" PRIu64 ")", __FUNCTION__,
181 std::vector<lldb::pid_t> tds;
182 if (!GetMonitor().GetCurrentThreadIDs(tds)) {
186 ThreadList old_thread_list_copy(old_thread_list);
187 for (size_t i = 0; i < tds.size(); ++i) {
189 ThreadSP thread_sp(old_thread_list_copy.RemoveThreadByID(tid, false));
191 thread_sp.reset(new FreeBSDThread(*this, tid));
193 log->Printf("ProcessFreeBSD::%s new tid = %" PRIu64, __FUNCTION__, tid);
196 log->Printf("ProcessFreeBSD::%s existing tid = %" PRIu64, __FUNCTION__,
199 new_thread_list.AddThread(thread_sp);
201 for (size_t i = 0; i < old_thread_list_copy.GetSize(false); ++i) {
202 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
205 log->Printf("ProcessFreeBSD::%s remove tid", __FUNCTION__);
212 Status ProcessFreeBSD::WillResume() {
214 m_suspend_tids.clear();
217 return Process::WillResume();
220 void ProcessFreeBSD::SendMessage(const ProcessMessage &message) {
221 std::lock_guard<std::recursive_mutex> guard(m_message_mutex);
223 switch (message.GetKind()) {
224 case ProcessMessage::eInvalidMessage:
227 case ProcessMessage::eAttachMessage:
228 SetPrivateState(eStateStopped);
231 case ProcessMessage::eLimboMessage:
232 case ProcessMessage::eExitMessage:
233 SetExitStatus(message.GetExitStatus(), NULL);
236 case ProcessMessage::eSignalMessage:
237 case ProcessMessage::eSignalDeliveredMessage:
238 case ProcessMessage::eBreakpointMessage:
239 case ProcessMessage::eTraceMessage:
240 case ProcessMessage::eWatchpointMessage:
241 case ProcessMessage::eCrashMessage:
242 SetPrivateState(eStateStopped);
245 case ProcessMessage::eNewThreadMessage:
246 llvm_unreachable("eNewThreadMessage unexpected on FreeBSD");
249 case ProcessMessage::eExecMessage:
250 SetPrivateState(eStateStopped);
254 m_message_queue.push(message);
257 //------------------------------------------------------------------------------
258 // Constructors and destructors.
260 ProcessFreeBSD::ProcessFreeBSD(lldb::TargetSP target_sp,
261 lldb::ListenerSP listener_sp,
262 UnixSignalsSP &unix_signals_sp)
263 : Process(target_sp, listener_sp, unix_signals_sp),
264 m_byte_order(endian::InlHostByteOrder()), m_monitor(NULL), m_module(NULL),
265 m_message_mutex(), m_exit_now(false), m_seen_initial_stop(),
267 // FIXME: Putting this code in the ctor and saving the byte order in a
268 // member variable is a hack to avoid const qual issues in GetByteOrder.
269 lldb::ModuleSP module = GetTarget().GetExecutableModule();
270 if (module && module->GetObjectFile())
271 m_byte_order = module->GetObjectFile()->GetByteOrder();
274 ProcessFreeBSD::~ProcessFreeBSD() { delete m_monitor; }
276 //------------------------------------------------------------------------------
278 void ProcessFreeBSD::Finalize() {
282 m_monitor->StopMonitor();
285 bool ProcessFreeBSD::CanDebug(lldb::TargetSP target_sp,
286 bool plugin_specified_by_name) {
287 // For now we are just making sure the file exists for a given module
288 ModuleSP exe_module_sp(target_sp->GetExecutableModule());
289 if (exe_module_sp.get())
290 return exe_module_sp->GetFileSpec().Exists();
291 // If there is no executable module, we return true since we might be
292 // preparing to attach.
297 ProcessFreeBSD::DoAttachToProcessWithID(lldb::pid_t pid,
298 const ProcessAttachInfo &attach_info) {
300 assert(m_monitor == NULL);
302 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
303 LLDB_LOGV(log, "pid = {0}", GetID());
305 m_monitor = new ProcessMonitor(this, pid, error);
307 if (!error.Success())
310 PlatformSP platform_sp(GetTarget().GetPlatform());
311 assert(platform_sp.get());
313 return error; // FIXME: Detatch?
315 // Find out what we can about this process
316 ProcessInstanceInfo process_info;
317 platform_sp->GetProcessInfo(pid, process_info);
319 // Resolve the executable module
320 ModuleSP exe_module_sp;
321 FileSpecList executable_search_paths(
322 Target::GetDefaultExecutableSearchPaths());
323 ModuleSpec exe_module_spec(process_info.GetExecutableFile(),
324 GetTarget().GetArchitecture());
325 error = platform_sp->ResolveExecutable(
326 exe_module_spec, exe_module_sp,
327 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
328 if (!error.Success())
331 // Fix the target architecture if necessary
332 const ArchSpec &module_arch = exe_module_sp->GetArchitecture();
333 if (module_arch.IsValid() &&
334 !GetTarget().GetArchitecture().IsExactMatch(module_arch))
335 GetTarget().SetArchitecture(module_arch);
337 // Initialize the target module list
338 GetTarget().SetExecutableModule(exe_module_sp, true);
340 SetSTDIOFileDescriptor(m_monitor->GetTerminalFD());
347 Status ProcessFreeBSD::WillLaunch(Module *module) {
353 ProcessFreeBSD::GetFileSpec(const lldb_private::FileAction *file_action,
354 const FileSpec &default_file_spec,
355 const FileSpec &dbg_pts_file_spec) {
356 FileSpec file_spec{};
358 if (file_action && file_action->GetAction() == FileAction::eFileActionOpen) {
359 file_spec = file_action->GetFileSpec();
360 // By default the stdio paths passed in will be pseudo-terminal
361 // (/dev/pts). If so, convert to using a different default path
362 // instead to redirect I/O to the debugger console. This should
363 // also handle user overrides to /dev/null or a different file.
364 if (!file_spec || file_spec == dbg_pts_file_spec)
365 file_spec = default_file_spec;
370 Status ProcessFreeBSD::DoLaunch(Module *module,
371 ProcessLaunchInfo &launch_info) {
373 assert(m_monitor == NULL);
375 FileSpec working_dir = launch_info.GetWorkingDirectory();
376 namespace fs = llvm::sys::fs;
377 if (working_dir && (!working_dir.ResolvePath() ||
378 !fs::is_directory(working_dir.GetPath()))) {
379 error.SetErrorStringWithFormat("No such file or directory: %s",
380 working_dir.GetCString());
384 SetPrivateState(eStateLaunching);
386 const lldb_private::FileAction *file_action;
388 // Default of empty will mean to use existing open file descriptors
389 FileSpec stdin_file_spec{};
390 FileSpec stdout_file_spec{};
391 FileSpec stderr_file_spec{};
393 const FileSpec dbg_pts_file_spec{launch_info.GetPTY().GetSlaveName(NULL, 0),
396 file_action = launch_info.GetFileActionForFD(STDIN_FILENO);
398 GetFileSpec(file_action, stdin_file_spec, dbg_pts_file_spec);
400 file_action = launch_info.GetFileActionForFD(STDOUT_FILENO);
402 GetFileSpec(file_action, stdout_file_spec, dbg_pts_file_spec);
404 file_action = launch_info.GetFileActionForFD(STDERR_FILENO);
406 GetFileSpec(file_action, stderr_file_spec, dbg_pts_file_spec);
408 m_monitor = new ProcessMonitor(
409 this, module, launch_info.GetArguments().GetConstArgumentVector(),
410 launch_info.GetEnvironmentEntries().GetConstArgumentVector(),
411 stdin_file_spec, stdout_file_spec, stderr_file_spec, working_dir,
416 if (!error.Success())
419 int terminal = m_monitor->GetTerminalFD();
421 // The reader thread will close the file descriptor when done, so we pass it a
423 #ifdef F_DUPFD_CLOEXEC
424 int stdio = fcntl(terminal, F_DUPFD_CLOEXEC, 0);
426 error.SetErrorToErrno();
430 // Special case when F_DUPFD_CLOEXEC does not exist (Debian kFreeBSD)
431 int stdio = fcntl(terminal, F_DUPFD, 0);
433 error.SetErrorToErrno();
436 stdio = fcntl(terminal, F_SETFD, FD_CLOEXEC);
438 error.SetErrorToErrno();
442 SetSTDIOFileDescriptor(stdio);
445 SetID(m_monitor->GetPID());
449 void ProcessFreeBSD::DidLaunch() {}
451 addr_t ProcessFreeBSD::GetImageInfoAddress() {
452 Target *target = &GetTarget();
453 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
454 Address addr = obj_file->GetImageInfoAddress(target);
457 return addr.GetLoadAddress(target);
458 return LLDB_INVALID_ADDRESS;
461 Status ProcessFreeBSD::DoHalt(bool &caused_stop) {
466 } else if (kill(GetID(), SIGSTOP)) {
468 error.SetErrorToErrno();
475 Status ProcessFreeBSD::DoSignal(int signal) {
478 if (kill(GetID(), signal))
479 error.SetErrorToErrno();
484 Status ProcessFreeBSD::DoDestroy() {
490 if (GetID() == LLDB_INVALID_PROCESS_ID) {
491 error.SetErrorString("invalid process id");
494 if (!m_monitor->Kill()) {
495 error.SetErrorToErrno();
499 SetPrivateState(eStateExited);
505 void ProcessFreeBSD::DoDidExec() {
506 Target *target = &GetTarget();
508 PlatformSP platform_sp(target->GetPlatform());
509 assert(platform_sp.get());
511 ProcessInstanceInfo process_info;
512 platform_sp->GetProcessInfo(GetID(), process_info);
513 ModuleSP exe_module_sp;
514 ModuleSpec exe_module_spec(process_info.GetExecutableFile(),
515 target->GetArchitecture());
516 FileSpecList executable_search_paths(
517 Target::GetDefaultExecutableSearchPaths());
518 Status error = platform_sp->ResolveExecutable(
519 exe_module_spec, exe_module_sp,
520 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
521 if (!error.Success())
523 target->SetExecutableModule(exe_module_sp, true);
528 bool ProcessFreeBSD::AddThreadForInitialStopIfNeeded(lldb::tid_t stop_tid) {
529 bool added_to_set = false;
530 ThreadStopSet::iterator it = m_seen_initial_stop.find(stop_tid);
531 if (it == m_seen_initial_stop.end()) {
532 m_seen_initial_stop.insert(stop_tid);
538 bool ProcessFreeBSD::WaitingForInitialStop(lldb::tid_t stop_tid) {
539 return (m_seen_initial_stop.find(stop_tid) == m_seen_initial_stop.end());
543 ProcessFreeBSD::CreateNewFreeBSDThread(lldb_private::Process &process,
545 return new FreeBSDThread(process, tid);
548 void ProcessFreeBSD::RefreshStateAfterStop() {
549 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
550 LLDB_LOGV(log, "message_queue size = {0}", m_message_queue.size());
552 std::lock_guard<std::recursive_mutex> guard(m_message_mutex);
554 // This method used to only handle one message. Changing it to loop allows
555 // it to handle the case where we hit a breakpoint while handling a different
557 while (!m_message_queue.empty()) {
558 ProcessMessage &message = m_message_queue.front();
560 // Resolve the thread this message corresponds to and pass it along.
561 lldb::tid_t tid = message.GetTID();
562 LLDB_LOGV(log, " message_queue size = {0}, pid = {1}",
563 m_message_queue.size(), tid);
565 m_thread_list.RefreshStateAfterStop();
567 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
568 GetThreadList().FindThreadByID(tid, false).get());
570 thread->Notify(message);
572 if (message.GetKind() == ProcessMessage::eExitMessage) {
573 // FIXME: We should tell the user about this, but the limbo message is
574 // probably better for that.
575 LLDB_LOG(log, "removing thread, tid = {0}", tid);
576 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
578 ThreadSP thread_sp = m_thread_list.RemoveThreadByID(tid, false);
580 m_seen_initial_stop.erase(tid);
583 m_message_queue.pop();
587 bool ProcessFreeBSD::IsAlive() {
588 StateType state = GetPrivateState();
589 return state != eStateDetached && state != eStateExited &&
590 state != eStateInvalid && state != eStateUnloaded;
593 size_t ProcessFreeBSD::DoReadMemory(addr_t vm_addr, void *buf, size_t size,
596 return m_monitor->ReadMemory(vm_addr, buf, size, error);
599 size_t ProcessFreeBSD::DoWriteMemory(addr_t vm_addr, const void *buf,
600 size_t size, Status &error) {
602 return m_monitor->WriteMemory(vm_addr, buf, size, error);
605 addr_t ProcessFreeBSD::DoAllocateMemory(size_t size, uint32_t permissions,
607 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
610 if (permissions & lldb::ePermissionsReadable)
611 prot |= eMmapProtRead;
612 if (permissions & lldb::ePermissionsWritable)
613 prot |= eMmapProtWrite;
614 if (permissions & lldb::ePermissionsExecutable)
615 prot |= eMmapProtExec;
617 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
618 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
619 m_addr_to_mmap_size[allocated_addr] = size;
622 allocated_addr = LLDB_INVALID_ADDRESS;
623 error.SetErrorStringWithFormat(
624 "unable to allocate %zu bytes of memory with permissions %s", size,
625 GetPermissionsAsCString(permissions));
628 return allocated_addr;
631 Status ProcessFreeBSD::DoDeallocateMemory(lldb::addr_t addr) {
633 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
634 if (pos != m_addr_to_mmap_size.end() &&
635 InferiorCallMunmap(this, addr, pos->second))
636 m_addr_to_mmap_size.erase(pos);
638 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64,
645 ProcessFreeBSD::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
646 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xD4};
647 static const uint8_t g_i386_opcode[] = {0xCC};
649 ArchSpec arch = GetTarget().GetArchitecture();
650 const uint8_t *opcode = NULL;
651 size_t opcode_size = 0;
653 switch (arch.GetMachine()) {
655 assert(false && "CPU type not supported!");
658 case llvm::Triple::arm: {
659 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe
660 // but the linux kernel does otherwise.
661 static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
662 static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
664 lldb::BreakpointLocationSP bp_loc_sp(bp_site->GetOwnerAtIndex(0));
665 AddressClass addr_class = eAddressClassUnknown;
668 addr_class = bp_loc_sp->GetAddress().GetAddressClass();
670 if (addr_class == eAddressClassCodeAlternateISA ||
671 (addr_class == eAddressClassUnknown &&
672 bp_loc_sp->GetAddress().GetOffset() & 1)) {
673 opcode = g_thumb_breakpoint_opcode;
674 opcode_size = sizeof(g_thumb_breakpoint_opcode);
676 opcode = g_arm_breakpoint_opcode;
677 opcode_size = sizeof(g_arm_breakpoint_opcode);
680 case llvm::Triple::aarch64:
681 opcode = g_aarch64_opcode;
682 opcode_size = sizeof(g_aarch64_opcode);
685 case llvm::Triple::x86:
686 case llvm::Triple::x86_64:
687 opcode = g_i386_opcode;
688 opcode_size = sizeof(g_i386_opcode);
692 bp_site->SetTrapOpcode(opcode, opcode_size);
696 Status ProcessFreeBSD::EnableBreakpointSite(BreakpointSite *bp_site) {
697 return EnableSoftwareBreakpoint(bp_site);
700 Status ProcessFreeBSD::DisableBreakpointSite(BreakpointSite *bp_site) {
701 return DisableSoftwareBreakpoint(bp_site);
704 Status ProcessFreeBSD::EnableWatchpoint(Watchpoint *wp, bool notify) {
707 user_id_t watchID = wp->GetID();
708 addr_t addr = wp->GetLoadAddress();
709 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
711 log->Printf("ProcessFreeBSD::EnableWatchpoint(watchID = %" PRIu64 ")",
713 if (wp->IsEnabled()) {
715 log->Printf("ProcessFreeBSD::EnableWatchpoint(watchID = %" PRIu64
716 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
717 watchID, (uint64_t)addr);
721 // Try to find a vacant watchpoint slot in the inferiors' main thread
722 uint32_t wp_hw_index = LLDB_INVALID_INDEX32;
723 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
724 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
725 m_thread_list.GetThreadAtIndex(0, false).get());
728 wp_hw_index = thread->FindVacantWatchpointIndex();
730 if (wp_hw_index == LLDB_INVALID_INDEX32) {
731 error.SetErrorString("Setting hardware watchpoint failed.");
733 wp->SetHardwareIndex(wp_hw_index);
734 bool wp_enabled = true;
735 uint32_t thread_count = m_thread_list.GetSize(false);
736 for (uint32_t i = 0; i < thread_count; ++i) {
737 thread = static_cast<FreeBSDThread *>(
738 m_thread_list.GetThreadAtIndex(i, false).get());
740 wp_enabled &= thread->EnableHardwareWatchpoint(wp);
745 wp->SetEnabled(true, notify);
748 // Watchpoint enabling failed on at least one
749 // of the threads so roll back all of them
750 DisableWatchpoint(wp, false);
751 error.SetErrorString("Setting hardware watchpoint failed");
755 error.SetErrorString("Watchpoint argument was NULL.");
759 Status ProcessFreeBSD::DisableWatchpoint(Watchpoint *wp, bool notify) {
762 user_id_t watchID = wp->GetID();
763 addr_t addr = wp->GetLoadAddress();
764 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
766 log->Printf("ProcessFreeBSD::DisableWatchpoint(watchID = %" PRIu64 ")",
768 if (!wp->IsEnabled()) {
770 log->Printf("ProcessFreeBSD::DisableWatchpoint(watchID = %" PRIu64
771 ") addr = 0x%8.8" PRIx64 ": watchpoint already disabled.",
772 watchID, (uint64_t)addr);
773 // This is needed (for now) to keep watchpoints disabled correctly
774 wp->SetEnabled(false, notify);
778 if (wp->IsHardware()) {
779 bool wp_disabled = true;
780 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
781 uint32_t thread_count = m_thread_list.GetSize(false);
782 for (uint32_t i = 0; i < thread_count; ++i) {
783 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
784 m_thread_list.GetThreadAtIndex(i, false).get());
786 wp_disabled &= thread->DisableHardwareWatchpoint(wp);
791 wp->SetHardwareIndex(LLDB_INVALID_INDEX32);
792 wp->SetEnabled(false, notify);
795 error.SetErrorString("Disabling hardware watchpoint failed");
798 error.SetErrorString("Watchpoint argument was NULL.");
802 Status ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num) {
804 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
805 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
806 m_thread_list.GetThreadAtIndex(0, false).get());
808 num = thread->NumSupportedHardwareWatchpoints();
810 error.SetErrorString("Process does not exist.");
814 Status ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num, bool &after) {
815 Status error = GetWatchpointSupportInfo(num);
816 // Watchpoints trigger and halt the inferior after
817 // the corresponding instruction has been executed.
822 uint32_t ProcessFreeBSD::UpdateThreadListIfNeeded() {
823 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
824 // Do not allow recursive updates.
825 return m_thread_list.GetSize(false);
828 ByteOrder ProcessFreeBSD::GetByteOrder() const {
829 // FIXME: We should be able to extract this value directly. See comment in
834 size_t ProcessFreeBSD::PutSTDIN(const char *buf, size_t len, Status &error) {
836 if ((status = write(m_monitor->GetTerminalFD(), buf, len)) < 0) {
837 error.SetErrorToErrno();
843 //------------------------------------------------------------------------------
844 // Utility functions.
846 bool ProcessFreeBSD::HasExited() {
847 switch (GetPrivateState()) {
859 bool ProcessFreeBSD::IsStopped() {
860 switch (GetPrivateState()) {
866 case eStateSuspended:
873 bool ProcessFreeBSD::IsAThreadRunning() {
874 bool is_running = false;
875 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
876 uint32_t thread_count = m_thread_list.GetSize(false);
877 for (uint32_t i = 0; i < thread_count; ++i) {
878 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
879 m_thread_list.GetThreadAtIndex(i, false).get());
880 StateType thread_state = thread->GetState();
881 if (thread_state == eStateRunning || thread_state == eStateStepping) {
889 const DataBufferSP ProcessFreeBSD::GetAuxvData() {
890 // If we're the local platform, we can ask the host for auxv data.
891 PlatformSP platform_sp = GetTarget().GetPlatform();
892 assert(platform_sp && platform_sp->IsHost());
894 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_AUXV, (int)m_process->GetID()};
895 size_t auxv_size = AT_COUNT * sizeof(Elf_Auxinfo);
896 DataBufferSP buf_sp(new DataBufferHeap(auxv_size, 0));
898 if (::sysctl(mib, 4, buf_sp->GetBytes(), &auxv_size, NULL, 0) != 0) {
899 perror("sysctl failed on auxv");
906 struct EmulatorBaton {
907 ProcessFreeBSD *m_process;
908 RegisterContext *m_reg_context;
910 // eRegisterKindDWARF -> RegisterValue
911 std::unordered_map<uint32_t, RegisterValue> m_register_values;
913 EmulatorBaton(ProcessFreeBSD *process, RegisterContext *reg_context)
914 : m_process(process), m_reg_context(reg_context) {}
917 static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
918 const EmulateInstruction::Context &context,
919 lldb::addr_t addr, void *dst, size_t length) {
920 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
924 emulator_baton->m_process->DoReadMemory(addr, dst, length, error);
925 if (!error.Success())
930 static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
931 const RegisterInfo *reg_info,
932 RegisterValue ®_value) {
933 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
935 auto it = emulator_baton->m_register_values.find(
936 reg_info->kinds[eRegisterKindDWARF]);
937 if (it != emulator_baton->m_register_values.end()) {
938 reg_value = it->second;
942 // The emulator only fills in the dwarf register numbers (and in some cases
943 // the generic register numbers). Get the full register info from the
944 // register context based on the dwarf register numbers.
945 const RegisterInfo *full_reg_info =
946 emulator_baton->m_reg_context->GetRegisterInfo(
947 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
950 emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
954 static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
955 const EmulateInstruction::Context &context,
956 const RegisterInfo *reg_info,
957 const RegisterValue ®_value) {
958 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
959 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
964 static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
965 const EmulateInstruction::Context &context,
966 lldb::addr_t addr, const void *dst,
971 bool ProcessFreeBSD::SingleStepBreakpointHit(
972 void *baton, lldb_private::StoppointCallbackContext *context,
973 lldb::user_id_t break_id, lldb::user_id_t break_loc_id) {
977 Status ProcessFreeBSD::SetSoftwareSingleStepBreakpoint(lldb::tid_t tid,
981 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
983 log->Printf("ProcessFreeBSD::%s addr = 0x%" PRIx64, __FUNCTION__, addr);
984 log->Printf("SoftwareBreakpoint::%s addr = 0x%" PRIx64, __FUNCTION__, addr);
987 // Validate the address.
988 if (addr == LLDB_INVALID_ADDRESS)
989 return Status("ProcessFreeBSD::%s invalid load address specified.",
992 Breakpoint *const sw_step_break =
993 m_process->GetTarget().CreateBreakpoint(addr, true, false).get();
994 sw_step_break->SetCallback(SingleStepBreakpointHit, this, true);
995 sw_step_break->SetBreakpointKind("software-signle-step");
998 log->Printf("ProcessFreeBSD::%s addr = 0x%" PRIx64 " -- SUCCESS",
1001 m_threads_stepping_with_breakpoint.insert({tid, sw_step_break->GetID()});
1005 bool ProcessFreeBSD::IsSoftwareStepBreakpoint(lldb::tid_t tid) {
1006 ThreadSP thread = GetThreadList().FindThreadByID(tid);
1010 assert(thread->GetRegisterContext());
1011 lldb::addr_t stop_pc = thread->GetRegisterContext()->GetPC();
1013 const auto &iter = m_threads_stepping_with_breakpoint.find(tid);
1014 if (iter == m_threads_stepping_with_breakpoint.end())
1017 lldb::break_id_t bp_id = iter->second;
1018 BreakpointSP bp = GetTarget().GetBreakpointByID(bp_id);
1022 BreakpointLocationSP bp_loc = bp->FindLocationByAddress(stop_pc);
1026 GetTarget().RemoveBreakpointByID(bp_id);
1027 m_threads_stepping_with_breakpoint.erase(tid);
1031 bool ProcessFreeBSD::SupportHardwareSingleStepping() const {
1032 lldb_private::ArchSpec arch = GetTarget().GetArchitecture();
1033 if (arch.GetMachine() == llvm::Triple::arm ||
1034 arch.GetMachine() == llvm::Triple::mips64 ||
1035 arch.GetMachine() == llvm::Triple::mips64el ||
1036 arch.GetMachine() == llvm::Triple::mips ||
1037 arch.GetMachine() == llvm::Triple::mipsel)
1042 Status ProcessFreeBSD::SetupSoftwareSingleStepping(lldb::tid_t tid) {
1043 std::unique_ptr<EmulateInstruction> emulator_ap(
1044 EmulateInstruction::FindPlugin(GetTarget().GetArchitecture(),
1045 eInstructionTypePCModifying, nullptr));
1047 if (emulator_ap == nullptr)
1048 return Status("Instruction emulator not found!");
1050 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
1051 m_thread_list.FindThreadByID(tid, false).get());
1053 return Status("Thread not found not found!");
1055 lldb::RegisterContextSP register_context_sp = thread->GetRegisterContext();
1057 EmulatorBaton baton(this, register_context_sp.get());
1058 emulator_ap->SetBaton(&baton);
1059 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
1060 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
1061 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
1062 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
1064 if (!emulator_ap->ReadInstruction())
1065 return Status("Read instruction failed!");
1067 bool emulation_result =
1068 emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
1069 const RegisterInfo *reg_info_pc = register_context_sp->GetRegisterInfo(
1070 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1072 baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1074 lldb::addr_t next_pc;
1075 if (emulation_result) {
1076 assert(pc_it != baton.m_register_values.end() &&
1077 "Emulation was successful but PC wasn't updated");
1078 next_pc = pc_it->second.GetAsUInt64();
1079 } else if (pc_it == baton.m_register_values.end()) {
1080 // Emulate instruction failed and it haven't changed PC. Advance PC
1081 // with the size of the current opcode because the emulation of all
1082 // PC modifying instruction should be successful. The failure most
1083 // likely caused by a not supported instruction which don't modify PC.
1085 register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
1087 // The instruction emulation failed after it modified the PC. It is an
1088 // unknown error where we can't continue because the next instruction is
1089 // modifying the PC but we don't know how.
1090 return Status("Instruction emulation failed unexpectedly");
1093 SetSoftwareSingleStepBreakpoint(tid, next_pc);