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)
143*b09bc8a2SMichal 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     }
198f07a9995SKamil Rytarowski   }
199f07a9995SKamil Rytarowski }
200f07a9995SKamil Rytarowski 
201f07a9995SKamil Rytarowski void NativeProcessNetBSD::MonitorSIGTRAP(lldb::pid_t pid) {
202f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
203f07a9995SKamil Rytarowski   ptrace_siginfo_t info;
204f07a9995SKamil Rytarowski 
205f07a9995SKamil Rytarowski   const auto siginfo_err =
206f07a9995SKamil Rytarowski       PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info));
207f07a9995SKamil Rytarowski 
208f07a9995SKamil Rytarowski   // Get details on the signal raised.
20936e23ecaSKamil Rytarowski   if (siginfo_err.Fail()) {
21036e23ecaSKamil Rytarowski     return;
21136e23ecaSKamil Rytarowski   }
21236e23ecaSKamil Rytarowski 
213f07a9995SKamil Rytarowski   switch (info.psi_siginfo.si_code) {
214f07a9995SKamil Rytarowski   case TRAP_BRKPT:
215a5be48b3SPavel Labath     for (const auto &thread : m_threads) {
216a5be48b3SPavel Labath       static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByBreakpoint();
217a5be48b3SPavel Labath       FixupBreakpointPCAsNeeded(static_cast<NativeThreadNetBSD &>(*thread));
218f07a9995SKamil Rytarowski     }
219f07a9995SKamil Rytarowski     SetState(StateType::eStateStopped, true);
220f07a9995SKamil Rytarowski     break;
2213eef2b5eSKamil Rytarowski   case TRAP_TRACE:
222a5be48b3SPavel Labath     for (const auto &thread : m_threads)
223a5be48b3SPavel Labath       static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByTrace();
2243eef2b5eSKamil Rytarowski     SetState(StateType::eStateStopped, true);
2253eef2b5eSKamil Rytarowski     break;
2263eef2b5eSKamil Rytarowski   case TRAP_EXEC: {
22797206d57SZachary Turner     Status error = ReinitializeThreads();
2283eef2b5eSKamil Rytarowski     if (error.Fail()) {
2293eef2b5eSKamil Rytarowski       SetState(StateType::eStateInvalid);
2303eef2b5eSKamil Rytarowski       return;
2313eef2b5eSKamil Rytarowski     }
2323eef2b5eSKamil Rytarowski 
2333eef2b5eSKamil Rytarowski     // Let our delegate know we have just exec'd.
2343eef2b5eSKamil Rytarowski     NotifyDidExec();
2353eef2b5eSKamil Rytarowski 
236a5be48b3SPavel Labath     for (const auto &thread : m_threads)
237a5be48b3SPavel Labath       static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByExec();
2383eef2b5eSKamil Rytarowski     SetState(StateType::eStateStopped, true);
2393eef2b5eSKamil Rytarowski   } break;
24036e23ecaSKamil Rytarowski   case TRAP_DBREG: {
241baf64b65SMichal Gorny     // Find the thread.
242baf64b65SMichal Gorny     NativeThreadNetBSD* thread = nullptr;
243baf64b65SMichal Gorny     for (const auto &t : m_threads) {
244baf64b65SMichal Gorny       if (t->GetID() == info.psi_lwpid) {
245baf64b65SMichal Gorny         thread = static_cast<NativeThreadNetBSD *>(t.get());
246baf64b65SMichal Gorny         break;
247baf64b65SMichal Gorny       }
248baf64b65SMichal Gorny     }
249baf64b65SMichal Gorny     if (!thread) {
250baf64b65SMichal Gorny       LLDB_LOG(log,
251baf64b65SMichal Gorny                "thread not found in m_threads, pid = {0}, LWP = {1}",
252baf64b65SMichal Gorny                GetID(), info.psi_lwpid);
253baf64b65SMichal Gorny       break;
254baf64b65SMichal Gorny     }
255baf64b65SMichal Gorny 
25636e23ecaSKamil Rytarowski     // If a watchpoint was hit, report it
257baf64b65SMichal Gorny     uint32_t wp_index = LLDB_INVALID_INDEX32;
258baf64b65SMichal Gorny     Status error = thread->GetRegisterContext().GetWatchpointHitIndex(
259a5be48b3SPavel Labath         wp_index, (uintptr_t)info.psi_siginfo.si_addr);
26036e23ecaSKamil Rytarowski     if (error.Fail())
26136e23ecaSKamil Rytarowski       LLDB_LOG(log,
26236e23ecaSKamil Rytarowski                "received error while checking for watchpoint hits, pid = "
26336e23ecaSKamil Rytarowski                "{0}, LWP = {1}, error = {2}",
26436e23ecaSKamil Rytarowski                GetID(), info.psi_lwpid, error);
26536e23ecaSKamil Rytarowski     if (wp_index != LLDB_INVALID_INDEX32) {
266a5be48b3SPavel Labath       for (const auto &thread : m_threads)
267a5be48b3SPavel Labath         static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByWatchpoint(
268a5be48b3SPavel Labath             wp_index);
26936e23ecaSKamil Rytarowski       SetState(StateType::eStateStopped, true);
27036e23ecaSKamil Rytarowski       break;
27136e23ecaSKamil Rytarowski     }
27236e23ecaSKamil Rytarowski 
27336e23ecaSKamil Rytarowski     // If a breakpoint was hit, report it
274baf64b65SMichal Gorny     uint32_t bp_index = LLDB_INVALID_INDEX32;
275baf64b65SMichal Gorny     error = thread->GetRegisterContext().GetHardwareBreakHitIndex(
276baf64b65SMichal Gorny         bp_index, (uintptr_t)info.psi_siginfo.si_addr);
27736e23ecaSKamil Rytarowski     if (error.Fail())
27836e23ecaSKamil Rytarowski       LLDB_LOG(log,
27936e23ecaSKamil Rytarowski                "received error while checking for hardware "
28036e23ecaSKamil Rytarowski                "breakpoint hits, pid = {0}, LWP = {1}, error = {2}",
28136e23ecaSKamil Rytarowski                GetID(), info.psi_lwpid, error);
28236e23ecaSKamil Rytarowski     if (bp_index != LLDB_INVALID_INDEX32) {
283a5be48b3SPavel Labath       for (const auto &thread : m_threads)
284a5be48b3SPavel Labath         static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByBreakpoint();
28536e23ecaSKamil Rytarowski       SetState(StateType::eStateStopped, true);
28636e23ecaSKamil Rytarowski       break;
28736e23ecaSKamil Rytarowski     }
28836e23ecaSKamil Rytarowski   } break;
289f07a9995SKamil Rytarowski   }
290f07a9995SKamil Rytarowski }
291f07a9995SKamil Rytarowski 
292f07a9995SKamil Rytarowski void NativeProcessNetBSD::MonitorSignal(lldb::pid_t pid, int signal) {
293f07a9995SKamil Rytarowski   ptrace_siginfo_t info;
294f07a9995SKamil Rytarowski   const auto siginfo_err =
295f07a9995SKamil Rytarowski       PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info));
296f07a9995SKamil Rytarowski 
297a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
298a5be48b3SPavel Labath     static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(
299f07a9995SKamil Rytarowski         info.psi_siginfo.si_signo, &info.psi_siginfo);
300f07a9995SKamil Rytarowski   }
301f07a9995SKamil Rytarowski   SetState(StateType::eStateStopped, true);
302f07a9995SKamil Rytarowski }
303f07a9995SKamil Rytarowski 
30497206d57SZachary Turner Status NativeProcessNetBSD::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
305f07a9995SKamil Rytarowski                                           int data, int *result) {
306f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
30797206d57SZachary Turner   Status error;
308f07a9995SKamil Rytarowski   int ret;
309f07a9995SKamil Rytarowski 
310f07a9995SKamil Rytarowski   errno = 0;
311f07a9995SKamil Rytarowski   ret = ptrace(req, static_cast<::pid_t>(pid), addr, data);
312f07a9995SKamil Rytarowski 
313f07a9995SKamil Rytarowski   if (ret == -1)
314f07a9995SKamil Rytarowski     error.SetErrorToErrno();
315f07a9995SKamil Rytarowski 
316f07a9995SKamil Rytarowski   if (result)
317f07a9995SKamil Rytarowski     *result = ret;
318f07a9995SKamil Rytarowski 
319f07a9995SKamil Rytarowski   LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3})={4:x}", req, pid, addr, data, ret);
320f07a9995SKamil Rytarowski 
321f07a9995SKamil Rytarowski   if (error.Fail())
322f07a9995SKamil Rytarowski     LLDB_LOG(log, "ptrace() failed: {0}", error);
323f07a9995SKamil Rytarowski 
324f07a9995SKamil Rytarowski   return error;
325f07a9995SKamil Rytarowski }
326f07a9995SKamil Rytarowski 
32797206d57SZachary Turner Status NativeProcessNetBSD::Resume(const ResumeActionList &resume_actions) {
328f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
329f07a9995SKamil Rytarowski   LLDB_LOG(log, "pid {0}", GetID());
330f07a9995SKamil Rytarowski 
331a5be48b3SPavel Labath   const auto &thread = m_threads[0];
332f07a9995SKamil Rytarowski   const ResumeAction *const action =
333a5be48b3SPavel Labath       resume_actions.GetActionForThread(thread->GetID(), true);
334f07a9995SKamil Rytarowski 
335f07a9995SKamil Rytarowski   if (action == nullptr) {
336f07a9995SKamil Rytarowski     LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
337a5be48b3SPavel Labath              thread->GetID());
33897206d57SZachary Turner     return Status();
339f07a9995SKamil Rytarowski   }
340f07a9995SKamil Rytarowski 
34197206d57SZachary Turner   Status error;
3423eef2b5eSKamil Rytarowski 
343f07a9995SKamil Rytarowski   switch (action->state) {
344f07a9995SKamil Rytarowski   case eStateRunning: {
345f07a9995SKamil Rytarowski     // Run the thread, possibly feeding it the signal.
3463eef2b5eSKamil Rytarowski     error = NativeProcessNetBSD::PtraceWrapper(PT_CONTINUE, GetID(), (void *)1,
3473eef2b5eSKamil Rytarowski                                                action->signal);
348f07a9995SKamil Rytarowski     if (!error.Success())
349f07a9995SKamil Rytarowski       return error;
350a5be48b3SPavel Labath     for (const auto &thread : m_threads)
351a5be48b3SPavel Labath       static_cast<NativeThreadNetBSD &>(*thread).SetRunning();
352f07a9995SKamil Rytarowski     SetState(eStateRunning, true);
353f07a9995SKamil Rytarowski     break;
354f07a9995SKamil Rytarowski   }
355f07a9995SKamil Rytarowski   case eStateStepping:
3563eef2b5eSKamil Rytarowski     // Run the thread, possibly feeding it the signal.
3573eef2b5eSKamil Rytarowski     error = NativeProcessNetBSD::PtraceWrapper(PT_STEP, GetID(), (void *)1,
3583eef2b5eSKamil Rytarowski                                                action->signal);
3593eef2b5eSKamil Rytarowski     if (!error.Success())
3603eef2b5eSKamil Rytarowski       return error;
361a5be48b3SPavel Labath     for (const auto &thread : m_threads)
362a5be48b3SPavel Labath       static_cast<NativeThreadNetBSD &>(*thread).SetStepping();
3633eef2b5eSKamil Rytarowski     SetState(eStateStepping, true);
364f07a9995SKamil Rytarowski     break;
365f07a9995SKamil Rytarowski 
366f07a9995SKamil Rytarowski   case eStateSuspended:
367f07a9995SKamil Rytarowski   case eStateStopped:
368f07a9995SKamil Rytarowski     llvm_unreachable("Unexpected state");
369f07a9995SKamil Rytarowski 
370f07a9995SKamil Rytarowski   default:
37197206d57SZachary Turner     return Status("NativeProcessNetBSD::%s (): unexpected state %s specified "
372f07a9995SKamil Rytarowski                   "for pid %" PRIu64 ", tid %" PRIu64,
373f07a9995SKamil Rytarowski                   __FUNCTION__, StateAsCString(action->state), GetID(),
374a5be48b3SPavel Labath                   thread->GetID());
375f07a9995SKamil Rytarowski   }
376f07a9995SKamil Rytarowski 
37797206d57SZachary Turner   return Status();
378f07a9995SKamil Rytarowski }
379f07a9995SKamil Rytarowski 
38097206d57SZachary Turner Status NativeProcessNetBSD::Halt() {
38197206d57SZachary Turner   Status error;
382f07a9995SKamil Rytarowski 
383f07a9995SKamil Rytarowski   if (kill(GetID(), SIGSTOP) != 0)
384f07a9995SKamil Rytarowski     error.SetErrorToErrno();
385f07a9995SKamil Rytarowski 
386f07a9995SKamil Rytarowski   return error;
387f07a9995SKamil Rytarowski }
388f07a9995SKamil Rytarowski 
38997206d57SZachary Turner Status NativeProcessNetBSD::Detach() {
39097206d57SZachary Turner   Status error;
391f07a9995SKamil Rytarowski 
392f07a9995SKamil Rytarowski   // Stop monitoring the inferior.
393f07a9995SKamil Rytarowski   m_sigchld_handle.reset();
394f07a9995SKamil Rytarowski 
395f07a9995SKamil Rytarowski   // Tell ptrace to detach from the process.
396f07a9995SKamil Rytarowski   if (GetID() == LLDB_INVALID_PROCESS_ID)
397f07a9995SKamil Rytarowski     return error;
398f07a9995SKamil Rytarowski 
399f07a9995SKamil Rytarowski   return PtraceWrapper(PT_DETACH, GetID());
400f07a9995SKamil Rytarowski }
401f07a9995SKamil Rytarowski 
40297206d57SZachary Turner Status NativeProcessNetBSD::Signal(int signo) {
40397206d57SZachary Turner   Status error;
404f07a9995SKamil Rytarowski 
405f07a9995SKamil Rytarowski   if (kill(GetID(), signo))
406f07a9995SKamil Rytarowski     error.SetErrorToErrno();
407f07a9995SKamil Rytarowski 
408f07a9995SKamil Rytarowski   return error;
409f07a9995SKamil Rytarowski }
410f07a9995SKamil Rytarowski 
41197206d57SZachary Turner Status NativeProcessNetBSD::Kill() {
412f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
413f07a9995SKamil Rytarowski   LLDB_LOG(log, "pid {0}", GetID());
414f07a9995SKamil Rytarowski 
41597206d57SZachary Turner   Status error;
416f07a9995SKamil Rytarowski 
417f07a9995SKamil Rytarowski   switch (m_state) {
418f07a9995SKamil Rytarowski   case StateType::eStateInvalid:
419f07a9995SKamil Rytarowski   case StateType::eStateExited:
420f07a9995SKamil Rytarowski   case StateType::eStateCrashed:
421f07a9995SKamil Rytarowski   case StateType::eStateDetached:
422f07a9995SKamil Rytarowski   case StateType::eStateUnloaded:
423f07a9995SKamil Rytarowski     // Nothing to do - the process is already dead.
424f07a9995SKamil Rytarowski     LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
425f07a9995SKamil Rytarowski              StateAsCString(m_state));
426f07a9995SKamil Rytarowski     return error;
427f07a9995SKamil Rytarowski 
428f07a9995SKamil Rytarowski   case StateType::eStateConnected:
429f07a9995SKamil Rytarowski   case StateType::eStateAttaching:
430f07a9995SKamil Rytarowski   case StateType::eStateLaunching:
431f07a9995SKamil Rytarowski   case StateType::eStateStopped:
432f07a9995SKamil Rytarowski   case StateType::eStateRunning:
433f07a9995SKamil Rytarowski   case StateType::eStateStepping:
434f07a9995SKamil Rytarowski   case StateType::eStateSuspended:
435f07a9995SKamil Rytarowski     // We can try to kill a process in these states.
436f07a9995SKamil Rytarowski     break;
437f07a9995SKamil Rytarowski   }
438f07a9995SKamil Rytarowski 
439f07a9995SKamil Rytarowski   if (kill(GetID(), SIGKILL) != 0) {
440f07a9995SKamil Rytarowski     error.SetErrorToErrno();
441f07a9995SKamil Rytarowski     return error;
442f07a9995SKamil Rytarowski   }
443f07a9995SKamil Rytarowski 
444f07a9995SKamil Rytarowski   return error;
445f07a9995SKamil Rytarowski }
446f07a9995SKamil Rytarowski 
44797206d57SZachary Turner Status NativeProcessNetBSD::GetMemoryRegionInfo(lldb::addr_t load_addr,
448f07a9995SKamil Rytarowski                                                 MemoryRegionInfo &range_info) {
449f07a9995SKamil Rytarowski 
450f07a9995SKamil Rytarowski   if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
451f07a9995SKamil Rytarowski     // We're done.
45297206d57SZachary Turner     return Status("unsupported");
453f07a9995SKamil Rytarowski   }
454f07a9995SKamil Rytarowski 
45597206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
456f07a9995SKamil Rytarowski   if (error.Fail()) {
457f07a9995SKamil Rytarowski     return error;
458f07a9995SKamil Rytarowski   }
459f07a9995SKamil Rytarowski 
460f07a9995SKamil Rytarowski   lldb::addr_t prev_base_address = 0;
461f07a9995SKamil Rytarowski   // FIXME start by finding the last region that is <= target address using
462f07a9995SKamil Rytarowski   // binary search.  Data is sorted.
463f07a9995SKamil Rytarowski   // There can be a ton of regions on pthreads apps with lots of threads.
464f07a9995SKamil Rytarowski   for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
465f07a9995SKamil Rytarowski        ++it) {
466f07a9995SKamil Rytarowski     MemoryRegionInfo &proc_entry_info = it->first;
467f07a9995SKamil Rytarowski     // Sanity check assumption that memory map entries are ascending.
468f07a9995SKamil Rytarowski     assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
469f07a9995SKamil Rytarowski            "descending memory map entries detected, unexpected");
470f07a9995SKamil Rytarowski     prev_base_address = proc_entry_info.GetRange().GetRangeBase();
471f07a9995SKamil Rytarowski     UNUSED_IF_ASSERT_DISABLED(prev_base_address);
47205097246SAdrian Prantl     // If the target address comes before this entry, indicate distance to next
47305097246SAdrian Prantl     // region.
474f07a9995SKamil Rytarowski     if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
475f07a9995SKamil Rytarowski       range_info.GetRange().SetRangeBase(load_addr);
476f07a9995SKamil Rytarowski       range_info.GetRange().SetByteSize(
477f07a9995SKamil Rytarowski           proc_entry_info.GetRange().GetRangeBase() - load_addr);
478f07a9995SKamil Rytarowski       range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
479f07a9995SKamil Rytarowski       range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
480f07a9995SKamil Rytarowski       range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
481f07a9995SKamil Rytarowski       range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
482f07a9995SKamil Rytarowski       return error;
483f07a9995SKamil Rytarowski     } else if (proc_entry_info.GetRange().Contains(load_addr)) {
484f07a9995SKamil Rytarowski       // The target address is within the memory region we're processing here.
485f07a9995SKamil Rytarowski       range_info = proc_entry_info;
486f07a9995SKamil Rytarowski       return error;
487f07a9995SKamil Rytarowski     }
488f07a9995SKamil Rytarowski     // The target memory address comes somewhere after the region we just
489f07a9995SKamil Rytarowski     // parsed.
490f07a9995SKamil Rytarowski   }
491f07a9995SKamil Rytarowski   // If we made it here, we didn't find an entry that contained the given
49205097246SAdrian Prantl   // address. Return the load_addr as start and the amount of bytes betwwen
49305097246SAdrian Prantl   // load address and the end of the memory as size.
494f07a9995SKamil Rytarowski   range_info.GetRange().SetRangeBase(load_addr);
495f07a9995SKamil Rytarowski   range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
496f07a9995SKamil Rytarowski   range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
497f07a9995SKamil Rytarowski   range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
498f07a9995SKamil Rytarowski   range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
499f07a9995SKamil Rytarowski   range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
500f07a9995SKamil Rytarowski   return error;
501f07a9995SKamil Rytarowski }
502f07a9995SKamil Rytarowski 
50397206d57SZachary Turner Status NativeProcessNetBSD::PopulateMemoryRegionCache() {
504f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
505f07a9995SKamil Rytarowski   // If our cache is empty, pull the latest.  There should always be at least
506f07a9995SKamil Rytarowski   // one memory region if memory region handling is supported.
507f07a9995SKamil Rytarowski   if (!m_mem_region_cache.empty()) {
508f07a9995SKamil Rytarowski     LLDB_LOG(log, "reusing {0} cached memory region entries",
509f07a9995SKamil Rytarowski              m_mem_region_cache.size());
51097206d57SZachary Turner     return Status();
511f07a9995SKamil Rytarowski   }
512f07a9995SKamil Rytarowski 
513f07a9995SKamil Rytarowski   struct kinfo_vmentry *vm;
514f07a9995SKamil Rytarowski   size_t count, i;
515f07a9995SKamil Rytarowski   vm = kinfo_getvmmap(GetID(), &count);
516f07a9995SKamil Rytarowski   if (vm == NULL) {
517f07a9995SKamil Rytarowski     m_supports_mem_region = LazyBool::eLazyBoolNo;
51897206d57SZachary Turner     Status error;
519f07a9995SKamil Rytarowski     error.SetErrorString("not supported");
520f07a9995SKamil Rytarowski     return error;
521f07a9995SKamil Rytarowski   }
522f07a9995SKamil Rytarowski   for (i = 0; i < count; i++) {
523f07a9995SKamil Rytarowski     MemoryRegionInfo info;
524f07a9995SKamil Rytarowski     info.Clear();
525f07a9995SKamil Rytarowski     info.GetRange().SetRangeBase(vm[i].kve_start);
526f07a9995SKamil Rytarowski     info.GetRange().SetRangeEnd(vm[i].kve_end);
527f07a9995SKamil Rytarowski     info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
528f07a9995SKamil Rytarowski 
529f07a9995SKamil Rytarowski     if (vm[i].kve_protection & VM_PROT_READ)
530f07a9995SKamil Rytarowski       info.SetReadable(MemoryRegionInfo::OptionalBool::eYes);
531f07a9995SKamil Rytarowski     else
532f07a9995SKamil Rytarowski       info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
533f07a9995SKamil Rytarowski 
534f07a9995SKamil Rytarowski     if (vm[i].kve_protection & VM_PROT_WRITE)
535f07a9995SKamil Rytarowski       info.SetWritable(MemoryRegionInfo::OptionalBool::eYes);
536f07a9995SKamil Rytarowski     else
537f07a9995SKamil Rytarowski       info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
538f07a9995SKamil Rytarowski 
539f07a9995SKamil Rytarowski     if (vm[i].kve_protection & VM_PROT_EXECUTE)
540f07a9995SKamil Rytarowski       info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes);
541f07a9995SKamil Rytarowski     else
542f07a9995SKamil Rytarowski       info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
543f07a9995SKamil Rytarowski 
544f07a9995SKamil Rytarowski     if (vm[i].kve_path[0])
545f07a9995SKamil Rytarowski       info.SetName(vm[i].kve_path);
546f07a9995SKamil Rytarowski 
547f07a9995SKamil Rytarowski     m_mem_region_cache.emplace_back(
548a0a44e9cSKamil Rytarowski         info, FileSpec(info.GetName().GetCString()));
549f07a9995SKamil Rytarowski   }
550f07a9995SKamil Rytarowski   free(vm);
551f07a9995SKamil Rytarowski 
552f07a9995SKamil Rytarowski   if (m_mem_region_cache.empty()) {
55305097246SAdrian Prantl     // No entries after attempting to read them.  This shouldn't happen. Assume
55405097246SAdrian Prantl     // we don't support map entries.
555f07a9995SKamil Rytarowski     LLDB_LOG(log, "failed to find any vmmap entries, assuming no support "
556f07a9995SKamil Rytarowski                   "for memory region metadata retrieval");
557f07a9995SKamil Rytarowski     m_supports_mem_region = LazyBool::eLazyBoolNo;
55897206d57SZachary Turner     Status error;
559f07a9995SKamil Rytarowski     error.SetErrorString("not supported");
560f07a9995SKamil Rytarowski     return error;
561f07a9995SKamil Rytarowski   }
562f07a9995SKamil Rytarowski   LLDB_LOG(log, "read {0} memory region entries from process {1}",
563f07a9995SKamil Rytarowski            m_mem_region_cache.size(), GetID());
564f07a9995SKamil Rytarowski   // We support memory retrieval, remember that.
565f07a9995SKamil Rytarowski   m_supports_mem_region = LazyBool::eLazyBoolYes;
56697206d57SZachary Turner   return Status();
567f07a9995SKamil Rytarowski }
568f07a9995SKamil Rytarowski 
56997206d57SZachary Turner Status NativeProcessNetBSD::AllocateMemory(size_t size, uint32_t permissions,
570f07a9995SKamil Rytarowski                                            lldb::addr_t &addr) {
57197206d57SZachary Turner   return Status("Unimplemented");
572f07a9995SKamil Rytarowski }
573f07a9995SKamil Rytarowski 
57497206d57SZachary Turner Status NativeProcessNetBSD::DeallocateMemory(lldb::addr_t addr) {
57597206d57SZachary Turner   return Status("Unimplemented");
576f07a9995SKamil Rytarowski }
577f07a9995SKamil Rytarowski 
578f07a9995SKamil Rytarowski lldb::addr_t NativeProcessNetBSD::GetSharedLibraryInfoAddress() {
579f07a9995SKamil Rytarowski   // punt on this for now
580f07a9995SKamil Rytarowski   return LLDB_INVALID_ADDRESS;
581f07a9995SKamil Rytarowski }
582f07a9995SKamil Rytarowski 
583f07a9995SKamil Rytarowski size_t NativeProcessNetBSD::UpdateThreads() { return m_threads.size(); }
584f07a9995SKamil Rytarowski 
58597206d57SZachary Turner Status NativeProcessNetBSD::SetBreakpoint(lldb::addr_t addr, uint32_t size,
586f07a9995SKamil Rytarowski                                           bool hardware) {
587f07a9995SKamil Rytarowski   if (hardware)
58897206d57SZachary Turner     return Status("NativeProcessNetBSD does not support hardware breakpoints");
589f07a9995SKamil Rytarowski   else
590f07a9995SKamil Rytarowski     return SetSoftwareBreakpoint(addr, size);
591f07a9995SKamil Rytarowski }
592f07a9995SKamil Rytarowski 
59397206d57SZachary Turner Status NativeProcessNetBSD::GetLoadedModuleFileSpec(const char *module_path,
594f07a9995SKamil Rytarowski                                                     FileSpec &file_spec) {
59597206d57SZachary Turner   return Status("Unimplemented");
596f07a9995SKamil Rytarowski }
597f07a9995SKamil Rytarowski 
59897206d57SZachary Turner Status NativeProcessNetBSD::GetFileLoadAddress(const llvm::StringRef &file_name,
599f07a9995SKamil Rytarowski                                                lldb::addr_t &load_addr) {
600f07a9995SKamil Rytarowski   load_addr = LLDB_INVALID_ADDRESS;
60197206d57SZachary Turner   return Status();
602f07a9995SKamil Rytarowski }
603f07a9995SKamil Rytarowski 
604f07a9995SKamil Rytarowski void NativeProcessNetBSD::SigchldHandler() {
605f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
606f07a9995SKamil Rytarowski   // Process all pending waitpid notifications.
607f07a9995SKamil Rytarowski   int status;
608c1a6b128SPavel Labath   ::pid_t wait_pid =
609c1a6b128SPavel Labath       llvm::sys::RetryAfterSignal(-1, waitpid, GetID(), &status, WALLSIG | WNOHANG);
610f07a9995SKamil Rytarowski 
611f07a9995SKamil Rytarowski   if (wait_pid == 0)
612f07a9995SKamil Rytarowski     return; // We are done.
613f07a9995SKamil Rytarowski 
614f07a9995SKamil Rytarowski   if (wait_pid == -1) {
61597206d57SZachary Turner     Status error(errno, eErrorTypePOSIX);
616f07a9995SKamil Rytarowski     LLDB_LOG(log, "waitpid ({0}, &status, _) failed: {1}", GetID(), error);
617f07a9995SKamil Rytarowski   }
618f07a9995SKamil Rytarowski 
6193508fc8cSPavel Labath   WaitStatus wait_status = WaitStatus::Decode(status);
6203508fc8cSPavel Labath   bool exited = wait_status.type == WaitStatus::Exit ||
6213508fc8cSPavel Labath                 (wait_status.type == WaitStatus::Signal &&
6223508fc8cSPavel Labath                  wait_pid == static_cast<::pid_t>(GetID()));
623f07a9995SKamil Rytarowski 
624f07a9995SKamil Rytarowski   LLDB_LOG(log,
6253508fc8cSPavel Labath            "waitpid ({0}, &status, _) => pid = {1}, status = {2}, exited = {3}",
6263508fc8cSPavel Labath            GetID(), wait_pid, status, exited);
627f07a9995SKamil Rytarowski 
628f07a9995SKamil Rytarowski   if (exited)
6293508fc8cSPavel Labath     MonitorExited(wait_pid, wait_status);
6303508fc8cSPavel Labath   else {
6314bb74415SKamil Rytarowski     assert(wait_status.type == WaitStatus::Stop);
6323508fc8cSPavel Labath     MonitorCallback(wait_pid, wait_status.status);
6333508fc8cSPavel Labath   }
634f07a9995SKamil Rytarowski }
635f07a9995SKamil Rytarowski 
636269eec03SKamil Rytarowski bool NativeProcessNetBSD::HasThreadNoLock(lldb::tid_t thread_id) {
637a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
638a5be48b3SPavel Labath     assert(thread && "thread list should not contain NULL threads");
639a5be48b3SPavel Labath     if (thread->GetID() == thread_id) {
640269eec03SKamil Rytarowski       // We have this thread.
641269eec03SKamil Rytarowski       return true;
642269eec03SKamil Rytarowski     }
643269eec03SKamil Rytarowski   }
644269eec03SKamil Rytarowski 
645269eec03SKamil Rytarowski   // We don't have this thread.
646269eec03SKamil Rytarowski   return false;
647269eec03SKamil Rytarowski }
648269eec03SKamil Rytarowski 
649a5be48b3SPavel Labath NativeThreadNetBSD &NativeProcessNetBSD::AddThread(lldb::tid_t thread_id) {
650f07a9995SKamil Rytarowski 
651f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
652f07a9995SKamil Rytarowski   LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
653f07a9995SKamil Rytarowski 
654f07a9995SKamil Rytarowski   assert(!HasThreadNoLock(thread_id) &&
655f07a9995SKamil Rytarowski          "attempted to add a thread by id that already exists");
656f07a9995SKamil Rytarowski 
657f07a9995SKamil Rytarowski   // If this is the first thread, save it as the current thread
658f07a9995SKamil Rytarowski   if (m_threads.empty())
659f07a9995SKamil Rytarowski     SetCurrentThreadID(thread_id);
660f07a9995SKamil Rytarowski 
661a5be48b3SPavel Labath   m_threads.push_back(llvm::make_unique<NativeThreadNetBSD>(*this, thread_id));
662a5be48b3SPavel Labath   return static_cast<NativeThreadNetBSD &>(*m_threads.back());
663f07a9995SKamil Rytarowski }
664f07a9995SKamil Rytarowski 
66596e600fcSPavel Labath Status NativeProcessNetBSD::Attach() {
666f07a9995SKamil Rytarowski   // Attach to the requested process.
667f07a9995SKamil Rytarowski   // An attach will cause the thread to stop with a SIGSTOP.
66896e600fcSPavel Labath   Status status = PtraceWrapper(PT_ATTACH, m_pid);
66996e600fcSPavel Labath   if (status.Fail())
67096e600fcSPavel Labath     return status;
671f07a9995SKamil Rytarowski 
67296e600fcSPavel Labath   int wstatus;
67305097246SAdrian Prantl   // Need to use WALLSIG otherwise we receive an error with errno=ECHLD At this
67405097246SAdrian Prantl   // point we should have a thread stopped if waitpid succeeds.
6752819136fSMichal Gorny   if ((wstatus = llvm::sys::RetryAfterSignal(-1, waitpid,
676c5d7bc86SMichal Gorny           m_pid, nullptr, WALLSIG)) < 0)
67796e600fcSPavel Labath     return Status(errno, eErrorTypePOSIX);
678f07a9995SKamil Rytarowski 
679f07a9995SKamil Rytarowski   /* Initialize threads */
68096e600fcSPavel Labath   status = ReinitializeThreads();
68196e600fcSPavel Labath   if (status.Fail())
68296e600fcSPavel Labath     return status;
683f07a9995SKamil Rytarowski 
684a5be48b3SPavel Labath   for (const auto &thread : m_threads)
685a5be48b3SPavel Labath     static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(SIGSTOP);
68636e23ecaSKamil Rytarowski 
687f07a9995SKamil Rytarowski   // Let our process instance know the thread has stopped.
688f07a9995SKamil Rytarowski   SetState(StateType::eStateStopped);
68996e600fcSPavel Labath   return Status();
690f07a9995SKamil Rytarowski }
691f07a9995SKamil Rytarowski 
69297206d57SZachary Turner Status NativeProcessNetBSD::ReadMemory(lldb::addr_t addr, void *buf,
69397206d57SZachary Turner                                        size_t size, size_t &bytes_read) {
694f07a9995SKamil Rytarowski   unsigned char *dst = static_cast<unsigned char *>(buf);
695f07a9995SKamil Rytarowski   struct ptrace_io_desc io;
696f07a9995SKamil Rytarowski 
697f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
698f07a9995SKamil Rytarowski   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
699f07a9995SKamil Rytarowski 
700f07a9995SKamil Rytarowski   bytes_read = 0;
701f07a9995SKamil Rytarowski   io.piod_op = PIOD_READ_D;
702f07a9995SKamil Rytarowski   io.piod_len = size;
703f07a9995SKamil Rytarowski 
704f07a9995SKamil Rytarowski   do {
705f07a9995SKamil Rytarowski     io.piod_offs = (void *)(addr + bytes_read);
706f07a9995SKamil Rytarowski     io.piod_addr = dst + bytes_read;
707f07a9995SKamil Rytarowski 
70897206d57SZachary Turner     Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
709d14a0de9SMichal Gorny     if (error.Fail() || io.piod_len == 0)
710f07a9995SKamil Rytarowski       return error;
711f07a9995SKamil Rytarowski 
712d14a0de9SMichal Gorny     bytes_read += io.piod_len;
713f07a9995SKamil Rytarowski     io.piod_len = size - bytes_read;
714f07a9995SKamil Rytarowski   } while (bytes_read < size);
715f07a9995SKamil Rytarowski 
71697206d57SZachary Turner   return Status();
717f07a9995SKamil Rytarowski }
718f07a9995SKamil Rytarowski 
71997206d57SZachary Turner Status NativeProcessNetBSD::WriteMemory(lldb::addr_t addr, const void *buf,
720f07a9995SKamil Rytarowski                                         size_t size, size_t &bytes_written) {
721f07a9995SKamil Rytarowski   const unsigned char *src = static_cast<const unsigned char *>(buf);
72297206d57SZachary Turner   Status error;
723f07a9995SKamil Rytarowski   struct ptrace_io_desc io;
724f07a9995SKamil Rytarowski 
725f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
726f07a9995SKamil Rytarowski   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
727f07a9995SKamil Rytarowski 
728f07a9995SKamil Rytarowski   bytes_written = 0;
729f07a9995SKamil Rytarowski   io.piod_op = PIOD_WRITE_D;
730f07a9995SKamil Rytarowski   io.piod_len = size;
731f07a9995SKamil Rytarowski 
732f07a9995SKamil Rytarowski   do {
733269eec03SKamil Rytarowski     io.piod_addr = const_cast<void *>(static_cast<const void *>(src + bytes_written));
734f07a9995SKamil Rytarowski     io.piod_offs = (void *)(addr + bytes_written);
735f07a9995SKamil Rytarowski 
73697206d57SZachary Turner     Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
737d14a0de9SMichal Gorny     if (error.Fail() || io.piod_len == 0)
738f07a9995SKamil Rytarowski       return error;
739f07a9995SKamil Rytarowski 
740d14a0de9SMichal Gorny     bytes_written += io.piod_len;
741f07a9995SKamil Rytarowski     io.piod_len = size - bytes_written;
742f07a9995SKamil Rytarowski   } while (bytes_written < size);
743f07a9995SKamil Rytarowski 
744f07a9995SKamil Rytarowski   return error;
745f07a9995SKamil Rytarowski }
746f07a9995SKamil Rytarowski 
747f07a9995SKamil Rytarowski llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
748f07a9995SKamil Rytarowski NativeProcessNetBSD::GetAuxvData() const {
749f07a9995SKamil Rytarowski   /*
750f07a9995SKamil Rytarowski    * ELF_AUX_ENTRIES is currently restricted to kernel
751f07a9995SKamil Rytarowski    * (<sys/exec_elf.h> r. 1.155 specifies 15)
752f07a9995SKamil Rytarowski    *
753f07a9995SKamil Rytarowski    * ptrace(2) returns the whole AUXV including extra fiels after AT_NULL this
754f07a9995SKamil Rytarowski    * information isn't needed.
755f07a9995SKamil Rytarowski    */
756f07a9995SKamil Rytarowski   size_t auxv_size = 100 * sizeof(AuxInfo);
757f07a9995SKamil Rytarowski 
758e831bb3cSPavel Labath   ErrorOr<std::unique_ptr<WritableMemoryBuffer>> buf =
759dbda2851SPavel Labath       llvm::WritableMemoryBuffer::getNewMemBuffer(auxv_size);
760f07a9995SKamil Rytarowski 
761269eec03SKamil Rytarowski   struct ptrace_io_desc io;
762269eec03SKamil Rytarowski   io.piod_op = PIOD_READ_AUXV;
763269eec03SKamil Rytarowski   io.piod_offs = 0;
764e831bb3cSPavel Labath   io.piod_addr = static_cast<void *>(buf.get()->getBufferStart());
765269eec03SKamil Rytarowski   io.piod_len = auxv_size;
766f07a9995SKamil Rytarowski 
76797206d57SZachary Turner   Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
768f07a9995SKamil Rytarowski 
769f07a9995SKamil Rytarowski   if (error.Fail())
770f07a9995SKamil Rytarowski     return std::error_code(error.GetError(), std::generic_category());
771f07a9995SKamil Rytarowski 
772f07a9995SKamil Rytarowski   if (io.piod_len < 1)
773f07a9995SKamil Rytarowski     return std::error_code(ECANCELED, std::generic_category());
774f07a9995SKamil Rytarowski 
775e831bb3cSPavel Labath   return std::move(buf);
776f07a9995SKamil Rytarowski }
7773eef2b5eSKamil Rytarowski 
77897206d57SZachary Turner Status NativeProcessNetBSD::ReinitializeThreads() {
7793eef2b5eSKamil Rytarowski   // Clear old threads
7803eef2b5eSKamil Rytarowski   m_threads.clear();
7813eef2b5eSKamil Rytarowski 
7823eef2b5eSKamil Rytarowski   // Initialize new thread
7833eef2b5eSKamil Rytarowski   struct ptrace_lwpinfo info = {};
78497206d57SZachary Turner   Status error = PtraceWrapper(PT_LWPINFO, GetID(), &info, sizeof(info));
7853eef2b5eSKamil Rytarowski   if (error.Fail()) {
7863eef2b5eSKamil Rytarowski     return error;
7873eef2b5eSKamil Rytarowski   }
7883eef2b5eSKamil Rytarowski   // Reinitialize from scratch threads and register them in process
7893eef2b5eSKamil Rytarowski   while (info.pl_lwpid != 0) {
790a5be48b3SPavel Labath     AddThread(info.pl_lwpid);
7913eef2b5eSKamil Rytarowski     error = PtraceWrapper(PT_LWPINFO, GetID(), &info, sizeof(info));
7923eef2b5eSKamil Rytarowski     if (error.Fail()) {
7933eef2b5eSKamil Rytarowski       return error;
7943eef2b5eSKamil Rytarowski     }
7953eef2b5eSKamil Rytarowski   }
7963eef2b5eSKamil Rytarowski 
7973eef2b5eSKamil Rytarowski   return error;
7983eef2b5eSKamil Rytarowski }
799