xref: /freebsd-src/contrib/llvm-project/lldb/source/Plugins/Process/FreeBSD/NativeProcessFreeBSD.cpp (revision 2eb4d8dc723da3cf7d735a3226ae49da4c8c5dbc)
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       LLDB_LOG(log, "SIGTRAP/TRAP_BRKPT: si_addr: {0}",
269                info.pl_siginfo.si_addr);
270 
271       if (thread) {
272         auto thread_info =
273             m_threads_stepping_with_breakpoint.find(thread->GetID());
274         if (thread_info != m_threads_stepping_with_breakpoint.end()) {
275           thread->SetStoppedByTrace();
276           Status brkpt_error = RemoveBreakpoint(thread_info->second);
277           if (brkpt_error.Fail())
278             LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}",
279                      thread_info->first, brkpt_error);
280           m_threads_stepping_with_breakpoint.erase(thread_info);
281         } else
282           thread->SetStoppedByBreakpoint();
283         FixupBreakpointPCAsNeeded(*thread);
284       }
285       SetState(StateType::eStateStopped, true);
286       return;
287     case TRAP_TRACE:
288       LLDB_LOG(log, "SIGTRAP/TRAP_TRACE: si_addr: {0}",
289                info.pl_siginfo.si_addr);
290 
291       if (thread) {
292         auto &regctx = static_cast<NativeRegisterContextFreeBSD &>(
293             thread->GetRegisterContext());
294         uint32_t wp_index = LLDB_INVALID_INDEX32;
295         Status error = regctx.GetWatchpointHitIndex(
296             wp_index, reinterpret_cast<uintptr_t>(info.pl_siginfo.si_addr));
297         if (error.Fail())
298           LLDB_LOG(log,
299                    "received error while checking for watchpoint hits, pid = "
300                    "{0}, LWP = {1}, error = {2}",
301                    pid, info.pl_lwpid, error);
302         if (wp_index != LLDB_INVALID_INDEX32) {
303           regctx.ClearWatchpointHit(wp_index);
304           thread->SetStoppedByWatchpoint(wp_index);
305           SetState(StateType::eStateStopped, true);
306           break;
307         }
308 
309         thread->SetStoppedByTrace();
310       }
311 
312       SetState(StateType::eStateStopped, true);
313       return;
314     }
315   }
316 
317   // Either user-generated SIGTRAP or an unknown event that would
318   // otherwise leave the debugger hanging.
319   LLDB_LOG(log, "unknown SIGTRAP, passing to generic handler");
320   MonitorSignal(pid, SIGTRAP);
321 }
322 
323 void NativeProcessFreeBSD::MonitorSignal(lldb::pid_t pid, int signal) {
324   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
325   struct ptrace_lwpinfo info;
326 
327   const auto siginfo_err = PtraceWrapper(PT_LWPINFO, pid, &info, sizeof(info));
328   if (siginfo_err.Fail()) {
329     LLDB_LOG(log, "PT_LWPINFO failed {0}", siginfo_err);
330     return;
331   }
332   assert(info.pl_event == PL_EVENT_SIGNAL);
333   // TODO: do we need to handle !PL_FLAG_SI?
334   assert(info.pl_flags & PL_FLAG_SI);
335   assert(info.pl_siginfo.si_signo == signal);
336 
337   for (const auto &abs_thread : m_threads) {
338     NativeThreadFreeBSD &thread =
339         static_cast<NativeThreadFreeBSD &>(*abs_thread);
340     assert(info.pl_lwpid >= 0);
341     if (info.pl_lwpid == 0 ||
342         static_cast<lldb::tid_t>(info.pl_lwpid) == thread.GetID())
343       thread.SetStoppedBySignal(info.pl_siginfo.si_signo, &info.pl_siginfo);
344     else
345       thread.SetStoppedWithNoReason();
346   }
347   SetState(StateType::eStateStopped, true);
348 }
349 
350 Status NativeProcessFreeBSD::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
351                                            int data, int *result) {
352   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
353   Status error;
354   int ret;
355 
356   errno = 0;
357   ret =
358       ptrace(req, static_cast<::pid_t>(pid), static_cast<caddr_t>(addr), data);
359 
360   if (ret == -1)
361     error.SetErrorToErrno();
362 
363   if (result)
364     *result = ret;
365 
366   LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3})={4:x}", req, pid, addr, data, ret);
367 
368   if (error.Fail())
369     LLDB_LOG(log, "ptrace() failed: {0}", error);
370 
371   return error;
372 }
373 
374 llvm::Expected<llvm::ArrayRef<uint8_t>>
375 NativeProcessFreeBSD::GetSoftwareBreakpointTrapOpcode(size_t size_hint) {
376   static const uint8_t g_arm_opcode[] = {0xfe, 0xde, 0xff, 0xe7};
377   static const uint8_t g_thumb_opcode[] = {0x01, 0xde};
378 
379   switch (GetArchitecture().GetMachine()) {
380   case llvm::Triple::arm:
381     switch (size_hint) {
382     case 2:
383       return llvm::makeArrayRef(g_thumb_opcode);
384     case 4:
385       return llvm::makeArrayRef(g_arm_opcode);
386     default:
387       return llvm::createStringError(llvm::inconvertibleErrorCode(),
388                                      "Unrecognised trap opcode size hint!");
389     }
390   default:
391     return NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_hint);
392   }
393 }
394 
395 Status NativeProcessFreeBSD::Resume(const ResumeActionList &resume_actions) {
396   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
397   LLDB_LOG(log, "pid {0}", GetID());
398 
399   Status ret;
400 
401   int signal = 0;
402   for (const auto &abs_thread : m_threads) {
403     assert(abs_thread && "thread list should not contain NULL threads");
404     NativeThreadFreeBSD &thread =
405         static_cast<NativeThreadFreeBSD &>(*abs_thread);
406 
407     const ResumeAction *action =
408         resume_actions.GetActionForThread(thread.GetID(), true);
409     // we need to explicit issue suspend requests, so it is simpler to map it
410     // into proper action
411     ResumeAction suspend_action{thread.GetID(), eStateSuspended,
412                                 LLDB_INVALID_SIGNAL_NUMBER};
413 
414     if (action == nullptr) {
415       LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
416                thread.GetID());
417       action = &suspend_action;
418     }
419 
420     LLDB_LOG(
421         log,
422         "processing resume action state {0} signal {1} for pid {2} tid {3}",
423         action->state, action->signal, GetID(), thread.GetID());
424 
425     switch (action->state) {
426     case eStateRunning:
427       ret = thread.Resume();
428       break;
429     case eStateStepping:
430       ret = thread.SingleStep();
431       break;
432     case eStateSuspended:
433     case eStateStopped:
434       if (action->signal != LLDB_INVALID_SIGNAL_NUMBER)
435         return Status("Passing signal to suspended thread unsupported");
436 
437       ret = thread.Suspend();
438       break;
439 
440     default:
441       return Status(
442           "NativeProcessFreeBSD::%s (): unexpected state %s specified "
443           "for pid %" PRIu64 ", tid %" PRIu64,
444           __FUNCTION__, StateAsCString(action->state), GetID(), thread.GetID());
445     }
446 
447     if (!ret.Success())
448       return ret;
449     if (action->signal != LLDB_INVALID_SIGNAL_NUMBER)
450       signal = action->signal;
451   }
452 
453   ret =
454       PtraceWrapper(PT_CONTINUE, GetID(), reinterpret_cast<void *>(1), signal);
455   if (ret.Success())
456     SetState(eStateRunning, true);
457   return ret;
458 }
459 
460 Status NativeProcessFreeBSD::Halt() {
461   Status error;
462 
463   if (kill(GetID(), SIGSTOP) != 0)
464     error.SetErrorToErrno();
465   return error;
466 }
467 
468 Status NativeProcessFreeBSD::Detach() {
469   Status error;
470 
471   // Stop monitoring the inferior.
472   m_sigchld_handle.reset();
473 
474   // Tell ptrace to detach from the process.
475   if (GetID() == LLDB_INVALID_PROCESS_ID)
476     return error;
477 
478   return PtraceWrapper(PT_DETACH, GetID());
479 }
480 
481 Status NativeProcessFreeBSD::Signal(int signo) {
482   Status error;
483 
484   if (kill(GetID(), signo))
485     error.SetErrorToErrno();
486 
487   return error;
488 }
489 
490 Status NativeProcessFreeBSD::Interrupt() { return Halt(); }
491 
492 Status NativeProcessFreeBSD::Kill() {
493   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
494   LLDB_LOG(log, "pid {0}", GetID());
495 
496   Status error;
497 
498   switch (m_state) {
499   case StateType::eStateInvalid:
500   case StateType::eStateExited:
501   case StateType::eStateCrashed:
502   case StateType::eStateDetached:
503   case StateType::eStateUnloaded:
504     // Nothing to do - the process is already dead.
505     LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
506              StateAsCString(m_state));
507     return error;
508 
509   case StateType::eStateConnected:
510   case StateType::eStateAttaching:
511   case StateType::eStateLaunching:
512   case StateType::eStateStopped:
513   case StateType::eStateRunning:
514   case StateType::eStateStepping:
515   case StateType::eStateSuspended:
516     // We can try to kill a process in these states.
517     break;
518   }
519 
520   return PtraceWrapper(PT_KILL, m_pid);
521 }
522 
523 Status NativeProcessFreeBSD::GetMemoryRegionInfo(lldb::addr_t load_addr,
524                                                  MemoryRegionInfo &range_info) {
525 
526   if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
527     // We're done.
528     return Status("unsupported");
529   }
530 
531   Status error = PopulateMemoryRegionCache();
532   if (error.Fail()) {
533     return error;
534   }
535 
536   lldb::addr_t prev_base_address = 0;
537   // FIXME start by finding the last region that is <= target address using
538   // binary search.  Data is sorted.
539   // There can be a ton of regions on pthreads apps with lots of threads.
540   for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
541        ++it) {
542     MemoryRegionInfo &proc_entry_info = it->first;
543     // Sanity check assumption that memory map entries are ascending.
544     assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
545            "descending memory map entries detected, unexpected");
546     prev_base_address = proc_entry_info.GetRange().GetRangeBase();
547     UNUSED_IF_ASSERT_DISABLED(prev_base_address);
548     // If the target address comes before this entry, indicate distance to next
549     // region.
550     if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
551       range_info.GetRange().SetRangeBase(load_addr);
552       range_info.GetRange().SetByteSize(
553           proc_entry_info.GetRange().GetRangeBase() - load_addr);
554       range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
555       range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
556       range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
557       range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
558       return error;
559     } else if (proc_entry_info.GetRange().Contains(load_addr)) {
560       // The target address is within the memory region we're processing here.
561       range_info = proc_entry_info;
562       return error;
563     }
564     // The target memory address comes somewhere after the region we just
565     // parsed.
566   }
567   // If we made it here, we didn't find an entry that contained the given
568   // address. Return the load_addr as start and the amount of bytes betwwen
569   // load address and the end of the memory as size.
570   range_info.GetRange().SetRangeBase(load_addr);
571   range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
572   range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
573   range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
574   range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
575   range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
576   return error;
577 }
578 
579 Status NativeProcessFreeBSD::PopulateMemoryRegionCache() {
580   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
581   // If our cache is empty, pull the latest.  There should always be at least
582   // one memory region if memory region handling is supported.
583   if (!m_mem_region_cache.empty()) {
584     LLDB_LOG(log, "reusing {0} cached memory region entries",
585              m_mem_region_cache.size());
586     return Status();
587   }
588 
589   int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_VMMAP, static_cast<int>(m_pid)};
590   int ret;
591   size_t len;
592 
593   ret = ::sysctl(mib, 4, nullptr, &len, nullptr, 0);
594   if (ret != 0) {
595     m_supports_mem_region = LazyBool::eLazyBoolNo;
596     return Status("sysctl() for KERN_PROC_VMMAP failed");
597   }
598 
599   std::unique_ptr<WritableMemoryBuffer> buf =
600       llvm::WritableMemoryBuffer::getNewMemBuffer(len);
601   ret = ::sysctl(mib, 4, buf->getBufferStart(), &len, nullptr, 0);
602   if (ret != 0) {
603     m_supports_mem_region = LazyBool::eLazyBoolNo;
604     return Status("sysctl() for KERN_PROC_VMMAP failed");
605   }
606 
607   char *bp = buf->getBufferStart();
608   char *end = bp + len;
609   while (bp < end) {
610     auto *kv = reinterpret_cast<struct kinfo_vmentry *>(bp);
611     if (kv->kve_structsize == 0)
612       break;
613     bp += kv->kve_structsize;
614 
615     MemoryRegionInfo info;
616     info.Clear();
617     info.GetRange().SetRangeBase(kv->kve_start);
618     info.GetRange().SetRangeEnd(kv->kve_end);
619     info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
620 
621     if (kv->kve_protection & VM_PROT_READ)
622       info.SetReadable(MemoryRegionInfo::OptionalBool::eYes);
623     else
624       info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
625 
626     if (kv->kve_protection & VM_PROT_WRITE)
627       info.SetWritable(MemoryRegionInfo::OptionalBool::eYes);
628     else
629       info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
630 
631     if (kv->kve_protection & VM_PROT_EXECUTE)
632       info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes);
633     else
634       info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
635 
636     if (kv->kve_path[0])
637       info.SetName(kv->kve_path);
638 
639     m_mem_region_cache.emplace_back(info,
640                                     FileSpec(info.GetName().GetCString()));
641   }
642 
643   if (m_mem_region_cache.empty()) {
644     // No entries after attempting to read them.  This shouldn't happen. Assume
645     // we don't support map entries.
646     LLDB_LOG(log, "failed to find any vmmap entries, assuming no support "
647                   "for memory region metadata retrieval");
648     m_supports_mem_region = LazyBool::eLazyBoolNo;
649     return Status("not supported");
650   }
651   LLDB_LOG(log, "read {0} memory region entries from process {1}",
652            m_mem_region_cache.size(), GetID());
653   // We support memory retrieval, remember that.
654   m_supports_mem_region = LazyBool::eLazyBoolYes;
655 
656   return Status();
657 }
658 
659 size_t NativeProcessFreeBSD::UpdateThreads() { return m_threads.size(); }
660 
661 Status NativeProcessFreeBSD::SetBreakpoint(lldb::addr_t addr, uint32_t size,
662                                            bool hardware) {
663   if (hardware)
664     return SetHardwareBreakpoint(addr, size);
665   return SetSoftwareBreakpoint(addr, size);
666 }
667 
668 Status NativeProcessFreeBSD::GetLoadedModuleFileSpec(const char *module_path,
669                                                      FileSpec &file_spec) {
670   Status error = PopulateMemoryRegionCache();
671   if (error.Fail())
672     return error;
673 
674   FileSpec module_file_spec(module_path);
675   FileSystem::Instance().Resolve(module_file_spec);
676 
677   file_spec.Clear();
678   for (const auto &it : m_mem_region_cache) {
679     if (it.second.GetFilename() == module_file_spec.GetFilename()) {
680       file_spec = it.second;
681       return Status();
682     }
683   }
684   return Status("Module file (%s) not found in process' memory map!",
685                 module_file_spec.GetFilename().AsCString());
686 }
687 
688 Status
689 NativeProcessFreeBSD::GetFileLoadAddress(const llvm::StringRef &file_name,
690                                          lldb::addr_t &load_addr) {
691   load_addr = LLDB_INVALID_ADDRESS;
692   Status error = PopulateMemoryRegionCache();
693   if (error.Fail())
694     return error;
695 
696   FileSpec file(file_name);
697   for (const auto &it : m_mem_region_cache) {
698     if (it.second == file) {
699       load_addr = it.first.GetRange().GetRangeBase();
700       return Status();
701     }
702   }
703   return Status("No load address found for file %s.", file_name.str().c_str());
704 }
705 
706 void NativeProcessFreeBSD::SigchldHandler() {
707   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
708   // Process all pending waitpid notifications.
709   int status;
710   ::pid_t wait_pid =
711       llvm::sys::RetryAfterSignal(-1, waitpid, GetID(), &status, WNOHANG);
712 
713   if (wait_pid == 0)
714     return; // We are done.
715 
716   if (wait_pid == -1) {
717     Status error(errno, eErrorTypePOSIX);
718     LLDB_LOG(log, "waitpid ({0}, &status, _) failed: {1}", GetID(), error);
719   }
720 
721   WaitStatus wait_status = WaitStatus::Decode(status);
722   bool exited = wait_status.type == WaitStatus::Exit ||
723                 (wait_status.type == WaitStatus::Signal &&
724                  wait_pid == static_cast<::pid_t>(GetID()));
725 
726   LLDB_LOG(log,
727            "waitpid ({0}, &status, _) => pid = {1}, status = {2}, exited = {3}",
728            GetID(), wait_pid, status, exited);
729 
730   if (exited)
731     MonitorExited(wait_pid, wait_status);
732   else {
733     assert(wait_status.type == WaitStatus::Stop);
734     MonitorCallback(wait_pid, wait_status.status);
735   }
736 }
737 
738 bool NativeProcessFreeBSD::HasThreadNoLock(lldb::tid_t thread_id) {
739   for (const auto &thread : m_threads) {
740     assert(thread && "thread list should not contain NULL threads");
741     if (thread->GetID() == thread_id) {
742       // We have this thread.
743       return true;
744     }
745   }
746 
747   // We don't have this thread.
748   return false;
749 }
750 
751 NativeThreadFreeBSD &NativeProcessFreeBSD::AddThread(lldb::tid_t thread_id) {
752   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
753   LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
754 
755   assert(thread_id > 0);
756   assert(!HasThreadNoLock(thread_id) &&
757          "attempted to add a thread by id that already exists");
758 
759   // If this is the first thread, save it as the current thread
760   if (m_threads.empty())
761     SetCurrentThreadID(thread_id);
762 
763   m_threads.push_back(std::make_unique<NativeThreadFreeBSD>(*this, thread_id));
764   return static_cast<NativeThreadFreeBSD &>(*m_threads.back());
765 }
766 
767 void NativeProcessFreeBSD::RemoveThread(lldb::tid_t thread_id) {
768   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
769   LLDB_LOG(log, "pid {0} removing thread with tid {1}", GetID(), thread_id);
770 
771   assert(thread_id > 0);
772   assert(HasThreadNoLock(thread_id) &&
773          "attempted to remove a thread that does not exist");
774 
775   for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
776     if ((*it)->GetID() == thread_id) {
777       m_threads.erase(it);
778       break;
779     }
780   }
781 }
782 
783 Status NativeProcessFreeBSD::Attach() {
784   // Attach to the requested process.
785   // An attach will cause the thread to stop with a SIGSTOP.
786   Status status = PtraceWrapper(PT_ATTACH, m_pid);
787   if (status.Fail())
788     return status;
789 
790   int wstatus;
791   // Need to use WALLSIG otherwise we receive an error with errno=ECHLD At this
792   // point we should have a thread stopped if waitpid succeeds.
793   if ((wstatus = llvm::sys::RetryAfterSignal(-1, waitpid, m_pid, nullptr, 0)) <
794       0)
795     return Status(errno, eErrorTypePOSIX);
796 
797   // Initialize threads and tracing status
798   // NB: this needs to be called before we set thread state
799   status = SetupTrace();
800   if (status.Fail())
801     return status;
802 
803   for (const auto &thread : m_threads)
804     static_cast<NativeThreadFreeBSD &>(*thread).SetStoppedBySignal(SIGSTOP);
805 
806   // Let our process instance know the thread has stopped.
807   SetCurrentThreadID(m_threads.front()->GetID());
808   SetState(StateType::eStateStopped, false);
809   return Status();
810 }
811 
812 Status NativeProcessFreeBSD::ReadMemory(lldb::addr_t addr, void *buf,
813                                         size_t size, size_t &bytes_read) {
814   unsigned char *dst = static_cast<unsigned char *>(buf);
815   struct ptrace_io_desc io;
816 
817   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
818   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
819 
820   bytes_read = 0;
821   io.piod_op = PIOD_READ_D;
822   io.piod_len = size;
823 
824   do {
825     io.piod_offs = (void *)(addr + bytes_read);
826     io.piod_addr = dst + bytes_read;
827 
828     Status error = NativeProcessFreeBSD::PtraceWrapper(PT_IO, GetID(), &io);
829     if (error.Fail() || io.piod_len == 0)
830       return error;
831 
832     bytes_read += io.piod_len;
833     io.piod_len = size - bytes_read;
834   } while (bytes_read < size);
835 
836   return Status();
837 }
838 
839 Status NativeProcessFreeBSD::WriteMemory(lldb::addr_t addr, const void *buf,
840                                          size_t size, size_t &bytes_written) {
841   const unsigned char *src = static_cast<const unsigned char *>(buf);
842   Status error;
843   struct ptrace_io_desc io;
844 
845   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
846   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
847 
848   bytes_written = 0;
849   io.piod_op = PIOD_WRITE_D;
850   io.piod_len = size;
851 
852   do {
853     io.piod_addr =
854         const_cast<void *>(static_cast<const void *>(src + bytes_written));
855     io.piod_offs = (void *)(addr + bytes_written);
856 
857     Status error = NativeProcessFreeBSD::PtraceWrapper(PT_IO, GetID(), &io);
858     if (error.Fail() || io.piod_len == 0)
859       return error;
860 
861     bytes_written += io.piod_len;
862     io.piod_len = size - bytes_written;
863   } while (bytes_written < size);
864 
865   return error;
866 }
867 
868 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
869 NativeProcessFreeBSD::GetAuxvData() const {
870   int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_AUXV, static_cast<int>(GetID())};
871   size_t auxv_size = AT_COUNT * sizeof(Elf_Auxinfo);
872   std::unique_ptr<WritableMemoryBuffer> buf =
873       llvm::WritableMemoryBuffer::getNewMemBuffer(auxv_size);
874 
875   if (::sysctl(mib, 4, buf->getBufferStart(), &auxv_size, nullptr, 0) != 0)
876     return std::error_code(errno, std::generic_category());
877 
878   return buf;
879 }
880 
881 Status NativeProcessFreeBSD::SetupTrace() {
882   // Enable event reporting
883   int events;
884   Status status =
885       PtraceWrapper(PT_GET_EVENT_MASK, GetID(), &events, sizeof(events));
886   if (status.Fail())
887     return status;
888   events |= PTRACE_LWP;
889   status = PtraceWrapper(PT_SET_EVENT_MASK, GetID(), &events, sizeof(events));
890   if (status.Fail())
891     return status;
892 
893   return ReinitializeThreads();
894 }
895 
896 Status NativeProcessFreeBSD::ReinitializeThreads() {
897   // Clear old threads
898   m_threads.clear();
899 
900   int num_lwps;
901   Status error = PtraceWrapper(PT_GETNUMLWPS, GetID(), nullptr, 0, &num_lwps);
902   if (error.Fail())
903     return error;
904 
905   std::vector<lwpid_t> lwp_ids;
906   lwp_ids.resize(num_lwps);
907   error = PtraceWrapper(PT_GETLWPLIST, GetID(), lwp_ids.data(),
908                         lwp_ids.size() * sizeof(lwpid_t), &num_lwps);
909   if (error.Fail())
910     return error;
911 
912   // Reinitialize from scratch threads and register them in process
913   for (lwpid_t lwp : lwp_ids)
914     AddThread(lwp);
915 
916   return error;
917 }
918 
919 bool NativeProcessFreeBSD::SupportHardwareSingleStepping() const {
920   return !m_arch.IsMIPS();
921 }
922