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