1 //===-- NativeProcessNetBSD.cpp -------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "NativeProcessNetBSD.h"
10 
11 #include "Plugins/Process/NetBSD/NativeRegisterContextNetBSD.h"
12 #include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
13 #include "lldb/Host/HostProcess.h"
14 #include "lldb/Host/common/NativeRegisterContext.h"
15 #include "lldb/Host/posix/ProcessLauncherPosixFork.h"
16 #include "lldb/Target/Process.h"
17 #include "lldb/Utility/State.h"
18 #include "llvm/Support/Errno.h"
19 
20 // System includes - They have to be included after framework includes because
21 // they define some macros which collide with variable names in other modules
22 // clang-format off
23 #include <sys/types.h>
24 #include <sys/ptrace.h>
25 #include <sys/sysctl.h>
26 #include <sys/wait.h>
27 #include <uvm/uvm_prot.h>
28 #include <elf.h>
29 #include <util.h>
30 // clang-format on
31 
32 using namespace lldb;
33 using namespace lldb_private;
34 using namespace lldb_private::process_netbsd;
35 using namespace llvm;
36 
37 // Simple helper function to ensure flags are enabled on the given file
38 // descriptor.
39 static Status EnsureFDFlags(int fd, int flags) {
40   Status error;
41 
42   int status = fcntl(fd, F_GETFL);
43   if (status == -1) {
44     error.SetErrorToErrno();
45     return error;
46   }
47 
48   if (fcntl(fd, F_SETFL, status | flags) == -1) {
49     error.SetErrorToErrno();
50     return error;
51   }
52 
53   return error;
54 }
55 
56 // Public Static Methods
57 
58 llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
59 NativeProcessNetBSD::Factory::Launch(ProcessLaunchInfo &launch_info,
60                                      NativeDelegate &native_delegate,
61                                      MainLoop &mainloop) const {
62   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
63 
64   Status status;
65   ::pid_t pid = ProcessLauncherPosixFork()
66                     .LaunchProcess(launch_info, status)
67                     .GetProcessId();
68   LLDB_LOG(log, "pid = {0:x}", pid);
69   if (status.Fail()) {
70     LLDB_LOG(log, "failed to launch process: {0}", status);
71     return status.ToError();
72   }
73 
74   // Wait for the child process to trap on its call to execve.
75   int wstatus;
76   ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0);
77   assert(wpid == pid);
78   (void)wpid;
79   if (!WIFSTOPPED(wstatus)) {
80     LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}",
81              WaitStatus::Decode(wstatus));
82     return llvm::make_error<StringError>("Could not sync with inferior process",
83                                          llvm::inconvertibleErrorCode());
84   }
85   LLDB_LOG(log, "inferior started, now in stopped state");
86 
87   ProcessInstanceInfo Info;
88   if (!Host::GetProcessInfo(pid, Info)) {
89     return llvm::make_error<StringError>("Cannot get process architecture",
90                                          llvm::inconvertibleErrorCode());
91   }
92 
93   // Set the architecture to the exe architecture.
94   LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid,
95            Info.GetArchitecture().GetArchitectureName());
96 
97   std::unique_ptr<NativeProcessNetBSD> process_up(new NativeProcessNetBSD(
98       pid, launch_info.GetPTY().ReleasePrimaryFileDescriptor(), native_delegate,
99       Info.GetArchitecture(), mainloop));
100 
101   status = process_up->SetupTrace();
102   if (status.Fail())
103     return status.ToError();
104 
105   for (const auto &thread : process_up->m_threads)
106     static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(SIGSTOP);
107   process_up->SetState(StateType::eStateStopped, false);
108 
109   return std::move(process_up);
110 }
111 
112 llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
113 NativeProcessNetBSD::Factory::Attach(
114     lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
115     MainLoop &mainloop) const {
116   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
117   LLDB_LOG(log, "pid = {0:x}", pid);
118 
119   // Retrieve the architecture for the running process.
120   ProcessInstanceInfo Info;
121   if (!Host::GetProcessInfo(pid, Info)) {
122     return llvm::make_error<StringError>("Cannot get process architecture",
123                                          llvm::inconvertibleErrorCode());
124   }
125 
126   std::unique_ptr<NativeProcessNetBSD> process_up(new NativeProcessNetBSD(
127       pid, -1, native_delegate, Info.GetArchitecture(), mainloop));
128 
129   Status status = process_up->Attach();
130   if (!status.Success())
131     return status.ToError();
132 
133   return std::move(process_up);
134 }
135 
136 // Public Instance Methods
137 
138 NativeProcessNetBSD::NativeProcessNetBSD(::pid_t pid, int terminal_fd,
139                                          NativeDelegate &delegate,
140                                          const ArchSpec &arch,
141                                          MainLoop &mainloop)
142     : NativeProcessELF(pid, terminal_fd, delegate), m_arch(arch) {
143   if (m_terminal_fd != -1) {
144     Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
145     assert(status.Success());
146   }
147 
148   Status status;
149   m_sigchld_handle = mainloop.RegisterSignal(
150       SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status);
151   assert(m_sigchld_handle && status.Success());
152 }
153 
154 // Handles all waitpid events from the inferior process.
155 void NativeProcessNetBSD::MonitorCallback(lldb::pid_t pid, int signal) {
156   switch (signal) {
157   case SIGTRAP:
158     return MonitorSIGTRAP(pid);
159   case SIGSTOP:
160     return MonitorSIGSTOP(pid);
161   default:
162     return MonitorSignal(pid, signal);
163   }
164 }
165 
166 void NativeProcessNetBSD::MonitorExited(lldb::pid_t pid, WaitStatus status) {
167   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
168 
169   LLDB_LOG(log, "got exit signal({0}) , pid = {1}", status, pid);
170 
171   /* Stop Tracking All Threads attached to Process */
172   m_threads.clear();
173 
174   SetExitStatus(status, true);
175 
176   // Notify delegate that our process has exited.
177   SetState(StateType::eStateExited, true);
178 }
179 
180 void NativeProcessNetBSD::MonitorSIGSTOP(lldb::pid_t pid) {
181   ptrace_siginfo_t info;
182 
183   const auto siginfo_err =
184       PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info));
185 
186   // Get details on the signal raised.
187   if (siginfo_err.Success()) {
188     // Handle SIGSTOP from LLGS (LLDB GDB Server)
189     if (info.psi_siginfo.si_code == SI_USER &&
190         info.psi_siginfo.si_pid == ::getpid()) {
191       /* Stop Tracking all Threads attached to Process */
192       for (const auto &thread : m_threads) {
193         static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(
194             SIGSTOP, &info.psi_siginfo);
195       }
196     }
197     SetState(StateType::eStateStopped, true);
198   }
199 }
200 
201 void NativeProcessNetBSD::MonitorSIGTRAP(lldb::pid_t pid) {
202   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
203   ptrace_siginfo_t info;
204 
205   const auto siginfo_err =
206       PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info));
207 
208   // Get details on the signal raised.
209   if (siginfo_err.Fail()) {
210     LLDB_LOG(log, "PT_GET_SIGINFO failed {0}", siginfo_err);
211     return;
212   }
213 
214   LLDB_LOG(log, "got SIGTRAP, pid = {0}, lwpid = {1}, si_code = {2}", pid,
215            info.psi_lwpid, info.psi_siginfo.si_code);
216   NativeThreadNetBSD *thread = nullptr;
217 
218   if (info.psi_lwpid > 0) {
219     for (const auto &t : m_threads) {
220       if (t->GetID() == static_cast<lldb::tid_t>(info.psi_lwpid)) {
221         thread = static_cast<NativeThreadNetBSD *>(t.get());
222         break;
223       }
224       static_cast<NativeThreadNetBSD *>(t.get())->SetStoppedWithNoReason();
225     }
226     if (!thread)
227       LLDB_LOG(log, "thread not found in m_threads, pid = {0}, LWP = {1}", pid,
228                info.psi_lwpid);
229   }
230 
231   switch (info.psi_siginfo.si_code) {
232   case TRAP_BRKPT:
233     if (thread) {
234       thread->SetStoppedByBreakpoint();
235       FixupBreakpointPCAsNeeded(*thread);
236     }
237     SetState(StateType::eStateStopped, true);
238     return;
239   case TRAP_TRACE:
240     if (thread)
241       thread->SetStoppedByTrace();
242     SetState(StateType::eStateStopped, true);
243     return;
244   case TRAP_EXEC: {
245     Status error = ReinitializeThreads();
246     if (error.Fail()) {
247       SetState(StateType::eStateInvalid);
248       return;
249     }
250 
251     // Let our delegate know we have just exec'd.
252     NotifyDidExec();
253 
254     for (const auto &thread : m_threads)
255       static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByExec();
256     SetState(StateType::eStateStopped, true);
257     return;
258   }
259   case TRAP_LWP: {
260     ptrace_state_t pst;
261     Status error = PtraceWrapper(PT_GET_PROCESS_STATE, pid, &pst, sizeof(pst));
262     if (error.Fail()) {
263       SetState(StateType::eStateInvalid);
264       return;
265     }
266 
267     switch (pst.pe_report_event) {
268     case PTRACE_LWP_CREATE: {
269       LLDB_LOG(log, "monitoring new thread, pid = {0}, LWP = {1}", pid,
270                pst.pe_lwp);
271       NativeThreadNetBSD &t = AddThread(pst.pe_lwp);
272       error = t.CopyWatchpointsFrom(
273           static_cast<NativeThreadNetBSD &>(*GetCurrentThread()));
274       if (error.Fail()) {
275         LLDB_LOG(log, "failed to copy watchpoints to new thread {0}: {1}",
276                  pst.pe_lwp, error);
277         SetState(StateType::eStateInvalid);
278         return;
279       }
280     } break;
281     case PTRACE_LWP_EXIT:
282       LLDB_LOG(log, "removing exited thread, pid = {0}, LWP = {1}", pid,
283                pst.pe_lwp);
284       RemoveThread(pst.pe_lwp);
285       break;
286     }
287 
288     error = PtraceWrapper(PT_CONTINUE, pid, reinterpret_cast<void *>(1), 0);
289     if (error.Fail())
290       SetState(StateType::eStateInvalid);
291     return;
292   }
293   case TRAP_DBREG: {
294     if (!thread)
295       break;
296 
297     auto &regctx = static_cast<NativeRegisterContextNetBSD &>(
298         thread->GetRegisterContext());
299     uint32_t wp_index = LLDB_INVALID_INDEX32;
300     Status error = regctx.GetWatchpointHitIndex(
301         wp_index, (uintptr_t)info.psi_siginfo.si_addr);
302     if (error.Fail())
303       LLDB_LOG(log,
304                "received error while checking for watchpoint hits, pid = "
305                "{0}, LWP = {1}, error = {2}",
306                pid, info.psi_lwpid, error);
307     if (wp_index != LLDB_INVALID_INDEX32) {
308       thread->SetStoppedByWatchpoint(wp_index);
309       regctx.ClearWatchpointHit(wp_index);
310       SetState(StateType::eStateStopped, true);
311       return;
312     }
313 
314     thread->SetStoppedByTrace();
315     SetState(StateType::eStateStopped, true);
316     return;
317   }
318   }
319 
320   // Either user-generated SIGTRAP or an unknown event that would
321   // otherwise leave the debugger hanging.
322   LLDB_LOG(log, "unknown SIGTRAP, passing to generic handler");
323   MonitorSignal(pid, SIGTRAP);
324 }
325 
326 void NativeProcessNetBSD::MonitorSignal(lldb::pid_t pid, int signal) {
327   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
328   ptrace_siginfo_t info;
329 
330   const auto siginfo_err =
331       PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info));
332   if (siginfo_err.Fail()) {
333     LLDB_LOG(log, "PT_LWPINFO failed {0}", siginfo_err);
334     return;
335   }
336 
337   for (const auto &abs_thread : m_threads) {
338     NativeThreadNetBSD &thread = static_cast<NativeThreadNetBSD &>(*abs_thread);
339     assert(info.psi_lwpid >= 0);
340     if (info.psi_lwpid == 0 ||
341         static_cast<lldb::tid_t>(info.psi_lwpid) == thread.GetID())
342       thread.SetStoppedBySignal(info.psi_siginfo.si_signo, &info.psi_siginfo);
343     else
344       thread.SetStoppedWithNoReason();
345   }
346   SetState(StateType::eStateStopped, true);
347 }
348 
349 Status NativeProcessNetBSD::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
350                                           int data, int *result) {
351   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
352   Status error;
353   int ret;
354 
355   errno = 0;
356   ret = ptrace(req, static_cast<::pid_t>(pid), addr, data);
357 
358   if (ret == -1)
359     error.SetErrorToErrno();
360 
361   if (result)
362     *result = ret;
363 
364   LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3})={4:x}", req, pid, addr, data, ret);
365 
366   if (error.Fail())
367     LLDB_LOG(log, "ptrace() failed: {0}", error);
368 
369   return error;
370 }
371 
372 static llvm::Expected<ptrace_siginfo_t> ComputeSignalInfo(
373     const std::vector<std::unique_ptr<NativeThreadProtocol>> &threads,
374     const ResumeActionList &resume_actions) {
375   // We need to account for three possible scenarios:
376   // 1. no signal being sent.
377   // 2. a signal being sent to one thread.
378   // 3. a signal being sent to the whole process.
379 
380   // Count signaled threads.  While at it, determine which signal is being sent
381   // and ensure there's only one.
382   size_t signaled_threads = 0;
383   int signal = LLDB_INVALID_SIGNAL_NUMBER;
384   lldb::tid_t signaled_lwp;
385   for (const auto &thread : threads) {
386     assert(thread && "thread list should not contain NULL threads");
387     const ResumeAction *action =
388         resume_actions.GetActionForThread(thread->GetID(), true);
389     if (action) {
390       if (action->signal != LLDB_INVALID_SIGNAL_NUMBER) {
391         signaled_threads++;
392         if (action->signal != signal) {
393           if (signal != LLDB_INVALID_SIGNAL_NUMBER)
394             return Status("NetBSD does not support passing multiple signals "
395                           "simultaneously")
396                 .ToError();
397           signal = action->signal;
398           signaled_lwp = thread->GetID();
399         }
400       }
401     }
402   }
403 
404   if (signaled_threads == 0) {
405     ptrace_siginfo_t siginfo;
406     siginfo.psi_siginfo.si_signo = LLDB_INVALID_SIGNAL_NUMBER;
407     return siginfo;
408   }
409 
410   if (signaled_threads > 1 && signaled_threads < threads.size())
411     return Status("NetBSD does not support passing signal to 1<i<all threads")
412         .ToError();
413 
414   ptrace_siginfo_t siginfo;
415   siginfo.psi_siginfo.si_signo = signal;
416   siginfo.psi_siginfo.si_code = SI_USER;
417   siginfo.psi_siginfo.si_pid = getpid();
418   siginfo.psi_siginfo.si_uid = getuid();
419   if (signaled_threads == 1)
420     siginfo.psi_lwpid = signaled_lwp;
421   else // signal for the whole process
422     siginfo.psi_lwpid = 0;
423   return siginfo;
424 }
425 
426 Status NativeProcessNetBSD::Resume(const ResumeActionList &resume_actions) {
427   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
428   LLDB_LOG(log, "pid {0}", GetID());
429 
430   Status ret;
431 
432   Expected<ptrace_siginfo_t> siginfo =
433       ComputeSignalInfo(m_threads, resume_actions);
434   if (!siginfo)
435     return Status(siginfo.takeError());
436 
437   for (const auto &abs_thread : m_threads) {
438     assert(abs_thread && "thread list should not contain NULL threads");
439     NativeThreadNetBSD &thread = static_cast<NativeThreadNetBSD &>(*abs_thread);
440 
441     const ResumeAction *action =
442         resume_actions.GetActionForThread(thread.GetID(), true);
443     // we need to explicit issue suspend requests, so it is simpler to map it
444     // into proper action
445     ResumeAction suspend_action{thread.GetID(), eStateSuspended,
446                                 LLDB_INVALID_SIGNAL_NUMBER};
447 
448     if (action == nullptr) {
449       LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
450                thread.GetID());
451       action = &suspend_action;
452     }
453 
454     LLDB_LOG(
455         log,
456         "processing resume action state {0} signal {1} for pid {2} tid {3}",
457         action->state, action->signal, GetID(), thread.GetID());
458 
459     switch (action->state) {
460     case eStateRunning:
461       ret = thread.Resume();
462       break;
463     case eStateStepping:
464       ret = thread.SingleStep();
465       break;
466     case eStateSuspended:
467     case eStateStopped:
468       if (action->signal != LLDB_INVALID_SIGNAL_NUMBER)
469         return Status("Passing signal to suspended thread unsupported");
470 
471       ret = thread.Suspend();
472       break;
473 
474     default:
475       return Status("NativeProcessNetBSD::%s (): unexpected state %s specified "
476                     "for pid %" PRIu64 ", tid %" PRIu64,
477                     __FUNCTION__, StateAsCString(action->state), GetID(),
478                     thread.GetID());
479     }
480 
481     if (!ret.Success())
482       return ret;
483   }
484 
485   int signal = 0;
486   if (siginfo->psi_siginfo.si_signo != LLDB_INVALID_SIGNAL_NUMBER) {
487     ret = PtraceWrapper(PT_SET_SIGINFO, GetID(), &siginfo.get(),
488                         sizeof(*siginfo));
489     if (!ret.Success())
490       return ret;
491     signal = siginfo->psi_siginfo.si_signo;
492   }
493 
494   ret =
495       PtraceWrapper(PT_CONTINUE, GetID(), reinterpret_cast<void *>(1), signal);
496   if (ret.Success())
497     SetState(eStateRunning, true);
498   return ret;
499 }
500 
501 Status NativeProcessNetBSD::Halt() { return PtraceWrapper(PT_STOP, GetID()); }
502 
503 Status NativeProcessNetBSD::Detach() {
504   Status error;
505 
506   // Stop monitoring the inferior.
507   m_sigchld_handle.reset();
508 
509   // Tell ptrace to detach from the process.
510   if (GetID() == LLDB_INVALID_PROCESS_ID)
511     return error;
512 
513   return PtraceWrapper(PT_DETACH, GetID());
514 }
515 
516 Status NativeProcessNetBSD::Signal(int signo) {
517   Status error;
518 
519   if (kill(GetID(), signo))
520     error.SetErrorToErrno();
521 
522   return error;
523 }
524 
525 Status NativeProcessNetBSD::Interrupt() {
526   return PtraceWrapper(PT_STOP, GetID());
527 }
528 
529 Status NativeProcessNetBSD::Kill() {
530   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
531   LLDB_LOG(log, "pid {0}", GetID());
532 
533   Status error;
534 
535   switch (m_state) {
536   case StateType::eStateInvalid:
537   case StateType::eStateExited:
538   case StateType::eStateCrashed:
539   case StateType::eStateDetached:
540   case StateType::eStateUnloaded:
541     // Nothing to do - the process is already dead.
542     LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
543              StateAsCString(m_state));
544     return error;
545 
546   case StateType::eStateConnected:
547   case StateType::eStateAttaching:
548   case StateType::eStateLaunching:
549   case StateType::eStateStopped:
550   case StateType::eStateRunning:
551   case StateType::eStateStepping:
552   case StateType::eStateSuspended:
553     // We can try to kill a process in these states.
554     break;
555   }
556 
557   if (kill(GetID(), SIGKILL) != 0) {
558     error.SetErrorToErrno();
559     return error;
560   }
561 
562   return error;
563 }
564 
565 Status NativeProcessNetBSD::GetMemoryRegionInfo(lldb::addr_t load_addr,
566                                                 MemoryRegionInfo &range_info) {
567 
568   if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
569     // We're done.
570     return Status("unsupported");
571   }
572 
573   Status error = PopulateMemoryRegionCache();
574   if (error.Fail()) {
575     return error;
576   }
577 
578   lldb::addr_t prev_base_address = 0;
579   // FIXME start by finding the last region that is <= target address using
580   // binary search.  Data is sorted.
581   // There can be a ton of regions on pthreads apps with lots of threads.
582   for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
583        ++it) {
584     MemoryRegionInfo &proc_entry_info = it->first;
585     // Sanity check assumption that memory map entries are ascending.
586     assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
587            "descending memory map entries detected, unexpected");
588     prev_base_address = proc_entry_info.GetRange().GetRangeBase();
589     UNUSED_IF_ASSERT_DISABLED(prev_base_address);
590     // If the target address comes before this entry, indicate distance to next
591     // region.
592     if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
593       range_info.GetRange().SetRangeBase(load_addr);
594       range_info.GetRange().SetByteSize(
595           proc_entry_info.GetRange().GetRangeBase() - load_addr);
596       range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
597       range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
598       range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
599       range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
600       return error;
601     } else if (proc_entry_info.GetRange().Contains(load_addr)) {
602       // The target address is within the memory region we're processing here.
603       range_info = proc_entry_info;
604       return error;
605     }
606     // The target memory address comes somewhere after the region we just
607     // parsed.
608   }
609   // If we made it here, we didn't find an entry that contained the given
610   // address. Return the load_addr as start and the amount of bytes betwwen
611   // load address and the end of the memory as size.
612   range_info.GetRange().SetRangeBase(load_addr);
613   range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
614   range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
615   range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
616   range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
617   range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
618   return error;
619 }
620 
621 Status NativeProcessNetBSD::PopulateMemoryRegionCache() {
622   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
623   // If our cache is empty, pull the latest.  There should always be at least
624   // one memory region if memory region handling is supported.
625   if (!m_mem_region_cache.empty()) {
626     LLDB_LOG(log, "reusing {0} cached memory region entries",
627              m_mem_region_cache.size());
628     return Status();
629   }
630 
631   struct kinfo_vmentry *vm;
632   size_t count, i;
633   vm = kinfo_getvmmap(GetID(), &count);
634   if (vm == NULL) {
635     m_supports_mem_region = LazyBool::eLazyBoolNo;
636     Status error;
637     error.SetErrorString("not supported");
638     return error;
639   }
640   for (i = 0; i < count; i++) {
641     MemoryRegionInfo info;
642     info.Clear();
643     info.GetRange().SetRangeBase(vm[i].kve_start);
644     info.GetRange().SetRangeEnd(vm[i].kve_end);
645     info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
646 
647     if (vm[i].kve_protection & VM_PROT_READ)
648       info.SetReadable(MemoryRegionInfo::OptionalBool::eYes);
649     else
650       info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
651 
652     if (vm[i].kve_protection & VM_PROT_WRITE)
653       info.SetWritable(MemoryRegionInfo::OptionalBool::eYes);
654     else
655       info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
656 
657     if (vm[i].kve_protection & VM_PROT_EXECUTE)
658       info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes);
659     else
660       info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
661 
662     if (vm[i].kve_path[0])
663       info.SetName(vm[i].kve_path);
664 
665     m_mem_region_cache.emplace_back(info,
666                                     FileSpec(info.GetName().GetCString()));
667   }
668   free(vm);
669 
670   if (m_mem_region_cache.empty()) {
671     // No entries after attempting to read them.  This shouldn't happen. Assume
672     // we don't support map entries.
673     LLDB_LOG(log, "failed to find any vmmap entries, assuming no support "
674                   "for memory region metadata retrieval");
675     m_supports_mem_region = LazyBool::eLazyBoolNo;
676     Status error;
677     error.SetErrorString("not supported");
678     return error;
679   }
680   LLDB_LOG(log, "read {0} memory region entries from process {1}",
681            m_mem_region_cache.size(), GetID());
682   // We support memory retrieval, remember that.
683   m_supports_mem_region = LazyBool::eLazyBoolYes;
684   return Status();
685 }
686 
687 lldb::addr_t NativeProcessNetBSD::GetSharedLibraryInfoAddress() {
688   // punt on this for now
689   return LLDB_INVALID_ADDRESS;
690 }
691 
692 size_t NativeProcessNetBSD::UpdateThreads() { return m_threads.size(); }
693 
694 Status NativeProcessNetBSD::SetBreakpoint(lldb::addr_t addr, uint32_t size,
695                                           bool hardware) {
696   if (hardware)
697     return Status("NativeProcessNetBSD does not support hardware breakpoints");
698   else
699     return SetSoftwareBreakpoint(addr, size);
700 }
701 
702 Status NativeProcessNetBSD::GetLoadedModuleFileSpec(const char *module_path,
703                                                     FileSpec &file_spec) {
704   Status error = PopulateMemoryRegionCache();
705   if (error.Fail())
706     return error;
707 
708   FileSpec module_file_spec(module_path);
709   FileSystem::Instance().Resolve(module_file_spec);
710 
711   file_spec.Clear();
712   for (const auto &it : m_mem_region_cache) {
713     if (it.second.GetFilename() == module_file_spec.GetFilename()) {
714       file_spec = it.second;
715       return Status();
716     }
717   }
718   return Status("Module file (%s) not found in process' memory map!",
719                 module_file_spec.GetFilename().AsCString());
720 }
721 
722 Status NativeProcessNetBSD::GetFileLoadAddress(const llvm::StringRef &file_name,
723                                                lldb::addr_t &load_addr) {
724   load_addr = LLDB_INVALID_ADDRESS;
725   Status error = PopulateMemoryRegionCache();
726   if (error.Fail())
727     return error;
728 
729   FileSpec file(file_name);
730   for (const auto &it : m_mem_region_cache) {
731     if (it.second == file) {
732       load_addr = it.first.GetRange().GetRangeBase();
733       return Status();
734     }
735   }
736   return Status("No load address found for file %s.", file_name.str().c_str());
737 }
738 
739 void NativeProcessNetBSD::SigchldHandler() {
740   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
741   // Process all pending waitpid notifications.
742   int status;
743   ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, waitpid, GetID(), &status,
744                                                  WALLSIG | WNOHANG);
745 
746   if (wait_pid == 0)
747     return; // We are done.
748 
749   if (wait_pid == -1) {
750     Status error(errno, eErrorTypePOSIX);
751     LLDB_LOG(log, "waitpid ({0}, &status, _) failed: {1}", GetID(), error);
752   }
753 
754   WaitStatus wait_status = WaitStatus::Decode(status);
755   bool exited = wait_status.type == WaitStatus::Exit ||
756                 (wait_status.type == WaitStatus::Signal &&
757                  wait_pid == static_cast<::pid_t>(GetID()));
758 
759   LLDB_LOG(log,
760            "waitpid ({0}, &status, _) => pid = {1}, status = {2}, exited = {3}",
761            GetID(), wait_pid, status, exited);
762 
763   if (exited)
764     MonitorExited(wait_pid, wait_status);
765   else {
766     assert(wait_status.type == WaitStatus::Stop);
767     MonitorCallback(wait_pid, wait_status.status);
768   }
769 }
770 
771 bool NativeProcessNetBSD::HasThreadNoLock(lldb::tid_t thread_id) {
772   for (const auto &thread : m_threads) {
773     assert(thread && "thread list should not contain NULL threads");
774     if (thread->GetID() == thread_id) {
775       // We have this thread.
776       return true;
777     }
778   }
779 
780   // We don't have this thread.
781   return false;
782 }
783 
784 NativeThreadNetBSD &NativeProcessNetBSD::AddThread(lldb::tid_t thread_id) {
785   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
786   LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
787 
788   assert(thread_id > 0);
789   assert(!HasThreadNoLock(thread_id) &&
790          "attempted to add a thread by id that already exists");
791 
792   // If this is the first thread, save it as the current thread
793   if (m_threads.empty())
794     SetCurrentThreadID(thread_id);
795 
796   m_threads.push_back(std::make_unique<NativeThreadNetBSD>(*this, thread_id));
797   return static_cast<NativeThreadNetBSD &>(*m_threads.back());
798 }
799 
800 void NativeProcessNetBSD::RemoveThread(lldb::tid_t thread_id) {
801   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
802   LLDB_LOG(log, "pid {0} removing thread with tid {1}", GetID(), thread_id);
803 
804   assert(thread_id > 0);
805   assert(HasThreadNoLock(thread_id) &&
806          "attempted to remove a thread that does not exist");
807 
808   for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
809     if ((*it)->GetID() == thread_id) {
810       m_threads.erase(it);
811       break;
812     }
813   }
814 }
815 
816 Status NativeProcessNetBSD::Attach() {
817   // Attach to the requested process.
818   // An attach will cause the thread to stop with a SIGSTOP.
819   Status status = PtraceWrapper(PT_ATTACH, m_pid);
820   if (status.Fail())
821     return status;
822 
823   int wstatus;
824   // Need to use WALLSIG otherwise we receive an error with errno=ECHLD At this
825   // point we should have a thread stopped if waitpid succeeds.
826   if ((wstatus = llvm::sys::RetryAfterSignal(-1, waitpid, m_pid, nullptr,
827                                              WALLSIG)) < 0)
828     return Status(errno, eErrorTypePOSIX);
829 
830   // Initialize threads and tracing status
831   // NB: this needs to be called before we set thread state
832   status = SetupTrace();
833   if (status.Fail())
834     return status;
835 
836   for (const auto &thread : m_threads)
837     static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(SIGSTOP);
838 
839   // Let our process instance know the thread has stopped.
840   SetCurrentThreadID(m_threads.front()->GetID());
841   SetState(StateType::eStateStopped, false);
842   return Status();
843 }
844 
845 Status NativeProcessNetBSD::ReadMemory(lldb::addr_t addr, void *buf,
846                                        size_t size, size_t &bytes_read) {
847   unsigned char *dst = static_cast<unsigned char *>(buf);
848   struct ptrace_io_desc io;
849 
850   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
851   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
852 
853   bytes_read = 0;
854   io.piod_op = PIOD_READ_D;
855   io.piod_len = size;
856 
857   do {
858     io.piod_offs = (void *)(addr + bytes_read);
859     io.piod_addr = dst + bytes_read;
860 
861     Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
862     if (error.Fail() || io.piod_len == 0)
863       return error;
864 
865     bytes_read += io.piod_len;
866     io.piod_len = size - bytes_read;
867   } while (bytes_read < size);
868 
869   return Status();
870 }
871 
872 Status NativeProcessNetBSD::WriteMemory(lldb::addr_t addr, const void *buf,
873                                         size_t size, size_t &bytes_written) {
874   const unsigned char *src = static_cast<const unsigned char *>(buf);
875   Status error;
876   struct ptrace_io_desc io;
877 
878   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
879   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
880 
881   bytes_written = 0;
882   io.piod_op = PIOD_WRITE_D;
883   io.piod_len = size;
884 
885   do {
886     io.piod_addr =
887         const_cast<void *>(static_cast<const void *>(src + bytes_written));
888     io.piod_offs = (void *)(addr + bytes_written);
889 
890     Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
891     if (error.Fail() || io.piod_len == 0)
892       return error;
893 
894     bytes_written += io.piod_len;
895     io.piod_len = size - bytes_written;
896   } while (bytes_written < size);
897 
898   return error;
899 }
900 
901 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
902 NativeProcessNetBSD::GetAuxvData() const {
903   /*
904    * ELF_AUX_ENTRIES is currently restricted to kernel
905    * (<sys/exec_elf.h> r. 1.155 specifies 15)
906    *
907    * ptrace(2) returns the whole AUXV including extra fiels after AT_NULL this
908    * information isn't needed.
909    */
910   size_t auxv_size = 100 * sizeof(AuxInfo);
911 
912   ErrorOr<std::unique_ptr<WritableMemoryBuffer>> buf =
913       llvm::WritableMemoryBuffer::getNewMemBuffer(auxv_size);
914 
915   struct ptrace_io_desc io;
916   io.piod_op = PIOD_READ_AUXV;
917   io.piod_offs = 0;
918   io.piod_addr = static_cast<void *>(buf.get()->getBufferStart());
919   io.piod_len = auxv_size;
920 
921   Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
922 
923   if (error.Fail())
924     return std::error_code(error.GetError(), std::generic_category());
925 
926   if (io.piod_len < 1)
927     return std::error_code(ECANCELED, std::generic_category());
928 
929   return std::move(buf);
930 }
931 
932 Status NativeProcessNetBSD::SetupTrace() {
933   // Enable event reporting
934   ptrace_event_t events;
935   Status status =
936       PtraceWrapper(PT_GET_EVENT_MASK, GetID(), &events, sizeof(events));
937   if (status.Fail())
938     return status;
939   // TODO: PTRACE_FORK | PTRACE_VFORK | PTRACE_POSIX_SPAWN?
940   events.pe_set_event |= PTRACE_LWP_CREATE | PTRACE_LWP_EXIT;
941   status = PtraceWrapper(PT_SET_EVENT_MASK, GetID(), &events, sizeof(events));
942   if (status.Fail())
943     return status;
944 
945   return ReinitializeThreads();
946 }
947 
948 Status NativeProcessNetBSD::ReinitializeThreads() {
949   // Clear old threads
950   m_threads.clear();
951 
952   // Initialize new thread
953 #ifdef PT_LWPSTATUS
954   struct ptrace_lwpstatus info = {};
955   int op = PT_LWPNEXT;
956 #else
957   struct ptrace_lwpinfo info = {};
958   int op = PT_LWPINFO;
959 #endif
960 
961   Status error = PtraceWrapper(op, GetID(), &info, sizeof(info));
962 
963   if (error.Fail()) {
964     return error;
965   }
966   // Reinitialize from scratch threads and register them in process
967   while (info.pl_lwpid != 0) {
968     AddThread(info.pl_lwpid);
969     error = PtraceWrapper(op, GetID(), &info, sizeof(info));
970     if (error.Fail()) {
971       return error;
972     }
973   }
974 
975   return error;
976 }
977