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

source code of lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp