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 = Status::FromErrno();
207 return error;
208 }
209
210 if (fcntl(fd: fd, F_SETFL, status | flags) == -1) {
211 error = Status::FromErrno();
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 S: "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: {0}", 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 NativeRegisterContextLinux &reg_ctx = thread.GetRegisterContext();
833 auto stepping_with_bp_it =
834 m_threads_stepping_with_breakpoint.find(x: thread.GetID());
835 if (stepping_with_bp_it != m_threads_stepping_with_breakpoint.end() &&
836 stepping_with_bp_it->second == reg_ctx.GetPC())
837 thread.SetStoppedByTrace();
838
839 StopRunningThreads(triggering_tid: thread.GetID());
840}
841
842void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread,
843 uint32_t wp_index) {
844 Log *log = GetLog(mask: LLDBLog::Process | LLDBLog::Watchpoints);
845 LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}",
846 thread.GetID(), wp_index);
847
848 // Mark the thread as stopped at watchpoint. The address is at
849 // (lldb::addr_t)info->si_addr if we need it.
850 thread.SetStoppedByWatchpoint(wp_index);
851
852 // We need to tell all other running threads before we notify the delegate
853 // about this stop.
854 StopRunningThreads(triggering_tid: thread.GetID());
855}
856
857void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
858 NativeThreadLinux &thread) {
859 const int signo = info.si_signo;
860 const bool is_from_llgs = info.si_pid == getpid();
861
862 Log *log = GetLog(mask: POSIXLog::Process);
863
864 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
865 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a kill(2)
866 // or raise(3). Similarly for tgkill(2) on Linux.
867 //
868 // IOW, user generated signals never generate what we consider to be a
869 // "crash".
870 //
871 // Similarly, ACK signals generated by this monitor.
872
873 // Handle the signal.
874 LLDB_LOG(log,
875 "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
876 "waitpid pid = {4})",
877 Host::GetSignalAsCString(signo), signo, info.si_code, info.si_pid,
878 thread.GetID());
879
880 // Check for thread stop notification.
881 if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) {
882 // This is a tgkill()-based stop.
883 LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID());
884
885 // Check that we're not already marked with a stop reason. Note this thread
886 // really shouldn't already be marked as stopped - if we were, that would
887 // imply that the kernel signaled us with the thread stopping which we
888 // handled and marked as stopped, and that, without an intervening resume,
889 // we received another stop. It is more likely that we are missing the
890 // marking of a run state somewhere if we find that the thread was marked
891 // as stopped.
892 const StateType thread_state = thread.GetState();
893 if (!StateIsStoppedState(state: thread_state, must_exist: false)) {
894 // An inferior thread has stopped because of a SIGSTOP we have sent it.
895 // Generally, these are not important stops and we don't want to report
896 // them as they are just used to stop other threads when one thread (the
897 // one with the *real* stop reason) hits a breakpoint (watchpoint,
898 // etc...). However, in the case of an asynchronous Interrupt(), this
899 // *is* the real stop reason, so we leave the signal intact if this is
900 // the thread that was chosen as the triggering thread.
901 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
902 if (m_pending_notification_tid == thread.GetID())
903 thread.SetStoppedBySignal(SIGSTOP, info: &info);
904 else
905 thread.SetStoppedWithNoReason();
906
907 SetCurrentThreadID(thread.GetID());
908 SignalIfAllThreadsStopped();
909 } else {
910 // We can end up here if stop was initiated by LLGS but by this time a
911 // thread stop has occurred - maybe initiated by another event.
912 Status error = ResumeThread(thread, state: thread.GetState(), signo: 0);
913 if (error.Fail())
914 LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(),
915 error);
916 }
917 } else {
918 LLDB_LOG(log,
919 "pid {0} tid {1}, thread was already marked as a stopped "
920 "state (state={2}), leaving stop signal as is",
921 GetID(), thread.GetID(), thread_state);
922 SignalIfAllThreadsStopped();
923 }
924
925 // Done handling.
926 return;
927 }
928
929 // Check if debugger should stop at this signal or just ignore it and resume
930 // the inferior.
931 if (m_signals_to_ignore.contains(V: signo)) {
932 ResumeThread(thread, state: thread.GetState(), signo);
933 return;
934 }
935
936 // This thread is stopped.
937 LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo));
938 thread.SetStoppedBySignal(signo, info: &info);
939
940 // Send a stop to the debugger after we get all other threads to stop.
941 StopRunningThreads(triggering_tid: thread.GetID());
942}
943
944bool NativeProcessLinux::MonitorClone(NativeThreadLinux &parent,
945 lldb::pid_t child_pid, int event) {
946 Log *log = GetLog(mask: POSIXLog::Process);
947 LLDB_LOG(log, "parent_tid={0}, child_pid={1}, event={2}", parent.GetID(),
948 child_pid, event);
949
950 m_manager.CollectThread(tid: child_pid);
951
952 switch (event) {
953 case PTRACE_EVENT_CLONE: {
954 // PTRACE_EVENT_CLONE can either mean a new thread or a new process.
955 // Try to grab the new process' PGID to figure out which one it is.
956 // If PGID is the same as the PID, then it's a new process. Otherwise,
957 // it's a thread.
958 auto tgid_ret = getPIDForTID(tid: child_pid);
959 if (tgid_ret != child_pid) {
960 // A new thread should have PGID matching our process' PID.
961 assert(!tgid_ret || *tgid_ret == GetID());
962
963 NativeThreadLinux &child_thread = AddThread(thread_id: child_pid, /*resume*/ true);
964 ThreadWasCreated(thread&: child_thread);
965
966 // Resume the parent.
967 ResumeThread(thread&: parent, state: parent.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
968 break;
969 }
970 }
971 [[fallthrough]];
972 case PTRACE_EVENT_FORK:
973 case PTRACE_EVENT_VFORK: {
974 bool is_vfork = event == PTRACE_EVENT_VFORK;
975 std::unique_ptr<NativeProcessLinux> child_process{new NativeProcessLinux(
976 static_cast<::pid_t>(child_pid), m_terminal_fd, m_delegate, m_arch,
977 m_manager, {static_cast<::pid_t>(child_pid)})};
978 if (!is_vfork)
979 child_process->m_software_breakpoints = m_software_breakpoints;
980
981 Extension expected_ext = is_vfork ? Extension::vfork : Extension::fork;
982 if (bool(m_enabled_extensions & expected_ext)) {
983 m_delegate.NewSubprocess(parent_process: this, child_process: std::move(child_process));
984 // NB: non-vfork clone() is reported as fork
985 parent.SetStoppedByFork(is_vfork, child_pid);
986 StopRunningThreads(triggering_tid: parent.GetID());
987 } else {
988 child_process->Detach();
989 ResumeThread(thread&: parent, state: parent.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
990 }
991 break;
992 }
993 default:
994 llvm_unreachable("unknown clone_info.event");
995 }
996
997 return true;
998}
999
1000bool NativeProcessLinux::SupportHardwareSingleStepping() const {
1001 if (m_arch.IsMIPS() || m_arch.GetMachine() == llvm::Triple::arm ||
1002 m_arch.GetTriple().isRISCV() || m_arch.GetTriple().isLoongArch())
1003 return false;
1004 return true;
1005}
1006
1007Status NativeProcessLinux::Resume(const ResumeActionList &resume_actions) {
1008 Log *log = GetLog(mask: POSIXLog::Process);
1009 LLDB_LOG(log, "pid {0}", GetID());
1010
1011 NotifyTracersProcessWillResume();
1012
1013 bool software_single_step = !SupportHardwareSingleStepping();
1014
1015 if (software_single_step) {
1016 for (const auto &thread : m_threads) {
1017 assert(thread && "thread list should not contain NULL threads");
1018
1019 const ResumeAction *const action =
1020 resume_actions.GetActionForThread(tid: thread->GetID(), default_ok: true);
1021 if (action == nullptr)
1022 continue;
1023
1024 if (action->state == eStateStepping) {
1025 Status error = SetupSoftwareSingleStepping(
1026 static_cast<NativeThreadLinux &>(*thread));
1027 if (error.Fail())
1028 return error;
1029 }
1030 }
1031 }
1032
1033 for (const auto &thread : m_threads) {
1034 assert(thread && "thread list should not contain NULL threads");
1035
1036 const ResumeAction *const action =
1037 resume_actions.GetActionForThread(tid: thread->GetID(), default_ok: true);
1038
1039 if (action == nullptr) {
1040 LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
1041 thread->GetID());
1042 continue;
1043 }
1044
1045 LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}",
1046 action->state, GetID(), thread->GetID());
1047
1048 switch (action->state) {
1049 case eStateRunning:
1050 case eStateStepping: {
1051 // Run the thread, possibly feeding it the signal.
1052 const int signo = action->signal;
1053 Status error = ResumeThread(thread&: static_cast<NativeThreadLinux &>(*thread),
1054 state: action->state, signo);
1055 if (error.Fail())
1056 return Status::FromErrorStringWithFormat(
1057 format: "NativeProcessLinux::%s: failed to resume thread "
1058 "for pid %" PRIu64 ", tid %" PRIu64 ", error = %s",
1059 __FUNCTION__, GetID(), thread->GetID(), error.AsCString());
1060
1061 break;
1062 }
1063
1064 case eStateSuspended:
1065 case eStateStopped:
1066 break;
1067
1068 default:
1069 return Status::FromErrorStringWithFormat(
1070 format: "NativeProcessLinux::%s (): unexpected state %s specified "
1071 "for pid %" PRIu64 ", tid %" PRIu64,
1072 __FUNCTION__, StateAsCString(state: action->state), GetID(),
1073 thread->GetID());
1074 }
1075 }
1076
1077 return Status();
1078}
1079
1080Status NativeProcessLinux::Halt() {
1081 Status error;
1082
1083 if (kill(pid: GetID(), SIGSTOP) != 0)
1084 error = Status::FromErrno();
1085
1086 return error;
1087}
1088
1089Status NativeProcessLinux::Detach() {
1090 Status error;
1091
1092 // Tell ptrace to detach from the process.
1093 if (GetID() == LLDB_INVALID_PROCESS_ID)
1094 return error;
1095
1096 // Cancel out any SIGSTOPs we may have sent while stopping the process.
1097 // Otherwise, the process may stop as soon as we detach from it.
1098 kill(pid: GetID(), SIGCONT);
1099
1100 for (const auto &thread : m_threads) {
1101 Status e = Detach(tid: thread->GetID());
1102 // Save the error, but still attempt to detach from other threads.
1103 if (e.Fail())
1104 error = e.Clone();
1105 }
1106
1107 m_intel_pt_collector.Clear();
1108
1109 return error;
1110}
1111
1112Status NativeProcessLinux::Signal(int signo) {
1113 Status error;
1114
1115 Log *log = GetLog(mask: POSIXLog::Process);
1116 LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo,
1117 Host::GetSignalAsCString(signo), GetID());
1118
1119 if (kill(pid: GetID(), sig: signo))
1120 error = Status::FromErrno();
1121
1122 return error;
1123}
1124
1125Status NativeProcessLinux::Interrupt() {
1126 // Pick a running thread (or if none, a not-dead stopped thread) as the
1127 // chosen thread that will be the stop-reason thread.
1128 Log *log = GetLog(mask: POSIXLog::Process);
1129
1130 NativeThreadProtocol *running_thread = nullptr;
1131 NativeThreadProtocol *stopped_thread = nullptr;
1132
1133 LLDB_LOG(log, "selecting running thread for interrupt target");
1134 for (const auto &thread : m_threads) {
1135 // If we have a running or stepping thread, we'll call that the target of
1136 // the interrupt.
1137 const auto thread_state = thread->GetState();
1138 if (thread_state == eStateRunning || thread_state == eStateStepping) {
1139 running_thread = thread.get();
1140 break;
1141 } else if (!stopped_thread && StateIsStoppedState(state: thread_state, must_exist: true)) {
1142 // Remember the first non-dead stopped thread. We'll use that as a
1143 // backup if there are no running threads.
1144 stopped_thread = thread.get();
1145 }
1146 }
1147
1148 if (!running_thread && !stopped_thread) {
1149 Status error("found no running/stepping or live stopped threads as target "
1150 "for interrupt");
1151 LLDB_LOG(log, "skipping due to error: {0}", error);
1152
1153 return error;
1154 }
1155
1156 NativeThreadProtocol *deferred_signal_thread =
1157 running_thread ? running_thread : stopped_thread;
1158
1159 LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(),
1160 running_thread ? "running" : "stopped",
1161 deferred_signal_thread->GetID());
1162
1163 StopRunningThreads(triggering_tid: deferred_signal_thread->GetID());
1164
1165 return Status();
1166}
1167
1168Status NativeProcessLinux::Kill() {
1169 Log *log = GetLog(mask: POSIXLog::Process);
1170 LLDB_LOG(log, "pid {0}", GetID());
1171
1172 Status error;
1173
1174 switch (m_state) {
1175 case StateType::eStateInvalid:
1176 case StateType::eStateExited:
1177 case StateType::eStateCrashed:
1178 case StateType::eStateDetached:
1179 case StateType::eStateUnloaded:
1180 // Nothing to do - the process is already dead.
1181 LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
1182 m_state);
1183 return error;
1184
1185 case StateType::eStateConnected:
1186 case StateType::eStateAttaching:
1187 case StateType::eStateLaunching:
1188 case StateType::eStateStopped:
1189 case StateType::eStateRunning:
1190 case StateType::eStateStepping:
1191 case StateType::eStateSuspended:
1192 // We can try to kill a process in these states.
1193 break;
1194 }
1195
1196 if (kill(pid: GetID(), SIGKILL) != 0) {
1197 error = Status::FromErrno();
1198 return error;
1199 }
1200
1201 return error;
1202}
1203
1204Status NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr,
1205 MemoryRegionInfo &range_info) {
1206 // FIXME review that the final memory region returned extends to the end of
1207 // the virtual address space,
1208 // with no perms if it is not mapped.
1209
1210 // Use an approach that reads memory regions from /proc/{pid}/maps. Assume
1211 // proc maps entries are in ascending order.
1212 // FIXME assert if we find differently.
1213
1214 if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
1215 // We're done.
1216 return Status::FromErrorString(str: "unsupported");
1217 }
1218
1219 Status error = PopulateMemoryRegionCache();
1220 if (error.Fail()) {
1221 return error;
1222 }
1223
1224 lldb::addr_t prev_base_address = 0;
1225
1226 // FIXME start by finding the last region that is <= target address using
1227 // binary search. Data is sorted.
1228 // There can be a ton of regions on pthreads apps with lots of threads.
1229 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1230 ++it) {
1231 MemoryRegionInfo &proc_entry_info = it->first;
1232
1233 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1234 assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
1235 "descending /proc/pid/maps entries detected, unexpected");
1236 prev_base_address = proc_entry_info.GetRange().GetRangeBase();
1237 UNUSED_IF_ASSERT_DISABLED(prev_base_address);
1238
1239 // If the target address comes before this entry, indicate distance to next
1240 // region.
1241 if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1242 range_info.GetRange().SetRangeBase(load_addr);
1243 range_info.GetRange().SetByteSize(
1244 proc_entry_info.GetRange().GetRangeBase() - load_addr);
1245 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1246 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1247 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1248 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1249
1250 return error;
1251 } else if (proc_entry_info.GetRange().Contains(r: load_addr)) {
1252 // The target address is within the memory region we're processing here.
1253 range_info = proc_entry_info;
1254 return error;
1255 }
1256
1257 // The target memory address comes somewhere after the region we just
1258 // parsed.
1259 }
1260
1261 // If we made it here, we didn't find an entry that contained the given
1262 // address. Return the load_addr as start and the amount of bytes betwwen
1263 // load address and the end of the memory as size.
1264 range_info.GetRange().SetRangeBase(load_addr);
1265 range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
1266 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1267 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1268 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1269 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1270 return error;
1271}
1272
1273Status NativeProcessLinux::PopulateMemoryRegionCache() {
1274 Log *log = GetLog(mask: POSIXLog::Process);
1275
1276 // If our cache is empty, pull the latest. There should always be at least
1277 // one memory region if memory region handling is supported.
1278 if (!m_mem_region_cache.empty()) {
1279 LLDB_LOG(log, "reusing {0} cached memory region entries",
1280 m_mem_region_cache.size());
1281 return Status();
1282 }
1283
1284 Status Result;
1285 LinuxMapCallback callback = [&](llvm::Expected<MemoryRegionInfo> Info) {
1286 if (Info) {
1287 FileSpec file_spec(Info->GetName().GetCString());
1288 FileSystem::Instance().Resolve(file_spec);
1289 m_mem_region_cache.emplace_back(args&: *Info, args&: file_spec);
1290 return true;
1291 }
1292
1293 Result = Status::FromError(error: Info.takeError());
1294 m_supports_mem_region = LazyBool::eLazyBoolNo;
1295 LLDB_LOG(log, "failed to parse proc maps: {0}", Result);
1296 return false;
1297 };
1298
1299 // Linux kernel since 2.6.14 has /proc/{pid}/smaps
1300 // if CONFIG_PROC_PAGE_MONITOR is enabled
1301 auto BufferOrError = getProcFile(pid: GetID(), tid: GetCurrentThreadID(), file: "smaps");
1302 if (BufferOrError)
1303 ParseLinuxSMapRegions(linux_smap: BufferOrError.get()->getBuffer(), callback);
1304 else {
1305 BufferOrError = getProcFile(pid: GetID(), tid: GetCurrentThreadID(), file: "maps");
1306 if (!BufferOrError) {
1307 m_supports_mem_region = LazyBool::eLazyBoolNo;
1308 return BufferOrError.getError();
1309 }
1310
1311 ParseLinuxMapRegions(linux_map: BufferOrError.get()->getBuffer(), callback);
1312 }
1313
1314 if (Result.Fail())
1315 return Result;
1316
1317 if (m_mem_region_cache.empty()) {
1318 // No entries after attempting to read them. This shouldn't happen if
1319 // /proc/{pid}/maps is supported. Assume we don't support map entries via
1320 // procfs.
1321 m_supports_mem_region = LazyBool::eLazyBoolNo;
1322 LLDB_LOG(log,
1323 "failed to find any procfs maps entries, assuming no support "
1324 "for memory region metadata retrieval");
1325 return Status::FromErrorString(str: "not supported");
1326 }
1327
1328 LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps",
1329 m_mem_region_cache.size(), GetID());
1330
1331 // We support memory retrieval, remember that.
1332 m_supports_mem_region = LazyBool::eLazyBoolYes;
1333 return Status();
1334}
1335
1336void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
1337 Log *log = GetLog(mask: POSIXLog::Process);
1338 LLDB_LOG(log, "newBumpId={0}", newBumpId);
1339 LLDB_LOG(log, "clearing {0} entries from memory region cache",
1340 m_mem_region_cache.size());
1341 m_mem_region_cache.clear();
1342}
1343
1344llvm::Expected<uint64_t>
1345NativeProcessLinux::Syscall(llvm::ArrayRef<uint64_t> args) {
1346 PopulateMemoryRegionCache();
1347 auto region_it = llvm::find_if(Range&: m_mem_region_cache, P: [](const auto &pair) {
1348 return pair.first.GetExecutable() == MemoryRegionInfo::eYes &&
1349 pair.first.GetShared() != MemoryRegionInfo::eYes;
1350 });
1351 if (region_it == m_mem_region_cache.end())
1352 return llvm::createStringError(EC: llvm::inconvertibleErrorCode(),
1353 S: "No executable memory region found!");
1354
1355 addr_t exe_addr = region_it->first.GetRange().GetRangeBase();
1356
1357 NativeThreadLinux &thread = *GetCurrentThread();
1358 assert(thread.GetState() == eStateStopped);
1359 NativeRegisterContextLinux &reg_ctx = thread.GetRegisterContext();
1360
1361 NativeRegisterContextLinux::SyscallData syscall_data =
1362 *reg_ctx.GetSyscallData();
1363
1364 WritableDataBufferSP registers_sp;
1365 if (llvm::Error Err = reg_ctx.ReadAllRegisterValues(data_sp&: registers_sp).ToError())
1366 return std::move(Err);
1367 auto restore_regs = llvm::make_scope_exit(
1368 F: [&] { reg_ctx.WriteAllRegisterValues(data_sp: registers_sp); });
1369
1370 llvm::SmallVector<uint8_t, 8> memory(syscall_data.Insn.size());
1371 size_t bytes_read;
1372 if (llvm::Error Err =
1373 ReadMemory(addr: exe_addr, buf: memory.data(), size: memory.size(), bytes_read)
1374 .ToError()) {
1375 return std::move(Err);
1376 }
1377
1378 auto restore_mem = llvm::make_scope_exit(
1379 F: [&] { WriteMemory(addr: exe_addr, buf: memory.data(), size: memory.size(), bytes_written&: bytes_read); });
1380
1381 if (llvm::Error Err = reg_ctx.SetPC(exe_addr).ToError())
1382 return std::move(Err);
1383
1384 for (const auto &zip : llvm::zip_first(t&: args, u&: syscall_data.Args)) {
1385 if (llvm::Error Err =
1386 reg_ctx
1387 .WriteRegisterFromUnsigned(reg: std::get<1>(t: zip), uval: std::get<0>(t: zip))
1388 .ToError()) {
1389 return std::move(Err);
1390 }
1391 }
1392 if (llvm::Error Err = WriteMemory(addr: exe_addr, buf: syscall_data.Insn.data(),
1393 size: syscall_data.Insn.size(), bytes_written&: bytes_read)
1394 .ToError())
1395 return std::move(Err);
1396
1397 m_mem_region_cache.clear();
1398
1399 // With software single stepping the syscall insn buffer must also include a
1400 // trap instruction to stop the process.
1401 int req = SupportHardwareSingleStepping() ? PTRACE_SINGLESTEP : PTRACE_CONT;
1402 if (llvm::Error Err =
1403 PtraceWrapper(req, pid: thread.GetID(), addr: nullptr, data: nullptr).ToError())
1404 return std::move(Err);
1405
1406 int status;
1407 ::pid_t wait_pid = llvm::sys::RetryAfterSignal(Fail: -1, F&: ::waitpid, As: thread.GetID(),
1408 As: &status, __WALL);
1409 if (wait_pid == -1) {
1410 return llvm::errorCodeToError(
1411 EC: std::error_code(errno, std::generic_category()));
1412 }
1413 assert((unsigned)wait_pid == thread.GetID());
1414
1415 uint64_t result = reg_ctx.ReadRegisterAsUnsigned(reg: syscall_data.Result, fail_value: -ESRCH);
1416
1417 // Values larger than this are actually negative errno numbers.
1418 uint64_t errno_threshold =
1419 (uint64_t(-1) >> (64 - 8 * m_arch.GetAddressByteSize())) - 0x1000;
1420 if (result > errno_threshold) {
1421 return llvm::errorCodeToError(
1422 EC: std::error_code(-result & 0xfff, std::generic_category()));
1423 }
1424
1425 return result;
1426}
1427
1428llvm::Expected<addr_t>
1429NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions) {
1430
1431 std::optional<NativeRegisterContextLinux::MmapData> mmap_data =
1432 GetCurrentThread()->GetRegisterContext().GetMmapData();
1433 if (!mmap_data)
1434 return llvm::make_error<UnimplementedError>();
1435
1436 unsigned prot = PROT_NONE;
1437 assert((permissions & (ePermissionsReadable | ePermissionsWritable |
1438 ePermissionsExecutable)) == permissions &&
1439 "Unknown permission!");
1440 if (permissions & ePermissionsReadable)
1441 prot |= PROT_READ;
1442 if (permissions & ePermissionsWritable)
1443 prot |= PROT_WRITE;
1444 if (permissions & ePermissionsExecutable)
1445 prot |= PROT_EXEC;
1446
1447 llvm::Expected<uint64_t> Result =
1448 Syscall(args: {mmap_data->SysMmap, 0, size, prot, MAP_ANONYMOUS | MAP_PRIVATE,
1449 uint64_t(-1), 0});
1450 if (Result)
1451 m_allocated_memory.try_emplace(Key: *Result, Args&: size);
1452 return Result;
1453}
1454
1455llvm::Error NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {
1456 std::optional<NativeRegisterContextLinux::MmapData> mmap_data =
1457 GetCurrentThread()->GetRegisterContext().GetMmapData();
1458 if (!mmap_data)
1459 return llvm::make_error<UnimplementedError>();
1460
1461 auto it = m_allocated_memory.find(Val: addr);
1462 if (it == m_allocated_memory.end())
1463 return llvm::createStringError(EC: llvm::errc::invalid_argument,
1464 S: "Memory not allocated by the debugger.");
1465
1466 llvm::Expected<uint64_t> Result =
1467 Syscall(args: {mmap_data->SysMunmap, addr, it->second});
1468 if (!Result)
1469 return Result.takeError();
1470
1471 m_allocated_memory.erase(I: it);
1472 return llvm::Error::success();
1473}
1474
1475Status NativeProcessLinux::ReadMemoryTags(int32_t type, lldb::addr_t addr,
1476 size_t len,
1477 std::vector<uint8_t> &tags) {
1478 llvm::Expected<NativeRegisterContextLinux::MemoryTaggingDetails> details =
1479 GetCurrentThread()->GetRegisterContext().GetMemoryTaggingDetails(type);
1480 if (!details)
1481 return Status::FromError(error: details.takeError());
1482
1483 // Ignore 0 length read
1484 if (!len)
1485 return Status();
1486
1487 // lldb will align the range it requests but it is not required to by
1488 // the protocol so we'll do it again just in case.
1489 // Remove tag bits too. Ptrace calls may work regardless but that
1490 // is not a guarantee.
1491 MemoryTagManager::TagRange range(details->manager->RemoveTagBits(addr), len);
1492 range = details->manager->ExpandToGranule(range);
1493
1494 // Allocate enough space for all tags to be read
1495 size_t num_tags = range.GetByteSize() / details->manager->GetGranuleSize();
1496 tags.resize(new_size: num_tags * details->manager->GetTagSizeInBytes());
1497
1498 struct iovec tags_iovec;
1499 uint8_t *dest = tags.data();
1500 lldb::addr_t read_addr = range.GetRangeBase();
1501
1502 // This call can return partial data so loop until we error or
1503 // get all tags back.
1504 while (num_tags) {
1505 tags_iovec.iov_base = dest;
1506 tags_iovec.iov_len = num_tags;
1507
1508 Status error = NativeProcessLinux::PtraceWrapper(
1509 req: details->ptrace_read_req, pid: GetCurrentThreadID(),
1510 addr: reinterpret_cast<void *>(read_addr), data: static_cast<void *>(&tags_iovec),
1511 data_size: 0, result: nullptr);
1512
1513 if (error.Fail()) {
1514 // Discard partial reads
1515 tags.resize(new_size: 0);
1516 return error;
1517 }
1518
1519 size_t tags_read = tags_iovec.iov_len;
1520 assert(tags_read && (tags_read <= num_tags));
1521
1522 dest += tags_read * details->manager->GetTagSizeInBytes();
1523 read_addr += details->manager->GetGranuleSize() * tags_read;
1524 num_tags -= tags_read;
1525 }
1526
1527 return Status();
1528}
1529
1530Status NativeProcessLinux::WriteMemoryTags(int32_t type, lldb::addr_t addr,
1531 size_t len,
1532 const std::vector<uint8_t> &tags) {
1533 llvm::Expected<NativeRegisterContextLinux::MemoryTaggingDetails> details =
1534 GetCurrentThread()->GetRegisterContext().GetMemoryTaggingDetails(type);
1535 if (!details)
1536 return Status::FromError(error: details.takeError());
1537
1538 // Ignore 0 length write
1539 if (!len)
1540 return Status();
1541
1542 // lldb will align the range it requests but it is not required to by
1543 // the protocol so we'll do it again just in case.
1544 // Remove tag bits too. Ptrace calls may work regardless but that
1545 // is not a guarantee.
1546 MemoryTagManager::TagRange range(details->manager->RemoveTagBits(addr), len);
1547 range = details->manager->ExpandToGranule(range);
1548
1549 // Not checking number of tags here, we may repeat them below
1550 llvm::Expected<std::vector<lldb::addr_t>> unpacked_tags_or_err =
1551 details->manager->UnpackTagsData(tags);
1552 if (!unpacked_tags_or_err)
1553 return Status::FromError(error: unpacked_tags_or_err.takeError());
1554
1555 llvm::Expected<std::vector<lldb::addr_t>> repeated_tags_or_err =
1556 details->manager->RepeatTagsForRange(tags: *unpacked_tags_or_err, range);
1557 if (!repeated_tags_or_err)
1558 return Status::FromError(error: repeated_tags_or_err.takeError());
1559
1560 // Repack them for ptrace to use
1561 llvm::Expected<std::vector<uint8_t>> final_tag_data =
1562 details->manager->PackTags(tags: *repeated_tags_or_err);
1563 if (!final_tag_data)
1564 return Status::FromError(error: final_tag_data.takeError());
1565
1566 struct iovec tags_vec;
1567 uint8_t *src = final_tag_data->data();
1568 lldb::addr_t write_addr = range.GetRangeBase();
1569 // unpacked tags size because the number of bytes per tag might not be 1
1570 size_t num_tags = repeated_tags_or_err->size();
1571
1572 // This call can partially write tags, so we loop until we
1573 // error or all tags have been written.
1574 while (num_tags > 0) {
1575 tags_vec.iov_base = src;
1576 tags_vec.iov_len = num_tags;
1577
1578 Status error = NativeProcessLinux::PtraceWrapper(
1579 req: details->ptrace_write_req, pid: GetCurrentThreadID(),
1580 addr: reinterpret_cast<void *>(write_addr), data: static_cast<void *>(&tags_vec), data_size: 0,
1581 result: nullptr);
1582
1583 if (error.Fail()) {
1584 // Don't attempt to restore the original values in the case of a partial
1585 // write
1586 return error;
1587 }
1588
1589 size_t tags_written = tags_vec.iov_len;
1590 assert(tags_written && (tags_written <= num_tags));
1591
1592 src += tags_written * details->manager->GetTagSizeInBytes();
1593 write_addr += details->manager->GetGranuleSize() * tags_written;
1594 num_tags -= tags_written;
1595 }
1596
1597 return Status();
1598}
1599
1600size_t NativeProcessLinux::UpdateThreads() {
1601 // The NativeProcessLinux monitoring threads are always up to date with
1602 // respect to thread state and they keep the thread list populated properly.
1603 // All this method needs to do is return the thread count.
1604 return m_threads.size();
1605}
1606
1607Status NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,
1608 bool hardware) {
1609 if (hardware)
1610 return SetHardwareBreakpoint(addr, size);
1611 else
1612 return SetSoftwareBreakpoint(addr, size_hint: size);
1613}
1614
1615Status NativeProcessLinux::RemoveBreakpoint(lldb::addr_t addr, bool hardware) {
1616 if (hardware)
1617 return RemoveHardwareBreakpoint(addr);
1618 else
1619 return NativeProcessProtocol::RemoveBreakpoint(addr);
1620}
1621
1622llvm::Expected<llvm::ArrayRef<uint8_t>>
1623NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(size_t size_hint) {
1624 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1625 // linux kernel does otherwise.
1626 static const uint8_t g_arm_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1627 static const uint8_t g_thumb_opcode[] = {0x01, 0xde};
1628
1629 switch (GetArchitecture().GetMachine()) {
1630 case llvm::Triple::arm:
1631 switch (size_hint) {
1632 case 2:
1633 return llvm::ArrayRef(g_thumb_opcode);
1634 case 4:
1635 return llvm::ArrayRef(g_arm_opcode);
1636 default:
1637 return llvm::createStringError(EC: llvm::inconvertibleErrorCode(),
1638 S: "Unrecognised trap opcode size hint!");
1639 }
1640 default:
1641 return NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_hint);
1642 }
1643}
1644
1645Status NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
1646 size_t &bytes_read) {
1647 Log *log = GetLog(mask: POSIXLog::Memory);
1648 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
1649
1650 bytes_read = 0;
1651 if (ProcessVmReadvSupported()) {
1652 // The process_vm_readv path is about 50 times faster than ptrace api. We
1653 // want to use this syscall if it is supported.
1654
1655 struct iovec local_iov, remote_iov;
1656 local_iov.iov_base = buf;
1657 local_iov.iov_len = size;
1658 remote_iov.iov_base = reinterpret_cast<void *>(addr);
1659 remote_iov.iov_len = size;
1660
1661 ssize_t read_result = process_vm_readv(pid: GetCurrentThreadID(), lvec: &local_iov, liovcnt: 1,
1662 rvec: &remote_iov, riovcnt: 1, flags: 0);
1663 int error = 0;
1664 if (read_result < 0)
1665 error = errno;
1666 else
1667 bytes_read = read_result;
1668
1669 LLDB_LOG(log,
1670 "process_vm_readv({0}, [iovec({1}, {2})], [iovec({3:x}, {2})], 1, "
1671 "0) => {4} ({5})",
1672 GetCurrentThreadID(), buf, size, addr, read_result,
1673 error > 0 ? llvm::sys::StrError(errno) : "sucesss");
1674 }
1675
1676 unsigned char *dst = static_cast<unsigned char *>(buf);
1677 size_t remainder;
1678 long data;
1679
1680 for (; bytes_read < size; bytes_read += remainder) {
1681 Status error = NativeProcessLinux::PtraceWrapper(
1682 req: PTRACE_PEEKDATA, pid: GetCurrentThreadID(),
1683 addr: reinterpret_cast<void *>(addr + bytes_read), data: nullptr, data_size: 0, result: &data);
1684 if (error.Fail())
1685 return error;
1686
1687 remainder = size - bytes_read;
1688 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
1689
1690 // Copy the data into our buffer
1691 memcpy(dest: dst + bytes_read, src: &data, n: remainder);
1692 }
1693 return Status();
1694}
1695
1696Status NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,
1697 size_t size, size_t &bytes_written) {
1698 const unsigned char *src = static_cast<const unsigned char *>(buf);
1699 size_t remainder;
1700 Status error;
1701
1702 Log *log = GetLog(mask: POSIXLog::Memory);
1703 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
1704
1705 for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
1706 remainder = size - bytes_written;
1707 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
1708
1709 if (remainder == k_ptrace_word_size) {
1710 unsigned long data = 0;
1711 memcpy(dest: &data, src: src, n: k_ptrace_word_size);
1712
1713 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
1714 error = NativeProcessLinux::PtraceWrapper(
1715 req: PTRACE_POKEDATA, pid: GetCurrentThreadID(), addr: (void *)addr, data: (void *)data);
1716 if (error.Fail())
1717 return error;
1718 } else {
1719 unsigned char buff[8];
1720 size_t bytes_read;
1721 error = ReadMemory(addr, buf: buff, size: k_ptrace_word_size, bytes_read);
1722 if (error.Fail())
1723 return error;
1724
1725 memcpy(dest: buff, src: src, n: remainder);
1726
1727 size_t bytes_written_rec;
1728 error = WriteMemory(addr, buf: buff, size: k_ptrace_word_size, bytes_written&: bytes_written_rec);
1729 if (error.Fail())
1730 return error;
1731
1732 LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src,
1733 *(unsigned long *)buff);
1734 }
1735
1736 addr += k_ptrace_word_size;
1737 src += k_ptrace_word_size;
1738 }
1739 return error;
1740}
1741
1742Status NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) const {
1743 return PtraceWrapper(req: PTRACE_GETSIGINFO, pid: tid, addr: nullptr, data: siginfo);
1744}
1745
1746Status NativeProcessLinux::GetEventMessage(lldb::tid_t tid,
1747 unsigned long *message) {
1748 return PtraceWrapper(req: PTRACE_GETEVENTMSG, pid: tid, addr: nullptr, data: message);
1749}
1750
1751Status NativeProcessLinux::Detach(lldb::tid_t tid) {
1752 if (tid == LLDB_INVALID_THREAD_ID)
1753 return Status();
1754
1755 return PtraceWrapper(req: PTRACE_DETACH, pid: tid);
1756}
1757
1758bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {
1759 for (const auto &thread : m_threads) {
1760 assert(thread && "thread list should not contain NULL threads");
1761 if (thread->GetID() == thread_id) {
1762 // We have this thread.
1763 return true;
1764 }
1765 }
1766
1767 // We don't have this thread.
1768 return false;
1769}
1770
1771void NativeProcessLinux::StopTrackingThread(NativeThreadLinux &thread) {
1772 Log *const log = GetLog(mask: POSIXLog::Thread);
1773 lldb::tid_t thread_id = thread.GetID();
1774 LLDB_LOG(log, "tid: {0}", thread_id);
1775
1776 auto it = llvm::find_if(Range&: m_threads, P: [&](const auto &thread_up) {
1777 return thread_up.get() == &thread;
1778 });
1779 assert(it != m_threads.end());
1780 m_threads.erase(position: it);
1781
1782 NotifyTracersOfThreadDestroyed(tid: thread_id);
1783 SignalIfAllThreadsStopped();
1784}
1785
1786void NativeProcessLinux::NotifyTracersProcessDidStop() {
1787 m_intel_pt_collector.ProcessDidStop();
1788}
1789
1790void NativeProcessLinux::NotifyTracersProcessWillResume() {
1791 m_intel_pt_collector.ProcessWillResume();
1792}
1793
1794Status NativeProcessLinux::NotifyTracersOfNewThread(lldb::tid_t tid) {
1795 Log *log = GetLog(mask: POSIXLog::Thread);
1796 Status error = Status::FromError(error: m_intel_pt_collector.OnThreadCreated(tid));
1797 if (error.Fail())
1798 LLDB_LOG(log, "Failed to trace a new thread with intel-pt, tid = {0}. {1}",
1799 tid, error.AsCString());
1800 return error;
1801}
1802
1803Status NativeProcessLinux::NotifyTracersOfThreadDestroyed(lldb::tid_t tid) {
1804 Log *log = GetLog(mask: POSIXLog::Thread);
1805 Status error = Status::FromError(error: m_intel_pt_collector.OnThreadDestroyed(tid));
1806 if (error.Fail())
1807 LLDB_LOG(log,
1808 "Failed to stop a destroyed thread with intel-pt, tid = {0}. {1}",
1809 tid, error.AsCString());
1810 return error;
1811}
1812
1813NativeThreadLinux &NativeProcessLinux::AddThread(lldb::tid_t thread_id,
1814 bool resume) {
1815 Log *log = GetLog(mask: POSIXLog::Thread);
1816 LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
1817
1818 assert(!HasThreadNoLock(thread_id) &&
1819 "attempted to add a thread by id that already exists");
1820
1821 // If this is the first thread, save it as the current thread
1822 if (m_threads.empty())
1823 SetCurrentThreadID(thread_id);
1824
1825 m_threads.push_back(x: std::make_unique<NativeThreadLinux>(args&: *this, args&: thread_id));
1826 NativeThreadLinux &thread =
1827 static_cast<NativeThreadLinux &>(*m_threads.back());
1828
1829 Status tracing_error = NotifyTracersOfNewThread(tid: thread.GetID());
1830 if (tracing_error.Fail()) {
1831 thread.SetStoppedByProcessorTrace(tracing_error.AsCString());
1832 StopRunningThreads(triggering_tid: thread.GetID());
1833 } else if (resume)
1834 ResumeThread(thread, state: eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
1835 else
1836 thread.SetStoppedBySignal(SIGSTOP);
1837
1838 return thread;
1839}
1840
1841Status NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,
1842 FileSpec &file_spec) {
1843 Status error = PopulateMemoryRegionCache();
1844 if (error.Fail())
1845 return error;
1846
1847 FileSpec module_file_spec(module_path);
1848 FileSystem::Instance().Resolve(file_spec&: module_file_spec);
1849
1850 file_spec.Clear();
1851 for (const auto &it : m_mem_region_cache) {
1852 if (it.second.GetFilename() == module_file_spec.GetFilename()) {
1853 file_spec = it.second;
1854 return Status();
1855 }
1856 }
1857 return Status::FromErrorStringWithFormat(
1858 format: "Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
1859 module_file_spec.GetFilename().AsCString(), GetID());
1860}
1861
1862Status NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
1863 lldb::addr_t &load_addr) {
1864 load_addr = LLDB_INVALID_ADDRESS;
1865 Status error = PopulateMemoryRegionCache();
1866 if (error.Fail())
1867 return error;
1868
1869 FileSpec file(file_name);
1870 for (const auto &it : m_mem_region_cache) {
1871 if (it.second == file) {
1872 load_addr = it.first.GetRange().GetRangeBase();
1873 return Status();
1874 }
1875 }
1876 return Status::FromErrorString(str: "No load address found for specified file.");
1877}
1878
1879NativeThreadLinux *NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {
1880 return static_cast<NativeThreadLinux *>(
1881 NativeProcessProtocol::GetThreadByID(tid));
1882}
1883
1884NativeThreadLinux *NativeProcessLinux::GetCurrentThread() {
1885 return static_cast<NativeThreadLinux *>(
1886 NativeProcessProtocol::GetCurrentThread());
1887}
1888
1889Status NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,
1890 lldb::StateType state, int signo) {
1891 Log *const log = GetLog(mask: POSIXLog::Thread);
1892 LLDB_LOG(log, "tid: {0}", thread.GetID());
1893
1894 // Before we do the resume below, first check if we have a pending stop
1895 // notification that is currently waiting for all threads to stop. This is
1896 // potentially a buggy situation since we're ostensibly waiting for threads
1897 // to stop before we send out the pending notification, and here we are
1898 // resuming one before we send out the pending stop notification.
1899 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
1900 LLDB_LOG(log,
1901 "about to resume tid {0} per explicit request but we have a "
1902 "pending stop notification (tid {1}) that is actively "
1903 "waiting for this thread to stop. Valid sequence of events?",
1904 thread.GetID(), m_pending_notification_tid);
1905 }
1906
1907 // Request a resume. We expect this to be synchronous and the system to
1908 // reflect it is running after this completes.
1909 switch (state) {
1910 case eStateRunning: {
1911 Status resume_result = thread.Resume(signo);
1912 if (resume_result.Success())
1913 SetState(state: eStateRunning, notify_delegates: true);
1914 return resume_result;
1915 }
1916 case eStateStepping: {
1917 Status step_result = thread.SingleStep(signo);
1918 if (step_result.Success())
1919 SetState(state: eStateRunning, notify_delegates: true);
1920 return step_result;
1921 }
1922 default:
1923 LLDB_LOG(log, "Unhandled state {0}.", state);
1924 llvm_unreachable("Unhandled state for resume");
1925 }
1926}
1927
1928//===----------------------------------------------------------------------===//
1929
1930void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {
1931 Log *const log = GetLog(mask: POSIXLog::Thread);
1932 LLDB_LOG(log, "about to process event: (triggering_tid: {0})",
1933 triggering_tid);
1934
1935 m_pending_notification_tid = triggering_tid;
1936
1937 // Request a stop for all the thread stops that need to be stopped and are
1938 // not already known to be stopped.
1939 for (const auto &thread : m_threads) {
1940 if (StateIsRunningState(state: thread->GetState()))
1941 static_cast<NativeThreadLinux *>(thread.get())->RequestStop();
1942 }
1943
1944 SignalIfAllThreadsStopped();
1945 LLDB_LOG(log, "event processing done");
1946}
1947
1948void NativeProcessLinux::SignalIfAllThreadsStopped() {
1949 if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
1950 return; // No pending notification. Nothing to do.
1951
1952 for (const auto &thread_sp : m_threads) {
1953 if (StateIsRunningState(state: thread_sp->GetState()))
1954 return; // Some threads are still running. Don't signal yet.
1955 }
1956
1957 // We have a pending notification and all threads have stopped.
1958 Log *log = GetLog(mask: LLDBLog::Process | LLDBLog::Breakpoints);
1959
1960 // Clear any temporary breakpoints we used to implement software single
1961 // stepping.
1962 for (const auto &thread_info : m_threads_stepping_with_breakpoint) {
1963 Status error = RemoveBreakpoint(addr: thread_info.second);
1964 if (error.Fail())
1965 LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}",
1966 thread_info.first, error);
1967 }
1968 m_threads_stepping_with_breakpoint.clear();
1969
1970 // Notify the delegate about the stop
1971 SetCurrentThreadID(m_pending_notification_tid);
1972 SetState(state: StateType::eStateStopped, notify_delegates: true);
1973 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
1974}
1975
1976void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {
1977 Log *const log = GetLog(mask: POSIXLog::Thread);
1978 LLDB_LOG(log, "tid: {0}", thread.GetID());
1979
1980 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID &&
1981 StateIsRunningState(state: thread.GetState())) {
1982 // We will need to wait for this new thread to stop as well before firing
1983 // the notification.
1984 thread.RequestStop();
1985 }
1986}
1987
1988// Wrapper for ptrace to catch errors and log calls. Note that ptrace sets
1989// errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
1990Status NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
1991 void *data, size_t data_size,
1992 long *result) {
1993 Status error;
1994 long int ret;
1995
1996 Log *log = GetLog(mask: POSIXLog::Ptrace);
1997
1998 PtraceDisplayBytes(req, data, data_size);
1999
2000 errno = 0;
2001 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
2002 ret = ptrace(request: static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2003 *(unsigned int *)addr, data);
2004 else
2005 ret = ptrace(request: static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2006 addr, data);
2007
2008 if (ret == -1)
2009 error = Status::FromErrno();
2010
2011 if (result)
2012 *result = ret;
2013
2014 LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data,
2015 data_size, ret);
2016
2017 PtraceDisplayBytes(req, data, data_size);
2018
2019 if (error.Fail())
2020 LLDB_LOG(log, "ptrace() failed: {0}", error);
2021
2022 return error;
2023}
2024
2025llvm::Expected<TraceSupportedResponse> NativeProcessLinux::TraceSupported() {
2026 if (IntelPTCollector::IsSupported())
2027 return TraceSupportedResponse{.name: "intel-pt", .description: "Intel Processor Trace"};
2028 return NativeProcessProtocol::TraceSupported();
2029}
2030
2031Error NativeProcessLinux::TraceStart(StringRef json_request, StringRef type) {
2032 if (type == "intel-pt") {
2033 if (Expected<TraceIntelPTStartRequest> request =
2034 json::parse<TraceIntelPTStartRequest>(JSON: json_request,
2035 RootName: "TraceIntelPTStartRequest")) {
2036 return m_intel_pt_collector.TraceStart(request: *request);
2037 } else
2038 return request.takeError();
2039 }
2040
2041 return NativeProcessProtocol::TraceStart(json_params: json_request, type);
2042}
2043
2044Error NativeProcessLinux::TraceStop(const TraceStopRequest &request) {
2045 if (request.type == "intel-pt")
2046 return m_intel_pt_collector.TraceStop(request);
2047 return NativeProcessProtocol::TraceStop(request);
2048}
2049
2050Expected<json::Value> NativeProcessLinux::TraceGetState(StringRef type) {
2051 if (type == "intel-pt")
2052 return m_intel_pt_collector.GetState();
2053 return NativeProcessProtocol::TraceGetState(type);
2054}
2055
2056Expected<std::vector<uint8_t>> NativeProcessLinux::TraceGetBinaryData(
2057 const TraceGetBinaryDataRequest &request) {
2058 if (request.type == "intel-pt")
2059 return m_intel_pt_collector.GetBinaryData(request);
2060 return NativeProcessProtocol::TraceGetBinaryData(request);
2061}
2062

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