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 
6782abefa4SPavel Labath llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
6896e600fcSPavel Labath NativeProcessNetBSD::Factory::Launch(ProcessLaunchInfo &launch_info,
6996e600fcSPavel Labath                                      NativeDelegate &native_delegate,
7096e600fcSPavel Labath                                      MainLoop &mainloop) const {
71f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
72f07a9995SKamil Rytarowski 
7396e600fcSPavel Labath   Status status;
7496e600fcSPavel Labath   ::pid_t pid = ProcessLauncherPosixFork()
7596e600fcSPavel Labath                     .LaunchProcess(launch_info, status)
7696e600fcSPavel Labath                     .GetProcessId();
7796e600fcSPavel Labath   LLDB_LOG(log, "pid = {0:x}", pid);
7896e600fcSPavel Labath   if (status.Fail()) {
7996e600fcSPavel Labath     LLDB_LOG(log, "failed to launch process: {0}", status);
8096e600fcSPavel Labath     return status.ToError();
81f07a9995SKamil Rytarowski   }
82f07a9995SKamil Rytarowski 
8396e600fcSPavel Labath   // Wait for the child process to trap on its call to execve.
8496e600fcSPavel Labath   int wstatus;
8596e600fcSPavel Labath   ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0);
8696e600fcSPavel Labath   assert(wpid == pid);
8796e600fcSPavel Labath   (void)wpid;
8896e600fcSPavel Labath   if (!WIFSTOPPED(wstatus)) {
8996e600fcSPavel Labath     LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}",
9096e600fcSPavel Labath              WaitStatus::Decode(wstatus));
9196e600fcSPavel Labath     return llvm::make_error<StringError>("Could not sync with inferior process",
9296e600fcSPavel Labath                                          llvm::inconvertibleErrorCode());
9396e600fcSPavel Labath   }
9496e600fcSPavel Labath   LLDB_LOG(log, "inferior started, now in stopped state");
95f07a9995SKamil Rytarowski 
9696e600fcSPavel Labath   ArchSpec arch;
9796e600fcSPavel Labath   if ((status = ResolveProcessArchitecture(pid, arch)).Fail())
9896e600fcSPavel Labath     return status.ToError();
9996e600fcSPavel Labath 
10096e600fcSPavel Labath   // Set the architecture to the exe architecture.
10196e600fcSPavel Labath   LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid,
10296e600fcSPavel Labath            arch.GetArchitectureName());
10396e600fcSPavel Labath 
10482abefa4SPavel Labath   std::unique_ptr<NativeProcessNetBSD> process_up(new NativeProcessNetBSD(
10596e600fcSPavel Labath       pid, launch_info.GetPTY().ReleaseMasterFileDescriptor(), native_delegate,
10696e600fcSPavel Labath       arch, mainloop));
10796e600fcSPavel Labath 
10882abefa4SPavel Labath   status = process_up->ReinitializeThreads();
10996e600fcSPavel Labath   if (status.Fail())
11096e600fcSPavel Labath     return status.ToError();
11196e600fcSPavel Labath 
112*a5be48b3SPavel Labath   for (const auto &thread : process_up->m_threads)
113*a5be48b3SPavel Labath     static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(SIGSTOP);
11482abefa4SPavel Labath   process_up->SetState(StateType::eStateStopped);
11596e600fcSPavel Labath 
11682abefa4SPavel Labath   return std::move(process_up);
117f07a9995SKamil Rytarowski }
118f07a9995SKamil Rytarowski 
11982abefa4SPavel Labath llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
12082abefa4SPavel Labath NativeProcessNetBSD::Factory::Attach(
1211a3d19ddSKamil Rytarowski     lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
12296e600fcSPavel Labath     MainLoop &mainloop) const {
123f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
124f07a9995SKamil Rytarowski   LLDB_LOG(log, "pid = {0:x}", pid);
125f07a9995SKamil Rytarowski 
126f07a9995SKamil Rytarowski   // Retrieve the architecture for the running process.
12796e600fcSPavel Labath   ArchSpec arch;
12896e600fcSPavel Labath   Status status = ResolveProcessArchitecture(pid, arch);
12996e600fcSPavel Labath   if (!status.Success())
13096e600fcSPavel Labath     return status.ToError();
131f07a9995SKamil Rytarowski 
13282abefa4SPavel Labath   std::unique_ptr<NativeProcessNetBSD> process_up(
13396e600fcSPavel Labath       new NativeProcessNetBSD(pid, -1, native_delegate, arch, mainloop));
134f07a9995SKamil Rytarowski 
13582abefa4SPavel Labath   status = process_up->Attach();
13696e600fcSPavel Labath   if (!status.Success())
13796e600fcSPavel Labath     return status.ToError();
138f07a9995SKamil Rytarowski 
13982abefa4SPavel Labath   return std::move(process_up);
1401a3d19ddSKamil Rytarowski }
1411a3d19ddSKamil Rytarowski 
1421a3d19ddSKamil Rytarowski // -----------------------------------------------------------------------------
1431a3d19ddSKamil Rytarowski // Public Instance Methods
1441a3d19ddSKamil Rytarowski // -----------------------------------------------------------------------------
1451a3d19ddSKamil Rytarowski 
14696e600fcSPavel Labath NativeProcessNetBSD::NativeProcessNetBSD(::pid_t pid, int terminal_fd,
14796e600fcSPavel Labath                                          NativeDelegate &delegate,
14896e600fcSPavel Labath                                          const ArchSpec &arch,
14996e600fcSPavel Labath                                          MainLoop &mainloop)
15096e600fcSPavel Labath     : NativeProcessProtocol(pid, terminal_fd, delegate), m_arch(arch) {
15196e600fcSPavel Labath   if (m_terminal_fd != -1) {
15296e600fcSPavel Labath     Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
15396e600fcSPavel Labath     assert(status.Success());
15496e600fcSPavel Labath   }
15596e600fcSPavel Labath 
15696e600fcSPavel Labath   Status status;
15796e600fcSPavel Labath   m_sigchld_handle = mainloop.RegisterSignal(
15896e600fcSPavel Labath       SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status);
15996e600fcSPavel Labath   assert(m_sigchld_handle && status.Success());
16096e600fcSPavel Labath }
161f07a9995SKamil Rytarowski 
162f07a9995SKamil Rytarowski // Handles all waitpid events from the inferior process.
163f07a9995SKamil Rytarowski void NativeProcessNetBSD::MonitorCallback(lldb::pid_t pid, int signal) {
164f07a9995SKamil Rytarowski   switch (signal) {
165f07a9995SKamil Rytarowski   case SIGTRAP:
166f07a9995SKamil Rytarowski     return MonitorSIGTRAP(pid);
167f07a9995SKamil Rytarowski   case SIGSTOP:
168f07a9995SKamil Rytarowski     return MonitorSIGSTOP(pid);
169f07a9995SKamil Rytarowski   default:
170f07a9995SKamil Rytarowski     return MonitorSignal(pid, signal);
171f07a9995SKamil Rytarowski   }
172f07a9995SKamil Rytarowski }
173f07a9995SKamil Rytarowski 
1743508fc8cSPavel Labath void NativeProcessNetBSD::MonitorExited(lldb::pid_t pid, WaitStatus status) {
175f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
176f07a9995SKamil Rytarowski 
1773508fc8cSPavel Labath   LLDB_LOG(log, "got exit signal({0}) , pid = {1}", status, pid);
178f07a9995SKamil Rytarowski 
179f07a9995SKamil Rytarowski   /* Stop Tracking All Threads attached to Process */
180f07a9995SKamil Rytarowski   m_threads.clear();
181f07a9995SKamil Rytarowski 
1823508fc8cSPavel Labath   SetExitStatus(status, true);
183f07a9995SKamil Rytarowski 
184f07a9995SKamil Rytarowski   // Notify delegate that our process has exited.
185f07a9995SKamil Rytarowski   SetState(StateType::eStateExited, true);
186f07a9995SKamil Rytarowski }
187f07a9995SKamil Rytarowski 
188f07a9995SKamil Rytarowski void NativeProcessNetBSD::MonitorSIGSTOP(lldb::pid_t pid) {
189f07a9995SKamil Rytarowski   ptrace_siginfo_t info;
190f07a9995SKamil Rytarowski 
191f07a9995SKamil Rytarowski   const auto siginfo_err =
192f07a9995SKamil Rytarowski       PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info));
193f07a9995SKamil Rytarowski 
194f07a9995SKamil Rytarowski   // Get details on the signal raised.
195f07a9995SKamil Rytarowski   if (siginfo_err.Success()) {
196f07a9995SKamil Rytarowski     // Handle SIGSTOP from LLGS (LLDB GDB Server)
197f07a9995SKamil Rytarowski     if (info.psi_siginfo.si_code == SI_USER &&
198f07a9995SKamil Rytarowski         info.psi_siginfo.si_pid == ::getpid()) {
199*a5be48b3SPavel Labath       /* Stop Tracking all Threads attached to Process */
200*a5be48b3SPavel Labath       for (const auto &thread : m_threads) {
201*a5be48b3SPavel Labath         static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(
202f07a9995SKamil Rytarowski             SIGSTOP, &info.psi_siginfo);
203f07a9995SKamil Rytarowski       }
204f07a9995SKamil Rytarowski     }
205f07a9995SKamil Rytarowski   }
206f07a9995SKamil Rytarowski }
207f07a9995SKamil Rytarowski 
208f07a9995SKamil Rytarowski void NativeProcessNetBSD::MonitorSIGTRAP(lldb::pid_t pid) {
209f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
210f07a9995SKamil Rytarowski   ptrace_siginfo_t info;
211f07a9995SKamil Rytarowski 
212f07a9995SKamil Rytarowski   const auto siginfo_err =
213f07a9995SKamil Rytarowski       PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info));
214f07a9995SKamil Rytarowski 
215f07a9995SKamil Rytarowski   // Get details on the signal raised.
21636e23ecaSKamil Rytarowski   if (siginfo_err.Fail()) {
21736e23ecaSKamil Rytarowski     return;
21836e23ecaSKamil Rytarowski   }
21936e23ecaSKamil Rytarowski 
220f07a9995SKamil Rytarowski   switch (info.psi_siginfo.si_code) {
221f07a9995SKamil Rytarowski   case TRAP_BRKPT:
222*a5be48b3SPavel Labath     for (const auto &thread : m_threads) {
223*a5be48b3SPavel Labath       static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByBreakpoint();
224*a5be48b3SPavel Labath       FixupBreakpointPCAsNeeded(static_cast<NativeThreadNetBSD &>(*thread));
225f07a9995SKamil Rytarowski     }
226f07a9995SKamil Rytarowski     SetState(StateType::eStateStopped, true);
227f07a9995SKamil Rytarowski     break;
2283eef2b5eSKamil Rytarowski   case TRAP_TRACE:
229*a5be48b3SPavel Labath     for (const auto &thread : m_threads)
230*a5be48b3SPavel Labath       static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByTrace();
2313eef2b5eSKamil Rytarowski     SetState(StateType::eStateStopped, true);
2323eef2b5eSKamil Rytarowski     break;
2333eef2b5eSKamil Rytarowski   case TRAP_EXEC: {
23497206d57SZachary Turner     Status error = ReinitializeThreads();
2353eef2b5eSKamil Rytarowski     if (error.Fail()) {
2363eef2b5eSKamil Rytarowski       SetState(StateType::eStateInvalid);
2373eef2b5eSKamil Rytarowski       return;
2383eef2b5eSKamil Rytarowski     }
2393eef2b5eSKamil Rytarowski 
2403eef2b5eSKamil Rytarowski     // Let our delegate know we have just exec'd.
2413eef2b5eSKamil Rytarowski     NotifyDidExec();
2423eef2b5eSKamil Rytarowski 
243*a5be48b3SPavel Labath     for (const auto &thread : m_threads)
244*a5be48b3SPavel Labath       static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByExec();
2453eef2b5eSKamil Rytarowski     SetState(StateType::eStateStopped, true);
2463eef2b5eSKamil Rytarowski   } break;
24736e23ecaSKamil Rytarowski   case TRAP_DBREG: {
24836e23ecaSKamil Rytarowski     // If a watchpoint was hit, report it
24936e23ecaSKamil Rytarowski     uint32_t wp_index;
250*a5be48b3SPavel Labath     Status error = static_cast<NativeThreadNetBSD &>(*m_threads[info.psi_lwpid])
251*a5be48b3SPavel Labath                        .GetRegisterContext()
252*a5be48b3SPavel Labath                        ->GetWatchpointHitIndex(
253*a5be48b3SPavel Labath                            wp_index, (uintptr_t)info.psi_siginfo.si_addr);
25436e23ecaSKamil Rytarowski     if (error.Fail())
25536e23ecaSKamil Rytarowski       LLDB_LOG(log,
25636e23ecaSKamil Rytarowski                "received error while checking for watchpoint hits, pid = "
25736e23ecaSKamil Rytarowski                "{0}, LWP = {1}, error = {2}",
25836e23ecaSKamil Rytarowski                GetID(), info.psi_lwpid, error);
25936e23ecaSKamil Rytarowski     if (wp_index != LLDB_INVALID_INDEX32) {
260*a5be48b3SPavel Labath       for (const auto &thread : m_threads)
261*a5be48b3SPavel Labath         static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByWatchpoint(
262*a5be48b3SPavel Labath             wp_index);
26336e23ecaSKamil Rytarowski       SetState(StateType::eStateStopped, true);
26436e23ecaSKamil Rytarowski       break;
26536e23ecaSKamil Rytarowski     }
26636e23ecaSKamil Rytarowski 
26736e23ecaSKamil Rytarowski     // If a breakpoint was hit, report it
26836e23ecaSKamil Rytarowski     uint32_t bp_index;
269*a5be48b3SPavel Labath     error = static_cast<NativeThreadNetBSD &>(*m_threads[info.psi_lwpid])
270*a5be48b3SPavel Labath                 .GetRegisterContext()
27136e23ecaSKamil Rytarowski                 ->GetHardwareBreakHitIndex(bp_index,
27236e23ecaSKamil Rytarowski                                            (uintptr_t)info.psi_siginfo.si_addr);
27336e23ecaSKamil Rytarowski     if (error.Fail())
27436e23ecaSKamil Rytarowski       LLDB_LOG(log,
27536e23ecaSKamil Rytarowski                "received error while checking for hardware "
27636e23ecaSKamil Rytarowski                "breakpoint hits, pid = {0}, LWP = {1}, error = {2}",
27736e23ecaSKamil Rytarowski                GetID(), info.psi_lwpid, error);
27836e23ecaSKamil Rytarowski     if (bp_index != LLDB_INVALID_INDEX32) {
279*a5be48b3SPavel Labath       for (const auto &thread : m_threads)
280*a5be48b3SPavel Labath         static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByBreakpoint();
28136e23ecaSKamil Rytarowski       SetState(StateType::eStateStopped, true);
28236e23ecaSKamil Rytarowski       break;
28336e23ecaSKamil Rytarowski     }
28436e23ecaSKamil Rytarowski   } break;
285f07a9995SKamil Rytarowski   }
286f07a9995SKamil Rytarowski }
287f07a9995SKamil Rytarowski 
288f07a9995SKamil Rytarowski void NativeProcessNetBSD::MonitorSignal(lldb::pid_t pid, int signal) {
289f07a9995SKamil Rytarowski   ptrace_siginfo_t info;
290f07a9995SKamil Rytarowski   const auto siginfo_err =
291f07a9995SKamil Rytarowski       PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info));
292f07a9995SKamil Rytarowski 
293*a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
294*a5be48b3SPavel Labath     static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(
295f07a9995SKamil Rytarowski         info.psi_siginfo.si_signo, &info.psi_siginfo);
296f07a9995SKamil Rytarowski   }
297f07a9995SKamil Rytarowski   SetState(StateType::eStateStopped, true);
298f07a9995SKamil Rytarowski }
299f07a9995SKamil Rytarowski 
30097206d57SZachary Turner Status NativeProcessNetBSD::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
301f07a9995SKamil Rytarowski                                           int data, int *result) {
302f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
30397206d57SZachary Turner   Status error;
304f07a9995SKamil Rytarowski   int ret;
305f07a9995SKamil Rytarowski 
306f07a9995SKamil Rytarowski   errno = 0;
307f07a9995SKamil Rytarowski   ret = ptrace(req, static_cast<::pid_t>(pid), addr, data);
308f07a9995SKamil Rytarowski 
309f07a9995SKamil Rytarowski   if (ret == -1)
310f07a9995SKamil Rytarowski     error.SetErrorToErrno();
311f07a9995SKamil Rytarowski 
312f07a9995SKamil Rytarowski   if (result)
313f07a9995SKamil Rytarowski     *result = ret;
314f07a9995SKamil Rytarowski 
315f07a9995SKamil Rytarowski   LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3})={4:x}", req, pid, addr, data, ret);
316f07a9995SKamil Rytarowski 
317f07a9995SKamil Rytarowski   if (error.Fail())
318f07a9995SKamil Rytarowski     LLDB_LOG(log, "ptrace() failed: {0}", error);
319f07a9995SKamil Rytarowski 
320f07a9995SKamil Rytarowski   return error;
321f07a9995SKamil Rytarowski }
322f07a9995SKamil Rytarowski 
32397206d57SZachary Turner Status NativeProcessNetBSD::GetSoftwareBreakpointPCOffset(
324f07a9995SKamil Rytarowski     uint32_t &actual_opcode_size) {
325f07a9995SKamil Rytarowski   // FIXME put this behind a breakpoint protocol class that can be
326f07a9995SKamil Rytarowski   // set per architecture.  Need ARM, MIPS support here.
327f07a9995SKamil Rytarowski   static const uint8_t g_i386_opcode[] = {0xCC};
328f07a9995SKamil Rytarowski   switch (m_arch.GetMachine()) {
329f07a9995SKamil Rytarowski   case llvm::Triple::x86_64:
330f07a9995SKamil Rytarowski     actual_opcode_size = static_cast<uint32_t>(sizeof(g_i386_opcode));
33197206d57SZachary Turner     return Status();
332f07a9995SKamil Rytarowski   default:
333f07a9995SKamil Rytarowski     assert(false && "CPU type not supported!");
33497206d57SZachary Turner     return Status("CPU type not supported");
335f07a9995SKamil Rytarowski   }
336f07a9995SKamil Rytarowski }
337f07a9995SKamil Rytarowski 
33897206d57SZachary Turner Status
33997206d57SZachary Turner NativeProcessNetBSD::FixupBreakpointPCAsNeeded(NativeThreadNetBSD &thread) {
340f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_BREAKPOINTS));
34197206d57SZachary Turner   Status error;
342f07a9995SKamil Rytarowski   // Find out the size of a breakpoint (might depend on where we are in the
343f07a9995SKamil Rytarowski   // code).
344f07a9995SKamil Rytarowski   NativeRegisterContextSP context_sp = thread.GetRegisterContext();
345f07a9995SKamil Rytarowski   if (!context_sp) {
346f07a9995SKamil Rytarowski     error.SetErrorString("cannot get a NativeRegisterContext for the thread");
347f07a9995SKamil Rytarowski     LLDB_LOG(log, "failed: {0}", error);
348f07a9995SKamil Rytarowski     return error;
349f07a9995SKamil Rytarowski   }
350f07a9995SKamil Rytarowski   uint32_t breakpoint_size = 0;
351f07a9995SKamil Rytarowski   error = GetSoftwareBreakpointPCOffset(breakpoint_size);
352f07a9995SKamil Rytarowski   if (error.Fail()) {
353f07a9995SKamil Rytarowski     LLDB_LOG(log, "GetBreakpointSize() failed: {0}", error);
354f07a9995SKamil Rytarowski     return error;
355f07a9995SKamil Rytarowski   } else
356f07a9995SKamil Rytarowski     LLDB_LOG(log, "breakpoint size: {0}", breakpoint_size);
35736e23ecaSKamil Rytarowski   // First try probing for a breakpoint at a software breakpoint location: PC
35836e23ecaSKamil Rytarowski   // - breakpoint size.
359f07a9995SKamil Rytarowski   const lldb::addr_t initial_pc_addr =
360f07a9995SKamil Rytarowski       context_sp->GetPCfromBreakpointLocation();
361f07a9995SKamil Rytarowski   lldb::addr_t breakpoint_addr = initial_pc_addr;
362f07a9995SKamil Rytarowski   if (breakpoint_size > 0) {
363f07a9995SKamil Rytarowski     // Do not allow breakpoint probe to wrap around.
364f07a9995SKamil Rytarowski     if (breakpoint_addr >= breakpoint_size)
365f07a9995SKamil Rytarowski       breakpoint_addr -= breakpoint_size;
366f07a9995SKamil Rytarowski   }
367f07a9995SKamil Rytarowski   // Check if we stopped because of a breakpoint.
368f07a9995SKamil Rytarowski   NativeBreakpointSP breakpoint_sp;
369f07a9995SKamil Rytarowski   error = m_breakpoint_list.GetBreakpoint(breakpoint_addr, breakpoint_sp);
370f07a9995SKamil Rytarowski   if (!error.Success() || !breakpoint_sp) {
371f07a9995SKamil Rytarowski     // We didn't find one at a software probe location.  Nothing to do.
372f07a9995SKamil Rytarowski     LLDB_LOG(log,
373f07a9995SKamil Rytarowski              "pid {0} no lldb breakpoint found at current pc with "
374f07a9995SKamil Rytarowski              "adjustment: {1}",
375f07a9995SKamil Rytarowski              GetID(), breakpoint_addr);
37697206d57SZachary Turner     return Status();
377f07a9995SKamil Rytarowski   }
378f07a9995SKamil Rytarowski   // If the breakpoint is not a software breakpoint, nothing to do.
379f07a9995SKamil Rytarowski   if (!breakpoint_sp->IsSoftwareBreakpoint()) {
380f07a9995SKamil Rytarowski     LLDB_LOG(
381f07a9995SKamil Rytarowski         log,
382f07a9995SKamil Rytarowski         "pid {0} breakpoint found at {1:x}, not software, nothing to adjust",
383f07a9995SKamil Rytarowski         GetID(), breakpoint_addr);
38497206d57SZachary Turner     return Status();
385f07a9995SKamil Rytarowski   }
386f07a9995SKamil Rytarowski   //
387f07a9995SKamil Rytarowski   // We have a software breakpoint and need to adjust the PC.
388f07a9995SKamil Rytarowski   //
389f07a9995SKamil Rytarowski   // Sanity check.
390f07a9995SKamil Rytarowski   if (breakpoint_size == 0) {
391f07a9995SKamil Rytarowski     // Nothing to do!  How did we get here?
392f07a9995SKamil Rytarowski     LLDB_LOG(log,
393f07a9995SKamil Rytarowski              "pid {0} breakpoint found at {1:x}, it is software, but the "
394f07a9995SKamil Rytarowski              "size is zero, nothing to do (unexpected)",
395f07a9995SKamil Rytarowski              GetID(), breakpoint_addr);
39697206d57SZachary Turner     return Status();
397f07a9995SKamil Rytarowski   }
398f07a9995SKamil Rytarowski   //
399f07a9995SKamil Rytarowski   // We have a software breakpoint and need to adjust the PC.
400f07a9995SKamil Rytarowski   //
401f07a9995SKamil Rytarowski   // Sanity check.
402f07a9995SKamil Rytarowski   if (breakpoint_size == 0) {
403f07a9995SKamil Rytarowski     // Nothing to do!  How did we get here?
404f07a9995SKamil Rytarowski     LLDB_LOG(log,
405f07a9995SKamil Rytarowski              "pid {0} breakpoint found at {1:x}, it is software, but the "
406f07a9995SKamil Rytarowski              "size is zero, nothing to do (unexpected)",
407f07a9995SKamil Rytarowski              GetID(), breakpoint_addr);
40897206d57SZachary Turner     return Status();
409f07a9995SKamil Rytarowski   }
410f07a9995SKamil Rytarowski   // Change the program counter.
411f07a9995SKamil Rytarowski   LLDB_LOG(log, "pid {0} tid {1}: changing PC from {2:x} to {3:x}", GetID(),
412f07a9995SKamil Rytarowski            thread.GetID(), initial_pc_addr, breakpoint_addr);
413f07a9995SKamil Rytarowski   error = context_sp->SetPC(breakpoint_addr);
414f07a9995SKamil Rytarowski   if (error.Fail()) {
415f07a9995SKamil Rytarowski     LLDB_LOG(log, "pid {0} tid {1}: failed to set PC: {2}", GetID(),
416f07a9995SKamil Rytarowski              thread.GetID(), error);
417f07a9995SKamil Rytarowski     return error;
418f07a9995SKamil Rytarowski   }
419f07a9995SKamil Rytarowski   return error;
420f07a9995SKamil Rytarowski }
421f07a9995SKamil Rytarowski 
42297206d57SZachary Turner Status NativeProcessNetBSD::Resume(const ResumeActionList &resume_actions) {
423f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
424f07a9995SKamil Rytarowski   LLDB_LOG(log, "pid {0}", GetID());
425f07a9995SKamil Rytarowski 
426*a5be48b3SPavel Labath   const auto &thread = m_threads[0];
427f07a9995SKamil Rytarowski   const ResumeAction *const action =
428*a5be48b3SPavel Labath       resume_actions.GetActionForThread(thread->GetID(), true);
429f07a9995SKamil Rytarowski 
430f07a9995SKamil Rytarowski   if (action == nullptr) {
431f07a9995SKamil Rytarowski     LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
432*a5be48b3SPavel Labath              thread->GetID());
43397206d57SZachary Turner     return Status();
434f07a9995SKamil Rytarowski   }
435f07a9995SKamil Rytarowski 
43697206d57SZachary Turner   Status error;
4373eef2b5eSKamil Rytarowski 
438f07a9995SKamil Rytarowski   switch (action->state) {
439f07a9995SKamil Rytarowski   case eStateRunning: {
440f07a9995SKamil Rytarowski     // Run the thread, possibly feeding it the signal.
4413eef2b5eSKamil Rytarowski     error = NativeProcessNetBSD::PtraceWrapper(PT_CONTINUE, GetID(), (void *)1,
4423eef2b5eSKamil Rytarowski                                                action->signal);
443f07a9995SKamil Rytarowski     if (!error.Success())
444f07a9995SKamil Rytarowski       return error;
445*a5be48b3SPavel Labath     for (const auto &thread : m_threads)
446*a5be48b3SPavel Labath       static_cast<NativeThreadNetBSD &>(*thread).SetRunning();
447f07a9995SKamil Rytarowski     SetState(eStateRunning, true);
448f07a9995SKamil Rytarowski     break;
449f07a9995SKamil Rytarowski   }
450f07a9995SKamil Rytarowski   case eStateStepping:
4513eef2b5eSKamil Rytarowski     // Run the thread, possibly feeding it the signal.
4523eef2b5eSKamil Rytarowski     error = NativeProcessNetBSD::PtraceWrapper(PT_STEP, GetID(), (void *)1,
4533eef2b5eSKamil Rytarowski                                                action->signal);
4543eef2b5eSKamil Rytarowski     if (!error.Success())
4553eef2b5eSKamil Rytarowski       return error;
456*a5be48b3SPavel Labath     for (const auto &thread : m_threads)
457*a5be48b3SPavel Labath       static_cast<NativeThreadNetBSD &>(*thread).SetStepping();
4583eef2b5eSKamil Rytarowski     SetState(eStateStepping, true);
459f07a9995SKamil Rytarowski     break;
460f07a9995SKamil Rytarowski 
461f07a9995SKamil Rytarowski   case eStateSuspended:
462f07a9995SKamil Rytarowski   case eStateStopped:
463f07a9995SKamil Rytarowski     llvm_unreachable("Unexpected state");
464f07a9995SKamil Rytarowski 
465f07a9995SKamil Rytarowski   default:
46697206d57SZachary Turner     return Status("NativeProcessNetBSD::%s (): unexpected state %s specified "
467f07a9995SKamil Rytarowski                   "for pid %" PRIu64 ", tid %" PRIu64,
468f07a9995SKamil Rytarowski                   __FUNCTION__, StateAsCString(action->state), GetID(),
469*a5be48b3SPavel Labath                   thread->GetID());
470f07a9995SKamil Rytarowski   }
471f07a9995SKamil Rytarowski 
47297206d57SZachary Turner   return Status();
473f07a9995SKamil Rytarowski }
474f07a9995SKamil Rytarowski 
47597206d57SZachary Turner Status NativeProcessNetBSD::Halt() {
47697206d57SZachary Turner   Status error;
477f07a9995SKamil Rytarowski 
478f07a9995SKamil Rytarowski   if (kill(GetID(), SIGSTOP) != 0)
479f07a9995SKamil Rytarowski     error.SetErrorToErrno();
480f07a9995SKamil Rytarowski 
481f07a9995SKamil Rytarowski   return error;
482f07a9995SKamil Rytarowski }
483f07a9995SKamil Rytarowski 
48497206d57SZachary Turner Status NativeProcessNetBSD::Detach() {
48597206d57SZachary Turner   Status error;
486f07a9995SKamil Rytarowski 
487f07a9995SKamil Rytarowski   // Stop monitoring the inferior.
488f07a9995SKamil Rytarowski   m_sigchld_handle.reset();
489f07a9995SKamil Rytarowski 
490f07a9995SKamil Rytarowski   // Tell ptrace to detach from the process.
491f07a9995SKamil Rytarowski   if (GetID() == LLDB_INVALID_PROCESS_ID)
492f07a9995SKamil Rytarowski     return error;
493f07a9995SKamil Rytarowski 
494f07a9995SKamil Rytarowski   return PtraceWrapper(PT_DETACH, GetID());
495f07a9995SKamil Rytarowski }
496f07a9995SKamil Rytarowski 
49797206d57SZachary Turner Status NativeProcessNetBSD::Signal(int signo) {
49897206d57SZachary Turner   Status error;
499f07a9995SKamil Rytarowski 
500f07a9995SKamil Rytarowski   if (kill(GetID(), signo))
501f07a9995SKamil Rytarowski     error.SetErrorToErrno();
502f07a9995SKamil Rytarowski 
503f07a9995SKamil Rytarowski   return error;
504f07a9995SKamil Rytarowski }
505f07a9995SKamil Rytarowski 
50697206d57SZachary Turner Status NativeProcessNetBSD::Kill() {
507f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
508f07a9995SKamil Rytarowski   LLDB_LOG(log, "pid {0}", GetID());
509f07a9995SKamil Rytarowski 
51097206d57SZachary Turner   Status error;
511f07a9995SKamil Rytarowski 
512f07a9995SKamil Rytarowski   switch (m_state) {
513f07a9995SKamil Rytarowski   case StateType::eStateInvalid:
514f07a9995SKamil Rytarowski   case StateType::eStateExited:
515f07a9995SKamil Rytarowski   case StateType::eStateCrashed:
516f07a9995SKamil Rytarowski   case StateType::eStateDetached:
517f07a9995SKamil Rytarowski   case StateType::eStateUnloaded:
518f07a9995SKamil Rytarowski     // Nothing to do - the process is already dead.
519f07a9995SKamil Rytarowski     LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
520f07a9995SKamil Rytarowski              StateAsCString(m_state));
521f07a9995SKamil Rytarowski     return error;
522f07a9995SKamil Rytarowski 
523f07a9995SKamil Rytarowski   case StateType::eStateConnected:
524f07a9995SKamil Rytarowski   case StateType::eStateAttaching:
525f07a9995SKamil Rytarowski   case StateType::eStateLaunching:
526f07a9995SKamil Rytarowski   case StateType::eStateStopped:
527f07a9995SKamil Rytarowski   case StateType::eStateRunning:
528f07a9995SKamil Rytarowski   case StateType::eStateStepping:
529f07a9995SKamil Rytarowski   case StateType::eStateSuspended:
530f07a9995SKamil Rytarowski     // We can try to kill a process in these states.
531f07a9995SKamil Rytarowski     break;
532f07a9995SKamil Rytarowski   }
533f07a9995SKamil Rytarowski 
534f07a9995SKamil Rytarowski   if (kill(GetID(), SIGKILL) != 0) {
535f07a9995SKamil Rytarowski     error.SetErrorToErrno();
536f07a9995SKamil Rytarowski     return error;
537f07a9995SKamil Rytarowski   }
538f07a9995SKamil Rytarowski 
539f07a9995SKamil Rytarowski   return error;
540f07a9995SKamil Rytarowski }
541f07a9995SKamil Rytarowski 
54297206d57SZachary Turner Status NativeProcessNetBSD::GetMemoryRegionInfo(lldb::addr_t load_addr,
543f07a9995SKamil Rytarowski                                                 MemoryRegionInfo &range_info) {
544f07a9995SKamil Rytarowski 
545f07a9995SKamil Rytarowski   if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
546f07a9995SKamil Rytarowski     // We're done.
54797206d57SZachary Turner     return Status("unsupported");
548f07a9995SKamil Rytarowski   }
549f07a9995SKamil Rytarowski 
55097206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
551f07a9995SKamil Rytarowski   if (error.Fail()) {
552f07a9995SKamil Rytarowski     return error;
553f07a9995SKamil Rytarowski   }
554f07a9995SKamil Rytarowski 
555f07a9995SKamil Rytarowski   lldb::addr_t prev_base_address = 0;
556f07a9995SKamil Rytarowski   // FIXME start by finding the last region that is <= target address using
557f07a9995SKamil Rytarowski   // binary search.  Data is sorted.
558f07a9995SKamil Rytarowski   // There can be a ton of regions on pthreads apps with lots of threads.
559f07a9995SKamil Rytarowski   for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
560f07a9995SKamil Rytarowski        ++it) {
561f07a9995SKamil Rytarowski     MemoryRegionInfo &proc_entry_info = it->first;
562f07a9995SKamil Rytarowski     // Sanity check assumption that memory map entries are ascending.
563f07a9995SKamil Rytarowski     assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
564f07a9995SKamil Rytarowski            "descending memory map entries detected, unexpected");
565f07a9995SKamil Rytarowski     prev_base_address = proc_entry_info.GetRange().GetRangeBase();
566f07a9995SKamil Rytarowski     UNUSED_IF_ASSERT_DISABLED(prev_base_address);
56736e23ecaSKamil Rytarowski     // If the target address comes before this entry, indicate distance to
56836e23ecaSKamil Rytarowski     // next region.
569f07a9995SKamil Rytarowski     if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
570f07a9995SKamil Rytarowski       range_info.GetRange().SetRangeBase(load_addr);
571f07a9995SKamil Rytarowski       range_info.GetRange().SetByteSize(
572f07a9995SKamil Rytarowski           proc_entry_info.GetRange().GetRangeBase() - load_addr);
573f07a9995SKamil Rytarowski       range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
574f07a9995SKamil Rytarowski       range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
575f07a9995SKamil Rytarowski       range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
576f07a9995SKamil Rytarowski       range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
577f07a9995SKamil Rytarowski       return error;
578f07a9995SKamil Rytarowski     } else if (proc_entry_info.GetRange().Contains(load_addr)) {
579f07a9995SKamil Rytarowski       // The target address is within the memory region we're processing here.
580f07a9995SKamil Rytarowski       range_info = proc_entry_info;
581f07a9995SKamil Rytarowski       return error;
582f07a9995SKamil Rytarowski     }
583f07a9995SKamil Rytarowski     // The target memory address comes somewhere after the region we just
584f07a9995SKamil Rytarowski     // parsed.
585f07a9995SKamil Rytarowski   }
586f07a9995SKamil Rytarowski   // If we made it here, we didn't find an entry that contained the given
587f07a9995SKamil Rytarowski   // address. Return the
58836e23ecaSKamil Rytarowski   // load_addr as start and the amount of bytes betwwen load address and the
58936e23ecaSKamil Rytarowski   // end of the memory as size.
590f07a9995SKamil Rytarowski   range_info.GetRange().SetRangeBase(load_addr);
591f07a9995SKamil Rytarowski   range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
592f07a9995SKamil Rytarowski   range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
593f07a9995SKamil Rytarowski   range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
594f07a9995SKamil Rytarowski   range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
595f07a9995SKamil Rytarowski   range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
596f07a9995SKamil Rytarowski   return error;
597f07a9995SKamil Rytarowski }
598f07a9995SKamil Rytarowski 
59997206d57SZachary Turner Status NativeProcessNetBSD::PopulateMemoryRegionCache() {
600f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
601f07a9995SKamil Rytarowski   // If our cache is empty, pull the latest.  There should always be at least
602f07a9995SKamil Rytarowski   // one memory region if memory region handling is supported.
603f07a9995SKamil Rytarowski   if (!m_mem_region_cache.empty()) {
604f07a9995SKamil Rytarowski     LLDB_LOG(log, "reusing {0} cached memory region entries",
605f07a9995SKamil Rytarowski              m_mem_region_cache.size());
60697206d57SZachary Turner     return Status();
607f07a9995SKamil Rytarowski   }
608f07a9995SKamil Rytarowski 
609f07a9995SKamil Rytarowski   struct kinfo_vmentry *vm;
610f07a9995SKamil Rytarowski   size_t count, i;
611f07a9995SKamil Rytarowski   vm = kinfo_getvmmap(GetID(), &count);
612f07a9995SKamil Rytarowski   if (vm == NULL) {
613f07a9995SKamil Rytarowski     m_supports_mem_region = LazyBool::eLazyBoolNo;
61497206d57SZachary Turner     Status error;
615f07a9995SKamil Rytarowski     error.SetErrorString("not supported");
616f07a9995SKamil Rytarowski     return error;
617f07a9995SKamil Rytarowski   }
618f07a9995SKamil Rytarowski   for (i = 0; i < count; i++) {
619f07a9995SKamil Rytarowski     MemoryRegionInfo info;
620f07a9995SKamil Rytarowski     info.Clear();
621f07a9995SKamil Rytarowski     info.GetRange().SetRangeBase(vm[i].kve_start);
622f07a9995SKamil Rytarowski     info.GetRange().SetRangeEnd(vm[i].kve_end);
623f07a9995SKamil Rytarowski     info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
624f07a9995SKamil Rytarowski 
625f07a9995SKamil Rytarowski     if (vm[i].kve_protection & VM_PROT_READ)
626f07a9995SKamil Rytarowski       info.SetReadable(MemoryRegionInfo::OptionalBool::eYes);
627f07a9995SKamil Rytarowski     else
628f07a9995SKamil Rytarowski       info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
629f07a9995SKamil Rytarowski 
630f07a9995SKamil Rytarowski     if (vm[i].kve_protection & VM_PROT_WRITE)
631f07a9995SKamil Rytarowski       info.SetWritable(MemoryRegionInfo::OptionalBool::eYes);
632f07a9995SKamil Rytarowski     else
633f07a9995SKamil Rytarowski       info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
634f07a9995SKamil Rytarowski 
635f07a9995SKamil Rytarowski     if (vm[i].kve_protection & VM_PROT_EXECUTE)
636f07a9995SKamil Rytarowski       info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes);
637f07a9995SKamil Rytarowski     else
638f07a9995SKamil Rytarowski       info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
639f07a9995SKamil Rytarowski 
640f07a9995SKamil Rytarowski     if (vm[i].kve_path[0])
641f07a9995SKamil Rytarowski       info.SetName(vm[i].kve_path);
642f07a9995SKamil Rytarowski 
643f07a9995SKamil Rytarowski     m_mem_region_cache.emplace_back(
644f07a9995SKamil Rytarowski         info, FileSpec(info.GetName().GetCString(), true));
645f07a9995SKamil Rytarowski   }
646f07a9995SKamil Rytarowski   free(vm);
647f07a9995SKamil Rytarowski 
648f07a9995SKamil Rytarowski   if (m_mem_region_cache.empty()) {
649f07a9995SKamil Rytarowski     // No entries after attempting to read them.  This shouldn't happen.
650f07a9995SKamil Rytarowski     // Assume we don't support map entries.
651f07a9995SKamil Rytarowski     LLDB_LOG(log, "failed to find any vmmap entries, assuming no support "
652f07a9995SKamil Rytarowski                   "for memory region metadata retrieval");
653f07a9995SKamil Rytarowski     m_supports_mem_region = LazyBool::eLazyBoolNo;
65497206d57SZachary Turner     Status error;
655f07a9995SKamil Rytarowski     error.SetErrorString("not supported");
656f07a9995SKamil Rytarowski     return error;
657f07a9995SKamil Rytarowski   }
658f07a9995SKamil Rytarowski   LLDB_LOG(log, "read {0} memory region entries from process {1}",
659f07a9995SKamil Rytarowski            m_mem_region_cache.size(), GetID());
660f07a9995SKamil Rytarowski   // We support memory retrieval, remember that.
661f07a9995SKamil Rytarowski   m_supports_mem_region = LazyBool::eLazyBoolYes;
66297206d57SZachary Turner   return Status();
663f07a9995SKamil Rytarowski }
664f07a9995SKamil Rytarowski 
66597206d57SZachary Turner Status NativeProcessNetBSD::AllocateMemory(size_t size, uint32_t permissions,
666f07a9995SKamil Rytarowski                                            lldb::addr_t &addr) {
66797206d57SZachary Turner   return Status("Unimplemented");
668f07a9995SKamil Rytarowski }
669f07a9995SKamil Rytarowski 
67097206d57SZachary Turner Status NativeProcessNetBSD::DeallocateMemory(lldb::addr_t addr) {
67197206d57SZachary Turner   return Status("Unimplemented");
672f07a9995SKamil Rytarowski }
673f07a9995SKamil Rytarowski 
674f07a9995SKamil Rytarowski lldb::addr_t NativeProcessNetBSD::GetSharedLibraryInfoAddress() {
675f07a9995SKamil Rytarowski   // punt on this for now
676f07a9995SKamil Rytarowski   return LLDB_INVALID_ADDRESS;
677f07a9995SKamil Rytarowski }
678f07a9995SKamil Rytarowski 
679f07a9995SKamil Rytarowski size_t NativeProcessNetBSD::UpdateThreads() { return m_threads.size(); }
680f07a9995SKamil Rytarowski 
681f07a9995SKamil Rytarowski bool NativeProcessNetBSD::GetArchitecture(ArchSpec &arch) const {
682f07a9995SKamil Rytarowski   arch = m_arch;
683f07a9995SKamil Rytarowski   return true;
684f07a9995SKamil Rytarowski }
685f07a9995SKamil Rytarowski 
68697206d57SZachary Turner Status NativeProcessNetBSD::SetBreakpoint(lldb::addr_t addr, uint32_t size,
687f07a9995SKamil Rytarowski                                           bool hardware) {
688f07a9995SKamil Rytarowski   if (hardware)
68997206d57SZachary Turner     return Status("NativeProcessNetBSD does not support hardware breakpoints");
690f07a9995SKamil Rytarowski   else
691f07a9995SKamil Rytarowski     return SetSoftwareBreakpoint(addr, size);
692f07a9995SKamil Rytarowski }
693f07a9995SKamil Rytarowski 
69497206d57SZachary Turner Status NativeProcessNetBSD::GetSoftwareBreakpointTrapOpcode(
695f07a9995SKamil Rytarowski     size_t trap_opcode_size_hint, size_t &actual_opcode_size,
696f07a9995SKamil Rytarowski     const uint8_t *&trap_opcode_bytes) {
697f07a9995SKamil Rytarowski   static const uint8_t g_i386_opcode[] = {0xCC};
698f07a9995SKamil Rytarowski 
699f07a9995SKamil Rytarowski   switch (m_arch.GetMachine()) {
700f07a9995SKamil Rytarowski   case llvm::Triple::x86:
701f07a9995SKamil Rytarowski   case llvm::Triple::x86_64:
702f07a9995SKamil Rytarowski     trap_opcode_bytes = g_i386_opcode;
703f07a9995SKamil Rytarowski     actual_opcode_size = sizeof(g_i386_opcode);
70497206d57SZachary Turner     return Status();
705f07a9995SKamil Rytarowski   default:
706f07a9995SKamil Rytarowski     assert(false && "CPU type not supported!");
70797206d57SZachary Turner     return Status("CPU type not supported");
708f07a9995SKamil Rytarowski   }
709f07a9995SKamil Rytarowski }
710f07a9995SKamil Rytarowski 
71197206d57SZachary Turner Status NativeProcessNetBSD::GetLoadedModuleFileSpec(const char *module_path,
712f07a9995SKamil Rytarowski                                                     FileSpec &file_spec) {
71397206d57SZachary Turner   return Status("Unimplemented");
714f07a9995SKamil Rytarowski }
715f07a9995SKamil Rytarowski 
71697206d57SZachary Turner Status NativeProcessNetBSD::GetFileLoadAddress(const llvm::StringRef &file_name,
717f07a9995SKamil Rytarowski                                                lldb::addr_t &load_addr) {
718f07a9995SKamil Rytarowski   load_addr = LLDB_INVALID_ADDRESS;
71997206d57SZachary Turner   return Status();
720f07a9995SKamil Rytarowski }
721f07a9995SKamil Rytarowski 
722f07a9995SKamil Rytarowski void NativeProcessNetBSD::SigchldHandler() {
723f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
724f07a9995SKamil Rytarowski   // Process all pending waitpid notifications.
725f07a9995SKamil Rytarowski   int status;
726c1a6b128SPavel Labath   ::pid_t wait_pid =
727c1a6b128SPavel Labath       llvm::sys::RetryAfterSignal(-1, waitpid, GetID(), &status, WALLSIG | WNOHANG);
728f07a9995SKamil Rytarowski 
729f07a9995SKamil Rytarowski   if (wait_pid == 0)
730f07a9995SKamil Rytarowski     return; // We are done.
731f07a9995SKamil Rytarowski 
732f07a9995SKamil Rytarowski   if (wait_pid == -1) {
73397206d57SZachary Turner     Status error(errno, eErrorTypePOSIX);
734f07a9995SKamil Rytarowski     LLDB_LOG(log, "waitpid ({0}, &status, _) failed: {1}", GetID(), error);
735f07a9995SKamil Rytarowski   }
736f07a9995SKamil Rytarowski 
7373508fc8cSPavel Labath   WaitStatus wait_status = WaitStatus::Decode(status);
7383508fc8cSPavel Labath   bool exited = wait_status.type == WaitStatus::Exit ||
7393508fc8cSPavel Labath                 (wait_status.type == WaitStatus::Signal &&
7403508fc8cSPavel Labath                  wait_pid == static_cast<::pid_t>(GetID()));
741f07a9995SKamil Rytarowski 
742f07a9995SKamil Rytarowski   LLDB_LOG(log,
7433508fc8cSPavel Labath            "waitpid ({0}, &status, _) => pid = {1}, status = {2}, exited = {3}",
7443508fc8cSPavel Labath            GetID(), wait_pid, status, exited);
745f07a9995SKamil Rytarowski 
746f07a9995SKamil Rytarowski   if (exited)
7473508fc8cSPavel Labath     MonitorExited(wait_pid, wait_status);
7483508fc8cSPavel Labath   else {
7494bb74415SKamil Rytarowski     assert(wait_status.type == WaitStatus::Stop);
7503508fc8cSPavel Labath     MonitorCallback(wait_pid, wait_status.status);
7513508fc8cSPavel Labath   }
752f07a9995SKamil Rytarowski }
753f07a9995SKamil Rytarowski 
754269eec03SKamil Rytarowski bool NativeProcessNetBSD::HasThreadNoLock(lldb::tid_t thread_id) {
755*a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
756*a5be48b3SPavel Labath     assert(thread && "thread list should not contain NULL threads");
757*a5be48b3SPavel Labath     if (thread->GetID() == thread_id) {
758269eec03SKamil Rytarowski       // We have this thread.
759269eec03SKamil Rytarowski       return true;
760269eec03SKamil Rytarowski     }
761269eec03SKamil Rytarowski   }
762269eec03SKamil Rytarowski 
763269eec03SKamil Rytarowski   // We don't have this thread.
764269eec03SKamil Rytarowski   return false;
765269eec03SKamil Rytarowski }
766269eec03SKamil Rytarowski 
767*a5be48b3SPavel Labath NativeThreadNetBSD &NativeProcessNetBSD::AddThread(lldb::tid_t thread_id) {
768f07a9995SKamil Rytarowski 
769f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
770f07a9995SKamil Rytarowski   LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
771f07a9995SKamil Rytarowski 
772f07a9995SKamil Rytarowski   assert(!HasThreadNoLock(thread_id) &&
773f07a9995SKamil Rytarowski          "attempted to add a thread by id that already exists");
774f07a9995SKamil Rytarowski 
775f07a9995SKamil Rytarowski   // If this is the first thread, save it as the current thread
776f07a9995SKamil Rytarowski   if (m_threads.empty())
777f07a9995SKamil Rytarowski     SetCurrentThreadID(thread_id);
778f07a9995SKamil Rytarowski 
779*a5be48b3SPavel Labath   m_threads.push_back(llvm::make_unique<NativeThreadNetBSD>(*this, thread_id));
780*a5be48b3SPavel Labath   return static_cast<NativeThreadNetBSD &>(*m_threads.back());
781f07a9995SKamil Rytarowski }
782f07a9995SKamil Rytarowski 
78396e600fcSPavel Labath Status NativeProcessNetBSD::Attach() {
784f07a9995SKamil Rytarowski   // Attach to the requested process.
785f07a9995SKamil Rytarowski   // An attach will cause the thread to stop with a SIGSTOP.
78696e600fcSPavel Labath   Status status = PtraceWrapper(PT_ATTACH, m_pid);
78796e600fcSPavel Labath   if (status.Fail())
78896e600fcSPavel Labath     return status;
789f07a9995SKamil Rytarowski 
79096e600fcSPavel Labath   int wstatus;
791f07a9995SKamil Rytarowski   // Need to use WALLSIG otherwise we receive an error with errno=ECHLD
792f07a9995SKamil Rytarowski   // At this point we should have a thread stopped if waitpid succeeds.
79396e600fcSPavel Labath   if ((wstatus = waitpid(m_pid, NULL, WALLSIG)) < 0)
79496e600fcSPavel Labath     return Status(errno, eErrorTypePOSIX);
795f07a9995SKamil Rytarowski 
796f07a9995SKamil Rytarowski   /* Initialize threads */
79796e600fcSPavel Labath   status = ReinitializeThreads();
79896e600fcSPavel Labath   if (status.Fail())
79996e600fcSPavel Labath     return status;
800f07a9995SKamil Rytarowski 
801*a5be48b3SPavel Labath   for (const auto &thread : m_threads)
802*a5be48b3SPavel Labath     static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(SIGSTOP);
80336e23ecaSKamil Rytarowski 
804f07a9995SKamil Rytarowski   // Let our process instance know the thread has stopped.
805f07a9995SKamil Rytarowski   SetState(StateType::eStateStopped);
80696e600fcSPavel Labath   return Status();
807f07a9995SKamil Rytarowski }
808f07a9995SKamil Rytarowski 
80997206d57SZachary Turner Status NativeProcessNetBSD::ReadMemory(lldb::addr_t addr, void *buf,
81097206d57SZachary Turner                                        size_t size, size_t &bytes_read) {
811f07a9995SKamil Rytarowski   unsigned char *dst = static_cast<unsigned char *>(buf);
812f07a9995SKamil Rytarowski   struct ptrace_io_desc io;
813f07a9995SKamil Rytarowski 
814f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
815f07a9995SKamil Rytarowski   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
816f07a9995SKamil Rytarowski 
817f07a9995SKamil Rytarowski   bytes_read = 0;
818f07a9995SKamil Rytarowski   io.piod_op = PIOD_READ_D;
819f07a9995SKamil Rytarowski   io.piod_len = size;
820f07a9995SKamil Rytarowski 
821f07a9995SKamil Rytarowski   do {
822f07a9995SKamil Rytarowski     io.piod_offs = (void *)(addr + bytes_read);
823f07a9995SKamil Rytarowski     io.piod_addr = dst + bytes_read;
824f07a9995SKamil Rytarowski 
82597206d57SZachary Turner     Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
826f07a9995SKamil Rytarowski     if (error.Fail())
827f07a9995SKamil Rytarowski       return error;
828f07a9995SKamil Rytarowski 
829f07a9995SKamil Rytarowski     bytes_read = io.piod_len;
830f07a9995SKamil Rytarowski     io.piod_len = size - bytes_read;
831f07a9995SKamil Rytarowski   } while (bytes_read < size);
832f07a9995SKamil Rytarowski 
83397206d57SZachary Turner   return Status();
834f07a9995SKamil Rytarowski }
835f07a9995SKamil Rytarowski 
83697206d57SZachary Turner Status NativeProcessNetBSD::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf,
837f07a9995SKamil Rytarowski                                                   size_t size,
838f07a9995SKamil Rytarowski                                                   size_t &bytes_read) {
83997206d57SZachary Turner   Status error = ReadMemory(addr, buf, size, bytes_read);
840f07a9995SKamil Rytarowski   if (error.Fail())
841f07a9995SKamil Rytarowski     return error;
842f07a9995SKamil Rytarowski   return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
843f07a9995SKamil Rytarowski }
844f07a9995SKamil Rytarowski 
84597206d57SZachary Turner Status NativeProcessNetBSD::WriteMemory(lldb::addr_t addr, const void *buf,
846f07a9995SKamil Rytarowski                                         size_t size, size_t &bytes_written) {
847f07a9995SKamil Rytarowski   const unsigned char *src = static_cast<const unsigned char *>(buf);
84897206d57SZachary Turner   Status error;
849f07a9995SKamil Rytarowski   struct ptrace_io_desc io;
850f07a9995SKamil Rytarowski 
851f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
852f07a9995SKamil Rytarowski   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
853f07a9995SKamil Rytarowski 
854f07a9995SKamil Rytarowski   bytes_written = 0;
855f07a9995SKamil Rytarowski   io.piod_op = PIOD_WRITE_D;
856f07a9995SKamil Rytarowski   io.piod_len = size;
857f07a9995SKamil Rytarowski 
858f07a9995SKamil Rytarowski   do {
859269eec03SKamil Rytarowski     io.piod_addr = const_cast<void *>(static_cast<const void *>(src + bytes_written));
860f07a9995SKamil Rytarowski     io.piod_offs = (void *)(addr + bytes_written);
861f07a9995SKamil Rytarowski 
86297206d57SZachary Turner     Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
863f07a9995SKamil Rytarowski     if (error.Fail())
864f07a9995SKamil Rytarowski       return error;
865f07a9995SKamil Rytarowski 
866f07a9995SKamil Rytarowski     bytes_written = io.piod_len;
867f07a9995SKamil Rytarowski     io.piod_len = size - bytes_written;
868f07a9995SKamil Rytarowski   } while (bytes_written < size);
869f07a9995SKamil Rytarowski 
870f07a9995SKamil Rytarowski   return error;
871f07a9995SKamil Rytarowski }
872f07a9995SKamil Rytarowski 
873f07a9995SKamil Rytarowski llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
874f07a9995SKamil Rytarowski NativeProcessNetBSD::GetAuxvData() const {
875f07a9995SKamil Rytarowski   /*
876f07a9995SKamil Rytarowski    * ELF_AUX_ENTRIES is currently restricted to kernel
877f07a9995SKamil Rytarowski    * (<sys/exec_elf.h> r. 1.155 specifies 15)
878f07a9995SKamil Rytarowski    *
879f07a9995SKamil Rytarowski    * ptrace(2) returns the whole AUXV including extra fiels after AT_NULL this
880f07a9995SKamil Rytarowski    * information isn't needed.
881f07a9995SKamil Rytarowski    */
882f07a9995SKamil Rytarowski   size_t auxv_size = 100 * sizeof(AuxInfo);
883f07a9995SKamil Rytarowski 
884f07a9995SKamil Rytarowski   ErrorOr<std::unique_ptr<MemoryBuffer>> buf =
885f07a9995SKamil Rytarowski       llvm::MemoryBuffer::getNewMemBuffer(auxv_size);
886f07a9995SKamil Rytarowski 
887269eec03SKamil Rytarowski   struct ptrace_io_desc io;
888269eec03SKamil Rytarowski   io.piod_op = PIOD_READ_AUXV;
889269eec03SKamil Rytarowski   io.piod_offs = 0;
890269eec03SKamil Rytarowski   io.piod_addr = const_cast<void *>(static_cast<const void *>(buf.get()->getBufferStart()));
891269eec03SKamil Rytarowski   io.piod_len = auxv_size;
892f07a9995SKamil Rytarowski 
89397206d57SZachary Turner   Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
894f07a9995SKamil Rytarowski 
895f07a9995SKamil Rytarowski   if (error.Fail())
896f07a9995SKamil Rytarowski     return std::error_code(error.GetError(), std::generic_category());
897f07a9995SKamil Rytarowski 
898f07a9995SKamil Rytarowski   if (io.piod_len < 1)
899f07a9995SKamil Rytarowski     return std::error_code(ECANCELED, std::generic_category());
900f07a9995SKamil Rytarowski 
901f07a9995SKamil Rytarowski   return buf;
902f07a9995SKamil Rytarowski }
9033eef2b5eSKamil Rytarowski 
90497206d57SZachary Turner Status NativeProcessNetBSD::ReinitializeThreads() {
9053eef2b5eSKamil Rytarowski   // Clear old threads
9063eef2b5eSKamil Rytarowski   m_threads.clear();
9073eef2b5eSKamil Rytarowski 
9083eef2b5eSKamil Rytarowski   // Initialize new thread
9093eef2b5eSKamil Rytarowski   struct ptrace_lwpinfo info = {};
91097206d57SZachary Turner   Status error = PtraceWrapper(PT_LWPINFO, GetID(), &info, sizeof(info));
9113eef2b5eSKamil Rytarowski   if (error.Fail()) {
9123eef2b5eSKamil Rytarowski     return error;
9133eef2b5eSKamil Rytarowski   }
9143eef2b5eSKamil Rytarowski   // Reinitialize from scratch threads and register them in process
9153eef2b5eSKamil Rytarowski   while (info.pl_lwpid != 0) {
916*a5be48b3SPavel Labath     AddThread(info.pl_lwpid);
9173eef2b5eSKamil Rytarowski     error = PtraceWrapper(PT_LWPINFO, GetID(), &info, sizeof(info));
9183eef2b5eSKamil Rytarowski     if (error.Fail()) {
9193eef2b5eSKamil Rytarowski       return error;
9203eef2b5eSKamil Rytarowski     }
9213eef2b5eSKamil Rytarowski   }
9223eef2b5eSKamil Rytarowski 
9233eef2b5eSKamil Rytarowski   return error;
9243eef2b5eSKamil Rytarowski }
925