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   return PtraceWrapper(PT_STOP, GetID());
385 }
386 
387 Status NativeProcessNetBSD::Detach() {
388   Status error;
389 
390   // Stop monitoring the inferior.
391   m_sigchld_handle.reset();
392 
393   // Tell ptrace to detach from the process.
394   if (GetID() == LLDB_INVALID_PROCESS_ID)
395     return error;
396 
397   return PtraceWrapper(PT_DETACH, GetID());
398 }
399 
400 Status NativeProcessNetBSD::Signal(int signo) {
401   Status error;
402 
403   if (kill(GetID(), signo))
404     error.SetErrorToErrno();
405 
406   return error;
407 }
408 
409 Status NativeProcessNetBSD::Interrupt() {
410   return PtraceWrapper(PT_STOP, GetID());
411 }
412 
413 Status NativeProcessNetBSD::Kill() {
414   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
415   LLDB_LOG(log, "pid {0}", GetID());
416 
417   Status error;
418 
419   switch (m_state) {
420   case StateType::eStateInvalid:
421   case StateType::eStateExited:
422   case StateType::eStateCrashed:
423   case StateType::eStateDetached:
424   case StateType::eStateUnloaded:
425     // Nothing to do - the process is already dead.
426     LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
427              StateAsCString(m_state));
428     return error;
429 
430   case StateType::eStateConnected:
431   case StateType::eStateAttaching:
432   case StateType::eStateLaunching:
433   case StateType::eStateStopped:
434   case StateType::eStateRunning:
435   case StateType::eStateStepping:
436   case StateType::eStateSuspended:
437     // We can try to kill a process in these states.
438     break;
439   }
440 
441   if (kill(GetID(), SIGKILL) != 0) {
442     error.SetErrorToErrno();
443     return error;
444   }
445 
446   return error;
447 }
448 
449 Status NativeProcessNetBSD::GetMemoryRegionInfo(lldb::addr_t load_addr,
450                                                 MemoryRegionInfo &range_info) {
451 
452   if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
453     // We're done.
454     return Status("unsupported");
455   }
456 
457   Status error = PopulateMemoryRegionCache();
458   if (error.Fail()) {
459     return error;
460   }
461 
462   lldb::addr_t prev_base_address = 0;
463   // FIXME start by finding the last region that is <= target address using
464   // binary search.  Data is sorted.
465   // There can be a ton of regions on pthreads apps with lots of threads.
466   for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
467        ++it) {
468     MemoryRegionInfo &proc_entry_info = it->first;
469     // Sanity check assumption that memory map entries are ascending.
470     assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
471            "descending memory map entries detected, unexpected");
472     prev_base_address = proc_entry_info.GetRange().GetRangeBase();
473     UNUSED_IF_ASSERT_DISABLED(prev_base_address);
474     // If the target address comes before this entry, indicate distance to next
475     // region.
476     if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
477       range_info.GetRange().SetRangeBase(load_addr);
478       range_info.GetRange().SetByteSize(
479           proc_entry_info.GetRange().GetRangeBase() - load_addr);
480       range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
481       range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
482       range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
483       range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
484       return error;
485     } else if (proc_entry_info.GetRange().Contains(load_addr)) {
486       // The target address is within the memory region we're processing here.
487       range_info = proc_entry_info;
488       return error;
489     }
490     // The target memory address comes somewhere after the region we just
491     // parsed.
492   }
493   // If we made it here, we didn't find an entry that contained the given
494   // address. Return the load_addr as start and the amount of bytes betwwen
495   // load address and the end of the memory as size.
496   range_info.GetRange().SetRangeBase(load_addr);
497   range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
498   range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
499   range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
500   range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
501   range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
502   return error;
503 }
504 
505 Status NativeProcessNetBSD::PopulateMemoryRegionCache() {
506   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
507   // If our cache is empty, pull the latest.  There should always be at least
508   // one memory region if memory region handling is supported.
509   if (!m_mem_region_cache.empty()) {
510     LLDB_LOG(log, "reusing {0} cached memory region entries",
511              m_mem_region_cache.size());
512     return Status();
513   }
514 
515   struct kinfo_vmentry *vm;
516   size_t count, i;
517   vm = kinfo_getvmmap(GetID(), &count);
518   if (vm == NULL) {
519     m_supports_mem_region = LazyBool::eLazyBoolNo;
520     Status error;
521     error.SetErrorString("not supported");
522     return error;
523   }
524   for (i = 0; i < count; i++) {
525     MemoryRegionInfo info;
526     info.Clear();
527     info.GetRange().SetRangeBase(vm[i].kve_start);
528     info.GetRange().SetRangeEnd(vm[i].kve_end);
529     info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
530 
531     if (vm[i].kve_protection & VM_PROT_READ)
532       info.SetReadable(MemoryRegionInfo::OptionalBool::eYes);
533     else
534       info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
535 
536     if (vm[i].kve_protection & VM_PROT_WRITE)
537       info.SetWritable(MemoryRegionInfo::OptionalBool::eYes);
538     else
539       info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
540 
541     if (vm[i].kve_protection & VM_PROT_EXECUTE)
542       info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes);
543     else
544       info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
545 
546     if (vm[i].kve_path[0])
547       info.SetName(vm[i].kve_path);
548 
549     m_mem_region_cache.emplace_back(
550         info, FileSpec(info.GetName().GetCString()));
551   }
552   free(vm);
553 
554   if (m_mem_region_cache.empty()) {
555     // No entries after attempting to read them.  This shouldn't happen. Assume
556     // we don't support map entries.
557     LLDB_LOG(log, "failed to find any vmmap entries, assuming no support "
558                   "for memory region metadata retrieval");
559     m_supports_mem_region = LazyBool::eLazyBoolNo;
560     Status error;
561     error.SetErrorString("not supported");
562     return error;
563   }
564   LLDB_LOG(log, "read {0} memory region entries from process {1}",
565            m_mem_region_cache.size(), GetID());
566   // We support memory retrieval, remember that.
567   m_supports_mem_region = LazyBool::eLazyBoolYes;
568   return Status();
569 }
570 
571 Status NativeProcessNetBSD::AllocateMemory(size_t size, uint32_t permissions,
572                                            lldb::addr_t &addr) {
573   return Status("Unimplemented");
574 }
575 
576 Status NativeProcessNetBSD::DeallocateMemory(lldb::addr_t addr) {
577   return Status("Unimplemented");
578 }
579 
580 lldb::addr_t NativeProcessNetBSD::GetSharedLibraryInfoAddress() {
581   // punt on this for now
582   return LLDB_INVALID_ADDRESS;
583 }
584 
585 size_t NativeProcessNetBSD::UpdateThreads() { return m_threads.size(); }
586 
587 Status NativeProcessNetBSD::SetBreakpoint(lldb::addr_t addr, uint32_t size,
588                                           bool hardware) {
589   if (hardware)
590     return Status("NativeProcessNetBSD does not support hardware breakpoints");
591   else
592     return SetSoftwareBreakpoint(addr, size);
593 }
594 
595 Status NativeProcessNetBSD::GetLoadedModuleFileSpec(const char *module_path,
596                                                     FileSpec &file_spec) {
597   return Status("Unimplemented");
598 }
599 
600 Status NativeProcessNetBSD::GetFileLoadAddress(const llvm::StringRef &file_name,
601                                                lldb::addr_t &load_addr) {
602   load_addr = LLDB_INVALID_ADDRESS;
603   return Status();
604 }
605 
606 void NativeProcessNetBSD::SigchldHandler() {
607   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
608   // Process all pending waitpid notifications.
609   int status;
610   ::pid_t wait_pid =
611       llvm::sys::RetryAfterSignal(-1, waitpid, GetID(), &status, WALLSIG | WNOHANG);
612 
613   if (wait_pid == 0)
614     return; // We are done.
615 
616   if (wait_pid == -1) {
617     Status error(errno, eErrorTypePOSIX);
618     LLDB_LOG(log, "waitpid ({0}, &status, _) failed: {1}", GetID(), error);
619   }
620 
621   WaitStatus wait_status = WaitStatus::Decode(status);
622   bool exited = wait_status.type == WaitStatus::Exit ||
623                 (wait_status.type == WaitStatus::Signal &&
624                  wait_pid == static_cast<::pid_t>(GetID()));
625 
626   LLDB_LOG(log,
627            "waitpid ({0}, &status, _) => pid = {1}, status = {2}, exited = {3}",
628            GetID(), wait_pid, status, exited);
629 
630   if (exited)
631     MonitorExited(wait_pid, wait_status);
632   else {
633     assert(wait_status.type == WaitStatus::Stop);
634     MonitorCallback(wait_pid, wait_status.status);
635   }
636 }
637 
638 bool NativeProcessNetBSD::HasThreadNoLock(lldb::tid_t thread_id) {
639   for (const auto &thread : m_threads) {
640     assert(thread && "thread list should not contain NULL threads");
641     if (thread->GetID() == thread_id) {
642       // We have this thread.
643       return true;
644     }
645   }
646 
647   // We don't have this thread.
648   return false;
649 }
650 
651 NativeThreadNetBSD &NativeProcessNetBSD::AddThread(lldb::tid_t thread_id) {
652 
653   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
654   LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
655 
656   assert(!HasThreadNoLock(thread_id) &&
657          "attempted to add a thread by id that already exists");
658 
659   // If this is the first thread, save it as the current thread
660   if (m_threads.empty())
661     SetCurrentThreadID(thread_id);
662 
663   m_threads.push_back(std::make_unique<NativeThreadNetBSD>(*this, thread_id));
664   return static_cast<NativeThreadNetBSD &>(*m_threads.back());
665 }
666 
667 Status NativeProcessNetBSD::Attach() {
668   // Attach to the requested process.
669   // An attach will cause the thread to stop with a SIGSTOP.
670   Status status = PtraceWrapper(PT_ATTACH, m_pid);
671   if (status.Fail())
672     return status;
673 
674   int wstatus;
675   // Need to use WALLSIG otherwise we receive an error with errno=ECHLD At this
676   // point we should have a thread stopped if waitpid succeeds.
677   if ((wstatus = llvm::sys::RetryAfterSignal(-1, waitpid,
678           m_pid, nullptr, WALLSIG)) < 0)
679     return Status(errno, eErrorTypePOSIX);
680 
681   /* Initialize threads */
682   status = ReinitializeThreads();
683   if (status.Fail())
684     return status;
685 
686   for (const auto &thread : m_threads)
687     static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(SIGSTOP);
688 
689   // Let our process instance know the thread has stopped.
690   SetState(StateType::eStateStopped);
691   return Status();
692 }
693 
694 Status NativeProcessNetBSD::ReadMemory(lldb::addr_t addr, void *buf,
695                                        size_t size, size_t &bytes_read) {
696   unsigned char *dst = static_cast<unsigned char *>(buf);
697   struct ptrace_io_desc io;
698 
699   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
700   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
701 
702   bytes_read = 0;
703   io.piod_op = PIOD_READ_D;
704   io.piod_len = size;
705 
706   do {
707     io.piod_offs = (void *)(addr + bytes_read);
708     io.piod_addr = dst + bytes_read;
709 
710     Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
711     if (error.Fail() || io.piod_len == 0)
712       return error;
713 
714     bytes_read += io.piod_len;
715     io.piod_len = size - bytes_read;
716   } while (bytes_read < size);
717 
718   return Status();
719 }
720 
721 Status NativeProcessNetBSD::WriteMemory(lldb::addr_t addr, const void *buf,
722                                         size_t size, size_t &bytes_written) {
723   const unsigned char *src = static_cast<const unsigned char *>(buf);
724   Status error;
725   struct ptrace_io_desc io;
726 
727   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
728   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
729 
730   bytes_written = 0;
731   io.piod_op = PIOD_WRITE_D;
732   io.piod_len = size;
733 
734   do {
735     io.piod_addr = const_cast<void *>(static_cast<const void *>(src + bytes_written));
736     io.piod_offs = (void *)(addr + bytes_written);
737 
738     Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
739     if (error.Fail() || io.piod_len == 0)
740       return error;
741 
742     bytes_written += io.piod_len;
743     io.piod_len = size - bytes_written;
744   } while (bytes_written < size);
745 
746   return error;
747 }
748 
749 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
750 NativeProcessNetBSD::GetAuxvData() const {
751   /*
752    * ELF_AUX_ENTRIES is currently restricted to kernel
753    * (<sys/exec_elf.h> r. 1.155 specifies 15)
754    *
755    * ptrace(2) returns the whole AUXV including extra fiels after AT_NULL this
756    * information isn't needed.
757    */
758   size_t auxv_size = 100 * sizeof(AuxInfo);
759 
760   ErrorOr<std::unique_ptr<WritableMemoryBuffer>> buf =
761       llvm::WritableMemoryBuffer::getNewMemBuffer(auxv_size);
762 
763   struct ptrace_io_desc io;
764   io.piod_op = PIOD_READ_AUXV;
765   io.piod_offs = 0;
766   io.piod_addr = static_cast<void *>(buf.get()->getBufferStart());
767   io.piod_len = auxv_size;
768 
769   Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
770 
771   if (error.Fail())
772     return std::error_code(error.GetError(), std::generic_category());
773 
774   if (io.piod_len < 1)
775     return std::error_code(ECANCELED, std::generic_category());
776 
777   return std::move(buf);
778 }
779 
780 Status NativeProcessNetBSD::ReinitializeThreads() {
781   // Clear old threads
782   m_threads.clear();
783 
784   // Initialize new thread
785   struct ptrace_lwpinfo info = {};
786   Status error = PtraceWrapper(PT_LWPINFO, GetID(), &info, sizeof(info));
787   if (error.Fail()) {
788     return error;
789   }
790   // Reinitialize from scratch threads and register them in process
791   while (info.pl_lwpid != 0) {
792     AddThread(info.pl_lwpid);
793     error = PtraceWrapper(PT_LWPINFO, GetID(), &info, sizeof(info));
794     if (error.Fail()) {
795       return error;
796     }
797   }
798 
799   return error;
800 }
801