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