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