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()) {
340af245d11STodd Fiala           // No such thread. The thread may have exited.
341af245d11STodd Fiala           // More error handling 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);
351af245d11STodd Fiala         // Need to use __WALL otherwise we receive an error with errno=ECHLD
352af245d11STodd Fiala         // At this point we should have a thread stopped if waitpid succeeds.
35396e600fcSPavel Labath         if (wpid < 0) {
354af245d11STodd Fiala           // No such thread. The thread may have exited.
355af245d11STodd Fiala           // More error handling 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 
400af245d11STodd Fiala   // Have the tracer notify us before execve returns
401af245d11STodd Fiala   // (needed to disable legacy 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) {
441b9c1b51eSKate Stone     // Normally, the only situation when we cannot find the thread is if we have
442a6321a8eSPavel Labath     // 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) {
474fa03ad2eSChaoren Lin       // This is a group stop reception for this tid.
475b9c1b51eSKate Stone       // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU
476a6321a8eSPavel Labath       // into the tracee, triggering the group-stop mechanism. Normally
477a6321a8eSPavel Labath       // receiving these would stop the process, pending a SIGCONT. Simulating
478a6321a8eSPavel Labath       // this state in a debugger is hard and is generally not needed (one use
479a6321a8eSPavel Labath       // case is debugging background task being managed by a shell). For
480a6321a8eSPavel Labath       // general use, it is sufficient to stop the process in a signal-delivery
481b9c1b51eSKate Stone       // stop which happens before the group stop. This done by MonitorSignal
482a6321a8eSPavel Labath       // and works 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
508b9c1b51eSKate Stone         // have been killed outside
509af245d11STodd Fiala         // our control.  Is eStateExited the right 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
578b9c1b51eSKate Stone   // inferiors' children.  We'd need this to debug a monitor.
579af245d11STodd Fiala   // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
580af245d11STodd Fiala   // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
581af245d11STodd Fiala 
582b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): {
583b9c1b51eSKate Stone     // This is the notification on the parent thread which informs us of new
584b9c1b51eSKate Stone     // thread
585426bdf88SPavel Labath     // creation.
586b9c1b51eSKate Stone     // We don't want to do anything with the parent thread so we just resume it.
587b9c1b51eSKate Stone     // In case we
588b9c1b51eSKate Stone     // want to implement "break on thread creation" functionality, we would need
589b9c1b51eSKate Stone     // to stop
590426bdf88SPavel Labath     // here.
591af245d11STodd Fiala 
592af245d11STodd Fiala     unsigned long event_message = 0;
593b9c1b51eSKate Stone     if (GetEventMessage(thread.GetID(), &event_message).Fail()) {
594a6321a8eSPavel Labath       LLDB_LOG(log,
595a6321a8eSPavel Labath                "pid {0} received thread creation event but "
596a6321a8eSPavel Labath                "GetEventMessage failed so we don't know the new tid",
597a6321a8eSPavel Labath                thread.GetID());
598426bdf88SPavel Labath     } else
599426bdf88SPavel Labath       WaitForNewThread(event_message);
600af245d11STodd Fiala 
601b9cc0c75SPavel Labath     ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
602af245d11STodd Fiala     break;
603af245d11STodd Fiala   }
604af245d11STodd Fiala 
605b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): {
606a6321a8eSPavel Labath     LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP);
607a9882ceeSTodd Fiala 
6081dbc6c9cSPavel Labath     // Exec clears any pending notifications.
6090e1d729bSPavel Labath     m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
610fa03ad2eSChaoren Lin 
611b9c1b51eSKate Stone     // Remove all but the main thread here.  Linux fork creates a new process
612b9c1b51eSKate Stone     // which only copies the main thread.
613a6321a8eSPavel Labath     LLDB_LOG(log, "exec received, stop tracking all but main thread");
614a9882ceeSTodd Fiala 
615a5be48b3SPavel Labath     for (auto i = m_threads.begin(); i != m_threads.end();) {
616a5be48b3SPavel Labath       if ((*i)->GetID() == GetID())
617a5be48b3SPavel Labath         i = m_threads.erase(i);
618a5be48b3SPavel Labath       else
619a5be48b3SPavel Labath         ++i;
620a9882ceeSTodd Fiala     }
621a5be48b3SPavel Labath     assert(m_threads.size() == 1);
622a5be48b3SPavel Labath     auto *main_thread = static_cast<NativeThreadLinux *>(m_threads[0].get());
623a9882ceeSTodd Fiala 
624a5be48b3SPavel Labath     SetCurrentThreadID(main_thread->GetID());
625a5be48b3SPavel Labath     main_thread->SetStoppedByExec();
626a9882ceeSTodd Fiala 
627fa03ad2eSChaoren Lin     // Tell coordinator about about the "new" (since exec) stopped main thread.
628a5be48b3SPavel Labath     ThreadWasCreated(*main_thread);
629fa03ad2eSChaoren Lin 
630a9882ceeSTodd Fiala     // Let our delegate know we have just exec'd.
631a9882ceeSTodd Fiala     NotifyDidExec();
632a9882ceeSTodd Fiala 
633fa03ad2eSChaoren Lin     // Let the process know we're stopped.
634a5be48b3SPavel Labath     StopRunningThreads(main_thread->GetID());
635a9882ceeSTodd Fiala 
636af245d11STodd Fiala     break;
637a9882ceeSTodd Fiala   }
638af245d11STodd Fiala 
639b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): {
640af245d11STodd Fiala     // The inferior process or one of its threads is about to exit.
641b9c1b51eSKate Stone     // We don't want to do anything with the thread so we just resume it. In
642d8b3c1a1SPavel Labath     // case we want to implement "break on thread exit" functionality, we would
643d8b3c1a1SPavel Labath     // need to stop here.
644fa03ad2eSChaoren Lin 
645af245d11STodd Fiala     unsigned long data = 0;
646b9cc0c75SPavel Labath     if (GetEventMessage(thread.GetID(), &data).Fail())
647af245d11STodd Fiala       data = -1;
648af245d11STodd Fiala 
649a6321a8eSPavel Labath     LLDB_LOG(log,
650a6321a8eSPavel Labath              "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
651a6321a8eSPavel Labath              "WIFSIGNALED={2}, pid = {3}, main_thread = {4}",
652a6321a8eSPavel Labath              data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(),
653a6321a8eSPavel Labath              is_main_thread);
654af245d11STodd Fiala 
65575f47c3aSTodd Fiala 
65686852d36SPavel Labath     StateType state = thread.GetState();
657b9c1b51eSKate Stone     if (!StateIsRunningState(state)) {
658b9c1b51eSKate Stone       // Due to a kernel bug, we may sometimes get this stop after the inferior
659d8b3c1a1SPavel Labath       // gets a SIGKILL. This confuses our state tracking logic in
660d8b3c1a1SPavel Labath       // ResumeThread(), since normally, we should not be receiving any ptrace
661d8b3c1a1SPavel Labath       // events while the inferior is stopped. This makes sure that the inferior
662d8b3c1a1SPavel Labath       // is resumed and exits normally.
66386852d36SPavel Labath       state = eStateRunning;
66486852d36SPavel Labath     }
66586852d36SPavel Labath     ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
666af245d11STodd Fiala 
667af245d11STodd Fiala     break;
668af245d11STodd Fiala   }
669af245d11STodd Fiala 
670af245d11STodd Fiala   case 0:
671c16f5dcaSChaoren Lin   case TRAP_TRACE:  // We receive this on single stepping.
672c16f5dcaSChaoren Lin   case TRAP_HWBKPT: // We receive this on watchpoint hit
67386fd8e45SChaoren Lin   {
674c16f5dcaSChaoren Lin     // If a watchpoint was hit, report it
675c16f5dcaSChaoren Lin     uint32_t wp_index;
676d37349f3SPavel Labath     Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
677b9c1b51eSKate Stone         wp_index, (uintptr_t)info.si_addr);
678a6321a8eSPavel Labath     if (error.Fail())
679a6321a8eSPavel Labath       LLDB_LOG(log,
680a6321a8eSPavel Labath                "received error while checking for watchpoint hits, pid = "
681a6321a8eSPavel Labath                "{0}, error = {1}",
682a6321a8eSPavel Labath                thread.GetID(), error);
683b9c1b51eSKate Stone     if (wp_index != LLDB_INVALID_INDEX32) {
684b9cc0c75SPavel Labath       MonitorWatchpoint(thread, wp_index);
685c16f5dcaSChaoren Lin       break;
686c16f5dcaSChaoren Lin     }
687b9cc0c75SPavel Labath 
688d5ffbad2SOmair Javaid     // If a breakpoint was hit, report it
689d5ffbad2SOmair Javaid     uint32_t bp_index;
690d37349f3SPavel Labath     error = thread.GetRegisterContext().GetHardwareBreakHitIndex(
691d5ffbad2SOmair Javaid         bp_index, (uintptr_t)info.si_addr);
692d5ffbad2SOmair Javaid     if (error.Fail())
693d5ffbad2SOmair Javaid       LLDB_LOG(log, "received error while checking for hardware "
694d5ffbad2SOmair Javaid                     "breakpoint hits, pid = {0}, error = {1}",
695d5ffbad2SOmair Javaid                thread.GetID(), error);
696d5ffbad2SOmair Javaid     if (bp_index != LLDB_INVALID_INDEX32) {
697d5ffbad2SOmair Javaid       MonitorBreakpoint(thread);
698d5ffbad2SOmair Javaid       break;
699d5ffbad2SOmair Javaid     }
700d5ffbad2SOmair Javaid 
701be379e15STamas Berghammer     // Otherwise, report step over
702be379e15STamas Berghammer     MonitorTrace(thread);
703af245d11STodd Fiala     break;
704b9cc0c75SPavel Labath   }
705af245d11STodd Fiala 
706af245d11STodd Fiala   case SI_KERNEL:
70735799963SMohit K. Bhakkad #if defined __mips__
70835799963SMohit K. Bhakkad     // For mips there is no special signal for watchpoint
70935799963SMohit K. Bhakkad     // So we check for watchpoint in kernel trap
71035799963SMohit K. Bhakkad     {
71135799963SMohit K. Bhakkad       // If a watchpoint was hit, report it
71235799963SMohit K. Bhakkad       uint32_t wp_index;
713d37349f3SPavel Labath       Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
714b9c1b51eSKate Stone           wp_index, LLDB_INVALID_ADDRESS);
715a6321a8eSPavel Labath       if (error.Fail())
716a6321a8eSPavel Labath         LLDB_LOG(log,
717a6321a8eSPavel Labath                  "received error while checking for watchpoint hits, pid = "
718a6321a8eSPavel Labath                  "{0}, error = {1}",
719a6321a8eSPavel Labath                  thread.GetID(), error);
720b9c1b51eSKate Stone       if (wp_index != LLDB_INVALID_INDEX32) {
721b9cc0c75SPavel Labath         MonitorWatchpoint(thread, wp_index);
72235799963SMohit K. Bhakkad         break;
72335799963SMohit K. Bhakkad       }
72435799963SMohit K. Bhakkad     }
72535799963SMohit K. Bhakkad // NO BREAK
72635799963SMohit K. Bhakkad #endif
727af245d11STodd Fiala   case TRAP_BRKPT:
728b9cc0c75SPavel Labath     MonitorBreakpoint(thread);
729af245d11STodd Fiala     break;
730af245d11STodd Fiala 
731af245d11STodd Fiala   case SIGTRAP:
732af245d11STodd Fiala   case (SIGTRAP | 0x80):
733a6321a8eSPavel Labath     LLDB_LOG(
734a6321a8eSPavel Labath         log,
735a6321a8eSPavel Labath         "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",
736a6321a8eSPavel Labath         info.si_code, GetID(), thread.GetID());
737fa03ad2eSChaoren Lin 
738af245d11STodd Fiala     // Ignore these signals until we know more about them.
739b9cc0c75SPavel Labath     ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
740af245d11STodd Fiala     break;
741af245d11STodd Fiala 
742af245d11STodd Fiala   default:
74321a365baSPavel Labath     LLDB_LOG(log, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}",
744a6321a8eSPavel Labath              info.si_code, GetID(), thread.GetID());
74521a365baSPavel Labath     MonitorSignal(info, thread, false);
746af245d11STodd Fiala     break;
747af245d11STodd Fiala   }
748af245d11STodd Fiala }
749af245d11STodd Fiala 
750b9c1b51eSKate Stone void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) {
751a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
752a6321a8eSPavel Labath   LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID());
753c16f5dcaSChaoren Lin 
7540e1d729bSPavel Labath   // This thread is currently stopped.
755b9cc0c75SPavel Labath   thread.SetStoppedByTrace();
756c16f5dcaSChaoren Lin 
757b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
758c16f5dcaSChaoren Lin }
759c16f5dcaSChaoren Lin 
760b9c1b51eSKate Stone void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) {
761b9c1b51eSKate Stone   Log *log(
762b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
763a6321a8eSPavel Labath   LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID());
764c16f5dcaSChaoren Lin 
765c16f5dcaSChaoren Lin   // Mark the thread as stopped at breakpoint.
766b9cc0c75SPavel Labath   thread.SetStoppedByBreakpoint();
76797206d57SZachary Turner   Status error = FixupBreakpointPCAsNeeded(thread);
768c16f5dcaSChaoren Lin   if (error.Fail())
769a6321a8eSPavel Labath     LLDB_LOG(log, "pid = {0} fixup: {1}", thread.GetID(), error);
770d8c338d4STamas Berghammer 
771b9c1b51eSKate Stone   if (m_threads_stepping_with_breakpoint.find(thread.GetID()) !=
772b9c1b51eSKate Stone       m_threads_stepping_with_breakpoint.end())
773b9cc0c75SPavel Labath     thread.SetStoppedByTrace();
774c16f5dcaSChaoren Lin 
775b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
776c16f5dcaSChaoren Lin }
777c16f5dcaSChaoren Lin 
778b9c1b51eSKate Stone void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread,
779b9c1b51eSKate Stone                                            uint32_t wp_index) {
780b9c1b51eSKate Stone   Log *log(
781b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
782a6321a8eSPavel Labath   LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}",
783a6321a8eSPavel Labath            thread.GetID(), wp_index);
784c16f5dcaSChaoren Lin 
785c16f5dcaSChaoren Lin   // Mark the thread as stopped at watchpoint.
786c16f5dcaSChaoren Lin   // The address is at (lldb::addr_t)info->si_addr if we need it.
787f9077782SPavel Labath   thread.SetStoppedByWatchpoint(wp_index);
788c16f5dcaSChaoren Lin 
789b9c1b51eSKate Stone   // We need to tell all other running threads before we notify the delegate
790b9c1b51eSKate Stone   // about this stop.
791f9077782SPavel Labath   StopRunningThreads(thread.GetID());
792c16f5dcaSChaoren Lin }
793c16f5dcaSChaoren Lin 
794b9c1b51eSKate Stone void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
795b9c1b51eSKate Stone                                        NativeThreadLinux &thread, bool exited) {
796b9cc0c75SPavel Labath   const int signo = info.si_signo;
797b9cc0c75SPavel Labath   const bool is_from_llgs = info.si_pid == getpid();
798af245d11STodd Fiala 
799a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
800af245d11STodd Fiala 
801af245d11STodd Fiala   // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
802af245d11STodd Fiala   // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
803af245d11STodd Fiala   // kill(2) or raise(3).  Similarly for tgkill(2) on Linux.
804af245d11STodd Fiala   //
805af245d11STodd Fiala   // IOW, user generated signals never generate what we consider to be a
806af245d11STodd Fiala   // "crash".
807af245d11STodd Fiala   //
808af245d11STodd Fiala   // Similarly, ACK signals generated by this monitor.
809af245d11STodd Fiala 
810af245d11STodd Fiala   // Handle the signal.
811a6321a8eSPavel Labath   LLDB_LOG(log,
812a6321a8eSPavel Labath            "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
813a6321a8eSPavel Labath            "waitpid pid = {4})",
814a6321a8eSPavel Labath            Host::GetSignalAsCString(signo), signo, info.si_code,
815b9cc0c75SPavel Labath            thread.GetID());
81658a2f669STodd Fiala 
81758a2f669STodd Fiala   // Check for thread stop notification.
818b9c1b51eSKate Stone   if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) {
819af245d11STodd Fiala     // This is a tgkill()-based stop.
820a6321a8eSPavel Labath     LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID());
821fa03ad2eSChaoren Lin 
822aab58633SChaoren Lin     // Check that we're not already marked with a stop reason.
823b9c1b51eSKate Stone     // Note this thread really shouldn't already be marked as stopped - if we
824a6321a8eSPavel Labath     // were, that would imply that the kernel signaled us with the thread
825a6321a8eSPavel Labath     // stopping which we handled and marked as stopped, and that, without an
826a6321a8eSPavel Labath     // intervening resume, we received another stop.  It is more likely that we
827a6321a8eSPavel Labath     // are missing the marking of a run state somewhere if we find that the
828a6321a8eSPavel Labath     // thread was marked as stopped.
829b9cc0c75SPavel Labath     const StateType thread_state = thread.GetState();
830b9c1b51eSKate Stone     if (!StateIsStoppedState(thread_state, false)) {
831ed89c7feSPavel Labath       // An inferior thread has stopped because of a SIGSTOP we have sent it.
832b9c1b51eSKate Stone       // Generally, these are not important stops and we don't want to report
833a6321a8eSPavel Labath       // them as they are just used to stop other threads when one thread (the
834a6321a8eSPavel Labath       // one with the *real* stop reason) hits a breakpoint (watchpoint,
835a6321a8eSPavel Labath       // etc...). However, in the case of an asynchronous Interrupt(), this *is*
836a6321a8eSPavel Labath       // the real stop reason, so we leave the signal intact if this is the
837a6321a8eSPavel Labath       // thread that was chosen as the triggering thread.
838b9c1b51eSKate Stone       if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
839b9cc0c75SPavel Labath         if (m_pending_notification_tid == thread.GetID())
840b9cc0c75SPavel Labath           thread.SetStoppedBySignal(SIGSTOP, &info);
841ed89c7feSPavel Labath         else
842b9cc0c75SPavel Labath           thread.SetStoppedWithNoReason();
843ed89c7feSPavel Labath 
844b9cc0c75SPavel Labath         SetCurrentThreadID(thread.GetID());
8450e1d729bSPavel Labath         SignalIfAllThreadsStopped();
846b9c1b51eSKate Stone       } else {
8470e1d729bSPavel Labath         // We can end up here if stop was initiated by LLGS but by this time a
8480e1d729bSPavel Labath         // thread stop has occurred - maybe initiated by another event.
84997206d57SZachary Turner         Status error = ResumeThread(thread, thread.GetState(), 0);
850a6321a8eSPavel Labath         if (error.Fail())
851a6321a8eSPavel Labath           LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(),
852a6321a8eSPavel Labath                    error);
8530e1d729bSPavel Labath       }
854b9c1b51eSKate Stone     } else {
855a6321a8eSPavel Labath       LLDB_LOG(log,
856a6321a8eSPavel Labath                "pid {0} tid {1}, thread was already marked as a stopped "
857a6321a8eSPavel Labath                "state (state={2}), leaving stop signal as is",
8588198db30SPavel Labath                GetID(), thread.GetID(), thread_state);
8590e1d729bSPavel Labath       SignalIfAllThreadsStopped();
860af245d11STodd Fiala     }
861af245d11STodd Fiala 
86258a2f669STodd Fiala     // Done handling.
863af245d11STodd Fiala     return;
864af245d11STodd Fiala   }
865af245d11STodd Fiala 
8664a705e7eSPavel Labath   // Check if debugger should stop at this signal or just ignore it
8674a705e7eSPavel Labath   // and resume the inferior.
8684a705e7eSPavel Labath   if (m_signals_to_ignore.find(signo) != m_signals_to_ignore.end()) {
8694a705e7eSPavel Labath      ResumeThread(thread, thread.GetState(), signo);
8704a705e7eSPavel Labath      return;
8714a705e7eSPavel Labath   }
8724a705e7eSPavel Labath 
87386fd8e45SChaoren Lin   // This thread is stopped.
874a6321a8eSPavel Labath   LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo));
875b9cc0c75SPavel Labath   thread.SetStoppedBySignal(signo, &info);
87686fd8e45SChaoren Lin 
87786fd8e45SChaoren Lin   // Send a stop to the debugger after we get all other threads to stop.
878b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
879511e5cdcSTodd Fiala }
880af245d11STodd Fiala 
881e7708688STamas Berghammer namespace {
882e7708688STamas Berghammer 
883b9c1b51eSKate Stone struct EmulatorBaton {
884d37349f3SPavel Labath   NativeProcessLinux &m_process;
885d37349f3SPavel Labath   NativeRegisterContext &m_reg_context;
8866648fcc3SPavel Labath 
8876648fcc3SPavel Labath   // eRegisterKindDWARF -> RegsiterValue
8886648fcc3SPavel Labath   std::unordered_map<uint32_t, RegisterValue> m_register_values;
889e7708688STamas Berghammer 
890d37349f3SPavel Labath   EmulatorBaton(NativeProcessLinux &process, NativeRegisterContext &reg_context)
891b9c1b51eSKate Stone       : m_process(process), m_reg_context(reg_context) {}
892e7708688STamas Berghammer };
893e7708688STamas Berghammer 
894e7708688STamas Berghammer } // anonymous namespace
895e7708688STamas Berghammer 
896b9c1b51eSKate Stone static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
897e7708688STamas Berghammer                                  const EmulateInstruction::Context &context,
898b9c1b51eSKate Stone                                  lldb::addr_t addr, void *dst, size_t length) {
899e7708688STamas Berghammer   EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
900e7708688STamas Berghammer 
9013eb4b458SChaoren Lin   size_t bytes_read;
902d37349f3SPavel Labath   emulator_baton->m_process.ReadMemory(addr, dst, length, bytes_read);
903e7708688STamas Berghammer   return bytes_read;
904e7708688STamas Berghammer }
905e7708688STamas Berghammer 
906b9c1b51eSKate Stone static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
907e7708688STamas Berghammer                                  const RegisterInfo *reg_info,
908b9c1b51eSKate Stone                                  RegisterValue &reg_value) {
909e7708688STamas Berghammer   EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
910e7708688STamas Berghammer 
911b9c1b51eSKate Stone   auto it = emulator_baton->m_register_values.find(
912b9c1b51eSKate Stone       reg_info->kinds[eRegisterKindDWARF]);
913b9c1b51eSKate Stone   if (it != emulator_baton->m_register_values.end()) {
9146648fcc3SPavel Labath     reg_value = it->second;
9156648fcc3SPavel Labath     return true;
9166648fcc3SPavel Labath   }
9176648fcc3SPavel Labath 
918e7708688STamas Berghammer   // The emulator only fill in the dwarf regsiter numbers (and in some case
919e7708688STamas Berghammer   // the generic register numbers). Get the full register info from the
920e7708688STamas Berghammer   // register context based on the dwarf register numbers.
921b9c1b51eSKate Stone   const RegisterInfo *full_reg_info =
922d37349f3SPavel Labath       emulator_baton->m_reg_context.GetRegisterInfo(
923e7708688STamas Berghammer           eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
924e7708688STamas Berghammer 
92597206d57SZachary Turner   Status error =
926d37349f3SPavel Labath       emulator_baton->m_reg_context.ReadRegister(full_reg_info, reg_value);
9276648fcc3SPavel Labath   if (error.Success())
9286648fcc3SPavel Labath     return true;
929cdc22a88SMohit K. Bhakkad 
9306648fcc3SPavel Labath   return false;
931e7708688STamas Berghammer }
932e7708688STamas Berghammer 
933b9c1b51eSKate Stone static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
934e7708688STamas Berghammer                                   const EmulateInstruction::Context &context,
935e7708688STamas Berghammer                                   const RegisterInfo *reg_info,
936b9c1b51eSKate Stone                                   const RegisterValue &reg_value) {
937e7708688STamas Berghammer   EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
938b9c1b51eSKate Stone   emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
939b9c1b51eSKate Stone       reg_value;
940e7708688STamas Berghammer   return true;
941e7708688STamas Berghammer }
942e7708688STamas Berghammer 
943b9c1b51eSKate Stone static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
944e7708688STamas Berghammer                                   const EmulateInstruction::Context &context,
945b9c1b51eSKate Stone                                   lldb::addr_t addr, const void *dst,
946b9c1b51eSKate Stone                                   size_t length) {
947e7708688STamas Berghammer   return length;
948e7708688STamas Berghammer }
949e7708688STamas Berghammer 
950d37349f3SPavel Labath static lldb::addr_t ReadFlags(NativeRegisterContext &regsiter_context) {
951d37349f3SPavel Labath   const RegisterInfo *flags_info = regsiter_context.GetRegisterInfo(
952e7708688STamas Berghammer       eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
953d37349f3SPavel Labath   return regsiter_context.ReadRegisterAsUnsigned(flags_info,
954b9c1b51eSKate Stone                                                  LLDB_INVALID_ADDRESS);
955e7708688STamas Berghammer }
956e7708688STamas Berghammer 
95797206d57SZachary Turner Status
95897206d57SZachary Turner NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadLinux &thread) {
95997206d57SZachary Turner   Status error;
960d37349f3SPavel Labath   NativeRegisterContext& register_context = thread.GetRegisterContext();
961e7708688STamas Berghammer 
962e7708688STamas Berghammer   std::unique_ptr<EmulateInstruction> emulator_ap(
963b9c1b51eSKate Stone       EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying,
964b9c1b51eSKate Stone                                      nullptr));
965e7708688STamas Berghammer 
966e7708688STamas Berghammer   if (emulator_ap == nullptr)
96797206d57SZachary Turner     return Status("Instruction emulator not found!");
968e7708688STamas Berghammer 
969d37349f3SPavel Labath   EmulatorBaton baton(*this, register_context);
970e7708688STamas Berghammer   emulator_ap->SetBaton(&baton);
971e7708688STamas Berghammer   emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
972e7708688STamas Berghammer   emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
973e7708688STamas Berghammer   emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
974e7708688STamas Berghammer   emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
975e7708688STamas Berghammer 
976e7708688STamas Berghammer   if (!emulator_ap->ReadInstruction())
97797206d57SZachary Turner     return Status("Read instruction failed!");
978e7708688STamas Berghammer 
979b9c1b51eSKate Stone   bool emulation_result =
980b9c1b51eSKate Stone       emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
9816648fcc3SPavel Labath 
982d37349f3SPavel Labath   const RegisterInfo *reg_info_pc = register_context.GetRegisterInfo(
983b9c1b51eSKate Stone       eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
984d37349f3SPavel Labath   const RegisterInfo *reg_info_flags = register_context.GetRegisterInfo(
985b9c1b51eSKate Stone       eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
9866648fcc3SPavel Labath 
987b9c1b51eSKate Stone   auto pc_it =
988b9c1b51eSKate Stone       baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
989b9c1b51eSKate Stone   auto flags_it =
990b9c1b51eSKate Stone       baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
9916648fcc3SPavel Labath 
992e7708688STamas Berghammer   lldb::addr_t next_pc;
993e7708688STamas Berghammer   lldb::addr_t next_flags;
994b9c1b51eSKate Stone   if (emulation_result) {
995b9c1b51eSKate Stone     assert(pc_it != baton.m_register_values.end() &&
996b9c1b51eSKate Stone            "Emulation was successfull but PC wasn't updated");
9976648fcc3SPavel Labath     next_pc = pc_it->second.GetAsUInt64();
9986648fcc3SPavel Labath 
9996648fcc3SPavel Labath     if (flags_it != baton.m_register_values.end())
10006648fcc3SPavel Labath       next_flags = flags_it->second.GetAsUInt64();
1001e7708688STamas Berghammer     else
1002d37349f3SPavel Labath       next_flags = ReadFlags(register_context);
1003b9c1b51eSKate Stone   } else if (pc_it == baton.m_register_values.end()) {
1004e7708688STamas Berghammer     // Emulate instruction failed and it haven't changed PC. Advance PC
1005e7708688STamas Berghammer     // with the size of the current opcode because the emulation of all
1006e7708688STamas Berghammer     // PC modifying instruction should be successful. The failure most
1007e7708688STamas Berghammer     // likely caused by a not supported instruction which don't modify PC.
1008d37349f3SPavel Labath     next_pc = register_context.GetPC() + emulator_ap->GetOpcode().GetByteSize();
1009d37349f3SPavel Labath     next_flags = ReadFlags(register_context);
1010b9c1b51eSKate Stone   } else {
1011e7708688STamas Berghammer     // The instruction emulation failed after it modified the PC. It is an
1012e7708688STamas Berghammer     // unknown error where we can't continue because the next instruction is
1013e7708688STamas Berghammer     // modifying the PC but we don't  know how.
101497206d57SZachary Turner     return Status("Instruction emulation failed unexpectedly.");
1015e7708688STamas Berghammer   }
1016e7708688STamas Berghammer 
1017b9c1b51eSKate Stone   if (m_arch.GetMachine() == llvm::Triple::arm) {
1018b9c1b51eSKate Stone     if (next_flags & 0x20) {
1019e7708688STamas Berghammer       // Thumb mode
1020e7708688STamas Berghammer       error = SetSoftwareBreakpoint(next_pc, 2);
1021b9c1b51eSKate Stone     } else {
1022e7708688STamas Berghammer       // Arm mode
1023e7708688STamas Berghammer       error = SetSoftwareBreakpoint(next_pc, 4);
1024e7708688STamas Berghammer     }
1025b9c1b51eSKate Stone   } else if (m_arch.GetMachine() == llvm::Triple::mips64 ||
1026b9c1b51eSKate Stone              m_arch.GetMachine() == llvm::Triple::mips64el ||
1027b9c1b51eSKate Stone              m_arch.GetMachine() == llvm::Triple::mips ||
1028aae0a752SEugene Zemtsov              m_arch.GetMachine() == llvm::Triple::mipsel ||
1029aae0a752SEugene Zemtsov              m_arch.GetMachine() == llvm::Triple::ppc64le)
1030cdc22a88SMohit K. Bhakkad     error = SetSoftwareBreakpoint(next_pc, 4);
1031b9c1b51eSKate Stone   else {
1032e7708688STamas Berghammer     // No size hint is given for the next breakpoint
1033e7708688STamas Berghammer     error = SetSoftwareBreakpoint(next_pc, 0);
1034e7708688STamas Berghammer   }
1035e7708688STamas Berghammer 
103642eb6908SPavel Labath   // If setting the breakpoint fails because next_pc is out of
103742eb6908SPavel Labath   // the address space, ignore it and let the debugee segfault.
103842eb6908SPavel Labath   if (error.GetError() == EIO || error.GetError() == EFAULT) {
103997206d57SZachary Turner     return Status();
104042eb6908SPavel Labath   } else if (error.Fail())
1041e7708688STamas Berghammer     return error;
1042e7708688STamas Berghammer 
1043b9cc0c75SPavel Labath   m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
1044e7708688STamas Berghammer 
104597206d57SZachary Turner   return Status();
1046e7708688STamas Berghammer }
1047e7708688STamas Berghammer 
1048b9c1b51eSKate Stone bool NativeProcessLinux::SupportHardwareSingleStepping() const {
1049b9c1b51eSKate Stone   if (m_arch.GetMachine() == llvm::Triple::arm ||
1050b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mips64 ||
1051b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mips64el ||
1052b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mips ||
1053b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mipsel)
1054cdc22a88SMohit K. Bhakkad     return false;
1055cdc22a88SMohit K. Bhakkad   return true;
1056e7708688STamas Berghammer }
1057e7708688STamas Berghammer 
105897206d57SZachary Turner Status NativeProcessLinux::Resume(const ResumeActionList &resume_actions) {
1059a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1060a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0}", GetID());
1061af245d11STodd Fiala 
1062e7708688STamas Berghammer   bool software_single_step = !SupportHardwareSingleStepping();
1063af245d11STodd Fiala 
1064b9c1b51eSKate Stone   if (software_single_step) {
1065a5be48b3SPavel Labath     for (const auto &thread : m_threads) {
1066a5be48b3SPavel Labath       assert(thread && "thread list should not contain NULL threads");
1067e7708688STamas Berghammer 
1068b9c1b51eSKate Stone       const ResumeAction *const action =
1069a5be48b3SPavel Labath           resume_actions.GetActionForThread(thread->GetID(), true);
1070e7708688STamas Berghammer       if (action == nullptr)
1071e7708688STamas Berghammer         continue;
1072e7708688STamas Berghammer 
1073b9c1b51eSKate Stone       if (action->state == eStateStepping) {
107497206d57SZachary Turner         Status error = SetupSoftwareSingleStepping(
1075a5be48b3SPavel Labath             static_cast<NativeThreadLinux &>(*thread));
1076e7708688STamas Berghammer         if (error.Fail())
1077e7708688STamas Berghammer           return error;
1078e7708688STamas Berghammer       }
1079e7708688STamas Berghammer     }
1080e7708688STamas Berghammer   }
1081e7708688STamas Berghammer 
1082a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
1083a5be48b3SPavel Labath     assert(thread && "thread list should not contain NULL threads");
1084af245d11STodd Fiala 
1085b9c1b51eSKate Stone     const ResumeAction *const action =
1086a5be48b3SPavel Labath         resume_actions.GetActionForThread(thread->GetID(), true);
10876a196ce6SChaoren Lin 
1088b9c1b51eSKate Stone     if (action == nullptr) {
1089a6321a8eSPavel Labath       LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
1090a5be48b3SPavel Labath                thread->GetID());
10916a196ce6SChaoren Lin       continue;
10926a196ce6SChaoren Lin     }
1093af245d11STodd Fiala 
1094a6321a8eSPavel Labath     LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}",
1095a5be48b3SPavel Labath              action->state, GetID(), thread->GetID());
1096af245d11STodd Fiala 
1097b9c1b51eSKate Stone     switch (action->state) {
1098af245d11STodd Fiala     case eStateRunning:
1099b9c1b51eSKate Stone     case eStateStepping: {
1100af245d11STodd Fiala       // Run the thread, possibly feeding it the signal.
1101fa03ad2eSChaoren Lin       const int signo = action->signal;
1102a5be48b3SPavel Labath       ResumeThread(static_cast<NativeThreadLinux &>(*thread), action->state,
1103b9c1b51eSKate Stone                    signo);
1104af245d11STodd Fiala       break;
1105ae29d395SChaoren Lin     }
1106af245d11STodd Fiala 
1107af245d11STodd Fiala     case eStateSuspended:
1108af245d11STodd Fiala     case eStateStopped:
1109a6321a8eSPavel Labath       llvm_unreachable("Unexpected state");
1110af245d11STodd Fiala 
1111af245d11STodd Fiala     default:
111297206d57SZachary Turner       return Status("NativeProcessLinux::%s (): unexpected state %s specified "
1113b9c1b51eSKate Stone                     "for pid %" PRIu64 ", tid %" PRIu64,
1114b9c1b51eSKate Stone                     __FUNCTION__, StateAsCString(action->state), GetID(),
1115a5be48b3SPavel Labath                     thread->GetID());
1116af245d11STodd Fiala     }
1117af245d11STodd Fiala   }
1118af245d11STodd Fiala 
111997206d57SZachary Turner   return Status();
1120af245d11STodd Fiala }
1121af245d11STodd Fiala 
112297206d57SZachary Turner Status NativeProcessLinux::Halt() {
112397206d57SZachary Turner   Status error;
1124af245d11STodd Fiala 
1125af245d11STodd Fiala   if (kill(GetID(), SIGSTOP) != 0)
1126af245d11STodd Fiala     error.SetErrorToErrno();
1127af245d11STodd Fiala 
1128af245d11STodd Fiala   return error;
1129af245d11STodd Fiala }
1130af245d11STodd Fiala 
113197206d57SZachary Turner Status NativeProcessLinux::Detach() {
113297206d57SZachary Turner   Status error;
1133af245d11STodd Fiala 
1134af245d11STodd Fiala   // Stop monitoring the inferior.
113519cbe96aSPavel Labath   m_sigchld_handle.reset();
1136af245d11STodd Fiala 
11377a9495bcSPavel Labath   // Tell ptrace to detach from the process.
11387a9495bcSPavel Labath   if (GetID() == LLDB_INVALID_PROCESS_ID)
11397a9495bcSPavel Labath     return error;
11407a9495bcSPavel Labath 
1141a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
1142a5be48b3SPavel Labath     Status e = Detach(thread->GetID());
11437a9495bcSPavel Labath     if (e.Fail())
1144b9c1b51eSKate Stone       error =
1145b9c1b51eSKate Stone           e; // Save the error, but still attempt to detach from other threads.
11467a9495bcSPavel Labath   }
11477a9495bcSPavel Labath 
114899e37695SRavitheja Addepally   m_processor_trace_monitor.clear();
114999e37695SRavitheja Addepally   m_pt_proces_trace_id = LLDB_INVALID_UID;
115099e37695SRavitheja Addepally 
1151af245d11STodd Fiala   return error;
1152af245d11STodd Fiala }
1153af245d11STodd Fiala 
115497206d57SZachary Turner Status NativeProcessLinux::Signal(int signo) {
115597206d57SZachary Turner   Status error;
1156af245d11STodd Fiala 
1157a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1158a6321a8eSPavel Labath   LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo,
1159a6321a8eSPavel Labath            Host::GetSignalAsCString(signo), GetID());
1160af245d11STodd Fiala 
1161af245d11STodd Fiala   if (kill(GetID(), signo))
1162af245d11STodd Fiala     error.SetErrorToErrno();
1163af245d11STodd Fiala 
1164af245d11STodd Fiala   return error;
1165af245d11STodd Fiala }
1166af245d11STodd Fiala 
116797206d57SZachary Turner Status NativeProcessLinux::Interrupt() {
1168e9547b80SChaoren Lin   // Pick a running thread (or if none, a not-dead stopped thread) as
1169e9547b80SChaoren Lin   // the chosen thread that will be the stop-reason thread.
1170a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1171e9547b80SChaoren Lin 
1172a5be48b3SPavel Labath   NativeThreadProtocol *running_thread = nullptr;
1173a5be48b3SPavel Labath   NativeThreadProtocol *stopped_thread = nullptr;
1174e9547b80SChaoren Lin 
1175a6321a8eSPavel Labath   LLDB_LOG(log, "selecting running thread for interrupt target");
1176a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
1177e9547b80SChaoren Lin     // If we have a running or stepping thread, we'll call that the
1178e9547b80SChaoren Lin     // target of the interrupt.
1179a5be48b3SPavel Labath     const auto thread_state = thread->GetState();
1180b9c1b51eSKate Stone     if (thread_state == eStateRunning || thread_state == eStateStepping) {
1181a5be48b3SPavel Labath       running_thread = thread.get();
1182e9547b80SChaoren Lin       break;
1183a5be48b3SPavel Labath     } else if (!stopped_thread && StateIsStoppedState(thread_state, true)) {
1184b9c1b51eSKate Stone       // Remember the first non-dead stopped thread.  We'll use that as a backup
1185b9c1b51eSKate Stone       // if there are no running threads.
1186a5be48b3SPavel Labath       stopped_thread = thread.get();
1187e9547b80SChaoren Lin     }
1188e9547b80SChaoren Lin   }
1189e9547b80SChaoren Lin 
1190a5be48b3SPavel Labath   if (!running_thread && !stopped_thread) {
119197206d57SZachary Turner     Status error("found no running/stepping or live stopped threads as target "
1192b9c1b51eSKate Stone                  "for interrupt");
1193a6321a8eSPavel Labath     LLDB_LOG(log, "skipping due to error: {0}", error);
11945830aa75STamas Berghammer 
1195e9547b80SChaoren Lin     return error;
1196e9547b80SChaoren Lin   }
1197e9547b80SChaoren Lin 
1198a5be48b3SPavel Labath   NativeThreadProtocol *deferred_signal_thread =
1199a5be48b3SPavel Labath       running_thread ? running_thread : stopped_thread;
1200e9547b80SChaoren Lin 
1201a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(),
1202a5be48b3SPavel Labath            running_thread ? "running" : "stopped",
1203a5be48b3SPavel Labath            deferred_signal_thread->GetID());
1204e9547b80SChaoren Lin 
1205a5be48b3SPavel Labath   StopRunningThreads(deferred_signal_thread->GetID());
120645f5cb31SPavel Labath 
120797206d57SZachary Turner   return Status();
1208e9547b80SChaoren Lin }
1209e9547b80SChaoren Lin 
121097206d57SZachary Turner Status NativeProcessLinux::Kill() {
1211a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1212a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0}", GetID());
1213af245d11STodd Fiala 
121497206d57SZachary Turner   Status error;
1215af245d11STodd Fiala 
1216b9c1b51eSKate Stone   switch (m_state) {
1217af245d11STodd Fiala   case StateType::eStateInvalid:
1218af245d11STodd Fiala   case StateType::eStateExited:
1219af245d11STodd Fiala   case StateType::eStateCrashed:
1220af245d11STodd Fiala   case StateType::eStateDetached:
1221af245d11STodd Fiala   case StateType::eStateUnloaded:
1222af245d11STodd Fiala     // Nothing to do - the process is already dead.
1223a6321a8eSPavel Labath     LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
12248198db30SPavel Labath              m_state);
1225af245d11STodd Fiala     return error;
1226af245d11STodd Fiala 
1227af245d11STodd Fiala   case StateType::eStateConnected:
1228af245d11STodd Fiala   case StateType::eStateAttaching:
1229af245d11STodd Fiala   case StateType::eStateLaunching:
1230af245d11STodd Fiala   case StateType::eStateStopped:
1231af245d11STodd Fiala   case StateType::eStateRunning:
1232af245d11STodd Fiala   case StateType::eStateStepping:
1233af245d11STodd Fiala   case StateType::eStateSuspended:
1234af245d11STodd Fiala     // We can try to kill a process in these states.
1235af245d11STodd Fiala     break;
1236af245d11STodd Fiala   }
1237af245d11STodd Fiala 
1238b9c1b51eSKate Stone   if (kill(GetID(), SIGKILL) != 0) {
1239af245d11STodd Fiala     error.SetErrorToErrno();
1240af245d11STodd Fiala     return error;
1241af245d11STodd Fiala   }
1242af245d11STodd Fiala 
1243af245d11STodd Fiala   return error;
1244af245d11STodd Fiala }
1245af245d11STodd Fiala 
124697206d57SZachary Turner static Status
124715930862SPavel Labath ParseMemoryRegionInfoFromProcMapsLine(llvm::StringRef &maps_line,
1248b9c1b51eSKate Stone                                       MemoryRegionInfo &memory_region_info) {
1249af245d11STodd Fiala   memory_region_info.Clear();
1250af245d11STodd Fiala 
125115930862SPavel Labath   StringExtractor line_extractor(maps_line);
1252af245d11STodd Fiala 
1253b9c1b51eSKate Stone   // Format: {address_start_hex}-{address_end_hex} perms offset  dev   inode
1254b9c1b51eSKate Stone   // pathname
1255b9c1b51eSKate Stone   // perms: rwxp   (letter is present if set, '-' if not, final character is
1256b9c1b51eSKate Stone   // p=private, s=shared).
1257af245d11STodd Fiala 
1258af245d11STodd Fiala   // Parse out the starting address
1259af245d11STodd Fiala   lldb::addr_t start_address = line_extractor.GetHexMaxU64(false, 0);
1260af245d11STodd Fiala 
1261af245d11STodd Fiala   // Parse out hyphen separating start and end address from range.
1262af245d11STodd Fiala   if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != '-'))
126397206d57SZachary Turner     return Status(
1264b9c1b51eSKate Stone         "malformed /proc/{pid}/maps entry, missing dash between address range");
1265af245d11STodd Fiala 
1266af245d11STodd Fiala   // Parse out the ending address
1267af245d11STodd Fiala   lldb::addr_t end_address = line_extractor.GetHexMaxU64(false, start_address);
1268af245d11STodd Fiala 
1269af245d11STodd Fiala   // Parse out the space after the address.
1270af245d11STodd Fiala   if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != ' '))
127197206d57SZachary Turner     return Status(
127297206d57SZachary Turner         "malformed /proc/{pid}/maps entry, missing space after range");
1273af245d11STodd Fiala 
1274af245d11STodd Fiala   // Save the range.
1275af245d11STodd Fiala   memory_region_info.GetRange().SetRangeBase(start_address);
1276af245d11STodd Fiala   memory_region_info.GetRange().SetRangeEnd(end_address);
1277af245d11STodd Fiala 
1278b9c1b51eSKate Stone   // Any memory region in /proc/{pid}/maps is by definition mapped into the
1279b9c1b51eSKate Stone   // process.
1280ad007563SHoward Hellyer   memory_region_info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
1281ad007563SHoward Hellyer 
1282af245d11STodd Fiala   // Parse out each permission entry.
1283af245d11STodd Fiala   if (line_extractor.GetBytesLeft() < 4)
128497206d57SZachary Turner     return Status("malformed /proc/{pid}/maps entry, missing some portion of "
1285b9c1b51eSKate Stone                   "permissions");
1286af245d11STodd Fiala 
1287af245d11STodd Fiala   // Handle read permission.
1288af245d11STodd Fiala   const char read_perm_char = line_extractor.GetChar();
1289af245d11STodd Fiala   if (read_perm_char == 'r')
1290af245d11STodd Fiala     memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eYes);
1291c73301bbSTamas Berghammer   else if (read_perm_char == '-')
1292af245d11STodd Fiala     memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1293c73301bbSTamas Berghammer   else
129497206d57SZachary Turner     return Status("unexpected /proc/{pid}/maps read permission char");
1295af245d11STodd Fiala 
1296af245d11STodd Fiala   // Handle write permission.
1297af245d11STodd Fiala   const char write_perm_char = line_extractor.GetChar();
1298af245d11STodd Fiala   if (write_perm_char == 'w')
1299af245d11STodd Fiala     memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eYes);
1300c73301bbSTamas Berghammer   else if (write_perm_char == '-')
1301af245d11STodd Fiala     memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1302c73301bbSTamas Berghammer   else
130397206d57SZachary Turner     return Status("unexpected /proc/{pid}/maps write permission char");
1304af245d11STodd Fiala 
1305af245d11STodd Fiala   // Handle execute permission.
1306af245d11STodd Fiala   const char exec_perm_char = line_extractor.GetChar();
1307af245d11STodd Fiala   if (exec_perm_char == 'x')
1308af245d11STodd Fiala     memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes);
1309c73301bbSTamas Berghammer   else if (exec_perm_char == '-')
1310af245d11STodd Fiala     memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1311c73301bbSTamas Berghammer   else
131297206d57SZachary Turner     return Status("unexpected /proc/{pid}/maps exec permission char");
1313af245d11STodd Fiala 
1314d7d69f80STamas Berghammer   line_extractor.GetChar();              // Read the private bit
1315d7d69f80STamas Berghammer   line_extractor.SkipSpaces();           // Skip the separator
1316d7d69f80STamas Berghammer   line_extractor.GetHexMaxU64(false, 0); // Read the offset
1317d7d69f80STamas Berghammer   line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1318d7d69f80STamas Berghammer   line_extractor.GetChar();              // Read the device id separator
1319d7d69f80STamas Berghammer   line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1320d7d69f80STamas Berghammer   line_extractor.SkipSpaces();           // Skip the separator
1321d7d69f80STamas Berghammer   line_extractor.GetU64(0, 10);          // Read the inode number
1322d7d69f80STamas Berghammer 
1323d7d69f80STamas Berghammer   line_extractor.SkipSpaces();
1324b9739d40SPavel Labath   const char *name = line_extractor.Peek();
1325b9739d40SPavel Labath   if (name)
1326b9739d40SPavel Labath     memory_region_info.SetName(name);
1327d7d69f80STamas Berghammer 
132897206d57SZachary Turner   return Status();
1329af245d11STodd Fiala }
1330af245d11STodd Fiala 
133197206d57SZachary Turner Status NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr,
1332b9c1b51eSKate Stone                                                MemoryRegionInfo &range_info) {
1333b9c1b51eSKate Stone   // FIXME review that the final memory region returned extends to the end of
1334b9c1b51eSKate Stone   // the virtual address space,
1335af245d11STodd Fiala   // with no perms if it is not mapped.
1336af245d11STodd Fiala 
1337af245d11STodd Fiala   // Use an approach that reads memory regions from /proc/{pid}/maps.
1338af245d11STodd Fiala   // Assume proc maps entries are in ascending order.
1339af245d11STodd Fiala   // FIXME assert if we find differently.
1340af245d11STodd Fiala 
1341b9c1b51eSKate Stone   if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
1342af245d11STodd Fiala     // We're done.
134397206d57SZachary Turner     return Status("unsupported");
1344af245d11STodd Fiala   }
1345af245d11STodd Fiala 
134697206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
1347b9c1b51eSKate Stone   if (error.Fail()) {
1348af245d11STodd Fiala     return error;
1349af245d11STodd Fiala   }
1350af245d11STodd Fiala 
1351af245d11STodd Fiala   lldb::addr_t prev_base_address = 0;
1352af245d11STodd Fiala 
1353b9c1b51eSKate Stone   // FIXME start by finding the last region that is <= target address using
1354b9c1b51eSKate Stone   // binary search.  Data is sorted.
1355af245d11STodd Fiala   // There can be a ton of regions on pthreads apps with lots of threads.
1356b9c1b51eSKate Stone   for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1357b9c1b51eSKate Stone        ++it) {
1358a6f5795aSTamas Berghammer     MemoryRegionInfo &proc_entry_info = it->first;
1359af245d11STodd Fiala 
1360af245d11STodd Fiala     // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1361b9c1b51eSKate Stone     assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
1362b9c1b51eSKate Stone            "descending /proc/pid/maps entries detected, unexpected");
1363af245d11STodd Fiala     prev_base_address = proc_entry_info.GetRange().GetRangeBase();
1364b1554311SHafiz Abid Qadeer     UNUSED_IF_ASSERT_DISABLED(prev_base_address);
1365af245d11STodd Fiala 
1366b9c1b51eSKate Stone     // If the target address comes before this entry, indicate distance to next
1367b9c1b51eSKate Stone     // region.
1368b9c1b51eSKate Stone     if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1369af245d11STodd Fiala       range_info.GetRange().SetRangeBase(load_addr);
1370b9c1b51eSKate Stone       range_info.GetRange().SetByteSize(
1371b9c1b51eSKate Stone           proc_entry_info.GetRange().GetRangeBase() - load_addr);
1372af245d11STodd Fiala       range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1373af245d11STodd Fiala       range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1374af245d11STodd Fiala       range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1375ad007563SHoward Hellyer       range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1376af245d11STodd Fiala 
1377af245d11STodd Fiala       return error;
1378b9c1b51eSKate Stone     } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1379af245d11STodd Fiala       // The target address is within the memory region we're processing here.
1380af245d11STodd Fiala       range_info = proc_entry_info;
1381af245d11STodd Fiala       return error;
1382af245d11STodd Fiala     }
1383af245d11STodd Fiala 
1384b9c1b51eSKate Stone     // The target memory address comes somewhere after the region we just
1385b9c1b51eSKate Stone     // parsed.
1386af245d11STodd Fiala   }
1387af245d11STodd Fiala 
1388b9c1b51eSKate Stone   // If we made it here, we didn't find an entry that contained the given
1389b9c1b51eSKate Stone   // address. Return the
1390b9c1b51eSKate Stone   // load_addr as start and the amount of bytes betwwen load address and the end
1391b9c1b51eSKate Stone   // of the memory as
139209839c33STamas Berghammer   // size.
139309839c33STamas Berghammer   range_info.GetRange().SetRangeBase(load_addr);
1394ad007563SHoward Hellyer   range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
139509839c33STamas Berghammer   range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
139609839c33STamas Berghammer   range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
139709839c33STamas Berghammer   range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1398ad007563SHoward Hellyer   range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1399af245d11STodd Fiala   return error;
1400af245d11STodd Fiala }
1401af245d11STodd Fiala 
140297206d57SZachary Turner Status NativeProcessLinux::PopulateMemoryRegionCache() {
1403a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1404a6f5795aSTamas Berghammer 
1405a6f5795aSTamas Berghammer   // If our cache is empty, pull the latest.  There should always be at least
1406a6f5795aSTamas Berghammer   // one memory region if memory region handling is supported.
1407a6f5795aSTamas Berghammer   if (!m_mem_region_cache.empty()) {
1408a6321a8eSPavel Labath     LLDB_LOG(log, "reusing {0} cached memory region entries",
1409a6321a8eSPavel Labath              m_mem_region_cache.size());
141097206d57SZachary Turner     return Status();
1411a6f5795aSTamas Berghammer   }
1412a6f5795aSTamas Berghammer 
141315930862SPavel Labath   auto BufferOrError = getProcFile(GetID(), "maps");
141415930862SPavel Labath   if (!BufferOrError) {
141515930862SPavel Labath     m_supports_mem_region = LazyBool::eLazyBoolNo;
141615930862SPavel Labath     return BufferOrError.getError();
141715930862SPavel Labath   }
141815930862SPavel Labath   StringRef Rest = BufferOrError.get()->getBuffer();
141915930862SPavel Labath   while (! Rest.empty()) {
142015930862SPavel Labath     StringRef Line;
142115930862SPavel Labath     std::tie(Line, Rest) = Rest.split('\n');
1422a6f5795aSTamas Berghammer     MemoryRegionInfo info;
142397206d57SZachary Turner     const Status parse_error =
142497206d57SZachary Turner         ParseMemoryRegionInfoFromProcMapsLine(Line, info);
142515930862SPavel Labath     if (parse_error.Fail()) {
142615930862SPavel Labath       LLDB_LOG(log, "failed to parse proc maps line '{0}': {1}", Line,
142715930862SPavel Labath                parse_error);
142815930862SPavel Labath       m_supports_mem_region = LazyBool::eLazyBoolNo;
142915930862SPavel Labath       return parse_error;
143015930862SPavel Labath     }
1431a6f5795aSTamas Berghammer     m_mem_region_cache.emplace_back(
1432a6f5795aSTamas Berghammer         info, FileSpec(info.GetName().GetCString(), true));
1433a6f5795aSTamas Berghammer   }
1434a6f5795aSTamas Berghammer 
143515930862SPavel Labath   if (m_mem_region_cache.empty()) {
1436a6f5795aSTamas Berghammer     // No entries after attempting to read them.  This shouldn't happen if
1437a6f5795aSTamas Berghammer     // /proc/{pid}/maps is supported. Assume we don't support map entries
1438a6f5795aSTamas Berghammer     // via procfs.
143915930862SPavel Labath     m_supports_mem_region = LazyBool::eLazyBoolNo;
1440a6321a8eSPavel Labath     LLDB_LOG(log,
1441a6321a8eSPavel Labath              "failed to find any procfs maps entries, assuming no support "
1442a6321a8eSPavel Labath              "for memory region metadata retrieval");
144397206d57SZachary Turner     return Status("not supported");
1444a6f5795aSTamas Berghammer   }
1445a6f5795aSTamas Berghammer 
1446a6321a8eSPavel Labath   LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps",
1447a6321a8eSPavel Labath            m_mem_region_cache.size(), GetID());
1448a6f5795aSTamas Berghammer 
1449a6f5795aSTamas Berghammer   // We support memory retrieval, remember that.
1450a6f5795aSTamas Berghammer   m_supports_mem_region = LazyBool::eLazyBoolYes;
145197206d57SZachary Turner   return Status();
1452a6f5795aSTamas Berghammer }
1453a6f5795aSTamas Berghammer 
1454b9c1b51eSKate Stone void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
1455a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1456a6321a8eSPavel Labath   LLDB_LOG(log, "newBumpId={0}", newBumpId);
1457a6321a8eSPavel Labath   LLDB_LOG(log, "clearing {0} entries from memory region cache",
1458a6321a8eSPavel Labath            m_mem_region_cache.size());
1459af245d11STodd Fiala   m_mem_region_cache.clear();
1460af245d11STodd Fiala }
1461af245d11STodd Fiala 
146297206d57SZachary Turner Status NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions,
1463b9c1b51eSKate Stone                                           lldb::addr_t &addr) {
1464af245d11STodd Fiala // FIXME implementing this requires the equivalent of
1465af245d11STodd Fiala // InferiorCallPOSIX::InferiorCallMmap, which depends on
1466af245d11STodd Fiala // functional ThreadPlans working with Native*Protocol.
1467af245d11STodd Fiala #if 1
146897206d57SZachary Turner   return Status("not implemented yet");
1469af245d11STodd Fiala #else
1470af245d11STodd Fiala   addr = LLDB_INVALID_ADDRESS;
1471af245d11STodd Fiala 
1472af245d11STodd Fiala   unsigned prot = 0;
1473af245d11STodd Fiala   if (permissions & lldb::ePermissionsReadable)
1474af245d11STodd Fiala     prot |= eMmapProtRead;
1475af245d11STodd Fiala   if (permissions & lldb::ePermissionsWritable)
1476af245d11STodd Fiala     prot |= eMmapProtWrite;
1477af245d11STodd Fiala   if (permissions & lldb::ePermissionsExecutable)
1478af245d11STodd Fiala     prot |= eMmapProtExec;
1479af245d11STodd Fiala 
1480af245d11STodd Fiala   // TODO implement this directly in NativeProcessLinux
1481af245d11STodd Fiala   // (and lift to NativeProcessPOSIX if/when that class is
1482af245d11STodd Fiala   // refactored out).
1483af245d11STodd Fiala   if (InferiorCallMmap(this, addr, 0, size, prot,
1484af245d11STodd Fiala                        eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
1485af245d11STodd Fiala     m_addr_to_mmap_size[addr] = size;
148697206d57SZachary Turner     return Status();
1487af245d11STodd Fiala   } else {
1488af245d11STodd Fiala     addr = LLDB_INVALID_ADDRESS;
148997206d57SZachary Turner     return Status("unable to allocate %" PRIu64
1490b9c1b51eSKate Stone                   " bytes of memory with permissions %s",
1491b9c1b51eSKate Stone                   size, GetPermissionsAsCString(permissions));
1492af245d11STodd Fiala   }
1493af245d11STodd Fiala #endif
1494af245d11STodd Fiala }
1495af245d11STodd Fiala 
149697206d57SZachary Turner Status NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {
1497af245d11STodd Fiala   // FIXME see comments in AllocateMemory - required lower-level
1498af245d11STodd Fiala   // bits not in place yet (ThreadPlans)
149997206d57SZachary Turner   return Status("not implemented");
1500af245d11STodd Fiala }
1501af245d11STodd Fiala 
1502b9c1b51eSKate Stone lldb::addr_t NativeProcessLinux::GetSharedLibraryInfoAddress() {
1503af245d11STodd Fiala   // punt on this for now
1504af245d11STodd Fiala   return LLDB_INVALID_ADDRESS;
1505af245d11STodd Fiala }
1506af245d11STodd Fiala 
1507b9c1b51eSKate Stone size_t NativeProcessLinux::UpdateThreads() {
1508af245d11STodd Fiala   // The NativeProcessLinux monitoring threads are always up to date
1509af245d11STodd Fiala   // with respect to thread state and they keep the thread list
1510af245d11STodd Fiala   // populated properly. All this method needs to do is return the
1511af245d11STodd Fiala   // thread count.
1512af245d11STodd Fiala   return m_threads.size();
1513af245d11STodd Fiala }
1514af245d11STodd Fiala 
151597206d57SZachary Turner Status NativeProcessLinux::GetSoftwareBreakpointPCOffset(
1516b9c1b51eSKate Stone     uint32_t &actual_opcode_size) {
1517af245d11STodd Fiala   // FIXME put this behind a breakpoint protocol class that can be
1518af245d11STodd Fiala   // set per architecture.  Need ARM, MIPS support here.
1519af245d11STodd Fiala   static const uint8_t g_i386_opcode[] = {0xCC};
1520bb00d0b6SUlrich Weigand   static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
1521af245d11STodd Fiala 
1522b9c1b51eSKate Stone   switch (m_arch.GetMachine()) {
1523af245d11STodd Fiala   case llvm::Triple::x86:
1524af245d11STodd Fiala   case llvm::Triple::x86_64:
1525af245d11STodd Fiala     actual_opcode_size = static_cast<uint32_t>(sizeof(g_i386_opcode));
152697206d57SZachary Turner     return Status();
1527af245d11STodd Fiala 
1528bb00d0b6SUlrich Weigand   case llvm::Triple::systemz:
1529bb00d0b6SUlrich Weigand     actual_opcode_size = static_cast<uint32_t>(sizeof(g_s390x_opcode));
153097206d57SZachary Turner     return Status();
1531bb00d0b6SUlrich Weigand 
1532ff7fd900STamas Berghammer   case llvm::Triple::arm:
1533ff7fd900STamas Berghammer   case llvm::Triple::aarch64:
1534e8659b5dSMohit K. Bhakkad   case llvm::Triple::mips64:
1535e8659b5dSMohit K. Bhakkad   case llvm::Triple::mips64el:
1536ce815e45SSagar Thakur   case llvm::Triple::mips:
1537ce815e45SSagar Thakur   case llvm::Triple::mipsel:
1538*a3952ea7SPavel Labath   case llvm::Triple::ppc64le:
1539ff7fd900STamas Berghammer     // On these architectures the PC don't get updated for breakpoint hits
1540c60c9452SJaydeep Patil     actual_opcode_size = 0;
154197206d57SZachary Turner     return Status();
1542e8659b5dSMohit K. Bhakkad 
1543af245d11STodd Fiala   default:
1544af245d11STodd Fiala     assert(false && "CPU type not supported!");
154597206d57SZachary Turner     return Status("CPU type not supported");
1546af245d11STodd Fiala   }
1547af245d11STodd Fiala }
1548af245d11STodd Fiala 
154997206d57SZachary Turner Status NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,
1550b9c1b51eSKate Stone                                          bool hardware) {
1551af245d11STodd Fiala   if (hardware)
1552d5ffbad2SOmair Javaid     return SetHardwareBreakpoint(addr, size);
1553af245d11STodd Fiala   else
1554af245d11STodd Fiala     return SetSoftwareBreakpoint(addr, size);
1555af245d11STodd Fiala }
1556af245d11STodd Fiala 
155797206d57SZachary Turner Status NativeProcessLinux::RemoveBreakpoint(lldb::addr_t addr, bool hardware) {
1558d5ffbad2SOmair Javaid   if (hardware)
1559d5ffbad2SOmair Javaid     return RemoveHardwareBreakpoint(addr);
1560d5ffbad2SOmair Javaid   else
1561d5ffbad2SOmair Javaid     return NativeProcessProtocol::RemoveBreakpoint(addr);
1562d5ffbad2SOmair Javaid }
1563d5ffbad2SOmair Javaid 
156497206d57SZachary Turner Status NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(
1565b9c1b51eSKate Stone     size_t trap_opcode_size_hint, size_t &actual_opcode_size,
1566b9c1b51eSKate Stone     const uint8_t *&trap_opcode_bytes) {
156763c8be95STamas Berghammer   // FIXME put this behind a breakpoint protocol class that can be set per
156863c8be95STamas Berghammer   // architecture.  Need MIPS support here.
15692afc5966STodd Fiala   static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};
1570be379e15STamas Berghammer   // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1571be379e15STamas Berghammer   // linux kernel does otherwise.
1572be379e15STamas Berghammer   static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1573af245d11STodd Fiala   static const uint8_t g_i386_opcode[] = {0xCC};
15743df471c3SMohit K. Bhakkad   static const uint8_t g_mips64_opcode[] = {0x00, 0x00, 0x00, 0x0d};
15752c2acf96SMohit K. Bhakkad   static const uint8_t g_mips64el_opcode[] = {0x0d, 0x00, 0x00, 0x00};
1576bb00d0b6SUlrich Weigand   static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
1577be379e15STamas Berghammer   static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
1578aae0a752SEugene Zemtsov   static const uint8_t g_ppc64le_opcode[] = {0x08, 0x00, 0xe0, 0x7f}; // trap
1579af245d11STodd Fiala 
1580b9c1b51eSKate Stone   switch (m_arch.GetMachine()) {
15812afc5966STodd Fiala   case llvm::Triple::aarch64:
15822afc5966STodd Fiala     trap_opcode_bytes = g_aarch64_opcode;
15832afc5966STodd Fiala     actual_opcode_size = sizeof(g_aarch64_opcode);
158497206d57SZachary Turner     return Status();
15852afc5966STodd Fiala 
158663c8be95STamas Berghammer   case llvm::Triple::arm:
1587b9c1b51eSKate Stone     switch (trap_opcode_size_hint) {
158863c8be95STamas Berghammer     case 2:
158963c8be95STamas Berghammer       trap_opcode_bytes = g_thumb_breakpoint_opcode;
159063c8be95STamas Berghammer       actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
159197206d57SZachary Turner       return Status();
159263c8be95STamas Berghammer     case 4:
159363c8be95STamas Berghammer       trap_opcode_bytes = g_arm_breakpoint_opcode;
159463c8be95STamas Berghammer       actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
159597206d57SZachary Turner       return Status();
159663c8be95STamas Berghammer     default:
159763c8be95STamas Berghammer       assert(false && "Unrecognised trap opcode size hint!");
159897206d57SZachary Turner       return Status("Unrecognised trap opcode size hint!");
159963c8be95STamas Berghammer     }
160063c8be95STamas Berghammer 
1601af245d11STodd Fiala   case llvm::Triple::x86:
1602af245d11STodd Fiala   case llvm::Triple::x86_64:
1603af245d11STodd Fiala     trap_opcode_bytes = g_i386_opcode;
1604af245d11STodd Fiala     actual_opcode_size = sizeof(g_i386_opcode);
160597206d57SZachary Turner     return Status();
1606af245d11STodd Fiala 
1607ce815e45SSagar Thakur   case llvm::Triple::mips:
16083df471c3SMohit K. Bhakkad   case llvm::Triple::mips64:
16093df471c3SMohit K. Bhakkad     trap_opcode_bytes = g_mips64_opcode;
16103df471c3SMohit K. Bhakkad     actual_opcode_size = sizeof(g_mips64_opcode);
161197206d57SZachary Turner     return Status();
16123df471c3SMohit K. Bhakkad 
1613ce815e45SSagar Thakur   case llvm::Triple::mipsel:
16142c2acf96SMohit K. Bhakkad   case llvm::Triple::mips64el:
16152c2acf96SMohit K. Bhakkad     trap_opcode_bytes = g_mips64el_opcode;
16162c2acf96SMohit K. Bhakkad     actual_opcode_size = sizeof(g_mips64el_opcode);
161797206d57SZachary Turner     return Status();
16182c2acf96SMohit K. Bhakkad 
1619bb00d0b6SUlrich Weigand   case llvm::Triple::systemz:
1620bb00d0b6SUlrich Weigand     trap_opcode_bytes = g_s390x_opcode;
1621bb00d0b6SUlrich Weigand     actual_opcode_size = sizeof(g_s390x_opcode);
162297206d57SZachary Turner     return Status();
1623bb00d0b6SUlrich Weigand 
1624aae0a752SEugene Zemtsov   case llvm::Triple::ppc64le:
1625aae0a752SEugene Zemtsov     trap_opcode_bytes = g_ppc64le_opcode;
1626aae0a752SEugene Zemtsov     actual_opcode_size = sizeof(g_ppc64le_opcode);
1627aae0a752SEugene Zemtsov     return Status();
1628aae0a752SEugene Zemtsov 
1629af245d11STodd Fiala   default:
1630af245d11STodd Fiala     assert(false && "CPU type not supported!");
163197206d57SZachary Turner     return Status("CPU type not supported");
1632af245d11STodd Fiala   }
1633af245d11STodd Fiala }
1634af245d11STodd Fiala 
1635af245d11STodd Fiala #if 0
1636af245d11STodd Fiala ProcessMessage::CrashReason
1637af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
1638af245d11STodd Fiala {
1639af245d11STodd Fiala     ProcessMessage::CrashReason reason;
1640af245d11STodd Fiala     assert(info->si_signo == SIGSEGV);
1641af245d11STodd Fiala 
1642af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
1643af245d11STodd Fiala 
1644af245d11STodd Fiala     switch (info->si_code)
1645af245d11STodd Fiala     {
1646af245d11STodd Fiala     default:
1647af245d11STodd Fiala         assert(false && "unexpected si_code for SIGSEGV");
1648af245d11STodd Fiala         break;
1649af245d11STodd Fiala     case SI_KERNEL:
1650af245d11STodd Fiala         // Linux will occasionally send spurious SI_KERNEL codes.
1651af245d11STodd Fiala         // (this is poorly documented in sigaction)
1652af245d11STodd Fiala         // One way to get this is via unaligned SIMD loads.
1653af245d11STodd Fiala         reason = ProcessMessage::eInvalidAddress; // for lack of anything better
1654af245d11STodd Fiala         break;
1655af245d11STodd Fiala     case SEGV_MAPERR:
1656af245d11STodd Fiala         reason = ProcessMessage::eInvalidAddress;
1657af245d11STodd Fiala         break;
1658af245d11STodd Fiala     case SEGV_ACCERR:
1659af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedAddress;
1660af245d11STodd Fiala         break;
1661af245d11STodd Fiala     }
1662af245d11STodd Fiala 
1663af245d11STodd Fiala     return reason;
1664af245d11STodd Fiala }
1665af245d11STodd Fiala #endif
1666af245d11STodd Fiala 
1667af245d11STodd Fiala #if 0
1668af245d11STodd Fiala ProcessMessage::CrashReason
1669af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
1670af245d11STodd Fiala {
1671af245d11STodd Fiala     ProcessMessage::CrashReason reason;
1672af245d11STodd Fiala     assert(info->si_signo == SIGILL);
1673af245d11STodd Fiala 
1674af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
1675af245d11STodd Fiala 
1676af245d11STodd Fiala     switch (info->si_code)
1677af245d11STodd Fiala     {
1678af245d11STodd Fiala     default:
1679af245d11STodd Fiala         assert(false && "unexpected si_code for SIGILL");
1680af245d11STodd Fiala         break;
1681af245d11STodd Fiala     case ILL_ILLOPC:
1682af245d11STodd Fiala         reason = ProcessMessage::eIllegalOpcode;
1683af245d11STodd Fiala         break;
1684af245d11STodd Fiala     case ILL_ILLOPN:
1685af245d11STodd Fiala         reason = ProcessMessage::eIllegalOperand;
1686af245d11STodd Fiala         break;
1687af245d11STodd Fiala     case ILL_ILLADR:
1688af245d11STodd Fiala         reason = ProcessMessage::eIllegalAddressingMode;
1689af245d11STodd Fiala         break;
1690af245d11STodd Fiala     case ILL_ILLTRP:
1691af245d11STodd Fiala         reason = ProcessMessage::eIllegalTrap;
1692af245d11STodd Fiala         break;
1693af245d11STodd Fiala     case ILL_PRVOPC:
1694af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedOpcode;
1695af245d11STodd Fiala         break;
1696af245d11STodd Fiala     case ILL_PRVREG:
1697af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedRegister;
1698af245d11STodd Fiala         break;
1699af245d11STodd Fiala     case ILL_COPROC:
1700af245d11STodd Fiala         reason = ProcessMessage::eCoprocessorError;
1701af245d11STodd Fiala         break;
1702af245d11STodd Fiala     case ILL_BADSTK:
1703af245d11STodd Fiala         reason = ProcessMessage::eInternalStackError;
1704af245d11STodd Fiala         break;
1705af245d11STodd Fiala     }
1706af245d11STodd Fiala 
1707af245d11STodd Fiala     return reason;
1708af245d11STodd Fiala }
1709af245d11STodd Fiala #endif
1710af245d11STodd Fiala 
1711af245d11STodd Fiala #if 0
1712af245d11STodd Fiala ProcessMessage::CrashReason
1713af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
1714af245d11STodd Fiala {
1715af245d11STodd Fiala     ProcessMessage::CrashReason reason;
1716af245d11STodd Fiala     assert(info->si_signo == SIGFPE);
1717af245d11STodd Fiala 
1718af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
1719af245d11STodd Fiala 
1720af245d11STodd Fiala     switch (info->si_code)
1721af245d11STodd Fiala     {
1722af245d11STodd Fiala     default:
1723af245d11STodd Fiala         assert(false && "unexpected si_code for SIGFPE");
1724af245d11STodd Fiala         break;
1725af245d11STodd Fiala     case FPE_INTDIV:
1726af245d11STodd Fiala         reason = ProcessMessage::eIntegerDivideByZero;
1727af245d11STodd Fiala         break;
1728af245d11STodd Fiala     case FPE_INTOVF:
1729af245d11STodd Fiala         reason = ProcessMessage::eIntegerOverflow;
1730af245d11STodd Fiala         break;
1731af245d11STodd Fiala     case FPE_FLTDIV:
1732af245d11STodd Fiala         reason = ProcessMessage::eFloatDivideByZero;
1733af245d11STodd Fiala         break;
1734af245d11STodd Fiala     case FPE_FLTOVF:
1735af245d11STodd Fiala         reason = ProcessMessage::eFloatOverflow;
1736af245d11STodd Fiala         break;
1737af245d11STodd Fiala     case FPE_FLTUND:
1738af245d11STodd Fiala         reason = ProcessMessage::eFloatUnderflow;
1739af245d11STodd Fiala         break;
1740af245d11STodd Fiala     case FPE_FLTRES:
1741af245d11STodd Fiala         reason = ProcessMessage::eFloatInexactResult;
1742af245d11STodd Fiala         break;
1743af245d11STodd Fiala     case FPE_FLTINV:
1744af245d11STodd Fiala         reason = ProcessMessage::eFloatInvalidOperation;
1745af245d11STodd Fiala         break;
1746af245d11STodd Fiala     case FPE_FLTSUB:
1747af245d11STodd Fiala         reason = ProcessMessage::eFloatSubscriptRange;
1748af245d11STodd Fiala         break;
1749af245d11STodd Fiala     }
1750af245d11STodd Fiala 
1751af245d11STodd Fiala     return reason;
1752af245d11STodd Fiala }
1753af245d11STodd Fiala #endif
1754af245d11STodd Fiala 
1755af245d11STodd Fiala #if 0
1756af245d11STodd Fiala ProcessMessage::CrashReason
1757af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
1758af245d11STodd Fiala {
1759af245d11STodd Fiala     ProcessMessage::CrashReason reason;
1760af245d11STodd Fiala     assert(info->si_signo == SIGBUS);
1761af245d11STodd Fiala 
1762af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
1763af245d11STodd Fiala 
1764af245d11STodd Fiala     switch (info->si_code)
1765af245d11STodd Fiala     {
1766af245d11STodd Fiala     default:
1767af245d11STodd Fiala         assert(false && "unexpected si_code for SIGBUS");
1768af245d11STodd Fiala         break;
1769af245d11STodd Fiala     case BUS_ADRALN:
1770af245d11STodd Fiala         reason = ProcessMessage::eIllegalAlignment;
1771af245d11STodd Fiala         break;
1772af245d11STodd Fiala     case BUS_ADRERR:
1773af245d11STodd Fiala         reason = ProcessMessage::eIllegalAddress;
1774af245d11STodd Fiala         break;
1775af245d11STodd Fiala     case BUS_OBJERR:
1776af245d11STodd Fiala         reason = ProcessMessage::eHardwareError;
1777af245d11STodd Fiala         break;
1778af245d11STodd Fiala     }
1779af245d11STodd Fiala 
1780af245d11STodd Fiala     return reason;
1781af245d11STodd Fiala }
1782af245d11STodd Fiala #endif
1783af245d11STodd Fiala 
178497206d57SZachary Turner Status NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
1785b9c1b51eSKate Stone                                       size_t &bytes_read) {
1786df7c6995SPavel Labath   if (ProcessVmReadvSupported()) {
1787b9c1b51eSKate Stone     // The process_vm_readv path is about 50 times faster than ptrace api. We
1788b9c1b51eSKate Stone     // want to use
1789df7c6995SPavel Labath     // this syscall if it is supported.
1790df7c6995SPavel Labath 
1791df7c6995SPavel Labath     const ::pid_t pid = GetID();
1792df7c6995SPavel Labath 
1793df7c6995SPavel Labath     struct iovec local_iov, remote_iov;
1794df7c6995SPavel Labath     local_iov.iov_base = buf;
1795df7c6995SPavel Labath     local_iov.iov_len = size;
1796df7c6995SPavel Labath     remote_iov.iov_base = reinterpret_cast<void *>(addr);
1797df7c6995SPavel Labath     remote_iov.iov_len = size;
1798df7c6995SPavel Labath 
1799df7c6995SPavel Labath     bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
1800df7c6995SPavel Labath     const bool success = bytes_read == size;
1801df7c6995SPavel Labath 
1802a6321a8eSPavel Labath     Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1803a6321a8eSPavel Labath     LLDB_LOG(log,
1804a6321a8eSPavel Labath              "using process_vm_readv to read {0} bytes from inferior "
1805a6321a8eSPavel Labath              "address {1:x}: {2}",
180610c41f37SPavel Labath              size, addr, success ? "Success" : llvm::sys::StrError(errno));
1807df7c6995SPavel Labath 
1808df7c6995SPavel Labath     if (success)
180997206d57SZachary Turner       return Status();
1810a6321a8eSPavel Labath     // else the call failed for some reason, let's retry the read using ptrace
1811b9c1b51eSKate Stone     // api.
1812df7c6995SPavel Labath   }
1813df7c6995SPavel Labath 
181419cbe96aSPavel Labath   unsigned char *dst = static_cast<unsigned char *>(buf);
181519cbe96aSPavel Labath   size_t remainder;
181619cbe96aSPavel Labath   long data;
181719cbe96aSPavel Labath 
1818a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1819a6321a8eSPavel Labath   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
182019cbe96aSPavel Labath 
1821b9c1b51eSKate Stone   for (bytes_read = 0; bytes_read < size; bytes_read += remainder) {
182297206d57SZachary Turner     Status error = NativeProcessLinux::PtraceWrapper(
1823b9c1b51eSKate Stone         PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data);
1824a6321a8eSPavel Labath     if (error.Fail())
182519cbe96aSPavel Labath       return error;
182619cbe96aSPavel Labath 
182719cbe96aSPavel Labath     remainder = size - bytes_read;
182819cbe96aSPavel Labath     remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
182919cbe96aSPavel Labath 
183019cbe96aSPavel Labath     // Copy the data into our buffer
1831f6ef187bSMohit K. Bhakkad     memcpy(dst, &data, remainder);
183219cbe96aSPavel Labath 
1833a6321a8eSPavel Labath     LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
183419cbe96aSPavel Labath     addr += k_ptrace_word_size;
183519cbe96aSPavel Labath     dst += k_ptrace_word_size;
183619cbe96aSPavel Labath   }
183797206d57SZachary Turner   return Status();
1838af245d11STodd Fiala }
1839af245d11STodd Fiala 
184097206d57SZachary Turner Status NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf,
1841b9c1b51eSKate Stone                                                  size_t size,
1842b9c1b51eSKate Stone                                                  size_t &bytes_read) {
184397206d57SZachary Turner   Status error = ReadMemory(addr, buf, size, bytes_read);
1844b9c1b51eSKate Stone   if (error.Fail())
1845b9c1b51eSKate Stone     return error;
18463eb4b458SChaoren Lin   return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
18473eb4b458SChaoren Lin }
18483eb4b458SChaoren Lin 
184997206d57SZachary Turner Status NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,
1850b9c1b51eSKate Stone                                        size_t size, size_t &bytes_written) {
185119cbe96aSPavel Labath   const unsigned char *src = static_cast<const unsigned char *>(buf);
185219cbe96aSPavel Labath   size_t remainder;
185397206d57SZachary Turner   Status error;
185419cbe96aSPavel Labath 
1855a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1856a6321a8eSPavel Labath   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
185719cbe96aSPavel Labath 
1858b9c1b51eSKate Stone   for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
185919cbe96aSPavel Labath     remainder = size - bytes_written;
186019cbe96aSPavel Labath     remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
186119cbe96aSPavel Labath 
1862b9c1b51eSKate Stone     if (remainder == k_ptrace_word_size) {
186319cbe96aSPavel Labath       unsigned long data = 0;
1864f6ef187bSMohit K. Bhakkad       memcpy(&data, src, k_ptrace_word_size);
186519cbe96aSPavel Labath 
1866a6321a8eSPavel Labath       LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
1867b9c1b51eSKate Stone       error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(),
1868b9c1b51eSKate Stone                                                 (void *)addr, (void *)data);
1869a6321a8eSPavel Labath       if (error.Fail())
187019cbe96aSPavel Labath         return error;
1871b9c1b51eSKate Stone     } else {
187219cbe96aSPavel Labath       unsigned char buff[8];
187319cbe96aSPavel Labath       size_t bytes_read;
187419cbe96aSPavel Labath       error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
1875a6321a8eSPavel Labath       if (error.Fail())
187619cbe96aSPavel Labath         return error;
187719cbe96aSPavel Labath 
187819cbe96aSPavel Labath       memcpy(buff, src, remainder);
187919cbe96aSPavel Labath 
188019cbe96aSPavel Labath       size_t bytes_written_rec;
188119cbe96aSPavel Labath       error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
1882a6321a8eSPavel Labath       if (error.Fail())
188319cbe96aSPavel Labath         return error;
188419cbe96aSPavel Labath 
1885a6321a8eSPavel Labath       LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src,
1886b9c1b51eSKate Stone                *(unsigned long *)buff);
188719cbe96aSPavel Labath     }
188819cbe96aSPavel Labath 
188919cbe96aSPavel Labath     addr += k_ptrace_word_size;
189019cbe96aSPavel Labath     src += k_ptrace_word_size;
189119cbe96aSPavel Labath   }
189219cbe96aSPavel Labath   return error;
1893af245d11STodd Fiala }
1894af245d11STodd Fiala 
189597206d57SZachary Turner Status NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) {
189619cbe96aSPavel Labath   return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
1897af245d11STodd Fiala }
1898af245d11STodd Fiala 
189997206d57SZachary Turner Status NativeProcessLinux::GetEventMessage(lldb::tid_t tid,
1900b9c1b51eSKate Stone                                            unsigned long *message) {
190119cbe96aSPavel Labath   return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
1902af245d11STodd Fiala }
1903af245d11STodd Fiala 
190497206d57SZachary Turner Status NativeProcessLinux::Detach(lldb::tid_t tid) {
190597ccc294SChaoren Lin   if (tid == LLDB_INVALID_THREAD_ID)
190697206d57SZachary Turner     return Status();
190797ccc294SChaoren Lin 
190819cbe96aSPavel Labath   return PtraceWrapper(PTRACE_DETACH, tid);
1909af245d11STodd Fiala }
1910af245d11STodd Fiala 
1911b9c1b51eSKate Stone bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {
1912a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
1913a5be48b3SPavel Labath     assert(thread && "thread list should not contain NULL threads");
1914a5be48b3SPavel Labath     if (thread->GetID() == thread_id) {
1915af245d11STodd Fiala       // We have this thread.
1916af245d11STodd Fiala       return true;
1917af245d11STodd Fiala     }
1918af245d11STodd Fiala   }
1919af245d11STodd Fiala 
1920af245d11STodd Fiala   // We don't have this thread.
1921af245d11STodd Fiala   return false;
1922af245d11STodd Fiala }
1923af245d11STodd Fiala 
1924b9c1b51eSKate Stone bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) {
1925a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1926a6321a8eSPavel Labath   LLDB_LOG(log, "tid: {0})", thread_id);
19271dbc6c9cSPavel Labath 
19281dbc6c9cSPavel Labath   bool found = false;
1929b9c1b51eSKate Stone   for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
1930b9c1b51eSKate Stone     if (*it && ((*it)->GetID() == thread_id)) {
1931af245d11STodd Fiala       m_threads.erase(it);
19321dbc6c9cSPavel Labath       found = true;
19331dbc6c9cSPavel Labath       break;
1934af245d11STodd Fiala     }
1935af245d11STodd Fiala   }
1936af245d11STodd Fiala 
193799e37695SRavitheja Addepally   if (found)
193899e37695SRavitheja Addepally     StopTracingForThread(thread_id);
19399eb1ecb9SPavel Labath   SignalIfAllThreadsStopped();
19401dbc6c9cSPavel Labath   return found;
1941af245d11STodd Fiala }
1942af245d11STodd Fiala 
1943a5be48b3SPavel Labath NativeThreadLinux &NativeProcessLinux::AddThread(lldb::tid_t thread_id) {
1944a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
1945a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
1946af245d11STodd Fiala 
1947b9c1b51eSKate Stone   assert(!HasThreadNoLock(thread_id) &&
1948b9c1b51eSKate Stone          "attempted to add a thread by id that already exists");
1949af245d11STodd Fiala 
1950af245d11STodd Fiala   // If this is the first thread, save it as the current thread
1951af245d11STodd Fiala   if (m_threads.empty())
1952af245d11STodd Fiala     SetCurrentThreadID(thread_id);
1953af245d11STodd Fiala 
1954a5be48b3SPavel Labath   m_threads.push_back(llvm::make_unique<NativeThreadLinux>(*this, thread_id));
195599e37695SRavitheja Addepally 
195699e37695SRavitheja Addepally   if (m_pt_proces_trace_id != LLDB_INVALID_UID) {
195799e37695SRavitheja Addepally     auto traceMonitor = ProcessorTraceMonitor::Create(
195899e37695SRavitheja Addepally         GetID(), thread_id, m_pt_process_trace_config, true);
195999e37695SRavitheja Addepally     if (traceMonitor) {
196099e37695SRavitheja Addepally       m_pt_traced_thread_group.insert(thread_id);
196199e37695SRavitheja Addepally       m_processor_trace_monitor.insert(
196299e37695SRavitheja Addepally           std::make_pair(thread_id, std::move(*traceMonitor)));
196399e37695SRavitheja Addepally     } else {
196499e37695SRavitheja Addepally       LLDB_LOG(log, "failed to start trace on thread {0}", thread_id);
196599e37695SRavitheja Addepally       Status error(traceMonitor.takeError());
196699e37695SRavitheja Addepally       LLDB_LOG(log, "error {0}", error);
196799e37695SRavitheja Addepally     }
196899e37695SRavitheja Addepally   }
196999e37695SRavitheja Addepally 
1970a5be48b3SPavel Labath   return static_cast<NativeThreadLinux &>(*m_threads.back());
1971af245d11STodd Fiala }
1972af245d11STodd Fiala 
197397206d57SZachary Turner Status
197497206d57SZachary Turner NativeProcessLinux::FixupBreakpointPCAsNeeded(NativeThreadLinux &thread) {
1975a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_BREAKPOINTS));
1976af245d11STodd Fiala 
197797206d57SZachary Turner   Status error;
1978af245d11STodd Fiala 
1979b9c1b51eSKate Stone   // Find out the size of a breakpoint (might depend on where we are in the
1980b9c1b51eSKate Stone   // code).
1981d37349f3SPavel Labath   NativeRegisterContext &context = thread.GetRegisterContext();
1982af245d11STodd Fiala 
1983af245d11STodd Fiala   uint32_t breakpoint_size = 0;
1984b9cc0c75SPavel Labath   error = GetSoftwareBreakpointPCOffset(breakpoint_size);
1985b9c1b51eSKate Stone   if (error.Fail()) {
1986a6321a8eSPavel Labath     LLDB_LOG(log, "GetBreakpointSize() failed: {0}", error);
1987af245d11STodd Fiala     return error;
1988a6321a8eSPavel Labath   } else
1989a6321a8eSPavel Labath     LLDB_LOG(log, "breakpoint size: {0}", breakpoint_size);
1990af245d11STodd Fiala 
1991b9c1b51eSKate Stone   // First try probing for a breakpoint at a software breakpoint location: PC -
1992b9c1b51eSKate Stone   // breakpoint size.
1993d37349f3SPavel Labath   const lldb::addr_t initial_pc_addr = context.GetPCfromBreakpointLocation();
1994af245d11STodd Fiala   lldb::addr_t breakpoint_addr = initial_pc_addr;
1995b9c1b51eSKate Stone   if (breakpoint_size > 0) {
1996af245d11STodd Fiala     // Do not allow breakpoint probe to wrap around.
19973eb4b458SChaoren Lin     if (breakpoint_addr >= breakpoint_size)
19983eb4b458SChaoren Lin       breakpoint_addr -= breakpoint_size;
1999af245d11STodd Fiala   }
2000af245d11STodd Fiala 
2001af245d11STodd Fiala   // Check if we stopped because of a breakpoint.
2002af245d11STodd Fiala   NativeBreakpointSP breakpoint_sp;
2003af245d11STodd Fiala   error = m_breakpoint_list.GetBreakpoint(breakpoint_addr, breakpoint_sp);
2004b9c1b51eSKate Stone   if (!error.Success() || !breakpoint_sp) {
2005af245d11STodd Fiala     // We didn't find one at a software probe location.  Nothing to do.
2006a6321a8eSPavel Labath     LLDB_LOG(log,
2007a6321a8eSPavel Labath              "pid {0} no lldb breakpoint found at current pc with "
2008a6321a8eSPavel Labath              "adjustment: {1}",
2009a6321a8eSPavel Labath              GetID(), breakpoint_addr);
201097206d57SZachary Turner     return Status();
2011af245d11STodd Fiala   }
2012af245d11STodd Fiala 
2013af245d11STodd Fiala   // If the breakpoint is not a software breakpoint, nothing to do.
2014b9c1b51eSKate Stone   if (!breakpoint_sp->IsSoftwareBreakpoint()) {
2015a6321a8eSPavel Labath     LLDB_LOG(
2016a6321a8eSPavel Labath         log,
2017a6321a8eSPavel Labath         "pid {0} breakpoint found at {1:x}, not software, nothing to adjust",
2018a6321a8eSPavel Labath         GetID(), breakpoint_addr);
201997206d57SZachary Turner     return Status();
2020af245d11STodd Fiala   }
2021af245d11STodd Fiala 
2022af245d11STodd Fiala   //
2023af245d11STodd Fiala   // We have a software breakpoint and need to adjust the PC.
2024af245d11STodd Fiala   //
2025af245d11STodd Fiala 
2026af245d11STodd Fiala   // Sanity check.
2027b9c1b51eSKate Stone   if (breakpoint_size == 0) {
2028af245d11STodd Fiala     // Nothing to do!  How did we get here?
2029a6321a8eSPavel Labath     LLDB_LOG(log,
2030a6321a8eSPavel Labath              "pid {0} breakpoint found at {1:x}, it is software, but the "
2031a6321a8eSPavel Labath              "size is zero, nothing to do (unexpected)",
2032a6321a8eSPavel Labath              GetID(), breakpoint_addr);
203397206d57SZachary Turner     return Status();
2034af245d11STodd Fiala   }
2035af245d11STodd Fiala 
2036af245d11STodd Fiala   // Change the program counter.
2037a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0} tid {1}: changing PC from {2:x} to {3:x}", GetID(),
2038a6321a8eSPavel Labath            thread.GetID(), initial_pc_addr, breakpoint_addr);
2039af245d11STodd Fiala 
2040d37349f3SPavel Labath   error = context.SetPC(breakpoint_addr);
2041b9c1b51eSKate Stone   if (error.Fail()) {
2042a6321a8eSPavel Labath     LLDB_LOG(log, "pid {0} tid {1}: failed to set PC: {2}", GetID(),
2043a6321a8eSPavel Labath              thread.GetID(), error);
2044af245d11STodd Fiala     return error;
2045af245d11STodd Fiala   }
2046af245d11STodd Fiala 
2047af245d11STodd Fiala   return error;
2048af245d11STodd Fiala }
2049fa03ad2eSChaoren Lin 
205097206d57SZachary Turner Status NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,
2051b9c1b51eSKate Stone                                                    FileSpec &file_spec) {
205297206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
2053a6f5795aSTamas Berghammer   if (error.Fail())
2054a6f5795aSTamas Berghammer     return error;
2055a6f5795aSTamas Berghammer 
20567cb18bf5STamas Berghammer   FileSpec module_file_spec(module_path, true);
20577cb18bf5STamas Berghammer 
20587cb18bf5STamas Berghammer   file_spec.Clear();
2059a6f5795aSTamas Berghammer   for (const auto &it : m_mem_region_cache) {
2060a6f5795aSTamas Berghammer     if (it.second.GetFilename() == module_file_spec.GetFilename()) {
2061a6f5795aSTamas Berghammer       file_spec = it.second;
206297206d57SZachary Turner       return Status();
2063a6f5795aSTamas Berghammer     }
2064a6f5795aSTamas Berghammer   }
206597206d57SZachary Turner   return Status("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
20667cb18bf5STamas Berghammer                 module_file_spec.GetFilename().AsCString(), GetID());
20677cb18bf5STamas Berghammer }
2068c076559aSPavel Labath 
206997206d57SZachary Turner Status NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
2070b9c1b51eSKate Stone                                               lldb::addr_t &load_addr) {
2071783bfc8cSTamas Berghammer   load_addr = LLDB_INVALID_ADDRESS;
207297206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
2073a6f5795aSTamas Berghammer   if (error.Fail())
2074783bfc8cSTamas Berghammer     return error;
2075a6f5795aSTamas Berghammer 
2076a6f5795aSTamas Berghammer   FileSpec file(file_name, false);
2077a6f5795aSTamas Berghammer   for (const auto &it : m_mem_region_cache) {
2078a6f5795aSTamas Berghammer     if (it.second == file) {
2079a6f5795aSTamas Berghammer       load_addr = it.first.GetRange().GetRangeBase();
208097206d57SZachary Turner       return Status();
2081a6f5795aSTamas Berghammer     }
2082a6f5795aSTamas Berghammer   }
208397206d57SZachary Turner   return Status("No load address found for specified file.");
2084783bfc8cSTamas Berghammer }
2085783bfc8cSTamas Berghammer 
2086a5be48b3SPavel Labath NativeThreadLinux *NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {
2087a5be48b3SPavel Labath   return static_cast<NativeThreadLinux *>(
2088b9c1b51eSKate Stone       NativeProcessProtocol::GetThreadByID(tid));
2089f9077782SPavel Labath }
2090f9077782SPavel Labath 
209197206d57SZachary Turner Status NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,
2092b9c1b51eSKate Stone                                         lldb::StateType state, int signo) {
2093a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2094a6321a8eSPavel Labath   LLDB_LOG(log, "tid: {0}", thread.GetID());
2095c076559aSPavel Labath 
2096c076559aSPavel Labath   // Before we do the resume below, first check if we have a pending
2097108c325dSPavel Labath   // stop notification that is currently waiting for
20980e1d729bSPavel Labath   // all threads to stop.  This is potentially a buggy situation since
2099c076559aSPavel Labath   // we're ostensibly waiting for threads to stop before we send out the
2100c076559aSPavel Labath   // pending notification, and here we are resuming one before we send
2101c076559aSPavel Labath   // out the pending stop notification.
2102a6321a8eSPavel Labath   if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
2103a6321a8eSPavel Labath     LLDB_LOG(log,
2104a6321a8eSPavel Labath              "about to resume tid {0} per explicit request but we have a "
2105a6321a8eSPavel Labath              "pending stop notification (tid {1}) that is actively "
2106a6321a8eSPavel Labath              "waiting for this thread to stop. Valid sequence of events?",
2107a6321a8eSPavel Labath              thread.GetID(), m_pending_notification_tid);
2108c076559aSPavel Labath   }
2109c076559aSPavel Labath 
2110c076559aSPavel Labath   // Request a resume.  We expect this to be synchronous and the system
2111c076559aSPavel Labath   // to reflect it is running after this completes.
2112b9c1b51eSKate Stone   switch (state) {
2113b9c1b51eSKate Stone   case eStateRunning: {
2114605b51b8SPavel Labath     const auto resume_result = thread.Resume(signo);
21150e1d729bSPavel Labath     if (resume_result.Success())
21160e1d729bSPavel Labath       SetState(eStateRunning, true);
21170e1d729bSPavel Labath     return resume_result;
2118c076559aSPavel Labath   }
2119b9c1b51eSKate Stone   case eStateStepping: {
2120605b51b8SPavel Labath     const auto step_result = thread.SingleStep(signo);
21210e1d729bSPavel Labath     if (step_result.Success())
21220e1d729bSPavel Labath       SetState(eStateRunning, true);
21230e1d729bSPavel Labath     return step_result;
21240e1d729bSPavel Labath   }
21250e1d729bSPavel Labath   default:
21268198db30SPavel Labath     LLDB_LOG(log, "Unhandled state {0}.", state);
21270e1d729bSPavel Labath     llvm_unreachable("Unhandled state for resume");
21280e1d729bSPavel Labath   }
2129c076559aSPavel Labath }
2130c076559aSPavel Labath 
2131c076559aSPavel Labath //===----------------------------------------------------------------------===//
2132c076559aSPavel Labath 
2133b9c1b51eSKate Stone void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {
2134a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2135a6321a8eSPavel Labath   LLDB_LOG(log, "about to process event: (triggering_tid: {0})",
2136a6321a8eSPavel Labath            triggering_tid);
2137c076559aSPavel Labath 
21380e1d729bSPavel Labath   m_pending_notification_tid = triggering_tid;
21390e1d729bSPavel Labath 
21400e1d729bSPavel Labath   // Request a stop for all the thread stops that need to be stopped
21410e1d729bSPavel Labath   // and are not already known to be stopped.
2142a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
2143a5be48b3SPavel Labath     if (StateIsRunningState(thread->GetState()))
2144a5be48b3SPavel Labath       static_cast<NativeThreadLinux *>(thread.get())->RequestStop();
21450e1d729bSPavel Labath   }
21460e1d729bSPavel Labath 
21470e1d729bSPavel Labath   SignalIfAllThreadsStopped();
2148a6321a8eSPavel Labath   LLDB_LOG(log, "event processing done");
2149c076559aSPavel Labath }
2150c076559aSPavel Labath 
2151b9c1b51eSKate Stone void NativeProcessLinux::SignalIfAllThreadsStopped() {
21520e1d729bSPavel Labath   if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
21530e1d729bSPavel Labath     return; // No pending notification. Nothing to do.
21540e1d729bSPavel Labath 
2155b9c1b51eSKate Stone   for (const auto &thread_sp : m_threads) {
21560e1d729bSPavel Labath     if (StateIsRunningState(thread_sp->GetState()))
21570e1d729bSPavel Labath       return; // Some threads are still running. Don't signal yet.
21580e1d729bSPavel Labath   }
21590e1d729bSPavel Labath 
21600e1d729bSPavel Labath   // We have a pending notification and all threads have stopped.
2161b9c1b51eSKate Stone   Log *log(
2162b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
21639eb1ecb9SPavel Labath 
2164b9c1b51eSKate Stone   // Clear any temporary breakpoints we used to implement software single
2165b9c1b51eSKate Stone   // stepping.
2166b9c1b51eSKate Stone   for (const auto &thread_info : m_threads_stepping_with_breakpoint) {
216797206d57SZachary Turner     Status error = RemoveBreakpoint(thread_info.second);
21689eb1ecb9SPavel Labath     if (error.Fail())
2169a6321a8eSPavel Labath       LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}",
2170a6321a8eSPavel Labath                thread_info.first, error);
21719eb1ecb9SPavel Labath   }
21729eb1ecb9SPavel Labath   m_threads_stepping_with_breakpoint.clear();
21739eb1ecb9SPavel Labath 
21749eb1ecb9SPavel Labath   // Notify the delegate about the stop
21750e1d729bSPavel Labath   SetCurrentThreadID(m_pending_notification_tid);
2176ed89c7feSPavel Labath   SetState(StateType::eStateStopped, true);
21770e1d729bSPavel Labath   m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
2178c076559aSPavel Labath }
2179c076559aSPavel Labath 
2180b9c1b51eSKate Stone void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {
2181a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2182a6321a8eSPavel Labath   LLDB_LOG(log, "tid: {0}", thread.GetID());
21831dbc6c9cSPavel Labath 
2184b9c1b51eSKate Stone   if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID &&
2185b9c1b51eSKate Stone       StateIsRunningState(thread.GetState())) {
2186b9c1b51eSKate Stone     // We will need to wait for this new thread to stop as well before firing
2187b9c1b51eSKate Stone     // the
2188c076559aSPavel Labath     // notification.
2189f9077782SPavel Labath     thread.RequestStop();
2190c076559aSPavel Labath   }
2191c076559aSPavel Labath }
2192068f8a7eSTamas Berghammer 
2193b9c1b51eSKate Stone void NativeProcessLinux::SigchldHandler() {
2194a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
219519cbe96aSPavel Labath   // Process all pending waitpid notifications.
2196b9c1b51eSKate Stone   while (true) {
219719cbe96aSPavel Labath     int status = -1;
2198c1a6b128SPavel Labath     ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, -1, &status,
2199c1a6b128SPavel Labath                                           __WALL | __WNOTHREAD | WNOHANG);
220019cbe96aSPavel Labath 
220119cbe96aSPavel Labath     if (wait_pid == 0)
220219cbe96aSPavel Labath       break; // We are done.
220319cbe96aSPavel Labath 
2204b9c1b51eSKate Stone     if (wait_pid == -1) {
220597206d57SZachary Turner       Status error(errno, eErrorTypePOSIX);
2206a6321a8eSPavel Labath       LLDB_LOG(log, "waitpid (-1, &status, _) failed: {0}", error);
220719cbe96aSPavel Labath       break;
220819cbe96aSPavel Labath     }
220919cbe96aSPavel Labath 
22103508fc8cSPavel Labath     WaitStatus wait_status = WaitStatus::Decode(status);
22113508fc8cSPavel Labath     bool exited = wait_status.type == WaitStatus::Exit ||
22123508fc8cSPavel Labath                   (wait_status.type == WaitStatus::Signal &&
22133508fc8cSPavel Labath                    wait_pid == static_cast<::pid_t>(GetID()));
221419cbe96aSPavel Labath 
22153508fc8cSPavel Labath     LLDB_LOG(
22163508fc8cSPavel Labath         log,
22173508fc8cSPavel Labath         "waitpid (-1, &status, _) => pid = {0}, status = {1}, exited = {2}",
22183508fc8cSPavel Labath         wait_pid, wait_status, exited);
221919cbe96aSPavel Labath 
22203508fc8cSPavel Labath     MonitorCallback(wait_pid, exited, wait_status);
222119cbe96aSPavel Labath   }
2222068f8a7eSTamas Berghammer }
2223068f8a7eSTamas Berghammer 
2224068f8a7eSTamas Berghammer // Wrapper for ptrace to catch errors and log calls.
2225b9c1b51eSKate Stone // Note that ptrace sets errno on error because -1 can be a valid result (i.e.
2226b9c1b51eSKate Stone // for PTRACE_PEEK*)
222797206d57SZachary Turner Status NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
2228b9c1b51eSKate Stone                                          void *data, size_t data_size,
2229b9c1b51eSKate Stone                                          long *result) {
223097206d57SZachary Turner   Status error;
22314a9babb2SPavel Labath   long int ret;
2232068f8a7eSTamas Berghammer 
2233068f8a7eSTamas Berghammer   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2234068f8a7eSTamas Berghammer 
2235068f8a7eSTamas Berghammer   PtraceDisplayBytes(req, data, data_size);
2236068f8a7eSTamas Berghammer 
2237068f8a7eSTamas Berghammer   errno = 0;
2238068f8a7eSTamas Berghammer   if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
2239b9c1b51eSKate Stone     ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2240b9c1b51eSKate Stone                  *(unsigned int *)addr, data);
2241068f8a7eSTamas Berghammer   else
2242b9c1b51eSKate Stone     ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2243b9c1b51eSKate Stone                  addr, data);
2244068f8a7eSTamas Berghammer 
22454a9babb2SPavel Labath   if (ret == -1)
2246068f8a7eSTamas Berghammer     error.SetErrorToErrno();
2247068f8a7eSTamas Berghammer 
22484a9babb2SPavel Labath   if (result)
22494a9babb2SPavel Labath     *result = ret;
22504a9babb2SPavel Labath 
225128096200SPavel Labath   LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data,
225228096200SPavel Labath            data_size, ret);
2253068f8a7eSTamas Berghammer 
2254068f8a7eSTamas Berghammer   PtraceDisplayBytes(req, data, data_size);
2255068f8a7eSTamas Berghammer 
2256a6321a8eSPavel Labath   if (error.Fail())
2257a6321a8eSPavel Labath     LLDB_LOG(log, "ptrace() failed: {0}", error);
2258068f8a7eSTamas Berghammer 
22594a9babb2SPavel Labath   return error;
2260068f8a7eSTamas Berghammer }
226199e37695SRavitheja Addepally 
226299e37695SRavitheja Addepally llvm::Expected<ProcessorTraceMonitor &>
226399e37695SRavitheja Addepally NativeProcessLinux::LookupProcessorTraceInstance(lldb::user_id_t traceid,
226499e37695SRavitheja Addepally                                                  lldb::tid_t thread) {
226599e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
226699e37695SRavitheja Addepally   if (thread == LLDB_INVALID_THREAD_ID && traceid == m_pt_proces_trace_id) {
226799e37695SRavitheja Addepally     LLDB_LOG(log, "thread not specified: {0}", traceid);
226899e37695SRavitheja Addepally     return Status("tracing not active thread not specified").ToError();
226999e37695SRavitheja Addepally   }
227099e37695SRavitheja Addepally 
227199e37695SRavitheja Addepally   for (auto& iter : m_processor_trace_monitor) {
227299e37695SRavitheja Addepally     if (traceid == iter.second->GetTraceID() &&
227399e37695SRavitheja Addepally         (thread == iter.first || thread == LLDB_INVALID_THREAD_ID))
227499e37695SRavitheja Addepally       return *(iter.second);
227599e37695SRavitheja Addepally   }
227699e37695SRavitheja Addepally 
227799e37695SRavitheja Addepally   LLDB_LOG(log, "traceid not being traced: {0}", traceid);
227899e37695SRavitheja Addepally   return Status("tracing not active for this thread").ToError();
227999e37695SRavitheja Addepally }
228099e37695SRavitheja Addepally 
228199e37695SRavitheja Addepally Status NativeProcessLinux::GetMetaData(lldb::user_id_t traceid,
228299e37695SRavitheja Addepally                                        lldb::tid_t thread,
228399e37695SRavitheja Addepally                                        llvm::MutableArrayRef<uint8_t> &buffer,
228499e37695SRavitheja Addepally                                        size_t offset) {
228599e37695SRavitheja Addepally   TraceOptions trace_options;
228699e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
228799e37695SRavitheja Addepally   Status error;
228899e37695SRavitheja Addepally 
228999e37695SRavitheja Addepally   LLDB_LOG(log, "traceid {0}", traceid);
229099e37695SRavitheja Addepally 
229199e37695SRavitheja Addepally   auto perf_monitor = LookupProcessorTraceInstance(traceid, thread);
229299e37695SRavitheja Addepally   if (!perf_monitor) {
229399e37695SRavitheja Addepally     LLDB_LOG(log, "traceid not being traced: {0}", traceid);
229499e37695SRavitheja Addepally     buffer = buffer.slice(buffer.size());
229599e37695SRavitheja Addepally     error = perf_monitor.takeError();
229699e37695SRavitheja Addepally     return error;
229799e37695SRavitheja Addepally   }
229899e37695SRavitheja Addepally   return (*perf_monitor).ReadPerfTraceData(buffer, offset);
229999e37695SRavitheja Addepally }
230099e37695SRavitheja Addepally 
230199e37695SRavitheja Addepally Status NativeProcessLinux::GetData(lldb::user_id_t traceid, lldb::tid_t thread,
230299e37695SRavitheja Addepally                                    llvm::MutableArrayRef<uint8_t> &buffer,
230399e37695SRavitheja Addepally                                    size_t offset) {
230499e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
230599e37695SRavitheja Addepally   Status error;
230699e37695SRavitheja Addepally 
230799e37695SRavitheja Addepally   LLDB_LOG(log, "traceid {0}", traceid);
230899e37695SRavitheja Addepally 
230999e37695SRavitheja Addepally   auto perf_monitor = LookupProcessorTraceInstance(traceid, thread);
231099e37695SRavitheja Addepally   if (!perf_monitor) {
231199e37695SRavitheja Addepally     LLDB_LOG(log, "traceid not being traced: {0}", traceid);
231299e37695SRavitheja Addepally     buffer = buffer.slice(buffer.size());
231399e37695SRavitheja Addepally     error = perf_monitor.takeError();
231499e37695SRavitheja Addepally     return error;
231599e37695SRavitheja Addepally   }
231699e37695SRavitheja Addepally   return (*perf_monitor).ReadPerfTraceAux(buffer, offset);
231799e37695SRavitheja Addepally }
231899e37695SRavitheja Addepally 
231999e37695SRavitheja Addepally Status NativeProcessLinux::GetTraceConfig(lldb::user_id_t traceid,
232099e37695SRavitheja Addepally                                           TraceOptions &config) {
232199e37695SRavitheja Addepally   Status error;
232299e37695SRavitheja Addepally   if (config.getThreadID() == LLDB_INVALID_THREAD_ID &&
232399e37695SRavitheja Addepally       m_pt_proces_trace_id == traceid) {
232499e37695SRavitheja Addepally     if (m_pt_proces_trace_id == LLDB_INVALID_UID) {
232599e37695SRavitheja Addepally       error.SetErrorString("tracing not active for this process");
232699e37695SRavitheja Addepally       return error;
232799e37695SRavitheja Addepally     }
232899e37695SRavitheja Addepally     config = m_pt_process_trace_config;
232999e37695SRavitheja Addepally   } else {
233099e37695SRavitheja Addepally     auto perf_monitor =
233199e37695SRavitheja Addepally         LookupProcessorTraceInstance(traceid, config.getThreadID());
233299e37695SRavitheja Addepally     if (!perf_monitor) {
233399e37695SRavitheja Addepally       error = perf_monitor.takeError();
233499e37695SRavitheja Addepally       return error;
233599e37695SRavitheja Addepally     }
233699e37695SRavitheja Addepally     error = (*perf_monitor).GetTraceConfig(config);
233799e37695SRavitheja Addepally   }
233899e37695SRavitheja Addepally   return error;
233999e37695SRavitheja Addepally }
234099e37695SRavitheja Addepally 
234199e37695SRavitheja Addepally lldb::user_id_t
234299e37695SRavitheja Addepally NativeProcessLinux::StartTraceGroup(const TraceOptions &config,
234399e37695SRavitheja Addepally                                            Status &error) {
234499e37695SRavitheja Addepally 
234599e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
234699e37695SRavitheja Addepally   if (config.getType() != TraceType::eTraceTypeProcessorTrace)
234799e37695SRavitheja Addepally     return LLDB_INVALID_UID;
234899e37695SRavitheja Addepally 
234999e37695SRavitheja Addepally   if (m_pt_proces_trace_id != LLDB_INVALID_UID) {
235099e37695SRavitheja Addepally     error.SetErrorString("tracing already active on this process");
235199e37695SRavitheja Addepally     return m_pt_proces_trace_id;
235299e37695SRavitheja Addepally   }
235399e37695SRavitheja Addepally 
235499e37695SRavitheja Addepally   for (const auto &thread_sp : m_threads) {
235599e37695SRavitheja Addepally     if (auto traceInstance = ProcessorTraceMonitor::Create(
235699e37695SRavitheja Addepally             GetID(), thread_sp->GetID(), config, true)) {
235799e37695SRavitheja Addepally       m_pt_traced_thread_group.insert(thread_sp->GetID());
235899e37695SRavitheja Addepally       m_processor_trace_monitor.insert(
235999e37695SRavitheja Addepally           std::make_pair(thread_sp->GetID(), std::move(*traceInstance)));
236099e37695SRavitheja Addepally     }
236199e37695SRavitheja Addepally   }
236299e37695SRavitheja Addepally 
236399e37695SRavitheja Addepally   m_pt_process_trace_config = config;
236499e37695SRavitheja Addepally   error = ProcessorTraceMonitor::GetCPUType(m_pt_process_trace_config);
236599e37695SRavitheja Addepally 
236699e37695SRavitheja Addepally   // Trace on Complete process will have traceid of 0
236799e37695SRavitheja Addepally   m_pt_proces_trace_id = 0;
236899e37695SRavitheja Addepally 
236999e37695SRavitheja Addepally   LLDB_LOG(log, "Process Trace ID {0}", m_pt_proces_trace_id);
237099e37695SRavitheja Addepally   return m_pt_proces_trace_id;
237199e37695SRavitheja Addepally }
237299e37695SRavitheja Addepally 
237399e37695SRavitheja Addepally lldb::user_id_t NativeProcessLinux::StartTrace(const TraceOptions &config,
237499e37695SRavitheja Addepally                                                Status &error) {
237599e37695SRavitheja Addepally   if (config.getType() != TraceType::eTraceTypeProcessorTrace)
237699e37695SRavitheja Addepally     return NativeProcessProtocol::StartTrace(config, error);
237799e37695SRavitheja Addepally 
237899e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
237999e37695SRavitheja Addepally 
238099e37695SRavitheja Addepally   lldb::tid_t threadid = config.getThreadID();
238199e37695SRavitheja Addepally 
238299e37695SRavitheja Addepally   if (threadid == LLDB_INVALID_THREAD_ID)
238399e37695SRavitheja Addepally     return StartTraceGroup(config, error);
238499e37695SRavitheja Addepally 
238599e37695SRavitheja Addepally   auto thread_sp = GetThreadByID(threadid);
238699e37695SRavitheja Addepally   if (!thread_sp) {
238799e37695SRavitheja Addepally     // Thread not tracked by lldb so don't trace.
238899e37695SRavitheja Addepally     error.SetErrorString("invalid thread id");
238999e37695SRavitheja Addepally     return LLDB_INVALID_UID;
239099e37695SRavitheja Addepally   }
239199e37695SRavitheja Addepally 
239299e37695SRavitheja Addepally   const auto &iter = m_processor_trace_monitor.find(threadid);
239399e37695SRavitheja Addepally   if (iter != m_processor_trace_monitor.end()) {
239499e37695SRavitheja Addepally     LLDB_LOG(log, "Thread already being traced");
239599e37695SRavitheja Addepally     error.SetErrorString("tracing already active on this thread");
239699e37695SRavitheja Addepally     return LLDB_INVALID_UID;
239799e37695SRavitheja Addepally   }
239899e37695SRavitheja Addepally 
239999e37695SRavitheja Addepally   auto traceMonitor =
240099e37695SRavitheja Addepally       ProcessorTraceMonitor::Create(GetID(), threadid, config, false);
240199e37695SRavitheja Addepally   if (!traceMonitor) {
240299e37695SRavitheja Addepally     error = traceMonitor.takeError();
240399e37695SRavitheja Addepally     LLDB_LOG(log, "error {0}", error);
240499e37695SRavitheja Addepally     return LLDB_INVALID_UID;
240599e37695SRavitheja Addepally   }
240699e37695SRavitheja Addepally   lldb::user_id_t ret_trace_id = (*traceMonitor)->GetTraceID();
240799e37695SRavitheja Addepally   m_processor_trace_monitor.insert(
240899e37695SRavitheja Addepally       std::make_pair(threadid, std::move(*traceMonitor)));
240999e37695SRavitheja Addepally   return ret_trace_id;
241099e37695SRavitheja Addepally }
241199e37695SRavitheja Addepally 
241299e37695SRavitheja Addepally Status NativeProcessLinux::StopTracingForThread(lldb::tid_t thread) {
241399e37695SRavitheja Addepally   Status error;
241499e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
241599e37695SRavitheja Addepally   LLDB_LOG(log, "Thread {0}", thread);
241699e37695SRavitheja Addepally 
241799e37695SRavitheja Addepally   const auto& iter = m_processor_trace_monitor.find(thread);
241899e37695SRavitheja Addepally   if (iter == m_processor_trace_monitor.end()) {
241999e37695SRavitheja Addepally     error.SetErrorString("tracing not active for this thread");
242099e37695SRavitheja Addepally     return error;
242199e37695SRavitheja Addepally   }
242299e37695SRavitheja Addepally 
242399e37695SRavitheja Addepally   if (iter->second->GetTraceID() == m_pt_proces_trace_id) {
242499e37695SRavitheja Addepally     // traceid maps to the whole process so we have to erase it from the
242599e37695SRavitheja Addepally     // thread group.
242699e37695SRavitheja Addepally     LLDB_LOG(log, "traceid maps to process");
242799e37695SRavitheja Addepally     m_pt_traced_thread_group.erase(thread);
242899e37695SRavitheja Addepally   }
242999e37695SRavitheja Addepally   m_processor_trace_monitor.erase(iter);
243099e37695SRavitheja Addepally 
243199e37695SRavitheja Addepally   return error;
243299e37695SRavitheja Addepally }
243399e37695SRavitheja Addepally 
243499e37695SRavitheja Addepally Status NativeProcessLinux::StopTrace(lldb::user_id_t traceid,
243599e37695SRavitheja Addepally                                      lldb::tid_t thread) {
243699e37695SRavitheja Addepally   Status error;
243799e37695SRavitheja Addepally 
243899e37695SRavitheja Addepally   TraceOptions trace_options;
243999e37695SRavitheja Addepally   trace_options.setThreadID(thread);
244099e37695SRavitheja Addepally   error = NativeProcessLinux::GetTraceConfig(traceid, trace_options);
244199e37695SRavitheja Addepally 
244299e37695SRavitheja Addepally   if (error.Fail())
244399e37695SRavitheja Addepally     return error;
244499e37695SRavitheja Addepally 
244599e37695SRavitheja Addepally   switch (trace_options.getType()) {
244699e37695SRavitheja Addepally   case lldb::TraceType::eTraceTypeProcessorTrace:
244799e37695SRavitheja Addepally     if (traceid == m_pt_proces_trace_id &&
244899e37695SRavitheja Addepally         thread == LLDB_INVALID_THREAD_ID)
244999e37695SRavitheja Addepally       StopProcessorTracingOnProcess();
245099e37695SRavitheja Addepally     else
245199e37695SRavitheja Addepally       error = StopProcessorTracingOnThread(traceid, thread);
245299e37695SRavitheja Addepally     break;
245399e37695SRavitheja Addepally   default:
245499e37695SRavitheja Addepally     error.SetErrorString("trace not supported");
245599e37695SRavitheja Addepally     break;
245699e37695SRavitheja Addepally   }
245799e37695SRavitheja Addepally 
245899e37695SRavitheja Addepally   return error;
245999e37695SRavitheja Addepally }
246099e37695SRavitheja Addepally 
246199e37695SRavitheja Addepally void NativeProcessLinux::StopProcessorTracingOnProcess() {
246299e37695SRavitheja Addepally   for (auto thread_id_iter : m_pt_traced_thread_group)
246399e37695SRavitheja Addepally     m_processor_trace_monitor.erase(thread_id_iter);
246499e37695SRavitheja Addepally   m_pt_traced_thread_group.clear();
246599e37695SRavitheja Addepally   m_pt_proces_trace_id = LLDB_INVALID_UID;
246699e37695SRavitheja Addepally }
246799e37695SRavitheja Addepally 
246899e37695SRavitheja Addepally Status NativeProcessLinux::StopProcessorTracingOnThread(lldb::user_id_t traceid,
246999e37695SRavitheja Addepally                                                         lldb::tid_t thread) {
247099e37695SRavitheja Addepally   Status error;
247199e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
247299e37695SRavitheja Addepally 
247399e37695SRavitheja Addepally   if (thread == LLDB_INVALID_THREAD_ID) {
247499e37695SRavitheja Addepally     for (auto& iter : m_processor_trace_monitor) {
247599e37695SRavitheja Addepally       if (iter.second->GetTraceID() == traceid) {
247699e37695SRavitheja Addepally         // Stopping a trace instance for an individual thread
247799e37695SRavitheja Addepally         // hence there will only be one traceid that can match.
247899e37695SRavitheja Addepally         m_processor_trace_monitor.erase(iter.first);
247999e37695SRavitheja Addepally         return error;
248099e37695SRavitheja Addepally       }
248199e37695SRavitheja Addepally       LLDB_LOG(log, "Trace ID {0}", iter.second->GetTraceID());
248299e37695SRavitheja Addepally     }
248399e37695SRavitheja Addepally 
248499e37695SRavitheja Addepally     LLDB_LOG(log, "Invalid TraceID");
248599e37695SRavitheja Addepally     error.SetErrorString("invalid trace id");
248699e37695SRavitheja Addepally     return error;
248799e37695SRavitheja Addepally   }
248899e37695SRavitheja Addepally 
248999e37695SRavitheja Addepally   // thread is specified so we can use find function on the map.
249099e37695SRavitheja Addepally   const auto& iter = m_processor_trace_monitor.find(thread);
249199e37695SRavitheja Addepally   if (iter == m_processor_trace_monitor.end()) {
249299e37695SRavitheja Addepally     // thread not found in our map.
249399e37695SRavitheja Addepally     LLDB_LOG(log, "thread not being traced");
249499e37695SRavitheja Addepally     error.SetErrorString("tracing not active for this thread");
249599e37695SRavitheja Addepally     return error;
249699e37695SRavitheja Addepally   }
249799e37695SRavitheja Addepally   if (iter->second->GetTraceID() != traceid) {
249899e37695SRavitheja Addepally     // traceid did not match so it has to be invalid.
249999e37695SRavitheja Addepally     LLDB_LOG(log, "Invalid TraceID");
250099e37695SRavitheja Addepally     error.SetErrorString("invalid trace id");
250199e37695SRavitheja Addepally     return error;
250299e37695SRavitheja Addepally   }
250399e37695SRavitheja Addepally 
250499e37695SRavitheja Addepally   LLDB_LOG(log, "UID - {0} , Thread -{1}", traceid, thread);
250599e37695SRavitheja Addepally 
250699e37695SRavitheja Addepally   if (traceid == m_pt_proces_trace_id) {
250799e37695SRavitheja Addepally     // traceid maps to the whole process so we have to erase it from the
250899e37695SRavitheja Addepally     // thread group.
250999e37695SRavitheja Addepally     LLDB_LOG(log, "traceid maps to process");
251099e37695SRavitheja Addepally     m_pt_traced_thread_group.erase(thread);
251199e37695SRavitheja Addepally   }
251299e37695SRavitheja Addepally   m_processor_trace_monitor.erase(iter);
251399e37695SRavitheja Addepally 
251499e37695SRavitheja Addepally   return error;
251599e37695SRavitheja Addepally }
2516