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