180814287SRaphael Isemann //===-- NativeProcessLinux.cpp --------------------------------------------===//
2af245d11STodd Fiala //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6af245d11STodd Fiala //
7af245d11STodd Fiala //===----------------------------------------------------------------------===//
8af245d11STodd Fiala 
9af245d11STodd Fiala #include "NativeProcessLinux.h"
10af245d11STodd Fiala 
1176e47d48SRaphael Isemann #include <cerrno>
1276e47d48SRaphael Isemann #include <cstdint>
1376e47d48SRaphael Isemann #include <cstring>
14af245d11STodd Fiala #include <unistd.h>
15af245d11STodd Fiala 
16af245d11STodd Fiala #include <fstream>
17df7c6995SPavel Labath #include <mutex>
18c076559aSPavel Labath #include <sstream>
19af245d11STodd Fiala #include <string>
205b981ab9SPavel Labath #include <unordered_map>
21af245d11STodd Fiala 
222c4226f8SPavel Labath #include "NativeThreadLinux.h"
232c4226f8SPavel Labath #include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
242c4226f8SPavel Labath #include "Plugins/Process/Utility/LinuxProcMaps.h"
252c4226f8SPavel Labath #include "Procfs.h"
266edef204SOleksiy Vyalov #include "lldb/Core/ModuleSpec.h"
27af245d11STodd Fiala #include "lldb/Host/Host.h"
285ad891f7SPavel Labath #include "lldb/Host/HostProcess.h"
29eef758e9SPavel Labath #include "lldb/Host/ProcessLaunchInfo.h"
3024ae6294SZachary Turner #include "lldb/Host/PseudoTerminal.h"
3139de3110SZachary Turner #include "lldb/Host/ThreadLauncher.h"
322a86b555SPavel Labath #include "lldb/Host/common/NativeRegisterContext.h"
33c8d18cbaSMichał Górny #include "lldb/Host/linux/Host.h"
344ee1c952SPavel Labath #include "lldb/Host/linux/Ptrace.h"
354ee1c952SPavel Labath #include "lldb/Host/linux/Uio.h"
36816ae4b0SKamil Rytarowski #include "lldb/Host/posix/ProcessLauncherPosixFork.h"
372a86b555SPavel Labath #include "lldb/Symbol/ObjectFile.h"
3890aff47cSZachary Turner #include "lldb/Target/Process.h"
395b981ab9SPavel Labath #include "lldb/Target/Target.h"
40c16f5dcaSChaoren Lin #include "lldb/Utility/LLDBAssert.h"
41d821c997SPavel Labath #include "lldb/Utility/State.h"
4297206d57SZachary Turner #include "lldb/Utility/Status.h"
43f805e190SPavel Labath #include "lldb/Utility/StringExtractor.h"
442c4226f8SPavel Labath #include "llvm/ADT/ScopeExit.h"
4510c41f37SPavel Labath #include "llvm/Support/Errno.h"
4610c41f37SPavel Labath #include "llvm/Support/FileSystem.h"
4710c41f37SPavel Labath #include "llvm/Support/Threading.h"
48af245d11STodd Fiala 
49d858487eSTamas Berghammer #include <linux/unistd.h>
50d858487eSTamas Berghammer #include <sys/socket.h>
51df7c6995SPavel Labath #include <sys/syscall.h>
52d858487eSTamas Berghammer #include <sys/types.h>
53d858487eSTamas Berghammer #include <sys/user.h>
54d858487eSTamas Berghammer #include <sys/wait.h>
55d858487eSTamas Berghammer 
568d58fbd0SDavid Spickett #ifdef __aarch64__
578d58fbd0SDavid Spickett #include <asm/hwcap.h>
588d58fbd0SDavid Spickett #include <sys/auxv.h>
598d58fbd0SDavid Spickett #endif
608d58fbd0SDavid Spickett 
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 
668d58fbd0SDavid Spickett #ifndef HWCAP2_MTE
678d58fbd0SDavid Spickett #define HWCAP2_MTE (1 << 18)
688d58fbd0SDavid Spickett #endif
698d58fbd0SDavid Spickett 
707cb18bf5STamas Berghammer using namespace lldb;
717cb18bf5STamas Berghammer using namespace lldb_private;
72db264a6dSTamas Berghammer using namespace lldb_private::process_linux;
737cb18bf5STamas Berghammer using namespace llvm;
747cb18bf5STamas Berghammer 
75af245d11STodd Fiala // Private bits we only need internally.
76df7c6995SPavel Labath 
77b9c1b51eSKate Stone static bool ProcessVmReadvSupported() {
78df7c6995SPavel Labath   static bool is_supported;
79c5f28e2aSKamil Rytarowski   static llvm::once_flag flag;
80df7c6995SPavel Labath 
81c5f28e2aSKamil Rytarowski   llvm::call_once(flag, [] {
82a6321a8eSPavel Labath     Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
83df7c6995SPavel Labath 
84df7c6995SPavel Labath     uint32_t source = 0x47424742;
85df7c6995SPavel Labath     uint32_t dest = 0;
86df7c6995SPavel Labath 
87df7c6995SPavel Labath     struct iovec local, remote;
88df7c6995SPavel Labath     remote.iov_base = &source;
89df7c6995SPavel Labath     local.iov_base = &dest;
90df7c6995SPavel Labath     remote.iov_len = local.iov_len = sizeof source;
91df7c6995SPavel Labath 
92b9c1b51eSKate Stone     // We shall try if cross-process-memory reads work by attempting to read a
93b9c1b51eSKate Stone     // value from our own process.
94df7c6995SPavel Labath     ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
95df7c6995SPavel Labath     is_supported = (res == sizeof(source) && source == dest);
96df7c6995SPavel Labath     if (is_supported)
97a6321a8eSPavel Labath       LLDB_LOG(log,
98a6321a8eSPavel Labath                "Detected kernel support for process_vm_readv syscall. "
99a6321a8eSPavel Labath                "Fast memory reads enabled.");
100df7c6995SPavel Labath     else
101a6321a8eSPavel Labath       LLDB_LOG(log,
102a6321a8eSPavel Labath                "syscall process_vm_readv failed (error: {0}). Fast memory "
103a6321a8eSPavel Labath                "reads disabled.",
10410c41f37SPavel Labath                llvm::sys::StrError());
105df7c6995SPavel Labath   });
106df7c6995SPavel Labath 
107df7c6995SPavel Labath   return is_supported;
108df7c6995SPavel Labath }
109df7c6995SPavel Labath 
11093c1b3caSPavel Labath static void MaybeLogLaunchInfo(const ProcessLaunchInfo &info) {
111a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1124abe5d69SPavel Labath   if (!log)
1134abe5d69SPavel Labath     return;
1144abe5d69SPavel Labath 
1154abe5d69SPavel Labath   if (const FileAction *action = info.GetFileActionForFD(STDIN_FILENO))
116a6321a8eSPavel Labath     LLDB_LOG(log, "setting STDIN to '{0}'", action->GetFileSpec());
1174abe5d69SPavel Labath   else
118a6321a8eSPavel Labath     LLDB_LOG(log, "leaving STDIN as is");
1194abe5d69SPavel Labath 
1204abe5d69SPavel Labath   if (const FileAction *action = info.GetFileActionForFD(STDOUT_FILENO))
121a6321a8eSPavel Labath     LLDB_LOG(log, "setting STDOUT to '{0}'", action->GetFileSpec());
1224abe5d69SPavel Labath   else
123a6321a8eSPavel Labath     LLDB_LOG(log, "leaving STDOUT as is");
1244abe5d69SPavel Labath 
1254abe5d69SPavel Labath   if (const FileAction *action = info.GetFileActionForFD(STDERR_FILENO))
126a6321a8eSPavel Labath     LLDB_LOG(log, "setting STDERR to '{0}'", action->GetFileSpec());
1274abe5d69SPavel Labath   else
128a6321a8eSPavel Labath     LLDB_LOG(log, "leaving STDERR as is");
1294abe5d69SPavel Labath 
1304abe5d69SPavel Labath   int i = 0;
131b9c1b51eSKate Stone   for (const char **args = info.GetArguments().GetConstArgumentVector(); *args;
132b9c1b51eSKate Stone        ++args, ++i)
133a6321a8eSPavel Labath     LLDB_LOG(log, "arg {0}: '{1}'", i, *args);
1344abe5d69SPavel Labath }
1354abe5d69SPavel Labath 
13693c1b3caSPavel Labath static void DisplayBytes(StreamString &s, void *bytes, uint32_t count) {
137af245d11STodd Fiala   uint8_t *ptr = (uint8_t *)bytes;
138af245d11STodd Fiala   const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
139b9c1b51eSKate Stone   for (uint32_t i = 0; i < loop_count; i++) {
140af245d11STodd Fiala     s.Printf("[%x]", *ptr);
141af245d11STodd Fiala     ptr++;
142af245d11STodd Fiala   }
143af245d11STodd Fiala }
144af245d11STodd Fiala 
14593c1b3caSPavel Labath static void PtraceDisplayBytes(int &req, void *data, size_t data_size) {
146aafe053cSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
147a6321a8eSPavel Labath   if (!log)
148a6321a8eSPavel Labath     return;
149af245d11STodd Fiala   StreamString buf;
150af245d11STodd Fiala 
151b9c1b51eSKate Stone   switch (req) {
152b9c1b51eSKate Stone   case PTRACE_POKETEXT: {
153af245d11STodd Fiala     DisplayBytes(buf, &data, 8);
154aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_POKETEXT {0}", buf.GetData());
155af245d11STodd Fiala     break;
156af245d11STodd Fiala   }
157b9c1b51eSKate Stone   case PTRACE_POKEDATA: {
158af245d11STodd Fiala     DisplayBytes(buf, &data, 8);
159aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_POKEDATA {0}", buf.GetData());
160af245d11STodd Fiala     break;
161af245d11STodd Fiala   }
162b9c1b51eSKate Stone   case PTRACE_POKEUSER: {
163af245d11STodd Fiala     DisplayBytes(buf, &data, 8);
164aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_POKEUSER {0}", buf.GetData());
165af245d11STodd Fiala     break;
166af245d11STodd Fiala   }
167b9c1b51eSKate Stone   case PTRACE_SETREGS: {
168af245d11STodd Fiala     DisplayBytes(buf, data, data_size);
169aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_SETREGS {0}", buf.GetData());
170af245d11STodd Fiala     break;
171af245d11STodd Fiala   }
172b9c1b51eSKate Stone   case PTRACE_SETFPREGS: {
173af245d11STodd Fiala     DisplayBytes(buf, data, data_size);
174aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_SETFPREGS {0}", buf.GetData());
175af245d11STodd Fiala     break;
176af245d11STodd Fiala   }
177b9c1b51eSKate Stone   case PTRACE_SETSIGINFO: {
178af245d11STodd Fiala     DisplayBytes(buf, data, sizeof(siginfo_t));
179aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_SETSIGINFO {0}", buf.GetData());
180af245d11STodd Fiala     break;
181af245d11STodd Fiala   }
182b9c1b51eSKate Stone   case PTRACE_SETREGSET: {
18311edb4eeSPavel Labath     // Extract iov_base from data, which is a pointer to the struct iovec
184af245d11STodd Fiala     DisplayBytes(buf, *(void **)data, data_size);
185aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_SETREGSET {0}", buf.GetData());
186af245d11STodd Fiala     break;
187af245d11STodd Fiala   }
188b9c1b51eSKate Stone   default: {}
189af245d11STodd Fiala   }
190af245d11STodd Fiala }
191af245d11STodd Fiala 
19219cbe96aSPavel Labath static constexpr unsigned k_ptrace_word_size = sizeof(void *);
193b9c1b51eSKate Stone static_assert(sizeof(long) >= k_ptrace_word_size,
194b9c1b51eSKate Stone               "Size of long must be larger than ptrace word size");
1951107b5a5SPavel Labath 
196bd7cbc5aSPavel Labath // Simple helper function to ensure flags are enabled on the given file
197bd7cbc5aSPavel Labath // descriptor.
19897206d57SZachary Turner static Status EnsureFDFlags(int fd, int flags) {
19997206d57SZachary Turner   Status error;
200bd7cbc5aSPavel Labath 
201bd7cbc5aSPavel Labath   int status = fcntl(fd, F_GETFL);
202b9c1b51eSKate Stone   if (status == -1) {
203bd7cbc5aSPavel Labath     error.SetErrorToErrno();
204bd7cbc5aSPavel Labath     return error;
205bd7cbc5aSPavel Labath   }
206bd7cbc5aSPavel Labath 
207b9c1b51eSKate Stone   if (fcntl(fd, F_SETFL, status | flags) == -1) {
208bd7cbc5aSPavel Labath     error.SetErrorToErrno();
209bd7cbc5aSPavel Labath     return error;
210bd7cbc5aSPavel Labath   }
211bd7cbc5aSPavel Labath 
212bd7cbc5aSPavel Labath   return error;
213bd7cbc5aSPavel Labath }
214bd7cbc5aSPavel Labath 
215af245d11STodd Fiala // Public Static Methods
216af245d11STodd Fiala 
21782abefa4SPavel Labath llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
21896e600fcSPavel Labath NativeProcessLinux::Factory::Launch(ProcessLaunchInfo &launch_info,
21996e600fcSPavel Labath                                     NativeDelegate &native_delegate,
22096e600fcSPavel Labath                                     MainLoop &mainloop) const {
221a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
222af245d11STodd Fiala 
22396e600fcSPavel Labath   MaybeLogLaunchInfo(launch_info);
224af245d11STodd Fiala 
22596e600fcSPavel Labath   Status status;
22696e600fcSPavel Labath   ::pid_t pid = ProcessLauncherPosixFork()
22796e600fcSPavel Labath                     .LaunchProcess(launch_info, status)
22896e600fcSPavel Labath                     .GetProcessId();
22996e600fcSPavel Labath   LLDB_LOG(log, "pid = {0:x}", pid);
23096e600fcSPavel Labath   if (status.Fail()) {
23196e600fcSPavel Labath     LLDB_LOG(log, "failed to launch process: {0}", status);
23296e600fcSPavel Labath     return status.ToError();
233af245d11STodd Fiala   }
234af245d11STodd Fiala 
23596e600fcSPavel Labath   // Wait for the child process to trap on its call to execve.
23696e600fcSPavel Labath   int wstatus;
23796e600fcSPavel Labath   ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0);
23896e600fcSPavel Labath   assert(wpid == pid);
23996e600fcSPavel Labath   (void)wpid;
24096e600fcSPavel Labath   if (!WIFSTOPPED(wstatus)) {
24196e600fcSPavel Labath     LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}",
24296e600fcSPavel Labath              WaitStatus::Decode(wstatus));
24396e600fcSPavel Labath     return llvm::make_error<StringError>("Could not sync with inferior process",
24496e600fcSPavel Labath                                          llvm::inconvertibleErrorCode());
24596e600fcSPavel Labath   }
24696e600fcSPavel Labath   LLDB_LOG(log, "inferior started, now in stopped state");
247af245d11STodd Fiala 
24836e82208SPavel Labath   ProcessInstanceInfo Info;
24936e82208SPavel Labath   if (!Host::GetProcessInfo(pid, Info)) {
25036e82208SPavel Labath     return llvm::make_error<StringError>("Cannot get process architecture",
25136e82208SPavel Labath                                          llvm::inconvertibleErrorCode());
25236e82208SPavel Labath   }
25396e600fcSPavel Labath 
25496e600fcSPavel Labath   // Set the architecture to the exe architecture.
25596e600fcSPavel Labath   LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid,
25636e82208SPavel Labath            Info.GetArchitecture().GetArchitectureName());
25796e600fcSPavel Labath 
25896e600fcSPavel Labath   status = SetDefaultPtraceOpts(pid);
25996e600fcSPavel Labath   if (status.Fail()) {
26096e600fcSPavel Labath     LLDB_LOG(log, "failed to set default ptrace options: {0}", status);
26196e600fcSPavel Labath     return status.ToError();
262af245d11STodd Fiala   }
263af245d11STodd Fiala 
26482abefa4SPavel Labath   return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
26564ec505dSJonas Devlieghere       pid, launch_info.GetPTY().ReleasePrimaryFileDescriptor(), native_delegate,
26636e82208SPavel Labath       Info.GetArchitecture(), mainloop, {pid}));
267af245d11STodd Fiala }
268af245d11STodd Fiala 
26982abefa4SPavel Labath llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
27082abefa4SPavel Labath NativeProcessLinux::Factory::Attach(
271b9c1b51eSKate Stone     lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
27296e600fcSPavel Labath     MainLoop &mainloop) const {
273a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
274a6321a8eSPavel Labath   LLDB_LOG(log, "pid = {0:x}", pid);
275af245d11STodd Fiala 
276af245d11STodd Fiala   // Retrieve the architecture for the running process.
27736e82208SPavel Labath   ProcessInstanceInfo Info;
27836e82208SPavel Labath   if (!Host::GetProcessInfo(pid, Info)) {
27936e82208SPavel Labath     return llvm::make_error<StringError>("Cannot get process architecture",
28036e82208SPavel Labath                                          llvm::inconvertibleErrorCode());
28136e82208SPavel Labath   }
282af245d11STodd Fiala 
28396e600fcSPavel Labath   auto tids_or = NativeProcessLinux::Attach(pid);
28496e600fcSPavel Labath   if (!tids_or)
28596e600fcSPavel Labath     return tids_or.takeError();
286af245d11STodd Fiala 
28782abefa4SPavel Labath   return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
28836e82208SPavel Labath       pid, -1, native_delegate, Info.GetArchitecture(), mainloop, *tids_or));
289af245d11STodd Fiala }
290af245d11STodd Fiala 
291fd0af0cfSMichał Górny NativeProcessLinux::Extension
292fd0af0cfSMichał Górny NativeProcessLinux::Factory::GetSupportedExtensions() const {
2938d58fbd0SDavid Spickett   NativeProcessLinux::Extension supported =
2948d58fbd0SDavid Spickett       Extension::multiprocess | Extension::fork | Extension::vfork |
295ca7824c2SMichał Górny       Extension::pass_signals | Extension::auxv | Extension::libraries_svr4;
2968d58fbd0SDavid Spickett 
2978d58fbd0SDavid Spickett #ifdef __aarch64__
2988d58fbd0SDavid Spickett   // At this point we do not have a process so read auxv directly.
2998d58fbd0SDavid Spickett   if ((getauxval(AT_HWCAP2) & HWCAP2_MTE))
3008d58fbd0SDavid Spickett     supported |= Extension::memory_tagging;
3018d58fbd0SDavid Spickett #endif
3028d58fbd0SDavid Spickett 
3038d58fbd0SDavid Spickett   return supported;
304fd0af0cfSMichał Górny }
305fd0af0cfSMichał Górny 
306af245d11STodd Fiala // Public Instance Methods
307af245d11STodd Fiala 
30896e600fcSPavel Labath NativeProcessLinux::NativeProcessLinux(::pid_t pid, int terminal_fd,
30996e600fcSPavel Labath                                        NativeDelegate &delegate,
31082abefa4SPavel Labath                                        const ArchSpec &arch, MainLoop &mainloop,
31182abefa4SPavel Labath                                        llvm::ArrayRef<::pid_t> tids)
3120b697561SWalter Erquinigo     : NativeProcessELF(pid, terminal_fd, delegate), m_arch(arch),
313fd0af0cfSMichał Górny       m_main_loop(mainloop), m_intel_pt_manager(pid) {
314b9c1b51eSKate Stone   if (m_terminal_fd != -1) {
31596e600fcSPavel Labath     Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
31696e600fcSPavel Labath     assert(status.Success());
3175ad891f7SPavel Labath   }
318af245d11STodd Fiala 
31996e600fcSPavel Labath   Status status;
32096e600fcSPavel Labath   m_sigchld_handle = mainloop.RegisterSignal(
32196e600fcSPavel Labath       SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status);
32296e600fcSPavel Labath   assert(m_sigchld_handle && status.Success());
32396e600fcSPavel Labath 
32496e600fcSPavel Labath   for (const auto &tid : tids) {
3250b697561SWalter Erquinigo     NativeThreadLinux &thread = AddThread(tid, /*resume*/ false);
326a5be48b3SPavel Labath     ThreadWasCreated(thread);
327af245d11STodd Fiala   }
328af245d11STodd Fiala 
32996e600fcSPavel Labath   // Let our process instance know the thread has stopped.
33096e600fcSPavel Labath   SetCurrentThreadID(tids[0]);
33196e600fcSPavel Labath   SetState(StateType::eStateStopped, false);
33296e600fcSPavel Labath 
33396e600fcSPavel Labath   // Proccess any signals we received before installing our handler
33496e600fcSPavel Labath   SigchldHandler();
33596e600fcSPavel Labath }
33696e600fcSPavel Labath 
33796e600fcSPavel Labath llvm::Expected<std::vector<::pid_t>> NativeProcessLinux::Attach(::pid_t pid) {
338a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
339af245d11STodd Fiala 
34096e600fcSPavel Labath   Status status;
341b9c1b51eSKate Stone   // Use a map to keep track of the threads which we have attached/need to
342b9c1b51eSKate Stone   // attach.
343af245d11STodd Fiala   Host::TidMap tids_to_attach;
344b9c1b51eSKate Stone   while (Host::FindProcessThreads(pid, tids_to_attach)) {
345af245d11STodd Fiala     for (Host::TidMap::iterator it = tids_to_attach.begin();
346b9c1b51eSKate Stone          it != tids_to_attach.end();) {
347b9c1b51eSKate Stone       if (it->second == false) {
348af245d11STodd Fiala         lldb::tid_t tid = it->first;
349af245d11STodd Fiala 
350af245d11STodd Fiala         // Attach to the requested process.
351af245d11STodd Fiala         // An attach will cause the thread to stop with a SIGSTOP.
35296e600fcSPavel Labath         if ((status = PtraceWrapper(PTRACE_ATTACH, tid)).Fail()) {
35305097246SAdrian Prantl           // No such thread. The thread may have exited. More error handling
35405097246SAdrian Prantl           // may be needed.
35596e600fcSPavel Labath           if (status.GetError() == ESRCH) {
356af245d11STodd Fiala             it = tids_to_attach.erase(it);
357af245d11STodd Fiala             continue;
35896e600fcSPavel Labath           }
35996e600fcSPavel Labath           return status.ToError();
360af245d11STodd Fiala         }
361af245d11STodd Fiala 
36296e600fcSPavel Labath         int wpid =
36396e600fcSPavel Labath             llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, nullptr, __WALL);
36405097246SAdrian Prantl         // Need to use __WALL otherwise we receive an error with errno=ECHLD At
36505097246SAdrian Prantl         // this point we should have a thread stopped if waitpid succeeds.
36696e600fcSPavel Labath         if (wpid < 0) {
36705097246SAdrian Prantl           // No such thread. The thread may have exited. More error handling
36805097246SAdrian Prantl           // may be needed.
369b9c1b51eSKate Stone           if (errno == ESRCH) {
370af245d11STodd Fiala             it = tids_to_attach.erase(it);
371af245d11STodd Fiala             continue;
372af245d11STodd Fiala           }
37396e600fcSPavel Labath           return llvm::errorCodeToError(
37496e600fcSPavel Labath               std::error_code(errno, std::generic_category()));
375af245d11STodd Fiala         }
376af245d11STodd Fiala 
37796e600fcSPavel Labath         if ((status = SetDefaultPtraceOpts(tid)).Fail())
37896e600fcSPavel Labath           return status.ToError();
379af245d11STodd Fiala 
380a6321a8eSPavel Labath         LLDB_LOG(log, "adding tid = {0}", tid);
381af245d11STodd Fiala         it->second = true;
382af245d11STodd Fiala       }
383af245d11STodd Fiala 
384af245d11STodd Fiala       // move the loop forward
385af245d11STodd Fiala       ++it;
386af245d11STodd Fiala     }
387af245d11STodd Fiala   }
388af245d11STodd Fiala 
38996e600fcSPavel Labath   size_t tid_count = tids_to_attach.size();
39096e600fcSPavel Labath   if (tid_count == 0)
39196e600fcSPavel Labath     return llvm::make_error<StringError>("No such process",
39296e600fcSPavel Labath                                          llvm::inconvertibleErrorCode());
393af245d11STodd Fiala 
39496e600fcSPavel Labath   std::vector<::pid_t> tids;
39596e600fcSPavel Labath   tids.reserve(tid_count);
39696e600fcSPavel Labath   for (const auto &p : tids_to_attach)
39796e600fcSPavel Labath     tids.push_back(p.first);
39896e600fcSPavel Labath   return std::move(tids);
399af245d11STodd Fiala }
400af245d11STodd Fiala 
40197206d57SZachary Turner Status NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid) {
402af245d11STodd Fiala   long ptrace_opts = 0;
403af245d11STodd Fiala 
404af245d11STodd Fiala   // Have the child raise an event on exit.  This is used to keep the child in
405af245d11STodd Fiala   // limbo until it is destroyed.
406af245d11STodd Fiala   ptrace_opts |= PTRACE_O_TRACEEXIT;
407af245d11STodd Fiala 
408af245d11STodd Fiala   // Have the tracer trace threads which spawn in the inferior process.
409af245d11STodd Fiala   ptrace_opts |= PTRACE_O_TRACECLONE;
410af245d11STodd Fiala 
41105097246SAdrian Prantl   // Have the tracer notify us before execve returns (needed to disable legacy
41205097246SAdrian Prantl   // SIGTRAP generation)
413af245d11STodd Fiala   ptrace_opts |= PTRACE_O_TRACEEXEC;
414af245d11STodd Fiala 
415c8d18cbaSMichał Górny   // Have the tracer trace forked children.
416c8d18cbaSMichał Górny   ptrace_opts |= PTRACE_O_TRACEFORK;
417c8d18cbaSMichał Górny 
418c8d18cbaSMichał Górny   // Have the tracer trace vforks.
419c8d18cbaSMichał Górny   ptrace_opts |= PTRACE_O_TRACEVFORK;
420c8d18cbaSMichał Górny 
421c8d18cbaSMichał Górny   // Have the tracer trace vfork-done in order to restore breakpoints after
422c8d18cbaSMichał Górny   // the child finishes sharing memory.
423c8d18cbaSMichał Górny   ptrace_opts |= PTRACE_O_TRACEVFORKDONE;
424c8d18cbaSMichał Górny 
4254a9babb2SPavel Labath   return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void *)ptrace_opts);
426af245d11STodd Fiala }
427af245d11STodd Fiala 
4281107b5a5SPavel Labath // Handles all waitpid events from the inferior process.
429*fdd741ddSPavel Labath void NativeProcessLinux::MonitorCallback(lldb::pid_t pid, WaitStatus status) {
430af245d11STodd Fiala   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
431af245d11STodd Fiala 
432b9c1b51eSKate Stone   // Certain activities differ based on whether the pid is the tid of the main
433b9c1b51eSKate Stone   // thread.
4341107b5a5SPavel Labath   const bool is_main_thread = (pid == GetID());
435af245d11STodd Fiala 
436af245d11STodd Fiala   // Handle when the thread exits.
437*fdd741ddSPavel Labath   if (status.type == WaitStatus::Exit || status.type == WaitStatus::Signal) {
438d8b3c1a1SPavel Labath     LLDB_LOG(log,
4399303afb3SPavel Labath              "got exit status({0}) , tid = {1} ({2} main thread), process "
440d8b3c1a1SPavel Labath              "state = {3}",
4419303afb3SPavel Labath              status, pid, is_main_thread ? "is" : "is not", GetState());
442af245d11STodd Fiala 
443af245d11STodd Fiala     // This is a thread that exited.  Ensure we're not tracking it anymore.
444d8b3c1a1SPavel Labath     StopTrackingThread(pid);
445af245d11STodd Fiala 
446b9c1b51eSKate Stone     if (is_main_thread) {
447af245d11STodd Fiala       // The main thread exited.  We're done monitoring.  Report to delegate.
4483508fc8cSPavel Labath       SetExitStatus(status, true);
449af245d11STodd Fiala 
450af245d11STodd Fiala       // Notify delegate that our process has exited.
4511107b5a5SPavel Labath       SetState(StateType::eStateExited, true);
452af245d11STodd Fiala     }
4531107b5a5SPavel Labath     return;
454af245d11STodd Fiala   }
455af245d11STodd Fiala 
456af245d11STodd Fiala   siginfo_t info;
457b9cc0c75SPavel Labath   const auto info_err = GetSignalInfo(pid, &info);
458b9cc0c75SPavel Labath   auto thread_sp = GetThreadByID(pid);
459b9cc0c75SPavel Labath 
460b9c1b51eSKate Stone   if (!thread_sp) {
46105097246SAdrian Prantl     // Normally, the only situation when we cannot find the thread is if we
46205097246SAdrian Prantl     // have just received a new thread notification. This is indicated by
463a6321a8eSPavel Labath     // GetSignalInfo() returning si_code == SI_USER and si_pid == 0
464a6321a8eSPavel Labath     LLDB_LOG(log, "received notification about an unknown tid {0}.", pid);
465b9cc0c75SPavel Labath 
466b9c1b51eSKate Stone     if (info_err.Fail()) {
467a6321a8eSPavel Labath       LLDB_LOG(log,
468a6321a8eSPavel Labath                "(tid {0}) GetSignalInfo failed ({1}). "
469a6321a8eSPavel Labath                "Ingoring this notification.",
470a6321a8eSPavel Labath                pid, info_err);
471b9cc0c75SPavel Labath       return;
472b9cc0c75SPavel Labath     }
473b9cc0c75SPavel Labath 
474a6321a8eSPavel Labath     LLDB_LOG(log, "tid {0}, si_code: {1}, si_pid: {2}", pid, info.si_code,
475a6321a8eSPavel Labath              info.si_pid);
476b9cc0c75SPavel Labath 
477c8d18cbaSMichał Górny     MonitorClone(pid, llvm::None);
478b9cc0c75SPavel Labath     return;
479b9cc0c75SPavel Labath   }
480b9cc0c75SPavel Labath 
481b9cc0c75SPavel Labath   // Get details on the signal raised.
482b9c1b51eSKate Stone   if (info_err.Success()) {
483fa03ad2eSChaoren Lin     // We have retrieved the signal info.  Dispatch appropriately.
484fa03ad2eSChaoren Lin     if (info.si_signo == SIGTRAP)
485b9cc0c75SPavel Labath       MonitorSIGTRAP(info, *thread_sp);
486fa03ad2eSChaoren Lin     else
487*fdd741ddSPavel Labath       MonitorSignal(info, *thread_sp);
488b9c1b51eSKate Stone   } else {
489b9c1b51eSKate Stone     if (info_err.GetError() == EINVAL) {
49005097246SAdrian Prantl       // This is a group stop reception for this tid. We can reach here if we
49105097246SAdrian Prantl       // reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the tracee,
49205097246SAdrian Prantl       // triggering the group-stop mechanism. Normally receiving these would
49305097246SAdrian Prantl       // stop the process, pending a SIGCONT. Simulating this state in a
49405097246SAdrian Prantl       // debugger is hard and is generally not needed (one use case is
49505097246SAdrian Prantl       // debugging background task being managed by a shell). For general use,
49605097246SAdrian Prantl       // it is sufficient to stop the process in a signal-delivery stop which
49705097246SAdrian Prantl       // happens before the group stop. This done by MonitorSignal and works
49805097246SAdrian Prantl       // correctly for all signals.
499a6321a8eSPavel Labath       LLDB_LOG(log,
500a6321a8eSPavel Labath                "received a group stop for pid {0} tid {1}. Transparent "
501a6321a8eSPavel Labath                "handling of group stops not supported, resuming the "
502a6321a8eSPavel Labath                "thread.",
503a6321a8eSPavel Labath                GetID(), pid);
504b9c1b51eSKate Stone       ResumeThread(*thread_sp, thread_sp->GetState(),
505b9c1b51eSKate Stone                    LLDB_INVALID_SIGNAL_NUMBER);
506b9c1b51eSKate Stone     } else {
507af245d11STodd Fiala       // ptrace(GETSIGINFO) failed (but not due to group-stop).
508af245d11STodd Fiala 
509b9c1b51eSKate Stone       // A return value of ESRCH means the thread/process is no longer on the
510a6321a8eSPavel Labath       // system, so it was killed somehow outside of our control.  Either way,
511a6321a8eSPavel Labath       // we can't do anything with it anymore.
512af245d11STodd Fiala 
513b9c1b51eSKate Stone       // Stop tracking the metadata for the thread since it's entirely off the
514b9c1b51eSKate Stone       // system now.
5151107b5a5SPavel Labath       const bool thread_found = StopTrackingThread(pid);
516af245d11STodd Fiala 
517a6321a8eSPavel Labath       LLDB_LOG(log,
5189303afb3SPavel Labath                "GetSignalInfo failed: {0}, tid = {1}, status = {2}, "
519a6321a8eSPavel Labath                "status = {3}, main_thread = {4}, thread_found: {5}",
5209303afb3SPavel Labath                info_err, pid, status, status, is_main_thread, thread_found);
521af245d11STodd Fiala 
522b9c1b51eSKate Stone       if (is_main_thread) {
523b9c1b51eSKate Stone         // Notify the delegate - our process is not available but appears to
52405097246SAdrian Prantl         // have been killed outside our control.  Is eStateExited the right
52505097246SAdrian Prantl         // exit state in this case?
5263508fc8cSPavel Labath         SetExitStatus(status, true);
5271107b5a5SPavel Labath         SetState(StateType::eStateExited, true);
528b9c1b51eSKate Stone       } else {
529b9c1b51eSKate Stone         // This thread was pulled out from underneath us.  Anything to do here?
530b9c1b51eSKate Stone         // Do we want to do an all stop?
531a6321a8eSPavel Labath         LLDB_LOG(log,
532a6321a8eSPavel Labath                  "pid {0} tid {1} non-main thread exit occurred, didn't "
533a6321a8eSPavel Labath                  "tell delegate anything since thread disappeared out "
534a6321a8eSPavel Labath                  "from underneath us",
535a6321a8eSPavel Labath                  GetID(), pid);
536af245d11STodd Fiala       }
537af245d11STodd Fiala     }
538af245d11STodd Fiala   }
539af245d11STodd Fiala }
540af245d11STodd Fiala 
541c8d18cbaSMichał Górny void NativeProcessLinux::WaitForCloneNotification(::pid_t pid) {
542a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
543426bdf88SPavel Labath 
544c8d18cbaSMichał Górny   // The PID is not tracked yet, let's wait for it to appear.
545426bdf88SPavel Labath   int status = -1;
546a6321a8eSPavel Labath   LLDB_LOG(log,
547c8d18cbaSMichał Górny            "received clone event for pid {0}. pid not tracked yet, "
548c8d18cbaSMichał Górny            "waiting for it to appear...",
549c8d18cbaSMichał Górny            pid);
550c8d18cbaSMichał Górny   ::pid_t wait_pid =
551c8d18cbaSMichał Górny       llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &status, __WALL);
552c8d18cbaSMichał Górny   // Since we are waiting on a specific pid, this must be the creation event.
553a6321a8eSPavel Labath   // But let's do some checks just in case.
554c8d18cbaSMichał Górny   if (wait_pid != pid) {
555a6321a8eSPavel Labath     LLDB_LOG(log,
556c8d18cbaSMichał Górny              "waiting for pid {0} failed. Assuming the pid has "
557a6321a8eSPavel Labath              "disappeared in the meantime",
558c8d18cbaSMichał Górny              pid);
559426bdf88SPavel Labath     // The only way I know of this could happen is if the whole process was
560b9c1b51eSKate Stone     // SIGKILLed in the mean time. In any case, we can't do anything about that
561b9c1b51eSKate Stone     // now.
562426bdf88SPavel Labath     return;
563426bdf88SPavel Labath   }
564b9c1b51eSKate Stone   if (WIFEXITED(status)) {
565a6321a8eSPavel Labath     LLDB_LOG(log,
566c8d18cbaSMichał Górny              "waiting for pid {0} returned an 'exited' event. Not "
567c8d18cbaSMichał Górny              "tracking it.",
568c8d18cbaSMichał Górny              pid);
569426bdf88SPavel Labath     // Also a very improbable event.
570c8d18cbaSMichał Górny     m_pending_pid_map.erase(pid);
571426bdf88SPavel Labath     return;
572426bdf88SPavel Labath   }
573426bdf88SPavel Labath 
574c8d18cbaSMichał Górny   MonitorClone(pid, llvm::None);
575426bdf88SPavel Labath }
576426bdf88SPavel Labath 
577b9c1b51eSKate Stone void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info,
578b9c1b51eSKate Stone                                         NativeThreadLinux &thread) {
579a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
580b9cc0c75SPavel Labath   const bool is_main_thread = (thread.GetID() == GetID());
581af245d11STodd Fiala 
582b9cc0c75SPavel Labath   assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
583af245d11STodd Fiala 
584b9c1b51eSKate Stone   switch (info.si_code) {
585c8d18cbaSMichał Górny   case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
586c8d18cbaSMichał Górny   case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
587b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): {
588c8d18cbaSMichał Górny     // This can either mean a new thread or a new process spawned via
589c8d18cbaSMichał Górny     // clone(2) without SIGCHLD or CLONE_VFORK flag.  Note that clone(2)
590c8d18cbaSMichał Górny     // can also cause PTRACE_EVENT_FORK and PTRACE_EVENT_VFORK if one
591c8d18cbaSMichał Górny     // of these flags are passed.
592af245d11STodd Fiala 
593af245d11STodd Fiala     unsigned long event_message = 0;
594b9c1b51eSKate Stone     if (GetEventMessage(thread.GetID(), &event_message).Fail()) {
595a6321a8eSPavel Labath       LLDB_LOG(log,
596c8d18cbaSMichał Górny                "pid {0} received clone() event but GetEventMessage failed "
597c8d18cbaSMichał Górny                "so we don't know the new pid/tid",
598a6321a8eSPavel Labath                thread.GetID());
599121cff78SPavel Labath       ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
600c8d18cbaSMichał Górny     } else {
601c8d18cbaSMichał Górny       if (!MonitorClone(event_message, {{(info.si_code >> 8), thread.GetID()}}))
602c8d18cbaSMichał Górny         WaitForCloneNotification(event_message);
603c8d18cbaSMichał Górny     }
604c8d18cbaSMichał Górny 
605af245d11STodd Fiala     break;
606af245d11STodd Fiala   }
607af245d11STodd Fiala 
608b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): {
609a6321a8eSPavel Labath     LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP);
610a9882ceeSTodd Fiala 
6111dbc6c9cSPavel Labath     // Exec clears any pending notifications.
6120e1d729bSPavel Labath     m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
613fa03ad2eSChaoren Lin 
614b9c1b51eSKate Stone     // Remove all but the main thread here.  Linux fork creates a new process
615b9c1b51eSKate Stone     // which only copies the main thread.
616a6321a8eSPavel Labath     LLDB_LOG(log, "exec received, stop tracking all but main thread");
617a9882ceeSTodd Fiala 
618ee74c9e5SPavel Labath     llvm::erase_if(m_threads, [&](std::unique_ptr<NativeThreadProtocol> &t) {
619ee74c9e5SPavel Labath       return t->GetID() != GetID();
620ee74c9e5SPavel Labath     });
621a5be48b3SPavel Labath     assert(m_threads.size() == 1);
622a5be48b3SPavel Labath     auto *main_thread = static_cast<NativeThreadLinux *>(m_threads[0].get());
623a9882ceeSTodd Fiala 
624a5be48b3SPavel Labath     SetCurrentThreadID(main_thread->GetID());
625a5be48b3SPavel Labath     main_thread->SetStoppedByExec();
626a9882ceeSTodd Fiala 
627fa03ad2eSChaoren Lin     // Tell coordinator about about the "new" (since exec) stopped main thread.
628a5be48b3SPavel Labath     ThreadWasCreated(*main_thread);
629fa03ad2eSChaoren Lin 
630a9882ceeSTodd Fiala     // Let our delegate know we have just exec'd.
631a9882ceeSTodd Fiala     NotifyDidExec();
632a9882ceeSTodd Fiala 
633fa03ad2eSChaoren Lin     // Let the process know we're stopped.
634a5be48b3SPavel Labath     StopRunningThreads(main_thread->GetID());
635a9882ceeSTodd Fiala 
636af245d11STodd Fiala     break;
637a9882ceeSTodd Fiala   }
638af245d11STodd Fiala 
639b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): {
64005097246SAdrian Prantl     // The inferior process or one of its threads is about to exit. We don't
64105097246SAdrian Prantl     // want to do anything with the thread so we just resume it. In case we
64205097246SAdrian Prantl     // want to implement "break on thread exit" functionality, we would need to
64305097246SAdrian Prantl     // stop here.
644fa03ad2eSChaoren Lin 
645af245d11STodd Fiala     unsigned long data = 0;
646b9cc0c75SPavel Labath     if (GetEventMessage(thread.GetID(), &data).Fail())
647af245d11STodd Fiala       data = -1;
648af245d11STodd Fiala 
649a6321a8eSPavel Labath     LLDB_LOG(log,
650a6321a8eSPavel Labath              "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
651a6321a8eSPavel Labath              "WIFSIGNALED={2}, pid = {3}, main_thread = {4}",
652a6321a8eSPavel Labath              data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(),
653a6321a8eSPavel Labath              is_main_thread);
654af245d11STodd Fiala 
65575f47c3aSTodd Fiala 
65686852d36SPavel Labath     StateType state = thread.GetState();
657b9c1b51eSKate Stone     if (!StateIsRunningState(state)) {
658b9c1b51eSKate Stone       // Due to a kernel bug, we may sometimes get this stop after the inferior
659d8b3c1a1SPavel Labath       // gets a SIGKILL. This confuses our state tracking logic in
660d8b3c1a1SPavel Labath       // ResumeThread(), since normally, we should not be receiving any ptrace
66105097246SAdrian Prantl       // events while the inferior is stopped. This makes sure that the
66205097246SAdrian Prantl       // inferior is resumed and exits normally.
66386852d36SPavel Labath       state = eStateRunning;
66486852d36SPavel Labath     }
66586852d36SPavel Labath     ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
666af245d11STodd Fiala 
667af245d11STodd Fiala     break;
668af245d11STodd Fiala   }
669af245d11STodd Fiala 
670c8d18cbaSMichał Górny   case (SIGTRAP | (PTRACE_EVENT_VFORK_DONE << 8)): {
671fd0af0cfSMichał Górny     if (bool(m_enabled_extensions & Extension::vfork)) {
672fd0af0cfSMichał Górny       thread.SetStoppedByVForkDone();
673fd0af0cfSMichał Górny       StopRunningThreads(thread.GetID());
674fd0af0cfSMichał Górny     }
675fd0af0cfSMichał Górny     else
676c8d18cbaSMichał Górny       ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
677c8d18cbaSMichał Górny     break;
678c8d18cbaSMichał Górny   }
679c8d18cbaSMichał Górny 
680af245d11STodd Fiala   case 0:
681c16f5dcaSChaoren Lin   case TRAP_TRACE:  // We receive this on single stepping.
682c16f5dcaSChaoren Lin   case TRAP_HWBKPT: // We receive this on watchpoint hit
68386fd8e45SChaoren Lin   {
684c16f5dcaSChaoren Lin     // If a watchpoint was hit, report it
685c16f5dcaSChaoren Lin     uint32_t wp_index;
686d37349f3SPavel Labath     Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
687b9c1b51eSKate Stone         wp_index, (uintptr_t)info.si_addr);
688a6321a8eSPavel Labath     if (error.Fail())
689a6321a8eSPavel Labath       LLDB_LOG(log,
690a6321a8eSPavel Labath                "received error while checking for watchpoint hits, pid = "
691a6321a8eSPavel Labath                "{0}, error = {1}",
692a6321a8eSPavel Labath                thread.GetID(), error);
693b9c1b51eSKate Stone     if (wp_index != LLDB_INVALID_INDEX32) {
694b9cc0c75SPavel Labath       MonitorWatchpoint(thread, wp_index);
695c16f5dcaSChaoren Lin       break;
696c16f5dcaSChaoren Lin     }
697b9cc0c75SPavel Labath 
698d5ffbad2SOmair Javaid     // If a breakpoint was hit, report it
699d5ffbad2SOmair Javaid     uint32_t bp_index;
700d37349f3SPavel Labath     error = thread.GetRegisterContext().GetHardwareBreakHitIndex(
701d5ffbad2SOmair Javaid         bp_index, (uintptr_t)info.si_addr);
702d5ffbad2SOmair Javaid     if (error.Fail())
703d5ffbad2SOmair Javaid       LLDB_LOG(log, "received error while checking for hardware "
704d5ffbad2SOmair Javaid                     "breakpoint hits, pid = {0}, error = {1}",
705d5ffbad2SOmair Javaid                thread.GetID(), error);
706d5ffbad2SOmair Javaid     if (bp_index != LLDB_INVALID_INDEX32) {
707d5ffbad2SOmair Javaid       MonitorBreakpoint(thread);
708d5ffbad2SOmair Javaid       break;
709d5ffbad2SOmair Javaid     }
710d5ffbad2SOmair Javaid 
711be379e15STamas Berghammer     // Otherwise, report step over
712be379e15STamas Berghammer     MonitorTrace(thread);
713af245d11STodd Fiala     break;
714b9cc0c75SPavel Labath   }
715af245d11STodd Fiala 
716af245d11STodd Fiala   case SI_KERNEL:
71735799963SMohit K. Bhakkad #if defined __mips__
71805097246SAdrian Prantl     // For mips there is no special signal for watchpoint So we check for
71905097246SAdrian Prantl     // watchpoint in kernel trap
72035799963SMohit K. Bhakkad     {
72135799963SMohit K. Bhakkad       // If a watchpoint was hit, report it
72235799963SMohit K. Bhakkad       uint32_t wp_index;
723d37349f3SPavel Labath       Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
724b9c1b51eSKate Stone           wp_index, LLDB_INVALID_ADDRESS);
725a6321a8eSPavel Labath       if (error.Fail())
726a6321a8eSPavel Labath         LLDB_LOG(log,
727a6321a8eSPavel Labath                  "received error while checking for watchpoint hits, pid = "
728a6321a8eSPavel Labath                  "{0}, error = {1}",
729a6321a8eSPavel Labath                  thread.GetID(), error);
730b9c1b51eSKate Stone       if (wp_index != LLDB_INVALID_INDEX32) {
731b9cc0c75SPavel Labath         MonitorWatchpoint(thread, wp_index);
73235799963SMohit K. Bhakkad         break;
73335799963SMohit K. Bhakkad       }
73435799963SMohit K. Bhakkad     }
73535799963SMohit K. Bhakkad // NO BREAK
73635799963SMohit K. Bhakkad #endif
737af245d11STodd Fiala   case TRAP_BRKPT:
738b9cc0c75SPavel Labath     MonitorBreakpoint(thread);
739af245d11STodd Fiala     break;
740af245d11STodd Fiala 
741af245d11STodd Fiala   case SIGTRAP:
742af245d11STodd Fiala   case (SIGTRAP | 0x80):
743a6321a8eSPavel Labath     LLDB_LOG(
744a6321a8eSPavel Labath         log,
745a6321a8eSPavel Labath         "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",
746a6321a8eSPavel Labath         info.si_code, GetID(), thread.GetID());
747fa03ad2eSChaoren Lin 
748af245d11STodd Fiala     // Ignore these signals until we know more about them.
749b9cc0c75SPavel Labath     ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
750af245d11STodd Fiala     break;
751af245d11STodd Fiala 
752af245d11STodd Fiala   default:
75321a365baSPavel Labath     LLDB_LOG(log, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}",
754a6321a8eSPavel Labath              info.si_code, GetID(), thread.GetID());
755*fdd741ddSPavel Labath     MonitorSignal(info, thread);
756af245d11STodd Fiala     break;
757af245d11STodd Fiala   }
758af245d11STodd Fiala }
759af245d11STodd Fiala 
760b9c1b51eSKate Stone void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) {
761a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
762a6321a8eSPavel Labath   LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID());
763c16f5dcaSChaoren Lin 
7640e1d729bSPavel Labath   // This thread is currently stopped.
765b9cc0c75SPavel Labath   thread.SetStoppedByTrace();
766c16f5dcaSChaoren Lin 
767b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
768c16f5dcaSChaoren Lin }
769c16f5dcaSChaoren Lin 
770b9c1b51eSKate Stone void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) {
771b9c1b51eSKate Stone   Log *log(
772b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
773a6321a8eSPavel Labath   LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID());
774c16f5dcaSChaoren Lin 
775c16f5dcaSChaoren Lin   // Mark the thread as stopped at breakpoint.
776b9cc0c75SPavel Labath   thread.SetStoppedByBreakpoint();
777aef7908fSPavel Labath   FixupBreakpointPCAsNeeded(thread);
778d8c338d4STamas Berghammer 
779b9c1b51eSKate Stone   if (m_threads_stepping_with_breakpoint.find(thread.GetID()) !=
780b9c1b51eSKate Stone       m_threads_stepping_with_breakpoint.end())
781b9cc0c75SPavel Labath     thread.SetStoppedByTrace();
782c16f5dcaSChaoren Lin 
783b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
784c16f5dcaSChaoren Lin }
785c16f5dcaSChaoren Lin 
786b9c1b51eSKate Stone void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread,
787b9c1b51eSKate Stone                                            uint32_t wp_index) {
788b9c1b51eSKate Stone   Log *log(
789b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
790a6321a8eSPavel Labath   LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}",
791a6321a8eSPavel Labath            thread.GetID(), wp_index);
792c16f5dcaSChaoren Lin 
79305097246SAdrian Prantl   // Mark the thread as stopped at watchpoint. The address is at
79405097246SAdrian Prantl   // (lldb::addr_t)info->si_addr if we need it.
795f9077782SPavel Labath   thread.SetStoppedByWatchpoint(wp_index);
796c16f5dcaSChaoren Lin 
797b9c1b51eSKate Stone   // We need to tell all other running threads before we notify the delegate
798b9c1b51eSKate Stone   // about this stop.
799f9077782SPavel Labath   StopRunningThreads(thread.GetID());
800c16f5dcaSChaoren Lin }
801c16f5dcaSChaoren Lin 
802b9c1b51eSKate Stone void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
803*fdd741ddSPavel Labath                                        NativeThreadLinux &thread) {
804b9cc0c75SPavel Labath   const int signo = info.si_signo;
805b9cc0c75SPavel Labath   const bool is_from_llgs = info.si_pid == getpid();
806af245d11STodd Fiala 
807a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
808af245d11STodd Fiala 
809af245d11STodd Fiala   // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
81005097246SAdrian Prantl   // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a kill(2)
81105097246SAdrian Prantl   // or raise(3).  Similarly for tgkill(2) on Linux.
812af245d11STodd Fiala   //
813af245d11STodd Fiala   // IOW, user generated signals never generate what we consider to be a
814af245d11STodd Fiala   // "crash".
815af245d11STodd Fiala   //
816af245d11STodd Fiala   // Similarly, ACK signals generated by this monitor.
817af245d11STodd Fiala 
818af245d11STodd Fiala   // Handle the signal.
819a6321a8eSPavel Labath   LLDB_LOG(log,
820a6321a8eSPavel Labath            "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
821a6321a8eSPavel Labath            "waitpid pid = {4})",
822a6321a8eSPavel Labath            Host::GetSignalAsCString(signo), signo, info.si_code,
823b9cc0c75SPavel Labath            thread.GetID());
82458a2f669STodd Fiala 
82558a2f669STodd Fiala   // Check for thread stop notification.
826b9c1b51eSKate Stone   if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) {
827af245d11STodd Fiala     // This is a tgkill()-based stop.
828a6321a8eSPavel Labath     LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID());
829fa03ad2eSChaoren Lin 
83005097246SAdrian Prantl     // Check that we're not already marked with a stop reason. Note this thread
83105097246SAdrian Prantl     // really shouldn't already be marked as stopped - if we were, that would
83205097246SAdrian Prantl     // imply that the kernel signaled us with the thread stopping which we
83305097246SAdrian Prantl     // handled and marked as stopped, and that, without an intervening resume,
83405097246SAdrian Prantl     // we received another stop.  It is more likely that we are missing the
83505097246SAdrian Prantl     // marking of a run state somewhere if we find that the thread was marked
83605097246SAdrian Prantl     // as stopped.
837b9cc0c75SPavel Labath     const StateType thread_state = thread.GetState();
838b9c1b51eSKate Stone     if (!StateIsStoppedState(thread_state, false)) {
839ed89c7feSPavel Labath       // An inferior thread has stopped because of a SIGSTOP we have sent it.
840b9c1b51eSKate Stone       // Generally, these are not important stops and we don't want to report
841a6321a8eSPavel Labath       // them as they are just used to stop other threads when one thread (the
842a6321a8eSPavel Labath       // one with the *real* stop reason) hits a breakpoint (watchpoint,
84305097246SAdrian Prantl       // etc...). However, in the case of an asynchronous Interrupt(), this
84405097246SAdrian Prantl       // *is* the real stop reason, so we leave the signal intact if this is
84505097246SAdrian Prantl       // the thread that was chosen as the triggering thread.
846b9c1b51eSKate Stone       if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
847b9cc0c75SPavel Labath         if (m_pending_notification_tid == thread.GetID())
848b9cc0c75SPavel Labath           thread.SetStoppedBySignal(SIGSTOP, &info);
849ed89c7feSPavel Labath         else
850b9cc0c75SPavel Labath           thread.SetStoppedWithNoReason();
851ed89c7feSPavel Labath 
852b9cc0c75SPavel Labath         SetCurrentThreadID(thread.GetID());
8530e1d729bSPavel Labath         SignalIfAllThreadsStopped();
854b9c1b51eSKate Stone       } else {
8550e1d729bSPavel Labath         // We can end up here if stop was initiated by LLGS but by this time a
8560e1d729bSPavel Labath         // thread stop has occurred - maybe initiated by another event.
85797206d57SZachary Turner         Status error = ResumeThread(thread, thread.GetState(), 0);
858a6321a8eSPavel Labath         if (error.Fail())
859a6321a8eSPavel Labath           LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(),
860a6321a8eSPavel Labath                    error);
8610e1d729bSPavel Labath       }
862b9c1b51eSKate Stone     } else {
863a6321a8eSPavel Labath       LLDB_LOG(log,
864a6321a8eSPavel Labath                "pid {0} tid {1}, thread was already marked as a stopped "
865a6321a8eSPavel Labath                "state (state={2}), leaving stop signal as is",
8668198db30SPavel Labath                GetID(), thread.GetID(), thread_state);
8670e1d729bSPavel Labath       SignalIfAllThreadsStopped();
868af245d11STodd Fiala     }
869af245d11STodd Fiala 
87058a2f669STodd Fiala     // Done handling.
871af245d11STodd Fiala     return;
872af245d11STodd Fiala   }
873af245d11STodd Fiala 
87405097246SAdrian Prantl   // Check if debugger should stop at this signal or just ignore it and resume
87505097246SAdrian Prantl   // the inferior.
87676f0f1ccSKazu Hirata   if (m_signals_to_ignore.contains(signo)) {
8774a705e7eSPavel Labath      ResumeThread(thread, thread.GetState(), signo);
8784a705e7eSPavel Labath      return;
8794a705e7eSPavel Labath   }
8804a705e7eSPavel Labath 
88186fd8e45SChaoren Lin   // This thread is stopped.
882a6321a8eSPavel Labath   LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo));
883b9cc0c75SPavel Labath   thread.SetStoppedBySignal(signo, &info);
88486fd8e45SChaoren Lin 
88586fd8e45SChaoren Lin   // Send a stop to the debugger after we get all other threads to stop.
886b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
887511e5cdcSTodd Fiala }
888af245d11STodd Fiala 
889c8d18cbaSMichał Górny bool NativeProcessLinux::MonitorClone(
890c8d18cbaSMichał Górny     lldb::pid_t child_pid,
891c8d18cbaSMichał Górny     llvm::Optional<NativeProcessLinux::CloneInfo> clone_info) {
892c8d18cbaSMichał Górny   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
893c8d18cbaSMichał Górny   LLDB_LOG(log, "clone, child_pid={0}, clone info?={1}", child_pid,
894c8d18cbaSMichał Górny            clone_info.hasValue());
895c8d18cbaSMichał Górny 
896c8d18cbaSMichał Górny   auto find_it = m_pending_pid_map.find(child_pid);
897c8d18cbaSMichał Górny   if (find_it == m_pending_pid_map.end()) {
898c8d18cbaSMichał Górny     // not in the map, so this is the first signal for the PID
899c8d18cbaSMichał Górny     m_pending_pid_map.insert({child_pid, clone_info});
900c8d18cbaSMichał Górny     return false;
901c8d18cbaSMichał Górny   }
902c8d18cbaSMichał Górny   m_pending_pid_map.erase(find_it);
903c8d18cbaSMichał Górny 
904c8d18cbaSMichał Górny   // second signal for the pid
905c8d18cbaSMichał Górny   assert(clone_info.hasValue() != find_it->second.hasValue());
906c8d18cbaSMichał Górny   if (!clone_info) {
907c8d18cbaSMichał Górny     // child signal does not indicate the event, so grab the one stored
908c8d18cbaSMichał Górny     // earlier
909c8d18cbaSMichał Górny     clone_info = find_it->second;
910c8d18cbaSMichał Górny   }
911c8d18cbaSMichał Górny 
912c8d18cbaSMichał Górny   LLDB_LOG(log, "second signal for child_pid={0}, parent_tid={1}, event={2}",
913c8d18cbaSMichał Górny            child_pid, clone_info->parent_tid, clone_info->event);
914c8d18cbaSMichał Górny 
915c8d18cbaSMichał Górny   auto *parent_thread = GetThreadByID(clone_info->parent_tid);
916c8d18cbaSMichał Górny   assert(parent_thread);
917c8d18cbaSMichał Górny 
918c8d18cbaSMichał Górny   switch (clone_info->event) {
919c8d18cbaSMichał Górny   case PTRACE_EVENT_CLONE: {
920c8d18cbaSMichał Górny     // PTRACE_EVENT_CLONE can either mean a new thread or a new process.
921c8d18cbaSMichał Górny     // Try to grab the new process' PGID to figure out which one it is.
922c8d18cbaSMichał Górny     // If PGID is the same as the PID, then it's a new process.  Otherwise,
923c8d18cbaSMichał Górny     // it's a thread.
924c8d18cbaSMichał Górny     auto tgid_ret = getPIDForTID(child_pid);
925c8d18cbaSMichał Górny     if (tgid_ret != child_pid) {
926c8d18cbaSMichał Górny       // A new thread should have PGID matching our process' PID.
927c8d18cbaSMichał Górny       assert(!tgid_ret || tgid_ret.getValue() == GetID());
928c8d18cbaSMichał Górny 
929c8d18cbaSMichał Górny       NativeThreadLinux &child_thread = AddThread(child_pid, /*resume*/ true);
930c8d18cbaSMichał Górny       ThreadWasCreated(child_thread);
931c8d18cbaSMichał Górny 
932c8d18cbaSMichał Górny       // Resume the parent.
933c8d18cbaSMichał Górny       ResumeThread(*parent_thread, parent_thread->GetState(),
934c8d18cbaSMichał Górny                    LLDB_INVALID_SIGNAL_NUMBER);
935c8d18cbaSMichał Górny       break;
936c8d18cbaSMichał Górny     }
937c8d18cbaSMichał Górny   }
938c8d18cbaSMichał Górny     LLVM_FALLTHROUGH;
939c8d18cbaSMichał Górny   case PTRACE_EVENT_FORK:
940c8d18cbaSMichał Górny   case PTRACE_EVENT_VFORK: {
941fd0af0cfSMichał Górny     bool is_vfork = clone_info->event == PTRACE_EVENT_VFORK;
942fd0af0cfSMichał Górny     std::unique_ptr<NativeProcessLinux> child_process{new NativeProcessLinux(
943fd0af0cfSMichał Górny         static_cast<::pid_t>(child_pid), m_terminal_fd, m_delegate, m_arch,
944fd0af0cfSMichał Górny         m_main_loop, {static_cast<::pid_t>(child_pid)})};
945fd0af0cfSMichał Górny     if (!is_vfork)
946fd0af0cfSMichał Górny       child_process->m_software_breakpoints = m_software_breakpoints;
947fd0af0cfSMichał Górny 
948fd0af0cfSMichał Górny     Extension expected_ext = is_vfork ? Extension::vfork : Extension::fork;
949fd0af0cfSMichał Górny     if (bool(m_enabled_extensions & expected_ext)) {
950fd0af0cfSMichał Górny       m_delegate.NewSubprocess(this, std::move(child_process));
951fd0af0cfSMichał Górny       // NB: non-vfork clone() is reported as fork
952fd0af0cfSMichał Górny       parent_thread->SetStoppedByFork(is_vfork, child_pid);
953fd0af0cfSMichał Górny       StopRunningThreads(parent_thread->GetID());
954fd0af0cfSMichał Górny     } else {
955fd0af0cfSMichał Górny       child_process->Detach();
956c8d18cbaSMichał Górny       ResumeThread(*parent_thread, parent_thread->GetState(),
957c8d18cbaSMichał Górny                    LLDB_INVALID_SIGNAL_NUMBER);
958fd0af0cfSMichał Górny     }
959c8d18cbaSMichał Górny     break;
960c8d18cbaSMichał Górny   }
961c8d18cbaSMichał Górny   default:
962c8d18cbaSMichał Górny     llvm_unreachable("unknown clone_info.event");
963c8d18cbaSMichał Górny   }
964c8d18cbaSMichał Górny 
965c8d18cbaSMichał Górny   return true;
966c8d18cbaSMichał Górny }
967c8d18cbaSMichał Górny 
968b9c1b51eSKate Stone bool NativeProcessLinux::SupportHardwareSingleStepping() const {
969ddb93b63SFangrui Song   if (m_arch.GetMachine() == llvm::Triple::arm || m_arch.IsMIPS())
970cdc22a88SMohit K. Bhakkad     return false;
971cdc22a88SMohit K. Bhakkad   return true;
972e7708688STamas Berghammer }
973e7708688STamas Berghammer 
97497206d57SZachary Turner Status NativeProcessLinux::Resume(const ResumeActionList &resume_actions) {
975a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
976a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0}", GetID());
977af245d11STodd Fiala 
978e7708688STamas Berghammer   bool software_single_step = !SupportHardwareSingleStepping();
979af245d11STodd Fiala 
980b9c1b51eSKate Stone   if (software_single_step) {
981a5be48b3SPavel Labath     for (const auto &thread : m_threads) {
982a5be48b3SPavel Labath       assert(thread && "thread list should not contain NULL threads");
983e7708688STamas Berghammer 
984b9c1b51eSKate Stone       const ResumeAction *const action =
985a5be48b3SPavel Labath           resume_actions.GetActionForThread(thread->GetID(), true);
986e7708688STamas Berghammer       if (action == nullptr)
987e7708688STamas Berghammer         continue;
988e7708688STamas Berghammer 
989b9c1b51eSKate Stone       if (action->state == eStateStepping) {
99097206d57SZachary Turner         Status error = SetupSoftwareSingleStepping(
991a5be48b3SPavel Labath             static_cast<NativeThreadLinux &>(*thread));
992e7708688STamas Berghammer         if (error.Fail())
993e7708688STamas Berghammer           return error;
994e7708688STamas Berghammer       }
995e7708688STamas Berghammer     }
996e7708688STamas Berghammer   }
997e7708688STamas Berghammer 
998a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
999a5be48b3SPavel Labath     assert(thread && "thread list should not contain NULL threads");
1000af245d11STodd Fiala 
1001b9c1b51eSKate Stone     const ResumeAction *const action =
1002a5be48b3SPavel Labath         resume_actions.GetActionForThread(thread->GetID(), true);
10036a196ce6SChaoren Lin 
1004b9c1b51eSKate Stone     if (action == nullptr) {
1005a6321a8eSPavel Labath       LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
1006a5be48b3SPavel Labath                thread->GetID());
10076a196ce6SChaoren Lin       continue;
10086a196ce6SChaoren Lin     }
1009af245d11STodd Fiala 
1010a6321a8eSPavel Labath     LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}",
1011a5be48b3SPavel Labath              action->state, GetID(), thread->GetID());
1012af245d11STodd Fiala 
1013b9c1b51eSKate Stone     switch (action->state) {
1014af245d11STodd Fiala     case eStateRunning:
1015b9c1b51eSKate Stone     case eStateStepping: {
1016af245d11STodd Fiala       // Run the thread, possibly feeding it the signal.
1017fa03ad2eSChaoren Lin       const int signo = action->signal;
1018a5be48b3SPavel Labath       ResumeThread(static_cast<NativeThreadLinux &>(*thread), action->state,
1019b9c1b51eSKate Stone                    signo);
1020af245d11STodd Fiala       break;
1021ae29d395SChaoren Lin     }
1022af245d11STodd Fiala 
1023af245d11STodd Fiala     case eStateSuspended:
1024af245d11STodd Fiala     case eStateStopped:
1025a6321a8eSPavel Labath       llvm_unreachable("Unexpected state");
1026af245d11STodd Fiala 
1027af245d11STodd Fiala     default:
102897206d57SZachary Turner       return Status("NativeProcessLinux::%s (): unexpected state %s specified "
1029b9c1b51eSKate Stone                     "for pid %" PRIu64 ", tid %" PRIu64,
1030b9c1b51eSKate Stone                     __FUNCTION__, StateAsCString(action->state), GetID(),
1031a5be48b3SPavel Labath                     thread->GetID());
1032af245d11STodd Fiala     }
1033af245d11STodd Fiala   }
1034af245d11STodd Fiala 
103597206d57SZachary Turner   return Status();
1036af245d11STodd Fiala }
1037af245d11STodd Fiala 
103897206d57SZachary Turner Status NativeProcessLinux::Halt() {
103997206d57SZachary Turner   Status error;
1040af245d11STodd Fiala 
1041af245d11STodd Fiala   if (kill(GetID(), SIGSTOP) != 0)
1042af245d11STodd Fiala     error.SetErrorToErrno();
1043af245d11STodd Fiala 
1044af245d11STodd Fiala   return error;
1045af245d11STodd Fiala }
1046af245d11STodd Fiala 
104797206d57SZachary Turner Status NativeProcessLinux::Detach() {
104897206d57SZachary Turner   Status error;
1049af245d11STodd Fiala 
1050af245d11STodd Fiala   // Stop monitoring the inferior.
105119cbe96aSPavel Labath   m_sigchld_handle.reset();
1052af245d11STodd Fiala 
10537a9495bcSPavel Labath   // Tell ptrace to detach from the process.
10547a9495bcSPavel Labath   if (GetID() == LLDB_INVALID_PROCESS_ID)
10557a9495bcSPavel Labath     return error;
10567a9495bcSPavel Labath 
1057a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
1058a5be48b3SPavel Labath     Status e = Detach(thread->GetID());
10597a9495bcSPavel Labath     if (e.Fail())
1060b9c1b51eSKate Stone       error =
1061b9c1b51eSKate Stone           e; // Save the error, but still attempt to detach from other threads.
10627a9495bcSPavel Labath   }
10637a9495bcSPavel Labath 
10640b697561SWalter Erquinigo   m_intel_pt_manager.Clear();
106599e37695SRavitheja Addepally 
1066af245d11STodd Fiala   return error;
1067af245d11STodd Fiala }
1068af245d11STodd Fiala 
106997206d57SZachary Turner Status NativeProcessLinux::Signal(int signo) {
107097206d57SZachary Turner   Status error;
1071af245d11STodd Fiala 
1072a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1073a6321a8eSPavel Labath   LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo,
1074a6321a8eSPavel Labath            Host::GetSignalAsCString(signo), GetID());
1075af245d11STodd Fiala 
1076af245d11STodd Fiala   if (kill(GetID(), signo))
1077af245d11STodd Fiala     error.SetErrorToErrno();
1078af245d11STodd Fiala 
1079af245d11STodd Fiala   return error;
1080af245d11STodd Fiala }
1081af245d11STodd Fiala 
108297206d57SZachary Turner Status NativeProcessLinux::Interrupt() {
108305097246SAdrian Prantl   // Pick a running thread (or if none, a not-dead stopped thread) as the
108405097246SAdrian Prantl   // chosen thread that will be the stop-reason thread.
1085a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1086e9547b80SChaoren Lin 
1087a5be48b3SPavel Labath   NativeThreadProtocol *running_thread = nullptr;
1088a5be48b3SPavel Labath   NativeThreadProtocol *stopped_thread = nullptr;
1089e9547b80SChaoren Lin 
1090a6321a8eSPavel Labath   LLDB_LOG(log, "selecting running thread for interrupt target");
1091a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
109205097246SAdrian Prantl     // If we have a running or stepping thread, we'll call that the target of
109305097246SAdrian Prantl     // the interrupt.
1094a5be48b3SPavel Labath     const auto thread_state = thread->GetState();
1095b9c1b51eSKate Stone     if (thread_state == eStateRunning || thread_state == eStateStepping) {
1096a5be48b3SPavel Labath       running_thread = thread.get();
1097e9547b80SChaoren Lin       break;
1098a5be48b3SPavel Labath     } else if (!stopped_thread && StateIsStoppedState(thread_state, true)) {
109905097246SAdrian Prantl       // Remember the first non-dead stopped thread.  We'll use that as a
110005097246SAdrian Prantl       // backup if there are no running threads.
1101a5be48b3SPavel Labath       stopped_thread = thread.get();
1102e9547b80SChaoren Lin     }
1103e9547b80SChaoren Lin   }
1104e9547b80SChaoren Lin 
1105a5be48b3SPavel Labath   if (!running_thread && !stopped_thread) {
110697206d57SZachary Turner     Status error("found no running/stepping or live stopped threads as target "
1107b9c1b51eSKate Stone                  "for interrupt");
1108a6321a8eSPavel Labath     LLDB_LOG(log, "skipping due to error: {0}", error);
11095830aa75STamas Berghammer 
1110e9547b80SChaoren Lin     return error;
1111e9547b80SChaoren Lin   }
1112e9547b80SChaoren Lin 
1113a5be48b3SPavel Labath   NativeThreadProtocol *deferred_signal_thread =
1114a5be48b3SPavel Labath       running_thread ? running_thread : stopped_thread;
1115e9547b80SChaoren Lin 
1116a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(),
1117a5be48b3SPavel Labath            running_thread ? "running" : "stopped",
1118a5be48b3SPavel Labath            deferred_signal_thread->GetID());
1119e9547b80SChaoren Lin 
1120a5be48b3SPavel Labath   StopRunningThreads(deferred_signal_thread->GetID());
112145f5cb31SPavel Labath 
112297206d57SZachary Turner   return Status();
1123e9547b80SChaoren Lin }
1124e9547b80SChaoren Lin 
112597206d57SZachary Turner Status NativeProcessLinux::Kill() {
1126a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1127a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0}", GetID());
1128af245d11STodd Fiala 
112997206d57SZachary Turner   Status error;
1130af245d11STodd Fiala 
1131b9c1b51eSKate Stone   switch (m_state) {
1132af245d11STodd Fiala   case StateType::eStateInvalid:
1133af245d11STodd Fiala   case StateType::eStateExited:
1134af245d11STodd Fiala   case StateType::eStateCrashed:
1135af245d11STodd Fiala   case StateType::eStateDetached:
1136af245d11STodd Fiala   case StateType::eStateUnloaded:
1137af245d11STodd Fiala     // Nothing to do - the process is already dead.
1138a6321a8eSPavel Labath     LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
11398198db30SPavel Labath              m_state);
1140af245d11STodd Fiala     return error;
1141af245d11STodd Fiala 
1142af245d11STodd Fiala   case StateType::eStateConnected:
1143af245d11STodd Fiala   case StateType::eStateAttaching:
1144af245d11STodd Fiala   case StateType::eStateLaunching:
1145af245d11STodd Fiala   case StateType::eStateStopped:
1146af245d11STodd Fiala   case StateType::eStateRunning:
1147af245d11STodd Fiala   case StateType::eStateStepping:
1148af245d11STodd Fiala   case StateType::eStateSuspended:
1149af245d11STodd Fiala     // We can try to kill a process in these states.
1150af245d11STodd Fiala     break;
1151af245d11STodd Fiala   }
1152af245d11STodd Fiala 
1153b9c1b51eSKate Stone   if (kill(GetID(), SIGKILL) != 0) {
1154af245d11STodd Fiala     error.SetErrorToErrno();
1155af245d11STodd Fiala     return error;
1156af245d11STodd Fiala   }
1157af245d11STodd Fiala 
1158af245d11STodd Fiala   return error;
1159af245d11STodd Fiala }
1160af245d11STodd Fiala 
116197206d57SZachary Turner Status NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr,
1162b9c1b51eSKate Stone                                                MemoryRegionInfo &range_info) {
1163b9c1b51eSKate Stone   // FIXME review that the final memory region returned extends to the end of
1164b9c1b51eSKate Stone   // the virtual address space,
1165af245d11STodd Fiala   // with no perms if it is not mapped.
1166af245d11STodd Fiala 
116705097246SAdrian Prantl   // Use an approach that reads memory regions from /proc/{pid}/maps. Assume
116805097246SAdrian Prantl   // proc maps entries are in ascending order.
1169af245d11STodd Fiala   // FIXME assert if we find differently.
1170af245d11STodd Fiala 
1171b9c1b51eSKate Stone   if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
1172af245d11STodd Fiala     // We're done.
117397206d57SZachary Turner     return Status("unsupported");
1174af245d11STodd Fiala   }
1175af245d11STodd Fiala 
117697206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
1177b9c1b51eSKate Stone   if (error.Fail()) {
1178af245d11STodd Fiala     return error;
1179af245d11STodd Fiala   }
1180af245d11STodd Fiala 
1181af245d11STodd Fiala   lldb::addr_t prev_base_address = 0;
1182af245d11STodd Fiala 
1183b9c1b51eSKate Stone   // FIXME start by finding the last region that is <= target address using
1184b9c1b51eSKate Stone   // binary search.  Data is sorted.
1185af245d11STodd Fiala   // There can be a ton of regions on pthreads apps with lots of threads.
1186b9c1b51eSKate Stone   for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1187b9c1b51eSKate Stone        ++it) {
1188a6f5795aSTamas Berghammer     MemoryRegionInfo &proc_entry_info = it->first;
1189af245d11STodd Fiala 
1190af245d11STodd Fiala     // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1191b9c1b51eSKate Stone     assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
1192b9c1b51eSKate Stone            "descending /proc/pid/maps entries detected, unexpected");
1193af245d11STodd Fiala     prev_base_address = proc_entry_info.GetRange().GetRangeBase();
1194b1554311SHafiz Abid Qadeer     UNUSED_IF_ASSERT_DISABLED(prev_base_address);
1195af245d11STodd Fiala 
1196b9c1b51eSKate Stone     // If the target address comes before this entry, indicate distance to next
1197b9c1b51eSKate Stone     // region.
1198b9c1b51eSKate Stone     if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1199af245d11STodd Fiala       range_info.GetRange().SetRangeBase(load_addr);
1200b9c1b51eSKate Stone       range_info.GetRange().SetByteSize(
1201b9c1b51eSKate Stone           proc_entry_info.GetRange().GetRangeBase() - load_addr);
1202af245d11STodd Fiala       range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1203af245d11STodd Fiala       range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1204af245d11STodd Fiala       range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1205ad007563SHoward Hellyer       range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1206af245d11STodd Fiala 
1207af245d11STodd Fiala       return error;
1208b9c1b51eSKate Stone     } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1209af245d11STodd Fiala       // The target address is within the memory region we're processing here.
1210af245d11STodd Fiala       range_info = proc_entry_info;
1211af245d11STodd Fiala       return error;
1212af245d11STodd Fiala     }
1213af245d11STodd Fiala 
1214b9c1b51eSKate Stone     // The target memory address comes somewhere after the region we just
1215b9c1b51eSKate Stone     // parsed.
1216af245d11STodd Fiala   }
1217af245d11STodd Fiala 
1218b9c1b51eSKate Stone   // If we made it here, we didn't find an entry that contained the given
121905097246SAdrian Prantl   // address. Return the load_addr as start and the amount of bytes betwwen
122005097246SAdrian Prantl   // load address and the end of the memory as size.
122109839c33STamas Berghammer   range_info.GetRange().SetRangeBase(load_addr);
1222ad007563SHoward Hellyer   range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
122309839c33STamas Berghammer   range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
122409839c33STamas Berghammer   range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
122509839c33STamas Berghammer   range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1226ad007563SHoward Hellyer   range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1227af245d11STodd Fiala   return error;
1228af245d11STodd Fiala }
1229af245d11STodd Fiala 
123097206d57SZachary Turner Status NativeProcessLinux::PopulateMemoryRegionCache() {
1231a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1232a6f5795aSTamas Berghammer 
1233a6f5795aSTamas Berghammer   // If our cache is empty, pull the latest.  There should always be at least
1234a6f5795aSTamas Berghammer   // one memory region if memory region handling is supported.
1235a6f5795aSTamas Berghammer   if (!m_mem_region_cache.empty()) {
1236a6321a8eSPavel Labath     LLDB_LOG(log, "reusing {0} cached memory region entries",
1237a6321a8eSPavel Labath              m_mem_region_cache.size());
123897206d57SZachary Turner     return Status();
1239a6f5795aSTamas Berghammer   }
1240a6f5795aSTamas Berghammer 
124132541685SDavid Spickett   Status Result;
124232541685SDavid Spickett   LinuxMapCallback callback = [&](llvm::Expected<MemoryRegionInfo> Info) {
124332541685SDavid Spickett     if (Info) {
124432541685SDavid Spickett       FileSpec file_spec(Info->GetName().GetCString());
124532541685SDavid Spickett       FileSystem::Instance().Resolve(file_spec);
124632541685SDavid Spickett       m_mem_region_cache.emplace_back(*Info, file_spec);
124732541685SDavid Spickett       return true;
124832541685SDavid Spickett     }
124932541685SDavid Spickett 
125032541685SDavid Spickett     Result = Info.takeError();
125132541685SDavid Spickett     m_supports_mem_region = LazyBool::eLazyBoolNo;
125232541685SDavid Spickett     LLDB_LOG(log, "failed to parse proc maps: {0}", Result);
125332541685SDavid Spickett     return false;
125432541685SDavid Spickett   };
125532541685SDavid Spickett 
125632541685SDavid Spickett   // Linux kernel since 2.6.14 has /proc/{pid}/smaps
125732541685SDavid Spickett   // if CONFIG_PROC_PAGE_MONITOR is enabled
125832541685SDavid Spickett   auto BufferOrError = getProcFile(GetID(), "smaps");
125932541685SDavid Spickett   if (BufferOrError)
126032541685SDavid Spickett     ParseLinuxSMapRegions(BufferOrError.get()->getBuffer(), callback);
126132541685SDavid Spickett   else {
126232541685SDavid Spickett     BufferOrError = getProcFile(GetID(), "maps");
126315930862SPavel Labath     if (!BufferOrError) {
126415930862SPavel Labath       m_supports_mem_region = LazyBool::eLazyBoolNo;
126515930862SPavel Labath       return BufferOrError.getError();
126615930862SPavel Labath     }
126732541685SDavid Spickett 
126832541685SDavid Spickett     ParseLinuxMapRegions(BufferOrError.get()->getBuffer(), callback);
1269a6f5795aSTamas Berghammer   }
127032541685SDavid Spickett 
1271c8e364e8SPavel Labath   if (Result.Fail())
1272c8e364e8SPavel Labath     return Result;
1273a6f5795aSTamas Berghammer 
127415930862SPavel Labath   if (m_mem_region_cache.empty()) {
1275a6f5795aSTamas Berghammer     // No entries after attempting to read them.  This shouldn't happen if
127605097246SAdrian Prantl     // /proc/{pid}/maps is supported. Assume we don't support map entries via
127705097246SAdrian Prantl     // procfs.
127815930862SPavel Labath     m_supports_mem_region = LazyBool::eLazyBoolNo;
1279a6321a8eSPavel Labath     LLDB_LOG(log,
1280a6321a8eSPavel Labath              "failed to find any procfs maps entries, assuming no support "
1281a6321a8eSPavel Labath              "for memory region metadata retrieval");
128297206d57SZachary Turner     return Status("not supported");
1283a6f5795aSTamas Berghammer   }
1284a6f5795aSTamas Berghammer 
1285a6321a8eSPavel Labath   LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps",
1286a6321a8eSPavel Labath            m_mem_region_cache.size(), GetID());
1287a6f5795aSTamas Berghammer 
1288a6f5795aSTamas Berghammer   // We support memory retrieval, remember that.
1289a6f5795aSTamas Berghammer   m_supports_mem_region = LazyBool::eLazyBoolYes;
129097206d57SZachary Turner   return Status();
1291a6f5795aSTamas Berghammer }
1292a6f5795aSTamas Berghammer 
1293b9c1b51eSKate Stone void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
1294a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1295a6321a8eSPavel Labath   LLDB_LOG(log, "newBumpId={0}", newBumpId);
1296a6321a8eSPavel Labath   LLDB_LOG(log, "clearing {0} entries from memory region cache",
1297a6321a8eSPavel Labath            m_mem_region_cache.size());
1298af245d11STodd Fiala   m_mem_region_cache.clear();
1299af245d11STodd Fiala }
1300af245d11STodd Fiala 
13012c4226f8SPavel Labath llvm::Expected<uint64_t>
13022c4226f8SPavel Labath NativeProcessLinux::Syscall(llvm::ArrayRef<uint64_t> args) {
13032c4226f8SPavel Labath   PopulateMemoryRegionCache();
13042c4226f8SPavel Labath   auto region_it = llvm::find_if(m_mem_region_cache, [](const auto &pair) {
13052c4226f8SPavel Labath     return pair.first.GetExecutable() == MemoryRegionInfo::eYes;
13062c4226f8SPavel Labath   });
13072c4226f8SPavel Labath   if (region_it == m_mem_region_cache.end())
13082c4226f8SPavel Labath     return llvm::createStringError(llvm::inconvertibleErrorCode(),
13092c4226f8SPavel Labath                                    "No executable memory region found!");
1310af245d11STodd Fiala 
13112c4226f8SPavel Labath   addr_t exe_addr = region_it->first.GetRange().GetRangeBase();
1312af245d11STodd Fiala 
13132c4226f8SPavel Labath   NativeThreadLinux &thread = *GetThreadByID(GetID());
13142c4226f8SPavel Labath   assert(thread.GetState() == eStateStopped);
13152c4226f8SPavel Labath   NativeRegisterContextLinux &reg_ctx = thread.GetRegisterContext();
13162c4226f8SPavel Labath 
13172c4226f8SPavel Labath   NativeRegisterContextLinux::SyscallData syscall_data =
13182c4226f8SPavel Labath       *reg_ctx.GetSyscallData();
13192c4226f8SPavel Labath 
13202c4226f8SPavel Labath   DataBufferSP registers_sp;
13212c4226f8SPavel Labath   if (llvm::Error Err = reg_ctx.ReadAllRegisterValues(registers_sp).ToError())
13222c4226f8SPavel Labath     return std::move(Err);
13232c4226f8SPavel Labath   auto restore_regs = llvm::make_scope_exit(
13242c4226f8SPavel Labath       [&] { reg_ctx.WriteAllRegisterValues(registers_sp); });
13252c4226f8SPavel Labath 
13262c4226f8SPavel Labath   llvm::SmallVector<uint8_t, 8> memory(syscall_data.Insn.size());
13272c4226f8SPavel Labath   size_t bytes_read;
13282c4226f8SPavel Labath   if (llvm::Error Err =
13292c4226f8SPavel Labath           ReadMemory(exe_addr, memory.data(), memory.size(), bytes_read)
13302c4226f8SPavel Labath               .ToError()) {
13312c4226f8SPavel Labath     return std::move(Err);
1332af245d11STodd Fiala   }
1333af245d11STodd Fiala 
13342c4226f8SPavel Labath   auto restore_mem = llvm::make_scope_exit(
13352c4226f8SPavel Labath       [&] { WriteMemory(exe_addr, memory.data(), memory.size(), bytes_read); });
13362c4226f8SPavel Labath 
13372c4226f8SPavel Labath   if (llvm::Error Err = reg_ctx.SetPC(exe_addr).ToError())
13382c4226f8SPavel Labath     return std::move(Err);
13392c4226f8SPavel Labath 
13402c4226f8SPavel Labath   for (const auto &zip : llvm::zip_first(args, syscall_data.Args)) {
13412c4226f8SPavel Labath     if (llvm::Error Err =
13422c4226f8SPavel Labath             reg_ctx
13432c4226f8SPavel Labath                 .WriteRegisterFromUnsigned(std::get<1>(zip), std::get<0>(zip))
13442c4226f8SPavel Labath                 .ToError()) {
13452c4226f8SPavel Labath       return std::move(Err);
13462c4226f8SPavel Labath     }
13472c4226f8SPavel Labath   }
13482c4226f8SPavel Labath   if (llvm::Error Err = WriteMemory(exe_addr, syscall_data.Insn.data(),
13492c4226f8SPavel Labath                                     syscall_data.Insn.size(), bytes_read)
13502c4226f8SPavel Labath                             .ToError())
13512c4226f8SPavel Labath     return std::move(Err);
13522c4226f8SPavel Labath 
13532c4226f8SPavel Labath   m_mem_region_cache.clear();
13542c4226f8SPavel Labath 
13552c4226f8SPavel Labath   // With software single stepping the syscall insn buffer must also include a
13562c4226f8SPavel Labath   // trap instruction to stop the process.
13572c4226f8SPavel Labath   int req = SupportHardwareSingleStepping() ? PTRACE_SINGLESTEP : PTRACE_CONT;
13582c4226f8SPavel Labath   if (llvm::Error Err =
13592c4226f8SPavel Labath           PtraceWrapper(req, thread.GetID(), nullptr, nullptr).ToError())
13602c4226f8SPavel Labath     return std::move(Err);
13612c4226f8SPavel Labath 
13622c4226f8SPavel Labath   int status;
13632c4226f8SPavel Labath   ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, thread.GetID(),
13642c4226f8SPavel Labath                                                  &status, __WALL);
13652c4226f8SPavel Labath   if (wait_pid == -1) {
13662c4226f8SPavel Labath     return llvm::errorCodeToError(
13672c4226f8SPavel Labath         std::error_code(errno, std::generic_category()));
13682c4226f8SPavel Labath   }
13692c4226f8SPavel Labath   assert((unsigned)wait_pid == thread.GetID());
13702c4226f8SPavel Labath 
13712c4226f8SPavel Labath   uint64_t result = reg_ctx.ReadRegisterAsUnsigned(syscall_data.Result, -ESRCH);
13722c4226f8SPavel Labath 
13732c4226f8SPavel Labath   // Values larger than this are actually negative errno numbers.
13742c4226f8SPavel Labath   uint64_t errno_threshold =
13752c4226f8SPavel Labath       (uint64_t(-1) >> (64 - 8 * m_arch.GetAddressByteSize())) - 0x1000;
13762c4226f8SPavel Labath   if (result > errno_threshold) {
13772c4226f8SPavel Labath     return llvm::errorCodeToError(
13782c4226f8SPavel Labath         std::error_code(-result & 0xfff, std::generic_category()));
13792c4226f8SPavel Labath   }
13802c4226f8SPavel Labath 
13812c4226f8SPavel Labath   return result;
13822c4226f8SPavel Labath }
13832c4226f8SPavel Labath 
13842c4226f8SPavel Labath llvm::Expected<addr_t>
13852c4226f8SPavel Labath NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions) {
13862c4226f8SPavel Labath 
13872c4226f8SPavel Labath   llvm::Optional<NativeRegisterContextLinux::MmapData> mmap_data =
13882c4226f8SPavel Labath       GetCurrentThread()->GetRegisterContext().GetMmapData();
13892c4226f8SPavel Labath   if (!mmap_data)
13902c4226f8SPavel Labath     return llvm::make_error<UnimplementedError>();
13912c4226f8SPavel Labath 
13922c4226f8SPavel Labath   unsigned prot = PROT_NONE;
13932c4226f8SPavel Labath   assert((permissions & (ePermissionsReadable | ePermissionsWritable |
13942c4226f8SPavel Labath                          ePermissionsExecutable)) == permissions &&
13952c4226f8SPavel Labath          "Unknown permission!");
13962c4226f8SPavel Labath   if (permissions & ePermissionsReadable)
13972c4226f8SPavel Labath     prot |= PROT_READ;
13982c4226f8SPavel Labath   if (permissions & ePermissionsWritable)
13992c4226f8SPavel Labath     prot |= PROT_WRITE;
14002c4226f8SPavel Labath   if (permissions & ePermissionsExecutable)
14012c4226f8SPavel Labath     prot |= PROT_EXEC;
14022c4226f8SPavel Labath 
14032c4226f8SPavel Labath   llvm::Expected<uint64_t> Result =
14042c4226f8SPavel Labath       Syscall({mmap_data->SysMmap, 0, size, prot, MAP_ANONYMOUS | MAP_PRIVATE,
14052c4226f8SPavel Labath                uint64_t(-1), 0});
14062c4226f8SPavel Labath   if (Result)
14072c4226f8SPavel Labath     m_allocated_memory.try_emplace(*Result, size);
14082c4226f8SPavel Labath   return Result;
14092c4226f8SPavel Labath }
14102c4226f8SPavel Labath 
14112c4226f8SPavel Labath llvm::Error NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {
14122c4226f8SPavel Labath   llvm::Optional<NativeRegisterContextLinux::MmapData> mmap_data =
14132c4226f8SPavel Labath       GetCurrentThread()->GetRegisterContext().GetMmapData();
14142c4226f8SPavel Labath   if (!mmap_data)
14152c4226f8SPavel Labath     return llvm::make_error<UnimplementedError>();
14162c4226f8SPavel Labath 
14172c4226f8SPavel Labath   auto it = m_allocated_memory.find(addr);
14182c4226f8SPavel Labath   if (it == m_allocated_memory.end())
14192c4226f8SPavel Labath     return llvm::createStringError(llvm::errc::invalid_argument,
14202c4226f8SPavel Labath                                    "Memory not allocated by the debugger.");
14212c4226f8SPavel Labath 
14222c4226f8SPavel Labath   llvm::Expected<uint64_t> Result =
14232c4226f8SPavel Labath       Syscall({mmap_data->SysMunmap, addr, it->second});
14242c4226f8SPavel Labath   if (!Result)
14252c4226f8SPavel Labath     return Result.takeError();
14262c4226f8SPavel Labath 
14272c4226f8SPavel Labath   m_allocated_memory.erase(it);
14282c4226f8SPavel Labath   return llvm::Error::success();
1429af245d11STodd Fiala }
1430af245d11STodd Fiala 
1431da2e614fSDavid Spickett Status NativeProcessLinux::ReadMemoryTags(int32_t type, lldb::addr_t addr,
1432da2e614fSDavid Spickett                                           size_t len,
1433da2e614fSDavid Spickett                                           std::vector<uint8_t> &tags) {
1434da2e614fSDavid Spickett   llvm::Expected<NativeRegisterContextLinux::MemoryTaggingDetails> details =
1435da2e614fSDavid Spickett       GetCurrentThread()->GetRegisterContext().GetMemoryTaggingDetails(type);
1436da2e614fSDavid Spickett   if (!details)
1437da2e614fSDavid Spickett     return Status(details.takeError());
1438da2e614fSDavid Spickett 
1439da2e614fSDavid Spickett   // Ignore 0 length read
1440da2e614fSDavid Spickett   if (!len)
1441da2e614fSDavid Spickett     return Status();
1442da2e614fSDavid Spickett 
1443da2e614fSDavid Spickett   // lldb will align the range it requests but it is not required to by
1444da2e614fSDavid Spickett   // the protocol so we'll do it again just in case.
1445da2e614fSDavid Spickett   // Remove non address bits too. Ptrace calls may work regardless but that
1446da2e614fSDavid Spickett   // is not a guarantee.
1447da2e614fSDavid Spickett   MemoryTagManager::TagRange range(details->manager->RemoveNonAddressBits(addr),
1448da2e614fSDavid Spickett                                    len);
1449da2e614fSDavid Spickett   range = details->manager->ExpandToGranule(range);
1450da2e614fSDavid Spickett 
1451da2e614fSDavid Spickett   // Allocate enough space for all tags to be read
1452da2e614fSDavid Spickett   size_t num_tags = range.GetByteSize() / details->manager->GetGranuleSize();
1453da2e614fSDavid Spickett   tags.resize(num_tags * details->manager->GetTagSizeInBytes());
1454da2e614fSDavid Spickett 
1455da2e614fSDavid Spickett   struct iovec tags_iovec;
1456da2e614fSDavid Spickett   uint8_t *dest = tags.data();
1457da2e614fSDavid Spickett   lldb::addr_t read_addr = range.GetRangeBase();
1458da2e614fSDavid Spickett 
1459da2e614fSDavid Spickett   // This call can return partial data so loop until we error or
1460da2e614fSDavid Spickett   // get all tags back.
1461da2e614fSDavid Spickett   while (num_tags) {
1462da2e614fSDavid Spickett     tags_iovec.iov_base = dest;
1463da2e614fSDavid Spickett     tags_iovec.iov_len = num_tags;
1464da2e614fSDavid Spickett 
1465da2e614fSDavid Spickett     Status error = NativeProcessLinux::PtraceWrapper(
1466da2e614fSDavid Spickett         details->ptrace_read_req, GetID(), reinterpret_cast<void *>(read_addr),
1467da2e614fSDavid Spickett         static_cast<void *>(&tags_iovec), 0, nullptr);
1468da2e614fSDavid Spickett 
1469da2e614fSDavid Spickett     if (error.Fail()) {
1470da2e614fSDavid Spickett       // Discard partial reads
1471da2e614fSDavid Spickett       tags.resize(0);
1472da2e614fSDavid Spickett       return error;
1473da2e614fSDavid Spickett     }
1474da2e614fSDavid Spickett 
1475da2e614fSDavid Spickett     size_t tags_read = tags_iovec.iov_len;
1476da2e614fSDavid Spickett     assert(tags_read && (tags_read <= num_tags));
1477da2e614fSDavid Spickett 
1478da2e614fSDavid Spickett     dest += tags_read * details->manager->GetTagSizeInBytes();
1479da2e614fSDavid Spickett     read_addr += details->manager->GetGranuleSize() * tags_read;
1480da2e614fSDavid Spickett     num_tags -= tags_read;
1481da2e614fSDavid Spickett   }
1482da2e614fSDavid Spickett 
1483da2e614fSDavid Spickett   return Status();
1484da2e614fSDavid Spickett }
1485da2e614fSDavid Spickett 
14867d27230dSDavid Spickett Status NativeProcessLinux::WriteMemoryTags(int32_t type, lldb::addr_t addr,
14877d27230dSDavid Spickett                                            size_t len,
14887d27230dSDavid Spickett                                            const std::vector<uint8_t> &tags) {
14897d27230dSDavid Spickett   llvm::Expected<NativeRegisterContextLinux::MemoryTaggingDetails> details =
14907d27230dSDavid Spickett       GetCurrentThread()->GetRegisterContext().GetMemoryTaggingDetails(type);
14917d27230dSDavid Spickett   if (!details)
14927d27230dSDavid Spickett     return Status(details.takeError());
14937d27230dSDavid Spickett 
14947d27230dSDavid Spickett   // Ignore 0 length write
14957d27230dSDavid Spickett   if (!len)
14967d27230dSDavid Spickett     return Status();
14977d27230dSDavid Spickett 
14987d27230dSDavid Spickett   // lldb will align the range it requests but it is not required to by
14997d27230dSDavid Spickett   // the protocol so we'll do it again just in case.
15007d27230dSDavid Spickett   // Remove non address bits too. Ptrace calls may work regardless but that
15017d27230dSDavid Spickett   // is not a guarantee.
15027d27230dSDavid Spickett   MemoryTagManager::TagRange range(details->manager->RemoveNonAddressBits(addr),
15037d27230dSDavid Spickett                                    len);
15047d27230dSDavid Spickett   range = details->manager->ExpandToGranule(range);
15057d27230dSDavid Spickett 
15067d27230dSDavid Spickett   // Not checking number of tags here, we may repeat them below
15077d27230dSDavid Spickett   llvm::Expected<std::vector<lldb::addr_t>> unpacked_tags_or_err =
15087d27230dSDavid Spickett       details->manager->UnpackTagsData(tags);
15097d27230dSDavid Spickett   if (!unpacked_tags_or_err)
15107d27230dSDavid Spickett     return Status(unpacked_tags_or_err.takeError());
15117d27230dSDavid Spickett 
15127d27230dSDavid Spickett   llvm::Expected<std::vector<lldb::addr_t>> repeated_tags_or_err =
15137d27230dSDavid Spickett       details->manager->RepeatTagsForRange(*unpacked_tags_or_err, range);
15147d27230dSDavid Spickett   if (!repeated_tags_or_err)
15157d27230dSDavid Spickett     return Status(repeated_tags_or_err.takeError());
15167d27230dSDavid Spickett 
15177d27230dSDavid Spickett   // Repack them for ptrace to use
15187d27230dSDavid Spickett   llvm::Expected<std::vector<uint8_t>> final_tag_data =
15197d27230dSDavid Spickett       details->manager->PackTags(*repeated_tags_or_err);
15207d27230dSDavid Spickett   if (!final_tag_data)
15217d27230dSDavid Spickett     return Status(final_tag_data.takeError());
15227d27230dSDavid Spickett 
15237d27230dSDavid Spickett   struct iovec tags_vec;
15247d27230dSDavid Spickett   uint8_t *src = final_tag_data->data();
15257d27230dSDavid Spickett   lldb::addr_t write_addr = range.GetRangeBase();
15267d27230dSDavid Spickett   // unpacked tags size because the number of bytes per tag might not be 1
15277d27230dSDavid Spickett   size_t num_tags = repeated_tags_or_err->size();
15287d27230dSDavid Spickett 
15297d27230dSDavid Spickett   // This call can partially write tags, so we loop until we
15307d27230dSDavid Spickett   // error or all tags have been written.
15317d27230dSDavid Spickett   while (num_tags > 0) {
15327d27230dSDavid Spickett     tags_vec.iov_base = src;
15337d27230dSDavid Spickett     tags_vec.iov_len = num_tags;
15347d27230dSDavid Spickett 
15357d27230dSDavid Spickett     Status error = NativeProcessLinux::PtraceWrapper(
15367d27230dSDavid Spickett         details->ptrace_write_req, GetID(),
15377d27230dSDavid Spickett         reinterpret_cast<void *>(write_addr), static_cast<void *>(&tags_vec), 0,
15387d27230dSDavid Spickett         nullptr);
15397d27230dSDavid Spickett 
15407d27230dSDavid Spickett     if (error.Fail()) {
15417d27230dSDavid Spickett       // Don't attempt to restore the original values in the case of a partial
15427d27230dSDavid Spickett       // write
15437d27230dSDavid Spickett       return error;
15447d27230dSDavid Spickett     }
15457d27230dSDavid Spickett 
15467d27230dSDavid Spickett     size_t tags_written = tags_vec.iov_len;
15477d27230dSDavid Spickett     assert(tags_written && (tags_written <= num_tags));
15487d27230dSDavid Spickett 
15497d27230dSDavid Spickett     src += tags_written * details->manager->GetTagSizeInBytes();
15507d27230dSDavid Spickett     write_addr += details->manager->GetGranuleSize() * tags_written;
15517d27230dSDavid Spickett     num_tags -= tags_written;
15527d27230dSDavid Spickett   }
15537d27230dSDavid Spickett 
15547d27230dSDavid Spickett   return Status();
15557d27230dSDavid Spickett }
15567d27230dSDavid Spickett 
1557b9c1b51eSKate Stone size_t NativeProcessLinux::UpdateThreads() {
155805097246SAdrian Prantl   // The NativeProcessLinux monitoring threads are always up to date with
155905097246SAdrian Prantl   // respect to thread state and they keep the thread list populated properly.
156005097246SAdrian Prantl   // All this method needs to do is return the thread count.
1561af245d11STodd Fiala   return m_threads.size();
1562af245d11STodd Fiala }
1563af245d11STodd Fiala 
156497206d57SZachary Turner Status NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,
1565b9c1b51eSKate Stone                                          bool hardware) {
1566af245d11STodd Fiala   if (hardware)
1567d5ffbad2SOmair Javaid     return SetHardwareBreakpoint(addr, size);
1568af245d11STodd Fiala   else
1569af245d11STodd Fiala     return SetSoftwareBreakpoint(addr, size);
1570af245d11STodd Fiala }
1571af245d11STodd Fiala 
157297206d57SZachary Turner Status NativeProcessLinux::RemoveBreakpoint(lldb::addr_t addr, bool hardware) {
1573d5ffbad2SOmair Javaid   if (hardware)
1574d5ffbad2SOmair Javaid     return RemoveHardwareBreakpoint(addr);
1575d5ffbad2SOmair Javaid   else
1576d5ffbad2SOmair Javaid     return NativeProcessProtocol::RemoveBreakpoint(addr);
1577d5ffbad2SOmair Javaid }
1578d5ffbad2SOmair Javaid 
1579f8b825f6SPavel Labath llvm::Expected<llvm::ArrayRef<uint8_t>>
1580f8b825f6SPavel Labath NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(size_t size_hint) {
1581be379e15STamas Berghammer   // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1582be379e15STamas Berghammer   // linux kernel does otherwise.
1583f8b825f6SPavel Labath   static const uint8_t g_arm_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1584f8b825f6SPavel Labath   static const uint8_t g_thumb_opcode[] = {0x01, 0xde};
158512286a27SPavel Labath 
1586f8b825f6SPavel Labath   switch (GetArchitecture().GetMachine()) {
158712286a27SPavel Labath   case llvm::Triple::arm:
1588f8b825f6SPavel Labath     switch (size_hint) {
158963c8be95STamas Berghammer     case 2:
15904f545074SPavel Labath       return llvm::makeArrayRef(g_thumb_opcode);
159163c8be95STamas Berghammer     case 4:
15924f545074SPavel Labath       return llvm::makeArrayRef(g_arm_opcode);
159363c8be95STamas Berghammer     default:
1594f8b825f6SPavel Labath       return llvm::createStringError(llvm::inconvertibleErrorCode(),
1595f8b825f6SPavel Labath                                      "Unrecognised trap opcode size hint!");
159663c8be95STamas Berghammer     }
1597af245d11STodd Fiala   default:
1598f8b825f6SPavel Labath     return NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_hint);
1599af245d11STodd Fiala   }
1600af245d11STodd Fiala }
1601af245d11STodd Fiala 
160297206d57SZachary Turner Status NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
1603b9c1b51eSKate Stone                                       size_t &bytes_read) {
1604df7c6995SPavel Labath   if (ProcessVmReadvSupported()) {
1605b9c1b51eSKate Stone     // The process_vm_readv path is about 50 times faster than ptrace api. We
160605097246SAdrian Prantl     // want to use this syscall if it is supported.
1607df7c6995SPavel Labath 
1608df7c6995SPavel Labath     const ::pid_t pid = GetID();
1609df7c6995SPavel Labath 
1610df7c6995SPavel Labath     struct iovec local_iov, remote_iov;
1611df7c6995SPavel Labath     local_iov.iov_base = buf;
1612df7c6995SPavel Labath     local_iov.iov_len = size;
1613df7c6995SPavel Labath     remote_iov.iov_base = reinterpret_cast<void *>(addr);
1614df7c6995SPavel Labath     remote_iov.iov_len = size;
1615df7c6995SPavel Labath 
1616df7c6995SPavel Labath     bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
1617df7c6995SPavel Labath     const bool success = bytes_read == size;
1618df7c6995SPavel Labath 
1619a6321a8eSPavel Labath     Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1620a6321a8eSPavel Labath     LLDB_LOG(log,
1621a6321a8eSPavel Labath              "using process_vm_readv to read {0} bytes from inferior "
1622a6321a8eSPavel Labath              "address {1:x}: {2}",
162310c41f37SPavel Labath              size, addr, success ? "Success" : llvm::sys::StrError(errno));
1624df7c6995SPavel Labath 
1625df7c6995SPavel Labath     if (success)
162697206d57SZachary Turner       return Status();
1627a6321a8eSPavel Labath     // else the call failed for some reason, let's retry the read using ptrace
1628b9c1b51eSKate Stone     // api.
1629df7c6995SPavel Labath   }
1630df7c6995SPavel Labath 
163119cbe96aSPavel Labath   unsigned char *dst = static_cast<unsigned char *>(buf);
163219cbe96aSPavel Labath   size_t remainder;
163319cbe96aSPavel Labath   long data;
163419cbe96aSPavel Labath 
1635a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1636a6321a8eSPavel Labath   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
163719cbe96aSPavel Labath 
1638b9c1b51eSKate Stone   for (bytes_read = 0; bytes_read < size; bytes_read += remainder) {
163997206d57SZachary Turner     Status error = NativeProcessLinux::PtraceWrapper(
1640b9c1b51eSKate Stone         PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data);
1641a6321a8eSPavel Labath     if (error.Fail())
164219cbe96aSPavel Labath       return error;
164319cbe96aSPavel Labath 
164419cbe96aSPavel Labath     remainder = size - bytes_read;
164519cbe96aSPavel Labath     remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
164619cbe96aSPavel Labath 
164719cbe96aSPavel Labath     // Copy the data into our buffer
1648f6ef187bSMohit K. Bhakkad     memcpy(dst, &data, remainder);
164919cbe96aSPavel Labath 
1650a6321a8eSPavel Labath     LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
165119cbe96aSPavel Labath     addr += k_ptrace_word_size;
165219cbe96aSPavel Labath     dst += k_ptrace_word_size;
165319cbe96aSPavel Labath   }
165497206d57SZachary Turner   return Status();
1655af245d11STodd Fiala }
1656af245d11STodd Fiala 
165797206d57SZachary Turner Status NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,
1658b9c1b51eSKate Stone                                        size_t size, size_t &bytes_written) {
165919cbe96aSPavel Labath   const unsigned char *src = static_cast<const unsigned char *>(buf);
166019cbe96aSPavel Labath   size_t remainder;
166197206d57SZachary Turner   Status error;
166219cbe96aSPavel Labath 
1663a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1664a6321a8eSPavel Labath   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
166519cbe96aSPavel Labath 
1666b9c1b51eSKate Stone   for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
166719cbe96aSPavel Labath     remainder = size - bytes_written;
166819cbe96aSPavel Labath     remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
166919cbe96aSPavel Labath 
1670b9c1b51eSKate Stone     if (remainder == k_ptrace_word_size) {
167119cbe96aSPavel Labath       unsigned long data = 0;
1672f6ef187bSMohit K. Bhakkad       memcpy(&data, src, k_ptrace_word_size);
167319cbe96aSPavel Labath 
1674a6321a8eSPavel Labath       LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
1675b9c1b51eSKate Stone       error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(),
1676b9c1b51eSKate Stone                                                 (void *)addr, (void *)data);
1677a6321a8eSPavel Labath       if (error.Fail())
167819cbe96aSPavel Labath         return error;
1679b9c1b51eSKate Stone     } else {
168019cbe96aSPavel Labath       unsigned char buff[8];
168119cbe96aSPavel Labath       size_t bytes_read;
168219cbe96aSPavel Labath       error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
1683a6321a8eSPavel Labath       if (error.Fail())
168419cbe96aSPavel Labath         return error;
168519cbe96aSPavel Labath 
168619cbe96aSPavel Labath       memcpy(buff, src, remainder);
168719cbe96aSPavel Labath 
168819cbe96aSPavel Labath       size_t bytes_written_rec;
168919cbe96aSPavel Labath       error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
1690a6321a8eSPavel Labath       if (error.Fail())
169119cbe96aSPavel Labath         return error;
169219cbe96aSPavel Labath 
1693a6321a8eSPavel Labath       LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src,
1694b9c1b51eSKate Stone                *(unsigned long *)buff);
169519cbe96aSPavel Labath     }
169619cbe96aSPavel Labath 
169719cbe96aSPavel Labath     addr += k_ptrace_word_size;
169819cbe96aSPavel Labath     src += k_ptrace_word_size;
169919cbe96aSPavel Labath   }
170019cbe96aSPavel Labath   return error;
1701af245d11STodd Fiala }
1702af245d11STodd Fiala 
170397206d57SZachary Turner Status NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) {
170419cbe96aSPavel Labath   return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
1705af245d11STodd Fiala }
1706af245d11STodd Fiala 
170797206d57SZachary Turner Status NativeProcessLinux::GetEventMessage(lldb::tid_t tid,
1708b9c1b51eSKate Stone                                            unsigned long *message) {
170919cbe96aSPavel Labath   return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
1710af245d11STodd Fiala }
1711af245d11STodd Fiala 
171297206d57SZachary Turner Status NativeProcessLinux::Detach(lldb::tid_t tid) {
171397ccc294SChaoren Lin   if (tid == LLDB_INVALID_THREAD_ID)
171497206d57SZachary Turner     return Status();
171597ccc294SChaoren Lin 
171619cbe96aSPavel Labath   return PtraceWrapper(PTRACE_DETACH, tid);
1717af245d11STodd Fiala }
1718af245d11STodd Fiala 
1719b9c1b51eSKate Stone bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {
1720a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
1721a5be48b3SPavel Labath     assert(thread && "thread list should not contain NULL threads");
1722a5be48b3SPavel Labath     if (thread->GetID() == thread_id) {
1723af245d11STodd Fiala       // We have this thread.
1724af245d11STodd Fiala       return true;
1725af245d11STodd Fiala     }
1726af245d11STodd Fiala   }
1727af245d11STodd Fiala 
1728af245d11STodd Fiala   // We don't have this thread.
1729af245d11STodd Fiala   return false;
1730af245d11STodd Fiala }
1731af245d11STodd Fiala 
1732b9c1b51eSKate Stone bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) {
1733a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1734a6321a8eSPavel Labath   LLDB_LOG(log, "tid: {0})", thread_id);
17351dbc6c9cSPavel Labath 
17361dbc6c9cSPavel Labath   bool found = false;
1737b9c1b51eSKate Stone   for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
1738b9c1b51eSKate Stone     if (*it && ((*it)->GetID() == thread_id)) {
1739af245d11STodd Fiala       m_threads.erase(it);
17401dbc6c9cSPavel Labath       found = true;
17411dbc6c9cSPavel Labath       break;
1742af245d11STodd Fiala     }
1743af245d11STodd Fiala   }
1744af245d11STodd Fiala 
174599e37695SRavitheja Addepally   if (found)
17460b697561SWalter Erquinigo     NotifyTracersOfThreadDestroyed(thread_id);
17470b697561SWalter Erquinigo 
17489eb1ecb9SPavel Labath   SignalIfAllThreadsStopped();
17491dbc6c9cSPavel Labath   return found;
1750af245d11STodd Fiala }
1751af245d11STodd Fiala 
17520b697561SWalter Erquinigo Status NativeProcessLinux::NotifyTracersOfNewThread(lldb::tid_t tid) {
17530b697561SWalter Erquinigo   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
17540b697561SWalter Erquinigo   Status error(m_intel_pt_manager.OnThreadCreated(tid));
17550b697561SWalter Erquinigo   if (error.Fail())
17560b697561SWalter Erquinigo     LLDB_LOG(log, "Failed to trace a new thread with intel-pt, tid = {0}. {1}",
17570b697561SWalter Erquinigo              tid, error.AsCString());
17580b697561SWalter Erquinigo   return error;
17590b697561SWalter Erquinigo }
17600b697561SWalter Erquinigo 
17610b697561SWalter Erquinigo Status NativeProcessLinux::NotifyTracersOfThreadDestroyed(lldb::tid_t tid) {
17620b697561SWalter Erquinigo   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
17630b697561SWalter Erquinigo   Status error(m_intel_pt_manager.OnThreadDestroyed(tid));
17640b697561SWalter Erquinigo   if (error.Fail())
17650b697561SWalter Erquinigo     LLDB_LOG(log,
17660b697561SWalter Erquinigo              "Failed to stop a destroyed thread with intel-pt, tid = {0}. {1}",
17670b697561SWalter Erquinigo              tid, error.AsCString());
17680b697561SWalter Erquinigo   return error;
17690b697561SWalter Erquinigo }
17700b697561SWalter Erquinigo 
17710b697561SWalter Erquinigo NativeThreadLinux &NativeProcessLinux::AddThread(lldb::tid_t thread_id,
17720b697561SWalter Erquinigo                                                  bool resume) {
1773a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
1774a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
1775af245d11STodd Fiala 
1776b9c1b51eSKate Stone   assert(!HasThreadNoLock(thread_id) &&
1777b9c1b51eSKate Stone          "attempted to add a thread by id that already exists");
1778af245d11STodd Fiala 
1779af245d11STodd Fiala   // If this is the first thread, save it as the current thread
1780af245d11STodd Fiala   if (m_threads.empty())
1781af245d11STodd Fiala     SetCurrentThreadID(thread_id);
1782af245d11STodd Fiala 
1783a8f3ae7cSJonas Devlieghere   m_threads.push_back(std::make_unique<NativeThreadLinux>(*this, thread_id));
17840b697561SWalter Erquinigo   NativeThreadLinux &thread =
17850b697561SWalter Erquinigo       static_cast<NativeThreadLinux &>(*m_threads.back());
178699e37695SRavitheja Addepally 
17870b697561SWalter Erquinigo   Status tracing_error = NotifyTracersOfNewThread(thread.GetID());
17880b697561SWalter Erquinigo   if (tracing_error.Fail()) {
17890b697561SWalter Erquinigo     thread.SetStoppedByProcessorTrace(tracing_error.AsCString());
17900b697561SWalter Erquinigo     StopRunningThreads(thread.GetID());
17910b697561SWalter Erquinigo   } else if (resume)
17920b697561SWalter Erquinigo     ResumeThread(thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
17930b697561SWalter Erquinigo   else
17940b697561SWalter Erquinigo     thread.SetStoppedBySignal(SIGSTOP);
179599e37695SRavitheja Addepally 
17960b697561SWalter Erquinigo   return thread;
1797af245d11STodd Fiala }
1798af245d11STodd Fiala 
179997206d57SZachary Turner Status NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,
1800b9c1b51eSKate Stone                                                    FileSpec &file_spec) {
180197206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
1802a6f5795aSTamas Berghammer   if (error.Fail())
1803a6f5795aSTamas Berghammer     return error;
1804a6f5795aSTamas Berghammer 
18058f3be7a3SJonas Devlieghere   FileSpec module_file_spec(module_path);
18068f3be7a3SJonas Devlieghere   FileSystem::Instance().Resolve(module_file_spec);
18077cb18bf5STamas Berghammer 
18087cb18bf5STamas Berghammer   file_spec.Clear();
1809a6f5795aSTamas Berghammer   for (const auto &it : m_mem_region_cache) {
1810a6f5795aSTamas Berghammer     if (it.second.GetFilename() == module_file_spec.GetFilename()) {
1811a6f5795aSTamas Berghammer       file_spec = it.second;
181297206d57SZachary Turner       return Status();
1813a6f5795aSTamas Berghammer     }
1814a6f5795aSTamas Berghammer   }
181597206d57SZachary Turner   return Status("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
18167cb18bf5STamas Berghammer                 module_file_spec.GetFilename().AsCString(), GetID());
18177cb18bf5STamas Berghammer }
1818c076559aSPavel Labath 
181997206d57SZachary Turner Status NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
1820b9c1b51eSKate Stone                                               lldb::addr_t &load_addr) {
1821783bfc8cSTamas Berghammer   load_addr = LLDB_INVALID_ADDRESS;
182297206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
1823a6f5795aSTamas Berghammer   if (error.Fail())
1824783bfc8cSTamas Berghammer     return error;
1825a6f5795aSTamas Berghammer 
18268f3be7a3SJonas Devlieghere   FileSpec file(file_name);
1827a6f5795aSTamas Berghammer   for (const auto &it : m_mem_region_cache) {
1828a6f5795aSTamas Berghammer     if (it.second == file) {
1829a6f5795aSTamas Berghammer       load_addr = it.first.GetRange().GetRangeBase();
183097206d57SZachary Turner       return Status();
1831a6f5795aSTamas Berghammer     }
1832a6f5795aSTamas Berghammer   }
183397206d57SZachary Turner   return Status("No load address found for specified file.");
1834783bfc8cSTamas Berghammer }
1835783bfc8cSTamas Berghammer 
1836a5be48b3SPavel Labath NativeThreadLinux *NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {
1837a5be48b3SPavel Labath   return static_cast<NativeThreadLinux *>(
1838b9c1b51eSKate Stone       NativeProcessProtocol::GetThreadByID(tid));
1839f9077782SPavel Labath }
1840f9077782SPavel Labath 
18412c4226f8SPavel Labath NativeThreadLinux *NativeProcessLinux::GetCurrentThread() {
18422c4226f8SPavel Labath   return static_cast<NativeThreadLinux *>(
18432c4226f8SPavel Labath       NativeProcessProtocol::GetCurrentThread());
18442c4226f8SPavel Labath }
18452c4226f8SPavel Labath 
184697206d57SZachary Turner Status NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,
1847b9c1b51eSKate Stone                                         lldb::StateType state, int signo) {
1848a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1849a6321a8eSPavel Labath   LLDB_LOG(log, "tid: {0}", thread.GetID());
1850c076559aSPavel Labath 
185105097246SAdrian Prantl   // Before we do the resume below, first check if we have a pending stop
185205097246SAdrian Prantl   // notification that is currently waiting for all threads to stop.  This is
185305097246SAdrian Prantl   // potentially a buggy situation since we're ostensibly waiting for threads
185405097246SAdrian Prantl   // to stop before we send out the pending notification, and here we are
185505097246SAdrian Prantl   // resuming one before we send out the pending stop notification.
1856a6321a8eSPavel Labath   if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
1857a6321a8eSPavel Labath     LLDB_LOG(log,
1858a6321a8eSPavel Labath              "about to resume tid {0} per explicit request but we have a "
1859a6321a8eSPavel Labath              "pending stop notification (tid {1}) that is actively "
1860a6321a8eSPavel Labath              "waiting for this thread to stop. Valid sequence of events?",
1861a6321a8eSPavel Labath              thread.GetID(), m_pending_notification_tid);
1862c076559aSPavel Labath   }
1863c076559aSPavel Labath 
186405097246SAdrian Prantl   // Request a resume.  We expect this to be synchronous and the system to
186505097246SAdrian Prantl   // reflect it is running after this completes.
1866b9c1b51eSKate Stone   switch (state) {
1867b9c1b51eSKate Stone   case eStateRunning: {
1868605b51b8SPavel Labath     const auto resume_result = thread.Resume(signo);
18690e1d729bSPavel Labath     if (resume_result.Success())
18700e1d729bSPavel Labath       SetState(eStateRunning, true);
18710e1d729bSPavel Labath     return resume_result;
1872c076559aSPavel Labath   }
1873b9c1b51eSKate Stone   case eStateStepping: {
1874605b51b8SPavel Labath     const auto step_result = thread.SingleStep(signo);
18750e1d729bSPavel Labath     if (step_result.Success())
18760e1d729bSPavel Labath       SetState(eStateRunning, true);
18770e1d729bSPavel Labath     return step_result;
18780e1d729bSPavel Labath   }
18790e1d729bSPavel Labath   default:
18808198db30SPavel Labath     LLDB_LOG(log, "Unhandled state {0}.", state);
18810e1d729bSPavel Labath     llvm_unreachable("Unhandled state for resume");
18820e1d729bSPavel Labath   }
1883c076559aSPavel Labath }
1884c076559aSPavel Labath 
1885c076559aSPavel Labath //===----------------------------------------------------------------------===//
1886c076559aSPavel Labath 
1887b9c1b51eSKate Stone void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {
1888a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1889a6321a8eSPavel Labath   LLDB_LOG(log, "about to process event: (triggering_tid: {0})",
1890a6321a8eSPavel Labath            triggering_tid);
1891c076559aSPavel Labath 
18920e1d729bSPavel Labath   m_pending_notification_tid = triggering_tid;
18930e1d729bSPavel Labath 
189405097246SAdrian Prantl   // Request a stop for all the thread stops that need to be stopped and are
189505097246SAdrian Prantl   // not already known to be stopped.
1896a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
1897a5be48b3SPavel Labath     if (StateIsRunningState(thread->GetState()))
1898a5be48b3SPavel Labath       static_cast<NativeThreadLinux *>(thread.get())->RequestStop();
18990e1d729bSPavel Labath   }
19000e1d729bSPavel Labath 
19010e1d729bSPavel Labath   SignalIfAllThreadsStopped();
1902a6321a8eSPavel Labath   LLDB_LOG(log, "event processing done");
1903c076559aSPavel Labath }
1904c076559aSPavel Labath 
1905b9c1b51eSKate Stone void NativeProcessLinux::SignalIfAllThreadsStopped() {
19060e1d729bSPavel Labath   if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
19070e1d729bSPavel Labath     return; // No pending notification. Nothing to do.
19080e1d729bSPavel Labath 
1909b9c1b51eSKate Stone   for (const auto &thread_sp : m_threads) {
19100e1d729bSPavel Labath     if (StateIsRunningState(thread_sp->GetState()))
19110e1d729bSPavel Labath       return; // Some threads are still running. Don't signal yet.
19120e1d729bSPavel Labath   }
19130e1d729bSPavel Labath 
19140e1d729bSPavel Labath   // We have a pending notification and all threads have stopped.
1915b9c1b51eSKate Stone   Log *log(
1916b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
19179eb1ecb9SPavel Labath 
1918b9c1b51eSKate Stone   // Clear any temporary breakpoints we used to implement software single
1919b9c1b51eSKate Stone   // stepping.
1920b9c1b51eSKate Stone   for (const auto &thread_info : m_threads_stepping_with_breakpoint) {
192197206d57SZachary Turner     Status error = RemoveBreakpoint(thread_info.second);
19229eb1ecb9SPavel Labath     if (error.Fail())
1923a6321a8eSPavel Labath       LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}",
1924a6321a8eSPavel Labath                thread_info.first, error);
19259eb1ecb9SPavel Labath   }
19269eb1ecb9SPavel Labath   m_threads_stepping_with_breakpoint.clear();
19279eb1ecb9SPavel Labath 
19289eb1ecb9SPavel Labath   // Notify the delegate about the stop
19290e1d729bSPavel Labath   SetCurrentThreadID(m_pending_notification_tid);
1930ed89c7feSPavel Labath   SetState(StateType::eStateStopped, true);
19310e1d729bSPavel Labath   m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
1932c076559aSPavel Labath }
1933c076559aSPavel Labath 
1934b9c1b51eSKate Stone void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {
1935a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1936a6321a8eSPavel Labath   LLDB_LOG(log, "tid: {0}", thread.GetID());
19371dbc6c9cSPavel Labath 
1938b9c1b51eSKate Stone   if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID &&
1939b9c1b51eSKate Stone       StateIsRunningState(thread.GetState())) {
1940b9c1b51eSKate Stone     // We will need to wait for this new thread to stop as well before firing
194105097246SAdrian Prantl     // the notification.
1942f9077782SPavel Labath     thread.RequestStop();
1943c076559aSPavel Labath   }
1944c076559aSPavel Labath }
1945068f8a7eSTamas Berghammer 
1946b9c1b51eSKate Stone void NativeProcessLinux::SigchldHandler() {
1947a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
194819cbe96aSPavel Labath   // Process all pending waitpid notifications.
1949b9c1b51eSKate Stone   while (true) {
195019cbe96aSPavel Labath     int status = -1;
1951c1a6b128SPavel Labath     ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, -1, &status,
1952c1a6b128SPavel Labath                                           __WALL | __WNOTHREAD | WNOHANG);
195319cbe96aSPavel Labath 
195419cbe96aSPavel Labath     if (wait_pid == 0)
195519cbe96aSPavel Labath       break; // We are done.
195619cbe96aSPavel Labath 
1957b9c1b51eSKate Stone     if (wait_pid == -1) {
195897206d57SZachary Turner       Status error(errno, eErrorTypePOSIX);
1959a6321a8eSPavel Labath       LLDB_LOG(log, "waitpid (-1, &status, _) failed: {0}", error);
196019cbe96aSPavel Labath       break;
196119cbe96aSPavel Labath     }
196219cbe96aSPavel Labath 
19633508fc8cSPavel Labath     WaitStatus wait_status = WaitStatus::Decode(status);
196419cbe96aSPavel Labath 
1965*fdd741ddSPavel Labath     LLDB_LOG(log, "waitpid (-1, &status, _) => pid = {0}, status = {1}",
1966*fdd741ddSPavel Labath              wait_pid, wait_status);
196719cbe96aSPavel Labath 
1968*fdd741ddSPavel Labath     MonitorCallback(wait_pid, wait_status);
196919cbe96aSPavel Labath   }
1970068f8a7eSTamas Berghammer }
1971068f8a7eSTamas Berghammer 
197205097246SAdrian Prantl // Wrapper for ptrace to catch errors and log calls. Note that ptrace sets
197305097246SAdrian Prantl // errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
197497206d57SZachary Turner Status NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
1975b9c1b51eSKate Stone                                          void *data, size_t data_size,
1976b9c1b51eSKate Stone                                          long *result) {
197797206d57SZachary Turner   Status error;
19784a9babb2SPavel Labath   long int ret;
1979068f8a7eSTamas Berghammer 
1980068f8a7eSTamas Berghammer   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
1981068f8a7eSTamas Berghammer 
1982068f8a7eSTamas Berghammer   PtraceDisplayBytes(req, data, data_size);
1983068f8a7eSTamas Berghammer 
1984068f8a7eSTamas Berghammer   errno = 0;
1985068f8a7eSTamas Berghammer   if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
1986b9c1b51eSKate Stone     ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
1987b9c1b51eSKate Stone                  *(unsigned int *)addr, data);
1988068f8a7eSTamas Berghammer   else
1989b9c1b51eSKate Stone     ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
1990b9c1b51eSKate Stone                  addr, data);
1991068f8a7eSTamas Berghammer 
19924a9babb2SPavel Labath   if (ret == -1)
1993068f8a7eSTamas Berghammer     error.SetErrorToErrno();
1994068f8a7eSTamas Berghammer 
19954a9babb2SPavel Labath   if (result)
19964a9babb2SPavel Labath     *result = ret;
19974a9babb2SPavel Labath 
199828096200SPavel Labath   LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data,
199928096200SPavel Labath            data_size, ret);
2000068f8a7eSTamas Berghammer 
2001068f8a7eSTamas Berghammer   PtraceDisplayBytes(req, data, data_size);
2002068f8a7eSTamas Berghammer 
2003a6321a8eSPavel Labath   if (error.Fail())
2004a6321a8eSPavel Labath     LLDB_LOG(log, "ptrace() failed: {0}", error);
2005068f8a7eSTamas Berghammer 
20064a9babb2SPavel Labath   return error;
2007068f8a7eSTamas Berghammer }
200899e37695SRavitheja Addepally 
20090b697561SWalter Erquinigo llvm::Expected<TraceSupportedResponse> NativeProcessLinux::TraceSupported() {
20100b697561SWalter Erquinigo   if (IntelPTManager::IsSupported())
20110b697561SWalter Erquinigo     return TraceSupportedResponse{"intel-pt", "Intel Processor Trace"};
20120b697561SWalter Erquinigo   return NativeProcessProtocol::TraceSupported();
201399e37695SRavitheja Addepally }
201499e37695SRavitheja Addepally 
20150b697561SWalter Erquinigo Error NativeProcessLinux::TraceStart(StringRef json_request, StringRef type) {
20160b697561SWalter Erquinigo   if (type == "intel-pt") {
20170b697561SWalter Erquinigo     if (Expected<TraceIntelPTStartRequest> request =
20180b697561SWalter Erquinigo             json::parse<TraceIntelPTStartRequest>(json_request,
20190b697561SWalter Erquinigo                                                   "TraceIntelPTStartRequest")) {
20200b697561SWalter Erquinigo       std::vector<lldb::tid_t> process_threads;
20210b697561SWalter Erquinigo       for (auto &thread : m_threads)
20220b697561SWalter Erquinigo         process_threads.push_back(thread->GetID());
20230b697561SWalter Erquinigo       return m_intel_pt_manager.TraceStart(*request, process_threads);
20240b697561SWalter Erquinigo     } else
20250b697561SWalter Erquinigo       return request.takeError();
202699e37695SRavitheja Addepally   }
202799e37695SRavitheja Addepally 
20280b697561SWalter Erquinigo   return NativeProcessProtocol::TraceStart(json_request, type);
202999e37695SRavitheja Addepally }
203099e37695SRavitheja Addepally 
20310b697561SWalter Erquinigo Error NativeProcessLinux::TraceStop(const TraceStopRequest &request) {
20320b697561SWalter Erquinigo   if (request.type == "intel-pt")
20330b697561SWalter Erquinigo     return m_intel_pt_manager.TraceStop(request);
20340b697561SWalter Erquinigo   return NativeProcessProtocol::TraceStop(request);
203599e37695SRavitheja Addepally }
203699e37695SRavitheja Addepally 
20370b697561SWalter Erquinigo Expected<json::Value> NativeProcessLinux::TraceGetState(StringRef type) {
20380b697561SWalter Erquinigo   if (type == "intel-pt")
20390b697561SWalter Erquinigo     return m_intel_pt_manager.GetState();
20400b697561SWalter Erquinigo   return NativeProcessProtocol::TraceGetState(type);
204199e37695SRavitheja Addepally }
204299e37695SRavitheja Addepally 
20430b697561SWalter Erquinigo Expected<std::vector<uint8_t>> NativeProcessLinux::TraceGetBinaryData(
20440b697561SWalter Erquinigo     const TraceGetBinaryDataRequest &request) {
20450b697561SWalter Erquinigo   if (request.type == "intel-pt")
20460b697561SWalter Erquinigo     return m_intel_pt_manager.GetBinaryData(request);
20470b697561SWalter Erquinigo   return NativeProcessProtocol::TraceGetBinaryData(request);
204899e37695SRavitheja Addepally }
2049