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