Bug Summary

File:build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp
Warning:line 141, column 5
2nd function call argument is an uninitialized value

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name NativeProcessLinux.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm/tools/clang/stage2-bins -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -isystem /usr/include/libxml2 -D HAVE_ROUND -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/lldb/source/Plugins/Process/Linux -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/lldb/source/Plugins/Process/Linux -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/lldb/include -I tools/lldb/include -I include -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/include -I /usr/include/python3.9 -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/include -I tools/lldb/../clang/include -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/lldb/source -I tools/lldb/source -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -O2 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -Wno-deprecated-declarations -Wno-unknown-pragmas -Wno-strict-aliasing -Wno-stringop-truncation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-10-03-140002-15933-1 -x c++ /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp
1//===-- NativeProcessLinux.cpp --------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "NativeProcessLinux.h"
10
11#include <cerrno>
12#include <cstdint>
13#include <cstring>
14#include <unistd.h>
15
16#include <fstream>
17#include <mutex>
18#include <sstream>
19#include <string>
20#include <unordered_map>
21
22#include "NativeThreadLinux.h"
23#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
24#include "Plugins/Process/Utility/LinuxProcMaps.h"
25#include "Procfs.h"
26#include "lldb/Core/ModuleSpec.h"
27#include "lldb/Host/Host.h"
28#include "lldb/Host/HostProcess.h"
29#include "lldb/Host/ProcessLaunchInfo.h"
30#include "lldb/Host/PseudoTerminal.h"
31#include "lldb/Host/ThreadLauncher.h"
32#include "lldb/Host/common/NativeRegisterContext.h"
33#include "lldb/Host/linux/Host.h"
34#include "lldb/Host/linux/Ptrace.h"
35#include "lldb/Host/linux/Uio.h"
36#include "lldb/Host/posix/ProcessLauncherPosixFork.h"
37#include "lldb/Symbol/ObjectFile.h"
38#include "lldb/Target/Process.h"
39#include "lldb/Target/Target.h"
40#include "lldb/Utility/LLDBAssert.h"
41#include "lldb/Utility/LLDBLog.h"
42#include "lldb/Utility/State.h"
43#include "lldb/Utility/Status.h"
44#include "lldb/Utility/StringExtractor.h"
45#include "llvm/ADT/ScopeExit.h"
46#include "llvm/Support/Errno.h"
47#include "llvm/Support/FileSystem.h"
48#include "llvm/Support/Threading.h"
49
50#include <linux/unistd.h>
51#include <sys/socket.h>
52#include <sys/syscall.h>
53#include <sys/types.h>
54#include <sys/user.h>
55#include <sys/wait.h>
56
57#ifdef __aarch64__
58#include <asm/hwcap.h>
59#include <sys/auxv.h>
60#endif
61
62// Support hardware breakpoints in case it has not been defined
63#ifndef TRAP_HWBKPTTRAP_HWBKPT
64#define TRAP_HWBKPTTRAP_HWBKPT 4
65#endif
66
67#ifndef HWCAP2_MTE(1 << 18)
68#define HWCAP2_MTE(1 << 18) (1 << 18)
69#endif
70
71using namespace lldb;
72using namespace lldb_private;
73using namespace lldb_private::process_linux;
74using namespace llvm;
75
76// Private bits we only need internally.
77
78static bool ProcessVmReadvSupported() {
79 static bool is_supported;
80 static llvm::once_flag flag;
81
82 llvm::call_once(flag, [] {
83 Log *log = GetLog(POSIXLog::Process);
84
85 uint32_t source = 0x47424742;
86 uint32_t dest = 0;
87
88 struct iovec local, remote;
89 remote.iov_base = &source;
90 local.iov_base = &dest;
91 remote.iov_len = local.iov_len = sizeof source;
92
93 // We shall try if cross-process-memory reads work by attempting to read a
94 // value from our own process.
95 ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
96 is_supported = (res == sizeof(source) && source == dest);
97 if (is_supported)
98 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "Detected kernel support for process_vm_readv syscall. "
"Fast memory reads enabled."); } while (0)
99 "Detected kernel support for process_vm_readv syscall. "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "Detected kernel support for process_vm_readv syscall. "
"Fast memory reads enabled."); } while (0)
100 "Fast memory reads enabled.")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "Detected kernel support for process_vm_readv syscall. "
"Fast memory reads enabled."); } while (0)
;
101 else
102 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "syscall process_vm_readv failed (error: {0}). Fast memory "
"reads disabled.", llvm::sys::StrError()); } while (0)
103 "syscall process_vm_readv failed (error: {0}). Fast memory "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "syscall process_vm_readv failed (error: {0}). Fast memory "
"reads disabled.", llvm::sys::StrError()); } while (0)
104 "reads disabled.",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "syscall process_vm_readv failed (error: {0}). Fast memory "
"reads disabled.", llvm::sys::StrError()); } while (0)
105 llvm::sys::StrError())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "syscall process_vm_readv failed (error: {0}). Fast memory "
"reads disabled.", llvm::sys::StrError()); } while (0)
;
106 });
107
108 return is_supported;
109}
110
111static void MaybeLogLaunchInfo(const ProcessLaunchInfo &info) {
112 Log *log = GetLog(POSIXLog::Process);
113 if (!log)
114 return;
115
116 if (const FileAction *action = info.GetFileActionForFD(STDIN_FILENO0))
117 LLDB_LOG(log, "setting STDIN to '{0}'", action->GetFileSpec())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "setting STDIN to '{0}'", action->GetFileSpec(
)); } while (0)
;
118 else
119 LLDB_LOG(log, "leaving STDIN as is")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "leaving STDIN as is"); } while (0)
;
120
121 if (const FileAction *action = info.GetFileActionForFD(STDOUT_FILENO1))
122 LLDB_LOG(log, "setting STDOUT to '{0}'", action->GetFileSpec())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "setting STDOUT to '{0}'", action->GetFileSpec
()); } while (0)
;
123 else
124 LLDB_LOG(log, "leaving STDOUT as is")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "leaving STDOUT as is"); } while (0)
;
125
126 if (const FileAction *action = info.GetFileActionForFD(STDERR_FILENO2))
127 LLDB_LOG(log, "setting STDERR to '{0}'", action->GetFileSpec())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "setting STDERR to '{0}'", action->GetFileSpec
()); } while (0)
;
128 else
129 LLDB_LOG(log, "leaving STDERR as is")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "leaving STDERR as is"); } while (0)
;
130
131 int i = 0;
132 for (const char **args = info.GetArguments().GetConstArgumentVector(); *args;
133 ++args, ++i)
134 LLDB_LOG(log, "arg {0}: '{1}'", i, *args)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "arg {0}: '{1}'", i, *args); } while (0)
;
135}
136
137static void DisplayBytes(StreamString &s, void *bytes, uint32_t count) {
138 uint8_t *ptr = (uint8_t *)bytes;
139 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES20, count);
140 for (uint32_t i = 0; i < loop_count; i++) {
14
Loop condition is true. Entering loop body
15
Loop condition is true. Entering loop body
141 s.Printf("[%x]", *ptr);
16
2nd function call argument is an uninitialized value
142 ptr++;
143 }
144}
145
146static void PtraceDisplayBytes(int &req, void *data, size_t data_size) {
147 Log *log = GetLog(POSIXLog::Ptrace);
148 if (!log
10.1
'log' is non-null
)
11
Taking false branch
149 return;
150 StreamString buf;
151
152 switch (req) {
12
Control jumps to 'case PTRACE_SETSIGINFO:' at line 178
153 case PTRACE_POKETEXT: {
154 DisplayBytes(buf, &data, 8);
155 LLDB_LOGV(log, "PTRACE_POKETEXT {0}", buf.GetData())do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp", __func__
, "PTRACE_POKETEXT {0}", buf.GetData()); } while (0)
;
156 break;
157 }
158 case PTRACE_POKEDATA: {
159 DisplayBytes(buf, &data, 8);
160 LLDB_LOGV(log, "PTRACE_POKEDATA {0}", buf.GetData())do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp", __func__
, "PTRACE_POKEDATA {0}", buf.GetData()); } while (0)
;
161 break;
162 }
163 case PTRACE_POKEUSER: {
164 DisplayBytes(buf, &data, 8);
165 LLDB_LOGV(log, "PTRACE_POKEUSER {0}", buf.GetData())do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp", __func__
, "PTRACE_POKEUSER {0}", buf.GetData()); } while (0)
;
166 break;
167 }
168 case PTRACE_SETREGS13: {
169 DisplayBytes(buf, data, data_size);
170 LLDB_LOGV(log, "PTRACE_SETREGS {0}", buf.GetData())do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp", __func__
, "PTRACE_SETREGS {0}", buf.GetData()); } while (0)
;
171 break;
172 }
173 case PTRACE_SETFPREGS15: {
174 DisplayBytes(buf, data, data_size);
175 LLDB_LOGV(log, "PTRACE_SETFPREGS {0}", buf.GetData())do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp", __func__
, "PTRACE_SETFPREGS {0}", buf.GetData()); } while (0)
;
176 break;
177 }
178 case PTRACE_SETSIGINFO: {
179 DisplayBytes(buf, data, sizeof(siginfo_t));
13
Calling 'DisplayBytes'
180 LLDB_LOGV(log, "PTRACE_SETSIGINFO {0}", buf.GetData())do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp", __func__
, "PTRACE_SETSIGINFO {0}", buf.GetData()); } while (0)
;
181 break;
182 }
183 case PTRACE_SETREGSETPTRACE_SETREGSET: {
184 // Extract iov_base from data, which is a pointer to the struct iovec
185 DisplayBytes(buf, *(void **)data, data_size);
186 LLDB_LOGV(log, "PTRACE_SETREGSET {0}", buf.GetData())do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp", __func__
, "PTRACE_SETREGSET {0}", buf.GetData()); } while (0)
;
187 break;
188 }
189 default: {}
190 }
191}
192
193static constexpr unsigned k_ptrace_word_size = sizeof(void *);
194static_assert(sizeof(long) >= k_ptrace_word_size,
195 "Size of long must be larger than ptrace word size");
196
197// Simple helper function to ensure flags are enabled on the given file
198// descriptor.
199static Status EnsureFDFlags(int fd, int flags) {
200 Status error;
201
202 int status = fcntl(fd, F_GETFL3);
203 if (status == -1) {
204 error.SetErrorToErrno();
205 return error;
206 }
207
208 if (fcntl(fd, F_SETFL4, status | flags) == -1) {
209 error.SetErrorToErrno();
210 return error;
211 }
212
213 return error;
214}
215
216// Public Static Methods
217
218llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
219NativeProcessLinux::Factory::Launch(ProcessLaunchInfo &launch_info,
220 NativeDelegate &native_delegate,
221 MainLoop &mainloop) const {
222 Log *log = GetLog(POSIXLog::Process);
223
224 MaybeLogLaunchInfo(launch_info);
225
226 Status status;
227 ::pid_t pid = ProcessLauncherPosixFork()
228 .LaunchProcess(launch_info, status)
229 .GetProcessId();
230 LLDB_LOG(log, "pid = {0:x}", pid)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid = {0:x}", pid); } while (0)
;
231 if (status.Fail()) {
232 LLDB_LOG(log, "failed to launch process: {0}", status)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "failed to launch process: {0}", status); } while
(0)
;
233 return status.ToError();
234 }
235
236 // Wait for the child process to trap on its call to execve.
237 int wstatus = 0;
238 ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0);
239 assert(wpid == pid)(static_cast <bool> (wpid == pid) ? void (0) : __assert_fail
("wpid == pid", "lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, 239, __extension__ __PRETTY_FUNCTION__))
;
240 (void)wpid;
241 if (!WIFSTOPPED(wstatus)(((wstatus) & 0xff) == 0x7f)) {
242 LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "Could not sync with inferior process: wstatus={1}"
, WaitStatus::Decode(wstatus)); } while (0)
243 WaitStatus::Decode(wstatus))do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "Could not sync with inferior process: wstatus={1}"
, WaitStatus::Decode(wstatus)); } while (0)
;
244 return llvm::make_error<StringError>("Could not sync with inferior process",
245 llvm::inconvertibleErrorCode());
246 }
247 LLDB_LOG(log, "inferior started, now in stopped state")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "inferior started, now in stopped state"); } while
(0)
;
248
249 status = SetDefaultPtraceOpts(pid);
250 if (status.Fail()) {
251 LLDB_LOG(log, "failed to set default ptrace options: {0}", status)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "failed to set default ptrace options: {0}", status
); } while (0)
;
252 return status.ToError();
253 }
254
255 llvm::Expected<ArchSpec> arch_or =
256 NativeRegisterContextLinux::DetermineArchitecture(pid);
257 if (!arch_or)
258 return arch_or.takeError();
259
260 return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
261 pid, launch_info.GetPTY().ReleasePrimaryFileDescriptor(), native_delegate,
262 *arch_or, mainloop, {pid}));
263}
264
265llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
266NativeProcessLinux::Factory::Attach(
267 lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
268 MainLoop &mainloop) const {
269 Log *log = GetLog(POSIXLog::Process);
270 LLDB_LOG(log, "pid = {0:x}", pid)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid = {0:x}", pid); } while (0)
;
271
272 auto tids_or = NativeProcessLinux::Attach(pid);
273 if (!tids_or)
274 return tids_or.takeError();
275 ArrayRef<::pid_t> tids = *tids_or;
276 llvm::Expected<ArchSpec> arch_or =
277 NativeRegisterContextLinux::DetermineArchitecture(tids[0]);
278 if (!arch_or)
279 return arch_or.takeError();
280
281 return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
282 pid, -1, native_delegate, *arch_or, mainloop, tids));
283}
284
285NativeProcessLinux::Extension
286NativeProcessLinux::Factory::GetSupportedExtensions() const {
287 NativeProcessLinux::Extension supported =
288 Extension::multiprocess | Extension::fork | Extension::vfork |
289 Extension::pass_signals | Extension::auxv | Extension::libraries_svr4 |
290 Extension::siginfo_read;
291
292#ifdef __aarch64__
293 // At this point we do not have a process so read auxv directly.
294 if ((getauxval(AT_HWCAP2) & HWCAP2_MTE(1 << 18)))
295 supported |= Extension::memory_tagging;
296#endif
297
298 return supported;
299}
300
301// Public Instance Methods
302
303NativeProcessLinux::NativeProcessLinux(::pid_t pid, int terminal_fd,
304 NativeDelegate &delegate,
305 const ArchSpec &arch, MainLoop &mainloop,
306 llvm::ArrayRef<::pid_t> tids)
307 : NativeProcessELF(pid, terminal_fd, delegate), m_arch(arch),
308 m_main_loop(mainloop), m_intel_pt_collector(*this) {
309 if (m_terminal_fd != -1) {
310 Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK04000);
311 assert(status.Success())(static_cast <bool> (status.Success()) ? void (0) : __assert_fail
("status.Success()", "lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, 311, __extension__ __PRETTY_FUNCTION__))
;
312 }
313
314 Status status;
315 m_sigchld_handle = mainloop.RegisterSignal(
316 SIGCHLD17, [this](MainLoopBase &) { SigchldHandler(); }, status);
317 assert(m_sigchld_handle && status.Success())(static_cast <bool> (m_sigchld_handle && status
.Success()) ? void (0) : __assert_fail ("m_sigchld_handle && status.Success()"
, "lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp",
317, __extension__ __PRETTY_FUNCTION__))
;
318
319 for (const auto &tid : tids) {
320 NativeThreadLinux &thread = AddThread(tid, /*resume*/ false);
321 ThreadWasCreated(thread);
322 }
323
324 // Let our process instance know the thread has stopped.
325 SetCurrentThreadID(tids[0]);
326 SetState(StateType::eStateStopped, false);
327
328 // Proccess any signals we received before installing our handler
329 SigchldHandler();
330}
331
332llvm::Expected<std::vector<::pid_t>> NativeProcessLinux::Attach(::pid_t pid) {
333 Log *log = GetLog(POSIXLog::Process);
334
335 Status status;
336 // Use a map to keep track of the threads which we have attached/need to
337 // attach.
338 Host::TidMap tids_to_attach;
339 while (Host::FindProcessThreads(pid, tids_to_attach)) {
340 for (Host::TidMap::iterator it = tids_to_attach.begin();
341 it != tids_to_attach.end();) {
342 if (it->second == false) {
343 lldb::tid_t tid = it->first;
344
345 // Attach to the requested process.
346 // An attach will cause the thread to stop with a SIGSTOP.
347 if ((status = PtraceWrapper(PTRACE_ATTACH, tid)).Fail()) {
348 // No such thread. The thread may have exited. More error handling
349 // may be needed.
350 if (status.GetError() == ESRCH3) {
351 it = tids_to_attach.erase(it);
352 continue;
353 }
354 return status.ToError();
355 }
356
357 int wpid =
358 llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, nullptr, __WALL0x40000000);
359 // Need to use __WALL otherwise we receive an error with errno=ECHLD At
360 // this point we should have a thread stopped if waitpid succeeds.
361 if (wpid < 0) {
362 // No such thread. The thread may have exited. More error handling
363 // may be needed.
364 if (errno(*__errno_location ()) == ESRCH3) {
365 it = tids_to_attach.erase(it);
366 continue;
367 }
368 return llvm::errorCodeToError(
369 std::error_code(errno(*__errno_location ()), std::generic_category()));
370 }
371
372 if ((status = SetDefaultPtraceOpts(tid)).Fail())
373 return status.ToError();
374
375 LLDB_LOG(log, "adding tid = {0}", tid)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "adding tid = {0}", tid); } while (0)
;
376 it->second = true;
377 }
378
379 // move the loop forward
380 ++it;
381 }
382 }
383
384 size_t tid_count = tids_to_attach.size();
385 if (tid_count == 0)
386 return llvm::make_error<StringError>("No such process",
387 llvm::inconvertibleErrorCode());
388
389 std::vector<::pid_t> tids;
390 tids.reserve(tid_count);
391 for (const auto &p : tids_to_attach)
392 tids.push_back(p.first);
393 return std::move(tids);
394}
395
396Status NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid) {
397 long ptrace_opts = 0;
398
399 // Have the child raise an event on exit. This is used to keep the child in
400 // limbo until it is destroyed.
401 ptrace_opts |= PTRACE_O_TRACEEXIT;
402
403 // Have the tracer trace threads which spawn in the inferior process.
404 ptrace_opts |= PTRACE_O_TRACECLONE;
405
406 // Have the tracer notify us before execve returns (needed to disable legacy
407 // SIGTRAP generation)
408 ptrace_opts |= PTRACE_O_TRACEEXEC;
409
410 // Have the tracer trace forked children.
411 ptrace_opts |= PTRACE_O_TRACEFORK;
412
413 // Have the tracer trace vforks.
414 ptrace_opts |= PTRACE_O_TRACEVFORK;
415
416 // Have the tracer trace vfork-done in order to restore breakpoints after
417 // the child finishes sharing memory.
418 ptrace_opts |= PTRACE_O_TRACEVFORKDONE;
419
420 return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void *)ptrace_opts);
421}
422
423// Handles all waitpid events from the inferior process.
424void NativeProcessLinux::MonitorCallback(NativeThreadLinux &thread,
425 WaitStatus status) {
426 Log *log = GetLog(LLDBLog::Process);
427
428 // Certain activities differ based on whether the pid is the tid of the main
429 // thread.
430 const bool is_main_thread = (thread.GetID() == GetID());
431
432 // Handle when the thread exits.
433 if (status.type == WaitStatus::Exit || status.type == WaitStatus::Signal) {
434 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "got exit status({0}) , tid = {1} ({2} main thread), process "
"state = {3}", status, thread.GetID(), is_main_thread ? "is"
: "is not", GetState()); } while (0)
435 "got exit status({0}) , tid = {1} ({2} main thread), process "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "got exit status({0}) , tid = {1} ({2} main thread), process "
"state = {3}", status, thread.GetID(), is_main_thread ? "is"
: "is not", GetState()); } while (0)
436 "state = {3}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "got exit status({0}) , tid = {1} ({2} main thread), process "
"state = {3}", status, thread.GetID(), is_main_thread ? "is"
: "is not", GetState()); } while (0)
437 status, thread.GetID(), is_main_thread ? "is" : "is not",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "got exit status({0}) , tid = {1} ({2} main thread), process "
"state = {3}", status, thread.GetID(), is_main_thread ? "is"
: "is not", GetState()); } while (0)
438 GetState())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "got exit status({0}) , tid = {1} ({2} main thread), process "
"state = {3}", status, thread.GetID(), is_main_thread ? "is"
: "is not", GetState()); } while (0)
;
439
440 // This is a thread that exited. Ensure we're not tracking it anymore.
441 StopTrackingThread(thread);
442
443 assert(!is_main_thread && "Main thread exits handled elsewhere")(static_cast <bool> (!is_main_thread && "Main thread exits handled elsewhere"
) ? void (0) : __assert_fail ("!is_main_thread && \"Main thread exits handled elsewhere\""
, "lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp",
443, __extension__ __PRETTY_FUNCTION__))
;
444 return;
445 }
446
447 siginfo_t info;
448 const auto info_err = GetSignalInfo(thread.GetID(), &info);
449
450 // Get details on the signal raised.
451 if (info_err.Success()) {
452 // We have retrieved the signal info. Dispatch appropriately.
453 if (info.si_signo == SIGTRAP5)
454 MonitorSIGTRAP(info, thread);
455 else
456 MonitorSignal(info, thread);
457 } else {
458 if (info_err.GetError() == EINVAL22) {
459 // This is a group stop reception for this tid. We can reach here if we
460 // reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the tracee,
461 // triggering the group-stop mechanism. Normally receiving these would
462 // stop the process, pending a SIGCONT. Simulating this state in a
463 // debugger is hard and is generally not needed (one use case is
464 // debugging background task being managed by a shell). For general use,
465 // it is sufficient to stop the process in a signal-delivery stop which
466 // happens before the group stop. This done by MonitorSignal and works
467 // correctly for all signals.
468 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received a group stop for pid {0} tid {1}. Transparent "
"handling of group stops not supported, resuming the " "thread."
, GetID(), thread.GetID()); } while (0)
469 "received a group stop for pid {0} tid {1}. Transparent "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received a group stop for pid {0} tid {1}. Transparent "
"handling of group stops not supported, resuming the " "thread."
, GetID(), thread.GetID()); } while (0)
470 "handling of group stops not supported, resuming the "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received a group stop for pid {0} tid {1}. Transparent "
"handling of group stops not supported, resuming the " "thread."
, GetID(), thread.GetID()); } while (0)
471 "thread.",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received a group stop for pid {0} tid {1}. Transparent "
"handling of group stops not supported, resuming the " "thread."
, GetID(), thread.GetID()); } while (0)
472 GetID(), thread.GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received a group stop for pid {0} tid {1}. Transparent "
"handling of group stops not supported, resuming the " "thread."
, GetID(), thread.GetID()); } while (0)
;
473 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER(2147483647));
474 } else {
475 // ptrace(GETSIGINFO) failed (but not due to group-stop).
476
477 // A return value of ESRCH means the thread/process has died in the mean
478 // time. This can (e.g.) happen when another thread does an exit_group(2)
479 // or the entire process get SIGKILLed.
480 // We can't do anything with this thread anymore, but we keep it around
481 // until we get the WIFEXITED event.
482
483 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "GetSignalInfo({0}) failed: {1}, status = {2}, main_thread = "
"{3}. Expecting WIFEXITED soon.", thread.GetID(), info_err, status
, is_main_thread); } while (0)
484 "GetSignalInfo({0}) failed: {1}, status = {2}, main_thread = "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "GetSignalInfo({0}) failed: {1}, status = {2}, main_thread = "
"{3}. Expecting WIFEXITED soon.", thread.GetID(), info_err, status
, is_main_thread); } while (0)
485 "{3}. Expecting WIFEXITED soon.",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "GetSignalInfo({0}) failed: {1}, status = {2}, main_thread = "
"{3}. Expecting WIFEXITED soon.", thread.GetID(), info_err, status
, is_main_thread); } while (0)
486 thread.GetID(), info_err, status, is_main_thread)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "GetSignalInfo({0}) failed: {1}, status = {2}, main_thread = "
"{3}. Expecting WIFEXITED soon.", thread.GetID(), info_err, status
, is_main_thread); } while (0)
;
487 }
488 }
489}
490
491void NativeProcessLinux::WaitForCloneNotification(::pid_t pid) {
492 Log *log = GetLog(POSIXLog::Process);
493
494 // The PID is not tracked yet, let's wait for it to appear.
495 int status = -1;
496 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received clone event for pid {0}. pid not tracked yet, "
"waiting for it to appear...", pid); } while (0)
497 "received clone event for pid {0}. pid not tracked yet, "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received clone event for pid {0}. pid not tracked yet, "
"waiting for it to appear...", pid); } while (0)
498 "waiting for it to appear...",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received clone event for pid {0}. pid not tracked yet, "
"waiting for it to appear...", pid); } while (0)
499 pid)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received clone event for pid {0}. pid not tracked yet, "
"waiting for it to appear...", pid); } while (0)
;
500 ::pid_t wait_pid =
501 llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &status, __WALL0x40000000);
502
503 // It's theoretically possible to get other events if the entire process was
504 // SIGKILLed before we got a chance to check this. In that case, we'll just
505 // clean everything up when we get the process exit event.
506
507 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "waitpid({0}, &status, __WALL) => {1} (errno: {2}, status = {3})"
, pid, wait_pid, (*__errno_location ()), WaitStatus::Decode(status
)); } while (0)
508 "waitpid({0}, &status, __WALL) => {1} (errno: {2}, status = {3})",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "waitpid({0}, &status, __WALL) => {1} (errno: {2}, status = {3})"
, pid, wait_pid, (*__errno_location ()), WaitStatus::Decode(status
)); } while (0)
509 pid, wait_pid, errno, WaitStatus::Decode(status))do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "waitpid({0}, &status, __WALL) => {1} (errno: {2}, status = {3})"
, pid, wait_pid, (*__errno_location ()), WaitStatus::Decode(status
)); } while (0)
;
510}
511
512void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info,
513 NativeThreadLinux &thread) {
514 Log *log = GetLog(POSIXLog::Process);
515 const bool is_main_thread = (thread.GetID() == GetID());
516
517 assert(info.si_signo == SIGTRAP && "Unexpected child signal!")(static_cast <bool> (info.si_signo == 5 && "Unexpected child signal!"
) ? void (0) : __assert_fail ("info.si_signo == SIGTRAP && \"Unexpected child signal!\""
, "lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp",
517, __extension__ __PRETTY_FUNCTION__))
;
518
519 switch (info.si_code) {
520 case (SIGTRAP5 | (PTRACE_EVENT_FORK << 8)):
521 case (SIGTRAP5 | (PTRACE_EVENT_VFORK << 8)):
522 case (SIGTRAP5 | (PTRACE_EVENT_CLONE << 8)): {
523 // This can either mean a new thread or a new process spawned via
524 // clone(2) without SIGCHLD or CLONE_VFORK flag. Note that clone(2)
525 // can also cause PTRACE_EVENT_FORK and PTRACE_EVENT_VFORK if one
526 // of these flags are passed.
527
528 unsigned long event_message = 0;
529 if (GetEventMessage(thread.GetID(), &event_message).Fail()) {
530 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0} received clone() event but GetEventMessage failed "
"so we don't know the new pid/tid", thread.GetID()); } while
(0)
531 "pid {0} received clone() event but GetEventMessage failed "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0} received clone() event but GetEventMessage failed "
"so we don't know the new pid/tid", thread.GetID()); } while
(0)
532 "so we don't know the new pid/tid",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0} received clone() event but GetEventMessage failed "
"so we don't know the new pid/tid", thread.GetID()); } while
(0)
533 thread.GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0} received clone() event but GetEventMessage failed "
"so we don't know the new pid/tid", thread.GetID()); } while
(0)
;
534 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER(2147483647));
535 } else {
536 MonitorClone(thread, event_message, info.si_code >> 8);
537 }
538
539 break;
540 }
541
542 case (SIGTRAP5 | (PTRACE_EVENT_EXEC << 8)): {
543 LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received exec event, code = {0}", info.si_code ^
5); } while (0)
;
544
545 // Exec clears any pending notifications.
546 m_pending_notification_tid = LLDB_INVALID_THREAD_ID0;
547
548 // Remove all but the main thread here. Linux fork creates a new process
549 // which only copies the main thread.
550 LLDB_LOG(log, "exec received, stop tracking all but main thread")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "exec received, stop tracking all but main thread"
); } while (0)
;
551
552 llvm::erase_if(m_threads, [&](std::unique_ptr<NativeThreadProtocol> &t) {
553 return t->GetID() != GetID();
554 });
555 assert(m_threads.size() == 1)(static_cast <bool> (m_threads.size() == 1) ? void (0) :
__assert_fail ("m_threads.size() == 1", "lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, 555, __extension__ __PRETTY_FUNCTION__))
;
556 auto *main_thread = static_cast<NativeThreadLinux *>(m_threads[0].get());
557
558 SetCurrentThreadID(main_thread->GetID());
559 main_thread->SetStoppedByExec();
560
561 // Tell coordinator about about the "new" (since exec) stopped main thread.
562 ThreadWasCreated(*main_thread);
563
564 // Let our delegate know we have just exec'd.
565 NotifyDidExec();
566
567 // Let the process know we're stopped.
568 StopRunningThreads(main_thread->GetID());
569
570 break;
571 }
572
573 case (SIGTRAP5 | (PTRACE_EVENT_EXIT << 8)): {
574 // The inferior process or one of its threads is about to exit. We don't
575 // want to do anything with the thread so we just resume it. In case we
576 // want to implement "break on thread exit" functionality, we would need to
577 // stop here.
578
579 unsigned long data = 0;
580 if (GetEventMessage(thread.GetID(), &data).Fail())
581 data = -1;
582
583 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
"WIFSIGNALED={2}, pid = {3}, main_thread = {4}", data, (((data
) & 0x7f) == 0), (((signed char) (((data) & 0x7f) + 1
) >> 1) > 0), thread.GetID(), is_main_thread); } while
(0)
584 "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
"WIFSIGNALED={2}, pid = {3}, main_thread = {4}", data, (((data
) & 0x7f) == 0), (((signed char) (((data) & 0x7f) + 1
) >> 1) > 0), thread.GetID(), is_main_thread); } while
(0)
585 "WIFSIGNALED={2}, pid = {3}, main_thread = {4}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
"WIFSIGNALED={2}, pid = {3}, main_thread = {4}", data, (((data
) & 0x7f) == 0), (((signed char) (((data) & 0x7f) + 1
) >> 1) > 0), thread.GetID(), is_main_thread); } while
(0)
586 data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(),do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
"WIFSIGNALED={2}, pid = {3}, main_thread = {4}", data, (((data
) & 0x7f) == 0), (((signed char) (((data) & 0x7f) + 1
) >> 1) > 0), thread.GetID(), is_main_thread); } while
(0)
587 is_main_thread)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
"WIFSIGNALED={2}, pid = {3}, main_thread = {4}", data, (((data
) & 0x7f) == 0), (((signed char) (((data) & 0x7f) + 1
) >> 1) > 0), thread.GetID(), is_main_thread); } while
(0)
;
588
589
590 StateType state = thread.GetState();
591 if (!StateIsRunningState(state)) {
592 // Due to a kernel bug, we may sometimes get this stop after the inferior
593 // gets a SIGKILL. This confuses our state tracking logic in
594 // ResumeThread(), since normally, we should not be receiving any ptrace
595 // events while the inferior is stopped. This makes sure that the
596 // inferior is resumed and exits normally.
597 state = eStateRunning;
598 }
599 ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER(2147483647));
600
601 if (is_main_thread) {
602 // Main thread report the read (WIFEXITED) event only after all threads in
603 // the process exit, so we need to stop tracking it here instead of in
604 // MonitorCallback
605 StopTrackingThread(thread);
606 }
607
608 break;
609 }
610
611 case (SIGTRAP5 | (PTRACE_EVENT_VFORK_DONE << 8)): {
612 if (bool(m_enabled_extensions & Extension::vfork)) {
613 thread.SetStoppedByVForkDone();
614 StopRunningThreads(thread.GetID());
615 }
616 else
617 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER(2147483647));
618 break;
619 }
620
621 case 0:
622 case TRAP_TRACETRAP_TRACE: // We receive this on single stepping.
623 case TRAP_HWBKPTTRAP_HWBKPT: // We receive this on watchpoint hit
624 {
625 // If a watchpoint was hit, report it
626 uint32_t wp_index;
627 Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
628 wp_index, (uintptr_t)info.si_addr_sifields._sigfault.si_addr);
629 if (error.Fail())
630 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received error while checking for watchpoint hits, pid = "
"{0}, error = {1}", thread.GetID(), error); } while (0)
631 "received error while checking for watchpoint hits, pid = "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received error while checking for watchpoint hits, pid = "
"{0}, error = {1}", thread.GetID(), error); } while (0)
632 "{0}, error = {1}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received error while checking for watchpoint hits, pid = "
"{0}, error = {1}", thread.GetID(), error); } while (0)
633 thread.GetID(), error)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received error while checking for watchpoint hits, pid = "
"{0}, error = {1}", thread.GetID(), error); } while (0)
;
634 if (wp_index != LLDB_INVALID_INDEX32(4294967295U)) {
635 MonitorWatchpoint(thread, wp_index);
636 break;
637 }
638
639 // If a breakpoint was hit, report it
640 uint32_t bp_index;
641 error = thread.GetRegisterContext().GetHardwareBreakHitIndex(
642 bp_index, (uintptr_t)info.si_addr_sifields._sigfault.si_addr);
643 if (error.Fail())
644 LLDB_LOG(log, "received error while checking for hardware "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received error while checking for hardware " "breakpoint hits, pid = {0}, error = {1}"
, thread.GetID(), error); } while (0)
645 "breakpoint hits, pid = {0}, error = {1}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received error while checking for hardware " "breakpoint hits, pid = {0}, error = {1}"
, thread.GetID(), error); } while (0)
646 thread.GetID(), error)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received error while checking for hardware " "breakpoint hits, pid = {0}, error = {1}"
, thread.GetID(), error); } while (0)
;
647 if (bp_index != LLDB_INVALID_INDEX32(4294967295U)) {
648 MonitorBreakpoint(thread);
649 break;
650 }
651
652 // Otherwise, report step over
653 MonitorTrace(thread);
654 break;
655 }
656
657 case SI_KERNELSI_KERNEL:
658#if defined __mips__
659 // For mips there is no special signal for watchpoint So we check for
660 // watchpoint in kernel trap
661 {
662 // If a watchpoint was hit, report it
663 uint32_t wp_index;
664 Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
665 wp_index, LLDB_INVALID_ADDRESS(18446744073709551615UL));
666 if (error.Fail())
667 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received error while checking for watchpoint hits, pid = "
"{0}, error = {1}", thread.GetID(), error); } while (0)
668 "received error while checking for watchpoint hits, pid = "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received error while checking for watchpoint hits, pid = "
"{0}, error = {1}", thread.GetID(), error); } while (0)
669 "{0}, error = {1}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received error while checking for watchpoint hits, pid = "
"{0}, error = {1}", thread.GetID(), error); } while (0)
670 thread.GetID(), error)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received error while checking for watchpoint hits, pid = "
"{0}, error = {1}", thread.GetID(), error); } while (0)
;
671 if (wp_index != LLDB_INVALID_INDEX32(4294967295U)) {
672 MonitorWatchpoint(thread, wp_index);
673 break;
674 }
675 }
676// NO BREAK
677#endif
678 case TRAP_BRKPTTRAP_BRKPT:
679 MonitorBreakpoint(thread);
680 break;
681
682 case SIGTRAP5:
683 case (SIGTRAP5 | 0x80):
684 LLDB_LOG(do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming"
, info.si_code, GetID(), thread.GetID()); } while (0)
685 log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming"
, info.si_code, GetID(), thread.GetID()); } while (0)
686 "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming"
, info.si_code, GetID(), thread.GetID()); } while (0)
687 info.si_code, GetID(), thread.GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming"
, info.si_code, GetID(), thread.GetID()); } while (0)
;
688
689 // Ignore these signals until we know more about them.
690 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER(2147483647));
691 break;
692
693 default:
694 LLDB_LOG(log, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}"
, info.si_code, GetID(), thread.GetID()); } while (0)
695 info.si_code, GetID(), thread.GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}"
, info.si_code, GetID(), thread.GetID()); } while (0)
;
696 MonitorSignal(info, thread);
697 break;
698 }
699}
700
701void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) {
702 Log *log = GetLog(POSIXLog::Process);
703 LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received trace event, pid = {0}", thread.GetID()
); } while (0)
;
704
705 // This thread is currently stopped.
706 thread.SetStoppedByTrace();
707
708 StopRunningThreads(thread.GetID());
709}
710
711void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) {
712 Log *log = GetLog(LLDBLog::Process | LLDBLog::Breakpoints);
713 LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received breakpoint event, pid = {0}", thread.GetID
()); } while (0)
;
714
715 // Mark the thread as stopped at breakpoint.
716 thread.SetStoppedByBreakpoint();
717 FixupBreakpointPCAsNeeded(thread);
718
719 if (m_threads_stepping_with_breakpoint.find(thread.GetID()) !=
720 m_threads_stepping_with_breakpoint.end())
721 thread.SetStoppedByTrace();
722
723 StopRunningThreads(thread.GetID());
724}
725
726void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread,
727 uint32_t wp_index) {
728 Log *log = GetLog(LLDBLog::Process | LLDBLog::Watchpoints);
729 LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received watchpoint event, pid = {0}, wp_index = {1}"
, thread.GetID(), wp_index); } while (0)
730 thread.GetID(), wp_index)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received watchpoint event, pid = {0}, wp_index = {1}"
, thread.GetID(), wp_index); } while (0)
;
731
732 // Mark the thread as stopped at watchpoint. The address is at
733 // (lldb::addr_t)info->si_addr if we need it.
734 thread.SetStoppedByWatchpoint(wp_index);
735
736 // We need to tell all other running threads before we notify the delegate
737 // about this stop.
738 StopRunningThreads(thread.GetID());
739}
740
741void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
742 NativeThreadLinux &thread) {
743 const int signo = info.si_signo;
744 const bool is_from_llgs = info.si_pid_sifields._kill.si_pid == getpid();
745
746 Log *log = GetLog(POSIXLog::Process);
747
748 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
749 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a kill(2)
750 // or raise(3). Similarly for tgkill(2) on Linux.
751 //
752 // IOW, user generated signals never generate what we consider to be a
753 // "crash".
754 //
755 // Similarly, ACK signals generated by this monitor.
756
757 // Handle the signal.
758 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
"waitpid pid = {4})", Host::GetSignalAsCString(signo), signo
, info.si_code, thread.GetID()); } while (0)
759 "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
"waitpid pid = {4})", Host::GetSignalAsCString(signo), signo
, info.si_code, thread.GetID()); } while (0)
760 "waitpid pid = {4})",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
"waitpid pid = {4})", Host::GetSignalAsCString(signo), signo
, info.si_code, thread.GetID()); } while (0)
761 Host::GetSignalAsCString(signo), signo, info.si_code,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
"waitpid pid = {4})", Host::GetSignalAsCString(signo), signo
, info.si_code, thread.GetID()); } while (0)
762 thread.GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
"waitpid pid = {4})", Host::GetSignalAsCString(signo), signo
, info.si_code, thread.GetID()); } while (0)
;
763
764 // Check for thread stop notification.
765 if (is_from_llgs && (info.si_code == SI_TKILLSI_TKILL) && (signo == SIGSTOP19)) {
766 // This is a tgkill()-based stop.
767 LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0} tid {1}, thread stopped", GetID(), thread
.GetID()); } while (0)
;
768
769 // Check that we're not already marked with a stop reason. Note this thread
770 // really shouldn't already be marked as stopped - if we were, that would
771 // imply that the kernel signaled us with the thread stopping which we
772 // handled and marked as stopped, and that, without an intervening resume,
773 // we received another stop. It is more likely that we are missing the
774 // marking of a run state somewhere if we find that the thread was marked
775 // as stopped.
776 const StateType thread_state = thread.GetState();
777 if (!StateIsStoppedState(thread_state, false)) {
778 // An inferior thread has stopped because of a SIGSTOP we have sent it.
779 // Generally, these are not important stops and we don't want to report
780 // them as they are just used to stop other threads when one thread (the
781 // one with the *real* stop reason) hits a breakpoint (watchpoint,
782 // etc...). However, in the case of an asynchronous Interrupt(), this
783 // *is* the real stop reason, so we leave the signal intact if this is
784 // the thread that was chosen as the triggering thread.
785 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID0) {
786 if (m_pending_notification_tid == thread.GetID())
787 thread.SetStoppedBySignal(SIGSTOP19, &info);
788 else
789 thread.SetStoppedWithNoReason();
790
791 SetCurrentThreadID(thread.GetID());
792 SignalIfAllThreadsStopped();
793 } else {
794 // We can end up here if stop was initiated by LLGS but by this time a
795 // thread stop has occurred - maybe initiated by another event.
796 Status error = ResumeThread(thread, thread.GetState(), 0);
797 if (error.Fail())
798 LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(),do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "failed to resume thread {0}: {1}", thread.GetID(
), error); } while (0)
799 error)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "failed to resume thread {0}: {1}", thread.GetID(
), error); } while (0)
;
800 }
801 } else {
802 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0} tid {1}, thread was already marked as a stopped "
"state (state={2}), leaving stop signal as is", GetID(), thread
.GetID(), thread_state); } while (0)
803 "pid {0} tid {1}, thread was already marked as a stopped "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0} tid {1}, thread was already marked as a stopped "
"state (state={2}), leaving stop signal as is", GetID(), thread
.GetID(), thread_state); } while (0)
804 "state (state={2}), leaving stop signal as is",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0} tid {1}, thread was already marked as a stopped "
"state (state={2}), leaving stop signal as is", GetID(), thread
.GetID(), thread_state); } while (0)
805 GetID(), thread.GetID(), thread_state)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0} tid {1}, thread was already marked as a stopped "
"state (state={2}), leaving stop signal as is", GetID(), thread
.GetID(), thread_state); } while (0)
;
806 SignalIfAllThreadsStopped();
807 }
808
809 // Done handling.
810 return;
811 }
812
813 // Check if debugger should stop at this signal or just ignore it and resume
814 // the inferior.
815 if (m_signals_to_ignore.contains(signo)) {
816 ResumeThread(thread, thread.GetState(), signo);
817 return;
818 }
819
820 // This thread is stopped.
821 LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo))do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "received signal {0}", Host::GetSignalAsCString(signo
)); } while (0)
;
822 thread.SetStoppedBySignal(signo, &info);
823
824 // Send a stop to the debugger after we get all other threads to stop.
825 StopRunningThreads(thread.GetID());
826}
827
828bool NativeProcessLinux::MonitorClone(NativeThreadLinux &parent,
829 lldb::pid_t child_pid, int event) {
830 Log *log = GetLog(POSIXLog::Process);
831 LLDB_LOG(log, "parent_tid={0}, child_pid={1}, event={2}", parent.GetID(),do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "parent_tid={0}, child_pid={1}, event={2}", parent
.GetID(), child_pid, event); } while (0)
832 child_pid, event)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "parent_tid={0}, child_pid={1}, event={2}", parent
.GetID(), child_pid, event); } while (0)
;
833
834 WaitForCloneNotification(child_pid);
835
836 switch (event) {
837 case PTRACE_EVENT_CLONE: {
838 // PTRACE_EVENT_CLONE can either mean a new thread or a new process.
839 // Try to grab the new process' PGID to figure out which one it is.
840 // If PGID is the same as the PID, then it's a new process. Otherwise,
841 // it's a thread.
842 auto tgid_ret = getPIDForTID(child_pid);
843 if (tgid_ret != child_pid) {
844 // A new thread should have PGID matching our process' PID.
845 assert(!tgid_ret || *tgid_ret == GetID())(static_cast <bool> (!tgid_ret || *tgid_ret == GetID())
? void (0) : __assert_fail ("!tgid_ret || *tgid_ret == GetID()"
, "lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp",
845, __extension__ __PRETTY_FUNCTION__))
;
846
847 NativeThreadLinux &child_thread = AddThread(child_pid, /*resume*/ true);
848 ThreadWasCreated(child_thread);
849
850 // Resume the parent.
851 ResumeThread(parent, parent.GetState(), LLDB_INVALID_SIGNAL_NUMBER(2147483647));
852 break;
853 }
854 }
855 [[fallthrough]];
856 case PTRACE_EVENT_FORK:
857 case PTRACE_EVENT_VFORK: {
858 bool is_vfork = event == PTRACE_EVENT_VFORK;
859 std::unique_ptr<NativeProcessLinux> child_process{new NativeProcessLinux(
860 static_cast<::pid_t>(child_pid), m_terminal_fd, m_delegate, m_arch,
861 m_main_loop, {static_cast<::pid_t>(child_pid)})};
862 if (!is_vfork)
863 child_process->m_software_breakpoints = m_software_breakpoints;
864
865 Extension expected_ext = is_vfork ? Extension::vfork : Extension::fork;
866 if (bool(m_enabled_extensions & expected_ext)) {
867 m_delegate.NewSubprocess(this, std::move(child_process));
868 // NB: non-vfork clone() is reported as fork
869 parent.SetStoppedByFork(is_vfork, child_pid);
870 StopRunningThreads(parent.GetID());
871 } else {
872 child_process->Detach();
873 ResumeThread(parent, parent.GetState(), LLDB_INVALID_SIGNAL_NUMBER(2147483647));
874 }
875 break;
876 }
877 default:
878 llvm_unreachable("unknown clone_info.event")::llvm::llvm_unreachable_internal("unknown clone_info.event",
"lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp", 878
)
;
879 }
880
881 return true;
882}
883
884bool NativeProcessLinux::SupportHardwareSingleStepping() const {
885 if (m_arch.IsMIPS() || m_arch.GetMachine() == llvm::Triple::arm ||
886 m_arch.GetTriple().isRISCV())
887 return false;
888 return true;
889}
890
891Status NativeProcessLinux::Resume(const ResumeActionList &resume_actions) {
892 Log *log = GetLog(POSIXLog::Process);
893 LLDB_LOG(log, "pid {0}", GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0}", GetID()); } while (0)
;
894
895 NotifyTracersProcessWillResume();
896
897 bool software_single_step = !SupportHardwareSingleStepping();
898
899 if (software_single_step) {
900 for (const auto &thread : m_threads) {
901 assert(thread && "thread list should not contain NULL threads")(static_cast <bool> (thread && "thread list should not contain NULL threads"
) ? void (0) : __assert_fail ("thread && \"thread list should not contain NULL threads\""
, "lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp",
901, __extension__ __PRETTY_FUNCTION__))
;
902
903 const ResumeAction *const action =
904 resume_actions.GetActionForThread(thread->GetID(), true);
905 if (action == nullptr)
906 continue;
907
908 if (action->state == eStateStepping) {
909 Status error = SetupSoftwareSingleStepping(
910 static_cast<NativeThreadLinux &>(*thread));
911 if (error.Fail())
912 return error;
913 }
914 }
915 }
916
917 for (const auto &thread : m_threads) {
918 assert(thread && "thread list should not contain NULL threads")(static_cast <bool> (thread && "thread list should not contain NULL threads"
) ? void (0) : __assert_fail ("thread && \"thread list should not contain NULL threads\""
, "lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp",
918, __extension__ __PRETTY_FUNCTION__))
;
919
920 const ResumeAction *const action =
921 resume_actions.GetActionForThread(thread->GetID(), true);
922
923 if (action == nullptr) {
924 LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "no action specified for pid {0} tid {1}", GetID(
), thread->GetID()); } while (0)
925 thread->GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "no action specified for pid {0} tid {1}", GetID(
), thread->GetID()); } while (0)
;
926 continue;
927 }
928
929 LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "processing resume action state {0} for pid {1} tid {2}"
, action->state, GetID(), thread->GetID()); } while (0)
930 action->state, GetID(), thread->GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "processing resume action state {0} for pid {1} tid {2}"
, action->state, GetID(), thread->GetID()); } while (0)
;
931
932 switch (action->state) {
933 case eStateRunning:
934 case eStateStepping: {
935 // Run the thread, possibly feeding it the signal.
936 const int signo = action->signal;
937 Status error = ResumeThread(static_cast<NativeThreadLinux &>(*thread),
938 action->state, signo);
939 if (error.Fail())
940 return Status("NativeProcessLinux::%s: failed to resume thread "
941 "for pid %" PRIu64"l" "u" ", tid %" PRIu64"l" "u" ", error = %s",
942 __FUNCTION__, GetID(), thread->GetID(),
943 error.AsCString());
944
945 break;
946 }
947
948 case eStateSuspended:
949 case eStateStopped:
950 break;
951
952 default:
953 return Status("NativeProcessLinux::%s (): unexpected state %s specified "
954 "for pid %" PRIu64"l" "u" ", tid %" PRIu64"l" "u",
955 __FUNCTION__, StateAsCString(action->state), GetID(),
956 thread->GetID());
957 }
958 }
959
960 return Status();
961}
962
963Status NativeProcessLinux::Halt() {
964 Status error;
965
966 if (kill(GetID(), SIGSTOP19) != 0)
967 error.SetErrorToErrno();
968
969 return error;
970}
971
972Status NativeProcessLinux::Detach() {
973 Status error;
974
975 // Stop monitoring the inferior.
976 m_sigchld_handle.reset();
977
978 // Tell ptrace to detach from the process.
979 if (GetID() == LLDB_INVALID_PROCESS_ID0)
980 return error;
981
982 for (const auto &thread : m_threads) {
983 Status e = Detach(thread->GetID());
984 if (e.Fail())
985 error =
986 e; // Save the error, but still attempt to detach from other threads.
987 }
988
989 m_intel_pt_collector.Clear();
990
991 return error;
992}
993
994Status NativeProcessLinux::Signal(int signo) {
995 Status error;
996
997 Log *log = GetLog(POSIXLog::Process);
998 LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "sending signal {0} ({1}) to pid {1}", signo, Host
::GetSignalAsCString(signo), GetID()); } while (0)
999 Host::GetSignalAsCString(signo), GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "sending signal {0} ({1}) to pid {1}", signo, Host
::GetSignalAsCString(signo), GetID()); } while (0)
;
1000
1001 if (kill(GetID(), signo))
1002 error.SetErrorToErrno();
1003
1004 return error;
1005}
1006
1007Status NativeProcessLinux::Interrupt() {
1008 // Pick a running thread (or if none, a not-dead stopped thread) as the
1009 // chosen thread that will be the stop-reason thread.
1010 Log *log = GetLog(POSIXLog::Process);
1011
1012 NativeThreadProtocol *running_thread = nullptr;
1013 NativeThreadProtocol *stopped_thread = nullptr;
1014
1015 LLDB_LOG(log, "selecting running thread for interrupt target")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "selecting running thread for interrupt target");
} while (0)
;
1016 for (const auto &thread : m_threads) {
1017 // If we have a running or stepping thread, we'll call that the target of
1018 // the interrupt.
1019 const auto thread_state = thread->GetState();
1020 if (thread_state == eStateRunning || thread_state == eStateStepping) {
1021 running_thread = thread.get();
1022 break;
1023 } else if (!stopped_thread && StateIsStoppedState(thread_state, true)) {
1024 // Remember the first non-dead stopped thread. We'll use that as a
1025 // backup if there are no running threads.
1026 stopped_thread = thread.get();
1027 }
1028 }
1029
1030 if (!running_thread && !stopped_thread) {
1031 Status error("found no running/stepping or live stopped threads as target "
1032 "for interrupt");
1033 LLDB_LOG(log, "skipping due to error: {0}", error)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "skipping due to error: {0}", error); } while (0)
;
1034
1035 return error;
1036 }
1037
1038 NativeThreadProtocol *deferred_signal_thread =
1039 running_thread ? running_thread : stopped_thread;
1040
1041 LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(),do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0} {1} tid {2} chosen for interrupt target"
, GetID(), running_thread ? "running" : "stopped", deferred_signal_thread
->GetID()); } while (0)
1042 running_thread ? "running" : "stopped",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0} {1} tid {2} chosen for interrupt target"
, GetID(), running_thread ? "running" : "stopped", deferred_signal_thread
->GetID()); } while (0)
1043 deferred_signal_thread->GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0} {1} tid {2} chosen for interrupt target"
, GetID(), running_thread ? "running" : "stopped", deferred_signal_thread
->GetID()); } while (0)
;
1044
1045 StopRunningThreads(deferred_signal_thread->GetID());
1046
1047 return Status();
1048}
1049
1050Status NativeProcessLinux::Kill() {
1051 Log *log = GetLog(POSIXLog::Process);
1052 LLDB_LOG(log, "pid {0}", GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0}", GetID()); } while (0)
;
1053
1054 Status error;
1055
1056 switch (m_state) {
1057 case StateType::eStateInvalid:
1058 case StateType::eStateExited:
1059 case StateType::eStateCrashed:
1060 case StateType::eStateDetached:
1061 case StateType::eStateUnloaded:
1062 // Nothing to do - the process is already dead.
1063 LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "ignored for PID {0} due to current state: {1}", GetID
(), m_state); } while (0)
1064 m_state)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "ignored for PID {0} due to current state: {1}", GetID
(), m_state); } while (0)
;
1065 return error;
1066
1067 case StateType::eStateConnected:
1068 case StateType::eStateAttaching:
1069 case StateType::eStateLaunching:
1070 case StateType::eStateStopped:
1071 case StateType::eStateRunning:
1072 case StateType::eStateStepping:
1073 case StateType::eStateSuspended:
1074 // We can try to kill a process in these states.
1075 break;
1076 }
1077
1078 if (kill(GetID(), SIGKILL9) != 0) {
1079 error.SetErrorToErrno();
1080 return error;
1081 }
1082
1083 return error;
1084}
1085
1086Status NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr,
1087 MemoryRegionInfo &range_info) {
1088 // FIXME review that the final memory region returned extends to the end of
1089 // the virtual address space,
1090 // with no perms if it is not mapped.
1091
1092 // Use an approach that reads memory regions from /proc/{pid}/maps. Assume
1093 // proc maps entries are in ascending order.
1094 // FIXME assert if we find differently.
1095
1096 if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
1097 // We're done.
1098 return Status("unsupported");
1099 }
1100
1101 Status error = PopulateMemoryRegionCache();
1102 if (error.Fail()) {
1103 return error;
1104 }
1105
1106 lldb::addr_t prev_base_address = 0;
1107
1108 // FIXME start by finding the last region that is <= target address using
1109 // binary search. Data is sorted.
1110 // There can be a ton of regions on pthreads apps with lots of threads.
1111 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1112 ++it) {
1113 MemoryRegionInfo &proc_entry_info = it->first;
1114
1115 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1116 assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&(static_cast <bool> ((proc_entry_info.GetRange().GetRangeBase
() >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected"
) ? void (0) : __assert_fail ("(proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) && \"descending /proc/pid/maps entries detected, unexpected\""
, "lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp",
1117, __extension__ __PRETTY_FUNCTION__))
1117 "descending /proc/pid/maps entries detected, unexpected")(static_cast <bool> ((proc_entry_info.GetRange().GetRangeBase
() >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected"
) ? void (0) : __assert_fail ("(proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) && \"descending /proc/pid/maps entries detected, unexpected\""
, "lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp",
1117, __extension__ __PRETTY_FUNCTION__))
;
1118 prev_base_address = proc_entry_info.GetRange().GetRangeBase();
1119 UNUSED_IF_ASSERT_DISABLED(prev_base_address)((void)(prev_base_address));
1120
1121 // If the target address comes before this entry, indicate distance to next
1122 // region.
1123 if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1124 range_info.GetRange().SetRangeBase(load_addr);
1125 range_info.GetRange().SetByteSize(
1126 proc_entry_info.GetRange().GetRangeBase() - load_addr);
1127 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1128 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1129 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1130 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1131
1132 return error;
1133 } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1134 // The target address is within the memory region we're processing here.
1135 range_info = proc_entry_info;
1136 return error;
1137 }
1138
1139 // The target memory address comes somewhere after the region we just
1140 // parsed.
1141 }
1142
1143 // If we made it here, we didn't find an entry that contained the given
1144 // address. Return the load_addr as start and the amount of bytes betwwen
1145 // load address and the end of the memory as size.
1146 range_info.GetRange().SetRangeBase(load_addr);
1147 range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS(18446744073709551615UL));
1148 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1149 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1150 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1151 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1152 return error;
1153}
1154
1155Status NativeProcessLinux::PopulateMemoryRegionCache() {
1156 Log *log = GetLog(POSIXLog::Process);
1157
1158 // If our cache is empty, pull the latest. There should always be at least
1159 // one memory region if memory region handling is supported.
1160 if (!m_mem_region_cache.empty()) {
1161 LLDB_LOG(log, "reusing {0} cached memory region entries",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "reusing {0} cached memory region entries", m_mem_region_cache
.size()); } while (0)
1162 m_mem_region_cache.size())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "reusing {0} cached memory region entries", m_mem_region_cache
.size()); } while (0)
;
1163 return Status();
1164 }
1165
1166 Status Result;
1167 LinuxMapCallback callback = [&](llvm::Expected<MemoryRegionInfo> Info) {
1168 if (Info) {
1169 FileSpec file_spec(Info->GetName().GetCString());
1170 FileSystem::Instance().Resolve(file_spec);
1171 m_mem_region_cache.emplace_back(*Info, file_spec);
1172 return true;
1173 }
1174
1175 Result = Info.takeError();
1176 m_supports_mem_region = LazyBool::eLazyBoolNo;
1177 LLDB_LOG(log, "failed to parse proc maps: {0}", Result)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "failed to parse proc maps: {0}", Result); } while
(0)
;
1178 return false;
1179 };
1180
1181 // Linux kernel since 2.6.14 has /proc/{pid}/smaps
1182 // if CONFIG_PROC_PAGE_MONITOR is enabled
1183 auto BufferOrError = getProcFile(GetID(), GetCurrentThreadID(), "smaps");
1184 if (BufferOrError)
1185 ParseLinuxSMapRegions(BufferOrError.get()->getBuffer(), callback);
1186 else {
1187 BufferOrError = getProcFile(GetID(), GetCurrentThreadID(), "maps");
1188 if (!BufferOrError) {
1189 m_supports_mem_region = LazyBool::eLazyBoolNo;
1190 return BufferOrError.getError();
1191 }
1192
1193 ParseLinuxMapRegions(BufferOrError.get()->getBuffer(), callback);
1194 }
1195
1196 if (Result.Fail())
1197 return Result;
1198
1199 if (m_mem_region_cache.empty()) {
1200 // No entries after attempting to read them. This shouldn't happen if
1201 // /proc/{pid}/maps is supported. Assume we don't support map entries via
1202 // procfs.
1203 m_supports_mem_region = LazyBool::eLazyBoolNo;
1204 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "failed to find any procfs maps entries, assuming no support "
"for memory region metadata retrieval"); } while (0)
1205 "failed to find any procfs maps entries, assuming no support "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "failed to find any procfs maps entries, assuming no support "
"for memory region metadata retrieval"); } while (0)
1206 "for memory region metadata retrieval")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "failed to find any procfs maps entries, assuming no support "
"for memory region metadata retrieval"); } while (0)
;
1207 return Status("not supported");
1208 }
1209
1210 LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "read {0} memory region entries from /proc/{1}/maps"
, m_mem_region_cache.size(), GetID()); } while (0)
1211 m_mem_region_cache.size(), GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "read {0} memory region entries from /proc/{1}/maps"
, m_mem_region_cache.size(), GetID()); } while (0)
;
1212
1213 // We support memory retrieval, remember that.
1214 m_supports_mem_region = LazyBool::eLazyBoolYes;
1215 return Status();
1216}
1217
1218void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
1219 Log *log = GetLog(POSIXLog::Process);
1220 LLDB_LOG(log, "newBumpId={0}", newBumpId)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "newBumpId={0}", newBumpId); } while (0)
;
1221 LLDB_LOG(log, "clearing {0} entries from memory region cache",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "clearing {0} entries from memory region cache", m_mem_region_cache
.size()); } while (0)
1222 m_mem_region_cache.size())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "clearing {0} entries from memory region cache", m_mem_region_cache
.size()); } while (0)
;
1223 m_mem_region_cache.clear();
1224}
1225
1226llvm::Expected<uint64_t>
1227NativeProcessLinux::Syscall(llvm::ArrayRef<uint64_t> args) {
1228 PopulateMemoryRegionCache();
1229 auto region_it = llvm::find_if(m_mem_region_cache, [](const auto &pair) {
1230 return pair.first.GetExecutable() == MemoryRegionInfo::eYes &&
1231 pair.first.GetShared() != MemoryRegionInfo::eYes;
1232 });
1233 if (region_it == m_mem_region_cache.end())
1234 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1235 "No executable memory region found!");
1236
1237 addr_t exe_addr = region_it->first.GetRange().GetRangeBase();
1238
1239 NativeThreadLinux &thread = *GetCurrentThread();
1240 assert(thread.GetState() == eStateStopped)(static_cast <bool> (thread.GetState() == eStateStopped
) ? void (0) : __assert_fail ("thread.GetState() == eStateStopped"
, "lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp",
1240, __extension__ __PRETTY_FUNCTION__))
;
1241 NativeRegisterContextLinux &reg_ctx = thread.GetRegisterContext();
1242
1243 NativeRegisterContextLinux::SyscallData syscall_data =
1244 *reg_ctx.GetSyscallData();
1245
1246 WritableDataBufferSP registers_sp;
1247 if (llvm::Error Err = reg_ctx.ReadAllRegisterValues(registers_sp).ToError())
1248 return std::move(Err);
1249 auto restore_regs = llvm::make_scope_exit(
1250 [&] { reg_ctx.WriteAllRegisterValues(registers_sp); });
1251
1252 llvm::SmallVector<uint8_t, 8> memory(syscall_data.Insn.size());
1253 size_t bytes_read;
1254 if (llvm::Error Err =
1255 ReadMemory(exe_addr, memory.data(), memory.size(), bytes_read)
1256 .ToError()) {
1257 return std::move(Err);
1258 }
1259
1260 auto restore_mem = llvm::make_scope_exit(
1261 [&] { WriteMemory(exe_addr, memory.data(), memory.size(), bytes_read); });
1262
1263 if (llvm::Error Err = reg_ctx.SetPC(exe_addr).ToError())
1264 return std::move(Err);
1265
1266 for (const auto &zip : llvm::zip_first(args, syscall_data.Args)) {
1267 if (llvm::Error Err =
1268 reg_ctx
1269 .WriteRegisterFromUnsigned(std::get<1>(zip), std::get<0>(zip))
1270 .ToError()) {
1271 return std::move(Err);
1272 }
1273 }
1274 if (llvm::Error Err = WriteMemory(exe_addr, syscall_data.Insn.data(),
1275 syscall_data.Insn.size(), bytes_read)
1276 .ToError())
1277 return std::move(Err);
1278
1279 m_mem_region_cache.clear();
1280
1281 // With software single stepping the syscall insn buffer must also include a
1282 // trap instruction to stop the process.
1283 int req = SupportHardwareSingleStepping() ? PTRACE_SINGLESTEP : PTRACE_CONT;
1284 if (llvm::Error Err =
1285 PtraceWrapper(req, thread.GetID(), nullptr, nullptr).ToError())
1286 return std::move(Err);
1287
1288 int status;
1289 ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, thread.GetID(),
1290 &status, __WALL0x40000000);
1291 if (wait_pid == -1) {
1292 return llvm::errorCodeToError(
1293 std::error_code(errno(*__errno_location ()), std::generic_category()));
1294 }
1295 assert((unsigned)wait_pid == thread.GetID())(static_cast <bool> ((unsigned)wait_pid == thread.GetID
()) ? void (0) : __assert_fail ("(unsigned)wait_pid == thread.GetID()"
, "lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp",
1295, __extension__ __PRETTY_FUNCTION__))
;
1296
1297 uint64_t result = reg_ctx.ReadRegisterAsUnsigned(syscall_data.Result, -ESRCH3);
1298
1299 // Values larger than this are actually negative errno numbers.
1300 uint64_t errno_threshold =
1301 (uint64_t(-1) >> (64 - 8 * m_arch.GetAddressByteSize())) - 0x1000;
1302 if (result > errno_threshold) {
1303 return llvm::errorCodeToError(
1304 std::error_code(-result & 0xfff, std::generic_category()));
1305 }
1306
1307 return result;
1308}
1309
1310llvm::Expected<addr_t>
1311NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions) {
1312
1313 llvm::Optional<NativeRegisterContextLinux::MmapData> mmap_data =
1314 GetCurrentThread()->GetRegisterContext().GetMmapData();
1315 if (!mmap_data)
1316 return llvm::make_error<UnimplementedError>();
1317
1318 unsigned prot = PROT_NONE0x0;
1319 assert((permissions & (ePermissionsReadable | ePermissionsWritable |(static_cast <bool> ((permissions & (ePermissionsReadable
| ePermissionsWritable | ePermissionsExecutable)) == permissions
&& "Unknown permission!") ? void (0) : __assert_fail
("(permissions & (ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable)) == permissions && \"Unknown permission!\""
, "lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp",
1321, __extension__ __PRETTY_FUNCTION__))
1320 ePermissionsExecutable)) == permissions &&(static_cast <bool> ((permissions & (ePermissionsReadable
| ePermissionsWritable | ePermissionsExecutable)) == permissions
&& "Unknown permission!") ? void (0) : __assert_fail
("(permissions & (ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable)) == permissions && \"Unknown permission!\""
, "lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp",
1321, __extension__ __PRETTY_FUNCTION__))
1321 "Unknown permission!")(static_cast <bool> ((permissions & (ePermissionsReadable
| ePermissionsWritable | ePermissionsExecutable)) == permissions
&& "Unknown permission!") ? void (0) : __assert_fail
("(permissions & (ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable)) == permissions && \"Unknown permission!\""
, "lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp",
1321, __extension__ __PRETTY_FUNCTION__))
;
1322 if (permissions & ePermissionsReadable)
1323 prot |= PROT_READ0x1;
1324 if (permissions & ePermissionsWritable)
1325 prot |= PROT_WRITE0x2;
1326 if (permissions & ePermissionsExecutable)
1327 prot |= PROT_EXEC0x4;
1328
1329 llvm::Expected<uint64_t> Result =
1330 Syscall({mmap_data->SysMmap, 0, size, prot, MAP_ANONYMOUS0x20 | MAP_PRIVATE0x02,
1331 uint64_t(-1), 0});
1332 if (Result)
1333 m_allocated_memory.try_emplace(*Result, size);
1334 return Result;
1335}
1336
1337llvm::Error NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {
1338 llvm::Optional<NativeRegisterContextLinux::MmapData> mmap_data =
1339 GetCurrentThread()->GetRegisterContext().GetMmapData();
1340 if (!mmap_data)
1341 return llvm::make_error<UnimplementedError>();
1342
1343 auto it = m_allocated_memory.find(addr);
1344 if (it == m_allocated_memory.end())
1345 return llvm::createStringError(llvm::errc::invalid_argument,
1346 "Memory not allocated by the debugger.");
1347
1348 llvm::Expected<uint64_t> Result =
1349 Syscall({mmap_data->SysMunmap, addr, it->second});
1350 if (!Result)
1351 return Result.takeError();
1352
1353 m_allocated_memory.erase(it);
1354 return llvm::Error::success();
1355}
1356
1357Status NativeProcessLinux::ReadMemoryTags(int32_t type, lldb::addr_t addr,
1358 size_t len,
1359 std::vector<uint8_t> &tags) {
1360 llvm::Expected<NativeRegisterContextLinux::MemoryTaggingDetails> details =
1361 GetCurrentThread()->GetRegisterContext().GetMemoryTaggingDetails(type);
1362 if (!details)
1363 return Status(details.takeError());
1364
1365 // Ignore 0 length read
1366 if (!len)
1367 return Status();
1368
1369 // lldb will align the range it requests but it is not required to by
1370 // the protocol so we'll do it again just in case.
1371 // Remove tag bits too. Ptrace calls may work regardless but that
1372 // is not a guarantee.
1373 MemoryTagManager::TagRange range(details->manager->RemoveTagBits(addr), len);
1374 range = details->manager->ExpandToGranule(range);
1375
1376 // Allocate enough space for all tags to be read
1377 size_t num_tags = range.GetByteSize() / details->manager->GetGranuleSize();
1378 tags.resize(num_tags * details->manager->GetTagSizeInBytes());
1379
1380 struct iovec tags_iovec;
1381 uint8_t *dest = tags.data();
1382 lldb::addr_t read_addr = range.GetRangeBase();
1383
1384 // This call can return partial data so loop until we error or
1385 // get all tags back.
1386 while (num_tags) {
1387 tags_iovec.iov_base = dest;
1388 tags_iovec.iov_len = num_tags;
1389
1390 Status error = NativeProcessLinux::PtraceWrapper(
1391 details->ptrace_read_req, GetCurrentThreadID(),
1392 reinterpret_cast<void *>(read_addr), static_cast<void *>(&tags_iovec),
1393 0, nullptr);
1394
1395 if (error.Fail()) {
1396 // Discard partial reads
1397 tags.resize(0);
1398 return error;
1399 }
1400
1401 size_t tags_read = tags_iovec.iov_len;
1402 assert(tags_read && (tags_read <= num_tags))(static_cast <bool> (tags_read && (tags_read <=
num_tags)) ? void (0) : __assert_fail ("tags_read && (tags_read <= num_tags)"
, "lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp",
1402, __extension__ __PRETTY_FUNCTION__))
;
1403
1404 dest += tags_read * details->manager->GetTagSizeInBytes();
1405 read_addr += details->manager->GetGranuleSize() * tags_read;
1406 num_tags -= tags_read;
1407 }
1408
1409 return Status();
1410}
1411
1412Status NativeProcessLinux::WriteMemoryTags(int32_t type, lldb::addr_t addr,
1413 size_t len,
1414 const std::vector<uint8_t> &tags) {
1415 llvm::Expected<NativeRegisterContextLinux::MemoryTaggingDetails> details =
1416 GetCurrentThread()->GetRegisterContext().GetMemoryTaggingDetails(type);
1417 if (!details)
1
Taking false branch
1418 return Status(details.takeError());
1419
1420 // Ignore 0 length write
1421 if (!len)
2
Assuming 'len' is not equal to 0
3
Taking false branch
1422 return Status();
1423
1424 // lldb will align the range it requests but it is not required to by
1425 // the protocol so we'll do it again just in case.
1426 // Remove tag bits too. Ptrace calls may work regardless but that
1427 // is not a guarantee.
1428 MemoryTagManager::TagRange range(details->manager->RemoveTagBits(addr), len);
1429 range = details->manager->ExpandToGranule(range);
1430
1431 // Not checking number of tags here, we may repeat them below
1432 llvm::Expected<std::vector<lldb::addr_t>> unpacked_tags_or_err =
1433 details->manager->UnpackTagsData(tags);
1434 if (!unpacked_tags_or_err)
4
Taking false branch
1435 return Status(unpacked_tags_or_err.takeError());
1436
1437 llvm::Expected<std::vector<lldb::addr_t>> repeated_tags_or_err =
1438 details->manager->RepeatTagsForRange(*unpacked_tags_or_err, range);
1439 if (!repeated_tags_or_err)
5
Taking false branch
1440 return Status(repeated_tags_or_err.takeError());
1441
1442 // Repack them for ptrace to use
1443 llvm::Expected<std::vector<uint8_t>> final_tag_data =
1444 details->manager->PackTags(*repeated_tags_or_err);
1445 if (!final_tag_data)
6
Taking false branch
1446 return Status(final_tag_data.takeError());
1447
1448 struct iovec tags_vec;
1449 uint8_t *src = final_tag_data->data();
1450 lldb::addr_t write_addr = range.GetRangeBase();
1451 // unpacked tags size because the number of bytes per tag might not be 1
1452 size_t num_tags = repeated_tags_or_err->size();
1453
1454 // This call can partially write tags, so we loop until we
1455 // error or all tags have been written.
1456 while (num_tags > 0) {
7
Assuming 'num_tags' is > 0
8
Loop condition is true. Entering loop body
1457 tags_vec.iov_base = src;
1458 tags_vec.iov_len = num_tags;
1459
1460 Status error = NativeProcessLinux::PtraceWrapper(
9
Calling 'NativeProcessLinux::PtraceWrapper'
1461 details->ptrace_write_req, GetCurrentThreadID(),
1462 reinterpret_cast<void *>(write_addr), static_cast<void *>(&tags_vec), 0,
1463 nullptr);
1464
1465 if (error.Fail()) {
1466 // Don't attempt to restore the original values in the case of a partial
1467 // write
1468 return error;
1469 }
1470
1471 size_t tags_written = tags_vec.iov_len;
1472 assert(tags_written && (tags_written <= num_tags))(static_cast <bool> (tags_written && (tags_written
<= num_tags)) ? void (0) : __assert_fail ("tags_written && (tags_written <= num_tags)"
, "lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp",
1472, __extension__ __PRETTY_FUNCTION__))
;
1473
1474 src += tags_written * details->manager->GetTagSizeInBytes();
1475 write_addr += details->manager->GetGranuleSize() * tags_written;
1476 num_tags -= tags_written;
1477 }
1478
1479 return Status();
1480}
1481
1482size_t NativeProcessLinux::UpdateThreads() {
1483 // The NativeProcessLinux monitoring threads are always up to date with
1484 // respect to thread state and they keep the thread list populated properly.
1485 // All this method needs to do is return the thread count.
1486 return m_threads.size();
1487}
1488
1489Status NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,
1490 bool hardware) {
1491 if (hardware)
1492 return SetHardwareBreakpoint(addr, size);
1493 else
1494 return SetSoftwareBreakpoint(addr, size);
1495}
1496
1497Status NativeProcessLinux::RemoveBreakpoint(lldb::addr_t addr, bool hardware) {
1498 if (hardware)
1499 return RemoveHardwareBreakpoint(addr);
1500 else
1501 return NativeProcessProtocol::RemoveBreakpoint(addr);
1502}
1503
1504llvm::Expected<llvm::ArrayRef<uint8_t>>
1505NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(size_t size_hint) {
1506 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1507 // linux kernel does otherwise.
1508 static const uint8_t g_arm_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1509 static const uint8_t g_thumb_opcode[] = {0x01, 0xde};
1510
1511 switch (GetArchitecture().GetMachine()) {
1512 case llvm::Triple::arm:
1513 switch (size_hint) {
1514 case 2:
1515 return llvm::makeArrayRef(g_thumb_opcode);
1516 case 4:
1517 return llvm::makeArrayRef(g_arm_opcode);
1518 default:
1519 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1520 "Unrecognised trap opcode size hint!");
1521 }
1522 default:
1523 return NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_hint);
1524 }
1525}
1526
1527Status NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
1528 size_t &bytes_read) {
1529 if (ProcessVmReadvSupported()) {
1530 // The process_vm_readv path is about 50 times faster than ptrace api. We
1531 // want to use this syscall if it is supported.
1532
1533 struct iovec local_iov, remote_iov;
1534 local_iov.iov_base = buf;
1535 local_iov.iov_len = size;
1536 remote_iov.iov_base = reinterpret_cast<void *>(addr);
1537 remote_iov.iov_len = size;
1538
1539 bytes_read = process_vm_readv(GetCurrentThreadID(), &local_iov, 1,
1540 &remote_iov, 1, 0);
1541 const bool success = bytes_read == size;
1542
1543 Log *log = GetLog(POSIXLog::Process);
1544 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "using process_vm_readv to read {0} bytes from inferior "
"address {1:x}: {2}", size, addr, success ? "Success" : llvm
::sys::StrError((*__errno_location ()))); } while (0)
1545 "using process_vm_readv to read {0} bytes from inferior "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "using process_vm_readv to read {0} bytes from inferior "
"address {1:x}: {2}", size, addr, success ? "Success" : llvm
::sys::StrError((*__errno_location ()))); } while (0)
1546 "address {1:x}: {2}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "using process_vm_readv to read {0} bytes from inferior "
"address {1:x}: {2}", size, addr, success ? "Success" : llvm
::sys::StrError((*__errno_location ()))); } while (0)
1547 size, addr, success ? "Success" : llvm::sys::StrError(errno))do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "using process_vm_readv to read {0} bytes from inferior "
"address {1:x}: {2}", size, addr, success ? "Success" : llvm
::sys::StrError((*__errno_location ()))); } while (0)
;
1548
1549 if (success)
1550 return Status();
1551 // else the call failed for some reason, let's retry the read using ptrace
1552 // api.
1553 }
1554
1555 unsigned char *dst = static_cast<unsigned char *>(buf);
1556 size_t remainder;
1557 long data;
1558
1559 Log *log = GetLog(POSIXLog::Memory);
1560 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "addr = {0}, buf = {1}, size = {2}", addr, buf, size
); } while (0)
;
1561
1562 for (bytes_read = 0; bytes_read < size; bytes_read += remainder) {
1563 Status error = NativeProcessLinux::PtraceWrapper(
1564 PTRACE_PEEKDATA, GetCurrentThreadID(), (void *)addr, nullptr, 0, &data);
1565 if (error.Fail())
1566 return error;
1567
1568 remainder = size - bytes_read;
1569 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
1570
1571 // Copy the data into our buffer
1572 memcpy(dst, &data, remainder);
1573
1574 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "[{0:x}]:{1:x}", addr, data); } while (0)
;
1575 addr += k_ptrace_word_size;
1576 dst += k_ptrace_word_size;
1577 }
1578 return Status();
1579}
1580
1581Status NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,
1582 size_t size, size_t &bytes_written) {
1583 const unsigned char *src = static_cast<const unsigned char *>(buf);
1584 size_t remainder;
1585 Status error;
1586
1587 Log *log = GetLog(POSIXLog::Memory);
1588 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "addr = {0}, buf = {1}, size = {2}", addr, buf, size
); } while (0)
;
1589
1590 for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
1591 remainder = size - bytes_written;
1592 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
1593
1594 if (remainder == k_ptrace_word_size) {
1595 unsigned long data = 0;
1596 memcpy(&data, src, k_ptrace_word_size);
1597
1598 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "[{0:x}]:{1:x}", addr, data); } while (0)
;
1599 error = NativeProcessLinux::PtraceWrapper(
1600 PTRACE_POKEDATA, GetCurrentThreadID(), (void *)addr, (void *)data);
1601 if (error.Fail())
1602 return error;
1603 } else {
1604 unsigned char buff[8];
1605 size_t bytes_read;
1606 error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
1607 if (error.Fail())
1608 return error;
1609
1610 memcpy(buff, src, remainder);
1611
1612 size_t bytes_written_rec;
1613 error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
1614 if (error.Fail())
1615 return error;
1616
1617 LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long
*)src, *(unsigned long *)buff); } while (0)
1618 *(unsigned long *)buff)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long
*)src, *(unsigned long *)buff); } while (0)
;
1619 }
1620
1621 addr += k_ptrace_word_size;
1622 src += k_ptrace_word_size;
1623 }
1624 return error;
1625}
1626
1627Status NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) const {
1628 return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
1629}
1630
1631Status NativeProcessLinux::GetEventMessage(lldb::tid_t tid,
1632 unsigned long *message) {
1633 return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
1634}
1635
1636Status NativeProcessLinux::Detach(lldb::tid_t tid) {
1637 if (tid == LLDB_INVALID_THREAD_ID0)
1638 return Status();
1639
1640 return PtraceWrapper(PTRACE_DETACH, tid);
1641}
1642
1643bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {
1644 for (const auto &thread : m_threads) {
1645 assert(thread && "thread list should not contain NULL threads")(static_cast <bool> (thread && "thread list should not contain NULL threads"
) ? void (0) : __assert_fail ("thread && \"thread list should not contain NULL threads\""
, "lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp",
1645, __extension__ __PRETTY_FUNCTION__))
;
1646 if (thread->GetID() == thread_id) {
1647 // We have this thread.
1648 return true;
1649 }
1650 }
1651
1652 // We don't have this thread.
1653 return false;
1654}
1655
1656void NativeProcessLinux::StopTrackingThread(NativeThreadLinux &thread) {
1657 Log *const log = GetLog(POSIXLog::Thread);
1658 lldb::tid_t thread_id = thread.GetID();
1659 LLDB_LOG(log, "tid: {0}", thread_id)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "tid: {0}", thread_id); } while (0)
;
1660
1661 auto it = llvm::find_if(m_threads, [&](const auto &thread_up) {
1662 return thread_up.get() == &thread;
1663 });
1664 assert(it != m_threads.end())(static_cast <bool> (it != m_threads.end()) ? void (0) :
__assert_fail ("it != m_threads.end()", "lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, 1664, __extension__ __PRETTY_FUNCTION__))
;
1665 m_threads.erase(it);
1666
1667 NotifyTracersOfThreadDestroyed(thread_id);
1668 SignalIfAllThreadsStopped();
1669}
1670
1671void NativeProcessLinux::NotifyTracersProcessDidStop() {
1672 m_intel_pt_collector.ProcessDidStop();
1673}
1674
1675void NativeProcessLinux::NotifyTracersProcessWillResume() {
1676 m_intel_pt_collector.ProcessWillResume();
1677}
1678
1679Status NativeProcessLinux::NotifyTracersOfNewThread(lldb::tid_t tid) {
1680 Log *log = GetLog(POSIXLog::Thread);
1681 Status error(m_intel_pt_collector.OnThreadCreated(tid));
1682 if (error.Fail())
1683 LLDB_LOG(log, "Failed to trace a new thread with intel-pt, tid = {0}. {1}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "Failed to trace a new thread with intel-pt, tid = {0}. {1}"
, tid, error.AsCString()); } while (0)
1684 tid, error.AsCString())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "Failed to trace a new thread with intel-pt, tid = {0}. {1}"
, tid, error.AsCString()); } while (0)
;
1685 return error;
1686}
1687
1688Status NativeProcessLinux::NotifyTracersOfThreadDestroyed(lldb::tid_t tid) {
1689 Log *log = GetLog(POSIXLog::Thread);
1690 Status error(m_intel_pt_collector.OnThreadDestroyed(tid));
1691 if (error.Fail())
1692 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "Failed to stop a destroyed thread with intel-pt, tid = {0}. {1}"
, tid, error.AsCString()); } while (0)
1693 "Failed to stop a destroyed thread with intel-pt, tid = {0}. {1}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "Failed to stop a destroyed thread with intel-pt, tid = {0}. {1}"
, tid, error.AsCString()); } while (0)
1694 tid, error.AsCString())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "Failed to stop a destroyed thread with intel-pt, tid = {0}. {1}"
, tid, error.AsCString()); } while (0)
;
1695 return error;
1696}
1697
1698NativeThreadLinux &NativeProcessLinux::AddThread(lldb::tid_t thread_id,
1699 bool resume) {
1700 Log *log = GetLog(POSIXLog::Thread);
1701 LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid {0} adding thread with tid {1}", GetID(), thread_id
); } while (0)
;
1702
1703 assert(!HasThreadNoLock(thread_id) &&(static_cast <bool> (!HasThreadNoLock(thread_id) &&
"attempted to add a thread by id that already exists") ? void
(0) : __assert_fail ("!HasThreadNoLock(thread_id) && \"attempted to add a thread by id that already exists\""
, "lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp",
1704, __extension__ __PRETTY_FUNCTION__))
1704 "attempted to add a thread by id that already exists")(static_cast <bool> (!HasThreadNoLock(thread_id) &&
"attempted to add a thread by id that already exists") ? void
(0) : __assert_fail ("!HasThreadNoLock(thread_id) && \"attempted to add a thread by id that already exists\""
, "lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp",
1704, __extension__ __PRETTY_FUNCTION__))
;
1705
1706 // If this is the first thread, save it as the current thread
1707 if (m_threads.empty())
1708 SetCurrentThreadID(thread_id);
1709
1710 m_threads.push_back(std::make_unique<NativeThreadLinux>(*this, thread_id));
1711 NativeThreadLinux &thread =
1712 static_cast<NativeThreadLinux &>(*m_threads.back());
1713
1714 Status tracing_error = NotifyTracersOfNewThread(thread.GetID());
1715 if (tracing_error.Fail()) {
1716 thread.SetStoppedByProcessorTrace(tracing_error.AsCString());
1717 StopRunningThreads(thread.GetID());
1718 } else if (resume)
1719 ResumeThread(thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER(2147483647));
1720 else
1721 thread.SetStoppedBySignal(SIGSTOP19);
1722
1723 return thread;
1724}
1725
1726Status NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,
1727 FileSpec &file_spec) {
1728 Status error = PopulateMemoryRegionCache();
1729 if (error.Fail())
1730 return error;
1731
1732 FileSpec module_file_spec(module_path);
1733 FileSystem::Instance().Resolve(module_file_spec);
1734
1735 file_spec.Clear();
1736 for (const auto &it : m_mem_region_cache) {
1737 if (it.second.GetFilename() == module_file_spec.GetFilename()) {
1738 file_spec = it.second;
1739 return Status();
1740 }
1741 }
1742 return Status("Module file (%s) not found in /proc/%" PRIu64"l" "u" "/maps file!",
1743 module_file_spec.GetFilename().AsCString(), GetID());
1744}
1745
1746Status NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
1747 lldb::addr_t &load_addr) {
1748 load_addr = LLDB_INVALID_ADDRESS(18446744073709551615UL);
1749 Status error = PopulateMemoryRegionCache();
1750 if (error.Fail())
1751 return error;
1752
1753 FileSpec file(file_name);
1754 for (const auto &it : m_mem_region_cache) {
1755 if (it.second == file) {
1756 load_addr = it.first.GetRange().GetRangeBase();
1757 return Status();
1758 }
1759 }
1760 return Status("No load address found for specified file.");
1761}
1762
1763NativeThreadLinux *NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {
1764 return static_cast<NativeThreadLinux *>(
1765 NativeProcessProtocol::GetThreadByID(tid));
1766}
1767
1768NativeThreadLinux *NativeProcessLinux::GetCurrentThread() {
1769 return static_cast<NativeThreadLinux *>(
1770 NativeProcessProtocol::GetCurrentThread());
1771}
1772
1773Status NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,
1774 lldb::StateType state, int signo) {
1775 Log *const log = GetLog(POSIXLog::Thread);
1776 LLDB_LOG(log, "tid: {0}", thread.GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "tid: {0}", thread.GetID()); } while (0)
;
1777
1778 // Before we do the resume below, first check if we have a pending stop
1779 // notification that is currently waiting for all threads to stop. This is
1780 // potentially a buggy situation since we're ostensibly waiting for threads
1781 // to stop before we send out the pending notification, and here we are
1782 // resuming one before we send out the pending stop notification.
1783 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID0) {
1784 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "about to resume tid {0} per explicit request but we have a "
"pending stop notification (tid {1}) that is actively " "waiting for this thread to stop. Valid sequence of events?"
, thread.GetID(), m_pending_notification_tid); } while (0)
1785 "about to resume tid {0} per explicit request but we have a "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "about to resume tid {0} per explicit request but we have a "
"pending stop notification (tid {1}) that is actively " "waiting for this thread to stop. Valid sequence of events?"
, thread.GetID(), m_pending_notification_tid); } while (0)
1786 "pending stop notification (tid {1}) that is actively "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "about to resume tid {0} per explicit request but we have a "
"pending stop notification (tid {1}) that is actively " "waiting for this thread to stop. Valid sequence of events?"
, thread.GetID(), m_pending_notification_tid); } while (0)
1787 "waiting for this thread to stop. Valid sequence of events?",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "about to resume tid {0} per explicit request but we have a "
"pending stop notification (tid {1}) that is actively " "waiting for this thread to stop. Valid sequence of events?"
, thread.GetID(), m_pending_notification_tid); } while (0)
1788 thread.GetID(), m_pending_notification_tid)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "about to resume tid {0} per explicit request but we have a "
"pending stop notification (tid {1}) that is actively " "waiting for this thread to stop. Valid sequence of events?"
, thread.GetID(), m_pending_notification_tid); } while (0)
;
1789 }
1790
1791 // Request a resume. We expect this to be synchronous and the system to
1792 // reflect it is running after this completes.
1793 switch (state) {
1794 case eStateRunning: {
1795 const auto resume_result = thread.Resume(signo);
1796 if (resume_result.Success())
1797 SetState(eStateRunning, true);
1798 return resume_result;
1799 }
1800 case eStateStepping: {
1801 const auto step_result = thread.SingleStep(signo);
1802 if (step_result.Success())
1803 SetState(eStateRunning, true);
1804 return step_result;
1805 }
1806 default:
1807 LLDB_LOG(log, "Unhandled state {0}.", state)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "Unhandled state {0}.", state); } while (0)
;
1808 llvm_unreachable("Unhandled state for resume")::llvm::llvm_unreachable_internal("Unhandled state for resume"
, "lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp",
1808)
;
1809 }
1810}
1811
1812//===----------------------------------------------------------------------===//
1813
1814void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {
1815 Log *const log = GetLog(POSIXLog::Thread);
1816 LLDB_LOG(log, "about to process event: (triggering_tid: {0})",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "about to process event: (triggering_tid: {0})", triggering_tid
); } while (0)
1817 triggering_tid)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "about to process event: (triggering_tid: {0})", triggering_tid
); } while (0)
;
1818
1819 m_pending_notification_tid = triggering_tid;
1820
1821 // Request a stop for all the thread stops that need to be stopped and are
1822 // not already known to be stopped.
1823 for (const auto &thread : m_threads) {
1824 if (StateIsRunningState(thread->GetState()))
1825 static_cast<NativeThreadLinux *>(thread.get())->RequestStop();
1826 }
1827
1828 SignalIfAllThreadsStopped();
1829 LLDB_LOG(log, "event processing done")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "event processing done"); } while (0)
;
1830}
1831
1832void NativeProcessLinux::SignalIfAllThreadsStopped() {
1833 if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID0)
1834 return; // No pending notification. Nothing to do.
1835
1836 for (const auto &thread_sp : m_threads) {
1837 if (StateIsRunningState(thread_sp->GetState()))
1838 return; // Some threads are still running. Don't signal yet.
1839 }
1840
1841 // We have a pending notification and all threads have stopped.
1842 Log *log = GetLog(LLDBLog::Process | LLDBLog::Breakpoints);
1843
1844 // Clear any temporary breakpoints we used to implement software single
1845 // stepping.
1846 for (const auto &thread_info : m_threads_stepping_with_breakpoint) {
1847 Status error = RemoveBreakpoint(thread_info.second);
1848 if (error.Fail())
1849 LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid = {0} remove stepping breakpoint: {1}", thread_info
.first, error); } while (0)
1850 thread_info.first, error)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "pid = {0} remove stepping breakpoint: {1}", thread_info
.first, error); } while (0)
;
1851 }
1852 m_threads_stepping_with_breakpoint.clear();
1853
1854 // Notify the delegate about the stop
1855 SetCurrentThreadID(m_pending_notification_tid);
1856 SetState(StateType::eStateStopped, true);
1857 m_pending_notification_tid = LLDB_INVALID_THREAD_ID0;
1858}
1859
1860void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {
1861 Log *const log = GetLog(POSIXLog::Thread);
1862 LLDB_LOG(log, "tid: {0}", thread.GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "tid: {0}", thread.GetID()); } while (0)
;
1863
1864 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID0 &&
1865 StateIsRunningState(thread.GetState())) {
1866 // We will need to wait for this new thread to stop as well before firing
1867 // the notification.
1868 thread.RequestStop();
1869 }
1870}
1871
1872static llvm::Optional<WaitStatus> HandlePid(::pid_t pid) {
1873 Log *log = GetLog(POSIXLog::Process);
1874
1875 int status;
1876 ::pid_t wait_pid = llvm::sys::RetryAfterSignal(
1877 -1, ::waitpid, pid, &status, __WALL0x40000000 | __WNOTHREAD0x20000000 | WNOHANG1);
1878
1879 if (wait_pid == 0)
1880 return llvm::None;
1881
1882 if (wait_pid == -1) {
1883 Status error(errno(*__errno_location ()), eErrorTypePOSIX);
1884 LLDB_LOG(log, "waitpid({0}, &status, _) failed: {1}", pid,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "waitpid({0}, &status, _) failed: {1}", pid, error
); } while (0)
1885 error)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "waitpid({0}, &status, _) failed: {1}", pid, error
); } while (0)
;
1886 return llvm::None;
1887 }
1888
1889 assert(wait_pid == pid)(static_cast <bool> (wait_pid == pid) ? void (0) : __assert_fail
("wait_pid == pid", "lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, 1889, __extension__ __PRETTY_FUNCTION__))
;
1890
1891 WaitStatus wait_status = WaitStatus::Decode(status);
1892
1893 LLDB_LOG(log, "waitpid({0}) got status = {1}", pid, wait_status)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "waitpid({0}) got status = {1}", pid, wait_status
); } while (0)
;
1894 return wait_status;
1895}
1896
1897void NativeProcessLinux::SigchldHandler() {
1898 Log *log = GetLog(POSIXLog::Process);
1899
1900 // Threads can appear or disappear as a result of event processing, so gather
1901 // the events upfront.
1902 llvm::DenseMap<lldb::tid_t, WaitStatus> tid_events;
1903 bool checked_main_thread = false;
1904 for (const auto &thread_up : m_threads) {
1905 if (thread_up->GetID() == GetID())
1906 checked_main_thread = true;
1907
1908 if (llvm::Optional<WaitStatus> status = HandlePid(thread_up->GetID()))
1909 tid_events.try_emplace(thread_up->GetID(), *status);
1910 }
1911 // Check the main thread even when we're not tracking it as process exit
1912 // events are reported that way.
1913 if (!checked_main_thread) {
1914 if (llvm::Optional<WaitStatus> status = HandlePid(GetID()))
1915 tid_events.try_emplace(GetID(), *status);
1916 }
1917
1918 for (auto &KV : tid_events) {
1919 LLDB_LOG(log, "processing {0}({1}) ...", KV.first, KV.second)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "processing {0}({1}) ...", KV.first, KV.second); }
while (0)
;
1920 if (KV.first == GetID() && (KV.second.type == WaitStatus::Exit ||
1921 KV.second.type == WaitStatus::Signal)) {
1922
1923 // The process exited. We're done monitoring. Report to delegate.
1924 SetExitStatus(KV.second, true);
1925 return;
1926 }
1927 NativeThreadLinux *thread = GetThreadByID(KV.first);
1928 assert(thread && "Why did this thread disappear?")(static_cast <bool> (thread && "Why did this thread disappear?"
) ? void (0) : __assert_fail ("thread && \"Why did this thread disappear?\""
, "lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp",
1928, __extension__ __PRETTY_FUNCTION__))
;
1929 MonitorCallback(*thread, KV.second);
1930 }
1931}
1932
1933// Wrapper for ptrace to catch errors and log calls. Note that ptrace sets
1934// errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
1935Status NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
1936 void *data, size_t data_size,
1937 long *result) {
1938 Status error;
1939 long int ret;
1940
1941 Log *log = GetLog(POSIXLog::Ptrace);
1942
1943 PtraceDisplayBytes(req, data, data_size);
10
Calling 'PtraceDisplayBytes'
1944
1945 errno(*__errno_location ()) = 0;
1946 if (req == PTRACE_GETREGSETPTRACE_GETREGSET || req == PTRACE_SETREGSETPTRACE_SETREGSET)
1947 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
1948 *(unsigned int *)addr, data);
1949 else
1950 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
1951 addr, data);
1952
1953 if (ret == -1)
1954 error.SetErrorToErrno();
1955
1956 if (result)
1957 *result = ret;
1958
1959 LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid
, addr, data, data_size, ret); } while (0)
1960 data_size, ret)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid
, addr, data, data_size, ret); } while (0)
;
1961
1962 PtraceDisplayBytes(req, data, data_size);
1963
1964 if (error.Fail())
1965 LLDB_LOG(log, "ptrace() failed: {0}", error)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp"
, __func__, "ptrace() failed: {0}", error); } while (0)
;
1966
1967 return error;
1968}
1969
1970llvm::Expected<TraceSupportedResponse> NativeProcessLinux::TraceSupported() {
1971 if (IntelPTCollector::IsSupported())
1972 return TraceSupportedResponse{"intel-pt", "Intel Processor Trace"};
1973 return NativeProcessProtocol::TraceSupported();
1974}
1975
1976Error NativeProcessLinux::TraceStart(StringRef json_request, StringRef type) {
1977 if (type == "intel-pt") {
1978 if (Expected<TraceIntelPTStartRequest> request =
1979 json::parse<TraceIntelPTStartRequest>(json_request,
1980 "TraceIntelPTStartRequest")) {
1981 return m_intel_pt_collector.TraceStart(*request);
1982 } else
1983 return request.takeError();
1984 }
1985
1986 return NativeProcessProtocol::TraceStart(json_request, type);
1987}
1988
1989Error NativeProcessLinux::TraceStop(const TraceStopRequest &request) {
1990 if (request.type == "intel-pt")
1991 return m_intel_pt_collector.TraceStop(request);
1992 return NativeProcessProtocol::TraceStop(request);
1993}
1994
1995Expected<json::Value> NativeProcessLinux::TraceGetState(StringRef type) {
1996 if (type == "intel-pt")
1997 return m_intel_pt_collector.GetState();
1998 return NativeProcessProtocol::TraceGetState(type);
1999}
2000
2001Expected<std::vector<uint8_t>> NativeProcessLinux::TraceGetBinaryData(
2002 const TraceGetBinaryDataRequest &request) {
2003 if (request.type == "intel-pt")
2004 return m_intel_pt_collector.GetBinaryData(request);
2005 return NativeProcessProtocol::TraceGetBinaryData(request);
2006}