LLDB mainline
NativeProcessLinux.cpp
Go to the documentation of this file.
1//===-- NativeProcessLinux.cpp --------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10
11#include <cerrno>
12#include <cstdint>
13#include <cstring>
14#include <unistd.h>
15
16#include <fstream>
17#include <mutex>
18#include <optional>
19#include <sstream>
20#include <string>
21#include <unordered_map>
22
23#include "NativeThreadLinux.h"
26#include "Procfs.h"
28#include "lldb/Host/Host.h"
36#include "lldb/Host/linux/Uio.h"
39#include "lldb/Target/Process.h"
40#include "lldb/Target/Target.h"
43#include "lldb/Utility/State.h"
44#include "lldb/Utility/Status.h"
46#include "llvm/ADT/ScopeExit.h"
47#include "llvm/Support/Errno.h"
48#include "llvm/Support/Error.h"
49#include "llvm/Support/FileSystem.h"
50#include "llvm/Support/Threading.h"
51
52#include <linux/unistd.h>
53#include <sys/socket.h>
54#include <sys/syscall.h>
55#include <sys/types.h>
56#include <sys/user.h>
57#include <sys/wait.h>
58
59#ifdef __aarch64__
60#include <asm/hwcap.h>
61#include <sys/auxv.h>
62#endif
63
64// Support hardware breakpoints in case it has not been defined
65#ifndef TRAP_HWBKPT
66#define TRAP_HWBKPT 4
67#endif
68
69#ifndef HWCAP2_MTE
70#define HWCAP2_MTE (1 << 18)
71#endif
72
73using namespace lldb;
74using namespace lldb_private;
75using namespace lldb_private::process_linux;
76using namespace llvm;
77
78// Private bits we only need internally.
79
81 static bool is_supported;
82 static llvm::once_flag flag;
83
84 llvm::call_once(flag, [] {
85 Log *log = GetLog(POSIXLog::Process);
86
87 uint32_t source = 0x47424742;
88 uint32_t dest = 0;
89
90 struct iovec local, remote;
91 remote.iov_base = &source;
92 local.iov_base = &dest;
93 remote.iov_len = local.iov_len = sizeof source;
94
95 // We shall try if cross-process-memory reads work by attempting to read a
96 // value from our own process.
97 ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
98 is_supported = (res == sizeof(source) && source == dest);
99 if (is_supported)
100 LLDB_LOG(log,
101 "Detected kernel support for process_vm_readv syscall. "
102 "Fast memory reads enabled.");
103 else
104 LLDB_LOG(log,
105 "syscall process_vm_readv failed (error: {0}). Fast memory "
106 "reads disabled.",
107 llvm::sys::StrError());
108 });
109
110 return is_supported;
111}
112
113static void MaybeLogLaunchInfo(const ProcessLaunchInfo &info) {
114 Log *log = GetLog(POSIXLog::Process);
115 if (!log)
116 return;
117
118 if (const FileAction *action = info.GetFileActionForFD(STDIN_FILENO))
119 LLDB_LOG(log, "setting STDIN to '{0}'", action->GetFileSpec());
120 else
121 LLDB_LOG(log, "leaving STDIN as is");
122
123 if (const FileAction *action = info.GetFileActionForFD(STDOUT_FILENO))
124 LLDB_LOG(log, "setting STDOUT to '{0}'", action->GetFileSpec());
125 else
126 LLDB_LOG(log, "leaving STDOUT as is");
127
128 if (const FileAction *action = info.GetFileActionForFD(STDERR_FILENO))
129 LLDB_LOG(log, "setting STDERR to '{0}'", action->GetFileSpec());
130 else
131 LLDB_LOG(log, "leaving STDERR as is");
132
133 int i = 0;
134 for (const char **args = info.GetArguments().GetConstArgumentVector(); *args;
135 ++args, ++i)
136 LLDB_LOG(log, "arg {0}: '{1}'", i, *args);
137}
138
139static void DisplayBytes(StreamString &s, void *bytes, uint32_t count) {
140 uint8_t *ptr = (uint8_t *)bytes;
141 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
142 for (uint32_t i = 0; i < loop_count; i++) {
143 s.Printf("[%x]", *ptr);
144 ptr++;
145 }
146}
147
148static void PtraceDisplayBytes(int &req, void *data, size_t data_size) {
149 Log *log = GetLog(POSIXLog::Ptrace);
150 if (!log)
151 return;
152 StreamString buf;
153
154 switch (req) {
155 case PTRACE_POKETEXT: {
156 DisplayBytes(buf, &data, 8);
157 LLDB_LOGV(log, "PTRACE_POKETEXT {0}", buf.GetData());
158 break;
159 }
160 case PTRACE_POKEDATA: {
161 DisplayBytes(buf, &data, 8);
162 LLDB_LOGV(log, "PTRACE_POKEDATA {0}", buf.GetData());
163 break;
164 }
165 case PTRACE_POKEUSER: {
166 DisplayBytes(buf, &data, 8);
167 LLDB_LOGV(log, "PTRACE_POKEUSER {0}", buf.GetData());
168 break;
169 }
170 case PTRACE_SETREGS: {
171 DisplayBytes(buf, data, data_size);
172 LLDB_LOGV(log, "PTRACE_SETREGS {0}", buf.GetData());
173 break;
174 }
175 case PTRACE_SETFPREGS: {
176 DisplayBytes(buf, data, data_size);
177 LLDB_LOGV(log, "PTRACE_SETFPREGS {0}", buf.GetData());
178 break;
179 }
180 case PTRACE_SETSIGINFO: {
181 DisplayBytes(buf, data, sizeof(siginfo_t));
182 LLDB_LOGV(log, "PTRACE_SETSIGINFO {0}", buf.GetData());
183 break;
184 }
185 case PTRACE_SETREGSET: {
186 // Extract iov_base from data, which is a pointer to the struct iovec
187 DisplayBytes(buf, *(void **)data, data_size);
188 LLDB_LOGV(log, "PTRACE_SETREGSET {0}", buf.GetData());
189 break;
190 }
191 default: {}
192 }
193}
194
195static constexpr unsigned k_ptrace_word_size = sizeof(void *);
196static_assert(sizeof(long) >= k_ptrace_word_size,
197 "Size of long must be larger than ptrace word size");
198
199// Simple helper function to ensure flags are enabled on the given file
200// descriptor.
201static Status EnsureFDFlags(int fd, int flags) {
203
204 int status = fcntl(fd, F_GETFL);
205 if (status == -1) {
206 error.SetErrorToErrno();
207 return error;
208 }
209
210 if (fcntl(fd, F_SETFL, status | flags) == -1) {
211 error.SetErrorToErrno();
212 return error;
213 }
214
215 return error;
216}
217
218static llvm::Error AddPtraceScopeNote(llvm::Error original_error) {
219 Expected<int> ptrace_scope = GetPtraceScope();
220 if (auto E = ptrace_scope.takeError()) {
221 Log *log = GetLog(POSIXLog::Process);
222 LLDB_LOG(log, "error reading value of ptrace_scope: {0}", E);
223
224 // The original error is probably more interesting than not being able to
225 // read or interpret ptrace_scope.
226 return original_error;
227 }
228
229 // We only have suggestions to provide for 1-3.
230 switch (*ptrace_scope) {
231 case 1:
232 case 2:
233 return llvm::createStringError(
234 std::error_code(errno, std::generic_category()),
235 "The current value of ptrace_scope is %d, which can cause ptrace to "
236 "fail to attach to a running process. To fix this, run:\n"
237 "\tsudo sysctl -w kernel.yama.ptrace_scope=0\n"
238 "For more information, see: "
239 "https://www.kernel.org/doc/Documentation/security/Yama.txt.",
240 *ptrace_scope);
241 case 3:
242 return llvm::createStringError(
243 std::error_code(errno, std::generic_category()),
244 "The current value of ptrace_scope is 3, which will cause ptrace to "
245 "fail to attach to a running process. This value cannot be changed "
246 "without rebooting.\n"
247 "For more information, see: "
248 "https://www.kernel.org/doc/Documentation/security/Yama.txt.");
249 case 0:
250 default:
251 return original_error;
252 }
253}
254
256 : NativeProcessProtocol::Manager(mainloop) {
257 Status status;
259 SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status);
260 assert(m_sigchld_handle && status.Success());
261}
262
263llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
265 NativeDelegate &native_delegate) {
267
268 MaybeLogLaunchInfo(launch_info);
269
270 Status status;
272 .LaunchProcess(launch_info, status)
273 .GetProcessId();
274 LLDB_LOG(log, "pid = {0:x}", pid);
275 if (status.Fail()) {
276 LLDB_LOG(log, "failed to launch process: {0}", status);
277 return status.ToError();
278 }
279
280 // Wait for the child process to trap on its call to execve.
281 int wstatus = 0;
282 ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0);
283 assert(wpid == pid);
285 if (!WIFSTOPPED(wstatus)) {
286 LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}",
287 WaitStatus::Decode(wstatus));
288 return llvm::make_error<StringError>("Could not sync with inferior process",
289 llvm::inconvertibleErrorCode());
290 }
291 LLDB_LOG(log, "inferior started, now in stopped state");
292
293 status = SetDefaultPtraceOpts(pid);
294 if (status.Fail()) {
295 LLDB_LOG(log, "failed to set default ptrace options: {0}", status);
296 return status.ToError();
297 }
298
299 llvm::Expected<ArchSpec> arch_or =
301 if (!arch_or)
302 return arch_or.takeError();
303
304 return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
305 pid, launch_info.GetPTY().ReleasePrimaryFileDescriptor(), native_delegate,
306 *arch_or, *this, {pid}));
307}
308
309llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
313 LLDB_LOG(log, "pid = {0:x}", pid);
314
315 auto tids_or = NativeProcessLinux::Attach(pid);
316 if (!tids_or)
317 return tids_or.takeError();
318 ArrayRef<::pid_t> tids = *tids_or;
319 llvm::Expected<ArchSpec> arch_or =
321 if (!arch_or)
322 return arch_or.takeError();
323
324 return std::unique_ptr<NativeProcessLinux>(
325 new NativeProcessLinux(pid, -1, native_delegate, *arch_or, *this, tids));
326}
327
334
335#ifdef __aarch64__
336 // At this point we do not have a process so read auxv directly.
337 if ((getauxval(AT_HWCAP2) & HWCAP2_MTE))
338 supported |= Extension::memory_tagging;
339#endif
340
341 return supported;
342}
343
344static std::optional<std::pair<lldb::pid_t, WaitStatus>> WaitPid() {
346
347 int status;
348 ::pid_t wait_pid = llvm::sys::RetryAfterSignal(
349 -1, ::waitpid, -1, &status, __WALL | __WNOTHREAD | WNOHANG);
350
351 if (wait_pid == 0)
352 return std::nullopt;
353
354 if (wait_pid == -1) {
356 LLDB_LOG(log, "waitpid(-1, &status, _) failed: {1}", error);
357 return std::nullopt;
358 }
359
360 WaitStatus wait_status = WaitStatus::Decode(status);
361
362 LLDB_LOG(log, "waitpid(-1, &status, _) = {0}, status = {1}", wait_pid,
363 wait_status);
364 return std::make_pair(wait_pid, wait_status);
365}
366
369 while (true) {
370 auto wait_result = WaitPid();
371 if (!wait_result)
372 return;
373 lldb::pid_t pid = wait_result->first;
374 WaitStatus status = wait_result->second;
375
376 // Ask each process whether it wants to handle the event. Each event should
377 // be handled by exactly one process, but thread creation events require
378 // special handling.
379 // Thread creation consists of two events (one on the parent and one on the
380 // child thread) and they can arrive in any order nondeterministically. The
381 // parent event carries the information about the child thread, but not
382 // vice-versa. This means that if the child event arrives first, it may not
383 // be handled by any process (because it doesn't know the thread belongs to
384 // it).
385 bool handled = llvm::any_of(m_processes, [&](NativeProcessLinux *process) {
386 return process->TryHandleWaitStatus(pid, status);
387 });
388 if (!handled) {
389 if (status.type == WaitStatus::Stop && status.status == SIGSTOP) {
390 // Store the thread creation event for later collection.
391 m_unowned_threads.insert(pid);
392 } else {
393 LLDB_LOG(log, "Ignoring waitpid event {0} for pid {1}", status, pid);
394 }
395 }
396 }
397}
398
401
402 if (m_unowned_threads.erase(tid))
403 return; // We've encountered this thread already.
404
405 // The TID is not tracked yet, let's wait for it to appear.
406 int status = -1;
407 LLDB_LOG(log,
408 "received clone event for tid {0}. tid not tracked yet, "
409 "waiting for it to appear...",
410 tid);
411 ::pid_t wait_pid =
412 llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, &status, __WALL);
413
414 // It's theoretically possible to get other events if the entire process was
415 // SIGKILLed before we got a chance to check this. In that case, we'll just
416 // clean everything up when we get the process exit event.
417
418 LLDB_LOG(log,
419 "waitpid({0}, &status, __WALL) => {1} (errno: {2}, status = {3})",
420 tid, wait_pid, errno, WaitStatus::Decode(status));
421}
422
423// Public Instance Methods
424
426 NativeDelegate &delegate,
427 const ArchSpec &arch, Manager &manager,
428 llvm::ArrayRef<::pid_t> tids)
429 : NativeProcessELF(pid, terminal_fd, delegate), m_manager(manager),
430 m_arch(arch), m_intel_pt_collector(*this) {
431 manager.AddProcess(*this);
432 if (m_terminal_fd != -1) {
434 assert(status.Success());
435 }
436
437 for (const auto &tid : tids) {
438 NativeThreadLinux &thread = AddThread(tid, /*resume*/ false);
439 ThreadWasCreated(thread);
440 }
441
442 // Let our process instance know the thread has stopped.
443 SetCurrentThreadID(tids[0]);
444 SetState(StateType::eStateStopped, false);
445}
446
447llvm::Expected<std::vector<::pid_t>> NativeProcessLinux::Attach(::pid_t pid) {
449
450 Status status;
451 // Use a map to keep track of the threads which we have attached/need to
452 // attach.
453 Host::TidMap tids_to_attach;
454 while (Host::FindProcessThreads(pid, tids_to_attach)) {
455 for (Host::TidMap::iterator it = tids_to_attach.begin();
456 it != tids_to_attach.end();) {
457 if (it->second == false) {
458 lldb::tid_t tid = it->first;
459
460 // Attach to the requested process.
461 // An attach will cause the thread to stop with a SIGSTOP.
462 if ((status = PtraceWrapper(PTRACE_ATTACH, tid)).Fail()) {
463 // No such thread. The thread may have exited. More error handling
464 // may be needed.
465 if (status.GetError() == ESRCH) {
466 it = tids_to_attach.erase(it);
467 continue;
468 }
469 if (status.GetError() == EPERM) {
470 // Depending on the value of ptrace_scope, we can return a different
471 // error that suggests how to fix it.
472 return AddPtraceScopeNote(status.ToError());
473 }
474 return status.ToError();
475 }
476
477 int wpid =
478 llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, nullptr, __WALL);
479 // Need to use __WALL otherwise we receive an error with errno=ECHLD At
480 // this point we should have a thread stopped if waitpid succeeds.
481 if (wpid < 0) {
482 // No such thread. The thread may have exited. More error handling
483 // may be needed.
484 if (errno == ESRCH) {
485 it = tids_to_attach.erase(it);
486 continue;
487 }
488 return llvm::errorCodeToError(
489 std::error_code(errno, std::generic_category()));
490 }
491
492 if ((status = SetDefaultPtraceOpts(tid)).Fail())
493 return status.ToError();
494
495 LLDB_LOG(log, "adding tid = {0}", tid);
496 it->second = true;
497 }
498
499 // move the loop forward
500 ++it;
501 }
502 }
503
504 size_t tid_count = tids_to_attach.size();
505 if (tid_count == 0)
506 return llvm::make_error<StringError>("No such process",
507 llvm::inconvertibleErrorCode());
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());
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());
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
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;
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;
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#if defined __mips__
772 // For mips there is no special signal for watchpoint So we check for
773 // watchpoint in kernel trap
774 {
775 // If a watchpoint was hit, report it
776 uint32_t wp_index;
778 wp_index, LLDB_INVALID_ADDRESS);
779 if (error.Fail())
780 LLDB_LOG(log,
781 "received error while checking for watchpoint hits, pid = "
782 "{0}, error = {1}",
783 thread.GetID(), error);
784 if (wp_index != LLDB_INVALID_INDEX32) {
785 MonitorWatchpoint(thread, wp_index);
786 break;
787 }
788 }
789// NO BREAK
790#endif
791 case TRAP_BRKPT:
792 MonitorBreakpoint(thread);
793 break;
794
795 case SIGTRAP:
796 case (SIGTRAP | 0x80):
797 LLDB_LOG(
798 log,
799 "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",
800 info.si_code, GetID(), thread.GetID());
801
802 // Ignore these signals until we know more about them.
804 break;
805
806 default:
807 LLDB_LOG(log, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}",
808 info.si_code, GetID(), thread.GetID());
809 MonitorSignal(info, thread);
810 break;
811 }
812}
813
816 LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID());
817
818 // This thread is currently stopped.
819 thread.SetStoppedByTrace();
820
821 StopRunningThreads(thread.GetID());
822}
823
826 LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID());
827
828 // Mark the thread as stopped at breakpoint.
829 thread.SetStoppedByBreakpoint();
831
832 if (m_threads_stepping_with_breakpoint.find(thread.GetID()) !=
834 thread.SetStoppedByTrace();
835
836 StopRunningThreads(thread.GetID());
837}
838
840 uint32_t wp_index) {
842 LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}",
843 thread.GetID(), wp_index);
844
845 // Mark the thread as stopped at watchpoint. The address is at
846 // (lldb::addr_t)info->si_addr if we need it.
847 thread.SetStoppedByWatchpoint(wp_index);
848
849 // We need to tell all other running threads before we notify the delegate
850 // about this stop.
851 StopRunningThreads(thread.GetID());
852}
853
854void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
855 NativeThreadLinux &thread) {
856 const int signo = info.si_signo;
857 const bool is_from_llgs = info.si_pid == getpid();
858
860
861 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
862 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a kill(2)
863 // or raise(3). Similarly for tgkill(2) on Linux.
864 //
865 // IOW, user generated signals never generate what we consider to be a
866 // "crash".
867 //
868 // Similarly, ACK signals generated by this monitor.
869
870 // Handle the signal.
871 LLDB_LOG(log,
872 "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
873 "waitpid pid = {4})",
874 Host::GetSignalAsCString(signo), signo, info.si_code,
875 thread.GetID());
876
877 // Check for thread stop notification.
878 if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) {
879 // This is a tgkill()-based stop.
880 LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID());
881
882 // Check that we're not already marked with a stop reason. Note this thread
883 // really shouldn't already be marked as stopped - if we were, that would
884 // imply that the kernel signaled us with the thread stopping which we
885 // handled and marked as stopped, and that, without an intervening resume,
886 // we received another stop. It is more likely that we are missing the
887 // marking of a run state somewhere if we find that the thread was marked
888 // as stopped.
889 const StateType thread_state = thread.GetState();
890 if (!StateIsStoppedState(thread_state, false)) {
891 // An inferior thread has stopped because of a SIGSTOP we have sent it.
892 // Generally, these are not important stops and we don't want to report
893 // them as they are just used to stop other threads when one thread (the
894 // one with the *real* stop reason) hits a breakpoint (watchpoint,
895 // etc...). However, in the case of an asynchronous Interrupt(), this
896 // *is* the real stop reason, so we leave the signal intact if this is
897 // the thread that was chosen as the triggering thread.
899 if (m_pending_notification_tid == thread.GetID())
900 thread.SetStoppedBySignal(SIGSTOP, &info);
901 else
902 thread.SetStoppedWithNoReason();
903
904 SetCurrentThreadID(thread.GetID());
906 } else {
907 // We can end up here if stop was initiated by LLGS but by this time a
908 // thread stop has occurred - maybe initiated by another event.
909 Status error = ResumeThread(thread, thread.GetState(), 0);
910 if (error.Fail())
911 LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(),
912 error);
913 }
914 } else {
915 LLDB_LOG(log,
916 "pid {0} tid {1}, thread was already marked as a stopped "
917 "state (state={2}), leaving stop signal as is",
918 GetID(), thread.GetID(), thread_state);
920 }
921
922 // Done handling.
923 return;
924 }
925
926 // Check if debugger should stop at this signal or just ignore it and resume
927 // the inferior.
928 if (m_signals_to_ignore.contains(signo)) {
929 ResumeThread(thread, thread.GetState(), signo);
930 return;
931 }
932
933 // This thread is stopped.
934 LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo));
935 thread.SetStoppedBySignal(signo, &info);
936
937 // Send a stop to the debugger after we get all other threads to stop.
938 StopRunningThreads(thread.GetID());
939}
940
942 lldb::pid_t child_pid, int event) {
944 LLDB_LOG(log, "parent_tid={0}, child_pid={1}, event={2}", parent.GetID(),
945 child_pid, event);
946
947 m_manager.CollectThread(child_pid);
948
949 switch (event) {
950 case PTRACE_EVENT_CLONE: {
951 // PTRACE_EVENT_CLONE can either mean a new thread or a new process.
952 // Try to grab the new process' PGID to figure out which one it is.
953 // If PGID is the same as the PID, then it's a new process. Otherwise,
954 // it's a thread.
955 auto tgid_ret = getPIDForTID(child_pid);
956 if (tgid_ret != child_pid) {
957 // A new thread should have PGID matching our process' PID.
958 assert(!tgid_ret || *tgid_ret == GetID());
959
960 NativeThreadLinux &child_thread = AddThread(child_pid, /*resume*/ true);
961 ThreadWasCreated(child_thread);
962
963 // Resume the parent.
965 break;
966 }
967 }
968 [[fallthrough]];
969 case PTRACE_EVENT_FORK:
970 case PTRACE_EVENT_VFORK: {
971 bool is_vfork = event == PTRACE_EVENT_VFORK;
972 std::unique_ptr<NativeProcessLinux> child_process{new NativeProcessLinux(
973 static_cast<::pid_t>(child_pid), m_terminal_fd, m_delegate, m_arch,
974 m_manager, {static_cast<::pid_t>(child_pid)})};
975 if (!is_vfork)
977
978 Extension expected_ext = is_vfork ? Extension::vfork : Extension::fork;
979 if (bool(m_enabled_extensions & expected_ext)) {
980 m_delegate.NewSubprocess(this, std::move(child_process));
981 // NB: non-vfork clone() is reported as fork
982 parent.SetStoppedByFork(is_vfork, child_pid);
983 StopRunningThreads(parent.GetID());
984 } else {
985 child_process->Detach();
987 }
988 break;
989 }
990 default:
991 llvm_unreachable("unknown clone_info.event");
992 }
993
994 return true;
995}
996
998 if (m_arch.IsMIPS() || m_arch.GetMachine() == llvm::Triple::arm ||
999 m_arch.GetTriple().isRISCV() || m_arch.GetTriple().isLoongArch())
1000 return false;
1001 return true;
1002}
1003
1006 LLDB_LOG(log, "pid {0}", GetID());
1007
1009
1010 bool software_single_step = !SupportHardwareSingleStepping();
1011
1012 if (software_single_step) {
1013 for (const auto &thread : m_threads) {
1014 assert(thread && "thread list should not contain NULL threads");
1015
1016 const ResumeAction *const action =
1017 resume_actions.GetActionForThread(thread->GetID(), true);
1018 if (action == nullptr)
1019 continue;
1020
1021 if (action->state == eStateStepping) {
1023 static_cast<NativeThreadLinux &>(*thread));
1024 if (error.Fail())
1025 return error;
1026 }
1027 }
1028 }
1029
1030 for (const auto &thread : m_threads) {
1031 assert(thread && "thread list should not contain NULL threads");
1032
1033 const ResumeAction *const action =
1034 resume_actions.GetActionForThread(thread->GetID(), true);
1035
1036 if (action == nullptr) {
1037 LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
1038 thread->GetID());
1039 continue;
1040 }
1041
1042 LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}",
1043 action->state, GetID(), thread->GetID());
1044
1045 switch (action->state) {
1046 case eStateRunning:
1047 case eStateStepping: {
1048 // Run the thread, possibly feeding it the signal.
1049 const int signo = action->signal;
1050 Status error = ResumeThread(static_cast<NativeThreadLinux &>(*thread),
1051 action->state, signo);
1052 if (error.Fail())
1053 return Status("NativeProcessLinux::%s: failed to resume thread "
1054 "for pid %" PRIu64 ", tid %" PRIu64 ", error = %s",
1055 __FUNCTION__, GetID(), thread->GetID(),
1056 error.AsCString());
1057
1058 break;
1059 }
1060
1061 case eStateSuspended:
1062 case eStateStopped:
1063 break;
1064
1065 default:
1066 return Status("NativeProcessLinux::%s (): unexpected state %s specified "
1067 "for pid %" PRIu64 ", tid %" PRIu64,
1068 __FUNCTION__, StateAsCString(action->state), GetID(),
1069 thread->GetID());
1070 }
1071 }
1072
1073 return Status();
1074}
1075
1077 Status error;
1078
1079 if (kill(GetID(), SIGSTOP) != 0)
1080 error.SetErrorToErrno();
1081
1082 return error;
1083}
1084
1086 Status error;
1087
1088 // Tell ptrace to detach from the process.
1090 return error;
1091
1092 // Cancel out any SIGSTOPs we may have sent while stopping the process.
1093 // Otherwise, the process may stop as soon as we detach from it.
1094 kill(GetID(), SIGCONT);
1095
1096 for (const auto &thread : m_threads) {
1097 Status e = Detach(thread->GetID());
1098 if (e.Fail())
1099 error =
1100 e; // Save the error, but still attempt to detach from other threads.
1101 }
1102
1104
1105 return error;
1106}
1107
1109 Status error;
1110
1112 LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo,
1114
1115 if (kill(GetID(), signo))
1116 error.SetErrorToErrno();
1117
1118 return error;
1119}
1120
1122 // Pick a running thread (or if none, a not-dead stopped thread) as the
1123 // chosen thread that will be the stop-reason thread.
1125
1126 NativeThreadProtocol *running_thread = nullptr;
1127 NativeThreadProtocol *stopped_thread = nullptr;
1128
1129 LLDB_LOG(log, "selecting running thread for interrupt target");
1130 for (const auto &thread : m_threads) {
1131 // If we have a running or stepping thread, we'll call that the target of
1132 // the interrupt.
1133 const auto thread_state = thread->GetState();
1134 if (thread_state == eStateRunning || thread_state == eStateStepping) {
1135 running_thread = thread.get();
1136 break;
1137 } else if (!stopped_thread && StateIsStoppedState(thread_state, true)) {
1138 // Remember the first non-dead stopped thread. We'll use that as a
1139 // backup if there are no running threads.
1140 stopped_thread = thread.get();
1141 }
1142 }
1143
1144 if (!running_thread && !stopped_thread) {
1145 Status error("found no running/stepping or live stopped threads as target "
1146 "for interrupt");
1147 LLDB_LOG(log, "skipping due to error: {0}", error);
1148
1149 return error;
1150 }
1151
1152 NativeThreadProtocol *deferred_signal_thread =
1153 running_thread ? running_thread : stopped_thread;
1154
1155 LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(),
1156 running_thread ? "running" : "stopped",
1157 deferred_signal_thread->GetID());
1158
1159 StopRunningThreads(deferred_signal_thread->GetID());
1160
1161 return Status();
1162}
1163
1166 LLDB_LOG(log, "pid {0}", GetID());
1167
1168 Status error;
1169
1170 switch (m_state) {
1171 case StateType::eStateInvalid:
1172 case StateType::eStateExited:
1173 case StateType::eStateCrashed:
1174 case StateType::eStateDetached:
1175 case StateType::eStateUnloaded:
1176 // Nothing to do - the process is already dead.
1177 LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
1178 m_state);
1179 return error;
1180
1181 case StateType::eStateConnected:
1182 case StateType::eStateAttaching:
1183 case StateType::eStateLaunching:
1184 case StateType::eStateStopped:
1185 case StateType::eStateRunning:
1186 case StateType::eStateStepping:
1187 case StateType::eStateSuspended:
1188 // We can try to kill a process in these states.
1189 break;
1190 }
1191
1192 if (kill(GetID(), SIGKILL) != 0) {
1193 error.SetErrorToErrno();
1194 return error;
1195 }
1196
1197 return error;
1198}
1199
1201 MemoryRegionInfo &range_info) {
1202 // FIXME review that the final memory region returned extends to the end of
1203 // the virtual address space,
1204 // with no perms if it is not mapped.
1205
1206 // Use an approach that reads memory regions from /proc/{pid}/maps. Assume
1207 // proc maps entries are in ascending order.
1208 // FIXME assert if we find differently.
1209
1211 // We're done.
1212 return Status("unsupported");
1213 }
1214
1216 if (error.Fail()) {
1217 return error;
1218 }
1219
1220 lldb::addr_t prev_base_address = 0;
1221
1222 // FIXME start by finding the last region that is <= target address using
1223 // binary search. Data is sorted.
1224 // There can be a ton of regions on pthreads apps with lots of threads.
1225 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1226 ++it) {
1227 MemoryRegionInfo &proc_entry_info = it->first;
1228
1229 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1230 assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
1231 "descending /proc/pid/maps entries detected, unexpected");
1232 prev_base_address = proc_entry_info.GetRange().GetRangeBase();
1233 UNUSED_IF_ASSERT_DISABLED(prev_base_address);
1234
1235 // If the target address comes before this entry, indicate distance to next
1236 // region.
1237 if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1238 range_info.GetRange().SetRangeBase(load_addr);
1239 range_info.GetRange().SetByteSize(
1240 proc_entry_info.GetRange().GetRangeBase() - load_addr);
1245
1246 return error;
1247 } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1248 // The target address is within the memory region we're processing here.
1249 range_info = proc_entry_info;
1250 return error;
1251 }
1252
1253 // The target memory address comes somewhere after the region we just
1254 // parsed.
1255 }
1256
1257 // If we made it here, we didn't find an entry that contained the given
1258 // address. Return the load_addr as start and the amount of bytes betwwen
1259 // load address and the end of the memory as size.
1260 range_info.GetRange().SetRangeBase(load_addr);
1266 return error;
1267}
1268
1271
1272 // If our cache is empty, pull the latest. There should always be at least
1273 // one memory region if memory region handling is supported.
1274 if (!m_mem_region_cache.empty()) {
1275 LLDB_LOG(log, "reusing {0} cached memory region entries",
1276 m_mem_region_cache.size());
1277 return Status();
1278 }
1279
1280 Status Result;
1281 LinuxMapCallback callback = [&](llvm::Expected<MemoryRegionInfo> Info) {
1282 if (Info) {
1283 FileSpec file_spec(Info->GetName().GetCString());
1284 FileSystem::Instance().Resolve(file_spec);
1285 m_mem_region_cache.emplace_back(*Info, file_spec);
1286 return true;
1287 }
1288
1289 Result = Info.takeError();
1291 LLDB_LOG(log, "failed to parse proc maps: {0}", Result);
1292 return false;
1293 };
1294
1295 // Linux kernel since 2.6.14 has /proc/{pid}/smaps
1296 // if CONFIG_PROC_PAGE_MONITOR is enabled
1297 auto BufferOrError = getProcFile(GetID(), GetCurrentThreadID(), "smaps");
1298 if (BufferOrError)
1299 ParseLinuxSMapRegions(BufferOrError.get()->getBuffer(), callback);
1300 else {
1301 BufferOrError = getProcFile(GetID(), GetCurrentThreadID(), "maps");
1302 if (!BufferOrError) {
1304 return BufferOrError.getError();
1305 }
1306
1307 ParseLinuxMapRegions(BufferOrError.get()->getBuffer(), callback);
1308 }
1309
1310 if (Result.Fail())
1311 return Result;
1312
1313 if (m_mem_region_cache.empty()) {
1314 // No entries after attempting to read them. This shouldn't happen if
1315 // /proc/{pid}/maps is supported. Assume we don't support map entries via
1316 // procfs.
1318 LLDB_LOG(log,
1319 "failed to find any procfs maps entries, assuming no support "
1320 "for memory region metadata retrieval");
1321 return Status("not supported");
1322 }
1323
1324 LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps",
1325 m_mem_region_cache.size(), GetID());
1326
1327 // We support memory retrieval, remember that.
1329 return Status();
1330}
1331
1332void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
1334 LLDB_LOG(log, "newBumpId={0}", newBumpId);
1335 LLDB_LOG(log, "clearing {0} entries from memory region cache",
1336 m_mem_region_cache.size());
1337 m_mem_region_cache.clear();
1338}
1339
1340llvm::Expected<uint64_t>
1341NativeProcessLinux::Syscall(llvm::ArrayRef<uint64_t> args) {
1343 auto region_it = llvm::find_if(m_mem_region_cache, [](const auto &pair) {
1344 return pair.first.GetExecutable() == MemoryRegionInfo::eYes &&
1345 pair.first.GetShared() != MemoryRegionInfo::eYes;
1346 });
1347 if (region_it == m_mem_region_cache.end())
1348 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1349 "No executable memory region found!");
1350
1351 addr_t exe_addr = region_it->first.GetRange().GetRangeBase();
1352
1354 assert(thread.GetState() == eStateStopped);
1356
1358 *reg_ctx.GetSyscallData();
1359
1360 WritableDataBufferSP registers_sp;
1361 if (llvm::Error Err = reg_ctx.ReadAllRegisterValues(registers_sp).ToError())
1362 return std::move(Err);
1363 auto restore_regs = llvm::make_scope_exit(
1364 [&] { reg_ctx.WriteAllRegisterValues(registers_sp); });
1365
1366 llvm::SmallVector<uint8_t, 8> memory(syscall_data.Insn.size());
1367 size_t bytes_read;
1368 if (llvm::Error Err =
1369 ReadMemory(exe_addr, memory.data(), memory.size(), bytes_read)
1370 .ToError()) {
1371 return std::move(Err);
1372 }
1373
1374 auto restore_mem = llvm::make_scope_exit(
1375 [&] { WriteMemory(exe_addr, memory.data(), memory.size(), bytes_read); });
1376
1377 if (llvm::Error Err = reg_ctx.SetPC(exe_addr).ToError())
1378 return std::move(Err);
1379
1380 for (const auto &zip : llvm::zip_first(args, syscall_data.Args)) {
1381 if (llvm::Error Err =
1382 reg_ctx
1383 .WriteRegisterFromUnsigned(std::get<1>(zip), std::get<0>(zip))
1384 .ToError()) {
1385 return std::move(Err);
1386 }
1387 }
1388 if (llvm::Error Err = WriteMemory(exe_addr, syscall_data.Insn.data(),
1389 syscall_data.Insn.size(), bytes_read)
1390 .ToError())
1391 return std::move(Err);
1392
1393 m_mem_region_cache.clear();
1394
1395 // With software single stepping the syscall insn buffer must also include a
1396 // trap instruction to stop the process.
1397 int req = SupportHardwareSingleStepping() ? PTRACE_SINGLESTEP : PTRACE_CONT;
1398 if (llvm::Error Err =
1399 PtraceWrapper(req, thread.GetID(), nullptr, nullptr).ToError())
1400 return std::move(Err);
1401
1402 int status;
1403 ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, thread.GetID(),
1404 &status, __WALL);
1405 if (wait_pid == -1) {
1406 return llvm::errorCodeToError(
1407 std::error_code(errno, std::generic_category()));
1408 }
1409 assert((unsigned)wait_pid == thread.GetID());
1410
1411 uint64_t result = reg_ctx.ReadRegisterAsUnsigned(syscall_data.Result, -ESRCH);
1412
1413 // Values larger than this are actually negative errno numbers.
1414 uint64_t errno_threshold =
1415 (uint64_t(-1) >> (64 - 8 * m_arch.GetAddressByteSize())) - 0x1000;
1416 if (result > errno_threshold) {
1417 return llvm::errorCodeToError(
1418 std::error_code(-result & 0xfff, std::generic_category()));
1419 }
1420
1421 return result;
1422}
1423
1424llvm::Expected<addr_t>
1425NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions) {
1426
1427 std::optional<NativeRegisterContextLinux::MmapData> mmap_data =
1429 if (!mmap_data)
1430 return llvm::make_error<UnimplementedError>();
1431
1432 unsigned prot = PROT_NONE;
1433 assert((permissions & (ePermissionsReadable | ePermissionsWritable |
1434 ePermissionsExecutable)) == permissions &&
1435 "Unknown permission!");
1436 if (permissions & ePermissionsReadable)
1437 prot |= PROT_READ;
1438 if (permissions & ePermissionsWritable)
1439 prot |= PROT_WRITE;
1440 if (permissions & ePermissionsExecutable)
1441 prot |= PROT_EXEC;
1442
1443 llvm::Expected<uint64_t> Result =
1444 Syscall({mmap_data->SysMmap, 0, size, prot, MAP_ANONYMOUS | MAP_PRIVATE,
1445 uint64_t(-1), 0});
1446 if (Result)
1447 m_allocated_memory.try_emplace(*Result, size);
1448 return Result;
1449}
1450
1452 std::optional<NativeRegisterContextLinux::MmapData> mmap_data =
1454 if (!mmap_data)
1455 return llvm::make_error<UnimplementedError>();
1456
1457 auto it = m_allocated_memory.find(addr);
1458 if (it == m_allocated_memory.end())
1459 return llvm::createStringError(llvm::errc::invalid_argument,
1460 "Memory not allocated by the debugger.");
1461
1462 llvm::Expected<uint64_t> Result =
1463 Syscall({mmap_data->SysMunmap, addr, it->second});
1464 if (!Result)
1465 return Result.takeError();
1466
1467 m_allocated_memory.erase(it);
1468 return llvm::Error::success();
1469}
1470
1472 size_t len,
1473 std::vector<uint8_t> &tags) {
1474 llvm::Expected<NativeRegisterContextLinux::MemoryTaggingDetails> details =
1476 if (!details)
1477 return Status(details.takeError());
1478
1479 // Ignore 0 length read
1480 if (!len)
1481 return Status();
1482
1483 // lldb will align the range it requests but it is not required to by
1484 // the protocol so we'll do it again just in case.
1485 // Remove tag bits too. Ptrace calls may work regardless but that
1486 // is not a guarantee.
1487 MemoryTagManager::TagRange range(details->manager->RemoveTagBits(addr), len);
1488 range = details->manager->ExpandToGranule(range);
1489
1490 // Allocate enough space for all tags to be read
1491 size_t num_tags = range.GetByteSize() / details->manager->GetGranuleSize();
1492 tags.resize(num_tags * details->manager->GetTagSizeInBytes());
1493
1494 struct iovec tags_iovec;
1495 uint8_t *dest = tags.data();
1496 lldb::addr_t read_addr = range.GetRangeBase();
1497
1498 // This call can return partial data so loop until we error or
1499 // get all tags back.
1500 while (num_tags) {
1501 tags_iovec.iov_base = dest;
1502 tags_iovec.iov_len = num_tags;
1503
1505 details->ptrace_read_req, GetCurrentThreadID(),
1506 reinterpret_cast<void *>(read_addr), static_cast<void *>(&tags_iovec),
1507 0, nullptr);
1508
1509 if (error.Fail()) {
1510 // Discard partial reads
1511 tags.resize(0);
1512 return error;
1513 }
1514
1515 size_t tags_read = tags_iovec.iov_len;
1516 assert(tags_read && (tags_read <= num_tags));
1517
1518 dest += tags_read * details->manager->GetTagSizeInBytes();
1519 read_addr += details->manager->GetGranuleSize() * tags_read;
1520 num_tags -= tags_read;
1521 }
1522
1523 return Status();
1524}
1525
1527 size_t len,
1528 const std::vector<uint8_t> &tags) {
1529 llvm::Expected<NativeRegisterContextLinux::MemoryTaggingDetails> details =
1531 if (!details)
1532 return Status(details.takeError());
1533
1534 // Ignore 0 length write
1535 if (!len)
1536 return Status();
1537
1538 // lldb will align the range it requests but it is not required to by
1539 // the protocol so we'll do it again just in case.
1540 // Remove tag bits too. Ptrace calls may work regardless but that
1541 // is not a guarantee.
1542 MemoryTagManager::TagRange range(details->manager->RemoveTagBits(addr), len);
1543 range = details->manager->ExpandToGranule(range);
1544
1545 // Not checking number of tags here, we may repeat them below
1546 llvm::Expected<std::vector<lldb::addr_t>> unpacked_tags_or_err =
1547 details->manager->UnpackTagsData(tags);
1548 if (!unpacked_tags_or_err)
1549 return Status(unpacked_tags_or_err.takeError());
1550
1551 llvm::Expected<std::vector<lldb::addr_t>> repeated_tags_or_err =
1552 details->manager->RepeatTagsForRange(*unpacked_tags_or_err, range);
1553 if (!repeated_tags_or_err)
1554 return Status(repeated_tags_or_err.takeError());
1555
1556 // Repack them for ptrace to use
1557 llvm::Expected<std::vector<uint8_t>> final_tag_data =
1558 details->manager->PackTags(*repeated_tags_or_err);
1559 if (!final_tag_data)
1560 return Status(final_tag_data.takeError());
1561
1562 struct iovec tags_vec;
1563 uint8_t *src = final_tag_data->data();
1564 lldb::addr_t write_addr = range.GetRangeBase();
1565 // unpacked tags size because the number of bytes per tag might not be 1
1566 size_t num_tags = repeated_tags_or_err->size();
1567
1568 // This call can partially write tags, so we loop until we
1569 // error or all tags have been written.
1570 while (num_tags > 0) {
1571 tags_vec.iov_base = src;
1572 tags_vec.iov_len = num_tags;
1573
1575 details->ptrace_write_req, GetCurrentThreadID(),
1576 reinterpret_cast<void *>(write_addr), static_cast<void *>(&tags_vec), 0,
1577 nullptr);
1578
1579 if (error.Fail()) {
1580 // Don't attempt to restore the original values in the case of a partial
1581 // write
1582 return error;
1583 }
1584
1585 size_t tags_written = tags_vec.iov_len;
1586 assert(tags_written && (tags_written <= num_tags));
1587
1588 src += tags_written * details->manager->GetTagSizeInBytes();
1589 write_addr += details->manager->GetGranuleSize() * tags_written;
1590 num_tags -= tags_written;
1591 }
1592
1593 return Status();
1594}
1595
1597 // The NativeProcessLinux monitoring threads are always up to date with
1598 // respect to thread state and they keep the thread list populated properly.
1599 // All this method needs to do is return the thread count.
1600 return m_threads.size();
1601}
1602
1604 bool hardware) {
1605 if (hardware)
1606 return SetHardwareBreakpoint(addr, size);
1607 else
1608 return SetSoftwareBreakpoint(addr, size);
1609}
1610
1612 if (hardware)
1613 return RemoveHardwareBreakpoint(addr);
1614 else
1616}
1617
1618llvm::Expected<llvm::ArrayRef<uint8_t>>
1620 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1621 // linux kernel does otherwise.
1622 static const uint8_t g_arm_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1623 static const uint8_t g_thumb_opcode[] = {0x01, 0xde};
1624
1625 switch (GetArchitecture().GetMachine()) {
1626 case llvm::Triple::arm:
1627 switch (size_hint) {
1628 case 2:
1629 return llvm::ArrayRef(g_thumb_opcode);
1630 case 4:
1631 return llvm::ArrayRef(g_arm_opcode);
1632 default:
1633 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1634 "Unrecognised trap opcode size hint!");
1635 }
1636 default:
1638 }
1639}
1640
1642 size_t &bytes_read) {
1644 // The process_vm_readv path is about 50 times faster than ptrace api. We
1645 // want to use this syscall if it is supported.
1646
1647 struct iovec local_iov, remote_iov;
1648 local_iov.iov_base = buf;
1649 local_iov.iov_len = size;
1650 remote_iov.iov_base = reinterpret_cast<void *>(addr);
1651 remote_iov.iov_len = size;
1652
1653 bytes_read = process_vm_readv(GetCurrentThreadID(), &local_iov, 1,
1654 &remote_iov, 1, 0);
1655 const bool success = bytes_read == size;
1656
1658 LLDB_LOG(log,
1659 "using process_vm_readv to read {0} bytes from inferior "
1660 "address {1:x}: {2}",
1661 size, addr, success ? "Success" : llvm::sys::StrError(errno));
1662
1663 if (success)
1664 return Status();
1665 // else the call failed for some reason, let's retry the read using ptrace
1666 // api.
1667 }
1668
1669 unsigned char *dst = static_cast<unsigned char *>(buf);
1670 size_t remainder;
1671 long data;
1672
1673 Log *log = GetLog(POSIXLog::Memory);
1674 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
1675
1676 for (bytes_read = 0; bytes_read < size; bytes_read += remainder) {
1678 PTRACE_PEEKDATA, GetCurrentThreadID(), (void *)addr, nullptr, 0, &data);
1679 if (error.Fail())
1680 return error;
1681
1682 remainder = size - bytes_read;
1683 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
1684
1685 // Copy the data into our buffer
1686 memcpy(dst, &data, remainder);
1687
1688 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
1689 addr += k_ptrace_word_size;
1690 dst += k_ptrace_word_size;
1691 }
1692 return Status();
1693}
1694
1696 size_t size, size_t &bytes_written) {
1697 const unsigned char *src = static_cast<const unsigned char *>(buf);
1698 size_t remainder;
1699 Status error;
1700
1701 Log *log = GetLog(POSIXLog::Memory);
1702 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
1703
1704 for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
1705 remainder = size - bytes_written;
1706 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
1707
1708 if (remainder == k_ptrace_word_size) {
1709 unsigned long data = 0;
1710 memcpy(&data, src, k_ptrace_word_size);
1711
1712 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
1714 PTRACE_POKEDATA, GetCurrentThreadID(), (void *)addr, (void *)data);
1715 if (error.Fail())
1716 return error;
1717 } else {
1718 unsigned char buff[8];
1719 size_t bytes_read;
1720 error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
1721 if (error.Fail())
1722 return error;
1723
1724 memcpy(buff, src, remainder);
1725
1726 size_t bytes_written_rec;
1727 error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
1728 if (error.Fail())
1729 return error;
1730
1731 LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src,
1732 *(unsigned long *)buff);
1733 }
1734
1735 addr += k_ptrace_word_size;
1736 src += k_ptrace_word_size;
1737 }
1738 return error;
1739}
1740
1742 return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
1743}
1744
1746 unsigned long *message) {
1747 return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
1748}
1749
1751 if (tid == LLDB_INVALID_THREAD_ID)
1752 return Status();
1753
1754 return PtraceWrapper(PTRACE_DETACH, tid);
1755}
1756
1758 for (const auto &thread : m_threads) {
1759 assert(thread && "thread list should not contain NULL threads");
1760 if (thread->GetID() == thread_id) {
1761 // We have this thread.
1762 return true;
1763 }
1764 }
1765
1766 // We don't have this thread.
1767 return false;
1768}
1769
1771 Log *const log = GetLog(POSIXLog::Thread);
1772 lldb::tid_t thread_id = thread.GetID();
1773 LLDB_LOG(log, "tid: {0}", thread_id);
1774
1775 auto it = llvm::find_if(m_threads, [&](const auto &thread_up) {
1776 return thread_up.get() == &thread;
1777 });
1778 assert(it != m_threads.end());
1779 m_threads.erase(it);
1780
1783}
1784
1787}
1788
1791}
1792
1794 Log *log = GetLog(POSIXLog::Thread);
1796 if (error.Fail())
1797 LLDB_LOG(log, "Failed to trace a new thread with intel-pt, tid = {0}. {1}",
1798 tid, error.AsCString());
1799 return error;
1800}
1801
1803 Log *log = GetLog(POSIXLog::Thread);
1805 if (error.Fail())
1806 LLDB_LOG(log,
1807 "Failed to stop a destroyed thread with intel-pt, tid = {0}. {1}",
1808 tid, error.AsCString());
1809 return error;
1810}
1811
1813 bool resume) {
1814 Log *log = GetLog(POSIXLog::Thread);
1815 LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
1816
1817 assert(!HasThreadNoLock(thread_id) &&
1818 "attempted to add a thread by id that already exists");
1819
1820 // If this is the first thread, save it as the current thread
1821 if (m_threads.empty())
1822 SetCurrentThreadID(thread_id);
1823
1824 m_threads.push_back(std::make_unique<NativeThreadLinux>(*this, thread_id));
1825 NativeThreadLinux &thread =
1826 static_cast<NativeThreadLinux &>(*m_threads.back());
1827
1828 Status tracing_error = NotifyTracersOfNewThread(thread.GetID());
1829 if (tracing_error.Fail()) {
1830 thread.SetStoppedByProcessorTrace(tracing_error.AsCString());
1831 StopRunningThreads(thread.GetID());
1832 } else if (resume)
1834 else
1836
1837 return thread;
1838}
1839
1841 FileSpec &file_spec) {
1843 if (error.Fail())
1844 return error;
1845
1846 FileSpec module_file_spec(module_path);
1847 FileSystem::Instance().Resolve(module_file_spec);
1848
1849 file_spec.Clear();
1850 for (const auto &it : m_mem_region_cache) {
1851 if (it.second.GetFilename() == module_file_spec.GetFilename()) {
1852 file_spec = it.second;
1853 return Status();
1854 }
1855 }
1856 return Status("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
1857 module_file_spec.GetFilename().AsCString(), GetID());
1858}
1859
1860Status NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
1861 lldb::addr_t &load_addr) {
1862 load_addr = LLDB_INVALID_ADDRESS;
1864 if (error.Fail())
1865 return error;
1866
1867 FileSpec file(file_name);
1868 for (const auto &it : m_mem_region_cache) {
1869 if (it.second == file) {
1870 load_addr = it.first.GetRange().GetRangeBase();
1871 return Status();
1872 }
1873 }
1874 return Status("No load address found for specified file.");
1875}
1876
1878 return static_cast<NativeThreadLinux *>(
1880}
1881
1883 return static_cast<NativeThreadLinux *>(
1885}
1886
1888 lldb::StateType state, int signo) {
1889 Log *const log = GetLog(POSIXLog::Thread);
1890 LLDB_LOG(log, "tid: {0}", thread.GetID());
1891
1892 // Before we do the resume below, first check if we have a pending stop
1893 // notification that is currently waiting for all threads to stop. This is
1894 // potentially a buggy situation since we're ostensibly waiting for threads
1895 // to stop before we send out the pending notification, and here we are
1896 // resuming one before we send out the pending stop notification.
1898 LLDB_LOG(log,
1899 "about to resume tid {0} per explicit request but we have a "
1900 "pending stop notification (tid {1}) that is actively "
1901 "waiting for this thread to stop. Valid sequence of events?",
1903 }
1904
1905 // Request a resume. We expect this to be synchronous and the system to
1906 // reflect it is running after this completes.
1907 switch (state) {
1908 case eStateRunning: {
1909 const auto resume_result = thread.Resume(signo);
1910 if (resume_result.Success())
1911 SetState(eStateRunning, true);
1912 return resume_result;
1913 }
1914 case eStateStepping: {
1915 const auto step_result = thread.SingleStep(signo);
1916 if (step_result.Success())
1917 SetState(eStateRunning, true);
1918 return step_result;
1919 }
1920 default:
1921 LLDB_LOG(log, "Unhandled state {0}.", state);
1922 llvm_unreachable("Unhandled state for resume");
1923 }
1924}
1925
1926//===----------------------------------------------------------------------===//
1927
1929 Log *const log = GetLog(POSIXLog::Thread);
1930 LLDB_LOG(log, "about to process event: (triggering_tid: {0})",
1931 triggering_tid);
1932
1933 m_pending_notification_tid = triggering_tid;
1934
1935 // Request a stop for all the thread stops that need to be stopped and are
1936 // not already known to be stopped.
1937 for (const auto &thread : m_threads) {
1938 if (StateIsRunningState(thread->GetState()))
1939 static_cast<NativeThreadLinux *>(thread.get())->RequestStop();
1940 }
1941
1943 LLDB_LOG(log, "event processing done");
1944}
1945
1948 return; // No pending notification. Nothing to do.
1949
1950 for (const auto &thread_sp : m_threads) {
1951 if (StateIsRunningState(thread_sp->GetState()))
1952 return; // Some threads are still running. Don't signal yet.
1953 }
1954
1955 // We have a pending notification and all threads have stopped.
1957
1958 // Clear any temporary breakpoints we used to implement software single
1959 // stepping.
1960 for (const auto &thread_info : m_threads_stepping_with_breakpoint) {
1961 Status error = RemoveBreakpoint(thread_info.second);
1962 if (error.Fail())
1963 LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}",
1964 thread_info.first, error);
1965 }
1967
1968 // Notify the delegate about the stop
1970 SetState(StateType::eStateStopped, true);
1972}
1973
1975 Log *const log = GetLog(POSIXLog::Thread);
1976 LLDB_LOG(log, "tid: {0}", thread.GetID());
1977
1979 StateIsRunningState(thread.GetState())) {
1980 // We will need to wait for this new thread to stop as well before firing
1981 // the notification.
1982 thread.RequestStop();
1983 }
1984}
1985
1986// Wrapper for ptrace to catch errors and log calls. Note that ptrace sets
1987// errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
1989 void *data, size_t data_size,
1990 long *result) {
1991 Status error;
1992 long int ret;
1993
1994 Log *log = GetLog(POSIXLog::Ptrace);
1995
1996 PtraceDisplayBytes(req, data, data_size);
1997
1998 errno = 0;
1999 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
2000 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2001 *(unsigned int *)addr, data);
2002 else
2003 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2004 addr, data);
2005
2006 if (ret == -1)
2007 error.SetErrorToErrno();
2008
2009 if (result)
2010 *result = ret;
2011
2012 LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data,
2013 data_size, ret);
2014
2015 PtraceDisplayBytes(req, data, data_size);
2016
2017 if (error.Fail())
2018 LLDB_LOG(log, "ptrace() failed: {0}", error);
2019
2020 return error;
2021}
2022
2023llvm::Expected<TraceSupportedResponse> NativeProcessLinux::TraceSupported() {
2025 return TraceSupportedResponse{"intel-pt", "Intel Processor Trace"};
2027}
2028
2029Error NativeProcessLinux::TraceStart(StringRef json_request, StringRef type) {
2030 if (type == "intel-pt") {
2031 if (Expected<TraceIntelPTStartRequest> request =
2032 json::parse<TraceIntelPTStartRequest>(json_request,
2033 "TraceIntelPTStartRequest")) {
2034 return m_intel_pt_collector.TraceStart(*request);
2035 } else
2036 return request.takeError();
2037 }
2038
2039 return NativeProcessProtocol::TraceStart(json_request, type);
2040}
2041
2043 if (request.type == "intel-pt")
2044 return m_intel_pt_collector.TraceStop(request);
2045 return NativeProcessProtocol::TraceStop(request);
2046}
2047
2048Expected<json::Value> NativeProcessLinux::TraceGetState(StringRef type) {
2049 if (type == "intel-pt")
2052}
2053
2054Expected<std::vector<uint8_t>> NativeProcessLinux::TraceGetBinaryData(
2055 const TraceGetBinaryDataRequest &request) {
2056 if (request.type == "intel-pt")
2057 return m_intel_pt_collector.GetBinaryData(request);
2059}
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:359
#define LLDB_LOGV(log,...)
Definition: Log.h:373
static Status EnsureFDFlags(int fd, int flags)
static void MaybeLogLaunchInfo(const ProcessLaunchInfo &info)
static std::optional< std::pair< lldb::pid_t, WaitStatus > > WaitPid()
#define TRAP_HWBKPT
static constexpr unsigned k_ptrace_word_size
static void PtraceDisplayBytes(int &req, void *data, size_t data_size)
static Status EnsureFDFlags(int fd, int flags)
static llvm::Error AddPtraceScopeNote(llvm::Error original_error)
#define HWCAP2_MTE
static void DisplayBytes(StreamString &s, void *bytes, uint32_t count)
static bool ProcessVmReadvSupported()
#define MAP_PRIVATE
int __ptrace_request
Definition: Ptrace.h:17
#define DEBUG_PTRACE_MAXBYTES
Definition: Ptrace.h:20
#define PTRACE_SETREGSET
Definition: Ptrace.h:39
#define PTRACE_SETREGS
Definition: Ptrace.h:27
#define PTRACE_SETFPREGS
Definition: Ptrace.h:33
#define PTRACE_GETREGSET
Definition: Ptrace.h:36
llvm::Error Error
ssize_t process_vm_readv(::pid_t pid, const struct iovec *local_iov, unsigned long liovcnt, const struct iovec *remote_iov, unsigned long riovcnt, unsigned long flags)
An architecture specification class.
Definition: ArchSpec.h:31
uint32_t GetAddressByteSize() const
Returns the size in bytes of an address of the current architecture.
Definition: ArchSpec.cpp:691
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition: ArchSpec.h:450
bool IsMIPS() const
if MIPS architecture return true.
Definition: ArchSpec.cpp:559
llvm::Triple::ArchType GetMachine() const
Returns a machine family for the current architecture.
Definition: ArchSpec.cpp:683
const char ** GetConstArgumentVector() const
Gets the argument vector.
Definition: Args.cpp:279
const char * AsCString(const char *value_if_empty=nullptr) const
Get the string value as a C string.
Definition: ConstString.h:188
A file utility class.
Definition: FileSpec.h:56
const ConstString & GetFilename() const
Filename string const get accessor.
Definition: FileSpec.h:240
void Clear()
Clears the object state.
Definition: FileSpec.cpp:259
void Resolve(llvm::SmallVectorImpl< char > &path)
Resolve path to make it canonical.
static FileSystem & Instance()
lldb::pid_t GetProcessId() const
Definition: HostProcess.cpp:25
static bool FindProcessThreads(const lldb::pid_t pid, TidMap &tids_to_attach)
std::map< lldb::pid_t, bool > TidMap
Definition: Host.h:160
static const char * GetSignalAsCString(int signo)
SignalHandleUP RegisterSignal(int signo, const Callback &callback, Status &error)
void SetMapped(OptionalBool val)
void SetReadable(OptionalBool val)
void SetExecutable(OptionalBool val)
void SetWritable(OptionalBool val)
Abstract class that extends NativeProcessProtocol with ELF specific logic.
void NotifyDidExec() override
Notify the delegate that an exec occurred.
virtual void NewSubprocess(NativeProcessProtocol *parent_process, std::unique_ptr< NativeProcessProtocol > child_process)=0
virtual llvm::Expected< TraceSupportedResponse > TraceSupported()
Get the processor tracing type supported for this process.
virtual llvm::Expected< std::vector< uint8_t > > TraceGetBinaryData(const TraceGetBinaryDataRequest &request)
Get binary data given a trace technology and a data identifier.
virtual llvm::Error TraceStop(const TraceStopRequest &request)
Stop tracing a live process or its threads.
Status SetSoftwareBreakpoint(lldb::addr_t addr, uint32_t size_hint)
virtual llvm::Expected< llvm::json::Value > TraceGetState(llvm::StringRef type)
Get the current tracing state of the process and its threads.
void SetState(lldb::StateType state, bool notify_delegates=true)
NativeThreadProtocol * GetThreadByID(lldb::tid_t tid)
std::vector< std::unique_ptr< NativeThreadProtocol > > m_threads
virtual bool SetExitStatus(WaitStatus status, bool bNotifyStateChange)
virtual Status RemoveBreakpoint(lldb::addr_t addr, bool hardware=false)
void FixupBreakpointPCAsNeeded(NativeThreadProtocol &thread)
Extension
Extension flag constants, returned by 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
Status SetupSoftwareSingleStepping(NativeThreadProtocol &thread)
std::map< lldb::tid_t, lldb::addr_t > m_threads_stepping_with_breakpoint
lldb::addr_t ReadRegisterAsUnsigned(uint32_t reg, lldb::addr_t fail_value)
virtual Status GetWatchpointHitIndex(uint32_t &wp_index, lldb::addr_t trap_addr)
virtual Status WriteAllRegisterValues(const lldb::DataBufferSP &data_sp)=0
virtual Status ReadAllRegisterValues(lldb::WritableDataBufferSP &data_sp)=0
virtual Status GetHardwareBreakHitIndex(uint32_t &bp_index, lldb::addr_t trap_addr)
const FileAction * GetFileActionForFD(int fd) const
HostProcess LaunchProcess(const ProcessLaunchInfo &launch_info, Status &error) override
int ReleasePrimaryFileDescriptor()
Release the primary file descriptor.
const ResumeAction * GetActionForThread(lldb::tid_t tid, bool default_ok) const
Definition: Debug.h:74
An error handling class.
Definition: Status.h:44
ValueType GetError() const
Access the error value.
Definition: Status.cpp:173
llvm::Error ToError() const
Definition: Status.cpp:89
bool Fail() const
Test for error condition.
Definition: Status.cpp:180
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
Definition: Status.cpp:129
bool Success() const
Test for success condition.
Definition: Status.cpp:278
const char * GetData() const
Definition: StreamString.h:45
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition: Stream.cpp:134
llvm::Expected< std::vector< uint8_t > > GetBinaryData(const TraceGetBinaryDataRequest &request)
Implementation of the jLLDBTraceGetBinaryData packet.
llvm::Error TraceStop(const TraceStopRequest &request)
Implementation of the jLLDBTraceStop packet.
llvm::Error TraceStart(const TraceIntelPTStartRequest &request)
Implementation of the jLLDBTraceStart packet.
llvm::Error OnThreadCreated(lldb::tid_t tid)
If "process tracing" is enabled, then trace the given thread.
llvm::Error OnThreadDestroyed(lldb::tid_t tid)
Stops tracing a tracing upon a destroy event.
llvm::Expected< llvm::json::Value > GetState()
Implementation of the jLLDBTraceGetState packet.
void ProcessWillResume()
To be invoked before the process will resume, so that we can capture the first instructions after the...
void ProcessDidStop()
To be invoked as soon as we know the process stopped.
llvm::Expected< std::unique_ptr< NativeProcessProtocol > > Attach(lldb::pid_t pid, NativeDelegate &native_delegate) override
Attach to an existing process.
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.
Manages communication with the inferior (debugee) process.
llvm::Expected< lldb::addr_t > AllocateMemory(size_t size, uint32_t permissions) override
void DoStopIDBumped(uint32_t newBumpId) override
llvm::Expected< std::vector< uint8_t > > TraceGetBinaryData(const TraceGetBinaryDataRequest &request) override
Get binary data given a trace technology and a data identifier.
NativeThreadLinux * GetThreadByID(lldb::tid_t id)
llvm::Error DeallocateMemory(lldb::addr_t addr) override
Status GetFileLoadAddress(const llvm::StringRef &file_name, lldb::addr_t &load_addr) override
Status NotifyTracersOfNewThread(lldb::tid_t tid)
Start tracing a new thread if process tracing is enabled.
const ArchSpec & GetArchitecture() const override
Status GetEventMessage(lldb::tid_t tid, unsigned long *message)
Writes the raw event message code (vis-a-vis PTRACE_GETEVENTMSG) corresponding to the given thread ID...
IntelPTCollector m_intel_pt_collector
Manages Intel PT process and thread traces.
llvm::Error TraceStart(llvm::StringRef json_request, llvm::StringRef type) override
Tracing These methods implement the jLLDBTrace packets.
bool MonitorClone(NativeThreadLinux &parent, lldb::pid_t child_pid, int event)
llvm::DenseMap< lldb::addr_t, lldb::addr_t > m_allocated_memory
Inferior memory (allocated by us) and its size.
Status Interrupt() override
Tells a process to interrupt all operations as if by a Ctrl-C.
std::vector< std::pair< MemoryRegionInfo, FileSpec > > m_mem_region_cache
llvm::Expected< llvm::ArrayRef< uint8_t > > GetSoftwareBreakpointTrapOpcode(size_t size_hint) override
void NotifyTracersProcessWillResume() override
Notify tracers that the target process will resume.
void MonitorSIGTRAP(const siginfo_t &info, NativeThreadLinux &thread)
Status SetBreakpoint(lldb::addr_t addr, uint32_t size, bool hardware) override
llvm::Expected< TraceSupportedResponse > TraceSupported() override
Get the processor tracing type supported for this process.
void MonitorWatchpoint(NativeThreadLinux &thread, uint32_t wp_index)
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
void StopRunningThreads(lldb::tid_t triggering_tid)
Status ResumeThread(NativeThreadLinux &thread, lldb::StateType state, int signo)
Status GetMemoryRegionInfo(lldb::addr_t load_addr, MemoryRegionInfo &range_info) override
NativeThreadLinux & AddThread(lldb::tid_t thread_id, bool resume)
Create a new thread.
static llvm::Expected< std::vector<::pid_t > > Attach(::pid_t pid)
llvm::Expected< uint64_t > Syscall(llvm::ArrayRef< uint64_t > args)
Status Signal(int signo) override
Sends a process a UNIX signal signal.
Status GetLoadedModuleFileSpec(const char *module_path, FileSpec &file_spec) override
void MonitorCallback(NativeThreadLinux &thread, WaitStatus status)
static Status PtraceWrapper(int req, lldb::pid_t pid, void *addr=nullptr, void *data=nullptr, size_t data_size=0, long *result=nullptr)
}
virtual llvm::Expected< MemoryTaggingDetails > GetMemoryTaggingDetails(int32_t type)
Return architecture specific data needed to use memory tags, if they are supported.
virtual std::optional< MmapData > GetMmapData()
Return the architecture-specific data needed to make mmap syscalls, if they are supported.
static llvm::Expected< ArchSpec > DetermineArchitecture(lldb::tid_t tid)
virtual std::optional< SyscallData > GetSyscallData()
Return architecture-specific data needed to make inferior syscalls, if they are supported.
void SetStoppedBySignal(uint32_t signo, const siginfo_t *info=nullptr)
Status SingleStep(uint32_t signo)
Single steps the thread.
void SetStoppedByProcessorTrace(llvm::StringRef description)
NativeRegisterContextLinux & GetRegisterContext() override
Status Resume(uint32_t signo)
Resumes the thread.
void SetStoppedByFork(bool is_vfork, lldb::pid_t child_pid)
#define LLDB_INVALID_SIGNAL_NUMBER
Definition: lldb-defines.h:92
#define LLDB_INVALID_THREAD_ID
Definition: lldb-defines.h:90
#define LLDB_INVALID_INDEX32
Definition: lldb-defines.h:83
#define UNUSED_IF_ASSERT_DISABLED(x)
Definition: lldb-defines.h:140
#define LLDB_INVALID_ADDRESS
Definition: lldb-defines.h:82
#define LLDB_INVALID_PROCESS_ID
Definition: lldb-defines.h:89
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:331
std::optional< lldb::pid_t > getPIDForTID(lldb::pid_t tid)
Definition: linux/Host.cpp:420
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getProcFile(::pid_t pid, ::pid_t tid, const llvm::Twine &file)
Definition: Support.cpp:15
bool StateIsStoppedState(lldb::StateType state, bool must_exist)
Check if a state represents a state where the process or thread is stopped.
Definition: State.cpp:89
bool StateIsRunningState(lldb::StateType state)
Check if a state represents a state where the process or thread is running.
Definition: State.cpp:68
const char * StateAsCString(lldb::StateType state)
Converts a StateType to a C string.
Definition: State.cpp:14
std::function< bool(llvm::Expected< MemoryRegionInfo >)> LinuxMapCallback
Definition: LinuxProcMaps.h:18
void ParseLinuxMapRegions(llvm::StringRef linux_map, LinuxMapCallback const &callback)
void ParseLinuxSMapRegions(llvm::StringRef linux_smap, LinuxMapCallback const &callback)
Definition: SBAddress.h:15
StateType
Process and Thread States.
@ eStateStopped
Process or thread is stopped and can be examined.
@ eStateSuspended
Process or thread is in a suspended state as far as the debugger is concerned while other processes o...
@ eStateRunning
Process or thread is running and can't be examined.
@ eStateStepping
Process or thread is in the process of stepping and can not be examined.
@ eErrorTypePOSIX
POSIX error codes.
uint64_t pid_t
Definition: lldb-types.h:83
std::shared_ptr< lldb_private::WritableDataBuffer > WritableDataBufferSP
Definition: lldb-forward.h:335
uint64_t addr_t
Definition: lldb-types.h:80
uint64_t tid_t
Definition: lldb-types.h:84
Definition: Debugger.h:54
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