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