1af245d11STodd Fiala //===-- NativeProcessLinux.cpp -------------------------------- -*- C++ -*-===//
2af245d11STodd Fiala //
3af245d11STodd Fiala //                     The LLVM Compiler Infrastructure
4af245d11STodd Fiala //
5af245d11STodd Fiala // This file is distributed under the University of Illinois Open Source
6af245d11STodd Fiala // License. See LICENSE.TXT for details.
7af245d11STodd Fiala //
8af245d11STodd Fiala //===----------------------------------------------------------------------===//
9af245d11STodd Fiala 
10af245d11STodd Fiala #include "NativeProcessLinux.h"
11af245d11STodd Fiala 
12af245d11STodd Fiala #include <errno.h>
13af245d11STodd Fiala #include <stdint.h>
14b9c1b51eSKate Stone #include <string.h>
15af245d11STodd Fiala #include <unistd.h>
16af245d11STodd Fiala 
17af245d11STodd Fiala #include <fstream>
18df7c6995SPavel Labath #include <mutex>
19c076559aSPavel Labath #include <sstream>
20af245d11STodd Fiala #include <string>
215b981ab9SPavel Labath #include <unordered_map>
22af245d11STodd Fiala 
23d8c338d4STamas Berghammer #include "lldb/Core/EmulateInstruction.h"
246edef204SOleksiy Vyalov #include "lldb/Core/ModuleSpec.h"
25af245d11STodd Fiala #include "lldb/Host/Host.h"
265ad891f7SPavel Labath #include "lldb/Host/HostProcess.h"
2724ae6294SZachary Turner #include "lldb/Host/PseudoTerminal.h"
2839de3110SZachary Turner #include "lldb/Host/ThreadLauncher.h"
292a86b555SPavel Labath #include "lldb/Host/common/NativeRegisterContext.h"
304ee1c952SPavel Labath #include "lldb/Host/linux/Ptrace.h"
314ee1c952SPavel Labath #include "lldb/Host/linux/Uio.h"
32816ae4b0SKamil Rytarowski #include "lldb/Host/posix/ProcessLauncherPosixFork.h"
332a86b555SPavel Labath #include "lldb/Symbol/ObjectFile.h"
3490aff47cSZachary Turner #include "lldb/Target/Process.h"
35af245d11STodd Fiala #include "lldb/Target/ProcessLaunchInfo.h"
365b981ab9SPavel Labath #include "lldb/Target/Target.h"
37c16f5dcaSChaoren Lin #include "lldb/Utility/LLDBAssert.h"
38d821c997SPavel Labath #include "lldb/Utility/RegisterValue.h"
39d821c997SPavel Labath #include "lldb/Utility/State.h"
4097206d57SZachary Turner #include "lldb/Utility/Status.h"
41f805e190SPavel Labath #include "lldb/Utility/StringExtractor.h"
4210c41f37SPavel Labath #include "llvm/Support/Errno.h"
4310c41f37SPavel Labath #include "llvm/Support/FileSystem.h"
4410c41f37SPavel Labath #include "llvm/Support/Threading.h"
45af245d11STodd Fiala 
46af245d11STodd Fiala #include "NativeThreadLinux.h"
47b9c1b51eSKate Stone #include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
48*c8e364e8SPavel Labath #include "Plugins/Process/Utility/LinuxProcMaps.h"
491e209fccSTamas Berghammer #include "Procfs.h"
50cacde7dfSTodd Fiala 
51d858487eSTamas Berghammer #include <linux/unistd.h>
52d858487eSTamas Berghammer #include <sys/socket.h>
53df7c6995SPavel Labath #include <sys/syscall.h>
54d858487eSTamas Berghammer #include <sys/types.h>
55d858487eSTamas Berghammer #include <sys/user.h>
56d858487eSTamas Berghammer #include <sys/wait.h>
57d858487eSTamas Berghammer 
58af245d11STodd Fiala // Support hardware breakpoints in case it has not been defined
59af245d11STodd Fiala #ifndef TRAP_HWBKPT
60af245d11STodd Fiala #define TRAP_HWBKPT 4
61af245d11STodd Fiala #endif
62af245d11STodd Fiala 
637cb18bf5STamas Berghammer using namespace lldb;
647cb18bf5STamas Berghammer using namespace lldb_private;
65db264a6dSTamas Berghammer using namespace lldb_private::process_linux;
667cb18bf5STamas Berghammer using namespace llvm;
677cb18bf5STamas Berghammer 
68af245d11STodd Fiala // Private bits we only need internally.
69df7c6995SPavel Labath 
70b9c1b51eSKate Stone static bool ProcessVmReadvSupported() {
71df7c6995SPavel Labath   static bool is_supported;
72c5f28e2aSKamil Rytarowski   static llvm::once_flag flag;
73df7c6995SPavel Labath 
74c5f28e2aSKamil Rytarowski   llvm::call_once(flag, [] {
75a6321a8eSPavel Labath     Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
76df7c6995SPavel Labath 
77df7c6995SPavel Labath     uint32_t source = 0x47424742;
78df7c6995SPavel Labath     uint32_t dest = 0;
79df7c6995SPavel Labath 
80df7c6995SPavel Labath     struct iovec local, remote;
81df7c6995SPavel Labath     remote.iov_base = &source;
82df7c6995SPavel Labath     local.iov_base = &dest;
83df7c6995SPavel Labath     remote.iov_len = local.iov_len = sizeof source;
84df7c6995SPavel Labath 
85b9c1b51eSKate Stone     // We shall try if cross-process-memory reads work by attempting to read a
86b9c1b51eSKate Stone     // value from our own process.
87df7c6995SPavel Labath     ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
88df7c6995SPavel Labath     is_supported = (res == sizeof(source) && source == dest);
89df7c6995SPavel Labath     if (is_supported)
90a6321a8eSPavel Labath       LLDB_LOG(log,
91a6321a8eSPavel Labath                "Detected kernel support for process_vm_readv syscall. "
92a6321a8eSPavel Labath                "Fast memory reads enabled.");
93df7c6995SPavel Labath     else
94a6321a8eSPavel Labath       LLDB_LOG(log,
95a6321a8eSPavel Labath                "syscall process_vm_readv failed (error: {0}). Fast memory "
96a6321a8eSPavel Labath                "reads disabled.",
9710c41f37SPavel Labath                llvm::sys::StrError());
98df7c6995SPavel Labath   });
99df7c6995SPavel Labath 
100df7c6995SPavel Labath   return is_supported;
101df7c6995SPavel Labath }
102df7c6995SPavel Labath 
103b9c1b51eSKate Stone namespace {
104b9c1b51eSKate Stone void MaybeLogLaunchInfo(const ProcessLaunchInfo &info) {
105a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1064abe5d69SPavel Labath   if (!log)
1074abe5d69SPavel Labath     return;
1084abe5d69SPavel Labath 
1094abe5d69SPavel Labath   if (const FileAction *action = info.GetFileActionForFD(STDIN_FILENO))
110a6321a8eSPavel Labath     LLDB_LOG(log, "setting STDIN to '{0}'", action->GetFileSpec());
1114abe5d69SPavel Labath   else
112a6321a8eSPavel Labath     LLDB_LOG(log, "leaving STDIN as is");
1134abe5d69SPavel Labath 
1144abe5d69SPavel Labath   if (const FileAction *action = info.GetFileActionForFD(STDOUT_FILENO))
115a6321a8eSPavel Labath     LLDB_LOG(log, "setting STDOUT to '{0}'", action->GetFileSpec());
1164abe5d69SPavel Labath   else
117a6321a8eSPavel Labath     LLDB_LOG(log, "leaving STDOUT as is");
1184abe5d69SPavel Labath 
1194abe5d69SPavel Labath   if (const FileAction *action = info.GetFileActionForFD(STDERR_FILENO))
120a6321a8eSPavel Labath     LLDB_LOG(log, "setting STDERR to '{0}'", action->GetFileSpec());
1214abe5d69SPavel Labath   else
122a6321a8eSPavel Labath     LLDB_LOG(log, "leaving STDERR as is");
1234abe5d69SPavel Labath 
1244abe5d69SPavel Labath   int i = 0;
125b9c1b51eSKate Stone   for (const char **args = info.GetArguments().GetConstArgumentVector(); *args;
126b9c1b51eSKate Stone        ++args, ++i)
127a6321a8eSPavel Labath     LLDB_LOG(log, "arg {0}: '{1}'", i, *args);
1284abe5d69SPavel Labath }
1294abe5d69SPavel Labath 
130b9c1b51eSKate Stone void DisplayBytes(StreamString &s, void *bytes, uint32_t count) {
131af245d11STodd Fiala   uint8_t *ptr = (uint8_t *)bytes;
132af245d11STodd Fiala   const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
133b9c1b51eSKate Stone   for (uint32_t i = 0; i < loop_count; i++) {
134af245d11STodd Fiala     s.Printf("[%x]", *ptr);
135af245d11STodd Fiala     ptr++;
136af245d11STodd Fiala   }
137af245d11STodd Fiala }
138af245d11STodd Fiala 
139b9c1b51eSKate Stone void PtraceDisplayBytes(int &req, void *data, size_t data_size) {
140aafe053cSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
141a6321a8eSPavel Labath   if (!log)
142a6321a8eSPavel Labath     return;
143af245d11STodd Fiala   StreamString buf;
144af245d11STodd Fiala 
145b9c1b51eSKate Stone   switch (req) {
146b9c1b51eSKate Stone   case PTRACE_POKETEXT: {
147af245d11STodd Fiala     DisplayBytes(buf, &data, 8);
148aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_POKETEXT {0}", buf.GetData());
149af245d11STodd Fiala     break;
150af245d11STodd Fiala   }
151b9c1b51eSKate Stone   case PTRACE_POKEDATA: {
152af245d11STodd Fiala     DisplayBytes(buf, &data, 8);
153aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_POKEDATA {0}", buf.GetData());
154af245d11STodd Fiala     break;
155af245d11STodd Fiala   }
156b9c1b51eSKate Stone   case PTRACE_POKEUSER: {
157af245d11STodd Fiala     DisplayBytes(buf, &data, 8);
158aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_POKEUSER {0}", buf.GetData());
159af245d11STodd Fiala     break;
160af245d11STodd Fiala   }
161b9c1b51eSKate Stone   case PTRACE_SETREGS: {
162af245d11STodd Fiala     DisplayBytes(buf, data, data_size);
163aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_SETREGS {0}", buf.GetData());
164af245d11STodd Fiala     break;
165af245d11STodd Fiala   }
166b9c1b51eSKate Stone   case PTRACE_SETFPREGS: {
167af245d11STodd Fiala     DisplayBytes(buf, data, data_size);
168aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_SETFPREGS {0}", buf.GetData());
169af245d11STodd Fiala     break;
170af245d11STodd Fiala   }
171b9c1b51eSKate Stone   case PTRACE_SETSIGINFO: {
172af245d11STodd Fiala     DisplayBytes(buf, data, sizeof(siginfo_t));
173aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_SETSIGINFO {0}", buf.GetData());
174af245d11STodd Fiala     break;
175af245d11STodd Fiala   }
176b9c1b51eSKate Stone   case PTRACE_SETREGSET: {
17711edb4eeSPavel Labath     // Extract iov_base from data, which is a pointer to the struct iovec
178af245d11STodd Fiala     DisplayBytes(buf, *(void **)data, data_size);
179aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_SETREGSET {0}", buf.GetData());
180af245d11STodd Fiala     break;
181af245d11STodd Fiala   }
182b9c1b51eSKate Stone   default: {}
183af245d11STodd Fiala   }
184af245d11STodd Fiala }
185af245d11STodd Fiala 
18619cbe96aSPavel Labath static constexpr unsigned k_ptrace_word_size = sizeof(void *);
187b9c1b51eSKate Stone static_assert(sizeof(long) >= k_ptrace_word_size,
188b9c1b51eSKate Stone               "Size of long must be larger than ptrace word size");
1891107b5a5SPavel Labath } // end of anonymous namespace
1901107b5a5SPavel Labath 
191bd7cbc5aSPavel Labath // Simple helper function to ensure flags are enabled on the given file
192bd7cbc5aSPavel Labath // descriptor.
19397206d57SZachary Turner static Status EnsureFDFlags(int fd, int flags) {
19497206d57SZachary Turner   Status error;
195bd7cbc5aSPavel Labath 
196bd7cbc5aSPavel Labath   int status = fcntl(fd, F_GETFL);
197b9c1b51eSKate Stone   if (status == -1) {
198bd7cbc5aSPavel Labath     error.SetErrorToErrno();
199bd7cbc5aSPavel Labath     return error;
200bd7cbc5aSPavel Labath   }
201bd7cbc5aSPavel Labath 
202b9c1b51eSKate Stone   if (fcntl(fd, F_SETFL, status | flags) == -1) {
203bd7cbc5aSPavel Labath     error.SetErrorToErrno();
204bd7cbc5aSPavel Labath     return error;
205bd7cbc5aSPavel Labath   }
206bd7cbc5aSPavel Labath 
207bd7cbc5aSPavel Labath   return error;
208bd7cbc5aSPavel Labath }
209bd7cbc5aSPavel Labath 
210af245d11STodd Fiala // -----------------------------------------------------------------------------
211af245d11STodd Fiala // Public Static Methods
212af245d11STodd Fiala // -----------------------------------------------------------------------------
213af245d11STodd Fiala 
21482abefa4SPavel Labath llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
21596e600fcSPavel Labath NativeProcessLinux::Factory::Launch(ProcessLaunchInfo &launch_info,
21696e600fcSPavel Labath                                     NativeDelegate &native_delegate,
21796e600fcSPavel Labath                                     MainLoop &mainloop) const {
218a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
219af245d11STodd Fiala 
22096e600fcSPavel Labath   MaybeLogLaunchInfo(launch_info);
221af245d11STodd Fiala 
22296e600fcSPavel Labath   Status status;
22396e600fcSPavel Labath   ::pid_t pid = ProcessLauncherPosixFork()
22496e600fcSPavel Labath                     .LaunchProcess(launch_info, status)
22596e600fcSPavel Labath                     .GetProcessId();
22696e600fcSPavel Labath   LLDB_LOG(log, "pid = {0:x}", pid);
22796e600fcSPavel Labath   if (status.Fail()) {
22896e600fcSPavel Labath     LLDB_LOG(log, "failed to launch process: {0}", status);
22996e600fcSPavel Labath     return status.ToError();
230af245d11STodd Fiala   }
231af245d11STodd Fiala 
23296e600fcSPavel Labath   // Wait for the child process to trap on its call to execve.
23396e600fcSPavel Labath   int wstatus;
23496e600fcSPavel Labath   ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0);
23596e600fcSPavel Labath   assert(wpid == pid);
23696e600fcSPavel Labath   (void)wpid;
23796e600fcSPavel Labath   if (!WIFSTOPPED(wstatus)) {
23896e600fcSPavel Labath     LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}",
23996e600fcSPavel Labath              WaitStatus::Decode(wstatus));
24096e600fcSPavel Labath     return llvm::make_error<StringError>("Could not sync with inferior process",
24196e600fcSPavel Labath                                          llvm::inconvertibleErrorCode());
24296e600fcSPavel Labath   }
24396e600fcSPavel Labath   LLDB_LOG(log, "inferior started, now in stopped state");
244af245d11STodd Fiala 
24536e82208SPavel Labath   ProcessInstanceInfo Info;
24636e82208SPavel Labath   if (!Host::GetProcessInfo(pid, Info)) {
24736e82208SPavel Labath     return llvm::make_error<StringError>("Cannot get process architecture",
24836e82208SPavel Labath                                          llvm::inconvertibleErrorCode());
24936e82208SPavel Labath   }
25096e600fcSPavel Labath 
25196e600fcSPavel Labath   // Set the architecture to the exe architecture.
25296e600fcSPavel Labath   LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid,
25336e82208SPavel Labath            Info.GetArchitecture().GetArchitectureName());
25496e600fcSPavel Labath 
25596e600fcSPavel Labath   status = SetDefaultPtraceOpts(pid);
25696e600fcSPavel Labath   if (status.Fail()) {
25796e600fcSPavel Labath     LLDB_LOG(log, "failed to set default ptrace options: {0}", status);
25896e600fcSPavel Labath     return status.ToError();
259af245d11STodd Fiala   }
260af245d11STodd Fiala 
26182abefa4SPavel Labath   return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
26296e600fcSPavel Labath       pid, launch_info.GetPTY().ReleaseMasterFileDescriptor(), native_delegate,
26336e82208SPavel Labath       Info.GetArchitecture(), mainloop, {pid}));
264af245d11STodd Fiala }
265af245d11STodd Fiala 
26682abefa4SPavel Labath llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
26782abefa4SPavel Labath NativeProcessLinux::Factory::Attach(
268b9c1b51eSKate Stone     lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
26996e600fcSPavel Labath     MainLoop &mainloop) const {
270a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
271a6321a8eSPavel Labath   LLDB_LOG(log, "pid = {0:x}", pid);
272af245d11STodd Fiala 
273af245d11STodd Fiala   // Retrieve the architecture for the running process.
27436e82208SPavel Labath   ProcessInstanceInfo Info;
27536e82208SPavel Labath   if (!Host::GetProcessInfo(pid, Info)) {
27636e82208SPavel Labath     return llvm::make_error<StringError>("Cannot get process architecture",
27736e82208SPavel Labath                                          llvm::inconvertibleErrorCode());
27836e82208SPavel Labath   }
279af245d11STodd Fiala 
28096e600fcSPavel Labath   auto tids_or = NativeProcessLinux::Attach(pid);
28196e600fcSPavel Labath   if (!tids_or)
28296e600fcSPavel Labath     return tids_or.takeError();
283af245d11STodd Fiala 
28482abefa4SPavel Labath   return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
28536e82208SPavel Labath       pid, -1, native_delegate, Info.GetArchitecture(), mainloop, *tids_or));
286af245d11STodd Fiala }
287af245d11STodd Fiala 
288af245d11STodd Fiala // -----------------------------------------------------------------------------
289af245d11STodd Fiala // Public Instance Methods
290af245d11STodd Fiala // -----------------------------------------------------------------------------
291af245d11STodd Fiala 
29296e600fcSPavel Labath NativeProcessLinux::NativeProcessLinux(::pid_t pid, int terminal_fd,
29396e600fcSPavel Labath                                        NativeDelegate &delegate,
29482abefa4SPavel Labath                                        const ArchSpec &arch, MainLoop &mainloop,
29582abefa4SPavel Labath                                        llvm::ArrayRef<::pid_t> tids)
29696e600fcSPavel Labath     : NativeProcessProtocol(pid, terminal_fd, delegate), m_arch(arch) {
297b9c1b51eSKate Stone   if (m_terminal_fd != -1) {
29896e600fcSPavel Labath     Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
29996e600fcSPavel Labath     assert(status.Success());
3005ad891f7SPavel Labath   }
301af245d11STodd Fiala 
30296e600fcSPavel Labath   Status status;
30396e600fcSPavel Labath   m_sigchld_handle = mainloop.RegisterSignal(
30496e600fcSPavel Labath       SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status);
30596e600fcSPavel Labath   assert(m_sigchld_handle && status.Success());
30696e600fcSPavel Labath 
30796e600fcSPavel Labath   for (const auto &tid : tids) {
308a5be48b3SPavel Labath     NativeThreadLinux &thread = AddThread(tid);
309a5be48b3SPavel Labath     thread.SetStoppedBySignal(SIGSTOP);
310a5be48b3SPavel Labath     ThreadWasCreated(thread);
311af245d11STodd Fiala   }
312af245d11STodd Fiala 
31396e600fcSPavel Labath   // Let our process instance know the thread has stopped.
31496e600fcSPavel Labath   SetCurrentThreadID(tids[0]);
31596e600fcSPavel Labath   SetState(StateType::eStateStopped, false);
31696e600fcSPavel Labath 
31796e600fcSPavel Labath   // Proccess any signals we received before installing our handler
31896e600fcSPavel Labath   SigchldHandler();
31996e600fcSPavel Labath }
32096e600fcSPavel Labath 
32196e600fcSPavel Labath llvm::Expected<std::vector<::pid_t>> NativeProcessLinux::Attach(::pid_t pid) {
322a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
323af245d11STodd Fiala 
32496e600fcSPavel Labath   Status status;
325b9c1b51eSKate Stone   // Use a map to keep track of the threads which we have attached/need to
326b9c1b51eSKate Stone   // attach.
327af245d11STodd Fiala   Host::TidMap tids_to_attach;
328b9c1b51eSKate Stone   while (Host::FindProcessThreads(pid, tids_to_attach)) {
329af245d11STodd Fiala     for (Host::TidMap::iterator it = tids_to_attach.begin();
330b9c1b51eSKate Stone          it != tids_to_attach.end();) {
331b9c1b51eSKate Stone       if (it->second == false) {
332af245d11STodd Fiala         lldb::tid_t tid = it->first;
333af245d11STodd Fiala 
334af245d11STodd Fiala         // Attach to the requested process.
335af245d11STodd Fiala         // An attach will cause the thread to stop with a SIGSTOP.
33696e600fcSPavel Labath         if ((status = PtraceWrapper(PTRACE_ATTACH, tid)).Fail()) {
33705097246SAdrian Prantl           // No such thread. The thread may have exited. More error handling
33805097246SAdrian Prantl           // may be needed.
33996e600fcSPavel Labath           if (status.GetError() == ESRCH) {
340af245d11STodd Fiala             it = tids_to_attach.erase(it);
341af245d11STodd Fiala             continue;
34296e600fcSPavel Labath           }
34396e600fcSPavel Labath           return status.ToError();
344af245d11STodd Fiala         }
345af245d11STodd Fiala 
34696e600fcSPavel Labath         int wpid =
34796e600fcSPavel Labath             llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, nullptr, __WALL);
34805097246SAdrian Prantl         // Need to use __WALL otherwise we receive an error with errno=ECHLD At
34905097246SAdrian Prantl         // this point we should have a thread stopped if waitpid succeeds.
35096e600fcSPavel Labath         if (wpid < 0) {
35105097246SAdrian Prantl           // No such thread. The thread may have exited. More error handling
35205097246SAdrian Prantl           // may be needed.
353b9c1b51eSKate Stone           if (errno == ESRCH) {
354af245d11STodd Fiala             it = tids_to_attach.erase(it);
355af245d11STodd Fiala             continue;
356af245d11STodd Fiala           }
35796e600fcSPavel Labath           return llvm::errorCodeToError(
35896e600fcSPavel Labath               std::error_code(errno, std::generic_category()));
359af245d11STodd Fiala         }
360af245d11STodd Fiala 
36196e600fcSPavel Labath         if ((status = SetDefaultPtraceOpts(tid)).Fail())
36296e600fcSPavel Labath           return status.ToError();
363af245d11STodd Fiala 
364a6321a8eSPavel Labath         LLDB_LOG(log, "adding tid = {0}", tid);
365af245d11STodd Fiala         it->second = true;
366af245d11STodd Fiala       }
367af245d11STodd Fiala 
368af245d11STodd Fiala       // move the loop forward
369af245d11STodd Fiala       ++it;
370af245d11STodd Fiala     }
371af245d11STodd Fiala   }
372af245d11STodd Fiala 
37396e600fcSPavel Labath   size_t tid_count = tids_to_attach.size();
37496e600fcSPavel Labath   if (tid_count == 0)
37596e600fcSPavel Labath     return llvm::make_error<StringError>("No such process",
37696e600fcSPavel Labath                                          llvm::inconvertibleErrorCode());
377af245d11STodd Fiala 
37896e600fcSPavel Labath   std::vector<::pid_t> tids;
37996e600fcSPavel Labath   tids.reserve(tid_count);
38096e600fcSPavel Labath   for (const auto &p : tids_to_attach)
38196e600fcSPavel Labath     tids.push_back(p.first);
38296e600fcSPavel Labath   return std::move(tids);
383af245d11STodd Fiala }
384af245d11STodd Fiala 
38597206d57SZachary Turner Status NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid) {
386af245d11STodd Fiala   long ptrace_opts = 0;
387af245d11STodd Fiala 
388af245d11STodd Fiala   // Have the child raise an event on exit.  This is used to keep the child in
389af245d11STodd Fiala   // limbo until it is destroyed.
390af245d11STodd Fiala   ptrace_opts |= PTRACE_O_TRACEEXIT;
391af245d11STodd Fiala 
392af245d11STodd Fiala   // Have the tracer trace threads which spawn in the inferior process.
393af245d11STodd Fiala   // TODO: if we want to support tracing the inferiors' child, add the
394af245d11STodd Fiala   // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
395af245d11STodd Fiala   ptrace_opts |= PTRACE_O_TRACECLONE;
396af245d11STodd Fiala 
39705097246SAdrian Prantl   // Have the tracer notify us before execve returns (needed to disable legacy
39805097246SAdrian Prantl   // SIGTRAP generation)
399af245d11STodd Fiala   ptrace_opts |= PTRACE_O_TRACEEXEC;
400af245d11STodd Fiala 
4014a9babb2SPavel Labath   return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void *)ptrace_opts);
402af245d11STodd Fiala }
403af245d11STodd Fiala 
4041107b5a5SPavel Labath // Handles all waitpid events from the inferior process.
405b9c1b51eSKate Stone void NativeProcessLinux::MonitorCallback(lldb::pid_t pid, bool exited,
4063508fc8cSPavel Labath                                          WaitStatus status) {
407af245d11STodd Fiala   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
408af245d11STodd Fiala 
409b9c1b51eSKate Stone   // Certain activities differ based on whether the pid is the tid of the main
410b9c1b51eSKate Stone   // thread.
4111107b5a5SPavel Labath   const bool is_main_thread = (pid == GetID());
412af245d11STodd Fiala 
413af245d11STodd Fiala   // Handle when the thread exits.
414b9c1b51eSKate Stone   if (exited) {
415d8b3c1a1SPavel Labath     LLDB_LOG(log,
416d8b3c1a1SPavel Labath              "got exit signal({0}) , tid = {1} ({2} main thread), process "
417d8b3c1a1SPavel Labath              "state = {3}",
418d8b3c1a1SPavel Labath              signal, pid, is_main_thread ? "is" : "is not", GetState());
419af245d11STodd Fiala 
420af245d11STodd Fiala     // This is a thread that exited.  Ensure we're not tracking it anymore.
421d8b3c1a1SPavel Labath     StopTrackingThread(pid);
422af245d11STodd Fiala 
423b9c1b51eSKate Stone     if (is_main_thread) {
424af245d11STodd Fiala       // The main thread exited.  We're done monitoring.  Report to delegate.
4253508fc8cSPavel Labath       SetExitStatus(status, true);
426af245d11STodd Fiala 
427af245d11STodd Fiala       // Notify delegate that our process has exited.
4281107b5a5SPavel Labath       SetState(StateType::eStateExited, true);
429af245d11STodd Fiala     }
4301107b5a5SPavel Labath     return;
431af245d11STodd Fiala   }
432af245d11STodd Fiala 
433af245d11STodd Fiala   siginfo_t info;
434b9cc0c75SPavel Labath   const auto info_err = GetSignalInfo(pid, &info);
435b9cc0c75SPavel Labath   auto thread_sp = GetThreadByID(pid);
436b9cc0c75SPavel Labath 
437b9c1b51eSKate Stone   if (!thread_sp) {
43805097246SAdrian Prantl     // Normally, the only situation when we cannot find the thread is if we
43905097246SAdrian Prantl     // have just received a new thread notification. This is indicated by
440a6321a8eSPavel Labath     // GetSignalInfo() returning si_code == SI_USER and si_pid == 0
441a6321a8eSPavel Labath     LLDB_LOG(log, "received notification about an unknown tid {0}.", pid);
442b9cc0c75SPavel Labath 
443b9c1b51eSKate Stone     if (info_err.Fail()) {
444a6321a8eSPavel Labath       LLDB_LOG(log,
445a6321a8eSPavel Labath                "(tid {0}) GetSignalInfo failed ({1}). "
446a6321a8eSPavel Labath                "Ingoring this notification.",
447a6321a8eSPavel Labath                pid, info_err);
448b9cc0c75SPavel Labath       return;
449b9cc0c75SPavel Labath     }
450b9cc0c75SPavel Labath 
451a6321a8eSPavel Labath     LLDB_LOG(log, "tid {0}, si_code: {1}, si_pid: {2}", pid, info.si_code,
452a6321a8eSPavel Labath              info.si_pid);
453b9cc0c75SPavel Labath 
454a5be48b3SPavel Labath     NativeThreadLinux &thread = AddThread(pid);
45599e37695SRavitheja Addepally 
456b9cc0c75SPavel Labath     // Resume the newly created thread.
457a5be48b3SPavel Labath     ResumeThread(thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
458a5be48b3SPavel Labath     ThreadWasCreated(thread);
459b9cc0c75SPavel Labath     return;
460b9cc0c75SPavel Labath   }
461b9cc0c75SPavel Labath 
462b9cc0c75SPavel Labath   // Get details on the signal raised.
463b9c1b51eSKate Stone   if (info_err.Success()) {
464fa03ad2eSChaoren Lin     // We have retrieved the signal info.  Dispatch appropriately.
465fa03ad2eSChaoren Lin     if (info.si_signo == SIGTRAP)
466b9cc0c75SPavel Labath       MonitorSIGTRAP(info, *thread_sp);
467fa03ad2eSChaoren Lin     else
468b9cc0c75SPavel Labath       MonitorSignal(info, *thread_sp, exited);
469b9c1b51eSKate Stone   } else {
470b9c1b51eSKate Stone     if (info_err.GetError() == EINVAL) {
47105097246SAdrian Prantl       // This is a group stop reception for this tid. We can reach here if we
47205097246SAdrian Prantl       // reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the tracee,
47305097246SAdrian Prantl       // triggering the group-stop mechanism. Normally receiving these would
47405097246SAdrian Prantl       // stop the process, pending a SIGCONT. Simulating this state in a
47505097246SAdrian Prantl       // debugger is hard and is generally not needed (one use case is
47605097246SAdrian Prantl       // debugging background task being managed by a shell). For general use,
47705097246SAdrian Prantl       // it is sufficient to stop the process in a signal-delivery stop which
47805097246SAdrian Prantl       // happens before the group stop. This done by MonitorSignal and works
47905097246SAdrian Prantl       // correctly for all signals.
480a6321a8eSPavel Labath       LLDB_LOG(log,
481a6321a8eSPavel Labath                "received a group stop for pid {0} tid {1}. Transparent "
482a6321a8eSPavel Labath                "handling of group stops not supported, resuming the "
483a6321a8eSPavel Labath                "thread.",
484a6321a8eSPavel Labath                GetID(), pid);
485b9c1b51eSKate Stone       ResumeThread(*thread_sp, thread_sp->GetState(),
486b9c1b51eSKate Stone                    LLDB_INVALID_SIGNAL_NUMBER);
487b9c1b51eSKate Stone     } else {
488af245d11STodd Fiala       // ptrace(GETSIGINFO) failed (but not due to group-stop).
489af245d11STodd Fiala 
490b9c1b51eSKate Stone       // A return value of ESRCH means the thread/process is no longer on the
491a6321a8eSPavel Labath       // system, so it was killed somehow outside of our control.  Either way,
492a6321a8eSPavel Labath       // we can't do anything with it anymore.
493af245d11STodd Fiala 
494b9c1b51eSKate Stone       // Stop tracking the metadata for the thread since it's entirely off the
495b9c1b51eSKate Stone       // system now.
4961107b5a5SPavel Labath       const bool thread_found = StopTrackingThread(pid);
497af245d11STodd Fiala 
498a6321a8eSPavel Labath       LLDB_LOG(log,
499a6321a8eSPavel Labath                "GetSignalInfo failed: {0}, tid = {1}, signal = {2}, "
500a6321a8eSPavel Labath                "status = {3}, main_thread = {4}, thread_found: {5}",
501a6321a8eSPavel Labath                info_err, pid, signal, status, is_main_thread, thread_found);
502af245d11STodd Fiala 
503b9c1b51eSKate Stone       if (is_main_thread) {
504b9c1b51eSKate Stone         // Notify the delegate - our process is not available but appears to
50505097246SAdrian Prantl         // have been killed outside our control.  Is eStateExited the right
50605097246SAdrian Prantl         // exit state in this case?
5073508fc8cSPavel Labath         SetExitStatus(status, true);
5081107b5a5SPavel Labath         SetState(StateType::eStateExited, true);
509b9c1b51eSKate Stone       } else {
510b9c1b51eSKate Stone         // This thread was pulled out from underneath us.  Anything to do here?
511b9c1b51eSKate Stone         // Do we want to do an all stop?
512a6321a8eSPavel Labath         LLDB_LOG(log,
513a6321a8eSPavel Labath                  "pid {0} tid {1} non-main thread exit occurred, didn't "
514a6321a8eSPavel Labath                  "tell delegate anything since thread disappeared out "
515a6321a8eSPavel Labath                  "from underneath us",
516a6321a8eSPavel Labath                  GetID(), pid);
517af245d11STodd Fiala       }
518af245d11STodd Fiala     }
519af245d11STodd Fiala   }
520af245d11STodd Fiala }
521af245d11STodd Fiala 
522b9c1b51eSKate Stone void NativeProcessLinux::WaitForNewThread(::pid_t tid) {
523a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
524426bdf88SPavel Labath 
525a5be48b3SPavel Labath   if (GetThreadByID(tid)) {
526b9c1b51eSKate Stone     // We are already tracking the thread - we got the event on the new thread
527a5be48b3SPavel Labath     // (see MonitorSignal) before this one. We are done.
528426bdf88SPavel Labath     return;
529426bdf88SPavel Labath   }
530426bdf88SPavel Labath 
531426bdf88SPavel Labath   // The thread is not tracked yet, let's wait for it to appear.
532426bdf88SPavel Labath   int status = -1;
533a6321a8eSPavel Labath   LLDB_LOG(log,
534a6321a8eSPavel Labath            "received thread creation event for tid {0}. tid not tracked "
535a6321a8eSPavel Labath            "yet, waiting for thread to appear...",
536a6321a8eSPavel Labath            tid);
537c1a6b128SPavel Labath   ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, &status, __WALL);
538b9c1b51eSKate Stone   // Since we are waiting on a specific tid, this must be the creation event.
539a6321a8eSPavel Labath   // But let's do some checks just in case.
540426bdf88SPavel Labath   if (wait_pid != tid) {
541a6321a8eSPavel Labath     LLDB_LOG(log,
542a6321a8eSPavel Labath              "waiting for tid {0} failed. Assuming the thread has "
543a6321a8eSPavel Labath              "disappeared in the meantime",
544a6321a8eSPavel Labath              tid);
545426bdf88SPavel Labath     // The only way I know of this could happen is if the whole process was
546b9c1b51eSKate Stone     // SIGKILLed in the mean time. In any case, we can't do anything about that
547b9c1b51eSKate Stone     // now.
548426bdf88SPavel Labath     return;
549426bdf88SPavel Labath   }
550b9c1b51eSKate Stone   if (WIFEXITED(status)) {
551a6321a8eSPavel Labath     LLDB_LOG(log,
552a6321a8eSPavel Labath              "waiting for tid {0} returned an 'exited' event. Not "
553a6321a8eSPavel Labath              "tracking the thread.",
554a6321a8eSPavel Labath              tid);
555426bdf88SPavel Labath     // Also a very improbable event.
556426bdf88SPavel Labath     return;
557426bdf88SPavel Labath   }
558426bdf88SPavel Labath 
559a6321a8eSPavel Labath   LLDB_LOG(log, "pid = {0}: tracking new thread tid {1}", GetID(), tid);
560a5be48b3SPavel Labath   NativeThreadLinux &new_thread = AddThread(tid);
56199e37695SRavitheja Addepally 
562a5be48b3SPavel Labath   ResumeThread(new_thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
563a5be48b3SPavel Labath   ThreadWasCreated(new_thread);
564426bdf88SPavel Labath }
565426bdf88SPavel Labath 
566b9c1b51eSKate Stone void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info,
567b9c1b51eSKate Stone                                         NativeThreadLinux &thread) {
568a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
569b9cc0c75SPavel Labath   const bool is_main_thread = (thread.GetID() == GetID());
570af245d11STodd Fiala 
571b9cc0c75SPavel Labath   assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
572af245d11STodd Fiala 
573b9c1b51eSKate Stone   switch (info.si_code) {
574b9c1b51eSKate Stone   // TODO: these two cases are required if we want to support tracing of the
57505097246SAdrian Prantl   // inferiors' children.  We'd need this to debug a monitor. case (SIGTRAP |
57605097246SAdrian Prantl   // (PTRACE_EVENT_FORK << 8)): case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
577af245d11STodd Fiala 
578b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): {
579b9c1b51eSKate Stone     // This is the notification on the parent thread which informs us of new
58005097246SAdrian Prantl     // thread creation. We don't want to do anything with the parent thread so
58105097246SAdrian Prantl     // we just resume it. In case we want to implement "break on thread
58205097246SAdrian Prantl     // creation" functionality, we would need to stop here.
583af245d11STodd Fiala 
584af245d11STodd Fiala     unsigned long event_message = 0;
585b9c1b51eSKate Stone     if (GetEventMessage(thread.GetID(), &event_message).Fail()) {
586a6321a8eSPavel Labath       LLDB_LOG(log,
587a6321a8eSPavel Labath                "pid {0} received thread creation event but "
588a6321a8eSPavel Labath                "GetEventMessage failed so we don't know the new tid",
589a6321a8eSPavel Labath                thread.GetID());
590426bdf88SPavel Labath     } else
591426bdf88SPavel Labath       WaitForNewThread(event_message);
592af245d11STodd Fiala 
593b9cc0c75SPavel Labath     ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
594af245d11STodd Fiala     break;
595af245d11STodd Fiala   }
596af245d11STodd Fiala 
597b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): {
598a6321a8eSPavel Labath     LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP);
599a9882ceeSTodd Fiala 
6001dbc6c9cSPavel Labath     // Exec clears any pending notifications.
6010e1d729bSPavel Labath     m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
602fa03ad2eSChaoren Lin 
603b9c1b51eSKate Stone     // Remove all but the main thread here.  Linux fork creates a new process
604b9c1b51eSKate Stone     // which only copies the main thread.
605a6321a8eSPavel Labath     LLDB_LOG(log, "exec received, stop tracking all but main thread");
606a9882ceeSTodd Fiala 
607a5be48b3SPavel Labath     for (auto i = m_threads.begin(); i != m_threads.end();) {
608a5be48b3SPavel Labath       if ((*i)->GetID() == GetID())
609a5be48b3SPavel Labath         i = m_threads.erase(i);
610a5be48b3SPavel Labath       else
611a5be48b3SPavel Labath         ++i;
612a9882ceeSTodd Fiala     }
613a5be48b3SPavel Labath     assert(m_threads.size() == 1);
614a5be48b3SPavel Labath     auto *main_thread = static_cast<NativeThreadLinux *>(m_threads[0].get());
615a9882ceeSTodd Fiala 
616a5be48b3SPavel Labath     SetCurrentThreadID(main_thread->GetID());
617a5be48b3SPavel Labath     main_thread->SetStoppedByExec();
618a9882ceeSTodd Fiala 
619fa03ad2eSChaoren Lin     // Tell coordinator about about the "new" (since exec) stopped main thread.
620a5be48b3SPavel Labath     ThreadWasCreated(*main_thread);
621fa03ad2eSChaoren Lin 
622a9882ceeSTodd Fiala     // Let our delegate know we have just exec'd.
623a9882ceeSTodd Fiala     NotifyDidExec();
624a9882ceeSTodd Fiala 
625fa03ad2eSChaoren Lin     // Let the process know we're stopped.
626a5be48b3SPavel Labath     StopRunningThreads(main_thread->GetID());
627a9882ceeSTodd Fiala 
628af245d11STodd Fiala     break;
629a9882ceeSTodd Fiala   }
630af245d11STodd Fiala 
631b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): {
63205097246SAdrian Prantl     // The inferior process or one of its threads is about to exit. We don't
63305097246SAdrian Prantl     // want to do anything with the thread so we just resume it. In case we
63405097246SAdrian Prantl     // want to implement "break on thread exit" functionality, we would need to
63505097246SAdrian Prantl     // stop here.
636fa03ad2eSChaoren Lin 
637af245d11STodd Fiala     unsigned long data = 0;
638b9cc0c75SPavel Labath     if (GetEventMessage(thread.GetID(), &data).Fail())
639af245d11STodd Fiala       data = -1;
640af245d11STodd Fiala 
641a6321a8eSPavel Labath     LLDB_LOG(log,
642a6321a8eSPavel Labath              "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
643a6321a8eSPavel Labath              "WIFSIGNALED={2}, pid = {3}, main_thread = {4}",
644a6321a8eSPavel Labath              data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(),
645a6321a8eSPavel Labath              is_main_thread);
646af245d11STodd Fiala 
64775f47c3aSTodd Fiala 
64886852d36SPavel Labath     StateType state = thread.GetState();
649b9c1b51eSKate Stone     if (!StateIsRunningState(state)) {
650b9c1b51eSKate Stone       // Due to a kernel bug, we may sometimes get this stop after the inferior
651d8b3c1a1SPavel Labath       // gets a SIGKILL. This confuses our state tracking logic in
652d8b3c1a1SPavel Labath       // ResumeThread(), since normally, we should not be receiving any ptrace
65305097246SAdrian Prantl       // events while the inferior is stopped. This makes sure that the
65405097246SAdrian Prantl       // inferior is resumed and exits normally.
65586852d36SPavel Labath       state = eStateRunning;
65686852d36SPavel Labath     }
65786852d36SPavel Labath     ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
658af245d11STodd Fiala 
659af245d11STodd Fiala     break;
660af245d11STodd Fiala   }
661af245d11STodd Fiala 
662af245d11STodd Fiala   case 0:
663c16f5dcaSChaoren Lin   case TRAP_TRACE:  // We receive this on single stepping.
664c16f5dcaSChaoren Lin   case TRAP_HWBKPT: // We receive this on watchpoint hit
66586fd8e45SChaoren Lin   {
666c16f5dcaSChaoren Lin     // If a watchpoint was hit, report it
667c16f5dcaSChaoren Lin     uint32_t wp_index;
668d37349f3SPavel Labath     Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
669b9c1b51eSKate Stone         wp_index, (uintptr_t)info.si_addr);
670a6321a8eSPavel Labath     if (error.Fail())
671a6321a8eSPavel Labath       LLDB_LOG(log,
672a6321a8eSPavel Labath                "received error while checking for watchpoint hits, pid = "
673a6321a8eSPavel Labath                "{0}, error = {1}",
674a6321a8eSPavel Labath                thread.GetID(), error);
675b9c1b51eSKate Stone     if (wp_index != LLDB_INVALID_INDEX32) {
676b9cc0c75SPavel Labath       MonitorWatchpoint(thread, wp_index);
677c16f5dcaSChaoren Lin       break;
678c16f5dcaSChaoren Lin     }
679b9cc0c75SPavel Labath 
680d5ffbad2SOmair Javaid     // If a breakpoint was hit, report it
681d5ffbad2SOmair Javaid     uint32_t bp_index;
682d37349f3SPavel Labath     error = thread.GetRegisterContext().GetHardwareBreakHitIndex(
683d5ffbad2SOmair Javaid         bp_index, (uintptr_t)info.si_addr);
684d5ffbad2SOmair Javaid     if (error.Fail())
685d5ffbad2SOmair Javaid       LLDB_LOG(log, "received error while checking for hardware "
686d5ffbad2SOmair Javaid                     "breakpoint hits, pid = {0}, error = {1}",
687d5ffbad2SOmair Javaid                thread.GetID(), error);
688d5ffbad2SOmair Javaid     if (bp_index != LLDB_INVALID_INDEX32) {
689d5ffbad2SOmair Javaid       MonitorBreakpoint(thread);
690d5ffbad2SOmair Javaid       break;
691d5ffbad2SOmair Javaid     }
692d5ffbad2SOmair Javaid 
693be379e15STamas Berghammer     // Otherwise, report step over
694be379e15STamas Berghammer     MonitorTrace(thread);
695af245d11STodd Fiala     break;
696b9cc0c75SPavel Labath   }
697af245d11STodd Fiala 
698af245d11STodd Fiala   case SI_KERNEL:
69935799963SMohit K. Bhakkad #if defined __mips__
70005097246SAdrian Prantl     // For mips there is no special signal for watchpoint So we check for
70105097246SAdrian Prantl     // watchpoint in kernel trap
70235799963SMohit K. Bhakkad     {
70335799963SMohit K. Bhakkad       // If a watchpoint was hit, report it
70435799963SMohit K. Bhakkad       uint32_t wp_index;
705d37349f3SPavel Labath       Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
706b9c1b51eSKate Stone           wp_index, LLDB_INVALID_ADDRESS);
707a6321a8eSPavel Labath       if (error.Fail())
708a6321a8eSPavel Labath         LLDB_LOG(log,
709a6321a8eSPavel Labath                  "received error while checking for watchpoint hits, pid = "
710a6321a8eSPavel Labath                  "{0}, error = {1}",
711a6321a8eSPavel Labath                  thread.GetID(), error);
712b9c1b51eSKate Stone       if (wp_index != LLDB_INVALID_INDEX32) {
713b9cc0c75SPavel Labath         MonitorWatchpoint(thread, wp_index);
71435799963SMohit K. Bhakkad         break;
71535799963SMohit K. Bhakkad       }
71635799963SMohit K. Bhakkad     }
71735799963SMohit K. Bhakkad // NO BREAK
71835799963SMohit K. Bhakkad #endif
719af245d11STodd Fiala   case TRAP_BRKPT:
720b9cc0c75SPavel Labath     MonitorBreakpoint(thread);
721af245d11STodd Fiala     break;
722af245d11STodd Fiala 
723af245d11STodd Fiala   case SIGTRAP:
724af245d11STodd Fiala   case (SIGTRAP | 0x80):
725a6321a8eSPavel Labath     LLDB_LOG(
726a6321a8eSPavel Labath         log,
727a6321a8eSPavel Labath         "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",
728a6321a8eSPavel Labath         info.si_code, GetID(), thread.GetID());
729fa03ad2eSChaoren Lin 
730af245d11STodd Fiala     // Ignore these signals until we know more about them.
731b9cc0c75SPavel Labath     ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
732af245d11STodd Fiala     break;
733af245d11STodd Fiala 
734af245d11STodd Fiala   default:
73521a365baSPavel Labath     LLDB_LOG(log, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}",
736a6321a8eSPavel Labath              info.si_code, GetID(), thread.GetID());
73721a365baSPavel Labath     MonitorSignal(info, thread, false);
738af245d11STodd Fiala     break;
739af245d11STodd Fiala   }
740af245d11STodd Fiala }
741af245d11STodd Fiala 
742b9c1b51eSKate Stone void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) {
743a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
744a6321a8eSPavel Labath   LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID());
745c16f5dcaSChaoren Lin 
7460e1d729bSPavel Labath   // This thread is currently stopped.
747b9cc0c75SPavel Labath   thread.SetStoppedByTrace();
748c16f5dcaSChaoren Lin 
749b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
750c16f5dcaSChaoren Lin }
751c16f5dcaSChaoren Lin 
752b9c1b51eSKate Stone void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) {
753b9c1b51eSKate Stone   Log *log(
754b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
755a6321a8eSPavel Labath   LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID());
756c16f5dcaSChaoren Lin 
757c16f5dcaSChaoren Lin   // Mark the thread as stopped at breakpoint.
758b9cc0c75SPavel Labath   thread.SetStoppedByBreakpoint();
759aef7908fSPavel Labath   FixupBreakpointPCAsNeeded(thread);
760d8c338d4STamas Berghammer 
761b9c1b51eSKate Stone   if (m_threads_stepping_with_breakpoint.find(thread.GetID()) !=
762b9c1b51eSKate Stone       m_threads_stepping_with_breakpoint.end())
763b9cc0c75SPavel Labath     thread.SetStoppedByTrace();
764c16f5dcaSChaoren Lin 
765b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
766c16f5dcaSChaoren Lin }
767c16f5dcaSChaoren Lin 
768b9c1b51eSKate Stone void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread,
769b9c1b51eSKate Stone                                            uint32_t wp_index) {
770b9c1b51eSKate Stone   Log *log(
771b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
772a6321a8eSPavel Labath   LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}",
773a6321a8eSPavel Labath            thread.GetID(), wp_index);
774c16f5dcaSChaoren Lin 
77505097246SAdrian Prantl   // Mark the thread as stopped at watchpoint. The address is at
77605097246SAdrian Prantl   // (lldb::addr_t)info->si_addr if we need it.
777f9077782SPavel Labath   thread.SetStoppedByWatchpoint(wp_index);
778c16f5dcaSChaoren Lin 
779b9c1b51eSKate Stone   // We need to tell all other running threads before we notify the delegate
780b9c1b51eSKate Stone   // about this stop.
781f9077782SPavel Labath   StopRunningThreads(thread.GetID());
782c16f5dcaSChaoren Lin }
783c16f5dcaSChaoren Lin 
784b9c1b51eSKate Stone void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
785b9c1b51eSKate Stone                                        NativeThreadLinux &thread, bool exited) {
786b9cc0c75SPavel Labath   const int signo = info.si_signo;
787b9cc0c75SPavel Labath   const bool is_from_llgs = info.si_pid == getpid();
788af245d11STodd Fiala 
789a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
790af245d11STodd Fiala 
791af245d11STodd Fiala   // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
79205097246SAdrian Prantl   // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a kill(2)
79305097246SAdrian Prantl   // or raise(3).  Similarly for tgkill(2) on Linux.
794af245d11STodd Fiala   //
795af245d11STodd Fiala   // IOW, user generated signals never generate what we consider to be a
796af245d11STodd Fiala   // "crash".
797af245d11STodd Fiala   //
798af245d11STodd Fiala   // Similarly, ACK signals generated by this monitor.
799af245d11STodd Fiala 
800af245d11STodd Fiala   // Handle the signal.
801a6321a8eSPavel Labath   LLDB_LOG(log,
802a6321a8eSPavel Labath            "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
803a6321a8eSPavel Labath            "waitpid pid = {4})",
804a6321a8eSPavel Labath            Host::GetSignalAsCString(signo), signo, info.si_code,
805b9cc0c75SPavel Labath            thread.GetID());
80658a2f669STodd Fiala 
80758a2f669STodd Fiala   // Check for thread stop notification.
808b9c1b51eSKate Stone   if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) {
809af245d11STodd Fiala     // This is a tgkill()-based stop.
810a6321a8eSPavel Labath     LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID());
811fa03ad2eSChaoren Lin 
81205097246SAdrian Prantl     // Check that we're not already marked with a stop reason. Note this thread
81305097246SAdrian Prantl     // really shouldn't already be marked as stopped - if we were, that would
81405097246SAdrian Prantl     // imply that the kernel signaled us with the thread stopping which we
81505097246SAdrian Prantl     // handled and marked as stopped, and that, without an intervening resume,
81605097246SAdrian Prantl     // we received another stop.  It is more likely that we are missing the
81705097246SAdrian Prantl     // marking of a run state somewhere if we find that the thread was marked
81805097246SAdrian Prantl     // as stopped.
819b9cc0c75SPavel Labath     const StateType thread_state = thread.GetState();
820b9c1b51eSKate Stone     if (!StateIsStoppedState(thread_state, false)) {
821ed89c7feSPavel Labath       // An inferior thread has stopped because of a SIGSTOP we have sent it.
822b9c1b51eSKate Stone       // Generally, these are not important stops and we don't want to report
823a6321a8eSPavel Labath       // them as they are just used to stop other threads when one thread (the
824a6321a8eSPavel Labath       // one with the *real* stop reason) hits a breakpoint (watchpoint,
82505097246SAdrian Prantl       // etc...). However, in the case of an asynchronous Interrupt(), this
82605097246SAdrian Prantl       // *is* the real stop reason, so we leave the signal intact if this is
82705097246SAdrian Prantl       // the thread that was chosen as the triggering thread.
828b9c1b51eSKate Stone       if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
829b9cc0c75SPavel Labath         if (m_pending_notification_tid == thread.GetID())
830b9cc0c75SPavel Labath           thread.SetStoppedBySignal(SIGSTOP, &info);
831ed89c7feSPavel Labath         else
832b9cc0c75SPavel Labath           thread.SetStoppedWithNoReason();
833ed89c7feSPavel Labath 
834b9cc0c75SPavel Labath         SetCurrentThreadID(thread.GetID());
8350e1d729bSPavel Labath         SignalIfAllThreadsStopped();
836b9c1b51eSKate Stone       } else {
8370e1d729bSPavel Labath         // We can end up here if stop was initiated by LLGS but by this time a
8380e1d729bSPavel Labath         // thread stop has occurred - maybe initiated by another event.
83997206d57SZachary Turner         Status error = ResumeThread(thread, thread.GetState(), 0);
840a6321a8eSPavel Labath         if (error.Fail())
841a6321a8eSPavel Labath           LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(),
842a6321a8eSPavel Labath                    error);
8430e1d729bSPavel Labath       }
844b9c1b51eSKate Stone     } else {
845a6321a8eSPavel Labath       LLDB_LOG(log,
846a6321a8eSPavel Labath                "pid {0} tid {1}, thread was already marked as a stopped "
847a6321a8eSPavel Labath                "state (state={2}), leaving stop signal as is",
8488198db30SPavel Labath                GetID(), thread.GetID(), thread_state);
8490e1d729bSPavel Labath       SignalIfAllThreadsStopped();
850af245d11STodd Fiala     }
851af245d11STodd Fiala 
85258a2f669STodd Fiala     // Done handling.
853af245d11STodd Fiala     return;
854af245d11STodd Fiala   }
855af245d11STodd Fiala 
85605097246SAdrian Prantl   // Check if debugger should stop at this signal or just ignore it and resume
85705097246SAdrian Prantl   // the inferior.
8584a705e7eSPavel Labath   if (m_signals_to_ignore.find(signo) != m_signals_to_ignore.end()) {
8594a705e7eSPavel Labath      ResumeThread(thread, thread.GetState(), signo);
8604a705e7eSPavel Labath      return;
8614a705e7eSPavel Labath   }
8624a705e7eSPavel Labath 
86386fd8e45SChaoren Lin   // This thread is stopped.
864a6321a8eSPavel Labath   LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo));
865b9cc0c75SPavel Labath   thread.SetStoppedBySignal(signo, &info);
86686fd8e45SChaoren Lin 
86786fd8e45SChaoren Lin   // Send a stop to the debugger after we get all other threads to stop.
868b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
869511e5cdcSTodd Fiala }
870af245d11STodd Fiala 
871e7708688STamas Berghammer namespace {
872e7708688STamas Berghammer 
873b9c1b51eSKate Stone struct EmulatorBaton {
874d37349f3SPavel Labath   NativeProcessLinux &m_process;
875d37349f3SPavel Labath   NativeRegisterContext &m_reg_context;
8766648fcc3SPavel Labath 
8776648fcc3SPavel Labath   // eRegisterKindDWARF -> RegsiterValue
8786648fcc3SPavel Labath   std::unordered_map<uint32_t, RegisterValue> m_register_values;
879e7708688STamas Berghammer 
880d37349f3SPavel Labath   EmulatorBaton(NativeProcessLinux &process, NativeRegisterContext &reg_context)
881b9c1b51eSKate Stone       : m_process(process), m_reg_context(reg_context) {}
882e7708688STamas Berghammer };
883e7708688STamas Berghammer 
884e7708688STamas Berghammer } // anonymous namespace
885e7708688STamas Berghammer 
886b9c1b51eSKate Stone static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
887e7708688STamas Berghammer                                  const EmulateInstruction::Context &context,
888b9c1b51eSKate Stone                                  lldb::addr_t addr, void *dst, size_t length) {
889e7708688STamas Berghammer   EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
890e7708688STamas Berghammer 
8913eb4b458SChaoren Lin   size_t bytes_read;
892d37349f3SPavel Labath   emulator_baton->m_process.ReadMemory(addr, dst, length, bytes_read);
893e7708688STamas Berghammer   return bytes_read;
894e7708688STamas Berghammer }
895e7708688STamas Berghammer 
896b9c1b51eSKate Stone static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
897e7708688STamas Berghammer                                  const RegisterInfo *reg_info,
898b9c1b51eSKate Stone                                  RegisterValue &reg_value) {
899e7708688STamas Berghammer   EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
900e7708688STamas Berghammer 
901b9c1b51eSKate Stone   auto it = emulator_baton->m_register_values.find(
902b9c1b51eSKate Stone       reg_info->kinds[eRegisterKindDWARF]);
903b9c1b51eSKate Stone   if (it != emulator_baton->m_register_values.end()) {
9046648fcc3SPavel Labath     reg_value = it->second;
9056648fcc3SPavel Labath     return true;
9066648fcc3SPavel Labath   }
9076648fcc3SPavel Labath 
90805097246SAdrian Prantl   // The emulator only fill in the dwarf regsiter numbers (and in some case the
90905097246SAdrian Prantl   // generic register numbers). Get the full register info from the register
91005097246SAdrian Prantl   // context based on the dwarf register numbers.
911b9c1b51eSKate Stone   const RegisterInfo *full_reg_info =
912d37349f3SPavel Labath       emulator_baton->m_reg_context.GetRegisterInfo(
913e7708688STamas Berghammer           eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
914e7708688STamas Berghammer 
91597206d57SZachary Turner   Status error =
916d37349f3SPavel Labath       emulator_baton->m_reg_context.ReadRegister(full_reg_info, reg_value);
9176648fcc3SPavel Labath   if (error.Success())
9186648fcc3SPavel Labath     return true;
919cdc22a88SMohit K. Bhakkad 
9206648fcc3SPavel Labath   return false;
921e7708688STamas Berghammer }
922e7708688STamas Berghammer 
923b9c1b51eSKate Stone static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
924e7708688STamas Berghammer                                   const EmulateInstruction::Context &context,
925e7708688STamas Berghammer                                   const RegisterInfo *reg_info,
926b9c1b51eSKate Stone                                   const RegisterValue &reg_value) {
927e7708688STamas Berghammer   EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
928b9c1b51eSKate Stone   emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
929b9c1b51eSKate Stone       reg_value;
930e7708688STamas Berghammer   return true;
931e7708688STamas Berghammer }
932e7708688STamas Berghammer 
933b9c1b51eSKate Stone static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
934e7708688STamas Berghammer                                   const EmulateInstruction::Context &context,
935b9c1b51eSKate Stone                                   lldb::addr_t addr, const void *dst,
936b9c1b51eSKate Stone                                   size_t length) {
937e7708688STamas Berghammer   return length;
938e7708688STamas Berghammer }
939e7708688STamas Berghammer 
940d37349f3SPavel Labath static lldb::addr_t ReadFlags(NativeRegisterContext &regsiter_context) {
941d37349f3SPavel Labath   const RegisterInfo *flags_info = regsiter_context.GetRegisterInfo(
942e7708688STamas Berghammer       eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
943d37349f3SPavel Labath   return regsiter_context.ReadRegisterAsUnsigned(flags_info,
944b9c1b51eSKate Stone                                                  LLDB_INVALID_ADDRESS);
945e7708688STamas Berghammer }
946e7708688STamas Berghammer 
94797206d57SZachary Turner Status
94897206d57SZachary Turner NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadLinux &thread) {
94997206d57SZachary Turner   Status error;
950d37349f3SPavel Labath   NativeRegisterContext& register_context = thread.GetRegisterContext();
951e7708688STamas Berghammer 
952e7708688STamas Berghammer   std::unique_ptr<EmulateInstruction> emulator_ap(
953b9c1b51eSKate Stone       EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying,
954b9c1b51eSKate Stone                                      nullptr));
955e7708688STamas Berghammer 
956e7708688STamas Berghammer   if (emulator_ap == nullptr)
95797206d57SZachary Turner     return Status("Instruction emulator not found!");
958e7708688STamas Berghammer 
959d37349f3SPavel Labath   EmulatorBaton baton(*this, register_context);
960e7708688STamas Berghammer   emulator_ap->SetBaton(&baton);
961e7708688STamas Berghammer   emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
962e7708688STamas Berghammer   emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
963e7708688STamas Berghammer   emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
964e7708688STamas Berghammer   emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
965e7708688STamas Berghammer 
966e7708688STamas Berghammer   if (!emulator_ap->ReadInstruction())
96797206d57SZachary Turner     return Status("Read instruction failed!");
968e7708688STamas Berghammer 
969b9c1b51eSKate Stone   bool emulation_result =
970b9c1b51eSKate Stone       emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
9716648fcc3SPavel Labath 
972d37349f3SPavel Labath   const RegisterInfo *reg_info_pc = register_context.GetRegisterInfo(
973b9c1b51eSKate Stone       eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
974d37349f3SPavel Labath   const RegisterInfo *reg_info_flags = register_context.GetRegisterInfo(
975b9c1b51eSKate Stone       eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
9766648fcc3SPavel Labath 
977b9c1b51eSKate Stone   auto pc_it =
978b9c1b51eSKate Stone       baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
979b9c1b51eSKate Stone   auto flags_it =
980b9c1b51eSKate Stone       baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
9816648fcc3SPavel Labath 
982e7708688STamas Berghammer   lldb::addr_t next_pc;
983e7708688STamas Berghammer   lldb::addr_t next_flags;
984b9c1b51eSKate Stone   if (emulation_result) {
985b9c1b51eSKate Stone     assert(pc_it != baton.m_register_values.end() &&
986b9c1b51eSKate Stone            "Emulation was successfull but PC wasn't updated");
9876648fcc3SPavel Labath     next_pc = pc_it->second.GetAsUInt64();
9886648fcc3SPavel Labath 
9896648fcc3SPavel Labath     if (flags_it != baton.m_register_values.end())
9906648fcc3SPavel Labath       next_flags = flags_it->second.GetAsUInt64();
991e7708688STamas Berghammer     else
992d37349f3SPavel Labath       next_flags = ReadFlags(register_context);
993b9c1b51eSKate Stone   } else if (pc_it == baton.m_register_values.end()) {
99405097246SAdrian Prantl     // Emulate instruction failed and it haven't changed PC. Advance PC with
99505097246SAdrian Prantl     // the size of the current opcode because the emulation of all
996e7708688STamas Berghammer     // PC modifying instruction should be successful. The failure most
997e7708688STamas Berghammer     // likely caused by a not supported instruction which don't modify PC.
998d37349f3SPavel Labath     next_pc = register_context.GetPC() + emulator_ap->GetOpcode().GetByteSize();
999d37349f3SPavel Labath     next_flags = ReadFlags(register_context);
1000b9c1b51eSKate Stone   } else {
1001e7708688STamas Berghammer     // The instruction emulation failed after it modified the PC. It is an
1002e7708688STamas Berghammer     // unknown error where we can't continue because the next instruction is
1003e7708688STamas Berghammer     // modifying the PC but we don't  know how.
100497206d57SZachary Turner     return Status("Instruction emulation failed unexpectedly.");
1005e7708688STamas Berghammer   }
1006e7708688STamas Berghammer 
1007b9c1b51eSKate Stone   if (m_arch.GetMachine() == llvm::Triple::arm) {
1008b9c1b51eSKate Stone     if (next_flags & 0x20) {
1009e7708688STamas Berghammer       // Thumb mode
1010e7708688STamas Berghammer       error = SetSoftwareBreakpoint(next_pc, 2);
1011b9c1b51eSKate Stone     } else {
1012e7708688STamas Berghammer       // Arm mode
1013e7708688STamas Berghammer       error = SetSoftwareBreakpoint(next_pc, 4);
1014e7708688STamas Berghammer     }
1015b9c1b51eSKate Stone   } else if (m_arch.GetMachine() == llvm::Triple::mips64 ||
1016b9c1b51eSKate Stone              m_arch.GetMachine() == llvm::Triple::mips64el ||
1017b9c1b51eSKate Stone              m_arch.GetMachine() == llvm::Triple::mips ||
1018aae0a752SEugene Zemtsov              m_arch.GetMachine() == llvm::Triple::mipsel ||
1019aae0a752SEugene Zemtsov              m_arch.GetMachine() == llvm::Triple::ppc64le)
1020cdc22a88SMohit K. Bhakkad     error = SetSoftwareBreakpoint(next_pc, 4);
1021b9c1b51eSKate Stone   else {
1022e7708688STamas Berghammer     // No size hint is given for the next breakpoint
1023e7708688STamas Berghammer     error = SetSoftwareBreakpoint(next_pc, 0);
1024e7708688STamas Berghammer   }
1025e7708688STamas Berghammer 
102605097246SAdrian Prantl   // If setting the breakpoint fails because next_pc is out of the address
102705097246SAdrian Prantl   // space, ignore it and let the debugee segfault.
102842eb6908SPavel Labath   if (error.GetError() == EIO || error.GetError() == EFAULT) {
102997206d57SZachary Turner     return Status();
103042eb6908SPavel Labath   } else if (error.Fail())
1031e7708688STamas Berghammer     return error;
1032e7708688STamas Berghammer 
1033b9cc0c75SPavel Labath   m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
1034e7708688STamas Berghammer 
103597206d57SZachary Turner   return Status();
1036e7708688STamas Berghammer }
1037e7708688STamas Berghammer 
1038b9c1b51eSKate Stone bool NativeProcessLinux::SupportHardwareSingleStepping() const {
1039b9c1b51eSKate Stone   if (m_arch.GetMachine() == llvm::Triple::arm ||
1040b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mips64 ||
1041b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mips64el ||
1042b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mips ||
1043b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mipsel)
1044cdc22a88SMohit K. Bhakkad     return false;
1045cdc22a88SMohit K. Bhakkad   return true;
1046e7708688STamas Berghammer }
1047e7708688STamas Berghammer 
104897206d57SZachary Turner Status NativeProcessLinux::Resume(const ResumeActionList &resume_actions) {
1049a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1050a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0}", GetID());
1051af245d11STodd Fiala 
1052e7708688STamas Berghammer   bool software_single_step = !SupportHardwareSingleStepping();
1053af245d11STodd Fiala 
1054b9c1b51eSKate Stone   if (software_single_step) {
1055a5be48b3SPavel Labath     for (const auto &thread : m_threads) {
1056a5be48b3SPavel Labath       assert(thread && "thread list should not contain NULL threads");
1057e7708688STamas Berghammer 
1058b9c1b51eSKate Stone       const ResumeAction *const action =
1059a5be48b3SPavel Labath           resume_actions.GetActionForThread(thread->GetID(), true);
1060e7708688STamas Berghammer       if (action == nullptr)
1061e7708688STamas Berghammer         continue;
1062e7708688STamas Berghammer 
1063b9c1b51eSKate Stone       if (action->state == eStateStepping) {
106497206d57SZachary Turner         Status error = SetupSoftwareSingleStepping(
1065a5be48b3SPavel Labath             static_cast<NativeThreadLinux &>(*thread));
1066e7708688STamas Berghammer         if (error.Fail())
1067e7708688STamas Berghammer           return error;
1068e7708688STamas Berghammer       }
1069e7708688STamas Berghammer     }
1070e7708688STamas Berghammer   }
1071e7708688STamas Berghammer 
1072a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
1073a5be48b3SPavel Labath     assert(thread && "thread list should not contain NULL threads");
1074af245d11STodd Fiala 
1075b9c1b51eSKate Stone     const ResumeAction *const action =
1076a5be48b3SPavel Labath         resume_actions.GetActionForThread(thread->GetID(), true);
10776a196ce6SChaoren Lin 
1078b9c1b51eSKate Stone     if (action == nullptr) {
1079a6321a8eSPavel Labath       LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
1080a5be48b3SPavel Labath                thread->GetID());
10816a196ce6SChaoren Lin       continue;
10826a196ce6SChaoren Lin     }
1083af245d11STodd Fiala 
1084a6321a8eSPavel Labath     LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}",
1085a5be48b3SPavel Labath              action->state, GetID(), thread->GetID());
1086af245d11STodd Fiala 
1087b9c1b51eSKate Stone     switch (action->state) {
1088af245d11STodd Fiala     case eStateRunning:
1089b9c1b51eSKate Stone     case eStateStepping: {
1090af245d11STodd Fiala       // Run the thread, possibly feeding it the signal.
1091fa03ad2eSChaoren Lin       const int signo = action->signal;
1092a5be48b3SPavel Labath       ResumeThread(static_cast<NativeThreadLinux &>(*thread), action->state,
1093b9c1b51eSKate Stone                    signo);
1094af245d11STodd Fiala       break;
1095ae29d395SChaoren Lin     }
1096af245d11STodd Fiala 
1097af245d11STodd Fiala     case eStateSuspended:
1098af245d11STodd Fiala     case eStateStopped:
1099a6321a8eSPavel Labath       llvm_unreachable("Unexpected state");
1100af245d11STodd Fiala 
1101af245d11STodd Fiala     default:
110297206d57SZachary Turner       return Status("NativeProcessLinux::%s (): unexpected state %s specified "
1103b9c1b51eSKate Stone                     "for pid %" PRIu64 ", tid %" PRIu64,
1104b9c1b51eSKate Stone                     __FUNCTION__, StateAsCString(action->state), GetID(),
1105a5be48b3SPavel Labath                     thread->GetID());
1106af245d11STodd Fiala     }
1107af245d11STodd Fiala   }
1108af245d11STodd Fiala 
110997206d57SZachary Turner   return Status();
1110af245d11STodd Fiala }
1111af245d11STodd Fiala 
111297206d57SZachary Turner Status NativeProcessLinux::Halt() {
111397206d57SZachary Turner   Status error;
1114af245d11STodd Fiala 
1115af245d11STodd Fiala   if (kill(GetID(), SIGSTOP) != 0)
1116af245d11STodd Fiala     error.SetErrorToErrno();
1117af245d11STodd Fiala 
1118af245d11STodd Fiala   return error;
1119af245d11STodd Fiala }
1120af245d11STodd Fiala 
112197206d57SZachary Turner Status NativeProcessLinux::Detach() {
112297206d57SZachary Turner   Status error;
1123af245d11STodd Fiala 
1124af245d11STodd Fiala   // Stop monitoring the inferior.
112519cbe96aSPavel Labath   m_sigchld_handle.reset();
1126af245d11STodd Fiala 
11277a9495bcSPavel Labath   // Tell ptrace to detach from the process.
11287a9495bcSPavel Labath   if (GetID() == LLDB_INVALID_PROCESS_ID)
11297a9495bcSPavel Labath     return error;
11307a9495bcSPavel Labath 
1131a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
1132a5be48b3SPavel Labath     Status e = Detach(thread->GetID());
11337a9495bcSPavel Labath     if (e.Fail())
1134b9c1b51eSKate Stone       error =
1135b9c1b51eSKate Stone           e; // Save the error, but still attempt to detach from other threads.
11367a9495bcSPavel Labath   }
11377a9495bcSPavel Labath 
113899e37695SRavitheja Addepally   m_processor_trace_monitor.clear();
113999e37695SRavitheja Addepally   m_pt_proces_trace_id = LLDB_INVALID_UID;
114099e37695SRavitheja Addepally 
1141af245d11STodd Fiala   return error;
1142af245d11STodd Fiala }
1143af245d11STodd Fiala 
114497206d57SZachary Turner Status NativeProcessLinux::Signal(int signo) {
114597206d57SZachary Turner   Status error;
1146af245d11STodd Fiala 
1147a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1148a6321a8eSPavel Labath   LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo,
1149a6321a8eSPavel Labath            Host::GetSignalAsCString(signo), GetID());
1150af245d11STodd Fiala 
1151af245d11STodd Fiala   if (kill(GetID(), signo))
1152af245d11STodd Fiala     error.SetErrorToErrno();
1153af245d11STodd Fiala 
1154af245d11STodd Fiala   return error;
1155af245d11STodd Fiala }
1156af245d11STodd Fiala 
115797206d57SZachary Turner Status NativeProcessLinux::Interrupt() {
115805097246SAdrian Prantl   // Pick a running thread (or if none, a not-dead stopped thread) as the
115905097246SAdrian Prantl   // chosen thread that will be the stop-reason thread.
1160a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1161e9547b80SChaoren Lin 
1162a5be48b3SPavel Labath   NativeThreadProtocol *running_thread = nullptr;
1163a5be48b3SPavel Labath   NativeThreadProtocol *stopped_thread = nullptr;
1164e9547b80SChaoren Lin 
1165a6321a8eSPavel Labath   LLDB_LOG(log, "selecting running thread for interrupt target");
1166a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
116705097246SAdrian Prantl     // If we have a running or stepping thread, we'll call that the target of
116805097246SAdrian Prantl     // the interrupt.
1169a5be48b3SPavel Labath     const auto thread_state = thread->GetState();
1170b9c1b51eSKate Stone     if (thread_state == eStateRunning || thread_state == eStateStepping) {
1171a5be48b3SPavel Labath       running_thread = thread.get();
1172e9547b80SChaoren Lin       break;
1173a5be48b3SPavel Labath     } else if (!stopped_thread && StateIsStoppedState(thread_state, true)) {
117405097246SAdrian Prantl       // Remember the first non-dead stopped thread.  We'll use that as a
117505097246SAdrian Prantl       // backup if there are no running threads.
1176a5be48b3SPavel Labath       stopped_thread = thread.get();
1177e9547b80SChaoren Lin     }
1178e9547b80SChaoren Lin   }
1179e9547b80SChaoren Lin 
1180a5be48b3SPavel Labath   if (!running_thread && !stopped_thread) {
118197206d57SZachary Turner     Status error("found no running/stepping or live stopped threads as target "
1182b9c1b51eSKate Stone                  "for interrupt");
1183a6321a8eSPavel Labath     LLDB_LOG(log, "skipping due to error: {0}", error);
11845830aa75STamas Berghammer 
1185e9547b80SChaoren Lin     return error;
1186e9547b80SChaoren Lin   }
1187e9547b80SChaoren Lin 
1188a5be48b3SPavel Labath   NativeThreadProtocol *deferred_signal_thread =
1189a5be48b3SPavel Labath       running_thread ? running_thread : stopped_thread;
1190e9547b80SChaoren Lin 
1191a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(),
1192a5be48b3SPavel Labath            running_thread ? "running" : "stopped",
1193a5be48b3SPavel Labath            deferred_signal_thread->GetID());
1194e9547b80SChaoren Lin 
1195a5be48b3SPavel Labath   StopRunningThreads(deferred_signal_thread->GetID());
119645f5cb31SPavel Labath 
119797206d57SZachary Turner   return Status();
1198e9547b80SChaoren Lin }
1199e9547b80SChaoren Lin 
120097206d57SZachary Turner Status NativeProcessLinux::Kill() {
1201a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1202a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0}", GetID());
1203af245d11STodd Fiala 
120497206d57SZachary Turner   Status error;
1205af245d11STodd Fiala 
1206b9c1b51eSKate Stone   switch (m_state) {
1207af245d11STodd Fiala   case StateType::eStateInvalid:
1208af245d11STodd Fiala   case StateType::eStateExited:
1209af245d11STodd Fiala   case StateType::eStateCrashed:
1210af245d11STodd Fiala   case StateType::eStateDetached:
1211af245d11STodd Fiala   case StateType::eStateUnloaded:
1212af245d11STodd Fiala     // Nothing to do - the process is already dead.
1213a6321a8eSPavel Labath     LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
12148198db30SPavel Labath              m_state);
1215af245d11STodd Fiala     return error;
1216af245d11STodd Fiala 
1217af245d11STodd Fiala   case StateType::eStateConnected:
1218af245d11STodd Fiala   case StateType::eStateAttaching:
1219af245d11STodd Fiala   case StateType::eStateLaunching:
1220af245d11STodd Fiala   case StateType::eStateStopped:
1221af245d11STodd Fiala   case StateType::eStateRunning:
1222af245d11STodd Fiala   case StateType::eStateStepping:
1223af245d11STodd Fiala   case StateType::eStateSuspended:
1224af245d11STodd Fiala     // We can try to kill a process in these states.
1225af245d11STodd Fiala     break;
1226af245d11STodd Fiala   }
1227af245d11STodd Fiala 
1228b9c1b51eSKate Stone   if (kill(GetID(), SIGKILL) != 0) {
1229af245d11STodd Fiala     error.SetErrorToErrno();
1230af245d11STodd Fiala     return error;
1231af245d11STodd Fiala   }
1232af245d11STodd Fiala 
1233af245d11STodd Fiala   return error;
1234af245d11STodd Fiala }
1235af245d11STodd Fiala 
123697206d57SZachary Turner Status NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr,
1237b9c1b51eSKate Stone                                                MemoryRegionInfo &range_info) {
1238b9c1b51eSKate Stone   // FIXME review that the final memory region returned extends to the end of
1239b9c1b51eSKate Stone   // the virtual address space,
1240af245d11STodd Fiala   // with no perms if it is not mapped.
1241af245d11STodd Fiala 
124205097246SAdrian Prantl   // Use an approach that reads memory regions from /proc/{pid}/maps. Assume
124305097246SAdrian Prantl   // proc maps entries are in ascending order.
1244af245d11STodd Fiala   // FIXME assert if we find differently.
1245af245d11STodd Fiala 
1246b9c1b51eSKate Stone   if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
1247af245d11STodd Fiala     // We're done.
124897206d57SZachary Turner     return Status("unsupported");
1249af245d11STodd Fiala   }
1250af245d11STodd Fiala 
125197206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
1252b9c1b51eSKate Stone   if (error.Fail()) {
1253af245d11STodd Fiala     return error;
1254af245d11STodd Fiala   }
1255af245d11STodd Fiala 
1256af245d11STodd Fiala   lldb::addr_t prev_base_address = 0;
1257af245d11STodd Fiala 
1258b9c1b51eSKate Stone   // FIXME start by finding the last region that is <= target address using
1259b9c1b51eSKate Stone   // binary search.  Data is sorted.
1260af245d11STodd Fiala   // There can be a ton of regions on pthreads apps with lots of threads.
1261b9c1b51eSKate Stone   for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1262b9c1b51eSKate Stone        ++it) {
1263a6f5795aSTamas Berghammer     MemoryRegionInfo &proc_entry_info = it->first;
1264af245d11STodd Fiala 
1265af245d11STodd Fiala     // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1266b9c1b51eSKate Stone     assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
1267b9c1b51eSKate Stone            "descending /proc/pid/maps entries detected, unexpected");
1268af245d11STodd Fiala     prev_base_address = proc_entry_info.GetRange().GetRangeBase();
1269b1554311SHafiz Abid Qadeer     UNUSED_IF_ASSERT_DISABLED(prev_base_address);
1270af245d11STodd Fiala 
1271b9c1b51eSKate Stone     // If the target address comes before this entry, indicate distance to next
1272b9c1b51eSKate Stone     // region.
1273b9c1b51eSKate Stone     if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1274af245d11STodd Fiala       range_info.GetRange().SetRangeBase(load_addr);
1275b9c1b51eSKate Stone       range_info.GetRange().SetByteSize(
1276b9c1b51eSKate Stone           proc_entry_info.GetRange().GetRangeBase() - load_addr);
1277af245d11STodd Fiala       range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1278af245d11STodd Fiala       range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1279af245d11STodd Fiala       range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1280ad007563SHoward Hellyer       range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1281af245d11STodd Fiala 
1282af245d11STodd Fiala       return error;
1283b9c1b51eSKate Stone     } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1284af245d11STodd Fiala       // The target address is within the memory region we're processing here.
1285af245d11STodd Fiala       range_info = proc_entry_info;
1286af245d11STodd Fiala       return error;
1287af245d11STodd Fiala     }
1288af245d11STodd Fiala 
1289b9c1b51eSKate Stone     // The target memory address comes somewhere after the region we just
1290b9c1b51eSKate Stone     // parsed.
1291af245d11STodd Fiala   }
1292af245d11STodd Fiala 
1293b9c1b51eSKate Stone   // If we made it here, we didn't find an entry that contained the given
129405097246SAdrian Prantl   // address. Return the load_addr as start and the amount of bytes betwwen
129505097246SAdrian Prantl   // load address and the end of the memory as size.
129609839c33STamas Berghammer   range_info.GetRange().SetRangeBase(load_addr);
1297ad007563SHoward Hellyer   range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
129809839c33STamas Berghammer   range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
129909839c33STamas Berghammer   range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
130009839c33STamas Berghammer   range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1301ad007563SHoward Hellyer   range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1302af245d11STodd Fiala   return error;
1303af245d11STodd Fiala }
1304af245d11STodd Fiala 
130597206d57SZachary Turner Status NativeProcessLinux::PopulateMemoryRegionCache() {
1306a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1307a6f5795aSTamas Berghammer 
1308a6f5795aSTamas Berghammer   // If our cache is empty, pull the latest.  There should always be at least
1309a6f5795aSTamas Berghammer   // one memory region if memory region handling is supported.
1310a6f5795aSTamas Berghammer   if (!m_mem_region_cache.empty()) {
1311a6321a8eSPavel Labath     LLDB_LOG(log, "reusing {0} cached memory region entries",
1312a6321a8eSPavel Labath              m_mem_region_cache.size());
131397206d57SZachary Turner     return Status();
1314a6f5795aSTamas Berghammer   }
1315a6f5795aSTamas Berghammer 
131615930862SPavel Labath   auto BufferOrError = getProcFile(GetID(), "maps");
131715930862SPavel Labath   if (!BufferOrError) {
131815930862SPavel Labath     m_supports_mem_region = LazyBool::eLazyBoolNo;
131915930862SPavel Labath     return BufferOrError.getError();
132015930862SPavel Labath   }
1321*c8e364e8SPavel Labath   Status Result;
1322*c8e364e8SPavel Labath   ParseLinuxMapRegions(BufferOrError.get()->getBuffer(),
1323*c8e364e8SPavel Labath                        [&](const MemoryRegionInfo &Info, const Status &ST) {
1324*c8e364e8SPavel Labath                          if (ST.Success()) {
1325*c8e364e8SPavel Labath                            FileSpec file_spec(Info.GetName().GetCString());
13268f3be7a3SJonas Devlieghere                            FileSystem::Instance().Resolve(file_spec);
1327*c8e364e8SPavel Labath                            m_mem_region_cache.emplace_back(Info, file_spec);
1328*c8e364e8SPavel Labath                            return true;
1329*c8e364e8SPavel Labath                          } else {
1330*c8e364e8SPavel Labath                            m_supports_mem_region = LazyBool::eLazyBoolNo;
1331*c8e364e8SPavel Labath                            LLDB_LOG(log, "failed to parse proc maps: {0}", ST);
1332*c8e364e8SPavel Labath                            Result = ST;
1333*c8e364e8SPavel Labath                            return false;
1334a6f5795aSTamas Berghammer                          }
1335*c8e364e8SPavel Labath                        });
1336*c8e364e8SPavel Labath   if (Result.Fail())
1337*c8e364e8SPavel Labath     return Result;
1338a6f5795aSTamas Berghammer 
133915930862SPavel Labath   if (m_mem_region_cache.empty()) {
1340a6f5795aSTamas Berghammer     // No entries after attempting to read them.  This shouldn't happen if
134105097246SAdrian Prantl     // /proc/{pid}/maps is supported. Assume we don't support map entries via
134205097246SAdrian Prantl     // procfs.
134315930862SPavel Labath     m_supports_mem_region = LazyBool::eLazyBoolNo;
1344a6321a8eSPavel Labath     LLDB_LOG(log,
1345a6321a8eSPavel Labath              "failed to find any procfs maps entries, assuming no support "
1346a6321a8eSPavel Labath              "for memory region metadata retrieval");
134797206d57SZachary Turner     return Status("not supported");
1348a6f5795aSTamas Berghammer   }
1349a6f5795aSTamas Berghammer 
1350a6321a8eSPavel Labath   LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps",
1351a6321a8eSPavel Labath            m_mem_region_cache.size(), GetID());
1352a6f5795aSTamas Berghammer 
1353a6f5795aSTamas Berghammer   // We support memory retrieval, remember that.
1354a6f5795aSTamas Berghammer   m_supports_mem_region = LazyBool::eLazyBoolYes;
135597206d57SZachary Turner   return Status();
1356a6f5795aSTamas Berghammer }
1357a6f5795aSTamas Berghammer 
1358b9c1b51eSKate Stone void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
1359a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1360a6321a8eSPavel Labath   LLDB_LOG(log, "newBumpId={0}", newBumpId);
1361a6321a8eSPavel Labath   LLDB_LOG(log, "clearing {0} entries from memory region cache",
1362a6321a8eSPavel Labath            m_mem_region_cache.size());
1363af245d11STodd Fiala   m_mem_region_cache.clear();
1364af245d11STodd Fiala }
1365af245d11STodd Fiala 
136697206d57SZachary Turner Status NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions,
1367b9c1b51eSKate Stone                                           lldb::addr_t &addr) {
1368af245d11STodd Fiala // FIXME implementing this requires the equivalent of
136905097246SAdrian Prantl // InferiorCallPOSIX::InferiorCallMmap, which depends on functional ThreadPlans
137005097246SAdrian Prantl // working with Native*Protocol.
1371af245d11STodd Fiala #if 1
137297206d57SZachary Turner   return Status("not implemented yet");
1373af245d11STodd Fiala #else
1374af245d11STodd Fiala   addr = LLDB_INVALID_ADDRESS;
1375af245d11STodd Fiala 
1376af245d11STodd Fiala   unsigned prot = 0;
1377af245d11STodd Fiala   if (permissions & lldb::ePermissionsReadable)
1378af245d11STodd Fiala     prot |= eMmapProtRead;
1379af245d11STodd Fiala   if (permissions & lldb::ePermissionsWritable)
1380af245d11STodd Fiala     prot |= eMmapProtWrite;
1381af245d11STodd Fiala   if (permissions & lldb::ePermissionsExecutable)
1382af245d11STodd Fiala     prot |= eMmapProtExec;
1383af245d11STodd Fiala 
1384af245d11STodd Fiala   // TODO implement this directly in NativeProcessLinux
138505097246SAdrian Prantl   // (and lift to NativeProcessPOSIX if/when that class is refactored out).
1386af245d11STodd Fiala   if (InferiorCallMmap(this, addr, 0, size, prot,
1387af245d11STodd Fiala                        eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
1388af245d11STodd Fiala     m_addr_to_mmap_size[addr] = size;
138997206d57SZachary Turner     return Status();
1390af245d11STodd Fiala   } else {
1391af245d11STodd Fiala     addr = LLDB_INVALID_ADDRESS;
139297206d57SZachary Turner     return Status("unable to allocate %" PRIu64
1393b9c1b51eSKate Stone                   " bytes of memory with permissions %s",
1394b9c1b51eSKate Stone                   size, GetPermissionsAsCString(permissions));
1395af245d11STodd Fiala   }
1396af245d11STodd Fiala #endif
1397af245d11STodd Fiala }
1398af245d11STodd Fiala 
139997206d57SZachary Turner Status NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {
1400af245d11STodd Fiala   // FIXME see comments in AllocateMemory - required lower-level
1401af245d11STodd Fiala   // bits not in place yet (ThreadPlans)
140297206d57SZachary Turner   return Status("not implemented");
1403af245d11STodd Fiala }
1404af245d11STodd Fiala 
1405b9c1b51eSKate Stone lldb::addr_t NativeProcessLinux::GetSharedLibraryInfoAddress() {
1406af245d11STodd Fiala   // punt on this for now
1407af245d11STodd Fiala   return LLDB_INVALID_ADDRESS;
1408af245d11STodd Fiala }
1409af245d11STodd Fiala 
1410b9c1b51eSKate Stone size_t NativeProcessLinux::UpdateThreads() {
141105097246SAdrian Prantl   // The NativeProcessLinux monitoring threads are always up to date with
141205097246SAdrian Prantl   // respect to thread state and they keep the thread list populated properly.
141305097246SAdrian Prantl   // All this method needs to do is return the thread count.
1414af245d11STodd Fiala   return m_threads.size();
1415af245d11STodd Fiala }
1416af245d11STodd Fiala 
141797206d57SZachary Turner Status NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,
1418b9c1b51eSKate Stone                                          bool hardware) {
1419af245d11STodd Fiala   if (hardware)
1420d5ffbad2SOmair Javaid     return SetHardwareBreakpoint(addr, size);
1421af245d11STodd Fiala   else
1422af245d11STodd Fiala     return SetSoftwareBreakpoint(addr, size);
1423af245d11STodd Fiala }
1424af245d11STodd Fiala 
142597206d57SZachary Turner Status NativeProcessLinux::RemoveBreakpoint(lldb::addr_t addr, bool hardware) {
1426d5ffbad2SOmair Javaid   if (hardware)
1427d5ffbad2SOmair Javaid     return RemoveHardwareBreakpoint(addr);
1428d5ffbad2SOmair Javaid   else
1429d5ffbad2SOmair Javaid     return NativeProcessProtocol::RemoveBreakpoint(addr);
1430d5ffbad2SOmair Javaid }
1431d5ffbad2SOmair Javaid 
1432f8b825f6SPavel Labath llvm::Expected<llvm::ArrayRef<uint8_t>>
1433f8b825f6SPavel Labath NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(size_t size_hint) {
1434be379e15STamas Berghammer   // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1435be379e15STamas Berghammer   // linux kernel does otherwise.
1436f8b825f6SPavel Labath   static const uint8_t g_arm_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1437f8b825f6SPavel Labath   static const uint8_t g_thumb_opcode[] = {0x01, 0xde};
143812286a27SPavel Labath 
1439f8b825f6SPavel Labath   switch (GetArchitecture().GetMachine()) {
144012286a27SPavel Labath   case llvm::Triple::arm:
1441f8b825f6SPavel Labath     switch (size_hint) {
144263c8be95STamas Berghammer     case 2:
14434f545074SPavel Labath       return llvm::makeArrayRef(g_thumb_opcode);
144463c8be95STamas Berghammer     case 4:
14454f545074SPavel Labath       return llvm::makeArrayRef(g_arm_opcode);
144663c8be95STamas Berghammer     default:
1447f8b825f6SPavel Labath       return llvm::createStringError(llvm::inconvertibleErrorCode(),
1448f8b825f6SPavel Labath                                      "Unrecognised trap opcode size hint!");
144963c8be95STamas Berghammer     }
1450af245d11STodd Fiala   default:
1451f8b825f6SPavel Labath     return NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_hint);
1452af245d11STodd Fiala   }
1453af245d11STodd Fiala }
1454af245d11STodd Fiala 
145597206d57SZachary Turner Status NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
1456b9c1b51eSKate Stone                                       size_t &bytes_read) {
1457df7c6995SPavel Labath   if (ProcessVmReadvSupported()) {
1458b9c1b51eSKate Stone     // The process_vm_readv path is about 50 times faster than ptrace api. We
145905097246SAdrian Prantl     // want to use this syscall if it is supported.
1460df7c6995SPavel Labath 
1461df7c6995SPavel Labath     const ::pid_t pid = GetID();
1462df7c6995SPavel Labath 
1463df7c6995SPavel Labath     struct iovec local_iov, remote_iov;
1464df7c6995SPavel Labath     local_iov.iov_base = buf;
1465df7c6995SPavel Labath     local_iov.iov_len = size;
1466df7c6995SPavel Labath     remote_iov.iov_base = reinterpret_cast<void *>(addr);
1467df7c6995SPavel Labath     remote_iov.iov_len = size;
1468df7c6995SPavel Labath 
1469df7c6995SPavel Labath     bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
1470df7c6995SPavel Labath     const bool success = bytes_read == size;
1471df7c6995SPavel Labath 
1472a6321a8eSPavel Labath     Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1473a6321a8eSPavel Labath     LLDB_LOG(log,
1474a6321a8eSPavel Labath              "using process_vm_readv to read {0} bytes from inferior "
1475a6321a8eSPavel Labath              "address {1:x}: {2}",
147610c41f37SPavel Labath              size, addr, success ? "Success" : llvm::sys::StrError(errno));
1477df7c6995SPavel Labath 
1478df7c6995SPavel Labath     if (success)
147997206d57SZachary Turner       return Status();
1480a6321a8eSPavel Labath     // else the call failed for some reason, let's retry the read using ptrace
1481b9c1b51eSKate Stone     // api.
1482df7c6995SPavel Labath   }
1483df7c6995SPavel Labath 
148419cbe96aSPavel Labath   unsigned char *dst = static_cast<unsigned char *>(buf);
148519cbe96aSPavel Labath   size_t remainder;
148619cbe96aSPavel Labath   long data;
148719cbe96aSPavel Labath 
1488a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1489a6321a8eSPavel Labath   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
149019cbe96aSPavel Labath 
1491b9c1b51eSKate Stone   for (bytes_read = 0; bytes_read < size; bytes_read += remainder) {
149297206d57SZachary Turner     Status error = NativeProcessLinux::PtraceWrapper(
1493b9c1b51eSKate Stone         PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data);
1494a6321a8eSPavel Labath     if (error.Fail())
149519cbe96aSPavel Labath       return error;
149619cbe96aSPavel Labath 
149719cbe96aSPavel Labath     remainder = size - bytes_read;
149819cbe96aSPavel Labath     remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
149919cbe96aSPavel Labath 
150019cbe96aSPavel Labath     // Copy the data into our buffer
1501f6ef187bSMohit K. Bhakkad     memcpy(dst, &data, remainder);
150219cbe96aSPavel Labath 
1503a6321a8eSPavel Labath     LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
150419cbe96aSPavel Labath     addr += k_ptrace_word_size;
150519cbe96aSPavel Labath     dst += k_ptrace_word_size;
150619cbe96aSPavel Labath   }
150797206d57SZachary Turner   return Status();
1508af245d11STodd Fiala }
1509af245d11STodd Fiala 
151097206d57SZachary Turner Status NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,
1511b9c1b51eSKate Stone                                        size_t size, size_t &bytes_written) {
151219cbe96aSPavel Labath   const unsigned char *src = static_cast<const unsigned char *>(buf);
151319cbe96aSPavel Labath   size_t remainder;
151497206d57SZachary Turner   Status error;
151519cbe96aSPavel Labath 
1516a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1517a6321a8eSPavel Labath   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
151819cbe96aSPavel Labath 
1519b9c1b51eSKate Stone   for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
152019cbe96aSPavel Labath     remainder = size - bytes_written;
152119cbe96aSPavel Labath     remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
152219cbe96aSPavel Labath 
1523b9c1b51eSKate Stone     if (remainder == k_ptrace_word_size) {
152419cbe96aSPavel Labath       unsigned long data = 0;
1525f6ef187bSMohit K. Bhakkad       memcpy(&data, src, k_ptrace_word_size);
152619cbe96aSPavel Labath 
1527a6321a8eSPavel Labath       LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
1528b9c1b51eSKate Stone       error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(),
1529b9c1b51eSKate Stone                                                 (void *)addr, (void *)data);
1530a6321a8eSPavel Labath       if (error.Fail())
153119cbe96aSPavel Labath         return error;
1532b9c1b51eSKate Stone     } else {
153319cbe96aSPavel Labath       unsigned char buff[8];
153419cbe96aSPavel Labath       size_t bytes_read;
153519cbe96aSPavel Labath       error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
1536a6321a8eSPavel Labath       if (error.Fail())
153719cbe96aSPavel Labath         return error;
153819cbe96aSPavel Labath 
153919cbe96aSPavel Labath       memcpy(buff, src, remainder);
154019cbe96aSPavel Labath 
154119cbe96aSPavel Labath       size_t bytes_written_rec;
154219cbe96aSPavel Labath       error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
1543a6321a8eSPavel Labath       if (error.Fail())
154419cbe96aSPavel Labath         return error;
154519cbe96aSPavel Labath 
1546a6321a8eSPavel Labath       LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src,
1547b9c1b51eSKate Stone                *(unsigned long *)buff);
154819cbe96aSPavel Labath     }
154919cbe96aSPavel Labath 
155019cbe96aSPavel Labath     addr += k_ptrace_word_size;
155119cbe96aSPavel Labath     src += k_ptrace_word_size;
155219cbe96aSPavel Labath   }
155319cbe96aSPavel Labath   return error;
1554af245d11STodd Fiala }
1555af245d11STodd Fiala 
155697206d57SZachary Turner Status NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) {
155719cbe96aSPavel Labath   return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
1558af245d11STodd Fiala }
1559af245d11STodd Fiala 
156097206d57SZachary Turner Status NativeProcessLinux::GetEventMessage(lldb::tid_t tid,
1561b9c1b51eSKate Stone                                            unsigned long *message) {
156219cbe96aSPavel Labath   return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
1563af245d11STodd Fiala }
1564af245d11STodd Fiala 
156597206d57SZachary Turner Status NativeProcessLinux::Detach(lldb::tid_t tid) {
156697ccc294SChaoren Lin   if (tid == LLDB_INVALID_THREAD_ID)
156797206d57SZachary Turner     return Status();
156897ccc294SChaoren Lin 
156919cbe96aSPavel Labath   return PtraceWrapper(PTRACE_DETACH, tid);
1570af245d11STodd Fiala }
1571af245d11STodd Fiala 
1572b9c1b51eSKate Stone bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {
1573a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
1574a5be48b3SPavel Labath     assert(thread && "thread list should not contain NULL threads");
1575a5be48b3SPavel Labath     if (thread->GetID() == thread_id) {
1576af245d11STodd Fiala       // We have this thread.
1577af245d11STodd Fiala       return true;
1578af245d11STodd Fiala     }
1579af245d11STodd Fiala   }
1580af245d11STodd Fiala 
1581af245d11STodd Fiala   // We don't have this thread.
1582af245d11STodd Fiala   return false;
1583af245d11STodd Fiala }
1584af245d11STodd Fiala 
1585b9c1b51eSKate Stone bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) {
1586a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1587a6321a8eSPavel Labath   LLDB_LOG(log, "tid: {0})", thread_id);
15881dbc6c9cSPavel Labath 
15891dbc6c9cSPavel Labath   bool found = false;
1590b9c1b51eSKate Stone   for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
1591b9c1b51eSKate Stone     if (*it && ((*it)->GetID() == thread_id)) {
1592af245d11STodd Fiala       m_threads.erase(it);
15931dbc6c9cSPavel Labath       found = true;
15941dbc6c9cSPavel Labath       break;
1595af245d11STodd Fiala     }
1596af245d11STodd Fiala   }
1597af245d11STodd Fiala 
159899e37695SRavitheja Addepally   if (found)
159999e37695SRavitheja Addepally     StopTracingForThread(thread_id);
16009eb1ecb9SPavel Labath   SignalIfAllThreadsStopped();
16011dbc6c9cSPavel Labath   return found;
1602af245d11STodd Fiala }
1603af245d11STodd Fiala 
1604a5be48b3SPavel Labath NativeThreadLinux &NativeProcessLinux::AddThread(lldb::tid_t thread_id) {
1605a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
1606a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
1607af245d11STodd Fiala 
1608b9c1b51eSKate Stone   assert(!HasThreadNoLock(thread_id) &&
1609b9c1b51eSKate Stone          "attempted to add a thread by id that already exists");
1610af245d11STodd Fiala 
1611af245d11STodd Fiala   // If this is the first thread, save it as the current thread
1612af245d11STodd Fiala   if (m_threads.empty())
1613af245d11STodd Fiala     SetCurrentThreadID(thread_id);
1614af245d11STodd Fiala 
1615a5be48b3SPavel Labath   m_threads.push_back(llvm::make_unique<NativeThreadLinux>(*this, thread_id));
161699e37695SRavitheja Addepally 
161799e37695SRavitheja Addepally   if (m_pt_proces_trace_id != LLDB_INVALID_UID) {
161899e37695SRavitheja Addepally     auto traceMonitor = ProcessorTraceMonitor::Create(
161999e37695SRavitheja Addepally         GetID(), thread_id, m_pt_process_trace_config, true);
162099e37695SRavitheja Addepally     if (traceMonitor) {
162199e37695SRavitheja Addepally       m_pt_traced_thread_group.insert(thread_id);
162299e37695SRavitheja Addepally       m_processor_trace_monitor.insert(
162399e37695SRavitheja Addepally           std::make_pair(thread_id, std::move(*traceMonitor)));
162499e37695SRavitheja Addepally     } else {
162599e37695SRavitheja Addepally       LLDB_LOG(log, "failed to start trace on thread {0}", thread_id);
162699e37695SRavitheja Addepally       Status error(traceMonitor.takeError());
162799e37695SRavitheja Addepally       LLDB_LOG(log, "error {0}", error);
162899e37695SRavitheja Addepally     }
162999e37695SRavitheja Addepally   }
163099e37695SRavitheja Addepally 
1631a5be48b3SPavel Labath   return static_cast<NativeThreadLinux &>(*m_threads.back());
1632af245d11STodd Fiala }
1633af245d11STodd Fiala 
163497206d57SZachary Turner Status NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,
1635b9c1b51eSKate Stone                                                    FileSpec &file_spec) {
163697206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
1637a6f5795aSTamas Berghammer   if (error.Fail())
1638a6f5795aSTamas Berghammer     return error;
1639a6f5795aSTamas Berghammer 
16408f3be7a3SJonas Devlieghere   FileSpec module_file_spec(module_path);
16418f3be7a3SJonas Devlieghere   FileSystem::Instance().Resolve(module_file_spec);
16427cb18bf5STamas Berghammer 
16437cb18bf5STamas Berghammer   file_spec.Clear();
1644a6f5795aSTamas Berghammer   for (const auto &it : m_mem_region_cache) {
1645a6f5795aSTamas Berghammer     if (it.second.GetFilename() == module_file_spec.GetFilename()) {
1646a6f5795aSTamas Berghammer       file_spec = it.second;
164797206d57SZachary Turner       return Status();
1648a6f5795aSTamas Berghammer     }
1649a6f5795aSTamas Berghammer   }
165097206d57SZachary Turner   return Status("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
16517cb18bf5STamas Berghammer                 module_file_spec.GetFilename().AsCString(), GetID());
16527cb18bf5STamas Berghammer }
1653c076559aSPavel Labath 
165497206d57SZachary Turner Status NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
1655b9c1b51eSKate Stone                                               lldb::addr_t &load_addr) {
1656783bfc8cSTamas Berghammer   load_addr = LLDB_INVALID_ADDRESS;
165797206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
1658a6f5795aSTamas Berghammer   if (error.Fail())
1659783bfc8cSTamas Berghammer     return error;
1660a6f5795aSTamas Berghammer 
16618f3be7a3SJonas Devlieghere   FileSpec file(file_name);
1662a6f5795aSTamas Berghammer   for (const auto &it : m_mem_region_cache) {
1663a6f5795aSTamas Berghammer     if (it.second == file) {
1664a6f5795aSTamas Berghammer       load_addr = it.first.GetRange().GetRangeBase();
166597206d57SZachary Turner       return Status();
1666a6f5795aSTamas Berghammer     }
1667a6f5795aSTamas Berghammer   }
166897206d57SZachary Turner   return Status("No load address found for specified file.");
1669783bfc8cSTamas Berghammer }
1670783bfc8cSTamas Berghammer 
1671a5be48b3SPavel Labath NativeThreadLinux *NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {
1672a5be48b3SPavel Labath   return static_cast<NativeThreadLinux *>(
1673b9c1b51eSKate Stone       NativeProcessProtocol::GetThreadByID(tid));
1674f9077782SPavel Labath }
1675f9077782SPavel Labath 
167697206d57SZachary Turner Status NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,
1677b9c1b51eSKate Stone                                         lldb::StateType state, int signo) {
1678a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1679a6321a8eSPavel Labath   LLDB_LOG(log, "tid: {0}", thread.GetID());
1680c076559aSPavel Labath 
168105097246SAdrian Prantl   // Before we do the resume below, first check if we have a pending stop
168205097246SAdrian Prantl   // notification that is currently waiting for all threads to stop.  This is
168305097246SAdrian Prantl   // potentially a buggy situation since we're ostensibly waiting for threads
168405097246SAdrian Prantl   // to stop before we send out the pending notification, and here we are
168505097246SAdrian Prantl   // resuming one before we send out the pending stop notification.
1686a6321a8eSPavel Labath   if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
1687a6321a8eSPavel Labath     LLDB_LOG(log,
1688a6321a8eSPavel Labath              "about to resume tid {0} per explicit request but we have a "
1689a6321a8eSPavel Labath              "pending stop notification (tid {1}) that is actively "
1690a6321a8eSPavel Labath              "waiting for this thread to stop. Valid sequence of events?",
1691a6321a8eSPavel Labath              thread.GetID(), m_pending_notification_tid);
1692c076559aSPavel Labath   }
1693c076559aSPavel Labath 
169405097246SAdrian Prantl   // Request a resume.  We expect this to be synchronous and the system to
169505097246SAdrian Prantl   // reflect it is running after this completes.
1696b9c1b51eSKate Stone   switch (state) {
1697b9c1b51eSKate Stone   case eStateRunning: {
1698605b51b8SPavel Labath     const auto resume_result = thread.Resume(signo);
16990e1d729bSPavel Labath     if (resume_result.Success())
17000e1d729bSPavel Labath       SetState(eStateRunning, true);
17010e1d729bSPavel Labath     return resume_result;
1702c076559aSPavel Labath   }
1703b9c1b51eSKate Stone   case eStateStepping: {
1704605b51b8SPavel Labath     const auto step_result = thread.SingleStep(signo);
17050e1d729bSPavel Labath     if (step_result.Success())
17060e1d729bSPavel Labath       SetState(eStateRunning, true);
17070e1d729bSPavel Labath     return step_result;
17080e1d729bSPavel Labath   }
17090e1d729bSPavel Labath   default:
17108198db30SPavel Labath     LLDB_LOG(log, "Unhandled state {0}.", state);
17110e1d729bSPavel Labath     llvm_unreachable("Unhandled state for resume");
17120e1d729bSPavel Labath   }
1713c076559aSPavel Labath }
1714c076559aSPavel Labath 
1715c076559aSPavel Labath //===----------------------------------------------------------------------===//
1716c076559aSPavel Labath 
1717b9c1b51eSKate Stone void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {
1718a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1719a6321a8eSPavel Labath   LLDB_LOG(log, "about to process event: (triggering_tid: {0})",
1720a6321a8eSPavel Labath            triggering_tid);
1721c076559aSPavel Labath 
17220e1d729bSPavel Labath   m_pending_notification_tid = triggering_tid;
17230e1d729bSPavel Labath 
172405097246SAdrian Prantl   // Request a stop for all the thread stops that need to be stopped and are
172505097246SAdrian Prantl   // not already known to be stopped.
1726a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
1727a5be48b3SPavel Labath     if (StateIsRunningState(thread->GetState()))
1728a5be48b3SPavel Labath       static_cast<NativeThreadLinux *>(thread.get())->RequestStop();
17290e1d729bSPavel Labath   }
17300e1d729bSPavel Labath 
17310e1d729bSPavel Labath   SignalIfAllThreadsStopped();
1732a6321a8eSPavel Labath   LLDB_LOG(log, "event processing done");
1733c076559aSPavel Labath }
1734c076559aSPavel Labath 
1735b9c1b51eSKate Stone void NativeProcessLinux::SignalIfAllThreadsStopped() {
17360e1d729bSPavel Labath   if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
17370e1d729bSPavel Labath     return; // No pending notification. Nothing to do.
17380e1d729bSPavel Labath 
1739b9c1b51eSKate Stone   for (const auto &thread_sp : m_threads) {
17400e1d729bSPavel Labath     if (StateIsRunningState(thread_sp->GetState()))
17410e1d729bSPavel Labath       return; // Some threads are still running. Don't signal yet.
17420e1d729bSPavel Labath   }
17430e1d729bSPavel Labath 
17440e1d729bSPavel Labath   // We have a pending notification and all threads have stopped.
1745b9c1b51eSKate Stone   Log *log(
1746b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
17479eb1ecb9SPavel Labath 
1748b9c1b51eSKate Stone   // Clear any temporary breakpoints we used to implement software single
1749b9c1b51eSKate Stone   // stepping.
1750b9c1b51eSKate Stone   for (const auto &thread_info : m_threads_stepping_with_breakpoint) {
175197206d57SZachary Turner     Status error = RemoveBreakpoint(thread_info.second);
17529eb1ecb9SPavel Labath     if (error.Fail())
1753a6321a8eSPavel Labath       LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}",
1754a6321a8eSPavel Labath                thread_info.first, error);
17559eb1ecb9SPavel Labath   }
17569eb1ecb9SPavel Labath   m_threads_stepping_with_breakpoint.clear();
17579eb1ecb9SPavel Labath 
17589eb1ecb9SPavel Labath   // Notify the delegate about the stop
17590e1d729bSPavel Labath   SetCurrentThreadID(m_pending_notification_tid);
1760ed89c7feSPavel Labath   SetState(StateType::eStateStopped, true);
17610e1d729bSPavel Labath   m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
1762c076559aSPavel Labath }
1763c076559aSPavel Labath 
1764b9c1b51eSKate Stone void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {
1765a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1766a6321a8eSPavel Labath   LLDB_LOG(log, "tid: {0}", thread.GetID());
17671dbc6c9cSPavel Labath 
1768b9c1b51eSKate Stone   if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID &&
1769b9c1b51eSKate Stone       StateIsRunningState(thread.GetState())) {
1770b9c1b51eSKate Stone     // We will need to wait for this new thread to stop as well before firing
177105097246SAdrian Prantl     // the notification.
1772f9077782SPavel Labath     thread.RequestStop();
1773c076559aSPavel Labath   }
1774c076559aSPavel Labath }
1775068f8a7eSTamas Berghammer 
1776b9c1b51eSKate Stone void NativeProcessLinux::SigchldHandler() {
1777a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
177819cbe96aSPavel Labath   // Process all pending waitpid notifications.
1779b9c1b51eSKate Stone   while (true) {
178019cbe96aSPavel Labath     int status = -1;
1781c1a6b128SPavel Labath     ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, -1, &status,
1782c1a6b128SPavel Labath                                           __WALL | __WNOTHREAD | WNOHANG);
178319cbe96aSPavel Labath 
178419cbe96aSPavel Labath     if (wait_pid == 0)
178519cbe96aSPavel Labath       break; // We are done.
178619cbe96aSPavel Labath 
1787b9c1b51eSKate Stone     if (wait_pid == -1) {
178897206d57SZachary Turner       Status error(errno, eErrorTypePOSIX);
1789a6321a8eSPavel Labath       LLDB_LOG(log, "waitpid (-1, &status, _) failed: {0}", error);
179019cbe96aSPavel Labath       break;
179119cbe96aSPavel Labath     }
179219cbe96aSPavel Labath 
17933508fc8cSPavel Labath     WaitStatus wait_status = WaitStatus::Decode(status);
17943508fc8cSPavel Labath     bool exited = wait_status.type == WaitStatus::Exit ||
17953508fc8cSPavel Labath                   (wait_status.type == WaitStatus::Signal &&
17963508fc8cSPavel Labath                    wait_pid == static_cast<::pid_t>(GetID()));
179719cbe96aSPavel Labath 
17983508fc8cSPavel Labath     LLDB_LOG(
17993508fc8cSPavel Labath         log,
18003508fc8cSPavel Labath         "waitpid (-1, &status, _) => pid = {0}, status = {1}, exited = {2}",
18013508fc8cSPavel Labath         wait_pid, wait_status, exited);
180219cbe96aSPavel Labath 
18033508fc8cSPavel Labath     MonitorCallback(wait_pid, exited, wait_status);
180419cbe96aSPavel Labath   }
1805068f8a7eSTamas Berghammer }
1806068f8a7eSTamas Berghammer 
180705097246SAdrian Prantl // Wrapper for ptrace to catch errors and log calls. Note that ptrace sets
180805097246SAdrian Prantl // errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
180997206d57SZachary Turner Status NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
1810b9c1b51eSKate Stone                                          void *data, size_t data_size,
1811b9c1b51eSKate Stone                                          long *result) {
181297206d57SZachary Turner   Status error;
18134a9babb2SPavel Labath   long int ret;
1814068f8a7eSTamas Berghammer 
1815068f8a7eSTamas Berghammer   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
1816068f8a7eSTamas Berghammer 
1817068f8a7eSTamas Berghammer   PtraceDisplayBytes(req, data, data_size);
1818068f8a7eSTamas Berghammer 
1819068f8a7eSTamas Berghammer   errno = 0;
1820068f8a7eSTamas Berghammer   if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
1821b9c1b51eSKate Stone     ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
1822b9c1b51eSKate Stone                  *(unsigned int *)addr, data);
1823068f8a7eSTamas Berghammer   else
1824b9c1b51eSKate Stone     ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
1825b9c1b51eSKate Stone                  addr, data);
1826068f8a7eSTamas Berghammer 
18274a9babb2SPavel Labath   if (ret == -1)
1828068f8a7eSTamas Berghammer     error.SetErrorToErrno();
1829068f8a7eSTamas Berghammer 
18304a9babb2SPavel Labath   if (result)
18314a9babb2SPavel Labath     *result = ret;
18324a9babb2SPavel Labath 
183328096200SPavel Labath   LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data,
183428096200SPavel Labath            data_size, ret);
1835068f8a7eSTamas Berghammer 
1836068f8a7eSTamas Berghammer   PtraceDisplayBytes(req, data, data_size);
1837068f8a7eSTamas Berghammer 
1838a6321a8eSPavel Labath   if (error.Fail())
1839a6321a8eSPavel Labath     LLDB_LOG(log, "ptrace() failed: {0}", error);
1840068f8a7eSTamas Berghammer 
18414a9babb2SPavel Labath   return error;
1842068f8a7eSTamas Berghammer }
184399e37695SRavitheja Addepally 
184499e37695SRavitheja Addepally llvm::Expected<ProcessorTraceMonitor &>
184599e37695SRavitheja Addepally NativeProcessLinux::LookupProcessorTraceInstance(lldb::user_id_t traceid,
184699e37695SRavitheja Addepally                                                  lldb::tid_t thread) {
184799e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
184899e37695SRavitheja Addepally   if (thread == LLDB_INVALID_THREAD_ID && traceid == m_pt_proces_trace_id) {
184999e37695SRavitheja Addepally     LLDB_LOG(log, "thread not specified: {0}", traceid);
185099e37695SRavitheja Addepally     return Status("tracing not active thread not specified").ToError();
185199e37695SRavitheja Addepally   }
185299e37695SRavitheja Addepally 
185399e37695SRavitheja Addepally   for (auto& iter : m_processor_trace_monitor) {
185499e37695SRavitheja Addepally     if (traceid == iter.second->GetTraceID() &&
185599e37695SRavitheja Addepally         (thread == iter.first || thread == LLDB_INVALID_THREAD_ID))
185699e37695SRavitheja Addepally       return *(iter.second);
185799e37695SRavitheja Addepally   }
185899e37695SRavitheja Addepally 
185999e37695SRavitheja Addepally   LLDB_LOG(log, "traceid not being traced: {0}", traceid);
186099e37695SRavitheja Addepally   return Status("tracing not active for this thread").ToError();
186199e37695SRavitheja Addepally }
186299e37695SRavitheja Addepally 
186399e37695SRavitheja Addepally Status NativeProcessLinux::GetMetaData(lldb::user_id_t traceid,
186499e37695SRavitheja Addepally                                        lldb::tid_t thread,
186599e37695SRavitheja Addepally                                        llvm::MutableArrayRef<uint8_t> &buffer,
186699e37695SRavitheja Addepally                                        size_t offset) {
186799e37695SRavitheja Addepally   TraceOptions trace_options;
186899e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
186999e37695SRavitheja Addepally   Status error;
187099e37695SRavitheja Addepally 
187199e37695SRavitheja Addepally   LLDB_LOG(log, "traceid {0}", traceid);
187299e37695SRavitheja Addepally 
187399e37695SRavitheja Addepally   auto perf_monitor = LookupProcessorTraceInstance(traceid, thread);
187499e37695SRavitheja Addepally   if (!perf_monitor) {
187599e37695SRavitheja Addepally     LLDB_LOG(log, "traceid not being traced: {0}", traceid);
187699e37695SRavitheja Addepally     buffer = buffer.slice(buffer.size());
187799e37695SRavitheja Addepally     error = perf_monitor.takeError();
187899e37695SRavitheja Addepally     return error;
187999e37695SRavitheja Addepally   }
188099e37695SRavitheja Addepally   return (*perf_monitor).ReadPerfTraceData(buffer, offset);
188199e37695SRavitheja Addepally }
188299e37695SRavitheja Addepally 
188399e37695SRavitheja Addepally Status NativeProcessLinux::GetData(lldb::user_id_t traceid, lldb::tid_t thread,
188499e37695SRavitheja Addepally                                    llvm::MutableArrayRef<uint8_t> &buffer,
188599e37695SRavitheja Addepally                                    size_t offset) {
188699e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
188799e37695SRavitheja Addepally   Status error;
188899e37695SRavitheja Addepally 
188999e37695SRavitheja Addepally   LLDB_LOG(log, "traceid {0}", traceid);
189099e37695SRavitheja Addepally 
189199e37695SRavitheja Addepally   auto perf_monitor = LookupProcessorTraceInstance(traceid, thread);
189299e37695SRavitheja Addepally   if (!perf_monitor) {
189399e37695SRavitheja Addepally     LLDB_LOG(log, "traceid not being traced: {0}", traceid);
189499e37695SRavitheja Addepally     buffer = buffer.slice(buffer.size());
189599e37695SRavitheja Addepally     error = perf_monitor.takeError();
189699e37695SRavitheja Addepally     return error;
189799e37695SRavitheja Addepally   }
189899e37695SRavitheja Addepally   return (*perf_monitor).ReadPerfTraceAux(buffer, offset);
189999e37695SRavitheja Addepally }
190099e37695SRavitheja Addepally 
190199e37695SRavitheja Addepally Status NativeProcessLinux::GetTraceConfig(lldb::user_id_t traceid,
190299e37695SRavitheja Addepally                                           TraceOptions &config) {
190399e37695SRavitheja Addepally   Status error;
190499e37695SRavitheja Addepally   if (config.getThreadID() == LLDB_INVALID_THREAD_ID &&
190599e37695SRavitheja Addepally       m_pt_proces_trace_id == traceid) {
190699e37695SRavitheja Addepally     if (m_pt_proces_trace_id == LLDB_INVALID_UID) {
190799e37695SRavitheja Addepally       error.SetErrorString("tracing not active for this process");
190899e37695SRavitheja Addepally       return error;
190999e37695SRavitheja Addepally     }
191099e37695SRavitheja Addepally     config = m_pt_process_trace_config;
191199e37695SRavitheja Addepally   } else {
191299e37695SRavitheja Addepally     auto perf_monitor =
191399e37695SRavitheja Addepally         LookupProcessorTraceInstance(traceid, config.getThreadID());
191499e37695SRavitheja Addepally     if (!perf_monitor) {
191599e37695SRavitheja Addepally       error = perf_monitor.takeError();
191699e37695SRavitheja Addepally       return error;
191799e37695SRavitheja Addepally     }
191899e37695SRavitheja Addepally     error = (*perf_monitor).GetTraceConfig(config);
191999e37695SRavitheja Addepally   }
192099e37695SRavitheja Addepally   return error;
192199e37695SRavitheja Addepally }
192299e37695SRavitheja Addepally 
192399e37695SRavitheja Addepally lldb::user_id_t
192499e37695SRavitheja Addepally NativeProcessLinux::StartTraceGroup(const TraceOptions &config,
192599e37695SRavitheja Addepally                                            Status &error) {
192699e37695SRavitheja Addepally 
192799e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
192899e37695SRavitheja Addepally   if (config.getType() != TraceType::eTraceTypeProcessorTrace)
192999e37695SRavitheja Addepally     return LLDB_INVALID_UID;
193099e37695SRavitheja Addepally 
193199e37695SRavitheja Addepally   if (m_pt_proces_trace_id != LLDB_INVALID_UID) {
193299e37695SRavitheja Addepally     error.SetErrorString("tracing already active on this process");
193399e37695SRavitheja Addepally     return m_pt_proces_trace_id;
193499e37695SRavitheja Addepally   }
193599e37695SRavitheja Addepally 
193699e37695SRavitheja Addepally   for (const auto &thread_sp : m_threads) {
193799e37695SRavitheja Addepally     if (auto traceInstance = ProcessorTraceMonitor::Create(
193899e37695SRavitheja Addepally             GetID(), thread_sp->GetID(), config, true)) {
193999e37695SRavitheja Addepally       m_pt_traced_thread_group.insert(thread_sp->GetID());
194099e37695SRavitheja Addepally       m_processor_trace_monitor.insert(
194199e37695SRavitheja Addepally           std::make_pair(thread_sp->GetID(), std::move(*traceInstance)));
194299e37695SRavitheja Addepally     }
194399e37695SRavitheja Addepally   }
194499e37695SRavitheja Addepally 
194599e37695SRavitheja Addepally   m_pt_process_trace_config = config;
194699e37695SRavitheja Addepally   error = ProcessorTraceMonitor::GetCPUType(m_pt_process_trace_config);
194799e37695SRavitheja Addepally 
194899e37695SRavitheja Addepally   // Trace on Complete process will have traceid of 0
194999e37695SRavitheja Addepally   m_pt_proces_trace_id = 0;
195099e37695SRavitheja Addepally 
195199e37695SRavitheja Addepally   LLDB_LOG(log, "Process Trace ID {0}", m_pt_proces_trace_id);
195299e37695SRavitheja Addepally   return m_pt_proces_trace_id;
195399e37695SRavitheja Addepally }
195499e37695SRavitheja Addepally 
195599e37695SRavitheja Addepally lldb::user_id_t NativeProcessLinux::StartTrace(const TraceOptions &config,
195699e37695SRavitheja Addepally                                                Status &error) {
195799e37695SRavitheja Addepally   if (config.getType() != TraceType::eTraceTypeProcessorTrace)
195899e37695SRavitheja Addepally     return NativeProcessProtocol::StartTrace(config, error);
195999e37695SRavitheja Addepally 
196099e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
196199e37695SRavitheja Addepally 
196299e37695SRavitheja Addepally   lldb::tid_t threadid = config.getThreadID();
196399e37695SRavitheja Addepally 
196499e37695SRavitheja Addepally   if (threadid == LLDB_INVALID_THREAD_ID)
196599e37695SRavitheja Addepally     return StartTraceGroup(config, error);
196699e37695SRavitheja Addepally 
196799e37695SRavitheja Addepally   auto thread_sp = GetThreadByID(threadid);
196899e37695SRavitheja Addepally   if (!thread_sp) {
196999e37695SRavitheja Addepally     // Thread not tracked by lldb so don't trace.
197099e37695SRavitheja Addepally     error.SetErrorString("invalid thread id");
197199e37695SRavitheja Addepally     return LLDB_INVALID_UID;
197299e37695SRavitheja Addepally   }
197399e37695SRavitheja Addepally 
197499e37695SRavitheja Addepally   const auto &iter = m_processor_trace_monitor.find(threadid);
197599e37695SRavitheja Addepally   if (iter != m_processor_trace_monitor.end()) {
197699e37695SRavitheja Addepally     LLDB_LOG(log, "Thread already being traced");
197799e37695SRavitheja Addepally     error.SetErrorString("tracing already active on this thread");
197899e37695SRavitheja Addepally     return LLDB_INVALID_UID;
197999e37695SRavitheja Addepally   }
198099e37695SRavitheja Addepally 
198199e37695SRavitheja Addepally   auto traceMonitor =
198299e37695SRavitheja Addepally       ProcessorTraceMonitor::Create(GetID(), threadid, config, false);
198399e37695SRavitheja Addepally   if (!traceMonitor) {
198499e37695SRavitheja Addepally     error = traceMonitor.takeError();
198599e37695SRavitheja Addepally     LLDB_LOG(log, "error {0}", error);
198699e37695SRavitheja Addepally     return LLDB_INVALID_UID;
198799e37695SRavitheja Addepally   }
198899e37695SRavitheja Addepally   lldb::user_id_t ret_trace_id = (*traceMonitor)->GetTraceID();
198999e37695SRavitheja Addepally   m_processor_trace_monitor.insert(
199099e37695SRavitheja Addepally       std::make_pair(threadid, std::move(*traceMonitor)));
199199e37695SRavitheja Addepally   return ret_trace_id;
199299e37695SRavitheja Addepally }
199399e37695SRavitheja Addepally 
199499e37695SRavitheja Addepally Status NativeProcessLinux::StopTracingForThread(lldb::tid_t thread) {
199599e37695SRavitheja Addepally   Status error;
199699e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
199799e37695SRavitheja Addepally   LLDB_LOG(log, "Thread {0}", thread);
199899e37695SRavitheja Addepally 
199999e37695SRavitheja Addepally   const auto& iter = m_processor_trace_monitor.find(thread);
200099e37695SRavitheja Addepally   if (iter == m_processor_trace_monitor.end()) {
200199e37695SRavitheja Addepally     error.SetErrorString("tracing not active for this thread");
200299e37695SRavitheja Addepally     return error;
200399e37695SRavitheja Addepally   }
200499e37695SRavitheja Addepally 
200599e37695SRavitheja Addepally   if (iter->second->GetTraceID() == m_pt_proces_trace_id) {
200605097246SAdrian Prantl     // traceid maps to the whole process so we have to erase it from the thread
200705097246SAdrian Prantl     // group.
200899e37695SRavitheja Addepally     LLDB_LOG(log, "traceid maps to process");
200999e37695SRavitheja Addepally     m_pt_traced_thread_group.erase(thread);
201099e37695SRavitheja Addepally   }
201199e37695SRavitheja Addepally   m_processor_trace_monitor.erase(iter);
201299e37695SRavitheja Addepally 
201399e37695SRavitheja Addepally   return error;
201499e37695SRavitheja Addepally }
201599e37695SRavitheja Addepally 
201699e37695SRavitheja Addepally Status NativeProcessLinux::StopTrace(lldb::user_id_t traceid,
201799e37695SRavitheja Addepally                                      lldb::tid_t thread) {
201899e37695SRavitheja Addepally   Status error;
201999e37695SRavitheja Addepally 
202099e37695SRavitheja Addepally   TraceOptions trace_options;
202199e37695SRavitheja Addepally   trace_options.setThreadID(thread);
202299e37695SRavitheja Addepally   error = NativeProcessLinux::GetTraceConfig(traceid, trace_options);
202399e37695SRavitheja Addepally 
202499e37695SRavitheja Addepally   if (error.Fail())
202599e37695SRavitheja Addepally     return error;
202699e37695SRavitheja Addepally 
202799e37695SRavitheja Addepally   switch (trace_options.getType()) {
202899e37695SRavitheja Addepally   case lldb::TraceType::eTraceTypeProcessorTrace:
202999e37695SRavitheja Addepally     if (traceid == m_pt_proces_trace_id &&
203099e37695SRavitheja Addepally         thread == LLDB_INVALID_THREAD_ID)
203199e37695SRavitheja Addepally       StopProcessorTracingOnProcess();
203299e37695SRavitheja Addepally     else
203399e37695SRavitheja Addepally       error = StopProcessorTracingOnThread(traceid, thread);
203499e37695SRavitheja Addepally     break;
203599e37695SRavitheja Addepally   default:
203699e37695SRavitheja Addepally     error.SetErrorString("trace not supported");
203799e37695SRavitheja Addepally     break;
203899e37695SRavitheja Addepally   }
203999e37695SRavitheja Addepally 
204099e37695SRavitheja Addepally   return error;
204199e37695SRavitheja Addepally }
204299e37695SRavitheja Addepally 
204399e37695SRavitheja Addepally void NativeProcessLinux::StopProcessorTracingOnProcess() {
204499e37695SRavitheja Addepally   for (auto thread_id_iter : m_pt_traced_thread_group)
204599e37695SRavitheja Addepally     m_processor_trace_monitor.erase(thread_id_iter);
204699e37695SRavitheja Addepally   m_pt_traced_thread_group.clear();
204799e37695SRavitheja Addepally   m_pt_proces_trace_id = LLDB_INVALID_UID;
204899e37695SRavitheja Addepally }
204999e37695SRavitheja Addepally 
205099e37695SRavitheja Addepally Status NativeProcessLinux::StopProcessorTracingOnThread(lldb::user_id_t traceid,
205199e37695SRavitheja Addepally                                                         lldb::tid_t thread) {
205299e37695SRavitheja Addepally   Status error;
205399e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
205499e37695SRavitheja Addepally 
205599e37695SRavitheja Addepally   if (thread == LLDB_INVALID_THREAD_ID) {
205699e37695SRavitheja Addepally     for (auto& iter : m_processor_trace_monitor) {
205799e37695SRavitheja Addepally       if (iter.second->GetTraceID() == traceid) {
205805097246SAdrian Prantl         // Stopping a trace instance for an individual thread hence there will
205905097246SAdrian Prantl         // only be one traceid that can match.
206099e37695SRavitheja Addepally         m_processor_trace_monitor.erase(iter.first);
206199e37695SRavitheja Addepally         return error;
206299e37695SRavitheja Addepally       }
206399e37695SRavitheja Addepally       LLDB_LOG(log, "Trace ID {0}", iter.second->GetTraceID());
206499e37695SRavitheja Addepally     }
206599e37695SRavitheja Addepally 
206699e37695SRavitheja Addepally     LLDB_LOG(log, "Invalid TraceID");
206799e37695SRavitheja Addepally     error.SetErrorString("invalid trace id");
206899e37695SRavitheja Addepally     return error;
206999e37695SRavitheja Addepally   }
207099e37695SRavitheja Addepally 
207199e37695SRavitheja Addepally   // thread is specified so we can use find function on the map.
207299e37695SRavitheja Addepally   const auto& iter = m_processor_trace_monitor.find(thread);
207399e37695SRavitheja Addepally   if (iter == m_processor_trace_monitor.end()) {
207499e37695SRavitheja Addepally     // thread not found in our map.
207599e37695SRavitheja Addepally     LLDB_LOG(log, "thread not being traced");
207699e37695SRavitheja Addepally     error.SetErrorString("tracing not active for this thread");
207799e37695SRavitheja Addepally     return error;
207899e37695SRavitheja Addepally   }
207999e37695SRavitheja Addepally   if (iter->second->GetTraceID() != traceid) {
208099e37695SRavitheja Addepally     // traceid did not match so it has to be invalid.
208199e37695SRavitheja Addepally     LLDB_LOG(log, "Invalid TraceID");
208299e37695SRavitheja Addepally     error.SetErrorString("invalid trace id");
208399e37695SRavitheja Addepally     return error;
208499e37695SRavitheja Addepally   }
208599e37695SRavitheja Addepally 
208699e37695SRavitheja Addepally   LLDB_LOG(log, "UID - {0} , Thread -{1}", traceid, thread);
208799e37695SRavitheja Addepally 
208899e37695SRavitheja Addepally   if (traceid == m_pt_proces_trace_id) {
208905097246SAdrian Prantl     // traceid maps to the whole process so we have to erase it from the thread
209005097246SAdrian Prantl     // group.
209199e37695SRavitheja Addepally     LLDB_LOG(log, "traceid maps to process");
209299e37695SRavitheja Addepally     m_pt_traced_thread_group.erase(thread);
209399e37695SRavitheja Addepally   }
209499e37695SRavitheja Addepally   m_processor_trace_monitor.erase(iter);
209599e37695SRavitheja Addepally 
209699e37695SRavitheja Addepally   return error;
209799e37695SRavitheja Addepally }
2098