1 //===-- ProcessFreeBSD.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 //===----------------------------------------------------------------------===//
12 #include <pthread_np.h>
14 #include <sys/sysctl.h>
15 #include <sys/types.h>
17 #include <machine/elf.h>
20 #include <unordered_map>
22 #include "lldb/Core/PluginManager.h"
23 #include "lldb/Host/FileSystem.h"
24 #include "lldb/Host/Host.h"
25 #include "lldb/Symbol/ObjectFile.h"
26 #include "lldb/Target/DynamicLoader.h"
27 #include "lldb/Target/Target.h"
28 #include "lldb/Utility/RegisterValue.h"
29 #include "lldb/Utility/State.h"
31 #include "FreeBSDThread.h"
32 #include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
33 #include "Plugins/Process/Utility/FreeBSDSignals.h"
34 #include "Plugins/Process/Utility/InferiorCallPOSIX.h"
35 #include "ProcessFreeBSD.h"
36 #include "ProcessMonitor.h"
38 #include "lldb/Breakpoint/BreakpointLocation.h"
39 #include "lldb/Breakpoint/Watchpoint.h"
40 #include "lldb/Core/Module.h"
41 #include "lldb/Core/ModuleSpec.h"
42 #include "lldb/Core/PluginManager.h"
43 #include "lldb/Host/Host.h"
44 #include "lldb/Symbol/ObjectFile.h"
45 #include "lldb/Target/DynamicLoader.h"
46 #include "lldb/Target/Platform.h"
47 #include "lldb/Target/Target.h"
48 #include "lldb/Utility/DataBufferHeap.h"
49 #include "lldb/Utility/FileSpec.h"
50 #include "lldb/Utility/State.h"
52 #include "lldb/Host/posix/Fcntl.h"
54 #include "llvm/Support/FileSystem.h"
55 #include "llvm/Support/Threading.h"
58 using namespace lldb_private;
61 UnixSignalsSP &GetFreeBSDSignals() {
62 static UnixSignalsSP s_freebsd_signals_sp(new FreeBSDSignals());
63 return s_freebsd_signals_sp;
70 ProcessFreeBSD::CreateInstance(lldb::TargetSP target_sp,
71 lldb::ListenerSP listener_sp,
72 const FileSpec *crash_file_path) {
73 lldb::ProcessSP process_sp;
74 if (crash_file_path == NULL)
76 new ProcessFreeBSD(target_sp, listener_sp, GetFreeBSDSignals()));
80 void ProcessFreeBSD::Initialize() {
81 static llvm::once_flag g_once_flag;
83 llvm::call_once(g_once_flag, []() {
84 PluginManager::RegisterPlugin(GetPluginNameStatic(),
85 GetPluginDescriptionStatic(), CreateInstance);
89 lldb_private::ConstString ProcessFreeBSD::GetPluginNameStatic() {
90 static ConstString g_name("freebsd");
94 const char *ProcessFreeBSD::GetPluginDescriptionStatic() {
95 return "Process plugin for FreeBSD";
98 // ProcessInterface protocol.
100 lldb_private::ConstString ProcessFreeBSD::GetPluginName() {
101 return GetPluginNameStatic();
104 uint32_t ProcessFreeBSD::GetPluginVersion() { return 1; }
106 void ProcessFreeBSD::Terminate() {}
108 Status ProcessFreeBSD::DoDetach(bool keep_stopped) {
111 error.SetErrorString("Detaching with keep_stopped true is not currently "
112 "supported on FreeBSD.");
116 error = m_monitor->Detach(GetID());
119 SetPrivateState(eStateDetached);
124 Status ProcessFreeBSD::DoResume() {
125 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
127 SetPrivateState(eStateRunning);
129 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
130 bool do_step = false;
131 bool software_single_step = !SupportHardwareSingleStepping();
133 for (tid_collection::const_iterator t_pos = m_run_tids.begin(),
134 t_end = m_run_tids.end();
135 t_pos != t_end; ++t_pos) {
136 m_monitor->ThreadSuspend(*t_pos, false);
138 for (tid_collection::const_iterator t_pos = m_step_tids.begin(),
139 t_end = m_step_tids.end();
140 t_pos != t_end; ++t_pos) {
141 m_monitor->ThreadSuspend(*t_pos, false);
143 if (software_single_step) {
144 Status error = SetupSoftwareSingleStepping(*t_pos);
149 for (tid_collection::const_iterator t_pos = m_suspend_tids.begin(),
150 t_end = m_suspend_tids.end();
151 t_pos != t_end; ++t_pos) {
152 m_monitor->ThreadSuspend(*t_pos, true);
153 // XXX Cannot PT_CONTINUE properly with suspended threads.
157 LLDB_LOGF(log, "process %" PRIu64 " resuming (%s)", GetID(),
158 do_step ? "step" : "continue");
159 if (do_step && !software_single_step)
160 m_monitor->SingleStep(GetID(), m_resume_signo);
162 m_monitor->Resume(GetID(), m_resume_signo);
167 bool ProcessFreeBSD::UpdateThreadList(ThreadList &old_thread_list,
168 ThreadList &new_thread_list) {
169 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
170 LLDB_LOGF(log, "ProcessFreeBSD::%s (pid = %" PRIu64 ")", __FUNCTION__,
173 std::vector<lldb::pid_t> tds;
174 if (!GetMonitor().GetCurrentThreadIDs(tds)) {
178 ThreadList old_thread_list_copy(old_thread_list);
179 for (size_t i = 0; i < tds.size(); ++i) {
181 ThreadSP thread_sp(old_thread_list_copy.RemoveThreadByID(tid, false));
183 thread_sp.reset(new FreeBSDThread(*this, tid));
184 LLDB_LOGF(log, "ProcessFreeBSD::%s new tid = %" PRIu64, __FUNCTION__,
187 LLDB_LOGF(log, "ProcessFreeBSD::%s existing tid = %" PRIu64, __FUNCTION__,
190 new_thread_list.AddThread(thread_sp);
192 for (size_t i = 0; i < old_thread_list_copy.GetSize(false); ++i) {
193 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
195 LLDB_LOGF(log, "ProcessFreeBSD::%s remove tid", __FUNCTION__);
202 Status ProcessFreeBSD::WillResume() {
204 m_suspend_tids.clear();
207 return Process::WillResume();
210 void ProcessFreeBSD::SendMessage(const ProcessMessage &message) {
211 std::lock_guard<std::recursive_mutex> guard(m_message_mutex);
213 switch (message.GetKind()) {
214 case ProcessMessage::eInvalidMessage:
217 case ProcessMessage::eAttachMessage:
218 SetPrivateState(eStateStopped);
221 case ProcessMessage::eLimboMessage:
222 case ProcessMessage::eExitMessage:
223 SetExitStatus(message.GetExitStatus(), NULL);
226 case ProcessMessage::eSignalMessage:
227 case ProcessMessage::eSignalDeliveredMessage:
228 case ProcessMessage::eBreakpointMessage:
229 case ProcessMessage::eTraceMessage:
230 case ProcessMessage::eWatchpointMessage:
231 case ProcessMessage::eCrashMessage:
232 SetPrivateState(eStateStopped);
235 case ProcessMessage::eNewThreadMessage:
236 llvm_unreachable("eNewThreadMessage unexpected on FreeBSD");
239 case ProcessMessage::eExecMessage:
240 SetPrivateState(eStateStopped);
244 m_message_queue.push(message);
247 // Constructors and destructors.
249 ProcessFreeBSD::ProcessFreeBSD(lldb::TargetSP target_sp,
250 lldb::ListenerSP listener_sp,
251 UnixSignalsSP &unix_signals_sp)
252 : Process(target_sp, listener_sp, unix_signals_sp),
253 m_byte_order(endian::InlHostByteOrder()), m_monitor(NULL), m_module(NULL),
254 m_message_mutex(), m_exit_now(false), m_seen_initial_stop(),
256 // FIXME: Putting this code in the ctor and saving the byte order in a
257 // member variable is a hack to avoid const qual issues in GetByteOrder.
258 lldb::ModuleSP module = GetTarget().GetExecutableModule();
259 if (module && module->GetObjectFile())
260 m_byte_order = module->GetObjectFile()->GetByteOrder();
263 ProcessFreeBSD::~ProcessFreeBSD() { delete m_monitor; }
266 void ProcessFreeBSD::Finalize() {
270 m_monitor->StopMonitor();
273 bool ProcessFreeBSD::CanDebug(lldb::TargetSP target_sp,
274 bool plugin_specified_by_name) {
275 // For now we are just making sure the file exists for a given module
276 ModuleSP exe_module_sp(target_sp->GetExecutableModule());
277 if (exe_module_sp.get())
278 return FileSystem::Instance().Exists(exe_module_sp->GetFileSpec());
279 // If there is no executable module, we return true since we might be
280 // preparing to attach.
285 ProcessFreeBSD::DoAttachToProcessWithID(lldb::pid_t pid,
286 const ProcessAttachInfo &attach_info) {
288 assert(m_monitor == NULL);
290 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
291 LLDB_LOGV(log, "pid = {0}", GetID());
293 m_monitor = new ProcessMonitor(this, pid, error);
295 if (!error.Success())
298 PlatformSP platform_sp(GetTarget().GetPlatform());
299 assert(platform_sp.get());
301 return error; // FIXME: Detatch?
303 // Find out what we can about this process
304 ProcessInstanceInfo process_info;
305 platform_sp->GetProcessInfo(pid, process_info);
307 // Resolve the executable module
308 ModuleSP exe_module_sp;
309 FileSpecList executable_search_paths(
310 Target::GetDefaultExecutableSearchPaths());
311 ModuleSpec exe_module_spec(process_info.GetExecutableFile(),
312 GetTarget().GetArchitecture());
313 error = platform_sp->ResolveExecutable(
314 exe_module_spec, exe_module_sp,
315 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
316 if (!error.Success())
319 // Fix the target architecture if necessary
320 const ArchSpec &module_arch = exe_module_sp->GetArchitecture();
321 if (module_arch.IsValid() &&
322 !GetTarget().GetArchitecture().IsExactMatch(module_arch))
323 GetTarget().SetArchitecture(module_arch);
325 // Initialize the target module list
326 GetTarget().SetExecutableModule(exe_module_sp, eLoadDependentsYes);
328 SetSTDIOFileDescriptor(m_monitor->GetTerminalFD());
335 Status ProcessFreeBSD::WillLaunch(Module *module) {
341 ProcessFreeBSD::GetFileSpec(const lldb_private::FileAction *file_action,
342 const FileSpec &default_file_spec,
343 const FileSpec &dbg_pts_file_spec) {
344 FileSpec file_spec{};
346 if (file_action && file_action->GetAction() == FileAction::eFileActionOpen) {
347 file_spec = file_action->GetFileSpec();
348 // By default the stdio paths passed in will be pseudo-terminal (/dev/pts).
349 // If so, convert to using a different default path instead to redirect I/O
350 // to the debugger console. This should also handle user overrides to
351 // /dev/null or a different file.
352 if (!file_spec || file_spec == dbg_pts_file_spec)
353 file_spec = default_file_spec;
358 Status ProcessFreeBSD::DoLaunch(Module *module,
359 ProcessLaunchInfo &launch_info) {
361 assert(m_monitor == NULL);
363 FileSpec working_dir = launch_info.GetWorkingDirectory();
365 FileSystem::Instance().Resolve(working_dir);
366 if (!FileSystem::Instance().IsDirectory(working_dir.GetPath())) {
367 error.SetErrorStringWithFormat("No such file or directory: %s",
368 working_dir.GetCString());
373 SetPrivateState(eStateLaunching);
375 const lldb_private::FileAction *file_action;
377 // Default of empty will mean to use existing open file descriptors
378 FileSpec stdin_file_spec{};
379 FileSpec stdout_file_spec{};
380 FileSpec stderr_file_spec{};
382 const FileSpec dbg_pts_file_spec{launch_info.GetPTY().GetSlaveName(NULL, 0)};
384 file_action = launch_info.GetFileActionForFD(STDIN_FILENO);
386 GetFileSpec(file_action, stdin_file_spec, dbg_pts_file_spec);
388 file_action = launch_info.GetFileActionForFD(STDOUT_FILENO);
390 GetFileSpec(file_action, stdout_file_spec, dbg_pts_file_spec);
392 file_action = launch_info.GetFileActionForFD(STDERR_FILENO);
394 GetFileSpec(file_action, stderr_file_spec, dbg_pts_file_spec);
396 m_monitor = new ProcessMonitor(
397 this, module, launch_info.GetArguments().GetConstArgumentVector(),
398 launch_info.GetEnvironment(), stdin_file_spec, stdout_file_spec,
399 stderr_file_spec, working_dir, launch_info, error);
403 if (!error.Success())
406 int terminal = m_monitor->GetTerminalFD();
408 // The reader thread will close the file descriptor when done, so we pass it a
410 #ifdef F_DUPFD_CLOEXEC
411 int stdio = fcntl(terminal, F_DUPFD_CLOEXEC, 0);
413 error.SetErrorToErrno();
417 // Special case when F_DUPFD_CLOEXEC does not exist (Debian kFreeBSD)
418 int stdio = fcntl(terminal, F_DUPFD, 0);
420 error.SetErrorToErrno();
423 stdio = fcntl(terminal, F_SETFD, FD_CLOEXEC);
425 error.SetErrorToErrno();
429 SetSTDIOFileDescriptor(stdio);
432 SetID(m_monitor->GetPID());
436 void ProcessFreeBSD::DidLaunch() {}
438 addr_t ProcessFreeBSD::GetImageInfoAddress() {
439 Target *target = &GetTarget();
440 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
441 Address addr = obj_file->GetImageInfoAddress(target);
444 return addr.GetLoadAddress(target);
445 return LLDB_INVALID_ADDRESS;
448 Status ProcessFreeBSD::DoHalt(bool &caused_stop) {
453 } else if (kill(GetID(), SIGSTOP)) {
455 error.SetErrorToErrno();
462 Status ProcessFreeBSD::DoSignal(int signal) {
465 if (kill(GetID(), signal))
466 error.SetErrorToErrno();
471 Status ProcessFreeBSD::DoDestroy() {
477 if (GetID() == LLDB_INVALID_PROCESS_ID) {
478 error.SetErrorString("invalid process id");
481 if (!m_monitor->Kill()) {
482 error.SetErrorToErrno();
486 SetPrivateState(eStateExited);
492 void ProcessFreeBSD::DoDidExec() {
493 Target *target = &GetTarget();
495 PlatformSP platform_sp(target->GetPlatform());
496 assert(platform_sp.get());
498 ProcessInstanceInfo process_info;
499 platform_sp->GetProcessInfo(GetID(), process_info);
500 ModuleSP exe_module_sp;
501 ModuleSpec exe_module_spec(process_info.GetExecutableFile(),
502 target->GetArchitecture());
503 FileSpecList executable_search_paths(
504 Target::GetDefaultExecutableSearchPaths());
505 Status error = platform_sp->ResolveExecutable(
506 exe_module_spec, exe_module_sp,
507 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
508 if (!error.Success())
510 target->SetExecutableModule(exe_module_sp, eLoadDependentsYes);
515 bool ProcessFreeBSD::AddThreadForInitialStopIfNeeded(lldb::tid_t stop_tid) {
516 bool added_to_set = false;
517 ThreadStopSet::iterator it = m_seen_initial_stop.find(stop_tid);
518 if (it == m_seen_initial_stop.end()) {
519 m_seen_initial_stop.insert(stop_tid);
525 bool ProcessFreeBSD::WaitingForInitialStop(lldb::tid_t stop_tid) {
526 return (m_seen_initial_stop.find(stop_tid) == m_seen_initial_stop.end());
530 ProcessFreeBSD::CreateNewFreeBSDThread(lldb_private::Process &process,
532 return new FreeBSDThread(process, tid);
535 void ProcessFreeBSD::RefreshStateAfterStop() {
536 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
537 LLDB_LOGV(log, "message_queue size = {0}", m_message_queue.size());
539 std::lock_guard<std::recursive_mutex> guard(m_message_mutex);
541 // This method used to only handle one message. Changing it to loop allows
542 // it to handle the case where we hit a breakpoint while handling a different
544 while (!m_message_queue.empty()) {
545 ProcessMessage &message = m_message_queue.front();
547 // Resolve the thread this message corresponds to and pass it along.
548 lldb::tid_t tid = message.GetTID();
549 LLDB_LOGV(log, " message_queue size = {0}, pid = {1}",
550 m_message_queue.size(), tid);
552 m_thread_list.RefreshStateAfterStop();
554 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
555 GetThreadList().FindThreadByID(tid, false).get());
557 thread->Notify(message);
559 if (message.GetKind() == ProcessMessage::eExitMessage) {
560 // FIXME: We should tell the user about this, but the limbo message is
561 // probably better for that.
562 LLDB_LOG(log, "removing thread, tid = {0}", tid);
563 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
565 ThreadSP thread_sp = m_thread_list.RemoveThreadByID(tid, false);
567 m_seen_initial_stop.erase(tid);
570 m_message_queue.pop();
574 bool ProcessFreeBSD::IsAlive() {
575 StateType state = GetPrivateState();
576 return state != eStateDetached && state != eStateExited &&
577 state != eStateInvalid && state != eStateUnloaded;
580 size_t ProcessFreeBSD::DoReadMemory(addr_t vm_addr, void *buf, size_t size,
583 return m_monitor->ReadMemory(vm_addr, buf, size, error);
586 size_t ProcessFreeBSD::DoWriteMemory(addr_t vm_addr, const void *buf,
587 size_t size, Status &error) {
589 return m_monitor->WriteMemory(vm_addr, buf, size, error);
592 addr_t ProcessFreeBSD::DoAllocateMemory(size_t size, uint32_t permissions,
594 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
597 if (permissions & lldb::ePermissionsReadable)
598 prot |= eMmapProtRead;
599 if (permissions & lldb::ePermissionsWritable)
600 prot |= eMmapProtWrite;
601 if (permissions & lldb::ePermissionsExecutable)
602 prot |= eMmapProtExec;
604 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
605 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
606 m_addr_to_mmap_size[allocated_addr] = size;
609 allocated_addr = LLDB_INVALID_ADDRESS;
610 error.SetErrorStringWithFormat(
611 "unable to allocate %zu bytes of memory with permissions %s", size,
612 GetPermissionsAsCString(permissions));
615 return allocated_addr;
618 Status ProcessFreeBSD::DoDeallocateMemory(lldb::addr_t addr) {
620 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
621 if (pos != m_addr_to_mmap_size.end() &&
622 InferiorCallMunmap(this, addr, pos->second))
623 m_addr_to_mmap_size.erase(pos);
625 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64,
632 ProcessFreeBSD::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
633 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xD4};
634 static const uint8_t g_i386_opcode[] = {0xCC};
636 ArchSpec arch = GetTarget().GetArchitecture();
637 const uint8_t *opcode = NULL;
638 size_t opcode_size = 0;
640 switch (arch.GetMachine()) {
642 assert(false && "CPU type not supported!");
645 case llvm::Triple::arm: {
646 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
647 // linux kernel does otherwise.
648 static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
649 static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
651 lldb::BreakpointLocationSP bp_loc_sp(bp_site->GetOwnerAtIndex(0));
652 AddressClass addr_class = AddressClass::eUnknown;
655 addr_class = bp_loc_sp->GetAddress().GetAddressClass();
657 if (addr_class == AddressClass::eCodeAlternateISA ||
658 (addr_class == AddressClass::eUnknown &&
659 bp_loc_sp->GetAddress().GetOffset() & 1)) {
660 opcode = g_thumb_breakpoint_opcode;
661 opcode_size = sizeof(g_thumb_breakpoint_opcode);
663 opcode = g_arm_breakpoint_opcode;
664 opcode_size = sizeof(g_arm_breakpoint_opcode);
667 case llvm::Triple::aarch64:
668 opcode = g_aarch64_opcode;
669 opcode_size = sizeof(g_aarch64_opcode);
672 case llvm::Triple::x86:
673 case llvm::Triple::x86_64:
674 opcode = g_i386_opcode;
675 opcode_size = sizeof(g_i386_opcode);
679 bp_site->SetTrapOpcode(opcode, opcode_size);
683 Status ProcessFreeBSD::EnableBreakpointSite(BreakpointSite *bp_site) {
684 return EnableSoftwareBreakpoint(bp_site);
687 Status ProcessFreeBSD::DisableBreakpointSite(BreakpointSite *bp_site) {
688 return DisableSoftwareBreakpoint(bp_site);
691 Status ProcessFreeBSD::EnableWatchpoint(Watchpoint *wp, bool notify) {
694 user_id_t watchID = wp->GetID();
695 addr_t addr = wp->GetLoadAddress();
696 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
697 LLDB_LOGF(log, "ProcessFreeBSD::EnableWatchpoint(watchID = %" PRIu64 ")",
699 if (wp->IsEnabled()) {
701 "ProcessFreeBSD::EnableWatchpoint(watchID = %" PRIu64
702 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
703 watchID, (uint64_t)addr);
707 // Try to find a vacant watchpoint slot in the inferiors' main thread
708 uint32_t wp_hw_index = LLDB_INVALID_INDEX32;
709 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
710 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
711 m_thread_list.GetThreadAtIndex(0, false).get());
714 wp_hw_index = thread->FindVacantWatchpointIndex();
716 if (wp_hw_index == LLDB_INVALID_INDEX32) {
717 error.SetErrorString("Setting hardware watchpoint failed.");
719 wp->SetHardwareIndex(wp_hw_index);
720 bool wp_enabled = true;
721 uint32_t thread_count = m_thread_list.GetSize(false);
722 for (uint32_t i = 0; i < thread_count; ++i) {
723 thread = static_cast<FreeBSDThread *>(
724 m_thread_list.GetThreadAtIndex(i, false).get());
726 wp_enabled &= thread->EnableHardwareWatchpoint(wp);
731 wp->SetEnabled(true, notify);
734 // Watchpoint enabling failed on at least one of the threads so roll
736 DisableWatchpoint(wp, false);
737 error.SetErrorString("Setting hardware watchpoint failed");
741 error.SetErrorString("Watchpoint argument was NULL.");
745 Status ProcessFreeBSD::DisableWatchpoint(Watchpoint *wp, bool notify) {
748 user_id_t watchID = wp->GetID();
749 addr_t addr = wp->GetLoadAddress();
750 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
751 LLDB_LOGF(log, "ProcessFreeBSD::DisableWatchpoint(watchID = %" PRIu64 ")",
753 if (!wp->IsEnabled()) {
755 "ProcessFreeBSD::DisableWatchpoint(watchID = %" PRIu64
756 ") addr = 0x%8.8" PRIx64 ": watchpoint already disabled.",
757 watchID, (uint64_t)addr);
758 // This is needed (for now) to keep watchpoints disabled correctly
759 wp->SetEnabled(false, notify);
763 if (wp->IsHardware()) {
764 bool wp_disabled = true;
765 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
766 uint32_t thread_count = m_thread_list.GetSize(false);
767 for (uint32_t i = 0; i < thread_count; ++i) {
768 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
769 m_thread_list.GetThreadAtIndex(i, false).get());
771 wp_disabled &= thread->DisableHardwareWatchpoint(wp);
776 wp->SetHardwareIndex(LLDB_INVALID_INDEX32);
777 wp->SetEnabled(false, notify);
780 error.SetErrorString("Disabling hardware watchpoint failed");
783 error.SetErrorString("Watchpoint argument was NULL.");
787 Status ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num) {
789 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
790 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
791 m_thread_list.GetThreadAtIndex(0, false).get());
793 num = thread->NumSupportedHardwareWatchpoints();
795 error.SetErrorString("Process does not exist.");
799 Status ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num, bool &after) {
800 Status error = GetWatchpointSupportInfo(num);
801 // Watchpoints trigger and halt the inferior after the corresponding
802 // instruction has been executed.
807 uint32_t ProcessFreeBSD::UpdateThreadListIfNeeded() {
808 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
809 // Do not allow recursive updates.
810 return m_thread_list.GetSize(false);
813 ByteOrder ProcessFreeBSD::GetByteOrder() const {
814 // FIXME: We should be able to extract this value directly. See comment in
819 size_t ProcessFreeBSD::PutSTDIN(const char *buf, size_t len, Status &error) {
821 if ((status = write(m_monitor->GetTerminalFD(), buf, len)) < 0) {
822 error.SetErrorToErrno();
828 // Utility functions.
830 bool ProcessFreeBSD::HasExited() {
831 switch (GetPrivateState()) {
843 bool ProcessFreeBSD::IsStopped() {
844 switch (GetPrivateState()) {
850 case eStateSuspended:
857 bool ProcessFreeBSD::IsAThreadRunning() {
858 bool is_running = false;
859 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
860 uint32_t thread_count = m_thread_list.GetSize(false);
861 for (uint32_t i = 0; i < thread_count; ++i) {
862 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
863 m_thread_list.GetThreadAtIndex(i, false).get());
864 StateType thread_state = thread->GetState();
865 if (thread_state == eStateRunning || thread_state == eStateStepping) {
873 lldb_private::DataExtractor ProcessFreeBSD::GetAuxvData() {
874 // If we're the local platform, we can ask the host for auxv data.
875 PlatformSP platform_sp = GetTarget().GetPlatform();
876 assert(platform_sp && platform_sp->IsHost());
878 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_AUXV, (int)m_process->GetID()};
879 size_t auxv_size = AT_COUNT * sizeof(Elf_Auxinfo);
880 DataBufferSP buf_sp(new DataBufferHeap(auxv_size, 0));
882 if (::sysctl(mib, 4, buf_sp->GetBytes(), &auxv_size, NULL, 0) != 0) {
883 perror("sysctl failed on auxv");
887 return DataExtractor(buf_sp, GetByteOrder(), GetAddressByteSize());
890 struct EmulatorBaton {
891 ProcessFreeBSD *m_process;
892 RegisterContext *m_reg_context;
894 // eRegisterKindDWARF -> RegisterValue
895 std::unordered_map<uint32_t, RegisterValue> m_register_values;
897 EmulatorBaton(ProcessFreeBSD *process, RegisterContext *reg_context)
898 : m_process(process), m_reg_context(reg_context) {}
901 static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
902 const EmulateInstruction::Context &context,
903 lldb::addr_t addr, void *dst, size_t length) {
904 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
908 emulator_baton->m_process->DoReadMemory(addr, dst, length, error);
909 if (!error.Success())
914 static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
915 const RegisterInfo *reg_info,
916 RegisterValue ®_value) {
917 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
919 auto it = emulator_baton->m_register_values.find(
920 reg_info->kinds[eRegisterKindDWARF]);
921 if (it != emulator_baton->m_register_values.end()) {
922 reg_value = it->second;
926 // The emulator only fills in the dwarf register numbers (and in some cases
927 // the generic register numbers). Get the full register info from the
928 // register context based on the dwarf register numbers.
929 const RegisterInfo *full_reg_info =
930 emulator_baton->m_reg_context->GetRegisterInfo(
931 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
934 emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
938 static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
939 const EmulateInstruction::Context &context,
940 const RegisterInfo *reg_info,
941 const RegisterValue ®_value) {
942 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
943 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
948 static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
949 const EmulateInstruction::Context &context,
950 lldb::addr_t addr, const void *dst,
955 bool ProcessFreeBSD::SingleStepBreakpointHit(
956 void *baton, lldb_private::StoppointCallbackContext *context,
957 lldb::user_id_t break_id, lldb::user_id_t break_loc_id) {
961 Status ProcessFreeBSD::SetSoftwareSingleStepBreakpoint(lldb::tid_t tid,
965 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
967 LLDB_LOGF(log, "ProcessFreeBSD::%s addr = 0x%" PRIx64, __FUNCTION__, addr);
968 LLDB_LOGF(log, "SoftwareBreakpoint::%s addr = 0x%" PRIx64, __FUNCTION__,
972 // Validate the address.
973 if (addr == LLDB_INVALID_ADDRESS)
974 return Status("ProcessFreeBSD::%s invalid load address specified.",
977 Breakpoint *const sw_step_break =
978 m_process->GetTarget().CreateBreakpoint(addr, true, false).get();
979 sw_step_break->SetCallback(SingleStepBreakpointHit, this, true);
980 sw_step_break->SetBreakpointKind("software-single-step");
982 LLDB_LOGF(log, "ProcessFreeBSD::%s addr = 0x%" PRIx64 " -- SUCCESS",
985 m_threads_stepping_with_breakpoint.insert({tid, sw_step_break->GetID()});
989 bool ProcessFreeBSD::IsSoftwareStepBreakpoint(lldb::tid_t tid) {
990 ThreadSP thread = GetThreadList().FindThreadByID(tid);
994 assert(thread->GetRegisterContext());
995 lldb::addr_t stop_pc = thread->GetRegisterContext()->GetPC();
997 const auto &iter = m_threads_stepping_with_breakpoint.find(tid);
998 if (iter == m_threads_stepping_with_breakpoint.end())
1001 lldb::break_id_t bp_id = iter->second;
1002 BreakpointSP bp = GetTarget().GetBreakpointByID(bp_id);
1006 BreakpointLocationSP bp_loc = bp->FindLocationByAddress(stop_pc);
1010 GetTarget().RemoveBreakpointByID(bp_id);
1011 m_threads_stepping_with_breakpoint.erase(tid);
1015 bool ProcessFreeBSD::SupportHardwareSingleStepping() const {
1016 lldb_private::ArchSpec arch = GetTarget().GetArchitecture();
1017 if (arch.GetMachine() == llvm::Triple::arm || arch.IsMIPS())
1022 Status ProcessFreeBSD::SetupSoftwareSingleStepping(lldb::tid_t tid) {
1023 std::unique_ptr<EmulateInstruction> emulator_up(
1024 EmulateInstruction::FindPlugin(GetTarget().GetArchitecture(),
1025 eInstructionTypePCModifying, nullptr));
1027 if (emulator_up == nullptr)
1028 return Status("Instruction emulator not found!");
1030 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
1031 m_thread_list.FindThreadByID(tid, false).get());
1033 return Status("Thread not found not found!");
1035 lldb::RegisterContextSP register_context_sp = thread->GetRegisterContext();
1037 EmulatorBaton baton(this, register_context_sp.get());
1038 emulator_up->SetBaton(&baton);
1039 emulator_up->SetReadMemCallback(&ReadMemoryCallback);
1040 emulator_up->SetReadRegCallback(&ReadRegisterCallback);
1041 emulator_up->SetWriteMemCallback(&WriteMemoryCallback);
1042 emulator_up->SetWriteRegCallback(&WriteRegisterCallback);
1044 if (!emulator_up->ReadInstruction())
1045 return Status("Read instruction failed!");
1047 bool emulation_result =
1048 emulator_up->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
1049 const RegisterInfo *reg_info_pc = register_context_sp->GetRegisterInfo(
1050 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1052 baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1054 lldb::addr_t next_pc;
1055 if (emulation_result) {
1056 assert(pc_it != baton.m_register_values.end() &&
1057 "Emulation was successful but PC wasn't updated");
1058 next_pc = pc_it->second.GetAsUInt64();
1059 } else if (pc_it == baton.m_register_values.end()) {
1060 // Emulate instruction failed and it haven't changed PC. Advance PC with
1061 // the size of the current opcode because the emulation of all
1062 // PC modifying instruction should be successful. The failure most
1063 // likely caused by a not supported instruction which don't modify PC.
1065 register_context_sp->GetPC() + emulator_up->GetOpcode().GetByteSize();
1067 // The instruction emulation failed after it modified the PC. It is an
1068 // unknown error where we can't continue because the next instruction is
1069 // modifying the PC but we don't know how.
1070 return Status("Instruction emulation failed unexpectedly");
1073 SetSoftwareSingleStepBreakpoint(tid, next_pc);