LLDB mainline
NativeProcessLinux.cpp
Go to the documentation of this file.
1//===-- NativeProcessLinux.cpp --------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10
16#include "lldb/Host/Host.h"
23#include "lldb/Host/linux/Uio.h"
26#include "lldb/Target/Process.h"
27#include "lldb/Target/Target.h"
30#include "lldb/Utility/State.h"
31#include "lldb/Utility/Status.h"
33#include "llvm/ADT/ScopeExit.h"
34#include "llvm/Support/Errno.h"
35#include "llvm/Support/Error.h"
36#include "llvm/Support/FileSystem.h"
37#include "llvm/Support/Threading.h"
38
39#include <cerrno>
40#include <cstdint>
41#include <cstring>
42#include <optional>
43
44// System includes - They have to be included after framework includes because
45// they define some macros which collide with variable names in other modules.
46#include <linux/unistd.h>
47#include <sys/ptrace.h>
48#include <sys/socket.h>
49#include <sys/syscall.h>
50#include <sys/types.h>
51#include <sys/user.h>
52#include <sys/wait.h>
53#include <unistd.h>
54
55#ifdef __aarch64__
56#include <asm/hwcap.h>
57#include <sys/auxv.h>
58#endif
59
60// Support hardware breakpoints in case it has not been defined
61#ifndef TRAP_HWBKPT
62#define TRAP_HWBKPT 4
63#endif
64
65#ifndef HWCAP2_MTE
66#define HWCAP2_MTE (1 << 18)
67#endif
68
69#ifndef PTRACE_SETREGS
70#define PTRACE_SETREGS 13
71#endif
72
73#ifndef PTRACE_SETFPREGS
74#define PTRACE_SETFPREGS 15
75#endif
76
77#ifndef PTRACE_GETREGSET
78#define PTRACE_GETREGSET 0x4204
79#endif
80
81#ifndef PTRACE_SETREGSET
82#define PTRACE_SETREGSET 0x4205
83#endif
84
85// glibc declares ptrace taking enum __ptrace_request (which requires a cast in
86// C++), whereas bionic and musl declare it taking int and do not define
87// __ptrace_request.
88#ifndef __GLIBC__
89typedef int __ptrace_request;
90#endif
91
92using namespace lldb;
93using namespace lldb_private;
94using namespace lldb_private::process_linux;
95using namespace llvm;
96
97// Private bits we only need internally.
98
100 static bool is_supported;
101 static llvm::once_flag flag;
102
103 llvm::call_once(flag, [] {
105
106 uint32_t source = 0x47424742;
107 uint32_t dest = 0;
108
109 struct iovec local, remote;
110 remote.iov_base = &source;
111 local.iov_base = &dest;
112 remote.iov_len = local.iov_len = sizeof source;
113
114 // We shall try if cross-process-memory reads work by attempting to read a
115 // value from our own process.
116 ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
117 is_supported = (res == sizeof(source) && source == dest);
118 if (is_supported)
119 LLDB_LOG(log,
120 "Detected kernel support for process_vm_readv syscall. "
121 "Fast memory reads enabled.");
122 else
123 LLDB_LOG(log,
124 "syscall process_vm_readv failed (error: {0}). Fast memory "
125 "reads disabled.",
126 llvm::sys::StrError());
127 });
128
129 return is_supported;
130}
131
132static void MaybeLogLaunchInfo(const ProcessLaunchInfo &info) {
134 if (!log)
135 return;
136
137 if (const FileAction *action = info.GetFileActionForFD(STDIN_FILENO))
138 LLDB_LOG(log, "setting STDIN to '{0}'", action->GetFileSpec());
139 else
140 LLDB_LOG(log, "leaving STDIN as is");
141
142 if (const FileAction *action = info.GetFileActionForFD(STDOUT_FILENO))
143 LLDB_LOG(log, "setting STDOUT to '{0}'", action->GetFileSpec());
144 else
145 LLDB_LOG(log, "leaving STDOUT as is");
146
147 if (const FileAction *action = info.GetFileActionForFD(STDERR_FILENO))
148 LLDB_LOG(log, "setting STDERR to '{0}'", action->GetFileSpec());
149 else
150 LLDB_LOG(log, "leaving STDERR as is");
151
152 int i = 0;
153 for (const char **args = info.GetArguments().GetConstArgumentVector(); *args;
154 ++args, ++i)
155 LLDB_LOG(log, "arg {0}: '{1}'", i, *args);
156}
157
158static void DisplayBytes(StreamString &s, void *bytes, uint32_t count) {
159 uint8_t *ptr = (uint8_t *)bytes;
160 constexpr uint32_t kDebugPTraceMaxBytes = 20;
161 const uint32_t loop_count = std::min<uint32_t>(kDebugPTraceMaxBytes, count);
162 for (uint32_t i = 0; i < loop_count; i++) {
163 s.Printf("[%x]", *ptr);
164 ptr++;
165 }
166}
167
168static void PtraceDisplayBytes(int &req, void *data, size_t data_size) {
170 if (!log)
171 return;
172 StreamString buf;
173
174 switch (req) {
175 case PTRACE_POKETEXT: {
176 DisplayBytes(buf, &data, 8);
177 LLDB_LOG_VERBOSE(log, "PTRACE_POKETEXT {0}", buf.GetData());
178 break;
179 }
180 case PTRACE_POKEDATA: {
181 DisplayBytes(buf, &data, 8);
182 LLDB_LOG_VERBOSE(log, "PTRACE_POKEDATA {0}", buf.GetData());
183 break;
184 }
185 case PTRACE_POKEUSER: {
186 DisplayBytes(buf, &data, 8);
187 LLDB_LOG_VERBOSE(log, "PTRACE_POKEUSER {0}", buf.GetData());
188 break;
189 }
190 case PTRACE_SETREGS: {
191 DisplayBytes(buf, data, data_size);
192 LLDB_LOG_VERBOSE(log, "PTRACE_SETREGS {0}", buf.GetData());
193 break;
194 }
195 case PTRACE_SETFPREGS: {
196 DisplayBytes(buf, data, data_size);
197 LLDB_LOG_VERBOSE(log, "PTRACE_SETFPREGS {0}", buf.GetData());
198 break;
199 }
200 case PTRACE_SETSIGINFO: {
201 DisplayBytes(buf, data, sizeof(siginfo_t));
202 LLDB_LOG_VERBOSE(log, "PTRACE_SETSIGINFO {0}", buf.GetData());
203 break;
204 }
205 case PTRACE_SETREGSET: {
206 // Extract iov_base from data, which is a pointer to the struct iovec
207 DisplayBytes(buf, *(void **)data, data_size);
208 LLDB_LOG_VERBOSE(log, "PTRACE_SETREGSET {0}", buf.GetData());
209 break;
210 }
211 default: {}
212 }
213}
214
215static constexpr unsigned k_ptrace_word_size = sizeof(void *);
216static_assert(sizeof(long) >= k_ptrace_word_size,
217 "Size of long must be larger than ptrace word size");
218
219// Simple helper function to ensure flags are enabled on the given file
220// descriptor.
221static Status EnsureFDFlags(int fd, int flags) {
223
224 int status = fcntl(fd, F_GETFL);
225 if (status == -1) {
227 return error;
228 }
229
230 if (fcntl(fd, F_SETFL, status | flags) == -1) {
232 return error;
233 }
234
235 return error;
236}
237
238static llvm::Error AddPtraceScopeNote(llvm::Error original_error) {
239 Expected<int> ptrace_scope = GetPtraceScope();
240 if (auto E = ptrace_scope.takeError()) {
242 "error reading value of ptrace_scope: {0}");
243
244 // The original error is probably more interesting than not being able to
245 // read or interpret ptrace_scope.
246 return original_error;
247 }
248
249 // We only have suggestions to provide for 1-3.
250 switch (*ptrace_scope) {
251 case 1:
252 case 2:
253 llvm::consumeError(std::move(original_error));
254 return llvm::createStringError(
255 std::error_code(errno, std::generic_category()),
256 "The current value of ptrace_scope is %d, which can cause ptrace to "
257 "fail to attach to a running process. To fix this, run:\n"
258 "\tsudo sysctl -w kernel.yama.ptrace_scope=0\n"
259 "For more information, see: "
260 "https://www.kernel.org/doc/Documentation/security/Yama.txt.",
261 *ptrace_scope);
262 case 3:
263 llvm::consumeError(std::move(original_error));
264 return llvm::createStringError(
265 std::error_code(errno, std::generic_category()),
266 "The current value of ptrace_scope is 3, which will cause ptrace to "
267 "fail to attach to a running process. This value cannot be changed "
268 "without rebooting.\n"
269 "For more information, see: "
270 "https://www.kernel.org/doc/Documentation/security/Yama.txt.");
271 case 0:
272 default:
273 return original_error;
274 }
275}
276
278 : NativeProcessProtocol::Manager(mainloop) {
279 Status status;
281 SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status);
282 assert(m_sigchld_handle && status.Success());
283}
284
285llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
287 NativeDelegate &native_delegate) {
289
290 MaybeLogLaunchInfo(launch_info);
291
292 Status status;
294 .LaunchProcess(launch_info, status)
295 .GetProcessId();
296 LLDB_LOG(log, "pid = {0:x}", pid);
297 if (status.Fail()) {
298 LLDB_LOG(log, "failed to launch process: {0}", status);
299 return status.ToError();
300 }
301
302 // Wait for the child process to trap on its call to execve.
303 int wstatus = 0;
304 ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0);
305 assert(wpid == pid);
307 if (!WIFSTOPPED(wstatus)) {
308 LLDB_LOG(log, "Could not sync with inferior process: wstatus={0}",
309 WaitStatus::Decode(wstatus));
310 return llvm::createStringError("could not sync with inferior process");
311 }
312 LLDB_LOG(log, "inferior started, now in stopped state");
313
314 status = SetDefaultPtraceOpts(pid);
315 if (status.Fail()) {
316 LLDB_LOG(log, "failed to set default ptrace options: {0}", status);
317 return status.ToError();
318 }
319
320 llvm::Expected<ArchSpec> arch_or =
322 if (!arch_or)
323 return arch_or.takeError();
324
325 return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
326 pid, launch_info.GetPTY().ReleasePrimaryFileDescriptor(), native_delegate,
327 *arch_or, *this, {pid}));
328}
329
330llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
334 LLDB_LOG(log, "pid = {0:x}", pid);
335
336 auto tids_or = NativeProcessLinux::Attach(pid);
337 if (!tids_or)
338 return tids_or.takeError();
339 ArrayRef<::pid_t> tids = *tids_or;
340 llvm::Expected<ArchSpec> arch_or =
342 if (!arch_or)
343 return arch_or.takeError();
344
345 return std::unique_ptr<NativeProcessLinux>(
346 new NativeProcessLinux(pid, -1, native_delegate, *arch_or, *this, tids));
347}
348
355
356#ifdef __aarch64__
357 // At this point we do not have a process so read auxv directly.
358 if ((getauxval(AT_HWCAP2) & HWCAP2_MTE))
359 supported |= Extension::memory_tagging;
360#endif
361
362 return supported;
363}
364
365static std::optional<std::pair<lldb::pid_t, WaitStatus>> WaitPid() {
367
368 int status;
369 ::pid_t wait_pid = llvm::sys::RetryAfterSignal(
370 -1, ::waitpid, -1, &status, __WALL | __WNOTHREAD | WNOHANG);
371
372 if (wait_pid == 0)
373 return std::nullopt;
374
375 if (wait_pid == -1) {
377 LLDB_LOG(log, "waitpid(-1, &status, _) failed: {0}", error);
378 return std::nullopt;
379 }
380
381 WaitStatus wait_status = WaitStatus::Decode(status);
382
383 LLDB_LOG(log, "waitpid(-1, &status, _) = {0}, status = {1}", wait_pid,
384 wait_status);
385 return std::make_pair(wait_pid, wait_status);
386}
387
390 while (true) {
391 auto wait_result = WaitPid();
392 if (!wait_result)
393 return;
394 lldb::pid_t pid = wait_result->first;
395 WaitStatus status = wait_result->second;
396
397 // Ask each process whether it wants to handle the event. Each event should
398 // be handled by exactly one process, but thread creation events require
399 // special handling.
400 // Thread creation consists of two events (one on the parent and one on the
401 // child thread) and they can arrive in any order nondeterministically. The
402 // parent event carries the information about the child thread, but not
403 // vice-versa. This means that if the child event arrives first, it may not
404 // be handled by any process (because it doesn't know the thread belongs to
405 // it).
406 // The loop below may modify m_processes (create or delete entries), so
407 // operate on a temporary copy.
408 auto processes = llvm::to_vector(m_processes);
409 bool handled = llvm::any_of(processes, [&](NativeProcessLinux *process) {
410 return process->TryHandleWaitStatus(pid, status);
411 });
412 if (!handled) {
413 if (status.type == WaitStatus::Stop && status.status == SIGSTOP) {
414 // Store the thread creation event for later collection.
415 m_unowned_threads.insert(pid);
416 } else {
417 LLDB_LOG(log, "Ignoring waitpid event {0} for pid {1}", status, pid);
418 }
419 }
420 }
421}
422
425
426 if (m_unowned_threads.erase(tid))
427 return; // We've encountered this thread already.
428
429 // The TID is not tracked yet, let's wait for it to appear.
430 int status = -1;
431 LLDB_LOG(log,
432 "received clone event for tid {0}. tid not tracked yet, "
433 "waiting for it to appear...",
434 tid);
435 ::pid_t wait_pid =
436 llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, &status, __WALL);
437
438 // It's theoretically possible to get other events if the entire process was
439 // SIGKILLed before we got a chance to check this. In that case, we'll just
440 // clean everything up when we get the process exit event.
441
442 LLDB_LOG(log,
443 "waitpid({0}, &status, __WALL) => {1} (errno: {2}, status = {3})",
444 tid, wait_pid, errno, WaitStatus::Decode(status));
445}
446
447// Public Instance Methods
448
450 NativeDelegate &delegate,
451 const ArchSpec &arch, Manager &manager,
452 llvm::ArrayRef<::pid_t> tids)
453 : NativeProcessELF(pid, terminal_fd, delegate), m_manager(manager),
454 m_arch(arch), m_intel_pt_collector(*this) {
455 manager.AddProcess(*this);
456 if (m_terminal_fd != -1) {
458 assert(status.Success());
459 }
460
461 for (const auto &tid : tids) {
462 NativeThreadLinux &thread = AddThread(tid, /*resume*/ false);
463 ThreadWasCreated(thread);
464 }
465
466 // Let our process instance know the thread has stopped.
467 SetCurrentThreadID(tids[0]);
469}
470
471llvm::Expected<std::vector<::pid_t>> NativeProcessLinux::Attach(::pid_t pid) {
473
474 Status status;
475 // Use a map to keep track of the threads which we have attached/need to
476 // attach.
477 Host::TidMap tids_to_attach;
478 while (Host::FindProcessThreads(pid, tids_to_attach)) {
479 for (Host::TidMap::iterator it = tids_to_attach.begin();
480 it != tids_to_attach.end();) {
481 if (it->second == false) {
482 lldb::tid_t tid = it->first;
483
484 // Attach to the requested process.
485 // An attach will cause the thread to stop with a SIGSTOP.
486 if ((status = PtraceWrapper(PTRACE_ATTACH, tid)).Fail()) {
487 // No such thread. The thread may have exited. More error handling
488 // may be needed.
489 if (status.GetError() == ESRCH) {
490 it = tids_to_attach.erase(it);
491 continue;
492 }
493 if (status.GetError() == EPERM) {
494 // Depending on the value of ptrace_scope, we can return a different
495 // error that suggests how to fix it.
496 return AddPtraceScopeNote(status.ToError());
497 }
498 return status.ToError();
499 }
500
501 int wpid =
502 llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, nullptr, __WALL);
503 // Need to use __WALL otherwise we receive an error with errno=ECHLD At
504 // this point we should have a thread stopped if waitpid succeeds.
505 if (wpid < 0) {
506 // No such thread. The thread may have exited. More error handling
507 // may be needed.
508 if (errno == ESRCH) {
509 it = tids_to_attach.erase(it);
510 continue;
511 }
512 return llvm::errorCodeToError(
513 std::error_code(errno, std::generic_category()));
514 }
515
516 if ((status = SetDefaultPtraceOpts(tid)).Fail())
517 return status.ToError();
518
519 LLDB_LOG(log, "adding tid = {0}", tid);
520 it->second = true;
521 }
522
523 // move the loop forward
524 ++it;
525 }
526 }
527
528 size_t tid_count = tids_to_attach.size();
529 if (tid_count == 0)
530 return llvm::createStringError("no such process");
531
532 std::vector<::pid_t> tids;
533 tids.reserve(tid_count);
534 for (const auto &p : tids_to_attach)
535 tids.push_back(p.first);
536 return std::move(tids);
537}
538
540 long ptrace_opts = 0;
541
542 // Have the child raise an event on exit. This is used to keep the child in
543 // limbo until it is destroyed.
544 ptrace_opts |= PTRACE_O_TRACEEXIT;
545
546 // Have the tracer trace threads which spawn in the inferior process.
547 ptrace_opts |= PTRACE_O_TRACECLONE;
548
549 // Have the tracer notify us before execve returns (needed to disable legacy
550 // SIGTRAP generation)
551 ptrace_opts |= PTRACE_O_TRACEEXEC;
552
553 // Have the tracer trace forked children.
554 ptrace_opts |= PTRACE_O_TRACEFORK;
555
556 // Have the tracer trace vforks.
557 ptrace_opts |= PTRACE_O_TRACEVFORK;
558
559 // Have the tracer trace vfork-done in order to restore breakpoints after
560 // the child finishes sharing memory.
561 ptrace_opts |= PTRACE_O_TRACEVFORKDONE;
562
563 return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void *)ptrace_opts);
564}
565
567 WaitStatus status) {
568 if (pid == GetID() &&
569 (status.type == WaitStatus::Exit || status.type == WaitStatus::Signal)) {
570 // The process exited. We're done monitoring. Report to delegate.
571 SetExitStatus(status, true);
572 return true;
573 }
574 if (NativeThreadLinux *thread = GetThreadByID(pid)) {
575 MonitorCallback(*thread, status);
576 return true;
577 }
578 return false;
579}
580
582 WaitStatus status) {
584
585 // Certain activities differ based on whether the pid is the tid of the main
586 // thread.
587 const bool is_main_thread = (thread.GetID() == GetID());
588
589 // Handle when the thread exits.
590 if (status.type == WaitStatus::Exit || status.type == WaitStatus::Signal) {
591 LLDB_LOG(log,
592 "got exit status({0}) , tid = {1} ({2} main thread), process "
593 "state = {3}",
594 status, thread.GetID(), is_main_thread ? "is" : "is not",
595 GetState());
596
597 // This is a thread that exited. Ensure we're not tracking it anymore.
598 StopTrackingThread(thread);
599
600 assert(!is_main_thread && "Main thread exits handled elsewhere");
601 return;
602 }
603
604 siginfo_t info;
605 const auto info_err = GetSignalInfo(thread.GetID(), &info);
606
607 // Get details on the signal raised.
608 if (info_err.Success()) {
609 // We have retrieved the signal info. Dispatch appropriately.
610 if (info.si_signo == SIGTRAP)
611 MonitorSIGTRAP(info, thread);
612 else
613 MonitorSignal(info, thread);
614 } else {
615 if (info_err.GetError() == EINVAL) {
616 // This is a group stop reception for this tid. We can reach here if we
617 // reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the tracee,
618 // triggering the group-stop mechanism. Normally receiving these would
619 // stop the process, pending a SIGCONT. Simulating this state in a
620 // debugger is hard and is generally not needed (one use case is
621 // debugging background task being managed by a shell). For general use,
622 // it is sufficient to stop the process in a signal-delivery stop which
623 // happens before the group stop. This done by MonitorSignal and works
624 // correctly for all signals.
625 LLDB_LOG(log,
626 "received a group stop for pid {0} tid {1}. Transparent "
627 "handling of group stops not supported, resuming the "
628 "thread.",
629 GetID(), thread.GetID());
630 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
631 } else {
632 // ptrace(GETSIGINFO) failed (but not due to group-stop).
633
634 // A return value of ESRCH means the thread/process has died in the mean
635 // time. This can (e.g.) happen when another thread does an exit_group(2)
636 // or the entire process get SIGKILLed.
637 // We can't do anything with this thread anymore, but we keep it around
638 // until we get the WIFEXITED event.
639
640 LLDB_LOG(log,
641 "GetSignalInfo({0}) failed: {1}, status = {2}, main_thread = "
642 "{3}. Expecting WIFEXITED soon.",
643 thread.GetID(), info_err, status, is_main_thread);
644 }
645 }
646}
647
648void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info,
649 NativeThreadLinux &thread) {
651 const bool is_main_thread = (thread.GetID() == GetID());
652
653 assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
654
655 switch (info.si_code) {
656 case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
657 case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
658 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): {
659 // This can either mean a new thread or a new process spawned via
660 // clone(2) without SIGCHLD or CLONE_VFORK flag. Note that clone(2)
661 // can also cause PTRACE_EVENT_FORK and PTRACE_EVENT_VFORK if one
662 // of these flags are passed.
663
664 unsigned long event_message = 0;
665 if (GetEventMessage(thread.GetID(), &event_message).Fail()) {
666 LLDB_LOG(log,
667 "pid {0} received clone() event but GetEventMessage failed "
668 "so we don't know the new pid/tid",
669 thread.GetID());
670 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
671 } else {
672 MonitorClone(thread, event_message, info.si_code >> 8);
673 }
674
675 break;
676 }
677
678 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): {
679 LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP);
680
681 // Exec clears any pending notifications.
683
684 // Remove all but the main thread here. Linux fork creates a new process
685 // which only copies the main thread.
686 LLDB_LOG(log, "exec received, stop tracking all but main thread");
687
688 llvm::erase_if(m_threads, [&](std::unique_ptr<NativeThreadProtocol> &t) {
689 return t->GetID() != GetID();
690 });
691 assert(m_threads.size() == 1);
692 auto *main_thread = static_cast<NativeThreadLinux *>(m_threads[0].get());
693
694 SetCurrentThreadID(main_thread->GetID());
695 main_thread->SetStoppedByExec();
696
697 // Tell coordinator about the "new" (since exec) stopped main thread.
698 ThreadWasCreated(*main_thread);
699
700 // Let our delegate know we have just exec'd.
702
703 // Let the process know we're stopped.
704 StopRunningThreads(main_thread->GetID());
705
706 break;
707 }
708
709 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): {
710 // The inferior process or one of its threads is about to exit. We don't
711 // want to do anything with the thread so we just resume it. In case we
712 // want to implement "break on thread exit" functionality, we would need to
713 // stop here.
714
715 unsigned long data = 0;
716 if (GetEventMessage(thread.GetID(), &data).Fail())
717 data = -1;
718
719 LLDB_LOG(log,
720 "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
721 "WIFSIGNALED={2}, pid = {3}, main_thread = {4}",
722 data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(),
723 is_main_thread);
724
725
726 StateType state = thread.GetState();
727 if (!StateIsRunningState(state)) {
728 // Due to a kernel bug, we may sometimes get this stop after the inferior
729 // gets a SIGKILL. This confuses our state tracking logic in
730 // ResumeThread(), since normally, we should not be receiving any ptrace
731 // events while the inferior is stopped. This makes sure that the
732 // inferior is resumed and exits normally.
733 state = eStateRunning;
734 }
736
737 if (is_main_thread) {
738 // Main thread report the read (WIFEXITED) event only after all threads in
739 // the process exit, so we need to stop tracking it here instead of in
740 // MonitorCallback
741 StopTrackingThread(thread);
742 }
743
744 break;
745 }
746
747 case (SIGTRAP | (PTRACE_EVENT_VFORK_DONE << 8)): {
749 thread.SetStoppedByVForkDone();
750 StopRunningThreads(thread.GetID());
751 }
752 else
753 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
754 break;
755 }
756
757 case 0:
758 case TRAP_TRACE: // We receive this on single stepping.
759 case TRAP_HWBKPT: // We receive this on watchpoint hit
760 {
761 // If a watchpoint was hit, report it
762 uint32_t wp_index;
763 Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
764 wp_index, (uintptr_t)info.si_addr);
765 if (error.Fail())
766 LLDB_LOG(log,
767 "received error while checking for watchpoint hits, pid = "
768 "{0}, error = {1}",
769 thread.GetID(), error);
770 if (wp_index != LLDB_INVALID_INDEX32) {
771 MonitorWatchpoint(thread, wp_index);
772 break;
773 }
774
775 // If a breakpoint was hit, report it
776 uint32_t bp_index;
777 error = thread.GetRegisterContext().GetHardwareBreakHitIndex(
778 bp_index, (uintptr_t)info.si_addr);
779 if (error.Fail())
780 LLDB_LOG(log, "received error while checking for hardware "
781 "breakpoint hits, pid = {0}, error = {1}",
782 thread.GetID(), error);
783 if (bp_index != LLDB_INVALID_INDEX32) {
784 MonitorBreakpoint(thread);
785 break;
786 }
787
788 // Otherwise, report step over
789 MonitorTrace(thread);
790 break;
791 }
792
793 case SI_KERNEL:
794 case TRAP_BRKPT:
795 MonitorBreakpoint(thread);
796 break;
797
798 case SIGTRAP:
799 case (SIGTRAP | 0x80):
800 LLDB_LOG(
801 log,
802 "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",
803 info.si_code, GetID(), thread.GetID());
804
805 // Ignore these signals until we know more about them.
806 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
807 break;
808
809 default:
810 LLDB_LOG(log, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}",
811 info.si_code, GetID(), thread.GetID());
812 MonitorSignal(info, thread);
813 break;
814 }
815}
816
819 LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID());
820
821 // This thread is currently stopped.
822 thread.SetStoppedByTrace();
823
824 StopRunningThreads(thread.GetID());
825}
826
829 LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID());
830
831 // Mark the thread as stopped at breakpoint.
832 thread.SetStoppedByBreakpoint();
834
835 NativeRegisterContextLinux &reg_ctx = thread.GetRegisterContext();
836 auto stepping_with_bp_it =
837 m_threads_stepping_with_breakpoint.find(thread.GetID());
838 if (stepping_with_bp_it != m_threads_stepping_with_breakpoint.end() &&
839 llvm::is_contained(stepping_with_bp_it->second, reg_ctx.GetPC()))
840 thread.SetStoppedByTrace();
841
842 StopRunningThreads(thread.GetID());
843}
844
846 uint32_t wp_index) {
848 LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}",
849 thread.GetID(), wp_index);
850
851 // Mark the thread as stopped at watchpoint. The address is at
852 // (lldb::addr_t)info->si_addr if we need it.
853 thread.SetStoppedByWatchpoint(wp_index);
854
855 // We need to tell all other running threads before we notify the delegate
856 // about this stop.
857 StopRunningThreads(thread.GetID());
858}
859
860void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
861 NativeThreadLinux &thread) {
862 const int signo = info.si_signo;
863 const bool is_from_llgs = info.si_pid == getpid();
864
866
867 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
868 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a kill(2)
869 // or raise(3). Similarly for tgkill(2) on Linux.
870 //
871 // IOW, user generated signals never generate what we consider to be a
872 // "crash".
873 //
874 // Similarly, ACK signals generated by this monitor.
875
876 // Handle the signal.
877 LLDB_LOG(log,
878 "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
879 "waitpid pid = {4})",
880 Host::GetSignalAsCString(signo), signo, info.si_code, info.si_pid,
881 thread.GetID());
882
883 // Check for thread stop notification.
884 if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) {
885 // This is a tgkill()-based stop.
886 LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID());
887
888 // Check that we're not already marked with a stop reason. Note this thread
889 // really shouldn't already be marked as stopped - if we were, that would
890 // imply that the kernel signaled us with the thread stopping which we
891 // handled and marked as stopped, and that, without an intervening resume,
892 // we received another stop. It is more likely that we are missing the
893 // marking of a run state somewhere if we find that the thread was marked
894 // as stopped.
895 const StateType thread_state = thread.GetState();
896 if (!StateIsStoppedState(thread_state, false)) {
897 // An inferior thread has stopped because of a SIGSTOP we have sent it.
898 // Generally, these are not important stops and we don't want to report
899 // them as they are just used to stop other threads when one thread (the
900 // one with the *real* stop reason) hits a breakpoint (watchpoint,
901 // etc...). However, in the case of an asynchronous Interrupt(), this
902 // *is* the real stop reason, so we leave the signal intact if this is
903 // the thread that was chosen as the triggering thread.
905 if (m_pending_notification_tid == thread.GetID())
906 thread.SetStoppedBySignal(SIGSTOP, &info);
907 else
908 thread.SetStoppedWithNoReason();
909
910 SetCurrentThreadID(thread.GetID());
912 } else {
913 // We can end up here if stop was initiated by LLGS but by this time a
914 // thread stop has occurred - maybe initiated by another event.
915 Status error = ResumeThread(thread, thread.GetState(), 0);
916 if (error.Fail())
917 LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(),
918 error);
919 }
920 } else {
921 LLDB_LOG(log,
922 "pid {0} tid {1}, thread was already marked as a stopped "
923 "state (state={2}), leaving stop signal as is",
924 GetID(), thread.GetID(), thread_state);
926 }
927
928 // Done handling.
929 return;
930 }
931
932 // Check if debugger should stop at this signal or just ignore it and resume
933 // the inferior.
934 if (m_signals_to_ignore.contains(signo)) {
935 ResumeThread(thread, thread.GetState(), signo);
936 return;
937 }
938
939 // This thread is stopped.
940 LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo));
941 thread.SetStoppedBySignal(signo, &info);
942
943 // Send a stop to the debugger after we get all other threads to stop.
944 StopRunningThreads(thread.GetID());
945}
946
948 lldb::pid_t child_pid, int event) {
950 LLDB_LOG(log, "parent_tid={0}, child_pid={1}, event={2}", parent.GetID(),
951 child_pid, event);
952
953 m_manager.CollectThread(child_pid);
954
955 switch (event) {
956 case PTRACE_EVENT_CLONE: {
957 // PTRACE_EVENT_CLONE can either mean a new thread or a new process.
958 // Try to grab the new process' PGID to figure out which one it is.
959 // If PGID is the same as the PID, then it's a new process. Otherwise,
960 // it's a thread.
961 auto tgid_ret = getPIDForTID(child_pid);
962 if (tgid_ret != child_pid) {
963 // A new thread should have PGID matching our process' PID.
964 assert(!tgid_ret || *tgid_ret == GetID());
965
966 NativeThreadLinux &child_thread = AddThread(child_pid, /*resume*/ true);
967 ThreadWasCreated(child_thread);
968
969 // Resume the parent.
971 break;
972 }
973 }
974 [[fallthrough]];
975 case PTRACE_EVENT_FORK:
976 case PTRACE_EVENT_VFORK: {
977 bool is_vfork = event == PTRACE_EVENT_VFORK;
978 std::unique_ptr<NativeProcessLinux> child_process{new NativeProcessLinux(
979 static_cast<::pid_t>(child_pid), m_terminal_fd, m_delegate, m_arch,
980 m_manager, {static_cast<::pid_t>(child_pid)})};
981 if (!is_vfork)
982 child_process->m_software_breakpoints = m_software_breakpoints;
983
984 Extension expected_ext = is_vfork ? Extension::vfork : Extension::fork;
985 if (bool(m_enabled_extensions & expected_ext)) {
986 m_delegate.NewSubprocess(this, std::move(child_process));
987 // NB: non-vfork clone() is reported as fork
988 parent.SetStoppedByFork(is_vfork, child_pid);
989 StopRunningThreads(parent.GetID());
990 } else {
991 child_process->Detach();
993 }
994 break;
995 }
996 default:
997 llvm_unreachable("unknown clone_info.event");
998 }
999
1000 return true;
1001}
1002
1004 if (m_arch.GetMachine() == llvm::Triple::arm ||
1005 m_arch.GetTriple().isRISCV() || m_arch.GetTriple().isLoongArch())
1006 return false;
1007 return true;
1008}
1009
1012 LLDB_LOG(log, "pid {0}", GetID());
1013
1015
1016 bool software_single_step = !SupportHardwareSingleStepping();
1017
1018 if (software_single_step) {
1019 for (const auto &thread : m_threads) {
1020 assert(thread && "thread list should not contain NULL threads");
1021
1022 const ResumeAction *const action =
1023 resume_actions.GetActionForThread(thread->GetID(), true);
1024 if (action == nullptr)
1025 continue;
1026
1027 if (action->state == eStateStepping) {
1029 static_cast<NativeThreadLinux &>(*thread));
1030 if (error.Fail())
1031 return error;
1032 }
1033 }
1034 }
1035
1036 for (const auto &thread : m_threads) {
1037 assert(thread && "thread list should not contain NULL threads");
1038
1039 const ResumeAction *const action =
1040 resume_actions.GetActionForThread(thread->GetID(), true);
1041
1042 if (action == nullptr) {
1043 LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
1044 thread->GetID());
1045 continue;
1046 }
1047
1048 LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}",
1049 action->state, GetID(), thread->GetID());
1050
1051 switch (action->state) {
1052 case eStateRunning:
1053 case eStateStepping: {
1054 // Run the thread, possibly feeding it the signal.
1055 const int signo = action->signal;
1056 Status error = ResumeThread(static_cast<NativeThreadLinux &>(*thread),
1057 action->state, signo);
1058 if (error.Fail())
1060 "NativeProcessLinux::%s: failed to resume thread "
1061 "for pid %" PRIu64 ", tid %" PRIu64 ", error = %s",
1062 __FUNCTION__, GetID(), thread->GetID(), error.AsCString());
1063
1064 break;
1065 }
1066
1067 case eStateSuspended:
1068 case eStateStopped:
1069 break;
1070
1071 default:
1073 "NativeProcessLinux::%s (): unexpected state %s specified "
1074 "for pid %" PRIu64 ", tid %" PRIu64,
1075 __FUNCTION__, StateAsCString(action->state), GetID(),
1076 thread->GetID());
1077 }
1078 }
1079
1080 return Status();
1081}
1082
1084 Status error;
1085
1086 if (kill(GetID(), SIGSTOP) != 0)
1088
1089 return error;
1090}
1091
1093 Status error;
1094
1095 // Tell ptrace to detach from the process.
1097 return error;
1098
1099 // Cancel out any SIGSTOPs we may have sent while stopping the process.
1100 // Otherwise, the process may stop as soon as we detach from it.
1101 kill(GetID(), SIGCONT);
1102
1103 for (const auto &thread : m_threads) {
1104 Status e = Detach(thread->GetID());
1105 // Save the error, but still attempt to detach from other threads.
1106 if (e.Fail())
1107 error = e.Clone();
1108 }
1109
1110 m_intel_pt_collector.Clear();
1111
1112 return error;
1113}
1114
1116 Status error;
1117
1119 LLDB_LOG(log, "sending signal {0} ({1}) to pid {2}", signo,
1121
1122 if (kill(GetID(), signo))
1124
1125 return error;
1126}
1127
1129 // Pick a running thread (or if none, a not-dead stopped thread) as the
1130 // chosen thread that will be the stop-reason thread.
1132
1133 NativeThreadProtocol *running_thread = nullptr;
1134 NativeThreadProtocol *stopped_thread = nullptr;
1135
1136 LLDB_LOG(log, "selecting running thread for interrupt target");
1137 for (const auto &thread : m_threads) {
1138 // If we have a running or stepping thread, we'll call that the target of
1139 // the interrupt.
1140 const auto thread_state = thread->GetState();
1141 if (thread_state == eStateRunning || thread_state == eStateStepping) {
1142 running_thread = thread.get();
1143 break;
1144 } else if (!stopped_thread && StateIsStoppedState(thread_state, true)) {
1145 // Remember the first non-dead stopped thread. We'll use that as a
1146 // backup if there are no running threads.
1147 stopped_thread = thread.get();
1148 }
1149 }
1150
1151 if (!running_thread && !stopped_thread) {
1152 Status error("found no running/stepping or live stopped threads as target "
1153 "for interrupt");
1154 LLDB_LOG(log, "skipping due to error: {0}", error);
1155
1156 return error;
1157 }
1158
1159 NativeThreadProtocol *deferred_signal_thread =
1160 running_thread ? running_thread : stopped_thread;
1161
1162 LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(),
1163 running_thread ? "running" : "stopped",
1164 deferred_signal_thread->GetID());
1165
1166 StopRunningThreads(deferred_signal_thread->GetID());
1167
1168 return Status();
1169}
1170
1173 LLDB_LOG(log, "pid {0}", GetID());
1174
1175 Status error;
1176
1177 switch (m_state) {
1183 // Nothing to do - the process is already dead.
1184 LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
1185 m_state);
1186 return error;
1187
1195 // We can try to kill a process in these states.
1196 break;
1197 }
1198
1199 if (kill(GetID(), SIGKILL) != 0) {
1201 return error;
1202 }
1203
1204 return error;
1205}
1206
1208 MemoryRegionInfo &range_info) {
1209 // FIXME review that the final memory region returned extends to the end of
1210 // the virtual address space,
1211 // with no perms if it is not mapped.
1212
1213 // Use an approach that reads memory regions from /proc/{pid}/maps. Assume
1214 // proc maps entries are in ascending order.
1215 // FIXME assert if we find differently.
1216
1218 // We're done.
1219 return Status::FromErrorString("unsupported");
1220 }
1221
1223 if (error.Fail()) {
1224 return error;
1225 }
1226
1227 lldb::addr_t prev_base_address = 0;
1228
1229 // FIXME start by finding the last region that is <= target address using
1230 // binary search. Data is sorted.
1231 // There can be a ton of regions on pthreads apps with lots of threads.
1232 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1233 ++it) {
1234 MemoryRegionInfo &proc_entry_info = it->first;
1235
1236 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1237 assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
1238 "descending /proc/pid/maps entries detected, unexpected");
1239 prev_base_address = proc_entry_info.GetRange().GetRangeBase();
1240 UNUSED_IF_ASSERT_DISABLED(prev_base_address);
1241
1242 // If the target address comes before this entry, indicate distance to next
1243 // region.
1244 if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1245 range_info.GetRange().SetRangeBase(load_addr);
1246 range_info.GetRange().SetByteSize(
1247 proc_entry_info.GetRange().GetRangeBase() - load_addr);
1248 range_info.SetReadable(eLazyBoolNo);
1249 range_info.SetWritable(eLazyBoolNo);
1250 range_info.SetExecutable(eLazyBoolNo);
1251 range_info.SetMapped(eLazyBoolNo);
1252
1253 return error;
1254 } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1255 // The target address is within the memory region we're processing here.
1256 range_info = proc_entry_info;
1257 return error;
1258 }
1259
1260 // The target memory address comes somewhere after the region we just
1261 // parsed.
1262 }
1263
1264 // If we made it here, we didn't find an entry that contained the given
1265 // address. Return the load_addr as start and the amount of bytes betwwen
1266 // load address and the end of the memory as size.
1267 range_info.GetRange().SetRangeBase(load_addr);
1269 range_info.SetReadable(eLazyBoolNo);
1270 range_info.SetWritable(eLazyBoolNo);
1271 range_info.SetExecutable(eLazyBoolNo);
1272 range_info.SetMapped(eLazyBoolNo);
1273 return error;
1274}
1275
1278
1279 // If our cache is empty, pull the latest. There should always be at least
1280 // one memory region if memory region handling is supported.
1281 if (!m_mem_region_cache.empty()) {
1282 LLDB_LOG(log, "reusing {0} cached memory region entries",
1283 m_mem_region_cache.size());
1284 return Status();
1285 }
1286
1287 Status Result;
1288 LinuxMapCallback callback = [&](llvm::Expected<MemoryRegionInfo> Info) {
1289 if (Info) {
1290 FileSpec file_spec(Info->GetName().GetCString());
1291 FileSystem::Instance().Resolve(file_spec);
1292 m_mem_region_cache.emplace_back(*Info, file_spec);
1293 return true;
1294 }
1295
1296 Result = Status::FromError(Info.takeError());
1298 LLDB_LOG(log, "failed to parse proc maps: {0}", Result);
1299 return false;
1300 };
1301
1302 // Linux kernel since 2.6.14 has /proc/{pid}/smaps
1303 // if CONFIG_PROC_PAGE_MONITOR is enabled
1304 auto BufferOrError = getProcFile(GetID(), GetCurrentThreadID(), "smaps");
1305 if (BufferOrError)
1306 ParseLinuxSMapRegions(BufferOrError.get()->getBuffer(), callback);
1307 else {
1308 BufferOrError = getProcFile(GetID(), GetCurrentThreadID(), "maps");
1309 if (!BufferOrError) {
1311 return BufferOrError.getError();
1312 }
1313
1314 ParseLinuxMapRegions(BufferOrError.get()->getBuffer(), callback);
1315 }
1316
1317 if (Result.Fail())
1318 return Result;
1319
1320 if (m_mem_region_cache.empty()) {
1321 // No entries after attempting to read them. This shouldn't happen if
1322 // /proc/{pid}/maps is supported. Assume we don't support map entries via
1323 // procfs.
1325 LLDB_LOG(log,
1326 "failed to find any procfs maps entries, assuming no support "
1327 "for memory region metadata retrieval");
1328 return Status::FromErrorString("not supported");
1329 }
1330
1331 LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps",
1332 m_mem_region_cache.size(), GetID());
1333
1334 // We support memory retrieval, remember that.
1336 return Status();
1337}
1338
1339llvm::Expected<uint64_t>
1340NativeProcessLinux::Syscall(llvm::ArrayRef<uint64_t> args) {
1342 auto region_it = llvm::find_if(m_mem_region_cache, [](const auto &pair) {
1343 return pair.first.GetExecutable() == eLazyBoolYes &&
1344 pair.first.GetShared() != eLazyBoolYes;
1345 });
1346 if (region_it == m_mem_region_cache.end())
1347 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1348 "No executable memory region found!");
1349
1350 addr_t exe_addr = region_it->first.GetRange().GetRangeBase();
1351
1353 assert(thread.GetState() == eStateStopped);
1354 NativeRegisterContextLinux &reg_ctx = thread.GetRegisterContext();
1355
1357 *reg_ctx.GetSyscallData();
1358
1359 WritableDataBufferSP registers_sp;
1360 if (llvm::Error Err = reg_ctx.ReadAllRegisterValues(registers_sp).ToError())
1361 return std::move(Err);
1362 llvm::scope_exit restore_regs(
1363 [&] { reg_ctx.WriteAllRegisterValues(registers_sp); });
1364
1365 llvm::SmallVector<uint8_t, 8> memory(syscall_data.Insn.size());
1366 size_t bytes_read;
1367 if (llvm::Error Err =
1368 ReadMemory(exe_addr, memory.data(), memory.size(), bytes_read)
1369 .ToError()) {
1370 return std::move(Err);
1371 }
1372
1373 llvm::scope_exit restore_mem([&] {
1374 DoWriteMemory(exe_addr, memory.data(), memory.size(), bytes_read);
1375 });
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 = DoWriteMemory(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::FromError(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::FromError(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::FromError(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::FromError(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::FromError(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 void *buf, size_t size,
1643 size_t &bytes_read) {
1644 lldb::addr_t addr = process_addr.GetValue();
1645 Log *log = GetLog(POSIXLog::Memory);
1646 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
1647
1648 bytes_read = 0;
1650 // The process_vm_readv path is about 50 times faster than ptrace api. We
1651 // want to use this syscall if it is supported.
1652
1653 struct iovec local_iov, remote_iov;
1654 local_iov.iov_base = buf;
1655 local_iov.iov_len = size;
1656 remote_iov.iov_base = reinterpret_cast<void *>(addr);
1657 remote_iov.iov_len = size;
1658
1659 ssize_t read_result = process_vm_readv(GetCurrentThreadID(), &local_iov, 1,
1660 &remote_iov, 1, 0);
1661 int error = 0;
1662 if (read_result < 0)
1663 error = errno;
1664 else
1665 bytes_read = read_result;
1666
1667 LLDB_LOG(log,
1668 "process_vm_readv({0}, [iovec({1}, {2})], [iovec({3:x}, {2})], 1, "
1669 "0) => {4} ({5})",
1670 GetCurrentThreadID(), buf, size, addr, read_result,
1671 error > 0 ? llvm::sys::StrError(errno) : "sucesss");
1672 }
1673
1674 unsigned char *dst = static_cast<unsigned char *>(buf);
1675 size_t remainder;
1676 long data;
1677
1678 for (; bytes_read < size; bytes_read += remainder) {
1680 PTRACE_PEEKDATA, GetCurrentThreadID(),
1681 reinterpret_cast<void *>(addr + bytes_read), nullptr, 0, &data);
1682 if (error.Fail())
1683 return error;
1684
1685 remainder = size - bytes_read;
1686 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
1687
1688 // Copy the data into our buffer
1689 memcpy(dst + bytes_read, &data, remainder);
1690 }
1691 return Status();
1692}
1693
1695 size_t size, size_t &bytes_written) {
1696 const unsigned char *src = static_cast<const unsigned char *>(buf);
1697 size_t remainder;
1698 Status error;
1699
1700 Log *log = GetLog(POSIXLog::Memory);
1701 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
1702
1703 for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
1704 remainder = size - bytes_written;
1705 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
1706
1707 if (remainder == k_ptrace_word_size) {
1708 unsigned long data = 0;
1709 memcpy(&data, src, k_ptrace_word_size);
1710
1711 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
1713 PTRACE_POKEDATA, GetCurrentThreadID(), (void *)addr, (void *)data);
1714 if (error.Fail())
1715 return error;
1716 } else {
1717 unsigned char buff[8];
1718 size_t bytes_read;
1719 error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
1720 if (error.Fail())
1721 return error;
1722
1723 memcpy(buff, src, remainder);
1724
1725 size_t bytes_written_rec;
1726 error = DoWriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
1727 if (error.Fail())
1728 return error;
1729
1730 LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src,
1731 *(unsigned long *)buff);
1732 }
1733
1734 addr += k_ptrace_word_size;
1735 src += k_ptrace_word_size;
1736 }
1737 return error;
1738}
1739
1741 return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
1742}
1743
1745 unsigned long *message) {
1746 return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
1747}
1748
1750 if (tid == LLDB_INVALID_THREAD_ID)
1751 return Status();
1752
1753 return PtraceWrapper(PTRACE_DETACH, tid);
1754}
1755
1757 for (const auto &thread : m_threads) {
1758 assert(thread && "thread list should not contain NULL threads");
1759 if (thread->GetID() == thread_id) {
1760 // We have this thread.
1761 return true;
1762 }
1763 }
1764
1765 // We don't have this thread.
1766 return false;
1767}
1768
1770 Log *const log = GetLog(POSIXLog::Thread);
1771 lldb::tid_t thread_id = thread.GetID();
1772 LLDB_LOG(log, "tid: {0}", thread_id);
1773
1774 auto it = llvm::find_if(m_threads, [&](const auto &thread_up) {
1775 return thread_up.get() == &thread;
1776 });
1777 assert(it != m_threads.end());
1778 m_threads.erase(it);
1779
1782}
1783
1787
1791
1793 Log *log = GetLog(POSIXLog::Thread);
1794 Status error = Status::FromError(m_intel_pt_collector.OnThreadCreated(tid));
1795 if (error.Fail())
1796 LLDB_LOG(log, "Failed to trace a new thread with intel-pt, tid = {0}. {1}",
1797 tid, error.AsCString());
1798 return error;
1799}
1800
1802 Log *log = GetLog(POSIXLog::Thread);
1803 Status error = Status::FromError(m_intel_pt_collector.OnThreadDestroyed(tid));
1804 if (error.Fail())
1805 LLDB_LOG(log,
1806 "Failed to stop a destroyed thread with intel-pt, tid = {0}. {1}",
1807 tid, error.AsCString());
1808 return error;
1809}
1810
1812 bool resume) {
1813 Log *log = GetLog(POSIXLog::Thread);
1814 LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
1815
1816 assert(!HasThreadNoLock(thread_id) &&
1817 "attempted to add a thread by id that already exists");
1818
1819 // If this is the first thread, save it as the current thread
1820 if (m_threads.empty())
1821 SetCurrentThreadID(thread_id);
1822
1823 m_threads.push_back(std::make_unique<NativeThreadLinux>(*this, thread_id));
1824 NativeThreadLinux &thread =
1825 static_cast<NativeThreadLinux &>(*m_threads.back());
1826
1827 Status tracing_error = NotifyTracersOfNewThread(thread.GetID());
1828 if (tracing_error.Fail()) {
1829 thread.SetStoppedByProcessorTrace(tracing_error.AsCString());
1830 StopRunningThreads(thread.GetID());
1831 } else if (resume)
1833 else
1834 thread.SetStoppedBySignal(SIGSTOP);
1835
1836 return thread;
1837}
1838
1840 FileSpec &file_spec) {
1842 if (error.Fail())
1843 return error;
1844
1845 FileSpec module_file_spec(module_path);
1846 FileSystem::Instance().Resolve(module_file_spec);
1847
1848 file_spec.Clear();
1849 for (const auto &it : m_mem_region_cache) {
1850 if (it.second.GetFilename() == module_file_spec.GetFilename()) {
1851 file_spec = it.second;
1852 return Status();
1853 }
1854 }
1856 "Module file ({0}) not found in /proc/{1}/maps file!",
1857 module_file_spec.GetFilename(), 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::FromErrorString("No load address found for specified file.");
1875}
1876
1881
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?",
1902 thread.GetID(), m_pending_notification_tid);
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 Status resume_result = thread.Resume(signo);
1910 if (resume_result.Success())
1911 SetState(eStateRunning, true);
1912 return resume_result;
1913 }
1914 case eStateStepping: {
1915 Status 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 (addr_t bp_addr : m_step_breakpoints) {
1961 Status error = RemoveBreakpoint(bp_addr);
1962 if (error.Fail())
1963 LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}", bp_addr,
1964 error);
1965 }
1966 m_step_breakpoints.clear();
1968
1969 // Notify the delegate about the stop
1973}
1974
1976 Log *const log = GetLog(POSIXLog::Thread);
1977 LLDB_LOG(log, "tid: {0}", thread.GetID());
1978
1980 StateIsRunningState(thread.GetState())) {
1981 // We will need to wait for this new thread to stop as well before firing
1982 // the notification.
1983 thread.RequestStop();
1984 }
1985}
1986
1987// Wrapper for ptrace to catch errors and log calls. Note that ptrace sets
1988// errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
1990 void *data, size_t data_size,
1991 long *result) {
1992 Status error;
1993 long int ret;
1994
1995 Log *log = GetLog(POSIXLog::Ptrace);
1996
1997 PtraceDisplayBytes(req, data, data_size);
1998
1999 errno = 0;
2000 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
2001 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2002 *(unsigned int *)addr, data);
2003 else
2004 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2005 addr, data);
2006
2007 if (ret == -1)
2009
2010 if (result)
2011 *result = ret;
2012
2013 LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data,
2014 data_size, ret);
2015
2016 PtraceDisplayBytes(req, data, data_size);
2017
2018 if (error.Fail())
2019 LLDB_LOG(log, "ptrace() failed: {0}", error);
2020
2021 return error;
2022}
2023
2024llvm::Expected<TraceSupportedResponse> NativeProcessLinux::TraceSupported() {
2026 return TraceSupportedResponse{"intel-pt", "Intel Processor Trace"};
2028}
2029
2030Error NativeProcessLinux::TraceStart(StringRef json_request, StringRef type) {
2031 if (type == "intel-pt") {
2032 if (Expected<TraceIntelPTStartRequest> request =
2033 json::parse<TraceIntelPTStartRequest>(json_request,
2034 "TraceIntelPTStartRequest")) {
2035 return m_intel_pt_collector.TraceStart(*request);
2036 } else
2037 return request.takeError();
2038 }
2039
2040 return NativeProcessProtocol::TraceStart(json_request, type);
2041}
2042
2044 if (request.type == "intel-pt")
2045 return m_intel_pt_collector.TraceStop(request);
2046 return NativeProcessProtocol::TraceStop(request);
2047}
2048
2049Expected<json::Value> NativeProcessLinux::TraceGetState(StringRef type) {
2050 if (type == "intel-pt")
2051 return m_intel_pt_collector.GetState();
2053}
2054
2055Expected<std::vector<uint8_t>> NativeProcessLinux::TraceGetBinaryData(
2056 const TraceGetBinaryDataRequest &request) {
2057 if (request.type == "intel-pt")
2058 return m_intel_pt_collector.GetBinaryData(request);
2060}
static llvm::raw_ostream & error(Stream &strm)
#define PROT_READ
#define PROT_WRITE
#define PROT_NONE
#define PROT_EXEC
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:375
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:405
#define LLDB_LOG_VERBOSE(log,...)
Definition Log.h:382
static std::optional< std::pair< lldb::pid_t, WaitStatus > > WaitPid()
static constexpr unsigned k_ptrace_word_size
static Status EnsureFDFlags(int fd, int flags)
static void MaybeLogLaunchInfo(const ProcessLaunchInfo &info)
#define TRAP_HWBKPT
int __ptrace_request
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 PTRACE_SETREGSET
#define HWCAP2_MTE
#define PTRACE_SETREGS
#define PTRACE_SETFPREGS
static void DisplayBytes(StreamString &s, void *bytes, uint32_t count)
static bool ProcessVmReadvSupported()
#define PTRACE_GETREGSET
#define MAP_PRIVATE
ssize_t process_vm_readv(::pid_t pid, const struct iovec *local_iov, unsigned long liovcnt, const struct iovec *remote_iov, unsigned long riovcnt, unsigned long flags)
Definition LibcGlue.cpp:18
An architecture specification class.
Definition ArchSpec.h:32
const char ** GetConstArgumentVector() const
Gets the argument vector.
Definition Args.cpp:289
Represents a file descriptor action to be performed during process launch.
Definition FileAction.h:21
A file utility class.
Definition FileSpec.h:56
llvm::StringRef GetFilename() const
Filename string const get accessor.
Definition FileSpec.h:248
void Clear()
Clears the object state.
Definition FileSpec.cpp:265
static FileSystem & Instance()
void Resolve(llvm::SmallVectorImpl< char > &path, bool force_make_absolute=false)
Resolve path to make it canonical.
lldb::pid_t GetProcessId() const
static bool FindProcessThreads(const lldb::pid_t pid, TidMap &tids_to_attach)
std::map< lldb::pid_t, bool > TidMap
Definition Host.h:179
static const char * GetSignalAsCString(int signo)
SignalHandleUP RegisterSignal(int signo, const Callback &callback, Status &error)
Range< lldb::addr_t, lldb::addr_t > TagRange
Abstract class that extends NativeProcessProtocol with ELF specific logic.
std::vector< std::pair< MemoryRegionInfo, FileSpec > > m_mem_region_cache
NativeProcessProtocol(lldb::pid_t pid, int terminal_fd, NativeDelegate &delegate)
void NotifyDidExec() override
Notify the delegate that an exec occurred.
virtual llvm::Expected< TraceSupportedResponse > TraceSupported()
Get the processor tracing type supported for this process.
virtual llvm::Expected< std::vector< uint8_t > > TraceGetBinaryData(const TraceGetBinaryDataRequest &request)
Get binary data given a trace technology and a data identifier.
virtual llvm::Error TraceStop(const TraceStopRequest &request)
Stop tracing a live process or its threads.
Status SetSoftwareBreakpoint(lldb::addr_t addr, uint32_t size_hint)
virtual llvm::Expected< llvm::json::Value > TraceGetState(llvm::StringRef type)
Get the current tracing state of the process and its threads.
void SetState(lldb::StateType state, bool notify_delegates=true)
NativeThreadProtocol * GetThreadByID(lldb::tid_t tid)
std::vector< std::unique_ptr< NativeThreadProtocol > > m_threads
virtual bool SetExitStatus(WaitStatus status, bool bNotifyStateChange)
virtual Status RemoveBreakpoint(lldb::addr_t addr, bool hardware=false)
void FixupBreakpointPCAsNeeded(NativeThreadProtocol &thread)
Extension
Extension flag constants, returned by Manager::GetSupportedExtensions() and passed to SetEnabledExten...
virtual Status SetHardwareBreakpoint(lldb::addr_t addr, size_t size)
std::map< lldb::addr_t, SoftwareBreakpoint > m_software_breakpoints
virtual llvm::Expected< llvm::ArrayRef< uint8_t > > GetSoftwareBreakpointTrapOpcode(size_t size_hint)
virtual llvm::Error TraceStart(llvm::StringRef json_params, llvm::StringRef type)
Start tracing a process or its threads.
virtual Status RemoveHardwareBreakpoint(lldb::addr_t addr)
std::map< lldb::tid_t, std::vector< lldb::addr_t > > m_threads_stepping_with_breakpoint
Status SetupSoftwareSingleStepping(NativeThreadProtocol &thread)
lldb::addr_t ReadRegisterAsUnsigned(uint32_t reg, lldb::addr_t fail_value)
virtual Status WriteAllRegisterValues(const lldb::DataBufferSP &data_sp)=0
lldb::addr_t GetPC(lldb::addr_t fail_value=LLDB_INVALID_ADDRESS)
virtual Status ReadAllRegisterValues(lldb::WritableDataBufferSP &data_sp)=0
An address in a process, qualified by an address space.
lldb::addr_t GetValue() const
const FileAction * GetFileActionForFD(int fd) const
HostProcess LaunchProcess(const ProcessLaunchInfo &launch_info, Status &error) override
int ReleasePrimaryFileDescriptor()
Release the primary file descriptor.
const ResumeAction * GetActionForThread(lldb::tid_t tid, bool default_ok) const
Definition Debug.h:74
An error handling class.
Definition Status.h:118
static Status FromErrno()
Set the current error to errno.
Definition Status.cpp:299
Status Clone() const
Don't call this function in new code.
Definition Status.h:174
ValueType GetError() const
Access the error value.
Definition Status.cpp:221
llvm::Error ToError() const
FIXME: Replace all uses with takeError() instead.
Definition Status.cpp:138
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
bool Fail() const
Test for error condition.
Definition Status.cpp:293
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
Definition Status.cpp:194
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition Status.h:151
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
Definition Status.cpp:136
bool Success() const
Test for success condition.
Definition Status.cpp:303
const char * GetData() const
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
llvm::Expected< std::unique_ptr< NativeProcessProtocol > > Attach(lldb::pid_t pid, NativeDelegate &native_delegate) override
Attach to an existing process.
llvm::SmallPtrSet< NativeProcessLinux *, 2 > m_processes
Extension GetSupportedExtensions() const override
Get the bitmask of extensions supported by this process plugin.
llvm::Expected< std::unique_ptr< NativeProcessProtocol > > Launch(ProcessLaunchInfo &launch_info, NativeDelegate &native_delegate) override
Launch a process for debugging.
llvm::Expected< lldb::addr_t > AllocateMemory(size_t size, uint32_t permissions) override
llvm::Expected< std::vector< uint8_t > > TraceGetBinaryData(const TraceGetBinaryDataRequest &request) override
Get binary data given a trace technology and a data identifier.
NativeThreadLinux * GetThreadByID(lldb::tid_t id)
llvm::Error DeallocateMemory(lldb::addr_t addr) override
Status GetFileLoadAddress(const llvm::StringRef &file_name, lldb::addr_t &load_addr) override
Status NotifyTracersOfNewThread(lldb::tid_t tid)
Start tracing a new thread if process tracing is enabled.
const ArchSpec & GetArchitecture() const override
Status GetEventMessage(lldb::tid_t tid, unsigned long *message)
Writes the raw event message code (vis-a-vis PTRACE_GETEVENTMSG) corresponding to the given thread ID...
Status DoWriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written) override
IntelPTCollector m_intel_pt_collector
Manages Intel PT process and thread traces.
llvm::Error TraceStart(llvm::StringRef json_request, llvm::StringRef type) override
Tracing These methods implement the jLLDBTrace packets.
bool MonitorClone(NativeThreadLinux &parent, lldb::pid_t child_pid, int event)
llvm::DenseMap< lldb::addr_t, lldb::addr_t > m_allocated_memory
Inferior memory (allocated by us) and its size.
Status Interrupt() override
Tells a process to interrupt all operations as if by a Ctrl-C.
llvm::Expected< llvm::ArrayRef< uint8_t > > GetSoftwareBreakpointTrapOpcode(size_t size_hint) override
void NotifyTracersProcessWillResume() override
Notify tracers that the target process will resume.
void MonitorSIGTRAP(const siginfo_t &info, NativeThreadLinux &thread)
Status SetBreakpoint(lldb::addr_t addr, uint32_t size, bool hardware) override
llvm::Expected< TraceSupportedResponse > TraceSupported() override
Get the processor tracing type supported for this process.
void MonitorWatchpoint(NativeThreadLinux &thread, uint32_t wp_index)
bool TryHandleWaitStatus(lldb::pid_t pid, WaitStatus status)
llvm::Error TraceStop(const TraceStopRequest &request) override
Stop tracing a live process or its threads.
Status Resume(const ResumeActionList &resume_actions) override
llvm::Expected< llvm::json::Value > TraceGetState(llvm::StringRef type) override
Get the current tracing state of the process and its threads.
Status RemoveBreakpoint(lldb::addr_t addr, bool hardware=false) override
NativeProcessLinux(::pid_t pid, int terminal_fd, NativeDelegate &delegate, const ArchSpec &arch, Manager &manager, llvm::ArrayRef<::pid_t > tids)
Status ReadMemory(const ProcessAddress &addr, void *buf, size_t size, size_t &bytes_read) override
Plugins without address spaces should error on a non-default one.
Status NotifyTracersOfThreadDestroyed(lldb::tid_t tid)
Stop tracing threads upon a destroy event.
void NotifyTracersProcessDidStop() override
Notify tracers that the target process just stopped.
static Status SetDefaultPtraceOpts(const lldb::pid_t)
void MonitorSignal(const siginfo_t &info, NativeThreadLinux &thread)
Status GetSignalInfo(lldb::tid_t tid, void *siginfo) const
Writes a siginfo_t structure corresponding to the given thread ID to the memory region pointed to by ...
Status WriteMemoryTags(int32_t type, lldb::addr_t addr, size_t len, const std::vector< uint8_t > &tags) override
Status ReadMemoryTags(int32_t type, lldb::addr_t addr, size_t len, std::vector< uint8_t > &tags) override
Status ResumeThread(NativeThreadLinux &thread, lldb::StateType state, int signo)
Status GetMemoryRegionInfo(lldb::addr_t load_addr, MemoryRegionInfo &range_info) override
NativeThreadLinux & AddThread(lldb::tid_t thread_id, bool resume)
Create a new thread.
static llvm::Expected< std::vector<::pid_t > > Attach(::pid_t pid)
llvm::Expected< uint64_t > Syscall(llvm::ArrayRef< uint64_t > args)
Status Signal(int signo) override
Sends a process a UNIX signal signal.
Status GetLoadedModuleFileSpec(const char *module_path, FileSpec &file_spec) override
void MonitorCallback(NativeThreadLinux &thread, WaitStatus status)
static Status PtraceWrapper(int req, lldb::pid_t pid, void *addr=nullptr, void *data=nullptr, size_t data_size=0, long *result=nullptr)
}
virtual llvm::Expected< MemoryTaggingDetails > GetMemoryTaggingDetails(int32_t type)
Return architecture specific data needed to use memory tags, if they are supported.
virtual std::optional< MmapData > GetMmapData()
Return the architecture-specific data needed to make mmap syscalls, if they are supported.
static llvm::Expected< ArchSpec > DetermineArchitecture(lldb::tid_t tid)
virtual std::optional< SyscallData > GetSyscallData()
Return architecture-specific data needed to make inferior syscalls, if they are supported.
NativeRegisterContextLinux & GetRegisterContext() override
void SetStoppedByFork(bool is_vfork, lldb::pid_t child_pid)
#define LLDB_INVALID_SIGNAL_NUMBER
#define LLDB_INVALID_THREAD_ID
#define LLDB_INVALID_INDEX32
#define UNUSED_IF_ASSERT_DISABLED(x)
#define LLDB_INVALID_ADDRESS
#define LLDB_INVALID_PROCESS_ID
llvm::Expected< int > GetPtraceScope()
Definition Procfs.cpp:74
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:338
std::optional< lldb::pid_t > getPIDForTID(lldb::pid_t tid)
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getProcFile(::pid_t pid, ::pid_t tid, const llvm::Twine &file)
bool StateIsStoppedState(lldb::StateType state, bool must_exist)
Check if a state represents a state where the process or thread is stopped.
Definition State.cpp:89
bool StateIsRunningState(lldb::StateType state)
Check if a state represents a state where the process or thread is running.
Definition State.cpp:68
const char * StateAsCString(lldb::StateType state)
Converts a StateType to a C string.
Definition State.cpp:14
MainLoopPosix MainLoop
Definition MainLoop.h:20
std::function< bool(llvm::Expected< MemoryRegionInfo >)> LinuxMapCallback
void ParseLinuxMapRegions(llvm::StringRef linux_map, LinuxMapCallback const &callback)
void ParseLinuxSMapRegions(llvm::StringRef linux_smap, LinuxMapCallback const &callback)
StateType
Process and Thread States.
@ eStateUnloaded
Process is object is valid, but not currently loaded.
@ eStateConnected
Process is connected to remote debug services, but not launched or attached to anything yet.
@ eStateDetached
Process has been detached and can't be examined.
@ eStateStopped
Process or thread is stopped and can be examined.
@ eStateSuspended
Process or thread is in a suspended state as far as the debugger is concerned while other processes o...
@ eStateRunning
Process or thread is running and can't be examined.
@ eStateLaunching
Process is in the process of launching.
@ eStateAttaching
Process is currently trying to attach.
@ eStateExited
Process has exited and can't be examined.
@ eStateStepping
Process or thread is in the process of stepping and can not be examined.
@ eStateCrashed
Process or thread has crashed and can be examined.
@ eErrorTypePOSIX
POSIX error codes.
uint64_t pid_t
Definition lldb-types.h:84
std::shared_ptr< lldb_private::WritableDataBuffer > WritableDataBufferSP
uint64_t addr_t
Definition lldb-types.h:80
uint64_t tid_t
Definition lldb-types.h:85
bool Contains(BaseType r) const
Definition RangeMap.h:93
BaseType GetRangeBase() const
Definition RangeMap.h:45
void SetRangeEnd(BaseType end)
Definition RangeMap.h:80
SizeType GetByteSize() const
Definition RangeMap.h:87
void SetRangeBase(BaseType b)
Set the start value for the range, and keep the same size.
Definition RangeMap.h:48
void SetByteSize(SizeType s)
Definition RangeMap.h:89
lldb::StateType state
Definition Debug.h:23
jLLDBTraceGetBinaryData gdb-remote packet
std::string type
Tracing technology name, e.g. intel-pt, arm-coresight.
jLLDBTraceStop gdb-remote packet
std::string type
Tracing technology name, e.g. intel-pt, arm-coresight.
jLLDBTraceSupported gdb-remote packet
static WaitStatus Decode(int wstatus)
llvm::ArrayRef< uint32_t > Args
Registers used for syscall arguments.
#define SIGSTOP
#define O_NONBLOCK
#define SIGTRAP
#define SIGKILL