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