1af245d11STodd Fiala //===-- NativeProcessLinux.cpp -------------------------------- -*- C++ -*-===//
2af245d11STodd Fiala //
3af245d11STodd Fiala //                     The LLVM Compiler Infrastructure
4af245d11STodd Fiala //
5af245d11STodd Fiala // This file is distributed under the University of Illinois Open Source
6af245d11STodd Fiala // License. See LICENSE.TXT for details.
7af245d11STodd Fiala //
8af245d11STodd Fiala //===----------------------------------------------------------------------===//
9af245d11STodd Fiala 
10af245d11STodd Fiala #include "NativeProcessLinux.h"
11af245d11STodd Fiala 
12af245d11STodd Fiala // C Includes
13af245d11STodd Fiala #include <errno.h>
14af245d11STodd Fiala #include <stdint.h>
15b9c1b51eSKate Stone #include <string.h>
16af245d11STodd Fiala #include <unistd.h>
17af245d11STodd Fiala 
18af245d11STodd Fiala // C++ Includes
19af245d11STodd Fiala #include <fstream>
20df7c6995SPavel Labath #include <mutex>
21c076559aSPavel Labath #include <sstream>
22af245d11STodd Fiala #include <string>
235b981ab9SPavel Labath #include <unordered_map>
24af245d11STodd Fiala 
25af245d11STodd Fiala // Other libraries and framework includes
26d8c338d4STamas Berghammer #include "lldb/Core/EmulateInstruction.h"
276edef204SOleksiy Vyalov #include "lldb/Core/ModuleSpec.h"
28af245d11STodd Fiala #include "lldb/Host/Host.h"
295ad891f7SPavel Labath #include "lldb/Host/HostProcess.h"
3024ae6294SZachary Turner #include "lldb/Host/PseudoTerminal.h"
3139de3110SZachary Turner #include "lldb/Host/ThreadLauncher.h"
322a86b555SPavel Labath #include "lldb/Host/common/NativeBreakpoint.h"
332a86b555SPavel Labath #include "lldb/Host/common/NativeRegisterContext.h"
344ee1c952SPavel Labath #include "lldb/Host/linux/Ptrace.h"
354ee1c952SPavel Labath #include "lldb/Host/linux/Uio.h"
36816ae4b0SKamil Rytarowski #include "lldb/Host/posix/ProcessLauncherPosixFork.h"
372a86b555SPavel Labath #include "lldb/Symbol/ObjectFile.h"
3890aff47cSZachary Turner #include "lldb/Target/Process.h"
39af245d11STodd Fiala #include "lldb/Target/ProcessLaunchInfo.h"
405b981ab9SPavel Labath #include "lldb/Target/Target.h"
41c16f5dcaSChaoren Lin #include "lldb/Utility/LLDBAssert.h"
42d821c997SPavel Labath #include "lldb/Utility/RegisterValue.h"
43d821c997SPavel Labath #include "lldb/Utility/State.h"
4497206d57SZachary Turner #include "lldb/Utility/Status.h"
45f805e190SPavel Labath #include "lldb/Utility/StringExtractor.h"
4610c41f37SPavel Labath #include "llvm/Support/Errno.h"
4710c41f37SPavel Labath #include "llvm/Support/FileSystem.h"
4810c41f37SPavel Labath #include "llvm/Support/Threading.h"
49af245d11STodd Fiala 
50af245d11STodd Fiala #include "NativeThreadLinux.h"
51b9c1b51eSKate Stone #include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
521e209fccSTamas Berghammer #include "Procfs.h"
53cacde7dfSTodd Fiala 
54d858487eSTamas Berghammer #include <linux/unistd.h>
55d858487eSTamas Berghammer #include <sys/socket.h>
56df7c6995SPavel Labath #include <sys/syscall.h>
57d858487eSTamas Berghammer #include <sys/types.h>
58d858487eSTamas Berghammer #include <sys/user.h>
59d858487eSTamas Berghammer #include <sys/wait.h>
60d858487eSTamas Berghammer 
61af245d11STodd Fiala // Support hardware breakpoints in case it has not been defined
62af245d11STodd Fiala #ifndef TRAP_HWBKPT
63af245d11STodd Fiala #define TRAP_HWBKPT 4
64af245d11STodd Fiala #endif
65af245d11STodd Fiala 
667cb18bf5STamas Berghammer using namespace lldb;
677cb18bf5STamas Berghammer using namespace lldb_private;
68db264a6dSTamas Berghammer using namespace lldb_private::process_linux;
697cb18bf5STamas Berghammer using namespace llvm;
707cb18bf5STamas Berghammer 
71af245d11STodd Fiala // Private bits we only need internally.
72df7c6995SPavel Labath 
73b9c1b51eSKate Stone static bool ProcessVmReadvSupported() {
74df7c6995SPavel Labath   static bool is_supported;
75c5f28e2aSKamil Rytarowski   static llvm::once_flag flag;
76df7c6995SPavel Labath 
77c5f28e2aSKamil Rytarowski   llvm::call_once(flag, [] {
78a6321a8eSPavel Labath     Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
79df7c6995SPavel Labath 
80df7c6995SPavel Labath     uint32_t source = 0x47424742;
81df7c6995SPavel Labath     uint32_t dest = 0;
82df7c6995SPavel Labath 
83df7c6995SPavel Labath     struct iovec local, remote;
84df7c6995SPavel Labath     remote.iov_base = &source;
85df7c6995SPavel Labath     local.iov_base = &dest;
86df7c6995SPavel Labath     remote.iov_len = local.iov_len = sizeof source;
87df7c6995SPavel Labath 
88b9c1b51eSKate Stone     // We shall try if cross-process-memory reads work by attempting to read a
89b9c1b51eSKate Stone     // value from our own process.
90df7c6995SPavel Labath     ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
91df7c6995SPavel Labath     is_supported = (res == sizeof(source) && source == dest);
92df7c6995SPavel Labath     if (is_supported)
93a6321a8eSPavel Labath       LLDB_LOG(log,
94a6321a8eSPavel Labath                "Detected kernel support for process_vm_readv syscall. "
95a6321a8eSPavel Labath                "Fast memory reads enabled.");
96df7c6995SPavel Labath     else
97a6321a8eSPavel Labath       LLDB_LOG(log,
98a6321a8eSPavel Labath                "syscall process_vm_readv failed (error: {0}). Fast memory "
99a6321a8eSPavel Labath                "reads disabled.",
10010c41f37SPavel Labath                llvm::sys::StrError());
101df7c6995SPavel Labath   });
102df7c6995SPavel Labath 
103df7c6995SPavel Labath   return is_supported;
104df7c6995SPavel Labath }
105df7c6995SPavel Labath 
106b9c1b51eSKate Stone namespace {
107b9c1b51eSKate Stone void MaybeLogLaunchInfo(const ProcessLaunchInfo &info) {
108a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1094abe5d69SPavel Labath   if (!log)
1104abe5d69SPavel Labath     return;
1114abe5d69SPavel Labath 
1124abe5d69SPavel Labath   if (const FileAction *action = info.GetFileActionForFD(STDIN_FILENO))
113a6321a8eSPavel Labath     LLDB_LOG(log, "setting STDIN to '{0}'", action->GetFileSpec());
1144abe5d69SPavel Labath   else
115a6321a8eSPavel Labath     LLDB_LOG(log, "leaving STDIN as is");
1164abe5d69SPavel Labath 
1174abe5d69SPavel Labath   if (const FileAction *action = info.GetFileActionForFD(STDOUT_FILENO))
118a6321a8eSPavel Labath     LLDB_LOG(log, "setting STDOUT to '{0}'", action->GetFileSpec());
1194abe5d69SPavel Labath   else
120a6321a8eSPavel Labath     LLDB_LOG(log, "leaving STDOUT as is");
1214abe5d69SPavel Labath 
1224abe5d69SPavel Labath   if (const FileAction *action = info.GetFileActionForFD(STDERR_FILENO))
123a6321a8eSPavel Labath     LLDB_LOG(log, "setting STDERR to '{0}'", action->GetFileSpec());
1244abe5d69SPavel Labath   else
125a6321a8eSPavel Labath     LLDB_LOG(log, "leaving STDERR as is");
1264abe5d69SPavel Labath 
1274abe5d69SPavel Labath   int i = 0;
128b9c1b51eSKate Stone   for (const char **args = info.GetArguments().GetConstArgumentVector(); *args;
129b9c1b51eSKate Stone        ++args, ++i)
130a6321a8eSPavel Labath     LLDB_LOG(log, "arg {0}: '{1}'", i, *args);
1314abe5d69SPavel Labath }
1324abe5d69SPavel Labath 
133b9c1b51eSKate Stone void DisplayBytes(StreamString &s, void *bytes, uint32_t count) {
134af245d11STodd Fiala   uint8_t *ptr = (uint8_t *)bytes;
135af245d11STodd Fiala   const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
136b9c1b51eSKate Stone   for (uint32_t i = 0; i < loop_count; i++) {
137af245d11STodd Fiala     s.Printf("[%x]", *ptr);
138af245d11STodd Fiala     ptr++;
139af245d11STodd Fiala   }
140af245d11STodd Fiala }
141af245d11STodd Fiala 
142b9c1b51eSKate Stone void PtraceDisplayBytes(int &req, void *data, size_t data_size) {
143aafe053cSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
144a6321a8eSPavel Labath   if (!log)
145a6321a8eSPavel Labath     return;
146af245d11STodd Fiala   StreamString buf;
147af245d11STodd Fiala 
148b9c1b51eSKate Stone   switch (req) {
149b9c1b51eSKate Stone   case PTRACE_POKETEXT: {
150af245d11STodd Fiala     DisplayBytes(buf, &data, 8);
151aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_POKETEXT {0}", buf.GetData());
152af245d11STodd Fiala     break;
153af245d11STodd Fiala   }
154b9c1b51eSKate Stone   case PTRACE_POKEDATA: {
155af245d11STodd Fiala     DisplayBytes(buf, &data, 8);
156aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_POKEDATA {0}", buf.GetData());
157af245d11STodd Fiala     break;
158af245d11STodd Fiala   }
159b9c1b51eSKate Stone   case PTRACE_POKEUSER: {
160af245d11STodd Fiala     DisplayBytes(buf, &data, 8);
161aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_POKEUSER {0}", buf.GetData());
162af245d11STodd Fiala     break;
163af245d11STodd Fiala   }
164b9c1b51eSKate Stone   case PTRACE_SETREGS: {
165af245d11STodd Fiala     DisplayBytes(buf, data, data_size);
166aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_SETREGS {0}", buf.GetData());
167af245d11STodd Fiala     break;
168af245d11STodd Fiala   }
169b9c1b51eSKate Stone   case PTRACE_SETFPREGS: {
170af245d11STodd Fiala     DisplayBytes(buf, data, data_size);
171aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_SETFPREGS {0}", buf.GetData());
172af245d11STodd Fiala     break;
173af245d11STodd Fiala   }
174b9c1b51eSKate Stone   case PTRACE_SETSIGINFO: {
175af245d11STodd Fiala     DisplayBytes(buf, data, sizeof(siginfo_t));
176aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_SETSIGINFO {0}", buf.GetData());
177af245d11STodd Fiala     break;
178af245d11STodd Fiala   }
179b9c1b51eSKate Stone   case PTRACE_SETREGSET: {
18011edb4eeSPavel Labath     // Extract iov_base from data, which is a pointer to the struct iovec
181af245d11STodd Fiala     DisplayBytes(buf, *(void **)data, data_size);
182aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_SETREGSET {0}", buf.GetData());
183af245d11STodd Fiala     break;
184af245d11STodd Fiala   }
185b9c1b51eSKate Stone   default: {}
186af245d11STodd Fiala   }
187af245d11STodd Fiala }
188af245d11STodd Fiala 
18919cbe96aSPavel Labath static constexpr unsigned k_ptrace_word_size = sizeof(void *);
190b9c1b51eSKate Stone static_assert(sizeof(long) >= k_ptrace_word_size,
191b9c1b51eSKate Stone               "Size of long must be larger than ptrace word size");
1921107b5a5SPavel Labath } // end of anonymous namespace
1931107b5a5SPavel Labath 
194bd7cbc5aSPavel Labath // Simple helper function to ensure flags are enabled on the given file
195bd7cbc5aSPavel Labath // descriptor.
19697206d57SZachary Turner static Status EnsureFDFlags(int fd, int flags) {
19797206d57SZachary Turner   Status error;
198bd7cbc5aSPavel Labath 
199bd7cbc5aSPavel Labath   int status = fcntl(fd, F_GETFL);
200b9c1b51eSKate Stone   if (status == -1) {
201bd7cbc5aSPavel Labath     error.SetErrorToErrno();
202bd7cbc5aSPavel Labath     return error;
203bd7cbc5aSPavel Labath   }
204bd7cbc5aSPavel Labath 
205b9c1b51eSKate Stone   if (fcntl(fd, F_SETFL, status | flags) == -1) {
206bd7cbc5aSPavel Labath     error.SetErrorToErrno();
207bd7cbc5aSPavel Labath     return error;
208bd7cbc5aSPavel Labath   }
209bd7cbc5aSPavel Labath 
210bd7cbc5aSPavel Labath   return error;
211bd7cbc5aSPavel Labath }
212bd7cbc5aSPavel Labath 
213af245d11STodd Fiala // -----------------------------------------------------------------------------
214af245d11STodd Fiala // Public Static Methods
215af245d11STodd Fiala // -----------------------------------------------------------------------------
216af245d11STodd Fiala 
21782abefa4SPavel Labath llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
21896e600fcSPavel Labath NativeProcessLinux::Factory::Launch(ProcessLaunchInfo &launch_info,
21996e600fcSPavel Labath                                     NativeDelegate &native_delegate,
22096e600fcSPavel Labath                                     MainLoop &mainloop) const {
221a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
222af245d11STodd Fiala 
22396e600fcSPavel Labath   MaybeLogLaunchInfo(launch_info);
224af245d11STodd Fiala 
22596e600fcSPavel Labath   Status status;
22696e600fcSPavel Labath   ::pid_t pid = ProcessLauncherPosixFork()
22796e600fcSPavel Labath                     .LaunchProcess(launch_info, status)
22896e600fcSPavel Labath                     .GetProcessId();
22996e600fcSPavel Labath   LLDB_LOG(log, "pid = {0:x}", pid);
23096e600fcSPavel Labath   if (status.Fail()) {
23196e600fcSPavel Labath     LLDB_LOG(log, "failed to launch process: {0}", status);
23296e600fcSPavel Labath     return status.ToError();
233af245d11STodd Fiala   }
234af245d11STodd Fiala 
23596e600fcSPavel Labath   // Wait for the child process to trap on its call to execve.
23696e600fcSPavel Labath   int wstatus;
23796e600fcSPavel Labath   ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0);
23896e600fcSPavel Labath   assert(wpid == pid);
23996e600fcSPavel Labath   (void)wpid;
24096e600fcSPavel Labath   if (!WIFSTOPPED(wstatus)) {
24196e600fcSPavel Labath     LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}",
24296e600fcSPavel Labath              WaitStatus::Decode(wstatus));
24396e600fcSPavel Labath     return llvm::make_error<StringError>("Could not sync with inferior process",
24496e600fcSPavel Labath                                          llvm::inconvertibleErrorCode());
24596e600fcSPavel Labath   }
24696e600fcSPavel Labath   LLDB_LOG(log, "inferior started, now in stopped state");
247af245d11STodd Fiala 
24836e82208SPavel Labath   ProcessInstanceInfo Info;
24936e82208SPavel Labath   if (!Host::GetProcessInfo(pid, Info)) {
25036e82208SPavel Labath     return llvm::make_error<StringError>("Cannot get process architecture",
25136e82208SPavel Labath                                          llvm::inconvertibleErrorCode());
25236e82208SPavel Labath   }
25396e600fcSPavel Labath 
25496e600fcSPavel Labath   // Set the architecture to the exe architecture.
25596e600fcSPavel Labath   LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid,
25636e82208SPavel Labath            Info.GetArchitecture().GetArchitectureName());
25796e600fcSPavel Labath 
25896e600fcSPavel Labath   status = SetDefaultPtraceOpts(pid);
25996e600fcSPavel Labath   if (status.Fail()) {
26096e600fcSPavel Labath     LLDB_LOG(log, "failed to set default ptrace options: {0}", status);
26196e600fcSPavel Labath     return status.ToError();
262af245d11STodd Fiala   }
263af245d11STodd Fiala 
26482abefa4SPavel Labath   return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
26596e600fcSPavel Labath       pid, launch_info.GetPTY().ReleaseMasterFileDescriptor(), native_delegate,
26636e82208SPavel Labath       Info.GetArchitecture(), mainloop, {pid}));
267af245d11STodd Fiala }
268af245d11STodd Fiala 
26982abefa4SPavel Labath llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
27082abefa4SPavel Labath NativeProcessLinux::Factory::Attach(
271b9c1b51eSKate Stone     lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
27296e600fcSPavel Labath     MainLoop &mainloop) const {
273a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
274a6321a8eSPavel Labath   LLDB_LOG(log, "pid = {0:x}", pid);
275af245d11STodd Fiala 
276af245d11STodd Fiala   // Retrieve the architecture for the running process.
27736e82208SPavel Labath   ProcessInstanceInfo Info;
27836e82208SPavel Labath   if (!Host::GetProcessInfo(pid, Info)) {
27936e82208SPavel Labath     return llvm::make_error<StringError>("Cannot get process architecture",
28036e82208SPavel Labath                                          llvm::inconvertibleErrorCode());
28136e82208SPavel Labath   }
282af245d11STodd Fiala 
28396e600fcSPavel Labath   auto tids_or = NativeProcessLinux::Attach(pid);
28496e600fcSPavel Labath   if (!tids_or)
28596e600fcSPavel Labath     return tids_or.takeError();
286af245d11STodd Fiala 
28782abefa4SPavel Labath   return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
28836e82208SPavel Labath       pid, -1, native_delegate, Info.GetArchitecture(), mainloop, *tids_or));
289af245d11STodd Fiala }
290af245d11STodd Fiala 
291af245d11STodd Fiala // -----------------------------------------------------------------------------
292af245d11STodd Fiala // Public Instance Methods
293af245d11STodd Fiala // -----------------------------------------------------------------------------
294af245d11STodd Fiala 
29596e600fcSPavel Labath NativeProcessLinux::NativeProcessLinux(::pid_t pid, int terminal_fd,
29696e600fcSPavel Labath                                        NativeDelegate &delegate,
29782abefa4SPavel Labath                                        const ArchSpec &arch, MainLoop &mainloop,
29882abefa4SPavel Labath                                        llvm::ArrayRef<::pid_t> tids)
29996e600fcSPavel Labath     : NativeProcessProtocol(pid, terminal_fd, delegate), m_arch(arch) {
300b9c1b51eSKate Stone   if (m_terminal_fd != -1) {
30196e600fcSPavel Labath     Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
30296e600fcSPavel Labath     assert(status.Success());
3035ad891f7SPavel Labath   }
304af245d11STodd Fiala 
30596e600fcSPavel Labath   Status status;
30696e600fcSPavel Labath   m_sigchld_handle = mainloop.RegisterSignal(
30796e600fcSPavel Labath       SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status);
30896e600fcSPavel Labath   assert(m_sigchld_handle && status.Success());
30996e600fcSPavel Labath 
31096e600fcSPavel Labath   for (const auto &tid : tids) {
311a5be48b3SPavel Labath     NativeThreadLinux &thread = AddThread(tid);
312a5be48b3SPavel Labath     thread.SetStoppedBySignal(SIGSTOP);
313a5be48b3SPavel Labath     ThreadWasCreated(thread);
314af245d11STodd Fiala   }
315af245d11STodd Fiala 
31696e600fcSPavel Labath   // Let our process instance know the thread has stopped.
31796e600fcSPavel Labath   SetCurrentThreadID(tids[0]);
31896e600fcSPavel Labath   SetState(StateType::eStateStopped, false);
31996e600fcSPavel Labath 
32096e600fcSPavel Labath   // Proccess any signals we received before installing our handler
32196e600fcSPavel Labath   SigchldHandler();
32296e600fcSPavel Labath }
32396e600fcSPavel Labath 
32496e600fcSPavel Labath llvm::Expected<std::vector<::pid_t>> NativeProcessLinux::Attach(::pid_t pid) {
325a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
326af245d11STodd Fiala 
32796e600fcSPavel Labath   Status status;
328b9c1b51eSKate Stone   // Use a map to keep track of the threads which we have attached/need to
329b9c1b51eSKate Stone   // attach.
330af245d11STodd Fiala   Host::TidMap tids_to_attach;
331b9c1b51eSKate Stone   while (Host::FindProcessThreads(pid, tids_to_attach)) {
332af245d11STodd Fiala     for (Host::TidMap::iterator it = tids_to_attach.begin();
333b9c1b51eSKate Stone          it != tids_to_attach.end();) {
334b9c1b51eSKate Stone       if (it->second == false) {
335af245d11STodd Fiala         lldb::tid_t tid = it->first;
336af245d11STodd Fiala 
337af245d11STodd Fiala         // Attach to the requested process.
338af245d11STodd Fiala         // An attach will cause the thread to stop with a SIGSTOP.
33996e600fcSPavel Labath         if ((status = PtraceWrapper(PTRACE_ATTACH, tid)).Fail()) {
34005097246SAdrian Prantl           // No such thread. The thread may have exited. More error handling
34105097246SAdrian Prantl           // may be needed.
34296e600fcSPavel Labath           if (status.GetError() == ESRCH) {
343af245d11STodd Fiala             it = tids_to_attach.erase(it);
344af245d11STodd Fiala             continue;
34596e600fcSPavel Labath           }
34696e600fcSPavel Labath           return status.ToError();
347af245d11STodd Fiala         }
348af245d11STodd Fiala 
34996e600fcSPavel Labath         int wpid =
35096e600fcSPavel Labath             llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, nullptr, __WALL);
35105097246SAdrian Prantl         // Need to use __WALL otherwise we receive an error with errno=ECHLD At
35205097246SAdrian Prantl         // this point we should have a thread stopped if waitpid succeeds.
35396e600fcSPavel Labath         if (wpid < 0) {
35405097246SAdrian Prantl           // No such thread. The thread may have exited. More error handling
35505097246SAdrian Prantl           // may be needed.
356b9c1b51eSKate Stone           if (errno == ESRCH) {
357af245d11STodd Fiala             it = tids_to_attach.erase(it);
358af245d11STodd Fiala             continue;
359af245d11STodd Fiala           }
36096e600fcSPavel Labath           return llvm::errorCodeToError(
36196e600fcSPavel Labath               std::error_code(errno, std::generic_category()));
362af245d11STodd Fiala         }
363af245d11STodd Fiala 
36496e600fcSPavel Labath         if ((status = SetDefaultPtraceOpts(tid)).Fail())
36596e600fcSPavel Labath           return status.ToError();
366af245d11STodd Fiala 
367a6321a8eSPavel Labath         LLDB_LOG(log, "adding tid = {0}", tid);
368af245d11STodd Fiala         it->second = true;
369af245d11STodd Fiala       }
370af245d11STodd Fiala 
371af245d11STodd Fiala       // move the loop forward
372af245d11STodd Fiala       ++it;
373af245d11STodd Fiala     }
374af245d11STodd Fiala   }
375af245d11STodd Fiala 
37696e600fcSPavel Labath   size_t tid_count = tids_to_attach.size();
37796e600fcSPavel Labath   if (tid_count == 0)
37896e600fcSPavel Labath     return llvm::make_error<StringError>("No such process",
37996e600fcSPavel Labath                                          llvm::inconvertibleErrorCode());
380af245d11STodd Fiala 
38196e600fcSPavel Labath   std::vector<::pid_t> tids;
38296e600fcSPavel Labath   tids.reserve(tid_count);
38396e600fcSPavel Labath   for (const auto &p : tids_to_attach)
38496e600fcSPavel Labath     tids.push_back(p.first);
38596e600fcSPavel Labath   return std::move(tids);
386af245d11STodd Fiala }
387af245d11STodd Fiala 
38897206d57SZachary Turner Status NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid) {
389af245d11STodd Fiala   long ptrace_opts = 0;
390af245d11STodd Fiala 
391af245d11STodd Fiala   // Have the child raise an event on exit.  This is used to keep the child in
392af245d11STodd Fiala   // limbo until it is destroyed.
393af245d11STodd Fiala   ptrace_opts |= PTRACE_O_TRACEEXIT;
394af245d11STodd Fiala 
395af245d11STodd Fiala   // Have the tracer trace threads which spawn in the inferior process.
396af245d11STodd Fiala   // TODO: if we want to support tracing the inferiors' child, add the
397af245d11STodd Fiala   // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
398af245d11STodd Fiala   ptrace_opts |= PTRACE_O_TRACECLONE;
399af245d11STodd Fiala 
40005097246SAdrian Prantl   // Have the tracer notify us before execve returns (needed to disable legacy
40105097246SAdrian Prantl   // SIGTRAP generation)
402af245d11STodd Fiala   ptrace_opts |= PTRACE_O_TRACEEXEC;
403af245d11STodd Fiala 
4044a9babb2SPavel Labath   return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void *)ptrace_opts);
405af245d11STodd Fiala }
406af245d11STodd Fiala 
4071107b5a5SPavel Labath // Handles all waitpid events from the inferior process.
408b9c1b51eSKate Stone void NativeProcessLinux::MonitorCallback(lldb::pid_t pid, bool exited,
4093508fc8cSPavel Labath                                          WaitStatus status) {
410af245d11STodd Fiala   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
411af245d11STodd Fiala 
412b9c1b51eSKate Stone   // Certain activities differ based on whether the pid is the tid of the main
413b9c1b51eSKate Stone   // thread.
4141107b5a5SPavel Labath   const bool is_main_thread = (pid == GetID());
415af245d11STodd Fiala 
416af245d11STodd Fiala   // Handle when the thread exits.
417b9c1b51eSKate Stone   if (exited) {
418d8b3c1a1SPavel Labath     LLDB_LOG(log,
419d8b3c1a1SPavel Labath              "got exit signal({0}) , tid = {1} ({2} main thread), process "
420d8b3c1a1SPavel Labath              "state = {3}",
421d8b3c1a1SPavel Labath              signal, pid, is_main_thread ? "is" : "is not", GetState());
422af245d11STodd Fiala 
423af245d11STodd Fiala     // This is a thread that exited.  Ensure we're not tracking it anymore.
424d8b3c1a1SPavel Labath     StopTrackingThread(pid);
425af245d11STodd Fiala 
426b9c1b51eSKate Stone     if (is_main_thread) {
427af245d11STodd Fiala       // The main thread exited.  We're done monitoring.  Report to delegate.
4283508fc8cSPavel Labath       SetExitStatus(status, true);
429af245d11STodd Fiala 
430af245d11STodd Fiala       // Notify delegate that our process has exited.
4311107b5a5SPavel Labath       SetState(StateType::eStateExited, true);
432af245d11STodd Fiala     }
4331107b5a5SPavel Labath     return;
434af245d11STodd Fiala   }
435af245d11STodd Fiala 
436af245d11STodd Fiala   siginfo_t info;
437b9cc0c75SPavel Labath   const auto info_err = GetSignalInfo(pid, &info);
438b9cc0c75SPavel Labath   auto thread_sp = GetThreadByID(pid);
439b9cc0c75SPavel Labath 
440b9c1b51eSKate Stone   if (!thread_sp) {
44105097246SAdrian Prantl     // Normally, the only situation when we cannot find the thread is if we
44205097246SAdrian Prantl     // have just received a new thread notification. This is indicated by
443a6321a8eSPavel Labath     // GetSignalInfo() returning si_code == SI_USER and si_pid == 0
444a6321a8eSPavel Labath     LLDB_LOG(log, "received notification about an unknown tid {0}.", pid);
445b9cc0c75SPavel Labath 
446b9c1b51eSKate Stone     if (info_err.Fail()) {
447a6321a8eSPavel Labath       LLDB_LOG(log,
448a6321a8eSPavel Labath                "(tid {0}) GetSignalInfo failed ({1}). "
449a6321a8eSPavel Labath                "Ingoring this notification.",
450a6321a8eSPavel Labath                pid, info_err);
451b9cc0c75SPavel Labath       return;
452b9cc0c75SPavel Labath     }
453b9cc0c75SPavel Labath 
454a6321a8eSPavel Labath     LLDB_LOG(log, "tid {0}, si_code: {1}, si_pid: {2}", pid, info.si_code,
455a6321a8eSPavel Labath              info.si_pid);
456b9cc0c75SPavel Labath 
457a5be48b3SPavel Labath     NativeThreadLinux &thread = AddThread(pid);
45899e37695SRavitheja Addepally 
459b9cc0c75SPavel Labath     // Resume the newly created thread.
460a5be48b3SPavel Labath     ResumeThread(thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
461a5be48b3SPavel Labath     ThreadWasCreated(thread);
462b9cc0c75SPavel Labath     return;
463b9cc0c75SPavel Labath   }
464b9cc0c75SPavel Labath 
465b9cc0c75SPavel Labath   // Get details on the signal raised.
466b9c1b51eSKate Stone   if (info_err.Success()) {
467fa03ad2eSChaoren Lin     // We have retrieved the signal info.  Dispatch appropriately.
468fa03ad2eSChaoren Lin     if (info.si_signo == SIGTRAP)
469b9cc0c75SPavel Labath       MonitorSIGTRAP(info, *thread_sp);
470fa03ad2eSChaoren Lin     else
471b9cc0c75SPavel Labath       MonitorSignal(info, *thread_sp, exited);
472b9c1b51eSKate Stone   } else {
473b9c1b51eSKate Stone     if (info_err.GetError() == EINVAL) {
47405097246SAdrian Prantl       // This is a group stop reception for this tid. We can reach here if we
47505097246SAdrian Prantl       // reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the tracee,
47605097246SAdrian Prantl       // triggering the group-stop mechanism. Normally receiving these would
47705097246SAdrian Prantl       // stop the process, pending a SIGCONT. Simulating this state in a
47805097246SAdrian Prantl       // debugger is hard and is generally not needed (one use case is
47905097246SAdrian Prantl       // debugging background task being managed by a shell). For general use,
48005097246SAdrian Prantl       // it is sufficient to stop the process in a signal-delivery stop which
48105097246SAdrian Prantl       // happens before the group stop. This done by MonitorSignal and works
48205097246SAdrian Prantl       // correctly for all signals.
483a6321a8eSPavel Labath       LLDB_LOG(log,
484a6321a8eSPavel Labath                "received a group stop for pid {0} tid {1}. Transparent "
485a6321a8eSPavel Labath                "handling of group stops not supported, resuming the "
486a6321a8eSPavel Labath                "thread.",
487a6321a8eSPavel Labath                GetID(), pid);
488b9c1b51eSKate Stone       ResumeThread(*thread_sp, thread_sp->GetState(),
489b9c1b51eSKate Stone                    LLDB_INVALID_SIGNAL_NUMBER);
490b9c1b51eSKate Stone     } else {
491af245d11STodd Fiala       // ptrace(GETSIGINFO) failed (but not due to group-stop).
492af245d11STodd Fiala 
493b9c1b51eSKate Stone       // A return value of ESRCH means the thread/process is no longer on the
494a6321a8eSPavel Labath       // system, so it was killed somehow outside of our control.  Either way,
495a6321a8eSPavel Labath       // we can't do anything with it anymore.
496af245d11STodd Fiala 
497b9c1b51eSKate Stone       // Stop tracking the metadata for the thread since it's entirely off the
498b9c1b51eSKate Stone       // system now.
4991107b5a5SPavel Labath       const bool thread_found = StopTrackingThread(pid);
500af245d11STodd Fiala 
501a6321a8eSPavel Labath       LLDB_LOG(log,
502a6321a8eSPavel Labath                "GetSignalInfo failed: {0}, tid = {1}, signal = {2}, "
503a6321a8eSPavel Labath                "status = {3}, main_thread = {4}, thread_found: {5}",
504a6321a8eSPavel Labath                info_err, pid, signal, status, is_main_thread, thread_found);
505af245d11STodd Fiala 
506b9c1b51eSKate Stone       if (is_main_thread) {
507b9c1b51eSKate Stone         // Notify the delegate - our process is not available but appears to
50805097246SAdrian Prantl         // have been killed outside our control.  Is eStateExited the right
50905097246SAdrian Prantl         // exit state in this case?
5103508fc8cSPavel Labath         SetExitStatus(status, true);
5111107b5a5SPavel Labath         SetState(StateType::eStateExited, true);
512b9c1b51eSKate Stone       } else {
513b9c1b51eSKate Stone         // This thread was pulled out from underneath us.  Anything to do here?
514b9c1b51eSKate Stone         // Do we want to do an all stop?
515a6321a8eSPavel Labath         LLDB_LOG(log,
516a6321a8eSPavel Labath                  "pid {0} tid {1} non-main thread exit occurred, didn't "
517a6321a8eSPavel Labath                  "tell delegate anything since thread disappeared out "
518a6321a8eSPavel Labath                  "from underneath us",
519a6321a8eSPavel Labath                  GetID(), pid);
520af245d11STodd Fiala       }
521af245d11STodd Fiala     }
522af245d11STodd Fiala   }
523af245d11STodd Fiala }
524af245d11STodd Fiala 
525b9c1b51eSKate Stone void NativeProcessLinux::WaitForNewThread(::pid_t tid) {
526a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
527426bdf88SPavel Labath 
528a5be48b3SPavel Labath   if (GetThreadByID(tid)) {
529b9c1b51eSKate Stone     // We are already tracking the thread - we got the event on the new thread
530a5be48b3SPavel Labath     // (see MonitorSignal) before this one. We are done.
531426bdf88SPavel Labath     return;
532426bdf88SPavel Labath   }
533426bdf88SPavel Labath 
534426bdf88SPavel Labath   // The thread is not tracked yet, let's wait for it to appear.
535426bdf88SPavel Labath   int status = -1;
536a6321a8eSPavel Labath   LLDB_LOG(log,
537a6321a8eSPavel Labath            "received thread creation event for tid {0}. tid not tracked "
538a6321a8eSPavel Labath            "yet, waiting for thread to appear...",
539a6321a8eSPavel Labath            tid);
540c1a6b128SPavel Labath   ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, &status, __WALL);
541b9c1b51eSKate Stone   // Since we are waiting on a specific tid, this must be the creation event.
542a6321a8eSPavel Labath   // But let's do some checks just in case.
543426bdf88SPavel Labath   if (wait_pid != tid) {
544a6321a8eSPavel Labath     LLDB_LOG(log,
545a6321a8eSPavel Labath              "waiting for tid {0} failed. Assuming the thread has "
546a6321a8eSPavel Labath              "disappeared in the meantime",
547a6321a8eSPavel Labath              tid);
548426bdf88SPavel Labath     // The only way I know of this could happen is if the whole process was
549b9c1b51eSKate Stone     // SIGKILLed in the mean time. In any case, we can't do anything about that
550b9c1b51eSKate Stone     // now.
551426bdf88SPavel Labath     return;
552426bdf88SPavel Labath   }
553b9c1b51eSKate Stone   if (WIFEXITED(status)) {
554a6321a8eSPavel Labath     LLDB_LOG(log,
555a6321a8eSPavel Labath              "waiting for tid {0} returned an 'exited' event. Not "
556a6321a8eSPavel Labath              "tracking the thread.",
557a6321a8eSPavel Labath              tid);
558426bdf88SPavel Labath     // Also a very improbable event.
559426bdf88SPavel Labath     return;
560426bdf88SPavel Labath   }
561426bdf88SPavel Labath 
562a6321a8eSPavel Labath   LLDB_LOG(log, "pid = {0}: tracking new thread tid {1}", GetID(), tid);
563a5be48b3SPavel Labath   NativeThreadLinux &new_thread = AddThread(tid);
56499e37695SRavitheja Addepally 
565a5be48b3SPavel Labath   ResumeThread(new_thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
566a5be48b3SPavel Labath   ThreadWasCreated(new_thread);
567426bdf88SPavel Labath }
568426bdf88SPavel Labath 
569b9c1b51eSKate Stone void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info,
570b9c1b51eSKate Stone                                         NativeThreadLinux &thread) {
571a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
572b9cc0c75SPavel Labath   const bool is_main_thread = (thread.GetID() == GetID());
573af245d11STodd Fiala 
574b9cc0c75SPavel Labath   assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
575af245d11STodd Fiala 
576b9c1b51eSKate Stone   switch (info.si_code) {
577b9c1b51eSKate Stone   // TODO: these two cases are required if we want to support tracing of the
57805097246SAdrian Prantl   // inferiors' children.  We'd need this to debug a monitor. case (SIGTRAP |
57905097246SAdrian Prantl   // (PTRACE_EVENT_FORK << 8)): case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
580af245d11STodd Fiala 
581b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): {
582b9c1b51eSKate Stone     // This is the notification on the parent thread which informs us of new
58305097246SAdrian Prantl     // thread creation. We don't want to do anything with the parent thread so
58405097246SAdrian Prantl     // we just resume it. In case we want to implement "break on thread
58505097246SAdrian Prantl     // creation" functionality, we would need to stop here.
586af245d11STodd Fiala 
587af245d11STodd Fiala     unsigned long event_message = 0;
588b9c1b51eSKate Stone     if (GetEventMessage(thread.GetID(), &event_message).Fail()) {
589a6321a8eSPavel Labath       LLDB_LOG(log,
590a6321a8eSPavel Labath                "pid {0} received thread creation event but "
591a6321a8eSPavel Labath                "GetEventMessage failed so we don't know the new tid",
592a6321a8eSPavel Labath                thread.GetID());
593426bdf88SPavel Labath     } else
594426bdf88SPavel Labath       WaitForNewThread(event_message);
595af245d11STodd Fiala 
596b9cc0c75SPavel Labath     ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
597af245d11STodd Fiala     break;
598af245d11STodd Fiala   }
599af245d11STodd Fiala 
600b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): {
601a6321a8eSPavel Labath     LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP);
602a9882ceeSTodd Fiala 
6031dbc6c9cSPavel Labath     // Exec clears any pending notifications.
6040e1d729bSPavel Labath     m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
605fa03ad2eSChaoren Lin 
606b9c1b51eSKate Stone     // Remove all but the main thread here.  Linux fork creates a new process
607b9c1b51eSKate Stone     // which only copies the main thread.
608a6321a8eSPavel Labath     LLDB_LOG(log, "exec received, stop tracking all but main thread");
609a9882ceeSTodd Fiala 
610a5be48b3SPavel Labath     for (auto i = m_threads.begin(); i != m_threads.end();) {
611a5be48b3SPavel Labath       if ((*i)->GetID() == GetID())
612a5be48b3SPavel Labath         i = m_threads.erase(i);
613a5be48b3SPavel Labath       else
614a5be48b3SPavel Labath         ++i;
615a9882ceeSTodd Fiala     }
616a5be48b3SPavel Labath     assert(m_threads.size() == 1);
617a5be48b3SPavel Labath     auto *main_thread = static_cast<NativeThreadLinux *>(m_threads[0].get());
618a9882ceeSTodd Fiala 
619a5be48b3SPavel Labath     SetCurrentThreadID(main_thread->GetID());
620a5be48b3SPavel Labath     main_thread->SetStoppedByExec();
621a9882ceeSTodd Fiala 
622fa03ad2eSChaoren Lin     // Tell coordinator about about the "new" (since exec) stopped main thread.
623a5be48b3SPavel Labath     ThreadWasCreated(*main_thread);
624fa03ad2eSChaoren Lin 
625a9882ceeSTodd Fiala     // Let our delegate know we have just exec'd.
626a9882ceeSTodd Fiala     NotifyDidExec();
627a9882ceeSTodd Fiala 
628fa03ad2eSChaoren Lin     // Let the process know we're stopped.
629a5be48b3SPavel Labath     StopRunningThreads(main_thread->GetID());
630a9882ceeSTodd Fiala 
631af245d11STodd Fiala     break;
632a9882ceeSTodd Fiala   }
633af245d11STodd Fiala 
634b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): {
63505097246SAdrian Prantl     // The inferior process or one of its threads is about to exit. We don't
63605097246SAdrian Prantl     // want to do anything with the thread so we just resume it. In case we
63705097246SAdrian Prantl     // want to implement "break on thread exit" functionality, we would need to
63805097246SAdrian Prantl     // stop here.
639fa03ad2eSChaoren Lin 
640af245d11STodd Fiala     unsigned long data = 0;
641b9cc0c75SPavel Labath     if (GetEventMessage(thread.GetID(), &data).Fail())
642af245d11STodd Fiala       data = -1;
643af245d11STodd Fiala 
644a6321a8eSPavel Labath     LLDB_LOG(log,
645a6321a8eSPavel Labath              "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
646a6321a8eSPavel Labath              "WIFSIGNALED={2}, pid = {3}, main_thread = {4}",
647a6321a8eSPavel Labath              data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(),
648a6321a8eSPavel Labath              is_main_thread);
649af245d11STodd Fiala 
65075f47c3aSTodd Fiala 
65186852d36SPavel Labath     StateType state = thread.GetState();
652b9c1b51eSKate Stone     if (!StateIsRunningState(state)) {
653b9c1b51eSKate Stone       // Due to a kernel bug, we may sometimes get this stop after the inferior
654d8b3c1a1SPavel Labath       // gets a SIGKILL. This confuses our state tracking logic in
655d8b3c1a1SPavel Labath       // ResumeThread(), since normally, we should not be receiving any ptrace
65605097246SAdrian Prantl       // events while the inferior is stopped. This makes sure that the
65705097246SAdrian Prantl       // inferior is resumed and exits normally.
65886852d36SPavel Labath       state = eStateRunning;
65986852d36SPavel Labath     }
66086852d36SPavel Labath     ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
661af245d11STodd Fiala 
662af245d11STodd Fiala     break;
663af245d11STodd Fiala   }
664af245d11STodd Fiala 
665af245d11STodd Fiala   case 0:
666c16f5dcaSChaoren Lin   case TRAP_TRACE:  // We receive this on single stepping.
667c16f5dcaSChaoren Lin   case TRAP_HWBKPT: // We receive this on watchpoint hit
66886fd8e45SChaoren Lin   {
669c16f5dcaSChaoren Lin     // If a watchpoint was hit, report it
670c16f5dcaSChaoren Lin     uint32_t wp_index;
671d37349f3SPavel Labath     Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
672b9c1b51eSKate Stone         wp_index, (uintptr_t)info.si_addr);
673a6321a8eSPavel Labath     if (error.Fail())
674a6321a8eSPavel Labath       LLDB_LOG(log,
675a6321a8eSPavel Labath                "received error while checking for watchpoint hits, pid = "
676a6321a8eSPavel Labath                "{0}, error = {1}",
677a6321a8eSPavel Labath                thread.GetID(), error);
678b9c1b51eSKate Stone     if (wp_index != LLDB_INVALID_INDEX32) {
679b9cc0c75SPavel Labath       MonitorWatchpoint(thread, wp_index);
680c16f5dcaSChaoren Lin       break;
681c16f5dcaSChaoren Lin     }
682b9cc0c75SPavel Labath 
683d5ffbad2SOmair Javaid     // If a breakpoint was hit, report it
684d5ffbad2SOmair Javaid     uint32_t bp_index;
685d37349f3SPavel Labath     error = thread.GetRegisterContext().GetHardwareBreakHitIndex(
686d5ffbad2SOmair Javaid         bp_index, (uintptr_t)info.si_addr);
687d5ffbad2SOmair Javaid     if (error.Fail())
688d5ffbad2SOmair Javaid       LLDB_LOG(log, "received error while checking for hardware "
689d5ffbad2SOmair Javaid                     "breakpoint hits, pid = {0}, error = {1}",
690d5ffbad2SOmair Javaid                thread.GetID(), error);
691d5ffbad2SOmair Javaid     if (bp_index != LLDB_INVALID_INDEX32) {
692d5ffbad2SOmair Javaid       MonitorBreakpoint(thread);
693d5ffbad2SOmair Javaid       break;
694d5ffbad2SOmair Javaid     }
695d5ffbad2SOmair Javaid 
696be379e15STamas Berghammer     // Otherwise, report step over
697be379e15STamas Berghammer     MonitorTrace(thread);
698af245d11STodd Fiala     break;
699b9cc0c75SPavel Labath   }
700af245d11STodd Fiala 
701af245d11STodd Fiala   case SI_KERNEL:
70235799963SMohit K. Bhakkad #if defined __mips__
70305097246SAdrian Prantl     // For mips there is no special signal for watchpoint So we check for
70405097246SAdrian Prantl     // watchpoint in kernel trap
70535799963SMohit K. Bhakkad     {
70635799963SMohit K. Bhakkad       // If a watchpoint was hit, report it
70735799963SMohit K. Bhakkad       uint32_t wp_index;
708d37349f3SPavel Labath       Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
709b9c1b51eSKate Stone           wp_index, LLDB_INVALID_ADDRESS);
710a6321a8eSPavel Labath       if (error.Fail())
711a6321a8eSPavel Labath         LLDB_LOG(log,
712a6321a8eSPavel Labath                  "received error while checking for watchpoint hits, pid = "
713a6321a8eSPavel Labath                  "{0}, error = {1}",
714a6321a8eSPavel Labath                  thread.GetID(), error);
715b9c1b51eSKate Stone       if (wp_index != LLDB_INVALID_INDEX32) {
716b9cc0c75SPavel Labath         MonitorWatchpoint(thread, wp_index);
71735799963SMohit K. Bhakkad         break;
71835799963SMohit K. Bhakkad       }
71935799963SMohit K. Bhakkad     }
72035799963SMohit K. Bhakkad // NO BREAK
72135799963SMohit K. Bhakkad #endif
722af245d11STodd Fiala   case TRAP_BRKPT:
723b9cc0c75SPavel Labath     MonitorBreakpoint(thread);
724af245d11STodd Fiala     break;
725af245d11STodd Fiala 
726af245d11STodd Fiala   case SIGTRAP:
727af245d11STodd Fiala   case (SIGTRAP | 0x80):
728a6321a8eSPavel Labath     LLDB_LOG(
729a6321a8eSPavel Labath         log,
730a6321a8eSPavel Labath         "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",
731a6321a8eSPavel Labath         info.si_code, GetID(), thread.GetID());
732fa03ad2eSChaoren Lin 
733af245d11STodd Fiala     // Ignore these signals until we know more about them.
734b9cc0c75SPavel Labath     ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
735af245d11STodd Fiala     break;
736af245d11STodd Fiala 
737af245d11STodd Fiala   default:
73821a365baSPavel Labath     LLDB_LOG(log, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}",
739a6321a8eSPavel Labath              info.si_code, GetID(), thread.GetID());
74021a365baSPavel Labath     MonitorSignal(info, thread, false);
741af245d11STodd Fiala     break;
742af245d11STodd Fiala   }
743af245d11STodd Fiala }
744af245d11STodd Fiala 
745b9c1b51eSKate Stone void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) {
746a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
747a6321a8eSPavel Labath   LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID());
748c16f5dcaSChaoren Lin 
7490e1d729bSPavel Labath   // This thread is currently stopped.
750b9cc0c75SPavel Labath   thread.SetStoppedByTrace();
751c16f5dcaSChaoren Lin 
752b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
753c16f5dcaSChaoren Lin }
754c16f5dcaSChaoren Lin 
755b9c1b51eSKate Stone void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) {
756b9c1b51eSKate Stone   Log *log(
757b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
758a6321a8eSPavel Labath   LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID());
759c16f5dcaSChaoren Lin 
760c16f5dcaSChaoren Lin   // Mark the thread as stopped at breakpoint.
761b9cc0c75SPavel Labath   thread.SetStoppedByBreakpoint();
76297206d57SZachary Turner   Status error = FixupBreakpointPCAsNeeded(thread);
763c16f5dcaSChaoren Lin   if (error.Fail())
764a6321a8eSPavel Labath     LLDB_LOG(log, "pid = {0} fixup: {1}", thread.GetID(), error);
765d8c338d4STamas Berghammer 
766b9c1b51eSKate Stone   if (m_threads_stepping_with_breakpoint.find(thread.GetID()) !=
767b9c1b51eSKate Stone       m_threads_stepping_with_breakpoint.end())
768b9cc0c75SPavel Labath     thread.SetStoppedByTrace();
769c16f5dcaSChaoren Lin 
770b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
771c16f5dcaSChaoren Lin }
772c16f5dcaSChaoren Lin 
773b9c1b51eSKate Stone void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread,
774b9c1b51eSKate Stone                                            uint32_t wp_index) {
775b9c1b51eSKate Stone   Log *log(
776b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
777a6321a8eSPavel Labath   LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}",
778a6321a8eSPavel Labath            thread.GetID(), wp_index);
779c16f5dcaSChaoren Lin 
78005097246SAdrian Prantl   // Mark the thread as stopped at watchpoint. The address is at
78105097246SAdrian Prantl   // (lldb::addr_t)info->si_addr if we need it.
782f9077782SPavel Labath   thread.SetStoppedByWatchpoint(wp_index);
783c16f5dcaSChaoren Lin 
784b9c1b51eSKate Stone   // We need to tell all other running threads before we notify the delegate
785b9c1b51eSKate Stone   // about this stop.
786f9077782SPavel Labath   StopRunningThreads(thread.GetID());
787c16f5dcaSChaoren Lin }
788c16f5dcaSChaoren Lin 
789b9c1b51eSKate Stone void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
790b9c1b51eSKate Stone                                        NativeThreadLinux &thread, bool exited) {
791b9cc0c75SPavel Labath   const int signo = info.si_signo;
792b9cc0c75SPavel Labath   const bool is_from_llgs = info.si_pid == getpid();
793af245d11STodd Fiala 
794a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
795af245d11STodd Fiala 
796af245d11STodd Fiala   // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
79705097246SAdrian Prantl   // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a kill(2)
79805097246SAdrian Prantl   // or raise(3).  Similarly for tgkill(2) on Linux.
799af245d11STodd Fiala   //
800af245d11STodd Fiala   // IOW, user generated signals never generate what we consider to be a
801af245d11STodd Fiala   // "crash".
802af245d11STodd Fiala   //
803af245d11STodd Fiala   // Similarly, ACK signals generated by this monitor.
804af245d11STodd Fiala 
805af245d11STodd Fiala   // Handle the signal.
806a6321a8eSPavel Labath   LLDB_LOG(log,
807a6321a8eSPavel Labath            "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
808a6321a8eSPavel Labath            "waitpid pid = {4})",
809a6321a8eSPavel Labath            Host::GetSignalAsCString(signo), signo, info.si_code,
810b9cc0c75SPavel Labath            thread.GetID());
81158a2f669STodd Fiala 
81258a2f669STodd Fiala   // Check for thread stop notification.
813b9c1b51eSKate Stone   if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) {
814af245d11STodd Fiala     // This is a tgkill()-based stop.
815a6321a8eSPavel Labath     LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID());
816fa03ad2eSChaoren Lin 
81705097246SAdrian Prantl     // Check that we're not already marked with a stop reason. Note this thread
81805097246SAdrian Prantl     // really shouldn't already be marked as stopped - if we were, that would
81905097246SAdrian Prantl     // imply that the kernel signaled us with the thread stopping which we
82005097246SAdrian Prantl     // handled and marked as stopped, and that, without an intervening resume,
82105097246SAdrian Prantl     // we received another stop.  It is more likely that we are missing the
82205097246SAdrian Prantl     // marking of a run state somewhere if we find that the thread was marked
82305097246SAdrian Prantl     // as stopped.
824b9cc0c75SPavel Labath     const StateType thread_state = thread.GetState();
825b9c1b51eSKate Stone     if (!StateIsStoppedState(thread_state, false)) {
826ed89c7feSPavel Labath       // An inferior thread has stopped because of a SIGSTOP we have sent it.
827b9c1b51eSKate Stone       // Generally, these are not important stops and we don't want to report
828a6321a8eSPavel Labath       // them as they are just used to stop other threads when one thread (the
829a6321a8eSPavel Labath       // one with the *real* stop reason) hits a breakpoint (watchpoint,
83005097246SAdrian Prantl       // etc...). However, in the case of an asynchronous Interrupt(), this
83105097246SAdrian Prantl       // *is* the real stop reason, so we leave the signal intact if this is
83205097246SAdrian Prantl       // the thread that was chosen as the triggering thread.
833b9c1b51eSKate Stone       if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
834b9cc0c75SPavel Labath         if (m_pending_notification_tid == thread.GetID())
835b9cc0c75SPavel Labath           thread.SetStoppedBySignal(SIGSTOP, &info);
836ed89c7feSPavel Labath         else
837b9cc0c75SPavel Labath           thread.SetStoppedWithNoReason();
838ed89c7feSPavel Labath 
839b9cc0c75SPavel Labath         SetCurrentThreadID(thread.GetID());
8400e1d729bSPavel Labath         SignalIfAllThreadsStopped();
841b9c1b51eSKate Stone       } else {
8420e1d729bSPavel Labath         // We can end up here if stop was initiated by LLGS but by this time a
8430e1d729bSPavel Labath         // thread stop has occurred - maybe initiated by another event.
84497206d57SZachary Turner         Status error = ResumeThread(thread, thread.GetState(), 0);
845a6321a8eSPavel Labath         if (error.Fail())
846a6321a8eSPavel Labath           LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(),
847a6321a8eSPavel Labath                    error);
8480e1d729bSPavel Labath       }
849b9c1b51eSKate Stone     } else {
850a6321a8eSPavel Labath       LLDB_LOG(log,
851a6321a8eSPavel Labath                "pid {0} tid {1}, thread was already marked as a stopped "
852a6321a8eSPavel Labath                "state (state={2}), leaving stop signal as is",
8538198db30SPavel Labath                GetID(), thread.GetID(), thread_state);
8540e1d729bSPavel Labath       SignalIfAllThreadsStopped();
855af245d11STodd Fiala     }
856af245d11STodd Fiala 
85758a2f669STodd Fiala     // Done handling.
858af245d11STodd Fiala     return;
859af245d11STodd Fiala   }
860af245d11STodd Fiala 
86105097246SAdrian Prantl   // Check if debugger should stop at this signal or just ignore it and resume
86205097246SAdrian Prantl   // the inferior.
8634a705e7eSPavel Labath   if (m_signals_to_ignore.find(signo) != m_signals_to_ignore.end()) {
8644a705e7eSPavel Labath      ResumeThread(thread, thread.GetState(), signo);
8654a705e7eSPavel Labath      return;
8664a705e7eSPavel Labath   }
8674a705e7eSPavel Labath 
86886fd8e45SChaoren Lin   // This thread is stopped.
869a6321a8eSPavel Labath   LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo));
870b9cc0c75SPavel Labath   thread.SetStoppedBySignal(signo, &info);
87186fd8e45SChaoren Lin 
87286fd8e45SChaoren Lin   // Send a stop to the debugger after we get all other threads to stop.
873b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
874511e5cdcSTodd Fiala }
875af245d11STodd Fiala 
876e7708688STamas Berghammer namespace {
877e7708688STamas Berghammer 
878b9c1b51eSKate Stone struct EmulatorBaton {
879d37349f3SPavel Labath   NativeProcessLinux &m_process;
880d37349f3SPavel Labath   NativeRegisterContext &m_reg_context;
8816648fcc3SPavel Labath 
8826648fcc3SPavel Labath   // eRegisterKindDWARF -> RegsiterValue
8836648fcc3SPavel Labath   std::unordered_map<uint32_t, RegisterValue> m_register_values;
884e7708688STamas Berghammer 
885d37349f3SPavel Labath   EmulatorBaton(NativeProcessLinux &process, NativeRegisterContext &reg_context)
886b9c1b51eSKate Stone       : m_process(process), m_reg_context(reg_context) {}
887e7708688STamas Berghammer };
888e7708688STamas Berghammer 
889e7708688STamas Berghammer } // anonymous namespace
890e7708688STamas Berghammer 
891b9c1b51eSKate Stone static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
892e7708688STamas Berghammer                                  const EmulateInstruction::Context &context,
893b9c1b51eSKate Stone                                  lldb::addr_t addr, void *dst, size_t length) {
894e7708688STamas Berghammer   EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
895e7708688STamas Berghammer 
8963eb4b458SChaoren Lin   size_t bytes_read;
897d37349f3SPavel Labath   emulator_baton->m_process.ReadMemory(addr, dst, length, bytes_read);
898e7708688STamas Berghammer   return bytes_read;
899e7708688STamas Berghammer }
900e7708688STamas Berghammer 
901b9c1b51eSKate Stone static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
902e7708688STamas Berghammer                                  const RegisterInfo *reg_info,
903b9c1b51eSKate Stone                                  RegisterValue &reg_value) {
904e7708688STamas Berghammer   EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
905e7708688STamas Berghammer 
906b9c1b51eSKate Stone   auto it = emulator_baton->m_register_values.find(
907b9c1b51eSKate Stone       reg_info->kinds[eRegisterKindDWARF]);
908b9c1b51eSKate Stone   if (it != emulator_baton->m_register_values.end()) {
9096648fcc3SPavel Labath     reg_value = it->second;
9106648fcc3SPavel Labath     return true;
9116648fcc3SPavel Labath   }
9126648fcc3SPavel Labath 
91305097246SAdrian Prantl   // The emulator only fill in the dwarf regsiter numbers (and in some case the
91405097246SAdrian Prantl   // generic register numbers). Get the full register info from the register
91505097246SAdrian Prantl   // context based on the dwarf register numbers.
916b9c1b51eSKate Stone   const RegisterInfo *full_reg_info =
917d37349f3SPavel Labath       emulator_baton->m_reg_context.GetRegisterInfo(
918e7708688STamas Berghammer           eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
919e7708688STamas Berghammer 
92097206d57SZachary Turner   Status error =
921d37349f3SPavel Labath       emulator_baton->m_reg_context.ReadRegister(full_reg_info, reg_value);
9226648fcc3SPavel Labath   if (error.Success())
9236648fcc3SPavel Labath     return true;
924cdc22a88SMohit K. Bhakkad 
9256648fcc3SPavel Labath   return false;
926e7708688STamas Berghammer }
927e7708688STamas Berghammer 
928b9c1b51eSKate Stone static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
929e7708688STamas Berghammer                                   const EmulateInstruction::Context &context,
930e7708688STamas Berghammer                                   const RegisterInfo *reg_info,
931b9c1b51eSKate Stone                                   const RegisterValue &reg_value) {
932e7708688STamas Berghammer   EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
933b9c1b51eSKate Stone   emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
934b9c1b51eSKate Stone       reg_value;
935e7708688STamas Berghammer   return true;
936e7708688STamas Berghammer }
937e7708688STamas Berghammer 
938b9c1b51eSKate Stone static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
939e7708688STamas Berghammer                                   const EmulateInstruction::Context &context,
940b9c1b51eSKate Stone                                   lldb::addr_t addr, const void *dst,
941b9c1b51eSKate Stone                                   size_t length) {
942e7708688STamas Berghammer   return length;
943e7708688STamas Berghammer }
944e7708688STamas Berghammer 
945d37349f3SPavel Labath static lldb::addr_t ReadFlags(NativeRegisterContext &regsiter_context) {
946d37349f3SPavel Labath   const RegisterInfo *flags_info = regsiter_context.GetRegisterInfo(
947e7708688STamas Berghammer       eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
948d37349f3SPavel Labath   return regsiter_context.ReadRegisterAsUnsigned(flags_info,
949b9c1b51eSKate Stone                                                  LLDB_INVALID_ADDRESS);
950e7708688STamas Berghammer }
951e7708688STamas Berghammer 
95297206d57SZachary Turner Status
95397206d57SZachary Turner NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadLinux &thread) {
95497206d57SZachary Turner   Status error;
955d37349f3SPavel Labath   NativeRegisterContext& register_context = thread.GetRegisterContext();
956e7708688STamas Berghammer 
957e7708688STamas Berghammer   std::unique_ptr<EmulateInstruction> emulator_ap(
958b9c1b51eSKate Stone       EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying,
959b9c1b51eSKate Stone                                      nullptr));
960e7708688STamas Berghammer 
961e7708688STamas Berghammer   if (emulator_ap == nullptr)
96297206d57SZachary Turner     return Status("Instruction emulator not found!");
963e7708688STamas Berghammer 
964d37349f3SPavel Labath   EmulatorBaton baton(*this, register_context);
965e7708688STamas Berghammer   emulator_ap->SetBaton(&baton);
966e7708688STamas Berghammer   emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
967e7708688STamas Berghammer   emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
968e7708688STamas Berghammer   emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
969e7708688STamas Berghammer   emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
970e7708688STamas Berghammer 
971e7708688STamas Berghammer   if (!emulator_ap->ReadInstruction())
97297206d57SZachary Turner     return Status("Read instruction failed!");
973e7708688STamas Berghammer 
974b9c1b51eSKate Stone   bool emulation_result =
975b9c1b51eSKate Stone       emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
9766648fcc3SPavel Labath 
977d37349f3SPavel Labath   const RegisterInfo *reg_info_pc = register_context.GetRegisterInfo(
978b9c1b51eSKate Stone       eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
979d37349f3SPavel Labath   const RegisterInfo *reg_info_flags = register_context.GetRegisterInfo(
980b9c1b51eSKate Stone       eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
9816648fcc3SPavel Labath 
982b9c1b51eSKate Stone   auto pc_it =
983b9c1b51eSKate Stone       baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
984b9c1b51eSKate Stone   auto flags_it =
985b9c1b51eSKate Stone       baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
9866648fcc3SPavel Labath 
987e7708688STamas Berghammer   lldb::addr_t next_pc;
988e7708688STamas Berghammer   lldb::addr_t next_flags;
989b9c1b51eSKate Stone   if (emulation_result) {
990b9c1b51eSKate Stone     assert(pc_it != baton.m_register_values.end() &&
991b9c1b51eSKate Stone            "Emulation was successfull but PC wasn't updated");
9926648fcc3SPavel Labath     next_pc = pc_it->second.GetAsUInt64();
9936648fcc3SPavel Labath 
9946648fcc3SPavel Labath     if (flags_it != baton.m_register_values.end())
9956648fcc3SPavel Labath       next_flags = flags_it->second.GetAsUInt64();
996e7708688STamas Berghammer     else
997d37349f3SPavel Labath       next_flags = ReadFlags(register_context);
998b9c1b51eSKate Stone   } else if (pc_it == baton.m_register_values.end()) {
99905097246SAdrian Prantl     // Emulate instruction failed and it haven't changed PC. Advance PC with
100005097246SAdrian Prantl     // the size of the current opcode because the emulation of all
1001e7708688STamas Berghammer     // PC modifying instruction should be successful. The failure most
1002e7708688STamas Berghammer     // likely caused by a not supported instruction which don't modify PC.
1003d37349f3SPavel Labath     next_pc = register_context.GetPC() + emulator_ap->GetOpcode().GetByteSize();
1004d37349f3SPavel Labath     next_flags = ReadFlags(register_context);
1005b9c1b51eSKate Stone   } else {
1006e7708688STamas Berghammer     // The instruction emulation failed after it modified the PC. It is an
1007e7708688STamas Berghammer     // unknown error where we can't continue because the next instruction is
1008e7708688STamas Berghammer     // modifying the PC but we don't  know how.
100997206d57SZachary Turner     return Status("Instruction emulation failed unexpectedly.");
1010e7708688STamas Berghammer   }
1011e7708688STamas Berghammer 
1012b9c1b51eSKate Stone   if (m_arch.GetMachine() == llvm::Triple::arm) {
1013b9c1b51eSKate Stone     if (next_flags & 0x20) {
1014e7708688STamas Berghammer       // Thumb mode
1015e7708688STamas Berghammer       error = SetSoftwareBreakpoint(next_pc, 2);
1016b9c1b51eSKate Stone     } else {
1017e7708688STamas Berghammer       // Arm mode
1018e7708688STamas Berghammer       error = SetSoftwareBreakpoint(next_pc, 4);
1019e7708688STamas Berghammer     }
1020b9c1b51eSKate Stone   } else if (m_arch.GetMachine() == llvm::Triple::mips64 ||
1021b9c1b51eSKate Stone              m_arch.GetMachine() == llvm::Triple::mips64el ||
1022b9c1b51eSKate Stone              m_arch.GetMachine() == llvm::Triple::mips ||
1023aae0a752SEugene Zemtsov              m_arch.GetMachine() == llvm::Triple::mipsel ||
1024aae0a752SEugene Zemtsov              m_arch.GetMachine() == llvm::Triple::ppc64le)
1025cdc22a88SMohit K. Bhakkad     error = SetSoftwareBreakpoint(next_pc, 4);
1026b9c1b51eSKate Stone   else {
1027e7708688STamas Berghammer     // No size hint is given for the next breakpoint
1028e7708688STamas Berghammer     error = SetSoftwareBreakpoint(next_pc, 0);
1029e7708688STamas Berghammer   }
1030e7708688STamas Berghammer 
103105097246SAdrian Prantl   // If setting the breakpoint fails because next_pc is out of the address
103205097246SAdrian Prantl   // space, ignore it and let the debugee segfault.
103342eb6908SPavel Labath   if (error.GetError() == EIO || error.GetError() == EFAULT) {
103497206d57SZachary Turner     return Status();
103542eb6908SPavel Labath   } else if (error.Fail())
1036e7708688STamas Berghammer     return error;
1037e7708688STamas Berghammer 
1038b9cc0c75SPavel Labath   m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
1039e7708688STamas Berghammer 
104097206d57SZachary Turner   return Status();
1041e7708688STamas Berghammer }
1042e7708688STamas Berghammer 
1043b9c1b51eSKate Stone bool NativeProcessLinux::SupportHardwareSingleStepping() const {
1044b9c1b51eSKate Stone   if (m_arch.GetMachine() == llvm::Triple::arm ||
1045b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mips64 ||
1046b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mips64el ||
1047b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mips ||
1048b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mipsel)
1049cdc22a88SMohit K. Bhakkad     return false;
1050cdc22a88SMohit K. Bhakkad   return true;
1051e7708688STamas Berghammer }
1052e7708688STamas Berghammer 
105397206d57SZachary Turner Status NativeProcessLinux::Resume(const ResumeActionList &resume_actions) {
1054a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1055a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0}", GetID());
1056af245d11STodd Fiala 
1057e7708688STamas Berghammer   bool software_single_step = !SupportHardwareSingleStepping();
1058af245d11STodd Fiala 
1059b9c1b51eSKate Stone   if (software_single_step) {
1060a5be48b3SPavel Labath     for (const auto &thread : m_threads) {
1061a5be48b3SPavel Labath       assert(thread && "thread list should not contain NULL threads");
1062e7708688STamas Berghammer 
1063b9c1b51eSKate Stone       const ResumeAction *const action =
1064a5be48b3SPavel Labath           resume_actions.GetActionForThread(thread->GetID(), true);
1065e7708688STamas Berghammer       if (action == nullptr)
1066e7708688STamas Berghammer         continue;
1067e7708688STamas Berghammer 
1068b9c1b51eSKate Stone       if (action->state == eStateStepping) {
106997206d57SZachary Turner         Status error = SetupSoftwareSingleStepping(
1070a5be48b3SPavel Labath             static_cast<NativeThreadLinux &>(*thread));
1071e7708688STamas Berghammer         if (error.Fail())
1072e7708688STamas Berghammer           return error;
1073e7708688STamas Berghammer       }
1074e7708688STamas Berghammer     }
1075e7708688STamas Berghammer   }
1076e7708688STamas Berghammer 
1077a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
1078a5be48b3SPavel Labath     assert(thread && "thread list should not contain NULL threads");
1079af245d11STodd Fiala 
1080b9c1b51eSKate Stone     const ResumeAction *const action =
1081a5be48b3SPavel Labath         resume_actions.GetActionForThread(thread->GetID(), true);
10826a196ce6SChaoren Lin 
1083b9c1b51eSKate Stone     if (action == nullptr) {
1084a6321a8eSPavel Labath       LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
1085a5be48b3SPavel Labath                thread->GetID());
10866a196ce6SChaoren Lin       continue;
10876a196ce6SChaoren Lin     }
1088af245d11STodd Fiala 
1089a6321a8eSPavel Labath     LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}",
1090a5be48b3SPavel Labath              action->state, GetID(), thread->GetID());
1091af245d11STodd Fiala 
1092b9c1b51eSKate Stone     switch (action->state) {
1093af245d11STodd Fiala     case eStateRunning:
1094b9c1b51eSKate Stone     case eStateStepping: {
1095af245d11STodd Fiala       // Run the thread, possibly feeding it the signal.
1096fa03ad2eSChaoren Lin       const int signo = action->signal;
1097a5be48b3SPavel Labath       ResumeThread(static_cast<NativeThreadLinux &>(*thread), action->state,
1098b9c1b51eSKate Stone                    signo);
1099af245d11STodd Fiala       break;
1100ae29d395SChaoren Lin     }
1101af245d11STodd Fiala 
1102af245d11STodd Fiala     case eStateSuspended:
1103af245d11STodd Fiala     case eStateStopped:
1104a6321a8eSPavel Labath       llvm_unreachable("Unexpected state");
1105af245d11STodd Fiala 
1106af245d11STodd Fiala     default:
110797206d57SZachary Turner       return Status("NativeProcessLinux::%s (): unexpected state %s specified "
1108b9c1b51eSKate Stone                     "for pid %" PRIu64 ", tid %" PRIu64,
1109b9c1b51eSKate Stone                     __FUNCTION__, StateAsCString(action->state), GetID(),
1110a5be48b3SPavel Labath                     thread->GetID());
1111af245d11STodd Fiala     }
1112af245d11STodd Fiala   }
1113af245d11STodd Fiala 
111497206d57SZachary Turner   return Status();
1115af245d11STodd Fiala }
1116af245d11STodd Fiala 
111797206d57SZachary Turner Status NativeProcessLinux::Halt() {
111897206d57SZachary Turner   Status error;
1119af245d11STodd Fiala 
1120af245d11STodd Fiala   if (kill(GetID(), SIGSTOP) != 0)
1121af245d11STodd Fiala     error.SetErrorToErrno();
1122af245d11STodd Fiala 
1123af245d11STodd Fiala   return error;
1124af245d11STodd Fiala }
1125af245d11STodd Fiala 
112697206d57SZachary Turner Status NativeProcessLinux::Detach() {
112797206d57SZachary Turner   Status error;
1128af245d11STodd Fiala 
1129af245d11STodd Fiala   // Stop monitoring the inferior.
113019cbe96aSPavel Labath   m_sigchld_handle.reset();
1131af245d11STodd Fiala 
11327a9495bcSPavel Labath   // Tell ptrace to detach from the process.
11337a9495bcSPavel Labath   if (GetID() == LLDB_INVALID_PROCESS_ID)
11347a9495bcSPavel Labath     return error;
11357a9495bcSPavel Labath 
1136a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
1137a5be48b3SPavel Labath     Status e = Detach(thread->GetID());
11387a9495bcSPavel Labath     if (e.Fail())
1139b9c1b51eSKate Stone       error =
1140b9c1b51eSKate Stone           e; // Save the error, but still attempt to detach from other threads.
11417a9495bcSPavel Labath   }
11427a9495bcSPavel Labath 
114399e37695SRavitheja Addepally   m_processor_trace_monitor.clear();
114499e37695SRavitheja Addepally   m_pt_proces_trace_id = LLDB_INVALID_UID;
114599e37695SRavitheja Addepally 
1146af245d11STodd Fiala   return error;
1147af245d11STodd Fiala }
1148af245d11STodd Fiala 
114997206d57SZachary Turner Status NativeProcessLinux::Signal(int signo) {
115097206d57SZachary Turner   Status error;
1151af245d11STodd Fiala 
1152a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1153a6321a8eSPavel Labath   LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo,
1154a6321a8eSPavel Labath            Host::GetSignalAsCString(signo), GetID());
1155af245d11STodd Fiala 
1156af245d11STodd Fiala   if (kill(GetID(), signo))
1157af245d11STodd Fiala     error.SetErrorToErrno();
1158af245d11STodd Fiala 
1159af245d11STodd Fiala   return error;
1160af245d11STodd Fiala }
1161af245d11STodd Fiala 
116297206d57SZachary Turner Status NativeProcessLinux::Interrupt() {
116305097246SAdrian Prantl   // Pick a running thread (or if none, a not-dead stopped thread) as the
116405097246SAdrian Prantl   // chosen thread that will be the stop-reason thread.
1165a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1166e9547b80SChaoren Lin 
1167a5be48b3SPavel Labath   NativeThreadProtocol *running_thread = nullptr;
1168a5be48b3SPavel Labath   NativeThreadProtocol *stopped_thread = nullptr;
1169e9547b80SChaoren Lin 
1170a6321a8eSPavel Labath   LLDB_LOG(log, "selecting running thread for interrupt target");
1171a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
117205097246SAdrian Prantl     // If we have a running or stepping thread, we'll call that the target of
117305097246SAdrian Prantl     // the interrupt.
1174a5be48b3SPavel Labath     const auto thread_state = thread->GetState();
1175b9c1b51eSKate Stone     if (thread_state == eStateRunning || thread_state == eStateStepping) {
1176a5be48b3SPavel Labath       running_thread = thread.get();
1177e9547b80SChaoren Lin       break;
1178a5be48b3SPavel Labath     } else if (!stopped_thread && StateIsStoppedState(thread_state, true)) {
117905097246SAdrian Prantl       // Remember the first non-dead stopped thread.  We'll use that as a
118005097246SAdrian Prantl       // backup if there are no running threads.
1181a5be48b3SPavel Labath       stopped_thread = thread.get();
1182e9547b80SChaoren Lin     }
1183e9547b80SChaoren Lin   }
1184e9547b80SChaoren Lin 
1185a5be48b3SPavel Labath   if (!running_thread && !stopped_thread) {
118697206d57SZachary Turner     Status error("found no running/stepping or live stopped threads as target "
1187b9c1b51eSKate Stone                  "for interrupt");
1188a6321a8eSPavel Labath     LLDB_LOG(log, "skipping due to error: {0}", error);
11895830aa75STamas Berghammer 
1190e9547b80SChaoren Lin     return error;
1191e9547b80SChaoren Lin   }
1192e9547b80SChaoren Lin 
1193a5be48b3SPavel Labath   NativeThreadProtocol *deferred_signal_thread =
1194a5be48b3SPavel Labath       running_thread ? running_thread : stopped_thread;
1195e9547b80SChaoren Lin 
1196a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(),
1197a5be48b3SPavel Labath            running_thread ? "running" : "stopped",
1198a5be48b3SPavel Labath            deferred_signal_thread->GetID());
1199e9547b80SChaoren Lin 
1200a5be48b3SPavel Labath   StopRunningThreads(deferred_signal_thread->GetID());
120145f5cb31SPavel Labath 
120297206d57SZachary Turner   return Status();
1203e9547b80SChaoren Lin }
1204e9547b80SChaoren Lin 
120597206d57SZachary Turner Status NativeProcessLinux::Kill() {
1206a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1207a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0}", GetID());
1208af245d11STodd Fiala 
120997206d57SZachary Turner   Status error;
1210af245d11STodd Fiala 
1211b9c1b51eSKate Stone   switch (m_state) {
1212af245d11STodd Fiala   case StateType::eStateInvalid:
1213af245d11STodd Fiala   case StateType::eStateExited:
1214af245d11STodd Fiala   case StateType::eStateCrashed:
1215af245d11STodd Fiala   case StateType::eStateDetached:
1216af245d11STodd Fiala   case StateType::eStateUnloaded:
1217af245d11STodd Fiala     // Nothing to do - the process is already dead.
1218a6321a8eSPavel Labath     LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
12198198db30SPavel Labath              m_state);
1220af245d11STodd Fiala     return error;
1221af245d11STodd Fiala 
1222af245d11STodd Fiala   case StateType::eStateConnected:
1223af245d11STodd Fiala   case StateType::eStateAttaching:
1224af245d11STodd Fiala   case StateType::eStateLaunching:
1225af245d11STodd Fiala   case StateType::eStateStopped:
1226af245d11STodd Fiala   case StateType::eStateRunning:
1227af245d11STodd Fiala   case StateType::eStateStepping:
1228af245d11STodd Fiala   case StateType::eStateSuspended:
1229af245d11STodd Fiala     // We can try to kill a process in these states.
1230af245d11STodd Fiala     break;
1231af245d11STodd Fiala   }
1232af245d11STodd Fiala 
1233b9c1b51eSKate Stone   if (kill(GetID(), SIGKILL) != 0) {
1234af245d11STodd Fiala     error.SetErrorToErrno();
1235af245d11STodd Fiala     return error;
1236af245d11STodd Fiala   }
1237af245d11STodd Fiala 
1238af245d11STodd Fiala   return error;
1239af245d11STodd Fiala }
1240af245d11STodd Fiala 
124197206d57SZachary Turner static Status
124215930862SPavel Labath ParseMemoryRegionInfoFromProcMapsLine(llvm::StringRef &maps_line,
1243b9c1b51eSKate Stone                                       MemoryRegionInfo &memory_region_info) {
1244af245d11STodd Fiala   memory_region_info.Clear();
1245af245d11STodd Fiala 
124615930862SPavel Labath   StringExtractor line_extractor(maps_line);
1247af245d11STodd Fiala 
1248b9c1b51eSKate Stone   // Format: {address_start_hex}-{address_end_hex} perms offset  dev   inode
124905097246SAdrian Prantl   // pathname perms: rwxp   (letter is present if set, '-' if not, final
125005097246SAdrian Prantl   // character is p=private, s=shared).
1251af245d11STodd Fiala 
1252af245d11STodd Fiala   // Parse out the starting address
1253af245d11STodd Fiala   lldb::addr_t start_address = line_extractor.GetHexMaxU64(false, 0);
1254af245d11STodd Fiala 
1255af245d11STodd Fiala   // Parse out hyphen separating start and end address from range.
1256af245d11STodd Fiala   if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != '-'))
125797206d57SZachary Turner     return Status(
1258b9c1b51eSKate Stone         "malformed /proc/{pid}/maps entry, missing dash between address range");
1259af245d11STodd Fiala 
1260af245d11STodd Fiala   // Parse out the ending address
1261af245d11STodd Fiala   lldb::addr_t end_address = line_extractor.GetHexMaxU64(false, start_address);
1262af245d11STodd Fiala 
1263af245d11STodd Fiala   // Parse out the space after the address.
1264af245d11STodd Fiala   if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != ' '))
126597206d57SZachary Turner     return Status(
126697206d57SZachary Turner         "malformed /proc/{pid}/maps entry, missing space after range");
1267af245d11STodd Fiala 
1268af245d11STodd Fiala   // Save the range.
1269af245d11STodd Fiala   memory_region_info.GetRange().SetRangeBase(start_address);
1270af245d11STodd Fiala   memory_region_info.GetRange().SetRangeEnd(end_address);
1271af245d11STodd Fiala 
1272b9c1b51eSKate Stone   // Any memory region in /proc/{pid}/maps is by definition mapped into the
1273b9c1b51eSKate Stone   // process.
1274ad007563SHoward Hellyer   memory_region_info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
1275ad007563SHoward Hellyer 
1276af245d11STodd Fiala   // Parse out each permission entry.
1277af245d11STodd Fiala   if (line_extractor.GetBytesLeft() < 4)
127897206d57SZachary Turner     return Status("malformed /proc/{pid}/maps entry, missing some portion of "
1279b9c1b51eSKate Stone                   "permissions");
1280af245d11STodd Fiala 
1281af245d11STodd Fiala   // Handle read permission.
1282af245d11STodd Fiala   const char read_perm_char = line_extractor.GetChar();
1283af245d11STodd Fiala   if (read_perm_char == 'r')
1284af245d11STodd Fiala     memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eYes);
1285c73301bbSTamas Berghammer   else if (read_perm_char == '-')
1286af245d11STodd Fiala     memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1287c73301bbSTamas Berghammer   else
128897206d57SZachary Turner     return Status("unexpected /proc/{pid}/maps read permission char");
1289af245d11STodd Fiala 
1290af245d11STodd Fiala   // Handle write permission.
1291af245d11STodd Fiala   const char write_perm_char = line_extractor.GetChar();
1292af245d11STodd Fiala   if (write_perm_char == 'w')
1293af245d11STodd Fiala     memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eYes);
1294c73301bbSTamas Berghammer   else if (write_perm_char == '-')
1295af245d11STodd Fiala     memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1296c73301bbSTamas Berghammer   else
129797206d57SZachary Turner     return Status("unexpected /proc/{pid}/maps write permission char");
1298af245d11STodd Fiala 
1299af245d11STodd Fiala   // Handle execute permission.
1300af245d11STodd Fiala   const char exec_perm_char = line_extractor.GetChar();
1301af245d11STodd Fiala   if (exec_perm_char == 'x')
1302af245d11STodd Fiala     memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes);
1303c73301bbSTamas Berghammer   else if (exec_perm_char == '-')
1304af245d11STodd Fiala     memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1305c73301bbSTamas Berghammer   else
130697206d57SZachary Turner     return Status("unexpected /proc/{pid}/maps exec permission char");
1307af245d11STodd Fiala 
1308d7d69f80STamas Berghammer   line_extractor.GetChar();              // Read the private bit
1309d7d69f80STamas Berghammer   line_extractor.SkipSpaces();           // Skip the separator
1310d7d69f80STamas Berghammer   line_extractor.GetHexMaxU64(false, 0); // Read the offset
1311d7d69f80STamas Berghammer   line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1312d7d69f80STamas Berghammer   line_extractor.GetChar();              // Read the device id separator
1313d7d69f80STamas Berghammer   line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1314d7d69f80STamas Berghammer   line_extractor.SkipSpaces();           // Skip the separator
1315d7d69f80STamas Berghammer   line_extractor.GetU64(0, 10);          // Read the inode number
1316d7d69f80STamas Berghammer 
1317d7d69f80STamas Berghammer   line_extractor.SkipSpaces();
1318b9739d40SPavel Labath   const char *name = line_extractor.Peek();
1319b9739d40SPavel Labath   if (name)
1320b9739d40SPavel Labath     memory_region_info.SetName(name);
1321d7d69f80STamas Berghammer 
132297206d57SZachary Turner   return Status();
1323af245d11STodd Fiala }
1324af245d11STodd Fiala 
132597206d57SZachary Turner Status NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr,
1326b9c1b51eSKate Stone                                                MemoryRegionInfo &range_info) {
1327b9c1b51eSKate Stone   // FIXME review that the final memory region returned extends to the end of
1328b9c1b51eSKate Stone   // the virtual address space,
1329af245d11STodd Fiala   // with no perms if it is not mapped.
1330af245d11STodd Fiala 
133105097246SAdrian Prantl   // Use an approach that reads memory regions from /proc/{pid}/maps. Assume
133205097246SAdrian Prantl   // proc maps entries are in ascending order.
1333af245d11STodd Fiala   // FIXME assert if we find differently.
1334af245d11STodd Fiala 
1335b9c1b51eSKate Stone   if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
1336af245d11STodd Fiala     // We're done.
133797206d57SZachary Turner     return Status("unsupported");
1338af245d11STodd Fiala   }
1339af245d11STodd Fiala 
134097206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
1341b9c1b51eSKate Stone   if (error.Fail()) {
1342af245d11STodd Fiala     return error;
1343af245d11STodd Fiala   }
1344af245d11STodd Fiala 
1345af245d11STodd Fiala   lldb::addr_t prev_base_address = 0;
1346af245d11STodd Fiala 
1347b9c1b51eSKate Stone   // FIXME start by finding the last region that is <= target address using
1348b9c1b51eSKate Stone   // binary search.  Data is sorted.
1349af245d11STodd Fiala   // There can be a ton of regions on pthreads apps with lots of threads.
1350b9c1b51eSKate Stone   for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1351b9c1b51eSKate Stone        ++it) {
1352a6f5795aSTamas Berghammer     MemoryRegionInfo &proc_entry_info = it->first;
1353af245d11STodd Fiala 
1354af245d11STodd Fiala     // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1355b9c1b51eSKate Stone     assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
1356b9c1b51eSKate Stone            "descending /proc/pid/maps entries detected, unexpected");
1357af245d11STodd Fiala     prev_base_address = proc_entry_info.GetRange().GetRangeBase();
1358b1554311SHafiz Abid Qadeer     UNUSED_IF_ASSERT_DISABLED(prev_base_address);
1359af245d11STodd Fiala 
1360b9c1b51eSKate Stone     // If the target address comes before this entry, indicate distance to next
1361b9c1b51eSKate Stone     // region.
1362b9c1b51eSKate Stone     if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1363af245d11STodd Fiala       range_info.GetRange().SetRangeBase(load_addr);
1364b9c1b51eSKate Stone       range_info.GetRange().SetByteSize(
1365b9c1b51eSKate Stone           proc_entry_info.GetRange().GetRangeBase() - load_addr);
1366af245d11STodd Fiala       range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1367af245d11STodd Fiala       range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1368af245d11STodd Fiala       range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1369ad007563SHoward Hellyer       range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1370af245d11STodd Fiala 
1371af245d11STodd Fiala       return error;
1372b9c1b51eSKate Stone     } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1373af245d11STodd Fiala       // The target address is within the memory region we're processing here.
1374af245d11STodd Fiala       range_info = proc_entry_info;
1375af245d11STodd Fiala       return error;
1376af245d11STodd Fiala     }
1377af245d11STodd Fiala 
1378b9c1b51eSKate Stone     // The target memory address comes somewhere after the region we just
1379b9c1b51eSKate Stone     // parsed.
1380af245d11STodd Fiala   }
1381af245d11STodd Fiala 
1382b9c1b51eSKate Stone   // If we made it here, we didn't find an entry that contained the given
138305097246SAdrian Prantl   // address. Return the load_addr as start and the amount of bytes betwwen
138405097246SAdrian Prantl   // load address and the end of the memory as size.
138509839c33STamas Berghammer   range_info.GetRange().SetRangeBase(load_addr);
1386ad007563SHoward Hellyer   range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
138709839c33STamas Berghammer   range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
138809839c33STamas Berghammer   range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
138909839c33STamas Berghammer   range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1390ad007563SHoward Hellyer   range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1391af245d11STodd Fiala   return error;
1392af245d11STodd Fiala }
1393af245d11STodd Fiala 
139497206d57SZachary Turner Status NativeProcessLinux::PopulateMemoryRegionCache() {
1395a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1396a6f5795aSTamas Berghammer 
1397a6f5795aSTamas Berghammer   // If our cache is empty, pull the latest.  There should always be at least
1398a6f5795aSTamas Berghammer   // one memory region if memory region handling is supported.
1399a6f5795aSTamas Berghammer   if (!m_mem_region_cache.empty()) {
1400a6321a8eSPavel Labath     LLDB_LOG(log, "reusing {0} cached memory region entries",
1401a6321a8eSPavel Labath              m_mem_region_cache.size());
140297206d57SZachary Turner     return Status();
1403a6f5795aSTamas Berghammer   }
1404a6f5795aSTamas Berghammer 
140515930862SPavel Labath   auto BufferOrError = getProcFile(GetID(), "maps");
140615930862SPavel Labath   if (!BufferOrError) {
140715930862SPavel Labath     m_supports_mem_region = LazyBool::eLazyBoolNo;
140815930862SPavel Labath     return BufferOrError.getError();
140915930862SPavel Labath   }
141015930862SPavel Labath   StringRef Rest = BufferOrError.get()->getBuffer();
141115930862SPavel Labath   while (! Rest.empty()) {
141215930862SPavel Labath     StringRef Line;
141315930862SPavel Labath     std::tie(Line, Rest) = Rest.split('\n');
1414a6f5795aSTamas Berghammer     MemoryRegionInfo info;
141597206d57SZachary Turner     const Status parse_error =
141697206d57SZachary Turner         ParseMemoryRegionInfoFromProcMapsLine(Line, info);
141715930862SPavel Labath     if (parse_error.Fail()) {
141815930862SPavel Labath       LLDB_LOG(log, "failed to parse proc maps line '{0}': {1}", Line,
141915930862SPavel Labath                parse_error);
142015930862SPavel Labath       m_supports_mem_region = LazyBool::eLazyBoolNo;
142115930862SPavel Labath       return parse_error;
142215930862SPavel Labath     }
1423a6f5795aSTamas Berghammer     m_mem_region_cache.emplace_back(
1424a6f5795aSTamas Berghammer         info, FileSpec(info.GetName().GetCString(), true));
1425a6f5795aSTamas Berghammer   }
1426a6f5795aSTamas Berghammer 
142715930862SPavel Labath   if (m_mem_region_cache.empty()) {
1428a6f5795aSTamas Berghammer     // No entries after attempting to read them.  This shouldn't happen if
142905097246SAdrian Prantl     // /proc/{pid}/maps is supported. Assume we don't support map entries via
143005097246SAdrian Prantl     // procfs.
143115930862SPavel Labath     m_supports_mem_region = LazyBool::eLazyBoolNo;
1432a6321a8eSPavel Labath     LLDB_LOG(log,
1433a6321a8eSPavel Labath              "failed to find any procfs maps entries, assuming no support "
1434a6321a8eSPavel Labath              "for memory region metadata retrieval");
143597206d57SZachary Turner     return Status("not supported");
1436a6f5795aSTamas Berghammer   }
1437a6f5795aSTamas Berghammer 
1438a6321a8eSPavel Labath   LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps",
1439a6321a8eSPavel Labath            m_mem_region_cache.size(), GetID());
1440a6f5795aSTamas Berghammer 
1441a6f5795aSTamas Berghammer   // We support memory retrieval, remember that.
1442a6f5795aSTamas Berghammer   m_supports_mem_region = LazyBool::eLazyBoolYes;
144397206d57SZachary Turner   return Status();
1444a6f5795aSTamas Berghammer }
1445a6f5795aSTamas Berghammer 
1446b9c1b51eSKate Stone void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
1447a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1448a6321a8eSPavel Labath   LLDB_LOG(log, "newBumpId={0}", newBumpId);
1449a6321a8eSPavel Labath   LLDB_LOG(log, "clearing {0} entries from memory region cache",
1450a6321a8eSPavel Labath            m_mem_region_cache.size());
1451af245d11STodd Fiala   m_mem_region_cache.clear();
1452af245d11STodd Fiala }
1453af245d11STodd Fiala 
145497206d57SZachary Turner Status NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions,
1455b9c1b51eSKate Stone                                           lldb::addr_t &addr) {
1456af245d11STodd Fiala // FIXME implementing this requires the equivalent of
145705097246SAdrian Prantl // InferiorCallPOSIX::InferiorCallMmap, which depends on functional ThreadPlans
145805097246SAdrian Prantl // working with Native*Protocol.
1459af245d11STodd Fiala #if 1
146097206d57SZachary Turner   return Status("not implemented yet");
1461af245d11STodd Fiala #else
1462af245d11STodd Fiala   addr = LLDB_INVALID_ADDRESS;
1463af245d11STodd Fiala 
1464af245d11STodd Fiala   unsigned prot = 0;
1465af245d11STodd Fiala   if (permissions & lldb::ePermissionsReadable)
1466af245d11STodd Fiala     prot |= eMmapProtRead;
1467af245d11STodd Fiala   if (permissions & lldb::ePermissionsWritable)
1468af245d11STodd Fiala     prot |= eMmapProtWrite;
1469af245d11STodd Fiala   if (permissions & lldb::ePermissionsExecutable)
1470af245d11STodd Fiala     prot |= eMmapProtExec;
1471af245d11STodd Fiala 
1472af245d11STodd Fiala   // TODO implement this directly in NativeProcessLinux
147305097246SAdrian Prantl   // (and lift to NativeProcessPOSIX if/when that class is refactored out).
1474af245d11STodd Fiala   if (InferiorCallMmap(this, addr, 0, size, prot,
1475af245d11STodd Fiala                        eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
1476af245d11STodd Fiala     m_addr_to_mmap_size[addr] = size;
147797206d57SZachary Turner     return Status();
1478af245d11STodd Fiala   } else {
1479af245d11STodd Fiala     addr = LLDB_INVALID_ADDRESS;
148097206d57SZachary Turner     return Status("unable to allocate %" PRIu64
1481b9c1b51eSKate Stone                   " bytes of memory with permissions %s",
1482b9c1b51eSKate Stone                   size, GetPermissionsAsCString(permissions));
1483af245d11STodd Fiala   }
1484af245d11STodd Fiala #endif
1485af245d11STodd Fiala }
1486af245d11STodd Fiala 
148797206d57SZachary Turner Status NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {
1488af245d11STodd Fiala   // FIXME see comments in AllocateMemory - required lower-level
1489af245d11STodd Fiala   // bits not in place yet (ThreadPlans)
149097206d57SZachary Turner   return Status("not implemented");
1491af245d11STodd Fiala }
1492af245d11STodd Fiala 
1493b9c1b51eSKate Stone lldb::addr_t NativeProcessLinux::GetSharedLibraryInfoAddress() {
1494af245d11STodd Fiala   // punt on this for now
1495af245d11STodd Fiala   return LLDB_INVALID_ADDRESS;
1496af245d11STodd Fiala }
1497af245d11STodd Fiala 
1498b9c1b51eSKate Stone size_t NativeProcessLinux::UpdateThreads() {
149905097246SAdrian Prantl   // The NativeProcessLinux monitoring threads are always up to date with
150005097246SAdrian Prantl   // respect to thread state and they keep the thread list populated properly.
150105097246SAdrian Prantl   // All this method needs to do is return the thread count.
1502af245d11STodd Fiala   return m_threads.size();
1503af245d11STodd Fiala }
1504af245d11STodd Fiala 
150597206d57SZachary Turner Status NativeProcessLinux::GetSoftwareBreakpointPCOffset(
1506b9c1b51eSKate Stone     uint32_t &actual_opcode_size) {
1507af245d11STodd Fiala   // FIXME put this behind a breakpoint protocol class that can be
1508af245d11STodd Fiala   // set per architecture.  Need ARM, MIPS support here.
1509af245d11STodd Fiala   static const uint8_t g_i386_opcode[] = {0xCC};
1510bb00d0b6SUlrich Weigand   static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
1511af245d11STodd Fiala 
1512b9c1b51eSKate Stone   switch (m_arch.GetMachine()) {
1513af245d11STodd Fiala   case llvm::Triple::x86:
1514af245d11STodd Fiala   case llvm::Triple::x86_64:
1515af245d11STodd Fiala     actual_opcode_size = static_cast<uint32_t>(sizeof(g_i386_opcode));
151697206d57SZachary Turner     return Status();
1517af245d11STodd Fiala 
1518bb00d0b6SUlrich Weigand   case llvm::Triple::systemz:
1519bb00d0b6SUlrich Weigand     actual_opcode_size = static_cast<uint32_t>(sizeof(g_s390x_opcode));
152097206d57SZachary Turner     return Status();
1521bb00d0b6SUlrich Weigand 
1522ff7fd900STamas Berghammer   case llvm::Triple::arm:
1523ff7fd900STamas Berghammer   case llvm::Triple::aarch64:
1524e8659b5dSMohit K. Bhakkad   case llvm::Triple::mips64:
1525e8659b5dSMohit K. Bhakkad   case llvm::Triple::mips64el:
1526ce815e45SSagar Thakur   case llvm::Triple::mips:
1527ce815e45SSagar Thakur   case llvm::Triple::mipsel:
1528a3952ea7SPavel Labath   case llvm::Triple::ppc64le:
1529ff7fd900STamas Berghammer     // On these architectures the PC don't get updated for breakpoint hits
1530c60c9452SJaydeep Patil     actual_opcode_size = 0;
153197206d57SZachary Turner     return Status();
1532e8659b5dSMohit K. Bhakkad 
1533af245d11STodd Fiala   default:
1534af245d11STodd Fiala     assert(false && "CPU type not supported!");
153597206d57SZachary Turner     return Status("CPU type not supported");
1536af245d11STodd Fiala   }
1537af245d11STodd Fiala }
1538af245d11STodd Fiala 
153997206d57SZachary Turner Status NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,
1540b9c1b51eSKate Stone                                          bool hardware) {
1541af245d11STodd Fiala   if (hardware)
1542d5ffbad2SOmair Javaid     return SetHardwareBreakpoint(addr, size);
1543af245d11STodd Fiala   else
1544af245d11STodd Fiala     return SetSoftwareBreakpoint(addr, size);
1545af245d11STodd Fiala }
1546af245d11STodd Fiala 
154797206d57SZachary Turner Status NativeProcessLinux::RemoveBreakpoint(lldb::addr_t addr, bool hardware) {
1548d5ffbad2SOmair Javaid   if (hardware)
1549d5ffbad2SOmair Javaid     return RemoveHardwareBreakpoint(addr);
1550d5ffbad2SOmair Javaid   else
1551d5ffbad2SOmair Javaid     return NativeProcessProtocol::RemoveBreakpoint(addr);
1552d5ffbad2SOmair Javaid }
1553d5ffbad2SOmair Javaid 
1554*f8b825f6SPavel Labath llvm::Expected<llvm::ArrayRef<uint8_t>>
1555*f8b825f6SPavel Labath NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(size_t size_hint) {
1556be379e15STamas Berghammer   // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1557be379e15STamas Berghammer   // linux kernel does otherwise.
1558*f8b825f6SPavel Labath   static const uint8_t g_arm_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1559*f8b825f6SPavel Labath   static const uint8_t g_thumb_opcode[] = {0x01, 0xde};
156012286a27SPavel Labath 
1561*f8b825f6SPavel Labath   switch (GetArchitecture().GetMachine()) {
156212286a27SPavel Labath   case llvm::Triple::arm:
1563*f8b825f6SPavel Labath     switch (size_hint) {
156463c8be95STamas Berghammer     case 2:
1565*f8b825f6SPavel Labath       return g_thumb_opcode;
156663c8be95STamas Berghammer     case 4:
1567*f8b825f6SPavel Labath       return g_arm_opcode;
156863c8be95STamas Berghammer     default:
1569*f8b825f6SPavel Labath       return llvm::createStringError(llvm::inconvertibleErrorCode(),
1570*f8b825f6SPavel Labath                                      "Unrecognised trap opcode size hint!");
157163c8be95STamas Berghammer     }
1572af245d11STodd Fiala   default:
1573*f8b825f6SPavel Labath     return NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_hint);
1574af245d11STodd Fiala   }
1575af245d11STodd Fiala }
1576af245d11STodd Fiala 
157797206d57SZachary Turner Status NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
1578b9c1b51eSKate Stone                                       size_t &bytes_read) {
1579df7c6995SPavel Labath   if (ProcessVmReadvSupported()) {
1580b9c1b51eSKate Stone     // The process_vm_readv path is about 50 times faster than ptrace api. We
158105097246SAdrian Prantl     // want to use this syscall if it is supported.
1582df7c6995SPavel Labath 
1583df7c6995SPavel Labath     const ::pid_t pid = GetID();
1584df7c6995SPavel Labath 
1585df7c6995SPavel Labath     struct iovec local_iov, remote_iov;
1586df7c6995SPavel Labath     local_iov.iov_base = buf;
1587df7c6995SPavel Labath     local_iov.iov_len = size;
1588df7c6995SPavel Labath     remote_iov.iov_base = reinterpret_cast<void *>(addr);
1589df7c6995SPavel Labath     remote_iov.iov_len = size;
1590df7c6995SPavel Labath 
1591df7c6995SPavel Labath     bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
1592df7c6995SPavel Labath     const bool success = bytes_read == size;
1593df7c6995SPavel Labath 
1594a6321a8eSPavel Labath     Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1595a6321a8eSPavel Labath     LLDB_LOG(log,
1596a6321a8eSPavel Labath              "using process_vm_readv to read {0} bytes from inferior "
1597a6321a8eSPavel Labath              "address {1:x}: {2}",
159810c41f37SPavel Labath              size, addr, success ? "Success" : llvm::sys::StrError(errno));
1599df7c6995SPavel Labath 
1600df7c6995SPavel Labath     if (success)
160197206d57SZachary Turner       return Status();
1602a6321a8eSPavel Labath     // else the call failed for some reason, let's retry the read using ptrace
1603b9c1b51eSKate Stone     // api.
1604df7c6995SPavel Labath   }
1605df7c6995SPavel Labath 
160619cbe96aSPavel Labath   unsigned char *dst = static_cast<unsigned char *>(buf);
160719cbe96aSPavel Labath   size_t remainder;
160819cbe96aSPavel Labath   long data;
160919cbe96aSPavel Labath 
1610a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1611a6321a8eSPavel Labath   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
161219cbe96aSPavel Labath 
1613b9c1b51eSKate Stone   for (bytes_read = 0; bytes_read < size; bytes_read += remainder) {
161497206d57SZachary Turner     Status error = NativeProcessLinux::PtraceWrapper(
1615b9c1b51eSKate Stone         PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data);
1616a6321a8eSPavel Labath     if (error.Fail())
161719cbe96aSPavel Labath       return error;
161819cbe96aSPavel Labath 
161919cbe96aSPavel Labath     remainder = size - bytes_read;
162019cbe96aSPavel Labath     remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
162119cbe96aSPavel Labath 
162219cbe96aSPavel Labath     // Copy the data into our buffer
1623f6ef187bSMohit K. Bhakkad     memcpy(dst, &data, remainder);
162419cbe96aSPavel Labath 
1625a6321a8eSPavel Labath     LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
162619cbe96aSPavel Labath     addr += k_ptrace_word_size;
162719cbe96aSPavel Labath     dst += k_ptrace_word_size;
162819cbe96aSPavel Labath   }
162997206d57SZachary Turner   return Status();
1630af245d11STodd Fiala }
1631af245d11STodd Fiala 
163297206d57SZachary Turner Status NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf,
1633b9c1b51eSKate Stone                                                  size_t size,
1634b9c1b51eSKate Stone                                                  size_t &bytes_read) {
163597206d57SZachary Turner   Status error = ReadMemory(addr, buf, size, bytes_read);
1636b9c1b51eSKate Stone   if (error.Fail())
1637b9c1b51eSKate Stone     return error;
16383eb4b458SChaoren Lin   return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
16393eb4b458SChaoren Lin }
16403eb4b458SChaoren Lin 
164197206d57SZachary Turner Status NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,
1642b9c1b51eSKate Stone                                        size_t size, size_t &bytes_written) {
164319cbe96aSPavel Labath   const unsigned char *src = static_cast<const unsigned char *>(buf);
164419cbe96aSPavel Labath   size_t remainder;
164597206d57SZachary Turner   Status error;
164619cbe96aSPavel Labath 
1647a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1648a6321a8eSPavel Labath   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
164919cbe96aSPavel Labath 
1650b9c1b51eSKate Stone   for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
165119cbe96aSPavel Labath     remainder = size - bytes_written;
165219cbe96aSPavel Labath     remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
165319cbe96aSPavel Labath 
1654b9c1b51eSKate Stone     if (remainder == k_ptrace_word_size) {
165519cbe96aSPavel Labath       unsigned long data = 0;
1656f6ef187bSMohit K. Bhakkad       memcpy(&data, src, k_ptrace_word_size);
165719cbe96aSPavel Labath 
1658a6321a8eSPavel Labath       LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
1659b9c1b51eSKate Stone       error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(),
1660b9c1b51eSKate Stone                                                 (void *)addr, (void *)data);
1661a6321a8eSPavel Labath       if (error.Fail())
166219cbe96aSPavel Labath         return error;
1663b9c1b51eSKate Stone     } else {
166419cbe96aSPavel Labath       unsigned char buff[8];
166519cbe96aSPavel Labath       size_t bytes_read;
166619cbe96aSPavel Labath       error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
1667a6321a8eSPavel Labath       if (error.Fail())
166819cbe96aSPavel Labath         return error;
166919cbe96aSPavel Labath 
167019cbe96aSPavel Labath       memcpy(buff, src, remainder);
167119cbe96aSPavel Labath 
167219cbe96aSPavel Labath       size_t bytes_written_rec;
167319cbe96aSPavel Labath       error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
1674a6321a8eSPavel Labath       if (error.Fail())
167519cbe96aSPavel Labath         return error;
167619cbe96aSPavel Labath 
1677a6321a8eSPavel Labath       LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src,
1678b9c1b51eSKate Stone                *(unsigned long *)buff);
167919cbe96aSPavel Labath     }
168019cbe96aSPavel Labath 
168119cbe96aSPavel Labath     addr += k_ptrace_word_size;
168219cbe96aSPavel Labath     src += k_ptrace_word_size;
168319cbe96aSPavel Labath   }
168419cbe96aSPavel Labath   return error;
1685af245d11STodd Fiala }
1686af245d11STodd Fiala 
168797206d57SZachary Turner Status NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) {
168819cbe96aSPavel Labath   return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
1689af245d11STodd Fiala }
1690af245d11STodd Fiala 
169197206d57SZachary Turner Status NativeProcessLinux::GetEventMessage(lldb::tid_t tid,
1692b9c1b51eSKate Stone                                            unsigned long *message) {
169319cbe96aSPavel Labath   return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
1694af245d11STodd Fiala }
1695af245d11STodd Fiala 
169697206d57SZachary Turner Status NativeProcessLinux::Detach(lldb::tid_t tid) {
169797ccc294SChaoren Lin   if (tid == LLDB_INVALID_THREAD_ID)
169897206d57SZachary Turner     return Status();
169997ccc294SChaoren Lin 
170019cbe96aSPavel Labath   return PtraceWrapper(PTRACE_DETACH, tid);
1701af245d11STodd Fiala }
1702af245d11STodd Fiala 
1703b9c1b51eSKate Stone bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {
1704a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
1705a5be48b3SPavel Labath     assert(thread && "thread list should not contain NULL threads");
1706a5be48b3SPavel Labath     if (thread->GetID() == thread_id) {
1707af245d11STodd Fiala       // We have this thread.
1708af245d11STodd Fiala       return true;
1709af245d11STodd Fiala     }
1710af245d11STodd Fiala   }
1711af245d11STodd Fiala 
1712af245d11STodd Fiala   // We don't have this thread.
1713af245d11STodd Fiala   return false;
1714af245d11STodd Fiala }
1715af245d11STodd Fiala 
1716b9c1b51eSKate Stone bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) {
1717a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1718a6321a8eSPavel Labath   LLDB_LOG(log, "tid: {0})", thread_id);
17191dbc6c9cSPavel Labath 
17201dbc6c9cSPavel Labath   bool found = false;
1721b9c1b51eSKate Stone   for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
1722b9c1b51eSKate Stone     if (*it && ((*it)->GetID() == thread_id)) {
1723af245d11STodd Fiala       m_threads.erase(it);
17241dbc6c9cSPavel Labath       found = true;
17251dbc6c9cSPavel Labath       break;
1726af245d11STodd Fiala     }
1727af245d11STodd Fiala   }
1728af245d11STodd Fiala 
172999e37695SRavitheja Addepally   if (found)
173099e37695SRavitheja Addepally     StopTracingForThread(thread_id);
17319eb1ecb9SPavel Labath   SignalIfAllThreadsStopped();
17321dbc6c9cSPavel Labath   return found;
1733af245d11STodd Fiala }
1734af245d11STodd Fiala 
1735a5be48b3SPavel Labath NativeThreadLinux &NativeProcessLinux::AddThread(lldb::tid_t thread_id) {
1736a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
1737a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
1738af245d11STodd Fiala 
1739b9c1b51eSKate Stone   assert(!HasThreadNoLock(thread_id) &&
1740b9c1b51eSKate Stone          "attempted to add a thread by id that already exists");
1741af245d11STodd Fiala 
1742af245d11STodd Fiala   // If this is the first thread, save it as the current thread
1743af245d11STodd Fiala   if (m_threads.empty())
1744af245d11STodd Fiala     SetCurrentThreadID(thread_id);
1745af245d11STodd Fiala 
1746a5be48b3SPavel Labath   m_threads.push_back(llvm::make_unique<NativeThreadLinux>(*this, thread_id));
174799e37695SRavitheja Addepally 
174899e37695SRavitheja Addepally   if (m_pt_proces_trace_id != LLDB_INVALID_UID) {
174999e37695SRavitheja Addepally     auto traceMonitor = ProcessorTraceMonitor::Create(
175099e37695SRavitheja Addepally         GetID(), thread_id, m_pt_process_trace_config, true);
175199e37695SRavitheja Addepally     if (traceMonitor) {
175299e37695SRavitheja Addepally       m_pt_traced_thread_group.insert(thread_id);
175399e37695SRavitheja Addepally       m_processor_trace_monitor.insert(
175499e37695SRavitheja Addepally           std::make_pair(thread_id, std::move(*traceMonitor)));
175599e37695SRavitheja Addepally     } else {
175699e37695SRavitheja Addepally       LLDB_LOG(log, "failed to start trace on thread {0}", thread_id);
175799e37695SRavitheja Addepally       Status error(traceMonitor.takeError());
175899e37695SRavitheja Addepally       LLDB_LOG(log, "error {0}", error);
175999e37695SRavitheja Addepally     }
176099e37695SRavitheja Addepally   }
176199e37695SRavitheja Addepally 
1762a5be48b3SPavel Labath   return static_cast<NativeThreadLinux &>(*m_threads.back());
1763af245d11STodd Fiala }
1764af245d11STodd Fiala 
176597206d57SZachary Turner Status
176697206d57SZachary Turner NativeProcessLinux::FixupBreakpointPCAsNeeded(NativeThreadLinux &thread) {
1767a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_BREAKPOINTS));
1768af245d11STodd Fiala 
176997206d57SZachary Turner   Status error;
1770af245d11STodd Fiala 
1771b9c1b51eSKate Stone   // Find out the size of a breakpoint (might depend on where we are in the
1772b9c1b51eSKate Stone   // code).
1773d37349f3SPavel Labath   NativeRegisterContext &context = thread.GetRegisterContext();
1774af245d11STodd Fiala 
1775af245d11STodd Fiala   uint32_t breakpoint_size = 0;
1776b9cc0c75SPavel Labath   error = GetSoftwareBreakpointPCOffset(breakpoint_size);
1777b9c1b51eSKate Stone   if (error.Fail()) {
1778a6321a8eSPavel Labath     LLDB_LOG(log, "GetBreakpointSize() failed: {0}", error);
1779af245d11STodd Fiala     return error;
1780a6321a8eSPavel Labath   } else
1781a6321a8eSPavel Labath     LLDB_LOG(log, "breakpoint size: {0}", breakpoint_size);
1782af245d11STodd Fiala 
1783b9c1b51eSKate Stone   // First try probing for a breakpoint at a software breakpoint location: PC -
1784b9c1b51eSKate Stone   // breakpoint size.
1785d37349f3SPavel Labath   const lldb::addr_t initial_pc_addr = context.GetPCfromBreakpointLocation();
1786af245d11STodd Fiala   lldb::addr_t breakpoint_addr = initial_pc_addr;
1787b9c1b51eSKate Stone   if (breakpoint_size > 0) {
1788af245d11STodd Fiala     // Do not allow breakpoint probe to wrap around.
17893eb4b458SChaoren Lin     if (breakpoint_addr >= breakpoint_size)
17903eb4b458SChaoren Lin       breakpoint_addr -= breakpoint_size;
1791af245d11STodd Fiala   }
1792af245d11STodd Fiala 
1793af245d11STodd Fiala   // Check if we stopped because of a breakpoint.
1794af245d11STodd Fiala   NativeBreakpointSP breakpoint_sp;
1795af245d11STodd Fiala   error = m_breakpoint_list.GetBreakpoint(breakpoint_addr, breakpoint_sp);
1796b9c1b51eSKate Stone   if (!error.Success() || !breakpoint_sp) {
1797af245d11STodd Fiala     // We didn't find one at a software probe location.  Nothing to do.
1798a6321a8eSPavel Labath     LLDB_LOG(log,
1799a6321a8eSPavel Labath              "pid {0} no lldb breakpoint found at current pc with "
1800a6321a8eSPavel Labath              "adjustment: {1}",
1801a6321a8eSPavel Labath              GetID(), breakpoint_addr);
180297206d57SZachary Turner     return Status();
1803af245d11STodd Fiala   }
1804af245d11STodd Fiala 
1805af245d11STodd Fiala   // If the breakpoint is not a software breakpoint, nothing to do.
1806b9c1b51eSKate Stone   if (!breakpoint_sp->IsSoftwareBreakpoint()) {
1807a6321a8eSPavel Labath     LLDB_LOG(
1808a6321a8eSPavel Labath         log,
1809a6321a8eSPavel Labath         "pid {0} breakpoint found at {1:x}, not software, nothing to adjust",
1810a6321a8eSPavel Labath         GetID(), breakpoint_addr);
181197206d57SZachary Turner     return Status();
1812af245d11STodd Fiala   }
1813af245d11STodd Fiala 
1814af245d11STodd Fiala   //
1815af245d11STodd Fiala   // We have a software breakpoint and need to adjust the PC.
1816af245d11STodd Fiala   //
1817af245d11STodd Fiala 
1818af245d11STodd Fiala   // Sanity check.
1819b9c1b51eSKate Stone   if (breakpoint_size == 0) {
1820af245d11STodd Fiala     // Nothing to do!  How did we get here?
1821a6321a8eSPavel Labath     LLDB_LOG(log,
1822a6321a8eSPavel Labath              "pid {0} breakpoint found at {1:x}, it is software, but the "
1823a6321a8eSPavel Labath              "size is zero, nothing to do (unexpected)",
1824a6321a8eSPavel Labath              GetID(), breakpoint_addr);
182597206d57SZachary Turner     return Status();
1826af245d11STodd Fiala   }
1827af245d11STodd Fiala 
1828af245d11STodd Fiala   // Change the program counter.
1829a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0} tid {1}: changing PC from {2:x} to {3:x}", GetID(),
1830a6321a8eSPavel Labath            thread.GetID(), initial_pc_addr, breakpoint_addr);
1831af245d11STodd Fiala 
1832d37349f3SPavel Labath   error = context.SetPC(breakpoint_addr);
1833b9c1b51eSKate Stone   if (error.Fail()) {
1834a6321a8eSPavel Labath     LLDB_LOG(log, "pid {0} tid {1}: failed to set PC: {2}", GetID(),
1835a6321a8eSPavel Labath              thread.GetID(), error);
1836af245d11STodd Fiala     return error;
1837af245d11STodd Fiala   }
1838af245d11STodd Fiala 
1839af245d11STodd Fiala   return error;
1840af245d11STodd Fiala }
1841fa03ad2eSChaoren Lin 
184297206d57SZachary Turner Status NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,
1843b9c1b51eSKate Stone                                                    FileSpec &file_spec) {
184497206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
1845a6f5795aSTamas Berghammer   if (error.Fail())
1846a6f5795aSTamas Berghammer     return error;
1847a6f5795aSTamas Berghammer 
18487cb18bf5STamas Berghammer   FileSpec module_file_spec(module_path, true);
18497cb18bf5STamas Berghammer 
18507cb18bf5STamas Berghammer   file_spec.Clear();
1851a6f5795aSTamas Berghammer   for (const auto &it : m_mem_region_cache) {
1852a6f5795aSTamas Berghammer     if (it.second.GetFilename() == module_file_spec.GetFilename()) {
1853a6f5795aSTamas Berghammer       file_spec = it.second;
185497206d57SZachary Turner       return Status();
1855a6f5795aSTamas Berghammer     }
1856a6f5795aSTamas Berghammer   }
185797206d57SZachary Turner   return Status("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
18587cb18bf5STamas Berghammer                 module_file_spec.GetFilename().AsCString(), GetID());
18597cb18bf5STamas Berghammer }
1860c076559aSPavel Labath 
186197206d57SZachary Turner Status NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
1862b9c1b51eSKate Stone                                               lldb::addr_t &load_addr) {
1863783bfc8cSTamas Berghammer   load_addr = LLDB_INVALID_ADDRESS;
186497206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
1865a6f5795aSTamas Berghammer   if (error.Fail())
1866783bfc8cSTamas Berghammer     return error;
1867a6f5795aSTamas Berghammer 
1868a6f5795aSTamas Berghammer   FileSpec file(file_name, false);
1869a6f5795aSTamas Berghammer   for (const auto &it : m_mem_region_cache) {
1870a6f5795aSTamas Berghammer     if (it.second == file) {
1871a6f5795aSTamas Berghammer       load_addr = it.first.GetRange().GetRangeBase();
187297206d57SZachary Turner       return Status();
1873a6f5795aSTamas Berghammer     }
1874a6f5795aSTamas Berghammer   }
187597206d57SZachary Turner   return Status("No load address found for specified file.");
1876783bfc8cSTamas Berghammer }
1877783bfc8cSTamas Berghammer 
1878a5be48b3SPavel Labath NativeThreadLinux *NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {
1879a5be48b3SPavel Labath   return static_cast<NativeThreadLinux *>(
1880b9c1b51eSKate Stone       NativeProcessProtocol::GetThreadByID(tid));
1881f9077782SPavel Labath }
1882f9077782SPavel Labath 
188397206d57SZachary Turner Status NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,
1884b9c1b51eSKate Stone                                         lldb::StateType state, int signo) {
1885a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1886a6321a8eSPavel Labath   LLDB_LOG(log, "tid: {0}", thread.GetID());
1887c076559aSPavel Labath 
188805097246SAdrian Prantl   // Before we do the resume below, first check if we have a pending stop
188905097246SAdrian Prantl   // notification that is currently waiting for all threads to stop.  This is
189005097246SAdrian Prantl   // potentially a buggy situation since we're ostensibly waiting for threads
189105097246SAdrian Prantl   // to stop before we send out the pending notification, and here we are
189205097246SAdrian Prantl   // resuming one before we send out the pending stop notification.
1893a6321a8eSPavel Labath   if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
1894a6321a8eSPavel Labath     LLDB_LOG(log,
1895a6321a8eSPavel Labath              "about to resume tid {0} per explicit request but we have a "
1896a6321a8eSPavel Labath              "pending stop notification (tid {1}) that is actively "
1897a6321a8eSPavel Labath              "waiting for this thread to stop. Valid sequence of events?",
1898a6321a8eSPavel Labath              thread.GetID(), m_pending_notification_tid);
1899c076559aSPavel Labath   }
1900c076559aSPavel Labath 
190105097246SAdrian Prantl   // Request a resume.  We expect this to be synchronous and the system to
190205097246SAdrian Prantl   // reflect it is running after this completes.
1903b9c1b51eSKate Stone   switch (state) {
1904b9c1b51eSKate Stone   case eStateRunning: {
1905605b51b8SPavel Labath     const auto resume_result = thread.Resume(signo);
19060e1d729bSPavel Labath     if (resume_result.Success())
19070e1d729bSPavel Labath       SetState(eStateRunning, true);
19080e1d729bSPavel Labath     return resume_result;
1909c076559aSPavel Labath   }
1910b9c1b51eSKate Stone   case eStateStepping: {
1911605b51b8SPavel Labath     const auto step_result = thread.SingleStep(signo);
19120e1d729bSPavel Labath     if (step_result.Success())
19130e1d729bSPavel Labath       SetState(eStateRunning, true);
19140e1d729bSPavel Labath     return step_result;
19150e1d729bSPavel Labath   }
19160e1d729bSPavel Labath   default:
19178198db30SPavel Labath     LLDB_LOG(log, "Unhandled state {0}.", state);
19180e1d729bSPavel Labath     llvm_unreachable("Unhandled state for resume");
19190e1d729bSPavel Labath   }
1920c076559aSPavel Labath }
1921c076559aSPavel Labath 
1922c076559aSPavel Labath //===----------------------------------------------------------------------===//
1923c076559aSPavel Labath 
1924b9c1b51eSKate Stone void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {
1925a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1926a6321a8eSPavel Labath   LLDB_LOG(log, "about to process event: (triggering_tid: {0})",
1927a6321a8eSPavel Labath            triggering_tid);
1928c076559aSPavel Labath 
19290e1d729bSPavel Labath   m_pending_notification_tid = triggering_tid;
19300e1d729bSPavel Labath 
193105097246SAdrian Prantl   // Request a stop for all the thread stops that need to be stopped and are
193205097246SAdrian Prantl   // not already known to be stopped.
1933a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
1934a5be48b3SPavel Labath     if (StateIsRunningState(thread->GetState()))
1935a5be48b3SPavel Labath       static_cast<NativeThreadLinux *>(thread.get())->RequestStop();
19360e1d729bSPavel Labath   }
19370e1d729bSPavel Labath 
19380e1d729bSPavel Labath   SignalIfAllThreadsStopped();
1939a6321a8eSPavel Labath   LLDB_LOG(log, "event processing done");
1940c076559aSPavel Labath }
1941c076559aSPavel Labath 
1942b9c1b51eSKate Stone void NativeProcessLinux::SignalIfAllThreadsStopped() {
19430e1d729bSPavel Labath   if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
19440e1d729bSPavel Labath     return; // No pending notification. Nothing to do.
19450e1d729bSPavel Labath 
1946b9c1b51eSKate Stone   for (const auto &thread_sp : m_threads) {
19470e1d729bSPavel Labath     if (StateIsRunningState(thread_sp->GetState()))
19480e1d729bSPavel Labath       return; // Some threads are still running. Don't signal yet.
19490e1d729bSPavel Labath   }
19500e1d729bSPavel Labath 
19510e1d729bSPavel Labath   // We have a pending notification and all threads have stopped.
1952b9c1b51eSKate Stone   Log *log(
1953b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
19549eb1ecb9SPavel Labath 
1955b9c1b51eSKate Stone   // Clear any temporary breakpoints we used to implement software single
1956b9c1b51eSKate Stone   // stepping.
1957b9c1b51eSKate Stone   for (const auto &thread_info : m_threads_stepping_with_breakpoint) {
195897206d57SZachary Turner     Status error = RemoveBreakpoint(thread_info.second);
19599eb1ecb9SPavel Labath     if (error.Fail())
1960a6321a8eSPavel Labath       LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}",
1961a6321a8eSPavel Labath                thread_info.first, error);
19629eb1ecb9SPavel Labath   }
19639eb1ecb9SPavel Labath   m_threads_stepping_with_breakpoint.clear();
19649eb1ecb9SPavel Labath 
19659eb1ecb9SPavel Labath   // Notify the delegate about the stop
19660e1d729bSPavel Labath   SetCurrentThreadID(m_pending_notification_tid);
1967ed89c7feSPavel Labath   SetState(StateType::eStateStopped, true);
19680e1d729bSPavel Labath   m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
1969c076559aSPavel Labath }
1970c076559aSPavel Labath 
1971b9c1b51eSKate Stone void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {
1972a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1973a6321a8eSPavel Labath   LLDB_LOG(log, "tid: {0}", thread.GetID());
19741dbc6c9cSPavel Labath 
1975b9c1b51eSKate Stone   if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID &&
1976b9c1b51eSKate Stone       StateIsRunningState(thread.GetState())) {
1977b9c1b51eSKate Stone     // We will need to wait for this new thread to stop as well before firing
197805097246SAdrian Prantl     // the notification.
1979f9077782SPavel Labath     thread.RequestStop();
1980c076559aSPavel Labath   }
1981c076559aSPavel Labath }
1982068f8a7eSTamas Berghammer 
1983b9c1b51eSKate Stone void NativeProcessLinux::SigchldHandler() {
1984a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
198519cbe96aSPavel Labath   // Process all pending waitpid notifications.
1986b9c1b51eSKate Stone   while (true) {
198719cbe96aSPavel Labath     int status = -1;
1988c1a6b128SPavel Labath     ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, -1, &status,
1989c1a6b128SPavel Labath                                           __WALL | __WNOTHREAD | WNOHANG);
199019cbe96aSPavel Labath 
199119cbe96aSPavel Labath     if (wait_pid == 0)
199219cbe96aSPavel Labath       break; // We are done.
199319cbe96aSPavel Labath 
1994b9c1b51eSKate Stone     if (wait_pid == -1) {
199597206d57SZachary Turner       Status error(errno, eErrorTypePOSIX);
1996a6321a8eSPavel Labath       LLDB_LOG(log, "waitpid (-1, &status, _) failed: {0}", error);
199719cbe96aSPavel Labath       break;
199819cbe96aSPavel Labath     }
199919cbe96aSPavel Labath 
20003508fc8cSPavel Labath     WaitStatus wait_status = WaitStatus::Decode(status);
20013508fc8cSPavel Labath     bool exited = wait_status.type == WaitStatus::Exit ||
20023508fc8cSPavel Labath                   (wait_status.type == WaitStatus::Signal &&
20033508fc8cSPavel Labath                    wait_pid == static_cast<::pid_t>(GetID()));
200419cbe96aSPavel Labath 
20053508fc8cSPavel Labath     LLDB_LOG(
20063508fc8cSPavel Labath         log,
20073508fc8cSPavel Labath         "waitpid (-1, &status, _) => pid = {0}, status = {1}, exited = {2}",
20083508fc8cSPavel Labath         wait_pid, wait_status, exited);
200919cbe96aSPavel Labath 
20103508fc8cSPavel Labath     MonitorCallback(wait_pid, exited, wait_status);
201119cbe96aSPavel Labath   }
2012068f8a7eSTamas Berghammer }
2013068f8a7eSTamas Berghammer 
201405097246SAdrian Prantl // Wrapper for ptrace to catch errors and log calls. Note that ptrace sets
201505097246SAdrian Prantl // errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
201697206d57SZachary Turner Status NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
2017b9c1b51eSKate Stone                                          void *data, size_t data_size,
2018b9c1b51eSKate Stone                                          long *result) {
201997206d57SZachary Turner   Status error;
20204a9babb2SPavel Labath   long int ret;
2021068f8a7eSTamas Berghammer 
2022068f8a7eSTamas Berghammer   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2023068f8a7eSTamas Berghammer 
2024068f8a7eSTamas Berghammer   PtraceDisplayBytes(req, data, data_size);
2025068f8a7eSTamas Berghammer 
2026068f8a7eSTamas Berghammer   errno = 0;
2027068f8a7eSTamas Berghammer   if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
2028b9c1b51eSKate Stone     ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2029b9c1b51eSKate Stone                  *(unsigned int *)addr, data);
2030068f8a7eSTamas Berghammer   else
2031b9c1b51eSKate Stone     ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2032b9c1b51eSKate Stone                  addr, data);
2033068f8a7eSTamas Berghammer 
20344a9babb2SPavel Labath   if (ret == -1)
2035068f8a7eSTamas Berghammer     error.SetErrorToErrno();
2036068f8a7eSTamas Berghammer 
20374a9babb2SPavel Labath   if (result)
20384a9babb2SPavel Labath     *result = ret;
20394a9babb2SPavel Labath 
204028096200SPavel Labath   LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data,
204128096200SPavel Labath            data_size, ret);
2042068f8a7eSTamas Berghammer 
2043068f8a7eSTamas Berghammer   PtraceDisplayBytes(req, data, data_size);
2044068f8a7eSTamas Berghammer 
2045a6321a8eSPavel Labath   if (error.Fail())
2046a6321a8eSPavel Labath     LLDB_LOG(log, "ptrace() failed: {0}", error);
2047068f8a7eSTamas Berghammer 
20484a9babb2SPavel Labath   return error;
2049068f8a7eSTamas Berghammer }
205099e37695SRavitheja Addepally 
205199e37695SRavitheja Addepally llvm::Expected<ProcessorTraceMonitor &>
205299e37695SRavitheja Addepally NativeProcessLinux::LookupProcessorTraceInstance(lldb::user_id_t traceid,
205399e37695SRavitheja Addepally                                                  lldb::tid_t thread) {
205499e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
205599e37695SRavitheja Addepally   if (thread == LLDB_INVALID_THREAD_ID && traceid == m_pt_proces_trace_id) {
205699e37695SRavitheja Addepally     LLDB_LOG(log, "thread not specified: {0}", traceid);
205799e37695SRavitheja Addepally     return Status("tracing not active thread not specified").ToError();
205899e37695SRavitheja Addepally   }
205999e37695SRavitheja Addepally 
206099e37695SRavitheja Addepally   for (auto& iter : m_processor_trace_monitor) {
206199e37695SRavitheja Addepally     if (traceid == iter.second->GetTraceID() &&
206299e37695SRavitheja Addepally         (thread == iter.first || thread == LLDB_INVALID_THREAD_ID))
206399e37695SRavitheja Addepally       return *(iter.second);
206499e37695SRavitheja Addepally   }
206599e37695SRavitheja Addepally 
206699e37695SRavitheja Addepally   LLDB_LOG(log, "traceid not being traced: {0}", traceid);
206799e37695SRavitheja Addepally   return Status("tracing not active for this thread").ToError();
206899e37695SRavitheja Addepally }
206999e37695SRavitheja Addepally 
207099e37695SRavitheja Addepally Status NativeProcessLinux::GetMetaData(lldb::user_id_t traceid,
207199e37695SRavitheja Addepally                                        lldb::tid_t thread,
207299e37695SRavitheja Addepally                                        llvm::MutableArrayRef<uint8_t> &buffer,
207399e37695SRavitheja Addepally                                        size_t offset) {
207499e37695SRavitheja Addepally   TraceOptions trace_options;
207599e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
207699e37695SRavitheja Addepally   Status error;
207799e37695SRavitheja Addepally 
207899e37695SRavitheja Addepally   LLDB_LOG(log, "traceid {0}", traceid);
207999e37695SRavitheja Addepally 
208099e37695SRavitheja Addepally   auto perf_monitor = LookupProcessorTraceInstance(traceid, thread);
208199e37695SRavitheja Addepally   if (!perf_monitor) {
208299e37695SRavitheja Addepally     LLDB_LOG(log, "traceid not being traced: {0}", traceid);
208399e37695SRavitheja Addepally     buffer = buffer.slice(buffer.size());
208499e37695SRavitheja Addepally     error = perf_monitor.takeError();
208599e37695SRavitheja Addepally     return error;
208699e37695SRavitheja Addepally   }
208799e37695SRavitheja Addepally   return (*perf_monitor).ReadPerfTraceData(buffer, offset);
208899e37695SRavitheja Addepally }
208999e37695SRavitheja Addepally 
209099e37695SRavitheja Addepally Status NativeProcessLinux::GetData(lldb::user_id_t traceid, lldb::tid_t thread,
209199e37695SRavitheja Addepally                                    llvm::MutableArrayRef<uint8_t> &buffer,
209299e37695SRavitheja Addepally                                    size_t offset) {
209399e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
209499e37695SRavitheja Addepally   Status error;
209599e37695SRavitheja Addepally 
209699e37695SRavitheja Addepally   LLDB_LOG(log, "traceid {0}", traceid);
209799e37695SRavitheja Addepally 
209899e37695SRavitheja Addepally   auto perf_monitor = LookupProcessorTraceInstance(traceid, thread);
209999e37695SRavitheja Addepally   if (!perf_monitor) {
210099e37695SRavitheja Addepally     LLDB_LOG(log, "traceid not being traced: {0}", traceid);
210199e37695SRavitheja Addepally     buffer = buffer.slice(buffer.size());
210299e37695SRavitheja Addepally     error = perf_monitor.takeError();
210399e37695SRavitheja Addepally     return error;
210499e37695SRavitheja Addepally   }
210599e37695SRavitheja Addepally   return (*perf_monitor).ReadPerfTraceAux(buffer, offset);
210699e37695SRavitheja Addepally }
210799e37695SRavitheja Addepally 
210899e37695SRavitheja Addepally Status NativeProcessLinux::GetTraceConfig(lldb::user_id_t traceid,
210999e37695SRavitheja Addepally                                           TraceOptions &config) {
211099e37695SRavitheja Addepally   Status error;
211199e37695SRavitheja Addepally   if (config.getThreadID() == LLDB_INVALID_THREAD_ID &&
211299e37695SRavitheja Addepally       m_pt_proces_trace_id == traceid) {
211399e37695SRavitheja Addepally     if (m_pt_proces_trace_id == LLDB_INVALID_UID) {
211499e37695SRavitheja Addepally       error.SetErrorString("tracing not active for this process");
211599e37695SRavitheja Addepally       return error;
211699e37695SRavitheja Addepally     }
211799e37695SRavitheja Addepally     config = m_pt_process_trace_config;
211899e37695SRavitheja Addepally   } else {
211999e37695SRavitheja Addepally     auto perf_monitor =
212099e37695SRavitheja Addepally         LookupProcessorTraceInstance(traceid, config.getThreadID());
212199e37695SRavitheja Addepally     if (!perf_monitor) {
212299e37695SRavitheja Addepally       error = perf_monitor.takeError();
212399e37695SRavitheja Addepally       return error;
212499e37695SRavitheja Addepally     }
212599e37695SRavitheja Addepally     error = (*perf_monitor).GetTraceConfig(config);
212699e37695SRavitheja Addepally   }
212799e37695SRavitheja Addepally   return error;
212899e37695SRavitheja Addepally }
212999e37695SRavitheja Addepally 
213099e37695SRavitheja Addepally lldb::user_id_t
213199e37695SRavitheja Addepally NativeProcessLinux::StartTraceGroup(const TraceOptions &config,
213299e37695SRavitheja Addepally                                            Status &error) {
213399e37695SRavitheja Addepally 
213499e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
213599e37695SRavitheja Addepally   if (config.getType() != TraceType::eTraceTypeProcessorTrace)
213699e37695SRavitheja Addepally     return LLDB_INVALID_UID;
213799e37695SRavitheja Addepally 
213899e37695SRavitheja Addepally   if (m_pt_proces_trace_id != LLDB_INVALID_UID) {
213999e37695SRavitheja Addepally     error.SetErrorString("tracing already active on this process");
214099e37695SRavitheja Addepally     return m_pt_proces_trace_id;
214199e37695SRavitheja Addepally   }
214299e37695SRavitheja Addepally 
214399e37695SRavitheja Addepally   for (const auto &thread_sp : m_threads) {
214499e37695SRavitheja Addepally     if (auto traceInstance = ProcessorTraceMonitor::Create(
214599e37695SRavitheja Addepally             GetID(), thread_sp->GetID(), config, true)) {
214699e37695SRavitheja Addepally       m_pt_traced_thread_group.insert(thread_sp->GetID());
214799e37695SRavitheja Addepally       m_processor_trace_monitor.insert(
214899e37695SRavitheja Addepally           std::make_pair(thread_sp->GetID(), std::move(*traceInstance)));
214999e37695SRavitheja Addepally     }
215099e37695SRavitheja Addepally   }
215199e37695SRavitheja Addepally 
215299e37695SRavitheja Addepally   m_pt_process_trace_config = config;
215399e37695SRavitheja Addepally   error = ProcessorTraceMonitor::GetCPUType(m_pt_process_trace_config);
215499e37695SRavitheja Addepally 
215599e37695SRavitheja Addepally   // Trace on Complete process will have traceid of 0
215699e37695SRavitheja Addepally   m_pt_proces_trace_id = 0;
215799e37695SRavitheja Addepally 
215899e37695SRavitheja Addepally   LLDB_LOG(log, "Process Trace ID {0}", m_pt_proces_trace_id);
215999e37695SRavitheja Addepally   return m_pt_proces_trace_id;
216099e37695SRavitheja Addepally }
216199e37695SRavitheja Addepally 
216299e37695SRavitheja Addepally lldb::user_id_t NativeProcessLinux::StartTrace(const TraceOptions &config,
216399e37695SRavitheja Addepally                                                Status &error) {
216499e37695SRavitheja Addepally   if (config.getType() != TraceType::eTraceTypeProcessorTrace)
216599e37695SRavitheja Addepally     return NativeProcessProtocol::StartTrace(config, error);
216699e37695SRavitheja Addepally 
216799e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
216899e37695SRavitheja Addepally 
216999e37695SRavitheja Addepally   lldb::tid_t threadid = config.getThreadID();
217099e37695SRavitheja Addepally 
217199e37695SRavitheja Addepally   if (threadid == LLDB_INVALID_THREAD_ID)
217299e37695SRavitheja Addepally     return StartTraceGroup(config, error);
217399e37695SRavitheja Addepally 
217499e37695SRavitheja Addepally   auto thread_sp = GetThreadByID(threadid);
217599e37695SRavitheja Addepally   if (!thread_sp) {
217699e37695SRavitheja Addepally     // Thread not tracked by lldb so don't trace.
217799e37695SRavitheja Addepally     error.SetErrorString("invalid thread id");
217899e37695SRavitheja Addepally     return LLDB_INVALID_UID;
217999e37695SRavitheja Addepally   }
218099e37695SRavitheja Addepally 
218199e37695SRavitheja Addepally   const auto &iter = m_processor_trace_monitor.find(threadid);
218299e37695SRavitheja Addepally   if (iter != m_processor_trace_monitor.end()) {
218399e37695SRavitheja Addepally     LLDB_LOG(log, "Thread already being traced");
218499e37695SRavitheja Addepally     error.SetErrorString("tracing already active on this thread");
218599e37695SRavitheja Addepally     return LLDB_INVALID_UID;
218699e37695SRavitheja Addepally   }
218799e37695SRavitheja Addepally 
218899e37695SRavitheja Addepally   auto traceMonitor =
218999e37695SRavitheja Addepally       ProcessorTraceMonitor::Create(GetID(), threadid, config, false);
219099e37695SRavitheja Addepally   if (!traceMonitor) {
219199e37695SRavitheja Addepally     error = traceMonitor.takeError();
219299e37695SRavitheja Addepally     LLDB_LOG(log, "error {0}", error);
219399e37695SRavitheja Addepally     return LLDB_INVALID_UID;
219499e37695SRavitheja Addepally   }
219599e37695SRavitheja Addepally   lldb::user_id_t ret_trace_id = (*traceMonitor)->GetTraceID();
219699e37695SRavitheja Addepally   m_processor_trace_monitor.insert(
219799e37695SRavitheja Addepally       std::make_pair(threadid, std::move(*traceMonitor)));
219899e37695SRavitheja Addepally   return ret_trace_id;
219999e37695SRavitheja Addepally }
220099e37695SRavitheja Addepally 
220199e37695SRavitheja Addepally Status NativeProcessLinux::StopTracingForThread(lldb::tid_t thread) {
220299e37695SRavitheja Addepally   Status error;
220399e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
220499e37695SRavitheja Addepally   LLDB_LOG(log, "Thread {0}", thread);
220599e37695SRavitheja Addepally 
220699e37695SRavitheja Addepally   const auto& iter = m_processor_trace_monitor.find(thread);
220799e37695SRavitheja Addepally   if (iter == m_processor_trace_monitor.end()) {
220899e37695SRavitheja Addepally     error.SetErrorString("tracing not active for this thread");
220999e37695SRavitheja Addepally     return error;
221099e37695SRavitheja Addepally   }
221199e37695SRavitheja Addepally 
221299e37695SRavitheja Addepally   if (iter->second->GetTraceID() == m_pt_proces_trace_id) {
221305097246SAdrian Prantl     // traceid maps to the whole process so we have to erase it from the thread
221405097246SAdrian Prantl     // group.
221599e37695SRavitheja Addepally     LLDB_LOG(log, "traceid maps to process");
221699e37695SRavitheja Addepally     m_pt_traced_thread_group.erase(thread);
221799e37695SRavitheja Addepally   }
221899e37695SRavitheja Addepally   m_processor_trace_monitor.erase(iter);
221999e37695SRavitheja Addepally 
222099e37695SRavitheja Addepally   return error;
222199e37695SRavitheja Addepally }
222299e37695SRavitheja Addepally 
222399e37695SRavitheja Addepally Status NativeProcessLinux::StopTrace(lldb::user_id_t traceid,
222499e37695SRavitheja Addepally                                      lldb::tid_t thread) {
222599e37695SRavitheja Addepally   Status error;
222699e37695SRavitheja Addepally 
222799e37695SRavitheja Addepally   TraceOptions trace_options;
222899e37695SRavitheja Addepally   trace_options.setThreadID(thread);
222999e37695SRavitheja Addepally   error = NativeProcessLinux::GetTraceConfig(traceid, trace_options);
223099e37695SRavitheja Addepally 
223199e37695SRavitheja Addepally   if (error.Fail())
223299e37695SRavitheja Addepally     return error;
223399e37695SRavitheja Addepally 
223499e37695SRavitheja Addepally   switch (trace_options.getType()) {
223599e37695SRavitheja Addepally   case lldb::TraceType::eTraceTypeProcessorTrace:
223699e37695SRavitheja Addepally     if (traceid == m_pt_proces_trace_id &&
223799e37695SRavitheja Addepally         thread == LLDB_INVALID_THREAD_ID)
223899e37695SRavitheja Addepally       StopProcessorTracingOnProcess();
223999e37695SRavitheja Addepally     else
224099e37695SRavitheja Addepally       error = StopProcessorTracingOnThread(traceid, thread);
224199e37695SRavitheja Addepally     break;
224299e37695SRavitheja Addepally   default:
224399e37695SRavitheja Addepally     error.SetErrorString("trace not supported");
224499e37695SRavitheja Addepally     break;
224599e37695SRavitheja Addepally   }
224699e37695SRavitheja Addepally 
224799e37695SRavitheja Addepally   return error;
224899e37695SRavitheja Addepally }
224999e37695SRavitheja Addepally 
225099e37695SRavitheja Addepally void NativeProcessLinux::StopProcessorTracingOnProcess() {
225199e37695SRavitheja Addepally   for (auto thread_id_iter : m_pt_traced_thread_group)
225299e37695SRavitheja Addepally     m_processor_trace_monitor.erase(thread_id_iter);
225399e37695SRavitheja Addepally   m_pt_traced_thread_group.clear();
225499e37695SRavitheja Addepally   m_pt_proces_trace_id = LLDB_INVALID_UID;
225599e37695SRavitheja Addepally }
225699e37695SRavitheja Addepally 
225799e37695SRavitheja Addepally Status NativeProcessLinux::StopProcessorTracingOnThread(lldb::user_id_t traceid,
225899e37695SRavitheja Addepally                                                         lldb::tid_t thread) {
225999e37695SRavitheja Addepally   Status error;
226099e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
226199e37695SRavitheja Addepally 
226299e37695SRavitheja Addepally   if (thread == LLDB_INVALID_THREAD_ID) {
226399e37695SRavitheja Addepally     for (auto& iter : m_processor_trace_monitor) {
226499e37695SRavitheja Addepally       if (iter.second->GetTraceID() == traceid) {
226505097246SAdrian Prantl         // Stopping a trace instance for an individual thread hence there will
226605097246SAdrian Prantl         // only be one traceid that can match.
226799e37695SRavitheja Addepally         m_processor_trace_monitor.erase(iter.first);
226899e37695SRavitheja Addepally         return error;
226999e37695SRavitheja Addepally       }
227099e37695SRavitheja Addepally       LLDB_LOG(log, "Trace ID {0}", iter.second->GetTraceID());
227199e37695SRavitheja Addepally     }
227299e37695SRavitheja Addepally 
227399e37695SRavitheja Addepally     LLDB_LOG(log, "Invalid TraceID");
227499e37695SRavitheja Addepally     error.SetErrorString("invalid trace id");
227599e37695SRavitheja Addepally     return error;
227699e37695SRavitheja Addepally   }
227799e37695SRavitheja Addepally 
227899e37695SRavitheja Addepally   // thread is specified so we can use find function on the map.
227999e37695SRavitheja Addepally   const auto& iter = m_processor_trace_monitor.find(thread);
228099e37695SRavitheja Addepally   if (iter == m_processor_trace_monitor.end()) {
228199e37695SRavitheja Addepally     // thread not found in our map.
228299e37695SRavitheja Addepally     LLDB_LOG(log, "thread not being traced");
228399e37695SRavitheja Addepally     error.SetErrorString("tracing not active for this thread");
228499e37695SRavitheja Addepally     return error;
228599e37695SRavitheja Addepally   }
228699e37695SRavitheja Addepally   if (iter->second->GetTraceID() != traceid) {
228799e37695SRavitheja Addepally     // traceid did not match so it has to be invalid.
228899e37695SRavitheja Addepally     LLDB_LOG(log, "Invalid TraceID");
228999e37695SRavitheja Addepally     error.SetErrorString("invalid trace id");
229099e37695SRavitheja Addepally     return error;
229199e37695SRavitheja Addepally   }
229299e37695SRavitheja Addepally 
229399e37695SRavitheja Addepally   LLDB_LOG(log, "UID - {0} , Thread -{1}", traceid, thread);
229499e37695SRavitheja Addepally 
229599e37695SRavitheja Addepally   if (traceid == m_pt_proces_trace_id) {
229605097246SAdrian Prantl     // traceid maps to the whole process so we have to erase it from the thread
229705097246SAdrian Prantl     // group.
229899e37695SRavitheja Addepally     LLDB_LOG(log, "traceid maps to process");
229999e37695SRavitheja Addepally     m_pt_traced_thread_group.erase(thread);
230099e37695SRavitheja Addepally   }
230199e37695SRavitheja Addepally   m_processor_trace_monitor.erase(iter);
230299e37695SRavitheja Addepally 
230399e37695SRavitheja Addepally   return error;
230499e37695SRavitheja Addepally }
2305