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_CHLD: {
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     if (pst.pe_report_event == PTRACE_VFORK_DONE) {
268       Status error =
269           PtraceWrapper(PT_CONTINUE, pid, reinterpret_cast<void *>(1), 0);
270       if (error.Fail())
271         SetState(StateType::eStateInvalid);
272       return;
273     } else
274       MonitorClone(pst.pe_other_pid);
275     return;
276   }
277   case TRAP_LWP: {
278     ptrace_state_t pst;
279     Status error = PtraceWrapper(PT_GET_PROCESS_STATE, pid, &pst, sizeof(pst));
280     if (error.Fail()) {
281       SetState(StateType::eStateInvalid);
282       return;
283     }
284 
285     switch (pst.pe_report_event) {
286     case PTRACE_LWP_CREATE: {
287       LLDB_LOG(log, "monitoring new thread, pid = {0}, LWP = {1}", pid,
288                pst.pe_lwp);
289       NativeThreadNetBSD &t = AddThread(pst.pe_lwp);
290       error = t.CopyWatchpointsFrom(
291           static_cast<NativeThreadNetBSD &>(*GetCurrentThread()));
292       if (error.Fail()) {
293         LLDB_LOG(log, "failed to copy watchpoints to new thread {0}: {1}",
294                  pst.pe_lwp, error);
295         SetState(StateType::eStateInvalid);
296         return;
297       }
298     } break;
299     case PTRACE_LWP_EXIT:
300       LLDB_LOG(log, "removing exited thread, pid = {0}, LWP = {1}", pid,
301                pst.pe_lwp);
302       RemoveThread(pst.pe_lwp);
303       break;
304     }
305 
306     error = PtraceWrapper(PT_CONTINUE, pid, reinterpret_cast<void *>(1), 0);
307     if (error.Fail())
308       SetState(StateType::eStateInvalid);
309     return;
310   }
311   case TRAP_DBREG: {
312     if (!thread)
313       break;
314 
315     auto &regctx = static_cast<NativeRegisterContextNetBSD &>(
316         thread->GetRegisterContext());
317     uint32_t wp_index = LLDB_INVALID_INDEX32;
318     Status error = regctx.GetWatchpointHitIndex(
319         wp_index, (uintptr_t)info.psi_siginfo.si_addr);
320     if (error.Fail())
321       LLDB_LOG(log,
322                "received error while checking for watchpoint hits, pid = "
323                "{0}, LWP = {1}, error = {2}",
324                pid, info.psi_lwpid, error);
325     if (wp_index != LLDB_INVALID_INDEX32) {
326       thread->SetStoppedByWatchpoint(wp_index);
327       regctx.ClearWatchpointHit(wp_index);
328       SetState(StateType::eStateStopped, true);
329       return;
330     }
331 
332     thread->SetStoppedByTrace();
333     SetState(StateType::eStateStopped, true);
334     return;
335   }
336   }
337 
338   // Either user-generated SIGTRAP or an unknown event that would
339   // otherwise leave the debugger hanging.
340   LLDB_LOG(log, "unknown SIGTRAP, passing to generic handler");
341   MonitorSignal(pid, SIGTRAP);
342 }
343 
344 void NativeProcessNetBSD::MonitorSignal(lldb::pid_t pid, int signal) {
345   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
346   ptrace_siginfo_t info;
347 
348   const auto siginfo_err =
349       PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info));
350   if (siginfo_err.Fail()) {
351     LLDB_LOG(log, "PT_LWPINFO failed {0}", siginfo_err);
352     return;
353   }
354 
355   for (const auto &abs_thread : m_threads) {
356     NativeThreadNetBSD &thread = static_cast<NativeThreadNetBSD &>(*abs_thread);
357     assert(info.psi_lwpid >= 0);
358     if (info.psi_lwpid == 0 ||
359         static_cast<lldb::tid_t>(info.psi_lwpid) == thread.GetID())
360       thread.SetStoppedBySignal(info.psi_siginfo.si_signo, &info.psi_siginfo);
361     else
362       thread.SetStoppedWithNoReason();
363   }
364   SetState(StateType::eStateStopped, true);
365 }
366 
367 Status NativeProcessNetBSD::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
368                                           int data, int *result) {
369   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
370   Status error;
371   int ret;
372 
373   errno = 0;
374   ret = ptrace(req, static_cast<::pid_t>(pid), addr, data);
375 
376   if (ret == -1)
377     error.SetErrorToErrno();
378 
379   if (result)
380     *result = ret;
381 
382   LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3})={4:x}", req, pid, addr, data, ret);
383 
384   if (error.Fail())
385     LLDB_LOG(log, "ptrace() failed: {0}", error);
386 
387   return error;
388 }
389 
390 static llvm::Expected<ptrace_siginfo_t> ComputeSignalInfo(
391     const std::vector<std::unique_ptr<NativeThreadProtocol>> &threads,
392     const ResumeActionList &resume_actions) {
393   // We need to account for three possible scenarios:
394   // 1. no signal being sent.
395   // 2. a signal being sent to one thread.
396   // 3. a signal being sent to the whole process.
397 
398   // Count signaled threads.  While at it, determine which signal is being sent
399   // and ensure there's only one.
400   size_t signaled_threads = 0;
401   int signal = LLDB_INVALID_SIGNAL_NUMBER;
402   lldb::tid_t signaled_lwp;
403   for (const auto &thread : threads) {
404     assert(thread && "thread list should not contain NULL threads");
405     const ResumeAction *action =
406         resume_actions.GetActionForThread(thread->GetID(), true);
407     if (action) {
408       if (action->signal != LLDB_INVALID_SIGNAL_NUMBER) {
409         signaled_threads++;
410         if (action->signal != signal) {
411           if (signal != LLDB_INVALID_SIGNAL_NUMBER)
412             return Status("NetBSD does not support passing multiple signals "
413                           "simultaneously")
414                 .ToError();
415           signal = action->signal;
416           signaled_lwp = thread->GetID();
417         }
418       }
419     }
420   }
421 
422   if (signaled_threads == 0) {
423     ptrace_siginfo_t siginfo;
424     siginfo.psi_siginfo.si_signo = LLDB_INVALID_SIGNAL_NUMBER;
425     return siginfo;
426   }
427 
428   if (signaled_threads > 1 && signaled_threads < threads.size())
429     return Status("NetBSD does not support passing signal to 1<i<all threads")
430         .ToError();
431 
432   ptrace_siginfo_t siginfo;
433   siginfo.psi_siginfo.si_signo = signal;
434   siginfo.psi_siginfo.si_code = SI_USER;
435   siginfo.psi_siginfo.si_pid = getpid();
436   siginfo.psi_siginfo.si_uid = getuid();
437   if (signaled_threads == 1)
438     siginfo.psi_lwpid = signaled_lwp;
439   else // signal for the whole process
440     siginfo.psi_lwpid = 0;
441   return siginfo;
442 }
443 
444 Status NativeProcessNetBSD::Resume(const ResumeActionList &resume_actions) {
445   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
446   LLDB_LOG(log, "pid {0}", GetID());
447 
448   Status ret;
449 
450   Expected<ptrace_siginfo_t> siginfo =
451       ComputeSignalInfo(m_threads, resume_actions);
452   if (!siginfo)
453     return Status(siginfo.takeError());
454 
455   for (const auto &abs_thread : m_threads) {
456     assert(abs_thread && "thread list should not contain NULL threads");
457     NativeThreadNetBSD &thread = static_cast<NativeThreadNetBSD &>(*abs_thread);
458 
459     const ResumeAction *action =
460         resume_actions.GetActionForThread(thread.GetID(), true);
461     // we need to explicit issue suspend requests, so it is simpler to map it
462     // into proper action
463     ResumeAction suspend_action{thread.GetID(), eStateSuspended,
464                                 LLDB_INVALID_SIGNAL_NUMBER};
465 
466     if (action == nullptr) {
467       LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
468                thread.GetID());
469       action = &suspend_action;
470     }
471 
472     LLDB_LOG(
473         log,
474         "processing resume action state {0} signal {1} for pid {2} tid {3}",
475         action->state, action->signal, GetID(), thread.GetID());
476 
477     switch (action->state) {
478     case eStateRunning:
479       ret = thread.Resume();
480       break;
481     case eStateStepping:
482       ret = thread.SingleStep();
483       break;
484     case eStateSuspended:
485     case eStateStopped:
486       if (action->signal != LLDB_INVALID_SIGNAL_NUMBER)
487         return Status("Passing signal to suspended thread unsupported");
488 
489       ret = thread.Suspend();
490       break;
491 
492     default:
493       return Status("NativeProcessNetBSD::%s (): unexpected state %s specified "
494                     "for pid %" PRIu64 ", tid %" PRIu64,
495                     __FUNCTION__, StateAsCString(action->state), GetID(),
496                     thread.GetID());
497     }
498 
499     if (!ret.Success())
500       return ret;
501   }
502 
503   int signal = 0;
504   if (siginfo->psi_siginfo.si_signo != LLDB_INVALID_SIGNAL_NUMBER) {
505     ret = PtraceWrapper(PT_SET_SIGINFO, GetID(), &siginfo.get(),
506                         sizeof(*siginfo));
507     if (!ret.Success())
508       return ret;
509     signal = siginfo->psi_siginfo.si_signo;
510   }
511 
512   ret =
513       PtraceWrapper(PT_CONTINUE, GetID(), reinterpret_cast<void *>(1), signal);
514   if (ret.Success())
515     SetState(eStateRunning, true);
516   return ret;
517 }
518 
519 Status NativeProcessNetBSD::Halt() { return PtraceWrapper(PT_STOP, GetID()); }
520 
521 Status NativeProcessNetBSD::Detach() {
522   Status error;
523 
524   // Stop monitoring the inferior.
525   m_sigchld_handle.reset();
526 
527   // Tell ptrace to detach from the process.
528   if (GetID() == LLDB_INVALID_PROCESS_ID)
529     return error;
530 
531   return PtraceWrapper(PT_DETACH, GetID(), reinterpret_cast<void *>(1));
532 }
533 
534 Status NativeProcessNetBSD::Signal(int signo) {
535   Status error;
536 
537   if (kill(GetID(), signo))
538     error.SetErrorToErrno();
539 
540   return error;
541 }
542 
543 Status NativeProcessNetBSD::Interrupt() {
544   return PtraceWrapper(PT_STOP, GetID());
545 }
546 
547 Status NativeProcessNetBSD::Kill() {
548   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
549   LLDB_LOG(log, "pid {0}", GetID());
550 
551   Status error;
552 
553   switch (m_state) {
554   case StateType::eStateInvalid:
555   case StateType::eStateExited:
556   case StateType::eStateCrashed:
557   case StateType::eStateDetached:
558   case StateType::eStateUnloaded:
559     // Nothing to do - the process is already dead.
560     LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
561              StateAsCString(m_state));
562     return error;
563 
564   case StateType::eStateConnected:
565   case StateType::eStateAttaching:
566   case StateType::eStateLaunching:
567   case StateType::eStateStopped:
568   case StateType::eStateRunning:
569   case StateType::eStateStepping:
570   case StateType::eStateSuspended:
571     // We can try to kill a process in these states.
572     break;
573   }
574 
575   if (kill(GetID(), SIGKILL) != 0) {
576     error.SetErrorToErrno();
577     return error;
578   }
579 
580   return error;
581 }
582 
583 Status NativeProcessNetBSD::GetMemoryRegionInfo(lldb::addr_t load_addr,
584                                                 MemoryRegionInfo &range_info) {
585 
586   if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
587     // We're done.
588     return Status("unsupported");
589   }
590 
591   Status error = PopulateMemoryRegionCache();
592   if (error.Fail()) {
593     return error;
594   }
595 
596   lldb::addr_t prev_base_address = 0;
597   // FIXME start by finding the last region that is <= target address using
598   // binary search.  Data is sorted.
599   // There can be a ton of regions on pthreads apps with lots of threads.
600   for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
601        ++it) {
602     MemoryRegionInfo &proc_entry_info = it->first;
603     // Sanity check assumption that memory map entries are ascending.
604     assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
605            "descending memory map entries detected, unexpected");
606     prev_base_address = proc_entry_info.GetRange().GetRangeBase();
607     UNUSED_IF_ASSERT_DISABLED(prev_base_address);
608     // If the target address comes before this entry, indicate distance to next
609     // region.
610     if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
611       range_info.GetRange().SetRangeBase(load_addr);
612       range_info.GetRange().SetByteSize(
613           proc_entry_info.GetRange().GetRangeBase() - load_addr);
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     } else if (proc_entry_info.GetRange().Contains(load_addr)) {
620       // The target address is within the memory region we're processing here.
621       range_info = proc_entry_info;
622       return error;
623     }
624     // The target memory address comes somewhere after the region we just
625     // parsed.
626   }
627   // If we made it here, we didn't find an entry that contained the given
628   // address. Return the load_addr as start and the amount of bytes betwwen
629   // load address and the end of the memory as size.
630   range_info.GetRange().SetRangeBase(load_addr);
631   range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
632   range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
633   range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
634   range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
635   range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
636   return error;
637 }
638 
639 Status NativeProcessNetBSD::PopulateMemoryRegionCache() {
640   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
641   // If our cache is empty, pull the latest.  There should always be at least
642   // one memory region if memory region handling is supported.
643   if (!m_mem_region_cache.empty()) {
644     LLDB_LOG(log, "reusing {0} cached memory region entries",
645              m_mem_region_cache.size());
646     return Status();
647   }
648 
649   struct kinfo_vmentry *vm;
650   size_t count, i;
651   vm = kinfo_getvmmap(GetID(), &count);
652   if (vm == NULL) {
653     m_supports_mem_region = LazyBool::eLazyBoolNo;
654     Status error;
655     error.SetErrorString("not supported");
656     return error;
657   }
658   for (i = 0; i < count; i++) {
659     MemoryRegionInfo info;
660     info.Clear();
661     info.GetRange().SetRangeBase(vm[i].kve_start);
662     info.GetRange().SetRangeEnd(vm[i].kve_end);
663     info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
664 
665     if (vm[i].kve_protection & VM_PROT_READ)
666       info.SetReadable(MemoryRegionInfo::OptionalBool::eYes);
667     else
668       info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
669 
670     if (vm[i].kve_protection & VM_PROT_WRITE)
671       info.SetWritable(MemoryRegionInfo::OptionalBool::eYes);
672     else
673       info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
674 
675     if (vm[i].kve_protection & VM_PROT_EXECUTE)
676       info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes);
677     else
678       info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
679 
680     if (vm[i].kve_path[0])
681       info.SetName(vm[i].kve_path);
682 
683     m_mem_region_cache.emplace_back(info,
684                                     FileSpec(info.GetName().GetCString()));
685   }
686   free(vm);
687 
688   if (m_mem_region_cache.empty()) {
689     // No entries after attempting to read them.  This shouldn't happen. Assume
690     // we don't support map entries.
691     LLDB_LOG(log, "failed to find any vmmap entries, assuming no support "
692                   "for memory region metadata retrieval");
693     m_supports_mem_region = LazyBool::eLazyBoolNo;
694     Status error;
695     error.SetErrorString("not supported");
696     return error;
697   }
698   LLDB_LOG(log, "read {0} memory region entries from process {1}",
699            m_mem_region_cache.size(), GetID());
700   // We support memory retrieval, remember that.
701   m_supports_mem_region = LazyBool::eLazyBoolYes;
702   return Status();
703 }
704 
705 lldb::addr_t NativeProcessNetBSD::GetSharedLibraryInfoAddress() {
706   // punt on this for now
707   return LLDB_INVALID_ADDRESS;
708 }
709 
710 size_t NativeProcessNetBSD::UpdateThreads() { return m_threads.size(); }
711 
712 Status NativeProcessNetBSD::SetBreakpoint(lldb::addr_t addr, uint32_t size,
713                                           bool hardware) {
714   if (hardware)
715     return Status("NativeProcessNetBSD does not support hardware breakpoints");
716   else
717     return SetSoftwareBreakpoint(addr, size);
718 }
719 
720 Status NativeProcessNetBSD::GetLoadedModuleFileSpec(const char *module_path,
721                                                     FileSpec &file_spec) {
722   Status error = PopulateMemoryRegionCache();
723   if (error.Fail())
724     return error;
725 
726   FileSpec module_file_spec(module_path);
727   FileSystem::Instance().Resolve(module_file_spec);
728 
729   file_spec.Clear();
730   for (const auto &it : m_mem_region_cache) {
731     if (it.second.GetFilename() == module_file_spec.GetFilename()) {
732       file_spec = it.second;
733       return Status();
734     }
735   }
736   return Status("Module file (%s) not found in process' memory map!",
737                 module_file_spec.GetFilename().AsCString());
738 }
739 
740 Status NativeProcessNetBSD::GetFileLoadAddress(const llvm::StringRef &file_name,
741                                                lldb::addr_t &load_addr) {
742   load_addr = LLDB_INVALID_ADDRESS;
743   Status error = PopulateMemoryRegionCache();
744   if (error.Fail())
745     return error;
746 
747   FileSpec file(file_name);
748   for (const auto &it : m_mem_region_cache) {
749     if (it.second == file) {
750       load_addr = it.first.GetRange().GetRangeBase();
751       return Status();
752     }
753   }
754   return Status("No load address found for file %s.", file_name.str().c_str());
755 }
756 
757 void NativeProcessNetBSD::SigchldHandler() {
758   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
759   int status;
760   ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, waitpid, GetID(), &status,
761                                                  WALLSIG | WNOHANG);
762 
763   if (wait_pid == 0)
764     return;
765 
766   if (wait_pid == -1) {
767     Status error(errno, eErrorTypePOSIX);
768     LLDB_LOG(log, "waitpid ({0}, &status, _) failed: {1}", GetID(), error);
769     return;
770   }
771 
772   WaitStatus wait_status = WaitStatus::Decode(status);
773   bool exited = wait_status.type == WaitStatus::Exit ||
774                 (wait_status.type == WaitStatus::Signal &&
775                  wait_pid == static_cast<::pid_t>(GetID()));
776 
777   LLDB_LOG(log,
778            "waitpid ({0}, &status, _) => pid = {1}, status = {2}, exited = {3}",
779            GetID(), wait_pid, status, exited);
780 
781   if (exited)
782     MonitorExited(wait_pid, wait_status);
783   else {
784     assert(wait_status.type == WaitStatus::Stop);
785     MonitorCallback(wait_pid, wait_status.status);
786   }
787 }
788 
789 bool NativeProcessNetBSD::HasThreadNoLock(lldb::tid_t thread_id) {
790   for (const auto &thread : m_threads) {
791     assert(thread && "thread list should not contain NULL threads");
792     if (thread->GetID() == thread_id) {
793       // We have this thread.
794       return true;
795     }
796   }
797 
798   // We don't have this thread.
799   return false;
800 }
801 
802 NativeThreadNetBSD &NativeProcessNetBSD::AddThread(lldb::tid_t thread_id) {
803   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
804   LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
805 
806   assert(thread_id > 0);
807   assert(!HasThreadNoLock(thread_id) &&
808          "attempted to add a thread by id that already exists");
809 
810   // If this is the first thread, save it as the current thread
811   if (m_threads.empty())
812     SetCurrentThreadID(thread_id);
813 
814   m_threads.push_back(std::make_unique<NativeThreadNetBSD>(*this, thread_id));
815   return static_cast<NativeThreadNetBSD &>(*m_threads.back());
816 }
817 
818 void NativeProcessNetBSD::RemoveThread(lldb::tid_t thread_id) {
819   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
820   LLDB_LOG(log, "pid {0} removing thread with tid {1}", GetID(), thread_id);
821 
822   assert(thread_id > 0);
823   assert(HasThreadNoLock(thread_id) &&
824          "attempted to remove a thread that does not exist");
825 
826   for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
827     if ((*it)->GetID() == thread_id) {
828       m_threads.erase(it);
829       break;
830     }
831   }
832 }
833 
834 Status NativeProcessNetBSD::Attach() {
835   // Attach to the requested process.
836   // An attach will cause the thread to stop with a SIGSTOP.
837   Status status = PtraceWrapper(PT_ATTACH, m_pid);
838   if (status.Fail())
839     return status;
840 
841   int wstatus;
842   // Need to use WALLSIG otherwise we receive an error with errno=ECHLD At this
843   // point we should have a thread stopped if waitpid succeeds.
844   if ((wstatus = llvm::sys::RetryAfterSignal(-1, waitpid, m_pid, nullptr,
845                                              WALLSIG)) < 0)
846     return Status(errno, eErrorTypePOSIX);
847 
848   // Initialize threads and tracing status
849   // NB: this needs to be called before we set thread state
850   status = SetupTrace();
851   if (status.Fail())
852     return status;
853 
854   for (const auto &thread : m_threads)
855     static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(SIGSTOP);
856 
857   // Let our process instance know the thread has stopped.
858   SetCurrentThreadID(m_threads.front()->GetID());
859   SetState(StateType::eStateStopped, false);
860   return Status();
861 }
862 
863 Status NativeProcessNetBSD::ReadMemory(lldb::addr_t addr, void *buf,
864                                        size_t size, size_t &bytes_read) {
865   unsigned char *dst = static_cast<unsigned char *>(buf);
866   struct ptrace_io_desc io;
867 
868   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
869   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
870 
871   bytes_read = 0;
872   io.piod_op = PIOD_READ_D;
873   io.piod_len = size;
874 
875   do {
876     io.piod_offs = (void *)(addr + bytes_read);
877     io.piod_addr = dst + bytes_read;
878 
879     Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
880     if (error.Fail() || io.piod_len == 0)
881       return error;
882 
883     bytes_read += io.piod_len;
884     io.piod_len = size - bytes_read;
885   } while (bytes_read < size);
886 
887   return Status();
888 }
889 
890 Status NativeProcessNetBSD::WriteMemory(lldb::addr_t addr, const void *buf,
891                                         size_t size, size_t &bytes_written) {
892   const unsigned char *src = static_cast<const unsigned char *>(buf);
893   Status error;
894   struct ptrace_io_desc io;
895 
896   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
897   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
898 
899   bytes_written = 0;
900   io.piod_op = PIOD_WRITE_D;
901   io.piod_len = size;
902 
903   do {
904     io.piod_addr =
905         const_cast<void *>(static_cast<const void *>(src + bytes_written));
906     io.piod_offs = (void *)(addr + bytes_written);
907 
908     Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
909     if (error.Fail() || io.piod_len == 0)
910       return error;
911 
912     bytes_written += io.piod_len;
913     io.piod_len = size - bytes_written;
914   } while (bytes_written < size);
915 
916   return error;
917 }
918 
919 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
920 NativeProcessNetBSD::GetAuxvData() const {
921   /*
922    * ELF_AUX_ENTRIES is currently restricted to kernel
923    * (<sys/exec_elf.h> r. 1.155 specifies 15)
924    *
925    * ptrace(2) returns the whole AUXV including extra fiels after AT_NULL this
926    * information isn't needed.
927    */
928   size_t auxv_size = 100 * sizeof(AuxInfo);
929 
930   ErrorOr<std::unique_ptr<WritableMemoryBuffer>> buf =
931       llvm::WritableMemoryBuffer::getNewMemBuffer(auxv_size);
932 
933   struct ptrace_io_desc io;
934   io.piod_op = PIOD_READ_AUXV;
935   io.piod_offs = 0;
936   io.piod_addr = static_cast<void *>(buf.get()->getBufferStart());
937   io.piod_len = auxv_size;
938 
939   Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
940 
941   if (error.Fail())
942     return std::error_code(error.GetError(), std::generic_category());
943 
944   if (io.piod_len < 1)
945     return std::error_code(ECANCELED, std::generic_category());
946 
947   return std::move(buf);
948 }
949 
950 Status NativeProcessNetBSD::SetupTrace() {
951   // Enable event reporting
952   ptrace_event_t events;
953   Status status =
954       PtraceWrapper(PT_GET_EVENT_MASK, GetID(), &events, sizeof(events));
955   if (status.Fail())
956     return status;
957   // TODO: PTRACE_POSIX_SPAWN?
958   events.pe_set_event |= PTRACE_LWP_CREATE | PTRACE_LWP_EXIT | PTRACE_FORK |
959                          PTRACE_VFORK | PTRACE_VFORK_DONE;
960   status = PtraceWrapper(PT_SET_EVENT_MASK, GetID(), &events, sizeof(events));
961   if (status.Fail())
962     return status;
963 
964   return ReinitializeThreads();
965 }
966 
967 Status NativeProcessNetBSD::ReinitializeThreads() {
968   // Clear old threads
969   m_threads.clear();
970 
971   // Initialize new thread
972 #ifdef PT_LWPSTATUS
973   struct ptrace_lwpstatus info = {};
974   int op = PT_LWPNEXT;
975 #else
976   struct ptrace_lwpinfo info = {};
977   int op = PT_LWPINFO;
978 #endif
979 
980   Status error = PtraceWrapper(op, GetID(), &info, sizeof(info));
981 
982   if (error.Fail()) {
983     return error;
984   }
985   // Reinitialize from scratch threads and register them in process
986   while (info.pl_lwpid != 0) {
987     AddThread(info.pl_lwpid);
988     error = PtraceWrapper(op, GetID(), &info, sizeof(info));
989     if (error.Fail()) {
990       return error;
991     }
992   }
993 
994   return error;
995 }
996 
997 void NativeProcessNetBSD::MonitorClone(::pid_t child_pid) {
998   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
999   LLDB_LOG(log, "clone, child_pid={0}", child_pid);
1000 
1001   int status;
1002   ::pid_t wait_pid =
1003       llvm::sys::RetryAfterSignal(-1, ::waitpid, child_pid, &status, 0);
1004   if (wait_pid != child_pid) {
1005     LLDB_LOG(log,
1006              "waiting for pid {0} failed. Assuming the pid has "
1007              "disappeared in the meantime",
1008              child_pid);
1009     return;
1010   }
1011   if (WIFEXITED(status)) {
1012     LLDB_LOG(log,
1013              "waiting for pid {0} returned an 'exited' event. Not "
1014              "tracking it.",
1015              child_pid);
1016     return;
1017   }
1018 
1019   MainLoop unused_loop;
1020   NativeProcessNetBSD child_process{static_cast<::pid_t>(child_pid),
1021                                     m_terminal_fd, *m_delegates[0], m_arch,
1022                                     unused_loop};
1023   child_process.Detach();
1024   Status pt_error =
1025       PtraceWrapper(PT_CONTINUE, GetID(), reinterpret_cast<void *>(1), 0);
1026   if (pt_error.Fail()) {
1027     LLDB_LOG_ERROR(log, std::move(pt_error.ToError()),
1028                    "unable to resume parent process {1}: {0}", GetID());
1029     SetState(StateType::eStateInvalid);
1030   }
1031 }
1032