11a3d19ddSKamil Rytarowski //===-- NativeProcessNetBSD.cpp ------------------------------- -*- C++ -*-===//
21a3d19ddSKamil Rytarowski //
31a3d19ddSKamil Rytarowski //                     The LLVM Compiler Infrastructure
41a3d19ddSKamil Rytarowski //
51a3d19ddSKamil Rytarowski // This file is distributed under the University of Illinois Open Source
61a3d19ddSKamil Rytarowski // License. See LICENSE.TXT for details.
71a3d19ddSKamil Rytarowski //
81a3d19ddSKamil Rytarowski //===----------------------------------------------------------------------===//
91a3d19ddSKamil Rytarowski 
101a3d19ddSKamil Rytarowski #include "NativeProcessNetBSD.h"
111a3d19ddSKamil Rytarowski 
121a3d19ddSKamil Rytarowski // C Includes
131a3d19ddSKamil Rytarowski 
141a3d19ddSKamil Rytarowski // C++ Includes
151a3d19ddSKamil Rytarowski 
161a3d19ddSKamil Rytarowski // Other libraries and framework includes
171a3d19ddSKamil Rytarowski #include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
18f07a9995SKamil Rytarowski #include "lldb/Core/State.h"
19f07a9995SKamil Rytarowski #include "lldb/Host/HostProcess.h"
20f07a9995SKamil Rytarowski #include "lldb/Host/common/NativeBreakpoint.h"
21f07a9995SKamil Rytarowski #include "lldb/Host/common/NativeRegisterContext.h"
22f07a9995SKamil Rytarowski #include "lldb/Host/posix/ProcessLauncherPosixFork.h"
23f07a9995SKamil Rytarowski #include "lldb/Target/Process.h"
24c1a6b128SPavel Labath #include "llvm/Support/Errno.h"
251a3d19ddSKamil Rytarowski 
261a3d19ddSKamil Rytarowski // System includes - They have to be included after framework includes because
271a3d19ddSKamil Rytarowski // they define some
281a3d19ddSKamil Rytarowski // macros which collide with variable names in other modules
29f07a9995SKamil Rytarowski // clang-format off
30f07a9995SKamil Rytarowski #include <sys/types.h>
31f07a9995SKamil Rytarowski #include <sys/ptrace.h>
32f07a9995SKamil Rytarowski #include <sys/sysctl.h>
33f07a9995SKamil Rytarowski #include <sys/wait.h>
34f07a9995SKamil Rytarowski #include <uvm/uvm_prot.h>
35f07a9995SKamil Rytarowski #include <elf.h>
36f07a9995SKamil Rytarowski #include <util.h>
37f07a9995SKamil Rytarowski // clang-format on
381a3d19ddSKamil Rytarowski 
391a3d19ddSKamil Rytarowski using namespace lldb;
401a3d19ddSKamil Rytarowski using namespace lldb_private;
411a3d19ddSKamil Rytarowski using namespace lldb_private::process_netbsd;
421a3d19ddSKamil Rytarowski using namespace llvm;
431a3d19ddSKamil Rytarowski 
44f07a9995SKamil Rytarowski // Simple helper function to ensure flags are enabled on the given file
45f07a9995SKamil Rytarowski // descriptor.
4697206d57SZachary Turner static Status EnsureFDFlags(int fd, int flags) {
4797206d57SZachary Turner   Status error;
48f07a9995SKamil Rytarowski 
49f07a9995SKamil Rytarowski   int status = fcntl(fd, F_GETFL);
50f07a9995SKamil Rytarowski   if (status == -1) {
51f07a9995SKamil Rytarowski     error.SetErrorToErrno();
52f07a9995SKamil Rytarowski     return error;
53f07a9995SKamil Rytarowski   }
54f07a9995SKamil Rytarowski 
55f07a9995SKamil Rytarowski   if (fcntl(fd, F_SETFL, status | flags) == -1) {
56f07a9995SKamil Rytarowski     error.SetErrorToErrno();
57f07a9995SKamil Rytarowski     return error;
58f07a9995SKamil Rytarowski   }
59f07a9995SKamil Rytarowski 
60f07a9995SKamil Rytarowski   return error;
61f07a9995SKamil Rytarowski }
62f07a9995SKamil Rytarowski 
631a3d19ddSKamil Rytarowski // -----------------------------------------------------------------------------
641a3d19ddSKamil Rytarowski // Public Static Methods
651a3d19ddSKamil Rytarowski // -----------------------------------------------------------------------------
661a3d19ddSKamil Rytarowski 
67*96e600fcSPavel Labath llvm::Expected<NativeProcessProtocolSP>
68*96e600fcSPavel Labath NativeProcessNetBSD::Factory::Launch(ProcessLaunchInfo &launch_info,
69*96e600fcSPavel Labath                                      NativeDelegate &native_delegate,
70*96e600fcSPavel Labath                                      MainLoop &mainloop) const {
71f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
72f07a9995SKamil Rytarowski 
73*96e600fcSPavel Labath   Status status;
74*96e600fcSPavel Labath   ::pid_t pid = ProcessLauncherPosixFork()
75*96e600fcSPavel Labath                     .LaunchProcess(launch_info, status)
76*96e600fcSPavel Labath                     .GetProcessId();
77*96e600fcSPavel Labath   LLDB_LOG(log, "pid = {0:x}", pid);
78*96e600fcSPavel Labath   if (status.Fail()) {
79*96e600fcSPavel Labath     LLDB_LOG(log, "failed to launch process: {0}", status);
80*96e600fcSPavel Labath     return status.ToError();
81f07a9995SKamil Rytarowski   }
82f07a9995SKamil Rytarowski 
83*96e600fcSPavel Labath   // Wait for the child process to trap on its call to execve.
84*96e600fcSPavel Labath   int wstatus;
85*96e600fcSPavel Labath   ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0);
86*96e600fcSPavel Labath   assert(wpid == pid);
87*96e600fcSPavel Labath   (void)wpid;
88*96e600fcSPavel Labath   if (!WIFSTOPPED(wstatus)) {
89*96e600fcSPavel Labath     LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}",
90*96e600fcSPavel Labath              WaitStatus::Decode(wstatus));
91*96e600fcSPavel Labath     return llvm::make_error<StringError>("Could not sync with inferior process",
92*96e600fcSPavel Labath                                          llvm::inconvertibleErrorCode());
93*96e600fcSPavel Labath   }
94*96e600fcSPavel Labath   LLDB_LOG(log, "inferior started, now in stopped state");
95f07a9995SKamil Rytarowski 
96*96e600fcSPavel Labath   ArchSpec arch;
97*96e600fcSPavel Labath   if ((status = ResolveProcessArchitecture(pid, arch)).Fail())
98*96e600fcSPavel Labath     return status.ToError();
99*96e600fcSPavel Labath 
100*96e600fcSPavel Labath   // Set the architecture to the exe architecture.
101*96e600fcSPavel Labath   LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid,
102*96e600fcSPavel Labath            arch.GetArchitectureName());
103*96e600fcSPavel Labath 
104*96e600fcSPavel Labath   std::shared_ptr<NativeProcessNetBSD> process_sp(new NativeProcessNetBSD(
105*96e600fcSPavel Labath       pid, launch_info.GetPTY().ReleaseMasterFileDescriptor(), native_delegate,
106*96e600fcSPavel Labath       arch, mainloop));
107*96e600fcSPavel Labath 
108*96e600fcSPavel Labath   status = process_sp->ReinitializeThreads();
109*96e600fcSPavel Labath   if (status.Fail())
110*96e600fcSPavel Labath     return status.ToError();
111*96e600fcSPavel Labath 
112*96e600fcSPavel Labath   for (const auto &thread_sp : process_sp->m_threads) {
113*96e600fcSPavel Labath     static_pointer_cast<NativeThreadNetBSD>(thread_sp)->SetStoppedBySignal(
114*96e600fcSPavel Labath         SIGSTOP);
115*96e600fcSPavel Labath   }
116*96e600fcSPavel Labath   process_sp->SetState(StateType::eStateStopped);
117*96e600fcSPavel Labath 
118*96e600fcSPavel Labath   return process_sp;
119f07a9995SKamil Rytarowski }
120f07a9995SKamil Rytarowski 
121*96e600fcSPavel Labath llvm::Expected<NativeProcessProtocolSP> NativeProcessNetBSD::Factory::Attach(
1221a3d19ddSKamil Rytarowski     lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
123*96e600fcSPavel Labath     MainLoop &mainloop) const {
124f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
125f07a9995SKamil Rytarowski   LLDB_LOG(log, "pid = {0:x}", pid);
126f07a9995SKamil Rytarowski 
127f07a9995SKamil Rytarowski   // Retrieve the architecture for the running process.
128*96e600fcSPavel Labath   ArchSpec arch;
129*96e600fcSPavel Labath   Status status = ResolveProcessArchitecture(pid, arch);
130*96e600fcSPavel Labath   if (!status.Success())
131*96e600fcSPavel Labath     return status.ToError();
132f07a9995SKamil Rytarowski 
133*96e600fcSPavel Labath   std::shared_ptr<NativeProcessNetBSD> process_sp(
134*96e600fcSPavel Labath       new NativeProcessNetBSD(pid, -1, native_delegate, arch, mainloop));
135f07a9995SKamil Rytarowski 
136*96e600fcSPavel Labath   status = process_sp->Attach();
137*96e600fcSPavel Labath   if (!status.Success())
138*96e600fcSPavel Labath     return status.ToError();
139f07a9995SKamil Rytarowski 
140*96e600fcSPavel Labath   return process_sp;
1411a3d19ddSKamil Rytarowski }
1421a3d19ddSKamil Rytarowski 
1431a3d19ddSKamil Rytarowski // -----------------------------------------------------------------------------
1441a3d19ddSKamil Rytarowski // Public Instance Methods
1451a3d19ddSKamil Rytarowski // -----------------------------------------------------------------------------
1461a3d19ddSKamil Rytarowski 
147*96e600fcSPavel Labath NativeProcessNetBSD::NativeProcessNetBSD(::pid_t pid, int terminal_fd,
148*96e600fcSPavel Labath                                          NativeDelegate &delegate,
149*96e600fcSPavel Labath                                          const ArchSpec &arch,
150*96e600fcSPavel Labath                                          MainLoop &mainloop)
151*96e600fcSPavel Labath     : NativeProcessProtocol(pid, terminal_fd, delegate), m_arch(arch) {
152*96e600fcSPavel Labath   if (m_terminal_fd != -1) {
153*96e600fcSPavel Labath     Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
154*96e600fcSPavel Labath     assert(status.Success());
155*96e600fcSPavel Labath   }
156*96e600fcSPavel Labath 
157*96e600fcSPavel Labath   Status status;
158*96e600fcSPavel Labath   m_sigchld_handle = mainloop.RegisterSignal(
159*96e600fcSPavel Labath       SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status);
160*96e600fcSPavel Labath   assert(m_sigchld_handle && status.Success());
161*96e600fcSPavel Labath }
162f07a9995SKamil Rytarowski 
163f07a9995SKamil Rytarowski // Handles all waitpid events from the inferior process.
164f07a9995SKamil Rytarowski void NativeProcessNetBSD::MonitorCallback(lldb::pid_t pid, int signal) {
165f07a9995SKamil Rytarowski   switch (signal) {
166f07a9995SKamil Rytarowski   case SIGTRAP:
167f07a9995SKamil Rytarowski     return MonitorSIGTRAP(pid);
168f07a9995SKamil Rytarowski   case SIGSTOP:
169f07a9995SKamil Rytarowski     return MonitorSIGSTOP(pid);
170f07a9995SKamil Rytarowski   default:
171f07a9995SKamil Rytarowski     return MonitorSignal(pid, signal);
172f07a9995SKamil Rytarowski   }
173f07a9995SKamil Rytarowski }
174f07a9995SKamil Rytarowski 
1753508fc8cSPavel Labath void NativeProcessNetBSD::MonitorExited(lldb::pid_t pid, WaitStatus status) {
176f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
177f07a9995SKamil Rytarowski 
1783508fc8cSPavel Labath   LLDB_LOG(log, "got exit signal({0}) , pid = {1}", status, pid);
179f07a9995SKamil Rytarowski 
180f07a9995SKamil Rytarowski   /* Stop Tracking All Threads attached to Process */
181f07a9995SKamil Rytarowski   m_threads.clear();
182f07a9995SKamil Rytarowski 
1833508fc8cSPavel Labath   SetExitStatus(status, true);
184f07a9995SKamil Rytarowski 
185f07a9995SKamil Rytarowski   // Notify delegate that our process has exited.
186f07a9995SKamil Rytarowski   SetState(StateType::eStateExited, true);
187f07a9995SKamil Rytarowski }
188f07a9995SKamil Rytarowski 
189f07a9995SKamil Rytarowski void NativeProcessNetBSD::MonitorSIGSTOP(lldb::pid_t pid) {
190f07a9995SKamil Rytarowski   ptrace_siginfo_t info;
191f07a9995SKamil Rytarowski 
192f07a9995SKamil Rytarowski   const auto siginfo_err =
193f07a9995SKamil Rytarowski       PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info));
194f07a9995SKamil Rytarowski 
195f07a9995SKamil Rytarowski   // Get details on the signal raised.
196f07a9995SKamil Rytarowski   if (siginfo_err.Success()) {
197f07a9995SKamil Rytarowski     // Handle SIGSTOP from LLGS (LLDB GDB Server)
198f07a9995SKamil Rytarowski     if (info.psi_siginfo.si_code == SI_USER &&
199f07a9995SKamil Rytarowski         info.psi_siginfo.si_pid == ::getpid()) {
200f07a9995SKamil Rytarowski       /* Stop Tracking All Threads attached to Process */
201f07a9995SKamil Rytarowski       for (const auto &thread_sp : m_threads) {
202f07a9995SKamil Rytarowski         static_pointer_cast<NativeThreadNetBSD>(thread_sp)->SetStoppedBySignal(
203f07a9995SKamil Rytarowski             SIGSTOP, &info.psi_siginfo);
204f07a9995SKamil Rytarowski       }
205f07a9995SKamil Rytarowski     }
206f07a9995SKamil Rytarowski   }
207f07a9995SKamil Rytarowski }
208f07a9995SKamil Rytarowski 
209f07a9995SKamil Rytarowski void NativeProcessNetBSD::MonitorSIGTRAP(lldb::pid_t pid) {
210f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
211f07a9995SKamil Rytarowski   ptrace_siginfo_t info;
212f07a9995SKamil Rytarowski 
213f07a9995SKamil Rytarowski   const auto siginfo_err =
214f07a9995SKamil Rytarowski       PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info));
215f07a9995SKamil Rytarowski 
216f07a9995SKamil Rytarowski   // Get details on the signal raised.
21736e23ecaSKamil Rytarowski   if (siginfo_err.Fail()) {
21836e23ecaSKamil Rytarowski     return;
21936e23ecaSKamil Rytarowski   }
22036e23ecaSKamil Rytarowski 
221f07a9995SKamil Rytarowski   switch (info.psi_siginfo.si_code) {
222f07a9995SKamil Rytarowski   case TRAP_BRKPT:
223f07a9995SKamil Rytarowski     for (const auto &thread_sp : m_threads) {
224f07a9995SKamil Rytarowski       static_pointer_cast<NativeThreadNetBSD>(thread_sp)
225f07a9995SKamil Rytarowski           ->SetStoppedByBreakpoint();
226f07a9995SKamil Rytarowski       FixupBreakpointPCAsNeeded(
227f07a9995SKamil Rytarowski           *static_pointer_cast<NativeThreadNetBSD>(thread_sp));
228f07a9995SKamil Rytarowski     }
229f07a9995SKamil Rytarowski     SetState(StateType::eStateStopped, true);
230f07a9995SKamil Rytarowski     break;
2313eef2b5eSKamil Rytarowski   case TRAP_TRACE:
2323eef2b5eSKamil Rytarowski     for (const auto &thread_sp : m_threads) {
2333eef2b5eSKamil Rytarowski       static_pointer_cast<NativeThreadNetBSD>(thread_sp)->SetStoppedByTrace();
2343eef2b5eSKamil Rytarowski     }
2353eef2b5eSKamil Rytarowski     SetState(StateType::eStateStopped, true);
2363eef2b5eSKamil Rytarowski     break;
2373eef2b5eSKamil Rytarowski   case TRAP_EXEC: {
23897206d57SZachary Turner     Status error = ReinitializeThreads();
2393eef2b5eSKamil Rytarowski     if (error.Fail()) {
2403eef2b5eSKamil Rytarowski       SetState(StateType::eStateInvalid);
2413eef2b5eSKamil Rytarowski       return;
2423eef2b5eSKamil Rytarowski     }
2433eef2b5eSKamil Rytarowski 
2443eef2b5eSKamil Rytarowski     // Let our delegate know we have just exec'd.
2453eef2b5eSKamil Rytarowski     NotifyDidExec();
2463eef2b5eSKamil Rytarowski 
24736e23ecaSKamil Rytarowski     for (const auto &thread_sp : m_threads) {
24836e23ecaSKamil Rytarowski       static_pointer_cast<NativeThreadNetBSD>(thread_sp)->SetStoppedByExec();
24936e23ecaSKamil Rytarowski     }
2503eef2b5eSKamil Rytarowski     SetState(StateType::eStateStopped, true);
2513eef2b5eSKamil Rytarowski   } break;
25236e23ecaSKamil Rytarowski   case TRAP_DBREG: {
25336e23ecaSKamil Rytarowski     // If a watchpoint was hit, report it
25436e23ecaSKamil Rytarowski     uint32_t wp_index;
25597206d57SZachary Turner     Status error =
25636e23ecaSKamil Rytarowski         static_pointer_cast<NativeThreadNetBSD>(m_threads[info.psi_lwpid])
25736e23ecaSKamil Rytarowski             ->GetRegisterContext()
25836e23ecaSKamil Rytarowski             ->GetWatchpointHitIndex(wp_index,
25936e23ecaSKamil Rytarowski                                     (uintptr_t)info.psi_siginfo.si_addr);
26036e23ecaSKamil Rytarowski     if (error.Fail())
26136e23ecaSKamil Rytarowski       LLDB_LOG(log,
26236e23ecaSKamil Rytarowski                "received error while checking for watchpoint hits, pid = "
26336e23ecaSKamil Rytarowski                "{0}, LWP = {1}, error = {2}",
26436e23ecaSKamil Rytarowski                GetID(), info.psi_lwpid, error);
26536e23ecaSKamil Rytarowski     if (wp_index != LLDB_INVALID_INDEX32) {
26636e23ecaSKamil Rytarowski       for (const auto &thread_sp : m_threads) {
26736e23ecaSKamil Rytarowski         static_pointer_cast<NativeThreadNetBSD>(thread_sp)
26836e23ecaSKamil Rytarowski             ->SetStoppedByWatchpoint(wp_index);
269f07a9995SKamil Rytarowski       }
27036e23ecaSKamil Rytarowski       SetState(StateType::eStateStopped, true);
27136e23ecaSKamil Rytarowski       break;
27236e23ecaSKamil Rytarowski     }
27336e23ecaSKamil Rytarowski 
27436e23ecaSKamil Rytarowski     // If a breakpoint was hit, report it
27536e23ecaSKamil Rytarowski     uint32_t bp_index;
27636e23ecaSKamil Rytarowski     error = static_pointer_cast<NativeThreadNetBSD>(m_threads[info.psi_lwpid])
27736e23ecaSKamil Rytarowski                 ->GetRegisterContext()
27836e23ecaSKamil Rytarowski                 ->GetHardwareBreakHitIndex(bp_index,
27936e23ecaSKamil Rytarowski                                            (uintptr_t)info.psi_siginfo.si_addr);
28036e23ecaSKamil Rytarowski     if (error.Fail())
28136e23ecaSKamil Rytarowski       LLDB_LOG(log,
28236e23ecaSKamil Rytarowski                "received error while checking for hardware "
28336e23ecaSKamil Rytarowski                "breakpoint hits, pid = {0}, LWP = {1}, error = {2}",
28436e23ecaSKamil Rytarowski                GetID(), info.psi_lwpid, error);
28536e23ecaSKamil Rytarowski     if (bp_index != LLDB_INVALID_INDEX32) {
28636e23ecaSKamil Rytarowski       for (const auto &thread_sp : m_threads) {
28736e23ecaSKamil Rytarowski         static_pointer_cast<NativeThreadNetBSD>(thread_sp)
28836e23ecaSKamil Rytarowski             ->SetStoppedByBreakpoint();
28936e23ecaSKamil Rytarowski       }
29036e23ecaSKamil Rytarowski       SetState(StateType::eStateStopped, true);
29136e23ecaSKamil Rytarowski       break;
29236e23ecaSKamil Rytarowski     }
29336e23ecaSKamil Rytarowski   } break;
294f07a9995SKamil Rytarowski   }
295f07a9995SKamil Rytarowski }
296f07a9995SKamil Rytarowski 
297f07a9995SKamil Rytarowski void NativeProcessNetBSD::MonitorSignal(lldb::pid_t pid, int signal) {
298f07a9995SKamil Rytarowski   ptrace_siginfo_t info;
299f07a9995SKamil Rytarowski   const auto siginfo_err =
300f07a9995SKamil Rytarowski       PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info));
301f07a9995SKamil Rytarowski 
302f07a9995SKamil Rytarowski   for (const auto &thread_sp : m_threads) {
303f07a9995SKamil Rytarowski     static_pointer_cast<NativeThreadNetBSD>(thread_sp)->SetStoppedBySignal(
304f07a9995SKamil Rytarowski         info.psi_siginfo.si_signo, &info.psi_siginfo);
305f07a9995SKamil Rytarowski   }
306f07a9995SKamil Rytarowski   SetState(StateType::eStateStopped, true);
307f07a9995SKamil Rytarowski }
308f07a9995SKamil Rytarowski 
30997206d57SZachary Turner Status NativeProcessNetBSD::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
310f07a9995SKamil Rytarowski                                           int data, int *result) {
311f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
31297206d57SZachary Turner   Status error;
313f07a9995SKamil Rytarowski   int ret;
314f07a9995SKamil Rytarowski 
315f07a9995SKamil Rytarowski   errno = 0;
316f07a9995SKamil Rytarowski   ret = ptrace(req, static_cast<::pid_t>(pid), addr, data);
317f07a9995SKamil Rytarowski 
318f07a9995SKamil Rytarowski   if (ret == -1)
319f07a9995SKamil Rytarowski     error.SetErrorToErrno();
320f07a9995SKamil Rytarowski 
321f07a9995SKamil Rytarowski   if (result)
322f07a9995SKamil Rytarowski     *result = ret;
323f07a9995SKamil Rytarowski 
324f07a9995SKamil Rytarowski   LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3})={4:x}", req, pid, addr, data, ret);
325f07a9995SKamil Rytarowski 
326f07a9995SKamil Rytarowski   if (error.Fail())
327f07a9995SKamil Rytarowski     LLDB_LOG(log, "ptrace() failed: {0}", error);
328f07a9995SKamil Rytarowski 
329f07a9995SKamil Rytarowski   return error;
330f07a9995SKamil Rytarowski }
331f07a9995SKamil Rytarowski 
33297206d57SZachary Turner Status NativeProcessNetBSD::GetSoftwareBreakpointPCOffset(
333f07a9995SKamil Rytarowski     uint32_t &actual_opcode_size) {
334f07a9995SKamil Rytarowski   // FIXME put this behind a breakpoint protocol class that can be
335f07a9995SKamil Rytarowski   // set per architecture.  Need ARM, MIPS support here.
336f07a9995SKamil Rytarowski   static const uint8_t g_i386_opcode[] = {0xCC};
337f07a9995SKamil Rytarowski   switch (m_arch.GetMachine()) {
338f07a9995SKamil Rytarowski   case llvm::Triple::x86_64:
339f07a9995SKamil Rytarowski     actual_opcode_size = static_cast<uint32_t>(sizeof(g_i386_opcode));
34097206d57SZachary Turner     return Status();
341f07a9995SKamil Rytarowski   default:
342f07a9995SKamil Rytarowski     assert(false && "CPU type not supported!");
34397206d57SZachary Turner     return Status("CPU type not supported");
344f07a9995SKamil Rytarowski   }
345f07a9995SKamil Rytarowski }
346f07a9995SKamil Rytarowski 
34797206d57SZachary Turner Status
34897206d57SZachary Turner NativeProcessNetBSD::FixupBreakpointPCAsNeeded(NativeThreadNetBSD &thread) {
349f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_BREAKPOINTS));
35097206d57SZachary Turner   Status error;
351f07a9995SKamil Rytarowski   // Find out the size of a breakpoint (might depend on where we are in the
352f07a9995SKamil Rytarowski   // code).
353f07a9995SKamil Rytarowski   NativeRegisterContextSP context_sp = thread.GetRegisterContext();
354f07a9995SKamil Rytarowski   if (!context_sp) {
355f07a9995SKamil Rytarowski     error.SetErrorString("cannot get a NativeRegisterContext for the thread");
356f07a9995SKamil Rytarowski     LLDB_LOG(log, "failed: {0}", error);
357f07a9995SKamil Rytarowski     return error;
358f07a9995SKamil Rytarowski   }
359f07a9995SKamil Rytarowski   uint32_t breakpoint_size = 0;
360f07a9995SKamil Rytarowski   error = GetSoftwareBreakpointPCOffset(breakpoint_size);
361f07a9995SKamil Rytarowski   if (error.Fail()) {
362f07a9995SKamil Rytarowski     LLDB_LOG(log, "GetBreakpointSize() failed: {0}", error);
363f07a9995SKamil Rytarowski     return error;
364f07a9995SKamil Rytarowski   } else
365f07a9995SKamil Rytarowski     LLDB_LOG(log, "breakpoint size: {0}", breakpoint_size);
36636e23ecaSKamil Rytarowski   // First try probing for a breakpoint at a software breakpoint location: PC
36736e23ecaSKamil Rytarowski   // - breakpoint size.
368f07a9995SKamil Rytarowski   const lldb::addr_t initial_pc_addr =
369f07a9995SKamil Rytarowski       context_sp->GetPCfromBreakpointLocation();
370f07a9995SKamil Rytarowski   lldb::addr_t breakpoint_addr = initial_pc_addr;
371f07a9995SKamil Rytarowski   if (breakpoint_size > 0) {
372f07a9995SKamil Rytarowski     // Do not allow breakpoint probe to wrap around.
373f07a9995SKamil Rytarowski     if (breakpoint_addr >= breakpoint_size)
374f07a9995SKamil Rytarowski       breakpoint_addr -= breakpoint_size;
375f07a9995SKamil Rytarowski   }
376f07a9995SKamil Rytarowski   // Check if we stopped because of a breakpoint.
377f07a9995SKamil Rytarowski   NativeBreakpointSP breakpoint_sp;
378f07a9995SKamil Rytarowski   error = m_breakpoint_list.GetBreakpoint(breakpoint_addr, breakpoint_sp);
379f07a9995SKamil Rytarowski   if (!error.Success() || !breakpoint_sp) {
380f07a9995SKamil Rytarowski     // We didn't find one at a software probe location.  Nothing to do.
381f07a9995SKamil Rytarowski     LLDB_LOG(log,
382f07a9995SKamil Rytarowski              "pid {0} no lldb breakpoint found at current pc with "
383f07a9995SKamil Rytarowski              "adjustment: {1}",
384f07a9995SKamil Rytarowski              GetID(), breakpoint_addr);
38597206d57SZachary Turner     return Status();
386f07a9995SKamil Rytarowski   }
387f07a9995SKamil Rytarowski   // If the breakpoint is not a software breakpoint, nothing to do.
388f07a9995SKamil Rytarowski   if (!breakpoint_sp->IsSoftwareBreakpoint()) {
389f07a9995SKamil Rytarowski     LLDB_LOG(
390f07a9995SKamil Rytarowski         log,
391f07a9995SKamil Rytarowski         "pid {0} breakpoint found at {1:x}, not software, nothing to adjust",
392f07a9995SKamil Rytarowski         GetID(), breakpoint_addr);
39397206d57SZachary Turner     return Status();
394f07a9995SKamil Rytarowski   }
395f07a9995SKamil Rytarowski   //
396f07a9995SKamil Rytarowski   // We have a software breakpoint and need to adjust the PC.
397f07a9995SKamil Rytarowski   //
398f07a9995SKamil Rytarowski   // Sanity check.
399f07a9995SKamil Rytarowski   if (breakpoint_size == 0) {
400f07a9995SKamil Rytarowski     // Nothing to do!  How did we get here?
401f07a9995SKamil Rytarowski     LLDB_LOG(log,
402f07a9995SKamil Rytarowski              "pid {0} breakpoint found at {1:x}, it is software, but the "
403f07a9995SKamil Rytarowski              "size is zero, nothing to do (unexpected)",
404f07a9995SKamil Rytarowski              GetID(), breakpoint_addr);
40597206d57SZachary Turner     return Status();
406f07a9995SKamil Rytarowski   }
407f07a9995SKamil Rytarowski   //
408f07a9995SKamil Rytarowski   // We have a software breakpoint and need to adjust the PC.
409f07a9995SKamil Rytarowski   //
410f07a9995SKamil Rytarowski   // Sanity check.
411f07a9995SKamil Rytarowski   if (breakpoint_size == 0) {
412f07a9995SKamil Rytarowski     // Nothing to do!  How did we get here?
413f07a9995SKamil Rytarowski     LLDB_LOG(log,
414f07a9995SKamil Rytarowski              "pid {0} breakpoint found at {1:x}, it is software, but the "
415f07a9995SKamil Rytarowski              "size is zero, nothing to do (unexpected)",
416f07a9995SKamil Rytarowski              GetID(), breakpoint_addr);
41797206d57SZachary Turner     return Status();
418f07a9995SKamil Rytarowski   }
419f07a9995SKamil Rytarowski   // Change the program counter.
420f07a9995SKamil Rytarowski   LLDB_LOG(log, "pid {0} tid {1}: changing PC from {2:x} to {3:x}", GetID(),
421f07a9995SKamil Rytarowski            thread.GetID(), initial_pc_addr, breakpoint_addr);
422f07a9995SKamil Rytarowski   error = context_sp->SetPC(breakpoint_addr);
423f07a9995SKamil Rytarowski   if (error.Fail()) {
424f07a9995SKamil Rytarowski     LLDB_LOG(log, "pid {0} tid {1}: failed to set PC: {2}", GetID(),
425f07a9995SKamil Rytarowski              thread.GetID(), error);
426f07a9995SKamil Rytarowski     return error;
427f07a9995SKamil Rytarowski   }
428f07a9995SKamil Rytarowski   return error;
429f07a9995SKamil Rytarowski }
430f07a9995SKamil Rytarowski 
43197206d57SZachary Turner Status NativeProcessNetBSD::Resume(const ResumeActionList &resume_actions) {
432f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
433f07a9995SKamil Rytarowski   LLDB_LOG(log, "pid {0}", GetID());
434f07a9995SKamil Rytarowski 
435f07a9995SKamil Rytarowski   const auto &thread_sp = m_threads[0];
436f07a9995SKamil Rytarowski   const ResumeAction *const action =
437f07a9995SKamil Rytarowski       resume_actions.GetActionForThread(thread_sp->GetID(), true);
438f07a9995SKamil Rytarowski 
439f07a9995SKamil Rytarowski   if (action == nullptr) {
440f07a9995SKamil Rytarowski     LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
441f07a9995SKamil Rytarowski              thread_sp->GetID());
44297206d57SZachary Turner     return Status();
443f07a9995SKamil Rytarowski   }
444f07a9995SKamil Rytarowski 
44597206d57SZachary Turner   Status error;
4463eef2b5eSKamil Rytarowski 
447f07a9995SKamil Rytarowski   switch (action->state) {
448f07a9995SKamil Rytarowski   case eStateRunning: {
449f07a9995SKamil Rytarowski     // Run the thread, possibly feeding it the signal.
4503eef2b5eSKamil Rytarowski     error = NativeProcessNetBSD::PtraceWrapper(PT_CONTINUE, GetID(), (void *)1,
4513eef2b5eSKamil Rytarowski                                                action->signal);
452f07a9995SKamil Rytarowski     if (!error.Success())
453f07a9995SKamil Rytarowski       return error;
454f07a9995SKamil Rytarowski     for (const auto &thread_sp : m_threads) {
455f07a9995SKamil Rytarowski       static_pointer_cast<NativeThreadNetBSD>(thread_sp)->SetRunning();
456f07a9995SKamil Rytarowski     }
457f07a9995SKamil Rytarowski     SetState(eStateRunning, true);
458f07a9995SKamil Rytarowski     break;
459f07a9995SKamil Rytarowski   }
460f07a9995SKamil Rytarowski   case eStateStepping:
4613eef2b5eSKamil Rytarowski     // Run the thread, possibly feeding it the signal.
4623eef2b5eSKamil Rytarowski     error = NativeProcessNetBSD::PtraceWrapper(PT_STEP, GetID(), (void *)1,
4633eef2b5eSKamil Rytarowski                                                action->signal);
4643eef2b5eSKamil Rytarowski     if (!error.Success())
4653eef2b5eSKamil Rytarowski       return error;
4663eef2b5eSKamil Rytarowski     for (const auto &thread_sp : m_threads) {
4673eef2b5eSKamil Rytarowski       static_pointer_cast<NativeThreadNetBSD>(thread_sp)->SetStepping();
4683eef2b5eSKamil Rytarowski     }
4693eef2b5eSKamil Rytarowski     SetState(eStateStepping, true);
470f07a9995SKamil Rytarowski     break;
471f07a9995SKamil Rytarowski 
472f07a9995SKamil Rytarowski   case eStateSuspended:
473f07a9995SKamil Rytarowski   case eStateStopped:
474f07a9995SKamil Rytarowski     llvm_unreachable("Unexpected state");
475f07a9995SKamil Rytarowski 
476f07a9995SKamil Rytarowski   default:
47797206d57SZachary Turner     return Status("NativeProcessNetBSD::%s (): unexpected state %s specified "
478f07a9995SKamil Rytarowski                   "for pid %" PRIu64 ", tid %" PRIu64,
479f07a9995SKamil Rytarowski                   __FUNCTION__, StateAsCString(action->state), GetID(),
480f07a9995SKamil Rytarowski                   thread_sp->GetID());
481f07a9995SKamil Rytarowski   }
482f07a9995SKamil Rytarowski 
48397206d57SZachary Turner   return Status();
484f07a9995SKamil Rytarowski }
485f07a9995SKamil Rytarowski 
48697206d57SZachary Turner Status NativeProcessNetBSD::Halt() {
48797206d57SZachary Turner   Status error;
488f07a9995SKamil Rytarowski 
489f07a9995SKamil Rytarowski   if (kill(GetID(), SIGSTOP) != 0)
490f07a9995SKamil Rytarowski     error.SetErrorToErrno();
491f07a9995SKamil Rytarowski 
492f07a9995SKamil Rytarowski   return error;
493f07a9995SKamil Rytarowski }
494f07a9995SKamil Rytarowski 
49597206d57SZachary Turner Status NativeProcessNetBSD::Detach() {
49697206d57SZachary Turner   Status error;
497f07a9995SKamil Rytarowski 
498f07a9995SKamil Rytarowski   // Stop monitoring the inferior.
499f07a9995SKamil Rytarowski   m_sigchld_handle.reset();
500f07a9995SKamil Rytarowski 
501f07a9995SKamil Rytarowski   // Tell ptrace to detach from the process.
502f07a9995SKamil Rytarowski   if (GetID() == LLDB_INVALID_PROCESS_ID)
503f07a9995SKamil Rytarowski     return error;
504f07a9995SKamil Rytarowski 
505f07a9995SKamil Rytarowski   return PtraceWrapper(PT_DETACH, GetID());
506f07a9995SKamil Rytarowski }
507f07a9995SKamil Rytarowski 
50897206d57SZachary Turner Status NativeProcessNetBSD::Signal(int signo) {
50997206d57SZachary Turner   Status error;
510f07a9995SKamil Rytarowski 
511f07a9995SKamil Rytarowski   if (kill(GetID(), signo))
512f07a9995SKamil Rytarowski     error.SetErrorToErrno();
513f07a9995SKamil Rytarowski 
514f07a9995SKamil Rytarowski   return error;
515f07a9995SKamil Rytarowski }
516f07a9995SKamil Rytarowski 
51797206d57SZachary Turner Status NativeProcessNetBSD::Kill() {
518f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
519f07a9995SKamil Rytarowski   LLDB_LOG(log, "pid {0}", GetID());
520f07a9995SKamil Rytarowski 
52197206d57SZachary Turner   Status error;
522f07a9995SKamil Rytarowski 
523f07a9995SKamil Rytarowski   switch (m_state) {
524f07a9995SKamil Rytarowski   case StateType::eStateInvalid:
525f07a9995SKamil Rytarowski   case StateType::eStateExited:
526f07a9995SKamil Rytarowski   case StateType::eStateCrashed:
527f07a9995SKamil Rytarowski   case StateType::eStateDetached:
528f07a9995SKamil Rytarowski   case StateType::eStateUnloaded:
529f07a9995SKamil Rytarowski     // Nothing to do - the process is already dead.
530f07a9995SKamil Rytarowski     LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
531f07a9995SKamil Rytarowski              StateAsCString(m_state));
532f07a9995SKamil Rytarowski     return error;
533f07a9995SKamil Rytarowski 
534f07a9995SKamil Rytarowski   case StateType::eStateConnected:
535f07a9995SKamil Rytarowski   case StateType::eStateAttaching:
536f07a9995SKamil Rytarowski   case StateType::eStateLaunching:
537f07a9995SKamil Rytarowski   case StateType::eStateStopped:
538f07a9995SKamil Rytarowski   case StateType::eStateRunning:
539f07a9995SKamil Rytarowski   case StateType::eStateStepping:
540f07a9995SKamil Rytarowski   case StateType::eStateSuspended:
541f07a9995SKamil Rytarowski     // We can try to kill a process in these states.
542f07a9995SKamil Rytarowski     break;
543f07a9995SKamil Rytarowski   }
544f07a9995SKamil Rytarowski 
545f07a9995SKamil Rytarowski   if (kill(GetID(), SIGKILL) != 0) {
546f07a9995SKamil Rytarowski     error.SetErrorToErrno();
547f07a9995SKamil Rytarowski     return error;
548f07a9995SKamil Rytarowski   }
549f07a9995SKamil Rytarowski 
550f07a9995SKamil Rytarowski   return error;
551f07a9995SKamil Rytarowski }
552f07a9995SKamil Rytarowski 
55397206d57SZachary Turner Status NativeProcessNetBSD::GetMemoryRegionInfo(lldb::addr_t load_addr,
554f07a9995SKamil Rytarowski                                                 MemoryRegionInfo &range_info) {
555f07a9995SKamil Rytarowski 
556f07a9995SKamil Rytarowski   if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
557f07a9995SKamil Rytarowski     // We're done.
55897206d57SZachary Turner     return Status("unsupported");
559f07a9995SKamil Rytarowski   }
560f07a9995SKamil Rytarowski 
56197206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
562f07a9995SKamil Rytarowski   if (error.Fail()) {
563f07a9995SKamil Rytarowski     return error;
564f07a9995SKamil Rytarowski   }
565f07a9995SKamil Rytarowski 
566f07a9995SKamil Rytarowski   lldb::addr_t prev_base_address = 0;
567f07a9995SKamil Rytarowski   // FIXME start by finding the last region that is <= target address using
568f07a9995SKamil Rytarowski   // binary search.  Data is sorted.
569f07a9995SKamil Rytarowski   // There can be a ton of regions on pthreads apps with lots of threads.
570f07a9995SKamil Rytarowski   for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
571f07a9995SKamil Rytarowski        ++it) {
572f07a9995SKamil Rytarowski     MemoryRegionInfo &proc_entry_info = it->first;
573f07a9995SKamil Rytarowski     // Sanity check assumption that memory map entries are ascending.
574f07a9995SKamil Rytarowski     assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
575f07a9995SKamil Rytarowski            "descending memory map entries detected, unexpected");
576f07a9995SKamil Rytarowski     prev_base_address = proc_entry_info.GetRange().GetRangeBase();
577f07a9995SKamil Rytarowski     UNUSED_IF_ASSERT_DISABLED(prev_base_address);
57836e23ecaSKamil Rytarowski     // If the target address comes before this entry, indicate distance to
57936e23ecaSKamil Rytarowski     // next region.
580f07a9995SKamil Rytarowski     if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
581f07a9995SKamil Rytarowski       range_info.GetRange().SetRangeBase(load_addr);
582f07a9995SKamil Rytarowski       range_info.GetRange().SetByteSize(
583f07a9995SKamil Rytarowski           proc_entry_info.GetRange().GetRangeBase() - load_addr);
584f07a9995SKamil Rytarowski       range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
585f07a9995SKamil Rytarowski       range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
586f07a9995SKamil Rytarowski       range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
587f07a9995SKamil Rytarowski       range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
588f07a9995SKamil Rytarowski       return error;
589f07a9995SKamil Rytarowski     } else if (proc_entry_info.GetRange().Contains(load_addr)) {
590f07a9995SKamil Rytarowski       // The target address is within the memory region we're processing here.
591f07a9995SKamil Rytarowski       range_info = proc_entry_info;
592f07a9995SKamil Rytarowski       return error;
593f07a9995SKamil Rytarowski     }
594f07a9995SKamil Rytarowski     // The target memory address comes somewhere after the region we just
595f07a9995SKamil Rytarowski     // parsed.
596f07a9995SKamil Rytarowski   }
597f07a9995SKamil Rytarowski   // If we made it here, we didn't find an entry that contained the given
598f07a9995SKamil Rytarowski   // address. Return the
59936e23ecaSKamil Rytarowski   // load_addr as start and the amount of bytes betwwen load address and the
60036e23ecaSKamil Rytarowski   // end of the memory as size.
601f07a9995SKamil Rytarowski   range_info.GetRange().SetRangeBase(load_addr);
602f07a9995SKamil Rytarowski   range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
603f07a9995SKamil Rytarowski   range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
604f07a9995SKamil Rytarowski   range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
605f07a9995SKamil Rytarowski   range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
606f07a9995SKamil Rytarowski   range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
607f07a9995SKamil Rytarowski   return error;
608f07a9995SKamil Rytarowski }
609f07a9995SKamil Rytarowski 
61097206d57SZachary Turner Status NativeProcessNetBSD::PopulateMemoryRegionCache() {
611f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
612f07a9995SKamil Rytarowski   // If our cache is empty, pull the latest.  There should always be at least
613f07a9995SKamil Rytarowski   // one memory region if memory region handling is supported.
614f07a9995SKamil Rytarowski   if (!m_mem_region_cache.empty()) {
615f07a9995SKamil Rytarowski     LLDB_LOG(log, "reusing {0} cached memory region entries",
616f07a9995SKamil Rytarowski              m_mem_region_cache.size());
61797206d57SZachary Turner     return Status();
618f07a9995SKamil Rytarowski   }
619f07a9995SKamil Rytarowski 
620f07a9995SKamil Rytarowski   struct kinfo_vmentry *vm;
621f07a9995SKamil Rytarowski   size_t count, i;
622f07a9995SKamil Rytarowski   vm = kinfo_getvmmap(GetID(), &count);
623f07a9995SKamil Rytarowski   if (vm == NULL) {
624f07a9995SKamil Rytarowski     m_supports_mem_region = LazyBool::eLazyBoolNo;
62597206d57SZachary Turner     Status error;
626f07a9995SKamil Rytarowski     error.SetErrorString("not supported");
627f07a9995SKamil Rytarowski     return error;
628f07a9995SKamil Rytarowski   }
629f07a9995SKamil Rytarowski   for (i = 0; i < count; i++) {
630f07a9995SKamil Rytarowski     MemoryRegionInfo info;
631f07a9995SKamil Rytarowski     info.Clear();
632f07a9995SKamil Rytarowski     info.GetRange().SetRangeBase(vm[i].kve_start);
633f07a9995SKamil Rytarowski     info.GetRange().SetRangeEnd(vm[i].kve_end);
634f07a9995SKamil Rytarowski     info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
635f07a9995SKamil Rytarowski 
636f07a9995SKamil Rytarowski     if (vm[i].kve_protection & VM_PROT_READ)
637f07a9995SKamil Rytarowski       info.SetReadable(MemoryRegionInfo::OptionalBool::eYes);
638f07a9995SKamil Rytarowski     else
639f07a9995SKamil Rytarowski       info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
640f07a9995SKamil Rytarowski 
641f07a9995SKamil Rytarowski     if (vm[i].kve_protection & VM_PROT_WRITE)
642f07a9995SKamil Rytarowski       info.SetWritable(MemoryRegionInfo::OptionalBool::eYes);
643f07a9995SKamil Rytarowski     else
644f07a9995SKamil Rytarowski       info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
645f07a9995SKamil Rytarowski 
646f07a9995SKamil Rytarowski     if (vm[i].kve_protection & VM_PROT_EXECUTE)
647f07a9995SKamil Rytarowski       info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes);
648f07a9995SKamil Rytarowski     else
649f07a9995SKamil Rytarowski       info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
650f07a9995SKamil Rytarowski 
651f07a9995SKamil Rytarowski     if (vm[i].kve_path[0])
652f07a9995SKamil Rytarowski       info.SetName(vm[i].kve_path);
653f07a9995SKamil Rytarowski 
654f07a9995SKamil Rytarowski     m_mem_region_cache.emplace_back(
655f07a9995SKamil Rytarowski         info, FileSpec(info.GetName().GetCString(), true));
656f07a9995SKamil Rytarowski   }
657f07a9995SKamil Rytarowski   free(vm);
658f07a9995SKamil Rytarowski 
659f07a9995SKamil Rytarowski   if (m_mem_region_cache.empty()) {
660f07a9995SKamil Rytarowski     // No entries after attempting to read them.  This shouldn't happen.
661f07a9995SKamil Rytarowski     // Assume we don't support map entries.
662f07a9995SKamil Rytarowski     LLDB_LOG(log, "failed to find any vmmap entries, assuming no support "
663f07a9995SKamil Rytarowski                   "for memory region metadata retrieval");
664f07a9995SKamil Rytarowski     m_supports_mem_region = LazyBool::eLazyBoolNo;
66597206d57SZachary Turner     Status error;
666f07a9995SKamil Rytarowski     error.SetErrorString("not supported");
667f07a9995SKamil Rytarowski     return error;
668f07a9995SKamil Rytarowski   }
669f07a9995SKamil Rytarowski   LLDB_LOG(log, "read {0} memory region entries from process {1}",
670f07a9995SKamil Rytarowski            m_mem_region_cache.size(), GetID());
671f07a9995SKamil Rytarowski   // We support memory retrieval, remember that.
672f07a9995SKamil Rytarowski   m_supports_mem_region = LazyBool::eLazyBoolYes;
67397206d57SZachary Turner   return Status();
674f07a9995SKamil Rytarowski }
675f07a9995SKamil Rytarowski 
67697206d57SZachary Turner Status NativeProcessNetBSD::AllocateMemory(size_t size, uint32_t permissions,
677f07a9995SKamil Rytarowski                                            lldb::addr_t &addr) {
67897206d57SZachary Turner   return Status("Unimplemented");
679f07a9995SKamil Rytarowski }
680f07a9995SKamil Rytarowski 
68197206d57SZachary Turner Status NativeProcessNetBSD::DeallocateMemory(lldb::addr_t addr) {
68297206d57SZachary Turner   return Status("Unimplemented");
683f07a9995SKamil Rytarowski }
684f07a9995SKamil Rytarowski 
685f07a9995SKamil Rytarowski lldb::addr_t NativeProcessNetBSD::GetSharedLibraryInfoAddress() {
686f07a9995SKamil Rytarowski   // punt on this for now
687f07a9995SKamil Rytarowski   return LLDB_INVALID_ADDRESS;
688f07a9995SKamil Rytarowski }
689f07a9995SKamil Rytarowski 
690f07a9995SKamil Rytarowski size_t NativeProcessNetBSD::UpdateThreads() { return m_threads.size(); }
691f07a9995SKamil Rytarowski 
692f07a9995SKamil Rytarowski bool NativeProcessNetBSD::GetArchitecture(ArchSpec &arch) const {
693f07a9995SKamil Rytarowski   arch = m_arch;
694f07a9995SKamil Rytarowski   return true;
695f07a9995SKamil Rytarowski }
696f07a9995SKamil Rytarowski 
69797206d57SZachary Turner Status NativeProcessNetBSD::SetBreakpoint(lldb::addr_t addr, uint32_t size,
698f07a9995SKamil Rytarowski                                           bool hardware) {
699f07a9995SKamil Rytarowski   if (hardware)
70097206d57SZachary Turner     return Status("NativeProcessNetBSD does not support hardware breakpoints");
701f07a9995SKamil Rytarowski   else
702f07a9995SKamil Rytarowski     return SetSoftwareBreakpoint(addr, size);
703f07a9995SKamil Rytarowski }
704f07a9995SKamil Rytarowski 
70597206d57SZachary Turner Status NativeProcessNetBSD::GetSoftwareBreakpointTrapOpcode(
706f07a9995SKamil Rytarowski     size_t trap_opcode_size_hint, size_t &actual_opcode_size,
707f07a9995SKamil Rytarowski     const uint8_t *&trap_opcode_bytes) {
708f07a9995SKamil Rytarowski   static const uint8_t g_i386_opcode[] = {0xCC};
709f07a9995SKamil Rytarowski 
710f07a9995SKamil Rytarowski   switch (m_arch.GetMachine()) {
711f07a9995SKamil Rytarowski   case llvm::Triple::x86:
712f07a9995SKamil Rytarowski   case llvm::Triple::x86_64:
713f07a9995SKamil Rytarowski     trap_opcode_bytes = g_i386_opcode;
714f07a9995SKamil Rytarowski     actual_opcode_size = sizeof(g_i386_opcode);
71597206d57SZachary Turner     return Status();
716f07a9995SKamil Rytarowski   default:
717f07a9995SKamil Rytarowski     assert(false && "CPU type not supported!");
71897206d57SZachary Turner     return Status("CPU type not supported");
719f07a9995SKamil Rytarowski   }
720f07a9995SKamil Rytarowski }
721f07a9995SKamil Rytarowski 
72297206d57SZachary Turner Status NativeProcessNetBSD::GetLoadedModuleFileSpec(const char *module_path,
723f07a9995SKamil Rytarowski                                                     FileSpec &file_spec) {
72497206d57SZachary Turner   return Status("Unimplemented");
725f07a9995SKamil Rytarowski }
726f07a9995SKamil Rytarowski 
72797206d57SZachary Turner Status NativeProcessNetBSD::GetFileLoadAddress(const llvm::StringRef &file_name,
728f07a9995SKamil Rytarowski                                                lldb::addr_t &load_addr) {
729f07a9995SKamil Rytarowski   load_addr = LLDB_INVALID_ADDRESS;
73097206d57SZachary Turner   return Status();
731f07a9995SKamil Rytarowski }
732f07a9995SKamil Rytarowski 
733f07a9995SKamil Rytarowski void NativeProcessNetBSD::SigchldHandler() {
734f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
735f07a9995SKamil Rytarowski   // Process all pending waitpid notifications.
736f07a9995SKamil Rytarowski   int status;
737c1a6b128SPavel Labath   ::pid_t wait_pid =
738c1a6b128SPavel Labath       llvm::sys::RetryAfterSignal(-1, waitpid, GetID(), &status, WALLSIG | WNOHANG);
739f07a9995SKamil Rytarowski 
740f07a9995SKamil Rytarowski   if (wait_pid == 0)
741f07a9995SKamil Rytarowski     return; // We are done.
742f07a9995SKamil Rytarowski 
743f07a9995SKamil Rytarowski   if (wait_pid == -1) {
74497206d57SZachary Turner     Status error(errno, eErrorTypePOSIX);
745f07a9995SKamil Rytarowski     LLDB_LOG(log, "waitpid ({0}, &status, _) failed: {1}", GetID(), error);
746f07a9995SKamil Rytarowski   }
747f07a9995SKamil Rytarowski 
7483508fc8cSPavel Labath   WaitStatus wait_status = WaitStatus::Decode(status);
7493508fc8cSPavel Labath   bool exited = wait_status.type == WaitStatus::Exit ||
7503508fc8cSPavel Labath                 (wait_status.type == WaitStatus::Signal &&
7513508fc8cSPavel Labath                  wait_pid == static_cast<::pid_t>(GetID()));
752f07a9995SKamil Rytarowski 
753f07a9995SKamil Rytarowski   LLDB_LOG(log,
7543508fc8cSPavel Labath            "waitpid ({0}, &status, _) => pid = {1}, status = {2}, exited = {3}",
7553508fc8cSPavel Labath            GetID(), wait_pid, status, exited);
756f07a9995SKamil Rytarowski 
757f07a9995SKamil Rytarowski   if (exited)
7583508fc8cSPavel Labath     MonitorExited(wait_pid, wait_status);
7593508fc8cSPavel Labath   else {
7604bb74415SKamil Rytarowski     assert(wait_status.type == WaitStatus::Stop);
7613508fc8cSPavel Labath     MonitorCallback(wait_pid, wait_status.status);
7623508fc8cSPavel Labath   }
763f07a9995SKamil Rytarowski }
764f07a9995SKamil Rytarowski 
765269eec03SKamil Rytarowski bool NativeProcessNetBSD::HasThreadNoLock(lldb::tid_t thread_id) {
766269eec03SKamil Rytarowski   for (auto thread_sp : m_threads) {
767269eec03SKamil Rytarowski     assert(thread_sp && "thread list should not contain NULL threads");
768269eec03SKamil Rytarowski     if (thread_sp->GetID() == thread_id) {
769269eec03SKamil Rytarowski       // We have this thread.
770269eec03SKamil Rytarowski       return true;
771269eec03SKamil Rytarowski     }
772269eec03SKamil Rytarowski   }
773269eec03SKamil Rytarowski 
774269eec03SKamil Rytarowski   // We don't have this thread.
775269eec03SKamil Rytarowski   return false;
776269eec03SKamil Rytarowski }
777269eec03SKamil Rytarowski 
778f07a9995SKamil Rytarowski NativeThreadNetBSDSP NativeProcessNetBSD::AddThread(lldb::tid_t thread_id) {
779f07a9995SKamil Rytarowski 
780f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
781f07a9995SKamil Rytarowski   LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
782f07a9995SKamil Rytarowski 
783f07a9995SKamil Rytarowski   assert(!HasThreadNoLock(thread_id) &&
784f07a9995SKamil Rytarowski          "attempted to add a thread by id that already exists");
785f07a9995SKamil Rytarowski 
786f07a9995SKamil Rytarowski   // If this is the first thread, save it as the current thread
787f07a9995SKamil Rytarowski   if (m_threads.empty())
788f07a9995SKamil Rytarowski     SetCurrentThreadID(thread_id);
789f07a9995SKamil Rytarowski 
790f07a9995SKamil Rytarowski   auto thread_sp = std::make_shared<NativeThreadNetBSD>(this, thread_id);
791f07a9995SKamil Rytarowski   m_threads.push_back(thread_sp);
792f07a9995SKamil Rytarowski   return thread_sp;
793f07a9995SKamil Rytarowski }
794f07a9995SKamil Rytarowski 
795*96e600fcSPavel Labath Status NativeProcessNetBSD::Attach() {
796f07a9995SKamil Rytarowski   // Attach to the requested process.
797f07a9995SKamil Rytarowski   // An attach will cause the thread to stop with a SIGSTOP.
798*96e600fcSPavel Labath   Status status = PtraceWrapper(PT_ATTACH, m_pid);
799*96e600fcSPavel Labath   if (status.Fail())
800*96e600fcSPavel Labath     return status;
801f07a9995SKamil Rytarowski 
802*96e600fcSPavel Labath   int wstatus;
803f07a9995SKamil Rytarowski   // Need to use WALLSIG otherwise we receive an error with errno=ECHLD
804f07a9995SKamil Rytarowski   // At this point we should have a thread stopped if waitpid succeeds.
805*96e600fcSPavel Labath   if ((wstatus = waitpid(m_pid, NULL, WALLSIG)) < 0)
806*96e600fcSPavel Labath     return Status(errno, eErrorTypePOSIX);
807f07a9995SKamil Rytarowski 
808f07a9995SKamil Rytarowski   /* Initialize threads */
809*96e600fcSPavel Labath   status = ReinitializeThreads();
810*96e600fcSPavel Labath   if (status.Fail())
811*96e600fcSPavel Labath     return status;
812f07a9995SKamil Rytarowski 
81336e23ecaSKamil Rytarowski   for (const auto &thread_sp : m_threads) {
81436e23ecaSKamil Rytarowski     static_pointer_cast<NativeThreadNetBSD>(thread_sp)->SetStoppedBySignal(
81536e23ecaSKamil Rytarowski         SIGSTOP);
81636e23ecaSKamil Rytarowski   }
81736e23ecaSKamil Rytarowski 
818f07a9995SKamil Rytarowski   // Let our process instance know the thread has stopped.
819f07a9995SKamil Rytarowski   SetState(StateType::eStateStopped);
820*96e600fcSPavel Labath   return Status();
821f07a9995SKamil Rytarowski }
822f07a9995SKamil Rytarowski 
82397206d57SZachary Turner Status NativeProcessNetBSD::ReadMemory(lldb::addr_t addr, void *buf,
82497206d57SZachary Turner                                        size_t size, size_t &bytes_read) {
825f07a9995SKamil Rytarowski   unsigned char *dst = static_cast<unsigned char *>(buf);
826f07a9995SKamil Rytarowski   struct ptrace_io_desc io;
827f07a9995SKamil Rytarowski 
828f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
829f07a9995SKamil Rytarowski   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
830f07a9995SKamil Rytarowski 
831f07a9995SKamil Rytarowski   bytes_read = 0;
832f07a9995SKamil Rytarowski   io.piod_op = PIOD_READ_D;
833f07a9995SKamil Rytarowski   io.piod_len = size;
834f07a9995SKamil Rytarowski 
835f07a9995SKamil Rytarowski   do {
836f07a9995SKamil Rytarowski     io.piod_offs = (void *)(addr + bytes_read);
837f07a9995SKamil Rytarowski     io.piod_addr = dst + bytes_read;
838f07a9995SKamil Rytarowski 
83997206d57SZachary Turner     Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
840f07a9995SKamil Rytarowski     if (error.Fail())
841f07a9995SKamil Rytarowski       return error;
842f07a9995SKamil Rytarowski 
843f07a9995SKamil Rytarowski     bytes_read = io.piod_len;
844f07a9995SKamil Rytarowski     io.piod_len = size - bytes_read;
845f07a9995SKamil Rytarowski   } while (bytes_read < size);
846f07a9995SKamil Rytarowski 
84797206d57SZachary Turner   return Status();
848f07a9995SKamil Rytarowski }
849f07a9995SKamil Rytarowski 
85097206d57SZachary Turner Status NativeProcessNetBSD::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf,
851f07a9995SKamil Rytarowski                                                   size_t size,
852f07a9995SKamil Rytarowski                                                   size_t &bytes_read) {
85397206d57SZachary Turner   Status error = ReadMemory(addr, buf, size, bytes_read);
854f07a9995SKamil Rytarowski   if (error.Fail())
855f07a9995SKamil Rytarowski     return error;
856f07a9995SKamil Rytarowski   return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
857f07a9995SKamil Rytarowski }
858f07a9995SKamil Rytarowski 
85997206d57SZachary Turner Status NativeProcessNetBSD::WriteMemory(lldb::addr_t addr, const void *buf,
860f07a9995SKamil Rytarowski                                         size_t size, size_t &bytes_written) {
861f07a9995SKamil Rytarowski   const unsigned char *src = static_cast<const unsigned char *>(buf);
86297206d57SZachary Turner   Status error;
863f07a9995SKamil Rytarowski   struct ptrace_io_desc io;
864f07a9995SKamil Rytarowski 
865f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
866f07a9995SKamil Rytarowski   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
867f07a9995SKamil Rytarowski 
868f07a9995SKamil Rytarowski   bytes_written = 0;
869f07a9995SKamil Rytarowski   io.piod_op = PIOD_WRITE_D;
870f07a9995SKamil Rytarowski   io.piod_len = size;
871f07a9995SKamil Rytarowski 
872f07a9995SKamil Rytarowski   do {
873269eec03SKamil Rytarowski     io.piod_addr = const_cast<void *>(static_cast<const void *>(src + bytes_written));
874f07a9995SKamil Rytarowski     io.piod_offs = (void *)(addr + bytes_written);
875f07a9995SKamil Rytarowski 
87697206d57SZachary Turner     Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
877f07a9995SKamil Rytarowski     if (error.Fail())
878f07a9995SKamil Rytarowski       return error;
879f07a9995SKamil Rytarowski 
880f07a9995SKamil Rytarowski     bytes_written = io.piod_len;
881f07a9995SKamil Rytarowski     io.piod_len = size - bytes_written;
882f07a9995SKamil Rytarowski   } while (bytes_written < size);
883f07a9995SKamil Rytarowski 
884f07a9995SKamil Rytarowski   return error;
885f07a9995SKamil Rytarowski }
886f07a9995SKamil Rytarowski 
887f07a9995SKamil Rytarowski llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
888f07a9995SKamil Rytarowski NativeProcessNetBSD::GetAuxvData() const {
889f07a9995SKamil Rytarowski   /*
890f07a9995SKamil Rytarowski    * ELF_AUX_ENTRIES is currently restricted to kernel
891f07a9995SKamil Rytarowski    * (<sys/exec_elf.h> r. 1.155 specifies 15)
892f07a9995SKamil Rytarowski    *
893f07a9995SKamil Rytarowski    * ptrace(2) returns the whole AUXV including extra fiels after AT_NULL this
894f07a9995SKamil Rytarowski    * information isn't needed.
895f07a9995SKamil Rytarowski    */
896f07a9995SKamil Rytarowski   size_t auxv_size = 100 * sizeof(AuxInfo);
897f07a9995SKamil Rytarowski 
898f07a9995SKamil Rytarowski   ErrorOr<std::unique_ptr<MemoryBuffer>> buf =
899f07a9995SKamil Rytarowski       llvm::MemoryBuffer::getNewMemBuffer(auxv_size);
900f07a9995SKamil Rytarowski 
901269eec03SKamil Rytarowski   struct ptrace_io_desc io;
902269eec03SKamil Rytarowski   io.piod_op = PIOD_READ_AUXV;
903269eec03SKamil Rytarowski   io.piod_offs = 0;
904269eec03SKamil Rytarowski   io.piod_addr = const_cast<void *>(static_cast<const void *>(buf.get()->getBufferStart()));
905269eec03SKamil Rytarowski   io.piod_len = auxv_size;
906f07a9995SKamil Rytarowski 
90797206d57SZachary Turner   Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
908f07a9995SKamil Rytarowski 
909f07a9995SKamil Rytarowski   if (error.Fail())
910f07a9995SKamil Rytarowski     return std::error_code(error.GetError(), std::generic_category());
911f07a9995SKamil Rytarowski 
912f07a9995SKamil Rytarowski   if (io.piod_len < 1)
913f07a9995SKamil Rytarowski     return std::error_code(ECANCELED, std::generic_category());
914f07a9995SKamil Rytarowski 
915f07a9995SKamil Rytarowski   return buf;
916f07a9995SKamil Rytarowski }
9173eef2b5eSKamil Rytarowski 
91897206d57SZachary Turner Status NativeProcessNetBSD::ReinitializeThreads() {
9193eef2b5eSKamil Rytarowski   // Clear old threads
9203eef2b5eSKamil Rytarowski   m_threads.clear();
9213eef2b5eSKamil Rytarowski 
9223eef2b5eSKamil Rytarowski   // Initialize new thread
9233eef2b5eSKamil Rytarowski   struct ptrace_lwpinfo info = {};
92497206d57SZachary Turner   Status error = PtraceWrapper(PT_LWPINFO, GetID(), &info, sizeof(info));
9253eef2b5eSKamil Rytarowski   if (error.Fail()) {
9263eef2b5eSKamil Rytarowski     return error;
9273eef2b5eSKamil Rytarowski   }
9283eef2b5eSKamil Rytarowski   // Reinitialize from scratch threads and register them in process
9293eef2b5eSKamil Rytarowski   while (info.pl_lwpid != 0) {
9303eef2b5eSKamil Rytarowski     NativeThreadNetBSDSP thread_sp = AddThread(info.pl_lwpid);
9313eef2b5eSKamil Rytarowski     error = PtraceWrapper(PT_LWPINFO, GetID(), &info, sizeof(info));
9323eef2b5eSKamil Rytarowski     if (error.Fail()) {
9333eef2b5eSKamil Rytarowski       return error;
9343eef2b5eSKamil Rytarowski     }
9353eef2b5eSKamil Rytarowski   }
9363eef2b5eSKamil Rytarowski 
9373eef2b5eSKamil Rytarowski   return error;
9383eef2b5eSKamil Rytarowski }
939