1dda28197Spatrick //===-- NativeProcessLinux.cpp --------------------------------------------===//
2061da546Spatrick //
3061da546Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4061da546Spatrick // See https://llvm.org/LICENSE.txt for license information.
5061da546Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6061da546Spatrick //
7061da546Spatrick //===----------------------------------------------------------------------===//
8061da546Spatrick
9061da546Spatrick #include "NativeProcessLinux.h"
10061da546Spatrick
11be691f3bSpatrick #include <cerrno>
12be691f3bSpatrick #include <cstdint>
13be691f3bSpatrick #include <cstring>
14061da546Spatrick #include <unistd.h>
15061da546Spatrick
16061da546Spatrick #include <fstream>
17061da546Spatrick #include <mutex>
18*f6aab3d8Srobert #include <optional>
19061da546Spatrick #include <sstream>
20061da546Spatrick #include <string>
21061da546Spatrick #include <unordered_map>
22061da546Spatrick
23be691f3bSpatrick #include "NativeThreadLinux.h"
24be691f3bSpatrick #include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
25be691f3bSpatrick #include "Plugins/Process/Utility/LinuxProcMaps.h"
26be691f3bSpatrick #include "Procfs.h"
27061da546Spatrick #include "lldb/Core/ModuleSpec.h"
28061da546Spatrick #include "lldb/Host/Host.h"
29061da546Spatrick #include "lldb/Host/HostProcess.h"
30061da546Spatrick #include "lldb/Host/ProcessLaunchInfo.h"
31061da546Spatrick #include "lldb/Host/PseudoTerminal.h"
32061da546Spatrick #include "lldb/Host/ThreadLauncher.h"
33061da546Spatrick #include "lldb/Host/common/NativeRegisterContext.h"
34be691f3bSpatrick #include "lldb/Host/linux/Host.h"
35061da546Spatrick #include "lldb/Host/linux/Ptrace.h"
36061da546Spatrick #include "lldb/Host/linux/Uio.h"
37061da546Spatrick #include "lldb/Host/posix/ProcessLauncherPosixFork.h"
38061da546Spatrick #include "lldb/Symbol/ObjectFile.h"
39061da546Spatrick #include "lldb/Target/Process.h"
40061da546Spatrick #include "lldb/Target/Target.h"
41061da546Spatrick #include "lldb/Utility/LLDBAssert.h"
42*f6aab3d8Srobert #include "lldb/Utility/LLDBLog.h"
43061da546Spatrick #include "lldb/Utility/State.h"
44061da546Spatrick #include "lldb/Utility/Status.h"
45061da546Spatrick #include "lldb/Utility/StringExtractor.h"
46be691f3bSpatrick #include "llvm/ADT/ScopeExit.h"
47061da546Spatrick #include "llvm/Support/Errno.h"
48061da546Spatrick #include "llvm/Support/FileSystem.h"
49061da546Spatrick #include "llvm/Support/Threading.h"
50061da546Spatrick
51061da546Spatrick #include <linux/unistd.h>
52061da546Spatrick #include <sys/socket.h>
53061da546Spatrick #include <sys/syscall.h>
54061da546Spatrick #include <sys/types.h>
55061da546Spatrick #include <sys/user.h>
56061da546Spatrick #include <sys/wait.h>
57061da546Spatrick
58be691f3bSpatrick #ifdef __aarch64__
59be691f3bSpatrick #include <asm/hwcap.h>
60be691f3bSpatrick #include <sys/auxv.h>
61be691f3bSpatrick #endif
62be691f3bSpatrick
63061da546Spatrick // Support hardware breakpoints in case it has not been defined
64061da546Spatrick #ifndef TRAP_HWBKPT
65061da546Spatrick #define TRAP_HWBKPT 4
66061da546Spatrick #endif
67061da546Spatrick
68be691f3bSpatrick #ifndef HWCAP2_MTE
69be691f3bSpatrick #define HWCAP2_MTE (1 << 18)
70be691f3bSpatrick #endif
71be691f3bSpatrick
72061da546Spatrick using namespace lldb;
73061da546Spatrick using namespace lldb_private;
74061da546Spatrick using namespace lldb_private::process_linux;
75061da546Spatrick using namespace llvm;
76061da546Spatrick
77061da546Spatrick // Private bits we only need internally.
78061da546Spatrick
ProcessVmReadvSupported()79061da546Spatrick static bool ProcessVmReadvSupported() {
80061da546Spatrick static bool is_supported;
81061da546Spatrick static llvm::once_flag flag;
82061da546Spatrick
83061da546Spatrick llvm::call_once(flag, [] {
84*f6aab3d8Srobert Log *log = GetLog(POSIXLog::Process);
85061da546Spatrick
86061da546Spatrick uint32_t source = 0x47424742;
87061da546Spatrick uint32_t dest = 0;
88061da546Spatrick
89061da546Spatrick struct iovec local, remote;
90061da546Spatrick remote.iov_base = &source;
91061da546Spatrick local.iov_base = &dest;
92061da546Spatrick remote.iov_len = local.iov_len = sizeof source;
93061da546Spatrick
94061da546Spatrick // We shall try if cross-process-memory reads work by attempting to read a
95061da546Spatrick // value from our own process.
96061da546Spatrick ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
97061da546Spatrick is_supported = (res == sizeof(source) && source == dest);
98061da546Spatrick if (is_supported)
99061da546Spatrick LLDB_LOG(log,
100061da546Spatrick "Detected kernel support for process_vm_readv syscall. "
101061da546Spatrick "Fast memory reads enabled.");
102061da546Spatrick else
103061da546Spatrick LLDB_LOG(log,
104061da546Spatrick "syscall process_vm_readv failed (error: {0}). Fast memory "
105061da546Spatrick "reads disabled.",
106061da546Spatrick llvm::sys::StrError());
107061da546Spatrick });
108061da546Spatrick
109061da546Spatrick return is_supported;
110061da546Spatrick }
111061da546Spatrick
MaybeLogLaunchInfo(const ProcessLaunchInfo & info)112*f6aab3d8Srobert static void MaybeLogLaunchInfo(const ProcessLaunchInfo &info) {
113*f6aab3d8Srobert Log *log = GetLog(POSIXLog::Process);
114061da546Spatrick if (!log)
115061da546Spatrick return;
116061da546Spatrick
117061da546Spatrick if (const FileAction *action = info.GetFileActionForFD(STDIN_FILENO))
118061da546Spatrick LLDB_LOG(log, "setting STDIN to '{0}'", action->GetFileSpec());
119061da546Spatrick else
120061da546Spatrick LLDB_LOG(log, "leaving STDIN as is");
121061da546Spatrick
122061da546Spatrick if (const FileAction *action = info.GetFileActionForFD(STDOUT_FILENO))
123061da546Spatrick LLDB_LOG(log, "setting STDOUT to '{0}'", action->GetFileSpec());
124061da546Spatrick else
125061da546Spatrick LLDB_LOG(log, "leaving STDOUT as is");
126061da546Spatrick
127061da546Spatrick if (const FileAction *action = info.GetFileActionForFD(STDERR_FILENO))
128061da546Spatrick LLDB_LOG(log, "setting STDERR to '{0}'", action->GetFileSpec());
129061da546Spatrick else
130061da546Spatrick LLDB_LOG(log, "leaving STDERR as is");
131061da546Spatrick
132061da546Spatrick int i = 0;
133061da546Spatrick for (const char **args = info.GetArguments().GetConstArgumentVector(); *args;
134061da546Spatrick ++args, ++i)
135061da546Spatrick LLDB_LOG(log, "arg {0}: '{1}'", i, *args);
136061da546Spatrick }
137061da546Spatrick
DisplayBytes(StreamString & s,void * bytes,uint32_t count)138*f6aab3d8Srobert static void DisplayBytes(StreamString &s, void *bytes, uint32_t count) {
139061da546Spatrick uint8_t *ptr = (uint8_t *)bytes;
140061da546Spatrick const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
141061da546Spatrick for (uint32_t i = 0; i < loop_count; i++) {
142061da546Spatrick s.Printf("[%x]", *ptr);
143061da546Spatrick ptr++;
144061da546Spatrick }
145061da546Spatrick }
146061da546Spatrick
PtraceDisplayBytes(int & req,void * data,size_t data_size)147*f6aab3d8Srobert static void PtraceDisplayBytes(int &req, void *data, size_t data_size) {
148*f6aab3d8Srobert Log *log = GetLog(POSIXLog::Ptrace);
149061da546Spatrick if (!log)
150061da546Spatrick return;
151061da546Spatrick StreamString buf;
152061da546Spatrick
153061da546Spatrick switch (req) {
154061da546Spatrick case PTRACE_POKETEXT: {
155061da546Spatrick DisplayBytes(buf, &data, 8);
156061da546Spatrick LLDB_LOGV(log, "PTRACE_POKETEXT {0}", buf.GetData());
157061da546Spatrick break;
158061da546Spatrick }
159061da546Spatrick case PTRACE_POKEDATA: {
160061da546Spatrick DisplayBytes(buf, &data, 8);
161061da546Spatrick LLDB_LOGV(log, "PTRACE_POKEDATA {0}", buf.GetData());
162061da546Spatrick break;
163061da546Spatrick }
164061da546Spatrick case PTRACE_POKEUSER: {
165061da546Spatrick DisplayBytes(buf, &data, 8);
166061da546Spatrick LLDB_LOGV(log, "PTRACE_POKEUSER {0}", buf.GetData());
167061da546Spatrick break;
168061da546Spatrick }
169061da546Spatrick case PTRACE_SETREGS: {
170061da546Spatrick DisplayBytes(buf, data, data_size);
171061da546Spatrick LLDB_LOGV(log, "PTRACE_SETREGS {0}", buf.GetData());
172061da546Spatrick break;
173061da546Spatrick }
174061da546Spatrick case PTRACE_SETFPREGS: {
175061da546Spatrick DisplayBytes(buf, data, data_size);
176061da546Spatrick LLDB_LOGV(log, "PTRACE_SETFPREGS {0}", buf.GetData());
177061da546Spatrick break;
178061da546Spatrick }
179061da546Spatrick case PTRACE_SETSIGINFO: {
180061da546Spatrick DisplayBytes(buf, data, sizeof(siginfo_t));
181061da546Spatrick LLDB_LOGV(log, "PTRACE_SETSIGINFO {0}", buf.GetData());
182061da546Spatrick break;
183061da546Spatrick }
184061da546Spatrick case PTRACE_SETREGSET: {
185061da546Spatrick // Extract iov_base from data, which is a pointer to the struct iovec
186061da546Spatrick DisplayBytes(buf, *(void **)data, data_size);
187061da546Spatrick LLDB_LOGV(log, "PTRACE_SETREGSET {0}", buf.GetData());
188061da546Spatrick break;
189061da546Spatrick }
190061da546Spatrick default: {}
191061da546Spatrick }
192061da546Spatrick }
193061da546Spatrick
194061da546Spatrick static constexpr unsigned k_ptrace_word_size = sizeof(void *);
195061da546Spatrick static_assert(sizeof(long) >= k_ptrace_word_size,
196061da546Spatrick "Size of long must be larger than ptrace word size");
197061da546Spatrick
198061da546Spatrick // Simple helper function to ensure flags are enabled on the given file
199061da546Spatrick // descriptor.
EnsureFDFlags(int fd,int flags)200061da546Spatrick static Status EnsureFDFlags(int fd, int flags) {
201061da546Spatrick Status error;
202061da546Spatrick
203061da546Spatrick int status = fcntl(fd, F_GETFL);
204061da546Spatrick if (status == -1) {
205061da546Spatrick error.SetErrorToErrno();
206061da546Spatrick return error;
207061da546Spatrick }
208061da546Spatrick
209061da546Spatrick if (fcntl(fd, F_SETFL, status | flags) == -1) {
210061da546Spatrick error.SetErrorToErrno();
211061da546Spatrick return error;
212061da546Spatrick }
213061da546Spatrick
214061da546Spatrick return error;
215061da546Spatrick }
216061da546Spatrick
217061da546Spatrick // Public Static Methods
218061da546Spatrick
219061da546Spatrick llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
Launch(ProcessLaunchInfo & launch_info,NativeDelegate & native_delegate,MainLoop & mainloop) const220061da546Spatrick NativeProcessLinux::Factory::Launch(ProcessLaunchInfo &launch_info,
221061da546Spatrick NativeDelegate &native_delegate,
222061da546Spatrick MainLoop &mainloop) const {
223*f6aab3d8Srobert Log *log = GetLog(POSIXLog::Process);
224061da546Spatrick
225061da546Spatrick MaybeLogLaunchInfo(launch_info);
226061da546Spatrick
227061da546Spatrick Status status;
228061da546Spatrick ::pid_t pid = ProcessLauncherPosixFork()
229061da546Spatrick .LaunchProcess(launch_info, status)
230061da546Spatrick .GetProcessId();
231061da546Spatrick LLDB_LOG(log, "pid = {0:x}", pid);
232061da546Spatrick if (status.Fail()) {
233061da546Spatrick LLDB_LOG(log, "failed to launch process: {0}", status);
234061da546Spatrick return status.ToError();
235061da546Spatrick }
236061da546Spatrick
237061da546Spatrick // Wait for the child process to trap on its call to execve.
238*f6aab3d8Srobert int wstatus = 0;
239061da546Spatrick ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0);
240061da546Spatrick assert(wpid == pid);
241061da546Spatrick (void)wpid;
242061da546Spatrick if (!WIFSTOPPED(wstatus)) {
243061da546Spatrick LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}",
244061da546Spatrick WaitStatus::Decode(wstatus));
245061da546Spatrick return llvm::make_error<StringError>("Could not sync with inferior process",
246061da546Spatrick llvm::inconvertibleErrorCode());
247061da546Spatrick }
248061da546Spatrick LLDB_LOG(log, "inferior started, now in stopped state");
249061da546Spatrick
250061da546Spatrick status = SetDefaultPtraceOpts(pid);
251061da546Spatrick if (status.Fail()) {
252061da546Spatrick LLDB_LOG(log, "failed to set default ptrace options: {0}", status);
253061da546Spatrick return status.ToError();
254061da546Spatrick }
255061da546Spatrick
256*f6aab3d8Srobert llvm::Expected<ArchSpec> arch_or =
257*f6aab3d8Srobert NativeRegisterContextLinux::DetermineArchitecture(pid);
258*f6aab3d8Srobert if (!arch_or)
259*f6aab3d8Srobert return arch_or.takeError();
260*f6aab3d8Srobert
261061da546Spatrick return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
262dda28197Spatrick pid, launch_info.GetPTY().ReleasePrimaryFileDescriptor(), native_delegate,
263*f6aab3d8Srobert *arch_or, mainloop, {pid}));
264061da546Spatrick }
265061da546Spatrick
266061da546Spatrick llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
Attach(lldb::pid_t pid,NativeProcessProtocol::NativeDelegate & native_delegate,MainLoop & mainloop) const267061da546Spatrick NativeProcessLinux::Factory::Attach(
268061da546Spatrick lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
269061da546Spatrick MainLoop &mainloop) const {
270*f6aab3d8Srobert Log *log = GetLog(POSIXLog::Process);
271061da546Spatrick LLDB_LOG(log, "pid = {0:x}", pid);
272061da546Spatrick
273061da546Spatrick auto tids_or = NativeProcessLinux::Attach(pid);
274061da546Spatrick if (!tids_or)
275061da546Spatrick return tids_or.takeError();
276*f6aab3d8Srobert ArrayRef<::pid_t> tids = *tids_or;
277*f6aab3d8Srobert llvm::Expected<ArchSpec> arch_or =
278*f6aab3d8Srobert NativeRegisterContextLinux::DetermineArchitecture(tids[0]);
279*f6aab3d8Srobert if (!arch_or)
280*f6aab3d8Srobert return arch_or.takeError();
281061da546Spatrick
282061da546Spatrick return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
283*f6aab3d8Srobert pid, -1, native_delegate, *arch_or, mainloop, tids));
284061da546Spatrick }
285061da546Spatrick
286be691f3bSpatrick NativeProcessLinux::Extension
GetSupportedExtensions() const287be691f3bSpatrick NativeProcessLinux::Factory::GetSupportedExtensions() const {
288be691f3bSpatrick NativeProcessLinux::Extension supported =
289be691f3bSpatrick Extension::multiprocess | Extension::fork | Extension::vfork |
290*f6aab3d8Srobert Extension::pass_signals | Extension::auxv | Extension::libraries_svr4 |
291*f6aab3d8Srobert Extension::siginfo_read;
292be691f3bSpatrick
293be691f3bSpatrick #ifdef __aarch64__
294be691f3bSpatrick // At this point we do not have a process so read auxv directly.
295be691f3bSpatrick if ((getauxval(AT_HWCAP2) & HWCAP2_MTE))
296be691f3bSpatrick supported |= Extension::memory_tagging;
297be691f3bSpatrick #endif
298be691f3bSpatrick
299be691f3bSpatrick return supported;
300be691f3bSpatrick }
301be691f3bSpatrick
302061da546Spatrick // Public Instance Methods
303061da546Spatrick
NativeProcessLinux(::pid_t pid,int terminal_fd,NativeDelegate & delegate,const ArchSpec & arch,MainLoop & mainloop,llvm::ArrayRef<::pid_t> tids)304061da546Spatrick NativeProcessLinux::NativeProcessLinux(::pid_t pid, int terminal_fd,
305061da546Spatrick NativeDelegate &delegate,
306061da546Spatrick const ArchSpec &arch, MainLoop &mainloop,
307061da546Spatrick llvm::ArrayRef<::pid_t> tids)
308be691f3bSpatrick : NativeProcessELF(pid, terminal_fd, delegate), m_arch(arch),
309*f6aab3d8Srobert m_main_loop(mainloop), m_intel_pt_collector(*this) {
310061da546Spatrick if (m_terminal_fd != -1) {
311061da546Spatrick Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
312061da546Spatrick assert(status.Success());
313061da546Spatrick }
314061da546Spatrick
315061da546Spatrick Status status;
316061da546Spatrick m_sigchld_handle = mainloop.RegisterSignal(
317061da546Spatrick SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status);
318061da546Spatrick assert(m_sigchld_handle && status.Success());
319061da546Spatrick
320061da546Spatrick for (const auto &tid : tids) {
321be691f3bSpatrick NativeThreadLinux &thread = AddThread(tid, /*resume*/ false);
322061da546Spatrick ThreadWasCreated(thread);
323061da546Spatrick }
324061da546Spatrick
325061da546Spatrick // Let our process instance know the thread has stopped.
326061da546Spatrick SetCurrentThreadID(tids[0]);
327061da546Spatrick SetState(StateType::eStateStopped, false);
328061da546Spatrick
329061da546Spatrick // Proccess any signals we received before installing our handler
330061da546Spatrick SigchldHandler();
331061da546Spatrick }
332061da546Spatrick
Attach(::pid_t pid)333061da546Spatrick llvm::Expected<std::vector<::pid_t>> NativeProcessLinux::Attach(::pid_t pid) {
334*f6aab3d8Srobert Log *log = GetLog(POSIXLog::Process);
335061da546Spatrick
336061da546Spatrick Status status;
337061da546Spatrick // Use a map to keep track of the threads which we have attached/need to
338061da546Spatrick // attach.
339061da546Spatrick Host::TidMap tids_to_attach;
340061da546Spatrick while (Host::FindProcessThreads(pid, tids_to_attach)) {
341061da546Spatrick for (Host::TidMap::iterator it = tids_to_attach.begin();
342061da546Spatrick it != tids_to_attach.end();) {
343061da546Spatrick if (it->second == false) {
344061da546Spatrick lldb::tid_t tid = it->first;
345061da546Spatrick
346061da546Spatrick // Attach to the requested process.
347061da546Spatrick // An attach will cause the thread to stop with a SIGSTOP.
348061da546Spatrick if ((status = PtraceWrapper(PTRACE_ATTACH, tid)).Fail()) {
349061da546Spatrick // No such thread. The thread may have exited. More error handling
350061da546Spatrick // may be needed.
351061da546Spatrick if (status.GetError() == ESRCH) {
352061da546Spatrick it = tids_to_attach.erase(it);
353061da546Spatrick continue;
354061da546Spatrick }
355061da546Spatrick return status.ToError();
356061da546Spatrick }
357061da546Spatrick
358061da546Spatrick int wpid =
359061da546Spatrick llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, nullptr, __WALL);
360061da546Spatrick // Need to use __WALL otherwise we receive an error with errno=ECHLD At
361061da546Spatrick // this point we should have a thread stopped if waitpid succeeds.
362061da546Spatrick if (wpid < 0) {
363061da546Spatrick // No such thread. The thread may have exited. More error handling
364061da546Spatrick // may be needed.
365061da546Spatrick if (errno == ESRCH) {
366061da546Spatrick it = tids_to_attach.erase(it);
367061da546Spatrick continue;
368061da546Spatrick }
369061da546Spatrick return llvm::errorCodeToError(
370061da546Spatrick std::error_code(errno, std::generic_category()));
371061da546Spatrick }
372061da546Spatrick
373061da546Spatrick if ((status = SetDefaultPtraceOpts(tid)).Fail())
374061da546Spatrick return status.ToError();
375061da546Spatrick
376061da546Spatrick LLDB_LOG(log, "adding tid = {0}", tid);
377061da546Spatrick it->second = true;
378061da546Spatrick }
379061da546Spatrick
380061da546Spatrick // move the loop forward
381061da546Spatrick ++it;
382061da546Spatrick }
383061da546Spatrick }
384061da546Spatrick
385061da546Spatrick size_t tid_count = tids_to_attach.size();
386061da546Spatrick if (tid_count == 0)
387061da546Spatrick return llvm::make_error<StringError>("No such process",
388061da546Spatrick llvm::inconvertibleErrorCode());
389061da546Spatrick
390061da546Spatrick std::vector<::pid_t> tids;
391061da546Spatrick tids.reserve(tid_count);
392061da546Spatrick for (const auto &p : tids_to_attach)
393061da546Spatrick tids.push_back(p.first);
394061da546Spatrick return std::move(tids);
395061da546Spatrick }
396061da546Spatrick
SetDefaultPtraceOpts(lldb::pid_t pid)397061da546Spatrick Status NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid) {
398061da546Spatrick long ptrace_opts = 0;
399061da546Spatrick
400061da546Spatrick // Have the child raise an event on exit. This is used to keep the child in
401061da546Spatrick // limbo until it is destroyed.
402061da546Spatrick ptrace_opts |= PTRACE_O_TRACEEXIT;
403061da546Spatrick
404061da546Spatrick // Have the tracer trace threads which spawn in the inferior process.
405061da546Spatrick ptrace_opts |= PTRACE_O_TRACECLONE;
406061da546Spatrick
407061da546Spatrick // Have the tracer notify us before execve returns (needed to disable legacy
408061da546Spatrick // SIGTRAP generation)
409061da546Spatrick ptrace_opts |= PTRACE_O_TRACEEXEC;
410061da546Spatrick
411be691f3bSpatrick // Have the tracer trace forked children.
412be691f3bSpatrick ptrace_opts |= PTRACE_O_TRACEFORK;
413be691f3bSpatrick
414be691f3bSpatrick // Have the tracer trace vforks.
415be691f3bSpatrick ptrace_opts |= PTRACE_O_TRACEVFORK;
416be691f3bSpatrick
417be691f3bSpatrick // Have the tracer trace vfork-done in order to restore breakpoints after
418be691f3bSpatrick // the child finishes sharing memory.
419be691f3bSpatrick ptrace_opts |= PTRACE_O_TRACEVFORKDONE;
420be691f3bSpatrick
421061da546Spatrick return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void *)ptrace_opts);
422061da546Spatrick }
423061da546Spatrick
424061da546Spatrick // Handles all waitpid events from the inferior process.
MonitorCallback(NativeThreadLinux & thread,WaitStatus status)425*f6aab3d8Srobert void NativeProcessLinux::MonitorCallback(NativeThreadLinux &thread,
426061da546Spatrick WaitStatus status) {
427*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
428061da546Spatrick
429061da546Spatrick // Certain activities differ based on whether the pid is the tid of the main
430061da546Spatrick // thread.
431*f6aab3d8Srobert const bool is_main_thread = (thread.GetID() == GetID());
432061da546Spatrick
433061da546Spatrick // Handle when the thread exits.
434*f6aab3d8Srobert if (status.type == WaitStatus::Exit || status.type == WaitStatus::Signal) {
435061da546Spatrick LLDB_LOG(log,
436061da546Spatrick "got exit status({0}) , tid = {1} ({2} main thread), process "
437061da546Spatrick "state = {3}",
438*f6aab3d8Srobert status, thread.GetID(), is_main_thread ? "is" : "is not",
439*f6aab3d8Srobert GetState());
440061da546Spatrick
441061da546Spatrick // This is a thread that exited. Ensure we're not tracking it anymore.
442*f6aab3d8Srobert StopTrackingThread(thread);
443061da546Spatrick
444*f6aab3d8Srobert assert(!is_main_thread && "Main thread exits handled elsewhere");
445061da546Spatrick return;
446061da546Spatrick }
447061da546Spatrick
448061da546Spatrick siginfo_t info;
449*f6aab3d8Srobert const auto info_err = GetSignalInfo(thread.GetID(), &info);
450061da546Spatrick
451061da546Spatrick // Get details on the signal raised.
452061da546Spatrick if (info_err.Success()) {
453061da546Spatrick // We have retrieved the signal info. Dispatch appropriately.
454061da546Spatrick if (info.si_signo == SIGTRAP)
455*f6aab3d8Srobert MonitorSIGTRAP(info, thread);
456061da546Spatrick else
457*f6aab3d8Srobert MonitorSignal(info, thread);
458061da546Spatrick } else {
459061da546Spatrick if (info_err.GetError() == EINVAL) {
460061da546Spatrick // This is a group stop reception for this tid. We can reach here if we
461061da546Spatrick // reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the tracee,
462061da546Spatrick // triggering the group-stop mechanism. Normally receiving these would
463061da546Spatrick // stop the process, pending a SIGCONT. Simulating this state in a
464061da546Spatrick // debugger is hard and is generally not needed (one use case is
465061da546Spatrick // debugging background task being managed by a shell). For general use,
466061da546Spatrick // it is sufficient to stop the process in a signal-delivery stop which
467061da546Spatrick // happens before the group stop. This done by MonitorSignal and works
468061da546Spatrick // correctly for all signals.
469061da546Spatrick LLDB_LOG(log,
470061da546Spatrick "received a group stop for pid {0} tid {1}. Transparent "
471061da546Spatrick "handling of group stops not supported, resuming the "
472061da546Spatrick "thread.",
473*f6aab3d8Srobert GetID(), thread.GetID());
474*f6aab3d8Srobert ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
475061da546Spatrick } else {
476061da546Spatrick // ptrace(GETSIGINFO) failed (but not due to group-stop).
477061da546Spatrick
478*f6aab3d8Srobert // A return value of ESRCH means the thread/process has died in the mean
479*f6aab3d8Srobert // time. This can (e.g.) happen when another thread does an exit_group(2)
480*f6aab3d8Srobert // or the entire process get SIGKILLed.
481*f6aab3d8Srobert // We can't do anything with this thread anymore, but we keep it around
482*f6aab3d8Srobert // until we get the WIFEXITED event.
483061da546Spatrick
484061da546Spatrick LLDB_LOG(log,
485*f6aab3d8Srobert "GetSignalInfo({0}) failed: {1}, status = {2}, main_thread = "
486*f6aab3d8Srobert "{3}. Expecting WIFEXITED soon.",
487*f6aab3d8Srobert thread.GetID(), info_err, status, is_main_thread);
488061da546Spatrick }
489061da546Spatrick }
490061da546Spatrick }
491061da546Spatrick
WaitForCloneNotification(::pid_t pid)492be691f3bSpatrick void NativeProcessLinux::WaitForCloneNotification(::pid_t pid) {
493*f6aab3d8Srobert Log *log = GetLog(POSIXLog::Process);
494061da546Spatrick
495be691f3bSpatrick // The PID is not tracked yet, let's wait for it to appear.
496061da546Spatrick int status = -1;
497061da546Spatrick LLDB_LOG(log,
498be691f3bSpatrick "received clone event for pid {0}. pid not tracked yet, "
499be691f3bSpatrick "waiting for it to appear...",
500be691f3bSpatrick pid);
501be691f3bSpatrick ::pid_t wait_pid =
502be691f3bSpatrick llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &status, __WALL);
503061da546Spatrick
504*f6aab3d8Srobert // It's theoretically possible to get other events if the entire process was
505*f6aab3d8Srobert // SIGKILLed before we got a chance to check this. In that case, we'll just
506*f6aab3d8Srobert // clean everything up when we get the process exit event.
507*f6aab3d8Srobert
508*f6aab3d8Srobert LLDB_LOG(log,
509*f6aab3d8Srobert "waitpid({0}, &status, __WALL) => {1} (errno: {2}, status = {3})",
510*f6aab3d8Srobert pid, wait_pid, errno, WaitStatus::Decode(status));
511061da546Spatrick }
512061da546Spatrick
MonitorSIGTRAP(const siginfo_t & info,NativeThreadLinux & thread)513061da546Spatrick void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info,
514061da546Spatrick NativeThreadLinux &thread) {
515*f6aab3d8Srobert Log *log = GetLog(POSIXLog::Process);
516061da546Spatrick const bool is_main_thread = (thread.GetID() == GetID());
517061da546Spatrick
518061da546Spatrick assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
519061da546Spatrick
520061da546Spatrick switch (info.si_code) {
521be691f3bSpatrick case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
522be691f3bSpatrick case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
523061da546Spatrick case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): {
524be691f3bSpatrick // This can either mean a new thread or a new process spawned via
525be691f3bSpatrick // clone(2) without SIGCHLD or CLONE_VFORK flag. Note that clone(2)
526be691f3bSpatrick // can also cause PTRACE_EVENT_FORK and PTRACE_EVENT_VFORK if one
527be691f3bSpatrick // of these flags are passed.
528061da546Spatrick
529061da546Spatrick unsigned long event_message = 0;
530061da546Spatrick if (GetEventMessage(thread.GetID(), &event_message).Fail()) {
531061da546Spatrick LLDB_LOG(log,
532be691f3bSpatrick "pid {0} received clone() event but GetEventMessage failed "
533be691f3bSpatrick "so we don't know the new pid/tid",
534061da546Spatrick thread.GetID());
535061da546Spatrick ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
536be691f3bSpatrick } else {
537*f6aab3d8Srobert MonitorClone(thread, event_message, info.si_code >> 8);
538be691f3bSpatrick }
539be691f3bSpatrick
540061da546Spatrick break;
541061da546Spatrick }
542061da546Spatrick
543061da546Spatrick case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): {
544061da546Spatrick LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP);
545061da546Spatrick
546061da546Spatrick // Exec clears any pending notifications.
547061da546Spatrick m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
548061da546Spatrick
549061da546Spatrick // Remove all but the main thread here. Linux fork creates a new process
550061da546Spatrick // which only copies the main thread.
551061da546Spatrick LLDB_LOG(log, "exec received, stop tracking all but main thread");
552061da546Spatrick
553061da546Spatrick llvm::erase_if(m_threads, [&](std::unique_ptr<NativeThreadProtocol> &t) {
554061da546Spatrick return t->GetID() != GetID();
555061da546Spatrick });
556061da546Spatrick assert(m_threads.size() == 1);
557061da546Spatrick auto *main_thread = static_cast<NativeThreadLinux *>(m_threads[0].get());
558061da546Spatrick
559061da546Spatrick SetCurrentThreadID(main_thread->GetID());
560061da546Spatrick main_thread->SetStoppedByExec();
561061da546Spatrick
562061da546Spatrick // Tell coordinator about about the "new" (since exec) stopped main thread.
563061da546Spatrick ThreadWasCreated(*main_thread);
564061da546Spatrick
565061da546Spatrick // Let our delegate know we have just exec'd.
566061da546Spatrick NotifyDidExec();
567061da546Spatrick
568061da546Spatrick // Let the process know we're stopped.
569061da546Spatrick StopRunningThreads(main_thread->GetID());
570061da546Spatrick
571061da546Spatrick break;
572061da546Spatrick }
573061da546Spatrick
574061da546Spatrick case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): {
575061da546Spatrick // The inferior process or one of its threads is about to exit. We don't
576061da546Spatrick // want to do anything with the thread so we just resume it. In case we
577061da546Spatrick // want to implement "break on thread exit" functionality, we would need to
578061da546Spatrick // stop here.
579061da546Spatrick
580061da546Spatrick unsigned long data = 0;
581061da546Spatrick if (GetEventMessage(thread.GetID(), &data).Fail())
582061da546Spatrick data = -1;
583061da546Spatrick
584061da546Spatrick LLDB_LOG(log,
585061da546Spatrick "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
586061da546Spatrick "WIFSIGNALED={2}, pid = {3}, main_thread = {4}",
587061da546Spatrick data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(),
588061da546Spatrick is_main_thread);
589061da546Spatrick
590061da546Spatrick
591061da546Spatrick StateType state = thread.GetState();
592061da546Spatrick if (!StateIsRunningState(state)) {
593061da546Spatrick // Due to a kernel bug, we may sometimes get this stop after the inferior
594061da546Spatrick // gets a SIGKILL. This confuses our state tracking logic in
595061da546Spatrick // ResumeThread(), since normally, we should not be receiving any ptrace
596061da546Spatrick // events while the inferior is stopped. This makes sure that the
597061da546Spatrick // inferior is resumed and exits normally.
598061da546Spatrick state = eStateRunning;
599061da546Spatrick }
600061da546Spatrick ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
601061da546Spatrick
602*f6aab3d8Srobert if (is_main_thread) {
603*f6aab3d8Srobert // Main thread report the read (WIFEXITED) event only after all threads in
604*f6aab3d8Srobert // the process exit, so we need to stop tracking it here instead of in
605*f6aab3d8Srobert // MonitorCallback
606*f6aab3d8Srobert StopTrackingThread(thread);
607*f6aab3d8Srobert }
608*f6aab3d8Srobert
609061da546Spatrick break;
610061da546Spatrick }
611061da546Spatrick
612be691f3bSpatrick case (SIGTRAP | (PTRACE_EVENT_VFORK_DONE << 8)): {
613be691f3bSpatrick if (bool(m_enabled_extensions & Extension::vfork)) {
614be691f3bSpatrick thread.SetStoppedByVForkDone();
615be691f3bSpatrick StopRunningThreads(thread.GetID());
616be691f3bSpatrick }
617be691f3bSpatrick else
618be691f3bSpatrick ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
619be691f3bSpatrick break;
620be691f3bSpatrick }
621be691f3bSpatrick
622061da546Spatrick case 0:
623061da546Spatrick case TRAP_TRACE: // We receive this on single stepping.
624061da546Spatrick case TRAP_HWBKPT: // We receive this on watchpoint hit
625061da546Spatrick {
626061da546Spatrick // If a watchpoint was hit, report it
627061da546Spatrick uint32_t wp_index;
628061da546Spatrick Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
629061da546Spatrick wp_index, (uintptr_t)info.si_addr);
630061da546Spatrick if (error.Fail())
631061da546Spatrick LLDB_LOG(log,
632061da546Spatrick "received error while checking for watchpoint hits, pid = "
633061da546Spatrick "{0}, error = {1}",
634061da546Spatrick thread.GetID(), error);
635061da546Spatrick if (wp_index != LLDB_INVALID_INDEX32) {
636061da546Spatrick MonitorWatchpoint(thread, wp_index);
637061da546Spatrick break;
638061da546Spatrick }
639061da546Spatrick
640061da546Spatrick // If a breakpoint was hit, report it
641061da546Spatrick uint32_t bp_index;
642061da546Spatrick error = thread.GetRegisterContext().GetHardwareBreakHitIndex(
643061da546Spatrick bp_index, (uintptr_t)info.si_addr);
644061da546Spatrick if (error.Fail())
645061da546Spatrick LLDB_LOG(log, "received error while checking for hardware "
646061da546Spatrick "breakpoint hits, pid = {0}, error = {1}",
647061da546Spatrick thread.GetID(), error);
648061da546Spatrick if (bp_index != LLDB_INVALID_INDEX32) {
649061da546Spatrick MonitorBreakpoint(thread);
650061da546Spatrick break;
651061da546Spatrick }
652061da546Spatrick
653061da546Spatrick // Otherwise, report step over
654061da546Spatrick MonitorTrace(thread);
655061da546Spatrick break;
656061da546Spatrick }
657061da546Spatrick
658061da546Spatrick case SI_KERNEL:
659061da546Spatrick #if defined __mips__
660061da546Spatrick // For mips there is no special signal for watchpoint So we check for
661061da546Spatrick // watchpoint in kernel trap
662061da546Spatrick {
663061da546Spatrick // If a watchpoint was hit, report it
664061da546Spatrick uint32_t wp_index;
665061da546Spatrick Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
666061da546Spatrick wp_index, LLDB_INVALID_ADDRESS);
667061da546Spatrick if (error.Fail())
668061da546Spatrick LLDB_LOG(log,
669061da546Spatrick "received error while checking for watchpoint hits, pid = "
670061da546Spatrick "{0}, error = {1}",
671061da546Spatrick thread.GetID(), error);
672061da546Spatrick if (wp_index != LLDB_INVALID_INDEX32) {
673061da546Spatrick MonitorWatchpoint(thread, wp_index);
674061da546Spatrick break;
675061da546Spatrick }
676061da546Spatrick }
677061da546Spatrick // NO BREAK
678061da546Spatrick #endif
679061da546Spatrick case TRAP_BRKPT:
680061da546Spatrick MonitorBreakpoint(thread);
681061da546Spatrick break;
682061da546Spatrick
683061da546Spatrick case SIGTRAP:
684061da546Spatrick case (SIGTRAP | 0x80):
685061da546Spatrick LLDB_LOG(
686061da546Spatrick log,
687061da546Spatrick "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",
688061da546Spatrick info.si_code, GetID(), thread.GetID());
689061da546Spatrick
690061da546Spatrick // Ignore these signals until we know more about them.
691061da546Spatrick ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
692061da546Spatrick break;
693061da546Spatrick
694061da546Spatrick default:
695061da546Spatrick LLDB_LOG(log, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}",
696061da546Spatrick info.si_code, GetID(), thread.GetID());
697*f6aab3d8Srobert MonitorSignal(info, thread);
698061da546Spatrick break;
699061da546Spatrick }
700061da546Spatrick }
701061da546Spatrick
MonitorTrace(NativeThreadLinux & thread)702061da546Spatrick void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) {
703*f6aab3d8Srobert Log *log = GetLog(POSIXLog::Process);
704061da546Spatrick LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID());
705061da546Spatrick
706061da546Spatrick // This thread is currently stopped.
707061da546Spatrick thread.SetStoppedByTrace();
708061da546Spatrick
709061da546Spatrick StopRunningThreads(thread.GetID());
710061da546Spatrick }
711061da546Spatrick
MonitorBreakpoint(NativeThreadLinux & thread)712061da546Spatrick void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) {
713*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process | LLDBLog::Breakpoints);
714061da546Spatrick LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID());
715061da546Spatrick
716061da546Spatrick // Mark the thread as stopped at breakpoint.
717061da546Spatrick thread.SetStoppedByBreakpoint();
718061da546Spatrick FixupBreakpointPCAsNeeded(thread);
719061da546Spatrick
720061da546Spatrick if (m_threads_stepping_with_breakpoint.find(thread.GetID()) !=
721061da546Spatrick m_threads_stepping_with_breakpoint.end())
722061da546Spatrick thread.SetStoppedByTrace();
723061da546Spatrick
724061da546Spatrick StopRunningThreads(thread.GetID());
725061da546Spatrick }
726061da546Spatrick
MonitorWatchpoint(NativeThreadLinux & thread,uint32_t wp_index)727061da546Spatrick void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread,
728061da546Spatrick uint32_t wp_index) {
729*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process | LLDBLog::Watchpoints);
730061da546Spatrick LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}",
731061da546Spatrick thread.GetID(), wp_index);
732061da546Spatrick
733061da546Spatrick // Mark the thread as stopped at watchpoint. The address is at
734061da546Spatrick // (lldb::addr_t)info->si_addr if we need it.
735061da546Spatrick thread.SetStoppedByWatchpoint(wp_index);
736061da546Spatrick
737061da546Spatrick // We need to tell all other running threads before we notify the delegate
738061da546Spatrick // about this stop.
739061da546Spatrick StopRunningThreads(thread.GetID());
740061da546Spatrick }
741061da546Spatrick
MonitorSignal(const siginfo_t & info,NativeThreadLinux & thread)742061da546Spatrick void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
743*f6aab3d8Srobert NativeThreadLinux &thread) {
744061da546Spatrick const int signo = info.si_signo;
745061da546Spatrick const bool is_from_llgs = info.si_pid == getpid();
746061da546Spatrick
747*f6aab3d8Srobert Log *log = GetLog(POSIXLog::Process);
748061da546Spatrick
749061da546Spatrick // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
750061da546Spatrick // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a kill(2)
751061da546Spatrick // or raise(3). Similarly for tgkill(2) on Linux.
752061da546Spatrick //
753061da546Spatrick // IOW, user generated signals never generate what we consider to be a
754061da546Spatrick // "crash".
755061da546Spatrick //
756061da546Spatrick // Similarly, ACK signals generated by this monitor.
757061da546Spatrick
758061da546Spatrick // Handle the signal.
759061da546Spatrick LLDB_LOG(log,
760061da546Spatrick "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
761061da546Spatrick "waitpid pid = {4})",
762061da546Spatrick Host::GetSignalAsCString(signo), signo, info.si_code,
763061da546Spatrick thread.GetID());
764061da546Spatrick
765061da546Spatrick // Check for thread stop notification.
766061da546Spatrick if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) {
767061da546Spatrick // This is a tgkill()-based stop.
768061da546Spatrick LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID());
769061da546Spatrick
770061da546Spatrick // Check that we're not already marked with a stop reason. Note this thread
771061da546Spatrick // really shouldn't already be marked as stopped - if we were, that would
772061da546Spatrick // imply that the kernel signaled us with the thread stopping which we
773061da546Spatrick // handled and marked as stopped, and that, without an intervening resume,
774061da546Spatrick // we received another stop. It is more likely that we are missing the
775061da546Spatrick // marking of a run state somewhere if we find that the thread was marked
776061da546Spatrick // as stopped.
777061da546Spatrick const StateType thread_state = thread.GetState();
778061da546Spatrick if (!StateIsStoppedState(thread_state, false)) {
779061da546Spatrick // An inferior thread has stopped because of a SIGSTOP we have sent it.
780061da546Spatrick // Generally, these are not important stops and we don't want to report
781061da546Spatrick // them as they are just used to stop other threads when one thread (the
782061da546Spatrick // one with the *real* stop reason) hits a breakpoint (watchpoint,
783061da546Spatrick // etc...). However, in the case of an asynchronous Interrupt(), this
784061da546Spatrick // *is* the real stop reason, so we leave the signal intact if this is
785061da546Spatrick // the thread that was chosen as the triggering thread.
786061da546Spatrick if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
787061da546Spatrick if (m_pending_notification_tid == thread.GetID())
788061da546Spatrick thread.SetStoppedBySignal(SIGSTOP, &info);
789061da546Spatrick else
790061da546Spatrick thread.SetStoppedWithNoReason();
791061da546Spatrick
792061da546Spatrick SetCurrentThreadID(thread.GetID());
793061da546Spatrick SignalIfAllThreadsStopped();
794061da546Spatrick } else {
795061da546Spatrick // We can end up here if stop was initiated by LLGS but by this time a
796061da546Spatrick // thread stop has occurred - maybe initiated by another event.
797061da546Spatrick Status error = ResumeThread(thread, thread.GetState(), 0);
798061da546Spatrick if (error.Fail())
799061da546Spatrick LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(),
800061da546Spatrick error);
801061da546Spatrick }
802061da546Spatrick } else {
803061da546Spatrick LLDB_LOG(log,
804061da546Spatrick "pid {0} tid {1}, thread was already marked as a stopped "
805061da546Spatrick "state (state={2}), leaving stop signal as is",
806061da546Spatrick GetID(), thread.GetID(), thread_state);
807061da546Spatrick SignalIfAllThreadsStopped();
808061da546Spatrick }
809061da546Spatrick
810061da546Spatrick // Done handling.
811061da546Spatrick return;
812061da546Spatrick }
813061da546Spatrick
814061da546Spatrick // Check if debugger should stop at this signal or just ignore it and resume
815061da546Spatrick // the inferior.
816*f6aab3d8Srobert if (m_signals_to_ignore.contains(signo)) {
817061da546Spatrick ResumeThread(thread, thread.GetState(), signo);
818061da546Spatrick return;
819061da546Spatrick }
820061da546Spatrick
821061da546Spatrick // This thread is stopped.
822061da546Spatrick LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo));
823061da546Spatrick thread.SetStoppedBySignal(signo, &info);
824061da546Spatrick
825061da546Spatrick // Send a stop to the debugger after we get all other threads to stop.
826061da546Spatrick StopRunningThreads(thread.GetID());
827061da546Spatrick }
828061da546Spatrick
MonitorClone(NativeThreadLinux & parent,lldb::pid_t child_pid,int event)829*f6aab3d8Srobert bool NativeProcessLinux::MonitorClone(NativeThreadLinux &parent,
830*f6aab3d8Srobert lldb::pid_t child_pid, int event) {
831*f6aab3d8Srobert Log *log = GetLog(POSIXLog::Process);
832*f6aab3d8Srobert LLDB_LOG(log, "parent_tid={0}, child_pid={1}, event={2}", parent.GetID(),
833*f6aab3d8Srobert child_pid, event);
834061da546Spatrick
835*f6aab3d8Srobert WaitForCloneNotification(child_pid);
836061da546Spatrick
837*f6aab3d8Srobert switch (event) {
838be691f3bSpatrick case PTRACE_EVENT_CLONE: {
839be691f3bSpatrick // PTRACE_EVENT_CLONE can either mean a new thread or a new process.
840be691f3bSpatrick // Try to grab the new process' PGID to figure out which one it is.
841be691f3bSpatrick // If PGID is the same as the PID, then it's a new process. Otherwise,
842be691f3bSpatrick // it's a thread.
843be691f3bSpatrick auto tgid_ret = getPIDForTID(child_pid);
844be691f3bSpatrick if (tgid_ret != child_pid) {
845be691f3bSpatrick // A new thread should have PGID matching our process' PID.
846*f6aab3d8Srobert assert(!tgid_ret || *tgid_ret == GetID());
847be691f3bSpatrick
848be691f3bSpatrick NativeThreadLinux &child_thread = AddThread(child_pid, /*resume*/ true);
849be691f3bSpatrick ThreadWasCreated(child_thread);
850be691f3bSpatrick
851be691f3bSpatrick // Resume the parent.
852*f6aab3d8Srobert ResumeThread(parent, parent.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
853be691f3bSpatrick break;
854be691f3bSpatrick }
855be691f3bSpatrick }
856*f6aab3d8Srobert [[fallthrough]];
857be691f3bSpatrick case PTRACE_EVENT_FORK:
858be691f3bSpatrick case PTRACE_EVENT_VFORK: {
859*f6aab3d8Srobert bool is_vfork = event == PTRACE_EVENT_VFORK;
860be691f3bSpatrick std::unique_ptr<NativeProcessLinux> child_process{new NativeProcessLinux(
861be691f3bSpatrick static_cast<::pid_t>(child_pid), m_terminal_fd, m_delegate, m_arch,
862be691f3bSpatrick m_main_loop, {static_cast<::pid_t>(child_pid)})};
863be691f3bSpatrick if (!is_vfork)
864be691f3bSpatrick child_process->m_software_breakpoints = m_software_breakpoints;
865be691f3bSpatrick
866be691f3bSpatrick Extension expected_ext = is_vfork ? Extension::vfork : Extension::fork;
867be691f3bSpatrick if (bool(m_enabled_extensions & expected_ext)) {
868be691f3bSpatrick m_delegate.NewSubprocess(this, std::move(child_process));
869be691f3bSpatrick // NB: non-vfork clone() is reported as fork
870*f6aab3d8Srobert parent.SetStoppedByFork(is_vfork, child_pid);
871*f6aab3d8Srobert StopRunningThreads(parent.GetID());
872be691f3bSpatrick } else {
873be691f3bSpatrick child_process->Detach();
874*f6aab3d8Srobert ResumeThread(parent, parent.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
875be691f3bSpatrick }
876be691f3bSpatrick break;
877be691f3bSpatrick }
878be691f3bSpatrick default:
879be691f3bSpatrick llvm_unreachable("unknown clone_info.event");
880be691f3bSpatrick }
881be691f3bSpatrick
882061da546Spatrick return true;
883061da546Spatrick }
884061da546Spatrick
SupportHardwareSingleStepping() const885061da546Spatrick bool NativeProcessLinux::SupportHardwareSingleStepping() const {
886*f6aab3d8Srobert if (m_arch.IsMIPS() || m_arch.GetMachine() == llvm::Triple::arm ||
887*f6aab3d8Srobert m_arch.GetTriple().isRISCV() || m_arch.GetTriple().isLoongArch())
888061da546Spatrick return false;
889061da546Spatrick return true;
890061da546Spatrick }
891061da546Spatrick
Resume(const ResumeActionList & resume_actions)892061da546Spatrick Status NativeProcessLinux::Resume(const ResumeActionList &resume_actions) {
893*f6aab3d8Srobert Log *log = GetLog(POSIXLog::Process);
894061da546Spatrick LLDB_LOG(log, "pid {0}", GetID());
895061da546Spatrick
896*f6aab3d8Srobert NotifyTracersProcessWillResume();
897*f6aab3d8Srobert
898061da546Spatrick bool software_single_step = !SupportHardwareSingleStepping();
899061da546Spatrick
900061da546Spatrick if (software_single_step) {
901061da546Spatrick for (const auto &thread : m_threads) {
902061da546Spatrick assert(thread && "thread list should not contain NULL threads");
903061da546Spatrick
904061da546Spatrick const ResumeAction *const action =
905061da546Spatrick resume_actions.GetActionForThread(thread->GetID(), true);
906061da546Spatrick if (action == nullptr)
907061da546Spatrick continue;
908061da546Spatrick
909061da546Spatrick if (action->state == eStateStepping) {
910061da546Spatrick Status error = SetupSoftwareSingleStepping(
911061da546Spatrick static_cast<NativeThreadLinux &>(*thread));
912061da546Spatrick if (error.Fail())
913061da546Spatrick return error;
914061da546Spatrick }
915061da546Spatrick }
916061da546Spatrick }
917061da546Spatrick
918061da546Spatrick for (const auto &thread : m_threads) {
919061da546Spatrick assert(thread && "thread list should not contain NULL threads");
920061da546Spatrick
921061da546Spatrick const ResumeAction *const action =
922061da546Spatrick resume_actions.GetActionForThread(thread->GetID(), true);
923061da546Spatrick
924061da546Spatrick if (action == nullptr) {
925061da546Spatrick LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
926061da546Spatrick thread->GetID());
927061da546Spatrick continue;
928061da546Spatrick }
929061da546Spatrick
930061da546Spatrick LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}",
931061da546Spatrick action->state, GetID(), thread->GetID());
932061da546Spatrick
933061da546Spatrick switch (action->state) {
934061da546Spatrick case eStateRunning:
935061da546Spatrick case eStateStepping: {
936061da546Spatrick // Run the thread, possibly feeding it the signal.
937061da546Spatrick const int signo = action->signal;
938*f6aab3d8Srobert Status error = ResumeThread(static_cast<NativeThreadLinux &>(*thread),
939*f6aab3d8Srobert action->state, signo);
940*f6aab3d8Srobert if (error.Fail())
941*f6aab3d8Srobert return Status("NativeProcessLinux::%s: failed to resume thread "
942*f6aab3d8Srobert "for pid %" PRIu64 ", tid %" PRIu64 ", error = %s",
943*f6aab3d8Srobert __FUNCTION__, GetID(), thread->GetID(),
944*f6aab3d8Srobert error.AsCString());
945*f6aab3d8Srobert
946061da546Spatrick break;
947061da546Spatrick }
948061da546Spatrick
949061da546Spatrick case eStateSuspended:
950061da546Spatrick case eStateStopped:
951*f6aab3d8Srobert break;
952061da546Spatrick
953061da546Spatrick default:
954061da546Spatrick return Status("NativeProcessLinux::%s (): unexpected state %s specified "
955061da546Spatrick "for pid %" PRIu64 ", tid %" PRIu64,
956061da546Spatrick __FUNCTION__, StateAsCString(action->state), GetID(),
957061da546Spatrick thread->GetID());
958061da546Spatrick }
959061da546Spatrick }
960061da546Spatrick
961061da546Spatrick return Status();
962061da546Spatrick }
963061da546Spatrick
Halt()964061da546Spatrick Status NativeProcessLinux::Halt() {
965061da546Spatrick Status error;
966061da546Spatrick
967061da546Spatrick if (kill(GetID(), SIGSTOP) != 0)
968061da546Spatrick error.SetErrorToErrno();
969061da546Spatrick
970061da546Spatrick return error;
971061da546Spatrick }
972061da546Spatrick
Detach()973061da546Spatrick Status NativeProcessLinux::Detach() {
974061da546Spatrick Status error;
975061da546Spatrick
976061da546Spatrick // Stop monitoring the inferior.
977061da546Spatrick m_sigchld_handle.reset();
978061da546Spatrick
979061da546Spatrick // Tell ptrace to detach from the process.
980061da546Spatrick if (GetID() == LLDB_INVALID_PROCESS_ID)
981061da546Spatrick return error;
982061da546Spatrick
983061da546Spatrick for (const auto &thread : m_threads) {
984061da546Spatrick Status e = Detach(thread->GetID());
985061da546Spatrick if (e.Fail())
986061da546Spatrick error =
987061da546Spatrick e; // Save the error, but still attempt to detach from other threads.
988061da546Spatrick }
989061da546Spatrick
990*f6aab3d8Srobert m_intel_pt_collector.Clear();
991061da546Spatrick
992061da546Spatrick return error;
993061da546Spatrick }
994061da546Spatrick
Signal(int signo)995061da546Spatrick Status NativeProcessLinux::Signal(int signo) {
996061da546Spatrick Status error;
997061da546Spatrick
998*f6aab3d8Srobert Log *log = GetLog(POSIXLog::Process);
999061da546Spatrick LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo,
1000061da546Spatrick Host::GetSignalAsCString(signo), GetID());
1001061da546Spatrick
1002061da546Spatrick if (kill(GetID(), signo))
1003061da546Spatrick error.SetErrorToErrno();
1004061da546Spatrick
1005061da546Spatrick return error;
1006061da546Spatrick }
1007061da546Spatrick
Interrupt()1008061da546Spatrick Status NativeProcessLinux::Interrupt() {
1009061da546Spatrick // Pick a running thread (or if none, a not-dead stopped thread) as the
1010061da546Spatrick // chosen thread that will be the stop-reason thread.
1011*f6aab3d8Srobert Log *log = GetLog(POSIXLog::Process);
1012061da546Spatrick
1013061da546Spatrick NativeThreadProtocol *running_thread = nullptr;
1014061da546Spatrick NativeThreadProtocol *stopped_thread = nullptr;
1015061da546Spatrick
1016061da546Spatrick LLDB_LOG(log, "selecting running thread for interrupt target");
1017061da546Spatrick for (const auto &thread : m_threads) {
1018061da546Spatrick // If we have a running or stepping thread, we'll call that the target of
1019061da546Spatrick // the interrupt.
1020061da546Spatrick const auto thread_state = thread->GetState();
1021061da546Spatrick if (thread_state == eStateRunning || thread_state == eStateStepping) {
1022061da546Spatrick running_thread = thread.get();
1023061da546Spatrick break;
1024061da546Spatrick } else if (!stopped_thread && StateIsStoppedState(thread_state, true)) {
1025061da546Spatrick // Remember the first non-dead stopped thread. We'll use that as a
1026061da546Spatrick // backup if there are no running threads.
1027061da546Spatrick stopped_thread = thread.get();
1028061da546Spatrick }
1029061da546Spatrick }
1030061da546Spatrick
1031061da546Spatrick if (!running_thread && !stopped_thread) {
1032061da546Spatrick Status error("found no running/stepping or live stopped threads as target "
1033061da546Spatrick "for interrupt");
1034061da546Spatrick LLDB_LOG(log, "skipping due to error: {0}", error);
1035061da546Spatrick
1036061da546Spatrick return error;
1037061da546Spatrick }
1038061da546Spatrick
1039061da546Spatrick NativeThreadProtocol *deferred_signal_thread =
1040061da546Spatrick running_thread ? running_thread : stopped_thread;
1041061da546Spatrick
1042061da546Spatrick LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(),
1043061da546Spatrick running_thread ? "running" : "stopped",
1044061da546Spatrick deferred_signal_thread->GetID());
1045061da546Spatrick
1046061da546Spatrick StopRunningThreads(deferred_signal_thread->GetID());
1047061da546Spatrick
1048061da546Spatrick return Status();
1049061da546Spatrick }
1050061da546Spatrick
Kill()1051061da546Spatrick Status NativeProcessLinux::Kill() {
1052*f6aab3d8Srobert Log *log = GetLog(POSIXLog::Process);
1053061da546Spatrick LLDB_LOG(log, "pid {0}", GetID());
1054061da546Spatrick
1055061da546Spatrick Status error;
1056061da546Spatrick
1057061da546Spatrick switch (m_state) {
1058061da546Spatrick case StateType::eStateInvalid:
1059061da546Spatrick case StateType::eStateExited:
1060061da546Spatrick case StateType::eStateCrashed:
1061061da546Spatrick case StateType::eStateDetached:
1062061da546Spatrick case StateType::eStateUnloaded:
1063061da546Spatrick // Nothing to do - the process is already dead.
1064061da546Spatrick LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
1065061da546Spatrick m_state);
1066061da546Spatrick return error;
1067061da546Spatrick
1068061da546Spatrick case StateType::eStateConnected:
1069061da546Spatrick case StateType::eStateAttaching:
1070061da546Spatrick case StateType::eStateLaunching:
1071061da546Spatrick case StateType::eStateStopped:
1072061da546Spatrick case StateType::eStateRunning:
1073061da546Spatrick case StateType::eStateStepping:
1074061da546Spatrick case StateType::eStateSuspended:
1075061da546Spatrick // We can try to kill a process in these states.
1076061da546Spatrick break;
1077061da546Spatrick }
1078061da546Spatrick
1079061da546Spatrick if (kill(GetID(), SIGKILL) != 0) {
1080061da546Spatrick error.SetErrorToErrno();
1081061da546Spatrick return error;
1082061da546Spatrick }
1083061da546Spatrick
1084061da546Spatrick return error;
1085061da546Spatrick }
1086061da546Spatrick
GetMemoryRegionInfo(lldb::addr_t load_addr,MemoryRegionInfo & range_info)1087061da546Spatrick Status NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr,
1088061da546Spatrick MemoryRegionInfo &range_info) {
1089061da546Spatrick // FIXME review that the final memory region returned extends to the end of
1090061da546Spatrick // the virtual address space,
1091061da546Spatrick // with no perms if it is not mapped.
1092061da546Spatrick
1093061da546Spatrick // Use an approach that reads memory regions from /proc/{pid}/maps. Assume
1094061da546Spatrick // proc maps entries are in ascending order.
1095061da546Spatrick // FIXME assert if we find differently.
1096061da546Spatrick
1097061da546Spatrick if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
1098061da546Spatrick // We're done.
1099061da546Spatrick return Status("unsupported");
1100061da546Spatrick }
1101061da546Spatrick
1102061da546Spatrick Status error = PopulateMemoryRegionCache();
1103061da546Spatrick if (error.Fail()) {
1104061da546Spatrick return error;
1105061da546Spatrick }
1106061da546Spatrick
1107061da546Spatrick lldb::addr_t prev_base_address = 0;
1108061da546Spatrick
1109061da546Spatrick // FIXME start by finding the last region that is <= target address using
1110061da546Spatrick // binary search. Data is sorted.
1111061da546Spatrick // There can be a ton of regions on pthreads apps with lots of threads.
1112061da546Spatrick for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1113061da546Spatrick ++it) {
1114061da546Spatrick MemoryRegionInfo &proc_entry_info = it->first;
1115061da546Spatrick
1116061da546Spatrick // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1117061da546Spatrick assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
1118061da546Spatrick "descending /proc/pid/maps entries detected, unexpected");
1119061da546Spatrick prev_base_address = proc_entry_info.GetRange().GetRangeBase();
1120061da546Spatrick UNUSED_IF_ASSERT_DISABLED(prev_base_address);
1121061da546Spatrick
1122061da546Spatrick // If the target address comes before this entry, indicate distance to next
1123061da546Spatrick // region.
1124061da546Spatrick if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1125061da546Spatrick range_info.GetRange().SetRangeBase(load_addr);
1126061da546Spatrick range_info.GetRange().SetByteSize(
1127061da546Spatrick proc_entry_info.GetRange().GetRangeBase() - load_addr);
1128061da546Spatrick range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1129061da546Spatrick range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1130061da546Spatrick range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1131061da546Spatrick range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1132061da546Spatrick
1133061da546Spatrick return error;
1134061da546Spatrick } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1135061da546Spatrick // The target address is within the memory region we're processing here.
1136061da546Spatrick range_info = proc_entry_info;
1137061da546Spatrick return error;
1138061da546Spatrick }
1139061da546Spatrick
1140061da546Spatrick // The target memory address comes somewhere after the region we just
1141061da546Spatrick // parsed.
1142061da546Spatrick }
1143061da546Spatrick
1144061da546Spatrick // If we made it here, we didn't find an entry that contained the given
1145061da546Spatrick // address. Return the load_addr as start and the amount of bytes betwwen
1146061da546Spatrick // load address and the end of the memory as size.
1147061da546Spatrick range_info.GetRange().SetRangeBase(load_addr);
1148061da546Spatrick range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
1149061da546Spatrick range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1150061da546Spatrick range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1151061da546Spatrick range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1152061da546Spatrick range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1153061da546Spatrick return error;
1154061da546Spatrick }
1155061da546Spatrick
PopulateMemoryRegionCache()1156061da546Spatrick Status NativeProcessLinux::PopulateMemoryRegionCache() {
1157*f6aab3d8Srobert Log *log = GetLog(POSIXLog::Process);
1158061da546Spatrick
1159061da546Spatrick // If our cache is empty, pull the latest. There should always be at least
1160061da546Spatrick // one memory region if memory region handling is supported.
1161061da546Spatrick if (!m_mem_region_cache.empty()) {
1162061da546Spatrick LLDB_LOG(log, "reusing {0} cached memory region entries",
1163061da546Spatrick m_mem_region_cache.size());
1164061da546Spatrick return Status();
1165061da546Spatrick }
1166061da546Spatrick
1167be691f3bSpatrick Status Result;
1168be691f3bSpatrick LinuxMapCallback callback = [&](llvm::Expected<MemoryRegionInfo> Info) {
1169be691f3bSpatrick if (Info) {
1170be691f3bSpatrick FileSpec file_spec(Info->GetName().GetCString());
1171be691f3bSpatrick FileSystem::Instance().Resolve(file_spec);
1172be691f3bSpatrick m_mem_region_cache.emplace_back(*Info, file_spec);
1173be691f3bSpatrick return true;
1174be691f3bSpatrick }
1175be691f3bSpatrick
1176be691f3bSpatrick Result = Info.takeError();
1177be691f3bSpatrick m_supports_mem_region = LazyBool::eLazyBoolNo;
1178be691f3bSpatrick LLDB_LOG(log, "failed to parse proc maps: {0}", Result);
1179be691f3bSpatrick return false;
1180be691f3bSpatrick };
1181be691f3bSpatrick
1182be691f3bSpatrick // Linux kernel since 2.6.14 has /proc/{pid}/smaps
1183be691f3bSpatrick // if CONFIG_PROC_PAGE_MONITOR is enabled
1184*f6aab3d8Srobert auto BufferOrError = getProcFile(GetID(), GetCurrentThreadID(), "smaps");
1185be691f3bSpatrick if (BufferOrError)
1186be691f3bSpatrick ParseLinuxSMapRegions(BufferOrError.get()->getBuffer(), callback);
1187be691f3bSpatrick else {
1188*f6aab3d8Srobert BufferOrError = getProcFile(GetID(), GetCurrentThreadID(), "maps");
1189061da546Spatrick if (!BufferOrError) {
1190061da546Spatrick m_supports_mem_region = LazyBool::eLazyBoolNo;
1191061da546Spatrick return BufferOrError.getError();
1192061da546Spatrick }
1193be691f3bSpatrick
1194be691f3bSpatrick ParseLinuxMapRegions(BufferOrError.get()->getBuffer(), callback);
1195061da546Spatrick }
1196be691f3bSpatrick
1197061da546Spatrick if (Result.Fail())
1198061da546Spatrick return Result;
1199061da546Spatrick
1200061da546Spatrick if (m_mem_region_cache.empty()) {
1201061da546Spatrick // No entries after attempting to read them. This shouldn't happen if
1202061da546Spatrick // /proc/{pid}/maps is supported. Assume we don't support map entries via
1203061da546Spatrick // procfs.
1204061da546Spatrick m_supports_mem_region = LazyBool::eLazyBoolNo;
1205061da546Spatrick LLDB_LOG(log,
1206061da546Spatrick "failed to find any procfs maps entries, assuming no support "
1207061da546Spatrick "for memory region metadata retrieval");
1208061da546Spatrick return Status("not supported");
1209061da546Spatrick }
1210061da546Spatrick
1211061da546Spatrick LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps",
1212061da546Spatrick m_mem_region_cache.size(), GetID());
1213061da546Spatrick
1214061da546Spatrick // We support memory retrieval, remember that.
1215061da546Spatrick m_supports_mem_region = LazyBool::eLazyBoolYes;
1216061da546Spatrick return Status();
1217061da546Spatrick }
1218061da546Spatrick
DoStopIDBumped(uint32_t newBumpId)1219061da546Spatrick void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
1220*f6aab3d8Srobert Log *log = GetLog(POSIXLog::Process);
1221061da546Spatrick LLDB_LOG(log, "newBumpId={0}", newBumpId);
1222061da546Spatrick LLDB_LOG(log, "clearing {0} entries from memory region cache",
1223061da546Spatrick m_mem_region_cache.size());
1224061da546Spatrick m_mem_region_cache.clear();
1225061da546Spatrick }
1226061da546Spatrick
1227be691f3bSpatrick llvm::Expected<uint64_t>
Syscall(llvm::ArrayRef<uint64_t> args)1228be691f3bSpatrick NativeProcessLinux::Syscall(llvm::ArrayRef<uint64_t> args) {
1229be691f3bSpatrick PopulateMemoryRegionCache();
1230be691f3bSpatrick auto region_it = llvm::find_if(m_mem_region_cache, [](const auto &pair) {
1231*f6aab3d8Srobert return pair.first.GetExecutable() == MemoryRegionInfo::eYes &&
1232*f6aab3d8Srobert pair.first.GetShared() != MemoryRegionInfo::eYes;
1233be691f3bSpatrick });
1234be691f3bSpatrick if (region_it == m_mem_region_cache.end())
1235be691f3bSpatrick return llvm::createStringError(llvm::inconvertibleErrorCode(),
1236be691f3bSpatrick "No executable memory region found!");
1237061da546Spatrick
1238be691f3bSpatrick addr_t exe_addr = region_it->first.GetRange().GetRangeBase();
1239061da546Spatrick
1240*f6aab3d8Srobert NativeThreadLinux &thread = *GetCurrentThread();
1241be691f3bSpatrick assert(thread.GetState() == eStateStopped);
1242be691f3bSpatrick NativeRegisterContextLinux ®_ctx = thread.GetRegisterContext();
1243be691f3bSpatrick
1244be691f3bSpatrick NativeRegisterContextLinux::SyscallData syscall_data =
1245be691f3bSpatrick *reg_ctx.GetSyscallData();
1246be691f3bSpatrick
1247*f6aab3d8Srobert WritableDataBufferSP registers_sp;
1248be691f3bSpatrick if (llvm::Error Err = reg_ctx.ReadAllRegisterValues(registers_sp).ToError())
1249be691f3bSpatrick return std::move(Err);
1250be691f3bSpatrick auto restore_regs = llvm::make_scope_exit(
1251be691f3bSpatrick [&] { reg_ctx.WriteAllRegisterValues(registers_sp); });
1252be691f3bSpatrick
1253be691f3bSpatrick llvm::SmallVector<uint8_t, 8> memory(syscall_data.Insn.size());
1254be691f3bSpatrick size_t bytes_read;
1255be691f3bSpatrick if (llvm::Error Err =
1256be691f3bSpatrick ReadMemory(exe_addr, memory.data(), memory.size(), bytes_read)
1257be691f3bSpatrick .ToError()) {
1258be691f3bSpatrick return std::move(Err);
1259be691f3bSpatrick }
1260be691f3bSpatrick
1261be691f3bSpatrick auto restore_mem = llvm::make_scope_exit(
1262be691f3bSpatrick [&] { WriteMemory(exe_addr, memory.data(), memory.size(), bytes_read); });
1263be691f3bSpatrick
1264be691f3bSpatrick if (llvm::Error Err = reg_ctx.SetPC(exe_addr).ToError())
1265be691f3bSpatrick return std::move(Err);
1266be691f3bSpatrick
1267be691f3bSpatrick for (const auto &zip : llvm::zip_first(args, syscall_data.Args)) {
1268be691f3bSpatrick if (llvm::Error Err =
1269be691f3bSpatrick reg_ctx
1270be691f3bSpatrick .WriteRegisterFromUnsigned(std::get<1>(zip), std::get<0>(zip))
1271be691f3bSpatrick .ToError()) {
1272be691f3bSpatrick return std::move(Err);
1273be691f3bSpatrick }
1274be691f3bSpatrick }
1275be691f3bSpatrick if (llvm::Error Err = WriteMemory(exe_addr, syscall_data.Insn.data(),
1276be691f3bSpatrick syscall_data.Insn.size(), bytes_read)
1277be691f3bSpatrick .ToError())
1278be691f3bSpatrick return std::move(Err);
1279be691f3bSpatrick
1280be691f3bSpatrick m_mem_region_cache.clear();
1281be691f3bSpatrick
1282be691f3bSpatrick // With software single stepping the syscall insn buffer must also include a
1283be691f3bSpatrick // trap instruction to stop the process.
1284be691f3bSpatrick int req = SupportHardwareSingleStepping() ? PTRACE_SINGLESTEP : PTRACE_CONT;
1285be691f3bSpatrick if (llvm::Error Err =
1286be691f3bSpatrick PtraceWrapper(req, thread.GetID(), nullptr, nullptr).ToError())
1287be691f3bSpatrick return std::move(Err);
1288be691f3bSpatrick
1289be691f3bSpatrick int status;
1290be691f3bSpatrick ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, thread.GetID(),
1291be691f3bSpatrick &status, __WALL);
1292be691f3bSpatrick if (wait_pid == -1) {
1293be691f3bSpatrick return llvm::errorCodeToError(
1294be691f3bSpatrick std::error_code(errno, std::generic_category()));
1295be691f3bSpatrick }
1296be691f3bSpatrick assert((unsigned)wait_pid == thread.GetID());
1297be691f3bSpatrick
1298be691f3bSpatrick uint64_t result = reg_ctx.ReadRegisterAsUnsigned(syscall_data.Result, -ESRCH);
1299be691f3bSpatrick
1300be691f3bSpatrick // Values larger than this are actually negative errno numbers.
1301be691f3bSpatrick uint64_t errno_threshold =
1302be691f3bSpatrick (uint64_t(-1) >> (64 - 8 * m_arch.GetAddressByteSize())) - 0x1000;
1303be691f3bSpatrick if (result > errno_threshold) {
1304be691f3bSpatrick return llvm::errorCodeToError(
1305be691f3bSpatrick std::error_code(-result & 0xfff, std::generic_category()));
1306be691f3bSpatrick }
1307be691f3bSpatrick
1308be691f3bSpatrick return result;
1309be691f3bSpatrick }
1310be691f3bSpatrick
1311be691f3bSpatrick llvm::Expected<addr_t>
AllocateMemory(size_t size,uint32_t permissions)1312be691f3bSpatrick NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions) {
1313be691f3bSpatrick
1314*f6aab3d8Srobert std::optional<NativeRegisterContextLinux::MmapData> mmap_data =
1315be691f3bSpatrick GetCurrentThread()->GetRegisterContext().GetMmapData();
1316be691f3bSpatrick if (!mmap_data)
1317be691f3bSpatrick return llvm::make_error<UnimplementedError>();
1318be691f3bSpatrick
1319be691f3bSpatrick unsigned prot = PROT_NONE;
1320be691f3bSpatrick assert((permissions & (ePermissionsReadable | ePermissionsWritable |
1321be691f3bSpatrick ePermissionsExecutable)) == permissions &&
1322be691f3bSpatrick "Unknown permission!");
1323be691f3bSpatrick if (permissions & ePermissionsReadable)
1324be691f3bSpatrick prot |= PROT_READ;
1325be691f3bSpatrick if (permissions & ePermissionsWritable)
1326be691f3bSpatrick prot |= PROT_WRITE;
1327be691f3bSpatrick if (permissions & ePermissionsExecutable)
1328be691f3bSpatrick prot |= PROT_EXEC;
1329be691f3bSpatrick
1330be691f3bSpatrick llvm::Expected<uint64_t> Result =
1331be691f3bSpatrick Syscall({mmap_data->SysMmap, 0, size, prot, MAP_ANONYMOUS | MAP_PRIVATE,
1332be691f3bSpatrick uint64_t(-1), 0});
1333be691f3bSpatrick if (Result)
1334be691f3bSpatrick m_allocated_memory.try_emplace(*Result, size);
1335be691f3bSpatrick return Result;
1336be691f3bSpatrick }
1337be691f3bSpatrick
DeallocateMemory(lldb::addr_t addr)1338be691f3bSpatrick llvm::Error NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {
1339*f6aab3d8Srobert std::optional<NativeRegisterContextLinux::MmapData> mmap_data =
1340be691f3bSpatrick GetCurrentThread()->GetRegisterContext().GetMmapData();
1341be691f3bSpatrick if (!mmap_data)
1342be691f3bSpatrick return llvm::make_error<UnimplementedError>();
1343be691f3bSpatrick
1344be691f3bSpatrick auto it = m_allocated_memory.find(addr);
1345be691f3bSpatrick if (it == m_allocated_memory.end())
1346be691f3bSpatrick return llvm::createStringError(llvm::errc::invalid_argument,
1347be691f3bSpatrick "Memory not allocated by the debugger.");
1348be691f3bSpatrick
1349be691f3bSpatrick llvm::Expected<uint64_t> Result =
1350be691f3bSpatrick Syscall({mmap_data->SysMunmap, addr, it->second});
1351be691f3bSpatrick if (!Result)
1352be691f3bSpatrick return Result.takeError();
1353be691f3bSpatrick
1354be691f3bSpatrick m_allocated_memory.erase(it);
1355be691f3bSpatrick return llvm::Error::success();
1356be691f3bSpatrick }
1357be691f3bSpatrick
ReadMemoryTags(int32_t type,lldb::addr_t addr,size_t len,std::vector<uint8_t> & tags)1358be691f3bSpatrick Status NativeProcessLinux::ReadMemoryTags(int32_t type, lldb::addr_t addr,
1359be691f3bSpatrick size_t len,
1360be691f3bSpatrick std::vector<uint8_t> &tags) {
1361be691f3bSpatrick llvm::Expected<NativeRegisterContextLinux::MemoryTaggingDetails> details =
1362be691f3bSpatrick GetCurrentThread()->GetRegisterContext().GetMemoryTaggingDetails(type);
1363be691f3bSpatrick if (!details)
1364be691f3bSpatrick return Status(details.takeError());
1365be691f3bSpatrick
1366be691f3bSpatrick // Ignore 0 length read
1367be691f3bSpatrick if (!len)
1368061da546Spatrick return Status();
1369be691f3bSpatrick
1370be691f3bSpatrick // lldb will align the range it requests but it is not required to by
1371be691f3bSpatrick // the protocol so we'll do it again just in case.
1372*f6aab3d8Srobert // Remove tag bits too. Ptrace calls may work regardless but that
1373be691f3bSpatrick // is not a guarantee.
1374*f6aab3d8Srobert MemoryTagManager::TagRange range(details->manager->RemoveTagBits(addr), len);
1375be691f3bSpatrick range = details->manager->ExpandToGranule(range);
1376be691f3bSpatrick
1377be691f3bSpatrick // Allocate enough space for all tags to be read
1378be691f3bSpatrick size_t num_tags = range.GetByteSize() / details->manager->GetGranuleSize();
1379be691f3bSpatrick tags.resize(num_tags * details->manager->GetTagSizeInBytes());
1380be691f3bSpatrick
1381be691f3bSpatrick struct iovec tags_iovec;
1382be691f3bSpatrick uint8_t *dest = tags.data();
1383be691f3bSpatrick lldb::addr_t read_addr = range.GetRangeBase();
1384be691f3bSpatrick
1385be691f3bSpatrick // This call can return partial data so loop until we error or
1386be691f3bSpatrick // get all tags back.
1387be691f3bSpatrick while (num_tags) {
1388be691f3bSpatrick tags_iovec.iov_base = dest;
1389be691f3bSpatrick tags_iovec.iov_len = num_tags;
1390be691f3bSpatrick
1391be691f3bSpatrick Status error = NativeProcessLinux::PtraceWrapper(
1392*f6aab3d8Srobert details->ptrace_read_req, GetCurrentThreadID(),
1393*f6aab3d8Srobert reinterpret_cast<void *>(read_addr), static_cast<void *>(&tags_iovec),
1394*f6aab3d8Srobert 0, nullptr);
1395be691f3bSpatrick
1396be691f3bSpatrick if (error.Fail()) {
1397be691f3bSpatrick // Discard partial reads
1398be691f3bSpatrick tags.resize(0);
1399be691f3bSpatrick return error;
1400061da546Spatrick }
1401061da546Spatrick
1402be691f3bSpatrick size_t tags_read = tags_iovec.iov_len;
1403be691f3bSpatrick assert(tags_read && (tags_read <= num_tags));
1404be691f3bSpatrick
1405be691f3bSpatrick dest += tags_read * details->manager->GetTagSizeInBytes();
1406be691f3bSpatrick read_addr += details->manager->GetGranuleSize() * tags_read;
1407be691f3bSpatrick num_tags -= tags_read;
1408be691f3bSpatrick }
1409be691f3bSpatrick
1410be691f3bSpatrick return Status();
1411be691f3bSpatrick }
1412be691f3bSpatrick
WriteMemoryTags(int32_t type,lldb::addr_t addr,size_t len,const std::vector<uint8_t> & tags)1413be691f3bSpatrick Status NativeProcessLinux::WriteMemoryTags(int32_t type, lldb::addr_t addr,
1414be691f3bSpatrick size_t len,
1415be691f3bSpatrick const std::vector<uint8_t> &tags) {
1416be691f3bSpatrick llvm::Expected<NativeRegisterContextLinux::MemoryTaggingDetails> details =
1417be691f3bSpatrick GetCurrentThread()->GetRegisterContext().GetMemoryTaggingDetails(type);
1418be691f3bSpatrick if (!details)
1419be691f3bSpatrick return Status(details.takeError());
1420be691f3bSpatrick
1421be691f3bSpatrick // Ignore 0 length write
1422be691f3bSpatrick if (!len)
1423be691f3bSpatrick return Status();
1424be691f3bSpatrick
1425be691f3bSpatrick // lldb will align the range it requests but it is not required to by
1426be691f3bSpatrick // the protocol so we'll do it again just in case.
1427*f6aab3d8Srobert // Remove tag bits too. Ptrace calls may work regardless but that
1428be691f3bSpatrick // is not a guarantee.
1429*f6aab3d8Srobert MemoryTagManager::TagRange range(details->manager->RemoveTagBits(addr), len);
1430be691f3bSpatrick range = details->manager->ExpandToGranule(range);
1431be691f3bSpatrick
1432be691f3bSpatrick // Not checking number of tags here, we may repeat them below
1433be691f3bSpatrick llvm::Expected<std::vector<lldb::addr_t>> unpacked_tags_or_err =
1434be691f3bSpatrick details->manager->UnpackTagsData(tags);
1435be691f3bSpatrick if (!unpacked_tags_or_err)
1436be691f3bSpatrick return Status(unpacked_tags_or_err.takeError());
1437be691f3bSpatrick
1438be691f3bSpatrick llvm::Expected<std::vector<lldb::addr_t>> repeated_tags_or_err =
1439be691f3bSpatrick details->manager->RepeatTagsForRange(*unpacked_tags_or_err, range);
1440be691f3bSpatrick if (!repeated_tags_or_err)
1441be691f3bSpatrick return Status(repeated_tags_or_err.takeError());
1442be691f3bSpatrick
1443be691f3bSpatrick // Repack them for ptrace to use
1444be691f3bSpatrick llvm::Expected<std::vector<uint8_t>> final_tag_data =
1445be691f3bSpatrick details->manager->PackTags(*repeated_tags_or_err);
1446be691f3bSpatrick if (!final_tag_data)
1447be691f3bSpatrick return Status(final_tag_data.takeError());
1448be691f3bSpatrick
1449be691f3bSpatrick struct iovec tags_vec;
1450be691f3bSpatrick uint8_t *src = final_tag_data->data();
1451be691f3bSpatrick lldb::addr_t write_addr = range.GetRangeBase();
1452be691f3bSpatrick // unpacked tags size because the number of bytes per tag might not be 1
1453be691f3bSpatrick size_t num_tags = repeated_tags_or_err->size();
1454be691f3bSpatrick
1455be691f3bSpatrick // This call can partially write tags, so we loop until we
1456be691f3bSpatrick // error or all tags have been written.
1457be691f3bSpatrick while (num_tags > 0) {
1458be691f3bSpatrick tags_vec.iov_base = src;
1459be691f3bSpatrick tags_vec.iov_len = num_tags;
1460be691f3bSpatrick
1461be691f3bSpatrick Status error = NativeProcessLinux::PtraceWrapper(
1462*f6aab3d8Srobert details->ptrace_write_req, GetCurrentThreadID(),
1463be691f3bSpatrick reinterpret_cast<void *>(write_addr), static_cast<void *>(&tags_vec), 0,
1464be691f3bSpatrick nullptr);
1465be691f3bSpatrick
1466be691f3bSpatrick if (error.Fail()) {
1467be691f3bSpatrick // Don't attempt to restore the original values in the case of a partial
1468be691f3bSpatrick // write
1469be691f3bSpatrick return error;
1470be691f3bSpatrick }
1471be691f3bSpatrick
1472be691f3bSpatrick size_t tags_written = tags_vec.iov_len;
1473be691f3bSpatrick assert(tags_written && (tags_written <= num_tags));
1474be691f3bSpatrick
1475be691f3bSpatrick src += tags_written * details->manager->GetTagSizeInBytes();
1476be691f3bSpatrick write_addr += details->manager->GetGranuleSize() * tags_written;
1477be691f3bSpatrick num_tags -= tags_written;
1478be691f3bSpatrick }
1479be691f3bSpatrick
1480be691f3bSpatrick return Status();
1481061da546Spatrick }
1482061da546Spatrick
UpdateThreads()1483061da546Spatrick size_t NativeProcessLinux::UpdateThreads() {
1484061da546Spatrick // The NativeProcessLinux monitoring threads are always up to date with
1485061da546Spatrick // respect to thread state and they keep the thread list populated properly.
1486061da546Spatrick // All this method needs to do is return the thread count.
1487061da546Spatrick return m_threads.size();
1488061da546Spatrick }
1489061da546Spatrick
SetBreakpoint(lldb::addr_t addr,uint32_t size,bool hardware)1490061da546Spatrick Status NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,
1491061da546Spatrick bool hardware) {
1492061da546Spatrick if (hardware)
1493061da546Spatrick return SetHardwareBreakpoint(addr, size);
1494061da546Spatrick else
1495061da546Spatrick return SetSoftwareBreakpoint(addr, size);
1496061da546Spatrick }
1497061da546Spatrick
RemoveBreakpoint(lldb::addr_t addr,bool hardware)1498061da546Spatrick Status NativeProcessLinux::RemoveBreakpoint(lldb::addr_t addr, bool hardware) {
1499061da546Spatrick if (hardware)
1500061da546Spatrick return RemoveHardwareBreakpoint(addr);
1501061da546Spatrick else
1502061da546Spatrick return NativeProcessProtocol::RemoveBreakpoint(addr);
1503061da546Spatrick }
1504061da546Spatrick
1505061da546Spatrick llvm::Expected<llvm::ArrayRef<uint8_t>>
GetSoftwareBreakpointTrapOpcode(size_t size_hint)1506061da546Spatrick NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(size_t size_hint) {
1507061da546Spatrick // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1508061da546Spatrick // linux kernel does otherwise.
1509061da546Spatrick static const uint8_t g_arm_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1510061da546Spatrick static const uint8_t g_thumb_opcode[] = {0x01, 0xde};
1511061da546Spatrick
1512061da546Spatrick switch (GetArchitecture().GetMachine()) {
1513061da546Spatrick case llvm::Triple::arm:
1514061da546Spatrick switch (size_hint) {
1515061da546Spatrick case 2:
1516*f6aab3d8Srobert return llvm::ArrayRef(g_thumb_opcode);
1517061da546Spatrick case 4:
1518*f6aab3d8Srobert return llvm::ArrayRef(g_arm_opcode);
1519061da546Spatrick default:
1520061da546Spatrick return llvm::createStringError(llvm::inconvertibleErrorCode(),
1521061da546Spatrick "Unrecognised trap opcode size hint!");
1522061da546Spatrick }
1523061da546Spatrick default:
1524061da546Spatrick return NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_hint);
1525061da546Spatrick }
1526061da546Spatrick }
1527061da546Spatrick
ReadMemory(lldb::addr_t addr,void * buf,size_t size,size_t & bytes_read)1528061da546Spatrick Status NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
1529061da546Spatrick size_t &bytes_read) {
1530061da546Spatrick if (ProcessVmReadvSupported()) {
1531061da546Spatrick // The process_vm_readv path is about 50 times faster than ptrace api. We
1532061da546Spatrick // want to use this syscall if it is supported.
1533061da546Spatrick
1534061da546Spatrick struct iovec local_iov, remote_iov;
1535061da546Spatrick local_iov.iov_base = buf;
1536061da546Spatrick local_iov.iov_len = size;
1537061da546Spatrick remote_iov.iov_base = reinterpret_cast<void *>(addr);
1538061da546Spatrick remote_iov.iov_len = size;
1539061da546Spatrick
1540*f6aab3d8Srobert bytes_read = process_vm_readv(GetCurrentThreadID(), &local_iov, 1,
1541*f6aab3d8Srobert &remote_iov, 1, 0);
1542061da546Spatrick const bool success = bytes_read == size;
1543061da546Spatrick
1544*f6aab3d8Srobert Log *log = GetLog(POSIXLog::Process);
1545061da546Spatrick LLDB_LOG(log,
1546061da546Spatrick "using process_vm_readv to read {0} bytes from inferior "
1547061da546Spatrick "address {1:x}: {2}",
1548061da546Spatrick size, addr, success ? "Success" : llvm::sys::StrError(errno));
1549061da546Spatrick
1550061da546Spatrick if (success)
1551061da546Spatrick return Status();
1552061da546Spatrick // else the call failed for some reason, let's retry the read using ptrace
1553061da546Spatrick // api.
1554061da546Spatrick }
1555061da546Spatrick
1556061da546Spatrick unsigned char *dst = static_cast<unsigned char *>(buf);
1557061da546Spatrick size_t remainder;
1558061da546Spatrick long data;
1559061da546Spatrick
1560*f6aab3d8Srobert Log *log = GetLog(POSIXLog::Memory);
1561061da546Spatrick LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
1562061da546Spatrick
1563061da546Spatrick for (bytes_read = 0; bytes_read < size; bytes_read += remainder) {
1564061da546Spatrick Status error = NativeProcessLinux::PtraceWrapper(
1565*f6aab3d8Srobert PTRACE_PEEKDATA, GetCurrentThreadID(), (void *)addr, nullptr, 0, &data);
1566061da546Spatrick if (error.Fail())
1567061da546Spatrick return error;
1568061da546Spatrick
1569061da546Spatrick remainder = size - bytes_read;
1570061da546Spatrick remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
1571061da546Spatrick
1572061da546Spatrick // Copy the data into our buffer
1573061da546Spatrick memcpy(dst, &data, remainder);
1574061da546Spatrick
1575061da546Spatrick LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
1576061da546Spatrick addr += k_ptrace_word_size;
1577061da546Spatrick dst += k_ptrace_word_size;
1578061da546Spatrick }
1579061da546Spatrick return Status();
1580061da546Spatrick }
1581061da546Spatrick
WriteMemory(lldb::addr_t addr,const void * buf,size_t size,size_t & bytes_written)1582061da546Spatrick Status NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,
1583061da546Spatrick size_t size, size_t &bytes_written) {
1584061da546Spatrick const unsigned char *src = static_cast<const unsigned char *>(buf);
1585061da546Spatrick size_t remainder;
1586061da546Spatrick Status error;
1587061da546Spatrick
1588*f6aab3d8Srobert Log *log = GetLog(POSIXLog::Memory);
1589061da546Spatrick LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
1590061da546Spatrick
1591061da546Spatrick for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
1592061da546Spatrick remainder = size - bytes_written;
1593061da546Spatrick remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
1594061da546Spatrick
1595061da546Spatrick if (remainder == k_ptrace_word_size) {
1596061da546Spatrick unsigned long data = 0;
1597061da546Spatrick memcpy(&data, src, k_ptrace_word_size);
1598061da546Spatrick
1599061da546Spatrick LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
1600*f6aab3d8Srobert error = NativeProcessLinux::PtraceWrapper(
1601*f6aab3d8Srobert PTRACE_POKEDATA, GetCurrentThreadID(), (void *)addr, (void *)data);
1602061da546Spatrick if (error.Fail())
1603061da546Spatrick return error;
1604061da546Spatrick } else {
1605061da546Spatrick unsigned char buff[8];
1606061da546Spatrick size_t bytes_read;
1607061da546Spatrick error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
1608061da546Spatrick if (error.Fail())
1609061da546Spatrick return error;
1610061da546Spatrick
1611061da546Spatrick memcpy(buff, src, remainder);
1612061da546Spatrick
1613061da546Spatrick size_t bytes_written_rec;
1614061da546Spatrick error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
1615061da546Spatrick if (error.Fail())
1616061da546Spatrick return error;
1617061da546Spatrick
1618061da546Spatrick LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src,
1619061da546Spatrick *(unsigned long *)buff);
1620061da546Spatrick }
1621061da546Spatrick
1622061da546Spatrick addr += k_ptrace_word_size;
1623061da546Spatrick src += k_ptrace_word_size;
1624061da546Spatrick }
1625061da546Spatrick return error;
1626061da546Spatrick }
1627061da546Spatrick
GetSignalInfo(lldb::tid_t tid,void * siginfo) const1628*f6aab3d8Srobert Status NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) const {
1629061da546Spatrick return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
1630061da546Spatrick }
1631061da546Spatrick
GetEventMessage(lldb::tid_t tid,unsigned long * message)1632061da546Spatrick Status NativeProcessLinux::GetEventMessage(lldb::tid_t tid,
1633061da546Spatrick unsigned long *message) {
1634061da546Spatrick return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
1635061da546Spatrick }
1636061da546Spatrick
Detach(lldb::tid_t tid)1637061da546Spatrick Status NativeProcessLinux::Detach(lldb::tid_t tid) {
1638061da546Spatrick if (tid == LLDB_INVALID_THREAD_ID)
1639061da546Spatrick return Status();
1640061da546Spatrick
1641061da546Spatrick return PtraceWrapper(PTRACE_DETACH, tid);
1642061da546Spatrick }
1643061da546Spatrick
HasThreadNoLock(lldb::tid_t thread_id)1644061da546Spatrick bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {
1645061da546Spatrick for (const auto &thread : m_threads) {
1646061da546Spatrick assert(thread && "thread list should not contain NULL threads");
1647061da546Spatrick if (thread->GetID() == thread_id) {
1648061da546Spatrick // We have this thread.
1649061da546Spatrick return true;
1650061da546Spatrick }
1651061da546Spatrick }
1652061da546Spatrick
1653061da546Spatrick // We don't have this thread.
1654061da546Spatrick return false;
1655061da546Spatrick }
1656061da546Spatrick
StopTrackingThread(NativeThreadLinux & thread)1657*f6aab3d8Srobert void NativeProcessLinux::StopTrackingThread(NativeThreadLinux &thread) {
1658*f6aab3d8Srobert Log *const log = GetLog(POSIXLog::Thread);
1659*f6aab3d8Srobert lldb::tid_t thread_id = thread.GetID();
1660*f6aab3d8Srobert LLDB_LOG(log, "tid: {0}", thread_id);
1661061da546Spatrick
1662*f6aab3d8Srobert auto it = llvm::find_if(m_threads, [&](const auto &thread_up) {
1663*f6aab3d8Srobert return thread_up.get() == &thread;
1664*f6aab3d8Srobert });
1665*f6aab3d8Srobert assert(it != m_threads.end());
1666061da546Spatrick m_threads.erase(it);
1667061da546Spatrick
1668be691f3bSpatrick NotifyTracersOfThreadDestroyed(thread_id);
1669061da546Spatrick SignalIfAllThreadsStopped();
1670*f6aab3d8Srobert }
1671*f6aab3d8Srobert
NotifyTracersProcessDidStop()1672*f6aab3d8Srobert void NativeProcessLinux::NotifyTracersProcessDidStop() {
1673*f6aab3d8Srobert m_intel_pt_collector.ProcessDidStop();
1674*f6aab3d8Srobert }
1675*f6aab3d8Srobert
NotifyTracersProcessWillResume()1676*f6aab3d8Srobert void NativeProcessLinux::NotifyTracersProcessWillResume() {
1677*f6aab3d8Srobert m_intel_pt_collector.ProcessWillResume();
1678061da546Spatrick }
1679061da546Spatrick
NotifyTracersOfNewThread(lldb::tid_t tid)1680be691f3bSpatrick Status NativeProcessLinux::NotifyTracersOfNewThread(lldb::tid_t tid) {
1681*f6aab3d8Srobert Log *log = GetLog(POSIXLog::Thread);
1682*f6aab3d8Srobert Status error(m_intel_pt_collector.OnThreadCreated(tid));
1683be691f3bSpatrick if (error.Fail())
1684be691f3bSpatrick LLDB_LOG(log, "Failed to trace a new thread with intel-pt, tid = {0}. {1}",
1685be691f3bSpatrick tid, error.AsCString());
1686be691f3bSpatrick return error;
1687be691f3bSpatrick }
1688be691f3bSpatrick
NotifyTracersOfThreadDestroyed(lldb::tid_t tid)1689be691f3bSpatrick Status NativeProcessLinux::NotifyTracersOfThreadDestroyed(lldb::tid_t tid) {
1690*f6aab3d8Srobert Log *log = GetLog(POSIXLog::Thread);
1691*f6aab3d8Srobert Status error(m_intel_pt_collector.OnThreadDestroyed(tid));
1692be691f3bSpatrick if (error.Fail())
1693be691f3bSpatrick LLDB_LOG(log,
1694be691f3bSpatrick "Failed to stop a destroyed thread with intel-pt, tid = {0}. {1}",
1695be691f3bSpatrick tid, error.AsCString());
1696be691f3bSpatrick return error;
1697be691f3bSpatrick }
1698be691f3bSpatrick
AddThread(lldb::tid_t thread_id,bool resume)1699be691f3bSpatrick NativeThreadLinux &NativeProcessLinux::AddThread(lldb::tid_t thread_id,
1700be691f3bSpatrick bool resume) {
1701*f6aab3d8Srobert Log *log = GetLog(POSIXLog::Thread);
1702061da546Spatrick LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
1703061da546Spatrick
1704061da546Spatrick assert(!HasThreadNoLock(thread_id) &&
1705061da546Spatrick "attempted to add a thread by id that already exists");
1706061da546Spatrick
1707061da546Spatrick // If this is the first thread, save it as the current thread
1708061da546Spatrick if (m_threads.empty())
1709061da546Spatrick SetCurrentThreadID(thread_id);
1710061da546Spatrick
1711061da546Spatrick m_threads.push_back(std::make_unique<NativeThreadLinux>(*this, thread_id));
1712be691f3bSpatrick NativeThreadLinux &thread =
1713be691f3bSpatrick static_cast<NativeThreadLinux &>(*m_threads.back());
1714061da546Spatrick
1715be691f3bSpatrick Status tracing_error = NotifyTracersOfNewThread(thread.GetID());
1716be691f3bSpatrick if (tracing_error.Fail()) {
1717be691f3bSpatrick thread.SetStoppedByProcessorTrace(tracing_error.AsCString());
1718be691f3bSpatrick StopRunningThreads(thread.GetID());
1719be691f3bSpatrick } else if (resume)
1720be691f3bSpatrick ResumeThread(thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
1721be691f3bSpatrick else
1722be691f3bSpatrick thread.SetStoppedBySignal(SIGSTOP);
1723061da546Spatrick
1724be691f3bSpatrick return thread;
1725061da546Spatrick }
1726061da546Spatrick
GetLoadedModuleFileSpec(const char * module_path,FileSpec & file_spec)1727061da546Spatrick Status NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,
1728061da546Spatrick FileSpec &file_spec) {
1729061da546Spatrick Status error = PopulateMemoryRegionCache();
1730061da546Spatrick if (error.Fail())
1731061da546Spatrick return error;
1732061da546Spatrick
1733061da546Spatrick FileSpec module_file_spec(module_path);
1734061da546Spatrick FileSystem::Instance().Resolve(module_file_spec);
1735061da546Spatrick
1736061da546Spatrick file_spec.Clear();
1737061da546Spatrick for (const auto &it : m_mem_region_cache) {
1738061da546Spatrick if (it.second.GetFilename() == module_file_spec.GetFilename()) {
1739061da546Spatrick file_spec = it.second;
1740061da546Spatrick return Status();
1741061da546Spatrick }
1742061da546Spatrick }
1743061da546Spatrick return Status("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
1744061da546Spatrick module_file_spec.GetFilename().AsCString(), GetID());
1745061da546Spatrick }
1746061da546Spatrick
GetFileLoadAddress(const llvm::StringRef & file_name,lldb::addr_t & load_addr)1747061da546Spatrick Status NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
1748061da546Spatrick lldb::addr_t &load_addr) {
1749061da546Spatrick load_addr = LLDB_INVALID_ADDRESS;
1750061da546Spatrick Status error = PopulateMemoryRegionCache();
1751061da546Spatrick if (error.Fail())
1752061da546Spatrick return error;
1753061da546Spatrick
1754061da546Spatrick FileSpec file(file_name);
1755061da546Spatrick for (const auto &it : m_mem_region_cache) {
1756061da546Spatrick if (it.second == file) {
1757061da546Spatrick load_addr = it.first.GetRange().GetRangeBase();
1758061da546Spatrick return Status();
1759061da546Spatrick }
1760061da546Spatrick }
1761061da546Spatrick return Status("No load address found for specified file.");
1762061da546Spatrick }
1763061da546Spatrick
GetThreadByID(lldb::tid_t tid)1764061da546Spatrick NativeThreadLinux *NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {
1765061da546Spatrick return static_cast<NativeThreadLinux *>(
1766061da546Spatrick NativeProcessProtocol::GetThreadByID(tid));
1767061da546Spatrick }
1768061da546Spatrick
GetCurrentThread()1769be691f3bSpatrick NativeThreadLinux *NativeProcessLinux::GetCurrentThread() {
1770be691f3bSpatrick return static_cast<NativeThreadLinux *>(
1771be691f3bSpatrick NativeProcessProtocol::GetCurrentThread());
1772be691f3bSpatrick }
1773be691f3bSpatrick
ResumeThread(NativeThreadLinux & thread,lldb::StateType state,int signo)1774061da546Spatrick Status NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,
1775061da546Spatrick lldb::StateType state, int signo) {
1776*f6aab3d8Srobert Log *const log = GetLog(POSIXLog::Thread);
1777061da546Spatrick LLDB_LOG(log, "tid: {0}", thread.GetID());
1778061da546Spatrick
1779061da546Spatrick // Before we do the resume below, first check if we have a pending stop
1780061da546Spatrick // notification that is currently waiting for all threads to stop. This is
1781061da546Spatrick // potentially a buggy situation since we're ostensibly waiting for threads
1782061da546Spatrick // to stop before we send out the pending notification, and here we are
1783061da546Spatrick // resuming one before we send out the pending stop notification.
1784061da546Spatrick if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
1785061da546Spatrick LLDB_LOG(log,
1786061da546Spatrick "about to resume tid {0} per explicit request but we have a "
1787061da546Spatrick "pending stop notification (tid {1}) that is actively "
1788061da546Spatrick "waiting for this thread to stop. Valid sequence of events?",
1789061da546Spatrick thread.GetID(), m_pending_notification_tid);
1790061da546Spatrick }
1791061da546Spatrick
1792061da546Spatrick // Request a resume. We expect this to be synchronous and the system to
1793061da546Spatrick // reflect it is running after this completes.
1794061da546Spatrick switch (state) {
1795061da546Spatrick case eStateRunning: {
1796061da546Spatrick const auto resume_result = thread.Resume(signo);
1797061da546Spatrick if (resume_result.Success())
1798061da546Spatrick SetState(eStateRunning, true);
1799061da546Spatrick return resume_result;
1800061da546Spatrick }
1801061da546Spatrick case eStateStepping: {
1802061da546Spatrick const auto step_result = thread.SingleStep(signo);
1803061da546Spatrick if (step_result.Success())
1804061da546Spatrick SetState(eStateRunning, true);
1805061da546Spatrick return step_result;
1806061da546Spatrick }
1807061da546Spatrick default:
1808061da546Spatrick LLDB_LOG(log, "Unhandled state {0}.", state);
1809061da546Spatrick llvm_unreachable("Unhandled state for resume");
1810061da546Spatrick }
1811061da546Spatrick }
1812061da546Spatrick
1813061da546Spatrick //===----------------------------------------------------------------------===//
1814061da546Spatrick
StopRunningThreads(const lldb::tid_t triggering_tid)1815061da546Spatrick void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {
1816*f6aab3d8Srobert Log *const log = GetLog(POSIXLog::Thread);
1817061da546Spatrick LLDB_LOG(log, "about to process event: (triggering_tid: {0})",
1818061da546Spatrick triggering_tid);
1819061da546Spatrick
1820061da546Spatrick m_pending_notification_tid = triggering_tid;
1821061da546Spatrick
1822061da546Spatrick // Request a stop for all the thread stops that need to be stopped and are
1823061da546Spatrick // not already known to be stopped.
1824061da546Spatrick for (const auto &thread : m_threads) {
1825061da546Spatrick if (StateIsRunningState(thread->GetState()))
1826061da546Spatrick static_cast<NativeThreadLinux *>(thread.get())->RequestStop();
1827061da546Spatrick }
1828061da546Spatrick
1829061da546Spatrick SignalIfAllThreadsStopped();
1830061da546Spatrick LLDB_LOG(log, "event processing done");
1831061da546Spatrick }
1832061da546Spatrick
SignalIfAllThreadsStopped()1833061da546Spatrick void NativeProcessLinux::SignalIfAllThreadsStopped() {
1834061da546Spatrick if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
1835061da546Spatrick return; // No pending notification. Nothing to do.
1836061da546Spatrick
1837061da546Spatrick for (const auto &thread_sp : m_threads) {
1838061da546Spatrick if (StateIsRunningState(thread_sp->GetState()))
1839061da546Spatrick return; // Some threads are still running. Don't signal yet.
1840061da546Spatrick }
1841061da546Spatrick
1842061da546Spatrick // We have a pending notification and all threads have stopped.
1843*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process | LLDBLog::Breakpoints);
1844061da546Spatrick
1845061da546Spatrick // Clear any temporary breakpoints we used to implement software single
1846061da546Spatrick // stepping.
1847061da546Spatrick for (const auto &thread_info : m_threads_stepping_with_breakpoint) {
1848061da546Spatrick Status error = RemoveBreakpoint(thread_info.second);
1849061da546Spatrick if (error.Fail())
1850061da546Spatrick LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}",
1851061da546Spatrick thread_info.first, error);
1852061da546Spatrick }
1853061da546Spatrick m_threads_stepping_with_breakpoint.clear();
1854061da546Spatrick
1855061da546Spatrick // Notify the delegate about the stop
1856061da546Spatrick SetCurrentThreadID(m_pending_notification_tid);
1857061da546Spatrick SetState(StateType::eStateStopped, true);
1858061da546Spatrick m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
1859061da546Spatrick }
1860061da546Spatrick
ThreadWasCreated(NativeThreadLinux & thread)1861061da546Spatrick void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {
1862*f6aab3d8Srobert Log *const log = GetLog(POSIXLog::Thread);
1863061da546Spatrick LLDB_LOG(log, "tid: {0}", thread.GetID());
1864061da546Spatrick
1865061da546Spatrick if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID &&
1866061da546Spatrick StateIsRunningState(thread.GetState())) {
1867061da546Spatrick // We will need to wait for this new thread to stop as well before firing
1868061da546Spatrick // the notification.
1869061da546Spatrick thread.RequestStop();
1870061da546Spatrick }
1871061da546Spatrick }
1872061da546Spatrick
HandlePid(::pid_t pid)1873*f6aab3d8Srobert static std::optional<WaitStatus> HandlePid(::pid_t pid) {
1874*f6aab3d8Srobert Log *log = GetLog(POSIXLog::Process);
1875*f6aab3d8Srobert
1876*f6aab3d8Srobert int status;
1877*f6aab3d8Srobert ::pid_t wait_pid = llvm::sys::RetryAfterSignal(
1878*f6aab3d8Srobert -1, ::waitpid, pid, &status, __WALL | __WNOTHREAD | WNOHANG);
1879061da546Spatrick
1880061da546Spatrick if (wait_pid == 0)
1881*f6aab3d8Srobert return std::nullopt;
1882061da546Spatrick
1883061da546Spatrick if (wait_pid == -1) {
1884061da546Spatrick Status error(errno, eErrorTypePOSIX);
1885*f6aab3d8Srobert LLDB_LOG(log, "waitpid({0}, &status, _) failed: {1}", pid,
1886*f6aab3d8Srobert error);
1887*f6aab3d8Srobert return std::nullopt;
1888061da546Spatrick }
1889061da546Spatrick
1890*f6aab3d8Srobert assert(wait_pid == pid);
1891*f6aab3d8Srobert
1892061da546Spatrick WaitStatus wait_status = WaitStatus::Decode(status);
1893061da546Spatrick
1894*f6aab3d8Srobert LLDB_LOG(log, "waitpid({0}) got status = {1}", pid, wait_status);
1895*f6aab3d8Srobert return wait_status;
1896*f6aab3d8Srobert }
1897061da546Spatrick
SigchldHandler()1898*f6aab3d8Srobert void NativeProcessLinux::SigchldHandler() {
1899*f6aab3d8Srobert Log *log = GetLog(POSIXLog::Process);
1900*f6aab3d8Srobert
1901*f6aab3d8Srobert // Threads can appear or disappear as a result of event processing, so gather
1902*f6aab3d8Srobert // the events upfront.
1903*f6aab3d8Srobert llvm::DenseMap<lldb::tid_t, WaitStatus> tid_events;
1904*f6aab3d8Srobert bool checked_main_thread = false;
1905*f6aab3d8Srobert for (const auto &thread_up : m_threads) {
1906*f6aab3d8Srobert if (thread_up->GetID() == GetID())
1907*f6aab3d8Srobert checked_main_thread = true;
1908*f6aab3d8Srobert
1909*f6aab3d8Srobert if (std::optional<WaitStatus> status = HandlePid(thread_up->GetID()))
1910*f6aab3d8Srobert tid_events.try_emplace(thread_up->GetID(), *status);
1911*f6aab3d8Srobert }
1912*f6aab3d8Srobert // Check the main thread even when we're not tracking it as process exit
1913*f6aab3d8Srobert // events are reported that way.
1914*f6aab3d8Srobert if (!checked_main_thread) {
1915*f6aab3d8Srobert if (std::optional<WaitStatus> status = HandlePid(GetID()))
1916*f6aab3d8Srobert tid_events.try_emplace(GetID(), *status);
1917*f6aab3d8Srobert }
1918*f6aab3d8Srobert
1919*f6aab3d8Srobert for (auto &KV : tid_events) {
1920*f6aab3d8Srobert LLDB_LOG(log, "processing {0}({1}) ...", KV.first, KV.second);
1921*f6aab3d8Srobert if (KV.first == GetID() && (KV.second.type == WaitStatus::Exit ||
1922*f6aab3d8Srobert KV.second.type == WaitStatus::Signal)) {
1923*f6aab3d8Srobert
1924*f6aab3d8Srobert // The process exited. We're done monitoring. Report to delegate.
1925*f6aab3d8Srobert SetExitStatus(KV.second, true);
1926*f6aab3d8Srobert return;
1927*f6aab3d8Srobert }
1928*f6aab3d8Srobert NativeThreadLinux *thread = GetThreadByID(KV.first);
1929*f6aab3d8Srobert assert(thread && "Why did this thread disappear?");
1930*f6aab3d8Srobert MonitorCallback(*thread, KV.second);
1931061da546Spatrick }
1932061da546Spatrick }
1933061da546Spatrick
1934061da546Spatrick // Wrapper for ptrace to catch errors and log calls. Note that ptrace sets
1935061da546Spatrick // errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
PtraceWrapper(int req,lldb::pid_t pid,void * addr,void * data,size_t data_size,long * result)1936061da546Spatrick Status NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
1937061da546Spatrick void *data, size_t data_size,
1938061da546Spatrick long *result) {
1939061da546Spatrick Status error;
1940061da546Spatrick long int ret;
1941061da546Spatrick
1942*f6aab3d8Srobert Log *log = GetLog(POSIXLog::Ptrace);
1943061da546Spatrick
1944061da546Spatrick PtraceDisplayBytes(req, data, data_size);
1945061da546Spatrick
1946061da546Spatrick errno = 0;
1947061da546Spatrick if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
1948061da546Spatrick ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
1949061da546Spatrick *(unsigned int *)addr, data);
1950061da546Spatrick else
1951061da546Spatrick ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
1952061da546Spatrick addr, data);
1953061da546Spatrick
1954061da546Spatrick if (ret == -1)
1955061da546Spatrick error.SetErrorToErrno();
1956061da546Spatrick
1957061da546Spatrick if (result)
1958061da546Spatrick *result = ret;
1959061da546Spatrick
1960061da546Spatrick LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data,
1961061da546Spatrick data_size, ret);
1962061da546Spatrick
1963061da546Spatrick PtraceDisplayBytes(req, data, data_size);
1964061da546Spatrick
1965061da546Spatrick if (error.Fail())
1966061da546Spatrick LLDB_LOG(log, "ptrace() failed: {0}", error);
1967061da546Spatrick
1968061da546Spatrick return error;
1969061da546Spatrick }
1970061da546Spatrick
TraceSupported()1971be691f3bSpatrick llvm::Expected<TraceSupportedResponse> NativeProcessLinux::TraceSupported() {
1972*f6aab3d8Srobert if (IntelPTCollector::IsSupported())
1973be691f3bSpatrick return TraceSupportedResponse{"intel-pt", "Intel Processor Trace"};
1974be691f3bSpatrick return NativeProcessProtocol::TraceSupported();
1975061da546Spatrick }
1976061da546Spatrick
TraceStart(StringRef json_request,StringRef type)1977be691f3bSpatrick Error NativeProcessLinux::TraceStart(StringRef json_request, StringRef type) {
1978be691f3bSpatrick if (type == "intel-pt") {
1979be691f3bSpatrick if (Expected<TraceIntelPTStartRequest> request =
1980be691f3bSpatrick json::parse<TraceIntelPTStartRequest>(json_request,
1981be691f3bSpatrick "TraceIntelPTStartRequest")) {
1982*f6aab3d8Srobert return m_intel_pt_collector.TraceStart(*request);
1983be691f3bSpatrick } else
1984be691f3bSpatrick return request.takeError();
1985061da546Spatrick }
1986061da546Spatrick
1987be691f3bSpatrick return NativeProcessProtocol::TraceStart(json_request, type);
1988061da546Spatrick }
1989061da546Spatrick
TraceStop(const TraceStopRequest & request)1990be691f3bSpatrick Error NativeProcessLinux::TraceStop(const TraceStopRequest &request) {
1991be691f3bSpatrick if (request.type == "intel-pt")
1992*f6aab3d8Srobert return m_intel_pt_collector.TraceStop(request);
1993be691f3bSpatrick return NativeProcessProtocol::TraceStop(request);
1994061da546Spatrick }
1995061da546Spatrick
TraceGetState(StringRef type)1996be691f3bSpatrick Expected<json::Value> NativeProcessLinux::TraceGetState(StringRef type) {
1997be691f3bSpatrick if (type == "intel-pt")
1998*f6aab3d8Srobert return m_intel_pt_collector.GetState();
1999be691f3bSpatrick return NativeProcessProtocol::TraceGetState(type);
2000061da546Spatrick }
2001061da546Spatrick
TraceGetBinaryData(const TraceGetBinaryDataRequest & request)2002be691f3bSpatrick Expected<std::vector<uint8_t>> NativeProcessLinux::TraceGetBinaryData(
2003be691f3bSpatrick const TraceGetBinaryDataRequest &request) {
2004be691f3bSpatrick if (request.type == "intel-pt")
2005*f6aab3d8Srobert return m_intel_pt_collector.GetBinaryData(request);
2006be691f3bSpatrick return NativeProcessProtocol::TraceGetBinaryData(request);
2007061da546Spatrick }
2008