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