]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/source/Plugins/Process/NetBSD/NativeProcessNetBSD.cpp
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lldb / source / Plugins / Process / NetBSD / NativeProcessNetBSD.cpp
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     : NativeProcessProtocol(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   }
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     return;
211   }
212
213   switch (info.psi_siginfo.si_code) {
214   case TRAP_BRKPT:
215     for (const auto &thread : m_threads) {
216       static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByBreakpoint();
217       FixupBreakpointPCAsNeeded(static_cast<NativeThreadNetBSD &>(*thread));
218     }
219     SetState(StateType::eStateStopped, true);
220     break;
221   case TRAP_TRACE:
222     for (const auto &thread : m_threads)
223       static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByTrace();
224     SetState(StateType::eStateStopped, true);
225     break;
226   case TRAP_EXEC: {
227     Status error = ReinitializeThreads();
228     if (error.Fail()) {
229       SetState(StateType::eStateInvalid);
230       return;
231     }
232
233     // Let our delegate know we have just exec'd.
234     NotifyDidExec();
235
236     for (const auto &thread : m_threads)
237       static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByExec();
238     SetState(StateType::eStateStopped, true);
239   } break;
240   case TRAP_DBREG: {
241     // Find the thread.
242     NativeThreadNetBSD* thread = nullptr;
243     for (const auto &t : m_threads) {
244       if (t->GetID() == info.psi_lwpid) {
245         thread = static_cast<NativeThreadNetBSD *>(t.get());
246         break;
247       }
248     }
249     if (!thread) {
250       LLDB_LOG(log,
251                "thread not found in m_threads, pid = {0}, LWP = {1}",
252                GetID(), info.psi_lwpid);
253       break;
254     }
255
256     // If a watchpoint was hit, report it
257     uint32_t wp_index = LLDB_INVALID_INDEX32;
258     Status error = thread->GetRegisterContext().GetWatchpointHitIndex(
259         wp_index, (uintptr_t)info.psi_siginfo.si_addr);
260     if (error.Fail())
261       LLDB_LOG(log,
262                "received error while checking for watchpoint hits, pid = "
263                "{0}, LWP = {1}, error = {2}",
264                GetID(), info.psi_lwpid, error);
265     if (wp_index != LLDB_INVALID_INDEX32) {
266       for (const auto &thread : m_threads)
267         static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByWatchpoint(
268             wp_index);
269       SetState(StateType::eStateStopped, true);
270       break;
271     }
272
273     // If a breakpoint was hit, report it
274     uint32_t bp_index = LLDB_INVALID_INDEX32;
275     error = thread->GetRegisterContext().GetHardwareBreakHitIndex(
276         bp_index, (uintptr_t)info.psi_siginfo.si_addr);
277     if (error.Fail())
278       LLDB_LOG(log,
279                "received error while checking for hardware "
280                "breakpoint hits, pid = {0}, LWP = {1}, error = {2}",
281                GetID(), info.psi_lwpid, error);
282     if (bp_index != LLDB_INVALID_INDEX32) {
283       for (const auto &thread : m_threads)
284         static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByBreakpoint();
285       SetState(StateType::eStateStopped, true);
286       break;
287     }
288   } break;
289   }
290 }
291
292 void NativeProcessNetBSD::MonitorSignal(lldb::pid_t pid, int signal) {
293   ptrace_siginfo_t info;
294   const auto siginfo_err =
295       PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info));
296
297   for (const auto &thread : m_threads) {
298     static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(
299         info.psi_siginfo.si_signo, &info.psi_siginfo);
300   }
301   SetState(StateType::eStateStopped, true);
302 }
303
304 Status NativeProcessNetBSD::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
305                                           int data, int *result) {
306   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
307   Status error;
308   int ret;
309
310   errno = 0;
311   ret = ptrace(req, static_cast<::pid_t>(pid), addr, data);
312
313   if (ret == -1)
314     error.SetErrorToErrno();
315
316   if (result)
317     *result = ret;
318
319   LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3})={4:x}", req, pid, addr, data, ret);
320
321   if (error.Fail())
322     LLDB_LOG(log, "ptrace() failed: {0}", error);
323
324   return error;
325 }
326
327 Status NativeProcessNetBSD::Resume(const ResumeActionList &resume_actions) {
328   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
329   LLDB_LOG(log, "pid {0}", GetID());
330
331   const auto &thread = m_threads[0];
332   const ResumeAction *const action =
333       resume_actions.GetActionForThread(thread->GetID(), true);
334
335   if (action == nullptr) {
336     LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
337              thread->GetID());
338     return Status();
339   }
340
341   Status error;
342
343   switch (action->state) {
344   case eStateRunning: {
345     // Run the thread, possibly feeding it the signal.
346     error = NativeProcessNetBSD::PtraceWrapper(PT_CONTINUE, GetID(), (void *)1,
347                                                action->signal);
348     if (!error.Success())
349       return error;
350     for (const auto &thread : m_threads)
351       static_cast<NativeThreadNetBSD &>(*thread).SetRunning();
352     SetState(eStateRunning, true);
353     break;
354   }
355   case eStateStepping:
356     // Run the thread, possibly feeding it the signal.
357     error = NativeProcessNetBSD::PtraceWrapper(PT_STEP, GetID(), (void *)1,
358                                                action->signal);
359     if (!error.Success())
360       return error;
361     for (const auto &thread : m_threads)
362       static_cast<NativeThreadNetBSD &>(*thread).SetStepping();
363     SetState(eStateStepping, true);
364     break;
365
366   case eStateSuspended:
367   case eStateStopped:
368     llvm_unreachable("Unexpected state");
369
370   default:
371     return Status("NativeProcessNetBSD::%s (): unexpected state %s specified "
372                   "for pid %" PRIu64 ", tid %" PRIu64,
373                   __FUNCTION__, StateAsCString(action->state), GetID(),
374                   thread->GetID());
375   }
376
377   return Status();
378 }
379
380 Status NativeProcessNetBSD::Halt() {
381   Status error;
382
383   if (kill(GetID(), SIGSTOP) != 0)
384     error.SetErrorToErrno();
385
386   return error;
387 }
388
389 Status NativeProcessNetBSD::Detach() {
390   Status error;
391
392   // Stop monitoring the inferior.
393   m_sigchld_handle.reset();
394
395   // Tell ptrace to detach from the process.
396   if (GetID() == LLDB_INVALID_PROCESS_ID)
397     return error;
398
399   return PtraceWrapper(PT_DETACH, GetID());
400 }
401
402 Status NativeProcessNetBSD::Signal(int signo) {
403   Status error;
404
405   if (kill(GetID(), signo))
406     error.SetErrorToErrno();
407
408   return error;
409 }
410
411 Status NativeProcessNetBSD::Kill() {
412   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
413   LLDB_LOG(log, "pid {0}", GetID());
414
415   Status error;
416
417   switch (m_state) {
418   case StateType::eStateInvalid:
419   case StateType::eStateExited:
420   case StateType::eStateCrashed:
421   case StateType::eStateDetached:
422   case StateType::eStateUnloaded:
423     // Nothing to do - the process is already dead.
424     LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
425              StateAsCString(m_state));
426     return error;
427
428   case StateType::eStateConnected:
429   case StateType::eStateAttaching:
430   case StateType::eStateLaunching:
431   case StateType::eStateStopped:
432   case StateType::eStateRunning:
433   case StateType::eStateStepping:
434   case StateType::eStateSuspended:
435     // We can try to kill a process in these states.
436     break;
437   }
438
439   if (kill(GetID(), SIGKILL) != 0) {
440     error.SetErrorToErrno();
441     return error;
442   }
443
444   return error;
445 }
446
447 Status NativeProcessNetBSD::GetMemoryRegionInfo(lldb::addr_t load_addr,
448                                                 MemoryRegionInfo &range_info) {
449
450   if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
451     // We're done.
452     return Status("unsupported");
453   }
454
455   Status error = PopulateMemoryRegionCache();
456   if (error.Fail()) {
457     return error;
458   }
459
460   lldb::addr_t prev_base_address = 0;
461   // FIXME start by finding the last region that is <= target address using
462   // binary search.  Data is sorted.
463   // There can be a ton of regions on pthreads apps with lots of threads.
464   for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
465        ++it) {
466     MemoryRegionInfo &proc_entry_info = it->first;
467     // Sanity check assumption that memory map entries are ascending.
468     assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
469            "descending memory map entries detected, unexpected");
470     prev_base_address = proc_entry_info.GetRange().GetRangeBase();
471     UNUSED_IF_ASSERT_DISABLED(prev_base_address);
472     // If the target address comes before this entry, indicate distance to next
473     // region.
474     if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
475       range_info.GetRange().SetRangeBase(load_addr);
476       range_info.GetRange().SetByteSize(
477           proc_entry_info.GetRange().GetRangeBase() - load_addr);
478       range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
479       range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
480       range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
481       range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
482       return error;
483     } else if (proc_entry_info.GetRange().Contains(load_addr)) {
484       // The target address is within the memory region we're processing here.
485       range_info = proc_entry_info;
486       return error;
487     }
488     // The target memory address comes somewhere after the region we just
489     // parsed.
490   }
491   // If we made it here, we didn't find an entry that contained the given
492   // address. Return the load_addr as start and the amount of bytes betwwen
493   // load address and the end of the memory as size.
494   range_info.GetRange().SetRangeBase(load_addr);
495   range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
496   range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
497   range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
498   range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
499   range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
500   return error;
501 }
502
503 Status NativeProcessNetBSD::PopulateMemoryRegionCache() {
504   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
505   // If our cache is empty, pull the latest.  There should always be at least
506   // one memory region if memory region handling is supported.
507   if (!m_mem_region_cache.empty()) {
508     LLDB_LOG(log, "reusing {0} cached memory region entries",
509              m_mem_region_cache.size());
510     return Status();
511   }
512
513   struct kinfo_vmentry *vm;
514   size_t count, i;
515   vm = kinfo_getvmmap(GetID(), &count);
516   if (vm == NULL) {
517     m_supports_mem_region = LazyBool::eLazyBoolNo;
518     Status error;
519     error.SetErrorString("not supported");
520     return error;
521   }
522   for (i = 0; i < count; i++) {
523     MemoryRegionInfo info;
524     info.Clear();
525     info.GetRange().SetRangeBase(vm[i].kve_start);
526     info.GetRange().SetRangeEnd(vm[i].kve_end);
527     info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
528
529     if (vm[i].kve_protection & VM_PROT_READ)
530       info.SetReadable(MemoryRegionInfo::OptionalBool::eYes);
531     else
532       info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
533
534     if (vm[i].kve_protection & VM_PROT_WRITE)
535       info.SetWritable(MemoryRegionInfo::OptionalBool::eYes);
536     else
537       info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
538
539     if (vm[i].kve_protection & VM_PROT_EXECUTE)
540       info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes);
541     else
542       info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
543
544     if (vm[i].kve_path[0])
545       info.SetName(vm[i].kve_path);
546
547     m_mem_region_cache.emplace_back(
548         info, FileSpec(info.GetName().GetCString()));
549   }
550   free(vm);
551
552   if (m_mem_region_cache.empty()) {
553     // No entries after attempting to read them.  This shouldn't happen. Assume
554     // we don't support map entries.
555     LLDB_LOG(log, "failed to find any vmmap entries, assuming no support "
556                   "for memory region metadata retrieval");
557     m_supports_mem_region = LazyBool::eLazyBoolNo;
558     Status error;
559     error.SetErrorString("not supported");
560     return error;
561   }
562   LLDB_LOG(log, "read {0} memory region entries from process {1}",
563            m_mem_region_cache.size(), GetID());
564   // We support memory retrieval, remember that.
565   m_supports_mem_region = LazyBool::eLazyBoolYes;
566   return Status();
567 }
568
569 Status NativeProcessNetBSD::AllocateMemory(size_t size, uint32_t permissions,
570                                            lldb::addr_t &addr) {
571   return Status("Unimplemented");
572 }
573
574 Status NativeProcessNetBSD::DeallocateMemory(lldb::addr_t addr) {
575   return Status("Unimplemented");
576 }
577
578 lldb::addr_t NativeProcessNetBSD::GetSharedLibraryInfoAddress() {
579   // punt on this for now
580   return LLDB_INVALID_ADDRESS;
581 }
582
583 size_t NativeProcessNetBSD::UpdateThreads() { return m_threads.size(); }
584
585 Status NativeProcessNetBSD::SetBreakpoint(lldb::addr_t addr, uint32_t size,
586                                           bool hardware) {
587   if (hardware)
588     return Status("NativeProcessNetBSD does not support hardware breakpoints");
589   else
590     return SetSoftwareBreakpoint(addr, size);
591 }
592
593 Status NativeProcessNetBSD::GetLoadedModuleFileSpec(const char *module_path,
594                                                     FileSpec &file_spec) {
595   return Status("Unimplemented");
596 }
597
598 Status NativeProcessNetBSD::GetFileLoadAddress(const llvm::StringRef &file_name,
599                                                lldb::addr_t &load_addr) {
600   load_addr = LLDB_INVALID_ADDRESS;
601   return Status();
602 }
603
604 void NativeProcessNetBSD::SigchldHandler() {
605   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
606   // Process all pending waitpid notifications.
607   int status;
608   ::pid_t wait_pid =
609       llvm::sys::RetryAfterSignal(-1, waitpid, GetID(), &status, WALLSIG | WNOHANG);
610
611   if (wait_pid == 0)
612     return; // We are done.
613
614   if (wait_pid == -1) {
615     Status error(errno, eErrorTypePOSIX);
616     LLDB_LOG(log, "waitpid ({0}, &status, _) failed: {1}", GetID(), error);
617   }
618
619   WaitStatus wait_status = WaitStatus::Decode(status);
620   bool exited = wait_status.type == WaitStatus::Exit ||
621                 (wait_status.type == WaitStatus::Signal &&
622                  wait_pid == static_cast<::pid_t>(GetID()));
623
624   LLDB_LOG(log,
625            "waitpid ({0}, &status, _) => pid = {1}, status = {2}, exited = {3}",
626            GetID(), wait_pid, status, exited);
627
628   if (exited)
629     MonitorExited(wait_pid, wait_status);
630   else {
631     assert(wait_status.type == WaitStatus::Stop);
632     MonitorCallback(wait_pid, wait_status.status);
633   }
634 }
635
636 bool NativeProcessNetBSD::HasThreadNoLock(lldb::tid_t thread_id) {
637   for (const auto &thread : m_threads) {
638     assert(thread && "thread list should not contain NULL threads");
639     if (thread->GetID() == thread_id) {
640       // We have this thread.
641       return true;
642     }
643   }
644
645   // We don't have this thread.
646   return false;
647 }
648
649 NativeThreadNetBSD &NativeProcessNetBSD::AddThread(lldb::tid_t thread_id) {
650
651   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
652   LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
653
654   assert(!HasThreadNoLock(thread_id) &&
655          "attempted to add a thread by id that already exists");
656
657   // If this is the first thread, save it as the current thread
658   if (m_threads.empty())
659     SetCurrentThreadID(thread_id);
660
661   m_threads.push_back(llvm::make_unique<NativeThreadNetBSD>(*this, thread_id));
662   return static_cast<NativeThreadNetBSD &>(*m_threads.back());
663 }
664
665 Status NativeProcessNetBSD::Attach() {
666   // Attach to the requested process.
667   // An attach will cause the thread to stop with a SIGSTOP.
668   Status status = PtraceWrapper(PT_ATTACH, m_pid);
669   if (status.Fail())
670     return status;
671
672   int wstatus;
673   // Need to use WALLSIG otherwise we receive an error with errno=ECHLD At this
674   // point we should have a thread stopped if waitpid succeeds.
675   if ((wstatus = llvm::sys::RetryAfterSignal(-1, waitpid,
676           m_pid, nullptr, WALLSIG)) < 0)
677     return Status(errno, eErrorTypePOSIX);
678
679   /* Initialize threads */
680   status = ReinitializeThreads();
681   if (status.Fail())
682     return status;
683
684   for (const auto &thread : m_threads)
685     static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(SIGSTOP);
686
687   // Let our process instance know the thread has stopped.
688   SetState(StateType::eStateStopped);
689   return Status();
690 }
691
692 Status NativeProcessNetBSD::ReadMemory(lldb::addr_t addr, void *buf,
693                                        size_t size, size_t &bytes_read) {
694   unsigned char *dst = static_cast<unsigned char *>(buf);
695   struct ptrace_io_desc io;
696
697   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
698   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
699
700   bytes_read = 0;
701   io.piod_op = PIOD_READ_D;
702   io.piod_len = size;
703
704   do {
705     io.piod_offs = (void *)(addr + bytes_read);
706     io.piod_addr = dst + bytes_read;
707
708     Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
709     if (error.Fail() || io.piod_len == 0)
710       return error;
711
712     bytes_read += io.piod_len;
713     io.piod_len = size - bytes_read;
714   } while (bytes_read < size);
715
716   return Status();
717 }
718
719 Status NativeProcessNetBSD::WriteMemory(lldb::addr_t addr, const void *buf,
720                                         size_t size, size_t &bytes_written) {
721   const unsigned char *src = static_cast<const unsigned char *>(buf);
722   Status error;
723   struct ptrace_io_desc io;
724
725   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
726   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
727
728   bytes_written = 0;
729   io.piod_op = PIOD_WRITE_D;
730   io.piod_len = size;
731
732   do {
733     io.piod_addr = const_cast<void *>(static_cast<const void *>(src + bytes_written));
734     io.piod_offs = (void *)(addr + bytes_written);
735
736     Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
737     if (error.Fail() || io.piod_len == 0)
738       return error;
739
740     bytes_written += io.piod_len;
741     io.piod_len = size - bytes_written;
742   } while (bytes_written < size);
743
744   return error;
745 }
746
747 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
748 NativeProcessNetBSD::GetAuxvData() const {
749   /*
750    * ELF_AUX_ENTRIES is currently restricted to kernel
751    * (<sys/exec_elf.h> r. 1.155 specifies 15)
752    *
753    * ptrace(2) returns the whole AUXV including extra fiels after AT_NULL this
754    * information isn't needed.
755    */
756   size_t auxv_size = 100 * sizeof(AuxInfo);
757
758   ErrorOr<std::unique_ptr<WritableMemoryBuffer>> buf =
759       llvm::WritableMemoryBuffer::getNewMemBuffer(auxv_size);
760
761   struct ptrace_io_desc io;
762   io.piod_op = PIOD_READ_AUXV;
763   io.piod_offs = 0;
764   io.piod_addr = static_cast<void *>(buf.get()->getBufferStart());
765   io.piod_len = auxv_size;
766
767   Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
768
769   if (error.Fail())
770     return std::error_code(error.GetError(), std::generic_category());
771
772   if (io.piod_len < 1)
773     return std::error_code(ECANCELED, std::generic_category());
774
775   return std::move(buf);
776 }
777
778 Status NativeProcessNetBSD::ReinitializeThreads() {
779   // Clear old threads
780   m_threads.clear();
781
782   // Initialize new thread
783   struct ptrace_lwpinfo info = {};
784   Status error = PtraceWrapper(PT_LWPINFO, GetID(), &info, sizeof(info));
785   if (error.Fail()) {
786     return error;
787   }
788   // Reinitialize from scratch threads and register them in process
789   while (info.pl_lwpid != 0) {
790     AddThread(info.pl_lwpid);
791     error = PtraceWrapper(PT_LWPINFO, GetID(), &info, sizeof(info));
792     if (error.Fail()) {
793       return error;
794     }
795   }
796
797   return error;
798 }