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 
117644d8baSMichał Górny #include "Plugins/Process/NetBSD/NativeRegisterContextNetBSD.h"
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 
1018d9400b6SMichał Górny   // Enable event reporting
1028d9400b6SMichał Górny   ptrace_event_t events;
1038d9400b6SMichał Górny   status = PtraceWrapper(PT_GET_EVENT_MASK, pid, &events, sizeof(events));
1048d9400b6SMichał Górny   if (status.Fail())
1058d9400b6SMichał Górny     return status.ToError();
1068d9400b6SMichał Górny   // TODO: PTRACE_FORK | PTRACE_VFORK | PTRACE_POSIX_SPAWN?
1078d9400b6SMichał Górny   events.pe_set_event |= PTRACE_LWP_CREATE | PTRACE_LWP_EXIT;
1088d9400b6SMichał Górny   status = PtraceWrapper(PT_SET_EVENT_MASK, pid, &events, sizeof(events));
1098d9400b6SMichał Górny   if (status.Fail())
1108d9400b6SMichał Górny     return status.ToError();
1118d9400b6SMichał 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 
2248d9400b6SMichał Górny   NativeThreadNetBSD* thread = nullptr;
2258d9400b6SMichał Górny   if (info.psi_lwpid > 0) {
2268d9400b6SMichał Górny     for (const auto &t : m_threads) {
2278d9400b6SMichał Górny       if (t->GetID() == static_cast<lldb::tid_t>(info.psi_lwpid)) {
2288d9400b6SMichał Górny         thread = static_cast<NativeThreadNetBSD *>(t.get());
2298d9400b6SMichał Górny         break;
2308d9400b6SMichał Górny       }
2318d9400b6SMichał Górny       static_cast<NativeThreadNetBSD *>(t.get())->SetStoppedWithNoReason();
2328d9400b6SMichał Górny     }
2338d9400b6SMichał Górny     if (!thread)
2348d9400b6SMichał Górny       LLDB_LOG(log,
2358d9400b6SMichał Górny                "thread not found in m_threads, pid = {0}, LWP = {1}", pid,
2368d9400b6SMichał Górny                info.psi_lwpid);
2378d9400b6SMichał Górny   }
2388d9400b6SMichał Górny 
239f07a9995SKamil Rytarowski   switch (info.psi_siginfo.si_code) {
240f07a9995SKamil Rytarowski   case TRAP_BRKPT:
2418d9400b6SMichał Górny     if (thread) {
2428d9400b6SMichał Górny       thread->SetStoppedByBreakpoint();
2438d9400b6SMichał Górny       FixupBreakpointPCAsNeeded(*thread);
244f07a9995SKamil Rytarowski     }
245f07a9995SKamil Rytarowski     SetState(StateType::eStateStopped, true);
246f07a9995SKamil Rytarowski     break;
2473eef2b5eSKamil Rytarowski   case TRAP_TRACE:
2488d9400b6SMichał Górny     if (thread)
2498d9400b6SMichał 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;
2668d9400b6SMichał Górny   case TRAP_LWP: {
2678d9400b6SMichał Górny     ptrace_state_t pst;
2688d9400b6SMichał Górny     Status error = PtraceWrapper(PT_GET_PROCESS_STATE, pid, &pst, sizeof(pst));
2698d9400b6SMichał Górny     if (error.Fail()) {
2708d9400b6SMichał Górny       SetState(StateType::eStateInvalid);
2718d9400b6SMichał Górny       return;
272baf64b65SMichal Gorny     }
2738d9400b6SMichał Górny 
2748d9400b6SMichał Górny     switch (pst.pe_report_event) {
275d970d4d4SMichał Górny       case PTRACE_LWP_CREATE: {
276baf64b65SMichal Gorny         LLDB_LOG(log,
2778d9400b6SMichał Górny                  "monitoring new thread, pid = {0}, LWP = {1}", pid,
2788d9400b6SMichał Górny                  pst.pe_lwp);
279d970d4d4SMichał Górny         NativeThreadNetBSD& t = AddThread(pst.pe_lwp);
280d970d4d4SMichał Górny         error = t.CopyWatchpointsFrom(
281d970d4d4SMichał Górny             static_cast<NativeThreadNetBSD &>(*GetCurrentThread()));
282d970d4d4SMichał Górny         if (error.Fail()) {
283d970d4d4SMichał Górny           LLDB_LOG(log,
284d970d4d4SMichał Górny                    "failed to copy watchpoints to new thread {0}: {1}",
285d970d4d4SMichał Górny                    pst.pe_lwp, error);
286d970d4d4SMichał Górny           SetState(StateType::eStateInvalid);
287d970d4d4SMichał Górny           return;
288d970d4d4SMichał Górny         }
289d970d4d4SMichał Górny       } break;
2908d9400b6SMichał Górny       case PTRACE_LWP_EXIT:
2918d9400b6SMichał Górny         LLDB_LOG(log,
2928d9400b6SMichał Górny                  "removing exited thread, pid = {0}, LWP = {1}", pid,
2938d9400b6SMichał Górny                  pst.pe_lwp);
2948d9400b6SMichał Górny         RemoveThread(pst.pe_lwp);
295baf64b65SMichal Gorny         break;
296baf64b65SMichal Gorny     }
297baf64b65SMichal Gorny 
2988d9400b6SMichał Górny     error = PtraceWrapper(PT_CONTINUE, pid, reinterpret_cast<void*>(1), 0);
2998d9400b6SMichał Górny     if (error.Fail()) {
3008d9400b6SMichał Górny       SetState(StateType::eStateInvalid);
3018d9400b6SMichał Górny       return;
3028d9400b6SMichał Górny     }
3038d9400b6SMichał Górny   } break;
3048d9400b6SMichał Górny   case TRAP_DBREG: {
3058d9400b6SMichał Górny     if (!thread)
3068d9400b6SMichał Górny       break;
3078d9400b6SMichał Górny 
3087644d8baSMichał Górny     auto &regctx = static_cast<NativeRegisterContextNetBSD &>(
3097644d8baSMichał Górny         thread->GetRegisterContext());
310baf64b65SMichal Gorny     uint32_t wp_index = LLDB_INVALID_INDEX32;
3117644d8baSMichał Górny     Status error = regctx.GetWatchpointHitIndex(wp_index,
3127644d8baSMichał Górny         (uintptr_t)info.psi_siginfo.si_addr);
31336e23ecaSKamil Rytarowski     if (error.Fail())
31436e23ecaSKamil Rytarowski       LLDB_LOG(log,
31536e23ecaSKamil Rytarowski                "received error while checking for watchpoint hits, pid = "
3168d9400b6SMichał Górny                "{0}, LWP = {1}, error = {2}", pid, info.psi_lwpid, error);
31736e23ecaSKamil Rytarowski     if (wp_index != LLDB_INVALID_INDEX32) {
3188d9400b6SMichał Górny       thread->SetStoppedByWatchpoint(wp_index);
3197644d8baSMichał Górny       regctx.ClearWatchpointHit(wp_index);
32036e23ecaSKamil Rytarowski       SetState(StateType::eStateStopped, true);
32136e23ecaSKamil Rytarowski       break;
32236e23ecaSKamil Rytarowski     }
32336e23ecaSKamil Rytarowski 
3248d9400b6SMichał Górny     thread->SetStoppedByTrace();
32536e23ecaSKamil Rytarowski     SetState(StateType::eStateStopped, true);
32636e23ecaSKamil Rytarowski   } break;
327f07a9995SKamil Rytarowski   }
328f07a9995SKamil Rytarowski }
329f07a9995SKamil Rytarowski 
330f07a9995SKamil Rytarowski void NativeProcessNetBSD::MonitorSignal(lldb::pid_t pid, int signal) {
331f07a9995SKamil Rytarowski   ptrace_siginfo_t info;
332f07a9995SKamil Rytarowski   const auto siginfo_err =
333f07a9995SKamil Rytarowski       PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info));
334f07a9995SKamil Rytarowski 
3358d9400b6SMichał Górny   for (const auto &abs_thread : m_threads) {
3368d9400b6SMichał Górny     NativeThreadNetBSD &thread = static_cast<NativeThreadNetBSD &>(*abs_thread);
3378d9400b6SMichał Górny     assert(info.psi_lwpid >= 0);
3388d9400b6SMichał Górny     if (info.psi_lwpid == 0 ||
3398d9400b6SMichał Górny         static_cast<lldb::tid_t>(info.psi_lwpid) == thread.GetID())
3408d9400b6SMichał Górny       thread.SetStoppedBySignal(info.psi_siginfo.si_signo, &info.psi_siginfo);
3418d9400b6SMichał Górny     else
3428d9400b6SMichał Górny       thread.SetStoppedWithNoReason();
343f07a9995SKamil Rytarowski   }
344f07a9995SKamil Rytarowski   SetState(StateType::eStateStopped, true);
345f07a9995SKamil Rytarowski }
346f07a9995SKamil Rytarowski 
34797206d57SZachary Turner Status NativeProcessNetBSD::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
348f07a9995SKamil Rytarowski                                           int data, int *result) {
349f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
35097206d57SZachary Turner   Status error;
351f07a9995SKamil Rytarowski   int ret;
352f07a9995SKamil Rytarowski 
353f07a9995SKamil Rytarowski   errno = 0;
354f07a9995SKamil Rytarowski   ret = ptrace(req, static_cast<::pid_t>(pid), addr, data);
355f07a9995SKamil Rytarowski 
356f07a9995SKamil Rytarowski   if (ret == -1)
357f07a9995SKamil Rytarowski     error.SetErrorToErrno();
358f07a9995SKamil Rytarowski 
359f07a9995SKamil Rytarowski   if (result)
360f07a9995SKamil Rytarowski     *result = ret;
361f07a9995SKamil Rytarowski 
362f07a9995SKamil Rytarowski   LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3})={4:x}", req, pid, addr, data, ret);
363f07a9995SKamil Rytarowski 
364f07a9995SKamil Rytarowski   if (error.Fail())
365f07a9995SKamil Rytarowski     LLDB_LOG(log, "ptrace() failed: {0}", error);
366f07a9995SKamil Rytarowski 
367f07a9995SKamil Rytarowski   return error;
368f07a9995SKamil Rytarowski }
369f07a9995SKamil Rytarowski 
3708d9400b6SMichał Górny static llvm::Expected<ptrace_siginfo_t> ComputeSignalInfo(
3718d9400b6SMichał Górny     const std::vector<std::unique_ptr<NativeThreadProtocol>> &threads,
3728d9400b6SMichał Górny     const ResumeActionList &resume_actions) {
3738d9400b6SMichał Górny   // We need to account for three possible scenarios:
3748d9400b6SMichał Górny   // 1. no signal being sent.
3758d9400b6SMichał Górny   // 2. a signal being sent to one thread.
3768d9400b6SMichał Górny   // 3. a signal being sent to the whole process.
3778d9400b6SMichał Górny 
3788d9400b6SMichał Górny   // Count signaled threads.  While at it, determine which signal is being sent
3798d9400b6SMichał Górny   // and ensure there's only one.
3808d9400b6SMichał Górny   size_t signaled_threads = 0;
3818d9400b6SMichał Górny   int signal = LLDB_INVALID_SIGNAL_NUMBER;
3828d9400b6SMichał Górny   lldb::tid_t signaled_lwp;
3838d9400b6SMichał Górny   for (const auto &thread : threads) {
3848d9400b6SMichał Górny     assert(thread && "thread list should not contain NULL threads");
3858d9400b6SMichał Górny     const ResumeAction *action =
3868d9400b6SMichał Górny         resume_actions.GetActionForThread(thread->GetID(), true);
3878d9400b6SMichał Górny     if (action) {
3888d9400b6SMichał Górny       if (action->signal != LLDB_INVALID_SIGNAL_NUMBER) {
3898d9400b6SMichał Górny         signaled_threads++;
3908d9400b6SMichał Górny         if (action->signal != signal) {
3918d9400b6SMichał Górny           if (signal != LLDB_INVALID_SIGNAL_NUMBER)
3928d9400b6SMichał Górny             return Status("NetBSD does not support passing multiple signals "
3938d9400b6SMichał Górny                           "simultaneously")
3948d9400b6SMichał Górny                 .ToError();
3958d9400b6SMichał Górny           signal = action->signal;
3968d9400b6SMichał Górny           signaled_lwp = thread->GetID();
3978d9400b6SMichał Górny         }
3988d9400b6SMichał Górny       }
3998d9400b6SMichał Górny     }
4008d9400b6SMichał Górny   }
4018d9400b6SMichał Górny 
4028d9400b6SMichał Górny   if (signaled_threads == 0) {
4038d9400b6SMichał Górny     ptrace_siginfo_t siginfo;
4048d9400b6SMichał Górny     siginfo.psi_siginfo.si_signo = LLDB_INVALID_SIGNAL_NUMBER;
4058d9400b6SMichał Górny     return siginfo;
4068d9400b6SMichał Górny   }
4078d9400b6SMichał Górny 
4088d9400b6SMichał Górny   if (signaled_threads > 1 && signaled_threads < threads.size())
4098d9400b6SMichał Górny     return Status("NetBSD does not support passing signal to 1<i<all threads")
4108d9400b6SMichał Górny         .ToError();
4118d9400b6SMichał Górny 
4128d9400b6SMichał Górny   ptrace_siginfo_t siginfo;
4138d9400b6SMichał Górny   siginfo.psi_siginfo.si_signo = signal;
4148d9400b6SMichał Górny   siginfo.psi_siginfo.si_code = SI_USER;
4158d9400b6SMichał Górny   siginfo.psi_siginfo.si_pid = getpid();
4168d9400b6SMichał Górny   siginfo.psi_siginfo.si_uid = getuid();
4178d9400b6SMichał Górny   if (signaled_threads == 1)
4188d9400b6SMichał Górny     siginfo.psi_lwpid = signaled_lwp;
4198d9400b6SMichał Górny   else // signal for the whole process
4208d9400b6SMichał Górny     siginfo.psi_lwpid = 0;
4218d9400b6SMichał Górny   return siginfo;
4228d9400b6SMichał Górny }
4238d9400b6SMichał Górny 
42497206d57SZachary Turner Status NativeProcessNetBSD::Resume(const ResumeActionList &resume_actions) {
425f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
426f07a9995SKamil Rytarowski   LLDB_LOG(log, "pid {0}", GetID());
427f07a9995SKamil Rytarowski 
4288d9400b6SMichał Górny   Status ret;
4298d9400b6SMichał Górny 
4308d9400b6SMichał Górny   Expected<ptrace_siginfo_t> siginfo =
4318d9400b6SMichał Górny       ComputeSignalInfo(m_threads, resume_actions);
4328d9400b6SMichał Górny   if (!siginfo)
4338d9400b6SMichał Górny     return Status(siginfo.takeError());
4348d9400b6SMichał Górny 
4358d9400b6SMichał Górny   for (const auto &abs_thread : m_threads) {
4368d9400b6SMichał Górny     assert(abs_thread && "thread list should not contain NULL threads");
4378d9400b6SMichał Górny     NativeThreadNetBSD &thread = static_cast<NativeThreadNetBSD &>(*abs_thread);
4388d9400b6SMichał Górny 
4398d9400b6SMichał Górny     const ResumeAction *action =
4408d9400b6SMichał Górny         resume_actions.GetActionForThread(thread.GetID(), true);
4418d9400b6SMichał Górny     // we need to explicit issue suspend requests, so it is simpler to map it
4428d9400b6SMichał Górny     // into proper action
4438d9400b6SMichał Górny     ResumeAction suspend_action{thread.GetID(), eStateSuspended,
4448d9400b6SMichał Górny                                 LLDB_INVALID_SIGNAL_NUMBER};
445f07a9995SKamil Rytarowski 
446f07a9995SKamil Rytarowski     if (action == nullptr) {
447f07a9995SKamil Rytarowski       LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
4488d9400b6SMichał Górny                thread.GetID());
4498d9400b6SMichał Górny       action = &suspend_action;
450f07a9995SKamil Rytarowski     }
451f07a9995SKamil Rytarowski 
4528d9400b6SMichał Górny     LLDB_LOG(
4538d9400b6SMichał Górny         log,
4548d9400b6SMichał Górny         "processing resume action state {0} signal {1} for pid {2} tid {3}",
4558d9400b6SMichał Górny         action->state, action->signal, GetID(), thread.GetID());
4563eef2b5eSKamil Rytarowski 
457f07a9995SKamil Rytarowski     switch (action->state) {
4588d9400b6SMichał Górny     case eStateRunning:
4598d9400b6SMichał Górny       ret = thread.Resume();
460f07a9995SKamil Rytarowski       break;
461f07a9995SKamil Rytarowski     case eStateStepping:
4628d9400b6SMichał Górny       ret = thread.SingleStep();
463f07a9995SKamil Rytarowski       break;
464f07a9995SKamil Rytarowski     case eStateSuspended:
465f07a9995SKamil Rytarowski     case eStateStopped:
4668d9400b6SMichał Górny       if (action->signal != LLDB_INVALID_SIGNAL_NUMBER)
4678d9400b6SMichał Górny         return Status("Passing signal to suspended thread unsupported");
4688d9400b6SMichał Górny 
4698d9400b6SMichał Górny       ret = thread.Suspend();
4708d9400b6SMichał Górny       break;
471f07a9995SKamil Rytarowski 
472f07a9995SKamil Rytarowski     default:
47397206d57SZachary Turner       return Status("NativeProcessNetBSD::%s (): unexpected state %s specified "
474f07a9995SKamil Rytarowski                     "for pid %" PRIu64 ", tid %" PRIu64,
475f07a9995SKamil Rytarowski                     __FUNCTION__, StateAsCString(action->state), GetID(),
4768d9400b6SMichał Górny                     thread.GetID());
477f07a9995SKamil Rytarowski     }
478f07a9995SKamil Rytarowski 
4798d9400b6SMichał Górny     if (!ret.Success())
4808d9400b6SMichał Górny       return ret;
4818d9400b6SMichał Górny   }
4828d9400b6SMichał Górny 
4838d9400b6SMichał Górny   int signal = 0;
4848d9400b6SMichał Górny   if (siginfo->psi_siginfo.si_signo != LLDB_INVALID_SIGNAL_NUMBER) {
4858d9400b6SMichał Górny     ret = PtraceWrapper(PT_SET_SIGINFO, GetID(), &siginfo.get(),
4868d9400b6SMichał Górny                         sizeof(*siginfo));
4878d9400b6SMichał Górny     if (!ret.Success())
4888d9400b6SMichał Górny       return ret;
4898d9400b6SMichał Górny     signal = siginfo->psi_siginfo.si_signo;
4908d9400b6SMichał Górny   }
4918d9400b6SMichał Górny 
4928d9400b6SMichał Górny   ret = PtraceWrapper(PT_CONTINUE, GetID(), reinterpret_cast<void *>(1),
4938d9400b6SMichał Górny                       signal);
4948d9400b6SMichał Górny   if (ret.Success())
4958d9400b6SMichał Górny     SetState(eStateRunning, true);
4968d9400b6SMichał Górny   return ret;
497f07a9995SKamil Rytarowski }
498f07a9995SKamil Rytarowski 
49997206d57SZachary Turner Status NativeProcessNetBSD::Halt() {
50077cc2464SMichał Górny   return PtraceWrapper(PT_STOP, GetID());
501f07a9995SKamil Rytarowski }
502f07a9995SKamil Rytarowski 
50397206d57SZachary Turner Status NativeProcessNetBSD::Detach() {
50497206d57SZachary Turner   Status error;
505f07a9995SKamil Rytarowski 
506f07a9995SKamil Rytarowski   // Stop monitoring the inferior.
507f07a9995SKamil Rytarowski   m_sigchld_handle.reset();
508f07a9995SKamil Rytarowski 
509f07a9995SKamil Rytarowski   // Tell ptrace to detach from the process.
510f07a9995SKamil Rytarowski   if (GetID() == LLDB_INVALID_PROCESS_ID)
511f07a9995SKamil Rytarowski     return error;
512f07a9995SKamil Rytarowski 
513f07a9995SKamil Rytarowski   return PtraceWrapper(PT_DETACH, GetID());
514f07a9995SKamil Rytarowski }
515f07a9995SKamil Rytarowski 
51697206d57SZachary Turner Status NativeProcessNetBSD::Signal(int signo) {
51797206d57SZachary Turner   Status error;
518f07a9995SKamil Rytarowski 
519f07a9995SKamil Rytarowski   if (kill(GetID(), signo))
520f07a9995SKamil Rytarowski     error.SetErrorToErrno();
521f07a9995SKamil Rytarowski 
522f07a9995SKamil Rytarowski   return error;
523f07a9995SKamil Rytarowski }
524f07a9995SKamil Rytarowski 
52577cc2464SMichał Górny Status NativeProcessNetBSD::Interrupt() {
52677cc2464SMichał Górny   return PtraceWrapper(PT_STOP, GetID());
52777cc2464SMichał Górny }
52877cc2464SMichał Górny 
52997206d57SZachary Turner Status NativeProcessNetBSD::Kill() {
530f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
531f07a9995SKamil Rytarowski   LLDB_LOG(log, "pid {0}", GetID());
532f07a9995SKamil Rytarowski 
53397206d57SZachary Turner   Status error;
534f07a9995SKamil Rytarowski 
535f07a9995SKamil Rytarowski   switch (m_state) {
536f07a9995SKamil Rytarowski   case StateType::eStateInvalid:
537f07a9995SKamil Rytarowski   case StateType::eStateExited:
538f07a9995SKamil Rytarowski   case StateType::eStateCrashed:
539f07a9995SKamil Rytarowski   case StateType::eStateDetached:
540f07a9995SKamil Rytarowski   case StateType::eStateUnloaded:
541f07a9995SKamil Rytarowski     // Nothing to do - the process is already dead.
542f07a9995SKamil Rytarowski     LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
543f07a9995SKamil Rytarowski              StateAsCString(m_state));
544f07a9995SKamil Rytarowski     return error;
545f07a9995SKamil Rytarowski 
546f07a9995SKamil Rytarowski   case StateType::eStateConnected:
547f07a9995SKamil Rytarowski   case StateType::eStateAttaching:
548f07a9995SKamil Rytarowski   case StateType::eStateLaunching:
549f07a9995SKamil Rytarowski   case StateType::eStateStopped:
550f07a9995SKamil Rytarowski   case StateType::eStateRunning:
551f07a9995SKamil Rytarowski   case StateType::eStateStepping:
552f07a9995SKamil Rytarowski   case StateType::eStateSuspended:
553f07a9995SKamil Rytarowski     // We can try to kill a process in these states.
554f07a9995SKamil Rytarowski     break;
555f07a9995SKamil Rytarowski   }
556f07a9995SKamil Rytarowski 
557f07a9995SKamil Rytarowski   if (kill(GetID(), SIGKILL) != 0) {
558f07a9995SKamil Rytarowski     error.SetErrorToErrno();
559f07a9995SKamil Rytarowski     return error;
560f07a9995SKamil Rytarowski   }
561f07a9995SKamil Rytarowski 
562f07a9995SKamil Rytarowski   return error;
563f07a9995SKamil Rytarowski }
564f07a9995SKamil Rytarowski 
56597206d57SZachary Turner Status NativeProcessNetBSD::GetMemoryRegionInfo(lldb::addr_t load_addr,
566f07a9995SKamil Rytarowski                                                 MemoryRegionInfo &range_info) {
567f07a9995SKamil Rytarowski 
568f07a9995SKamil Rytarowski   if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
569f07a9995SKamil Rytarowski     // We're done.
57097206d57SZachary Turner     return Status("unsupported");
571f07a9995SKamil Rytarowski   }
572f07a9995SKamil Rytarowski 
57397206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
574f07a9995SKamil Rytarowski   if (error.Fail()) {
575f07a9995SKamil Rytarowski     return error;
576f07a9995SKamil Rytarowski   }
577f07a9995SKamil Rytarowski 
578f07a9995SKamil Rytarowski   lldb::addr_t prev_base_address = 0;
579f07a9995SKamil Rytarowski   // FIXME start by finding the last region that is <= target address using
580f07a9995SKamil Rytarowski   // binary search.  Data is sorted.
581f07a9995SKamil Rytarowski   // There can be a ton of regions on pthreads apps with lots of threads.
582f07a9995SKamil Rytarowski   for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
583f07a9995SKamil Rytarowski        ++it) {
584f07a9995SKamil Rytarowski     MemoryRegionInfo &proc_entry_info = it->first;
585f07a9995SKamil Rytarowski     // Sanity check assumption that memory map entries are ascending.
586f07a9995SKamil Rytarowski     assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
587f07a9995SKamil Rytarowski            "descending memory map entries detected, unexpected");
588f07a9995SKamil Rytarowski     prev_base_address = proc_entry_info.GetRange().GetRangeBase();
589f07a9995SKamil Rytarowski     UNUSED_IF_ASSERT_DISABLED(prev_base_address);
59005097246SAdrian Prantl     // If the target address comes before this entry, indicate distance to next
59105097246SAdrian Prantl     // region.
592f07a9995SKamil Rytarowski     if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
593f07a9995SKamil Rytarowski       range_info.GetRange().SetRangeBase(load_addr);
594f07a9995SKamil Rytarowski       range_info.GetRange().SetByteSize(
595f07a9995SKamil Rytarowski           proc_entry_info.GetRange().GetRangeBase() - load_addr);
596f07a9995SKamil Rytarowski       range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
597f07a9995SKamil Rytarowski       range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
598f07a9995SKamil Rytarowski       range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
599f07a9995SKamil Rytarowski       range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
600f07a9995SKamil Rytarowski       return error;
601f07a9995SKamil Rytarowski     } else if (proc_entry_info.GetRange().Contains(load_addr)) {
602f07a9995SKamil Rytarowski       // The target address is within the memory region we're processing here.
603f07a9995SKamil Rytarowski       range_info = proc_entry_info;
604f07a9995SKamil Rytarowski       return error;
605f07a9995SKamil Rytarowski     }
606f07a9995SKamil Rytarowski     // The target memory address comes somewhere after the region we just
607f07a9995SKamil Rytarowski     // parsed.
608f07a9995SKamil Rytarowski   }
609f07a9995SKamil Rytarowski   // If we made it here, we didn't find an entry that contained the given
61005097246SAdrian Prantl   // address. Return the load_addr as start and the amount of bytes betwwen
61105097246SAdrian Prantl   // load address and the end of the memory as size.
612f07a9995SKamil Rytarowski   range_info.GetRange().SetRangeBase(load_addr);
613f07a9995SKamil Rytarowski   range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
614f07a9995SKamil Rytarowski   range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
615f07a9995SKamil Rytarowski   range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
616f07a9995SKamil Rytarowski   range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
617f07a9995SKamil Rytarowski   range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
618f07a9995SKamil Rytarowski   return error;
619f07a9995SKamil Rytarowski }
620f07a9995SKamil Rytarowski 
62197206d57SZachary Turner Status NativeProcessNetBSD::PopulateMemoryRegionCache() {
622f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
623f07a9995SKamil Rytarowski   // If our cache is empty, pull the latest.  There should always be at least
624f07a9995SKamil Rytarowski   // one memory region if memory region handling is supported.
625f07a9995SKamil Rytarowski   if (!m_mem_region_cache.empty()) {
626f07a9995SKamil Rytarowski     LLDB_LOG(log, "reusing {0} cached memory region entries",
627f07a9995SKamil Rytarowski              m_mem_region_cache.size());
62897206d57SZachary Turner     return Status();
629f07a9995SKamil Rytarowski   }
630f07a9995SKamil Rytarowski 
631f07a9995SKamil Rytarowski   struct kinfo_vmentry *vm;
632f07a9995SKamil Rytarowski   size_t count, i;
633f07a9995SKamil Rytarowski   vm = kinfo_getvmmap(GetID(), &count);
634f07a9995SKamil Rytarowski   if (vm == NULL) {
635f07a9995SKamil Rytarowski     m_supports_mem_region = LazyBool::eLazyBoolNo;
63697206d57SZachary Turner     Status error;
637f07a9995SKamil Rytarowski     error.SetErrorString("not supported");
638f07a9995SKamil Rytarowski     return error;
639f07a9995SKamil Rytarowski   }
640f07a9995SKamil Rytarowski   for (i = 0; i < count; i++) {
641f07a9995SKamil Rytarowski     MemoryRegionInfo info;
642f07a9995SKamil Rytarowski     info.Clear();
643f07a9995SKamil Rytarowski     info.GetRange().SetRangeBase(vm[i].kve_start);
644f07a9995SKamil Rytarowski     info.GetRange().SetRangeEnd(vm[i].kve_end);
645f07a9995SKamil Rytarowski     info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
646f07a9995SKamil Rytarowski 
647f07a9995SKamil Rytarowski     if (vm[i].kve_protection & VM_PROT_READ)
648f07a9995SKamil Rytarowski       info.SetReadable(MemoryRegionInfo::OptionalBool::eYes);
649f07a9995SKamil Rytarowski     else
650f07a9995SKamil Rytarowski       info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
651f07a9995SKamil Rytarowski 
652f07a9995SKamil Rytarowski     if (vm[i].kve_protection & VM_PROT_WRITE)
653f07a9995SKamil Rytarowski       info.SetWritable(MemoryRegionInfo::OptionalBool::eYes);
654f07a9995SKamil Rytarowski     else
655f07a9995SKamil Rytarowski       info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
656f07a9995SKamil Rytarowski 
657f07a9995SKamil Rytarowski     if (vm[i].kve_protection & VM_PROT_EXECUTE)
658f07a9995SKamil Rytarowski       info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes);
659f07a9995SKamil Rytarowski     else
660f07a9995SKamil Rytarowski       info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
661f07a9995SKamil Rytarowski 
662f07a9995SKamil Rytarowski     if (vm[i].kve_path[0])
663f07a9995SKamil Rytarowski       info.SetName(vm[i].kve_path);
664f07a9995SKamil Rytarowski 
665f07a9995SKamil Rytarowski     m_mem_region_cache.emplace_back(
666a0a44e9cSKamil Rytarowski         info, FileSpec(info.GetName().GetCString()));
667f07a9995SKamil Rytarowski   }
668f07a9995SKamil Rytarowski   free(vm);
669f07a9995SKamil Rytarowski 
670f07a9995SKamil Rytarowski   if (m_mem_region_cache.empty()) {
67105097246SAdrian Prantl     // No entries after attempting to read them.  This shouldn't happen. Assume
67205097246SAdrian Prantl     // we don't support map entries.
673f07a9995SKamil Rytarowski     LLDB_LOG(log, "failed to find any vmmap entries, assuming no support "
674f07a9995SKamil Rytarowski                   "for memory region metadata retrieval");
675f07a9995SKamil Rytarowski     m_supports_mem_region = LazyBool::eLazyBoolNo;
67697206d57SZachary Turner     Status error;
677f07a9995SKamil Rytarowski     error.SetErrorString("not supported");
678f07a9995SKamil Rytarowski     return error;
679f07a9995SKamil Rytarowski   }
680f07a9995SKamil Rytarowski   LLDB_LOG(log, "read {0} memory region entries from process {1}",
681f07a9995SKamil Rytarowski            m_mem_region_cache.size(), GetID());
682f07a9995SKamil Rytarowski   // We support memory retrieval, remember that.
683f07a9995SKamil Rytarowski   m_supports_mem_region = LazyBool::eLazyBoolYes;
68497206d57SZachary Turner   return Status();
685f07a9995SKamil Rytarowski }
686f07a9995SKamil Rytarowski 
68797206d57SZachary Turner Status NativeProcessNetBSD::AllocateMemory(size_t size, uint32_t permissions,
688f07a9995SKamil Rytarowski                                            lldb::addr_t &addr) {
68997206d57SZachary Turner   return Status("Unimplemented");
690f07a9995SKamil Rytarowski }
691f07a9995SKamil Rytarowski 
69297206d57SZachary Turner Status NativeProcessNetBSD::DeallocateMemory(lldb::addr_t addr) {
69397206d57SZachary Turner   return Status("Unimplemented");
694f07a9995SKamil Rytarowski }
695f07a9995SKamil Rytarowski 
696f07a9995SKamil Rytarowski lldb::addr_t NativeProcessNetBSD::GetSharedLibraryInfoAddress() {
697f07a9995SKamil Rytarowski   // punt on this for now
698f07a9995SKamil Rytarowski   return LLDB_INVALID_ADDRESS;
699f07a9995SKamil Rytarowski }
700f07a9995SKamil Rytarowski 
701f07a9995SKamil Rytarowski size_t NativeProcessNetBSD::UpdateThreads() { return m_threads.size(); }
702f07a9995SKamil Rytarowski 
70397206d57SZachary Turner Status NativeProcessNetBSD::SetBreakpoint(lldb::addr_t addr, uint32_t size,
704f07a9995SKamil Rytarowski                                           bool hardware) {
705f07a9995SKamil Rytarowski   if (hardware)
70697206d57SZachary Turner     return Status("NativeProcessNetBSD does not support hardware breakpoints");
707f07a9995SKamil Rytarowski   else
708f07a9995SKamil Rytarowski     return SetSoftwareBreakpoint(addr, size);
709f07a9995SKamil Rytarowski }
710f07a9995SKamil Rytarowski 
71197206d57SZachary Turner Status NativeProcessNetBSD::GetLoadedModuleFileSpec(const char *module_path,
712f07a9995SKamil Rytarowski                                                     FileSpec &file_spec) {
71397206d57SZachary Turner   return Status("Unimplemented");
714f07a9995SKamil Rytarowski }
715f07a9995SKamil Rytarowski 
71697206d57SZachary Turner Status NativeProcessNetBSD::GetFileLoadAddress(const llvm::StringRef &file_name,
717f07a9995SKamil Rytarowski                                                lldb::addr_t &load_addr) {
718f07a9995SKamil Rytarowski   load_addr = LLDB_INVALID_ADDRESS;
71997206d57SZachary Turner   return Status();
720f07a9995SKamil Rytarowski }
721f07a9995SKamil Rytarowski 
722f07a9995SKamil Rytarowski void NativeProcessNetBSD::SigchldHandler() {
723f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
724f07a9995SKamil Rytarowski   // Process all pending waitpid notifications.
725f07a9995SKamil Rytarowski   int status;
726c1a6b128SPavel Labath   ::pid_t wait_pid =
727c1a6b128SPavel Labath       llvm::sys::RetryAfterSignal(-1, waitpid, GetID(), &status, WALLSIG | WNOHANG);
728f07a9995SKamil Rytarowski 
729f07a9995SKamil Rytarowski   if (wait_pid == 0)
730f07a9995SKamil Rytarowski     return; // We are done.
731f07a9995SKamil Rytarowski 
732f07a9995SKamil Rytarowski   if (wait_pid == -1) {
73397206d57SZachary Turner     Status error(errno, eErrorTypePOSIX);
734f07a9995SKamil Rytarowski     LLDB_LOG(log, "waitpid ({0}, &status, _) failed: {1}", GetID(), error);
735f07a9995SKamil Rytarowski   }
736f07a9995SKamil Rytarowski 
7373508fc8cSPavel Labath   WaitStatus wait_status = WaitStatus::Decode(status);
7383508fc8cSPavel Labath   bool exited = wait_status.type == WaitStatus::Exit ||
7393508fc8cSPavel Labath                 (wait_status.type == WaitStatus::Signal &&
7403508fc8cSPavel Labath                  wait_pid == static_cast<::pid_t>(GetID()));
741f07a9995SKamil Rytarowski 
742f07a9995SKamil Rytarowski   LLDB_LOG(log,
7433508fc8cSPavel Labath            "waitpid ({0}, &status, _) => pid = {1}, status = {2}, exited = {3}",
7443508fc8cSPavel Labath            GetID(), wait_pid, status, exited);
745f07a9995SKamil Rytarowski 
746f07a9995SKamil Rytarowski   if (exited)
7473508fc8cSPavel Labath     MonitorExited(wait_pid, wait_status);
7483508fc8cSPavel Labath   else {
7494bb74415SKamil Rytarowski     assert(wait_status.type == WaitStatus::Stop);
7503508fc8cSPavel Labath     MonitorCallback(wait_pid, wait_status.status);
7513508fc8cSPavel Labath   }
752f07a9995SKamil Rytarowski }
753f07a9995SKamil Rytarowski 
754269eec03SKamil Rytarowski bool NativeProcessNetBSD::HasThreadNoLock(lldb::tid_t thread_id) {
755a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
756a5be48b3SPavel Labath     assert(thread && "thread list should not contain NULL threads");
757a5be48b3SPavel Labath     if (thread->GetID() == thread_id) {
758269eec03SKamil Rytarowski       // We have this thread.
759269eec03SKamil Rytarowski       return true;
760269eec03SKamil Rytarowski     }
761269eec03SKamil Rytarowski   }
762269eec03SKamil Rytarowski 
763269eec03SKamil Rytarowski   // We don't have this thread.
764269eec03SKamil Rytarowski   return false;
765269eec03SKamil Rytarowski }
766269eec03SKamil Rytarowski 
767a5be48b3SPavel Labath NativeThreadNetBSD &NativeProcessNetBSD::AddThread(lldb::tid_t thread_id) {
768f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
769f07a9995SKamil Rytarowski   LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
770f07a9995SKamil Rytarowski 
7718d9400b6SMichał Górny   assert(thread_id > 0);
772f07a9995SKamil Rytarowski   assert(!HasThreadNoLock(thread_id) &&
773f07a9995SKamil Rytarowski          "attempted to add a thread by id that already exists");
774f07a9995SKamil Rytarowski 
775f07a9995SKamil Rytarowski   // If this is the first thread, save it as the current thread
776f07a9995SKamil Rytarowski   if (m_threads.empty())
777f07a9995SKamil Rytarowski     SetCurrentThreadID(thread_id);
778f07a9995SKamil Rytarowski 
779a8f3ae7cSJonas Devlieghere   m_threads.push_back(std::make_unique<NativeThreadNetBSD>(*this, thread_id));
780a5be48b3SPavel Labath   return static_cast<NativeThreadNetBSD &>(*m_threads.back());
781f07a9995SKamil Rytarowski }
782f07a9995SKamil Rytarowski 
7838d9400b6SMichał Górny void NativeProcessNetBSD::RemoveThread(lldb::tid_t thread_id) {
7848d9400b6SMichał Górny   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
7858d9400b6SMichał Górny   LLDB_LOG(log, "pid {0} removing thread with tid {1}", GetID(), thread_id);
7868d9400b6SMichał Górny 
7878d9400b6SMichał Górny   assert(thread_id > 0);
7888d9400b6SMichał Górny   assert(HasThreadNoLock(thread_id) &&
7898d9400b6SMichał Górny          "attempted to remove a thread that does not exist");
7908d9400b6SMichał Górny 
7918d9400b6SMichał Górny   for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
7928d9400b6SMichał Górny     if ((*it)->GetID() == thread_id) {
7938d9400b6SMichał Górny       m_threads.erase(it);
7948d9400b6SMichał Górny       break;
7958d9400b6SMichał Górny     }
7968d9400b6SMichał Górny   }
7978d9400b6SMichał Górny }
7988d9400b6SMichał Górny 
79996e600fcSPavel Labath Status NativeProcessNetBSD::Attach() {
800f07a9995SKamil Rytarowski   // Attach to the requested process.
801f07a9995SKamil Rytarowski   // An attach will cause the thread to stop with a SIGSTOP.
80296e600fcSPavel Labath   Status status = PtraceWrapper(PT_ATTACH, m_pid);
80396e600fcSPavel Labath   if (status.Fail())
80496e600fcSPavel Labath     return status;
805f07a9995SKamil Rytarowski 
80696e600fcSPavel Labath   int wstatus;
80705097246SAdrian Prantl   // Need to use WALLSIG otherwise we receive an error with errno=ECHLD At this
80805097246SAdrian Prantl   // point we should have a thread stopped if waitpid succeeds.
8092819136fSMichal Gorny   if ((wstatus = llvm::sys::RetryAfterSignal(-1, waitpid,
810c5d7bc86SMichal Gorny           m_pid, nullptr, WALLSIG)) < 0)
81196e600fcSPavel Labath     return Status(errno, eErrorTypePOSIX);
812f07a9995SKamil Rytarowski 
813f07a9995SKamil Rytarowski   /* Initialize threads */
81496e600fcSPavel Labath   status = ReinitializeThreads();
81596e600fcSPavel Labath   if (status.Fail())
81696e600fcSPavel Labath     return status;
817f07a9995SKamil Rytarowski 
818a5be48b3SPavel Labath   for (const auto &thread : m_threads)
819a5be48b3SPavel Labath     static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(SIGSTOP);
82036e23ecaSKamil Rytarowski 
821f07a9995SKamil Rytarowski   // Let our process instance know the thread has stopped.
822f07a9995SKamil Rytarowski   SetState(StateType::eStateStopped);
82396e600fcSPavel Labath   return Status();
824f07a9995SKamil Rytarowski }
825f07a9995SKamil Rytarowski 
82697206d57SZachary Turner Status NativeProcessNetBSD::ReadMemory(lldb::addr_t addr, void *buf,
82797206d57SZachary Turner                                        size_t size, size_t &bytes_read) {
828f07a9995SKamil Rytarowski   unsigned char *dst = static_cast<unsigned char *>(buf);
829f07a9995SKamil Rytarowski   struct ptrace_io_desc io;
830f07a9995SKamil Rytarowski 
831f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
832f07a9995SKamil Rytarowski   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
833f07a9995SKamil Rytarowski 
834f07a9995SKamil Rytarowski   bytes_read = 0;
835f07a9995SKamil Rytarowski   io.piod_op = PIOD_READ_D;
836f07a9995SKamil Rytarowski   io.piod_len = size;
837f07a9995SKamil Rytarowski 
838f07a9995SKamil Rytarowski   do {
839f07a9995SKamil Rytarowski     io.piod_offs = (void *)(addr + bytes_read);
840f07a9995SKamil Rytarowski     io.piod_addr = dst + bytes_read;
841f07a9995SKamil Rytarowski 
84297206d57SZachary Turner     Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
843d14a0de9SMichal Gorny     if (error.Fail() || io.piod_len == 0)
844f07a9995SKamil Rytarowski       return error;
845f07a9995SKamil Rytarowski 
846d14a0de9SMichal Gorny     bytes_read += io.piod_len;
847f07a9995SKamil Rytarowski     io.piod_len = size - bytes_read;
848f07a9995SKamil Rytarowski   } while (bytes_read < size);
849f07a9995SKamil Rytarowski 
85097206d57SZachary Turner   return Status();
851f07a9995SKamil Rytarowski }
852f07a9995SKamil Rytarowski 
85397206d57SZachary Turner Status NativeProcessNetBSD::WriteMemory(lldb::addr_t addr, const void *buf,
854f07a9995SKamil Rytarowski                                         size_t size, size_t &bytes_written) {
855f07a9995SKamil Rytarowski   const unsigned char *src = static_cast<const unsigned char *>(buf);
85697206d57SZachary Turner   Status error;
857f07a9995SKamil Rytarowski   struct ptrace_io_desc io;
858f07a9995SKamil Rytarowski 
859f07a9995SKamil Rytarowski   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
860f07a9995SKamil Rytarowski   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
861f07a9995SKamil Rytarowski 
862f07a9995SKamil Rytarowski   bytes_written = 0;
863f07a9995SKamil Rytarowski   io.piod_op = PIOD_WRITE_D;
864f07a9995SKamil Rytarowski   io.piod_len = size;
865f07a9995SKamil Rytarowski 
866f07a9995SKamil Rytarowski   do {
867269eec03SKamil Rytarowski     io.piod_addr = const_cast<void *>(static_cast<const void *>(src + bytes_written));
868f07a9995SKamil Rytarowski     io.piod_offs = (void *)(addr + bytes_written);
869f07a9995SKamil Rytarowski 
87097206d57SZachary Turner     Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
871d14a0de9SMichal Gorny     if (error.Fail() || io.piod_len == 0)
872f07a9995SKamil Rytarowski       return error;
873f07a9995SKamil Rytarowski 
874d14a0de9SMichal Gorny     bytes_written += io.piod_len;
875f07a9995SKamil Rytarowski     io.piod_len = size - bytes_written;
876f07a9995SKamil Rytarowski   } while (bytes_written < size);
877f07a9995SKamil Rytarowski 
878f07a9995SKamil Rytarowski   return error;
879f07a9995SKamil Rytarowski }
880f07a9995SKamil Rytarowski 
881f07a9995SKamil Rytarowski llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
882f07a9995SKamil Rytarowski NativeProcessNetBSD::GetAuxvData() const {
883f07a9995SKamil Rytarowski   /*
884f07a9995SKamil Rytarowski    * ELF_AUX_ENTRIES is currently restricted to kernel
885f07a9995SKamil Rytarowski    * (<sys/exec_elf.h> r. 1.155 specifies 15)
886f07a9995SKamil Rytarowski    *
887f07a9995SKamil Rytarowski    * ptrace(2) returns the whole AUXV including extra fiels after AT_NULL this
888f07a9995SKamil Rytarowski    * information isn't needed.
889f07a9995SKamil Rytarowski    */
890f07a9995SKamil Rytarowski   size_t auxv_size = 100 * sizeof(AuxInfo);
891f07a9995SKamil Rytarowski 
892e831bb3cSPavel Labath   ErrorOr<std::unique_ptr<WritableMemoryBuffer>> buf =
893dbda2851SPavel Labath       llvm::WritableMemoryBuffer::getNewMemBuffer(auxv_size);
894f07a9995SKamil Rytarowski 
895269eec03SKamil Rytarowski   struct ptrace_io_desc io;
896269eec03SKamil Rytarowski   io.piod_op = PIOD_READ_AUXV;
897269eec03SKamil Rytarowski   io.piod_offs = 0;
898e831bb3cSPavel Labath   io.piod_addr = static_cast<void *>(buf.get()->getBufferStart());
899269eec03SKamil Rytarowski   io.piod_len = auxv_size;
900f07a9995SKamil Rytarowski 
90197206d57SZachary Turner   Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
902f07a9995SKamil Rytarowski 
903f07a9995SKamil Rytarowski   if (error.Fail())
904f07a9995SKamil Rytarowski     return std::error_code(error.GetError(), std::generic_category());
905f07a9995SKamil Rytarowski 
906f07a9995SKamil Rytarowski   if (io.piod_len < 1)
907f07a9995SKamil Rytarowski     return std::error_code(ECANCELED, std::generic_category());
908f07a9995SKamil Rytarowski 
909e831bb3cSPavel Labath   return std::move(buf);
910f07a9995SKamil Rytarowski }
9113eef2b5eSKamil Rytarowski 
91297206d57SZachary Turner Status NativeProcessNetBSD::ReinitializeThreads() {
9133eef2b5eSKamil Rytarowski   // Clear old threads
9143eef2b5eSKamil Rytarowski   m_threads.clear();
9153eef2b5eSKamil Rytarowski 
9163eef2b5eSKamil Rytarowski   // Initialize new thread
917*ab8a7a29SKamil Rytarowski #ifdef PT_LWPSTATUS
918*ab8a7a29SKamil Rytarowski   struct ptrace_lwpstatus info = {};
919*ab8a7a29SKamil Rytarowski   int op = PT_LWPNEXT;
920*ab8a7a29SKamil Rytarowski #else
9213eef2b5eSKamil Rytarowski   struct ptrace_lwpinfo info = {};
922*ab8a7a29SKamil Rytarowski   int op = PT_LWPINFO;
923*ab8a7a29SKamil Rytarowski #endif
924*ab8a7a29SKamil Rytarowski 
925*ab8a7a29SKamil Rytarowski   Status error = PtraceWrapper(op, GetID(), &info, sizeof(info));
926*ab8a7a29SKamil Rytarowski 
9273eef2b5eSKamil Rytarowski   if (error.Fail()) {
9283eef2b5eSKamil Rytarowski     return error;
9293eef2b5eSKamil Rytarowski   }
9303eef2b5eSKamil Rytarowski   // Reinitialize from scratch threads and register them in process
9313eef2b5eSKamil Rytarowski   while (info.pl_lwpid != 0) {
932a5be48b3SPavel Labath     AddThread(info.pl_lwpid);
933*ab8a7a29SKamil Rytarowski     error = PtraceWrapper(op, GetID(), &info, sizeof(info));
9343eef2b5eSKamil Rytarowski     if (error.Fail()) {
9353eef2b5eSKamil Rytarowski       return error;
9363eef2b5eSKamil Rytarowski     }
9373eef2b5eSKamil Rytarowski   }
9383eef2b5eSKamil Rytarowski 
9393eef2b5eSKamil Rytarowski   return error;
9403eef2b5eSKamil Rytarowski }
941