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 // C Includes
13af245d11STodd Fiala #include <errno.h>
14af245d11STodd Fiala #include <stdint.h>
15b9c1b51eSKate Stone #include <string.h>
16af245d11STodd Fiala #include <unistd.h>
17af245d11STodd Fiala 
18af245d11STodd Fiala // C++ Includes
19af245d11STodd Fiala #include <fstream>
20df7c6995SPavel Labath #include <mutex>
21c076559aSPavel Labath #include <sstream>
22af245d11STodd Fiala #include <string>
235b981ab9SPavel Labath #include <unordered_map>
24af245d11STodd Fiala 
25af245d11STodd Fiala // Other libraries and framework includes
26d8c338d4STamas Berghammer #include "lldb/Core/EmulateInstruction.h"
276edef204SOleksiy Vyalov #include "lldb/Core/ModuleSpec.h"
28af245d11STodd Fiala #include "lldb/Host/Host.h"
295ad891f7SPavel Labath #include "lldb/Host/HostProcess.h"
3024ae6294SZachary Turner #include "lldb/Host/PseudoTerminal.h"
3139de3110SZachary Turner #include "lldb/Host/ThreadLauncher.h"
322a86b555SPavel Labath #include "lldb/Host/common/NativeBreakpoint.h"
332a86b555SPavel Labath #include "lldb/Host/common/NativeRegisterContext.h"
344ee1c952SPavel Labath #include "lldb/Host/linux/Ptrace.h"
354ee1c952SPavel Labath #include "lldb/Host/linux/Uio.h"
36816ae4b0SKamil Rytarowski #include "lldb/Host/posix/ProcessLauncherPosixFork.h"
372a86b555SPavel Labath #include "lldb/Symbol/ObjectFile.h"
3890aff47cSZachary Turner #include "lldb/Target/Process.h"
39af245d11STodd Fiala #include "lldb/Target/ProcessLaunchInfo.h"
405b981ab9SPavel Labath #include "lldb/Target/Target.h"
41c16f5dcaSChaoren Lin #include "lldb/Utility/LLDBAssert.h"
42d821c997SPavel Labath #include "lldb/Utility/RegisterValue.h"
43d821c997SPavel Labath #include "lldb/Utility/State.h"
4497206d57SZachary Turner #include "lldb/Utility/Status.h"
45f805e190SPavel Labath #include "lldb/Utility/StringExtractor.h"
4610c41f37SPavel Labath #include "llvm/Support/Errno.h"
4710c41f37SPavel Labath #include "llvm/Support/FileSystem.h"
4810c41f37SPavel Labath #include "llvm/Support/Threading.h"
49af245d11STodd Fiala 
50af245d11STodd Fiala #include "NativeThreadLinux.h"
51b9c1b51eSKate Stone #include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
521e209fccSTamas Berghammer #include "Procfs.h"
53cacde7dfSTodd Fiala 
54d858487eSTamas Berghammer #include <linux/unistd.h>
55d858487eSTamas Berghammer #include <sys/socket.h>
56df7c6995SPavel Labath #include <sys/syscall.h>
57d858487eSTamas Berghammer #include <sys/types.h>
58d858487eSTamas Berghammer #include <sys/user.h>
59d858487eSTamas Berghammer #include <sys/wait.h>
60d858487eSTamas Berghammer 
61af245d11STodd Fiala // Support hardware breakpoints in case it has not been defined
62af245d11STodd Fiala #ifndef TRAP_HWBKPT
63af245d11STodd Fiala #define TRAP_HWBKPT 4
64af245d11STodd Fiala #endif
65af245d11STodd Fiala 
667cb18bf5STamas Berghammer using namespace lldb;
677cb18bf5STamas Berghammer using namespace lldb_private;
68db264a6dSTamas Berghammer using namespace lldb_private::process_linux;
697cb18bf5STamas Berghammer using namespace llvm;
707cb18bf5STamas Berghammer 
71af245d11STodd Fiala // Private bits we only need internally.
72df7c6995SPavel Labath 
73b9c1b51eSKate Stone static bool ProcessVmReadvSupported() {
74df7c6995SPavel Labath   static bool is_supported;
75c5f28e2aSKamil Rytarowski   static llvm::once_flag flag;
76df7c6995SPavel Labath 
77c5f28e2aSKamil Rytarowski   llvm::call_once(flag, [] {
78a6321a8eSPavel Labath     Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
79df7c6995SPavel Labath 
80df7c6995SPavel Labath     uint32_t source = 0x47424742;
81df7c6995SPavel Labath     uint32_t dest = 0;
82df7c6995SPavel Labath 
83df7c6995SPavel Labath     struct iovec local, remote;
84df7c6995SPavel Labath     remote.iov_base = &source;
85df7c6995SPavel Labath     local.iov_base = &dest;
86df7c6995SPavel Labath     remote.iov_len = local.iov_len = sizeof source;
87df7c6995SPavel Labath 
88b9c1b51eSKate Stone     // We shall try if cross-process-memory reads work by attempting to read a
89b9c1b51eSKate Stone     // value from our own process.
90df7c6995SPavel Labath     ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
91df7c6995SPavel Labath     is_supported = (res == sizeof(source) && source == dest);
92df7c6995SPavel Labath     if (is_supported)
93a6321a8eSPavel Labath       LLDB_LOG(log,
94a6321a8eSPavel Labath                "Detected kernel support for process_vm_readv syscall. "
95a6321a8eSPavel Labath                "Fast memory reads enabled.");
96df7c6995SPavel Labath     else
97a6321a8eSPavel Labath       LLDB_LOG(log,
98a6321a8eSPavel Labath                "syscall process_vm_readv failed (error: {0}). Fast memory "
99a6321a8eSPavel Labath                "reads disabled.",
10010c41f37SPavel Labath                llvm::sys::StrError());
101df7c6995SPavel Labath   });
102df7c6995SPavel Labath 
103df7c6995SPavel Labath   return is_supported;
104df7c6995SPavel Labath }
105df7c6995SPavel Labath 
106b9c1b51eSKate Stone namespace {
107b9c1b51eSKate Stone void MaybeLogLaunchInfo(const ProcessLaunchInfo &info) {
108a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1094abe5d69SPavel Labath   if (!log)
1104abe5d69SPavel Labath     return;
1114abe5d69SPavel Labath 
1124abe5d69SPavel Labath   if (const FileAction *action = info.GetFileActionForFD(STDIN_FILENO))
113a6321a8eSPavel Labath     LLDB_LOG(log, "setting STDIN to '{0}'", action->GetFileSpec());
1144abe5d69SPavel Labath   else
115a6321a8eSPavel Labath     LLDB_LOG(log, "leaving STDIN as is");
1164abe5d69SPavel Labath 
1174abe5d69SPavel Labath   if (const FileAction *action = info.GetFileActionForFD(STDOUT_FILENO))
118a6321a8eSPavel Labath     LLDB_LOG(log, "setting STDOUT to '{0}'", action->GetFileSpec());
1194abe5d69SPavel Labath   else
120a6321a8eSPavel Labath     LLDB_LOG(log, "leaving STDOUT as is");
1214abe5d69SPavel Labath 
1224abe5d69SPavel Labath   if (const FileAction *action = info.GetFileActionForFD(STDERR_FILENO))
123a6321a8eSPavel Labath     LLDB_LOG(log, "setting STDERR to '{0}'", action->GetFileSpec());
1244abe5d69SPavel Labath   else
125a6321a8eSPavel Labath     LLDB_LOG(log, "leaving STDERR as is");
1264abe5d69SPavel Labath 
1274abe5d69SPavel Labath   int i = 0;
128b9c1b51eSKate Stone   for (const char **args = info.GetArguments().GetConstArgumentVector(); *args;
129b9c1b51eSKate Stone        ++args, ++i)
130a6321a8eSPavel Labath     LLDB_LOG(log, "arg {0}: '{1}'", i, *args);
1314abe5d69SPavel Labath }
1324abe5d69SPavel Labath 
133b9c1b51eSKate Stone void DisplayBytes(StreamString &s, void *bytes, uint32_t count) {
134af245d11STodd Fiala   uint8_t *ptr = (uint8_t *)bytes;
135af245d11STodd Fiala   const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
136b9c1b51eSKate Stone   for (uint32_t i = 0; i < loop_count; i++) {
137af245d11STodd Fiala     s.Printf("[%x]", *ptr);
138af245d11STodd Fiala     ptr++;
139af245d11STodd Fiala   }
140af245d11STodd Fiala }
141af245d11STodd Fiala 
142b9c1b51eSKate Stone void PtraceDisplayBytes(int &req, void *data, size_t data_size) {
143aafe053cSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
144a6321a8eSPavel Labath   if (!log)
145a6321a8eSPavel Labath     return;
146af245d11STodd Fiala   StreamString buf;
147af245d11STodd Fiala 
148b9c1b51eSKate Stone   switch (req) {
149b9c1b51eSKate Stone   case PTRACE_POKETEXT: {
150af245d11STodd Fiala     DisplayBytes(buf, &data, 8);
151aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_POKETEXT {0}", buf.GetData());
152af245d11STodd Fiala     break;
153af245d11STodd Fiala   }
154b9c1b51eSKate Stone   case PTRACE_POKEDATA: {
155af245d11STodd Fiala     DisplayBytes(buf, &data, 8);
156aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_POKEDATA {0}", buf.GetData());
157af245d11STodd Fiala     break;
158af245d11STodd Fiala   }
159b9c1b51eSKate Stone   case PTRACE_POKEUSER: {
160af245d11STodd Fiala     DisplayBytes(buf, &data, 8);
161aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_POKEUSER {0}", buf.GetData());
162af245d11STodd Fiala     break;
163af245d11STodd Fiala   }
164b9c1b51eSKate Stone   case PTRACE_SETREGS: {
165af245d11STodd Fiala     DisplayBytes(buf, data, data_size);
166aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_SETREGS {0}", buf.GetData());
167af245d11STodd Fiala     break;
168af245d11STodd Fiala   }
169b9c1b51eSKate Stone   case PTRACE_SETFPREGS: {
170af245d11STodd Fiala     DisplayBytes(buf, data, data_size);
171aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_SETFPREGS {0}", buf.GetData());
172af245d11STodd Fiala     break;
173af245d11STodd Fiala   }
174b9c1b51eSKate Stone   case PTRACE_SETSIGINFO: {
175af245d11STodd Fiala     DisplayBytes(buf, data, sizeof(siginfo_t));
176aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_SETSIGINFO {0}", buf.GetData());
177af245d11STodd Fiala     break;
178af245d11STodd Fiala   }
179b9c1b51eSKate Stone   case PTRACE_SETREGSET: {
18011edb4eeSPavel Labath     // Extract iov_base from data, which is a pointer to the struct iovec
181af245d11STodd Fiala     DisplayBytes(buf, *(void **)data, data_size);
182aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_SETREGSET {0}", buf.GetData());
183af245d11STodd Fiala     break;
184af245d11STodd Fiala   }
185b9c1b51eSKate Stone   default: {}
186af245d11STodd Fiala   }
187af245d11STodd Fiala }
188af245d11STodd Fiala 
18919cbe96aSPavel Labath static constexpr unsigned k_ptrace_word_size = sizeof(void *);
190b9c1b51eSKate Stone static_assert(sizeof(long) >= k_ptrace_word_size,
191b9c1b51eSKate Stone               "Size of long must be larger than ptrace word size");
1921107b5a5SPavel Labath } // end of anonymous namespace
1931107b5a5SPavel Labath 
194bd7cbc5aSPavel Labath // Simple helper function to ensure flags are enabled on the given file
195bd7cbc5aSPavel Labath // descriptor.
19697206d57SZachary Turner static Status EnsureFDFlags(int fd, int flags) {
19797206d57SZachary Turner   Status error;
198bd7cbc5aSPavel Labath 
199bd7cbc5aSPavel Labath   int status = fcntl(fd, F_GETFL);
200b9c1b51eSKate Stone   if (status == -1) {
201bd7cbc5aSPavel Labath     error.SetErrorToErrno();
202bd7cbc5aSPavel Labath     return error;
203bd7cbc5aSPavel Labath   }
204bd7cbc5aSPavel Labath 
205b9c1b51eSKate Stone   if (fcntl(fd, F_SETFL, status | flags) == -1) {
206bd7cbc5aSPavel Labath     error.SetErrorToErrno();
207bd7cbc5aSPavel Labath     return error;
208bd7cbc5aSPavel Labath   }
209bd7cbc5aSPavel Labath 
210bd7cbc5aSPavel Labath   return error;
211bd7cbc5aSPavel Labath }
212bd7cbc5aSPavel Labath 
213af245d11STodd Fiala // -----------------------------------------------------------------------------
214af245d11STodd Fiala // Public Static Methods
215af245d11STodd Fiala // -----------------------------------------------------------------------------
216af245d11STodd Fiala 
21782abefa4SPavel Labath llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
21896e600fcSPavel Labath NativeProcessLinux::Factory::Launch(ProcessLaunchInfo &launch_info,
21996e600fcSPavel Labath                                     NativeDelegate &native_delegate,
22096e600fcSPavel Labath                                     MainLoop &mainloop) const {
221a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
222af245d11STodd Fiala 
22396e600fcSPavel Labath   MaybeLogLaunchInfo(launch_info);
224af245d11STodd Fiala 
22596e600fcSPavel Labath   Status status;
22696e600fcSPavel Labath   ::pid_t pid = ProcessLauncherPosixFork()
22796e600fcSPavel Labath                     .LaunchProcess(launch_info, status)
22896e600fcSPavel Labath                     .GetProcessId();
22996e600fcSPavel Labath   LLDB_LOG(log, "pid = {0:x}", pid);
23096e600fcSPavel Labath   if (status.Fail()) {
23196e600fcSPavel Labath     LLDB_LOG(log, "failed to launch process: {0}", status);
23296e600fcSPavel Labath     return status.ToError();
233af245d11STodd Fiala   }
234af245d11STodd Fiala 
23596e600fcSPavel Labath   // Wait for the child process to trap on its call to execve.
23696e600fcSPavel Labath   int wstatus;
23796e600fcSPavel Labath   ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0);
23896e600fcSPavel Labath   assert(wpid == pid);
23996e600fcSPavel Labath   (void)wpid;
24096e600fcSPavel Labath   if (!WIFSTOPPED(wstatus)) {
24196e600fcSPavel Labath     LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}",
24296e600fcSPavel Labath              WaitStatus::Decode(wstatus));
24396e600fcSPavel Labath     return llvm::make_error<StringError>("Could not sync with inferior process",
24496e600fcSPavel Labath                                          llvm::inconvertibleErrorCode());
24596e600fcSPavel Labath   }
24696e600fcSPavel Labath   LLDB_LOG(log, "inferior started, now in stopped state");
247af245d11STodd Fiala 
24836e82208SPavel Labath   ProcessInstanceInfo Info;
24936e82208SPavel Labath   if (!Host::GetProcessInfo(pid, Info)) {
25036e82208SPavel Labath     return llvm::make_error<StringError>("Cannot get process architecture",
25136e82208SPavel Labath                                          llvm::inconvertibleErrorCode());
25236e82208SPavel Labath   }
25396e600fcSPavel Labath 
25496e600fcSPavel Labath   // Set the architecture to the exe architecture.
25596e600fcSPavel Labath   LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid,
25636e82208SPavel Labath            Info.GetArchitecture().GetArchitectureName());
25796e600fcSPavel Labath 
25896e600fcSPavel Labath   status = SetDefaultPtraceOpts(pid);
25996e600fcSPavel Labath   if (status.Fail()) {
26096e600fcSPavel Labath     LLDB_LOG(log, "failed to set default ptrace options: {0}", status);
26196e600fcSPavel Labath     return status.ToError();
262af245d11STodd Fiala   }
263af245d11STodd Fiala 
26482abefa4SPavel Labath   return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
26596e600fcSPavel Labath       pid, launch_info.GetPTY().ReleaseMasterFileDescriptor(), native_delegate,
26636e82208SPavel Labath       Info.GetArchitecture(), mainloop, {pid}));
267af245d11STodd Fiala }
268af245d11STodd Fiala 
26982abefa4SPavel Labath llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
27082abefa4SPavel Labath NativeProcessLinux::Factory::Attach(
271b9c1b51eSKate Stone     lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
27296e600fcSPavel Labath     MainLoop &mainloop) const {
273a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
274a6321a8eSPavel Labath   LLDB_LOG(log, "pid = {0:x}", pid);
275af245d11STodd Fiala 
276af245d11STodd Fiala   // Retrieve the architecture for the running process.
27736e82208SPavel Labath   ProcessInstanceInfo Info;
27836e82208SPavel Labath   if (!Host::GetProcessInfo(pid, Info)) {
27936e82208SPavel Labath     return llvm::make_error<StringError>("Cannot get process architecture",
28036e82208SPavel Labath                                          llvm::inconvertibleErrorCode());
28136e82208SPavel Labath   }
282af245d11STodd Fiala 
28396e600fcSPavel Labath   auto tids_or = NativeProcessLinux::Attach(pid);
28496e600fcSPavel Labath   if (!tids_or)
28596e600fcSPavel Labath     return tids_or.takeError();
286af245d11STodd Fiala 
28782abefa4SPavel Labath   return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
28836e82208SPavel Labath       pid, -1, native_delegate, Info.GetArchitecture(), mainloop, *tids_or));
289af245d11STodd Fiala }
290af245d11STodd Fiala 
291af245d11STodd Fiala // -----------------------------------------------------------------------------
292af245d11STodd Fiala // Public Instance Methods
293af245d11STodd Fiala // -----------------------------------------------------------------------------
294af245d11STodd Fiala 
29596e600fcSPavel Labath NativeProcessLinux::NativeProcessLinux(::pid_t pid, int terminal_fd,
29696e600fcSPavel Labath                                        NativeDelegate &delegate,
29782abefa4SPavel Labath                                        const ArchSpec &arch, MainLoop &mainloop,
29882abefa4SPavel Labath                                        llvm::ArrayRef<::pid_t> tids)
29996e600fcSPavel Labath     : NativeProcessProtocol(pid, terminal_fd, delegate), m_arch(arch) {
300b9c1b51eSKate Stone   if (m_terminal_fd != -1) {
30196e600fcSPavel Labath     Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
30296e600fcSPavel Labath     assert(status.Success());
3035ad891f7SPavel Labath   }
304af245d11STodd Fiala 
30596e600fcSPavel Labath   Status status;
30696e600fcSPavel Labath   m_sigchld_handle = mainloop.RegisterSignal(
30796e600fcSPavel Labath       SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status);
30896e600fcSPavel Labath   assert(m_sigchld_handle && status.Success());
30996e600fcSPavel Labath 
31096e600fcSPavel Labath   for (const auto &tid : tids) {
311a5be48b3SPavel Labath     NativeThreadLinux &thread = AddThread(tid);
312a5be48b3SPavel Labath     thread.SetStoppedBySignal(SIGSTOP);
313a5be48b3SPavel Labath     ThreadWasCreated(thread);
314af245d11STodd Fiala   }
315af245d11STodd Fiala 
31696e600fcSPavel Labath   // Let our process instance know the thread has stopped.
31796e600fcSPavel Labath   SetCurrentThreadID(tids[0]);
31896e600fcSPavel Labath   SetState(StateType::eStateStopped, false);
31996e600fcSPavel Labath 
32096e600fcSPavel Labath   // Proccess any signals we received before installing our handler
32196e600fcSPavel Labath   SigchldHandler();
32296e600fcSPavel Labath }
32396e600fcSPavel Labath 
32496e600fcSPavel Labath llvm::Expected<std::vector<::pid_t>> NativeProcessLinux::Attach(::pid_t pid) {
325a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
326af245d11STodd Fiala 
32796e600fcSPavel Labath   Status status;
328b9c1b51eSKate Stone   // Use a map to keep track of the threads which we have attached/need to
329b9c1b51eSKate Stone   // attach.
330af245d11STodd Fiala   Host::TidMap tids_to_attach;
331b9c1b51eSKate Stone   while (Host::FindProcessThreads(pid, tids_to_attach)) {
332af245d11STodd Fiala     for (Host::TidMap::iterator it = tids_to_attach.begin();
333b9c1b51eSKate Stone          it != tids_to_attach.end();) {
334b9c1b51eSKate Stone       if (it->second == false) {
335af245d11STodd Fiala         lldb::tid_t tid = it->first;
336af245d11STodd Fiala 
337af245d11STodd Fiala         // Attach to the requested process.
338af245d11STodd Fiala         // An attach will cause the thread to stop with a SIGSTOP.
33996e600fcSPavel Labath         if ((status = PtraceWrapper(PTRACE_ATTACH, tid)).Fail()) {
34005097246SAdrian Prantl           // No such thread. The thread may have exited. More error handling
34105097246SAdrian Prantl           // may be needed.
34296e600fcSPavel Labath           if (status.GetError() == ESRCH) {
343af245d11STodd Fiala             it = tids_to_attach.erase(it);
344af245d11STodd Fiala             continue;
34596e600fcSPavel Labath           }
34696e600fcSPavel Labath           return status.ToError();
347af245d11STodd Fiala         }
348af245d11STodd Fiala 
34996e600fcSPavel Labath         int wpid =
35096e600fcSPavel Labath             llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, nullptr, __WALL);
35105097246SAdrian Prantl         // Need to use __WALL otherwise we receive an error with errno=ECHLD At
35205097246SAdrian Prantl         // this point we should have a thread stopped if waitpid succeeds.
35396e600fcSPavel Labath         if (wpid < 0) {
35405097246SAdrian Prantl           // No such thread. The thread may have exited. More error handling
35505097246SAdrian Prantl           // may be needed.
356b9c1b51eSKate Stone           if (errno == ESRCH) {
357af245d11STodd Fiala             it = tids_to_attach.erase(it);
358af245d11STodd Fiala             continue;
359af245d11STodd Fiala           }
36096e600fcSPavel Labath           return llvm::errorCodeToError(
36196e600fcSPavel Labath               std::error_code(errno, std::generic_category()));
362af245d11STodd Fiala         }
363af245d11STodd Fiala 
36496e600fcSPavel Labath         if ((status = SetDefaultPtraceOpts(tid)).Fail())
36596e600fcSPavel Labath           return status.ToError();
366af245d11STodd Fiala 
367a6321a8eSPavel Labath         LLDB_LOG(log, "adding tid = {0}", tid);
368af245d11STodd Fiala         it->second = true;
369af245d11STodd Fiala       }
370af245d11STodd Fiala 
371af245d11STodd Fiala       // move the loop forward
372af245d11STodd Fiala       ++it;
373af245d11STodd Fiala     }
374af245d11STodd Fiala   }
375af245d11STodd Fiala 
37696e600fcSPavel Labath   size_t tid_count = tids_to_attach.size();
37796e600fcSPavel Labath   if (tid_count == 0)
37896e600fcSPavel Labath     return llvm::make_error<StringError>("No such process",
37996e600fcSPavel Labath                                          llvm::inconvertibleErrorCode());
380af245d11STodd Fiala 
38196e600fcSPavel Labath   std::vector<::pid_t> tids;
38296e600fcSPavel Labath   tids.reserve(tid_count);
38396e600fcSPavel Labath   for (const auto &p : tids_to_attach)
38496e600fcSPavel Labath     tids.push_back(p.first);
38596e600fcSPavel Labath   return std::move(tids);
386af245d11STodd Fiala }
387af245d11STodd Fiala 
38897206d57SZachary Turner Status NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid) {
389af245d11STodd Fiala   long ptrace_opts = 0;
390af245d11STodd Fiala 
391af245d11STodd Fiala   // Have the child raise an event on exit.  This is used to keep the child in
392af245d11STodd Fiala   // limbo until it is destroyed.
393af245d11STodd Fiala   ptrace_opts |= PTRACE_O_TRACEEXIT;
394af245d11STodd Fiala 
395af245d11STodd Fiala   // Have the tracer trace threads which spawn in the inferior process.
396af245d11STodd Fiala   // TODO: if we want to support tracing the inferiors' child, add the
397af245d11STodd Fiala   // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
398af245d11STodd Fiala   ptrace_opts |= PTRACE_O_TRACECLONE;
399af245d11STodd Fiala 
40005097246SAdrian Prantl   // Have the tracer notify us before execve returns (needed to disable legacy
40105097246SAdrian Prantl   // SIGTRAP generation)
402af245d11STodd Fiala   ptrace_opts |= PTRACE_O_TRACEEXEC;
403af245d11STodd Fiala 
4044a9babb2SPavel Labath   return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void *)ptrace_opts);
405af245d11STodd Fiala }
406af245d11STodd Fiala 
4071107b5a5SPavel Labath // Handles all waitpid events from the inferior process.
408b9c1b51eSKate Stone void NativeProcessLinux::MonitorCallback(lldb::pid_t pid, bool exited,
4093508fc8cSPavel Labath                                          WaitStatus status) {
410af245d11STodd Fiala   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
411af245d11STodd Fiala 
412b9c1b51eSKate Stone   // Certain activities differ based on whether the pid is the tid of the main
413b9c1b51eSKate Stone   // thread.
4141107b5a5SPavel Labath   const bool is_main_thread = (pid == GetID());
415af245d11STodd Fiala 
416af245d11STodd Fiala   // Handle when the thread exits.
417b9c1b51eSKate Stone   if (exited) {
418d8b3c1a1SPavel Labath     LLDB_LOG(log,
419d8b3c1a1SPavel Labath              "got exit signal({0}) , tid = {1} ({2} main thread), process "
420d8b3c1a1SPavel Labath              "state = {3}",
421d8b3c1a1SPavel Labath              signal, pid, is_main_thread ? "is" : "is not", GetState());
422af245d11STodd Fiala 
423af245d11STodd Fiala     // This is a thread that exited.  Ensure we're not tracking it anymore.
424d8b3c1a1SPavel Labath     StopTrackingThread(pid);
425af245d11STodd Fiala 
426b9c1b51eSKate Stone     if (is_main_thread) {
427af245d11STodd Fiala       // The main thread exited.  We're done monitoring.  Report to delegate.
4283508fc8cSPavel Labath       SetExitStatus(status, true);
429af245d11STodd Fiala 
430af245d11STodd Fiala       // Notify delegate that our process has exited.
4311107b5a5SPavel Labath       SetState(StateType::eStateExited, true);
432af245d11STodd Fiala     }
4331107b5a5SPavel Labath     return;
434af245d11STodd Fiala   }
435af245d11STodd Fiala 
436af245d11STodd Fiala   siginfo_t info;
437b9cc0c75SPavel Labath   const auto info_err = GetSignalInfo(pid, &info);
438b9cc0c75SPavel Labath   auto thread_sp = GetThreadByID(pid);
439b9cc0c75SPavel Labath 
440b9c1b51eSKate Stone   if (!thread_sp) {
44105097246SAdrian Prantl     // Normally, the only situation when we cannot find the thread is if we
44205097246SAdrian Prantl     // have just received a new thread notification. This is indicated by
443a6321a8eSPavel Labath     // GetSignalInfo() returning si_code == SI_USER and si_pid == 0
444a6321a8eSPavel Labath     LLDB_LOG(log, "received notification about an unknown tid {0}.", pid);
445b9cc0c75SPavel Labath 
446b9c1b51eSKate Stone     if (info_err.Fail()) {
447a6321a8eSPavel Labath       LLDB_LOG(log,
448a6321a8eSPavel Labath                "(tid {0}) GetSignalInfo failed ({1}). "
449a6321a8eSPavel Labath                "Ingoring this notification.",
450a6321a8eSPavel Labath                pid, info_err);
451b9cc0c75SPavel Labath       return;
452b9cc0c75SPavel Labath     }
453b9cc0c75SPavel Labath 
454a6321a8eSPavel Labath     LLDB_LOG(log, "tid {0}, si_code: {1}, si_pid: {2}", pid, info.si_code,
455a6321a8eSPavel Labath              info.si_pid);
456b9cc0c75SPavel Labath 
457a5be48b3SPavel Labath     NativeThreadLinux &thread = AddThread(pid);
45899e37695SRavitheja Addepally 
459b9cc0c75SPavel Labath     // Resume the newly created thread.
460a5be48b3SPavel Labath     ResumeThread(thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
461a5be48b3SPavel Labath     ThreadWasCreated(thread);
462b9cc0c75SPavel Labath     return;
463b9cc0c75SPavel Labath   }
464b9cc0c75SPavel Labath 
465b9cc0c75SPavel Labath   // Get details on the signal raised.
466b9c1b51eSKate Stone   if (info_err.Success()) {
467fa03ad2eSChaoren Lin     // We have retrieved the signal info.  Dispatch appropriately.
468fa03ad2eSChaoren Lin     if (info.si_signo == SIGTRAP)
469b9cc0c75SPavel Labath       MonitorSIGTRAP(info, *thread_sp);
470fa03ad2eSChaoren Lin     else
471b9cc0c75SPavel Labath       MonitorSignal(info, *thread_sp, exited);
472b9c1b51eSKate Stone   } else {
473b9c1b51eSKate Stone     if (info_err.GetError() == EINVAL) {
47405097246SAdrian Prantl       // This is a group stop reception for this tid. We can reach here if we
47505097246SAdrian Prantl       // reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the tracee,
47605097246SAdrian Prantl       // triggering the group-stop mechanism. Normally receiving these would
47705097246SAdrian Prantl       // stop the process, pending a SIGCONT. Simulating this state in a
47805097246SAdrian Prantl       // debugger is hard and is generally not needed (one use case is
47905097246SAdrian Prantl       // debugging background task being managed by a shell). For general use,
48005097246SAdrian Prantl       // it is sufficient to stop the process in a signal-delivery stop which
48105097246SAdrian Prantl       // happens before the group stop. This done by MonitorSignal and works
48205097246SAdrian Prantl       // correctly for all signals.
483a6321a8eSPavel Labath       LLDB_LOG(log,
484a6321a8eSPavel Labath                "received a group stop for pid {0} tid {1}. Transparent "
485a6321a8eSPavel Labath                "handling of group stops not supported, resuming the "
486a6321a8eSPavel Labath                "thread.",
487a6321a8eSPavel Labath                GetID(), pid);
488b9c1b51eSKate Stone       ResumeThread(*thread_sp, thread_sp->GetState(),
489b9c1b51eSKate Stone                    LLDB_INVALID_SIGNAL_NUMBER);
490b9c1b51eSKate Stone     } else {
491af245d11STodd Fiala       // ptrace(GETSIGINFO) failed (but not due to group-stop).
492af245d11STodd Fiala 
493b9c1b51eSKate Stone       // A return value of ESRCH means the thread/process is no longer on the
494a6321a8eSPavel Labath       // system, so it was killed somehow outside of our control.  Either way,
495a6321a8eSPavel Labath       // we can't do anything with it anymore.
496af245d11STodd Fiala 
497b9c1b51eSKate Stone       // Stop tracking the metadata for the thread since it's entirely off the
498b9c1b51eSKate Stone       // system now.
4991107b5a5SPavel Labath       const bool thread_found = StopTrackingThread(pid);
500af245d11STodd Fiala 
501a6321a8eSPavel Labath       LLDB_LOG(log,
502a6321a8eSPavel Labath                "GetSignalInfo failed: {0}, tid = {1}, signal = {2}, "
503a6321a8eSPavel Labath                "status = {3}, main_thread = {4}, thread_found: {5}",
504a6321a8eSPavel Labath                info_err, pid, signal, status, is_main_thread, thread_found);
505af245d11STodd Fiala 
506b9c1b51eSKate Stone       if (is_main_thread) {
507b9c1b51eSKate Stone         // Notify the delegate - our process is not available but appears to
50805097246SAdrian Prantl         // have been killed outside our control.  Is eStateExited the right
50905097246SAdrian Prantl         // exit state in this case?
5103508fc8cSPavel Labath         SetExitStatus(status, true);
5111107b5a5SPavel Labath         SetState(StateType::eStateExited, true);
512b9c1b51eSKate Stone       } else {
513b9c1b51eSKate Stone         // This thread was pulled out from underneath us.  Anything to do here?
514b9c1b51eSKate Stone         // Do we want to do an all stop?
515a6321a8eSPavel Labath         LLDB_LOG(log,
516a6321a8eSPavel Labath                  "pid {0} tid {1} non-main thread exit occurred, didn't "
517a6321a8eSPavel Labath                  "tell delegate anything since thread disappeared out "
518a6321a8eSPavel Labath                  "from underneath us",
519a6321a8eSPavel Labath                  GetID(), pid);
520af245d11STodd Fiala       }
521af245d11STodd Fiala     }
522af245d11STodd Fiala   }
523af245d11STodd Fiala }
524af245d11STodd Fiala 
525b9c1b51eSKate Stone void NativeProcessLinux::WaitForNewThread(::pid_t tid) {
526a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
527426bdf88SPavel Labath 
528a5be48b3SPavel Labath   if (GetThreadByID(tid)) {
529b9c1b51eSKate Stone     // We are already tracking the thread - we got the event on the new thread
530a5be48b3SPavel Labath     // (see MonitorSignal) before this one. We are done.
531426bdf88SPavel Labath     return;
532426bdf88SPavel Labath   }
533426bdf88SPavel Labath 
534426bdf88SPavel Labath   // The thread is not tracked yet, let's wait for it to appear.
535426bdf88SPavel Labath   int status = -1;
536a6321a8eSPavel Labath   LLDB_LOG(log,
537a6321a8eSPavel Labath            "received thread creation event for tid {0}. tid not tracked "
538a6321a8eSPavel Labath            "yet, waiting for thread to appear...",
539a6321a8eSPavel Labath            tid);
540c1a6b128SPavel Labath   ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, &status, __WALL);
541b9c1b51eSKate Stone   // Since we are waiting on a specific tid, this must be the creation event.
542a6321a8eSPavel Labath   // But let's do some checks just in case.
543426bdf88SPavel Labath   if (wait_pid != tid) {
544a6321a8eSPavel Labath     LLDB_LOG(log,
545a6321a8eSPavel Labath              "waiting for tid {0} failed. Assuming the thread has "
546a6321a8eSPavel Labath              "disappeared in the meantime",
547a6321a8eSPavel Labath              tid);
548426bdf88SPavel Labath     // The only way I know of this could happen is if the whole process was
549b9c1b51eSKate Stone     // SIGKILLed in the mean time. In any case, we can't do anything about that
550b9c1b51eSKate Stone     // now.
551426bdf88SPavel Labath     return;
552426bdf88SPavel Labath   }
553b9c1b51eSKate Stone   if (WIFEXITED(status)) {
554a6321a8eSPavel Labath     LLDB_LOG(log,
555a6321a8eSPavel Labath              "waiting for tid {0} returned an 'exited' event. Not "
556a6321a8eSPavel Labath              "tracking the thread.",
557a6321a8eSPavel Labath              tid);
558426bdf88SPavel Labath     // Also a very improbable event.
559426bdf88SPavel Labath     return;
560426bdf88SPavel Labath   }
561426bdf88SPavel Labath 
562a6321a8eSPavel Labath   LLDB_LOG(log, "pid = {0}: tracking new thread tid {1}", GetID(), tid);
563a5be48b3SPavel Labath   NativeThreadLinux &new_thread = AddThread(tid);
56499e37695SRavitheja Addepally 
565a5be48b3SPavel Labath   ResumeThread(new_thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
566a5be48b3SPavel Labath   ThreadWasCreated(new_thread);
567426bdf88SPavel Labath }
568426bdf88SPavel Labath 
569b9c1b51eSKate Stone void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info,
570b9c1b51eSKate Stone                                         NativeThreadLinux &thread) {
571a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
572b9cc0c75SPavel Labath   const bool is_main_thread = (thread.GetID() == GetID());
573af245d11STodd Fiala 
574b9cc0c75SPavel Labath   assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
575af245d11STodd Fiala 
576b9c1b51eSKate Stone   switch (info.si_code) {
577b9c1b51eSKate Stone   // TODO: these two cases are required if we want to support tracing of the
57805097246SAdrian Prantl   // inferiors' children.  We'd need this to debug a monitor. case (SIGTRAP |
57905097246SAdrian Prantl   // (PTRACE_EVENT_FORK << 8)): case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
580af245d11STodd Fiala 
581b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): {
582b9c1b51eSKate Stone     // This is the notification on the parent thread which informs us of new
58305097246SAdrian Prantl     // thread creation. We don't want to do anything with the parent thread so
58405097246SAdrian Prantl     // we just resume it. In case we want to implement "break on thread
58505097246SAdrian Prantl     // creation" functionality, we would need to stop here.
586af245d11STodd Fiala 
587af245d11STodd Fiala     unsigned long event_message = 0;
588b9c1b51eSKate Stone     if (GetEventMessage(thread.GetID(), &event_message).Fail()) {
589a6321a8eSPavel Labath       LLDB_LOG(log,
590a6321a8eSPavel Labath                "pid {0} received thread creation event but "
591a6321a8eSPavel Labath                "GetEventMessage failed so we don't know the new tid",
592a6321a8eSPavel Labath                thread.GetID());
593426bdf88SPavel Labath     } else
594426bdf88SPavel Labath       WaitForNewThread(event_message);
595af245d11STodd Fiala 
596b9cc0c75SPavel Labath     ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
597af245d11STodd Fiala     break;
598af245d11STodd Fiala   }
599af245d11STodd Fiala 
600b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): {
601a6321a8eSPavel Labath     LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP);
602a9882ceeSTodd Fiala 
6031dbc6c9cSPavel Labath     // Exec clears any pending notifications.
6040e1d729bSPavel Labath     m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
605fa03ad2eSChaoren Lin 
606b9c1b51eSKate Stone     // Remove all but the main thread here.  Linux fork creates a new process
607b9c1b51eSKate Stone     // which only copies the main thread.
608a6321a8eSPavel Labath     LLDB_LOG(log, "exec received, stop tracking all but main thread");
609a9882ceeSTodd Fiala 
610a5be48b3SPavel Labath     for (auto i = m_threads.begin(); i != m_threads.end();) {
611a5be48b3SPavel Labath       if ((*i)->GetID() == GetID())
612a5be48b3SPavel Labath         i = m_threads.erase(i);
613a5be48b3SPavel Labath       else
614a5be48b3SPavel Labath         ++i;
615a9882ceeSTodd Fiala     }
616a5be48b3SPavel Labath     assert(m_threads.size() == 1);
617a5be48b3SPavel Labath     auto *main_thread = static_cast<NativeThreadLinux *>(m_threads[0].get());
618a9882ceeSTodd Fiala 
619a5be48b3SPavel Labath     SetCurrentThreadID(main_thread->GetID());
620a5be48b3SPavel Labath     main_thread->SetStoppedByExec();
621a9882ceeSTodd Fiala 
622fa03ad2eSChaoren Lin     // Tell coordinator about about the "new" (since exec) stopped main thread.
623a5be48b3SPavel Labath     ThreadWasCreated(*main_thread);
624fa03ad2eSChaoren Lin 
625a9882ceeSTodd Fiala     // Let our delegate know we have just exec'd.
626a9882ceeSTodd Fiala     NotifyDidExec();
627a9882ceeSTodd Fiala 
628fa03ad2eSChaoren Lin     // Let the process know we're stopped.
629a5be48b3SPavel Labath     StopRunningThreads(main_thread->GetID());
630a9882ceeSTodd Fiala 
631af245d11STodd Fiala     break;
632a9882ceeSTodd Fiala   }
633af245d11STodd Fiala 
634b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): {
63505097246SAdrian Prantl     // The inferior process or one of its threads is about to exit. We don't
63605097246SAdrian Prantl     // want to do anything with the thread so we just resume it. In case we
63705097246SAdrian Prantl     // want to implement "break on thread exit" functionality, we would need to
63805097246SAdrian Prantl     // stop here.
639fa03ad2eSChaoren Lin 
640af245d11STodd Fiala     unsigned long data = 0;
641b9cc0c75SPavel Labath     if (GetEventMessage(thread.GetID(), &data).Fail())
642af245d11STodd Fiala       data = -1;
643af245d11STodd Fiala 
644a6321a8eSPavel Labath     LLDB_LOG(log,
645a6321a8eSPavel Labath              "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
646a6321a8eSPavel Labath              "WIFSIGNALED={2}, pid = {3}, main_thread = {4}",
647a6321a8eSPavel Labath              data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(),
648a6321a8eSPavel Labath              is_main_thread);
649af245d11STodd Fiala 
65075f47c3aSTodd Fiala 
65186852d36SPavel Labath     StateType state = thread.GetState();
652b9c1b51eSKate Stone     if (!StateIsRunningState(state)) {
653b9c1b51eSKate Stone       // Due to a kernel bug, we may sometimes get this stop after the inferior
654d8b3c1a1SPavel Labath       // gets a SIGKILL. This confuses our state tracking logic in
655d8b3c1a1SPavel Labath       // ResumeThread(), since normally, we should not be receiving any ptrace
65605097246SAdrian Prantl       // events while the inferior is stopped. This makes sure that the
65705097246SAdrian Prantl       // inferior is resumed and exits normally.
65886852d36SPavel Labath       state = eStateRunning;
65986852d36SPavel Labath     }
66086852d36SPavel Labath     ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
661af245d11STodd Fiala 
662af245d11STodd Fiala     break;
663af245d11STodd Fiala   }
664af245d11STodd Fiala 
665af245d11STodd Fiala   case 0:
666c16f5dcaSChaoren Lin   case TRAP_TRACE:  // We receive this on single stepping.
667c16f5dcaSChaoren Lin   case TRAP_HWBKPT: // We receive this on watchpoint hit
66886fd8e45SChaoren Lin   {
669c16f5dcaSChaoren Lin     // If a watchpoint was hit, report it
670c16f5dcaSChaoren Lin     uint32_t wp_index;
671d37349f3SPavel Labath     Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
672b9c1b51eSKate Stone         wp_index, (uintptr_t)info.si_addr);
673a6321a8eSPavel Labath     if (error.Fail())
674a6321a8eSPavel Labath       LLDB_LOG(log,
675a6321a8eSPavel Labath                "received error while checking for watchpoint hits, pid = "
676a6321a8eSPavel Labath                "{0}, error = {1}",
677a6321a8eSPavel Labath                thread.GetID(), error);
678b9c1b51eSKate Stone     if (wp_index != LLDB_INVALID_INDEX32) {
679b9cc0c75SPavel Labath       MonitorWatchpoint(thread, wp_index);
680c16f5dcaSChaoren Lin       break;
681c16f5dcaSChaoren Lin     }
682b9cc0c75SPavel Labath 
683d5ffbad2SOmair Javaid     // If a breakpoint was hit, report it
684d5ffbad2SOmair Javaid     uint32_t bp_index;
685d37349f3SPavel Labath     error = thread.GetRegisterContext().GetHardwareBreakHitIndex(
686d5ffbad2SOmair Javaid         bp_index, (uintptr_t)info.si_addr);
687d5ffbad2SOmair Javaid     if (error.Fail())
688d5ffbad2SOmair Javaid       LLDB_LOG(log, "received error while checking for hardware "
689d5ffbad2SOmair Javaid                     "breakpoint hits, pid = {0}, error = {1}",
690d5ffbad2SOmair Javaid                thread.GetID(), error);
691d5ffbad2SOmair Javaid     if (bp_index != LLDB_INVALID_INDEX32) {
692d5ffbad2SOmair Javaid       MonitorBreakpoint(thread);
693d5ffbad2SOmair Javaid       break;
694d5ffbad2SOmair Javaid     }
695d5ffbad2SOmair Javaid 
696be379e15STamas Berghammer     // Otherwise, report step over
697be379e15STamas Berghammer     MonitorTrace(thread);
698af245d11STodd Fiala     break;
699b9cc0c75SPavel Labath   }
700af245d11STodd Fiala 
701af245d11STodd Fiala   case SI_KERNEL:
70235799963SMohit K. Bhakkad #if defined __mips__
70305097246SAdrian Prantl     // For mips there is no special signal for watchpoint So we check for
70405097246SAdrian Prantl     // watchpoint in kernel trap
70535799963SMohit K. Bhakkad     {
70635799963SMohit K. Bhakkad       // If a watchpoint was hit, report it
70735799963SMohit K. Bhakkad       uint32_t wp_index;
708d37349f3SPavel Labath       Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
709b9c1b51eSKate Stone           wp_index, LLDB_INVALID_ADDRESS);
710a6321a8eSPavel Labath       if (error.Fail())
711a6321a8eSPavel Labath         LLDB_LOG(log,
712a6321a8eSPavel Labath                  "received error while checking for watchpoint hits, pid = "
713a6321a8eSPavel Labath                  "{0}, error = {1}",
714a6321a8eSPavel Labath                  thread.GetID(), error);
715b9c1b51eSKate Stone       if (wp_index != LLDB_INVALID_INDEX32) {
716b9cc0c75SPavel Labath         MonitorWatchpoint(thread, wp_index);
71735799963SMohit K. Bhakkad         break;
71835799963SMohit K. Bhakkad       }
71935799963SMohit K. Bhakkad     }
72035799963SMohit K. Bhakkad // NO BREAK
72135799963SMohit K. Bhakkad #endif
722af245d11STodd Fiala   case TRAP_BRKPT:
723b9cc0c75SPavel Labath     MonitorBreakpoint(thread);
724af245d11STodd Fiala     break;
725af245d11STodd Fiala 
726af245d11STodd Fiala   case SIGTRAP:
727af245d11STodd Fiala   case (SIGTRAP | 0x80):
728a6321a8eSPavel Labath     LLDB_LOG(
729a6321a8eSPavel Labath         log,
730a6321a8eSPavel Labath         "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",
731a6321a8eSPavel Labath         info.si_code, GetID(), thread.GetID());
732fa03ad2eSChaoren Lin 
733af245d11STodd Fiala     // Ignore these signals until we know more about them.
734b9cc0c75SPavel Labath     ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
735af245d11STodd Fiala     break;
736af245d11STodd Fiala 
737af245d11STodd Fiala   default:
73821a365baSPavel Labath     LLDB_LOG(log, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}",
739a6321a8eSPavel Labath              info.si_code, GetID(), thread.GetID());
74021a365baSPavel Labath     MonitorSignal(info, thread, false);
741af245d11STodd Fiala     break;
742af245d11STodd Fiala   }
743af245d11STodd Fiala }
744af245d11STodd Fiala 
745b9c1b51eSKate Stone void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) {
746a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
747a6321a8eSPavel Labath   LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID());
748c16f5dcaSChaoren Lin 
7490e1d729bSPavel Labath   // This thread is currently stopped.
750b9cc0c75SPavel Labath   thread.SetStoppedByTrace();
751c16f5dcaSChaoren Lin 
752b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
753c16f5dcaSChaoren Lin }
754c16f5dcaSChaoren Lin 
755b9c1b51eSKate Stone void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) {
756b9c1b51eSKate Stone   Log *log(
757b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
758a6321a8eSPavel Labath   LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID());
759c16f5dcaSChaoren Lin 
760c16f5dcaSChaoren Lin   // Mark the thread as stopped at breakpoint.
761b9cc0c75SPavel Labath   thread.SetStoppedByBreakpoint();
762aef7908fSPavel Labath   FixupBreakpointPCAsNeeded(thread);
763d8c338d4STamas Berghammer 
764b9c1b51eSKate Stone   if (m_threads_stepping_with_breakpoint.find(thread.GetID()) !=
765b9c1b51eSKate Stone       m_threads_stepping_with_breakpoint.end())
766b9cc0c75SPavel Labath     thread.SetStoppedByTrace();
767c16f5dcaSChaoren Lin 
768b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
769c16f5dcaSChaoren Lin }
770c16f5dcaSChaoren Lin 
771b9c1b51eSKate Stone void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread,
772b9c1b51eSKate Stone                                            uint32_t wp_index) {
773b9c1b51eSKate Stone   Log *log(
774b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
775a6321a8eSPavel Labath   LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}",
776a6321a8eSPavel Labath            thread.GetID(), wp_index);
777c16f5dcaSChaoren Lin 
77805097246SAdrian Prantl   // Mark the thread as stopped at watchpoint. The address is at
77905097246SAdrian Prantl   // (lldb::addr_t)info->si_addr if we need it.
780f9077782SPavel Labath   thread.SetStoppedByWatchpoint(wp_index);
781c16f5dcaSChaoren Lin 
782b9c1b51eSKate Stone   // We need to tell all other running threads before we notify the delegate
783b9c1b51eSKate Stone   // about this stop.
784f9077782SPavel Labath   StopRunningThreads(thread.GetID());
785c16f5dcaSChaoren Lin }
786c16f5dcaSChaoren Lin 
787b9c1b51eSKate Stone void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
788b9c1b51eSKate Stone                                        NativeThreadLinux &thread, bool exited) {
789b9cc0c75SPavel Labath   const int signo = info.si_signo;
790b9cc0c75SPavel Labath   const bool is_from_llgs = info.si_pid == getpid();
791af245d11STodd Fiala 
792a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
793af245d11STodd Fiala 
794af245d11STodd Fiala   // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
79505097246SAdrian Prantl   // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a kill(2)
79605097246SAdrian Prantl   // or raise(3).  Similarly for tgkill(2) on Linux.
797af245d11STodd Fiala   //
798af245d11STodd Fiala   // IOW, user generated signals never generate what we consider to be a
799af245d11STodd Fiala   // "crash".
800af245d11STodd Fiala   //
801af245d11STodd Fiala   // Similarly, ACK signals generated by this monitor.
802af245d11STodd Fiala 
803af245d11STodd Fiala   // Handle the signal.
804a6321a8eSPavel Labath   LLDB_LOG(log,
805a6321a8eSPavel Labath            "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
806a6321a8eSPavel Labath            "waitpid pid = {4})",
807a6321a8eSPavel Labath            Host::GetSignalAsCString(signo), signo, info.si_code,
808b9cc0c75SPavel Labath            thread.GetID());
80958a2f669STodd Fiala 
81058a2f669STodd Fiala   // Check for thread stop notification.
811b9c1b51eSKate Stone   if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) {
812af245d11STodd Fiala     // This is a tgkill()-based stop.
813a6321a8eSPavel Labath     LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID());
814fa03ad2eSChaoren Lin 
81505097246SAdrian Prantl     // Check that we're not already marked with a stop reason. Note this thread
81605097246SAdrian Prantl     // really shouldn't already be marked as stopped - if we were, that would
81705097246SAdrian Prantl     // imply that the kernel signaled us with the thread stopping which we
81805097246SAdrian Prantl     // handled and marked as stopped, and that, without an intervening resume,
81905097246SAdrian Prantl     // we received another stop.  It is more likely that we are missing the
82005097246SAdrian Prantl     // marking of a run state somewhere if we find that the thread was marked
82105097246SAdrian Prantl     // as stopped.
822b9cc0c75SPavel Labath     const StateType thread_state = thread.GetState();
823b9c1b51eSKate Stone     if (!StateIsStoppedState(thread_state, false)) {
824ed89c7feSPavel Labath       // An inferior thread has stopped because of a SIGSTOP we have sent it.
825b9c1b51eSKate Stone       // Generally, these are not important stops and we don't want to report
826a6321a8eSPavel Labath       // them as they are just used to stop other threads when one thread (the
827a6321a8eSPavel Labath       // one with the *real* stop reason) hits a breakpoint (watchpoint,
82805097246SAdrian Prantl       // etc...). However, in the case of an asynchronous Interrupt(), this
82905097246SAdrian Prantl       // *is* the real stop reason, so we leave the signal intact if this is
83005097246SAdrian Prantl       // the thread that was chosen as the triggering thread.
831b9c1b51eSKate Stone       if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
832b9cc0c75SPavel Labath         if (m_pending_notification_tid == thread.GetID())
833b9cc0c75SPavel Labath           thread.SetStoppedBySignal(SIGSTOP, &info);
834ed89c7feSPavel Labath         else
835b9cc0c75SPavel Labath           thread.SetStoppedWithNoReason();
836ed89c7feSPavel Labath 
837b9cc0c75SPavel Labath         SetCurrentThreadID(thread.GetID());
8380e1d729bSPavel Labath         SignalIfAllThreadsStopped();
839b9c1b51eSKate Stone       } else {
8400e1d729bSPavel Labath         // We can end up here if stop was initiated by LLGS but by this time a
8410e1d729bSPavel Labath         // thread stop has occurred - maybe initiated by another event.
84297206d57SZachary Turner         Status error = ResumeThread(thread, thread.GetState(), 0);
843a6321a8eSPavel Labath         if (error.Fail())
844a6321a8eSPavel Labath           LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(),
845a6321a8eSPavel Labath                    error);
8460e1d729bSPavel Labath       }
847b9c1b51eSKate Stone     } else {
848a6321a8eSPavel Labath       LLDB_LOG(log,
849a6321a8eSPavel Labath                "pid {0} tid {1}, thread was already marked as a stopped "
850a6321a8eSPavel Labath                "state (state={2}), leaving stop signal as is",
8518198db30SPavel Labath                GetID(), thread.GetID(), thread_state);
8520e1d729bSPavel Labath       SignalIfAllThreadsStopped();
853af245d11STodd Fiala     }
854af245d11STodd Fiala 
85558a2f669STodd Fiala     // Done handling.
856af245d11STodd Fiala     return;
857af245d11STodd Fiala   }
858af245d11STodd Fiala 
85905097246SAdrian Prantl   // Check if debugger should stop at this signal or just ignore it and resume
86005097246SAdrian Prantl   // the inferior.
8614a705e7eSPavel Labath   if (m_signals_to_ignore.find(signo) != m_signals_to_ignore.end()) {
8624a705e7eSPavel Labath      ResumeThread(thread, thread.GetState(), signo);
8634a705e7eSPavel Labath      return;
8644a705e7eSPavel Labath   }
8654a705e7eSPavel Labath 
86686fd8e45SChaoren Lin   // This thread is stopped.
867a6321a8eSPavel Labath   LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo));
868b9cc0c75SPavel Labath   thread.SetStoppedBySignal(signo, &info);
86986fd8e45SChaoren Lin 
87086fd8e45SChaoren Lin   // Send a stop to the debugger after we get all other threads to stop.
871b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
872511e5cdcSTodd Fiala }
873af245d11STodd Fiala 
874e7708688STamas Berghammer namespace {
875e7708688STamas Berghammer 
876b9c1b51eSKate Stone struct EmulatorBaton {
877d37349f3SPavel Labath   NativeProcessLinux &m_process;
878d37349f3SPavel Labath   NativeRegisterContext &m_reg_context;
8796648fcc3SPavel Labath 
8806648fcc3SPavel Labath   // eRegisterKindDWARF -> RegsiterValue
8816648fcc3SPavel Labath   std::unordered_map<uint32_t, RegisterValue> m_register_values;
882e7708688STamas Berghammer 
883d37349f3SPavel Labath   EmulatorBaton(NativeProcessLinux &process, NativeRegisterContext &reg_context)
884b9c1b51eSKate Stone       : m_process(process), m_reg_context(reg_context) {}
885e7708688STamas Berghammer };
886e7708688STamas Berghammer 
887e7708688STamas Berghammer } // anonymous namespace
888e7708688STamas Berghammer 
889b9c1b51eSKate Stone static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
890e7708688STamas Berghammer                                  const EmulateInstruction::Context &context,
891b9c1b51eSKate Stone                                  lldb::addr_t addr, void *dst, size_t length) {
892e7708688STamas Berghammer   EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
893e7708688STamas Berghammer 
8943eb4b458SChaoren Lin   size_t bytes_read;
895d37349f3SPavel Labath   emulator_baton->m_process.ReadMemory(addr, dst, length, bytes_read);
896e7708688STamas Berghammer   return bytes_read;
897e7708688STamas Berghammer }
898e7708688STamas Berghammer 
899b9c1b51eSKate Stone static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
900e7708688STamas Berghammer                                  const RegisterInfo *reg_info,
901b9c1b51eSKate Stone                                  RegisterValue &reg_value) {
902e7708688STamas Berghammer   EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
903e7708688STamas Berghammer 
904b9c1b51eSKate Stone   auto it = emulator_baton->m_register_values.find(
905b9c1b51eSKate Stone       reg_info->kinds[eRegisterKindDWARF]);
906b9c1b51eSKate Stone   if (it != emulator_baton->m_register_values.end()) {
9076648fcc3SPavel Labath     reg_value = it->second;
9086648fcc3SPavel Labath     return true;
9096648fcc3SPavel Labath   }
9106648fcc3SPavel Labath 
91105097246SAdrian Prantl   // The emulator only fill in the dwarf regsiter numbers (and in some case the
91205097246SAdrian Prantl   // generic register numbers). Get the full register info from the register
91305097246SAdrian Prantl   // context based on the dwarf register numbers.
914b9c1b51eSKate Stone   const RegisterInfo *full_reg_info =
915d37349f3SPavel Labath       emulator_baton->m_reg_context.GetRegisterInfo(
916e7708688STamas Berghammer           eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
917e7708688STamas Berghammer 
91897206d57SZachary Turner   Status error =
919d37349f3SPavel Labath       emulator_baton->m_reg_context.ReadRegister(full_reg_info, reg_value);
9206648fcc3SPavel Labath   if (error.Success())
9216648fcc3SPavel Labath     return true;
922cdc22a88SMohit K. Bhakkad 
9236648fcc3SPavel Labath   return false;
924e7708688STamas Berghammer }
925e7708688STamas Berghammer 
926b9c1b51eSKate Stone static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
927e7708688STamas Berghammer                                   const EmulateInstruction::Context &context,
928e7708688STamas Berghammer                                   const RegisterInfo *reg_info,
929b9c1b51eSKate Stone                                   const RegisterValue &reg_value) {
930e7708688STamas Berghammer   EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
931b9c1b51eSKate Stone   emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
932b9c1b51eSKate Stone       reg_value;
933e7708688STamas Berghammer   return true;
934e7708688STamas Berghammer }
935e7708688STamas Berghammer 
936b9c1b51eSKate Stone static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
937e7708688STamas Berghammer                                   const EmulateInstruction::Context &context,
938b9c1b51eSKate Stone                                   lldb::addr_t addr, const void *dst,
939b9c1b51eSKate Stone                                   size_t length) {
940e7708688STamas Berghammer   return length;
941e7708688STamas Berghammer }
942e7708688STamas Berghammer 
943d37349f3SPavel Labath static lldb::addr_t ReadFlags(NativeRegisterContext &regsiter_context) {
944d37349f3SPavel Labath   const RegisterInfo *flags_info = regsiter_context.GetRegisterInfo(
945e7708688STamas Berghammer       eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
946d37349f3SPavel Labath   return regsiter_context.ReadRegisterAsUnsigned(flags_info,
947b9c1b51eSKate Stone                                                  LLDB_INVALID_ADDRESS);
948e7708688STamas Berghammer }
949e7708688STamas Berghammer 
95097206d57SZachary Turner Status
95197206d57SZachary Turner NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadLinux &thread) {
95297206d57SZachary Turner   Status error;
953d37349f3SPavel Labath   NativeRegisterContext& register_context = thread.GetRegisterContext();
954e7708688STamas Berghammer 
955e7708688STamas Berghammer   std::unique_ptr<EmulateInstruction> emulator_ap(
956b9c1b51eSKate Stone       EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying,
957b9c1b51eSKate Stone                                      nullptr));
958e7708688STamas Berghammer 
959e7708688STamas Berghammer   if (emulator_ap == nullptr)
96097206d57SZachary Turner     return Status("Instruction emulator not found!");
961e7708688STamas Berghammer 
962d37349f3SPavel Labath   EmulatorBaton baton(*this, register_context);
963e7708688STamas Berghammer   emulator_ap->SetBaton(&baton);
964e7708688STamas Berghammer   emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
965e7708688STamas Berghammer   emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
966e7708688STamas Berghammer   emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
967e7708688STamas Berghammer   emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
968e7708688STamas Berghammer 
969e7708688STamas Berghammer   if (!emulator_ap->ReadInstruction())
97097206d57SZachary Turner     return Status("Read instruction failed!");
971e7708688STamas Berghammer 
972b9c1b51eSKate Stone   bool emulation_result =
973b9c1b51eSKate Stone       emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
9746648fcc3SPavel Labath 
975d37349f3SPavel Labath   const RegisterInfo *reg_info_pc = register_context.GetRegisterInfo(
976b9c1b51eSKate Stone       eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
977d37349f3SPavel Labath   const RegisterInfo *reg_info_flags = register_context.GetRegisterInfo(
978b9c1b51eSKate Stone       eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
9796648fcc3SPavel Labath 
980b9c1b51eSKate Stone   auto pc_it =
981b9c1b51eSKate Stone       baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
982b9c1b51eSKate Stone   auto flags_it =
983b9c1b51eSKate Stone       baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
9846648fcc3SPavel Labath 
985e7708688STamas Berghammer   lldb::addr_t next_pc;
986e7708688STamas Berghammer   lldb::addr_t next_flags;
987b9c1b51eSKate Stone   if (emulation_result) {
988b9c1b51eSKate Stone     assert(pc_it != baton.m_register_values.end() &&
989b9c1b51eSKate Stone            "Emulation was successfull but PC wasn't updated");
9906648fcc3SPavel Labath     next_pc = pc_it->second.GetAsUInt64();
9916648fcc3SPavel Labath 
9926648fcc3SPavel Labath     if (flags_it != baton.m_register_values.end())
9936648fcc3SPavel Labath       next_flags = flags_it->second.GetAsUInt64();
994e7708688STamas Berghammer     else
995d37349f3SPavel Labath       next_flags = ReadFlags(register_context);
996b9c1b51eSKate Stone   } else if (pc_it == baton.m_register_values.end()) {
99705097246SAdrian Prantl     // Emulate instruction failed and it haven't changed PC. Advance PC with
99805097246SAdrian Prantl     // the size of the current opcode because the emulation of all
999e7708688STamas Berghammer     // PC modifying instruction should be successful. The failure most
1000e7708688STamas Berghammer     // likely caused by a not supported instruction which don't modify PC.
1001d37349f3SPavel Labath     next_pc = register_context.GetPC() + emulator_ap->GetOpcode().GetByteSize();
1002d37349f3SPavel Labath     next_flags = ReadFlags(register_context);
1003b9c1b51eSKate Stone   } else {
1004e7708688STamas Berghammer     // The instruction emulation failed after it modified the PC. It is an
1005e7708688STamas Berghammer     // unknown error where we can't continue because the next instruction is
1006e7708688STamas Berghammer     // modifying the PC but we don't  know how.
100797206d57SZachary Turner     return Status("Instruction emulation failed unexpectedly.");
1008e7708688STamas Berghammer   }
1009e7708688STamas Berghammer 
1010b9c1b51eSKate Stone   if (m_arch.GetMachine() == llvm::Triple::arm) {
1011b9c1b51eSKate Stone     if (next_flags & 0x20) {
1012e7708688STamas Berghammer       // Thumb mode
1013e7708688STamas Berghammer       error = SetSoftwareBreakpoint(next_pc, 2);
1014b9c1b51eSKate Stone     } else {
1015e7708688STamas Berghammer       // Arm mode
1016e7708688STamas Berghammer       error = SetSoftwareBreakpoint(next_pc, 4);
1017e7708688STamas Berghammer     }
1018b9c1b51eSKate Stone   } else if (m_arch.GetMachine() == llvm::Triple::mips64 ||
1019b9c1b51eSKate Stone              m_arch.GetMachine() == llvm::Triple::mips64el ||
1020b9c1b51eSKate Stone              m_arch.GetMachine() == llvm::Triple::mips ||
1021aae0a752SEugene Zemtsov              m_arch.GetMachine() == llvm::Triple::mipsel ||
1022aae0a752SEugene Zemtsov              m_arch.GetMachine() == llvm::Triple::ppc64le)
1023cdc22a88SMohit K. Bhakkad     error = SetSoftwareBreakpoint(next_pc, 4);
1024b9c1b51eSKate Stone   else {
1025e7708688STamas Berghammer     // No size hint is given for the next breakpoint
1026e7708688STamas Berghammer     error = SetSoftwareBreakpoint(next_pc, 0);
1027e7708688STamas Berghammer   }
1028e7708688STamas Berghammer 
102905097246SAdrian Prantl   // If setting the breakpoint fails because next_pc is out of the address
103005097246SAdrian Prantl   // space, ignore it and let the debugee segfault.
103142eb6908SPavel Labath   if (error.GetError() == EIO || error.GetError() == EFAULT) {
103297206d57SZachary Turner     return Status();
103342eb6908SPavel Labath   } else if (error.Fail())
1034e7708688STamas Berghammer     return error;
1035e7708688STamas Berghammer 
1036b9cc0c75SPavel Labath   m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
1037e7708688STamas Berghammer 
103897206d57SZachary Turner   return Status();
1039e7708688STamas Berghammer }
1040e7708688STamas Berghammer 
1041b9c1b51eSKate Stone bool NativeProcessLinux::SupportHardwareSingleStepping() const {
1042b9c1b51eSKate Stone   if (m_arch.GetMachine() == llvm::Triple::arm ||
1043b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mips64 ||
1044b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mips64el ||
1045b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mips ||
1046b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mipsel)
1047cdc22a88SMohit K. Bhakkad     return false;
1048cdc22a88SMohit K. Bhakkad   return true;
1049e7708688STamas Berghammer }
1050e7708688STamas Berghammer 
105197206d57SZachary Turner Status NativeProcessLinux::Resume(const ResumeActionList &resume_actions) {
1052a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1053a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0}", GetID());
1054af245d11STodd Fiala 
1055e7708688STamas Berghammer   bool software_single_step = !SupportHardwareSingleStepping();
1056af245d11STodd Fiala 
1057b9c1b51eSKate Stone   if (software_single_step) {
1058a5be48b3SPavel Labath     for (const auto &thread : m_threads) {
1059a5be48b3SPavel Labath       assert(thread && "thread list should not contain NULL threads");
1060e7708688STamas Berghammer 
1061b9c1b51eSKate Stone       const ResumeAction *const action =
1062a5be48b3SPavel Labath           resume_actions.GetActionForThread(thread->GetID(), true);
1063e7708688STamas Berghammer       if (action == nullptr)
1064e7708688STamas Berghammer         continue;
1065e7708688STamas Berghammer 
1066b9c1b51eSKate Stone       if (action->state == eStateStepping) {
106797206d57SZachary Turner         Status error = SetupSoftwareSingleStepping(
1068a5be48b3SPavel Labath             static_cast<NativeThreadLinux &>(*thread));
1069e7708688STamas Berghammer         if (error.Fail())
1070e7708688STamas Berghammer           return error;
1071e7708688STamas Berghammer       }
1072e7708688STamas Berghammer     }
1073e7708688STamas Berghammer   }
1074e7708688STamas Berghammer 
1075a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
1076a5be48b3SPavel Labath     assert(thread && "thread list should not contain NULL threads");
1077af245d11STodd Fiala 
1078b9c1b51eSKate Stone     const ResumeAction *const action =
1079a5be48b3SPavel Labath         resume_actions.GetActionForThread(thread->GetID(), true);
10806a196ce6SChaoren Lin 
1081b9c1b51eSKate Stone     if (action == nullptr) {
1082a6321a8eSPavel Labath       LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
1083a5be48b3SPavel Labath                thread->GetID());
10846a196ce6SChaoren Lin       continue;
10856a196ce6SChaoren Lin     }
1086af245d11STodd Fiala 
1087a6321a8eSPavel Labath     LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}",
1088a5be48b3SPavel Labath              action->state, GetID(), thread->GetID());
1089af245d11STodd Fiala 
1090b9c1b51eSKate Stone     switch (action->state) {
1091af245d11STodd Fiala     case eStateRunning:
1092b9c1b51eSKate Stone     case eStateStepping: {
1093af245d11STodd Fiala       // Run the thread, possibly feeding it the signal.
1094fa03ad2eSChaoren Lin       const int signo = action->signal;
1095a5be48b3SPavel Labath       ResumeThread(static_cast<NativeThreadLinux &>(*thread), action->state,
1096b9c1b51eSKate Stone                    signo);
1097af245d11STodd Fiala       break;
1098ae29d395SChaoren Lin     }
1099af245d11STodd Fiala 
1100af245d11STodd Fiala     case eStateSuspended:
1101af245d11STodd Fiala     case eStateStopped:
1102a6321a8eSPavel Labath       llvm_unreachable("Unexpected state");
1103af245d11STodd Fiala 
1104af245d11STodd Fiala     default:
110597206d57SZachary Turner       return Status("NativeProcessLinux::%s (): unexpected state %s specified "
1106b9c1b51eSKate Stone                     "for pid %" PRIu64 ", tid %" PRIu64,
1107b9c1b51eSKate Stone                     __FUNCTION__, StateAsCString(action->state), GetID(),
1108a5be48b3SPavel Labath                     thread->GetID());
1109af245d11STodd Fiala     }
1110af245d11STodd Fiala   }
1111af245d11STodd Fiala 
111297206d57SZachary Turner   return Status();
1113af245d11STodd Fiala }
1114af245d11STodd Fiala 
111597206d57SZachary Turner Status NativeProcessLinux::Halt() {
111697206d57SZachary Turner   Status error;
1117af245d11STodd Fiala 
1118af245d11STodd Fiala   if (kill(GetID(), SIGSTOP) != 0)
1119af245d11STodd Fiala     error.SetErrorToErrno();
1120af245d11STodd Fiala 
1121af245d11STodd Fiala   return error;
1122af245d11STodd Fiala }
1123af245d11STodd Fiala 
112497206d57SZachary Turner Status NativeProcessLinux::Detach() {
112597206d57SZachary Turner   Status error;
1126af245d11STodd Fiala 
1127af245d11STodd Fiala   // Stop monitoring the inferior.
112819cbe96aSPavel Labath   m_sigchld_handle.reset();
1129af245d11STodd Fiala 
11307a9495bcSPavel Labath   // Tell ptrace to detach from the process.
11317a9495bcSPavel Labath   if (GetID() == LLDB_INVALID_PROCESS_ID)
11327a9495bcSPavel Labath     return error;
11337a9495bcSPavel Labath 
1134a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
1135a5be48b3SPavel Labath     Status e = Detach(thread->GetID());
11367a9495bcSPavel Labath     if (e.Fail())
1137b9c1b51eSKate Stone       error =
1138b9c1b51eSKate Stone           e; // Save the error, but still attempt to detach from other threads.
11397a9495bcSPavel Labath   }
11407a9495bcSPavel Labath 
114199e37695SRavitheja Addepally   m_processor_trace_monitor.clear();
114299e37695SRavitheja Addepally   m_pt_proces_trace_id = LLDB_INVALID_UID;
114399e37695SRavitheja Addepally 
1144af245d11STodd Fiala   return error;
1145af245d11STodd Fiala }
1146af245d11STodd Fiala 
114797206d57SZachary Turner Status NativeProcessLinux::Signal(int signo) {
114897206d57SZachary Turner   Status error;
1149af245d11STodd Fiala 
1150a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1151a6321a8eSPavel Labath   LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo,
1152a6321a8eSPavel Labath            Host::GetSignalAsCString(signo), GetID());
1153af245d11STodd Fiala 
1154af245d11STodd Fiala   if (kill(GetID(), signo))
1155af245d11STodd Fiala     error.SetErrorToErrno();
1156af245d11STodd Fiala 
1157af245d11STodd Fiala   return error;
1158af245d11STodd Fiala }
1159af245d11STodd Fiala 
116097206d57SZachary Turner Status NativeProcessLinux::Interrupt() {
116105097246SAdrian Prantl   // Pick a running thread (or if none, a not-dead stopped thread) as the
116205097246SAdrian Prantl   // chosen thread that will be the stop-reason thread.
1163a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1164e9547b80SChaoren Lin 
1165a5be48b3SPavel Labath   NativeThreadProtocol *running_thread = nullptr;
1166a5be48b3SPavel Labath   NativeThreadProtocol *stopped_thread = nullptr;
1167e9547b80SChaoren Lin 
1168a6321a8eSPavel Labath   LLDB_LOG(log, "selecting running thread for interrupt target");
1169a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
117005097246SAdrian Prantl     // If we have a running or stepping thread, we'll call that the target of
117105097246SAdrian Prantl     // the interrupt.
1172a5be48b3SPavel Labath     const auto thread_state = thread->GetState();
1173b9c1b51eSKate Stone     if (thread_state == eStateRunning || thread_state == eStateStepping) {
1174a5be48b3SPavel Labath       running_thread = thread.get();
1175e9547b80SChaoren Lin       break;
1176a5be48b3SPavel Labath     } else if (!stopped_thread && StateIsStoppedState(thread_state, true)) {
117705097246SAdrian Prantl       // Remember the first non-dead stopped thread.  We'll use that as a
117805097246SAdrian Prantl       // backup if there are no running threads.
1179a5be48b3SPavel Labath       stopped_thread = thread.get();
1180e9547b80SChaoren Lin     }
1181e9547b80SChaoren Lin   }
1182e9547b80SChaoren Lin 
1183a5be48b3SPavel Labath   if (!running_thread && !stopped_thread) {
118497206d57SZachary Turner     Status error("found no running/stepping or live stopped threads as target "
1185b9c1b51eSKate Stone                  "for interrupt");
1186a6321a8eSPavel Labath     LLDB_LOG(log, "skipping due to error: {0}", error);
11875830aa75STamas Berghammer 
1188e9547b80SChaoren Lin     return error;
1189e9547b80SChaoren Lin   }
1190e9547b80SChaoren Lin 
1191a5be48b3SPavel Labath   NativeThreadProtocol *deferred_signal_thread =
1192a5be48b3SPavel Labath       running_thread ? running_thread : stopped_thread;
1193e9547b80SChaoren Lin 
1194a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(),
1195a5be48b3SPavel Labath            running_thread ? "running" : "stopped",
1196a5be48b3SPavel Labath            deferred_signal_thread->GetID());
1197e9547b80SChaoren Lin 
1198a5be48b3SPavel Labath   StopRunningThreads(deferred_signal_thread->GetID());
119945f5cb31SPavel Labath 
120097206d57SZachary Turner   return Status();
1201e9547b80SChaoren Lin }
1202e9547b80SChaoren Lin 
120397206d57SZachary Turner Status NativeProcessLinux::Kill() {
1204a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1205a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0}", GetID());
1206af245d11STodd Fiala 
120797206d57SZachary Turner   Status error;
1208af245d11STodd Fiala 
1209b9c1b51eSKate Stone   switch (m_state) {
1210af245d11STodd Fiala   case StateType::eStateInvalid:
1211af245d11STodd Fiala   case StateType::eStateExited:
1212af245d11STodd Fiala   case StateType::eStateCrashed:
1213af245d11STodd Fiala   case StateType::eStateDetached:
1214af245d11STodd Fiala   case StateType::eStateUnloaded:
1215af245d11STodd Fiala     // Nothing to do - the process is already dead.
1216a6321a8eSPavel Labath     LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
12178198db30SPavel Labath              m_state);
1218af245d11STodd Fiala     return error;
1219af245d11STodd Fiala 
1220af245d11STodd Fiala   case StateType::eStateConnected:
1221af245d11STodd Fiala   case StateType::eStateAttaching:
1222af245d11STodd Fiala   case StateType::eStateLaunching:
1223af245d11STodd Fiala   case StateType::eStateStopped:
1224af245d11STodd Fiala   case StateType::eStateRunning:
1225af245d11STodd Fiala   case StateType::eStateStepping:
1226af245d11STodd Fiala   case StateType::eStateSuspended:
1227af245d11STodd Fiala     // We can try to kill a process in these states.
1228af245d11STodd Fiala     break;
1229af245d11STodd Fiala   }
1230af245d11STodd Fiala 
1231b9c1b51eSKate Stone   if (kill(GetID(), SIGKILL) != 0) {
1232af245d11STodd Fiala     error.SetErrorToErrno();
1233af245d11STodd Fiala     return error;
1234af245d11STodd Fiala   }
1235af245d11STodd Fiala 
1236af245d11STodd Fiala   return error;
1237af245d11STodd Fiala }
1238af245d11STodd Fiala 
123997206d57SZachary Turner static Status
124015930862SPavel Labath ParseMemoryRegionInfoFromProcMapsLine(llvm::StringRef &maps_line,
1241b9c1b51eSKate Stone                                       MemoryRegionInfo &memory_region_info) {
1242af245d11STodd Fiala   memory_region_info.Clear();
1243af245d11STodd Fiala 
124415930862SPavel Labath   StringExtractor line_extractor(maps_line);
1245af245d11STodd Fiala 
1246b9c1b51eSKate Stone   // Format: {address_start_hex}-{address_end_hex} perms offset  dev   inode
124705097246SAdrian Prantl   // pathname perms: rwxp   (letter is present if set, '-' if not, final
124805097246SAdrian Prantl   // character is p=private, s=shared).
1249af245d11STodd Fiala 
1250af245d11STodd Fiala   // Parse out the starting address
1251af245d11STodd Fiala   lldb::addr_t start_address = line_extractor.GetHexMaxU64(false, 0);
1252af245d11STodd Fiala 
1253af245d11STodd Fiala   // Parse out hyphen separating start and end address from range.
1254af245d11STodd Fiala   if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != '-'))
125597206d57SZachary Turner     return Status(
1256b9c1b51eSKate Stone         "malformed /proc/{pid}/maps entry, missing dash between address range");
1257af245d11STodd Fiala 
1258af245d11STodd Fiala   // Parse out the ending address
1259af245d11STodd Fiala   lldb::addr_t end_address = line_extractor.GetHexMaxU64(false, start_address);
1260af245d11STodd Fiala 
1261af245d11STodd Fiala   // Parse out the space after the address.
1262af245d11STodd Fiala   if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != ' '))
126397206d57SZachary Turner     return Status(
126497206d57SZachary Turner         "malformed /proc/{pid}/maps entry, missing space after range");
1265af245d11STodd Fiala 
1266af245d11STodd Fiala   // Save the range.
1267af245d11STodd Fiala   memory_region_info.GetRange().SetRangeBase(start_address);
1268af245d11STodd Fiala   memory_region_info.GetRange().SetRangeEnd(end_address);
1269af245d11STodd Fiala 
1270b9c1b51eSKate Stone   // Any memory region in /proc/{pid}/maps is by definition mapped into the
1271b9c1b51eSKate Stone   // process.
1272ad007563SHoward Hellyer   memory_region_info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
1273ad007563SHoward Hellyer 
1274af245d11STodd Fiala   // Parse out each permission entry.
1275af245d11STodd Fiala   if (line_extractor.GetBytesLeft() < 4)
127697206d57SZachary Turner     return Status("malformed /proc/{pid}/maps entry, missing some portion of "
1277b9c1b51eSKate Stone                   "permissions");
1278af245d11STodd Fiala 
1279af245d11STodd Fiala   // Handle read permission.
1280af245d11STodd Fiala   const char read_perm_char = line_extractor.GetChar();
1281af245d11STodd Fiala   if (read_perm_char == 'r')
1282af245d11STodd Fiala     memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eYes);
1283c73301bbSTamas Berghammer   else if (read_perm_char == '-')
1284af245d11STodd Fiala     memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1285c73301bbSTamas Berghammer   else
128697206d57SZachary Turner     return Status("unexpected /proc/{pid}/maps read permission char");
1287af245d11STodd Fiala 
1288af245d11STodd Fiala   // Handle write permission.
1289af245d11STodd Fiala   const char write_perm_char = line_extractor.GetChar();
1290af245d11STodd Fiala   if (write_perm_char == 'w')
1291af245d11STodd Fiala     memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eYes);
1292c73301bbSTamas Berghammer   else if (write_perm_char == '-')
1293af245d11STodd Fiala     memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1294c73301bbSTamas Berghammer   else
129597206d57SZachary Turner     return Status("unexpected /proc/{pid}/maps write permission char");
1296af245d11STodd Fiala 
1297af245d11STodd Fiala   // Handle execute permission.
1298af245d11STodd Fiala   const char exec_perm_char = line_extractor.GetChar();
1299af245d11STodd Fiala   if (exec_perm_char == 'x')
1300af245d11STodd Fiala     memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes);
1301c73301bbSTamas Berghammer   else if (exec_perm_char == '-')
1302af245d11STodd Fiala     memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1303c73301bbSTamas Berghammer   else
130497206d57SZachary Turner     return Status("unexpected /proc/{pid}/maps exec permission char");
1305af245d11STodd Fiala 
1306d7d69f80STamas Berghammer   line_extractor.GetChar();              // Read the private bit
1307d7d69f80STamas Berghammer   line_extractor.SkipSpaces();           // Skip the separator
1308d7d69f80STamas Berghammer   line_extractor.GetHexMaxU64(false, 0); // Read the offset
1309d7d69f80STamas Berghammer   line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1310d7d69f80STamas Berghammer   line_extractor.GetChar();              // Read the device id separator
1311d7d69f80STamas Berghammer   line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1312d7d69f80STamas Berghammer   line_extractor.SkipSpaces();           // Skip the separator
1313d7d69f80STamas Berghammer   line_extractor.GetU64(0, 10);          // Read the inode number
1314d7d69f80STamas Berghammer 
1315d7d69f80STamas Berghammer   line_extractor.SkipSpaces();
1316b9739d40SPavel Labath   const char *name = line_extractor.Peek();
1317b9739d40SPavel Labath   if (name)
1318b9739d40SPavel Labath     memory_region_info.SetName(name);
1319d7d69f80STamas Berghammer 
132097206d57SZachary Turner   return Status();
1321af245d11STodd Fiala }
1322af245d11STodd Fiala 
132397206d57SZachary Turner Status NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr,
1324b9c1b51eSKate Stone                                                MemoryRegionInfo &range_info) {
1325b9c1b51eSKate Stone   // FIXME review that the final memory region returned extends to the end of
1326b9c1b51eSKate Stone   // the virtual address space,
1327af245d11STodd Fiala   // with no perms if it is not mapped.
1328af245d11STodd Fiala 
132905097246SAdrian Prantl   // Use an approach that reads memory regions from /proc/{pid}/maps. Assume
133005097246SAdrian Prantl   // proc maps entries are in ascending order.
1331af245d11STodd Fiala   // FIXME assert if we find differently.
1332af245d11STodd Fiala 
1333b9c1b51eSKate Stone   if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
1334af245d11STodd Fiala     // We're done.
133597206d57SZachary Turner     return Status("unsupported");
1336af245d11STodd Fiala   }
1337af245d11STodd Fiala 
133897206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
1339b9c1b51eSKate Stone   if (error.Fail()) {
1340af245d11STodd Fiala     return error;
1341af245d11STodd Fiala   }
1342af245d11STodd Fiala 
1343af245d11STodd Fiala   lldb::addr_t prev_base_address = 0;
1344af245d11STodd Fiala 
1345b9c1b51eSKate Stone   // FIXME start by finding the last region that is <= target address using
1346b9c1b51eSKate Stone   // binary search.  Data is sorted.
1347af245d11STodd Fiala   // There can be a ton of regions on pthreads apps with lots of threads.
1348b9c1b51eSKate Stone   for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1349b9c1b51eSKate Stone        ++it) {
1350a6f5795aSTamas Berghammer     MemoryRegionInfo &proc_entry_info = it->first;
1351af245d11STodd Fiala 
1352af245d11STodd Fiala     // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1353b9c1b51eSKate Stone     assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
1354b9c1b51eSKate Stone            "descending /proc/pid/maps entries detected, unexpected");
1355af245d11STodd Fiala     prev_base_address = proc_entry_info.GetRange().GetRangeBase();
1356b1554311SHafiz Abid Qadeer     UNUSED_IF_ASSERT_DISABLED(prev_base_address);
1357af245d11STodd Fiala 
1358b9c1b51eSKate Stone     // If the target address comes before this entry, indicate distance to next
1359b9c1b51eSKate Stone     // region.
1360b9c1b51eSKate Stone     if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1361af245d11STodd Fiala       range_info.GetRange().SetRangeBase(load_addr);
1362b9c1b51eSKate Stone       range_info.GetRange().SetByteSize(
1363b9c1b51eSKate Stone           proc_entry_info.GetRange().GetRangeBase() - load_addr);
1364af245d11STodd Fiala       range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1365af245d11STodd Fiala       range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1366af245d11STodd Fiala       range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1367ad007563SHoward Hellyer       range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1368af245d11STodd Fiala 
1369af245d11STodd Fiala       return error;
1370b9c1b51eSKate Stone     } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1371af245d11STodd Fiala       // The target address is within the memory region we're processing here.
1372af245d11STodd Fiala       range_info = proc_entry_info;
1373af245d11STodd Fiala       return error;
1374af245d11STodd Fiala     }
1375af245d11STodd Fiala 
1376b9c1b51eSKate Stone     // The target memory address comes somewhere after the region we just
1377b9c1b51eSKate Stone     // parsed.
1378af245d11STodd Fiala   }
1379af245d11STodd Fiala 
1380b9c1b51eSKate Stone   // If we made it here, we didn't find an entry that contained the given
138105097246SAdrian Prantl   // address. Return the load_addr as start and the amount of bytes betwwen
138205097246SAdrian Prantl   // load address and the end of the memory as size.
138309839c33STamas Berghammer   range_info.GetRange().SetRangeBase(load_addr);
1384ad007563SHoward Hellyer   range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
138509839c33STamas Berghammer   range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
138609839c33STamas Berghammer   range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
138709839c33STamas Berghammer   range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1388ad007563SHoward Hellyer   range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1389af245d11STodd Fiala   return error;
1390af245d11STodd Fiala }
1391af245d11STodd Fiala 
139297206d57SZachary Turner Status NativeProcessLinux::PopulateMemoryRegionCache() {
1393a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1394a6f5795aSTamas Berghammer 
1395a6f5795aSTamas Berghammer   // If our cache is empty, pull the latest.  There should always be at least
1396a6f5795aSTamas Berghammer   // one memory region if memory region handling is supported.
1397a6f5795aSTamas Berghammer   if (!m_mem_region_cache.empty()) {
1398a6321a8eSPavel Labath     LLDB_LOG(log, "reusing {0} cached memory region entries",
1399a6321a8eSPavel Labath              m_mem_region_cache.size());
140097206d57SZachary Turner     return Status();
1401a6f5795aSTamas Berghammer   }
1402a6f5795aSTamas Berghammer 
140315930862SPavel Labath   auto BufferOrError = getProcFile(GetID(), "maps");
140415930862SPavel Labath   if (!BufferOrError) {
140515930862SPavel Labath     m_supports_mem_region = LazyBool::eLazyBoolNo;
140615930862SPavel Labath     return BufferOrError.getError();
140715930862SPavel Labath   }
140815930862SPavel Labath   StringRef Rest = BufferOrError.get()->getBuffer();
140915930862SPavel Labath   while (! Rest.empty()) {
141015930862SPavel Labath     StringRef Line;
141115930862SPavel Labath     std::tie(Line, Rest) = Rest.split('\n');
1412a6f5795aSTamas Berghammer     MemoryRegionInfo info;
141397206d57SZachary Turner     const Status parse_error =
141497206d57SZachary Turner         ParseMemoryRegionInfoFromProcMapsLine(Line, info);
141515930862SPavel Labath     if (parse_error.Fail()) {
141615930862SPavel Labath       LLDB_LOG(log, "failed to parse proc maps line '{0}': {1}", Line,
141715930862SPavel Labath                parse_error);
141815930862SPavel Labath       m_supports_mem_region = LazyBool::eLazyBoolNo;
141915930862SPavel Labath       return parse_error;
142015930862SPavel Labath     }
1421*8f3be7a3SJonas Devlieghere     FileSpec file_spec(info.GetName().GetCString());
1422*8f3be7a3SJonas Devlieghere     FileSystem::Instance().Resolve(file_spec);
1423*8f3be7a3SJonas Devlieghere     m_mem_region_cache.emplace_back(info, file_spec);
1424a6f5795aSTamas Berghammer   }
1425a6f5795aSTamas Berghammer 
142615930862SPavel Labath   if (m_mem_region_cache.empty()) {
1427a6f5795aSTamas Berghammer     // No entries after attempting to read them.  This shouldn't happen if
142805097246SAdrian Prantl     // /proc/{pid}/maps is supported. Assume we don't support map entries via
142905097246SAdrian Prantl     // procfs.
143015930862SPavel Labath     m_supports_mem_region = LazyBool::eLazyBoolNo;
1431a6321a8eSPavel Labath     LLDB_LOG(log,
1432a6321a8eSPavel Labath              "failed to find any procfs maps entries, assuming no support "
1433a6321a8eSPavel Labath              "for memory region metadata retrieval");
143497206d57SZachary Turner     return Status("not supported");
1435a6f5795aSTamas Berghammer   }
1436a6f5795aSTamas Berghammer 
1437a6321a8eSPavel Labath   LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps",
1438a6321a8eSPavel Labath            m_mem_region_cache.size(), GetID());
1439a6f5795aSTamas Berghammer 
1440a6f5795aSTamas Berghammer   // We support memory retrieval, remember that.
1441a6f5795aSTamas Berghammer   m_supports_mem_region = LazyBool::eLazyBoolYes;
144297206d57SZachary Turner   return Status();
1443a6f5795aSTamas Berghammer }
1444a6f5795aSTamas Berghammer 
1445b9c1b51eSKate Stone void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
1446a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1447a6321a8eSPavel Labath   LLDB_LOG(log, "newBumpId={0}", newBumpId);
1448a6321a8eSPavel Labath   LLDB_LOG(log, "clearing {0} entries from memory region cache",
1449a6321a8eSPavel Labath            m_mem_region_cache.size());
1450af245d11STodd Fiala   m_mem_region_cache.clear();
1451af245d11STodd Fiala }
1452af245d11STodd Fiala 
145397206d57SZachary Turner Status NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions,
1454b9c1b51eSKate Stone                                           lldb::addr_t &addr) {
1455af245d11STodd Fiala // FIXME implementing this requires the equivalent of
145605097246SAdrian Prantl // InferiorCallPOSIX::InferiorCallMmap, which depends on functional ThreadPlans
145705097246SAdrian Prantl // working with Native*Protocol.
1458af245d11STodd Fiala #if 1
145997206d57SZachary Turner   return Status("not implemented yet");
1460af245d11STodd Fiala #else
1461af245d11STodd Fiala   addr = LLDB_INVALID_ADDRESS;
1462af245d11STodd Fiala 
1463af245d11STodd Fiala   unsigned prot = 0;
1464af245d11STodd Fiala   if (permissions & lldb::ePermissionsReadable)
1465af245d11STodd Fiala     prot |= eMmapProtRead;
1466af245d11STodd Fiala   if (permissions & lldb::ePermissionsWritable)
1467af245d11STodd Fiala     prot |= eMmapProtWrite;
1468af245d11STodd Fiala   if (permissions & lldb::ePermissionsExecutable)
1469af245d11STodd Fiala     prot |= eMmapProtExec;
1470af245d11STodd Fiala 
1471af245d11STodd Fiala   // TODO implement this directly in NativeProcessLinux
147205097246SAdrian Prantl   // (and lift to NativeProcessPOSIX if/when that class is refactored out).
1473af245d11STodd Fiala   if (InferiorCallMmap(this, addr, 0, size, prot,
1474af245d11STodd Fiala                        eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
1475af245d11STodd Fiala     m_addr_to_mmap_size[addr] = size;
147697206d57SZachary Turner     return Status();
1477af245d11STodd Fiala   } else {
1478af245d11STodd Fiala     addr = LLDB_INVALID_ADDRESS;
147997206d57SZachary Turner     return Status("unable to allocate %" PRIu64
1480b9c1b51eSKate Stone                   " bytes of memory with permissions %s",
1481b9c1b51eSKate Stone                   size, GetPermissionsAsCString(permissions));
1482af245d11STodd Fiala   }
1483af245d11STodd Fiala #endif
1484af245d11STodd Fiala }
1485af245d11STodd Fiala 
148697206d57SZachary Turner Status NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {
1487af245d11STodd Fiala   // FIXME see comments in AllocateMemory - required lower-level
1488af245d11STodd Fiala   // bits not in place yet (ThreadPlans)
148997206d57SZachary Turner   return Status("not implemented");
1490af245d11STodd Fiala }
1491af245d11STodd Fiala 
1492b9c1b51eSKate Stone lldb::addr_t NativeProcessLinux::GetSharedLibraryInfoAddress() {
1493af245d11STodd Fiala   // punt on this for now
1494af245d11STodd Fiala   return LLDB_INVALID_ADDRESS;
1495af245d11STodd Fiala }
1496af245d11STodd Fiala 
1497b9c1b51eSKate Stone size_t NativeProcessLinux::UpdateThreads() {
149805097246SAdrian Prantl   // The NativeProcessLinux monitoring threads are always up to date with
149905097246SAdrian Prantl   // respect to thread state and they keep the thread list populated properly.
150005097246SAdrian Prantl   // All this method needs to do is return the thread count.
1501af245d11STodd Fiala   return m_threads.size();
1502af245d11STodd Fiala }
1503af245d11STodd Fiala 
150497206d57SZachary Turner Status NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,
1505b9c1b51eSKate Stone                                          bool hardware) {
1506af245d11STodd Fiala   if (hardware)
1507d5ffbad2SOmair Javaid     return SetHardwareBreakpoint(addr, size);
1508af245d11STodd Fiala   else
1509af245d11STodd Fiala     return SetSoftwareBreakpoint(addr, size);
1510af245d11STodd Fiala }
1511af245d11STodd Fiala 
151297206d57SZachary Turner Status NativeProcessLinux::RemoveBreakpoint(lldb::addr_t addr, bool hardware) {
1513d5ffbad2SOmair Javaid   if (hardware)
1514d5ffbad2SOmair Javaid     return RemoveHardwareBreakpoint(addr);
1515d5ffbad2SOmair Javaid   else
1516d5ffbad2SOmair Javaid     return NativeProcessProtocol::RemoveBreakpoint(addr);
1517d5ffbad2SOmair Javaid }
1518d5ffbad2SOmair Javaid 
1519f8b825f6SPavel Labath llvm::Expected<llvm::ArrayRef<uint8_t>>
1520f8b825f6SPavel Labath NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(size_t size_hint) {
1521be379e15STamas Berghammer   // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1522be379e15STamas Berghammer   // linux kernel does otherwise.
1523f8b825f6SPavel Labath   static const uint8_t g_arm_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1524f8b825f6SPavel Labath   static const uint8_t g_thumb_opcode[] = {0x01, 0xde};
152512286a27SPavel Labath 
1526f8b825f6SPavel Labath   switch (GetArchitecture().GetMachine()) {
152712286a27SPavel Labath   case llvm::Triple::arm:
1528f8b825f6SPavel Labath     switch (size_hint) {
152963c8be95STamas Berghammer     case 2:
15304f545074SPavel Labath       return llvm::makeArrayRef(g_thumb_opcode);
153163c8be95STamas Berghammer     case 4:
15324f545074SPavel Labath       return llvm::makeArrayRef(g_arm_opcode);
153363c8be95STamas Berghammer     default:
1534f8b825f6SPavel Labath       return llvm::createStringError(llvm::inconvertibleErrorCode(),
1535f8b825f6SPavel Labath                                      "Unrecognised trap opcode size hint!");
153663c8be95STamas Berghammer     }
1537af245d11STodd Fiala   default:
1538f8b825f6SPavel Labath     return NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_hint);
1539af245d11STodd Fiala   }
1540af245d11STodd Fiala }
1541af245d11STodd Fiala 
154297206d57SZachary Turner Status NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
1543b9c1b51eSKate Stone                                       size_t &bytes_read) {
1544df7c6995SPavel Labath   if (ProcessVmReadvSupported()) {
1545b9c1b51eSKate Stone     // The process_vm_readv path is about 50 times faster than ptrace api. We
154605097246SAdrian Prantl     // want to use this syscall if it is supported.
1547df7c6995SPavel Labath 
1548df7c6995SPavel Labath     const ::pid_t pid = GetID();
1549df7c6995SPavel Labath 
1550df7c6995SPavel Labath     struct iovec local_iov, remote_iov;
1551df7c6995SPavel Labath     local_iov.iov_base = buf;
1552df7c6995SPavel Labath     local_iov.iov_len = size;
1553df7c6995SPavel Labath     remote_iov.iov_base = reinterpret_cast<void *>(addr);
1554df7c6995SPavel Labath     remote_iov.iov_len = size;
1555df7c6995SPavel Labath 
1556df7c6995SPavel Labath     bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
1557df7c6995SPavel Labath     const bool success = bytes_read == size;
1558df7c6995SPavel Labath 
1559a6321a8eSPavel Labath     Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1560a6321a8eSPavel Labath     LLDB_LOG(log,
1561a6321a8eSPavel Labath              "using process_vm_readv to read {0} bytes from inferior "
1562a6321a8eSPavel Labath              "address {1:x}: {2}",
156310c41f37SPavel Labath              size, addr, success ? "Success" : llvm::sys::StrError(errno));
1564df7c6995SPavel Labath 
1565df7c6995SPavel Labath     if (success)
156697206d57SZachary Turner       return Status();
1567a6321a8eSPavel Labath     // else the call failed for some reason, let's retry the read using ptrace
1568b9c1b51eSKate Stone     // api.
1569df7c6995SPavel Labath   }
1570df7c6995SPavel Labath 
157119cbe96aSPavel Labath   unsigned char *dst = static_cast<unsigned char *>(buf);
157219cbe96aSPavel Labath   size_t remainder;
157319cbe96aSPavel Labath   long data;
157419cbe96aSPavel Labath 
1575a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1576a6321a8eSPavel Labath   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
157719cbe96aSPavel Labath 
1578b9c1b51eSKate Stone   for (bytes_read = 0; bytes_read < size; bytes_read += remainder) {
157997206d57SZachary Turner     Status error = NativeProcessLinux::PtraceWrapper(
1580b9c1b51eSKate Stone         PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data);
1581a6321a8eSPavel Labath     if (error.Fail())
158219cbe96aSPavel Labath       return error;
158319cbe96aSPavel Labath 
158419cbe96aSPavel Labath     remainder = size - bytes_read;
158519cbe96aSPavel Labath     remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
158619cbe96aSPavel Labath 
158719cbe96aSPavel Labath     // Copy the data into our buffer
1588f6ef187bSMohit K. Bhakkad     memcpy(dst, &data, remainder);
158919cbe96aSPavel Labath 
1590a6321a8eSPavel Labath     LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
159119cbe96aSPavel Labath     addr += k_ptrace_word_size;
159219cbe96aSPavel Labath     dst += k_ptrace_word_size;
159319cbe96aSPavel Labath   }
159497206d57SZachary Turner   return Status();
1595af245d11STodd Fiala }
1596af245d11STodd Fiala 
159797206d57SZachary Turner Status NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,
1598b9c1b51eSKate Stone                                        size_t size, size_t &bytes_written) {
159919cbe96aSPavel Labath   const unsigned char *src = static_cast<const unsigned char *>(buf);
160019cbe96aSPavel Labath   size_t remainder;
160197206d57SZachary Turner   Status error;
160219cbe96aSPavel Labath 
1603a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1604a6321a8eSPavel Labath   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
160519cbe96aSPavel Labath 
1606b9c1b51eSKate Stone   for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
160719cbe96aSPavel Labath     remainder = size - bytes_written;
160819cbe96aSPavel Labath     remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
160919cbe96aSPavel Labath 
1610b9c1b51eSKate Stone     if (remainder == k_ptrace_word_size) {
161119cbe96aSPavel Labath       unsigned long data = 0;
1612f6ef187bSMohit K. Bhakkad       memcpy(&data, src, k_ptrace_word_size);
161319cbe96aSPavel Labath 
1614a6321a8eSPavel Labath       LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
1615b9c1b51eSKate Stone       error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(),
1616b9c1b51eSKate Stone                                                 (void *)addr, (void *)data);
1617a6321a8eSPavel Labath       if (error.Fail())
161819cbe96aSPavel Labath         return error;
1619b9c1b51eSKate Stone     } else {
162019cbe96aSPavel Labath       unsigned char buff[8];
162119cbe96aSPavel Labath       size_t bytes_read;
162219cbe96aSPavel Labath       error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
1623a6321a8eSPavel Labath       if (error.Fail())
162419cbe96aSPavel Labath         return error;
162519cbe96aSPavel Labath 
162619cbe96aSPavel Labath       memcpy(buff, src, remainder);
162719cbe96aSPavel Labath 
162819cbe96aSPavel Labath       size_t bytes_written_rec;
162919cbe96aSPavel Labath       error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
1630a6321a8eSPavel Labath       if (error.Fail())
163119cbe96aSPavel Labath         return error;
163219cbe96aSPavel Labath 
1633a6321a8eSPavel Labath       LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src,
1634b9c1b51eSKate Stone                *(unsigned long *)buff);
163519cbe96aSPavel Labath     }
163619cbe96aSPavel Labath 
163719cbe96aSPavel Labath     addr += k_ptrace_word_size;
163819cbe96aSPavel Labath     src += k_ptrace_word_size;
163919cbe96aSPavel Labath   }
164019cbe96aSPavel Labath   return error;
1641af245d11STodd Fiala }
1642af245d11STodd Fiala 
164397206d57SZachary Turner Status NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) {
164419cbe96aSPavel Labath   return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
1645af245d11STodd Fiala }
1646af245d11STodd Fiala 
164797206d57SZachary Turner Status NativeProcessLinux::GetEventMessage(lldb::tid_t tid,
1648b9c1b51eSKate Stone                                            unsigned long *message) {
164919cbe96aSPavel Labath   return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
1650af245d11STodd Fiala }
1651af245d11STodd Fiala 
165297206d57SZachary Turner Status NativeProcessLinux::Detach(lldb::tid_t tid) {
165397ccc294SChaoren Lin   if (tid == LLDB_INVALID_THREAD_ID)
165497206d57SZachary Turner     return Status();
165597ccc294SChaoren Lin 
165619cbe96aSPavel Labath   return PtraceWrapper(PTRACE_DETACH, tid);
1657af245d11STodd Fiala }
1658af245d11STodd Fiala 
1659b9c1b51eSKate Stone bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {
1660a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
1661a5be48b3SPavel Labath     assert(thread && "thread list should not contain NULL threads");
1662a5be48b3SPavel Labath     if (thread->GetID() == thread_id) {
1663af245d11STodd Fiala       // We have this thread.
1664af245d11STodd Fiala       return true;
1665af245d11STodd Fiala     }
1666af245d11STodd Fiala   }
1667af245d11STodd Fiala 
1668af245d11STodd Fiala   // We don't have this thread.
1669af245d11STodd Fiala   return false;
1670af245d11STodd Fiala }
1671af245d11STodd Fiala 
1672b9c1b51eSKate Stone bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) {
1673a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1674a6321a8eSPavel Labath   LLDB_LOG(log, "tid: {0})", thread_id);
16751dbc6c9cSPavel Labath 
16761dbc6c9cSPavel Labath   bool found = false;
1677b9c1b51eSKate Stone   for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
1678b9c1b51eSKate Stone     if (*it && ((*it)->GetID() == thread_id)) {
1679af245d11STodd Fiala       m_threads.erase(it);
16801dbc6c9cSPavel Labath       found = true;
16811dbc6c9cSPavel Labath       break;
1682af245d11STodd Fiala     }
1683af245d11STodd Fiala   }
1684af245d11STodd Fiala 
168599e37695SRavitheja Addepally   if (found)
168699e37695SRavitheja Addepally     StopTracingForThread(thread_id);
16879eb1ecb9SPavel Labath   SignalIfAllThreadsStopped();
16881dbc6c9cSPavel Labath   return found;
1689af245d11STodd Fiala }
1690af245d11STodd Fiala 
1691a5be48b3SPavel Labath NativeThreadLinux &NativeProcessLinux::AddThread(lldb::tid_t thread_id) {
1692a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
1693a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
1694af245d11STodd Fiala 
1695b9c1b51eSKate Stone   assert(!HasThreadNoLock(thread_id) &&
1696b9c1b51eSKate Stone          "attempted to add a thread by id that already exists");
1697af245d11STodd Fiala 
1698af245d11STodd Fiala   // If this is the first thread, save it as the current thread
1699af245d11STodd Fiala   if (m_threads.empty())
1700af245d11STodd Fiala     SetCurrentThreadID(thread_id);
1701af245d11STodd Fiala 
1702a5be48b3SPavel Labath   m_threads.push_back(llvm::make_unique<NativeThreadLinux>(*this, thread_id));
170399e37695SRavitheja Addepally 
170499e37695SRavitheja Addepally   if (m_pt_proces_trace_id != LLDB_INVALID_UID) {
170599e37695SRavitheja Addepally     auto traceMonitor = ProcessorTraceMonitor::Create(
170699e37695SRavitheja Addepally         GetID(), thread_id, m_pt_process_trace_config, true);
170799e37695SRavitheja Addepally     if (traceMonitor) {
170899e37695SRavitheja Addepally       m_pt_traced_thread_group.insert(thread_id);
170999e37695SRavitheja Addepally       m_processor_trace_monitor.insert(
171099e37695SRavitheja Addepally           std::make_pair(thread_id, std::move(*traceMonitor)));
171199e37695SRavitheja Addepally     } else {
171299e37695SRavitheja Addepally       LLDB_LOG(log, "failed to start trace on thread {0}", thread_id);
171399e37695SRavitheja Addepally       Status error(traceMonitor.takeError());
171499e37695SRavitheja Addepally       LLDB_LOG(log, "error {0}", error);
171599e37695SRavitheja Addepally     }
171699e37695SRavitheja Addepally   }
171799e37695SRavitheja Addepally 
1718a5be48b3SPavel Labath   return static_cast<NativeThreadLinux &>(*m_threads.back());
1719af245d11STodd Fiala }
1720af245d11STodd Fiala 
172197206d57SZachary Turner Status NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,
1722b9c1b51eSKate Stone                                                    FileSpec &file_spec) {
172397206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
1724a6f5795aSTamas Berghammer   if (error.Fail())
1725a6f5795aSTamas Berghammer     return error;
1726a6f5795aSTamas Berghammer 
1727*8f3be7a3SJonas Devlieghere   FileSpec module_file_spec(module_path);
1728*8f3be7a3SJonas Devlieghere   FileSystem::Instance().Resolve(module_file_spec);
17297cb18bf5STamas Berghammer 
17307cb18bf5STamas Berghammer   file_spec.Clear();
1731a6f5795aSTamas Berghammer   for (const auto &it : m_mem_region_cache) {
1732a6f5795aSTamas Berghammer     if (it.second.GetFilename() == module_file_spec.GetFilename()) {
1733a6f5795aSTamas Berghammer       file_spec = it.second;
173497206d57SZachary Turner       return Status();
1735a6f5795aSTamas Berghammer     }
1736a6f5795aSTamas Berghammer   }
173797206d57SZachary Turner   return Status("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
17387cb18bf5STamas Berghammer                 module_file_spec.GetFilename().AsCString(), GetID());
17397cb18bf5STamas Berghammer }
1740c076559aSPavel Labath 
174197206d57SZachary Turner Status NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
1742b9c1b51eSKate Stone                                               lldb::addr_t &load_addr) {
1743783bfc8cSTamas Berghammer   load_addr = LLDB_INVALID_ADDRESS;
174497206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
1745a6f5795aSTamas Berghammer   if (error.Fail())
1746783bfc8cSTamas Berghammer     return error;
1747a6f5795aSTamas Berghammer 
1748*8f3be7a3SJonas Devlieghere   FileSpec file(file_name);
1749a6f5795aSTamas Berghammer   for (const auto &it : m_mem_region_cache) {
1750a6f5795aSTamas Berghammer     if (it.second == file) {
1751a6f5795aSTamas Berghammer       load_addr = it.first.GetRange().GetRangeBase();
175297206d57SZachary Turner       return Status();
1753a6f5795aSTamas Berghammer     }
1754a6f5795aSTamas Berghammer   }
175597206d57SZachary Turner   return Status("No load address found for specified file.");
1756783bfc8cSTamas Berghammer }
1757783bfc8cSTamas Berghammer 
1758a5be48b3SPavel Labath NativeThreadLinux *NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {
1759a5be48b3SPavel Labath   return static_cast<NativeThreadLinux *>(
1760b9c1b51eSKate Stone       NativeProcessProtocol::GetThreadByID(tid));
1761f9077782SPavel Labath }
1762f9077782SPavel Labath 
176397206d57SZachary Turner Status NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,
1764b9c1b51eSKate Stone                                         lldb::StateType state, int signo) {
1765a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1766a6321a8eSPavel Labath   LLDB_LOG(log, "tid: {0}", thread.GetID());
1767c076559aSPavel Labath 
176805097246SAdrian Prantl   // Before we do the resume below, first check if we have a pending stop
176905097246SAdrian Prantl   // notification that is currently waiting for all threads to stop.  This is
177005097246SAdrian Prantl   // potentially a buggy situation since we're ostensibly waiting for threads
177105097246SAdrian Prantl   // to stop before we send out the pending notification, and here we are
177205097246SAdrian Prantl   // resuming one before we send out the pending stop notification.
1773a6321a8eSPavel Labath   if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
1774a6321a8eSPavel Labath     LLDB_LOG(log,
1775a6321a8eSPavel Labath              "about to resume tid {0} per explicit request but we have a "
1776a6321a8eSPavel Labath              "pending stop notification (tid {1}) that is actively "
1777a6321a8eSPavel Labath              "waiting for this thread to stop. Valid sequence of events?",
1778a6321a8eSPavel Labath              thread.GetID(), m_pending_notification_tid);
1779c076559aSPavel Labath   }
1780c076559aSPavel Labath 
178105097246SAdrian Prantl   // Request a resume.  We expect this to be synchronous and the system to
178205097246SAdrian Prantl   // reflect it is running after this completes.
1783b9c1b51eSKate Stone   switch (state) {
1784b9c1b51eSKate Stone   case eStateRunning: {
1785605b51b8SPavel Labath     const auto resume_result = thread.Resume(signo);
17860e1d729bSPavel Labath     if (resume_result.Success())
17870e1d729bSPavel Labath       SetState(eStateRunning, true);
17880e1d729bSPavel Labath     return resume_result;
1789c076559aSPavel Labath   }
1790b9c1b51eSKate Stone   case eStateStepping: {
1791605b51b8SPavel Labath     const auto step_result = thread.SingleStep(signo);
17920e1d729bSPavel Labath     if (step_result.Success())
17930e1d729bSPavel Labath       SetState(eStateRunning, true);
17940e1d729bSPavel Labath     return step_result;
17950e1d729bSPavel Labath   }
17960e1d729bSPavel Labath   default:
17978198db30SPavel Labath     LLDB_LOG(log, "Unhandled state {0}.", state);
17980e1d729bSPavel Labath     llvm_unreachable("Unhandled state for resume");
17990e1d729bSPavel Labath   }
1800c076559aSPavel Labath }
1801c076559aSPavel Labath 
1802c076559aSPavel Labath //===----------------------------------------------------------------------===//
1803c076559aSPavel Labath 
1804b9c1b51eSKate Stone void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {
1805a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1806a6321a8eSPavel Labath   LLDB_LOG(log, "about to process event: (triggering_tid: {0})",
1807a6321a8eSPavel Labath            triggering_tid);
1808c076559aSPavel Labath 
18090e1d729bSPavel Labath   m_pending_notification_tid = triggering_tid;
18100e1d729bSPavel Labath 
181105097246SAdrian Prantl   // Request a stop for all the thread stops that need to be stopped and are
181205097246SAdrian Prantl   // not already known to be stopped.
1813a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
1814a5be48b3SPavel Labath     if (StateIsRunningState(thread->GetState()))
1815a5be48b3SPavel Labath       static_cast<NativeThreadLinux *>(thread.get())->RequestStop();
18160e1d729bSPavel Labath   }
18170e1d729bSPavel Labath 
18180e1d729bSPavel Labath   SignalIfAllThreadsStopped();
1819a6321a8eSPavel Labath   LLDB_LOG(log, "event processing done");
1820c076559aSPavel Labath }
1821c076559aSPavel Labath 
1822b9c1b51eSKate Stone void NativeProcessLinux::SignalIfAllThreadsStopped() {
18230e1d729bSPavel Labath   if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
18240e1d729bSPavel Labath     return; // No pending notification. Nothing to do.
18250e1d729bSPavel Labath 
1826b9c1b51eSKate Stone   for (const auto &thread_sp : m_threads) {
18270e1d729bSPavel Labath     if (StateIsRunningState(thread_sp->GetState()))
18280e1d729bSPavel Labath       return; // Some threads are still running. Don't signal yet.
18290e1d729bSPavel Labath   }
18300e1d729bSPavel Labath 
18310e1d729bSPavel Labath   // We have a pending notification and all threads have stopped.
1832b9c1b51eSKate Stone   Log *log(
1833b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
18349eb1ecb9SPavel Labath 
1835b9c1b51eSKate Stone   // Clear any temporary breakpoints we used to implement software single
1836b9c1b51eSKate Stone   // stepping.
1837b9c1b51eSKate Stone   for (const auto &thread_info : m_threads_stepping_with_breakpoint) {
183897206d57SZachary Turner     Status error = RemoveBreakpoint(thread_info.second);
18399eb1ecb9SPavel Labath     if (error.Fail())
1840a6321a8eSPavel Labath       LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}",
1841a6321a8eSPavel Labath                thread_info.first, error);
18429eb1ecb9SPavel Labath   }
18439eb1ecb9SPavel Labath   m_threads_stepping_with_breakpoint.clear();
18449eb1ecb9SPavel Labath 
18459eb1ecb9SPavel Labath   // Notify the delegate about the stop
18460e1d729bSPavel Labath   SetCurrentThreadID(m_pending_notification_tid);
1847ed89c7feSPavel Labath   SetState(StateType::eStateStopped, true);
18480e1d729bSPavel Labath   m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
1849c076559aSPavel Labath }
1850c076559aSPavel Labath 
1851b9c1b51eSKate Stone void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {
1852a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1853a6321a8eSPavel Labath   LLDB_LOG(log, "tid: {0}", thread.GetID());
18541dbc6c9cSPavel Labath 
1855b9c1b51eSKate Stone   if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID &&
1856b9c1b51eSKate Stone       StateIsRunningState(thread.GetState())) {
1857b9c1b51eSKate Stone     // We will need to wait for this new thread to stop as well before firing
185805097246SAdrian Prantl     // the notification.
1859f9077782SPavel Labath     thread.RequestStop();
1860c076559aSPavel Labath   }
1861c076559aSPavel Labath }
1862068f8a7eSTamas Berghammer 
1863b9c1b51eSKate Stone void NativeProcessLinux::SigchldHandler() {
1864a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
186519cbe96aSPavel Labath   // Process all pending waitpid notifications.
1866b9c1b51eSKate Stone   while (true) {
186719cbe96aSPavel Labath     int status = -1;
1868c1a6b128SPavel Labath     ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, -1, &status,
1869c1a6b128SPavel Labath                                           __WALL | __WNOTHREAD | WNOHANG);
187019cbe96aSPavel Labath 
187119cbe96aSPavel Labath     if (wait_pid == 0)
187219cbe96aSPavel Labath       break; // We are done.
187319cbe96aSPavel Labath 
1874b9c1b51eSKate Stone     if (wait_pid == -1) {
187597206d57SZachary Turner       Status error(errno, eErrorTypePOSIX);
1876a6321a8eSPavel Labath       LLDB_LOG(log, "waitpid (-1, &status, _) failed: {0}", error);
187719cbe96aSPavel Labath       break;
187819cbe96aSPavel Labath     }
187919cbe96aSPavel Labath 
18803508fc8cSPavel Labath     WaitStatus wait_status = WaitStatus::Decode(status);
18813508fc8cSPavel Labath     bool exited = wait_status.type == WaitStatus::Exit ||
18823508fc8cSPavel Labath                   (wait_status.type == WaitStatus::Signal &&
18833508fc8cSPavel Labath                    wait_pid == static_cast<::pid_t>(GetID()));
188419cbe96aSPavel Labath 
18853508fc8cSPavel Labath     LLDB_LOG(
18863508fc8cSPavel Labath         log,
18873508fc8cSPavel Labath         "waitpid (-1, &status, _) => pid = {0}, status = {1}, exited = {2}",
18883508fc8cSPavel Labath         wait_pid, wait_status, exited);
188919cbe96aSPavel Labath 
18903508fc8cSPavel Labath     MonitorCallback(wait_pid, exited, wait_status);
189119cbe96aSPavel Labath   }
1892068f8a7eSTamas Berghammer }
1893068f8a7eSTamas Berghammer 
189405097246SAdrian Prantl // Wrapper for ptrace to catch errors and log calls. Note that ptrace sets
189505097246SAdrian Prantl // errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
189697206d57SZachary Turner Status NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
1897b9c1b51eSKate Stone                                          void *data, size_t data_size,
1898b9c1b51eSKate Stone                                          long *result) {
189997206d57SZachary Turner   Status error;
19004a9babb2SPavel Labath   long int ret;
1901068f8a7eSTamas Berghammer 
1902068f8a7eSTamas Berghammer   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
1903068f8a7eSTamas Berghammer 
1904068f8a7eSTamas Berghammer   PtraceDisplayBytes(req, data, data_size);
1905068f8a7eSTamas Berghammer 
1906068f8a7eSTamas Berghammer   errno = 0;
1907068f8a7eSTamas Berghammer   if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
1908b9c1b51eSKate Stone     ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
1909b9c1b51eSKate Stone                  *(unsigned int *)addr, data);
1910068f8a7eSTamas Berghammer   else
1911b9c1b51eSKate Stone     ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
1912b9c1b51eSKate Stone                  addr, data);
1913068f8a7eSTamas Berghammer 
19144a9babb2SPavel Labath   if (ret == -1)
1915068f8a7eSTamas Berghammer     error.SetErrorToErrno();
1916068f8a7eSTamas Berghammer 
19174a9babb2SPavel Labath   if (result)
19184a9babb2SPavel Labath     *result = ret;
19194a9babb2SPavel Labath 
192028096200SPavel Labath   LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data,
192128096200SPavel Labath            data_size, ret);
1922068f8a7eSTamas Berghammer 
1923068f8a7eSTamas Berghammer   PtraceDisplayBytes(req, data, data_size);
1924068f8a7eSTamas Berghammer 
1925a6321a8eSPavel Labath   if (error.Fail())
1926a6321a8eSPavel Labath     LLDB_LOG(log, "ptrace() failed: {0}", error);
1927068f8a7eSTamas Berghammer 
19284a9babb2SPavel Labath   return error;
1929068f8a7eSTamas Berghammer }
193099e37695SRavitheja Addepally 
193199e37695SRavitheja Addepally llvm::Expected<ProcessorTraceMonitor &>
193299e37695SRavitheja Addepally NativeProcessLinux::LookupProcessorTraceInstance(lldb::user_id_t traceid,
193399e37695SRavitheja Addepally                                                  lldb::tid_t thread) {
193499e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
193599e37695SRavitheja Addepally   if (thread == LLDB_INVALID_THREAD_ID && traceid == m_pt_proces_trace_id) {
193699e37695SRavitheja Addepally     LLDB_LOG(log, "thread not specified: {0}", traceid);
193799e37695SRavitheja Addepally     return Status("tracing not active thread not specified").ToError();
193899e37695SRavitheja Addepally   }
193999e37695SRavitheja Addepally 
194099e37695SRavitheja Addepally   for (auto& iter : m_processor_trace_monitor) {
194199e37695SRavitheja Addepally     if (traceid == iter.second->GetTraceID() &&
194299e37695SRavitheja Addepally         (thread == iter.first || thread == LLDB_INVALID_THREAD_ID))
194399e37695SRavitheja Addepally       return *(iter.second);
194499e37695SRavitheja Addepally   }
194599e37695SRavitheja Addepally 
194699e37695SRavitheja Addepally   LLDB_LOG(log, "traceid not being traced: {0}", traceid);
194799e37695SRavitheja Addepally   return Status("tracing not active for this thread").ToError();
194899e37695SRavitheja Addepally }
194999e37695SRavitheja Addepally 
195099e37695SRavitheja Addepally Status NativeProcessLinux::GetMetaData(lldb::user_id_t traceid,
195199e37695SRavitheja Addepally                                        lldb::tid_t thread,
195299e37695SRavitheja Addepally                                        llvm::MutableArrayRef<uint8_t> &buffer,
195399e37695SRavitheja Addepally                                        size_t offset) {
195499e37695SRavitheja Addepally   TraceOptions trace_options;
195599e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
195699e37695SRavitheja Addepally   Status error;
195799e37695SRavitheja Addepally 
195899e37695SRavitheja Addepally   LLDB_LOG(log, "traceid {0}", traceid);
195999e37695SRavitheja Addepally 
196099e37695SRavitheja Addepally   auto perf_monitor = LookupProcessorTraceInstance(traceid, thread);
196199e37695SRavitheja Addepally   if (!perf_monitor) {
196299e37695SRavitheja Addepally     LLDB_LOG(log, "traceid not being traced: {0}", traceid);
196399e37695SRavitheja Addepally     buffer = buffer.slice(buffer.size());
196499e37695SRavitheja Addepally     error = perf_monitor.takeError();
196599e37695SRavitheja Addepally     return error;
196699e37695SRavitheja Addepally   }
196799e37695SRavitheja Addepally   return (*perf_monitor).ReadPerfTraceData(buffer, offset);
196899e37695SRavitheja Addepally }
196999e37695SRavitheja Addepally 
197099e37695SRavitheja Addepally Status NativeProcessLinux::GetData(lldb::user_id_t traceid, lldb::tid_t thread,
197199e37695SRavitheja Addepally                                    llvm::MutableArrayRef<uint8_t> &buffer,
197299e37695SRavitheja Addepally                                    size_t offset) {
197399e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
197499e37695SRavitheja Addepally   Status error;
197599e37695SRavitheja Addepally 
197699e37695SRavitheja Addepally   LLDB_LOG(log, "traceid {0}", traceid);
197799e37695SRavitheja Addepally 
197899e37695SRavitheja Addepally   auto perf_monitor = LookupProcessorTraceInstance(traceid, thread);
197999e37695SRavitheja Addepally   if (!perf_monitor) {
198099e37695SRavitheja Addepally     LLDB_LOG(log, "traceid not being traced: {0}", traceid);
198199e37695SRavitheja Addepally     buffer = buffer.slice(buffer.size());
198299e37695SRavitheja Addepally     error = perf_monitor.takeError();
198399e37695SRavitheja Addepally     return error;
198499e37695SRavitheja Addepally   }
198599e37695SRavitheja Addepally   return (*perf_monitor).ReadPerfTraceAux(buffer, offset);
198699e37695SRavitheja Addepally }
198799e37695SRavitheja Addepally 
198899e37695SRavitheja Addepally Status NativeProcessLinux::GetTraceConfig(lldb::user_id_t traceid,
198999e37695SRavitheja Addepally                                           TraceOptions &config) {
199099e37695SRavitheja Addepally   Status error;
199199e37695SRavitheja Addepally   if (config.getThreadID() == LLDB_INVALID_THREAD_ID &&
199299e37695SRavitheja Addepally       m_pt_proces_trace_id == traceid) {
199399e37695SRavitheja Addepally     if (m_pt_proces_trace_id == LLDB_INVALID_UID) {
199499e37695SRavitheja Addepally       error.SetErrorString("tracing not active for this process");
199599e37695SRavitheja Addepally       return error;
199699e37695SRavitheja Addepally     }
199799e37695SRavitheja Addepally     config = m_pt_process_trace_config;
199899e37695SRavitheja Addepally   } else {
199999e37695SRavitheja Addepally     auto perf_monitor =
200099e37695SRavitheja Addepally         LookupProcessorTraceInstance(traceid, config.getThreadID());
200199e37695SRavitheja Addepally     if (!perf_monitor) {
200299e37695SRavitheja Addepally       error = perf_monitor.takeError();
200399e37695SRavitheja Addepally       return error;
200499e37695SRavitheja Addepally     }
200599e37695SRavitheja Addepally     error = (*perf_monitor).GetTraceConfig(config);
200699e37695SRavitheja Addepally   }
200799e37695SRavitheja Addepally   return error;
200899e37695SRavitheja Addepally }
200999e37695SRavitheja Addepally 
201099e37695SRavitheja Addepally lldb::user_id_t
201199e37695SRavitheja Addepally NativeProcessLinux::StartTraceGroup(const TraceOptions &config,
201299e37695SRavitheja Addepally                                            Status &error) {
201399e37695SRavitheja Addepally 
201499e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
201599e37695SRavitheja Addepally   if (config.getType() != TraceType::eTraceTypeProcessorTrace)
201699e37695SRavitheja Addepally     return LLDB_INVALID_UID;
201799e37695SRavitheja Addepally 
201899e37695SRavitheja Addepally   if (m_pt_proces_trace_id != LLDB_INVALID_UID) {
201999e37695SRavitheja Addepally     error.SetErrorString("tracing already active on this process");
202099e37695SRavitheja Addepally     return m_pt_proces_trace_id;
202199e37695SRavitheja Addepally   }
202299e37695SRavitheja Addepally 
202399e37695SRavitheja Addepally   for (const auto &thread_sp : m_threads) {
202499e37695SRavitheja Addepally     if (auto traceInstance = ProcessorTraceMonitor::Create(
202599e37695SRavitheja Addepally             GetID(), thread_sp->GetID(), config, true)) {
202699e37695SRavitheja Addepally       m_pt_traced_thread_group.insert(thread_sp->GetID());
202799e37695SRavitheja Addepally       m_processor_trace_monitor.insert(
202899e37695SRavitheja Addepally           std::make_pair(thread_sp->GetID(), std::move(*traceInstance)));
202999e37695SRavitheja Addepally     }
203099e37695SRavitheja Addepally   }
203199e37695SRavitheja Addepally 
203299e37695SRavitheja Addepally   m_pt_process_trace_config = config;
203399e37695SRavitheja Addepally   error = ProcessorTraceMonitor::GetCPUType(m_pt_process_trace_config);
203499e37695SRavitheja Addepally 
203599e37695SRavitheja Addepally   // Trace on Complete process will have traceid of 0
203699e37695SRavitheja Addepally   m_pt_proces_trace_id = 0;
203799e37695SRavitheja Addepally 
203899e37695SRavitheja Addepally   LLDB_LOG(log, "Process Trace ID {0}", m_pt_proces_trace_id);
203999e37695SRavitheja Addepally   return m_pt_proces_trace_id;
204099e37695SRavitheja Addepally }
204199e37695SRavitheja Addepally 
204299e37695SRavitheja Addepally lldb::user_id_t NativeProcessLinux::StartTrace(const TraceOptions &config,
204399e37695SRavitheja Addepally                                                Status &error) {
204499e37695SRavitheja Addepally   if (config.getType() != TraceType::eTraceTypeProcessorTrace)
204599e37695SRavitheja Addepally     return NativeProcessProtocol::StartTrace(config, error);
204699e37695SRavitheja Addepally 
204799e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
204899e37695SRavitheja Addepally 
204999e37695SRavitheja Addepally   lldb::tid_t threadid = config.getThreadID();
205099e37695SRavitheja Addepally 
205199e37695SRavitheja Addepally   if (threadid == LLDB_INVALID_THREAD_ID)
205299e37695SRavitheja Addepally     return StartTraceGroup(config, error);
205399e37695SRavitheja Addepally 
205499e37695SRavitheja Addepally   auto thread_sp = GetThreadByID(threadid);
205599e37695SRavitheja Addepally   if (!thread_sp) {
205699e37695SRavitheja Addepally     // Thread not tracked by lldb so don't trace.
205799e37695SRavitheja Addepally     error.SetErrorString("invalid thread id");
205899e37695SRavitheja Addepally     return LLDB_INVALID_UID;
205999e37695SRavitheja Addepally   }
206099e37695SRavitheja Addepally 
206199e37695SRavitheja Addepally   const auto &iter = m_processor_trace_monitor.find(threadid);
206299e37695SRavitheja Addepally   if (iter != m_processor_trace_monitor.end()) {
206399e37695SRavitheja Addepally     LLDB_LOG(log, "Thread already being traced");
206499e37695SRavitheja Addepally     error.SetErrorString("tracing already active on this thread");
206599e37695SRavitheja Addepally     return LLDB_INVALID_UID;
206699e37695SRavitheja Addepally   }
206799e37695SRavitheja Addepally 
206899e37695SRavitheja Addepally   auto traceMonitor =
206999e37695SRavitheja Addepally       ProcessorTraceMonitor::Create(GetID(), threadid, config, false);
207099e37695SRavitheja Addepally   if (!traceMonitor) {
207199e37695SRavitheja Addepally     error = traceMonitor.takeError();
207299e37695SRavitheja Addepally     LLDB_LOG(log, "error {0}", error);
207399e37695SRavitheja Addepally     return LLDB_INVALID_UID;
207499e37695SRavitheja Addepally   }
207599e37695SRavitheja Addepally   lldb::user_id_t ret_trace_id = (*traceMonitor)->GetTraceID();
207699e37695SRavitheja Addepally   m_processor_trace_monitor.insert(
207799e37695SRavitheja Addepally       std::make_pair(threadid, std::move(*traceMonitor)));
207899e37695SRavitheja Addepally   return ret_trace_id;
207999e37695SRavitheja Addepally }
208099e37695SRavitheja Addepally 
208199e37695SRavitheja Addepally Status NativeProcessLinux::StopTracingForThread(lldb::tid_t thread) {
208299e37695SRavitheja Addepally   Status error;
208399e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
208499e37695SRavitheja Addepally   LLDB_LOG(log, "Thread {0}", thread);
208599e37695SRavitheja Addepally 
208699e37695SRavitheja Addepally   const auto& iter = m_processor_trace_monitor.find(thread);
208799e37695SRavitheja Addepally   if (iter == m_processor_trace_monitor.end()) {
208899e37695SRavitheja Addepally     error.SetErrorString("tracing not active for this thread");
208999e37695SRavitheja Addepally     return error;
209099e37695SRavitheja Addepally   }
209199e37695SRavitheja Addepally 
209299e37695SRavitheja Addepally   if (iter->second->GetTraceID() == m_pt_proces_trace_id) {
209305097246SAdrian Prantl     // traceid maps to the whole process so we have to erase it from the thread
209405097246SAdrian Prantl     // group.
209599e37695SRavitheja Addepally     LLDB_LOG(log, "traceid maps to process");
209699e37695SRavitheja Addepally     m_pt_traced_thread_group.erase(thread);
209799e37695SRavitheja Addepally   }
209899e37695SRavitheja Addepally   m_processor_trace_monitor.erase(iter);
209999e37695SRavitheja Addepally 
210099e37695SRavitheja Addepally   return error;
210199e37695SRavitheja Addepally }
210299e37695SRavitheja Addepally 
210399e37695SRavitheja Addepally Status NativeProcessLinux::StopTrace(lldb::user_id_t traceid,
210499e37695SRavitheja Addepally                                      lldb::tid_t thread) {
210599e37695SRavitheja Addepally   Status error;
210699e37695SRavitheja Addepally 
210799e37695SRavitheja Addepally   TraceOptions trace_options;
210899e37695SRavitheja Addepally   trace_options.setThreadID(thread);
210999e37695SRavitheja Addepally   error = NativeProcessLinux::GetTraceConfig(traceid, trace_options);
211099e37695SRavitheja Addepally 
211199e37695SRavitheja Addepally   if (error.Fail())
211299e37695SRavitheja Addepally     return error;
211399e37695SRavitheja Addepally 
211499e37695SRavitheja Addepally   switch (trace_options.getType()) {
211599e37695SRavitheja Addepally   case lldb::TraceType::eTraceTypeProcessorTrace:
211699e37695SRavitheja Addepally     if (traceid == m_pt_proces_trace_id &&
211799e37695SRavitheja Addepally         thread == LLDB_INVALID_THREAD_ID)
211899e37695SRavitheja Addepally       StopProcessorTracingOnProcess();
211999e37695SRavitheja Addepally     else
212099e37695SRavitheja Addepally       error = StopProcessorTracingOnThread(traceid, thread);
212199e37695SRavitheja Addepally     break;
212299e37695SRavitheja Addepally   default:
212399e37695SRavitheja Addepally     error.SetErrorString("trace not supported");
212499e37695SRavitheja Addepally     break;
212599e37695SRavitheja Addepally   }
212699e37695SRavitheja Addepally 
212799e37695SRavitheja Addepally   return error;
212899e37695SRavitheja Addepally }
212999e37695SRavitheja Addepally 
213099e37695SRavitheja Addepally void NativeProcessLinux::StopProcessorTracingOnProcess() {
213199e37695SRavitheja Addepally   for (auto thread_id_iter : m_pt_traced_thread_group)
213299e37695SRavitheja Addepally     m_processor_trace_monitor.erase(thread_id_iter);
213399e37695SRavitheja Addepally   m_pt_traced_thread_group.clear();
213499e37695SRavitheja Addepally   m_pt_proces_trace_id = LLDB_INVALID_UID;
213599e37695SRavitheja Addepally }
213699e37695SRavitheja Addepally 
213799e37695SRavitheja Addepally Status NativeProcessLinux::StopProcessorTracingOnThread(lldb::user_id_t traceid,
213899e37695SRavitheja Addepally                                                         lldb::tid_t thread) {
213999e37695SRavitheja Addepally   Status error;
214099e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
214199e37695SRavitheja Addepally 
214299e37695SRavitheja Addepally   if (thread == LLDB_INVALID_THREAD_ID) {
214399e37695SRavitheja Addepally     for (auto& iter : m_processor_trace_monitor) {
214499e37695SRavitheja Addepally       if (iter.second->GetTraceID() == traceid) {
214505097246SAdrian Prantl         // Stopping a trace instance for an individual thread hence there will
214605097246SAdrian Prantl         // only be one traceid that can match.
214799e37695SRavitheja Addepally         m_processor_trace_monitor.erase(iter.first);
214899e37695SRavitheja Addepally         return error;
214999e37695SRavitheja Addepally       }
215099e37695SRavitheja Addepally       LLDB_LOG(log, "Trace ID {0}", iter.second->GetTraceID());
215199e37695SRavitheja Addepally     }
215299e37695SRavitheja Addepally 
215399e37695SRavitheja Addepally     LLDB_LOG(log, "Invalid TraceID");
215499e37695SRavitheja Addepally     error.SetErrorString("invalid trace id");
215599e37695SRavitheja Addepally     return error;
215699e37695SRavitheja Addepally   }
215799e37695SRavitheja Addepally 
215899e37695SRavitheja Addepally   // thread is specified so we can use find function on the map.
215999e37695SRavitheja Addepally   const auto& iter = m_processor_trace_monitor.find(thread);
216099e37695SRavitheja Addepally   if (iter == m_processor_trace_monitor.end()) {
216199e37695SRavitheja Addepally     // thread not found in our map.
216299e37695SRavitheja Addepally     LLDB_LOG(log, "thread not being traced");
216399e37695SRavitheja Addepally     error.SetErrorString("tracing not active for this thread");
216499e37695SRavitheja Addepally     return error;
216599e37695SRavitheja Addepally   }
216699e37695SRavitheja Addepally   if (iter->second->GetTraceID() != traceid) {
216799e37695SRavitheja Addepally     // traceid did not match so it has to be invalid.
216899e37695SRavitheja Addepally     LLDB_LOG(log, "Invalid TraceID");
216999e37695SRavitheja Addepally     error.SetErrorString("invalid trace id");
217099e37695SRavitheja Addepally     return error;
217199e37695SRavitheja Addepally   }
217299e37695SRavitheja Addepally 
217399e37695SRavitheja Addepally   LLDB_LOG(log, "UID - {0} , Thread -{1}", traceid, thread);
217499e37695SRavitheja Addepally 
217599e37695SRavitheja Addepally   if (traceid == m_pt_proces_trace_id) {
217605097246SAdrian Prantl     // traceid maps to the whole process so we have to erase it from the thread
217705097246SAdrian Prantl     // group.
217899e37695SRavitheja Addepally     LLDB_LOG(log, "traceid maps to process");
217999e37695SRavitheja Addepally     m_pt_traced_thread_group.erase(thread);
218099e37695SRavitheja Addepally   }
218199e37695SRavitheja Addepally   m_processor_trace_monitor.erase(iter);
218299e37695SRavitheja Addepally 
218399e37695SRavitheja Addepally   return error;
218499e37695SRavitheja Addepally }
2185