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