LLDB  mainline
NativeProcessLinux.cpp
Go to the documentation of this file.
1 //===-- NativeProcessLinux.cpp -------------------------------- -*- C++ -*-===//
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 <errno.h>
12 #include <stdint.h>
13 #include <string.h>
14 #include <unistd.h>
15 
16 #include <fstream>
17 #include <mutex>
18 #include <sstream>
19 #include <string>
20 #include <unordered_map>
21 
23 #include "lldb/Core/ModuleSpec.h"
24 #include "lldb/Host/Host.h"
25 #include "lldb/Host/HostProcess.h"
30 #include "lldb/Host/linux/Ptrace.h"
31 #include "lldb/Host/linux/Uio.h"
33 #include "lldb/Symbol/ObjectFile.h"
34 #include "lldb/Target/Process.h"
35 #include "lldb/Target/Target.h"
38 #include "lldb/Utility/State.h"
39 #include "lldb/Utility/Status.h"
41 #include "llvm/Support/Errno.h"
42 #include "llvm/Support/FileSystem.h"
43 #include "llvm/Support/Threading.h"
44 
45 #include "NativeThreadLinux.h"
48 #include "Procfs.h"
49 
50 #include <linux/unistd.h>
51 #include <sys/socket.h>
52 #include <sys/syscall.h>
53 #include <sys/types.h>
54 #include <sys/user.h>
55 #include <sys/wait.h>
56 
57 // Support hardware breakpoints in case it has not been defined
58 #ifndef TRAP_HWBKPT
59 #define TRAP_HWBKPT 4
60 #endif
61 
62 using namespace lldb;
63 using namespace lldb_private;
64 using namespace lldb_private::process_linux;
65 using namespace llvm;
66 
67 // Private bits we only need internally.
68 
69 static bool ProcessVmReadvSupported() {
70  static bool is_supported;
71  static llvm::once_flag flag;
72 
73  llvm::call_once(flag, [] {
75 
76  uint32_t source = 0x47424742;
77  uint32_t dest = 0;
78 
79  struct iovec local, remote;
80  remote.iov_base = &source;
81  local.iov_base = &dest;
82  remote.iov_len = local.iov_len = sizeof source;
83 
84  // We shall try if cross-process-memory reads work by attempting to read a
85  // value from our own process.
86  ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
87  is_supported = (res == sizeof(source) && source == dest);
88  if (is_supported)
89  LLDB_LOG(log,
90  "Detected kernel support for process_vm_readv syscall. "
91  "Fast memory reads enabled.");
92  else
93  LLDB_LOG(log,
94  "syscall process_vm_readv failed (error: {0}). Fast memory "
95  "reads disabled.",
96  llvm::sys::StrError());
97  });
98 
99  return is_supported;
100 }
101 
102 namespace {
103 void MaybeLogLaunchInfo(const ProcessLaunchInfo &info) {
105  if (!log)
106  return;
107 
108  if (const FileAction *action = info.GetFileActionForFD(STDIN_FILENO))
109  LLDB_LOG(log, "setting STDIN to '{0}'", action->GetFileSpec());
110  else
111  LLDB_LOG(log, "leaving STDIN as is");
112 
113  if (const FileAction *action = info.GetFileActionForFD(STDOUT_FILENO))
114  LLDB_LOG(log, "setting STDOUT to '{0}'", action->GetFileSpec());
115  else
116  LLDB_LOG(log, "leaving STDOUT as is");
117 
118  if (const FileAction *action = info.GetFileActionForFD(STDERR_FILENO))
119  LLDB_LOG(log, "setting STDERR to '{0}'", action->GetFileSpec());
120  else
121  LLDB_LOG(log, "leaving STDERR as is");
122 
123  int i = 0;
124  for (const char **args = info.GetArguments().GetConstArgumentVector(); *args;
125  ++args, ++i)
126  LLDB_LOG(log, "arg {0}: '{1}'", i, *args);
127 }
128 
129 void DisplayBytes(StreamString &s, void *bytes, uint32_t count) {
130  uint8_t *ptr = (uint8_t *)bytes;
131  const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
132  for (uint32_t i = 0; i < loop_count; i++) {
133  s.Printf("[%x]", *ptr);
134  ptr++;
135  }
136 }
137 
138 void PtraceDisplayBytes(int &req, void *data, size_t data_size) {
140  if (!log)
141  return;
142  StreamString buf;
143 
144  switch (req) {
145  case PTRACE_POKETEXT: {
146  DisplayBytes(buf, &data, 8);
147  LLDB_LOGV(log, "PTRACE_POKETEXT {0}", buf.GetData());
148  break;
149  }
150  case PTRACE_POKEDATA: {
151  DisplayBytes(buf, &data, 8);
152  LLDB_LOGV(log, "PTRACE_POKEDATA {0}", buf.GetData());
153  break;
154  }
155  case PTRACE_POKEUSER: {
156  DisplayBytes(buf, &data, 8);
157  LLDB_LOGV(log, "PTRACE_POKEUSER {0}", buf.GetData());
158  break;
159  }
160  case PTRACE_SETREGS: {
161  DisplayBytes(buf, data, data_size);
162  LLDB_LOGV(log, "PTRACE_SETREGS {0}", buf.GetData());
163  break;
164  }
165  case PTRACE_SETFPREGS: {
166  DisplayBytes(buf, data, data_size);
167  LLDB_LOGV(log, "PTRACE_SETFPREGS {0}", buf.GetData());
168  break;
169  }
170  case PTRACE_SETSIGINFO: {
171  DisplayBytes(buf, data, sizeof(siginfo_t));
172  LLDB_LOGV(log, "PTRACE_SETSIGINFO {0}", buf.GetData());
173  break;
174  }
175  case PTRACE_SETREGSET: {
176  // Extract iov_base from data, which is a pointer to the struct iovec
177  DisplayBytes(buf, *(void **)data, data_size);
178  LLDB_LOGV(log, "PTRACE_SETREGSET {0}", buf.GetData());
179  break;
180  }
181  default: {}
182  }
183 }
184 
185 static constexpr unsigned k_ptrace_word_size = sizeof(void *);
186 static_assert(sizeof(long) >= k_ptrace_word_size,
187  "Size of long must be larger than ptrace word size");
188 } // end of anonymous namespace
189 
190 // Simple helper function to ensure flags are enabled on the given file
191 // descriptor.
192 static Status EnsureFDFlags(int fd, int flags) {
193  Status error;
194 
195  int status = fcntl(fd, F_GETFL);
196  if (status == -1) {
197  error.SetErrorToErrno();
198  return error;
199  }
200 
201  if (fcntl(fd, F_SETFL, status | flags) == -1) {
202  error.SetErrorToErrno();
203  return error;
204  }
205 
206  return error;
207 }
208 
209 // Public Static Methods
210 
211 llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
212 NativeProcessLinux::Factory::Launch(ProcessLaunchInfo &launch_info,
213  NativeDelegate &native_delegate,
214  MainLoop &mainloop) const {
216 
217  MaybeLogLaunchInfo(launch_info);
218 
219  Status status;
221  .LaunchProcess(launch_info, status)
222  .GetProcessId();
223  LLDB_LOG(log, "pid = {0:x}", pid);
224  if (status.Fail()) {
225  LLDB_LOG(log, "failed to launch process: {0}", status);
226  return status.ToError();
227  }
228 
229  // Wait for the child process to trap on its call to execve.
230  int wstatus;
231  ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0);
232  assert(wpid == pid);
233  (void)wpid;
234  if (!WIFSTOPPED(wstatus)) {
235  LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}",
236  WaitStatus::Decode(wstatus));
237  return llvm::make_error<StringError>("Could not sync with inferior process",
238  llvm::inconvertibleErrorCode());
239  }
240  LLDB_LOG(log, "inferior started, now in stopped state");
241 
242  ProcessInstanceInfo Info;
243  if (!Host::GetProcessInfo(pid, Info)) {
244  return llvm::make_error<StringError>("Cannot get process architecture",
245  llvm::inconvertibleErrorCode());
246  }
247 
248  // Set the architecture to the exe architecture.
249  LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid,
251 
252  status = SetDefaultPtraceOpts(pid);
253  if (status.Fail()) {
254  LLDB_LOG(log, "failed to set default ptrace options: {0}", status);
255  return status.ToError();
256  }
257 
258  return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
259  pid, launch_info.GetPTY().ReleaseMasterFileDescriptor(), native_delegate,
260  Info.GetArchitecture(), mainloop, {pid}));
261 }
262 
263 llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
264 NativeProcessLinux::Factory::Attach(
266  MainLoop &mainloop) const {
268  LLDB_LOG(log, "pid = {0:x}", pid);
269 
270  // Retrieve the architecture for the running process.
271  ProcessInstanceInfo Info;
272  if (!Host::GetProcessInfo(pid, Info)) {
273  return llvm::make_error<StringError>("Cannot get process architecture",
274  llvm::inconvertibleErrorCode());
275  }
276 
277  auto tids_or = NativeProcessLinux::Attach(pid);
278  if (!tids_or)
279  return tids_or.takeError();
280 
281  return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
282  pid, -1, native_delegate, Info.GetArchitecture(), mainloop, *tids_or));
283 }
284 
285 // Public Instance Methods
286 
287 NativeProcessLinux::NativeProcessLinux(::pid_t pid, int terminal_fd,
288  NativeDelegate &delegate,
289  const ArchSpec &arch, MainLoop &mainloop,
290  llvm::ArrayRef<::pid_t> tids)
291  : NativeProcessProtocol(pid, terminal_fd, delegate), m_arch(arch) {
292  if (m_terminal_fd != -1) {
293  Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
294  assert(status.Success());
295  }
296 
297  Status status;
298  m_sigchld_handle = mainloop.RegisterSignal(
299  SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status);
300  assert(m_sigchld_handle && status.Success());
301 
302  for (const auto &tid : tids) {
303  NativeThreadLinux &thread = AddThread(tid);
304  thread.SetStoppedBySignal(SIGSTOP);
305  ThreadWasCreated(thread);
306  }
307 
308  // Let our process instance know the thread has stopped.
309  SetCurrentThreadID(tids[0]);
310  SetState(StateType::eStateStopped, false);
311 
312  // Proccess any signals we received before installing our handler
313  SigchldHandler();
314 }
315 
316 llvm::Expected<std::vector<::pid_t>> NativeProcessLinux::Attach(::pid_t pid) {
318 
319  Status status;
320  // Use a map to keep track of the threads which we have attached/need to
321  // attach.
322  Host::TidMap tids_to_attach;
323  while (Host::FindProcessThreads(pid, tids_to_attach)) {
324  for (Host::TidMap::iterator it = tids_to_attach.begin();
325  it != tids_to_attach.end();) {
326  if (it->second == false) {
327  lldb::tid_t tid = it->first;
328 
329  // Attach to the requested process.
330  // An attach will cause the thread to stop with a SIGSTOP.
331  if ((status = PtraceWrapper(PTRACE_ATTACH, tid)).Fail()) {
332  // No such thread. The thread may have exited. More error handling
333  // may be needed.
334  if (status.GetError() == ESRCH) {
335  it = tids_to_attach.erase(it);
336  continue;
337  }
338  return status.ToError();
339  }
340 
341  int wpid =
342  llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, nullptr, __WALL);
343  // Need to use __WALL otherwise we receive an error with errno=ECHLD At
344  // this point we should have a thread stopped if waitpid succeeds.
345  if (wpid < 0) {
346  // No such thread. The thread may have exited. More error handling
347  // may be needed.
348  if (errno == ESRCH) {
349  it = tids_to_attach.erase(it);
350  continue;
351  }
352  return llvm::errorCodeToError(
353  std::error_code(errno, std::generic_category()));
354  }
355 
356  if ((status = SetDefaultPtraceOpts(tid)).Fail())
357  return status.ToError();
358 
359  LLDB_LOG(log, "adding tid = {0}", tid);
360  it->second = true;
361  }
362 
363  // move the loop forward
364  ++it;
365  }
366  }
367 
368  size_t tid_count = tids_to_attach.size();
369  if (tid_count == 0)
370  return llvm::make_error<StringError>("No such process",
371  llvm::inconvertibleErrorCode());
372 
373  std::vector<::pid_t> tids;
374  tids.reserve(tid_count);
375  for (const auto &p : tids_to_attach)
376  tids.push_back(p.first);
377  return std::move(tids);
378 }
379 
380 Status NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid) {
381  long ptrace_opts = 0;
382 
383  // Have the child raise an event on exit. This is used to keep the child in
384  // limbo until it is destroyed.
385  ptrace_opts |= PTRACE_O_TRACEEXIT;
386 
387  // Have the tracer trace threads which spawn in the inferior process.
388  // TODO: if we want to support tracing the inferiors' child, add the
389  // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
390  ptrace_opts |= PTRACE_O_TRACECLONE;
391 
392  // Have the tracer notify us before execve returns (needed to disable legacy
393  // SIGTRAP generation)
394  ptrace_opts |= PTRACE_O_TRACEEXEC;
395 
396  return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void *)ptrace_opts);
397 }
398 
399 // Handles all waitpid events from the inferior process.
400 void NativeProcessLinux::MonitorCallback(lldb::pid_t pid, bool exited,
401  WaitStatus status) {
403 
404  // Certain activities differ based on whether the pid is the tid of the main
405  // thread.
406  const bool is_main_thread = (pid == GetID());
407 
408  // Handle when the thread exits.
409  if (exited) {
410  LLDB_LOG(log,
411  "got exit status({0}) , tid = {1} ({2} main thread), process "
412  "state = {3}",
413  status, pid, is_main_thread ? "is" : "is not", GetState());
414 
415  // This is a thread that exited. Ensure we're not tracking it anymore.
416  StopTrackingThread(pid);
417 
418  if (is_main_thread) {
419  // The main thread exited. We're done monitoring. Report to delegate.
420  SetExitStatus(status, true);
421 
422  // Notify delegate that our process has exited.
423  SetState(StateType::eStateExited, true);
424  }
425  return;
426  }
427 
428  siginfo_t info;
429  const auto info_err = GetSignalInfo(pid, &info);
430  auto thread_sp = GetThreadByID(pid);
431 
432  if (!thread_sp) {
433  // Normally, the only situation when we cannot find the thread is if we
434  // have just received a new thread notification. This is indicated by
435  // GetSignalInfo() returning si_code == SI_USER and si_pid == 0
436  LLDB_LOG(log, "received notification about an unknown tid {0}.", pid);
437 
438  if (info_err.Fail()) {
439  LLDB_LOG(log,
440  "(tid {0}) GetSignalInfo failed ({1}). "
441  "Ingoring this notification.",
442  pid, info_err);
443  return;
444  }
445 
446  LLDB_LOG(log, "tid {0}, si_code: {1}, si_pid: {2}", pid, info.si_code,
447  info.si_pid);
448 
449  NativeThreadLinux &thread = AddThread(pid);
450 
451  // Resume the newly created thread.
452  ResumeThread(thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
453  ThreadWasCreated(thread);
454  return;
455  }
456 
457  // Get details on the signal raised.
458  if (info_err.Success()) {
459  // We have retrieved the signal info. Dispatch appropriately.
460  if (info.si_signo == SIGTRAP)
461  MonitorSIGTRAP(info, *thread_sp);
462  else
463  MonitorSignal(info, *thread_sp, exited);
464  } else {
465  if (info_err.GetError() == EINVAL) {
466  // This is a group stop reception for this tid. We can reach here if we
467  // reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the tracee,
468  // triggering the group-stop mechanism. Normally receiving these would
469  // stop the process, pending a SIGCONT. Simulating this state in a
470  // debugger is hard and is generally not needed (one use case is
471  // debugging background task being managed by a shell). For general use,
472  // it is sufficient to stop the process in a signal-delivery stop which
473  // happens before the group stop. This done by MonitorSignal and works
474  // correctly for all signals.
475  LLDB_LOG(log,
476  "received a group stop for pid {0} tid {1}. Transparent "
477  "handling of group stops not supported, resuming the "
478  "thread.",
479  GetID(), pid);
480  ResumeThread(*thread_sp, thread_sp->GetState(),
482  } else {
483  // ptrace(GETSIGINFO) failed (but not due to group-stop).
484 
485  // A return value of ESRCH means the thread/process is no longer on the
486  // system, so it was killed somehow outside of our control. Either way,
487  // we can't do anything with it anymore.
488 
489  // Stop tracking the metadata for the thread since it's entirely off the
490  // system now.
491  const bool thread_found = StopTrackingThread(pid);
492 
493  LLDB_LOG(log,
494  "GetSignalInfo failed: {0}, tid = {1}, status = {2}, "
495  "status = {3}, main_thread = {4}, thread_found: {5}",
496  info_err, pid, status, status, is_main_thread, thread_found);
497 
498  if (is_main_thread) {
499  // Notify the delegate - our process is not available but appears to
500  // have been killed outside our control. Is eStateExited the right
501  // exit state in this case?
502  SetExitStatus(status, true);
503  SetState(StateType::eStateExited, true);
504  } else {
505  // This thread was pulled out from underneath us. Anything to do here?
506  // Do we want to do an all stop?
507  LLDB_LOG(log,
508  "pid {0} tid {1} non-main thread exit occurred, didn't "
509  "tell delegate anything since thread disappeared out "
510  "from underneath us",
511  GetID(), pid);
512  }
513  }
514  }
515 }
516 
517 void NativeProcessLinux::WaitForNewThread(::pid_t tid) {
519 
520  if (GetThreadByID(tid)) {
521  // We are already tracking the thread - we got the event on the new thread
522  // (see MonitorSignal) before this one. We are done.
523  return;
524  }
525 
526  // The thread is not tracked yet, let's wait for it to appear.
527  int status = -1;
528  LLDB_LOG(log,
529  "received thread creation event for tid {0}. tid not tracked "
530  "yet, waiting for thread to appear...",
531  tid);
532  ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, &status, __WALL);
533  // Since we are waiting on a specific tid, this must be the creation event.
534  // But let's do some checks just in case.
535  if (wait_pid != tid) {
536  LLDB_LOG(log,
537  "waiting for tid {0} failed. Assuming the thread has "
538  "disappeared in the meantime",
539  tid);
540  // The only way I know of this could happen is if the whole process was
541  // SIGKILLed in the mean time. In any case, we can't do anything about that
542  // now.
543  return;
544  }
545  if (WIFEXITED(status)) {
546  LLDB_LOG(log,
547  "waiting for tid {0} returned an 'exited' event. Not "
548  "tracking the thread.",
549  tid);
550  // Also a very improbable event.
551  return;
552  }
553 
554  LLDB_LOG(log, "pid = {0}: tracking new thread tid {1}", GetID(), tid);
555  NativeThreadLinux &new_thread = AddThread(tid);
556 
557  ResumeThread(new_thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
558  ThreadWasCreated(new_thread);
559 }
560 
561 void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info,
562  NativeThreadLinux &thread) {
564  const bool is_main_thread = (thread.GetID() == GetID());
565 
566  assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
567 
568  switch (info.si_code) {
569  // TODO: these two cases are required if we want to support tracing of the
570  // inferiors' children. We'd need this to debug a monitor. case (SIGTRAP |
571  // (PTRACE_EVENT_FORK << 8)): case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
572 
573  case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): {
574  // This is the notification on the parent thread which informs us of new
575  // thread creation. We don't want to do anything with the parent thread so
576  // we just resume it. In case we want to implement "break on thread
577  // creation" functionality, we would need to stop here.
578 
579  unsigned long event_message = 0;
580  if (GetEventMessage(thread.GetID(), &event_message).Fail()) {
581  LLDB_LOG(log,
582  "pid {0} received thread creation event but "
583  "GetEventMessage failed so we don't know the new tid",
584  thread.GetID());
585  } else
586  WaitForNewThread(event_message);
587 
588  ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
589  break;
590  }
591 
592  case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): {
593  LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP);
594 
595  // Exec clears any pending notifications.
596  m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
597 
598  // Remove all but the main thread here. Linux fork creates a new process
599  // which only copies the main thread.
600  LLDB_LOG(log, "exec received, stop tracking all but main thread");
601 
602  for (auto i = m_threads.begin(); i != m_threads.end();) {
603  if ((*i)->GetID() == GetID())
604  i = m_threads.erase(i);
605  else
606  ++i;
607  }
608  assert(m_threads.size() == 1);
609  auto *main_thread = static_cast<NativeThreadLinux *>(m_threads[0].get());
610 
611  SetCurrentThreadID(main_thread->GetID());
612  main_thread->SetStoppedByExec();
613 
614  // Tell coordinator about about the "new" (since exec) stopped main thread.
615  ThreadWasCreated(*main_thread);
616 
617  // Let our delegate know we have just exec'd.
618  NotifyDidExec();
619 
620  // Let the process know we're stopped.
621  StopRunningThreads(main_thread->GetID());
622 
623  break;
624  }
625 
626  case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): {
627  // The inferior process or one of its threads is about to exit. We don't
628  // want to do anything with the thread so we just resume it. In case we
629  // want to implement "break on thread exit" functionality, we would need to
630  // stop here.
631 
632  unsigned long data = 0;
633  if (GetEventMessage(thread.GetID(), &data).Fail())
634  data = -1;
635 
636  LLDB_LOG(log,
637  "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
638  "WIFSIGNALED={2}, pid = {3}, main_thread = {4}",
639  data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(),
640  is_main_thread);
641 
642 
643  StateType state = thread.GetState();
644  if (!StateIsRunningState(state)) {
645  // Due to a kernel bug, we may sometimes get this stop after the inferior
646  // gets a SIGKILL. This confuses our state tracking logic in
647  // ResumeThread(), since normally, we should not be receiving any ptrace
648  // events while the inferior is stopped. This makes sure that the
649  // inferior is resumed and exits normally.
650  state = eStateRunning;
651  }
652  ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
653 
654  break;
655  }
656 
657  case 0:
658  case TRAP_TRACE: // We receive this on single stepping.
659  case TRAP_HWBKPT: // We receive this on watchpoint hit
660  {
661  // If a watchpoint was hit, report it
662  uint32_t wp_index;
664  wp_index, (uintptr_t)info.si_addr);
665  if (error.Fail())
666  LLDB_LOG(log,
667  "received error while checking for watchpoint hits, pid = "
668  "{0}, error = {1}",
669  thread.GetID(), error);
670  if (wp_index != LLDB_INVALID_INDEX32) {
671  MonitorWatchpoint(thread, wp_index);
672  break;
673  }
674 
675  // If a breakpoint was hit, report it
676  uint32_t bp_index;
678  bp_index, (uintptr_t)info.si_addr);
679  if (error.Fail())
680  LLDB_LOG(log, "received error while checking for hardware "
681  "breakpoint hits, pid = {0}, error = {1}",
682  thread.GetID(), error);
683  if (bp_index != LLDB_INVALID_INDEX32) {
684  MonitorBreakpoint(thread);
685  break;
686  }
687 
688  // Otherwise, report step over
689  MonitorTrace(thread);
690  break;
691  }
692 
693  case SI_KERNEL:
694 #if defined __mips__
695  // For mips there is no special signal for watchpoint So we check for
696  // watchpoint in kernel trap
697  {
698  // If a watchpoint was hit, report it
699  uint32_t wp_index;
701  wp_index, LLDB_INVALID_ADDRESS);
702  if (error.Fail())
703  LLDB_LOG(log,
704  "received error while checking for watchpoint hits, pid = "
705  "{0}, error = {1}",
706  thread.GetID(), error);
707  if (wp_index != LLDB_INVALID_INDEX32) {
708  MonitorWatchpoint(thread, wp_index);
709  break;
710  }
711  }
712 // NO BREAK
713 #endif
714  case TRAP_BRKPT:
715  MonitorBreakpoint(thread);
716  break;
717 
718  case SIGTRAP:
719  case (SIGTRAP | 0x80):
720  LLDB_LOG(
721  log,
722  "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",
723  info.si_code, GetID(), thread.GetID());
724 
725  // Ignore these signals until we know more about them.
726  ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
727  break;
728 
729  default:
730  LLDB_LOG(log, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}",
731  info.si_code, GetID(), thread.GetID());
732  MonitorSignal(info, thread, false);
733  break;
734  }
735 }
736 
737 void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) {
739  LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID());
740 
741  // This thread is currently stopped.
742  thread.SetStoppedByTrace();
743 
744  StopRunningThreads(thread.GetID());
745 }
746 
747 void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) {
748  Log *log(
750  LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID());
751 
752  // Mark the thread as stopped at breakpoint.
753  thread.SetStoppedByBreakpoint();
754  FixupBreakpointPCAsNeeded(thread);
755 
756  if (m_threads_stepping_with_breakpoint.find(thread.GetID()) !=
757  m_threads_stepping_with_breakpoint.end())
758  thread.SetStoppedByTrace();
759 
760  StopRunningThreads(thread.GetID());
761 }
762 
763 void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread,
764  uint32_t wp_index) {
765  Log *log(
767  LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}",
768  thread.GetID(), wp_index);
769 
770  // Mark the thread as stopped at watchpoint. The address is at
771  // (lldb::addr_t)info->si_addr if we need it.
772  thread.SetStoppedByWatchpoint(wp_index);
773 
774  // We need to tell all other running threads before we notify the delegate
775  // about this stop.
776  StopRunningThreads(thread.GetID());
777 }
778 
779 void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
780  NativeThreadLinux &thread, bool exited) {
781  const int signo = info.si_signo;
782  const bool is_from_llgs = info.si_pid == getpid();
783 
785 
786  // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
787  // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a kill(2)
788  // or raise(3). Similarly for tgkill(2) on Linux.
789  //
790  // IOW, user generated signals never generate what we consider to be a
791  // "crash".
792  //
793  // Similarly, ACK signals generated by this monitor.
794 
795  // Handle the signal.
796  LLDB_LOG(log,
797  "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
798  "waitpid pid = {4})",
799  Host::GetSignalAsCString(signo), signo, info.si_code,
800  thread.GetID());
801 
802  // Check for thread stop notification.
803  if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) {
804  // This is a tgkill()-based stop.
805  LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID());
806 
807  // Check that we're not already marked with a stop reason. Note this thread
808  // really shouldn't already be marked as stopped - if we were, that would
809  // imply that the kernel signaled us with the thread stopping which we
810  // handled and marked as stopped, and that, without an intervening resume,
811  // we received another stop. It is more likely that we are missing the
812  // marking of a run state somewhere if we find that the thread was marked
813  // as stopped.
814  const StateType thread_state = thread.GetState();
815  if (!StateIsStoppedState(thread_state, false)) {
816  // An inferior thread has stopped because of a SIGSTOP we have sent it.
817  // Generally, these are not important stops and we don't want to report
818  // them as they are just used to stop other threads when one thread (the
819  // one with the *real* stop reason) hits a breakpoint (watchpoint,
820  // etc...). However, in the case of an asynchronous Interrupt(), this
821  // *is* the real stop reason, so we leave the signal intact if this is
822  // the thread that was chosen as the triggering thread.
823  if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
824  if (m_pending_notification_tid == thread.GetID())
825  thread.SetStoppedBySignal(SIGSTOP, &info);
826  else
827  thread.SetStoppedWithNoReason();
828 
829  SetCurrentThreadID(thread.GetID());
830  SignalIfAllThreadsStopped();
831  } else {
832  // We can end up here if stop was initiated by LLGS but by this time a
833  // thread stop has occurred - maybe initiated by another event.
834  Status error = ResumeThread(thread, thread.GetState(), 0);
835  if (error.Fail())
836  LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(),
837  error);
838  }
839  } else {
840  LLDB_LOG(log,
841  "pid {0} tid {1}, thread was already marked as a stopped "
842  "state (state={2}), leaving stop signal as is",
843  GetID(), thread.GetID(), thread_state);
844  SignalIfAllThreadsStopped();
845  }
846 
847  // Done handling.
848  return;
849  }
850 
851  // Check if debugger should stop at this signal or just ignore it and resume
852  // the inferior.
853  if (m_signals_to_ignore.find(signo) != m_signals_to_ignore.end()) {
854  ResumeThread(thread, thread.GetState(), signo);
855  return;
856  }
857 
858  // This thread is stopped.
859  LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo));
860  thread.SetStoppedBySignal(signo, &info);
861 
862  // Send a stop to the debugger after we get all other threads to stop.
863  StopRunningThreads(thread.GetID());
864 }
865 
866 namespace {
867 
868 struct EmulatorBaton {
869  NativeProcessLinux &m_process;
870  NativeRegisterContext &m_reg_context;
871 
872  // eRegisterKindDWARF -> RegsiterValue
873  std::unordered_map<uint32_t, RegisterValue> m_register_values;
874 
875  EmulatorBaton(NativeProcessLinux &process, NativeRegisterContext &reg_context)
876  : m_process(process), m_reg_context(reg_context) {}
877 };
878 
879 } // anonymous namespace
880 
881 static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
882  const EmulateInstruction::Context &context,
883  lldb::addr_t addr, void *dst, size_t length) {
884  EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
885 
886  size_t bytes_read;
887  emulator_baton->m_process.ReadMemory(addr, dst, length, bytes_read);
888  return bytes_read;
889 }
890 
891 static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
892  const RegisterInfo *reg_info,
893  RegisterValue &reg_value) {
894  EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
895 
896  auto it = emulator_baton->m_register_values.find(
897  reg_info->kinds[eRegisterKindDWARF]);
898  if (it != emulator_baton->m_register_values.end()) {
899  reg_value = it->second;
900  return true;
901  }
902 
903  // The emulator only fill in the dwarf regsiter numbers (and in some case the
904  // generic register numbers). Get the full register info from the register
905  // context based on the dwarf register numbers.
906  const RegisterInfo *full_reg_info =
907  emulator_baton->m_reg_context.GetRegisterInfo(
908  eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
909 
910  Status error =
911  emulator_baton->m_reg_context.ReadRegister(full_reg_info, reg_value);
912  if (error.Success())
913  return true;
914 
915  return false;
916 }
917 
918 static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
919  const EmulateInstruction::Context &context,
920  const RegisterInfo *reg_info,
921  const RegisterValue &reg_value) {
922  EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
923  emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
924  reg_value;
925  return true;
926 }
927 
928 static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
929  const EmulateInstruction::Context &context,
930  lldb::addr_t addr, const void *dst,
931  size_t length) {
932  return length;
933 }
934 
935 static lldb::addr_t ReadFlags(NativeRegisterContext &regsiter_context) {
936  const RegisterInfo *flags_info = regsiter_context.GetRegisterInfo(
938  return regsiter_context.ReadRegisterAsUnsigned(flags_info,
940 }
941 
942 Status
943 NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadLinux &thread) {
944  Status error;
945  NativeRegisterContext& register_context = thread.GetRegisterContext();
946 
947  std::unique_ptr<EmulateInstruction> emulator_up(
948  EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying,
949  nullptr));
950 
951  if (emulator_up == nullptr)
952  return Status("Instruction emulator not found!");
953 
954  EmulatorBaton baton(*this, register_context);
955  emulator_up->SetBaton(&baton);
956  emulator_up->SetReadMemCallback(&ReadMemoryCallback);
957  emulator_up->SetReadRegCallback(&ReadRegisterCallback);
958  emulator_up->SetWriteMemCallback(&WriteMemoryCallback);
959  emulator_up->SetWriteRegCallback(&WriteRegisterCallback);
960 
961  if (!emulator_up->ReadInstruction())
962  return Status("Read instruction failed!");
963 
964  bool emulation_result =
965  emulator_up->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
966 
967  const RegisterInfo *reg_info_pc = register_context.GetRegisterInfo(
969  const RegisterInfo *reg_info_flags = register_context.GetRegisterInfo(
971 
972  auto pc_it =
973  baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
974  auto flags_it =
975  baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
976 
977  lldb::addr_t next_pc;
978  lldb::addr_t next_flags;
979  if (emulation_result) {
980  assert(pc_it != baton.m_register_values.end() &&
981  "Emulation was successfull but PC wasn't updated");
982  next_pc = pc_it->second.GetAsUInt64();
983 
984  if (flags_it != baton.m_register_values.end())
985  next_flags = flags_it->second.GetAsUInt64();
986  else
987  next_flags = ReadFlags(register_context);
988  } else if (pc_it == baton.m_register_values.end()) {
989  // Emulate instruction failed and it haven't changed PC. Advance PC with
990  // the size of the current opcode because the emulation of all
991  // PC modifying instruction should be successful. The failure most
992  // likely caused by a not supported instruction which don't modify PC.
993  next_pc = register_context.GetPC() + emulator_up->GetOpcode().GetByteSize();
994  next_flags = ReadFlags(register_context);
995  } else {
996  // The instruction emulation failed after it modified the PC. It is an
997  // unknown error where we can't continue because the next instruction is
998  // modifying the PC but we don't know how.
999  return Status("Instruction emulation failed unexpectedly.");
1000  }
1001 
1002  if (m_arch.GetMachine() == llvm::Triple::arm) {
1003  if (next_flags & 0x20) {
1004  // Thumb mode
1005  error = SetSoftwareBreakpoint(next_pc, 2);
1006  } else {
1007  // Arm mode
1008  error = SetSoftwareBreakpoint(next_pc, 4);
1009  }
1010  } else if (m_arch.GetMachine() == llvm::Triple::mips64 ||
1011  m_arch.GetMachine() == llvm::Triple::mips64el ||
1012  m_arch.GetMachine() == llvm::Triple::mips ||
1013  m_arch.GetMachine() == llvm::Triple::mipsel ||
1014  m_arch.GetMachine() == llvm::Triple::ppc64le)
1015  error = SetSoftwareBreakpoint(next_pc, 4);
1016  else {
1017  // No size hint is given for the next breakpoint
1018  error = SetSoftwareBreakpoint(next_pc, 0);
1019  }
1020 
1021  // If setting the breakpoint fails because next_pc is out of the address
1022  // space, ignore it and let the debugee segfault.
1023  if (error.GetError() == EIO || error.GetError() == EFAULT) {
1024  return Status();
1025  } else if (error.Fail())
1026  return error;
1027 
1028  m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
1029 
1030  return Status();
1031 }
1032 
1033 bool NativeProcessLinux::SupportHardwareSingleStepping() const {
1034  if (m_arch.GetMachine() == llvm::Triple::arm ||
1035  m_arch.GetMachine() == llvm::Triple::mips64 ||
1036  m_arch.GetMachine() == llvm::Triple::mips64el ||
1037  m_arch.GetMachine() == llvm::Triple::mips ||
1038  m_arch.GetMachine() == llvm::Triple::mipsel)
1039  return false;
1040  return true;
1041 }
1042 
1043 Status NativeProcessLinux::Resume(const ResumeActionList &resume_actions) {
1045  LLDB_LOG(log, "pid {0}", GetID());
1046 
1047  bool software_single_step = !SupportHardwareSingleStepping();
1048 
1049  if (software_single_step) {
1050  for (const auto &thread : m_threads) {
1051  assert(thread && "thread list should not contain NULL threads");
1052 
1053  const ResumeAction *const action =
1054  resume_actions.GetActionForThread(thread->GetID(), true);
1055  if (action == nullptr)
1056  continue;
1057 
1058  if (action->state == eStateStepping) {
1059  Status error = SetupSoftwareSingleStepping(
1060  static_cast<NativeThreadLinux &>(*thread));
1061  if (error.Fail())
1062  return error;
1063  }
1064  }
1065  }
1066 
1067  for (const auto &thread : m_threads) {
1068  assert(thread && "thread list should not contain NULL threads");
1069 
1070  const ResumeAction *const action =
1071  resume_actions.GetActionForThread(thread->GetID(), true);
1072 
1073  if (action == nullptr) {
1074  LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
1075  thread->GetID());
1076  continue;
1077  }
1078 
1079  LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}",
1080  action->state, GetID(), thread->GetID());
1081 
1082  switch (action->state) {
1083  case eStateRunning:
1084  case eStateStepping: {
1085  // Run the thread, possibly feeding it the signal.
1086  const int signo = action->signal;
1087  ResumeThread(static_cast<NativeThreadLinux &>(*thread), action->state,
1088  signo);
1089  break;
1090  }
1091 
1092  case eStateSuspended:
1093  case eStateStopped:
1094  llvm_unreachable("Unexpected state");
1095 
1096  default:
1097  return Status("NativeProcessLinux::%s (): unexpected state %s specified "
1098  "for pid %" PRIu64 ", tid %" PRIu64,
1099  __FUNCTION__, StateAsCString(action->state), GetID(),
1100  thread->GetID());
1101  }
1102  }
1103 
1104  return Status();
1105 }
1106 
1107 Status NativeProcessLinux::Halt() {
1108  Status error;
1109 
1110  if (kill(GetID(), SIGSTOP) != 0)
1111  error.SetErrorToErrno();
1112 
1113  return error;
1114 }
1115 
1116 Status NativeProcessLinux::Detach() {
1117  Status error;
1118 
1119  // Stop monitoring the inferior.
1120  m_sigchld_handle.reset();
1121 
1122  // Tell ptrace to detach from the process.
1123  if (GetID() == LLDB_INVALID_PROCESS_ID)
1124  return error;
1125 
1126  for (const auto &thread : m_threads) {
1127  Status e = Detach(thread->GetID());
1128  if (e.Fail())
1129  error =
1130  e; // Save the error, but still attempt to detach from other threads.
1131  }
1132 
1133  m_processor_trace_monitor.clear();
1134  m_pt_proces_trace_id = LLDB_INVALID_UID;
1135 
1136  return error;
1137 }
1138 
1139 Status NativeProcessLinux::Signal(int signo) {
1140  Status error;
1141 
1143  LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo,
1144  Host::GetSignalAsCString(signo), GetID());
1145 
1146  if (kill(GetID(), signo))
1147  error.SetErrorToErrno();
1148 
1149  return error;
1150 }
1151 
1152 Status NativeProcessLinux::Interrupt() {
1153  // Pick a running thread (or if none, a not-dead stopped thread) as the
1154  // chosen thread that will be the stop-reason thread.
1156 
1157  NativeThreadProtocol *running_thread = nullptr;
1158  NativeThreadProtocol *stopped_thread = nullptr;
1159 
1160  LLDB_LOG(log, "selecting running thread for interrupt target");
1161  for (const auto &thread : m_threads) {
1162  // If we have a running or stepping thread, we'll call that the target of
1163  // the interrupt.
1164  const auto thread_state = thread->GetState();
1165  if (thread_state == eStateRunning || thread_state == eStateStepping) {
1166  running_thread = thread.get();
1167  break;
1168  } else if (!stopped_thread && StateIsStoppedState(thread_state, true)) {
1169  // Remember the first non-dead stopped thread. We'll use that as a
1170  // backup if there are no running threads.
1171  stopped_thread = thread.get();
1172  }
1173  }
1174 
1175  if (!running_thread && !stopped_thread) {
1176  Status error("found no running/stepping or live stopped threads as target "
1177  "for interrupt");
1178  LLDB_LOG(log, "skipping due to error: {0}", error);
1179 
1180  return error;
1181  }
1182 
1183  NativeThreadProtocol *deferred_signal_thread =
1184  running_thread ? running_thread : stopped_thread;
1185 
1186  LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(),
1187  running_thread ? "running" : "stopped",
1188  deferred_signal_thread->GetID());
1189 
1190  StopRunningThreads(deferred_signal_thread->GetID());
1191 
1192  return Status();
1193 }
1194 
1195 Status NativeProcessLinux::Kill() {
1197  LLDB_LOG(log, "pid {0}", GetID());
1198 
1199  Status error;
1200 
1201  switch (m_state) {
1207  // Nothing to do - the process is already dead.
1208  LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
1209  m_state);
1210  return error;
1211 
1219  // We can try to kill a process in these states.
1220  break;
1221  }
1222 
1223  if (kill(GetID(), SIGKILL) != 0) {
1224  error.SetErrorToErrno();
1225  return error;
1226  }
1227 
1228  return error;
1229 }
1230 
1231 Status NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr,
1232  MemoryRegionInfo &range_info) {
1233  // FIXME review that the final memory region returned extends to the end of
1234  // the virtual address space,
1235  // with no perms if it is not mapped.
1236 
1237  // Use an approach that reads memory regions from /proc/{pid}/maps. Assume
1238  // proc maps entries are in ascending order.
1239  // FIXME assert if we find differently.
1240 
1241  if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
1242  // We're done.
1243  return Status("unsupported");
1244  }
1245 
1246  Status error = PopulateMemoryRegionCache();
1247  if (error.Fail()) {
1248  return error;
1249  }
1250 
1251  lldb::addr_t prev_base_address = 0;
1252 
1253  // FIXME start by finding the last region that is <= target address using
1254  // binary search. Data is sorted.
1255  // There can be a ton of regions on pthreads apps with lots of threads.
1256  for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1257  ++it) {
1258  MemoryRegionInfo &proc_entry_info = it->first;
1259 
1260  // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1261  assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
1262  "descending /proc/pid/maps entries detected, unexpected");
1263  prev_base_address = proc_entry_info.GetRange().GetRangeBase();
1264  UNUSED_IF_ASSERT_DISABLED(prev_base_address);
1265 
1266  // If the target address comes before this entry, indicate distance to next
1267  // region.
1268  if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1269  range_info.GetRange().SetRangeBase(load_addr);
1270  range_info.GetRange().SetByteSize(
1271  proc_entry_info.GetRange().GetRangeBase() - load_addr);
1272  range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1273  range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1274  range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1275  range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1276 
1277  return error;
1278  } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1279  // The target address is within the memory region we're processing here.
1280  range_info = proc_entry_info;
1281  return error;
1282  }
1283 
1284  // The target memory address comes somewhere after the region we just
1285  // parsed.
1286  }
1287 
1288  // If we made it here, we didn't find an entry that contained the given
1289  // address. Return the load_addr as start and the amount of bytes betwwen
1290  // load address and the end of the memory as size.
1291  range_info.GetRange().SetRangeBase(load_addr);
1293  range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1294  range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1295  range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1296  range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1297  return error;
1298 }
1299 
1300 Status NativeProcessLinux::PopulateMemoryRegionCache() {
1302 
1303  // If our cache is empty, pull the latest. There should always be at least
1304  // one memory region if memory region handling is supported.
1305  if (!m_mem_region_cache.empty()) {
1306  LLDB_LOG(log, "reusing {0} cached memory region entries",
1307  m_mem_region_cache.size());
1308  return Status();
1309  }
1310 
1311  auto BufferOrError = getProcFile(GetID(), "maps");
1312  if (!BufferOrError) {
1313  m_supports_mem_region = LazyBool::eLazyBoolNo;
1314  return BufferOrError.getError();
1315  }
1316  Status Result;
1317  ParseLinuxMapRegions(BufferOrError.get()->getBuffer(),
1318  [&](const MemoryRegionInfo &Info, const Status &ST) {
1319  if (ST.Success()) {
1320  FileSpec file_spec(Info.GetName().GetCString());
1321  FileSystem::Instance().Resolve(file_spec);
1322  m_mem_region_cache.emplace_back(Info, file_spec);
1323  return true;
1324  } else {
1325  m_supports_mem_region = LazyBool::eLazyBoolNo;
1326  LLDB_LOG(log, "failed to parse proc maps: {0}", ST);
1327  Result = ST;
1328  return false;
1329  }
1330  });
1331  if (Result.Fail())
1332  return Result;
1333 
1334  if (m_mem_region_cache.empty()) {
1335  // No entries after attempting to read them. This shouldn't happen if
1336  // /proc/{pid}/maps is supported. Assume we don't support map entries via
1337  // procfs.
1338  m_supports_mem_region = LazyBool::eLazyBoolNo;
1339  LLDB_LOG(log,
1340  "failed to find any procfs maps entries, assuming no support "
1341  "for memory region metadata retrieval");
1342  return Status("not supported");
1343  }
1344 
1345  LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps",
1346  m_mem_region_cache.size(), GetID());
1347 
1348  // We support memory retrieval, remember that.
1349  m_supports_mem_region = LazyBool::eLazyBoolYes;
1350  return Status();
1351 }
1352 
1353 void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
1355  LLDB_LOG(log, "newBumpId={0}", newBumpId);
1356  LLDB_LOG(log, "clearing {0} entries from memory region cache",
1357  m_mem_region_cache.size());
1358  m_mem_region_cache.clear();
1359 }
1360 
1361 Status NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions,
1362  lldb::addr_t &addr) {
1363 // FIXME implementing this requires the equivalent of
1364 // InferiorCallPOSIX::InferiorCallMmap, which depends on functional ThreadPlans
1365 // working with Native*Protocol.
1366 #if 1
1367  return Status("not implemented yet");
1368 #else
1369  addr = LLDB_INVALID_ADDRESS;
1370 
1371  unsigned prot = 0;
1372  if (permissions & lldb::ePermissionsReadable)
1373  prot |= eMmapProtRead;
1374  if (permissions & lldb::ePermissionsWritable)
1375  prot |= eMmapProtWrite;
1376  if (permissions & lldb::ePermissionsExecutable)
1377  prot |= eMmapProtExec;
1378 
1379  // TODO implement this directly in NativeProcessLinux
1380  // (and lift to NativeProcessPOSIX if/when that class is refactored out).
1381  if (InferiorCallMmap(this, addr, 0, size, prot,
1382  eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
1383  m_addr_to_mmap_size[addr] = size;
1384  return Status();
1385  } else {
1386  addr = LLDB_INVALID_ADDRESS;
1387  return Status("unable to allocate %" PRIu64
1388  " bytes of memory with permissions %s",
1389  size, GetPermissionsAsCString(permissions));
1390  }
1391 #endif
1392 }
1393 
1394 Status NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {
1395  // FIXME see comments in AllocateMemory - required lower-level
1396  // bits not in place yet (ThreadPlans)
1397  return Status("not implemented");
1398 }
1399 
1400 lldb::addr_t NativeProcessLinux::GetSharedLibraryInfoAddress() {
1401  // punt on this for now
1402  return LLDB_INVALID_ADDRESS;
1403 }
1404 
1405 size_t NativeProcessLinux::UpdateThreads() {
1406  // The NativeProcessLinux monitoring threads are always up to date with
1407  // respect to thread state and they keep the thread list populated properly.
1408  // All this method needs to do is return the thread count.
1409  return m_threads.size();
1410 }
1411 
1412 Status NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,
1413  bool hardware) {
1414  if (hardware)
1415  return SetHardwareBreakpoint(addr, size);
1416  else
1417  return SetSoftwareBreakpoint(addr, size);
1418 }
1419 
1420 Status NativeProcessLinux::RemoveBreakpoint(lldb::addr_t addr, bool hardware) {
1421  if (hardware)
1422  return RemoveHardwareBreakpoint(addr);
1423  else
1424  return NativeProcessProtocol::RemoveBreakpoint(addr);
1425 }
1426 
1427 llvm::Expected<llvm::ArrayRef<uint8_t>>
1428 NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(size_t size_hint) {
1429  // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1430  // linux kernel does otherwise.
1431  static const uint8_t g_arm_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1432  static const uint8_t g_thumb_opcode[] = {0x01, 0xde};
1433 
1434  switch (GetArchitecture().GetMachine()) {
1435  case llvm::Triple::arm:
1436  switch (size_hint) {
1437  case 2:
1438  return llvm::makeArrayRef(g_thumb_opcode);
1439  case 4:
1440  return llvm::makeArrayRef(g_arm_opcode);
1441  default:
1442  return llvm::createStringError(llvm::inconvertibleErrorCode(),
1443  "Unrecognised trap opcode size hint!");
1444  }
1445  default:
1446  return NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_hint);
1447  }
1448 }
1449 
1450 Status NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
1451  size_t &bytes_read) {
1452  if (ProcessVmReadvSupported()) {
1453  // The process_vm_readv path is about 50 times faster than ptrace api. We
1454  // want to use this syscall if it is supported.
1455 
1456  const ::pid_t pid = GetID();
1457 
1458  struct iovec local_iov, remote_iov;
1459  local_iov.iov_base = buf;
1460  local_iov.iov_len = size;
1461  remote_iov.iov_base = reinterpret_cast<void *>(addr);
1462  remote_iov.iov_len = size;
1463 
1464  bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
1465  const bool success = bytes_read == size;
1466 
1468  LLDB_LOG(log,
1469  "using process_vm_readv to read {0} bytes from inferior "
1470  "address {1:x}: {2}",
1471  size, addr, success ? "Success" : llvm::sys::StrError(errno));
1472 
1473  if (success)
1474  return Status();
1475  // else the call failed for some reason, let's retry the read using ptrace
1476  // api.
1477  }
1478 
1479  unsigned char *dst = static_cast<unsigned char *>(buf);
1480  size_t remainder;
1481  long data;
1482 
1484  LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
1485 
1486  for (bytes_read = 0; bytes_read < size; bytes_read += remainder) {
1488  PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data);
1489  if (error.Fail())
1490  return error;
1491 
1492  remainder = size - bytes_read;
1493  remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
1494 
1495  // Copy the data into our buffer
1496  memcpy(dst, &data, remainder);
1497 
1498  LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
1499  addr += k_ptrace_word_size;
1500  dst += k_ptrace_word_size;
1501  }
1502  return Status();
1503 }
1504 
1505 Status NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,
1506  size_t size, size_t &bytes_written) {
1507  const unsigned char *src = static_cast<const unsigned char *>(buf);
1508  size_t remainder;
1509  Status error;
1510 
1512  LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
1513 
1514  for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
1515  remainder = size - bytes_written;
1516  remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
1517 
1518  if (remainder == k_ptrace_word_size) {
1519  unsigned long data = 0;
1520  memcpy(&data, src, k_ptrace_word_size);
1521 
1522  LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
1523  error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(),
1524  (void *)addr, (void *)data);
1525  if (error.Fail())
1526  return error;
1527  } else {
1528  unsigned char buff[8];
1529  size_t bytes_read;
1530  error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
1531  if (error.Fail())
1532  return error;
1533 
1534  memcpy(buff, src, remainder);
1535 
1536  size_t bytes_written_rec;
1537  error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
1538  if (error.Fail())
1539  return error;
1540 
1541  LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src,
1542  *(unsigned long *)buff);
1543  }
1544 
1545  addr += k_ptrace_word_size;
1546  src += k_ptrace_word_size;
1547  }
1548  return error;
1549 }
1550 
1551 Status NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) {
1552  return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
1553 }
1554 
1555 Status NativeProcessLinux::GetEventMessage(lldb::tid_t tid,
1556  unsigned long *message) {
1557  return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
1558 }
1559 
1560 Status NativeProcessLinux::Detach(lldb::tid_t tid) {
1561  if (tid == LLDB_INVALID_THREAD_ID)
1562  return Status();
1563 
1564  return PtraceWrapper(PTRACE_DETACH, tid);
1565 }
1566 
1567 bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {
1568  for (const auto &thread : m_threads) {
1569  assert(thread && "thread list should not contain NULL threads");
1570  if (thread->GetID() == thread_id) {
1571  // We have this thread.
1572  return true;
1573  }
1574  }
1575 
1576  // We don't have this thread.
1577  return false;
1578 }
1579 
1580 bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) {
1582  LLDB_LOG(log, "tid: {0})", thread_id);
1583 
1584  bool found = false;
1585  for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
1586  if (*it && ((*it)->GetID() == thread_id)) {
1587  m_threads.erase(it);
1588  found = true;
1589  break;
1590  }
1591  }
1592 
1593  if (found)
1594  StopTracingForThread(thread_id);
1595  SignalIfAllThreadsStopped();
1596  return found;
1597 }
1598 
1599 NativeThreadLinux &NativeProcessLinux::AddThread(lldb::tid_t thread_id) {
1601  LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
1602 
1603  assert(!HasThreadNoLock(thread_id) &&
1604  "attempted to add a thread by id that already exists");
1605 
1606  // If this is the first thread, save it as the current thread
1607  if (m_threads.empty())
1608  SetCurrentThreadID(thread_id);
1609 
1610  m_threads.push_back(llvm::make_unique<NativeThreadLinux>(*this, thread_id));
1611 
1612  if (m_pt_proces_trace_id != LLDB_INVALID_UID) {
1613  auto traceMonitor = ProcessorTraceMonitor::Create(
1614  GetID(), thread_id, m_pt_process_trace_config, true);
1615  if (traceMonitor) {
1616  m_pt_traced_thread_group.insert(thread_id);
1617  m_processor_trace_monitor.insert(
1618  std::make_pair(thread_id, std::move(*traceMonitor)));
1619  } else {
1620  LLDB_LOG(log, "failed to start trace on thread {0}", thread_id);
1621  Status error(traceMonitor.takeError());
1622  LLDB_LOG(log, "error {0}", error);
1623  }
1624  }
1625 
1626  return static_cast<NativeThreadLinux &>(*m_threads.back());
1627 }
1628 
1629 Status NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,
1630  FileSpec &file_spec) {
1631  Status error = PopulateMemoryRegionCache();
1632  if (error.Fail())
1633  return error;
1634 
1635  FileSpec module_file_spec(module_path);
1636  FileSystem::Instance().Resolve(module_file_spec);
1637 
1638  file_spec.Clear();
1639  for (const auto &it : m_mem_region_cache) {
1640  if (it.second.GetFilename() == module_file_spec.GetFilename()) {
1641  file_spec = it.second;
1642  return Status();
1643  }
1644  }
1645  return Status("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
1646  module_file_spec.GetFilename().AsCString(), GetID());
1647 }
1648 
1649 Status NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
1650  lldb::addr_t &load_addr) {
1651  load_addr = LLDB_INVALID_ADDRESS;
1652  Status error = PopulateMemoryRegionCache();
1653  if (error.Fail())
1654  return error;
1655 
1656  FileSpec file(file_name);
1657  for (const auto &it : m_mem_region_cache) {
1658  if (it.second == file) {
1659  load_addr = it.first.GetRange().GetRangeBase();
1660  return Status();
1661  }
1662  }
1663  return Status("No load address found for specified file.");
1664 }
1665 
1666 NativeThreadLinux *NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {
1667  return static_cast<NativeThreadLinux *>(
1668  NativeProcessProtocol::GetThreadByID(tid));
1669 }
1670 
1671 Status NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,
1672  lldb::StateType state, int signo) {
1674  LLDB_LOG(log, "tid: {0}", thread.GetID());
1675 
1676  // Before we do the resume below, first check if we have a pending stop
1677  // notification that is currently waiting for all threads to stop. This is
1678  // potentially a buggy situation since we're ostensibly waiting for threads
1679  // to stop before we send out the pending notification, and here we are
1680  // resuming one before we send out the pending stop notification.
1681  if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
1682  LLDB_LOG(log,
1683  "about to resume tid {0} per explicit request but we have a "
1684  "pending stop notification (tid {1}) that is actively "
1685  "waiting for this thread to stop. Valid sequence of events?",
1686  thread.GetID(), m_pending_notification_tid);
1687  }
1688 
1689  // Request a resume. We expect this to be synchronous and the system to
1690  // reflect it is running after this completes.
1691  switch (state) {
1692  case eStateRunning: {
1693  const auto resume_result = thread.Resume(signo);
1694  if (resume_result.Success())
1695  SetState(eStateRunning, true);
1696  return resume_result;
1697  }
1698  case eStateStepping: {
1699  const auto step_result = thread.SingleStep(signo);
1700  if (step_result.Success())
1701  SetState(eStateRunning, true);
1702  return step_result;
1703  }
1704  default:
1705  LLDB_LOG(log, "Unhandled state {0}.", state);
1706  llvm_unreachable("Unhandled state for resume");
1707  }
1708 }
1709 
1710 //===----------------------------------------------------------------------===//
1711 
1712 void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {
1714  LLDB_LOG(log, "about to process event: (triggering_tid: {0})",
1715  triggering_tid);
1716 
1717  m_pending_notification_tid = triggering_tid;
1718 
1719  // Request a stop for all the thread stops that need to be stopped and are
1720  // not already known to be stopped.
1721  for (const auto &thread : m_threads) {
1722  if (StateIsRunningState(thread->GetState()))
1723  static_cast<NativeThreadLinux *>(thread.get())->RequestStop();
1724  }
1725 
1726  SignalIfAllThreadsStopped();
1727  LLDB_LOG(log, "event processing done");
1728 }
1729 
1730 void NativeProcessLinux::SignalIfAllThreadsStopped() {
1731  if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
1732  return; // No pending notification. Nothing to do.
1733 
1734  for (const auto &thread_sp : m_threads) {
1735  if (StateIsRunningState(thread_sp->GetState()))
1736  return; // Some threads are still running. Don't signal yet.
1737  }
1738 
1739  // We have a pending notification and all threads have stopped.
1740  Log *log(
1742 
1743  // Clear any temporary breakpoints we used to implement software single
1744  // stepping.
1745  for (const auto &thread_info : m_threads_stepping_with_breakpoint) {
1746  Status error = RemoveBreakpoint(thread_info.second);
1747  if (error.Fail())
1748  LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}",
1749  thread_info.first, error);
1750  }
1751  m_threads_stepping_with_breakpoint.clear();
1752 
1753  // Notify the delegate about the stop
1754  SetCurrentThreadID(m_pending_notification_tid);
1755  SetState(StateType::eStateStopped, true);
1756  m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
1757 }
1758 
1759 void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {
1761  LLDB_LOG(log, "tid: {0}", thread.GetID());
1762 
1763  if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID &&
1764  StateIsRunningState(thread.GetState())) {
1765  // We will need to wait for this new thread to stop as well before firing
1766  // the notification.
1767  thread.RequestStop();
1768  }
1769 }
1770 
1771 void NativeProcessLinux::SigchldHandler() {
1773  // Process all pending waitpid notifications.
1774  while (true) {
1775  int status = -1;
1776  ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, -1, &status,
1777  __WALL | __WNOTHREAD | WNOHANG);
1778 
1779  if (wait_pid == 0)
1780  break; // We are done.
1781 
1782  if (wait_pid == -1) {
1783  Status error(errno, eErrorTypePOSIX);
1784  LLDB_LOG(log, "waitpid (-1, &status, _) failed: {0}", error);
1785  break;
1786  }
1787 
1788  WaitStatus wait_status = WaitStatus::Decode(status);
1789  bool exited = wait_status.type == WaitStatus::Exit ||
1790  (wait_status.type == WaitStatus::Signal &&
1791  wait_pid == static_cast<::pid_t>(GetID()));
1792 
1793  LLDB_LOG(
1794  log,
1795  "waitpid (-1, &status, _) => pid = {0}, status = {1}, exited = {2}",
1796  wait_pid, wait_status, exited);
1797 
1798  MonitorCallback(wait_pid, exited, wait_status);
1799  }
1800 }
1801 
1802 // Wrapper for ptrace to catch errors and log calls. Note that ptrace sets
1803 // errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
1805  void *data, size_t data_size,
1806  long *result) {
1807  Status error;
1808  long int ret;
1809 
1811 
1812  PtraceDisplayBytes(req, data, data_size);
1813 
1814  errno = 0;
1815  if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
1816  ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
1817  *(unsigned int *)addr, data);
1818  else
1819  ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
1820  addr, data);
1821 
1822  if (ret == -1)
1823  error.SetErrorToErrno();
1824 
1825  if (result)
1826  *result = ret;
1827 
1828  LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data,
1829  data_size, ret);
1830 
1831  PtraceDisplayBytes(req, data, data_size);
1832 
1833  if (error.Fail())
1834  LLDB_LOG(log, "ptrace() failed: {0}", error);
1835 
1836  return error;
1837 }
1838 
1839 llvm::Expected<ProcessorTraceMonitor &>
1840 NativeProcessLinux::LookupProcessorTraceInstance(lldb::user_id_t traceid,
1841  lldb::tid_t thread) {
1843  if (thread == LLDB_INVALID_THREAD_ID && traceid == m_pt_proces_trace_id) {
1844  LLDB_LOG(log, "thread not specified: {0}", traceid);
1845  return Status("tracing not active thread not specified").ToError();
1846  }
1847 
1848  for (auto& iter : m_processor_trace_monitor) {
1849  if (traceid == iter.second->GetTraceID() &&
1850  (thread == iter.first || thread == LLDB_INVALID_THREAD_ID))
1851  return *(iter.second);
1852  }
1853 
1854  LLDB_LOG(log, "traceid not being traced: {0}", traceid);
1855  return Status("tracing not active for this thread").ToError();
1856 }
1857 
1858 Status NativeProcessLinux::GetMetaData(lldb::user_id_t traceid,
1859  lldb::tid_t thread,
1860  llvm::MutableArrayRef<uint8_t> &buffer,
1861  size_t offset) {
1862  TraceOptions trace_options;
1864  Status error;
1865 
1866  LLDB_LOG(log, "traceid {0}", traceid);
1867 
1868  auto perf_monitor = LookupProcessorTraceInstance(traceid, thread);
1869  if (!perf_monitor) {
1870  LLDB_LOG(log, "traceid not being traced: {0}", traceid);
1871  buffer = buffer.slice(buffer.size());
1872  error = perf_monitor.takeError();
1873  return error;
1874  }
1875  return (*perf_monitor).ReadPerfTraceData(buffer, offset);
1876 }
1877 
1878 Status NativeProcessLinux::GetData(lldb::user_id_t traceid, lldb::tid_t thread,
1879  llvm::MutableArrayRef<uint8_t> &buffer,
1880  size_t offset) {
1882  Status error;
1883 
1884  LLDB_LOG(log, "traceid {0}", traceid);
1885 
1886  auto perf_monitor = LookupProcessorTraceInstance(traceid, thread);
1887  if (!perf_monitor) {
1888  LLDB_LOG(log, "traceid not being traced: {0}", traceid);
1889  buffer = buffer.slice(buffer.size());
1890  error = perf_monitor.takeError();
1891  return error;
1892  }
1893  return (*perf_monitor).ReadPerfTraceAux(buffer, offset);
1894 }
1895 
1896 Status NativeProcessLinux::GetTraceConfig(lldb::user_id_t traceid,
1897  TraceOptions &config) {
1898  Status error;
1899  if (config.getThreadID() == LLDB_INVALID_THREAD_ID &&
1900  m_pt_proces_trace_id == traceid) {
1901  if (m_pt_proces_trace_id == LLDB_INVALID_UID) {
1902  error.SetErrorString("tracing not active for this process");
1903  return error;
1904  }
1905  config = m_pt_process_trace_config;
1906  } else {
1907  auto perf_monitor =
1908  LookupProcessorTraceInstance(traceid, config.getThreadID());
1909  if (!perf_monitor) {
1910  error = perf_monitor.takeError();
1911  return error;
1912  }
1913  error = (*perf_monitor).GetTraceConfig(config);
1914  }
1915  return error;
1916 }
1917 
1919 NativeProcessLinux::StartTraceGroup(const TraceOptions &config,
1920  Status &error) {
1921 
1924  return LLDB_INVALID_UID;
1925 
1926  if (m_pt_proces_trace_id != LLDB_INVALID_UID) {
1927  error.SetErrorString("tracing already active on this process");
1928  return m_pt_proces_trace_id;
1929  }
1930 
1931  for (const auto &thread_sp : m_threads) {
1932  if (auto traceInstance = ProcessorTraceMonitor::Create(
1933  GetID(), thread_sp->GetID(), config, true)) {
1934  m_pt_traced_thread_group.insert(thread_sp->GetID());
1935  m_processor_trace_monitor.insert(
1936  std::make_pair(thread_sp->GetID(), std::move(*traceInstance)));
1937  }
1938  }
1939 
1940  m_pt_process_trace_config = config;
1941  error = ProcessorTraceMonitor::GetCPUType(m_pt_process_trace_config);
1942 
1943  // Trace on Complete process will have traceid of 0
1944  m_pt_proces_trace_id = 0;
1945 
1946  LLDB_LOG(log, "Process Trace ID {0}", m_pt_proces_trace_id);
1947  return m_pt_proces_trace_id;
1948 }
1949 
1950 lldb::user_id_t NativeProcessLinux::StartTrace(const TraceOptions &config,
1951  Status &error) {
1953  return NativeProcessProtocol::StartTrace(config, error);
1954 
1956 
1957  lldb::tid_t threadid = config.getThreadID();
1958 
1959  if (threadid == LLDB_INVALID_THREAD_ID)
1960  return StartTraceGroup(config, error);
1961 
1962  auto thread_sp = GetThreadByID(threadid);
1963  if (!thread_sp) {
1964  // Thread not tracked by lldb so don't trace.
1965  error.SetErrorString("invalid thread id");
1966  return LLDB_INVALID_UID;
1967  }
1968 
1969  const auto &iter = m_processor_trace_monitor.find(threadid);
1970  if (iter != m_processor_trace_monitor.end()) {
1971  LLDB_LOG(log, "Thread already being traced");
1972  error.SetErrorString("tracing already active on this thread");
1973  return LLDB_INVALID_UID;
1974  }
1975 
1976  auto traceMonitor =
1977  ProcessorTraceMonitor::Create(GetID(), threadid, config, false);
1978  if (!traceMonitor) {
1979  error = traceMonitor.takeError();
1980  LLDB_LOG(log, "error {0}", error);
1981  return LLDB_INVALID_UID;
1982  }
1983  lldb::user_id_t ret_trace_id = (*traceMonitor)->GetTraceID();
1984  m_processor_trace_monitor.insert(
1985  std::make_pair(threadid, std::move(*traceMonitor)));
1986  return ret_trace_id;
1987 }
1988 
1989 Status NativeProcessLinux::StopTracingForThread(lldb::tid_t thread) {
1990  Status error;
1992  LLDB_LOG(log, "Thread {0}", thread);
1993 
1994  const auto& iter = m_processor_trace_monitor.find(thread);
1995  if (iter == m_processor_trace_monitor.end()) {
1996  error.SetErrorString("tracing not active for this thread");
1997  return error;
1998  }
1999 
2000  if (iter->second->GetTraceID() == m_pt_proces_trace_id) {
2001  // traceid maps to the whole process so we have to erase it from the thread
2002  // group.
2003  LLDB_LOG(log, "traceid maps to process");
2004  m_pt_traced_thread_group.erase(thread);
2005  }
2006  m_processor_trace_monitor.erase(iter);
2007 
2008  return error;
2009 }
2010 
2011 Status NativeProcessLinux::StopTrace(lldb::user_id_t traceid,
2012  lldb::tid_t thread) {
2013  Status error;
2014 
2015  TraceOptions trace_options;
2016  trace_options.setThreadID(thread);
2017  error = NativeProcessLinux::GetTraceConfig(traceid, trace_options);
2018 
2019  if (error.Fail())
2020  return error;
2021 
2022  switch (trace_options.getType()) {
2024  if (traceid == m_pt_proces_trace_id &&
2025  thread == LLDB_INVALID_THREAD_ID)
2026  StopProcessorTracingOnProcess();
2027  else
2028  error = StopProcessorTracingOnThread(traceid, thread);
2029  break;
2030  default:
2031  error.SetErrorString("trace not supported");
2032  break;
2033  }
2034 
2035  return error;
2036 }
2037 
2038 void NativeProcessLinux::StopProcessorTracingOnProcess() {
2039  for (auto thread_id_iter : m_pt_traced_thread_group)
2040  m_processor_trace_monitor.erase(thread_id_iter);
2041  m_pt_traced_thread_group.clear();
2042  m_pt_proces_trace_id = LLDB_INVALID_UID;
2043 }
2044 
2045 Status NativeProcessLinux::StopProcessorTracingOnThread(lldb::user_id_t traceid,
2046  lldb::tid_t thread) {
2047  Status error;
2049 
2050  if (thread == LLDB_INVALID_THREAD_ID) {
2051  for (auto& iter : m_processor_trace_monitor) {
2052  if (iter.second->GetTraceID() == traceid) {
2053  // Stopping a trace instance for an individual thread hence there will
2054  // only be one traceid that can match.
2055  m_processor_trace_monitor.erase(iter.first);
2056  return error;
2057  }
2058  LLDB_LOG(log, "Trace ID {0}", iter.second->GetTraceID());
2059  }
2060 
2061  LLDB_LOG(log, "Invalid TraceID");
2062  error.SetErrorString("invalid trace id");
2063  return error;
2064  }
2065 
2066  // thread is specified so we can use find function on the map.
2067  const auto& iter = m_processor_trace_monitor.find(thread);
2068  if (iter == m_processor_trace_monitor.end()) {
2069  // thread not found in our map.
2070  LLDB_LOG(log, "thread not being traced");
2071  error.SetErrorString("tracing not active for this thread");
2072  return error;
2073  }
2074  if (iter->second->GetTraceID() != traceid) {
2075  // traceid did not match so it has to be invalid.
2076  LLDB_LOG(log, "Invalid TraceID");
2077  error.SetErrorString("invalid trace id");
2078  return error;
2079  }
2080 
2081  LLDB_LOG(log, "UID - {0} , Thread -{1}", traceid, thread);
2082 
2083  if (traceid == m_pt_proces_trace_id) {
2084  // traceid maps to the whole process so we have to erase it from the thread
2085  // group.
2086  LLDB_LOG(log, "traceid maps to process");
2087  m_pt_traced_thread_group.erase(thread);
2088  }
2089  m_processor_trace_monitor.erase(iter);
2090 
2091  return error;
2092 }
static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton, const EmulateInstruction::Context &context, const RegisterInfo *reg_info, const RegisterValue &reg_value)
static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton, const EmulateInstruction::Context &context, lldb::addr_t addr, void *dst, size_t length)
ConstString & GetFilename()
Filename string get accessor.
Definition: FileSpec.cpp:369
#define PTRACE_SETREGSET
Definition: Ptrace.h:39
#define LLDB_REGNUM_GENERIC_PC
Definition: lldb-defines.h:63
llvm::Error ToError() const
Definition: Status.cpp:88
#define UNUSED_IF_ASSERT_DISABLED(x)
Definition: lldb-defines.h:134
lldb::addr_t ReadRegisterAsUnsigned(uint32_t reg, lldb::addr_t fail_value)
#define LIBLLDB_LOG_PROCESS
Definition: Logging.h:15
const char * StateAsCString(lldb::StateType state)
Converts a StateType to a C string.
Definition: State.cpp:14
Enumerations for broadcasting.
Definition: SBLaunchInfo.h:14
void SetExecutable(OptionalBool val)
const char * AsCString(const char *value_if_empty=nullptr) const
Get the string value as a C string.
Definition: ConstString.h:224
Definition: Debugger.h:71
bool Contains(BaseType r) const
Definition: RangeMap.h:77
long PtraceWrapper(int req, lldb::pid_t pid, void *addr, int data, const char *reqName, const char *file, int line)
Process is currently trying to attach.
static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton, const RegisterInfo *reg_info, RegisterValue &reg_value)
#define LLDB_INVALID_PROCESS_ID
Definition: lldb-defines.h:92
#define O_NONBLOCK
#define LLDB_INVALID_SIGNAL_NUMBER
Definition: lldb-defines.h:95
#define POSIX_LOG_MEMORY
NativeRegisterContextLinux & GetRegisterContext() override
static lldb::addr_t ReadFlags(NativeRegisterContext &regsiter_context)
virtual Status GetWatchpointHitIndex(uint32_t &wp_index, lldb::addr_t trap_addr)
#define POSIX_LOG_THREAD
A file utility class.
Definition: FileSpec.h:55
An architecture specification class.
Definition: ArchSpec.h:32
void SetMapped(OptionalBool val)
void Clear()
Clears the object state.
Definition: FileSpec.cpp:285
const ResumeAction * GetActionForThread(lldb::tid_t tid, bool default_ok) const
Definition: Debug.h:76
void ParseLinuxMapRegions(llvm::StringRef linux_map, LinuxMapCallback const &callback)
const char * GetPermissionsAsCString(uint32_t permissions)
Definition: State.cpp:44
static Status EnsureFDFlags(int fd, int flags)
Process or thread is stopped and can be examined.
"lldb/Core/EmulateInstruction.h" A class that allows emulation of CPU opcodes.
const char * GetData() const
Definition: StreamString.h:43
POSIX error codes.
#define LLDB_INVALID_UID
Definition: lldb-defines.h:91
void SetRangeEnd(BaseType end)
Definition: RangeMap.h:64
#define LIBLLDB_LOG_WATCHPOINTS
Definition: Logging.h:20
#define LLDB_LOG(log,...)
Definition: Log.h:209
int ReleaseMasterFileDescriptor()
Release the master file descriptor.
Process or thread has crashed and can be examined.
#define SIGSTOP
void SetErrorToErrno()
Set the current error to errno.
Definition: Status.cpp:223
Process has exited and can&#39;t be examined.
bool StateIsRunningState(lldb::StateType state)
Check if a state represents a state where the process or thread is running.
Definition: State.cpp:68
#define DEBUG_PTRACE_MAXBYTES
Definition: Ptrace.h:20
#define PTRACE_GETREGSET
Definition: Ptrace.h:36
const char * GetArchitectureName() const
Returns a static string representing the current architecture.
Definition: ArchSpec.cpp:591
#define PTRACE_SETREGS
Definition: Ptrace.h:27
#define LLDB_INVALID_ADDRESS
Invalid value definitions.
Definition: lldb-defines.h:85
uint64_t user_id_t
Definition: lldb-types.h:84
#define LLDB_INVALID_INDEX32
Definition: lldb-defines.h:86
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::StateType state
Definition: Debug.h:23
lldb::tid_t getThreadID() const
Definition: TraceOptions.h:44
Log * GetLogIfAllCategoriesSet(uint32_t mask)
Definition: Logging.cpp:57
#define POSIX_LOG_PROCESS
void setThreadID(lldb::tid_t thread_id)
Definition: TraceOptions.h:42
#define LIBLLDB_LOG_BREAKPOINTS
Definition: Logging.h:19
Process is connected to remote debug services, but not launched or attached to anything yet...
Process has been detached and can&#39;t be examined.
static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton, const EmulateInstruction::Context &context, lldb::addr_t addr, const void *dst, size_t length)
lldb::addr_t GetPC(lldb::addr_t fail_value=LLDB_INVALID_ADDRESS)
Process is in the process of launching.
uint64_t tid_t
Definition: lldb-types.h:86
Manages communication with the inferior (debugee) process.
void SetErrorString(llvm::StringRef err_str)
Set the current error string to err_str.
Definition: Status.cpp:241
#define LLDB_REGNUM_GENERIC_FLAGS
Definition: lldb-defines.h:67
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition: Stream.cpp:106
const FileAction * GetFileActionForFD(int fd) const
ArchSpec & GetArchitecture()
Definition: ProcessInfo.h:62
bool Success() const
Test for success condition.
Definition: Status.cpp:287
Process or thread is in the process of stepping and can not be examined.
Process is object is valid, but not currently loaded.
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > getProcFile(::pid_t pid, ::pid_t tid, const llvm::Twine &file)
Definition: Support.cpp:14
bool InferiorCallMmap(Process *proc, lldb::addr_t &allocated_addr, lldb::addr_t addr, lldb::addr_t length, unsigned prot, unsigned flags, lldb::addr_t fd, lldb::addr_t offset)
Process or thread is in a suspended state as far as the debugger is concerned while other processes o...
#define SIGKILL
void SetByteSize(SizeType s)
Definition: RangeMap.h:73
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)
#define LLDB_INVALID_THREAD_ID
Definition: lldb-defines.h:93
uint64_t addr_t
Definition: lldb-types.h:83
void SetReadable(OptionalBool val)
#define PTRACE_SETFPREGS
Definition: Ptrace.h:33
bool Fail() const
Test for error condition.
Definition: Status.cpp:181
const char * GetCString() const
Get the string value as a C string.
Definition: ConstString.h:247
HostProcess LaunchProcess(const ProcessLaunchInfo &launch_info, Status &error) override
Log * GetLogIfAnyCategoriesSet(uint32_t mask)
Definition: Logging.cpp:61
SignalHandleUP RegisterSignal(int signo, const Callback &callback, Status &error)
Definition: MainLoop.cpp:297
Definition: SBAddress.h:15
EmulatorBaton(ProcessFreeBSD *process, RegisterContext *reg_context)
lldb::TraceType getType() const
Definition: TraceOptions.h:26
uint64_t pid_t
Definition: lldb-types.h:85
std::map< lldb::pid_t, bool > TidMap
Definition: Host.h:180
void SetRangeBase(BaseType b)
Definition: RangeMap.h:48
void SetWritable(OptionalBool val)
#define POSIX_LOG_PTRACE
static bool ProcessVmReadvSupported()
#define TRAP_HWBKPT
const char ** GetConstArgumentVector() const
Gets the argument vector.
Definition: Args.cpp:278
#define SIGTRAP
ValueType GetError() const
Access the error value.
Definition: Status.cpp:174
virtual Status GetHardwareBreakHitIndex(uint32_t &bp_index, lldb::addr_t trap_addr)
lldb::pid_t GetProcessId() const
Definition: HostProcess.cpp:29
#define LLDB_LOGV(log,...)
Definition: Log.h:216
const RegisterInfo * GetRegisterInfo(uint32_t reg_kind, uint32_t reg_num)
An error handling class.
Definition: Status.h:44
BaseType GetRangeBase() const
Definition: RangeMap.h:46
Process or thread is running and can&#39;t be examined.