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/Core/RegisterValue.h"
29af245d11STodd Fiala #include "lldb/Core/State.h"
30af245d11STodd Fiala #include "lldb/Host/Host.h"
315ad891f7SPavel Labath #include "lldb/Host/HostProcess.h"
3224ae6294SZachary Turner #include "lldb/Host/PseudoTerminal.h"
3339de3110SZachary Turner #include "lldb/Host/ThreadLauncher.h"
342a86b555SPavel Labath #include "lldb/Host/common/NativeBreakpoint.h"
352a86b555SPavel Labath #include "lldb/Host/common/NativeRegisterContext.h"
364ee1c952SPavel Labath #include "lldb/Host/linux/Ptrace.h"
374ee1c952SPavel Labath #include "lldb/Host/linux/Uio.h"
38816ae4b0SKamil Rytarowski #include "lldb/Host/posix/ProcessLauncherPosixFork.h"
392a86b555SPavel Labath #include "lldb/Symbol/ObjectFile.h"
4090aff47cSZachary Turner #include "lldb/Target/Process.h"
41af245d11STodd Fiala #include "lldb/Target/ProcessLaunchInfo.h"
425b981ab9SPavel Labath #include "lldb/Target/Target.h"
43c16f5dcaSChaoren Lin #include "lldb/Utility/LLDBAssert.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()) {
340*05097246SAdrian Prantl           // No such thread. The thread may have exited. More error handling
341*05097246SAdrian 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);
351*05097246SAdrian Prantl         // Need to use __WALL otherwise we receive an error with errno=ECHLD At
352*05097246SAdrian Prantl         // this point we should have a thread stopped if waitpid succeeds.
35396e600fcSPavel Labath         if (wpid < 0) {
354*05097246SAdrian Prantl           // No such thread. The thread may have exited. More error handling
355*05097246SAdrian 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 
400*05097246SAdrian Prantl   // Have the tracer notify us before execve returns (needed to disable legacy
401*05097246SAdrian 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) {
441*05097246SAdrian Prantl     // Normally, the only situation when we cannot find the thread is if we
442*05097246SAdrian 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) {
474*05097246SAdrian Prantl       // This is a group stop reception for this tid. We can reach here if we
475*05097246SAdrian Prantl       // reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the tracee,
476*05097246SAdrian Prantl       // triggering the group-stop mechanism. Normally receiving these would
477*05097246SAdrian Prantl       // stop the process, pending a SIGCONT. Simulating this state in a
478*05097246SAdrian Prantl       // debugger is hard and is generally not needed (one use case is
479*05097246SAdrian Prantl       // debugging background task being managed by a shell). For general use,
480*05097246SAdrian Prantl       // it is sufficient to stop the process in a signal-delivery stop which
481*05097246SAdrian Prantl       // happens before the group stop. This done by MonitorSignal and works
482*05097246SAdrian 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
508*05097246SAdrian Prantl         // have been killed outside our control.  Is eStateExited the right
509*05097246SAdrian 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
578*05097246SAdrian Prantl   // inferiors' children.  We'd need this to debug a monitor. case (SIGTRAP |
579*05097246SAdrian 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
583*05097246SAdrian Prantl     // thread creation. We don't want to do anything with the parent thread so
584*05097246SAdrian Prantl     // we just resume it. In case we want to implement "break on thread
585*05097246SAdrian 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)): {
635*05097246SAdrian Prantl     // The inferior process or one of its threads is about to exit. We don't
636*05097246SAdrian Prantl     // want to do anything with the thread so we just resume it. In case we
637*05097246SAdrian Prantl     // want to implement "break on thread exit" functionality, we would need to
638*05097246SAdrian 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
656*05097246SAdrian Prantl       // events while the inferior is stopped. This makes sure that the
657*05097246SAdrian 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__
703*05097246SAdrian Prantl     // For mips there is no special signal for watchpoint So we check for
704*05097246SAdrian 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();
76297206d57SZachary Turner   Status error = FixupBreakpointPCAsNeeded(thread);
763c16f5dcaSChaoren Lin   if (error.Fail())
764a6321a8eSPavel Labath     LLDB_LOG(log, "pid = {0} fixup: {1}", thread.GetID(), error);
765d8c338d4STamas Berghammer 
766b9c1b51eSKate Stone   if (m_threads_stepping_with_breakpoint.find(thread.GetID()) !=
767b9c1b51eSKate Stone       m_threads_stepping_with_breakpoint.end())
768b9cc0c75SPavel Labath     thread.SetStoppedByTrace();
769c16f5dcaSChaoren Lin 
770b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
771c16f5dcaSChaoren Lin }
772c16f5dcaSChaoren Lin 
773b9c1b51eSKate Stone void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread,
774b9c1b51eSKate Stone                                            uint32_t wp_index) {
775b9c1b51eSKate Stone   Log *log(
776b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
777a6321a8eSPavel Labath   LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}",
778a6321a8eSPavel Labath            thread.GetID(), wp_index);
779c16f5dcaSChaoren Lin 
780*05097246SAdrian Prantl   // Mark the thread as stopped at watchpoint. The address is at
781*05097246SAdrian Prantl   // (lldb::addr_t)info->si_addr if we need it.
782f9077782SPavel Labath   thread.SetStoppedByWatchpoint(wp_index);
783c16f5dcaSChaoren Lin 
784b9c1b51eSKate Stone   // We need to tell all other running threads before we notify the delegate
785b9c1b51eSKate Stone   // about this stop.
786f9077782SPavel Labath   StopRunningThreads(thread.GetID());
787c16f5dcaSChaoren Lin }
788c16f5dcaSChaoren Lin 
789b9c1b51eSKate Stone void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
790b9c1b51eSKate Stone                                        NativeThreadLinux &thread, bool exited) {
791b9cc0c75SPavel Labath   const int signo = info.si_signo;
792b9cc0c75SPavel Labath   const bool is_from_llgs = info.si_pid == getpid();
793af245d11STodd Fiala 
794a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
795af245d11STodd Fiala 
796af245d11STodd Fiala   // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
797*05097246SAdrian Prantl   // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a kill(2)
798*05097246SAdrian Prantl   // or raise(3).  Similarly for tgkill(2) on Linux.
799af245d11STodd Fiala   //
800af245d11STodd Fiala   // IOW, user generated signals never generate what we consider to be a
801af245d11STodd Fiala   // "crash".
802af245d11STodd Fiala   //
803af245d11STodd Fiala   // Similarly, ACK signals generated by this monitor.
804af245d11STodd Fiala 
805af245d11STodd Fiala   // Handle the signal.
806a6321a8eSPavel Labath   LLDB_LOG(log,
807a6321a8eSPavel Labath            "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
808a6321a8eSPavel Labath            "waitpid pid = {4})",
809a6321a8eSPavel Labath            Host::GetSignalAsCString(signo), signo, info.si_code,
810b9cc0c75SPavel Labath            thread.GetID());
81158a2f669STodd Fiala 
81258a2f669STodd Fiala   // Check for thread stop notification.
813b9c1b51eSKate Stone   if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) {
814af245d11STodd Fiala     // This is a tgkill()-based stop.
815a6321a8eSPavel Labath     LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID());
816fa03ad2eSChaoren Lin 
817*05097246SAdrian Prantl     // Check that we're not already marked with a stop reason. Note this thread
818*05097246SAdrian Prantl     // really shouldn't already be marked as stopped - if we were, that would
819*05097246SAdrian Prantl     // imply that the kernel signaled us with the thread stopping which we
820*05097246SAdrian Prantl     // handled and marked as stopped, and that, without an intervening resume,
821*05097246SAdrian Prantl     // we received another stop.  It is more likely that we are missing the
822*05097246SAdrian Prantl     // marking of a run state somewhere if we find that the thread was marked
823*05097246SAdrian Prantl     // as stopped.
824b9cc0c75SPavel Labath     const StateType thread_state = thread.GetState();
825b9c1b51eSKate Stone     if (!StateIsStoppedState(thread_state, false)) {
826ed89c7feSPavel Labath       // An inferior thread has stopped because of a SIGSTOP we have sent it.
827b9c1b51eSKate Stone       // Generally, these are not important stops and we don't want to report
828a6321a8eSPavel Labath       // them as they are just used to stop other threads when one thread (the
829a6321a8eSPavel Labath       // one with the *real* stop reason) hits a breakpoint (watchpoint,
830*05097246SAdrian Prantl       // etc...). However, in the case of an asynchronous Interrupt(), this
831*05097246SAdrian Prantl       // *is* the real stop reason, so we leave the signal intact if this is
832*05097246SAdrian Prantl       // the thread that was chosen as the triggering thread.
833b9c1b51eSKate Stone       if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
834b9cc0c75SPavel Labath         if (m_pending_notification_tid == thread.GetID())
835b9cc0c75SPavel Labath           thread.SetStoppedBySignal(SIGSTOP, &info);
836ed89c7feSPavel Labath         else
837b9cc0c75SPavel Labath           thread.SetStoppedWithNoReason();
838ed89c7feSPavel Labath 
839b9cc0c75SPavel Labath         SetCurrentThreadID(thread.GetID());
8400e1d729bSPavel Labath         SignalIfAllThreadsStopped();
841b9c1b51eSKate Stone       } else {
8420e1d729bSPavel Labath         // We can end up here if stop was initiated by LLGS but by this time a
8430e1d729bSPavel Labath         // thread stop has occurred - maybe initiated by another event.
84497206d57SZachary Turner         Status error = ResumeThread(thread, thread.GetState(), 0);
845a6321a8eSPavel Labath         if (error.Fail())
846a6321a8eSPavel Labath           LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(),
847a6321a8eSPavel Labath                    error);
8480e1d729bSPavel Labath       }
849b9c1b51eSKate Stone     } else {
850a6321a8eSPavel Labath       LLDB_LOG(log,
851a6321a8eSPavel Labath                "pid {0} tid {1}, thread was already marked as a stopped "
852a6321a8eSPavel Labath                "state (state={2}), leaving stop signal as is",
8538198db30SPavel Labath                GetID(), thread.GetID(), thread_state);
8540e1d729bSPavel Labath       SignalIfAllThreadsStopped();
855af245d11STodd Fiala     }
856af245d11STodd Fiala 
85758a2f669STodd Fiala     // Done handling.
858af245d11STodd Fiala     return;
859af245d11STodd Fiala   }
860af245d11STodd Fiala 
861*05097246SAdrian Prantl   // Check if debugger should stop at this signal or just ignore it and resume
862*05097246SAdrian Prantl   // the inferior.
8634a705e7eSPavel Labath   if (m_signals_to_ignore.find(signo) != m_signals_to_ignore.end()) {
8644a705e7eSPavel Labath      ResumeThread(thread, thread.GetState(), signo);
8654a705e7eSPavel Labath      return;
8664a705e7eSPavel Labath   }
8674a705e7eSPavel Labath 
86886fd8e45SChaoren Lin   // This thread is stopped.
869a6321a8eSPavel Labath   LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo));
870b9cc0c75SPavel Labath   thread.SetStoppedBySignal(signo, &info);
87186fd8e45SChaoren Lin 
87286fd8e45SChaoren Lin   // Send a stop to the debugger after we get all other threads to stop.
873b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
874511e5cdcSTodd Fiala }
875af245d11STodd Fiala 
876e7708688STamas Berghammer namespace {
877e7708688STamas Berghammer 
878b9c1b51eSKate Stone struct EmulatorBaton {
879d37349f3SPavel Labath   NativeProcessLinux &m_process;
880d37349f3SPavel Labath   NativeRegisterContext &m_reg_context;
8816648fcc3SPavel Labath 
8826648fcc3SPavel Labath   // eRegisterKindDWARF -> RegsiterValue
8836648fcc3SPavel Labath   std::unordered_map<uint32_t, RegisterValue> m_register_values;
884e7708688STamas Berghammer 
885d37349f3SPavel Labath   EmulatorBaton(NativeProcessLinux &process, NativeRegisterContext &reg_context)
886b9c1b51eSKate Stone       : m_process(process), m_reg_context(reg_context) {}
887e7708688STamas Berghammer };
888e7708688STamas Berghammer 
889e7708688STamas Berghammer } // anonymous namespace
890e7708688STamas Berghammer 
891b9c1b51eSKate Stone static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
892e7708688STamas Berghammer                                  const EmulateInstruction::Context &context,
893b9c1b51eSKate Stone                                  lldb::addr_t addr, void *dst, size_t length) {
894e7708688STamas Berghammer   EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
895e7708688STamas Berghammer 
8963eb4b458SChaoren Lin   size_t bytes_read;
897d37349f3SPavel Labath   emulator_baton->m_process.ReadMemory(addr, dst, length, bytes_read);
898e7708688STamas Berghammer   return bytes_read;
899e7708688STamas Berghammer }
900e7708688STamas Berghammer 
901b9c1b51eSKate Stone static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
902e7708688STamas Berghammer                                  const RegisterInfo *reg_info,
903b9c1b51eSKate Stone                                  RegisterValue &reg_value) {
904e7708688STamas Berghammer   EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
905e7708688STamas Berghammer 
906b9c1b51eSKate Stone   auto it = emulator_baton->m_register_values.find(
907b9c1b51eSKate Stone       reg_info->kinds[eRegisterKindDWARF]);
908b9c1b51eSKate Stone   if (it != emulator_baton->m_register_values.end()) {
9096648fcc3SPavel Labath     reg_value = it->second;
9106648fcc3SPavel Labath     return true;
9116648fcc3SPavel Labath   }
9126648fcc3SPavel Labath 
913*05097246SAdrian Prantl   // The emulator only fill in the dwarf regsiter numbers (and in some case the
914*05097246SAdrian Prantl   // generic register numbers). Get the full register info from the register
915*05097246SAdrian Prantl   // context based on the dwarf register numbers.
916b9c1b51eSKate Stone   const RegisterInfo *full_reg_info =
917d37349f3SPavel Labath       emulator_baton->m_reg_context.GetRegisterInfo(
918e7708688STamas Berghammer           eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
919e7708688STamas Berghammer 
92097206d57SZachary Turner   Status error =
921d37349f3SPavel Labath       emulator_baton->m_reg_context.ReadRegister(full_reg_info, reg_value);
9226648fcc3SPavel Labath   if (error.Success())
9236648fcc3SPavel Labath     return true;
924cdc22a88SMohit K. Bhakkad 
9256648fcc3SPavel Labath   return false;
926e7708688STamas Berghammer }
927e7708688STamas Berghammer 
928b9c1b51eSKate Stone static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
929e7708688STamas Berghammer                                   const EmulateInstruction::Context &context,
930e7708688STamas Berghammer                                   const RegisterInfo *reg_info,
931b9c1b51eSKate Stone                                   const RegisterValue &reg_value) {
932e7708688STamas Berghammer   EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
933b9c1b51eSKate Stone   emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
934b9c1b51eSKate Stone       reg_value;
935e7708688STamas Berghammer   return true;
936e7708688STamas Berghammer }
937e7708688STamas Berghammer 
938b9c1b51eSKate Stone static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
939e7708688STamas Berghammer                                   const EmulateInstruction::Context &context,
940b9c1b51eSKate Stone                                   lldb::addr_t addr, const void *dst,
941b9c1b51eSKate Stone                                   size_t length) {
942e7708688STamas Berghammer   return length;
943e7708688STamas Berghammer }
944e7708688STamas Berghammer 
945d37349f3SPavel Labath static lldb::addr_t ReadFlags(NativeRegisterContext &regsiter_context) {
946d37349f3SPavel Labath   const RegisterInfo *flags_info = regsiter_context.GetRegisterInfo(
947e7708688STamas Berghammer       eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
948d37349f3SPavel Labath   return regsiter_context.ReadRegisterAsUnsigned(flags_info,
949b9c1b51eSKate Stone                                                  LLDB_INVALID_ADDRESS);
950e7708688STamas Berghammer }
951e7708688STamas Berghammer 
95297206d57SZachary Turner Status
95397206d57SZachary Turner NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadLinux &thread) {
95497206d57SZachary Turner   Status error;
955d37349f3SPavel Labath   NativeRegisterContext& register_context = thread.GetRegisterContext();
956e7708688STamas Berghammer 
957e7708688STamas Berghammer   std::unique_ptr<EmulateInstruction> emulator_ap(
958b9c1b51eSKate Stone       EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying,
959b9c1b51eSKate Stone                                      nullptr));
960e7708688STamas Berghammer 
961e7708688STamas Berghammer   if (emulator_ap == nullptr)
96297206d57SZachary Turner     return Status("Instruction emulator not found!");
963e7708688STamas Berghammer 
964d37349f3SPavel Labath   EmulatorBaton baton(*this, register_context);
965e7708688STamas Berghammer   emulator_ap->SetBaton(&baton);
966e7708688STamas Berghammer   emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
967e7708688STamas Berghammer   emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
968e7708688STamas Berghammer   emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
969e7708688STamas Berghammer   emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
970e7708688STamas Berghammer 
971e7708688STamas Berghammer   if (!emulator_ap->ReadInstruction())
97297206d57SZachary Turner     return Status("Read instruction failed!");
973e7708688STamas Berghammer 
974b9c1b51eSKate Stone   bool emulation_result =
975b9c1b51eSKate Stone       emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
9766648fcc3SPavel Labath 
977d37349f3SPavel Labath   const RegisterInfo *reg_info_pc = register_context.GetRegisterInfo(
978b9c1b51eSKate Stone       eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
979d37349f3SPavel Labath   const RegisterInfo *reg_info_flags = register_context.GetRegisterInfo(
980b9c1b51eSKate Stone       eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
9816648fcc3SPavel Labath 
982b9c1b51eSKate Stone   auto pc_it =
983b9c1b51eSKate Stone       baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
984b9c1b51eSKate Stone   auto flags_it =
985b9c1b51eSKate Stone       baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
9866648fcc3SPavel Labath 
987e7708688STamas Berghammer   lldb::addr_t next_pc;
988e7708688STamas Berghammer   lldb::addr_t next_flags;
989b9c1b51eSKate Stone   if (emulation_result) {
990b9c1b51eSKate Stone     assert(pc_it != baton.m_register_values.end() &&
991b9c1b51eSKate Stone            "Emulation was successfull but PC wasn't updated");
9926648fcc3SPavel Labath     next_pc = pc_it->second.GetAsUInt64();
9936648fcc3SPavel Labath 
9946648fcc3SPavel Labath     if (flags_it != baton.m_register_values.end())
9956648fcc3SPavel Labath       next_flags = flags_it->second.GetAsUInt64();
996e7708688STamas Berghammer     else
997d37349f3SPavel Labath       next_flags = ReadFlags(register_context);
998b9c1b51eSKate Stone   } else if (pc_it == baton.m_register_values.end()) {
999*05097246SAdrian Prantl     // Emulate instruction failed and it haven't changed PC. Advance PC with
1000*05097246SAdrian Prantl     // the size of the current opcode because the emulation of all
1001e7708688STamas Berghammer     // PC modifying instruction should be successful. The failure most
1002e7708688STamas Berghammer     // likely caused by a not supported instruction which don't modify PC.
1003d37349f3SPavel Labath     next_pc = register_context.GetPC() + emulator_ap->GetOpcode().GetByteSize();
1004d37349f3SPavel Labath     next_flags = ReadFlags(register_context);
1005b9c1b51eSKate Stone   } else {
1006e7708688STamas Berghammer     // The instruction emulation failed after it modified the PC. It is an
1007e7708688STamas Berghammer     // unknown error where we can't continue because the next instruction is
1008e7708688STamas Berghammer     // modifying the PC but we don't  know how.
100997206d57SZachary Turner     return Status("Instruction emulation failed unexpectedly.");
1010e7708688STamas Berghammer   }
1011e7708688STamas Berghammer 
1012b9c1b51eSKate Stone   if (m_arch.GetMachine() == llvm::Triple::arm) {
1013b9c1b51eSKate Stone     if (next_flags & 0x20) {
1014e7708688STamas Berghammer       // Thumb mode
1015e7708688STamas Berghammer       error = SetSoftwareBreakpoint(next_pc, 2);
1016b9c1b51eSKate Stone     } else {
1017e7708688STamas Berghammer       // Arm mode
1018e7708688STamas Berghammer       error = SetSoftwareBreakpoint(next_pc, 4);
1019e7708688STamas Berghammer     }
1020b9c1b51eSKate Stone   } else if (m_arch.GetMachine() == llvm::Triple::mips64 ||
1021b9c1b51eSKate Stone              m_arch.GetMachine() == llvm::Triple::mips64el ||
1022b9c1b51eSKate Stone              m_arch.GetMachine() == llvm::Triple::mips ||
1023aae0a752SEugene Zemtsov              m_arch.GetMachine() == llvm::Triple::mipsel ||
1024aae0a752SEugene Zemtsov              m_arch.GetMachine() == llvm::Triple::ppc64le)
1025cdc22a88SMohit K. Bhakkad     error = SetSoftwareBreakpoint(next_pc, 4);
1026b9c1b51eSKate Stone   else {
1027e7708688STamas Berghammer     // No size hint is given for the next breakpoint
1028e7708688STamas Berghammer     error = SetSoftwareBreakpoint(next_pc, 0);
1029e7708688STamas Berghammer   }
1030e7708688STamas Berghammer 
1031*05097246SAdrian Prantl   // If setting the breakpoint fails because next_pc is out of the address
1032*05097246SAdrian Prantl   // space, ignore it and let the debugee segfault.
103342eb6908SPavel Labath   if (error.GetError() == EIO || error.GetError() == EFAULT) {
103497206d57SZachary Turner     return Status();
103542eb6908SPavel Labath   } else if (error.Fail())
1036e7708688STamas Berghammer     return error;
1037e7708688STamas Berghammer 
1038b9cc0c75SPavel Labath   m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
1039e7708688STamas Berghammer 
104097206d57SZachary Turner   return Status();
1041e7708688STamas Berghammer }
1042e7708688STamas Berghammer 
1043b9c1b51eSKate Stone bool NativeProcessLinux::SupportHardwareSingleStepping() const {
1044b9c1b51eSKate Stone   if (m_arch.GetMachine() == llvm::Triple::arm ||
1045b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mips64 ||
1046b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mips64el ||
1047b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mips ||
1048b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mipsel)
1049cdc22a88SMohit K. Bhakkad     return false;
1050cdc22a88SMohit K. Bhakkad   return true;
1051e7708688STamas Berghammer }
1052e7708688STamas Berghammer 
105397206d57SZachary Turner Status NativeProcessLinux::Resume(const ResumeActionList &resume_actions) {
1054a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1055a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0}", GetID());
1056af245d11STodd Fiala 
1057e7708688STamas Berghammer   bool software_single_step = !SupportHardwareSingleStepping();
1058af245d11STodd Fiala 
1059b9c1b51eSKate Stone   if (software_single_step) {
1060a5be48b3SPavel Labath     for (const auto &thread : m_threads) {
1061a5be48b3SPavel Labath       assert(thread && "thread list should not contain NULL threads");
1062e7708688STamas Berghammer 
1063b9c1b51eSKate Stone       const ResumeAction *const action =
1064a5be48b3SPavel Labath           resume_actions.GetActionForThread(thread->GetID(), true);
1065e7708688STamas Berghammer       if (action == nullptr)
1066e7708688STamas Berghammer         continue;
1067e7708688STamas Berghammer 
1068b9c1b51eSKate Stone       if (action->state == eStateStepping) {
106997206d57SZachary Turner         Status error = SetupSoftwareSingleStepping(
1070a5be48b3SPavel Labath             static_cast<NativeThreadLinux &>(*thread));
1071e7708688STamas Berghammer         if (error.Fail())
1072e7708688STamas Berghammer           return error;
1073e7708688STamas Berghammer       }
1074e7708688STamas Berghammer     }
1075e7708688STamas Berghammer   }
1076e7708688STamas Berghammer 
1077a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
1078a5be48b3SPavel Labath     assert(thread && "thread list should not contain NULL threads");
1079af245d11STodd Fiala 
1080b9c1b51eSKate Stone     const ResumeAction *const action =
1081a5be48b3SPavel Labath         resume_actions.GetActionForThread(thread->GetID(), true);
10826a196ce6SChaoren Lin 
1083b9c1b51eSKate Stone     if (action == nullptr) {
1084a6321a8eSPavel Labath       LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
1085a5be48b3SPavel Labath                thread->GetID());
10866a196ce6SChaoren Lin       continue;
10876a196ce6SChaoren Lin     }
1088af245d11STodd Fiala 
1089a6321a8eSPavel Labath     LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}",
1090a5be48b3SPavel Labath              action->state, GetID(), thread->GetID());
1091af245d11STodd Fiala 
1092b9c1b51eSKate Stone     switch (action->state) {
1093af245d11STodd Fiala     case eStateRunning:
1094b9c1b51eSKate Stone     case eStateStepping: {
1095af245d11STodd Fiala       // Run the thread, possibly feeding it the signal.
1096fa03ad2eSChaoren Lin       const int signo = action->signal;
1097a5be48b3SPavel Labath       ResumeThread(static_cast<NativeThreadLinux &>(*thread), action->state,
1098b9c1b51eSKate Stone                    signo);
1099af245d11STodd Fiala       break;
1100ae29d395SChaoren Lin     }
1101af245d11STodd Fiala 
1102af245d11STodd Fiala     case eStateSuspended:
1103af245d11STodd Fiala     case eStateStopped:
1104a6321a8eSPavel Labath       llvm_unreachable("Unexpected state");
1105af245d11STodd Fiala 
1106af245d11STodd Fiala     default:
110797206d57SZachary Turner       return Status("NativeProcessLinux::%s (): unexpected state %s specified "
1108b9c1b51eSKate Stone                     "for pid %" PRIu64 ", tid %" PRIu64,
1109b9c1b51eSKate Stone                     __FUNCTION__, StateAsCString(action->state), GetID(),
1110a5be48b3SPavel Labath                     thread->GetID());
1111af245d11STodd Fiala     }
1112af245d11STodd Fiala   }
1113af245d11STodd Fiala 
111497206d57SZachary Turner   return Status();
1115af245d11STodd Fiala }
1116af245d11STodd Fiala 
111797206d57SZachary Turner Status NativeProcessLinux::Halt() {
111897206d57SZachary Turner   Status error;
1119af245d11STodd Fiala 
1120af245d11STodd Fiala   if (kill(GetID(), SIGSTOP) != 0)
1121af245d11STodd Fiala     error.SetErrorToErrno();
1122af245d11STodd Fiala 
1123af245d11STodd Fiala   return error;
1124af245d11STodd Fiala }
1125af245d11STodd Fiala 
112697206d57SZachary Turner Status NativeProcessLinux::Detach() {
112797206d57SZachary Turner   Status error;
1128af245d11STodd Fiala 
1129af245d11STodd Fiala   // Stop monitoring the inferior.
113019cbe96aSPavel Labath   m_sigchld_handle.reset();
1131af245d11STodd Fiala 
11327a9495bcSPavel Labath   // Tell ptrace to detach from the process.
11337a9495bcSPavel Labath   if (GetID() == LLDB_INVALID_PROCESS_ID)
11347a9495bcSPavel Labath     return error;
11357a9495bcSPavel Labath 
1136a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
1137a5be48b3SPavel Labath     Status e = Detach(thread->GetID());
11387a9495bcSPavel Labath     if (e.Fail())
1139b9c1b51eSKate Stone       error =
1140b9c1b51eSKate Stone           e; // Save the error, but still attempt to detach from other threads.
11417a9495bcSPavel Labath   }
11427a9495bcSPavel Labath 
114399e37695SRavitheja Addepally   m_processor_trace_monitor.clear();
114499e37695SRavitheja Addepally   m_pt_proces_trace_id = LLDB_INVALID_UID;
114599e37695SRavitheja Addepally 
1146af245d11STodd Fiala   return error;
1147af245d11STodd Fiala }
1148af245d11STodd Fiala 
114997206d57SZachary Turner Status NativeProcessLinux::Signal(int signo) {
115097206d57SZachary Turner   Status error;
1151af245d11STodd Fiala 
1152a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1153a6321a8eSPavel Labath   LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo,
1154a6321a8eSPavel Labath            Host::GetSignalAsCString(signo), GetID());
1155af245d11STodd Fiala 
1156af245d11STodd Fiala   if (kill(GetID(), signo))
1157af245d11STodd Fiala     error.SetErrorToErrno();
1158af245d11STodd Fiala 
1159af245d11STodd Fiala   return error;
1160af245d11STodd Fiala }
1161af245d11STodd Fiala 
116297206d57SZachary Turner Status NativeProcessLinux::Interrupt() {
1163*05097246SAdrian Prantl   // Pick a running thread (or if none, a not-dead stopped thread) as the
1164*05097246SAdrian Prantl   // chosen thread that will be the stop-reason thread.
1165a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1166e9547b80SChaoren Lin 
1167a5be48b3SPavel Labath   NativeThreadProtocol *running_thread = nullptr;
1168a5be48b3SPavel Labath   NativeThreadProtocol *stopped_thread = nullptr;
1169e9547b80SChaoren Lin 
1170a6321a8eSPavel Labath   LLDB_LOG(log, "selecting running thread for interrupt target");
1171a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
1172*05097246SAdrian Prantl     // If we have a running or stepping thread, we'll call that the target of
1173*05097246SAdrian Prantl     // the interrupt.
1174a5be48b3SPavel Labath     const auto thread_state = thread->GetState();
1175b9c1b51eSKate Stone     if (thread_state == eStateRunning || thread_state == eStateStepping) {
1176a5be48b3SPavel Labath       running_thread = thread.get();
1177e9547b80SChaoren Lin       break;
1178a5be48b3SPavel Labath     } else if (!stopped_thread && StateIsStoppedState(thread_state, true)) {
1179*05097246SAdrian Prantl       // Remember the first non-dead stopped thread.  We'll use that as a
1180*05097246SAdrian Prantl       // backup if there are no running threads.
1181a5be48b3SPavel Labath       stopped_thread = thread.get();
1182e9547b80SChaoren Lin     }
1183e9547b80SChaoren Lin   }
1184e9547b80SChaoren Lin 
1185a5be48b3SPavel Labath   if (!running_thread && !stopped_thread) {
118697206d57SZachary Turner     Status error("found no running/stepping or live stopped threads as target "
1187b9c1b51eSKate Stone                  "for interrupt");
1188a6321a8eSPavel Labath     LLDB_LOG(log, "skipping due to error: {0}", error);
11895830aa75STamas Berghammer 
1190e9547b80SChaoren Lin     return error;
1191e9547b80SChaoren Lin   }
1192e9547b80SChaoren Lin 
1193a5be48b3SPavel Labath   NativeThreadProtocol *deferred_signal_thread =
1194a5be48b3SPavel Labath       running_thread ? running_thread : stopped_thread;
1195e9547b80SChaoren Lin 
1196a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(),
1197a5be48b3SPavel Labath            running_thread ? "running" : "stopped",
1198a5be48b3SPavel Labath            deferred_signal_thread->GetID());
1199e9547b80SChaoren Lin 
1200a5be48b3SPavel Labath   StopRunningThreads(deferred_signal_thread->GetID());
120145f5cb31SPavel Labath 
120297206d57SZachary Turner   return Status();
1203e9547b80SChaoren Lin }
1204e9547b80SChaoren Lin 
120597206d57SZachary Turner Status NativeProcessLinux::Kill() {
1206a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1207a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0}", GetID());
1208af245d11STodd Fiala 
120997206d57SZachary Turner   Status error;
1210af245d11STodd Fiala 
1211b9c1b51eSKate Stone   switch (m_state) {
1212af245d11STodd Fiala   case StateType::eStateInvalid:
1213af245d11STodd Fiala   case StateType::eStateExited:
1214af245d11STodd Fiala   case StateType::eStateCrashed:
1215af245d11STodd Fiala   case StateType::eStateDetached:
1216af245d11STodd Fiala   case StateType::eStateUnloaded:
1217af245d11STodd Fiala     // Nothing to do - the process is already dead.
1218a6321a8eSPavel Labath     LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
12198198db30SPavel Labath              m_state);
1220af245d11STodd Fiala     return error;
1221af245d11STodd Fiala 
1222af245d11STodd Fiala   case StateType::eStateConnected:
1223af245d11STodd Fiala   case StateType::eStateAttaching:
1224af245d11STodd Fiala   case StateType::eStateLaunching:
1225af245d11STodd Fiala   case StateType::eStateStopped:
1226af245d11STodd Fiala   case StateType::eStateRunning:
1227af245d11STodd Fiala   case StateType::eStateStepping:
1228af245d11STodd Fiala   case StateType::eStateSuspended:
1229af245d11STodd Fiala     // We can try to kill a process in these states.
1230af245d11STodd Fiala     break;
1231af245d11STodd Fiala   }
1232af245d11STodd Fiala 
1233b9c1b51eSKate Stone   if (kill(GetID(), SIGKILL) != 0) {
1234af245d11STodd Fiala     error.SetErrorToErrno();
1235af245d11STodd Fiala     return error;
1236af245d11STodd Fiala   }
1237af245d11STodd Fiala 
1238af245d11STodd Fiala   return error;
1239af245d11STodd Fiala }
1240af245d11STodd Fiala 
124197206d57SZachary Turner static Status
124215930862SPavel Labath ParseMemoryRegionInfoFromProcMapsLine(llvm::StringRef &maps_line,
1243b9c1b51eSKate Stone                                       MemoryRegionInfo &memory_region_info) {
1244af245d11STodd Fiala   memory_region_info.Clear();
1245af245d11STodd Fiala 
124615930862SPavel Labath   StringExtractor line_extractor(maps_line);
1247af245d11STodd Fiala 
1248b9c1b51eSKate Stone   // Format: {address_start_hex}-{address_end_hex} perms offset  dev   inode
1249*05097246SAdrian Prantl   // pathname perms: rwxp   (letter is present if set, '-' if not, final
1250*05097246SAdrian Prantl   // character is p=private, s=shared).
1251af245d11STodd Fiala 
1252af245d11STodd Fiala   // Parse out the starting address
1253af245d11STodd Fiala   lldb::addr_t start_address = line_extractor.GetHexMaxU64(false, 0);
1254af245d11STodd Fiala 
1255af245d11STodd Fiala   // Parse out hyphen separating start and end address from range.
1256af245d11STodd Fiala   if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != '-'))
125797206d57SZachary Turner     return Status(
1258b9c1b51eSKate Stone         "malformed /proc/{pid}/maps entry, missing dash between address range");
1259af245d11STodd Fiala 
1260af245d11STodd Fiala   // Parse out the ending address
1261af245d11STodd Fiala   lldb::addr_t end_address = line_extractor.GetHexMaxU64(false, start_address);
1262af245d11STodd Fiala 
1263af245d11STodd Fiala   // Parse out the space after the address.
1264af245d11STodd Fiala   if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != ' '))
126597206d57SZachary Turner     return Status(
126697206d57SZachary Turner         "malformed /proc/{pid}/maps entry, missing space after range");
1267af245d11STodd Fiala 
1268af245d11STodd Fiala   // Save the range.
1269af245d11STodd Fiala   memory_region_info.GetRange().SetRangeBase(start_address);
1270af245d11STodd Fiala   memory_region_info.GetRange().SetRangeEnd(end_address);
1271af245d11STodd Fiala 
1272b9c1b51eSKate Stone   // Any memory region in /proc/{pid}/maps is by definition mapped into the
1273b9c1b51eSKate Stone   // process.
1274ad007563SHoward Hellyer   memory_region_info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
1275ad007563SHoward Hellyer 
1276af245d11STodd Fiala   // Parse out each permission entry.
1277af245d11STodd Fiala   if (line_extractor.GetBytesLeft() < 4)
127897206d57SZachary Turner     return Status("malformed /proc/{pid}/maps entry, missing some portion of "
1279b9c1b51eSKate Stone                   "permissions");
1280af245d11STodd Fiala 
1281af245d11STodd Fiala   // Handle read permission.
1282af245d11STodd Fiala   const char read_perm_char = line_extractor.GetChar();
1283af245d11STodd Fiala   if (read_perm_char == 'r')
1284af245d11STodd Fiala     memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eYes);
1285c73301bbSTamas Berghammer   else if (read_perm_char == '-')
1286af245d11STodd Fiala     memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1287c73301bbSTamas Berghammer   else
128897206d57SZachary Turner     return Status("unexpected /proc/{pid}/maps read permission char");
1289af245d11STodd Fiala 
1290af245d11STodd Fiala   // Handle write permission.
1291af245d11STodd Fiala   const char write_perm_char = line_extractor.GetChar();
1292af245d11STodd Fiala   if (write_perm_char == 'w')
1293af245d11STodd Fiala     memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eYes);
1294c73301bbSTamas Berghammer   else if (write_perm_char == '-')
1295af245d11STodd Fiala     memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1296c73301bbSTamas Berghammer   else
129797206d57SZachary Turner     return Status("unexpected /proc/{pid}/maps write permission char");
1298af245d11STodd Fiala 
1299af245d11STodd Fiala   // Handle execute permission.
1300af245d11STodd Fiala   const char exec_perm_char = line_extractor.GetChar();
1301af245d11STodd Fiala   if (exec_perm_char == 'x')
1302af245d11STodd Fiala     memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes);
1303c73301bbSTamas Berghammer   else if (exec_perm_char == '-')
1304af245d11STodd Fiala     memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1305c73301bbSTamas Berghammer   else
130697206d57SZachary Turner     return Status("unexpected /proc/{pid}/maps exec permission char");
1307af245d11STodd Fiala 
1308d7d69f80STamas Berghammer   line_extractor.GetChar();              // Read the private bit
1309d7d69f80STamas Berghammer   line_extractor.SkipSpaces();           // Skip the separator
1310d7d69f80STamas Berghammer   line_extractor.GetHexMaxU64(false, 0); // Read the offset
1311d7d69f80STamas Berghammer   line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1312d7d69f80STamas Berghammer   line_extractor.GetChar();              // Read the device id separator
1313d7d69f80STamas Berghammer   line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1314d7d69f80STamas Berghammer   line_extractor.SkipSpaces();           // Skip the separator
1315d7d69f80STamas Berghammer   line_extractor.GetU64(0, 10);          // Read the inode number
1316d7d69f80STamas Berghammer 
1317d7d69f80STamas Berghammer   line_extractor.SkipSpaces();
1318b9739d40SPavel Labath   const char *name = line_extractor.Peek();
1319b9739d40SPavel Labath   if (name)
1320b9739d40SPavel Labath     memory_region_info.SetName(name);
1321d7d69f80STamas Berghammer 
132297206d57SZachary Turner   return Status();
1323af245d11STodd Fiala }
1324af245d11STodd Fiala 
132597206d57SZachary Turner Status NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr,
1326b9c1b51eSKate Stone                                                MemoryRegionInfo &range_info) {
1327b9c1b51eSKate Stone   // FIXME review that the final memory region returned extends to the end of
1328b9c1b51eSKate Stone   // the virtual address space,
1329af245d11STodd Fiala   // with no perms if it is not mapped.
1330af245d11STodd Fiala 
1331*05097246SAdrian Prantl   // Use an approach that reads memory regions from /proc/{pid}/maps. Assume
1332*05097246SAdrian Prantl   // proc maps entries are in ascending order.
1333af245d11STodd Fiala   // FIXME assert if we find differently.
1334af245d11STodd Fiala 
1335b9c1b51eSKate Stone   if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
1336af245d11STodd Fiala     // We're done.
133797206d57SZachary Turner     return Status("unsupported");
1338af245d11STodd Fiala   }
1339af245d11STodd Fiala 
134097206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
1341b9c1b51eSKate Stone   if (error.Fail()) {
1342af245d11STodd Fiala     return error;
1343af245d11STodd Fiala   }
1344af245d11STodd Fiala 
1345af245d11STodd Fiala   lldb::addr_t prev_base_address = 0;
1346af245d11STodd Fiala 
1347b9c1b51eSKate Stone   // FIXME start by finding the last region that is <= target address using
1348b9c1b51eSKate Stone   // binary search.  Data is sorted.
1349af245d11STodd Fiala   // There can be a ton of regions on pthreads apps with lots of threads.
1350b9c1b51eSKate Stone   for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1351b9c1b51eSKate Stone        ++it) {
1352a6f5795aSTamas Berghammer     MemoryRegionInfo &proc_entry_info = it->first;
1353af245d11STodd Fiala 
1354af245d11STodd Fiala     // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1355b9c1b51eSKate Stone     assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
1356b9c1b51eSKate Stone            "descending /proc/pid/maps entries detected, unexpected");
1357af245d11STodd Fiala     prev_base_address = proc_entry_info.GetRange().GetRangeBase();
1358b1554311SHafiz Abid Qadeer     UNUSED_IF_ASSERT_DISABLED(prev_base_address);
1359af245d11STodd Fiala 
1360b9c1b51eSKate Stone     // If the target address comes before this entry, indicate distance to next
1361b9c1b51eSKate Stone     // region.
1362b9c1b51eSKate Stone     if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1363af245d11STodd Fiala       range_info.GetRange().SetRangeBase(load_addr);
1364b9c1b51eSKate Stone       range_info.GetRange().SetByteSize(
1365b9c1b51eSKate Stone           proc_entry_info.GetRange().GetRangeBase() - load_addr);
1366af245d11STodd Fiala       range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1367af245d11STodd Fiala       range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1368af245d11STodd Fiala       range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1369ad007563SHoward Hellyer       range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1370af245d11STodd Fiala 
1371af245d11STodd Fiala       return error;
1372b9c1b51eSKate Stone     } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1373af245d11STodd Fiala       // The target address is within the memory region we're processing here.
1374af245d11STodd Fiala       range_info = proc_entry_info;
1375af245d11STodd Fiala       return error;
1376af245d11STodd Fiala     }
1377af245d11STodd Fiala 
1378b9c1b51eSKate Stone     // The target memory address comes somewhere after the region we just
1379b9c1b51eSKate Stone     // parsed.
1380af245d11STodd Fiala   }
1381af245d11STodd Fiala 
1382b9c1b51eSKate Stone   // If we made it here, we didn't find an entry that contained the given
1383*05097246SAdrian Prantl   // address. Return the load_addr as start and the amount of bytes betwwen
1384*05097246SAdrian Prantl   // load address and the end of the memory as size.
138509839c33STamas Berghammer   range_info.GetRange().SetRangeBase(load_addr);
1386ad007563SHoward Hellyer   range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
138709839c33STamas Berghammer   range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
138809839c33STamas Berghammer   range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
138909839c33STamas Berghammer   range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1390ad007563SHoward Hellyer   range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1391af245d11STodd Fiala   return error;
1392af245d11STodd Fiala }
1393af245d11STodd Fiala 
139497206d57SZachary Turner Status NativeProcessLinux::PopulateMemoryRegionCache() {
1395a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1396a6f5795aSTamas Berghammer 
1397a6f5795aSTamas Berghammer   // If our cache is empty, pull the latest.  There should always be at least
1398a6f5795aSTamas Berghammer   // one memory region if memory region handling is supported.
1399a6f5795aSTamas Berghammer   if (!m_mem_region_cache.empty()) {
1400a6321a8eSPavel Labath     LLDB_LOG(log, "reusing {0} cached memory region entries",
1401a6321a8eSPavel Labath              m_mem_region_cache.size());
140297206d57SZachary Turner     return Status();
1403a6f5795aSTamas Berghammer   }
1404a6f5795aSTamas Berghammer 
140515930862SPavel Labath   auto BufferOrError = getProcFile(GetID(), "maps");
140615930862SPavel Labath   if (!BufferOrError) {
140715930862SPavel Labath     m_supports_mem_region = LazyBool::eLazyBoolNo;
140815930862SPavel Labath     return BufferOrError.getError();
140915930862SPavel Labath   }
141015930862SPavel Labath   StringRef Rest = BufferOrError.get()->getBuffer();
141115930862SPavel Labath   while (! Rest.empty()) {
141215930862SPavel Labath     StringRef Line;
141315930862SPavel Labath     std::tie(Line, Rest) = Rest.split('\n');
1414a6f5795aSTamas Berghammer     MemoryRegionInfo info;
141597206d57SZachary Turner     const Status parse_error =
141697206d57SZachary Turner         ParseMemoryRegionInfoFromProcMapsLine(Line, info);
141715930862SPavel Labath     if (parse_error.Fail()) {
141815930862SPavel Labath       LLDB_LOG(log, "failed to parse proc maps line '{0}': {1}", Line,
141915930862SPavel Labath                parse_error);
142015930862SPavel Labath       m_supports_mem_region = LazyBool::eLazyBoolNo;
142115930862SPavel Labath       return parse_error;
142215930862SPavel Labath     }
1423a6f5795aSTamas Berghammer     m_mem_region_cache.emplace_back(
1424a6f5795aSTamas Berghammer         info, FileSpec(info.GetName().GetCString(), true));
1425a6f5795aSTamas Berghammer   }
1426a6f5795aSTamas Berghammer 
142715930862SPavel Labath   if (m_mem_region_cache.empty()) {
1428a6f5795aSTamas Berghammer     // No entries after attempting to read them.  This shouldn't happen if
1429*05097246SAdrian Prantl     // /proc/{pid}/maps is supported. Assume we don't support map entries via
1430*05097246SAdrian Prantl     // procfs.
143115930862SPavel Labath     m_supports_mem_region = LazyBool::eLazyBoolNo;
1432a6321a8eSPavel Labath     LLDB_LOG(log,
1433a6321a8eSPavel Labath              "failed to find any procfs maps entries, assuming no support "
1434a6321a8eSPavel Labath              "for memory region metadata retrieval");
143597206d57SZachary Turner     return Status("not supported");
1436a6f5795aSTamas Berghammer   }
1437a6f5795aSTamas Berghammer 
1438a6321a8eSPavel Labath   LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps",
1439a6321a8eSPavel Labath            m_mem_region_cache.size(), GetID());
1440a6f5795aSTamas Berghammer 
1441a6f5795aSTamas Berghammer   // We support memory retrieval, remember that.
1442a6f5795aSTamas Berghammer   m_supports_mem_region = LazyBool::eLazyBoolYes;
144397206d57SZachary Turner   return Status();
1444a6f5795aSTamas Berghammer }
1445a6f5795aSTamas Berghammer 
1446b9c1b51eSKate Stone void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
1447a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1448a6321a8eSPavel Labath   LLDB_LOG(log, "newBumpId={0}", newBumpId);
1449a6321a8eSPavel Labath   LLDB_LOG(log, "clearing {0} entries from memory region cache",
1450a6321a8eSPavel Labath            m_mem_region_cache.size());
1451af245d11STodd Fiala   m_mem_region_cache.clear();
1452af245d11STodd Fiala }
1453af245d11STodd Fiala 
145497206d57SZachary Turner Status NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions,
1455b9c1b51eSKate Stone                                           lldb::addr_t &addr) {
1456af245d11STodd Fiala // FIXME implementing this requires the equivalent of
1457*05097246SAdrian Prantl // InferiorCallPOSIX::InferiorCallMmap, which depends on functional ThreadPlans
1458*05097246SAdrian Prantl // working with Native*Protocol.
1459af245d11STodd Fiala #if 1
146097206d57SZachary Turner   return Status("not implemented yet");
1461af245d11STodd Fiala #else
1462af245d11STodd Fiala   addr = LLDB_INVALID_ADDRESS;
1463af245d11STodd Fiala 
1464af245d11STodd Fiala   unsigned prot = 0;
1465af245d11STodd Fiala   if (permissions & lldb::ePermissionsReadable)
1466af245d11STodd Fiala     prot |= eMmapProtRead;
1467af245d11STodd Fiala   if (permissions & lldb::ePermissionsWritable)
1468af245d11STodd Fiala     prot |= eMmapProtWrite;
1469af245d11STodd Fiala   if (permissions & lldb::ePermissionsExecutable)
1470af245d11STodd Fiala     prot |= eMmapProtExec;
1471af245d11STodd Fiala 
1472af245d11STodd Fiala   // TODO implement this directly in NativeProcessLinux
1473*05097246SAdrian Prantl   // (and lift to NativeProcessPOSIX if/when that class is refactored out).
1474af245d11STodd Fiala   if (InferiorCallMmap(this, addr, 0, size, prot,
1475af245d11STodd Fiala                        eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
1476af245d11STodd Fiala     m_addr_to_mmap_size[addr] = size;
147797206d57SZachary Turner     return Status();
1478af245d11STodd Fiala   } else {
1479af245d11STodd Fiala     addr = LLDB_INVALID_ADDRESS;
148097206d57SZachary Turner     return Status("unable to allocate %" PRIu64
1481b9c1b51eSKate Stone                   " bytes of memory with permissions %s",
1482b9c1b51eSKate Stone                   size, GetPermissionsAsCString(permissions));
1483af245d11STodd Fiala   }
1484af245d11STodd Fiala #endif
1485af245d11STodd Fiala }
1486af245d11STodd Fiala 
148797206d57SZachary Turner Status NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {
1488af245d11STodd Fiala   // FIXME see comments in AllocateMemory - required lower-level
1489af245d11STodd Fiala   // bits not in place yet (ThreadPlans)
149097206d57SZachary Turner   return Status("not implemented");
1491af245d11STodd Fiala }
1492af245d11STodd Fiala 
1493b9c1b51eSKate Stone lldb::addr_t NativeProcessLinux::GetSharedLibraryInfoAddress() {
1494af245d11STodd Fiala   // punt on this for now
1495af245d11STodd Fiala   return LLDB_INVALID_ADDRESS;
1496af245d11STodd Fiala }
1497af245d11STodd Fiala 
1498b9c1b51eSKate Stone size_t NativeProcessLinux::UpdateThreads() {
1499*05097246SAdrian Prantl   // The NativeProcessLinux monitoring threads are always up to date with
1500*05097246SAdrian Prantl   // respect to thread state and they keep the thread list populated properly.
1501*05097246SAdrian Prantl   // All this method needs to do is return the thread count.
1502af245d11STodd Fiala   return m_threads.size();
1503af245d11STodd Fiala }
1504af245d11STodd Fiala 
150597206d57SZachary Turner Status NativeProcessLinux::GetSoftwareBreakpointPCOffset(
1506b9c1b51eSKate Stone     uint32_t &actual_opcode_size) {
1507af245d11STodd Fiala   // FIXME put this behind a breakpoint protocol class that can be
1508af245d11STodd Fiala   // set per architecture.  Need ARM, MIPS support here.
1509af245d11STodd Fiala   static const uint8_t g_i386_opcode[] = {0xCC};
1510bb00d0b6SUlrich Weigand   static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
1511af245d11STodd Fiala 
1512b9c1b51eSKate Stone   switch (m_arch.GetMachine()) {
1513af245d11STodd Fiala   case llvm::Triple::x86:
1514af245d11STodd Fiala   case llvm::Triple::x86_64:
1515af245d11STodd Fiala     actual_opcode_size = static_cast<uint32_t>(sizeof(g_i386_opcode));
151697206d57SZachary Turner     return Status();
1517af245d11STodd Fiala 
1518bb00d0b6SUlrich Weigand   case llvm::Triple::systemz:
1519bb00d0b6SUlrich Weigand     actual_opcode_size = static_cast<uint32_t>(sizeof(g_s390x_opcode));
152097206d57SZachary Turner     return Status();
1521bb00d0b6SUlrich Weigand 
1522ff7fd900STamas Berghammer   case llvm::Triple::arm:
1523ff7fd900STamas Berghammer   case llvm::Triple::aarch64:
1524e8659b5dSMohit K. Bhakkad   case llvm::Triple::mips64:
1525e8659b5dSMohit K. Bhakkad   case llvm::Triple::mips64el:
1526ce815e45SSagar Thakur   case llvm::Triple::mips:
1527ce815e45SSagar Thakur   case llvm::Triple::mipsel:
1528a3952ea7SPavel Labath   case llvm::Triple::ppc64le:
1529ff7fd900STamas Berghammer     // On these architectures the PC don't get updated for breakpoint hits
1530c60c9452SJaydeep Patil     actual_opcode_size = 0;
153197206d57SZachary Turner     return Status();
1532e8659b5dSMohit K. Bhakkad 
1533af245d11STodd Fiala   default:
1534af245d11STodd Fiala     assert(false && "CPU type not supported!");
153597206d57SZachary Turner     return Status("CPU type not supported");
1536af245d11STodd Fiala   }
1537af245d11STodd Fiala }
1538af245d11STodd Fiala 
153997206d57SZachary Turner Status NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,
1540b9c1b51eSKate Stone                                          bool hardware) {
1541af245d11STodd Fiala   if (hardware)
1542d5ffbad2SOmair Javaid     return SetHardwareBreakpoint(addr, size);
1543af245d11STodd Fiala   else
1544af245d11STodd Fiala     return SetSoftwareBreakpoint(addr, size);
1545af245d11STodd Fiala }
1546af245d11STodd Fiala 
154797206d57SZachary Turner Status NativeProcessLinux::RemoveBreakpoint(lldb::addr_t addr, bool hardware) {
1548d5ffbad2SOmair Javaid   if (hardware)
1549d5ffbad2SOmair Javaid     return RemoveHardwareBreakpoint(addr);
1550d5ffbad2SOmair Javaid   else
1551d5ffbad2SOmair Javaid     return NativeProcessProtocol::RemoveBreakpoint(addr);
1552d5ffbad2SOmair Javaid }
1553d5ffbad2SOmair Javaid 
155497206d57SZachary Turner Status NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(
1555b9c1b51eSKate Stone     size_t trap_opcode_size_hint, size_t &actual_opcode_size,
1556b9c1b51eSKate Stone     const uint8_t *&trap_opcode_bytes) {
155763c8be95STamas Berghammer   // FIXME put this behind a breakpoint protocol class that can be set per
155863c8be95STamas Berghammer   // architecture.  Need MIPS support here.
15592afc5966STodd Fiala   static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};
1560be379e15STamas Berghammer   // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1561be379e15STamas Berghammer   // linux kernel does otherwise.
1562be379e15STamas Berghammer   static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1563af245d11STodd Fiala   static const uint8_t g_i386_opcode[] = {0xCC};
15643df471c3SMohit K. Bhakkad   static const uint8_t g_mips64_opcode[] = {0x00, 0x00, 0x00, 0x0d};
15652c2acf96SMohit K. Bhakkad   static const uint8_t g_mips64el_opcode[] = {0x0d, 0x00, 0x00, 0x00};
1566bb00d0b6SUlrich Weigand   static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
1567be379e15STamas Berghammer   static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
1568aae0a752SEugene Zemtsov   static const uint8_t g_ppc64le_opcode[] = {0x08, 0x00, 0xe0, 0x7f}; // trap
1569af245d11STodd Fiala 
1570b9c1b51eSKate Stone   switch (m_arch.GetMachine()) {
15712afc5966STodd Fiala   case llvm::Triple::aarch64:
15722afc5966STodd Fiala     trap_opcode_bytes = g_aarch64_opcode;
15732afc5966STodd Fiala     actual_opcode_size = sizeof(g_aarch64_opcode);
157497206d57SZachary Turner     return Status();
15752afc5966STodd Fiala 
157663c8be95STamas Berghammer   case llvm::Triple::arm:
1577b9c1b51eSKate Stone     switch (trap_opcode_size_hint) {
157863c8be95STamas Berghammer     case 2:
157963c8be95STamas Berghammer       trap_opcode_bytes = g_thumb_breakpoint_opcode;
158063c8be95STamas Berghammer       actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
158197206d57SZachary Turner       return Status();
158263c8be95STamas Berghammer     case 4:
158363c8be95STamas Berghammer       trap_opcode_bytes = g_arm_breakpoint_opcode;
158463c8be95STamas Berghammer       actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
158597206d57SZachary Turner       return Status();
158663c8be95STamas Berghammer     default:
158763c8be95STamas Berghammer       assert(false && "Unrecognised trap opcode size hint!");
158897206d57SZachary Turner       return Status("Unrecognised trap opcode size hint!");
158963c8be95STamas Berghammer     }
159063c8be95STamas Berghammer 
1591af245d11STodd Fiala   case llvm::Triple::x86:
1592af245d11STodd Fiala   case llvm::Triple::x86_64:
1593af245d11STodd Fiala     trap_opcode_bytes = g_i386_opcode;
1594af245d11STodd Fiala     actual_opcode_size = sizeof(g_i386_opcode);
159597206d57SZachary Turner     return Status();
1596af245d11STodd Fiala 
1597ce815e45SSagar Thakur   case llvm::Triple::mips:
15983df471c3SMohit K. Bhakkad   case llvm::Triple::mips64:
15993df471c3SMohit K. Bhakkad     trap_opcode_bytes = g_mips64_opcode;
16003df471c3SMohit K. Bhakkad     actual_opcode_size = sizeof(g_mips64_opcode);
160197206d57SZachary Turner     return Status();
16023df471c3SMohit K. Bhakkad 
1603ce815e45SSagar Thakur   case llvm::Triple::mipsel:
16042c2acf96SMohit K. Bhakkad   case llvm::Triple::mips64el:
16052c2acf96SMohit K. Bhakkad     trap_opcode_bytes = g_mips64el_opcode;
16062c2acf96SMohit K. Bhakkad     actual_opcode_size = sizeof(g_mips64el_opcode);
160797206d57SZachary Turner     return Status();
16082c2acf96SMohit K. Bhakkad 
1609bb00d0b6SUlrich Weigand   case llvm::Triple::systemz:
1610bb00d0b6SUlrich Weigand     trap_opcode_bytes = g_s390x_opcode;
1611bb00d0b6SUlrich Weigand     actual_opcode_size = sizeof(g_s390x_opcode);
161297206d57SZachary Turner     return Status();
1613bb00d0b6SUlrich Weigand 
1614aae0a752SEugene Zemtsov   case llvm::Triple::ppc64le:
1615aae0a752SEugene Zemtsov     trap_opcode_bytes = g_ppc64le_opcode;
1616aae0a752SEugene Zemtsov     actual_opcode_size = sizeof(g_ppc64le_opcode);
1617aae0a752SEugene Zemtsov     return Status();
1618aae0a752SEugene Zemtsov 
1619af245d11STodd Fiala   default:
1620af245d11STodd Fiala     assert(false && "CPU type not supported!");
162197206d57SZachary Turner     return Status("CPU type not supported");
1622af245d11STodd Fiala   }
1623af245d11STodd Fiala }
1624af245d11STodd Fiala 
1625af245d11STodd Fiala #if 0
1626af245d11STodd Fiala ProcessMessage::CrashReason
1627af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
1628af245d11STodd Fiala {
1629af245d11STodd Fiala     ProcessMessage::CrashReason reason;
1630af245d11STodd Fiala     assert(info->si_signo == SIGSEGV);
1631af245d11STodd Fiala 
1632af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
1633af245d11STodd Fiala 
1634af245d11STodd Fiala     switch (info->si_code)
1635af245d11STodd Fiala     {
1636af245d11STodd Fiala     default:
1637af245d11STodd Fiala         assert(false && "unexpected si_code for SIGSEGV");
1638af245d11STodd Fiala         break;
1639af245d11STodd Fiala     case SI_KERNEL:
1640*05097246SAdrian Prantl         // Linux will occasionally send spurious SI_KERNEL codes. (this is
1641*05097246SAdrian Prantl         // poorly documented in sigaction) One way to get this is via unaligned
1642*05097246SAdrian Prantl         // SIMD loads.
1643af245d11STodd Fiala         reason = ProcessMessage::eInvalidAddress; // for lack of anything better
1644af245d11STodd Fiala         break;
1645af245d11STodd Fiala     case SEGV_MAPERR:
1646af245d11STodd Fiala         reason = ProcessMessage::eInvalidAddress;
1647af245d11STodd Fiala         break;
1648af245d11STodd Fiala     case SEGV_ACCERR:
1649af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedAddress;
1650af245d11STodd Fiala         break;
1651af245d11STodd Fiala     }
1652af245d11STodd Fiala 
1653af245d11STodd Fiala     return reason;
1654af245d11STodd Fiala }
1655af245d11STodd Fiala #endif
1656af245d11STodd Fiala 
1657af245d11STodd Fiala #if 0
1658af245d11STodd Fiala ProcessMessage::CrashReason
1659af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
1660af245d11STodd Fiala {
1661af245d11STodd Fiala     ProcessMessage::CrashReason reason;
1662af245d11STodd Fiala     assert(info->si_signo == SIGILL);
1663af245d11STodd Fiala 
1664af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
1665af245d11STodd Fiala 
1666af245d11STodd Fiala     switch (info->si_code)
1667af245d11STodd Fiala     {
1668af245d11STodd Fiala     default:
1669af245d11STodd Fiala         assert(false && "unexpected si_code for SIGILL");
1670af245d11STodd Fiala         break;
1671af245d11STodd Fiala     case ILL_ILLOPC:
1672af245d11STodd Fiala         reason = ProcessMessage::eIllegalOpcode;
1673af245d11STodd Fiala         break;
1674af245d11STodd Fiala     case ILL_ILLOPN:
1675af245d11STodd Fiala         reason = ProcessMessage::eIllegalOperand;
1676af245d11STodd Fiala         break;
1677af245d11STodd Fiala     case ILL_ILLADR:
1678af245d11STodd Fiala         reason = ProcessMessage::eIllegalAddressingMode;
1679af245d11STodd Fiala         break;
1680af245d11STodd Fiala     case ILL_ILLTRP:
1681af245d11STodd Fiala         reason = ProcessMessage::eIllegalTrap;
1682af245d11STodd Fiala         break;
1683af245d11STodd Fiala     case ILL_PRVOPC:
1684af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedOpcode;
1685af245d11STodd Fiala         break;
1686af245d11STodd Fiala     case ILL_PRVREG:
1687af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedRegister;
1688af245d11STodd Fiala         break;
1689af245d11STodd Fiala     case ILL_COPROC:
1690af245d11STodd Fiala         reason = ProcessMessage::eCoprocessorError;
1691af245d11STodd Fiala         break;
1692af245d11STodd Fiala     case ILL_BADSTK:
1693af245d11STodd Fiala         reason = ProcessMessage::eInternalStackError;
1694af245d11STodd Fiala         break;
1695af245d11STodd Fiala     }
1696af245d11STodd Fiala 
1697af245d11STodd Fiala     return reason;
1698af245d11STodd Fiala }
1699af245d11STodd Fiala #endif
1700af245d11STodd Fiala 
1701af245d11STodd Fiala #if 0
1702af245d11STodd Fiala ProcessMessage::CrashReason
1703af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
1704af245d11STodd Fiala {
1705af245d11STodd Fiala     ProcessMessage::CrashReason reason;
1706af245d11STodd Fiala     assert(info->si_signo == SIGFPE);
1707af245d11STodd Fiala 
1708af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
1709af245d11STodd Fiala 
1710af245d11STodd Fiala     switch (info->si_code)
1711af245d11STodd Fiala     {
1712af245d11STodd Fiala     default:
1713af245d11STodd Fiala         assert(false && "unexpected si_code for SIGFPE");
1714af245d11STodd Fiala         break;
1715af245d11STodd Fiala     case FPE_INTDIV:
1716af245d11STodd Fiala         reason = ProcessMessage::eIntegerDivideByZero;
1717af245d11STodd Fiala         break;
1718af245d11STodd Fiala     case FPE_INTOVF:
1719af245d11STodd Fiala         reason = ProcessMessage::eIntegerOverflow;
1720af245d11STodd Fiala         break;
1721af245d11STodd Fiala     case FPE_FLTDIV:
1722af245d11STodd Fiala         reason = ProcessMessage::eFloatDivideByZero;
1723af245d11STodd Fiala         break;
1724af245d11STodd Fiala     case FPE_FLTOVF:
1725af245d11STodd Fiala         reason = ProcessMessage::eFloatOverflow;
1726af245d11STodd Fiala         break;
1727af245d11STodd Fiala     case FPE_FLTUND:
1728af245d11STodd Fiala         reason = ProcessMessage::eFloatUnderflow;
1729af245d11STodd Fiala         break;
1730af245d11STodd Fiala     case FPE_FLTRES:
1731af245d11STodd Fiala         reason = ProcessMessage::eFloatInexactResult;
1732af245d11STodd Fiala         break;
1733af245d11STodd Fiala     case FPE_FLTINV:
1734af245d11STodd Fiala         reason = ProcessMessage::eFloatInvalidOperation;
1735af245d11STodd Fiala         break;
1736af245d11STodd Fiala     case FPE_FLTSUB:
1737af245d11STodd Fiala         reason = ProcessMessage::eFloatSubscriptRange;
1738af245d11STodd Fiala         break;
1739af245d11STodd Fiala     }
1740af245d11STodd Fiala 
1741af245d11STodd Fiala     return reason;
1742af245d11STodd Fiala }
1743af245d11STodd Fiala #endif
1744af245d11STodd Fiala 
1745af245d11STodd Fiala #if 0
1746af245d11STodd Fiala ProcessMessage::CrashReason
1747af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
1748af245d11STodd Fiala {
1749af245d11STodd Fiala     ProcessMessage::CrashReason reason;
1750af245d11STodd Fiala     assert(info->si_signo == SIGBUS);
1751af245d11STodd Fiala 
1752af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
1753af245d11STodd Fiala 
1754af245d11STodd Fiala     switch (info->si_code)
1755af245d11STodd Fiala     {
1756af245d11STodd Fiala     default:
1757af245d11STodd Fiala         assert(false && "unexpected si_code for SIGBUS");
1758af245d11STodd Fiala         break;
1759af245d11STodd Fiala     case BUS_ADRALN:
1760af245d11STodd Fiala         reason = ProcessMessage::eIllegalAlignment;
1761af245d11STodd Fiala         break;
1762af245d11STodd Fiala     case BUS_ADRERR:
1763af245d11STodd Fiala         reason = ProcessMessage::eIllegalAddress;
1764af245d11STodd Fiala         break;
1765af245d11STodd Fiala     case BUS_OBJERR:
1766af245d11STodd Fiala         reason = ProcessMessage::eHardwareError;
1767af245d11STodd Fiala         break;
1768af245d11STodd Fiala     }
1769af245d11STodd Fiala 
1770af245d11STodd Fiala     return reason;
1771af245d11STodd Fiala }
1772af245d11STodd Fiala #endif
1773af245d11STodd Fiala 
177497206d57SZachary Turner Status NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
1775b9c1b51eSKate Stone                                       size_t &bytes_read) {
1776df7c6995SPavel Labath   if (ProcessVmReadvSupported()) {
1777b9c1b51eSKate Stone     // The process_vm_readv path is about 50 times faster than ptrace api. We
1778*05097246SAdrian Prantl     // want to use this syscall if it is supported.
1779df7c6995SPavel Labath 
1780df7c6995SPavel Labath     const ::pid_t pid = GetID();
1781df7c6995SPavel Labath 
1782df7c6995SPavel Labath     struct iovec local_iov, remote_iov;
1783df7c6995SPavel Labath     local_iov.iov_base = buf;
1784df7c6995SPavel Labath     local_iov.iov_len = size;
1785df7c6995SPavel Labath     remote_iov.iov_base = reinterpret_cast<void *>(addr);
1786df7c6995SPavel Labath     remote_iov.iov_len = size;
1787df7c6995SPavel Labath 
1788df7c6995SPavel Labath     bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
1789df7c6995SPavel Labath     const bool success = bytes_read == size;
1790df7c6995SPavel Labath 
1791a6321a8eSPavel Labath     Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1792a6321a8eSPavel Labath     LLDB_LOG(log,
1793a6321a8eSPavel Labath              "using process_vm_readv to read {0} bytes from inferior "
1794a6321a8eSPavel Labath              "address {1:x}: {2}",
179510c41f37SPavel Labath              size, addr, success ? "Success" : llvm::sys::StrError(errno));
1796df7c6995SPavel Labath 
1797df7c6995SPavel Labath     if (success)
179897206d57SZachary Turner       return Status();
1799a6321a8eSPavel Labath     // else the call failed for some reason, let's retry the read using ptrace
1800b9c1b51eSKate Stone     // api.
1801df7c6995SPavel Labath   }
1802df7c6995SPavel Labath 
180319cbe96aSPavel Labath   unsigned char *dst = static_cast<unsigned char *>(buf);
180419cbe96aSPavel Labath   size_t remainder;
180519cbe96aSPavel Labath   long data;
180619cbe96aSPavel Labath 
1807a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1808a6321a8eSPavel Labath   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
180919cbe96aSPavel Labath 
1810b9c1b51eSKate Stone   for (bytes_read = 0; bytes_read < size; bytes_read += remainder) {
181197206d57SZachary Turner     Status error = NativeProcessLinux::PtraceWrapper(
1812b9c1b51eSKate Stone         PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data);
1813a6321a8eSPavel Labath     if (error.Fail())
181419cbe96aSPavel Labath       return error;
181519cbe96aSPavel Labath 
181619cbe96aSPavel Labath     remainder = size - bytes_read;
181719cbe96aSPavel Labath     remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
181819cbe96aSPavel Labath 
181919cbe96aSPavel Labath     // Copy the data into our buffer
1820f6ef187bSMohit K. Bhakkad     memcpy(dst, &data, remainder);
182119cbe96aSPavel Labath 
1822a6321a8eSPavel Labath     LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
182319cbe96aSPavel Labath     addr += k_ptrace_word_size;
182419cbe96aSPavel Labath     dst += k_ptrace_word_size;
182519cbe96aSPavel Labath   }
182697206d57SZachary Turner   return Status();
1827af245d11STodd Fiala }
1828af245d11STodd Fiala 
182997206d57SZachary Turner Status NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf,
1830b9c1b51eSKate Stone                                                  size_t size,
1831b9c1b51eSKate Stone                                                  size_t &bytes_read) {
183297206d57SZachary Turner   Status error = ReadMemory(addr, buf, size, bytes_read);
1833b9c1b51eSKate Stone   if (error.Fail())
1834b9c1b51eSKate Stone     return error;
18353eb4b458SChaoren Lin   return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
18363eb4b458SChaoren Lin }
18373eb4b458SChaoren Lin 
183897206d57SZachary Turner Status NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,
1839b9c1b51eSKate Stone                                        size_t size, size_t &bytes_written) {
184019cbe96aSPavel Labath   const unsigned char *src = static_cast<const unsigned char *>(buf);
184119cbe96aSPavel Labath   size_t remainder;
184297206d57SZachary Turner   Status error;
184319cbe96aSPavel Labath 
1844a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1845a6321a8eSPavel Labath   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
184619cbe96aSPavel Labath 
1847b9c1b51eSKate Stone   for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
184819cbe96aSPavel Labath     remainder = size - bytes_written;
184919cbe96aSPavel Labath     remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
185019cbe96aSPavel Labath 
1851b9c1b51eSKate Stone     if (remainder == k_ptrace_word_size) {
185219cbe96aSPavel Labath       unsigned long data = 0;
1853f6ef187bSMohit K. Bhakkad       memcpy(&data, src, k_ptrace_word_size);
185419cbe96aSPavel Labath 
1855a6321a8eSPavel Labath       LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
1856b9c1b51eSKate Stone       error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(),
1857b9c1b51eSKate Stone                                                 (void *)addr, (void *)data);
1858a6321a8eSPavel Labath       if (error.Fail())
185919cbe96aSPavel Labath         return error;
1860b9c1b51eSKate Stone     } else {
186119cbe96aSPavel Labath       unsigned char buff[8];
186219cbe96aSPavel Labath       size_t bytes_read;
186319cbe96aSPavel Labath       error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
1864a6321a8eSPavel Labath       if (error.Fail())
186519cbe96aSPavel Labath         return error;
186619cbe96aSPavel Labath 
186719cbe96aSPavel Labath       memcpy(buff, src, remainder);
186819cbe96aSPavel Labath 
186919cbe96aSPavel Labath       size_t bytes_written_rec;
187019cbe96aSPavel Labath       error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
1871a6321a8eSPavel Labath       if (error.Fail())
187219cbe96aSPavel Labath         return error;
187319cbe96aSPavel Labath 
1874a6321a8eSPavel Labath       LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src,
1875b9c1b51eSKate Stone                *(unsigned long *)buff);
187619cbe96aSPavel Labath     }
187719cbe96aSPavel Labath 
187819cbe96aSPavel Labath     addr += k_ptrace_word_size;
187919cbe96aSPavel Labath     src += k_ptrace_word_size;
188019cbe96aSPavel Labath   }
188119cbe96aSPavel Labath   return error;
1882af245d11STodd Fiala }
1883af245d11STodd Fiala 
188497206d57SZachary Turner Status NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) {
188519cbe96aSPavel Labath   return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
1886af245d11STodd Fiala }
1887af245d11STodd Fiala 
188897206d57SZachary Turner Status NativeProcessLinux::GetEventMessage(lldb::tid_t tid,
1889b9c1b51eSKate Stone                                            unsigned long *message) {
189019cbe96aSPavel Labath   return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
1891af245d11STodd Fiala }
1892af245d11STodd Fiala 
189397206d57SZachary Turner Status NativeProcessLinux::Detach(lldb::tid_t tid) {
189497ccc294SChaoren Lin   if (tid == LLDB_INVALID_THREAD_ID)
189597206d57SZachary Turner     return Status();
189697ccc294SChaoren Lin 
189719cbe96aSPavel Labath   return PtraceWrapper(PTRACE_DETACH, tid);
1898af245d11STodd Fiala }
1899af245d11STodd Fiala 
1900b9c1b51eSKate Stone bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {
1901a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
1902a5be48b3SPavel Labath     assert(thread && "thread list should not contain NULL threads");
1903a5be48b3SPavel Labath     if (thread->GetID() == thread_id) {
1904af245d11STodd Fiala       // We have this thread.
1905af245d11STodd Fiala       return true;
1906af245d11STodd Fiala     }
1907af245d11STodd Fiala   }
1908af245d11STodd Fiala 
1909af245d11STodd Fiala   // We don't have this thread.
1910af245d11STodd Fiala   return false;
1911af245d11STodd Fiala }
1912af245d11STodd Fiala 
1913b9c1b51eSKate Stone bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) {
1914a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1915a6321a8eSPavel Labath   LLDB_LOG(log, "tid: {0})", thread_id);
19161dbc6c9cSPavel Labath 
19171dbc6c9cSPavel Labath   bool found = false;
1918b9c1b51eSKate Stone   for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
1919b9c1b51eSKate Stone     if (*it && ((*it)->GetID() == thread_id)) {
1920af245d11STodd Fiala       m_threads.erase(it);
19211dbc6c9cSPavel Labath       found = true;
19221dbc6c9cSPavel Labath       break;
1923af245d11STodd Fiala     }
1924af245d11STodd Fiala   }
1925af245d11STodd Fiala 
192699e37695SRavitheja Addepally   if (found)
192799e37695SRavitheja Addepally     StopTracingForThread(thread_id);
19289eb1ecb9SPavel Labath   SignalIfAllThreadsStopped();
19291dbc6c9cSPavel Labath   return found;
1930af245d11STodd Fiala }
1931af245d11STodd Fiala 
1932a5be48b3SPavel Labath NativeThreadLinux &NativeProcessLinux::AddThread(lldb::tid_t thread_id) {
1933a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
1934a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
1935af245d11STodd Fiala 
1936b9c1b51eSKate Stone   assert(!HasThreadNoLock(thread_id) &&
1937b9c1b51eSKate Stone          "attempted to add a thread by id that already exists");
1938af245d11STodd Fiala 
1939af245d11STodd Fiala   // If this is the first thread, save it as the current thread
1940af245d11STodd Fiala   if (m_threads.empty())
1941af245d11STodd Fiala     SetCurrentThreadID(thread_id);
1942af245d11STodd Fiala 
1943a5be48b3SPavel Labath   m_threads.push_back(llvm::make_unique<NativeThreadLinux>(*this, thread_id));
194499e37695SRavitheja Addepally 
194599e37695SRavitheja Addepally   if (m_pt_proces_trace_id != LLDB_INVALID_UID) {
194699e37695SRavitheja Addepally     auto traceMonitor = ProcessorTraceMonitor::Create(
194799e37695SRavitheja Addepally         GetID(), thread_id, m_pt_process_trace_config, true);
194899e37695SRavitheja Addepally     if (traceMonitor) {
194999e37695SRavitheja Addepally       m_pt_traced_thread_group.insert(thread_id);
195099e37695SRavitheja Addepally       m_processor_trace_monitor.insert(
195199e37695SRavitheja Addepally           std::make_pair(thread_id, std::move(*traceMonitor)));
195299e37695SRavitheja Addepally     } else {
195399e37695SRavitheja Addepally       LLDB_LOG(log, "failed to start trace on thread {0}", thread_id);
195499e37695SRavitheja Addepally       Status error(traceMonitor.takeError());
195599e37695SRavitheja Addepally       LLDB_LOG(log, "error {0}", error);
195699e37695SRavitheja Addepally     }
195799e37695SRavitheja Addepally   }
195899e37695SRavitheja Addepally 
1959a5be48b3SPavel Labath   return static_cast<NativeThreadLinux &>(*m_threads.back());
1960af245d11STodd Fiala }
1961af245d11STodd Fiala 
196297206d57SZachary Turner Status
196397206d57SZachary Turner NativeProcessLinux::FixupBreakpointPCAsNeeded(NativeThreadLinux &thread) {
1964a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_BREAKPOINTS));
1965af245d11STodd Fiala 
196697206d57SZachary Turner   Status error;
1967af245d11STodd Fiala 
1968b9c1b51eSKate Stone   // Find out the size of a breakpoint (might depend on where we are in the
1969b9c1b51eSKate Stone   // code).
1970d37349f3SPavel Labath   NativeRegisterContext &context = thread.GetRegisterContext();
1971af245d11STodd Fiala 
1972af245d11STodd Fiala   uint32_t breakpoint_size = 0;
1973b9cc0c75SPavel Labath   error = GetSoftwareBreakpointPCOffset(breakpoint_size);
1974b9c1b51eSKate Stone   if (error.Fail()) {
1975a6321a8eSPavel Labath     LLDB_LOG(log, "GetBreakpointSize() failed: {0}", error);
1976af245d11STodd Fiala     return error;
1977a6321a8eSPavel Labath   } else
1978a6321a8eSPavel Labath     LLDB_LOG(log, "breakpoint size: {0}", breakpoint_size);
1979af245d11STodd Fiala 
1980b9c1b51eSKate Stone   // First try probing for a breakpoint at a software breakpoint location: PC -
1981b9c1b51eSKate Stone   // breakpoint size.
1982d37349f3SPavel Labath   const lldb::addr_t initial_pc_addr = context.GetPCfromBreakpointLocation();
1983af245d11STodd Fiala   lldb::addr_t breakpoint_addr = initial_pc_addr;
1984b9c1b51eSKate Stone   if (breakpoint_size > 0) {
1985af245d11STodd Fiala     // Do not allow breakpoint probe to wrap around.
19863eb4b458SChaoren Lin     if (breakpoint_addr >= breakpoint_size)
19873eb4b458SChaoren Lin       breakpoint_addr -= breakpoint_size;
1988af245d11STodd Fiala   }
1989af245d11STodd Fiala 
1990af245d11STodd Fiala   // Check if we stopped because of a breakpoint.
1991af245d11STodd Fiala   NativeBreakpointSP breakpoint_sp;
1992af245d11STodd Fiala   error = m_breakpoint_list.GetBreakpoint(breakpoint_addr, breakpoint_sp);
1993b9c1b51eSKate Stone   if (!error.Success() || !breakpoint_sp) {
1994af245d11STodd Fiala     // We didn't find one at a software probe location.  Nothing to do.
1995a6321a8eSPavel Labath     LLDB_LOG(log,
1996a6321a8eSPavel Labath              "pid {0} no lldb breakpoint found at current pc with "
1997a6321a8eSPavel Labath              "adjustment: {1}",
1998a6321a8eSPavel Labath              GetID(), breakpoint_addr);
199997206d57SZachary Turner     return Status();
2000af245d11STodd Fiala   }
2001af245d11STodd Fiala 
2002af245d11STodd Fiala   // If the breakpoint is not a software breakpoint, nothing to do.
2003b9c1b51eSKate Stone   if (!breakpoint_sp->IsSoftwareBreakpoint()) {
2004a6321a8eSPavel Labath     LLDB_LOG(
2005a6321a8eSPavel Labath         log,
2006a6321a8eSPavel Labath         "pid {0} breakpoint found at {1:x}, not software, nothing to adjust",
2007a6321a8eSPavel Labath         GetID(), breakpoint_addr);
200897206d57SZachary Turner     return Status();
2009af245d11STodd Fiala   }
2010af245d11STodd Fiala 
2011af245d11STodd Fiala   //
2012af245d11STodd Fiala   // We have a software breakpoint and need to adjust the PC.
2013af245d11STodd Fiala   //
2014af245d11STodd Fiala 
2015af245d11STodd Fiala   // Sanity check.
2016b9c1b51eSKate Stone   if (breakpoint_size == 0) {
2017af245d11STodd Fiala     // Nothing to do!  How did we get here?
2018a6321a8eSPavel Labath     LLDB_LOG(log,
2019a6321a8eSPavel Labath              "pid {0} breakpoint found at {1:x}, it is software, but the "
2020a6321a8eSPavel Labath              "size is zero, nothing to do (unexpected)",
2021a6321a8eSPavel Labath              GetID(), breakpoint_addr);
202297206d57SZachary Turner     return Status();
2023af245d11STodd Fiala   }
2024af245d11STodd Fiala 
2025af245d11STodd Fiala   // Change the program counter.
2026a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0} tid {1}: changing PC from {2:x} to {3:x}", GetID(),
2027a6321a8eSPavel Labath            thread.GetID(), initial_pc_addr, breakpoint_addr);
2028af245d11STodd Fiala 
2029d37349f3SPavel Labath   error = context.SetPC(breakpoint_addr);
2030b9c1b51eSKate Stone   if (error.Fail()) {
2031a6321a8eSPavel Labath     LLDB_LOG(log, "pid {0} tid {1}: failed to set PC: {2}", GetID(),
2032a6321a8eSPavel Labath              thread.GetID(), error);
2033af245d11STodd Fiala     return error;
2034af245d11STodd Fiala   }
2035af245d11STodd Fiala 
2036af245d11STodd Fiala   return error;
2037af245d11STodd Fiala }
2038fa03ad2eSChaoren Lin 
203997206d57SZachary Turner Status NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,
2040b9c1b51eSKate Stone                                                    FileSpec &file_spec) {
204197206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
2042a6f5795aSTamas Berghammer   if (error.Fail())
2043a6f5795aSTamas Berghammer     return error;
2044a6f5795aSTamas Berghammer 
20457cb18bf5STamas Berghammer   FileSpec module_file_spec(module_path, true);
20467cb18bf5STamas Berghammer 
20477cb18bf5STamas Berghammer   file_spec.Clear();
2048a6f5795aSTamas Berghammer   for (const auto &it : m_mem_region_cache) {
2049a6f5795aSTamas Berghammer     if (it.second.GetFilename() == module_file_spec.GetFilename()) {
2050a6f5795aSTamas Berghammer       file_spec = it.second;
205197206d57SZachary Turner       return Status();
2052a6f5795aSTamas Berghammer     }
2053a6f5795aSTamas Berghammer   }
205497206d57SZachary Turner   return Status("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
20557cb18bf5STamas Berghammer                 module_file_spec.GetFilename().AsCString(), GetID());
20567cb18bf5STamas Berghammer }
2057c076559aSPavel Labath 
205897206d57SZachary Turner Status NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
2059b9c1b51eSKate Stone                                               lldb::addr_t &load_addr) {
2060783bfc8cSTamas Berghammer   load_addr = LLDB_INVALID_ADDRESS;
206197206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
2062a6f5795aSTamas Berghammer   if (error.Fail())
2063783bfc8cSTamas Berghammer     return error;
2064a6f5795aSTamas Berghammer 
2065a6f5795aSTamas Berghammer   FileSpec file(file_name, false);
2066a6f5795aSTamas Berghammer   for (const auto &it : m_mem_region_cache) {
2067a6f5795aSTamas Berghammer     if (it.second == file) {
2068a6f5795aSTamas Berghammer       load_addr = it.first.GetRange().GetRangeBase();
206997206d57SZachary Turner       return Status();
2070a6f5795aSTamas Berghammer     }
2071a6f5795aSTamas Berghammer   }
207297206d57SZachary Turner   return Status("No load address found for specified file.");
2073783bfc8cSTamas Berghammer }
2074783bfc8cSTamas Berghammer 
2075a5be48b3SPavel Labath NativeThreadLinux *NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {
2076a5be48b3SPavel Labath   return static_cast<NativeThreadLinux *>(
2077b9c1b51eSKate Stone       NativeProcessProtocol::GetThreadByID(tid));
2078f9077782SPavel Labath }
2079f9077782SPavel Labath 
208097206d57SZachary Turner Status NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,
2081b9c1b51eSKate Stone                                         lldb::StateType state, int signo) {
2082a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2083a6321a8eSPavel Labath   LLDB_LOG(log, "tid: {0}", thread.GetID());
2084c076559aSPavel Labath 
2085*05097246SAdrian Prantl   // Before we do the resume below, first check if we have a pending stop
2086*05097246SAdrian Prantl   // notification that is currently waiting for all threads to stop.  This is
2087*05097246SAdrian Prantl   // potentially a buggy situation since we're ostensibly waiting for threads
2088*05097246SAdrian Prantl   // to stop before we send out the pending notification, and here we are
2089*05097246SAdrian Prantl   // resuming one before we send out the pending stop notification.
2090a6321a8eSPavel Labath   if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
2091a6321a8eSPavel Labath     LLDB_LOG(log,
2092a6321a8eSPavel Labath              "about to resume tid {0} per explicit request but we have a "
2093a6321a8eSPavel Labath              "pending stop notification (tid {1}) that is actively "
2094a6321a8eSPavel Labath              "waiting for this thread to stop. Valid sequence of events?",
2095a6321a8eSPavel Labath              thread.GetID(), m_pending_notification_tid);
2096c076559aSPavel Labath   }
2097c076559aSPavel Labath 
2098*05097246SAdrian Prantl   // Request a resume.  We expect this to be synchronous and the system to
2099*05097246SAdrian Prantl   // reflect it is running after this completes.
2100b9c1b51eSKate Stone   switch (state) {
2101b9c1b51eSKate Stone   case eStateRunning: {
2102605b51b8SPavel Labath     const auto resume_result = thread.Resume(signo);
21030e1d729bSPavel Labath     if (resume_result.Success())
21040e1d729bSPavel Labath       SetState(eStateRunning, true);
21050e1d729bSPavel Labath     return resume_result;
2106c076559aSPavel Labath   }
2107b9c1b51eSKate Stone   case eStateStepping: {
2108605b51b8SPavel Labath     const auto step_result = thread.SingleStep(signo);
21090e1d729bSPavel Labath     if (step_result.Success())
21100e1d729bSPavel Labath       SetState(eStateRunning, true);
21110e1d729bSPavel Labath     return step_result;
21120e1d729bSPavel Labath   }
21130e1d729bSPavel Labath   default:
21148198db30SPavel Labath     LLDB_LOG(log, "Unhandled state {0}.", state);
21150e1d729bSPavel Labath     llvm_unreachable("Unhandled state for resume");
21160e1d729bSPavel Labath   }
2117c076559aSPavel Labath }
2118c076559aSPavel Labath 
2119c076559aSPavel Labath //===----------------------------------------------------------------------===//
2120c076559aSPavel Labath 
2121b9c1b51eSKate Stone void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {
2122a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2123a6321a8eSPavel Labath   LLDB_LOG(log, "about to process event: (triggering_tid: {0})",
2124a6321a8eSPavel Labath            triggering_tid);
2125c076559aSPavel Labath 
21260e1d729bSPavel Labath   m_pending_notification_tid = triggering_tid;
21270e1d729bSPavel Labath 
2128*05097246SAdrian Prantl   // Request a stop for all the thread stops that need to be stopped and are
2129*05097246SAdrian Prantl   // not already known to be stopped.
2130a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
2131a5be48b3SPavel Labath     if (StateIsRunningState(thread->GetState()))
2132a5be48b3SPavel Labath       static_cast<NativeThreadLinux *>(thread.get())->RequestStop();
21330e1d729bSPavel Labath   }
21340e1d729bSPavel Labath 
21350e1d729bSPavel Labath   SignalIfAllThreadsStopped();
2136a6321a8eSPavel Labath   LLDB_LOG(log, "event processing done");
2137c076559aSPavel Labath }
2138c076559aSPavel Labath 
2139b9c1b51eSKate Stone void NativeProcessLinux::SignalIfAllThreadsStopped() {
21400e1d729bSPavel Labath   if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
21410e1d729bSPavel Labath     return; // No pending notification. Nothing to do.
21420e1d729bSPavel Labath 
2143b9c1b51eSKate Stone   for (const auto &thread_sp : m_threads) {
21440e1d729bSPavel Labath     if (StateIsRunningState(thread_sp->GetState()))
21450e1d729bSPavel Labath       return; // Some threads are still running. Don't signal yet.
21460e1d729bSPavel Labath   }
21470e1d729bSPavel Labath 
21480e1d729bSPavel Labath   // We have a pending notification and all threads have stopped.
2149b9c1b51eSKate Stone   Log *log(
2150b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
21519eb1ecb9SPavel Labath 
2152b9c1b51eSKate Stone   // Clear any temporary breakpoints we used to implement software single
2153b9c1b51eSKate Stone   // stepping.
2154b9c1b51eSKate Stone   for (const auto &thread_info : m_threads_stepping_with_breakpoint) {
215597206d57SZachary Turner     Status error = RemoveBreakpoint(thread_info.second);
21569eb1ecb9SPavel Labath     if (error.Fail())
2157a6321a8eSPavel Labath       LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}",
2158a6321a8eSPavel Labath                thread_info.first, error);
21599eb1ecb9SPavel Labath   }
21609eb1ecb9SPavel Labath   m_threads_stepping_with_breakpoint.clear();
21619eb1ecb9SPavel Labath 
21629eb1ecb9SPavel Labath   // Notify the delegate about the stop
21630e1d729bSPavel Labath   SetCurrentThreadID(m_pending_notification_tid);
2164ed89c7feSPavel Labath   SetState(StateType::eStateStopped, true);
21650e1d729bSPavel Labath   m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
2166c076559aSPavel Labath }
2167c076559aSPavel Labath 
2168b9c1b51eSKate Stone void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {
2169a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2170a6321a8eSPavel Labath   LLDB_LOG(log, "tid: {0}", thread.GetID());
21711dbc6c9cSPavel Labath 
2172b9c1b51eSKate Stone   if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID &&
2173b9c1b51eSKate Stone       StateIsRunningState(thread.GetState())) {
2174b9c1b51eSKate Stone     // We will need to wait for this new thread to stop as well before firing
2175*05097246SAdrian Prantl     // the notification.
2176f9077782SPavel Labath     thread.RequestStop();
2177c076559aSPavel Labath   }
2178c076559aSPavel Labath }
2179068f8a7eSTamas Berghammer 
2180b9c1b51eSKate Stone void NativeProcessLinux::SigchldHandler() {
2181a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
218219cbe96aSPavel Labath   // Process all pending waitpid notifications.
2183b9c1b51eSKate Stone   while (true) {
218419cbe96aSPavel Labath     int status = -1;
2185c1a6b128SPavel Labath     ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, -1, &status,
2186c1a6b128SPavel Labath                                           __WALL | __WNOTHREAD | WNOHANG);
218719cbe96aSPavel Labath 
218819cbe96aSPavel Labath     if (wait_pid == 0)
218919cbe96aSPavel Labath       break; // We are done.
219019cbe96aSPavel Labath 
2191b9c1b51eSKate Stone     if (wait_pid == -1) {
219297206d57SZachary Turner       Status error(errno, eErrorTypePOSIX);
2193a6321a8eSPavel Labath       LLDB_LOG(log, "waitpid (-1, &status, _) failed: {0}", error);
219419cbe96aSPavel Labath       break;
219519cbe96aSPavel Labath     }
219619cbe96aSPavel Labath 
21973508fc8cSPavel Labath     WaitStatus wait_status = WaitStatus::Decode(status);
21983508fc8cSPavel Labath     bool exited = wait_status.type == WaitStatus::Exit ||
21993508fc8cSPavel Labath                   (wait_status.type == WaitStatus::Signal &&
22003508fc8cSPavel Labath                    wait_pid == static_cast<::pid_t>(GetID()));
220119cbe96aSPavel Labath 
22023508fc8cSPavel Labath     LLDB_LOG(
22033508fc8cSPavel Labath         log,
22043508fc8cSPavel Labath         "waitpid (-1, &status, _) => pid = {0}, status = {1}, exited = {2}",
22053508fc8cSPavel Labath         wait_pid, wait_status, exited);
220619cbe96aSPavel Labath 
22073508fc8cSPavel Labath     MonitorCallback(wait_pid, exited, wait_status);
220819cbe96aSPavel Labath   }
2209068f8a7eSTamas Berghammer }
2210068f8a7eSTamas Berghammer 
2211*05097246SAdrian Prantl // Wrapper for ptrace to catch errors and log calls. Note that ptrace sets
2212*05097246SAdrian Prantl // errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
221397206d57SZachary Turner Status NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
2214b9c1b51eSKate Stone                                          void *data, size_t data_size,
2215b9c1b51eSKate Stone                                          long *result) {
221697206d57SZachary Turner   Status error;
22174a9babb2SPavel Labath   long int ret;
2218068f8a7eSTamas Berghammer 
2219068f8a7eSTamas Berghammer   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2220068f8a7eSTamas Berghammer 
2221068f8a7eSTamas Berghammer   PtraceDisplayBytes(req, data, data_size);
2222068f8a7eSTamas Berghammer 
2223068f8a7eSTamas Berghammer   errno = 0;
2224068f8a7eSTamas Berghammer   if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
2225b9c1b51eSKate Stone     ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2226b9c1b51eSKate Stone                  *(unsigned int *)addr, data);
2227068f8a7eSTamas Berghammer   else
2228b9c1b51eSKate Stone     ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2229b9c1b51eSKate Stone                  addr, data);
2230068f8a7eSTamas Berghammer 
22314a9babb2SPavel Labath   if (ret == -1)
2232068f8a7eSTamas Berghammer     error.SetErrorToErrno();
2233068f8a7eSTamas Berghammer 
22344a9babb2SPavel Labath   if (result)
22354a9babb2SPavel Labath     *result = ret;
22364a9babb2SPavel Labath 
223728096200SPavel Labath   LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data,
223828096200SPavel Labath            data_size, ret);
2239068f8a7eSTamas Berghammer 
2240068f8a7eSTamas Berghammer   PtraceDisplayBytes(req, data, data_size);
2241068f8a7eSTamas Berghammer 
2242a6321a8eSPavel Labath   if (error.Fail())
2243a6321a8eSPavel Labath     LLDB_LOG(log, "ptrace() failed: {0}", error);
2244068f8a7eSTamas Berghammer 
22454a9babb2SPavel Labath   return error;
2246068f8a7eSTamas Berghammer }
224799e37695SRavitheja Addepally 
224899e37695SRavitheja Addepally llvm::Expected<ProcessorTraceMonitor &>
224999e37695SRavitheja Addepally NativeProcessLinux::LookupProcessorTraceInstance(lldb::user_id_t traceid,
225099e37695SRavitheja Addepally                                                  lldb::tid_t thread) {
225199e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
225299e37695SRavitheja Addepally   if (thread == LLDB_INVALID_THREAD_ID && traceid == m_pt_proces_trace_id) {
225399e37695SRavitheja Addepally     LLDB_LOG(log, "thread not specified: {0}", traceid);
225499e37695SRavitheja Addepally     return Status("tracing not active thread not specified").ToError();
225599e37695SRavitheja Addepally   }
225699e37695SRavitheja Addepally 
225799e37695SRavitheja Addepally   for (auto& iter : m_processor_trace_monitor) {
225899e37695SRavitheja Addepally     if (traceid == iter.second->GetTraceID() &&
225999e37695SRavitheja Addepally         (thread == iter.first || thread == LLDB_INVALID_THREAD_ID))
226099e37695SRavitheja Addepally       return *(iter.second);
226199e37695SRavitheja Addepally   }
226299e37695SRavitheja Addepally 
226399e37695SRavitheja Addepally   LLDB_LOG(log, "traceid not being traced: {0}", traceid);
226499e37695SRavitheja Addepally   return Status("tracing not active for this thread").ToError();
226599e37695SRavitheja Addepally }
226699e37695SRavitheja Addepally 
226799e37695SRavitheja Addepally Status NativeProcessLinux::GetMetaData(lldb::user_id_t traceid,
226899e37695SRavitheja Addepally                                        lldb::tid_t thread,
226999e37695SRavitheja Addepally                                        llvm::MutableArrayRef<uint8_t> &buffer,
227099e37695SRavitheja Addepally                                        size_t offset) {
227199e37695SRavitheja Addepally   TraceOptions trace_options;
227299e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
227399e37695SRavitheja Addepally   Status error;
227499e37695SRavitheja Addepally 
227599e37695SRavitheja Addepally   LLDB_LOG(log, "traceid {0}", traceid);
227699e37695SRavitheja Addepally 
227799e37695SRavitheja Addepally   auto perf_monitor = LookupProcessorTraceInstance(traceid, thread);
227899e37695SRavitheja Addepally   if (!perf_monitor) {
227999e37695SRavitheja Addepally     LLDB_LOG(log, "traceid not being traced: {0}", traceid);
228099e37695SRavitheja Addepally     buffer = buffer.slice(buffer.size());
228199e37695SRavitheja Addepally     error = perf_monitor.takeError();
228299e37695SRavitheja Addepally     return error;
228399e37695SRavitheja Addepally   }
228499e37695SRavitheja Addepally   return (*perf_monitor).ReadPerfTraceData(buffer, offset);
228599e37695SRavitheja Addepally }
228699e37695SRavitheja Addepally 
228799e37695SRavitheja Addepally Status NativeProcessLinux::GetData(lldb::user_id_t traceid, lldb::tid_t thread,
228899e37695SRavitheja Addepally                                    llvm::MutableArrayRef<uint8_t> &buffer,
228999e37695SRavitheja Addepally                                    size_t offset) {
229099e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
229199e37695SRavitheja Addepally   Status error;
229299e37695SRavitheja Addepally 
229399e37695SRavitheja Addepally   LLDB_LOG(log, "traceid {0}", traceid);
229499e37695SRavitheja Addepally 
229599e37695SRavitheja Addepally   auto perf_monitor = LookupProcessorTraceInstance(traceid, thread);
229699e37695SRavitheja Addepally   if (!perf_monitor) {
229799e37695SRavitheja Addepally     LLDB_LOG(log, "traceid not being traced: {0}", traceid);
229899e37695SRavitheja Addepally     buffer = buffer.slice(buffer.size());
229999e37695SRavitheja Addepally     error = perf_monitor.takeError();
230099e37695SRavitheja Addepally     return error;
230199e37695SRavitheja Addepally   }
230299e37695SRavitheja Addepally   return (*perf_monitor).ReadPerfTraceAux(buffer, offset);
230399e37695SRavitheja Addepally }
230499e37695SRavitheja Addepally 
230599e37695SRavitheja Addepally Status NativeProcessLinux::GetTraceConfig(lldb::user_id_t traceid,
230699e37695SRavitheja Addepally                                           TraceOptions &config) {
230799e37695SRavitheja Addepally   Status error;
230899e37695SRavitheja Addepally   if (config.getThreadID() == LLDB_INVALID_THREAD_ID &&
230999e37695SRavitheja Addepally       m_pt_proces_trace_id == traceid) {
231099e37695SRavitheja Addepally     if (m_pt_proces_trace_id == LLDB_INVALID_UID) {
231199e37695SRavitheja Addepally       error.SetErrorString("tracing not active for this process");
231299e37695SRavitheja Addepally       return error;
231399e37695SRavitheja Addepally     }
231499e37695SRavitheja Addepally     config = m_pt_process_trace_config;
231599e37695SRavitheja Addepally   } else {
231699e37695SRavitheja Addepally     auto perf_monitor =
231799e37695SRavitheja Addepally         LookupProcessorTraceInstance(traceid, config.getThreadID());
231899e37695SRavitheja Addepally     if (!perf_monitor) {
231999e37695SRavitheja Addepally       error = perf_monitor.takeError();
232099e37695SRavitheja Addepally       return error;
232199e37695SRavitheja Addepally     }
232299e37695SRavitheja Addepally     error = (*perf_monitor).GetTraceConfig(config);
232399e37695SRavitheja Addepally   }
232499e37695SRavitheja Addepally   return error;
232599e37695SRavitheja Addepally }
232699e37695SRavitheja Addepally 
232799e37695SRavitheja Addepally lldb::user_id_t
232899e37695SRavitheja Addepally NativeProcessLinux::StartTraceGroup(const TraceOptions &config,
232999e37695SRavitheja Addepally                                            Status &error) {
233099e37695SRavitheja Addepally 
233199e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
233299e37695SRavitheja Addepally   if (config.getType() != TraceType::eTraceTypeProcessorTrace)
233399e37695SRavitheja Addepally     return LLDB_INVALID_UID;
233499e37695SRavitheja Addepally 
233599e37695SRavitheja Addepally   if (m_pt_proces_trace_id != LLDB_INVALID_UID) {
233699e37695SRavitheja Addepally     error.SetErrorString("tracing already active on this process");
233799e37695SRavitheja Addepally     return m_pt_proces_trace_id;
233899e37695SRavitheja Addepally   }
233999e37695SRavitheja Addepally 
234099e37695SRavitheja Addepally   for (const auto &thread_sp : m_threads) {
234199e37695SRavitheja Addepally     if (auto traceInstance = ProcessorTraceMonitor::Create(
234299e37695SRavitheja Addepally             GetID(), thread_sp->GetID(), config, true)) {
234399e37695SRavitheja Addepally       m_pt_traced_thread_group.insert(thread_sp->GetID());
234499e37695SRavitheja Addepally       m_processor_trace_monitor.insert(
234599e37695SRavitheja Addepally           std::make_pair(thread_sp->GetID(), std::move(*traceInstance)));
234699e37695SRavitheja Addepally     }
234799e37695SRavitheja Addepally   }
234899e37695SRavitheja Addepally 
234999e37695SRavitheja Addepally   m_pt_process_trace_config = config;
235099e37695SRavitheja Addepally   error = ProcessorTraceMonitor::GetCPUType(m_pt_process_trace_config);
235199e37695SRavitheja Addepally 
235299e37695SRavitheja Addepally   // Trace on Complete process will have traceid of 0
235399e37695SRavitheja Addepally   m_pt_proces_trace_id = 0;
235499e37695SRavitheja Addepally 
235599e37695SRavitheja Addepally   LLDB_LOG(log, "Process Trace ID {0}", m_pt_proces_trace_id);
235699e37695SRavitheja Addepally   return m_pt_proces_trace_id;
235799e37695SRavitheja Addepally }
235899e37695SRavitheja Addepally 
235999e37695SRavitheja Addepally lldb::user_id_t NativeProcessLinux::StartTrace(const TraceOptions &config,
236099e37695SRavitheja Addepally                                                Status &error) {
236199e37695SRavitheja Addepally   if (config.getType() != TraceType::eTraceTypeProcessorTrace)
236299e37695SRavitheja Addepally     return NativeProcessProtocol::StartTrace(config, error);
236399e37695SRavitheja Addepally 
236499e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
236599e37695SRavitheja Addepally 
236699e37695SRavitheja Addepally   lldb::tid_t threadid = config.getThreadID();
236799e37695SRavitheja Addepally 
236899e37695SRavitheja Addepally   if (threadid == LLDB_INVALID_THREAD_ID)
236999e37695SRavitheja Addepally     return StartTraceGroup(config, error);
237099e37695SRavitheja Addepally 
237199e37695SRavitheja Addepally   auto thread_sp = GetThreadByID(threadid);
237299e37695SRavitheja Addepally   if (!thread_sp) {
237399e37695SRavitheja Addepally     // Thread not tracked by lldb so don't trace.
237499e37695SRavitheja Addepally     error.SetErrorString("invalid thread id");
237599e37695SRavitheja Addepally     return LLDB_INVALID_UID;
237699e37695SRavitheja Addepally   }
237799e37695SRavitheja Addepally 
237899e37695SRavitheja Addepally   const auto &iter = m_processor_trace_monitor.find(threadid);
237999e37695SRavitheja Addepally   if (iter != m_processor_trace_monitor.end()) {
238099e37695SRavitheja Addepally     LLDB_LOG(log, "Thread already being traced");
238199e37695SRavitheja Addepally     error.SetErrorString("tracing already active on this thread");
238299e37695SRavitheja Addepally     return LLDB_INVALID_UID;
238399e37695SRavitheja Addepally   }
238499e37695SRavitheja Addepally 
238599e37695SRavitheja Addepally   auto traceMonitor =
238699e37695SRavitheja Addepally       ProcessorTraceMonitor::Create(GetID(), threadid, config, false);
238799e37695SRavitheja Addepally   if (!traceMonitor) {
238899e37695SRavitheja Addepally     error = traceMonitor.takeError();
238999e37695SRavitheja Addepally     LLDB_LOG(log, "error {0}", error);
239099e37695SRavitheja Addepally     return LLDB_INVALID_UID;
239199e37695SRavitheja Addepally   }
239299e37695SRavitheja Addepally   lldb::user_id_t ret_trace_id = (*traceMonitor)->GetTraceID();
239399e37695SRavitheja Addepally   m_processor_trace_monitor.insert(
239499e37695SRavitheja Addepally       std::make_pair(threadid, std::move(*traceMonitor)));
239599e37695SRavitheja Addepally   return ret_trace_id;
239699e37695SRavitheja Addepally }
239799e37695SRavitheja Addepally 
239899e37695SRavitheja Addepally Status NativeProcessLinux::StopTracingForThread(lldb::tid_t thread) {
239999e37695SRavitheja Addepally   Status error;
240099e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
240199e37695SRavitheja Addepally   LLDB_LOG(log, "Thread {0}", thread);
240299e37695SRavitheja Addepally 
240399e37695SRavitheja Addepally   const auto& iter = m_processor_trace_monitor.find(thread);
240499e37695SRavitheja Addepally   if (iter == m_processor_trace_monitor.end()) {
240599e37695SRavitheja Addepally     error.SetErrorString("tracing not active for this thread");
240699e37695SRavitheja Addepally     return error;
240799e37695SRavitheja Addepally   }
240899e37695SRavitheja Addepally 
240999e37695SRavitheja Addepally   if (iter->second->GetTraceID() == m_pt_proces_trace_id) {
2410*05097246SAdrian Prantl     // traceid maps to the whole process so we have to erase it from the thread
2411*05097246SAdrian Prantl     // group.
241299e37695SRavitheja Addepally     LLDB_LOG(log, "traceid maps to process");
241399e37695SRavitheja Addepally     m_pt_traced_thread_group.erase(thread);
241499e37695SRavitheja Addepally   }
241599e37695SRavitheja Addepally   m_processor_trace_monitor.erase(iter);
241699e37695SRavitheja Addepally 
241799e37695SRavitheja Addepally   return error;
241899e37695SRavitheja Addepally }
241999e37695SRavitheja Addepally 
242099e37695SRavitheja Addepally Status NativeProcessLinux::StopTrace(lldb::user_id_t traceid,
242199e37695SRavitheja Addepally                                      lldb::tid_t thread) {
242299e37695SRavitheja Addepally   Status error;
242399e37695SRavitheja Addepally 
242499e37695SRavitheja Addepally   TraceOptions trace_options;
242599e37695SRavitheja Addepally   trace_options.setThreadID(thread);
242699e37695SRavitheja Addepally   error = NativeProcessLinux::GetTraceConfig(traceid, trace_options);
242799e37695SRavitheja Addepally 
242899e37695SRavitheja Addepally   if (error.Fail())
242999e37695SRavitheja Addepally     return error;
243099e37695SRavitheja Addepally 
243199e37695SRavitheja Addepally   switch (trace_options.getType()) {
243299e37695SRavitheja Addepally   case lldb::TraceType::eTraceTypeProcessorTrace:
243399e37695SRavitheja Addepally     if (traceid == m_pt_proces_trace_id &&
243499e37695SRavitheja Addepally         thread == LLDB_INVALID_THREAD_ID)
243599e37695SRavitheja Addepally       StopProcessorTracingOnProcess();
243699e37695SRavitheja Addepally     else
243799e37695SRavitheja Addepally       error = StopProcessorTracingOnThread(traceid, thread);
243899e37695SRavitheja Addepally     break;
243999e37695SRavitheja Addepally   default:
244099e37695SRavitheja Addepally     error.SetErrorString("trace not supported");
244199e37695SRavitheja Addepally     break;
244299e37695SRavitheja Addepally   }
244399e37695SRavitheja Addepally 
244499e37695SRavitheja Addepally   return error;
244599e37695SRavitheja Addepally }
244699e37695SRavitheja Addepally 
244799e37695SRavitheja Addepally void NativeProcessLinux::StopProcessorTracingOnProcess() {
244899e37695SRavitheja Addepally   for (auto thread_id_iter : m_pt_traced_thread_group)
244999e37695SRavitheja Addepally     m_processor_trace_monitor.erase(thread_id_iter);
245099e37695SRavitheja Addepally   m_pt_traced_thread_group.clear();
245199e37695SRavitheja Addepally   m_pt_proces_trace_id = LLDB_INVALID_UID;
245299e37695SRavitheja Addepally }
245399e37695SRavitheja Addepally 
245499e37695SRavitheja Addepally Status NativeProcessLinux::StopProcessorTracingOnThread(lldb::user_id_t traceid,
245599e37695SRavitheja Addepally                                                         lldb::tid_t thread) {
245699e37695SRavitheja Addepally   Status error;
245799e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
245899e37695SRavitheja Addepally 
245999e37695SRavitheja Addepally   if (thread == LLDB_INVALID_THREAD_ID) {
246099e37695SRavitheja Addepally     for (auto& iter : m_processor_trace_monitor) {
246199e37695SRavitheja Addepally       if (iter.second->GetTraceID() == traceid) {
2462*05097246SAdrian Prantl         // Stopping a trace instance for an individual thread hence there will
2463*05097246SAdrian Prantl         // only be one traceid that can match.
246499e37695SRavitheja Addepally         m_processor_trace_monitor.erase(iter.first);
246599e37695SRavitheja Addepally         return error;
246699e37695SRavitheja Addepally       }
246799e37695SRavitheja Addepally       LLDB_LOG(log, "Trace ID {0}", iter.second->GetTraceID());
246899e37695SRavitheja Addepally     }
246999e37695SRavitheja Addepally 
247099e37695SRavitheja Addepally     LLDB_LOG(log, "Invalid TraceID");
247199e37695SRavitheja Addepally     error.SetErrorString("invalid trace id");
247299e37695SRavitheja Addepally     return error;
247399e37695SRavitheja Addepally   }
247499e37695SRavitheja Addepally 
247599e37695SRavitheja Addepally   // thread is specified so we can use find function on the map.
247699e37695SRavitheja Addepally   const auto& iter = m_processor_trace_monitor.find(thread);
247799e37695SRavitheja Addepally   if (iter == m_processor_trace_monitor.end()) {
247899e37695SRavitheja Addepally     // thread not found in our map.
247999e37695SRavitheja Addepally     LLDB_LOG(log, "thread not being traced");
248099e37695SRavitheja Addepally     error.SetErrorString("tracing not active for this thread");
248199e37695SRavitheja Addepally     return error;
248299e37695SRavitheja Addepally   }
248399e37695SRavitheja Addepally   if (iter->second->GetTraceID() != traceid) {
248499e37695SRavitheja Addepally     // traceid did not match so it has to be invalid.
248599e37695SRavitheja Addepally     LLDB_LOG(log, "Invalid TraceID");
248699e37695SRavitheja Addepally     error.SetErrorString("invalid trace id");
248799e37695SRavitheja Addepally     return error;
248899e37695SRavitheja Addepally   }
248999e37695SRavitheja Addepally 
249099e37695SRavitheja Addepally   LLDB_LOG(log, "UID - {0} , Thread -{1}", traceid, thread);
249199e37695SRavitheja Addepally 
249299e37695SRavitheja Addepally   if (traceid == m_pt_proces_trace_id) {
2493*05097246SAdrian Prantl     // traceid maps to the whole process so we have to erase it from the thread
2494*05097246SAdrian Prantl     // group.
249599e37695SRavitheja Addepally     LLDB_LOG(log, "traceid maps to process");
249699e37695SRavitheja Addepally     m_pt_traced_thread_group.erase(thread);
249799e37695SRavitheja Addepally   }
249899e37695SRavitheja Addepally   m_processor_trace_monitor.erase(iter);
249999e37695SRavitheja Addepally 
250099e37695SRavitheja Addepally   return error;
250199e37695SRavitheja Addepally }
2502