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