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