11a3d19ddSKamil Rytarowski //===-- NativeProcessNetBSD.cpp ------------------------------- -*- C++ -*-===//
21a3d19ddSKamil Rytarowski //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
61a3d19ddSKamil Rytarowski //
71a3d19ddSKamil Rytarowski //===----------------------------------------------------------------------===//
81a3d19ddSKamil Rytarowski 
91a3d19ddSKamil Rytarowski #include "NativeProcessNetBSD.h"
101a3d19ddSKamil Rytarowski 
111a3d19ddSKamil Rytarowski 
121a3d19ddSKamil Rytarowski 
131a3d19ddSKamil Rytarowski #include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
14f07a9995SKamil Rytarowski #include "lldb/Host/HostProcess.h"
15f07a9995SKamil Rytarowski #include "lldb/Host/common/NativeRegisterContext.h"
16f07a9995SKamil Rytarowski #include "lldb/Host/posix/ProcessLauncherPosixFork.h"
17f07a9995SKamil Rytarowski #include "lldb/Target/Process.h"
18d821c997SPavel Labath #include "lldb/Utility/State.h"
19c1a6b128SPavel Labath #include "llvm/Support/Errno.h"
201a3d19ddSKamil Rytarowski 
211a3d19ddSKamil Rytarowski // System includes - They have to be included after framework includes because
2205097246SAdrian Prantl // they define some macros which collide with variable names in other modules
23f07a9995SKamil Rytarowski // clang-format off
24f07a9995SKamil Rytarowski #include <sys/types.h>
25f07a9995SKamil Rytarowski #include <sys/ptrace.h>
26f07a9995SKamil Rytarowski #include <sys/sysctl.h>
27f07a9995SKamil Rytarowski #include <sys/wait.h>
28f07a9995SKamil Rytarowski #include <uvm/uvm_prot.h>
29f07a9995SKamil Rytarowski #include <elf.h>
30f07a9995SKamil Rytarowski #include <util.h>
31f07a9995SKamil Rytarowski // clang-format on
321a3d19ddSKamil Rytarowski 
331a3d19ddSKamil Rytarowski using namespace lldb;
341a3d19ddSKamil Rytarowski using namespace lldb_private;
351a3d19ddSKamil Rytarowski using namespace lldb_private::process_netbsd;
361a3d19ddSKamil Rytarowski using namespace llvm;
371a3d19ddSKamil Rytarowski 
38f07a9995SKamil Rytarowski // Simple helper function to ensure flags are enabled on the given file
39f07a9995SKamil Rytarowski // descriptor.
4097206d57SZachary Turner static Status EnsureFDFlags(int fd, int flags) {
4197206d57SZachary Turner   Status error;
42f07a9995SKamil Rytarowski 
43f07a9995SKamil Rytarowski   int status = fcntl(fd, F_GETFL);
44f07a9995SKamil Rytarowski   if (status == -1) {
45f07a9995SKamil Rytarowski     error.SetErrorToErrno();
46f07a9995SKamil Rytarowski     return error;
47f07a9995SKamil Rytarowski   }
48f07a9995SKamil Rytarowski 
49f07a9995SKamil Rytarowski   if (fcntl(fd, F_SETFL, status | flags) == -1) {
50f07a9995SKamil Rytarowski     error.SetErrorToErrno();
51f07a9995SKamil Rytarowski     return error;
52f07a9995SKamil Rytarowski   }
53f07a9995SKamil Rytarowski 
54f07a9995SKamil Rytarowski   return error;
55f07a9995SKamil Rytarowski }
56f07a9995SKamil Rytarowski 
571a3d19ddSKamil Rytarowski // Public Static Methods
581a3d19ddSKamil Rytarowski 
5982abefa4SPavel Labath llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
6096e600fcSPavel Labath NativeProcessNetBSD::Factory::Launch(ProcessLaunchInfo &launch_info,
6196e600fcSPavel Labath                                      NativeDelegate &native_delegate,
6296e600fcSPavel Labath                                      MainLoop &mainloop) const {
63f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
64f07a9995SKamil Rytarowski 
6596e600fcSPavel Labath   Status status;
6696e600fcSPavel Labath   ::pid_t pid = ProcessLauncherPosixFork()
6796e600fcSPavel Labath                     .LaunchProcess(launch_info, status)
6896e600fcSPavel Labath                     .GetProcessId();
6996e600fcSPavel Labath   LLDB_LOG(log, "pid = {0:x}", pid);
7096e600fcSPavel Labath   if (status.Fail()) {
7196e600fcSPavel Labath     LLDB_LOG(log, "failed to launch process: {0}", status);
7296e600fcSPavel Labath     return status.ToError();
73f07a9995SKamil Rytarowski   }
74f07a9995SKamil Rytarowski 
7596e600fcSPavel Labath   // Wait for the child process to trap on its call to execve.
7696e600fcSPavel Labath   int wstatus;
7796e600fcSPavel Labath   ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0);
7896e600fcSPavel Labath   assert(wpid == pid);
7996e600fcSPavel Labath   (void)wpid;
8096e600fcSPavel Labath   if (!WIFSTOPPED(wstatus)) {
8196e600fcSPavel Labath     LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}",
8296e600fcSPavel Labath              WaitStatus::Decode(wstatus));
8396e600fcSPavel Labath     return llvm::make_error<StringError>("Could not sync with inferior process",
8496e600fcSPavel Labath                                          llvm::inconvertibleErrorCode());
8596e600fcSPavel Labath   }
8696e600fcSPavel Labath   LLDB_LOG(log, "inferior started, now in stopped state");
87f07a9995SKamil Rytarowski 
8836e82208SPavel Labath   ProcessInstanceInfo Info;
8936e82208SPavel Labath   if (!Host::GetProcessInfo(pid, Info)) {
9036e82208SPavel Labath     return llvm::make_error<StringError>("Cannot get process architecture",
9136e82208SPavel Labath                                          llvm::inconvertibleErrorCode());
9236e82208SPavel Labath   }
9396e600fcSPavel Labath 
9496e600fcSPavel Labath   // Set the architecture to the exe architecture.
9596e600fcSPavel Labath   LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid,
9636e82208SPavel Labath            Info.GetArchitecture().GetArchitectureName());
9796e600fcSPavel Labath 
9882abefa4SPavel Labath   std::unique_ptr<NativeProcessNetBSD> process_up(new NativeProcessNetBSD(
9996e600fcSPavel Labath       pid, launch_info.GetPTY().ReleaseMasterFileDescriptor(), native_delegate,
10036e82208SPavel Labath       Info.GetArchitecture(), mainloop));
10196e600fcSPavel Labath 
10282abefa4SPavel Labath   status = process_up->ReinitializeThreads();
10396e600fcSPavel Labath   if (status.Fail())
10496e600fcSPavel Labath     return status.ToError();
10596e600fcSPavel Labath 
106a5be48b3SPavel Labath   for (const auto &thread : process_up->m_threads)
107a5be48b3SPavel Labath     static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(SIGSTOP);
1088a4bf06bSKamil Rytarowski   process_up->SetState(StateType::eStateStopped, false);
10996e600fcSPavel Labath 
11082abefa4SPavel Labath   return std::move(process_up);
111f07a9995SKamil Rytarowski }
112f07a9995SKamil Rytarowski 
11382abefa4SPavel Labath llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
11482abefa4SPavel Labath NativeProcessNetBSD::Factory::Attach(
1151a3d19ddSKamil Rytarowski     lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
11696e600fcSPavel Labath     MainLoop &mainloop) const {
117f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
118f07a9995SKamil Rytarowski   LLDB_LOG(log, "pid = {0:x}", pid);
119f07a9995SKamil Rytarowski 
120f07a9995SKamil Rytarowski   // Retrieve the architecture for the running process.
12136e82208SPavel Labath   ProcessInstanceInfo Info;
12236e82208SPavel Labath   if (!Host::GetProcessInfo(pid, Info)) {
12336e82208SPavel Labath     return llvm::make_error<StringError>("Cannot get process architecture",
12436e82208SPavel Labath                                          llvm::inconvertibleErrorCode());
12536e82208SPavel Labath   }
126f07a9995SKamil Rytarowski 
12736e82208SPavel Labath   std::unique_ptr<NativeProcessNetBSD> process_up(new NativeProcessNetBSD(
12836e82208SPavel Labath       pid, -1, native_delegate, Info.GetArchitecture(), mainloop));
129f07a9995SKamil Rytarowski 
13002d4e50eSPavel Labath   Status status = process_up->Attach();
13196e600fcSPavel Labath   if (!status.Success())
13296e600fcSPavel Labath     return status.ToError();
133f07a9995SKamil Rytarowski 
13482abefa4SPavel Labath   return std::move(process_up);
1351a3d19ddSKamil Rytarowski }
1361a3d19ddSKamil Rytarowski 
1371a3d19ddSKamil Rytarowski // Public Instance Methods
1381a3d19ddSKamil Rytarowski 
13996e600fcSPavel Labath NativeProcessNetBSD::NativeProcessNetBSD(::pid_t pid, int terminal_fd,
14096e600fcSPavel Labath                                          NativeDelegate &delegate,
14196e600fcSPavel Labath                                          const ArchSpec &arch,
14296e600fcSPavel Labath                                          MainLoop &mainloop)
143b09bc8a2SMichal Gorny     : NativeProcessELF(pid, terminal_fd, delegate), m_arch(arch) {
14496e600fcSPavel Labath   if (m_terminal_fd != -1) {
14596e600fcSPavel Labath     Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
14696e600fcSPavel Labath     assert(status.Success());
14796e600fcSPavel Labath   }
14896e600fcSPavel Labath 
14996e600fcSPavel Labath   Status status;
15096e600fcSPavel Labath   m_sigchld_handle = mainloop.RegisterSignal(
15196e600fcSPavel Labath       SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status);
15296e600fcSPavel Labath   assert(m_sigchld_handle && status.Success());
15396e600fcSPavel Labath }
154f07a9995SKamil Rytarowski 
155f07a9995SKamil Rytarowski // Handles all waitpid events from the inferior process.
156f07a9995SKamil Rytarowski void NativeProcessNetBSD::MonitorCallback(lldb::pid_t pid, int signal) {
157f07a9995SKamil Rytarowski   switch (signal) {
158f07a9995SKamil Rytarowski   case SIGTRAP:
159f07a9995SKamil Rytarowski     return MonitorSIGTRAP(pid);
160f07a9995SKamil Rytarowski   case SIGSTOP:
161f07a9995SKamil Rytarowski     return MonitorSIGSTOP(pid);
162f07a9995SKamil Rytarowski   default:
163f07a9995SKamil Rytarowski     return MonitorSignal(pid, signal);
164f07a9995SKamil Rytarowski   }
165f07a9995SKamil Rytarowski }
166f07a9995SKamil Rytarowski 
1673508fc8cSPavel Labath void NativeProcessNetBSD::MonitorExited(lldb::pid_t pid, WaitStatus status) {
168f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
169f07a9995SKamil Rytarowski 
1703508fc8cSPavel Labath   LLDB_LOG(log, "got exit signal({0}) , pid = {1}", status, pid);
171f07a9995SKamil Rytarowski 
172f07a9995SKamil Rytarowski   /* Stop Tracking All Threads attached to Process */
173f07a9995SKamil Rytarowski   m_threads.clear();
174f07a9995SKamil Rytarowski 
1753508fc8cSPavel Labath   SetExitStatus(status, true);
176f07a9995SKamil Rytarowski 
177f07a9995SKamil Rytarowski   // Notify delegate that our process has exited.
178f07a9995SKamil Rytarowski   SetState(StateType::eStateExited, true);
179f07a9995SKamil Rytarowski }
180f07a9995SKamil Rytarowski 
181f07a9995SKamil Rytarowski void NativeProcessNetBSD::MonitorSIGSTOP(lldb::pid_t pid) {
182f07a9995SKamil Rytarowski   ptrace_siginfo_t info;
183f07a9995SKamil Rytarowski 
184f07a9995SKamil Rytarowski   const auto siginfo_err =
185f07a9995SKamil Rytarowski       PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info));
186f07a9995SKamil Rytarowski 
187f07a9995SKamil Rytarowski   // Get details on the signal raised.
188f07a9995SKamil Rytarowski   if (siginfo_err.Success()) {
189f07a9995SKamil Rytarowski     // Handle SIGSTOP from LLGS (LLDB GDB Server)
190f07a9995SKamil Rytarowski     if (info.psi_siginfo.si_code == SI_USER &&
191f07a9995SKamil Rytarowski         info.psi_siginfo.si_pid == ::getpid()) {
192a5be48b3SPavel Labath       /* Stop Tracking all Threads attached to Process */
193a5be48b3SPavel Labath       for (const auto &thread : m_threads) {
194a5be48b3SPavel Labath         static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(
195f07a9995SKamil Rytarowski             SIGSTOP, &info.psi_siginfo);
196f07a9995SKamil Rytarowski       }
197f07a9995SKamil Rytarowski     }
198*e1c159e8SMichal Gorny     SetState(StateType::eStateStopped, true);
199f07a9995SKamil Rytarowski   }
200f07a9995SKamil Rytarowski }
201f07a9995SKamil Rytarowski 
202f07a9995SKamil Rytarowski void NativeProcessNetBSD::MonitorSIGTRAP(lldb::pid_t pid) {
203f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
204f07a9995SKamil Rytarowski   ptrace_siginfo_t info;
205f07a9995SKamil Rytarowski 
206f07a9995SKamil Rytarowski   const auto siginfo_err =
207f07a9995SKamil Rytarowski       PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info));
208f07a9995SKamil Rytarowski 
209f07a9995SKamil Rytarowski   // Get details on the signal raised.
21036e23ecaSKamil Rytarowski   if (siginfo_err.Fail()) {
21136e23ecaSKamil Rytarowski     return;
21236e23ecaSKamil Rytarowski   }
21336e23ecaSKamil Rytarowski 
214f07a9995SKamil Rytarowski   switch (info.psi_siginfo.si_code) {
215f07a9995SKamil Rytarowski   case TRAP_BRKPT:
216a5be48b3SPavel Labath     for (const auto &thread : m_threads) {
217a5be48b3SPavel Labath       static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByBreakpoint();
218a5be48b3SPavel Labath       FixupBreakpointPCAsNeeded(static_cast<NativeThreadNetBSD &>(*thread));
219f07a9995SKamil Rytarowski     }
220f07a9995SKamil Rytarowski     SetState(StateType::eStateStopped, true);
221f07a9995SKamil Rytarowski     break;
2223eef2b5eSKamil Rytarowski   case TRAP_TRACE:
223a5be48b3SPavel Labath     for (const auto &thread : m_threads)
224a5be48b3SPavel Labath       static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByTrace();
2253eef2b5eSKamil Rytarowski     SetState(StateType::eStateStopped, true);
2263eef2b5eSKamil Rytarowski     break;
2273eef2b5eSKamil Rytarowski   case TRAP_EXEC: {
22897206d57SZachary Turner     Status error = ReinitializeThreads();
2293eef2b5eSKamil Rytarowski     if (error.Fail()) {
2303eef2b5eSKamil Rytarowski       SetState(StateType::eStateInvalid);
2313eef2b5eSKamil Rytarowski       return;
2323eef2b5eSKamil Rytarowski     }
2333eef2b5eSKamil Rytarowski 
2343eef2b5eSKamil Rytarowski     // Let our delegate know we have just exec'd.
2353eef2b5eSKamil Rytarowski     NotifyDidExec();
2363eef2b5eSKamil Rytarowski 
237a5be48b3SPavel Labath     for (const auto &thread : m_threads)
238a5be48b3SPavel Labath       static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByExec();
2393eef2b5eSKamil Rytarowski     SetState(StateType::eStateStopped, true);
2403eef2b5eSKamil Rytarowski   } break;
24136e23ecaSKamil Rytarowski   case TRAP_DBREG: {
242baf64b65SMichal Gorny     // Find the thread.
243baf64b65SMichal Gorny     NativeThreadNetBSD* thread = nullptr;
244baf64b65SMichal Gorny     for (const auto &t : m_threads) {
245baf64b65SMichal Gorny       if (t->GetID() == info.psi_lwpid) {
246baf64b65SMichal Gorny         thread = static_cast<NativeThreadNetBSD *>(t.get());
247baf64b65SMichal Gorny         break;
248baf64b65SMichal Gorny       }
249baf64b65SMichal Gorny     }
250baf64b65SMichal Gorny     if (!thread) {
251baf64b65SMichal Gorny       LLDB_LOG(log,
252baf64b65SMichal Gorny                "thread not found in m_threads, pid = {0}, LWP = {1}",
253baf64b65SMichal Gorny                GetID(), info.psi_lwpid);
254baf64b65SMichal Gorny       break;
255baf64b65SMichal Gorny     }
256baf64b65SMichal Gorny 
25736e23ecaSKamil Rytarowski     // If a watchpoint was hit, report it
258baf64b65SMichal Gorny     uint32_t wp_index = LLDB_INVALID_INDEX32;
259baf64b65SMichal Gorny     Status error = thread->GetRegisterContext().GetWatchpointHitIndex(
260a5be48b3SPavel Labath         wp_index, (uintptr_t)info.psi_siginfo.si_addr);
26136e23ecaSKamil Rytarowski     if (error.Fail())
26236e23ecaSKamil Rytarowski       LLDB_LOG(log,
26336e23ecaSKamil Rytarowski                "received error while checking for watchpoint hits, pid = "
26436e23ecaSKamil Rytarowski                "{0}, LWP = {1}, error = {2}",
26536e23ecaSKamil Rytarowski                GetID(), info.psi_lwpid, error);
26636e23ecaSKamil Rytarowski     if (wp_index != LLDB_INVALID_INDEX32) {
267a5be48b3SPavel Labath       for (const auto &thread : m_threads)
268a5be48b3SPavel Labath         static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByWatchpoint(
269a5be48b3SPavel Labath             wp_index);
27036e23ecaSKamil Rytarowski       SetState(StateType::eStateStopped, true);
27136e23ecaSKamil Rytarowski       break;
27236e23ecaSKamil Rytarowski     }
27336e23ecaSKamil Rytarowski 
27436e23ecaSKamil Rytarowski     // If a breakpoint was hit, report it
275baf64b65SMichal Gorny     uint32_t bp_index = LLDB_INVALID_INDEX32;
276baf64b65SMichal Gorny     error = thread->GetRegisterContext().GetHardwareBreakHitIndex(
277baf64b65SMichal Gorny         bp_index, (uintptr_t)info.psi_siginfo.si_addr);
27836e23ecaSKamil Rytarowski     if (error.Fail())
27936e23ecaSKamil Rytarowski       LLDB_LOG(log,
28036e23ecaSKamil Rytarowski                "received error while checking for hardware "
28136e23ecaSKamil Rytarowski                "breakpoint hits, pid = {0}, LWP = {1}, error = {2}",
28236e23ecaSKamil Rytarowski                GetID(), info.psi_lwpid, error);
28336e23ecaSKamil Rytarowski     if (bp_index != LLDB_INVALID_INDEX32) {
284a5be48b3SPavel Labath       for (const auto &thread : m_threads)
285a5be48b3SPavel Labath         static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByBreakpoint();
28636e23ecaSKamil Rytarowski       SetState(StateType::eStateStopped, true);
28736e23ecaSKamil Rytarowski       break;
28836e23ecaSKamil Rytarowski     }
28936e23ecaSKamil Rytarowski   } break;
290f07a9995SKamil Rytarowski   }
291f07a9995SKamil Rytarowski }
292f07a9995SKamil Rytarowski 
293f07a9995SKamil Rytarowski void NativeProcessNetBSD::MonitorSignal(lldb::pid_t pid, int signal) {
294f07a9995SKamil Rytarowski   ptrace_siginfo_t info;
295f07a9995SKamil Rytarowski   const auto siginfo_err =
296f07a9995SKamil Rytarowski       PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info));
297f07a9995SKamil Rytarowski 
298a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
299a5be48b3SPavel Labath     static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(
300f07a9995SKamil Rytarowski         info.psi_siginfo.si_signo, &info.psi_siginfo);
301f07a9995SKamil Rytarowski   }
302f07a9995SKamil Rytarowski   SetState(StateType::eStateStopped, true);
303f07a9995SKamil Rytarowski }
304f07a9995SKamil Rytarowski 
30597206d57SZachary Turner Status NativeProcessNetBSD::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
306f07a9995SKamil Rytarowski                                           int data, int *result) {
307f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
30897206d57SZachary Turner   Status error;
309f07a9995SKamil Rytarowski   int ret;
310f07a9995SKamil Rytarowski 
311f07a9995SKamil Rytarowski   errno = 0;
312f07a9995SKamil Rytarowski   ret = ptrace(req, static_cast<::pid_t>(pid), addr, data);
313f07a9995SKamil Rytarowski 
314f07a9995SKamil Rytarowski   if (ret == -1)
315f07a9995SKamil Rytarowski     error.SetErrorToErrno();
316f07a9995SKamil Rytarowski 
317f07a9995SKamil Rytarowski   if (result)
318f07a9995SKamil Rytarowski     *result = ret;
319f07a9995SKamil Rytarowski 
320f07a9995SKamil Rytarowski   LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3})={4:x}", req, pid, addr, data, ret);
321f07a9995SKamil Rytarowski 
322f07a9995SKamil Rytarowski   if (error.Fail())
323f07a9995SKamil Rytarowski     LLDB_LOG(log, "ptrace() failed: {0}", error);
324f07a9995SKamil Rytarowski 
325f07a9995SKamil Rytarowski   return error;
326f07a9995SKamil Rytarowski }
327f07a9995SKamil Rytarowski 
32897206d57SZachary Turner Status NativeProcessNetBSD::Resume(const ResumeActionList &resume_actions) {
329f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
330f07a9995SKamil Rytarowski   LLDB_LOG(log, "pid {0}", GetID());
331f07a9995SKamil Rytarowski 
332a5be48b3SPavel Labath   const auto &thread = m_threads[0];
333f07a9995SKamil Rytarowski   const ResumeAction *const action =
334a5be48b3SPavel Labath       resume_actions.GetActionForThread(thread->GetID(), true);
335f07a9995SKamil Rytarowski 
336f07a9995SKamil Rytarowski   if (action == nullptr) {
337f07a9995SKamil Rytarowski     LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
338a5be48b3SPavel Labath              thread->GetID());
33997206d57SZachary Turner     return Status();
340f07a9995SKamil Rytarowski   }
341f07a9995SKamil Rytarowski 
34297206d57SZachary Turner   Status error;
3433eef2b5eSKamil Rytarowski 
344f07a9995SKamil Rytarowski   switch (action->state) {
345f07a9995SKamil Rytarowski   case eStateRunning: {
346f07a9995SKamil Rytarowski     // Run the thread, possibly feeding it the signal.
3473eef2b5eSKamil Rytarowski     error = NativeProcessNetBSD::PtraceWrapper(PT_CONTINUE, GetID(), (void *)1,
3483eef2b5eSKamil Rytarowski                                                action->signal);
349f07a9995SKamil Rytarowski     if (!error.Success())
350f07a9995SKamil Rytarowski       return error;
351a5be48b3SPavel Labath     for (const auto &thread : m_threads)
352a5be48b3SPavel Labath       static_cast<NativeThreadNetBSD &>(*thread).SetRunning();
353f07a9995SKamil Rytarowski     SetState(eStateRunning, true);
354f07a9995SKamil Rytarowski     break;
355f07a9995SKamil Rytarowski   }
356f07a9995SKamil Rytarowski   case eStateStepping:
3573eef2b5eSKamil Rytarowski     // Run the thread, possibly feeding it the signal.
3583eef2b5eSKamil Rytarowski     error = NativeProcessNetBSD::PtraceWrapper(PT_STEP, GetID(), (void *)1,
3593eef2b5eSKamil Rytarowski                                                action->signal);
3603eef2b5eSKamil Rytarowski     if (!error.Success())
3613eef2b5eSKamil Rytarowski       return error;
362a5be48b3SPavel Labath     for (const auto &thread : m_threads)
363a5be48b3SPavel Labath       static_cast<NativeThreadNetBSD &>(*thread).SetStepping();
3643eef2b5eSKamil Rytarowski     SetState(eStateStepping, true);
365f07a9995SKamil Rytarowski     break;
366f07a9995SKamil Rytarowski 
367f07a9995SKamil Rytarowski   case eStateSuspended:
368f07a9995SKamil Rytarowski   case eStateStopped:
369f07a9995SKamil Rytarowski     llvm_unreachable("Unexpected state");
370f07a9995SKamil Rytarowski 
371f07a9995SKamil Rytarowski   default:
37297206d57SZachary Turner     return Status("NativeProcessNetBSD::%s (): unexpected state %s specified "
373f07a9995SKamil Rytarowski                   "for pid %" PRIu64 ", tid %" PRIu64,
374f07a9995SKamil Rytarowski                   __FUNCTION__, StateAsCString(action->state), GetID(),
375a5be48b3SPavel Labath                   thread->GetID());
376f07a9995SKamil Rytarowski   }
377f07a9995SKamil Rytarowski 
37897206d57SZachary Turner   return Status();
379f07a9995SKamil Rytarowski }
380f07a9995SKamil Rytarowski 
38197206d57SZachary Turner Status NativeProcessNetBSD::Halt() {
38297206d57SZachary Turner   Status error;
383f07a9995SKamil Rytarowski 
384f07a9995SKamil Rytarowski   if (kill(GetID(), SIGSTOP) != 0)
385f07a9995SKamil Rytarowski     error.SetErrorToErrno();
386f07a9995SKamil Rytarowski 
387f07a9995SKamil Rytarowski   return error;
388f07a9995SKamil Rytarowski }
389f07a9995SKamil Rytarowski 
39097206d57SZachary Turner Status NativeProcessNetBSD::Detach() {
39197206d57SZachary Turner   Status error;
392f07a9995SKamil Rytarowski 
393f07a9995SKamil Rytarowski   // Stop monitoring the inferior.
394f07a9995SKamil Rytarowski   m_sigchld_handle.reset();
395f07a9995SKamil Rytarowski 
396f07a9995SKamil Rytarowski   // Tell ptrace to detach from the process.
397f07a9995SKamil Rytarowski   if (GetID() == LLDB_INVALID_PROCESS_ID)
398f07a9995SKamil Rytarowski     return error;
399f07a9995SKamil Rytarowski 
400f07a9995SKamil Rytarowski   return PtraceWrapper(PT_DETACH, GetID());
401f07a9995SKamil Rytarowski }
402f07a9995SKamil Rytarowski 
40397206d57SZachary Turner Status NativeProcessNetBSD::Signal(int signo) {
40497206d57SZachary Turner   Status error;
405f07a9995SKamil Rytarowski 
406f07a9995SKamil Rytarowski   if (kill(GetID(), signo))
407f07a9995SKamil Rytarowski     error.SetErrorToErrno();
408f07a9995SKamil Rytarowski 
409f07a9995SKamil Rytarowski   return error;
410f07a9995SKamil Rytarowski }
411f07a9995SKamil Rytarowski 
41297206d57SZachary Turner Status NativeProcessNetBSD::Kill() {
413f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
414f07a9995SKamil Rytarowski   LLDB_LOG(log, "pid {0}", GetID());
415f07a9995SKamil Rytarowski 
41697206d57SZachary Turner   Status error;
417f07a9995SKamil Rytarowski 
418f07a9995SKamil Rytarowski   switch (m_state) {
419f07a9995SKamil Rytarowski   case StateType::eStateInvalid:
420f07a9995SKamil Rytarowski   case StateType::eStateExited:
421f07a9995SKamil Rytarowski   case StateType::eStateCrashed:
422f07a9995SKamil Rytarowski   case StateType::eStateDetached:
423f07a9995SKamil Rytarowski   case StateType::eStateUnloaded:
424f07a9995SKamil Rytarowski     // Nothing to do - the process is already dead.
425f07a9995SKamil Rytarowski     LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
426f07a9995SKamil Rytarowski              StateAsCString(m_state));
427f07a9995SKamil Rytarowski     return error;
428f07a9995SKamil Rytarowski 
429f07a9995SKamil Rytarowski   case StateType::eStateConnected:
430f07a9995SKamil Rytarowski   case StateType::eStateAttaching:
431f07a9995SKamil Rytarowski   case StateType::eStateLaunching:
432f07a9995SKamil Rytarowski   case StateType::eStateStopped:
433f07a9995SKamil Rytarowski   case StateType::eStateRunning:
434f07a9995SKamil Rytarowski   case StateType::eStateStepping:
435f07a9995SKamil Rytarowski   case StateType::eStateSuspended:
436f07a9995SKamil Rytarowski     // We can try to kill a process in these states.
437f07a9995SKamil Rytarowski     break;
438f07a9995SKamil Rytarowski   }
439f07a9995SKamil Rytarowski 
440f07a9995SKamil Rytarowski   if (kill(GetID(), SIGKILL) != 0) {
441f07a9995SKamil Rytarowski     error.SetErrorToErrno();
442f07a9995SKamil Rytarowski     return error;
443f07a9995SKamil Rytarowski   }
444f07a9995SKamil Rytarowski 
445f07a9995SKamil Rytarowski   return error;
446f07a9995SKamil Rytarowski }
447f07a9995SKamil Rytarowski 
44897206d57SZachary Turner Status NativeProcessNetBSD::GetMemoryRegionInfo(lldb::addr_t load_addr,
449f07a9995SKamil Rytarowski                                                 MemoryRegionInfo &range_info) {
450f07a9995SKamil Rytarowski 
451f07a9995SKamil Rytarowski   if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
452f07a9995SKamil Rytarowski     // We're done.
45397206d57SZachary Turner     return Status("unsupported");
454f07a9995SKamil Rytarowski   }
455f07a9995SKamil Rytarowski 
45697206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
457f07a9995SKamil Rytarowski   if (error.Fail()) {
458f07a9995SKamil Rytarowski     return error;
459f07a9995SKamil Rytarowski   }
460f07a9995SKamil Rytarowski 
461f07a9995SKamil Rytarowski   lldb::addr_t prev_base_address = 0;
462f07a9995SKamil Rytarowski   // FIXME start by finding the last region that is <= target address using
463f07a9995SKamil Rytarowski   // binary search.  Data is sorted.
464f07a9995SKamil Rytarowski   // There can be a ton of regions on pthreads apps with lots of threads.
465f07a9995SKamil Rytarowski   for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
466f07a9995SKamil Rytarowski        ++it) {
467f07a9995SKamil Rytarowski     MemoryRegionInfo &proc_entry_info = it->first;
468f07a9995SKamil Rytarowski     // Sanity check assumption that memory map entries are ascending.
469f07a9995SKamil Rytarowski     assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
470f07a9995SKamil Rytarowski            "descending memory map entries detected, unexpected");
471f07a9995SKamil Rytarowski     prev_base_address = proc_entry_info.GetRange().GetRangeBase();
472f07a9995SKamil Rytarowski     UNUSED_IF_ASSERT_DISABLED(prev_base_address);
47305097246SAdrian Prantl     // If the target address comes before this entry, indicate distance to next
47405097246SAdrian Prantl     // region.
475f07a9995SKamil Rytarowski     if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
476f07a9995SKamil Rytarowski       range_info.GetRange().SetRangeBase(load_addr);
477f07a9995SKamil Rytarowski       range_info.GetRange().SetByteSize(
478f07a9995SKamil Rytarowski           proc_entry_info.GetRange().GetRangeBase() - load_addr);
479f07a9995SKamil Rytarowski       range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
480f07a9995SKamil Rytarowski       range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
481f07a9995SKamil Rytarowski       range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
482f07a9995SKamil Rytarowski       range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
483f07a9995SKamil Rytarowski       return error;
484f07a9995SKamil Rytarowski     } else if (proc_entry_info.GetRange().Contains(load_addr)) {
485f07a9995SKamil Rytarowski       // The target address is within the memory region we're processing here.
486f07a9995SKamil Rytarowski       range_info = proc_entry_info;
487f07a9995SKamil Rytarowski       return error;
488f07a9995SKamil Rytarowski     }
489f07a9995SKamil Rytarowski     // The target memory address comes somewhere after the region we just
490f07a9995SKamil Rytarowski     // parsed.
491f07a9995SKamil Rytarowski   }
492f07a9995SKamil Rytarowski   // If we made it here, we didn't find an entry that contained the given
49305097246SAdrian Prantl   // address. Return the load_addr as start and the amount of bytes betwwen
49405097246SAdrian Prantl   // load address and the end of the memory as size.
495f07a9995SKamil Rytarowski   range_info.GetRange().SetRangeBase(load_addr);
496f07a9995SKamil Rytarowski   range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
497f07a9995SKamil Rytarowski   range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
498f07a9995SKamil Rytarowski   range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
499f07a9995SKamil Rytarowski   range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
500f07a9995SKamil Rytarowski   range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
501f07a9995SKamil Rytarowski   return error;
502f07a9995SKamil Rytarowski }
503f07a9995SKamil Rytarowski 
50497206d57SZachary Turner Status NativeProcessNetBSD::PopulateMemoryRegionCache() {
505f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
506f07a9995SKamil Rytarowski   // If our cache is empty, pull the latest.  There should always be at least
507f07a9995SKamil Rytarowski   // one memory region if memory region handling is supported.
508f07a9995SKamil Rytarowski   if (!m_mem_region_cache.empty()) {
509f07a9995SKamil Rytarowski     LLDB_LOG(log, "reusing {0} cached memory region entries",
510f07a9995SKamil Rytarowski              m_mem_region_cache.size());
51197206d57SZachary Turner     return Status();
512f07a9995SKamil Rytarowski   }
513f07a9995SKamil Rytarowski 
514f07a9995SKamil Rytarowski   struct kinfo_vmentry *vm;
515f07a9995SKamil Rytarowski   size_t count, i;
516f07a9995SKamil Rytarowski   vm = kinfo_getvmmap(GetID(), &count);
517f07a9995SKamil Rytarowski   if (vm == NULL) {
518f07a9995SKamil Rytarowski     m_supports_mem_region = LazyBool::eLazyBoolNo;
51997206d57SZachary Turner     Status error;
520f07a9995SKamil Rytarowski     error.SetErrorString("not supported");
521f07a9995SKamil Rytarowski     return error;
522f07a9995SKamil Rytarowski   }
523f07a9995SKamil Rytarowski   for (i = 0; i < count; i++) {
524f07a9995SKamil Rytarowski     MemoryRegionInfo info;
525f07a9995SKamil Rytarowski     info.Clear();
526f07a9995SKamil Rytarowski     info.GetRange().SetRangeBase(vm[i].kve_start);
527f07a9995SKamil Rytarowski     info.GetRange().SetRangeEnd(vm[i].kve_end);
528f07a9995SKamil Rytarowski     info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
529f07a9995SKamil Rytarowski 
530f07a9995SKamil Rytarowski     if (vm[i].kve_protection & VM_PROT_READ)
531f07a9995SKamil Rytarowski       info.SetReadable(MemoryRegionInfo::OptionalBool::eYes);
532f07a9995SKamil Rytarowski     else
533f07a9995SKamil Rytarowski       info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
534f07a9995SKamil Rytarowski 
535f07a9995SKamil Rytarowski     if (vm[i].kve_protection & VM_PROT_WRITE)
536f07a9995SKamil Rytarowski       info.SetWritable(MemoryRegionInfo::OptionalBool::eYes);
537f07a9995SKamil Rytarowski     else
538f07a9995SKamil Rytarowski       info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
539f07a9995SKamil Rytarowski 
540f07a9995SKamil Rytarowski     if (vm[i].kve_protection & VM_PROT_EXECUTE)
541f07a9995SKamil Rytarowski       info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes);
542f07a9995SKamil Rytarowski     else
543f07a9995SKamil Rytarowski       info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
544f07a9995SKamil Rytarowski 
545f07a9995SKamil Rytarowski     if (vm[i].kve_path[0])
546f07a9995SKamil Rytarowski       info.SetName(vm[i].kve_path);
547f07a9995SKamil Rytarowski 
548f07a9995SKamil Rytarowski     m_mem_region_cache.emplace_back(
549a0a44e9cSKamil Rytarowski         info, FileSpec(info.GetName().GetCString()));
550f07a9995SKamil Rytarowski   }
551f07a9995SKamil Rytarowski   free(vm);
552f07a9995SKamil Rytarowski 
553f07a9995SKamil Rytarowski   if (m_mem_region_cache.empty()) {
55405097246SAdrian Prantl     // No entries after attempting to read them.  This shouldn't happen. Assume
55505097246SAdrian Prantl     // we don't support map entries.
556f07a9995SKamil Rytarowski     LLDB_LOG(log, "failed to find any vmmap entries, assuming no support "
557f07a9995SKamil Rytarowski                   "for memory region metadata retrieval");
558f07a9995SKamil Rytarowski     m_supports_mem_region = LazyBool::eLazyBoolNo;
55997206d57SZachary Turner     Status error;
560f07a9995SKamil Rytarowski     error.SetErrorString("not supported");
561f07a9995SKamil Rytarowski     return error;
562f07a9995SKamil Rytarowski   }
563f07a9995SKamil Rytarowski   LLDB_LOG(log, "read {0} memory region entries from process {1}",
564f07a9995SKamil Rytarowski            m_mem_region_cache.size(), GetID());
565f07a9995SKamil Rytarowski   // We support memory retrieval, remember that.
566f07a9995SKamil Rytarowski   m_supports_mem_region = LazyBool::eLazyBoolYes;
56797206d57SZachary Turner   return Status();
568f07a9995SKamil Rytarowski }
569f07a9995SKamil Rytarowski 
57097206d57SZachary Turner Status NativeProcessNetBSD::AllocateMemory(size_t size, uint32_t permissions,
571f07a9995SKamil Rytarowski                                            lldb::addr_t &addr) {
57297206d57SZachary Turner   return Status("Unimplemented");
573f07a9995SKamil Rytarowski }
574f07a9995SKamil Rytarowski 
57597206d57SZachary Turner Status NativeProcessNetBSD::DeallocateMemory(lldb::addr_t addr) {
57697206d57SZachary Turner   return Status("Unimplemented");
577f07a9995SKamil Rytarowski }
578f07a9995SKamil Rytarowski 
579f07a9995SKamil Rytarowski lldb::addr_t NativeProcessNetBSD::GetSharedLibraryInfoAddress() {
580f07a9995SKamil Rytarowski   // punt on this for now
581f07a9995SKamil Rytarowski   return LLDB_INVALID_ADDRESS;
582f07a9995SKamil Rytarowski }
583f07a9995SKamil Rytarowski 
584f07a9995SKamil Rytarowski size_t NativeProcessNetBSD::UpdateThreads() { return m_threads.size(); }
585f07a9995SKamil Rytarowski 
58697206d57SZachary Turner Status NativeProcessNetBSD::SetBreakpoint(lldb::addr_t addr, uint32_t size,
587f07a9995SKamil Rytarowski                                           bool hardware) {
588f07a9995SKamil Rytarowski   if (hardware)
58997206d57SZachary Turner     return Status("NativeProcessNetBSD does not support hardware breakpoints");
590f07a9995SKamil Rytarowski   else
591f07a9995SKamil Rytarowski     return SetSoftwareBreakpoint(addr, size);
592f07a9995SKamil Rytarowski }
593f07a9995SKamil Rytarowski 
59497206d57SZachary Turner Status NativeProcessNetBSD::GetLoadedModuleFileSpec(const char *module_path,
595f07a9995SKamil Rytarowski                                                     FileSpec &file_spec) {
59697206d57SZachary Turner   return Status("Unimplemented");
597f07a9995SKamil Rytarowski }
598f07a9995SKamil Rytarowski 
59997206d57SZachary Turner Status NativeProcessNetBSD::GetFileLoadAddress(const llvm::StringRef &file_name,
600f07a9995SKamil Rytarowski                                                lldb::addr_t &load_addr) {
601f07a9995SKamil Rytarowski   load_addr = LLDB_INVALID_ADDRESS;
60297206d57SZachary Turner   return Status();
603f07a9995SKamil Rytarowski }
604f07a9995SKamil Rytarowski 
605f07a9995SKamil Rytarowski void NativeProcessNetBSD::SigchldHandler() {
606f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
607f07a9995SKamil Rytarowski   // Process all pending waitpid notifications.
608f07a9995SKamil Rytarowski   int status;
609c1a6b128SPavel Labath   ::pid_t wait_pid =
610c1a6b128SPavel Labath       llvm::sys::RetryAfterSignal(-1, waitpid, GetID(), &status, WALLSIG | WNOHANG);
611f07a9995SKamil Rytarowski 
612f07a9995SKamil Rytarowski   if (wait_pid == 0)
613f07a9995SKamil Rytarowski     return; // We are done.
614f07a9995SKamil Rytarowski 
615f07a9995SKamil Rytarowski   if (wait_pid == -1) {
61697206d57SZachary Turner     Status error(errno, eErrorTypePOSIX);
617f07a9995SKamil Rytarowski     LLDB_LOG(log, "waitpid ({0}, &status, _) failed: {1}", GetID(), error);
618f07a9995SKamil Rytarowski   }
619f07a9995SKamil Rytarowski 
6203508fc8cSPavel Labath   WaitStatus wait_status = WaitStatus::Decode(status);
6213508fc8cSPavel Labath   bool exited = wait_status.type == WaitStatus::Exit ||
6223508fc8cSPavel Labath                 (wait_status.type == WaitStatus::Signal &&
6233508fc8cSPavel Labath                  wait_pid == static_cast<::pid_t>(GetID()));
624f07a9995SKamil Rytarowski 
625f07a9995SKamil Rytarowski   LLDB_LOG(log,
6263508fc8cSPavel Labath            "waitpid ({0}, &status, _) => pid = {1}, status = {2}, exited = {3}",
6273508fc8cSPavel Labath            GetID(), wait_pid, status, exited);
628f07a9995SKamil Rytarowski 
629f07a9995SKamil Rytarowski   if (exited)
6303508fc8cSPavel Labath     MonitorExited(wait_pid, wait_status);
6313508fc8cSPavel Labath   else {
6324bb74415SKamil Rytarowski     assert(wait_status.type == WaitStatus::Stop);
6333508fc8cSPavel Labath     MonitorCallback(wait_pid, wait_status.status);
6343508fc8cSPavel Labath   }
635f07a9995SKamil Rytarowski }
636f07a9995SKamil Rytarowski 
637269eec03SKamil Rytarowski bool NativeProcessNetBSD::HasThreadNoLock(lldb::tid_t thread_id) {
638a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
639a5be48b3SPavel Labath     assert(thread && "thread list should not contain NULL threads");
640a5be48b3SPavel Labath     if (thread->GetID() == thread_id) {
641269eec03SKamil Rytarowski       // We have this thread.
642269eec03SKamil Rytarowski       return true;
643269eec03SKamil Rytarowski     }
644269eec03SKamil Rytarowski   }
645269eec03SKamil Rytarowski 
646269eec03SKamil Rytarowski   // We don't have this thread.
647269eec03SKamil Rytarowski   return false;
648269eec03SKamil Rytarowski }
649269eec03SKamil Rytarowski 
650a5be48b3SPavel Labath NativeThreadNetBSD &NativeProcessNetBSD::AddThread(lldb::tid_t thread_id) {
651f07a9995SKamil Rytarowski 
652f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
653f07a9995SKamil Rytarowski   LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
654f07a9995SKamil Rytarowski 
655f07a9995SKamil Rytarowski   assert(!HasThreadNoLock(thread_id) &&
656f07a9995SKamil Rytarowski          "attempted to add a thread by id that already exists");
657f07a9995SKamil Rytarowski 
658f07a9995SKamil Rytarowski   // If this is the first thread, save it as the current thread
659f07a9995SKamil Rytarowski   if (m_threads.empty())
660f07a9995SKamil Rytarowski     SetCurrentThreadID(thread_id);
661f07a9995SKamil Rytarowski 
662a5be48b3SPavel Labath   m_threads.push_back(llvm::make_unique<NativeThreadNetBSD>(*this, thread_id));
663a5be48b3SPavel Labath   return static_cast<NativeThreadNetBSD &>(*m_threads.back());
664f07a9995SKamil Rytarowski }
665f07a9995SKamil Rytarowski 
66696e600fcSPavel Labath Status NativeProcessNetBSD::Attach() {
667f07a9995SKamil Rytarowski   // Attach to the requested process.
668f07a9995SKamil Rytarowski   // An attach will cause the thread to stop with a SIGSTOP.
66996e600fcSPavel Labath   Status status = PtraceWrapper(PT_ATTACH, m_pid);
67096e600fcSPavel Labath   if (status.Fail())
67196e600fcSPavel Labath     return status;
672f07a9995SKamil Rytarowski 
67396e600fcSPavel Labath   int wstatus;
67405097246SAdrian Prantl   // Need to use WALLSIG otherwise we receive an error with errno=ECHLD At this
67505097246SAdrian Prantl   // point we should have a thread stopped if waitpid succeeds.
6762819136fSMichal Gorny   if ((wstatus = llvm::sys::RetryAfterSignal(-1, waitpid,
677c5d7bc86SMichal Gorny           m_pid, nullptr, WALLSIG)) < 0)
67896e600fcSPavel Labath     return Status(errno, eErrorTypePOSIX);
679f07a9995SKamil Rytarowski 
680f07a9995SKamil Rytarowski   /* Initialize threads */
68196e600fcSPavel Labath   status = ReinitializeThreads();
68296e600fcSPavel Labath   if (status.Fail())
68396e600fcSPavel Labath     return status;
684f07a9995SKamil Rytarowski 
685a5be48b3SPavel Labath   for (const auto &thread : m_threads)
686a5be48b3SPavel Labath     static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(SIGSTOP);
68736e23ecaSKamil Rytarowski 
688f07a9995SKamil Rytarowski   // Let our process instance know the thread has stopped.
689f07a9995SKamil Rytarowski   SetState(StateType::eStateStopped);
69096e600fcSPavel Labath   return Status();
691f07a9995SKamil Rytarowski }
692f07a9995SKamil Rytarowski 
69397206d57SZachary Turner Status NativeProcessNetBSD::ReadMemory(lldb::addr_t addr, void *buf,
69497206d57SZachary Turner                                        size_t size, size_t &bytes_read) {
695f07a9995SKamil Rytarowski   unsigned char *dst = static_cast<unsigned char *>(buf);
696f07a9995SKamil Rytarowski   struct ptrace_io_desc io;
697f07a9995SKamil Rytarowski 
698f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
699f07a9995SKamil Rytarowski   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
700f07a9995SKamil Rytarowski 
701f07a9995SKamil Rytarowski   bytes_read = 0;
702f07a9995SKamil Rytarowski   io.piod_op = PIOD_READ_D;
703f07a9995SKamil Rytarowski   io.piod_len = size;
704f07a9995SKamil Rytarowski 
705f07a9995SKamil Rytarowski   do {
706f07a9995SKamil Rytarowski     io.piod_offs = (void *)(addr + bytes_read);
707f07a9995SKamil Rytarowski     io.piod_addr = dst + bytes_read;
708f07a9995SKamil Rytarowski 
70997206d57SZachary Turner     Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
710d14a0de9SMichal Gorny     if (error.Fail() || io.piod_len == 0)
711f07a9995SKamil Rytarowski       return error;
712f07a9995SKamil Rytarowski 
713d14a0de9SMichal Gorny     bytes_read += io.piod_len;
714f07a9995SKamil Rytarowski     io.piod_len = size - bytes_read;
715f07a9995SKamil Rytarowski   } while (bytes_read < size);
716f07a9995SKamil Rytarowski 
71797206d57SZachary Turner   return Status();
718f07a9995SKamil Rytarowski }
719f07a9995SKamil Rytarowski 
72097206d57SZachary Turner Status NativeProcessNetBSD::WriteMemory(lldb::addr_t addr, const void *buf,
721f07a9995SKamil Rytarowski                                         size_t size, size_t &bytes_written) {
722f07a9995SKamil Rytarowski   const unsigned char *src = static_cast<const unsigned char *>(buf);
72397206d57SZachary Turner   Status error;
724f07a9995SKamil Rytarowski   struct ptrace_io_desc io;
725f07a9995SKamil Rytarowski 
726f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
727f07a9995SKamil Rytarowski   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
728f07a9995SKamil Rytarowski 
729f07a9995SKamil Rytarowski   bytes_written = 0;
730f07a9995SKamil Rytarowski   io.piod_op = PIOD_WRITE_D;
731f07a9995SKamil Rytarowski   io.piod_len = size;
732f07a9995SKamil Rytarowski 
733f07a9995SKamil Rytarowski   do {
734269eec03SKamil Rytarowski     io.piod_addr = const_cast<void *>(static_cast<const void *>(src + bytes_written));
735f07a9995SKamil Rytarowski     io.piod_offs = (void *)(addr + bytes_written);
736f07a9995SKamil Rytarowski 
73797206d57SZachary Turner     Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
738d14a0de9SMichal Gorny     if (error.Fail() || io.piod_len == 0)
739f07a9995SKamil Rytarowski       return error;
740f07a9995SKamil Rytarowski 
741d14a0de9SMichal Gorny     bytes_written += io.piod_len;
742f07a9995SKamil Rytarowski     io.piod_len = size - bytes_written;
743f07a9995SKamil Rytarowski   } while (bytes_written < size);
744f07a9995SKamil Rytarowski 
745f07a9995SKamil Rytarowski   return error;
746f07a9995SKamil Rytarowski }
747f07a9995SKamil Rytarowski 
748f07a9995SKamil Rytarowski llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
749f07a9995SKamil Rytarowski NativeProcessNetBSD::GetAuxvData() const {
750f07a9995SKamil Rytarowski   /*
751f07a9995SKamil Rytarowski    * ELF_AUX_ENTRIES is currently restricted to kernel
752f07a9995SKamil Rytarowski    * (<sys/exec_elf.h> r. 1.155 specifies 15)
753f07a9995SKamil Rytarowski    *
754f07a9995SKamil Rytarowski    * ptrace(2) returns the whole AUXV including extra fiels after AT_NULL this
755f07a9995SKamil Rytarowski    * information isn't needed.
756f07a9995SKamil Rytarowski    */
757f07a9995SKamil Rytarowski   size_t auxv_size = 100 * sizeof(AuxInfo);
758f07a9995SKamil Rytarowski 
759e831bb3cSPavel Labath   ErrorOr<std::unique_ptr<WritableMemoryBuffer>> buf =
760dbda2851SPavel Labath       llvm::WritableMemoryBuffer::getNewMemBuffer(auxv_size);
761f07a9995SKamil Rytarowski 
762269eec03SKamil Rytarowski   struct ptrace_io_desc io;
763269eec03SKamil Rytarowski   io.piod_op = PIOD_READ_AUXV;
764269eec03SKamil Rytarowski   io.piod_offs = 0;
765e831bb3cSPavel Labath   io.piod_addr = static_cast<void *>(buf.get()->getBufferStart());
766269eec03SKamil Rytarowski   io.piod_len = auxv_size;
767f07a9995SKamil Rytarowski 
76897206d57SZachary Turner   Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
769f07a9995SKamil Rytarowski 
770f07a9995SKamil Rytarowski   if (error.Fail())
771f07a9995SKamil Rytarowski     return std::error_code(error.GetError(), std::generic_category());
772f07a9995SKamil Rytarowski 
773f07a9995SKamil Rytarowski   if (io.piod_len < 1)
774f07a9995SKamil Rytarowski     return std::error_code(ECANCELED, std::generic_category());
775f07a9995SKamil Rytarowski 
776e831bb3cSPavel Labath   return std::move(buf);
777f07a9995SKamil Rytarowski }
7783eef2b5eSKamil Rytarowski 
77997206d57SZachary Turner Status NativeProcessNetBSD::ReinitializeThreads() {
7803eef2b5eSKamil Rytarowski   // Clear old threads
7813eef2b5eSKamil Rytarowski   m_threads.clear();
7823eef2b5eSKamil Rytarowski 
7833eef2b5eSKamil Rytarowski   // Initialize new thread
7843eef2b5eSKamil Rytarowski   struct ptrace_lwpinfo info = {};
78597206d57SZachary Turner   Status error = PtraceWrapper(PT_LWPINFO, GetID(), &info, sizeof(info));
7863eef2b5eSKamil Rytarowski   if (error.Fail()) {
7873eef2b5eSKamil Rytarowski     return error;
7883eef2b5eSKamil Rytarowski   }
7893eef2b5eSKamil Rytarowski   // Reinitialize from scratch threads and register them in process
7903eef2b5eSKamil Rytarowski   while (info.pl_lwpid != 0) {
791a5be48b3SPavel Labath     AddThread(info.pl_lwpid);
7923eef2b5eSKamil Rytarowski     error = PtraceWrapper(PT_LWPINFO, GetID(), &info, sizeof(info));
7933eef2b5eSKamil Rytarowski     if (error.Fail()) {
7943eef2b5eSKamil Rytarowski       return error;
7953eef2b5eSKamil Rytarowski     }
7963eef2b5eSKamil Rytarowski   }
7973eef2b5eSKamil Rytarowski 
7983eef2b5eSKamil Rytarowski   return error;
7993eef2b5eSKamil Rytarowski }
800