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