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