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