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