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 #include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
13f07a9995SKamil Rytarowski #include "lldb/Host/HostProcess.h"
14f07a9995SKamil Rytarowski #include "lldb/Host/common/NativeRegisterContext.h"
15f07a9995SKamil Rytarowski #include "lldb/Host/posix/ProcessLauncherPosixFork.h"
16f07a9995SKamil Rytarowski #include "lldb/Target/Process.h"
17d821c997SPavel Labath #include "lldb/Utility/State.h"
18c1a6b128SPavel Labath #include "llvm/Support/Errno.h"
191a3d19ddSKamil Rytarowski 
201a3d19ddSKamil Rytarowski // System includes - They have to be included after framework includes because
2105097246SAdrian Prantl // they define some macros which collide with variable names in other modules
22f07a9995SKamil Rytarowski // clang-format off
23f07a9995SKamil Rytarowski #include <sys/types.h>
24f07a9995SKamil Rytarowski #include <sys/ptrace.h>
25f07a9995SKamil Rytarowski #include <sys/sysctl.h>
26f07a9995SKamil Rytarowski #include <sys/wait.h>
27f07a9995SKamil Rytarowski #include <uvm/uvm_prot.h>
28f07a9995SKamil Rytarowski #include <elf.h>
29f07a9995SKamil Rytarowski #include <util.h>
30f07a9995SKamil Rytarowski // clang-format on
311a3d19ddSKamil Rytarowski 
321a3d19ddSKamil Rytarowski using namespace lldb;
331a3d19ddSKamil Rytarowski using namespace lldb_private;
341a3d19ddSKamil Rytarowski using namespace lldb_private::process_netbsd;
351a3d19ddSKamil Rytarowski using namespace llvm;
361a3d19ddSKamil Rytarowski 
37f07a9995SKamil Rytarowski // Simple helper function to ensure flags are enabled on the given file
38f07a9995SKamil Rytarowski // descriptor.
3997206d57SZachary Turner static Status EnsureFDFlags(int fd, int flags) {
4097206d57SZachary Turner   Status error;
41f07a9995SKamil Rytarowski 
42f07a9995SKamil Rytarowski   int status = fcntl(fd, F_GETFL);
43f07a9995SKamil Rytarowski   if (status == -1) {
44f07a9995SKamil Rytarowski     error.SetErrorToErrno();
45f07a9995SKamil Rytarowski     return error;
46f07a9995SKamil Rytarowski   }
47f07a9995SKamil Rytarowski 
48f07a9995SKamil Rytarowski   if (fcntl(fd, F_SETFL, status | flags) == -1) {
49f07a9995SKamil Rytarowski     error.SetErrorToErrno();
50f07a9995SKamil Rytarowski     return error;
51f07a9995SKamil Rytarowski   }
52f07a9995SKamil Rytarowski 
53f07a9995SKamil Rytarowski   return error;
54f07a9995SKamil Rytarowski }
55f07a9995SKamil Rytarowski 
561a3d19ddSKamil Rytarowski // Public Static Methods
571a3d19ddSKamil Rytarowski 
5882abefa4SPavel Labath llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
5996e600fcSPavel Labath NativeProcessNetBSD::Factory::Launch(ProcessLaunchInfo &launch_info,
6096e600fcSPavel Labath                                      NativeDelegate &native_delegate,
6196e600fcSPavel Labath                                      MainLoop &mainloop) const {
62f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
63f07a9995SKamil Rytarowski 
6496e600fcSPavel Labath   Status status;
6596e600fcSPavel Labath   ::pid_t pid = ProcessLauncherPosixFork()
6696e600fcSPavel Labath                     .LaunchProcess(launch_info, status)
6796e600fcSPavel Labath                     .GetProcessId();
6896e600fcSPavel Labath   LLDB_LOG(log, "pid = {0:x}", pid);
6996e600fcSPavel Labath   if (status.Fail()) {
7096e600fcSPavel Labath     LLDB_LOG(log, "failed to launch process: {0}", status);
7196e600fcSPavel Labath     return status.ToError();
72f07a9995SKamil Rytarowski   }
73f07a9995SKamil Rytarowski 
7496e600fcSPavel Labath   // Wait for the child process to trap on its call to execve.
7596e600fcSPavel Labath   int wstatus;
7696e600fcSPavel Labath   ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0);
7796e600fcSPavel Labath   assert(wpid == pid);
7896e600fcSPavel Labath   (void)wpid;
7996e600fcSPavel Labath   if (!WIFSTOPPED(wstatus)) {
8096e600fcSPavel Labath     LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}",
8196e600fcSPavel Labath              WaitStatus::Decode(wstatus));
8296e600fcSPavel Labath     return llvm::make_error<StringError>("Could not sync with inferior process",
8396e600fcSPavel Labath                                          llvm::inconvertibleErrorCode());
8496e600fcSPavel Labath   }
8596e600fcSPavel Labath   LLDB_LOG(log, "inferior started, now in stopped state");
86f07a9995SKamil Rytarowski 
8736e82208SPavel Labath   ProcessInstanceInfo Info;
8836e82208SPavel Labath   if (!Host::GetProcessInfo(pid, Info)) {
8936e82208SPavel Labath     return llvm::make_error<StringError>("Cannot get process architecture",
9036e82208SPavel Labath                                          llvm::inconvertibleErrorCode());
9136e82208SPavel Labath   }
9296e600fcSPavel Labath 
9396e600fcSPavel Labath   // Set the architecture to the exe architecture.
9496e600fcSPavel Labath   LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid,
9536e82208SPavel Labath            Info.GetArchitecture().GetArchitectureName());
9696e600fcSPavel Labath 
9782abefa4SPavel Labath   std::unique_ptr<NativeProcessNetBSD> process_up(new NativeProcessNetBSD(
9896e600fcSPavel Labath       pid, launch_info.GetPTY().ReleaseMasterFileDescriptor(), native_delegate,
9936e82208SPavel Labath       Info.GetArchitecture(), mainloop));
10096e600fcSPavel Labath 
101*8d9400b6SMichał Górny   // Enable event reporting
102*8d9400b6SMichał Górny   ptrace_event_t events;
103*8d9400b6SMichał Górny   status = PtraceWrapper(PT_GET_EVENT_MASK, pid, &events, sizeof(events));
104*8d9400b6SMichał Górny   if (status.Fail())
105*8d9400b6SMichał Górny     return status.ToError();
106*8d9400b6SMichał Górny   // TODO: PTRACE_FORK | PTRACE_VFORK | PTRACE_POSIX_SPAWN?
107*8d9400b6SMichał Górny   events.pe_set_event |= PTRACE_LWP_CREATE | PTRACE_LWP_EXIT;
108*8d9400b6SMichał Górny   status = PtraceWrapper(PT_SET_EVENT_MASK, pid, &events, sizeof(events));
109*8d9400b6SMichał Górny   if (status.Fail())
110*8d9400b6SMichał Górny     return status.ToError();
111*8d9400b6SMichał Górny 
11282abefa4SPavel Labath   status = process_up->ReinitializeThreads();
11396e600fcSPavel Labath   if (status.Fail())
11496e600fcSPavel Labath     return status.ToError();
11596e600fcSPavel Labath 
116a5be48b3SPavel Labath   for (const auto &thread : process_up->m_threads)
117a5be48b3SPavel Labath     static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(SIGSTOP);
1188a4bf06bSKamil Rytarowski   process_up->SetState(StateType::eStateStopped, false);
11996e600fcSPavel Labath 
12082abefa4SPavel Labath   return std::move(process_up);
121f07a9995SKamil Rytarowski }
122f07a9995SKamil Rytarowski 
12382abefa4SPavel Labath llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
12482abefa4SPavel Labath NativeProcessNetBSD::Factory::Attach(
1251a3d19ddSKamil Rytarowski     lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
12696e600fcSPavel Labath     MainLoop &mainloop) const {
127f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
128f07a9995SKamil Rytarowski   LLDB_LOG(log, "pid = {0:x}", pid);
129f07a9995SKamil Rytarowski 
130f07a9995SKamil Rytarowski   // Retrieve the architecture for the running process.
13136e82208SPavel Labath   ProcessInstanceInfo Info;
13236e82208SPavel Labath   if (!Host::GetProcessInfo(pid, Info)) {
13336e82208SPavel Labath     return llvm::make_error<StringError>("Cannot get process architecture",
13436e82208SPavel Labath                                          llvm::inconvertibleErrorCode());
13536e82208SPavel Labath   }
136f07a9995SKamil Rytarowski 
13736e82208SPavel Labath   std::unique_ptr<NativeProcessNetBSD> process_up(new NativeProcessNetBSD(
13836e82208SPavel Labath       pid, -1, native_delegate, Info.GetArchitecture(), mainloop));
139f07a9995SKamil Rytarowski 
14002d4e50eSPavel Labath   Status status = process_up->Attach();
14196e600fcSPavel Labath   if (!status.Success())
14296e600fcSPavel Labath     return status.ToError();
143f07a9995SKamil Rytarowski 
14482abefa4SPavel Labath   return std::move(process_up);
1451a3d19ddSKamil Rytarowski }
1461a3d19ddSKamil Rytarowski 
1471a3d19ddSKamil Rytarowski // Public Instance Methods
1481a3d19ddSKamil Rytarowski 
14996e600fcSPavel Labath NativeProcessNetBSD::NativeProcessNetBSD(::pid_t pid, int terminal_fd,
15096e600fcSPavel Labath                                          NativeDelegate &delegate,
15196e600fcSPavel Labath                                          const ArchSpec &arch,
15296e600fcSPavel Labath                                          MainLoop &mainloop)
153b09bc8a2SMichal Gorny     : NativeProcessELF(pid, terminal_fd, delegate), m_arch(arch) {
15496e600fcSPavel Labath   if (m_terminal_fd != -1) {
15596e600fcSPavel Labath     Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
15696e600fcSPavel Labath     assert(status.Success());
15796e600fcSPavel Labath   }
15896e600fcSPavel Labath 
15996e600fcSPavel Labath   Status status;
16096e600fcSPavel Labath   m_sigchld_handle = mainloop.RegisterSignal(
16196e600fcSPavel Labath       SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status);
16296e600fcSPavel Labath   assert(m_sigchld_handle && status.Success());
16396e600fcSPavel Labath }
164f07a9995SKamil Rytarowski 
165f07a9995SKamil Rytarowski // Handles all waitpid events from the inferior process.
166f07a9995SKamil Rytarowski void NativeProcessNetBSD::MonitorCallback(lldb::pid_t pid, int signal) {
167f07a9995SKamil Rytarowski   switch (signal) {
168f07a9995SKamil Rytarowski   case SIGTRAP:
169f07a9995SKamil Rytarowski     return MonitorSIGTRAP(pid);
170f07a9995SKamil Rytarowski   case SIGSTOP:
171f07a9995SKamil Rytarowski     return MonitorSIGSTOP(pid);
172f07a9995SKamil Rytarowski   default:
173f07a9995SKamil Rytarowski     return MonitorSignal(pid, signal);
174f07a9995SKamil Rytarowski   }
175f07a9995SKamil Rytarowski }
176f07a9995SKamil Rytarowski 
1773508fc8cSPavel Labath void NativeProcessNetBSD::MonitorExited(lldb::pid_t pid, WaitStatus status) {
178f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
179f07a9995SKamil Rytarowski 
1803508fc8cSPavel Labath   LLDB_LOG(log, "got exit signal({0}) , pid = {1}", status, pid);
181f07a9995SKamil Rytarowski 
182f07a9995SKamil Rytarowski   /* Stop Tracking All Threads attached to Process */
183f07a9995SKamil Rytarowski   m_threads.clear();
184f07a9995SKamil Rytarowski 
1853508fc8cSPavel Labath   SetExitStatus(status, true);
186f07a9995SKamil Rytarowski 
187f07a9995SKamil Rytarowski   // Notify delegate that our process has exited.
188f07a9995SKamil Rytarowski   SetState(StateType::eStateExited, true);
189f07a9995SKamil Rytarowski }
190f07a9995SKamil Rytarowski 
191f07a9995SKamil Rytarowski void NativeProcessNetBSD::MonitorSIGSTOP(lldb::pid_t pid) {
192f07a9995SKamil Rytarowski   ptrace_siginfo_t info;
193f07a9995SKamil Rytarowski 
194f07a9995SKamil Rytarowski   const auto siginfo_err =
195f07a9995SKamil Rytarowski       PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info));
196f07a9995SKamil Rytarowski 
197f07a9995SKamil Rytarowski   // Get details on the signal raised.
198f07a9995SKamil Rytarowski   if (siginfo_err.Success()) {
199f07a9995SKamil Rytarowski     // Handle SIGSTOP from LLGS (LLDB GDB Server)
200f07a9995SKamil Rytarowski     if (info.psi_siginfo.si_code == SI_USER &&
201f07a9995SKamil Rytarowski         info.psi_siginfo.si_pid == ::getpid()) {
202a5be48b3SPavel Labath       /* Stop Tracking all Threads attached to Process */
203a5be48b3SPavel Labath       for (const auto &thread : m_threads) {
204a5be48b3SPavel Labath         static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(
205f07a9995SKamil Rytarowski             SIGSTOP, &info.psi_siginfo);
206f07a9995SKamil Rytarowski       }
207f07a9995SKamil Rytarowski     }
208e1c159e8SMichal Gorny     SetState(StateType::eStateStopped, true);
209f07a9995SKamil Rytarowski   }
210f07a9995SKamil Rytarowski }
211f07a9995SKamil Rytarowski 
212f07a9995SKamil Rytarowski void NativeProcessNetBSD::MonitorSIGTRAP(lldb::pid_t pid) {
213f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
214f07a9995SKamil Rytarowski   ptrace_siginfo_t info;
215f07a9995SKamil Rytarowski 
216f07a9995SKamil Rytarowski   const auto siginfo_err =
217f07a9995SKamil Rytarowski       PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info));
218f07a9995SKamil Rytarowski 
219f07a9995SKamil Rytarowski   // Get details on the signal raised.
22036e23ecaSKamil Rytarowski   if (siginfo_err.Fail()) {
22136e23ecaSKamil Rytarowski     return;
22236e23ecaSKamil Rytarowski   }
22336e23ecaSKamil Rytarowski 
224*8d9400b6SMichał Górny   NativeThreadNetBSD* thread = nullptr;
225*8d9400b6SMichał Górny   if (info.psi_lwpid > 0) {
226*8d9400b6SMichał Górny     for (const auto &t : m_threads) {
227*8d9400b6SMichał Górny       if (t->GetID() == static_cast<lldb::tid_t>(info.psi_lwpid)) {
228*8d9400b6SMichał Górny         thread = static_cast<NativeThreadNetBSD *>(t.get());
229*8d9400b6SMichał Górny         break;
230*8d9400b6SMichał Górny       }
231*8d9400b6SMichał Górny       static_cast<NativeThreadNetBSD *>(t.get())->SetStoppedWithNoReason();
232*8d9400b6SMichał Górny     }
233*8d9400b6SMichał Górny     if (!thread)
234*8d9400b6SMichał Górny       LLDB_LOG(log,
235*8d9400b6SMichał Górny                "thread not found in m_threads, pid = {0}, LWP = {1}", pid,
236*8d9400b6SMichał Górny                info.psi_lwpid);
237*8d9400b6SMichał Górny   }
238*8d9400b6SMichał Górny 
239f07a9995SKamil Rytarowski   switch (info.psi_siginfo.si_code) {
240f07a9995SKamil Rytarowski   case TRAP_BRKPT:
241*8d9400b6SMichał Górny     if (thread) {
242*8d9400b6SMichał Górny       thread->SetStoppedByBreakpoint();
243*8d9400b6SMichał Górny       FixupBreakpointPCAsNeeded(*thread);
244f07a9995SKamil Rytarowski     }
245f07a9995SKamil Rytarowski     SetState(StateType::eStateStopped, true);
246f07a9995SKamil Rytarowski     break;
2473eef2b5eSKamil Rytarowski   case TRAP_TRACE:
248*8d9400b6SMichał Górny     if (thread)
249*8d9400b6SMichał Górny       thread->SetStoppedByTrace();
2503eef2b5eSKamil Rytarowski     SetState(StateType::eStateStopped, true);
2513eef2b5eSKamil Rytarowski     break;
2523eef2b5eSKamil Rytarowski   case TRAP_EXEC: {
25397206d57SZachary Turner     Status error = ReinitializeThreads();
2543eef2b5eSKamil Rytarowski     if (error.Fail()) {
2553eef2b5eSKamil Rytarowski       SetState(StateType::eStateInvalid);
2563eef2b5eSKamil Rytarowski       return;
2573eef2b5eSKamil Rytarowski     }
2583eef2b5eSKamil Rytarowski 
2593eef2b5eSKamil Rytarowski     // Let our delegate know we have just exec'd.
2603eef2b5eSKamil Rytarowski     NotifyDidExec();
2613eef2b5eSKamil Rytarowski 
262a5be48b3SPavel Labath     for (const auto &thread : m_threads)
263a5be48b3SPavel Labath       static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByExec();
2643eef2b5eSKamil Rytarowski     SetState(StateType::eStateStopped, true);
2653eef2b5eSKamil Rytarowski   } break;
266*8d9400b6SMichał Górny   case TRAP_LWP: {
267*8d9400b6SMichał Górny     ptrace_state_t pst;
268*8d9400b6SMichał Górny     Status error = PtraceWrapper(PT_GET_PROCESS_STATE, pid, &pst, sizeof(pst));
269*8d9400b6SMichał Górny     if (error.Fail()) {
270*8d9400b6SMichał Górny       SetState(StateType::eStateInvalid);
271*8d9400b6SMichał Górny       return;
272baf64b65SMichal Gorny     }
273*8d9400b6SMichał Górny 
274*8d9400b6SMichał Górny     switch (pst.pe_report_event) {
275*8d9400b6SMichał Górny       case PTRACE_LWP_CREATE:
276baf64b65SMichal Gorny         LLDB_LOG(log,
277*8d9400b6SMichał Górny                  "monitoring new thread, pid = {0}, LWP = {1}", pid,
278*8d9400b6SMichał Górny                  pst.pe_lwp);
279*8d9400b6SMichał Górny         AddThread(pst.pe_lwp);
280*8d9400b6SMichał Górny         break;
281*8d9400b6SMichał Górny       case PTRACE_LWP_EXIT:
282*8d9400b6SMichał Górny         LLDB_LOG(log,
283*8d9400b6SMichał Górny                  "removing exited thread, pid = {0}, LWP = {1}", pid,
284*8d9400b6SMichał Górny                  pst.pe_lwp);
285*8d9400b6SMichał Górny         RemoveThread(pst.pe_lwp);
286baf64b65SMichal Gorny         break;
287baf64b65SMichal Gorny     }
288baf64b65SMichal Gorny 
289*8d9400b6SMichał Górny     error = PtraceWrapper(PT_CONTINUE, pid, reinterpret_cast<void*>(1), 0);
290*8d9400b6SMichał Górny     if (error.Fail()) {
291*8d9400b6SMichał Górny       SetState(StateType::eStateInvalid);
292*8d9400b6SMichał Górny       return;
293*8d9400b6SMichał Górny     }
294*8d9400b6SMichał Górny   } break;
295*8d9400b6SMichał Górny   case TRAP_DBREG: {
296*8d9400b6SMichał Górny     if (!thread)
297*8d9400b6SMichał Górny       break;
298*8d9400b6SMichał Górny 
299baf64b65SMichal Gorny     uint32_t wp_index = LLDB_INVALID_INDEX32;
300baf64b65SMichal Gorny     Status error = thread->GetRegisterContext().GetWatchpointHitIndex(
301a5be48b3SPavel Labath         wp_index, (uintptr_t)info.psi_siginfo.si_addr);
30236e23ecaSKamil Rytarowski     if (error.Fail())
30336e23ecaSKamil Rytarowski       LLDB_LOG(log,
30436e23ecaSKamil Rytarowski                "received error while checking for watchpoint hits, pid = "
305*8d9400b6SMichał Górny                "{0}, LWP = {1}, error = {2}", pid, info.psi_lwpid, error);
30636e23ecaSKamil Rytarowski     if (wp_index != LLDB_INVALID_INDEX32) {
307*8d9400b6SMichał Górny       thread->SetStoppedByWatchpoint(wp_index);
30836e23ecaSKamil Rytarowski       SetState(StateType::eStateStopped, true);
30936e23ecaSKamil Rytarowski       break;
31036e23ecaSKamil Rytarowski     }
31136e23ecaSKamil Rytarowski 
312*8d9400b6SMichał Górny     thread->SetStoppedByTrace();
31336e23ecaSKamil Rytarowski     SetState(StateType::eStateStopped, true);
31436e23ecaSKamil Rytarowski   } break;
315f07a9995SKamil Rytarowski   }
316f07a9995SKamil Rytarowski }
317f07a9995SKamil Rytarowski 
318f07a9995SKamil Rytarowski void NativeProcessNetBSD::MonitorSignal(lldb::pid_t pid, int signal) {
319f07a9995SKamil Rytarowski   ptrace_siginfo_t info;
320f07a9995SKamil Rytarowski   const auto siginfo_err =
321f07a9995SKamil Rytarowski       PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info));
322f07a9995SKamil Rytarowski 
323*8d9400b6SMichał Górny   for (const auto &abs_thread : m_threads) {
324*8d9400b6SMichał Górny     NativeThreadNetBSD &thread = static_cast<NativeThreadNetBSD &>(*abs_thread);
325*8d9400b6SMichał Górny     assert(info.psi_lwpid >= 0);
326*8d9400b6SMichał Górny     if (info.psi_lwpid == 0 ||
327*8d9400b6SMichał Górny         static_cast<lldb::tid_t>(info.psi_lwpid) == thread.GetID())
328*8d9400b6SMichał Górny       thread.SetStoppedBySignal(info.psi_siginfo.si_signo, &info.psi_siginfo);
329*8d9400b6SMichał Górny     else
330*8d9400b6SMichał Górny       thread.SetStoppedWithNoReason();
331f07a9995SKamil Rytarowski   }
332f07a9995SKamil Rytarowski   SetState(StateType::eStateStopped, true);
333f07a9995SKamil Rytarowski }
334f07a9995SKamil Rytarowski 
33597206d57SZachary Turner Status NativeProcessNetBSD::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
336f07a9995SKamil Rytarowski                                           int data, int *result) {
337f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
33897206d57SZachary Turner   Status error;
339f07a9995SKamil Rytarowski   int ret;
340f07a9995SKamil Rytarowski 
341f07a9995SKamil Rytarowski   errno = 0;
342f07a9995SKamil Rytarowski   ret = ptrace(req, static_cast<::pid_t>(pid), addr, data);
343f07a9995SKamil Rytarowski 
344f07a9995SKamil Rytarowski   if (ret == -1)
345f07a9995SKamil Rytarowski     error.SetErrorToErrno();
346f07a9995SKamil Rytarowski 
347f07a9995SKamil Rytarowski   if (result)
348f07a9995SKamil Rytarowski     *result = ret;
349f07a9995SKamil Rytarowski 
350f07a9995SKamil Rytarowski   LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3})={4:x}", req, pid, addr, data, ret);
351f07a9995SKamil Rytarowski 
352f07a9995SKamil Rytarowski   if (error.Fail())
353f07a9995SKamil Rytarowski     LLDB_LOG(log, "ptrace() failed: {0}", error);
354f07a9995SKamil Rytarowski 
355f07a9995SKamil Rytarowski   return error;
356f07a9995SKamil Rytarowski }
357f07a9995SKamil Rytarowski 
358*8d9400b6SMichał Górny static llvm::Expected<ptrace_siginfo_t> ComputeSignalInfo(
359*8d9400b6SMichał Górny     const std::vector<std::unique_ptr<NativeThreadProtocol>> &threads,
360*8d9400b6SMichał Górny     const ResumeActionList &resume_actions) {
361*8d9400b6SMichał Górny   // We need to account for three possible scenarios:
362*8d9400b6SMichał Górny   // 1. no signal being sent.
363*8d9400b6SMichał Górny   // 2. a signal being sent to one thread.
364*8d9400b6SMichał Górny   // 3. a signal being sent to the whole process.
365*8d9400b6SMichał Górny 
366*8d9400b6SMichał Górny   // Count signaled threads.  While at it, determine which signal is being sent
367*8d9400b6SMichał Górny   // and ensure there's only one.
368*8d9400b6SMichał Górny   size_t signaled_threads = 0;
369*8d9400b6SMichał Górny   int signal = LLDB_INVALID_SIGNAL_NUMBER;
370*8d9400b6SMichał Górny   lldb::tid_t signaled_lwp;
371*8d9400b6SMichał Górny   for (const auto &thread : threads) {
372*8d9400b6SMichał Górny     assert(thread && "thread list should not contain NULL threads");
373*8d9400b6SMichał Górny     const ResumeAction *action =
374*8d9400b6SMichał Górny         resume_actions.GetActionForThread(thread->GetID(), true);
375*8d9400b6SMichał Górny     if (action) {
376*8d9400b6SMichał Górny       if (action->signal != LLDB_INVALID_SIGNAL_NUMBER) {
377*8d9400b6SMichał Górny         signaled_threads++;
378*8d9400b6SMichał Górny         if (action->signal != signal) {
379*8d9400b6SMichał Górny           if (signal != LLDB_INVALID_SIGNAL_NUMBER)
380*8d9400b6SMichał Górny             return Status("NetBSD does not support passing multiple signals "
381*8d9400b6SMichał Górny                           "simultaneously")
382*8d9400b6SMichał Górny                 .ToError();
383*8d9400b6SMichał Górny           signal = action->signal;
384*8d9400b6SMichał Górny           signaled_lwp = thread->GetID();
385*8d9400b6SMichał Górny         }
386*8d9400b6SMichał Górny       }
387*8d9400b6SMichał Górny     }
388*8d9400b6SMichał Górny   }
389*8d9400b6SMichał Górny 
390*8d9400b6SMichał Górny   if (signaled_threads == 0) {
391*8d9400b6SMichał Górny     ptrace_siginfo_t siginfo;
392*8d9400b6SMichał Górny     siginfo.psi_siginfo.si_signo = LLDB_INVALID_SIGNAL_NUMBER;
393*8d9400b6SMichał Górny     return siginfo;
394*8d9400b6SMichał Górny   }
395*8d9400b6SMichał Górny 
396*8d9400b6SMichał Górny   if (signaled_threads > 1 && signaled_threads < threads.size())
397*8d9400b6SMichał Górny     return Status("NetBSD does not support passing signal to 1<i<all threads")
398*8d9400b6SMichał Górny         .ToError();
399*8d9400b6SMichał Górny 
400*8d9400b6SMichał Górny   ptrace_siginfo_t siginfo;
401*8d9400b6SMichał Górny   siginfo.psi_siginfo.si_signo = signal;
402*8d9400b6SMichał Górny   siginfo.psi_siginfo.si_code = SI_USER;
403*8d9400b6SMichał Górny   siginfo.psi_siginfo.si_pid = getpid();
404*8d9400b6SMichał Górny   siginfo.psi_siginfo.si_uid = getuid();
405*8d9400b6SMichał Górny   if (signaled_threads == 1)
406*8d9400b6SMichał Górny     siginfo.psi_lwpid = signaled_lwp;
407*8d9400b6SMichał Górny   else // signal for the whole process
408*8d9400b6SMichał Górny     siginfo.psi_lwpid = 0;
409*8d9400b6SMichał Górny   return siginfo;
410*8d9400b6SMichał Górny }
411*8d9400b6SMichał Górny 
41297206d57SZachary Turner Status NativeProcessNetBSD::Resume(const ResumeActionList &resume_actions) {
413f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
414f07a9995SKamil Rytarowski   LLDB_LOG(log, "pid {0}", GetID());
415f07a9995SKamil Rytarowski 
416*8d9400b6SMichał Górny   Status ret;
417*8d9400b6SMichał Górny 
418*8d9400b6SMichał Górny   Expected<ptrace_siginfo_t> siginfo =
419*8d9400b6SMichał Górny       ComputeSignalInfo(m_threads, resume_actions);
420*8d9400b6SMichał Górny   if (!siginfo)
421*8d9400b6SMichał Górny     return Status(siginfo.takeError());
422*8d9400b6SMichał Górny 
423*8d9400b6SMichał Górny   for (const auto &abs_thread : m_threads) {
424*8d9400b6SMichał Górny     assert(abs_thread && "thread list should not contain NULL threads");
425*8d9400b6SMichał Górny     NativeThreadNetBSD &thread = static_cast<NativeThreadNetBSD &>(*abs_thread);
426*8d9400b6SMichał Górny 
427*8d9400b6SMichał Górny     const ResumeAction *action =
428*8d9400b6SMichał Górny         resume_actions.GetActionForThread(thread.GetID(), true);
429*8d9400b6SMichał Górny     // we need to explicit issue suspend requests, so it is simpler to map it
430*8d9400b6SMichał Górny     // into proper action
431*8d9400b6SMichał Górny     ResumeAction suspend_action{thread.GetID(), eStateSuspended,
432*8d9400b6SMichał Górny                                 LLDB_INVALID_SIGNAL_NUMBER};
433f07a9995SKamil Rytarowski 
434f07a9995SKamil Rytarowski     if (action == nullptr) {
435f07a9995SKamil Rytarowski       LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
436*8d9400b6SMichał Górny                thread.GetID());
437*8d9400b6SMichał Górny       action = &suspend_action;
438f07a9995SKamil Rytarowski     }
439f07a9995SKamil Rytarowski 
440*8d9400b6SMichał Górny     LLDB_LOG(
441*8d9400b6SMichał Górny         log,
442*8d9400b6SMichał Górny         "processing resume action state {0} signal {1} for pid {2} tid {3}",
443*8d9400b6SMichał Górny         action->state, action->signal, GetID(), thread.GetID());
4443eef2b5eSKamil Rytarowski 
445f07a9995SKamil Rytarowski     switch (action->state) {
446*8d9400b6SMichał Górny     case eStateRunning:
447*8d9400b6SMichał Górny       ret = thread.Resume();
448f07a9995SKamil Rytarowski       break;
449f07a9995SKamil Rytarowski     case eStateStepping:
450*8d9400b6SMichał Górny       ret = thread.SingleStep();
451f07a9995SKamil Rytarowski       break;
452f07a9995SKamil Rytarowski     case eStateSuspended:
453f07a9995SKamil Rytarowski     case eStateStopped:
454*8d9400b6SMichał Górny       if (action->signal != LLDB_INVALID_SIGNAL_NUMBER)
455*8d9400b6SMichał Górny         return Status("Passing signal to suspended thread unsupported");
456*8d9400b6SMichał Górny 
457*8d9400b6SMichał Górny       ret = thread.Suspend();
458*8d9400b6SMichał Górny       break;
459f07a9995SKamil Rytarowski 
460f07a9995SKamil Rytarowski     default:
46197206d57SZachary Turner       return Status("NativeProcessNetBSD::%s (): unexpected state %s specified "
462f07a9995SKamil Rytarowski                     "for pid %" PRIu64 ", tid %" PRIu64,
463f07a9995SKamil Rytarowski                     __FUNCTION__, StateAsCString(action->state), GetID(),
464*8d9400b6SMichał Górny                     thread.GetID());
465f07a9995SKamil Rytarowski     }
466f07a9995SKamil Rytarowski 
467*8d9400b6SMichał Górny     if (!ret.Success())
468*8d9400b6SMichał Górny       return ret;
469*8d9400b6SMichał Górny   }
470*8d9400b6SMichał Górny 
471*8d9400b6SMichał Górny   int signal = 0;
472*8d9400b6SMichał Górny   if (siginfo->psi_siginfo.si_signo != LLDB_INVALID_SIGNAL_NUMBER) {
473*8d9400b6SMichał Górny     ret = PtraceWrapper(PT_SET_SIGINFO, GetID(), &siginfo.get(),
474*8d9400b6SMichał Górny                         sizeof(*siginfo));
475*8d9400b6SMichał Górny     if (!ret.Success())
476*8d9400b6SMichał Górny       return ret;
477*8d9400b6SMichał Górny     signal = siginfo->psi_siginfo.si_signo;
478*8d9400b6SMichał Górny   }
479*8d9400b6SMichał Górny 
480*8d9400b6SMichał Górny   ret = PtraceWrapper(PT_CONTINUE, GetID(), reinterpret_cast<void *>(1),
481*8d9400b6SMichał Górny                       signal);
482*8d9400b6SMichał Górny   if (ret.Success())
483*8d9400b6SMichał Górny     SetState(eStateRunning, true);
484*8d9400b6SMichał Górny   return ret;
485f07a9995SKamil Rytarowski }
486f07a9995SKamil Rytarowski 
48797206d57SZachary Turner Status NativeProcessNetBSD::Halt() {
48877cc2464SMichał Górny   return PtraceWrapper(PT_STOP, GetID());
489f07a9995SKamil Rytarowski }
490f07a9995SKamil Rytarowski 
49197206d57SZachary Turner Status NativeProcessNetBSD::Detach() {
49297206d57SZachary Turner   Status error;
493f07a9995SKamil Rytarowski 
494f07a9995SKamil Rytarowski   // Stop monitoring the inferior.
495f07a9995SKamil Rytarowski   m_sigchld_handle.reset();
496f07a9995SKamil Rytarowski 
497f07a9995SKamil Rytarowski   // Tell ptrace to detach from the process.
498f07a9995SKamil Rytarowski   if (GetID() == LLDB_INVALID_PROCESS_ID)
499f07a9995SKamil Rytarowski     return error;
500f07a9995SKamil Rytarowski 
501f07a9995SKamil Rytarowski   return PtraceWrapper(PT_DETACH, GetID());
502f07a9995SKamil Rytarowski }
503f07a9995SKamil Rytarowski 
50497206d57SZachary Turner Status NativeProcessNetBSD::Signal(int signo) {
50597206d57SZachary Turner   Status error;
506f07a9995SKamil Rytarowski 
507f07a9995SKamil Rytarowski   if (kill(GetID(), signo))
508f07a9995SKamil Rytarowski     error.SetErrorToErrno();
509f07a9995SKamil Rytarowski 
510f07a9995SKamil Rytarowski   return error;
511f07a9995SKamil Rytarowski }
512f07a9995SKamil Rytarowski 
51377cc2464SMichał Górny Status NativeProcessNetBSD::Interrupt() {
51477cc2464SMichał Górny   return PtraceWrapper(PT_STOP, GetID());
51577cc2464SMichał Górny }
51677cc2464SMichał Górny 
51797206d57SZachary Turner Status NativeProcessNetBSD::Kill() {
518f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
519f07a9995SKamil Rytarowski   LLDB_LOG(log, "pid {0}", GetID());
520f07a9995SKamil Rytarowski 
52197206d57SZachary Turner   Status error;
522f07a9995SKamil Rytarowski 
523f07a9995SKamil Rytarowski   switch (m_state) {
524f07a9995SKamil Rytarowski   case StateType::eStateInvalid:
525f07a9995SKamil Rytarowski   case StateType::eStateExited:
526f07a9995SKamil Rytarowski   case StateType::eStateCrashed:
527f07a9995SKamil Rytarowski   case StateType::eStateDetached:
528f07a9995SKamil Rytarowski   case StateType::eStateUnloaded:
529f07a9995SKamil Rytarowski     // Nothing to do - the process is already dead.
530f07a9995SKamil Rytarowski     LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
531f07a9995SKamil Rytarowski              StateAsCString(m_state));
532f07a9995SKamil Rytarowski     return error;
533f07a9995SKamil Rytarowski 
534f07a9995SKamil Rytarowski   case StateType::eStateConnected:
535f07a9995SKamil Rytarowski   case StateType::eStateAttaching:
536f07a9995SKamil Rytarowski   case StateType::eStateLaunching:
537f07a9995SKamil Rytarowski   case StateType::eStateStopped:
538f07a9995SKamil Rytarowski   case StateType::eStateRunning:
539f07a9995SKamil Rytarowski   case StateType::eStateStepping:
540f07a9995SKamil Rytarowski   case StateType::eStateSuspended:
541f07a9995SKamil Rytarowski     // We can try to kill a process in these states.
542f07a9995SKamil Rytarowski     break;
543f07a9995SKamil Rytarowski   }
544f07a9995SKamil Rytarowski 
545f07a9995SKamil Rytarowski   if (kill(GetID(), SIGKILL) != 0) {
546f07a9995SKamil Rytarowski     error.SetErrorToErrno();
547f07a9995SKamil Rytarowski     return error;
548f07a9995SKamil Rytarowski   }
549f07a9995SKamil Rytarowski 
550f07a9995SKamil Rytarowski   return error;
551f07a9995SKamil Rytarowski }
552f07a9995SKamil Rytarowski 
55397206d57SZachary Turner Status NativeProcessNetBSD::GetMemoryRegionInfo(lldb::addr_t load_addr,
554f07a9995SKamil Rytarowski                                                 MemoryRegionInfo &range_info) {
555f07a9995SKamil Rytarowski 
556f07a9995SKamil Rytarowski   if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
557f07a9995SKamil Rytarowski     // We're done.
55897206d57SZachary Turner     return Status("unsupported");
559f07a9995SKamil Rytarowski   }
560f07a9995SKamil Rytarowski 
56197206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
562f07a9995SKamil Rytarowski   if (error.Fail()) {
563f07a9995SKamil Rytarowski     return error;
564f07a9995SKamil Rytarowski   }
565f07a9995SKamil Rytarowski 
566f07a9995SKamil Rytarowski   lldb::addr_t prev_base_address = 0;
567f07a9995SKamil Rytarowski   // FIXME start by finding the last region that is <= target address using
568f07a9995SKamil Rytarowski   // binary search.  Data is sorted.
569f07a9995SKamil Rytarowski   // There can be a ton of regions on pthreads apps with lots of threads.
570f07a9995SKamil Rytarowski   for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
571f07a9995SKamil Rytarowski        ++it) {
572f07a9995SKamil Rytarowski     MemoryRegionInfo &proc_entry_info = it->first;
573f07a9995SKamil Rytarowski     // Sanity check assumption that memory map entries are ascending.
574f07a9995SKamil Rytarowski     assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
575f07a9995SKamil Rytarowski            "descending memory map entries detected, unexpected");
576f07a9995SKamil Rytarowski     prev_base_address = proc_entry_info.GetRange().GetRangeBase();
577f07a9995SKamil Rytarowski     UNUSED_IF_ASSERT_DISABLED(prev_base_address);
57805097246SAdrian Prantl     // If the target address comes before this entry, indicate distance to next
57905097246SAdrian Prantl     // region.
580f07a9995SKamil Rytarowski     if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
581f07a9995SKamil Rytarowski       range_info.GetRange().SetRangeBase(load_addr);
582f07a9995SKamil Rytarowski       range_info.GetRange().SetByteSize(
583f07a9995SKamil Rytarowski           proc_entry_info.GetRange().GetRangeBase() - load_addr);
584f07a9995SKamil Rytarowski       range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
585f07a9995SKamil Rytarowski       range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
586f07a9995SKamil Rytarowski       range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
587f07a9995SKamil Rytarowski       range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
588f07a9995SKamil Rytarowski       return error;
589f07a9995SKamil Rytarowski     } else if (proc_entry_info.GetRange().Contains(load_addr)) {
590f07a9995SKamil Rytarowski       // The target address is within the memory region we're processing here.
591f07a9995SKamil Rytarowski       range_info = proc_entry_info;
592f07a9995SKamil Rytarowski       return error;
593f07a9995SKamil Rytarowski     }
594f07a9995SKamil Rytarowski     // The target memory address comes somewhere after the region we just
595f07a9995SKamil Rytarowski     // parsed.
596f07a9995SKamil Rytarowski   }
597f07a9995SKamil Rytarowski   // If we made it here, we didn't find an entry that contained the given
59805097246SAdrian Prantl   // address. Return the load_addr as start and the amount of bytes betwwen
59905097246SAdrian Prantl   // load address and the end of the memory as size.
600f07a9995SKamil Rytarowski   range_info.GetRange().SetRangeBase(load_addr);
601f07a9995SKamil Rytarowski   range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
602f07a9995SKamil Rytarowski   range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
603f07a9995SKamil Rytarowski   range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
604f07a9995SKamil Rytarowski   range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
605f07a9995SKamil Rytarowski   range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
606f07a9995SKamil Rytarowski   return error;
607f07a9995SKamil Rytarowski }
608f07a9995SKamil Rytarowski 
60997206d57SZachary Turner Status NativeProcessNetBSD::PopulateMemoryRegionCache() {
610f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
611f07a9995SKamil Rytarowski   // If our cache is empty, pull the latest.  There should always be at least
612f07a9995SKamil Rytarowski   // one memory region if memory region handling is supported.
613f07a9995SKamil Rytarowski   if (!m_mem_region_cache.empty()) {
614f07a9995SKamil Rytarowski     LLDB_LOG(log, "reusing {0} cached memory region entries",
615f07a9995SKamil Rytarowski              m_mem_region_cache.size());
61697206d57SZachary Turner     return Status();
617f07a9995SKamil Rytarowski   }
618f07a9995SKamil Rytarowski 
619f07a9995SKamil Rytarowski   struct kinfo_vmentry *vm;
620f07a9995SKamil Rytarowski   size_t count, i;
621f07a9995SKamil Rytarowski   vm = kinfo_getvmmap(GetID(), &count);
622f07a9995SKamil Rytarowski   if (vm == NULL) {
623f07a9995SKamil Rytarowski     m_supports_mem_region = LazyBool::eLazyBoolNo;
62497206d57SZachary Turner     Status error;
625f07a9995SKamil Rytarowski     error.SetErrorString("not supported");
626f07a9995SKamil Rytarowski     return error;
627f07a9995SKamil Rytarowski   }
628f07a9995SKamil Rytarowski   for (i = 0; i < count; i++) {
629f07a9995SKamil Rytarowski     MemoryRegionInfo info;
630f07a9995SKamil Rytarowski     info.Clear();
631f07a9995SKamil Rytarowski     info.GetRange().SetRangeBase(vm[i].kve_start);
632f07a9995SKamil Rytarowski     info.GetRange().SetRangeEnd(vm[i].kve_end);
633f07a9995SKamil Rytarowski     info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
634f07a9995SKamil Rytarowski 
635f07a9995SKamil Rytarowski     if (vm[i].kve_protection & VM_PROT_READ)
636f07a9995SKamil Rytarowski       info.SetReadable(MemoryRegionInfo::OptionalBool::eYes);
637f07a9995SKamil Rytarowski     else
638f07a9995SKamil Rytarowski       info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
639f07a9995SKamil Rytarowski 
640f07a9995SKamil Rytarowski     if (vm[i].kve_protection & VM_PROT_WRITE)
641f07a9995SKamil Rytarowski       info.SetWritable(MemoryRegionInfo::OptionalBool::eYes);
642f07a9995SKamil Rytarowski     else
643f07a9995SKamil Rytarowski       info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
644f07a9995SKamil Rytarowski 
645f07a9995SKamil Rytarowski     if (vm[i].kve_protection & VM_PROT_EXECUTE)
646f07a9995SKamil Rytarowski       info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes);
647f07a9995SKamil Rytarowski     else
648f07a9995SKamil Rytarowski       info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
649f07a9995SKamil Rytarowski 
650f07a9995SKamil Rytarowski     if (vm[i].kve_path[0])
651f07a9995SKamil Rytarowski       info.SetName(vm[i].kve_path);
652f07a9995SKamil Rytarowski 
653f07a9995SKamil Rytarowski     m_mem_region_cache.emplace_back(
654a0a44e9cSKamil Rytarowski         info, FileSpec(info.GetName().GetCString()));
655f07a9995SKamil Rytarowski   }
656f07a9995SKamil Rytarowski   free(vm);
657f07a9995SKamil Rytarowski 
658f07a9995SKamil Rytarowski   if (m_mem_region_cache.empty()) {
65905097246SAdrian Prantl     // No entries after attempting to read them.  This shouldn't happen. Assume
66005097246SAdrian Prantl     // we don't support map entries.
661f07a9995SKamil Rytarowski     LLDB_LOG(log, "failed to find any vmmap entries, assuming no support "
662f07a9995SKamil Rytarowski                   "for memory region metadata retrieval");
663f07a9995SKamil Rytarowski     m_supports_mem_region = LazyBool::eLazyBoolNo;
66497206d57SZachary Turner     Status error;
665f07a9995SKamil Rytarowski     error.SetErrorString("not supported");
666f07a9995SKamil Rytarowski     return error;
667f07a9995SKamil Rytarowski   }
668f07a9995SKamil Rytarowski   LLDB_LOG(log, "read {0} memory region entries from process {1}",
669f07a9995SKamil Rytarowski            m_mem_region_cache.size(), GetID());
670f07a9995SKamil Rytarowski   // We support memory retrieval, remember that.
671f07a9995SKamil Rytarowski   m_supports_mem_region = LazyBool::eLazyBoolYes;
67297206d57SZachary Turner   return Status();
673f07a9995SKamil Rytarowski }
674f07a9995SKamil Rytarowski 
67597206d57SZachary Turner Status NativeProcessNetBSD::AllocateMemory(size_t size, uint32_t permissions,
676f07a9995SKamil Rytarowski                                            lldb::addr_t &addr) {
67797206d57SZachary Turner   return Status("Unimplemented");
678f07a9995SKamil Rytarowski }
679f07a9995SKamil Rytarowski 
68097206d57SZachary Turner Status NativeProcessNetBSD::DeallocateMemory(lldb::addr_t addr) {
68197206d57SZachary Turner   return Status("Unimplemented");
682f07a9995SKamil Rytarowski }
683f07a9995SKamil Rytarowski 
684f07a9995SKamil Rytarowski lldb::addr_t NativeProcessNetBSD::GetSharedLibraryInfoAddress() {
685f07a9995SKamil Rytarowski   // punt on this for now
686f07a9995SKamil Rytarowski   return LLDB_INVALID_ADDRESS;
687f07a9995SKamil Rytarowski }
688f07a9995SKamil Rytarowski 
689f07a9995SKamil Rytarowski size_t NativeProcessNetBSD::UpdateThreads() { return m_threads.size(); }
690f07a9995SKamil Rytarowski 
69197206d57SZachary Turner Status NativeProcessNetBSD::SetBreakpoint(lldb::addr_t addr, uint32_t size,
692f07a9995SKamil Rytarowski                                           bool hardware) {
693f07a9995SKamil Rytarowski   if (hardware)
69497206d57SZachary Turner     return Status("NativeProcessNetBSD does not support hardware breakpoints");
695f07a9995SKamil Rytarowski   else
696f07a9995SKamil Rytarowski     return SetSoftwareBreakpoint(addr, size);
697f07a9995SKamil Rytarowski }
698f07a9995SKamil Rytarowski 
69997206d57SZachary Turner Status NativeProcessNetBSD::GetLoadedModuleFileSpec(const char *module_path,
700f07a9995SKamil Rytarowski                                                     FileSpec &file_spec) {
70197206d57SZachary Turner   return Status("Unimplemented");
702f07a9995SKamil Rytarowski }
703f07a9995SKamil Rytarowski 
70497206d57SZachary Turner Status NativeProcessNetBSD::GetFileLoadAddress(const llvm::StringRef &file_name,
705f07a9995SKamil Rytarowski                                                lldb::addr_t &load_addr) {
706f07a9995SKamil Rytarowski   load_addr = LLDB_INVALID_ADDRESS;
70797206d57SZachary Turner   return Status();
708f07a9995SKamil Rytarowski }
709f07a9995SKamil Rytarowski 
710f07a9995SKamil Rytarowski void NativeProcessNetBSD::SigchldHandler() {
711f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
712f07a9995SKamil Rytarowski   // Process all pending waitpid notifications.
713f07a9995SKamil Rytarowski   int status;
714c1a6b128SPavel Labath   ::pid_t wait_pid =
715c1a6b128SPavel Labath       llvm::sys::RetryAfterSignal(-1, waitpid, GetID(), &status, WALLSIG | WNOHANG);
716f07a9995SKamil Rytarowski 
717f07a9995SKamil Rytarowski   if (wait_pid == 0)
718f07a9995SKamil Rytarowski     return; // We are done.
719f07a9995SKamil Rytarowski 
720f07a9995SKamil Rytarowski   if (wait_pid == -1) {
72197206d57SZachary Turner     Status error(errno, eErrorTypePOSIX);
722f07a9995SKamil Rytarowski     LLDB_LOG(log, "waitpid ({0}, &status, _) failed: {1}", GetID(), error);
723f07a9995SKamil Rytarowski   }
724f07a9995SKamil Rytarowski 
7253508fc8cSPavel Labath   WaitStatus wait_status = WaitStatus::Decode(status);
7263508fc8cSPavel Labath   bool exited = wait_status.type == WaitStatus::Exit ||
7273508fc8cSPavel Labath                 (wait_status.type == WaitStatus::Signal &&
7283508fc8cSPavel Labath                  wait_pid == static_cast<::pid_t>(GetID()));
729f07a9995SKamil Rytarowski 
730f07a9995SKamil Rytarowski   LLDB_LOG(log,
7313508fc8cSPavel Labath            "waitpid ({0}, &status, _) => pid = {1}, status = {2}, exited = {3}",
7323508fc8cSPavel Labath            GetID(), wait_pid, status, exited);
733f07a9995SKamil Rytarowski 
734f07a9995SKamil Rytarowski   if (exited)
7353508fc8cSPavel Labath     MonitorExited(wait_pid, wait_status);
7363508fc8cSPavel Labath   else {
7374bb74415SKamil Rytarowski     assert(wait_status.type == WaitStatus::Stop);
7383508fc8cSPavel Labath     MonitorCallback(wait_pid, wait_status.status);
7393508fc8cSPavel Labath   }
740f07a9995SKamil Rytarowski }
741f07a9995SKamil Rytarowski 
742269eec03SKamil Rytarowski bool NativeProcessNetBSD::HasThreadNoLock(lldb::tid_t thread_id) {
743a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
744a5be48b3SPavel Labath     assert(thread && "thread list should not contain NULL threads");
745a5be48b3SPavel Labath     if (thread->GetID() == thread_id) {
746269eec03SKamil Rytarowski       // We have this thread.
747269eec03SKamil Rytarowski       return true;
748269eec03SKamil Rytarowski     }
749269eec03SKamil Rytarowski   }
750269eec03SKamil Rytarowski 
751269eec03SKamil Rytarowski   // We don't have this thread.
752269eec03SKamil Rytarowski   return false;
753269eec03SKamil Rytarowski }
754269eec03SKamil Rytarowski 
755a5be48b3SPavel Labath NativeThreadNetBSD &NativeProcessNetBSD::AddThread(lldb::tid_t thread_id) {
756f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
757f07a9995SKamil Rytarowski   LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
758f07a9995SKamil Rytarowski 
759*8d9400b6SMichał Górny   assert(thread_id > 0);
760f07a9995SKamil Rytarowski   assert(!HasThreadNoLock(thread_id) &&
761f07a9995SKamil Rytarowski          "attempted to add a thread by id that already exists");
762f07a9995SKamil Rytarowski 
763f07a9995SKamil Rytarowski   // If this is the first thread, save it as the current thread
764f07a9995SKamil Rytarowski   if (m_threads.empty())
765f07a9995SKamil Rytarowski     SetCurrentThreadID(thread_id);
766f07a9995SKamil Rytarowski 
767a8f3ae7cSJonas Devlieghere   m_threads.push_back(std::make_unique<NativeThreadNetBSD>(*this, thread_id));
768a5be48b3SPavel Labath   return static_cast<NativeThreadNetBSD &>(*m_threads.back());
769f07a9995SKamil Rytarowski }
770f07a9995SKamil Rytarowski 
771*8d9400b6SMichał Górny void NativeProcessNetBSD::RemoveThread(lldb::tid_t thread_id) {
772*8d9400b6SMichał Górny   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
773*8d9400b6SMichał Górny   LLDB_LOG(log, "pid {0} removing thread with tid {1}", GetID(), thread_id);
774*8d9400b6SMichał Górny 
775*8d9400b6SMichał Górny   assert(thread_id > 0);
776*8d9400b6SMichał Górny   assert(HasThreadNoLock(thread_id) &&
777*8d9400b6SMichał Górny          "attempted to remove a thread that does not exist");
778*8d9400b6SMichał Górny 
779*8d9400b6SMichał Górny   for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
780*8d9400b6SMichał Górny     if ((*it)->GetID() == thread_id) {
781*8d9400b6SMichał Górny       m_threads.erase(it);
782*8d9400b6SMichał Górny       break;
783*8d9400b6SMichał Górny     }
784*8d9400b6SMichał Górny   }
785*8d9400b6SMichał Górny }
786*8d9400b6SMichał Górny 
78796e600fcSPavel Labath Status NativeProcessNetBSD::Attach() {
788f07a9995SKamil Rytarowski   // Attach to the requested process.
789f07a9995SKamil Rytarowski   // An attach will cause the thread to stop with a SIGSTOP.
79096e600fcSPavel Labath   Status status = PtraceWrapper(PT_ATTACH, m_pid);
79196e600fcSPavel Labath   if (status.Fail())
79296e600fcSPavel Labath     return status;
793f07a9995SKamil Rytarowski 
79496e600fcSPavel Labath   int wstatus;
79505097246SAdrian Prantl   // Need to use WALLSIG otherwise we receive an error with errno=ECHLD At this
79605097246SAdrian Prantl   // point we should have a thread stopped if waitpid succeeds.
7972819136fSMichal Gorny   if ((wstatus = llvm::sys::RetryAfterSignal(-1, waitpid,
798c5d7bc86SMichal Gorny           m_pid, nullptr, WALLSIG)) < 0)
79996e600fcSPavel Labath     return Status(errno, eErrorTypePOSIX);
800f07a9995SKamil Rytarowski 
801f07a9995SKamil Rytarowski   /* Initialize threads */
80296e600fcSPavel Labath   status = ReinitializeThreads();
80396e600fcSPavel Labath   if (status.Fail())
80496e600fcSPavel Labath     return status;
805f07a9995SKamil Rytarowski 
806a5be48b3SPavel Labath   for (const auto &thread : m_threads)
807a5be48b3SPavel Labath     static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(SIGSTOP);
80836e23ecaSKamil Rytarowski 
809f07a9995SKamil Rytarowski   // Let our process instance know the thread has stopped.
810f07a9995SKamil Rytarowski   SetState(StateType::eStateStopped);
81196e600fcSPavel Labath   return Status();
812f07a9995SKamil Rytarowski }
813f07a9995SKamil Rytarowski 
81497206d57SZachary Turner Status NativeProcessNetBSD::ReadMemory(lldb::addr_t addr, void *buf,
81597206d57SZachary Turner                                        size_t size, size_t &bytes_read) {
816f07a9995SKamil Rytarowski   unsigned char *dst = static_cast<unsigned char *>(buf);
817f07a9995SKamil Rytarowski   struct ptrace_io_desc io;
818f07a9995SKamil Rytarowski 
819f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
820f07a9995SKamil Rytarowski   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
821f07a9995SKamil Rytarowski 
822f07a9995SKamil Rytarowski   bytes_read = 0;
823f07a9995SKamil Rytarowski   io.piod_op = PIOD_READ_D;
824f07a9995SKamil Rytarowski   io.piod_len = size;
825f07a9995SKamil Rytarowski 
826f07a9995SKamil Rytarowski   do {
827f07a9995SKamil Rytarowski     io.piod_offs = (void *)(addr + bytes_read);
828f07a9995SKamil Rytarowski     io.piod_addr = dst + bytes_read;
829f07a9995SKamil Rytarowski 
83097206d57SZachary Turner     Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
831d14a0de9SMichal Gorny     if (error.Fail() || io.piod_len == 0)
832f07a9995SKamil Rytarowski       return error;
833f07a9995SKamil Rytarowski 
834d14a0de9SMichal Gorny     bytes_read += io.piod_len;
835f07a9995SKamil Rytarowski     io.piod_len = size - bytes_read;
836f07a9995SKamil Rytarowski   } while (bytes_read < size);
837f07a9995SKamil Rytarowski 
83897206d57SZachary Turner   return Status();
839f07a9995SKamil Rytarowski }
840f07a9995SKamil Rytarowski 
84197206d57SZachary Turner Status NativeProcessNetBSD::WriteMemory(lldb::addr_t addr, const void *buf,
842f07a9995SKamil Rytarowski                                         size_t size, size_t &bytes_written) {
843f07a9995SKamil Rytarowski   const unsigned char *src = static_cast<const unsigned char *>(buf);
84497206d57SZachary Turner   Status error;
845f07a9995SKamil Rytarowski   struct ptrace_io_desc io;
846f07a9995SKamil Rytarowski 
847f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
848f07a9995SKamil Rytarowski   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
849f07a9995SKamil Rytarowski 
850f07a9995SKamil Rytarowski   bytes_written = 0;
851f07a9995SKamil Rytarowski   io.piod_op = PIOD_WRITE_D;
852f07a9995SKamil Rytarowski   io.piod_len = size;
853f07a9995SKamil Rytarowski 
854f07a9995SKamil Rytarowski   do {
855269eec03SKamil Rytarowski     io.piod_addr = const_cast<void *>(static_cast<const void *>(src + bytes_written));
856f07a9995SKamil Rytarowski     io.piod_offs = (void *)(addr + bytes_written);
857f07a9995SKamil Rytarowski 
85897206d57SZachary Turner     Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
859d14a0de9SMichal Gorny     if (error.Fail() || io.piod_len == 0)
860f07a9995SKamil Rytarowski       return error;
861f07a9995SKamil Rytarowski 
862d14a0de9SMichal Gorny     bytes_written += io.piod_len;
863f07a9995SKamil Rytarowski     io.piod_len = size - bytes_written;
864f07a9995SKamil Rytarowski   } while (bytes_written < size);
865f07a9995SKamil Rytarowski 
866f07a9995SKamil Rytarowski   return error;
867f07a9995SKamil Rytarowski }
868f07a9995SKamil Rytarowski 
869f07a9995SKamil Rytarowski llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
870f07a9995SKamil Rytarowski NativeProcessNetBSD::GetAuxvData() const {
871f07a9995SKamil Rytarowski   /*
872f07a9995SKamil Rytarowski    * ELF_AUX_ENTRIES is currently restricted to kernel
873f07a9995SKamil Rytarowski    * (<sys/exec_elf.h> r. 1.155 specifies 15)
874f07a9995SKamil Rytarowski    *
875f07a9995SKamil Rytarowski    * ptrace(2) returns the whole AUXV including extra fiels after AT_NULL this
876f07a9995SKamil Rytarowski    * information isn't needed.
877f07a9995SKamil Rytarowski    */
878f07a9995SKamil Rytarowski   size_t auxv_size = 100 * sizeof(AuxInfo);
879f07a9995SKamil Rytarowski 
880e831bb3cSPavel Labath   ErrorOr<std::unique_ptr<WritableMemoryBuffer>> buf =
881dbda2851SPavel Labath       llvm::WritableMemoryBuffer::getNewMemBuffer(auxv_size);
882f07a9995SKamil Rytarowski 
883269eec03SKamil Rytarowski   struct ptrace_io_desc io;
884269eec03SKamil Rytarowski   io.piod_op = PIOD_READ_AUXV;
885269eec03SKamil Rytarowski   io.piod_offs = 0;
886e831bb3cSPavel Labath   io.piod_addr = static_cast<void *>(buf.get()->getBufferStart());
887269eec03SKamil Rytarowski   io.piod_len = auxv_size;
888f07a9995SKamil Rytarowski 
88997206d57SZachary Turner   Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
890f07a9995SKamil Rytarowski 
891f07a9995SKamil Rytarowski   if (error.Fail())
892f07a9995SKamil Rytarowski     return std::error_code(error.GetError(), std::generic_category());
893f07a9995SKamil Rytarowski 
894f07a9995SKamil Rytarowski   if (io.piod_len < 1)
895f07a9995SKamil Rytarowski     return std::error_code(ECANCELED, std::generic_category());
896f07a9995SKamil Rytarowski 
897e831bb3cSPavel Labath   return std::move(buf);
898f07a9995SKamil Rytarowski }
8993eef2b5eSKamil Rytarowski 
90097206d57SZachary Turner Status NativeProcessNetBSD::ReinitializeThreads() {
9013eef2b5eSKamil Rytarowski   // Clear old threads
9023eef2b5eSKamil Rytarowski   m_threads.clear();
9033eef2b5eSKamil Rytarowski 
9043eef2b5eSKamil Rytarowski   // Initialize new thread
9053eef2b5eSKamil Rytarowski   struct ptrace_lwpinfo info = {};
90697206d57SZachary Turner   Status error = PtraceWrapper(PT_LWPINFO, GetID(), &info, sizeof(info));
9073eef2b5eSKamil Rytarowski   if (error.Fail()) {
9083eef2b5eSKamil Rytarowski     return error;
9093eef2b5eSKamil Rytarowski   }
9103eef2b5eSKamil Rytarowski   // Reinitialize from scratch threads and register them in process
9113eef2b5eSKamil Rytarowski   while (info.pl_lwpid != 0) {
912a5be48b3SPavel Labath     AddThread(info.pl_lwpid);
9133eef2b5eSKamil Rytarowski     error = PtraceWrapper(PT_LWPINFO, GetID(), &info, sizeof(info));
9143eef2b5eSKamil Rytarowski     if (error.Fail()) {
9153eef2b5eSKamil Rytarowski       return error;
9163eef2b5eSKamil Rytarowski     }
9173eef2b5eSKamil Rytarowski   }
9183eef2b5eSKamil Rytarowski 
9193eef2b5eSKamil Rytarowski   return error;
9203eef2b5eSKamil Rytarowski }
921