1af245d11STodd Fiala //===-- NativeProcessLinux.cpp -------------------------------- -*- C++ -*-===//
2af245d11STodd Fiala //
3af245d11STodd Fiala //                     The LLVM Compiler Infrastructure
4af245d11STodd Fiala //
5af245d11STodd Fiala // This file is distributed under the University of Illinois Open Source
6af245d11STodd Fiala // License. See LICENSE.TXT for details.
7af245d11STodd Fiala //
8af245d11STodd Fiala //===----------------------------------------------------------------------===//
9af245d11STodd Fiala 
10af245d11STodd Fiala #include "NativeProcessLinux.h"
11af245d11STodd Fiala 
12af245d11STodd Fiala // C Includes
13af245d11STodd Fiala #include <errno.h>
14af245d11STodd Fiala #include <stdint.h>
15b9c1b51eSKate Stone #include <string.h>
16af245d11STodd Fiala #include <unistd.h>
17af245d11STodd Fiala 
18af245d11STodd Fiala // C++ Includes
19af245d11STodd Fiala #include <fstream>
20df7c6995SPavel Labath #include <mutex>
21c076559aSPavel Labath #include <sstream>
22af245d11STodd Fiala #include <string>
235b981ab9SPavel Labath #include <unordered_map>
24af245d11STodd Fiala 
25af245d11STodd Fiala // Other libraries and framework includes
26d8c338d4STamas Berghammer #include "lldb/Core/EmulateInstruction.h"
276edef204SOleksiy Vyalov #include "lldb/Core/ModuleSpec.h"
28af245d11STodd Fiala #include "lldb/Core/RegisterValue.h"
29af245d11STodd Fiala #include "lldb/Core/State.h"
30af245d11STodd Fiala #include "lldb/Host/Host.h"
315ad891f7SPavel Labath #include "lldb/Host/HostProcess.h"
3224ae6294SZachary Turner #include "lldb/Host/PseudoTerminal.h"
3339de3110SZachary Turner #include "lldb/Host/ThreadLauncher.h"
342a86b555SPavel Labath #include "lldb/Host/common/NativeBreakpoint.h"
352a86b555SPavel Labath #include "lldb/Host/common/NativeRegisterContext.h"
364ee1c952SPavel Labath #include "lldb/Host/linux/Ptrace.h"
374ee1c952SPavel Labath #include "lldb/Host/linux/Uio.h"
38816ae4b0SKamil Rytarowski #include "lldb/Host/posix/ProcessLauncherPosixFork.h"
392a86b555SPavel Labath #include "lldb/Symbol/ObjectFile.h"
4090aff47cSZachary Turner #include "lldb/Target/Process.h"
41af245d11STodd Fiala #include "lldb/Target/ProcessLaunchInfo.h"
425b981ab9SPavel Labath #include "lldb/Target/Target.h"
43c16f5dcaSChaoren Lin #include "lldb/Utility/LLDBAssert.h"
4497206d57SZachary Turner #include "lldb/Utility/Status.h"
45f805e190SPavel Labath #include "lldb/Utility/StringExtractor.h"
4610c41f37SPavel Labath #include "llvm/Support/Errno.h"
4710c41f37SPavel Labath #include "llvm/Support/FileSystem.h"
4810c41f37SPavel Labath #include "llvm/Support/Threading.h"
49af245d11STodd Fiala 
50af245d11STodd Fiala #include "NativeThreadLinux.h"
51b9c1b51eSKate Stone #include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
521e209fccSTamas Berghammer #include "Procfs.h"
53cacde7dfSTodd Fiala 
54d858487eSTamas Berghammer #include <linux/unistd.h>
55d858487eSTamas Berghammer #include <sys/socket.h>
56df7c6995SPavel Labath #include <sys/syscall.h>
57d858487eSTamas Berghammer #include <sys/types.h>
58d858487eSTamas Berghammer #include <sys/user.h>
59d858487eSTamas Berghammer #include <sys/wait.h>
60d858487eSTamas Berghammer 
61af245d11STodd Fiala // Support hardware breakpoints in case it has not been defined
62af245d11STodd Fiala #ifndef TRAP_HWBKPT
63af245d11STodd Fiala #define TRAP_HWBKPT 4
64af245d11STodd Fiala #endif
65af245d11STodd Fiala 
667cb18bf5STamas Berghammer using namespace lldb;
677cb18bf5STamas Berghammer using namespace lldb_private;
68db264a6dSTamas Berghammer using namespace lldb_private::process_linux;
697cb18bf5STamas Berghammer using namespace llvm;
707cb18bf5STamas Berghammer 
71af245d11STodd Fiala // Private bits we only need internally.
72df7c6995SPavel Labath 
73b9c1b51eSKate Stone static bool ProcessVmReadvSupported() {
74df7c6995SPavel Labath   static bool is_supported;
75c5f28e2aSKamil Rytarowski   static llvm::once_flag flag;
76df7c6995SPavel Labath 
77c5f28e2aSKamil Rytarowski   llvm::call_once(flag, [] {
78a6321a8eSPavel Labath     Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
79df7c6995SPavel Labath 
80df7c6995SPavel Labath     uint32_t source = 0x47424742;
81df7c6995SPavel Labath     uint32_t dest = 0;
82df7c6995SPavel Labath 
83df7c6995SPavel Labath     struct iovec local, remote;
84df7c6995SPavel Labath     remote.iov_base = &source;
85df7c6995SPavel Labath     local.iov_base = &dest;
86df7c6995SPavel Labath     remote.iov_len = local.iov_len = sizeof source;
87df7c6995SPavel Labath 
88b9c1b51eSKate Stone     // We shall try if cross-process-memory reads work by attempting to read a
89b9c1b51eSKate Stone     // value from our own process.
90df7c6995SPavel Labath     ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
91df7c6995SPavel Labath     is_supported = (res == sizeof(source) && source == dest);
92df7c6995SPavel Labath     if (is_supported)
93a6321a8eSPavel Labath       LLDB_LOG(log,
94a6321a8eSPavel Labath                "Detected kernel support for process_vm_readv syscall. "
95a6321a8eSPavel Labath                "Fast memory reads enabled.");
96df7c6995SPavel Labath     else
97a6321a8eSPavel Labath       LLDB_LOG(log,
98a6321a8eSPavel Labath                "syscall process_vm_readv failed (error: {0}). Fast memory "
99a6321a8eSPavel Labath                "reads disabled.",
10010c41f37SPavel Labath                llvm::sys::StrError());
101df7c6995SPavel Labath   });
102df7c6995SPavel Labath 
103df7c6995SPavel Labath   return is_supported;
104df7c6995SPavel Labath }
105df7c6995SPavel Labath 
106b9c1b51eSKate Stone namespace {
107b9c1b51eSKate Stone void MaybeLogLaunchInfo(const ProcessLaunchInfo &info) {
108a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1094abe5d69SPavel Labath   if (!log)
1104abe5d69SPavel Labath     return;
1114abe5d69SPavel Labath 
1124abe5d69SPavel Labath   if (const FileAction *action = info.GetFileActionForFD(STDIN_FILENO))
113a6321a8eSPavel Labath     LLDB_LOG(log, "setting STDIN to '{0}'", action->GetFileSpec());
1144abe5d69SPavel Labath   else
115a6321a8eSPavel Labath     LLDB_LOG(log, "leaving STDIN as is");
1164abe5d69SPavel Labath 
1174abe5d69SPavel Labath   if (const FileAction *action = info.GetFileActionForFD(STDOUT_FILENO))
118a6321a8eSPavel Labath     LLDB_LOG(log, "setting STDOUT to '{0}'", action->GetFileSpec());
1194abe5d69SPavel Labath   else
120a6321a8eSPavel Labath     LLDB_LOG(log, "leaving STDOUT as is");
1214abe5d69SPavel Labath 
1224abe5d69SPavel Labath   if (const FileAction *action = info.GetFileActionForFD(STDERR_FILENO))
123a6321a8eSPavel Labath     LLDB_LOG(log, "setting STDERR to '{0}'", action->GetFileSpec());
1244abe5d69SPavel Labath   else
125a6321a8eSPavel Labath     LLDB_LOG(log, "leaving STDERR as is");
1264abe5d69SPavel Labath 
1274abe5d69SPavel Labath   int i = 0;
128b9c1b51eSKate Stone   for (const char **args = info.GetArguments().GetConstArgumentVector(); *args;
129b9c1b51eSKate Stone        ++args, ++i)
130a6321a8eSPavel Labath     LLDB_LOG(log, "arg {0}: '{1}'", i, *args);
1314abe5d69SPavel Labath }
1324abe5d69SPavel Labath 
133b9c1b51eSKate Stone void DisplayBytes(StreamString &s, void *bytes, uint32_t count) {
134af245d11STodd Fiala   uint8_t *ptr = (uint8_t *)bytes;
135af245d11STodd Fiala   const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
136b9c1b51eSKate Stone   for (uint32_t i = 0; i < loop_count; i++) {
137af245d11STodd Fiala     s.Printf("[%x]", *ptr);
138af245d11STodd Fiala     ptr++;
139af245d11STodd Fiala   }
140af245d11STodd Fiala }
141af245d11STodd Fiala 
142b9c1b51eSKate Stone void PtraceDisplayBytes(int &req, void *data, size_t data_size) {
143aafe053cSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
144a6321a8eSPavel Labath   if (!log)
145a6321a8eSPavel Labath     return;
146af245d11STodd Fiala   StreamString buf;
147af245d11STodd Fiala 
148b9c1b51eSKate Stone   switch (req) {
149b9c1b51eSKate Stone   case PTRACE_POKETEXT: {
150af245d11STodd Fiala     DisplayBytes(buf, &data, 8);
151aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_POKETEXT {0}", buf.GetData());
152af245d11STodd Fiala     break;
153af245d11STodd Fiala   }
154b9c1b51eSKate Stone   case PTRACE_POKEDATA: {
155af245d11STodd Fiala     DisplayBytes(buf, &data, 8);
156aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_POKEDATA {0}", buf.GetData());
157af245d11STodd Fiala     break;
158af245d11STodd Fiala   }
159b9c1b51eSKate Stone   case PTRACE_POKEUSER: {
160af245d11STodd Fiala     DisplayBytes(buf, &data, 8);
161aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_POKEUSER {0}", buf.GetData());
162af245d11STodd Fiala     break;
163af245d11STodd Fiala   }
164b9c1b51eSKate Stone   case PTRACE_SETREGS: {
165af245d11STodd Fiala     DisplayBytes(buf, data, data_size);
166aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_SETREGS {0}", buf.GetData());
167af245d11STodd Fiala     break;
168af245d11STodd Fiala   }
169b9c1b51eSKate Stone   case PTRACE_SETFPREGS: {
170af245d11STodd Fiala     DisplayBytes(buf, data, data_size);
171aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_SETFPREGS {0}", buf.GetData());
172af245d11STodd Fiala     break;
173af245d11STodd Fiala   }
174b9c1b51eSKate Stone   case PTRACE_SETSIGINFO: {
175af245d11STodd Fiala     DisplayBytes(buf, data, sizeof(siginfo_t));
176aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_SETSIGINFO {0}", buf.GetData());
177af245d11STodd Fiala     break;
178af245d11STodd Fiala   }
179b9c1b51eSKate Stone   case PTRACE_SETREGSET: {
180*11edb4eeSPavel 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 
24896e600fcSPavel Labath   ArchSpec arch;
24996e600fcSPavel Labath   if ((status = ResolveProcessArchitecture(pid, arch)).Fail())
25096e600fcSPavel Labath     return status.ToError();
25196e600fcSPavel Labath 
25296e600fcSPavel Labath   // Set the architecture to the exe architecture.
25396e600fcSPavel Labath   LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid,
25496e600fcSPavel Labath            arch.GetArchitectureName());
25596e600fcSPavel Labath 
25696e600fcSPavel Labath   status = SetDefaultPtraceOpts(pid);
25796e600fcSPavel Labath   if (status.Fail()) {
25896e600fcSPavel Labath     LLDB_LOG(log, "failed to set default ptrace options: {0}", status);
25996e600fcSPavel Labath     return status.ToError();
260af245d11STodd Fiala   }
261af245d11STodd Fiala 
26282abefa4SPavel Labath   return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
26396e600fcSPavel Labath       pid, launch_info.GetPTY().ReleaseMasterFileDescriptor(), native_delegate,
26482abefa4SPavel Labath       arch, mainloop, {pid}));
265af245d11STodd Fiala }
266af245d11STodd Fiala 
26782abefa4SPavel Labath llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
26882abefa4SPavel Labath NativeProcessLinux::Factory::Attach(
269b9c1b51eSKate Stone     lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
27096e600fcSPavel Labath     MainLoop &mainloop) const {
271a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
272a6321a8eSPavel Labath   LLDB_LOG(log, "pid = {0:x}", pid);
273af245d11STodd Fiala 
274af245d11STodd Fiala   // Retrieve the architecture for the running process.
27596e600fcSPavel Labath   ArchSpec arch;
27696e600fcSPavel Labath   Status status = ResolveProcessArchitecture(pid, arch);
27796e600fcSPavel Labath   if (!status.Success())
27896e600fcSPavel Labath     return status.ToError();
279af245d11STodd Fiala 
28096e600fcSPavel Labath   auto tids_or = NativeProcessLinux::Attach(pid);
28196e600fcSPavel Labath   if (!tids_or)
28296e600fcSPavel Labath     return tids_or.takeError();
283af245d11STodd Fiala 
28482abefa4SPavel Labath   return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
28582abefa4SPavel Labath       pid, -1, native_delegate, arch, mainloop, *tids_or));
286af245d11STodd Fiala }
287af245d11STodd Fiala 
288af245d11STodd Fiala // -----------------------------------------------------------------------------
289af245d11STodd Fiala // Public Instance Methods
290af245d11STodd Fiala // -----------------------------------------------------------------------------
291af245d11STodd Fiala 
29296e600fcSPavel Labath NativeProcessLinux::NativeProcessLinux(::pid_t pid, int terminal_fd,
29396e600fcSPavel Labath                                        NativeDelegate &delegate,
29482abefa4SPavel Labath                                        const ArchSpec &arch, MainLoop &mainloop,
29582abefa4SPavel Labath                                        llvm::ArrayRef<::pid_t> tids)
29696e600fcSPavel Labath     : NativeProcessProtocol(pid, terminal_fd, delegate), m_arch(arch) {
297b9c1b51eSKate Stone   if (m_terminal_fd != -1) {
29896e600fcSPavel Labath     Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
29996e600fcSPavel Labath     assert(status.Success());
3005ad891f7SPavel Labath   }
301af245d11STodd Fiala 
30296e600fcSPavel Labath   Status status;
30396e600fcSPavel Labath   m_sigchld_handle = mainloop.RegisterSignal(
30496e600fcSPavel Labath       SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status);
30596e600fcSPavel Labath   assert(m_sigchld_handle && status.Success());
30696e600fcSPavel Labath 
30796e600fcSPavel Labath   for (const auto &tid : tids) {
308a5be48b3SPavel Labath     NativeThreadLinux &thread = AddThread(tid);
309a5be48b3SPavel Labath     thread.SetStoppedBySignal(SIGSTOP);
310a5be48b3SPavel Labath     ThreadWasCreated(thread);
311af245d11STodd Fiala   }
312af245d11STodd Fiala 
31396e600fcSPavel Labath   // Let our process instance know the thread has stopped.
31496e600fcSPavel Labath   SetCurrentThreadID(tids[0]);
31596e600fcSPavel Labath   SetState(StateType::eStateStopped, false);
31696e600fcSPavel Labath 
31796e600fcSPavel Labath   // Proccess any signals we received before installing our handler
31896e600fcSPavel Labath   SigchldHandler();
31996e600fcSPavel Labath }
32096e600fcSPavel Labath 
32196e600fcSPavel Labath llvm::Expected<std::vector<::pid_t>> NativeProcessLinux::Attach(::pid_t pid) {
322a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
323af245d11STodd Fiala 
32496e600fcSPavel Labath   Status status;
325b9c1b51eSKate Stone   // Use a map to keep track of the threads which we have attached/need to
326b9c1b51eSKate Stone   // attach.
327af245d11STodd Fiala   Host::TidMap tids_to_attach;
328b9c1b51eSKate Stone   while (Host::FindProcessThreads(pid, tids_to_attach)) {
329af245d11STodd Fiala     for (Host::TidMap::iterator it = tids_to_attach.begin();
330b9c1b51eSKate Stone          it != tids_to_attach.end();) {
331b9c1b51eSKate Stone       if (it->second == false) {
332af245d11STodd Fiala         lldb::tid_t tid = it->first;
333af245d11STodd Fiala 
334af245d11STodd Fiala         // Attach to the requested process.
335af245d11STodd Fiala         // An attach will cause the thread to stop with a SIGSTOP.
33696e600fcSPavel Labath         if ((status = PtraceWrapper(PTRACE_ATTACH, tid)).Fail()) {
337af245d11STodd Fiala           // No such thread. The thread may have exited.
338af245d11STodd Fiala           // More error handling may be needed.
33996e600fcSPavel Labath           if (status.GetError() == ESRCH) {
340af245d11STodd Fiala             it = tids_to_attach.erase(it);
341af245d11STodd Fiala             continue;
34296e600fcSPavel Labath           }
34396e600fcSPavel Labath           return status.ToError();
344af245d11STodd Fiala         }
345af245d11STodd Fiala 
34696e600fcSPavel Labath         int wpid =
34796e600fcSPavel Labath             llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, nullptr, __WALL);
348af245d11STodd Fiala         // Need to use __WALL otherwise we receive an error with errno=ECHLD
349af245d11STodd Fiala         // At this point we should have a thread stopped if waitpid succeeds.
35096e600fcSPavel Labath         if (wpid < 0) {
351af245d11STodd Fiala           // No such thread. The thread may have exited.
352af245d11STodd Fiala           // More error handling may be needed.
353b9c1b51eSKate Stone           if (errno == ESRCH) {
354af245d11STodd Fiala             it = tids_to_attach.erase(it);
355af245d11STodd Fiala             continue;
356af245d11STodd Fiala           }
35796e600fcSPavel Labath           return llvm::errorCodeToError(
35896e600fcSPavel Labath               std::error_code(errno, std::generic_category()));
359af245d11STodd Fiala         }
360af245d11STodd Fiala 
36196e600fcSPavel Labath         if ((status = SetDefaultPtraceOpts(tid)).Fail())
36296e600fcSPavel Labath           return status.ToError();
363af245d11STodd Fiala 
364a6321a8eSPavel Labath         LLDB_LOG(log, "adding tid = {0}", tid);
365af245d11STodd Fiala         it->second = true;
366af245d11STodd Fiala       }
367af245d11STodd Fiala 
368af245d11STodd Fiala       // move the loop forward
369af245d11STodd Fiala       ++it;
370af245d11STodd Fiala     }
371af245d11STodd Fiala   }
372af245d11STodd Fiala 
37396e600fcSPavel Labath   size_t tid_count = tids_to_attach.size();
37496e600fcSPavel Labath   if (tid_count == 0)
37596e600fcSPavel Labath     return llvm::make_error<StringError>("No such process",
37696e600fcSPavel Labath                                          llvm::inconvertibleErrorCode());
377af245d11STodd Fiala 
37896e600fcSPavel Labath   std::vector<::pid_t> tids;
37996e600fcSPavel Labath   tids.reserve(tid_count);
38096e600fcSPavel Labath   for (const auto &p : tids_to_attach)
38196e600fcSPavel Labath     tids.push_back(p.first);
38296e600fcSPavel Labath   return std::move(tids);
383af245d11STodd Fiala }
384af245d11STodd Fiala 
38597206d57SZachary Turner Status NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid) {
386af245d11STodd Fiala   long ptrace_opts = 0;
387af245d11STodd Fiala 
388af245d11STodd Fiala   // Have the child raise an event on exit.  This is used to keep the child in
389af245d11STodd Fiala   // limbo until it is destroyed.
390af245d11STodd Fiala   ptrace_opts |= PTRACE_O_TRACEEXIT;
391af245d11STodd Fiala 
392af245d11STodd Fiala   // Have the tracer trace threads which spawn in the inferior process.
393af245d11STodd Fiala   // TODO: if we want to support tracing the inferiors' child, add the
394af245d11STodd Fiala   // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
395af245d11STodd Fiala   ptrace_opts |= PTRACE_O_TRACECLONE;
396af245d11STodd Fiala 
397af245d11STodd Fiala   // Have the tracer notify us before execve returns
398af245d11STodd Fiala   // (needed to disable legacy SIGTRAP generation)
399af245d11STodd Fiala   ptrace_opts |= PTRACE_O_TRACEEXEC;
400af245d11STodd Fiala 
4014a9babb2SPavel Labath   return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void *)ptrace_opts);
402af245d11STodd Fiala }
403af245d11STodd Fiala 
4041107b5a5SPavel Labath // Handles all waitpid events from the inferior process.
405b9c1b51eSKate Stone void NativeProcessLinux::MonitorCallback(lldb::pid_t pid, bool exited,
4063508fc8cSPavel Labath                                          WaitStatus status) {
407af245d11STodd Fiala   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
408af245d11STodd Fiala 
409b9c1b51eSKate Stone   // Certain activities differ based on whether the pid is the tid of the main
410b9c1b51eSKate Stone   // thread.
4111107b5a5SPavel Labath   const bool is_main_thread = (pid == GetID());
412af245d11STodd Fiala 
413af245d11STodd Fiala   // Handle when the thread exits.
414b9c1b51eSKate Stone   if (exited) {
415a6321a8eSPavel Labath     LLDB_LOG(log, "got exit signal({0}) , tid = {1} ({2} main thread)", signal,
416a6321a8eSPavel Labath              pid, is_main_thread ? "is" : "is not");
417af245d11STodd Fiala 
418af245d11STodd Fiala     // This is a thread that exited.  Ensure we're not tracking it anymore.
4191107b5a5SPavel Labath     const bool thread_found = StopTrackingThread(pid);
420af245d11STodd Fiala 
421b9c1b51eSKate Stone     if (is_main_thread) {
422b9c1b51eSKate Stone       // We only set the exit status and notify the delegate if we haven't
423b9c1b51eSKate Stone       // already set the process
424b9c1b51eSKate Stone       // state to an exited state.  We normally should have received a SIGTRAP |
425b9c1b51eSKate Stone       // (PTRACE_EVENT_EXIT << 8)
426af245d11STodd Fiala       // for the main thread.
427b9c1b51eSKate Stone       const bool already_notified = (GetState() == StateType::eStateExited) ||
428b9c1b51eSKate Stone                                     (GetState() == StateType::eStateCrashed);
429b9c1b51eSKate Stone       if (!already_notified) {
430a6321a8eSPavel Labath         LLDB_LOG(
431a6321a8eSPavel Labath             log,
432a6321a8eSPavel Labath             "tid = {0} handling main thread exit ({1}), expected exit state "
433a6321a8eSPavel Labath             "already set but state was {2} instead, setting exit state now",
434a6321a8eSPavel Labath             pid,
435b9c1b51eSKate Stone             thread_found ? "stopped tracking thread metadata"
436b9c1b51eSKate Stone                          : "thread metadata not found",
4378198db30SPavel Labath             GetState());
438af245d11STodd Fiala         // The main thread exited.  We're done monitoring.  Report to delegate.
4393508fc8cSPavel Labath         SetExitStatus(status, true);
440af245d11STodd Fiala 
441af245d11STodd Fiala         // Notify delegate that our process has exited.
4421107b5a5SPavel Labath         SetState(StateType::eStateExited, true);
443a6321a8eSPavel Labath       } else
444a6321a8eSPavel Labath         LLDB_LOG(log, "tid = {0} main thread now exited (%s)", pid,
445b9c1b51eSKate Stone                  thread_found ? "stopped tracking thread metadata"
446b9c1b51eSKate Stone                               : "thread metadata not found");
447b9c1b51eSKate Stone     } else {
448b9c1b51eSKate Stone       // Do we want to report to the delegate in this case?  I think not.  If
449a6321a8eSPavel Labath       // this was an orderly thread exit, we would already have received the
450a6321a8eSPavel Labath       // SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal, and we would have done an
451a6321a8eSPavel Labath       // all-stop then.
452a6321a8eSPavel Labath       LLDB_LOG(log, "tid = {0} handling non-main thread exit (%s)", pid,
453b9c1b51eSKate Stone                thread_found ? "stopped tracking thread metadata"
454b9c1b51eSKate Stone                             : "thread metadata not found");
455af245d11STodd Fiala     }
4561107b5a5SPavel Labath     return;
457af245d11STodd Fiala   }
458af245d11STodd Fiala 
459af245d11STodd Fiala   siginfo_t info;
460b9cc0c75SPavel Labath   const auto info_err = GetSignalInfo(pid, &info);
461b9cc0c75SPavel Labath   auto thread_sp = GetThreadByID(pid);
462b9cc0c75SPavel Labath 
463b9c1b51eSKate Stone   if (!thread_sp) {
464b9c1b51eSKate Stone     // Normally, the only situation when we cannot find the thread is if we have
465a6321a8eSPavel Labath     // just received a new thread notification. This is indicated by
466a6321a8eSPavel Labath     // GetSignalInfo() returning si_code == SI_USER and si_pid == 0
467a6321a8eSPavel Labath     LLDB_LOG(log, "received notification about an unknown tid {0}.", pid);
468b9cc0c75SPavel Labath 
469b9c1b51eSKate Stone     if (info_err.Fail()) {
470a6321a8eSPavel Labath       LLDB_LOG(log,
471a6321a8eSPavel Labath                "(tid {0}) GetSignalInfo failed ({1}). "
472a6321a8eSPavel Labath                "Ingoring this notification.",
473a6321a8eSPavel Labath                pid, info_err);
474b9cc0c75SPavel Labath       return;
475b9cc0c75SPavel Labath     }
476b9cc0c75SPavel Labath 
477a6321a8eSPavel Labath     LLDB_LOG(log, "tid {0}, si_code: {1}, si_pid: {2}", pid, info.si_code,
478a6321a8eSPavel Labath              info.si_pid);
479b9cc0c75SPavel Labath 
480a5be48b3SPavel Labath     NativeThreadLinux &thread = AddThread(pid);
48199e37695SRavitheja Addepally 
482b9cc0c75SPavel Labath     // Resume the newly created thread.
483a5be48b3SPavel Labath     ResumeThread(thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
484a5be48b3SPavel Labath     ThreadWasCreated(thread);
485b9cc0c75SPavel Labath     return;
486b9cc0c75SPavel Labath   }
487b9cc0c75SPavel Labath 
488b9cc0c75SPavel Labath   // Get details on the signal raised.
489b9c1b51eSKate Stone   if (info_err.Success()) {
490fa03ad2eSChaoren Lin     // We have retrieved the signal info.  Dispatch appropriately.
491fa03ad2eSChaoren Lin     if (info.si_signo == SIGTRAP)
492b9cc0c75SPavel Labath       MonitorSIGTRAP(info, *thread_sp);
493fa03ad2eSChaoren Lin     else
494b9cc0c75SPavel Labath       MonitorSignal(info, *thread_sp, exited);
495b9c1b51eSKate Stone   } else {
496b9c1b51eSKate Stone     if (info_err.GetError() == EINVAL) {
497fa03ad2eSChaoren Lin       // This is a group stop reception for this tid.
498b9c1b51eSKate Stone       // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU
499a6321a8eSPavel Labath       // into the tracee, triggering the group-stop mechanism. Normally
500a6321a8eSPavel Labath       // receiving these would stop the process, pending a SIGCONT. Simulating
501a6321a8eSPavel Labath       // this state in a debugger is hard and is generally not needed (one use
502a6321a8eSPavel Labath       // case is debugging background task being managed by a shell). For
503a6321a8eSPavel Labath       // general use, it is sufficient to stop the process in a signal-delivery
504b9c1b51eSKate Stone       // stop which happens before the group stop. This done by MonitorSignal
505a6321a8eSPavel Labath       // and works correctly for all signals.
506a6321a8eSPavel Labath       LLDB_LOG(log,
507a6321a8eSPavel Labath                "received a group stop for pid {0} tid {1}. Transparent "
508a6321a8eSPavel Labath                "handling of group stops not supported, resuming the "
509a6321a8eSPavel Labath                "thread.",
510a6321a8eSPavel Labath                GetID(), pid);
511b9c1b51eSKate Stone       ResumeThread(*thread_sp, thread_sp->GetState(),
512b9c1b51eSKate Stone                    LLDB_INVALID_SIGNAL_NUMBER);
513b9c1b51eSKate Stone     } else {
514af245d11STodd Fiala       // ptrace(GETSIGINFO) failed (but not due to group-stop).
515af245d11STodd Fiala 
516b9c1b51eSKate Stone       // A return value of ESRCH means the thread/process is no longer on the
517a6321a8eSPavel Labath       // system, so it was killed somehow outside of our control.  Either way,
518a6321a8eSPavel Labath       // we can't do anything with it anymore.
519af245d11STodd Fiala 
520b9c1b51eSKate Stone       // Stop tracking the metadata for the thread since it's entirely off the
521b9c1b51eSKate Stone       // system now.
5221107b5a5SPavel Labath       const bool thread_found = StopTrackingThread(pid);
523af245d11STodd Fiala 
524a6321a8eSPavel Labath       LLDB_LOG(log,
525a6321a8eSPavel Labath                "GetSignalInfo failed: {0}, tid = {1}, signal = {2}, "
526a6321a8eSPavel Labath                "status = {3}, main_thread = {4}, thread_found: {5}",
527a6321a8eSPavel Labath                info_err, pid, signal, status, is_main_thread, thread_found);
528af245d11STodd Fiala 
529b9c1b51eSKate Stone       if (is_main_thread) {
530b9c1b51eSKate Stone         // Notify the delegate - our process is not available but appears to
531b9c1b51eSKate Stone         // have been killed outside
532af245d11STodd Fiala         // our control.  Is eStateExited the right exit state in this case?
5333508fc8cSPavel Labath         SetExitStatus(status, true);
5341107b5a5SPavel Labath         SetState(StateType::eStateExited, true);
535b9c1b51eSKate Stone       } else {
536b9c1b51eSKate Stone         // This thread was pulled out from underneath us.  Anything to do here?
537b9c1b51eSKate Stone         // Do we want to do an all stop?
538a6321a8eSPavel Labath         LLDB_LOG(log,
539a6321a8eSPavel Labath                  "pid {0} tid {1} non-main thread exit occurred, didn't "
540a6321a8eSPavel Labath                  "tell delegate anything since thread disappeared out "
541a6321a8eSPavel Labath                  "from underneath us",
542a6321a8eSPavel Labath                  GetID(), pid);
543af245d11STodd Fiala       }
544af245d11STodd Fiala     }
545af245d11STodd Fiala   }
546af245d11STodd Fiala }
547af245d11STodd Fiala 
548b9c1b51eSKate Stone void NativeProcessLinux::WaitForNewThread(::pid_t tid) {
549a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
550426bdf88SPavel Labath 
551a5be48b3SPavel Labath   if (GetThreadByID(tid)) {
552b9c1b51eSKate Stone     // We are already tracking the thread - we got the event on the new thread
553a5be48b3SPavel Labath     // (see MonitorSignal) before this one. We are done.
554426bdf88SPavel Labath     return;
555426bdf88SPavel Labath   }
556426bdf88SPavel Labath 
557426bdf88SPavel Labath   // The thread is not tracked yet, let's wait for it to appear.
558426bdf88SPavel Labath   int status = -1;
559a6321a8eSPavel Labath   LLDB_LOG(log,
560a6321a8eSPavel Labath            "received thread creation event for tid {0}. tid not tracked "
561a6321a8eSPavel Labath            "yet, waiting for thread to appear...",
562a6321a8eSPavel Labath            tid);
563c1a6b128SPavel Labath   ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, &status, __WALL);
564b9c1b51eSKate Stone   // Since we are waiting on a specific tid, this must be the creation event.
565a6321a8eSPavel Labath   // But let's do some checks just in case.
566426bdf88SPavel Labath   if (wait_pid != tid) {
567a6321a8eSPavel Labath     LLDB_LOG(log,
568a6321a8eSPavel Labath              "waiting for tid {0} failed. Assuming the thread has "
569a6321a8eSPavel Labath              "disappeared in the meantime",
570a6321a8eSPavel Labath              tid);
571426bdf88SPavel Labath     // The only way I know of this could happen is if the whole process was
572b9c1b51eSKate Stone     // SIGKILLed in the mean time. In any case, we can't do anything about that
573b9c1b51eSKate Stone     // now.
574426bdf88SPavel Labath     return;
575426bdf88SPavel Labath   }
576b9c1b51eSKate Stone   if (WIFEXITED(status)) {
577a6321a8eSPavel Labath     LLDB_LOG(log,
578a6321a8eSPavel Labath              "waiting for tid {0} returned an 'exited' event. Not "
579a6321a8eSPavel Labath              "tracking the thread.",
580a6321a8eSPavel Labath              tid);
581426bdf88SPavel Labath     // Also a very improbable event.
582426bdf88SPavel Labath     return;
583426bdf88SPavel Labath   }
584426bdf88SPavel Labath 
585a6321a8eSPavel Labath   LLDB_LOG(log, "pid = {0}: tracking new thread tid {1}", GetID(), tid);
586a5be48b3SPavel Labath   NativeThreadLinux &new_thread = AddThread(tid);
58799e37695SRavitheja Addepally 
588a5be48b3SPavel Labath   ResumeThread(new_thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
589a5be48b3SPavel Labath   ThreadWasCreated(new_thread);
590426bdf88SPavel Labath }
591426bdf88SPavel Labath 
592b9c1b51eSKate Stone void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info,
593b9c1b51eSKate Stone                                         NativeThreadLinux &thread) {
594a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
595b9cc0c75SPavel Labath   const bool is_main_thread = (thread.GetID() == GetID());
596af245d11STodd Fiala 
597b9cc0c75SPavel Labath   assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
598af245d11STodd Fiala 
599b9c1b51eSKate Stone   switch (info.si_code) {
600b9c1b51eSKate Stone   // TODO: these two cases are required if we want to support tracing of the
601b9c1b51eSKate Stone   // inferiors' children.  We'd need this to debug a monitor.
602af245d11STodd Fiala   // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
603af245d11STodd Fiala   // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
604af245d11STodd Fiala 
605b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): {
606b9c1b51eSKate Stone     // This is the notification on the parent thread which informs us of new
607b9c1b51eSKate Stone     // thread
608426bdf88SPavel Labath     // creation.
609b9c1b51eSKate Stone     // We don't want to do anything with the parent thread so we just resume it.
610b9c1b51eSKate Stone     // In case we
611b9c1b51eSKate Stone     // want to implement "break on thread creation" functionality, we would need
612b9c1b51eSKate Stone     // to stop
613426bdf88SPavel Labath     // here.
614af245d11STodd Fiala 
615af245d11STodd Fiala     unsigned long event_message = 0;
616b9c1b51eSKate Stone     if (GetEventMessage(thread.GetID(), &event_message).Fail()) {
617a6321a8eSPavel Labath       LLDB_LOG(log,
618a6321a8eSPavel Labath                "pid {0} received thread creation event but "
619a6321a8eSPavel Labath                "GetEventMessage failed so we don't know the new tid",
620a6321a8eSPavel Labath                thread.GetID());
621426bdf88SPavel Labath     } else
622426bdf88SPavel Labath       WaitForNewThread(event_message);
623af245d11STodd Fiala 
624b9cc0c75SPavel Labath     ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
625af245d11STodd Fiala     break;
626af245d11STodd Fiala   }
627af245d11STodd Fiala 
628b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): {
629a6321a8eSPavel Labath     LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP);
630a9882ceeSTodd Fiala 
6311dbc6c9cSPavel Labath     // Exec clears any pending notifications.
6320e1d729bSPavel Labath     m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
633fa03ad2eSChaoren Lin 
634b9c1b51eSKate Stone     // Remove all but the main thread here.  Linux fork creates a new process
635b9c1b51eSKate Stone     // which only copies the main thread.
636a6321a8eSPavel Labath     LLDB_LOG(log, "exec received, stop tracking all but main thread");
637a9882ceeSTodd Fiala 
638a5be48b3SPavel Labath     for (auto i = m_threads.begin(); i != m_threads.end();) {
639a5be48b3SPavel Labath       if ((*i)->GetID() == GetID())
640a5be48b3SPavel Labath         i = m_threads.erase(i);
641a5be48b3SPavel Labath       else
642a5be48b3SPavel Labath         ++i;
643a9882ceeSTodd Fiala     }
644a5be48b3SPavel Labath     assert(m_threads.size() == 1);
645a5be48b3SPavel Labath     auto *main_thread = static_cast<NativeThreadLinux *>(m_threads[0].get());
646a9882ceeSTodd Fiala 
647a5be48b3SPavel Labath     SetCurrentThreadID(main_thread->GetID());
648a5be48b3SPavel Labath     main_thread->SetStoppedByExec();
649a9882ceeSTodd Fiala 
650fa03ad2eSChaoren Lin     // Tell coordinator about about the "new" (since exec) stopped main thread.
651a5be48b3SPavel Labath     ThreadWasCreated(*main_thread);
652fa03ad2eSChaoren Lin 
653a9882ceeSTodd Fiala     // Let our delegate know we have just exec'd.
654a9882ceeSTodd Fiala     NotifyDidExec();
655a9882ceeSTodd Fiala 
656fa03ad2eSChaoren Lin     // Let the process know we're stopped.
657a5be48b3SPavel Labath     StopRunningThreads(main_thread->GetID());
658a9882ceeSTodd Fiala 
659af245d11STodd Fiala     break;
660a9882ceeSTodd Fiala   }
661af245d11STodd Fiala 
662b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): {
663af245d11STodd Fiala     // The inferior process or one of its threads is about to exit.
664b9c1b51eSKate Stone     // We don't want to do anything with the thread so we just resume it. In
665b9c1b51eSKate Stone     // case we
666b9c1b51eSKate Stone     // want to implement "break on thread exit" functionality, we would need to
667b9c1b51eSKate Stone     // stop
6686e35163cSPavel Labath     // here.
669fa03ad2eSChaoren Lin 
670af245d11STodd Fiala     unsigned long data = 0;
671b9cc0c75SPavel Labath     if (GetEventMessage(thread.GetID(), &data).Fail())
672af245d11STodd Fiala       data = -1;
673af245d11STodd Fiala 
674a6321a8eSPavel Labath     LLDB_LOG(log,
675a6321a8eSPavel Labath              "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
676a6321a8eSPavel Labath              "WIFSIGNALED={2}, pid = {3}, main_thread = {4}",
677a6321a8eSPavel Labath              data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(),
678a6321a8eSPavel Labath              is_main_thread);
679af245d11STodd Fiala 
6803508fc8cSPavel Labath     if (is_main_thread)
6813508fc8cSPavel Labath       SetExitStatus(WaitStatus::Decode(data), true);
68275f47c3aSTodd Fiala 
68386852d36SPavel Labath     StateType state = thread.GetState();
684b9c1b51eSKate Stone     if (!StateIsRunningState(state)) {
685b9c1b51eSKate Stone       // Due to a kernel bug, we may sometimes get this stop after the inferior
686b9c1b51eSKate Stone       // gets a
687b9c1b51eSKate Stone       // SIGKILL. This confuses our state tracking logic in ResumeThread(),
688b9c1b51eSKate Stone       // since normally,
689b9c1b51eSKate Stone       // we should not be receiving any ptrace events while the inferior is
690b9c1b51eSKate Stone       // stopped. This
69186852d36SPavel Labath       // makes sure that the inferior is resumed and exits normally.
69286852d36SPavel Labath       state = eStateRunning;
69386852d36SPavel Labath     }
69486852d36SPavel Labath     ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
695af245d11STodd Fiala 
696af245d11STodd Fiala     break;
697af245d11STodd Fiala   }
698af245d11STodd Fiala 
699af245d11STodd Fiala   case 0:
700c16f5dcaSChaoren Lin   case TRAP_TRACE:  // We receive this on single stepping.
701c16f5dcaSChaoren Lin   case TRAP_HWBKPT: // We receive this on watchpoint hit
70286fd8e45SChaoren Lin   {
703c16f5dcaSChaoren Lin     // If a watchpoint was hit, report it
704c16f5dcaSChaoren Lin     uint32_t wp_index;
705d37349f3SPavel Labath     Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
706b9c1b51eSKate Stone         wp_index, (uintptr_t)info.si_addr);
707a6321a8eSPavel Labath     if (error.Fail())
708a6321a8eSPavel Labath       LLDB_LOG(log,
709a6321a8eSPavel Labath                "received error while checking for watchpoint hits, pid = "
710a6321a8eSPavel Labath                "{0}, error = {1}",
711a6321a8eSPavel Labath                thread.GetID(), error);
712b9c1b51eSKate Stone     if (wp_index != LLDB_INVALID_INDEX32) {
713b9cc0c75SPavel Labath       MonitorWatchpoint(thread, wp_index);
714c16f5dcaSChaoren Lin       break;
715c16f5dcaSChaoren Lin     }
716b9cc0c75SPavel Labath 
717d5ffbad2SOmair Javaid     // If a breakpoint was hit, report it
718d5ffbad2SOmair Javaid     uint32_t bp_index;
719d37349f3SPavel Labath     error = thread.GetRegisterContext().GetHardwareBreakHitIndex(
720d5ffbad2SOmair Javaid         bp_index, (uintptr_t)info.si_addr);
721d5ffbad2SOmair Javaid     if (error.Fail())
722d5ffbad2SOmair Javaid       LLDB_LOG(log, "received error while checking for hardware "
723d5ffbad2SOmair Javaid                     "breakpoint hits, pid = {0}, error = {1}",
724d5ffbad2SOmair Javaid                thread.GetID(), error);
725d5ffbad2SOmair Javaid     if (bp_index != LLDB_INVALID_INDEX32) {
726d5ffbad2SOmair Javaid       MonitorBreakpoint(thread);
727d5ffbad2SOmair Javaid       break;
728d5ffbad2SOmair Javaid     }
729d5ffbad2SOmair Javaid 
730be379e15STamas Berghammer     // Otherwise, report step over
731be379e15STamas Berghammer     MonitorTrace(thread);
732af245d11STodd Fiala     break;
733b9cc0c75SPavel Labath   }
734af245d11STodd Fiala 
735af245d11STodd Fiala   case SI_KERNEL:
73635799963SMohit K. Bhakkad #if defined __mips__
73735799963SMohit K. Bhakkad     // For mips there is no special signal for watchpoint
73835799963SMohit K. Bhakkad     // So we check for watchpoint in kernel trap
73935799963SMohit K. Bhakkad     {
74035799963SMohit K. Bhakkad       // If a watchpoint was hit, report it
74135799963SMohit K. Bhakkad       uint32_t wp_index;
742d37349f3SPavel Labath       Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
743b9c1b51eSKate Stone           wp_index, LLDB_INVALID_ADDRESS);
744a6321a8eSPavel Labath       if (error.Fail())
745a6321a8eSPavel Labath         LLDB_LOG(log,
746a6321a8eSPavel Labath                  "received error while checking for watchpoint hits, pid = "
747a6321a8eSPavel Labath                  "{0}, error = {1}",
748a6321a8eSPavel Labath                  thread.GetID(), error);
749b9c1b51eSKate Stone       if (wp_index != LLDB_INVALID_INDEX32) {
750b9cc0c75SPavel Labath         MonitorWatchpoint(thread, wp_index);
75135799963SMohit K. Bhakkad         break;
75235799963SMohit K. Bhakkad       }
75335799963SMohit K. Bhakkad     }
75435799963SMohit K. Bhakkad // NO BREAK
75535799963SMohit K. Bhakkad #endif
756af245d11STodd Fiala   case TRAP_BRKPT:
757b9cc0c75SPavel Labath     MonitorBreakpoint(thread);
758af245d11STodd Fiala     break;
759af245d11STodd Fiala 
760af245d11STodd Fiala   case SIGTRAP:
761af245d11STodd Fiala   case (SIGTRAP | 0x80):
762a6321a8eSPavel Labath     LLDB_LOG(
763a6321a8eSPavel Labath         log,
764a6321a8eSPavel Labath         "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",
765a6321a8eSPavel Labath         info.si_code, GetID(), thread.GetID());
766fa03ad2eSChaoren Lin 
767af245d11STodd Fiala     // Ignore these signals until we know more about them.
768b9cc0c75SPavel Labath     ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
769af245d11STodd Fiala     break;
770af245d11STodd Fiala 
771af245d11STodd Fiala   default:
77221a365baSPavel Labath     LLDB_LOG(log, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}",
773a6321a8eSPavel Labath              info.si_code, GetID(), thread.GetID());
77421a365baSPavel Labath     MonitorSignal(info, thread, false);
775af245d11STodd Fiala     break;
776af245d11STodd Fiala   }
777af245d11STodd Fiala }
778af245d11STodd Fiala 
779b9c1b51eSKate Stone void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) {
780a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
781a6321a8eSPavel Labath   LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID());
782c16f5dcaSChaoren Lin 
7830e1d729bSPavel Labath   // This thread is currently stopped.
784b9cc0c75SPavel Labath   thread.SetStoppedByTrace();
785c16f5dcaSChaoren Lin 
786b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
787c16f5dcaSChaoren Lin }
788c16f5dcaSChaoren Lin 
789b9c1b51eSKate Stone void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) {
790b9c1b51eSKate Stone   Log *log(
791b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
792a6321a8eSPavel Labath   LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID());
793c16f5dcaSChaoren Lin 
794c16f5dcaSChaoren Lin   // Mark the thread as stopped at breakpoint.
795b9cc0c75SPavel Labath   thread.SetStoppedByBreakpoint();
79697206d57SZachary Turner   Status error = FixupBreakpointPCAsNeeded(thread);
797c16f5dcaSChaoren Lin   if (error.Fail())
798a6321a8eSPavel Labath     LLDB_LOG(log, "pid = {0} fixup: {1}", thread.GetID(), error);
799d8c338d4STamas Berghammer 
800b9c1b51eSKate Stone   if (m_threads_stepping_with_breakpoint.find(thread.GetID()) !=
801b9c1b51eSKate Stone       m_threads_stepping_with_breakpoint.end())
802b9cc0c75SPavel Labath     thread.SetStoppedByTrace();
803c16f5dcaSChaoren Lin 
804b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
805c16f5dcaSChaoren Lin }
806c16f5dcaSChaoren Lin 
807b9c1b51eSKate Stone void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread,
808b9c1b51eSKate Stone                                            uint32_t wp_index) {
809b9c1b51eSKate Stone   Log *log(
810b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
811a6321a8eSPavel Labath   LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}",
812a6321a8eSPavel Labath            thread.GetID(), wp_index);
813c16f5dcaSChaoren Lin 
814c16f5dcaSChaoren Lin   // Mark the thread as stopped at watchpoint.
815c16f5dcaSChaoren Lin   // The address is at (lldb::addr_t)info->si_addr if we need it.
816f9077782SPavel Labath   thread.SetStoppedByWatchpoint(wp_index);
817c16f5dcaSChaoren Lin 
818b9c1b51eSKate Stone   // We need to tell all other running threads before we notify the delegate
819b9c1b51eSKate Stone   // about this stop.
820f9077782SPavel Labath   StopRunningThreads(thread.GetID());
821c16f5dcaSChaoren Lin }
822c16f5dcaSChaoren Lin 
823b9c1b51eSKate Stone void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
824b9c1b51eSKate Stone                                        NativeThreadLinux &thread, bool exited) {
825b9cc0c75SPavel Labath   const int signo = info.si_signo;
826b9cc0c75SPavel Labath   const bool is_from_llgs = info.si_pid == getpid();
827af245d11STodd Fiala 
828a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
829af245d11STodd Fiala 
830af245d11STodd Fiala   // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
831af245d11STodd Fiala   // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
832af245d11STodd Fiala   // kill(2) or raise(3).  Similarly for tgkill(2) on Linux.
833af245d11STodd Fiala   //
834af245d11STodd Fiala   // IOW, user generated signals never generate what we consider to be a
835af245d11STodd Fiala   // "crash".
836af245d11STodd Fiala   //
837af245d11STodd Fiala   // Similarly, ACK signals generated by this monitor.
838af245d11STodd Fiala 
839af245d11STodd Fiala   // Handle the signal.
840a6321a8eSPavel Labath   LLDB_LOG(log,
841a6321a8eSPavel Labath            "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
842a6321a8eSPavel Labath            "waitpid pid = {4})",
843a6321a8eSPavel Labath            Host::GetSignalAsCString(signo), signo, info.si_code,
844b9cc0c75SPavel Labath            thread.GetID());
84558a2f669STodd Fiala 
84658a2f669STodd Fiala   // Check for thread stop notification.
847b9c1b51eSKate Stone   if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) {
848af245d11STodd Fiala     // This is a tgkill()-based stop.
849a6321a8eSPavel Labath     LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID());
850fa03ad2eSChaoren Lin 
851aab58633SChaoren Lin     // Check that we're not already marked with a stop reason.
852b9c1b51eSKate Stone     // Note this thread really shouldn't already be marked as stopped - if we
853a6321a8eSPavel Labath     // were, that would imply that the kernel signaled us with the thread
854a6321a8eSPavel Labath     // stopping which we handled and marked as stopped, and that, without an
855a6321a8eSPavel Labath     // intervening resume, we received another stop.  It is more likely that we
856a6321a8eSPavel Labath     // are missing the marking of a run state somewhere if we find that the
857a6321a8eSPavel Labath     // thread was marked as stopped.
858b9cc0c75SPavel Labath     const StateType thread_state = thread.GetState();
859b9c1b51eSKate Stone     if (!StateIsStoppedState(thread_state, false)) {
860ed89c7feSPavel Labath       // An inferior thread has stopped because of a SIGSTOP we have sent it.
861b9c1b51eSKate Stone       // Generally, these are not important stops and we don't want to report
862a6321a8eSPavel Labath       // them as they are just used to stop other threads when one thread (the
863a6321a8eSPavel Labath       // one with the *real* stop reason) hits a breakpoint (watchpoint,
864a6321a8eSPavel Labath       // etc...). However, in the case of an asynchronous Interrupt(), this *is*
865a6321a8eSPavel Labath       // the real stop reason, so we leave the signal intact if this is the
866a6321a8eSPavel Labath       // thread that was chosen as the triggering thread.
867b9c1b51eSKate Stone       if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
868b9cc0c75SPavel Labath         if (m_pending_notification_tid == thread.GetID())
869b9cc0c75SPavel Labath           thread.SetStoppedBySignal(SIGSTOP, &info);
870ed89c7feSPavel Labath         else
871b9cc0c75SPavel Labath           thread.SetStoppedWithNoReason();
872ed89c7feSPavel Labath 
873b9cc0c75SPavel Labath         SetCurrentThreadID(thread.GetID());
8740e1d729bSPavel Labath         SignalIfAllThreadsStopped();
875b9c1b51eSKate Stone       } else {
8760e1d729bSPavel Labath         // We can end up here if stop was initiated by LLGS but by this time a
8770e1d729bSPavel Labath         // thread stop has occurred - maybe initiated by another event.
87897206d57SZachary Turner         Status error = ResumeThread(thread, thread.GetState(), 0);
879a6321a8eSPavel Labath         if (error.Fail())
880a6321a8eSPavel Labath           LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(),
881a6321a8eSPavel Labath                    error);
8820e1d729bSPavel Labath       }
883b9c1b51eSKate Stone     } else {
884a6321a8eSPavel Labath       LLDB_LOG(log,
885a6321a8eSPavel Labath                "pid {0} tid {1}, thread was already marked as a stopped "
886a6321a8eSPavel Labath                "state (state={2}), leaving stop signal as is",
8878198db30SPavel Labath                GetID(), thread.GetID(), thread_state);
8880e1d729bSPavel Labath       SignalIfAllThreadsStopped();
889af245d11STodd Fiala     }
890af245d11STodd Fiala 
89158a2f669STodd Fiala     // Done handling.
892af245d11STodd Fiala     return;
893af245d11STodd Fiala   }
894af245d11STodd Fiala 
8954a705e7eSPavel Labath   // Check if debugger should stop at this signal or just ignore it
8964a705e7eSPavel Labath   // and resume the inferior.
8974a705e7eSPavel Labath   if (m_signals_to_ignore.find(signo) != m_signals_to_ignore.end()) {
8984a705e7eSPavel Labath      ResumeThread(thread, thread.GetState(), signo);
8994a705e7eSPavel Labath      return;
9004a705e7eSPavel Labath   }
9014a705e7eSPavel Labath 
90286fd8e45SChaoren Lin   // This thread is stopped.
903a6321a8eSPavel Labath   LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo));
904b9cc0c75SPavel Labath   thread.SetStoppedBySignal(signo, &info);
90586fd8e45SChaoren Lin 
90686fd8e45SChaoren Lin   // Send a stop to the debugger after we get all other threads to stop.
907b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
908511e5cdcSTodd Fiala }
909af245d11STodd Fiala 
910e7708688STamas Berghammer namespace {
911e7708688STamas Berghammer 
912b9c1b51eSKate Stone struct EmulatorBaton {
913d37349f3SPavel Labath   NativeProcessLinux &m_process;
914d37349f3SPavel Labath   NativeRegisterContext &m_reg_context;
9156648fcc3SPavel Labath 
9166648fcc3SPavel Labath   // eRegisterKindDWARF -> RegsiterValue
9176648fcc3SPavel Labath   std::unordered_map<uint32_t, RegisterValue> m_register_values;
918e7708688STamas Berghammer 
919d37349f3SPavel Labath   EmulatorBaton(NativeProcessLinux &process, NativeRegisterContext &reg_context)
920b9c1b51eSKate Stone       : m_process(process), m_reg_context(reg_context) {}
921e7708688STamas Berghammer };
922e7708688STamas Berghammer 
923e7708688STamas Berghammer } // anonymous namespace
924e7708688STamas Berghammer 
925b9c1b51eSKate Stone static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
926e7708688STamas Berghammer                                  const EmulateInstruction::Context &context,
927b9c1b51eSKate Stone                                  lldb::addr_t addr, void *dst, size_t length) {
928e7708688STamas Berghammer   EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
929e7708688STamas Berghammer 
9303eb4b458SChaoren Lin   size_t bytes_read;
931d37349f3SPavel Labath   emulator_baton->m_process.ReadMemory(addr, dst, length, bytes_read);
932e7708688STamas Berghammer   return bytes_read;
933e7708688STamas Berghammer }
934e7708688STamas Berghammer 
935b9c1b51eSKate Stone static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
936e7708688STamas Berghammer                                  const RegisterInfo *reg_info,
937b9c1b51eSKate Stone                                  RegisterValue &reg_value) {
938e7708688STamas Berghammer   EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
939e7708688STamas Berghammer 
940b9c1b51eSKate Stone   auto it = emulator_baton->m_register_values.find(
941b9c1b51eSKate Stone       reg_info->kinds[eRegisterKindDWARF]);
942b9c1b51eSKate Stone   if (it != emulator_baton->m_register_values.end()) {
9436648fcc3SPavel Labath     reg_value = it->second;
9446648fcc3SPavel Labath     return true;
9456648fcc3SPavel Labath   }
9466648fcc3SPavel Labath 
947e7708688STamas Berghammer   // The emulator only fill in the dwarf regsiter numbers (and in some case
948e7708688STamas Berghammer   // the generic register numbers). Get the full register info from the
949e7708688STamas Berghammer   // register context based on the dwarf register numbers.
950b9c1b51eSKate Stone   const RegisterInfo *full_reg_info =
951d37349f3SPavel Labath       emulator_baton->m_reg_context.GetRegisterInfo(
952e7708688STamas Berghammer           eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
953e7708688STamas Berghammer 
95497206d57SZachary Turner   Status error =
955d37349f3SPavel Labath       emulator_baton->m_reg_context.ReadRegister(full_reg_info, reg_value);
9566648fcc3SPavel Labath   if (error.Success())
9576648fcc3SPavel Labath     return true;
958cdc22a88SMohit K. Bhakkad 
9596648fcc3SPavel Labath   return false;
960e7708688STamas Berghammer }
961e7708688STamas Berghammer 
962b9c1b51eSKate Stone static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
963e7708688STamas Berghammer                                   const EmulateInstruction::Context &context,
964e7708688STamas Berghammer                                   const RegisterInfo *reg_info,
965b9c1b51eSKate Stone                                   const RegisterValue &reg_value) {
966e7708688STamas Berghammer   EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
967b9c1b51eSKate Stone   emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
968b9c1b51eSKate Stone       reg_value;
969e7708688STamas Berghammer   return true;
970e7708688STamas Berghammer }
971e7708688STamas Berghammer 
972b9c1b51eSKate Stone static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
973e7708688STamas Berghammer                                   const EmulateInstruction::Context &context,
974b9c1b51eSKate Stone                                   lldb::addr_t addr, const void *dst,
975b9c1b51eSKate Stone                                   size_t length) {
976e7708688STamas Berghammer   return length;
977e7708688STamas Berghammer }
978e7708688STamas Berghammer 
979d37349f3SPavel Labath static lldb::addr_t ReadFlags(NativeRegisterContext &regsiter_context) {
980d37349f3SPavel Labath   const RegisterInfo *flags_info = regsiter_context.GetRegisterInfo(
981e7708688STamas Berghammer       eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
982d37349f3SPavel Labath   return regsiter_context.ReadRegisterAsUnsigned(flags_info,
983b9c1b51eSKate Stone                                                  LLDB_INVALID_ADDRESS);
984e7708688STamas Berghammer }
985e7708688STamas Berghammer 
98697206d57SZachary Turner Status
98797206d57SZachary Turner NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadLinux &thread) {
98897206d57SZachary Turner   Status error;
989d37349f3SPavel Labath   NativeRegisterContext& register_context = thread.GetRegisterContext();
990e7708688STamas Berghammer 
991e7708688STamas Berghammer   std::unique_ptr<EmulateInstruction> emulator_ap(
992b9c1b51eSKate Stone       EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying,
993b9c1b51eSKate Stone                                      nullptr));
994e7708688STamas Berghammer 
995e7708688STamas Berghammer   if (emulator_ap == nullptr)
99697206d57SZachary Turner     return Status("Instruction emulator not found!");
997e7708688STamas Berghammer 
998d37349f3SPavel Labath   EmulatorBaton baton(*this, register_context);
999e7708688STamas Berghammer   emulator_ap->SetBaton(&baton);
1000e7708688STamas Berghammer   emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
1001e7708688STamas Berghammer   emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
1002e7708688STamas Berghammer   emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
1003e7708688STamas Berghammer   emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
1004e7708688STamas Berghammer 
1005e7708688STamas Berghammer   if (!emulator_ap->ReadInstruction())
100697206d57SZachary Turner     return Status("Read instruction failed!");
1007e7708688STamas Berghammer 
1008b9c1b51eSKate Stone   bool emulation_result =
1009b9c1b51eSKate Stone       emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
10106648fcc3SPavel Labath 
1011d37349f3SPavel Labath   const RegisterInfo *reg_info_pc = register_context.GetRegisterInfo(
1012b9c1b51eSKate Stone       eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1013d37349f3SPavel Labath   const RegisterInfo *reg_info_flags = register_context.GetRegisterInfo(
1014b9c1b51eSKate Stone       eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
10156648fcc3SPavel Labath 
1016b9c1b51eSKate Stone   auto pc_it =
1017b9c1b51eSKate Stone       baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1018b9c1b51eSKate Stone   auto flags_it =
1019b9c1b51eSKate Stone       baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
10206648fcc3SPavel Labath 
1021e7708688STamas Berghammer   lldb::addr_t next_pc;
1022e7708688STamas Berghammer   lldb::addr_t next_flags;
1023b9c1b51eSKate Stone   if (emulation_result) {
1024b9c1b51eSKate Stone     assert(pc_it != baton.m_register_values.end() &&
1025b9c1b51eSKate Stone            "Emulation was successfull but PC wasn't updated");
10266648fcc3SPavel Labath     next_pc = pc_it->second.GetAsUInt64();
10276648fcc3SPavel Labath 
10286648fcc3SPavel Labath     if (flags_it != baton.m_register_values.end())
10296648fcc3SPavel Labath       next_flags = flags_it->second.GetAsUInt64();
1030e7708688STamas Berghammer     else
1031d37349f3SPavel Labath       next_flags = ReadFlags(register_context);
1032b9c1b51eSKate Stone   } else if (pc_it == baton.m_register_values.end()) {
1033e7708688STamas Berghammer     // Emulate instruction failed and it haven't changed PC. Advance PC
1034e7708688STamas Berghammer     // with the size of the current opcode because the emulation of all
1035e7708688STamas Berghammer     // PC modifying instruction should be successful. The failure most
1036e7708688STamas Berghammer     // likely caused by a not supported instruction which don't modify PC.
1037d37349f3SPavel Labath     next_pc = register_context.GetPC() + emulator_ap->GetOpcode().GetByteSize();
1038d37349f3SPavel Labath     next_flags = ReadFlags(register_context);
1039b9c1b51eSKate Stone   } else {
1040e7708688STamas Berghammer     // The instruction emulation failed after it modified the PC. It is an
1041e7708688STamas Berghammer     // unknown error where we can't continue because the next instruction is
1042e7708688STamas Berghammer     // modifying the PC but we don't  know how.
104397206d57SZachary Turner     return Status("Instruction emulation failed unexpectedly.");
1044e7708688STamas Berghammer   }
1045e7708688STamas Berghammer 
1046b9c1b51eSKate Stone   if (m_arch.GetMachine() == llvm::Triple::arm) {
1047b9c1b51eSKate Stone     if (next_flags & 0x20) {
1048e7708688STamas Berghammer       // Thumb mode
1049e7708688STamas Berghammer       error = SetSoftwareBreakpoint(next_pc, 2);
1050b9c1b51eSKate Stone     } else {
1051e7708688STamas Berghammer       // Arm mode
1052e7708688STamas Berghammer       error = SetSoftwareBreakpoint(next_pc, 4);
1053e7708688STamas Berghammer     }
1054b9c1b51eSKate Stone   } else if (m_arch.GetMachine() == llvm::Triple::mips64 ||
1055b9c1b51eSKate Stone              m_arch.GetMachine() == llvm::Triple::mips64el ||
1056b9c1b51eSKate Stone              m_arch.GetMachine() == llvm::Triple::mips ||
1057aae0a752SEugene Zemtsov              m_arch.GetMachine() == llvm::Triple::mipsel ||
1058aae0a752SEugene Zemtsov              m_arch.GetMachine() == llvm::Triple::ppc64le)
1059cdc22a88SMohit K. Bhakkad     error = SetSoftwareBreakpoint(next_pc, 4);
1060b9c1b51eSKate Stone   else {
1061e7708688STamas Berghammer     // No size hint is given for the next breakpoint
1062e7708688STamas Berghammer     error = SetSoftwareBreakpoint(next_pc, 0);
1063e7708688STamas Berghammer   }
1064e7708688STamas Berghammer 
106542eb6908SPavel Labath   // If setting the breakpoint fails because next_pc is out of
106642eb6908SPavel Labath   // the address space, ignore it and let the debugee segfault.
106742eb6908SPavel Labath   if (error.GetError() == EIO || error.GetError() == EFAULT) {
106897206d57SZachary Turner     return Status();
106942eb6908SPavel Labath   } else if (error.Fail())
1070e7708688STamas Berghammer     return error;
1071e7708688STamas Berghammer 
1072b9cc0c75SPavel Labath   m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
1073e7708688STamas Berghammer 
107497206d57SZachary Turner   return Status();
1075e7708688STamas Berghammer }
1076e7708688STamas Berghammer 
1077b9c1b51eSKate Stone bool NativeProcessLinux::SupportHardwareSingleStepping() const {
1078b9c1b51eSKate Stone   if (m_arch.GetMachine() == llvm::Triple::arm ||
1079b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mips64 ||
1080b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mips64el ||
1081b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mips ||
1082b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mipsel)
1083cdc22a88SMohit K. Bhakkad     return false;
1084cdc22a88SMohit K. Bhakkad   return true;
1085e7708688STamas Berghammer }
1086e7708688STamas Berghammer 
108797206d57SZachary Turner Status NativeProcessLinux::Resume(const ResumeActionList &resume_actions) {
1088a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1089a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0}", GetID());
1090af245d11STodd Fiala 
1091e7708688STamas Berghammer   bool software_single_step = !SupportHardwareSingleStepping();
1092af245d11STodd Fiala 
1093b9c1b51eSKate Stone   if (software_single_step) {
1094a5be48b3SPavel Labath     for (const auto &thread : m_threads) {
1095a5be48b3SPavel Labath       assert(thread && "thread list should not contain NULL threads");
1096e7708688STamas Berghammer 
1097b9c1b51eSKate Stone       const ResumeAction *const action =
1098a5be48b3SPavel Labath           resume_actions.GetActionForThread(thread->GetID(), true);
1099e7708688STamas Berghammer       if (action == nullptr)
1100e7708688STamas Berghammer         continue;
1101e7708688STamas Berghammer 
1102b9c1b51eSKate Stone       if (action->state == eStateStepping) {
110397206d57SZachary Turner         Status error = SetupSoftwareSingleStepping(
1104a5be48b3SPavel Labath             static_cast<NativeThreadLinux &>(*thread));
1105e7708688STamas Berghammer         if (error.Fail())
1106e7708688STamas Berghammer           return error;
1107e7708688STamas Berghammer       }
1108e7708688STamas Berghammer     }
1109e7708688STamas Berghammer   }
1110e7708688STamas Berghammer 
1111a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
1112a5be48b3SPavel Labath     assert(thread && "thread list should not contain NULL threads");
1113af245d11STodd Fiala 
1114b9c1b51eSKate Stone     const ResumeAction *const action =
1115a5be48b3SPavel Labath         resume_actions.GetActionForThread(thread->GetID(), true);
11166a196ce6SChaoren Lin 
1117b9c1b51eSKate Stone     if (action == nullptr) {
1118a6321a8eSPavel Labath       LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
1119a5be48b3SPavel Labath                thread->GetID());
11206a196ce6SChaoren Lin       continue;
11216a196ce6SChaoren Lin     }
1122af245d11STodd Fiala 
1123a6321a8eSPavel Labath     LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}",
1124a5be48b3SPavel Labath              action->state, GetID(), thread->GetID());
1125af245d11STodd Fiala 
1126b9c1b51eSKate Stone     switch (action->state) {
1127af245d11STodd Fiala     case eStateRunning:
1128b9c1b51eSKate Stone     case eStateStepping: {
1129af245d11STodd Fiala       // Run the thread, possibly feeding it the signal.
1130fa03ad2eSChaoren Lin       const int signo = action->signal;
1131a5be48b3SPavel Labath       ResumeThread(static_cast<NativeThreadLinux &>(*thread), action->state,
1132b9c1b51eSKate Stone                    signo);
1133af245d11STodd Fiala       break;
1134ae29d395SChaoren Lin     }
1135af245d11STodd Fiala 
1136af245d11STodd Fiala     case eStateSuspended:
1137af245d11STodd Fiala     case eStateStopped:
1138a6321a8eSPavel Labath       llvm_unreachable("Unexpected state");
1139af245d11STodd Fiala 
1140af245d11STodd Fiala     default:
114197206d57SZachary Turner       return Status("NativeProcessLinux::%s (): unexpected state %s specified "
1142b9c1b51eSKate Stone                     "for pid %" PRIu64 ", tid %" PRIu64,
1143b9c1b51eSKate Stone                     __FUNCTION__, StateAsCString(action->state), GetID(),
1144a5be48b3SPavel Labath                     thread->GetID());
1145af245d11STodd Fiala     }
1146af245d11STodd Fiala   }
1147af245d11STodd Fiala 
114897206d57SZachary Turner   return Status();
1149af245d11STodd Fiala }
1150af245d11STodd Fiala 
115197206d57SZachary Turner Status NativeProcessLinux::Halt() {
115297206d57SZachary Turner   Status error;
1153af245d11STodd Fiala 
1154af245d11STodd Fiala   if (kill(GetID(), SIGSTOP) != 0)
1155af245d11STodd Fiala     error.SetErrorToErrno();
1156af245d11STodd Fiala 
1157af245d11STodd Fiala   return error;
1158af245d11STodd Fiala }
1159af245d11STodd Fiala 
116097206d57SZachary Turner Status NativeProcessLinux::Detach() {
116197206d57SZachary Turner   Status error;
1162af245d11STodd Fiala 
1163af245d11STodd Fiala   // Stop monitoring the inferior.
116419cbe96aSPavel Labath   m_sigchld_handle.reset();
1165af245d11STodd Fiala 
11667a9495bcSPavel Labath   // Tell ptrace to detach from the process.
11677a9495bcSPavel Labath   if (GetID() == LLDB_INVALID_PROCESS_ID)
11687a9495bcSPavel Labath     return error;
11697a9495bcSPavel Labath 
1170a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
1171a5be48b3SPavel Labath     Status e = Detach(thread->GetID());
11727a9495bcSPavel Labath     if (e.Fail())
1173b9c1b51eSKate Stone       error =
1174b9c1b51eSKate Stone           e; // Save the error, but still attempt to detach from other threads.
11757a9495bcSPavel Labath   }
11767a9495bcSPavel Labath 
117799e37695SRavitheja Addepally   m_processor_trace_monitor.clear();
117899e37695SRavitheja Addepally   m_pt_proces_trace_id = LLDB_INVALID_UID;
117999e37695SRavitheja Addepally 
1180af245d11STodd Fiala   return error;
1181af245d11STodd Fiala }
1182af245d11STodd Fiala 
118397206d57SZachary Turner Status NativeProcessLinux::Signal(int signo) {
118497206d57SZachary Turner   Status error;
1185af245d11STodd Fiala 
1186a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1187a6321a8eSPavel Labath   LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo,
1188a6321a8eSPavel Labath            Host::GetSignalAsCString(signo), GetID());
1189af245d11STodd Fiala 
1190af245d11STodd Fiala   if (kill(GetID(), signo))
1191af245d11STodd Fiala     error.SetErrorToErrno();
1192af245d11STodd Fiala 
1193af245d11STodd Fiala   return error;
1194af245d11STodd Fiala }
1195af245d11STodd Fiala 
119697206d57SZachary Turner Status NativeProcessLinux::Interrupt() {
1197e9547b80SChaoren Lin   // Pick a running thread (or if none, a not-dead stopped thread) as
1198e9547b80SChaoren Lin   // the chosen thread that will be the stop-reason thread.
1199a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1200e9547b80SChaoren Lin 
1201a5be48b3SPavel Labath   NativeThreadProtocol *running_thread = nullptr;
1202a5be48b3SPavel Labath   NativeThreadProtocol *stopped_thread = nullptr;
1203e9547b80SChaoren Lin 
1204a6321a8eSPavel Labath   LLDB_LOG(log, "selecting running thread for interrupt target");
1205a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
1206e9547b80SChaoren Lin     // If we have a running or stepping thread, we'll call that the
1207e9547b80SChaoren Lin     // target of the interrupt.
1208a5be48b3SPavel Labath     const auto thread_state = thread->GetState();
1209b9c1b51eSKate Stone     if (thread_state == eStateRunning || thread_state == eStateStepping) {
1210a5be48b3SPavel Labath       running_thread = thread.get();
1211e9547b80SChaoren Lin       break;
1212a5be48b3SPavel Labath     } else if (!stopped_thread && StateIsStoppedState(thread_state, true)) {
1213b9c1b51eSKate Stone       // Remember the first non-dead stopped thread.  We'll use that as a backup
1214b9c1b51eSKate Stone       // if there are no running threads.
1215a5be48b3SPavel Labath       stopped_thread = thread.get();
1216e9547b80SChaoren Lin     }
1217e9547b80SChaoren Lin   }
1218e9547b80SChaoren Lin 
1219a5be48b3SPavel Labath   if (!running_thread && !stopped_thread) {
122097206d57SZachary Turner     Status error("found no running/stepping or live stopped threads as target "
1221b9c1b51eSKate Stone                  "for interrupt");
1222a6321a8eSPavel Labath     LLDB_LOG(log, "skipping due to error: {0}", error);
12235830aa75STamas Berghammer 
1224e9547b80SChaoren Lin     return error;
1225e9547b80SChaoren Lin   }
1226e9547b80SChaoren Lin 
1227a5be48b3SPavel Labath   NativeThreadProtocol *deferred_signal_thread =
1228a5be48b3SPavel Labath       running_thread ? running_thread : stopped_thread;
1229e9547b80SChaoren Lin 
1230a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(),
1231a5be48b3SPavel Labath            running_thread ? "running" : "stopped",
1232a5be48b3SPavel Labath            deferred_signal_thread->GetID());
1233e9547b80SChaoren Lin 
1234a5be48b3SPavel Labath   StopRunningThreads(deferred_signal_thread->GetID());
123545f5cb31SPavel Labath 
123697206d57SZachary Turner   return Status();
1237e9547b80SChaoren Lin }
1238e9547b80SChaoren Lin 
123997206d57SZachary Turner Status NativeProcessLinux::Kill() {
1240a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1241a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0}", GetID());
1242af245d11STodd Fiala 
124397206d57SZachary Turner   Status error;
1244af245d11STodd Fiala 
1245b9c1b51eSKate Stone   switch (m_state) {
1246af245d11STodd Fiala   case StateType::eStateInvalid:
1247af245d11STodd Fiala   case StateType::eStateExited:
1248af245d11STodd Fiala   case StateType::eStateCrashed:
1249af245d11STodd Fiala   case StateType::eStateDetached:
1250af245d11STodd Fiala   case StateType::eStateUnloaded:
1251af245d11STodd Fiala     // Nothing to do - the process is already dead.
1252a6321a8eSPavel Labath     LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
12538198db30SPavel Labath              m_state);
1254af245d11STodd Fiala     return error;
1255af245d11STodd Fiala 
1256af245d11STodd Fiala   case StateType::eStateConnected:
1257af245d11STodd Fiala   case StateType::eStateAttaching:
1258af245d11STodd Fiala   case StateType::eStateLaunching:
1259af245d11STodd Fiala   case StateType::eStateStopped:
1260af245d11STodd Fiala   case StateType::eStateRunning:
1261af245d11STodd Fiala   case StateType::eStateStepping:
1262af245d11STodd Fiala   case StateType::eStateSuspended:
1263af245d11STodd Fiala     // We can try to kill a process in these states.
1264af245d11STodd Fiala     break;
1265af245d11STodd Fiala   }
1266af245d11STodd Fiala 
1267b9c1b51eSKate Stone   if (kill(GetID(), SIGKILL) != 0) {
1268af245d11STodd Fiala     error.SetErrorToErrno();
1269af245d11STodd Fiala     return error;
1270af245d11STodd Fiala   }
1271af245d11STodd Fiala 
1272af245d11STodd Fiala   return error;
1273af245d11STodd Fiala }
1274af245d11STodd Fiala 
127597206d57SZachary Turner static Status
127615930862SPavel Labath ParseMemoryRegionInfoFromProcMapsLine(llvm::StringRef &maps_line,
1277b9c1b51eSKate Stone                                       MemoryRegionInfo &memory_region_info) {
1278af245d11STodd Fiala   memory_region_info.Clear();
1279af245d11STodd Fiala 
128015930862SPavel Labath   StringExtractor line_extractor(maps_line);
1281af245d11STodd Fiala 
1282b9c1b51eSKate Stone   // Format: {address_start_hex}-{address_end_hex} perms offset  dev   inode
1283b9c1b51eSKate Stone   // pathname
1284b9c1b51eSKate Stone   // perms: rwxp   (letter is present if set, '-' if not, final character is
1285b9c1b51eSKate Stone   // p=private, s=shared).
1286af245d11STodd Fiala 
1287af245d11STodd Fiala   // Parse out the starting address
1288af245d11STodd Fiala   lldb::addr_t start_address = line_extractor.GetHexMaxU64(false, 0);
1289af245d11STodd Fiala 
1290af245d11STodd Fiala   // Parse out hyphen separating start and end address from range.
1291af245d11STodd Fiala   if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != '-'))
129297206d57SZachary Turner     return Status(
1293b9c1b51eSKate Stone         "malformed /proc/{pid}/maps entry, missing dash between address range");
1294af245d11STodd Fiala 
1295af245d11STodd Fiala   // Parse out the ending address
1296af245d11STodd Fiala   lldb::addr_t end_address = line_extractor.GetHexMaxU64(false, start_address);
1297af245d11STodd Fiala 
1298af245d11STodd Fiala   // Parse out the space after the address.
1299af245d11STodd Fiala   if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != ' '))
130097206d57SZachary Turner     return Status(
130197206d57SZachary Turner         "malformed /proc/{pid}/maps entry, missing space after range");
1302af245d11STodd Fiala 
1303af245d11STodd Fiala   // Save the range.
1304af245d11STodd Fiala   memory_region_info.GetRange().SetRangeBase(start_address);
1305af245d11STodd Fiala   memory_region_info.GetRange().SetRangeEnd(end_address);
1306af245d11STodd Fiala 
1307b9c1b51eSKate Stone   // Any memory region in /proc/{pid}/maps is by definition mapped into the
1308b9c1b51eSKate Stone   // process.
1309ad007563SHoward Hellyer   memory_region_info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
1310ad007563SHoward Hellyer 
1311af245d11STodd Fiala   // Parse out each permission entry.
1312af245d11STodd Fiala   if (line_extractor.GetBytesLeft() < 4)
131397206d57SZachary Turner     return Status("malformed /proc/{pid}/maps entry, missing some portion of "
1314b9c1b51eSKate Stone                   "permissions");
1315af245d11STodd Fiala 
1316af245d11STodd Fiala   // Handle read permission.
1317af245d11STodd Fiala   const char read_perm_char = line_extractor.GetChar();
1318af245d11STodd Fiala   if (read_perm_char == 'r')
1319af245d11STodd Fiala     memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eYes);
1320c73301bbSTamas Berghammer   else if (read_perm_char == '-')
1321af245d11STodd Fiala     memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1322c73301bbSTamas Berghammer   else
132397206d57SZachary Turner     return Status("unexpected /proc/{pid}/maps read permission char");
1324af245d11STodd Fiala 
1325af245d11STodd Fiala   // Handle write permission.
1326af245d11STodd Fiala   const char write_perm_char = line_extractor.GetChar();
1327af245d11STodd Fiala   if (write_perm_char == 'w')
1328af245d11STodd Fiala     memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eYes);
1329c73301bbSTamas Berghammer   else if (write_perm_char == '-')
1330af245d11STodd Fiala     memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1331c73301bbSTamas Berghammer   else
133297206d57SZachary Turner     return Status("unexpected /proc/{pid}/maps write permission char");
1333af245d11STodd Fiala 
1334af245d11STodd Fiala   // Handle execute permission.
1335af245d11STodd Fiala   const char exec_perm_char = line_extractor.GetChar();
1336af245d11STodd Fiala   if (exec_perm_char == 'x')
1337af245d11STodd Fiala     memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes);
1338c73301bbSTamas Berghammer   else if (exec_perm_char == '-')
1339af245d11STodd Fiala     memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1340c73301bbSTamas Berghammer   else
134197206d57SZachary Turner     return Status("unexpected /proc/{pid}/maps exec permission char");
1342af245d11STodd Fiala 
1343d7d69f80STamas Berghammer   line_extractor.GetChar();              // Read the private bit
1344d7d69f80STamas Berghammer   line_extractor.SkipSpaces();           // Skip the separator
1345d7d69f80STamas Berghammer   line_extractor.GetHexMaxU64(false, 0); // Read the offset
1346d7d69f80STamas Berghammer   line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1347d7d69f80STamas Berghammer   line_extractor.GetChar();              // Read the device id separator
1348d7d69f80STamas Berghammer   line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1349d7d69f80STamas Berghammer   line_extractor.SkipSpaces();           // Skip the separator
1350d7d69f80STamas Berghammer   line_extractor.GetU64(0, 10);          // Read the inode number
1351d7d69f80STamas Berghammer 
1352d7d69f80STamas Berghammer   line_extractor.SkipSpaces();
1353b9739d40SPavel Labath   const char *name = line_extractor.Peek();
1354b9739d40SPavel Labath   if (name)
1355b9739d40SPavel Labath     memory_region_info.SetName(name);
1356d7d69f80STamas Berghammer 
135797206d57SZachary Turner   return Status();
1358af245d11STodd Fiala }
1359af245d11STodd Fiala 
136097206d57SZachary Turner Status NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr,
1361b9c1b51eSKate Stone                                                MemoryRegionInfo &range_info) {
1362b9c1b51eSKate Stone   // FIXME review that the final memory region returned extends to the end of
1363b9c1b51eSKate Stone   // the virtual address space,
1364af245d11STodd Fiala   // with no perms if it is not mapped.
1365af245d11STodd Fiala 
1366af245d11STodd Fiala   // Use an approach that reads memory regions from /proc/{pid}/maps.
1367af245d11STodd Fiala   // Assume proc maps entries are in ascending order.
1368af245d11STodd Fiala   // FIXME assert if we find differently.
1369af245d11STodd Fiala 
1370b9c1b51eSKate Stone   if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
1371af245d11STodd Fiala     // We're done.
137297206d57SZachary Turner     return Status("unsupported");
1373af245d11STodd Fiala   }
1374af245d11STodd Fiala 
137597206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
1376b9c1b51eSKate Stone   if (error.Fail()) {
1377af245d11STodd Fiala     return error;
1378af245d11STodd Fiala   }
1379af245d11STodd Fiala 
1380af245d11STodd Fiala   lldb::addr_t prev_base_address = 0;
1381af245d11STodd Fiala 
1382b9c1b51eSKate Stone   // FIXME start by finding the last region that is <= target address using
1383b9c1b51eSKate Stone   // binary search.  Data is sorted.
1384af245d11STodd Fiala   // There can be a ton of regions on pthreads apps with lots of threads.
1385b9c1b51eSKate Stone   for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1386b9c1b51eSKate Stone        ++it) {
1387a6f5795aSTamas Berghammer     MemoryRegionInfo &proc_entry_info = it->first;
1388af245d11STodd Fiala 
1389af245d11STodd Fiala     // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1390b9c1b51eSKate Stone     assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
1391b9c1b51eSKate Stone            "descending /proc/pid/maps entries detected, unexpected");
1392af245d11STodd Fiala     prev_base_address = proc_entry_info.GetRange().GetRangeBase();
1393b1554311SHafiz Abid Qadeer     UNUSED_IF_ASSERT_DISABLED(prev_base_address);
1394af245d11STodd Fiala 
1395b9c1b51eSKate Stone     // If the target address comes before this entry, indicate distance to next
1396b9c1b51eSKate Stone     // region.
1397b9c1b51eSKate Stone     if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1398af245d11STodd Fiala       range_info.GetRange().SetRangeBase(load_addr);
1399b9c1b51eSKate Stone       range_info.GetRange().SetByteSize(
1400b9c1b51eSKate Stone           proc_entry_info.GetRange().GetRangeBase() - load_addr);
1401af245d11STodd Fiala       range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1402af245d11STodd Fiala       range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1403af245d11STodd Fiala       range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1404ad007563SHoward Hellyer       range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1405af245d11STodd Fiala 
1406af245d11STodd Fiala       return error;
1407b9c1b51eSKate Stone     } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1408af245d11STodd Fiala       // The target address is within the memory region we're processing here.
1409af245d11STodd Fiala       range_info = proc_entry_info;
1410af245d11STodd Fiala       return error;
1411af245d11STodd Fiala     }
1412af245d11STodd Fiala 
1413b9c1b51eSKate Stone     // The target memory address comes somewhere after the region we just
1414b9c1b51eSKate Stone     // parsed.
1415af245d11STodd Fiala   }
1416af245d11STodd Fiala 
1417b9c1b51eSKate Stone   // If we made it here, we didn't find an entry that contained the given
1418b9c1b51eSKate Stone   // address. Return the
1419b9c1b51eSKate Stone   // load_addr as start and the amount of bytes betwwen load address and the end
1420b9c1b51eSKate Stone   // of the memory as
142109839c33STamas Berghammer   // size.
142209839c33STamas Berghammer   range_info.GetRange().SetRangeBase(load_addr);
1423ad007563SHoward Hellyer   range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
142409839c33STamas Berghammer   range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
142509839c33STamas Berghammer   range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
142609839c33STamas Berghammer   range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1427ad007563SHoward Hellyer   range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1428af245d11STodd Fiala   return error;
1429af245d11STodd Fiala }
1430af245d11STodd Fiala 
143197206d57SZachary Turner Status NativeProcessLinux::PopulateMemoryRegionCache() {
1432a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1433a6f5795aSTamas Berghammer 
1434a6f5795aSTamas Berghammer   // If our cache is empty, pull the latest.  There should always be at least
1435a6f5795aSTamas Berghammer   // one memory region if memory region handling is supported.
1436a6f5795aSTamas Berghammer   if (!m_mem_region_cache.empty()) {
1437a6321a8eSPavel Labath     LLDB_LOG(log, "reusing {0} cached memory region entries",
1438a6321a8eSPavel Labath              m_mem_region_cache.size());
143997206d57SZachary Turner     return Status();
1440a6f5795aSTamas Berghammer   }
1441a6f5795aSTamas Berghammer 
144215930862SPavel Labath   auto BufferOrError = getProcFile(GetID(), "maps");
144315930862SPavel Labath   if (!BufferOrError) {
144415930862SPavel Labath     m_supports_mem_region = LazyBool::eLazyBoolNo;
144515930862SPavel Labath     return BufferOrError.getError();
144615930862SPavel Labath   }
144715930862SPavel Labath   StringRef Rest = BufferOrError.get()->getBuffer();
144815930862SPavel Labath   while (! Rest.empty()) {
144915930862SPavel Labath     StringRef Line;
145015930862SPavel Labath     std::tie(Line, Rest) = Rest.split('\n');
1451a6f5795aSTamas Berghammer     MemoryRegionInfo info;
145297206d57SZachary Turner     const Status parse_error =
145397206d57SZachary Turner         ParseMemoryRegionInfoFromProcMapsLine(Line, info);
145415930862SPavel Labath     if (parse_error.Fail()) {
145515930862SPavel Labath       LLDB_LOG(log, "failed to parse proc maps line '{0}': {1}", Line,
145615930862SPavel Labath                parse_error);
145715930862SPavel Labath       m_supports_mem_region = LazyBool::eLazyBoolNo;
145815930862SPavel Labath       return parse_error;
145915930862SPavel Labath     }
1460a6f5795aSTamas Berghammer     m_mem_region_cache.emplace_back(
1461a6f5795aSTamas Berghammer         info, FileSpec(info.GetName().GetCString(), true));
1462a6f5795aSTamas Berghammer   }
1463a6f5795aSTamas Berghammer 
146415930862SPavel Labath   if (m_mem_region_cache.empty()) {
1465a6f5795aSTamas Berghammer     // No entries after attempting to read them.  This shouldn't happen if
1466a6f5795aSTamas Berghammer     // /proc/{pid}/maps is supported. Assume we don't support map entries
1467a6f5795aSTamas Berghammer     // via procfs.
146815930862SPavel Labath     m_supports_mem_region = LazyBool::eLazyBoolNo;
1469a6321a8eSPavel Labath     LLDB_LOG(log,
1470a6321a8eSPavel Labath              "failed to find any procfs maps entries, assuming no support "
1471a6321a8eSPavel Labath              "for memory region metadata retrieval");
147297206d57SZachary Turner     return Status("not supported");
1473a6f5795aSTamas Berghammer   }
1474a6f5795aSTamas Berghammer 
1475a6321a8eSPavel Labath   LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps",
1476a6321a8eSPavel Labath            m_mem_region_cache.size(), GetID());
1477a6f5795aSTamas Berghammer 
1478a6f5795aSTamas Berghammer   // We support memory retrieval, remember that.
1479a6f5795aSTamas Berghammer   m_supports_mem_region = LazyBool::eLazyBoolYes;
148097206d57SZachary Turner   return Status();
1481a6f5795aSTamas Berghammer }
1482a6f5795aSTamas Berghammer 
1483b9c1b51eSKate Stone void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
1484a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1485a6321a8eSPavel Labath   LLDB_LOG(log, "newBumpId={0}", newBumpId);
1486a6321a8eSPavel Labath   LLDB_LOG(log, "clearing {0} entries from memory region cache",
1487a6321a8eSPavel Labath            m_mem_region_cache.size());
1488af245d11STodd Fiala   m_mem_region_cache.clear();
1489af245d11STodd Fiala }
1490af245d11STodd Fiala 
149197206d57SZachary Turner Status NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions,
1492b9c1b51eSKate Stone                                           lldb::addr_t &addr) {
1493af245d11STodd Fiala // FIXME implementing this requires the equivalent of
1494af245d11STodd Fiala // InferiorCallPOSIX::InferiorCallMmap, which depends on
1495af245d11STodd Fiala // functional ThreadPlans working with Native*Protocol.
1496af245d11STodd Fiala #if 1
149797206d57SZachary Turner   return Status("not implemented yet");
1498af245d11STodd Fiala #else
1499af245d11STodd Fiala   addr = LLDB_INVALID_ADDRESS;
1500af245d11STodd Fiala 
1501af245d11STodd Fiala   unsigned prot = 0;
1502af245d11STodd Fiala   if (permissions & lldb::ePermissionsReadable)
1503af245d11STodd Fiala     prot |= eMmapProtRead;
1504af245d11STodd Fiala   if (permissions & lldb::ePermissionsWritable)
1505af245d11STodd Fiala     prot |= eMmapProtWrite;
1506af245d11STodd Fiala   if (permissions & lldb::ePermissionsExecutable)
1507af245d11STodd Fiala     prot |= eMmapProtExec;
1508af245d11STodd Fiala 
1509af245d11STodd Fiala   // TODO implement this directly in NativeProcessLinux
1510af245d11STodd Fiala   // (and lift to NativeProcessPOSIX if/when that class is
1511af245d11STodd Fiala   // refactored out).
1512af245d11STodd Fiala   if (InferiorCallMmap(this, addr, 0, size, prot,
1513af245d11STodd Fiala                        eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
1514af245d11STodd Fiala     m_addr_to_mmap_size[addr] = size;
151597206d57SZachary Turner     return Status();
1516af245d11STodd Fiala   } else {
1517af245d11STodd Fiala     addr = LLDB_INVALID_ADDRESS;
151897206d57SZachary Turner     return Status("unable to allocate %" PRIu64
1519b9c1b51eSKate Stone                   " bytes of memory with permissions %s",
1520b9c1b51eSKate Stone                   size, GetPermissionsAsCString(permissions));
1521af245d11STodd Fiala   }
1522af245d11STodd Fiala #endif
1523af245d11STodd Fiala }
1524af245d11STodd Fiala 
152597206d57SZachary Turner Status NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {
1526af245d11STodd Fiala   // FIXME see comments in AllocateMemory - required lower-level
1527af245d11STodd Fiala   // bits not in place yet (ThreadPlans)
152897206d57SZachary Turner   return Status("not implemented");
1529af245d11STodd Fiala }
1530af245d11STodd Fiala 
1531b9c1b51eSKate Stone lldb::addr_t NativeProcessLinux::GetSharedLibraryInfoAddress() {
1532af245d11STodd Fiala   // punt on this for now
1533af245d11STodd Fiala   return LLDB_INVALID_ADDRESS;
1534af245d11STodd Fiala }
1535af245d11STodd Fiala 
1536b9c1b51eSKate Stone size_t NativeProcessLinux::UpdateThreads() {
1537af245d11STodd Fiala   // The NativeProcessLinux monitoring threads are always up to date
1538af245d11STodd Fiala   // with respect to thread state and they keep the thread list
1539af245d11STodd Fiala   // populated properly. All this method needs to do is return the
1540af245d11STodd Fiala   // thread count.
1541af245d11STodd Fiala   return m_threads.size();
1542af245d11STodd Fiala }
1543af245d11STodd Fiala 
154497206d57SZachary Turner Status NativeProcessLinux::GetSoftwareBreakpointPCOffset(
1545b9c1b51eSKate Stone     uint32_t &actual_opcode_size) {
1546af245d11STodd Fiala   // FIXME put this behind a breakpoint protocol class that can be
1547af245d11STodd Fiala   // set per architecture.  Need ARM, MIPS support here.
1548af245d11STodd Fiala   static const uint8_t g_i386_opcode[] = {0xCC};
1549bb00d0b6SUlrich Weigand   static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
1550aae0a752SEugene Zemtsov   static const uint8_t g_ppc64le_opcode[] = {0x08, 0x00, 0xe0, 0x7f}; // trap
1551af245d11STodd Fiala 
1552b9c1b51eSKate Stone   switch (m_arch.GetMachine()) {
1553af245d11STodd Fiala   case llvm::Triple::x86:
1554af245d11STodd Fiala   case llvm::Triple::x86_64:
1555af245d11STodd Fiala     actual_opcode_size = static_cast<uint32_t>(sizeof(g_i386_opcode));
155697206d57SZachary Turner     return Status();
1557af245d11STodd Fiala 
1558bb00d0b6SUlrich Weigand   case llvm::Triple::systemz:
1559bb00d0b6SUlrich Weigand     actual_opcode_size = static_cast<uint32_t>(sizeof(g_s390x_opcode));
156097206d57SZachary Turner     return Status();
1561bb00d0b6SUlrich Weigand 
1562aae0a752SEugene Zemtsov   case llvm::Triple::ppc64le:
1563aae0a752SEugene Zemtsov     actual_opcode_size = static_cast<uint32_t>(sizeof(g_ppc64le_opcode));
1564aae0a752SEugene Zemtsov     return Status();
1565aae0a752SEugene Zemtsov 
1566ff7fd900STamas Berghammer   case llvm::Triple::arm:
1567ff7fd900STamas Berghammer   case llvm::Triple::aarch64:
1568e8659b5dSMohit K. Bhakkad   case llvm::Triple::mips64:
1569e8659b5dSMohit K. Bhakkad   case llvm::Triple::mips64el:
1570ce815e45SSagar Thakur   case llvm::Triple::mips:
1571ce815e45SSagar Thakur   case llvm::Triple::mipsel:
1572ff7fd900STamas Berghammer     // On these architectures the PC don't get updated for breakpoint hits
1573c60c9452SJaydeep Patil     actual_opcode_size = 0;
157497206d57SZachary Turner     return Status();
1575e8659b5dSMohit K. Bhakkad 
1576af245d11STodd Fiala   default:
1577af245d11STodd Fiala     assert(false && "CPU type not supported!");
157897206d57SZachary Turner     return Status("CPU type not supported");
1579af245d11STodd Fiala   }
1580af245d11STodd Fiala }
1581af245d11STodd Fiala 
158297206d57SZachary Turner Status NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,
1583b9c1b51eSKate Stone                                          bool hardware) {
1584af245d11STodd Fiala   if (hardware)
1585d5ffbad2SOmair Javaid     return SetHardwareBreakpoint(addr, size);
1586af245d11STodd Fiala   else
1587af245d11STodd Fiala     return SetSoftwareBreakpoint(addr, size);
1588af245d11STodd Fiala }
1589af245d11STodd Fiala 
159097206d57SZachary Turner Status NativeProcessLinux::RemoveBreakpoint(lldb::addr_t addr, bool hardware) {
1591d5ffbad2SOmair Javaid   if (hardware)
1592d5ffbad2SOmair Javaid     return RemoveHardwareBreakpoint(addr);
1593d5ffbad2SOmair Javaid   else
1594d5ffbad2SOmair Javaid     return NativeProcessProtocol::RemoveBreakpoint(addr);
1595d5ffbad2SOmair Javaid }
1596d5ffbad2SOmair Javaid 
159797206d57SZachary Turner Status NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(
1598b9c1b51eSKate Stone     size_t trap_opcode_size_hint, size_t &actual_opcode_size,
1599b9c1b51eSKate Stone     const uint8_t *&trap_opcode_bytes) {
160063c8be95STamas Berghammer   // FIXME put this behind a breakpoint protocol class that can be set per
160163c8be95STamas Berghammer   // architecture.  Need MIPS support here.
16022afc5966STodd Fiala   static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};
1603be379e15STamas Berghammer   // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1604be379e15STamas Berghammer   // linux kernel does otherwise.
1605be379e15STamas Berghammer   static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1606af245d11STodd Fiala   static const uint8_t g_i386_opcode[] = {0xCC};
16073df471c3SMohit K. Bhakkad   static const uint8_t g_mips64_opcode[] = {0x00, 0x00, 0x00, 0x0d};
16082c2acf96SMohit K. Bhakkad   static const uint8_t g_mips64el_opcode[] = {0x0d, 0x00, 0x00, 0x00};
1609bb00d0b6SUlrich Weigand   static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
1610be379e15STamas Berghammer   static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
1611aae0a752SEugene Zemtsov   static const uint8_t g_ppc64le_opcode[] = {0x08, 0x00, 0xe0, 0x7f}; // trap
1612af245d11STodd Fiala 
1613b9c1b51eSKate Stone   switch (m_arch.GetMachine()) {
16142afc5966STodd Fiala   case llvm::Triple::aarch64:
16152afc5966STodd Fiala     trap_opcode_bytes = g_aarch64_opcode;
16162afc5966STodd Fiala     actual_opcode_size = sizeof(g_aarch64_opcode);
161797206d57SZachary Turner     return Status();
16182afc5966STodd Fiala 
161963c8be95STamas Berghammer   case llvm::Triple::arm:
1620b9c1b51eSKate Stone     switch (trap_opcode_size_hint) {
162163c8be95STamas Berghammer     case 2:
162263c8be95STamas Berghammer       trap_opcode_bytes = g_thumb_breakpoint_opcode;
162363c8be95STamas Berghammer       actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
162497206d57SZachary Turner       return Status();
162563c8be95STamas Berghammer     case 4:
162663c8be95STamas Berghammer       trap_opcode_bytes = g_arm_breakpoint_opcode;
162763c8be95STamas Berghammer       actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
162897206d57SZachary Turner       return Status();
162963c8be95STamas Berghammer     default:
163063c8be95STamas Berghammer       assert(false && "Unrecognised trap opcode size hint!");
163197206d57SZachary Turner       return Status("Unrecognised trap opcode size hint!");
163263c8be95STamas Berghammer     }
163363c8be95STamas Berghammer 
1634af245d11STodd Fiala   case llvm::Triple::x86:
1635af245d11STodd Fiala   case llvm::Triple::x86_64:
1636af245d11STodd Fiala     trap_opcode_bytes = g_i386_opcode;
1637af245d11STodd Fiala     actual_opcode_size = sizeof(g_i386_opcode);
163897206d57SZachary Turner     return Status();
1639af245d11STodd Fiala 
1640ce815e45SSagar Thakur   case llvm::Triple::mips:
16413df471c3SMohit K. Bhakkad   case llvm::Triple::mips64:
16423df471c3SMohit K. Bhakkad     trap_opcode_bytes = g_mips64_opcode;
16433df471c3SMohit K. Bhakkad     actual_opcode_size = sizeof(g_mips64_opcode);
164497206d57SZachary Turner     return Status();
16453df471c3SMohit K. Bhakkad 
1646ce815e45SSagar Thakur   case llvm::Triple::mipsel:
16472c2acf96SMohit K. Bhakkad   case llvm::Triple::mips64el:
16482c2acf96SMohit K. Bhakkad     trap_opcode_bytes = g_mips64el_opcode;
16492c2acf96SMohit K. Bhakkad     actual_opcode_size = sizeof(g_mips64el_opcode);
165097206d57SZachary Turner     return Status();
16512c2acf96SMohit K. Bhakkad 
1652bb00d0b6SUlrich Weigand   case llvm::Triple::systemz:
1653bb00d0b6SUlrich Weigand     trap_opcode_bytes = g_s390x_opcode;
1654bb00d0b6SUlrich Weigand     actual_opcode_size = sizeof(g_s390x_opcode);
165597206d57SZachary Turner     return Status();
1656bb00d0b6SUlrich Weigand 
1657aae0a752SEugene Zemtsov   case llvm::Triple::ppc64le:
1658aae0a752SEugene Zemtsov     trap_opcode_bytes = g_ppc64le_opcode;
1659aae0a752SEugene Zemtsov     actual_opcode_size = sizeof(g_ppc64le_opcode);
1660aae0a752SEugene Zemtsov     return Status();
1661aae0a752SEugene Zemtsov 
1662af245d11STodd Fiala   default:
1663af245d11STodd Fiala     assert(false && "CPU type not supported!");
166497206d57SZachary Turner     return Status("CPU type not supported");
1665af245d11STodd Fiala   }
1666af245d11STodd Fiala }
1667af245d11STodd Fiala 
1668af245d11STodd Fiala #if 0
1669af245d11STodd Fiala ProcessMessage::CrashReason
1670af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
1671af245d11STodd Fiala {
1672af245d11STodd Fiala     ProcessMessage::CrashReason reason;
1673af245d11STodd Fiala     assert(info->si_signo == SIGSEGV);
1674af245d11STodd Fiala 
1675af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
1676af245d11STodd Fiala 
1677af245d11STodd Fiala     switch (info->si_code)
1678af245d11STodd Fiala     {
1679af245d11STodd Fiala     default:
1680af245d11STodd Fiala         assert(false && "unexpected si_code for SIGSEGV");
1681af245d11STodd Fiala         break;
1682af245d11STodd Fiala     case SI_KERNEL:
1683af245d11STodd Fiala         // Linux will occasionally send spurious SI_KERNEL codes.
1684af245d11STodd Fiala         // (this is poorly documented in sigaction)
1685af245d11STodd Fiala         // One way to get this is via unaligned SIMD loads.
1686af245d11STodd Fiala         reason = ProcessMessage::eInvalidAddress; // for lack of anything better
1687af245d11STodd Fiala         break;
1688af245d11STodd Fiala     case SEGV_MAPERR:
1689af245d11STodd Fiala         reason = ProcessMessage::eInvalidAddress;
1690af245d11STodd Fiala         break;
1691af245d11STodd Fiala     case SEGV_ACCERR:
1692af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedAddress;
1693af245d11STodd Fiala         break;
1694af245d11STodd Fiala     }
1695af245d11STodd Fiala 
1696af245d11STodd Fiala     return reason;
1697af245d11STodd Fiala }
1698af245d11STodd Fiala #endif
1699af245d11STodd Fiala 
1700af245d11STodd Fiala #if 0
1701af245d11STodd Fiala ProcessMessage::CrashReason
1702af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
1703af245d11STodd Fiala {
1704af245d11STodd Fiala     ProcessMessage::CrashReason reason;
1705af245d11STodd Fiala     assert(info->si_signo == SIGILL);
1706af245d11STodd Fiala 
1707af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
1708af245d11STodd Fiala 
1709af245d11STodd Fiala     switch (info->si_code)
1710af245d11STodd Fiala     {
1711af245d11STodd Fiala     default:
1712af245d11STodd Fiala         assert(false && "unexpected si_code for SIGILL");
1713af245d11STodd Fiala         break;
1714af245d11STodd Fiala     case ILL_ILLOPC:
1715af245d11STodd Fiala         reason = ProcessMessage::eIllegalOpcode;
1716af245d11STodd Fiala         break;
1717af245d11STodd Fiala     case ILL_ILLOPN:
1718af245d11STodd Fiala         reason = ProcessMessage::eIllegalOperand;
1719af245d11STodd Fiala         break;
1720af245d11STodd Fiala     case ILL_ILLADR:
1721af245d11STodd Fiala         reason = ProcessMessage::eIllegalAddressingMode;
1722af245d11STodd Fiala         break;
1723af245d11STodd Fiala     case ILL_ILLTRP:
1724af245d11STodd Fiala         reason = ProcessMessage::eIllegalTrap;
1725af245d11STodd Fiala         break;
1726af245d11STodd Fiala     case ILL_PRVOPC:
1727af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedOpcode;
1728af245d11STodd Fiala         break;
1729af245d11STodd Fiala     case ILL_PRVREG:
1730af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedRegister;
1731af245d11STodd Fiala         break;
1732af245d11STodd Fiala     case ILL_COPROC:
1733af245d11STodd Fiala         reason = ProcessMessage::eCoprocessorError;
1734af245d11STodd Fiala         break;
1735af245d11STodd Fiala     case ILL_BADSTK:
1736af245d11STodd Fiala         reason = ProcessMessage::eInternalStackError;
1737af245d11STodd Fiala         break;
1738af245d11STodd Fiala     }
1739af245d11STodd Fiala 
1740af245d11STodd Fiala     return reason;
1741af245d11STodd Fiala }
1742af245d11STodd Fiala #endif
1743af245d11STodd Fiala 
1744af245d11STodd Fiala #if 0
1745af245d11STodd Fiala ProcessMessage::CrashReason
1746af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
1747af245d11STodd Fiala {
1748af245d11STodd Fiala     ProcessMessage::CrashReason reason;
1749af245d11STodd Fiala     assert(info->si_signo == SIGFPE);
1750af245d11STodd Fiala 
1751af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
1752af245d11STodd Fiala 
1753af245d11STodd Fiala     switch (info->si_code)
1754af245d11STodd Fiala     {
1755af245d11STodd Fiala     default:
1756af245d11STodd Fiala         assert(false && "unexpected si_code for SIGFPE");
1757af245d11STodd Fiala         break;
1758af245d11STodd Fiala     case FPE_INTDIV:
1759af245d11STodd Fiala         reason = ProcessMessage::eIntegerDivideByZero;
1760af245d11STodd Fiala         break;
1761af245d11STodd Fiala     case FPE_INTOVF:
1762af245d11STodd Fiala         reason = ProcessMessage::eIntegerOverflow;
1763af245d11STodd Fiala         break;
1764af245d11STodd Fiala     case FPE_FLTDIV:
1765af245d11STodd Fiala         reason = ProcessMessage::eFloatDivideByZero;
1766af245d11STodd Fiala         break;
1767af245d11STodd Fiala     case FPE_FLTOVF:
1768af245d11STodd Fiala         reason = ProcessMessage::eFloatOverflow;
1769af245d11STodd Fiala         break;
1770af245d11STodd Fiala     case FPE_FLTUND:
1771af245d11STodd Fiala         reason = ProcessMessage::eFloatUnderflow;
1772af245d11STodd Fiala         break;
1773af245d11STodd Fiala     case FPE_FLTRES:
1774af245d11STodd Fiala         reason = ProcessMessage::eFloatInexactResult;
1775af245d11STodd Fiala         break;
1776af245d11STodd Fiala     case FPE_FLTINV:
1777af245d11STodd Fiala         reason = ProcessMessage::eFloatInvalidOperation;
1778af245d11STodd Fiala         break;
1779af245d11STodd Fiala     case FPE_FLTSUB:
1780af245d11STodd Fiala         reason = ProcessMessage::eFloatSubscriptRange;
1781af245d11STodd Fiala         break;
1782af245d11STodd Fiala     }
1783af245d11STodd Fiala 
1784af245d11STodd Fiala     return reason;
1785af245d11STodd Fiala }
1786af245d11STodd Fiala #endif
1787af245d11STodd Fiala 
1788af245d11STodd Fiala #if 0
1789af245d11STodd Fiala ProcessMessage::CrashReason
1790af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
1791af245d11STodd Fiala {
1792af245d11STodd Fiala     ProcessMessage::CrashReason reason;
1793af245d11STodd Fiala     assert(info->si_signo == SIGBUS);
1794af245d11STodd Fiala 
1795af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
1796af245d11STodd Fiala 
1797af245d11STodd Fiala     switch (info->si_code)
1798af245d11STodd Fiala     {
1799af245d11STodd Fiala     default:
1800af245d11STodd Fiala         assert(false && "unexpected si_code for SIGBUS");
1801af245d11STodd Fiala         break;
1802af245d11STodd Fiala     case BUS_ADRALN:
1803af245d11STodd Fiala         reason = ProcessMessage::eIllegalAlignment;
1804af245d11STodd Fiala         break;
1805af245d11STodd Fiala     case BUS_ADRERR:
1806af245d11STodd Fiala         reason = ProcessMessage::eIllegalAddress;
1807af245d11STodd Fiala         break;
1808af245d11STodd Fiala     case BUS_OBJERR:
1809af245d11STodd Fiala         reason = ProcessMessage::eHardwareError;
1810af245d11STodd Fiala         break;
1811af245d11STodd Fiala     }
1812af245d11STodd Fiala 
1813af245d11STodd Fiala     return reason;
1814af245d11STodd Fiala }
1815af245d11STodd Fiala #endif
1816af245d11STodd Fiala 
181797206d57SZachary Turner Status NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
1818b9c1b51eSKate Stone                                       size_t &bytes_read) {
1819df7c6995SPavel Labath   if (ProcessVmReadvSupported()) {
1820b9c1b51eSKate Stone     // The process_vm_readv path is about 50 times faster than ptrace api. We
1821b9c1b51eSKate Stone     // want to use
1822df7c6995SPavel Labath     // this syscall if it is supported.
1823df7c6995SPavel Labath 
1824df7c6995SPavel Labath     const ::pid_t pid = GetID();
1825df7c6995SPavel Labath 
1826df7c6995SPavel Labath     struct iovec local_iov, remote_iov;
1827df7c6995SPavel Labath     local_iov.iov_base = buf;
1828df7c6995SPavel Labath     local_iov.iov_len = size;
1829df7c6995SPavel Labath     remote_iov.iov_base = reinterpret_cast<void *>(addr);
1830df7c6995SPavel Labath     remote_iov.iov_len = size;
1831df7c6995SPavel Labath 
1832df7c6995SPavel Labath     bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
1833df7c6995SPavel Labath     const bool success = bytes_read == size;
1834df7c6995SPavel Labath 
1835a6321a8eSPavel Labath     Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1836a6321a8eSPavel Labath     LLDB_LOG(log,
1837a6321a8eSPavel Labath              "using process_vm_readv to read {0} bytes from inferior "
1838a6321a8eSPavel Labath              "address {1:x}: {2}",
183910c41f37SPavel Labath              size, addr, success ? "Success" : llvm::sys::StrError(errno));
1840df7c6995SPavel Labath 
1841df7c6995SPavel Labath     if (success)
184297206d57SZachary Turner       return Status();
1843a6321a8eSPavel Labath     // else the call failed for some reason, let's retry the read using ptrace
1844b9c1b51eSKate Stone     // api.
1845df7c6995SPavel Labath   }
1846df7c6995SPavel Labath 
184719cbe96aSPavel Labath   unsigned char *dst = static_cast<unsigned char *>(buf);
184819cbe96aSPavel Labath   size_t remainder;
184919cbe96aSPavel Labath   long data;
185019cbe96aSPavel Labath 
1851a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1852a6321a8eSPavel Labath   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
185319cbe96aSPavel Labath 
1854b9c1b51eSKate Stone   for (bytes_read = 0; bytes_read < size; bytes_read += remainder) {
185597206d57SZachary Turner     Status error = NativeProcessLinux::PtraceWrapper(
1856b9c1b51eSKate Stone         PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data);
1857a6321a8eSPavel Labath     if (error.Fail())
185819cbe96aSPavel Labath       return error;
185919cbe96aSPavel Labath 
186019cbe96aSPavel Labath     remainder = size - bytes_read;
186119cbe96aSPavel Labath     remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
186219cbe96aSPavel Labath 
186319cbe96aSPavel Labath     // Copy the data into our buffer
1864f6ef187bSMohit K. Bhakkad     memcpy(dst, &data, remainder);
186519cbe96aSPavel Labath 
1866a6321a8eSPavel Labath     LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
186719cbe96aSPavel Labath     addr += k_ptrace_word_size;
186819cbe96aSPavel Labath     dst += k_ptrace_word_size;
186919cbe96aSPavel Labath   }
187097206d57SZachary Turner   return Status();
1871af245d11STodd Fiala }
1872af245d11STodd Fiala 
187397206d57SZachary Turner Status NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf,
1874b9c1b51eSKate Stone                                                  size_t size,
1875b9c1b51eSKate Stone                                                  size_t &bytes_read) {
187697206d57SZachary Turner   Status error = ReadMemory(addr, buf, size, bytes_read);
1877b9c1b51eSKate Stone   if (error.Fail())
1878b9c1b51eSKate Stone     return error;
18793eb4b458SChaoren Lin   return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
18803eb4b458SChaoren Lin }
18813eb4b458SChaoren Lin 
188297206d57SZachary Turner Status NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,
1883b9c1b51eSKate Stone                                        size_t size, size_t &bytes_written) {
188419cbe96aSPavel Labath   const unsigned char *src = static_cast<const unsigned char *>(buf);
188519cbe96aSPavel Labath   size_t remainder;
188697206d57SZachary Turner   Status error;
188719cbe96aSPavel Labath 
1888a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1889a6321a8eSPavel Labath   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
189019cbe96aSPavel Labath 
1891b9c1b51eSKate Stone   for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
189219cbe96aSPavel Labath     remainder = size - bytes_written;
189319cbe96aSPavel Labath     remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
189419cbe96aSPavel Labath 
1895b9c1b51eSKate Stone     if (remainder == k_ptrace_word_size) {
189619cbe96aSPavel Labath       unsigned long data = 0;
1897f6ef187bSMohit K. Bhakkad       memcpy(&data, src, k_ptrace_word_size);
189819cbe96aSPavel Labath 
1899a6321a8eSPavel Labath       LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
1900b9c1b51eSKate Stone       error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(),
1901b9c1b51eSKate Stone                                                 (void *)addr, (void *)data);
1902a6321a8eSPavel Labath       if (error.Fail())
190319cbe96aSPavel Labath         return error;
1904b9c1b51eSKate Stone     } else {
190519cbe96aSPavel Labath       unsigned char buff[8];
190619cbe96aSPavel Labath       size_t bytes_read;
190719cbe96aSPavel Labath       error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
1908a6321a8eSPavel Labath       if (error.Fail())
190919cbe96aSPavel Labath         return error;
191019cbe96aSPavel Labath 
191119cbe96aSPavel Labath       memcpy(buff, src, remainder);
191219cbe96aSPavel Labath 
191319cbe96aSPavel Labath       size_t bytes_written_rec;
191419cbe96aSPavel Labath       error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
1915a6321a8eSPavel Labath       if (error.Fail())
191619cbe96aSPavel Labath         return error;
191719cbe96aSPavel Labath 
1918a6321a8eSPavel Labath       LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src,
1919b9c1b51eSKate Stone                *(unsigned long *)buff);
192019cbe96aSPavel Labath     }
192119cbe96aSPavel Labath 
192219cbe96aSPavel Labath     addr += k_ptrace_word_size;
192319cbe96aSPavel Labath     src += k_ptrace_word_size;
192419cbe96aSPavel Labath   }
192519cbe96aSPavel Labath   return error;
1926af245d11STodd Fiala }
1927af245d11STodd Fiala 
192897206d57SZachary Turner Status NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) {
192919cbe96aSPavel Labath   return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
1930af245d11STodd Fiala }
1931af245d11STodd Fiala 
193297206d57SZachary Turner Status NativeProcessLinux::GetEventMessage(lldb::tid_t tid,
1933b9c1b51eSKate Stone                                            unsigned long *message) {
193419cbe96aSPavel Labath   return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
1935af245d11STodd Fiala }
1936af245d11STodd Fiala 
193797206d57SZachary Turner Status NativeProcessLinux::Detach(lldb::tid_t tid) {
193897ccc294SChaoren Lin   if (tid == LLDB_INVALID_THREAD_ID)
193997206d57SZachary Turner     return Status();
194097ccc294SChaoren Lin 
194119cbe96aSPavel Labath   return PtraceWrapper(PTRACE_DETACH, tid);
1942af245d11STodd Fiala }
1943af245d11STodd Fiala 
1944b9c1b51eSKate Stone bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {
1945a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
1946a5be48b3SPavel Labath     assert(thread && "thread list should not contain NULL threads");
1947a5be48b3SPavel Labath     if (thread->GetID() == thread_id) {
1948af245d11STodd Fiala       // We have this thread.
1949af245d11STodd Fiala       return true;
1950af245d11STodd Fiala     }
1951af245d11STodd Fiala   }
1952af245d11STodd Fiala 
1953af245d11STodd Fiala   // We don't have this thread.
1954af245d11STodd Fiala   return false;
1955af245d11STodd Fiala }
1956af245d11STodd Fiala 
1957b9c1b51eSKate Stone bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) {
1958a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1959a6321a8eSPavel Labath   LLDB_LOG(log, "tid: {0})", thread_id);
19601dbc6c9cSPavel Labath 
19611dbc6c9cSPavel Labath   bool found = false;
1962b9c1b51eSKate Stone   for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
1963b9c1b51eSKate Stone     if (*it && ((*it)->GetID() == thread_id)) {
1964af245d11STodd Fiala       m_threads.erase(it);
19651dbc6c9cSPavel Labath       found = true;
19661dbc6c9cSPavel Labath       break;
1967af245d11STodd Fiala     }
1968af245d11STodd Fiala   }
1969af245d11STodd Fiala 
197099e37695SRavitheja Addepally   if (found)
197199e37695SRavitheja Addepally     StopTracingForThread(thread_id);
19729eb1ecb9SPavel Labath   SignalIfAllThreadsStopped();
19731dbc6c9cSPavel Labath   return found;
1974af245d11STodd Fiala }
1975af245d11STodd Fiala 
1976a5be48b3SPavel Labath NativeThreadLinux &NativeProcessLinux::AddThread(lldb::tid_t thread_id) {
1977a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
1978a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
1979af245d11STodd Fiala 
1980b9c1b51eSKate Stone   assert(!HasThreadNoLock(thread_id) &&
1981b9c1b51eSKate Stone          "attempted to add a thread by id that already exists");
1982af245d11STodd Fiala 
1983af245d11STodd Fiala   // If this is the first thread, save it as the current thread
1984af245d11STodd Fiala   if (m_threads.empty())
1985af245d11STodd Fiala     SetCurrentThreadID(thread_id);
1986af245d11STodd Fiala 
1987a5be48b3SPavel Labath   m_threads.push_back(llvm::make_unique<NativeThreadLinux>(*this, thread_id));
198899e37695SRavitheja Addepally 
198999e37695SRavitheja Addepally   if (m_pt_proces_trace_id != LLDB_INVALID_UID) {
199099e37695SRavitheja Addepally     auto traceMonitor = ProcessorTraceMonitor::Create(
199199e37695SRavitheja Addepally         GetID(), thread_id, m_pt_process_trace_config, true);
199299e37695SRavitheja Addepally     if (traceMonitor) {
199399e37695SRavitheja Addepally       m_pt_traced_thread_group.insert(thread_id);
199499e37695SRavitheja Addepally       m_processor_trace_monitor.insert(
199599e37695SRavitheja Addepally           std::make_pair(thread_id, std::move(*traceMonitor)));
199699e37695SRavitheja Addepally     } else {
199799e37695SRavitheja Addepally       LLDB_LOG(log, "failed to start trace on thread {0}", thread_id);
199899e37695SRavitheja Addepally       Status error(traceMonitor.takeError());
199999e37695SRavitheja Addepally       LLDB_LOG(log, "error {0}", error);
200099e37695SRavitheja Addepally     }
200199e37695SRavitheja Addepally   }
200299e37695SRavitheja Addepally 
2003a5be48b3SPavel Labath   return static_cast<NativeThreadLinux &>(*m_threads.back());
2004af245d11STodd Fiala }
2005af245d11STodd Fiala 
200697206d57SZachary Turner Status
200797206d57SZachary Turner NativeProcessLinux::FixupBreakpointPCAsNeeded(NativeThreadLinux &thread) {
2008a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_BREAKPOINTS));
2009af245d11STodd Fiala 
201097206d57SZachary Turner   Status error;
2011af245d11STodd Fiala 
2012b9c1b51eSKate Stone   // Find out the size of a breakpoint (might depend on where we are in the
2013b9c1b51eSKate Stone   // code).
2014d37349f3SPavel Labath   NativeRegisterContext &context = thread.GetRegisterContext();
2015af245d11STodd Fiala 
2016af245d11STodd Fiala   uint32_t breakpoint_size = 0;
2017b9cc0c75SPavel Labath   error = GetSoftwareBreakpointPCOffset(breakpoint_size);
2018b9c1b51eSKate Stone   if (error.Fail()) {
2019a6321a8eSPavel Labath     LLDB_LOG(log, "GetBreakpointSize() failed: {0}", error);
2020af245d11STodd Fiala     return error;
2021a6321a8eSPavel Labath   } else
2022a6321a8eSPavel Labath     LLDB_LOG(log, "breakpoint size: {0}", breakpoint_size);
2023af245d11STodd Fiala 
2024b9c1b51eSKate Stone   // First try probing for a breakpoint at a software breakpoint location: PC -
2025b9c1b51eSKate Stone   // breakpoint size.
2026d37349f3SPavel Labath   const lldb::addr_t initial_pc_addr = context.GetPCfromBreakpointLocation();
2027af245d11STodd Fiala   lldb::addr_t breakpoint_addr = initial_pc_addr;
2028b9c1b51eSKate Stone   if (breakpoint_size > 0) {
2029af245d11STodd Fiala     // Do not allow breakpoint probe to wrap around.
20303eb4b458SChaoren Lin     if (breakpoint_addr >= breakpoint_size)
20313eb4b458SChaoren Lin       breakpoint_addr -= breakpoint_size;
2032af245d11STodd Fiala   }
2033af245d11STodd Fiala 
2034af245d11STodd Fiala   // Check if we stopped because of a breakpoint.
2035af245d11STodd Fiala   NativeBreakpointSP breakpoint_sp;
2036af245d11STodd Fiala   error = m_breakpoint_list.GetBreakpoint(breakpoint_addr, breakpoint_sp);
2037b9c1b51eSKate Stone   if (!error.Success() || !breakpoint_sp) {
2038af245d11STodd Fiala     // We didn't find one at a software probe location.  Nothing to do.
2039a6321a8eSPavel Labath     LLDB_LOG(log,
2040a6321a8eSPavel Labath              "pid {0} no lldb breakpoint found at current pc with "
2041a6321a8eSPavel Labath              "adjustment: {1}",
2042a6321a8eSPavel Labath              GetID(), breakpoint_addr);
204397206d57SZachary Turner     return Status();
2044af245d11STodd Fiala   }
2045af245d11STodd Fiala 
2046af245d11STodd Fiala   // If the breakpoint is not a software breakpoint, nothing to do.
2047b9c1b51eSKate Stone   if (!breakpoint_sp->IsSoftwareBreakpoint()) {
2048a6321a8eSPavel Labath     LLDB_LOG(
2049a6321a8eSPavel Labath         log,
2050a6321a8eSPavel Labath         "pid {0} breakpoint found at {1:x}, not software, nothing to adjust",
2051a6321a8eSPavel Labath         GetID(), breakpoint_addr);
205297206d57SZachary Turner     return Status();
2053af245d11STodd Fiala   }
2054af245d11STodd Fiala 
2055af245d11STodd Fiala   //
2056af245d11STodd Fiala   // We have a software breakpoint and need to adjust the PC.
2057af245d11STodd Fiala   //
2058af245d11STodd Fiala 
2059af245d11STodd Fiala   // Sanity check.
2060b9c1b51eSKate Stone   if (breakpoint_size == 0) {
2061af245d11STodd Fiala     // Nothing to do!  How did we get here?
2062a6321a8eSPavel Labath     LLDB_LOG(log,
2063a6321a8eSPavel Labath              "pid {0} breakpoint found at {1:x}, it is software, but the "
2064a6321a8eSPavel Labath              "size is zero, nothing to do (unexpected)",
2065a6321a8eSPavel Labath              GetID(), breakpoint_addr);
206697206d57SZachary Turner     return Status();
2067af245d11STodd Fiala   }
2068af245d11STodd Fiala 
2069af245d11STodd Fiala   // Change the program counter.
2070a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0} tid {1}: changing PC from {2:x} to {3:x}", GetID(),
2071a6321a8eSPavel Labath            thread.GetID(), initial_pc_addr, breakpoint_addr);
2072af245d11STodd Fiala 
2073d37349f3SPavel Labath   error = context.SetPC(breakpoint_addr);
2074b9c1b51eSKate Stone   if (error.Fail()) {
2075a6321a8eSPavel Labath     LLDB_LOG(log, "pid {0} tid {1}: failed to set PC: {2}", GetID(),
2076a6321a8eSPavel Labath              thread.GetID(), error);
2077af245d11STodd Fiala     return error;
2078af245d11STodd Fiala   }
2079af245d11STodd Fiala 
2080af245d11STodd Fiala   return error;
2081af245d11STodd Fiala }
2082fa03ad2eSChaoren Lin 
208397206d57SZachary Turner Status NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,
2084b9c1b51eSKate Stone                                                    FileSpec &file_spec) {
208597206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
2086a6f5795aSTamas Berghammer   if (error.Fail())
2087a6f5795aSTamas Berghammer     return error;
2088a6f5795aSTamas Berghammer 
20897cb18bf5STamas Berghammer   FileSpec module_file_spec(module_path, true);
20907cb18bf5STamas Berghammer 
20917cb18bf5STamas Berghammer   file_spec.Clear();
2092a6f5795aSTamas Berghammer   for (const auto &it : m_mem_region_cache) {
2093a6f5795aSTamas Berghammer     if (it.second.GetFilename() == module_file_spec.GetFilename()) {
2094a6f5795aSTamas Berghammer       file_spec = it.second;
209597206d57SZachary Turner       return Status();
2096a6f5795aSTamas Berghammer     }
2097a6f5795aSTamas Berghammer   }
209897206d57SZachary Turner   return Status("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
20997cb18bf5STamas Berghammer                 module_file_spec.GetFilename().AsCString(), GetID());
21007cb18bf5STamas Berghammer }
2101c076559aSPavel Labath 
210297206d57SZachary Turner Status NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
2103b9c1b51eSKate Stone                                               lldb::addr_t &load_addr) {
2104783bfc8cSTamas Berghammer   load_addr = LLDB_INVALID_ADDRESS;
210597206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
2106a6f5795aSTamas Berghammer   if (error.Fail())
2107783bfc8cSTamas Berghammer     return error;
2108a6f5795aSTamas Berghammer 
2109a6f5795aSTamas Berghammer   FileSpec file(file_name, false);
2110a6f5795aSTamas Berghammer   for (const auto &it : m_mem_region_cache) {
2111a6f5795aSTamas Berghammer     if (it.second == file) {
2112a6f5795aSTamas Berghammer       load_addr = it.first.GetRange().GetRangeBase();
211397206d57SZachary Turner       return Status();
2114a6f5795aSTamas Berghammer     }
2115a6f5795aSTamas Berghammer   }
211697206d57SZachary Turner   return Status("No load address found for specified file.");
2117783bfc8cSTamas Berghammer }
2118783bfc8cSTamas Berghammer 
2119a5be48b3SPavel Labath NativeThreadLinux *NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {
2120a5be48b3SPavel Labath   return static_cast<NativeThreadLinux *>(
2121b9c1b51eSKate Stone       NativeProcessProtocol::GetThreadByID(tid));
2122f9077782SPavel Labath }
2123f9077782SPavel Labath 
212497206d57SZachary Turner Status NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,
2125b9c1b51eSKate Stone                                         lldb::StateType state, int signo) {
2126a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2127a6321a8eSPavel Labath   LLDB_LOG(log, "tid: {0}", thread.GetID());
2128c076559aSPavel Labath 
2129c076559aSPavel Labath   // Before we do the resume below, first check if we have a pending
2130108c325dSPavel Labath   // stop notification that is currently waiting for
21310e1d729bSPavel Labath   // all threads to stop.  This is potentially a buggy situation since
2132c076559aSPavel Labath   // we're ostensibly waiting for threads to stop before we send out the
2133c076559aSPavel Labath   // pending notification, and here we are resuming one before we send
2134c076559aSPavel Labath   // out the pending stop notification.
2135a6321a8eSPavel Labath   if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
2136a6321a8eSPavel Labath     LLDB_LOG(log,
2137a6321a8eSPavel Labath              "about to resume tid {0} per explicit request but we have a "
2138a6321a8eSPavel Labath              "pending stop notification (tid {1}) that is actively "
2139a6321a8eSPavel Labath              "waiting for this thread to stop. Valid sequence of events?",
2140a6321a8eSPavel Labath              thread.GetID(), m_pending_notification_tid);
2141c076559aSPavel Labath   }
2142c076559aSPavel Labath 
2143c076559aSPavel Labath   // Request a resume.  We expect this to be synchronous and the system
2144c076559aSPavel Labath   // to reflect it is running after this completes.
2145b9c1b51eSKate Stone   switch (state) {
2146b9c1b51eSKate Stone   case eStateRunning: {
2147605b51b8SPavel Labath     const auto resume_result = thread.Resume(signo);
21480e1d729bSPavel Labath     if (resume_result.Success())
21490e1d729bSPavel Labath       SetState(eStateRunning, true);
21500e1d729bSPavel Labath     return resume_result;
2151c076559aSPavel Labath   }
2152b9c1b51eSKate Stone   case eStateStepping: {
2153605b51b8SPavel Labath     const auto step_result = thread.SingleStep(signo);
21540e1d729bSPavel Labath     if (step_result.Success())
21550e1d729bSPavel Labath       SetState(eStateRunning, true);
21560e1d729bSPavel Labath     return step_result;
21570e1d729bSPavel Labath   }
21580e1d729bSPavel Labath   default:
21598198db30SPavel Labath     LLDB_LOG(log, "Unhandled state {0}.", state);
21600e1d729bSPavel Labath     llvm_unreachable("Unhandled state for resume");
21610e1d729bSPavel Labath   }
2162c076559aSPavel Labath }
2163c076559aSPavel Labath 
2164c076559aSPavel Labath //===----------------------------------------------------------------------===//
2165c076559aSPavel Labath 
2166b9c1b51eSKate Stone void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {
2167a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2168a6321a8eSPavel Labath   LLDB_LOG(log, "about to process event: (triggering_tid: {0})",
2169a6321a8eSPavel Labath            triggering_tid);
2170c076559aSPavel Labath 
21710e1d729bSPavel Labath   m_pending_notification_tid = triggering_tid;
21720e1d729bSPavel Labath 
21730e1d729bSPavel Labath   // Request a stop for all the thread stops that need to be stopped
21740e1d729bSPavel Labath   // and are not already known to be stopped.
2175a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
2176a5be48b3SPavel Labath     if (StateIsRunningState(thread->GetState()))
2177a5be48b3SPavel Labath       static_cast<NativeThreadLinux *>(thread.get())->RequestStop();
21780e1d729bSPavel Labath   }
21790e1d729bSPavel Labath 
21800e1d729bSPavel Labath   SignalIfAllThreadsStopped();
2181a6321a8eSPavel Labath   LLDB_LOG(log, "event processing done");
2182c076559aSPavel Labath }
2183c076559aSPavel Labath 
2184b9c1b51eSKate Stone void NativeProcessLinux::SignalIfAllThreadsStopped() {
21850e1d729bSPavel Labath   if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
21860e1d729bSPavel Labath     return; // No pending notification. Nothing to do.
21870e1d729bSPavel Labath 
2188b9c1b51eSKate Stone   for (const auto &thread_sp : m_threads) {
21890e1d729bSPavel Labath     if (StateIsRunningState(thread_sp->GetState()))
21900e1d729bSPavel Labath       return; // Some threads are still running. Don't signal yet.
21910e1d729bSPavel Labath   }
21920e1d729bSPavel Labath 
21930e1d729bSPavel Labath   // We have a pending notification and all threads have stopped.
2194b9c1b51eSKate Stone   Log *log(
2195b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
21969eb1ecb9SPavel Labath 
2197b9c1b51eSKate Stone   // Clear any temporary breakpoints we used to implement software single
2198b9c1b51eSKate Stone   // stepping.
2199b9c1b51eSKate Stone   for (const auto &thread_info : m_threads_stepping_with_breakpoint) {
220097206d57SZachary Turner     Status error = RemoveBreakpoint(thread_info.second);
22019eb1ecb9SPavel Labath     if (error.Fail())
2202a6321a8eSPavel Labath       LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}",
2203a6321a8eSPavel Labath                thread_info.first, error);
22049eb1ecb9SPavel Labath   }
22059eb1ecb9SPavel Labath   m_threads_stepping_with_breakpoint.clear();
22069eb1ecb9SPavel Labath 
22079eb1ecb9SPavel Labath   // Notify the delegate about the stop
22080e1d729bSPavel Labath   SetCurrentThreadID(m_pending_notification_tid);
2209ed89c7feSPavel Labath   SetState(StateType::eStateStopped, true);
22100e1d729bSPavel Labath   m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
2211c076559aSPavel Labath }
2212c076559aSPavel Labath 
2213b9c1b51eSKate Stone void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {
2214a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2215a6321a8eSPavel Labath   LLDB_LOG(log, "tid: {0}", thread.GetID());
22161dbc6c9cSPavel Labath 
2217b9c1b51eSKate Stone   if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID &&
2218b9c1b51eSKate Stone       StateIsRunningState(thread.GetState())) {
2219b9c1b51eSKate Stone     // We will need to wait for this new thread to stop as well before firing
2220b9c1b51eSKate Stone     // the
2221c076559aSPavel Labath     // notification.
2222f9077782SPavel Labath     thread.RequestStop();
2223c076559aSPavel Labath   }
2224c076559aSPavel Labath }
2225068f8a7eSTamas Berghammer 
2226b9c1b51eSKate Stone void NativeProcessLinux::SigchldHandler() {
2227a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
222819cbe96aSPavel Labath   // Process all pending waitpid notifications.
2229b9c1b51eSKate Stone   while (true) {
223019cbe96aSPavel Labath     int status = -1;
2231c1a6b128SPavel Labath     ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, -1, &status,
2232c1a6b128SPavel Labath                                           __WALL | __WNOTHREAD | WNOHANG);
223319cbe96aSPavel Labath 
223419cbe96aSPavel Labath     if (wait_pid == 0)
223519cbe96aSPavel Labath       break; // We are done.
223619cbe96aSPavel Labath 
2237b9c1b51eSKate Stone     if (wait_pid == -1) {
223897206d57SZachary Turner       Status error(errno, eErrorTypePOSIX);
2239a6321a8eSPavel Labath       LLDB_LOG(log, "waitpid (-1, &status, _) failed: {0}", error);
224019cbe96aSPavel Labath       break;
224119cbe96aSPavel Labath     }
224219cbe96aSPavel Labath 
22433508fc8cSPavel Labath     WaitStatus wait_status = WaitStatus::Decode(status);
22443508fc8cSPavel Labath     bool exited = wait_status.type == WaitStatus::Exit ||
22453508fc8cSPavel Labath                   (wait_status.type == WaitStatus::Signal &&
22463508fc8cSPavel Labath                    wait_pid == static_cast<::pid_t>(GetID()));
224719cbe96aSPavel Labath 
22483508fc8cSPavel Labath     LLDB_LOG(
22493508fc8cSPavel Labath         log,
22503508fc8cSPavel Labath         "waitpid (-1, &status, _) => pid = {0}, status = {1}, exited = {2}",
22513508fc8cSPavel Labath         wait_pid, wait_status, exited);
225219cbe96aSPavel Labath 
22533508fc8cSPavel Labath     MonitorCallback(wait_pid, exited, wait_status);
225419cbe96aSPavel Labath   }
2255068f8a7eSTamas Berghammer }
2256068f8a7eSTamas Berghammer 
2257068f8a7eSTamas Berghammer // Wrapper for ptrace to catch errors and log calls.
2258b9c1b51eSKate Stone // Note that ptrace sets errno on error because -1 can be a valid result (i.e.
2259b9c1b51eSKate Stone // for PTRACE_PEEK*)
226097206d57SZachary Turner Status NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
2261b9c1b51eSKate Stone                                          void *data, size_t data_size,
2262b9c1b51eSKate Stone                                          long *result) {
226397206d57SZachary Turner   Status error;
22644a9babb2SPavel Labath   long int ret;
2265068f8a7eSTamas Berghammer 
2266068f8a7eSTamas Berghammer   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2267068f8a7eSTamas Berghammer 
2268068f8a7eSTamas Berghammer   PtraceDisplayBytes(req, data, data_size);
2269068f8a7eSTamas Berghammer 
2270068f8a7eSTamas Berghammer   errno = 0;
2271068f8a7eSTamas Berghammer   if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
2272b9c1b51eSKate Stone     ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2273b9c1b51eSKate Stone                  *(unsigned int *)addr, data);
2274068f8a7eSTamas Berghammer   else
2275b9c1b51eSKate Stone     ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2276b9c1b51eSKate Stone                  addr, data);
2277068f8a7eSTamas Berghammer 
22784a9babb2SPavel Labath   if (ret == -1)
2279068f8a7eSTamas Berghammer     error.SetErrorToErrno();
2280068f8a7eSTamas Berghammer 
22814a9babb2SPavel Labath   if (result)
22824a9babb2SPavel Labath     *result = ret;
22834a9babb2SPavel Labath 
228428096200SPavel Labath   LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data,
228528096200SPavel Labath            data_size, ret);
2286068f8a7eSTamas Berghammer 
2287068f8a7eSTamas Berghammer   PtraceDisplayBytes(req, data, data_size);
2288068f8a7eSTamas Berghammer 
2289a6321a8eSPavel Labath   if (error.Fail())
2290a6321a8eSPavel Labath     LLDB_LOG(log, "ptrace() failed: {0}", error);
2291068f8a7eSTamas Berghammer 
22924a9babb2SPavel Labath   return error;
2293068f8a7eSTamas Berghammer }
229499e37695SRavitheja Addepally 
229599e37695SRavitheja Addepally llvm::Expected<ProcessorTraceMonitor &>
229699e37695SRavitheja Addepally NativeProcessLinux::LookupProcessorTraceInstance(lldb::user_id_t traceid,
229799e37695SRavitheja Addepally                                                  lldb::tid_t thread) {
229899e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
229999e37695SRavitheja Addepally   if (thread == LLDB_INVALID_THREAD_ID && traceid == m_pt_proces_trace_id) {
230099e37695SRavitheja Addepally     LLDB_LOG(log, "thread not specified: {0}", traceid);
230199e37695SRavitheja Addepally     return Status("tracing not active thread not specified").ToError();
230299e37695SRavitheja Addepally   }
230399e37695SRavitheja Addepally 
230499e37695SRavitheja Addepally   for (auto& iter : m_processor_trace_monitor) {
230599e37695SRavitheja Addepally     if (traceid == iter.second->GetTraceID() &&
230699e37695SRavitheja Addepally         (thread == iter.first || thread == LLDB_INVALID_THREAD_ID))
230799e37695SRavitheja Addepally       return *(iter.second);
230899e37695SRavitheja Addepally   }
230999e37695SRavitheja Addepally 
231099e37695SRavitheja Addepally   LLDB_LOG(log, "traceid not being traced: {0}", traceid);
231199e37695SRavitheja Addepally   return Status("tracing not active for this thread").ToError();
231299e37695SRavitheja Addepally }
231399e37695SRavitheja Addepally 
231499e37695SRavitheja Addepally Status NativeProcessLinux::GetMetaData(lldb::user_id_t traceid,
231599e37695SRavitheja Addepally                                        lldb::tid_t thread,
231699e37695SRavitheja Addepally                                        llvm::MutableArrayRef<uint8_t> &buffer,
231799e37695SRavitheja Addepally                                        size_t offset) {
231899e37695SRavitheja Addepally   TraceOptions trace_options;
231999e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
232099e37695SRavitheja Addepally   Status error;
232199e37695SRavitheja Addepally 
232299e37695SRavitheja Addepally   LLDB_LOG(log, "traceid {0}", traceid);
232399e37695SRavitheja Addepally 
232499e37695SRavitheja Addepally   auto perf_monitor = LookupProcessorTraceInstance(traceid, thread);
232599e37695SRavitheja Addepally   if (!perf_monitor) {
232699e37695SRavitheja Addepally     LLDB_LOG(log, "traceid not being traced: {0}", traceid);
232799e37695SRavitheja Addepally     buffer = buffer.slice(buffer.size());
232899e37695SRavitheja Addepally     error = perf_monitor.takeError();
232999e37695SRavitheja Addepally     return error;
233099e37695SRavitheja Addepally   }
233199e37695SRavitheja Addepally   return (*perf_monitor).ReadPerfTraceData(buffer, offset);
233299e37695SRavitheja Addepally }
233399e37695SRavitheja Addepally 
233499e37695SRavitheja Addepally Status NativeProcessLinux::GetData(lldb::user_id_t traceid, lldb::tid_t thread,
233599e37695SRavitheja Addepally                                    llvm::MutableArrayRef<uint8_t> &buffer,
233699e37695SRavitheja Addepally                                    size_t offset) {
233799e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
233899e37695SRavitheja Addepally   Status error;
233999e37695SRavitheja Addepally 
234099e37695SRavitheja Addepally   LLDB_LOG(log, "traceid {0}", traceid);
234199e37695SRavitheja Addepally 
234299e37695SRavitheja Addepally   auto perf_monitor = LookupProcessorTraceInstance(traceid, thread);
234399e37695SRavitheja Addepally   if (!perf_monitor) {
234499e37695SRavitheja Addepally     LLDB_LOG(log, "traceid not being traced: {0}", traceid);
234599e37695SRavitheja Addepally     buffer = buffer.slice(buffer.size());
234699e37695SRavitheja Addepally     error = perf_monitor.takeError();
234799e37695SRavitheja Addepally     return error;
234899e37695SRavitheja Addepally   }
234999e37695SRavitheja Addepally   return (*perf_monitor).ReadPerfTraceAux(buffer, offset);
235099e37695SRavitheja Addepally }
235199e37695SRavitheja Addepally 
235299e37695SRavitheja Addepally Status NativeProcessLinux::GetTraceConfig(lldb::user_id_t traceid,
235399e37695SRavitheja Addepally                                           TraceOptions &config) {
235499e37695SRavitheja Addepally   Status error;
235599e37695SRavitheja Addepally   if (config.getThreadID() == LLDB_INVALID_THREAD_ID &&
235699e37695SRavitheja Addepally       m_pt_proces_trace_id == traceid) {
235799e37695SRavitheja Addepally     if (m_pt_proces_trace_id == LLDB_INVALID_UID) {
235899e37695SRavitheja Addepally       error.SetErrorString("tracing not active for this process");
235999e37695SRavitheja Addepally       return error;
236099e37695SRavitheja Addepally     }
236199e37695SRavitheja Addepally     config = m_pt_process_trace_config;
236299e37695SRavitheja Addepally   } else {
236399e37695SRavitheja Addepally     auto perf_monitor =
236499e37695SRavitheja Addepally         LookupProcessorTraceInstance(traceid, config.getThreadID());
236599e37695SRavitheja Addepally     if (!perf_monitor) {
236699e37695SRavitheja Addepally       error = perf_monitor.takeError();
236799e37695SRavitheja Addepally       return error;
236899e37695SRavitheja Addepally     }
236999e37695SRavitheja Addepally     error = (*perf_monitor).GetTraceConfig(config);
237099e37695SRavitheja Addepally   }
237199e37695SRavitheja Addepally   return error;
237299e37695SRavitheja Addepally }
237399e37695SRavitheja Addepally 
237499e37695SRavitheja Addepally lldb::user_id_t
237599e37695SRavitheja Addepally NativeProcessLinux::StartTraceGroup(const TraceOptions &config,
237699e37695SRavitheja Addepally                                            Status &error) {
237799e37695SRavitheja Addepally 
237899e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
237999e37695SRavitheja Addepally   if (config.getType() != TraceType::eTraceTypeProcessorTrace)
238099e37695SRavitheja Addepally     return LLDB_INVALID_UID;
238199e37695SRavitheja Addepally 
238299e37695SRavitheja Addepally   if (m_pt_proces_trace_id != LLDB_INVALID_UID) {
238399e37695SRavitheja Addepally     error.SetErrorString("tracing already active on this process");
238499e37695SRavitheja Addepally     return m_pt_proces_trace_id;
238599e37695SRavitheja Addepally   }
238699e37695SRavitheja Addepally 
238799e37695SRavitheja Addepally   for (const auto &thread_sp : m_threads) {
238899e37695SRavitheja Addepally     if (auto traceInstance = ProcessorTraceMonitor::Create(
238999e37695SRavitheja Addepally             GetID(), thread_sp->GetID(), config, true)) {
239099e37695SRavitheja Addepally       m_pt_traced_thread_group.insert(thread_sp->GetID());
239199e37695SRavitheja Addepally       m_processor_trace_monitor.insert(
239299e37695SRavitheja Addepally           std::make_pair(thread_sp->GetID(), std::move(*traceInstance)));
239399e37695SRavitheja Addepally     }
239499e37695SRavitheja Addepally   }
239599e37695SRavitheja Addepally 
239699e37695SRavitheja Addepally   m_pt_process_trace_config = config;
239799e37695SRavitheja Addepally   error = ProcessorTraceMonitor::GetCPUType(m_pt_process_trace_config);
239899e37695SRavitheja Addepally 
239999e37695SRavitheja Addepally   // Trace on Complete process will have traceid of 0
240099e37695SRavitheja Addepally   m_pt_proces_trace_id = 0;
240199e37695SRavitheja Addepally 
240299e37695SRavitheja Addepally   LLDB_LOG(log, "Process Trace ID {0}", m_pt_proces_trace_id);
240399e37695SRavitheja Addepally   return m_pt_proces_trace_id;
240499e37695SRavitheja Addepally }
240599e37695SRavitheja Addepally 
240699e37695SRavitheja Addepally lldb::user_id_t NativeProcessLinux::StartTrace(const TraceOptions &config,
240799e37695SRavitheja Addepally                                                Status &error) {
240899e37695SRavitheja Addepally   if (config.getType() != TraceType::eTraceTypeProcessorTrace)
240999e37695SRavitheja Addepally     return NativeProcessProtocol::StartTrace(config, error);
241099e37695SRavitheja Addepally 
241199e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
241299e37695SRavitheja Addepally 
241399e37695SRavitheja Addepally   lldb::tid_t threadid = config.getThreadID();
241499e37695SRavitheja Addepally 
241599e37695SRavitheja Addepally   if (threadid == LLDB_INVALID_THREAD_ID)
241699e37695SRavitheja Addepally     return StartTraceGroup(config, error);
241799e37695SRavitheja Addepally 
241899e37695SRavitheja Addepally   auto thread_sp = GetThreadByID(threadid);
241999e37695SRavitheja Addepally   if (!thread_sp) {
242099e37695SRavitheja Addepally     // Thread not tracked by lldb so don't trace.
242199e37695SRavitheja Addepally     error.SetErrorString("invalid thread id");
242299e37695SRavitheja Addepally     return LLDB_INVALID_UID;
242399e37695SRavitheja Addepally   }
242499e37695SRavitheja Addepally 
242599e37695SRavitheja Addepally   const auto &iter = m_processor_trace_monitor.find(threadid);
242699e37695SRavitheja Addepally   if (iter != m_processor_trace_monitor.end()) {
242799e37695SRavitheja Addepally     LLDB_LOG(log, "Thread already being traced");
242899e37695SRavitheja Addepally     error.SetErrorString("tracing already active on this thread");
242999e37695SRavitheja Addepally     return LLDB_INVALID_UID;
243099e37695SRavitheja Addepally   }
243199e37695SRavitheja Addepally 
243299e37695SRavitheja Addepally   auto traceMonitor =
243399e37695SRavitheja Addepally       ProcessorTraceMonitor::Create(GetID(), threadid, config, false);
243499e37695SRavitheja Addepally   if (!traceMonitor) {
243599e37695SRavitheja Addepally     error = traceMonitor.takeError();
243699e37695SRavitheja Addepally     LLDB_LOG(log, "error {0}", error);
243799e37695SRavitheja Addepally     return LLDB_INVALID_UID;
243899e37695SRavitheja Addepally   }
243999e37695SRavitheja Addepally   lldb::user_id_t ret_trace_id = (*traceMonitor)->GetTraceID();
244099e37695SRavitheja Addepally   m_processor_trace_monitor.insert(
244199e37695SRavitheja Addepally       std::make_pair(threadid, std::move(*traceMonitor)));
244299e37695SRavitheja Addepally   return ret_trace_id;
244399e37695SRavitheja Addepally }
244499e37695SRavitheja Addepally 
244599e37695SRavitheja Addepally Status NativeProcessLinux::StopTracingForThread(lldb::tid_t thread) {
244699e37695SRavitheja Addepally   Status error;
244799e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
244899e37695SRavitheja Addepally   LLDB_LOG(log, "Thread {0}", thread);
244999e37695SRavitheja Addepally 
245099e37695SRavitheja Addepally   const auto& iter = m_processor_trace_monitor.find(thread);
245199e37695SRavitheja Addepally   if (iter == m_processor_trace_monitor.end()) {
245299e37695SRavitheja Addepally     error.SetErrorString("tracing not active for this thread");
245399e37695SRavitheja Addepally     return error;
245499e37695SRavitheja Addepally   }
245599e37695SRavitheja Addepally 
245699e37695SRavitheja Addepally   if (iter->second->GetTraceID() == m_pt_proces_trace_id) {
245799e37695SRavitheja Addepally     // traceid maps to the whole process so we have to erase it from the
245899e37695SRavitheja Addepally     // thread group.
245999e37695SRavitheja Addepally     LLDB_LOG(log, "traceid maps to process");
246099e37695SRavitheja Addepally     m_pt_traced_thread_group.erase(thread);
246199e37695SRavitheja Addepally   }
246299e37695SRavitheja Addepally   m_processor_trace_monitor.erase(iter);
246399e37695SRavitheja Addepally 
246499e37695SRavitheja Addepally   return error;
246599e37695SRavitheja Addepally }
246699e37695SRavitheja Addepally 
246799e37695SRavitheja Addepally Status NativeProcessLinux::StopTrace(lldb::user_id_t traceid,
246899e37695SRavitheja Addepally                                      lldb::tid_t thread) {
246999e37695SRavitheja Addepally   Status error;
247099e37695SRavitheja Addepally 
247199e37695SRavitheja Addepally   TraceOptions trace_options;
247299e37695SRavitheja Addepally   trace_options.setThreadID(thread);
247399e37695SRavitheja Addepally   error = NativeProcessLinux::GetTraceConfig(traceid, trace_options);
247499e37695SRavitheja Addepally 
247599e37695SRavitheja Addepally   if (error.Fail())
247699e37695SRavitheja Addepally     return error;
247799e37695SRavitheja Addepally 
247899e37695SRavitheja Addepally   switch (trace_options.getType()) {
247999e37695SRavitheja Addepally   case lldb::TraceType::eTraceTypeProcessorTrace:
248099e37695SRavitheja Addepally     if (traceid == m_pt_proces_trace_id &&
248199e37695SRavitheja Addepally         thread == LLDB_INVALID_THREAD_ID)
248299e37695SRavitheja Addepally       StopProcessorTracingOnProcess();
248399e37695SRavitheja Addepally     else
248499e37695SRavitheja Addepally       error = StopProcessorTracingOnThread(traceid, thread);
248599e37695SRavitheja Addepally     break;
248699e37695SRavitheja Addepally   default:
248799e37695SRavitheja Addepally     error.SetErrorString("trace not supported");
248899e37695SRavitheja Addepally     break;
248999e37695SRavitheja Addepally   }
249099e37695SRavitheja Addepally 
249199e37695SRavitheja Addepally   return error;
249299e37695SRavitheja Addepally }
249399e37695SRavitheja Addepally 
249499e37695SRavitheja Addepally void NativeProcessLinux::StopProcessorTracingOnProcess() {
249599e37695SRavitheja Addepally   for (auto thread_id_iter : m_pt_traced_thread_group)
249699e37695SRavitheja Addepally     m_processor_trace_monitor.erase(thread_id_iter);
249799e37695SRavitheja Addepally   m_pt_traced_thread_group.clear();
249899e37695SRavitheja Addepally   m_pt_proces_trace_id = LLDB_INVALID_UID;
249999e37695SRavitheja Addepally }
250099e37695SRavitheja Addepally 
250199e37695SRavitheja Addepally Status NativeProcessLinux::StopProcessorTracingOnThread(lldb::user_id_t traceid,
250299e37695SRavitheja Addepally                                                         lldb::tid_t thread) {
250399e37695SRavitheja Addepally   Status error;
250499e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
250599e37695SRavitheja Addepally 
250699e37695SRavitheja Addepally   if (thread == LLDB_INVALID_THREAD_ID) {
250799e37695SRavitheja Addepally     for (auto& iter : m_processor_trace_monitor) {
250899e37695SRavitheja Addepally       if (iter.second->GetTraceID() == traceid) {
250999e37695SRavitheja Addepally         // Stopping a trace instance for an individual thread
251099e37695SRavitheja Addepally         // hence there will only be one traceid that can match.
251199e37695SRavitheja Addepally         m_processor_trace_monitor.erase(iter.first);
251299e37695SRavitheja Addepally         return error;
251399e37695SRavitheja Addepally       }
251499e37695SRavitheja Addepally       LLDB_LOG(log, "Trace ID {0}", iter.second->GetTraceID());
251599e37695SRavitheja Addepally     }
251699e37695SRavitheja Addepally 
251799e37695SRavitheja Addepally     LLDB_LOG(log, "Invalid TraceID");
251899e37695SRavitheja Addepally     error.SetErrorString("invalid trace id");
251999e37695SRavitheja Addepally     return error;
252099e37695SRavitheja Addepally   }
252199e37695SRavitheja Addepally 
252299e37695SRavitheja Addepally   // thread is specified so we can use find function on the map.
252399e37695SRavitheja Addepally   const auto& iter = m_processor_trace_monitor.find(thread);
252499e37695SRavitheja Addepally   if (iter == m_processor_trace_monitor.end()) {
252599e37695SRavitheja Addepally     // thread not found in our map.
252699e37695SRavitheja Addepally     LLDB_LOG(log, "thread not being traced");
252799e37695SRavitheja Addepally     error.SetErrorString("tracing not active for this thread");
252899e37695SRavitheja Addepally     return error;
252999e37695SRavitheja Addepally   }
253099e37695SRavitheja Addepally   if (iter->second->GetTraceID() != traceid) {
253199e37695SRavitheja Addepally     // traceid did not match so it has to be invalid.
253299e37695SRavitheja Addepally     LLDB_LOG(log, "Invalid TraceID");
253399e37695SRavitheja Addepally     error.SetErrorString("invalid trace id");
253499e37695SRavitheja Addepally     return error;
253599e37695SRavitheja Addepally   }
253699e37695SRavitheja Addepally 
253799e37695SRavitheja Addepally   LLDB_LOG(log, "UID - {0} , Thread -{1}", traceid, thread);
253899e37695SRavitheja Addepally 
253999e37695SRavitheja Addepally   if (traceid == m_pt_proces_trace_id) {
254099e37695SRavitheja Addepally     // traceid maps to the whole process so we have to erase it from the
254199e37695SRavitheja Addepally     // thread group.
254299e37695SRavitheja Addepally     LLDB_LOG(log, "traceid maps to process");
254399e37695SRavitheja Addepally     m_pt_traced_thread_group.erase(thread);
254499e37695SRavitheja Addepally   }
254599e37695SRavitheja Addepally   m_processor_trace_monitor.erase(iter);
254699e37695SRavitheja Addepally 
254799e37695SRavitheja Addepally   return error;
254899e37695SRavitheja Addepally }
2549