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