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