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"
41c34698a8SPavel Labath #include "lldb/Utility/LLDBLog.h"
42d821c997SPavel Labath #include "lldb/Utility/State.h"
4397206d57SZachary Turner #include "lldb/Utility/Status.h"
44f805e190SPavel Labath #include "lldb/Utility/StringExtractor.h"
452c4226f8SPavel Labath #include "llvm/ADT/ScopeExit.h"
4610c41f37SPavel Labath #include "llvm/Support/Errno.h"
4710c41f37SPavel Labath #include "llvm/Support/FileSystem.h"
4810c41f37SPavel Labath #include "llvm/Support/Threading.h"
49af245d11STodd Fiala 
50d858487eSTamas Berghammer #include <linux/unistd.h>
51d858487eSTamas Berghammer #include <sys/socket.h>
52df7c6995SPavel Labath #include <sys/syscall.h>
53d858487eSTamas Berghammer #include <sys/types.h>
54d858487eSTamas Berghammer #include <sys/user.h>
55d858487eSTamas Berghammer #include <sys/wait.h>
56d858487eSTamas Berghammer 
578d58fbd0SDavid Spickett #ifdef __aarch64__
588d58fbd0SDavid Spickett #include <asm/hwcap.h>
598d58fbd0SDavid Spickett #include <sys/auxv.h>
608d58fbd0SDavid Spickett #endif
618d58fbd0SDavid Spickett 
62af245d11STodd Fiala // Support hardware breakpoints in case it has not been defined
63af245d11STodd Fiala #ifndef TRAP_HWBKPT
64af245d11STodd Fiala #define TRAP_HWBKPT 4
65af245d11STodd Fiala #endif
66af245d11STodd Fiala 
678d58fbd0SDavid Spickett #ifndef HWCAP2_MTE
688d58fbd0SDavid Spickett #define HWCAP2_MTE (1 << 18)
698d58fbd0SDavid Spickett #endif
708d58fbd0SDavid Spickett 
717cb18bf5STamas Berghammer using namespace lldb;
727cb18bf5STamas Berghammer using namespace lldb_private;
73db264a6dSTamas Berghammer using namespace lldb_private::process_linux;
747cb18bf5STamas Berghammer using namespace llvm;
757cb18bf5STamas Berghammer 
76af245d11STodd Fiala // Private bits we only need internally.
77df7c6995SPavel Labath 
78b9c1b51eSKate Stone static bool ProcessVmReadvSupported() {
79df7c6995SPavel Labath   static bool is_supported;
80c5f28e2aSKamil Rytarowski   static llvm::once_flag flag;
81df7c6995SPavel Labath 
82c5f28e2aSKamil Rytarowski   llvm::call_once(flag, [] {
834fa1ad05SPavel Labath     Log *log = GetLog(POSIXLog::Process);
84df7c6995SPavel Labath 
85df7c6995SPavel Labath     uint32_t source = 0x47424742;
86df7c6995SPavel Labath     uint32_t dest = 0;
87df7c6995SPavel Labath 
88df7c6995SPavel Labath     struct iovec local, remote;
89df7c6995SPavel Labath     remote.iov_base = &source;
90df7c6995SPavel Labath     local.iov_base = &dest;
91df7c6995SPavel Labath     remote.iov_len = local.iov_len = sizeof source;
92df7c6995SPavel Labath 
93b9c1b51eSKate Stone     // We shall try if cross-process-memory reads work by attempting to read a
94b9c1b51eSKate Stone     // value from our own process.
95df7c6995SPavel Labath     ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
96df7c6995SPavel Labath     is_supported = (res == sizeof(source) && source == dest);
97df7c6995SPavel Labath     if (is_supported)
98a6321a8eSPavel Labath       LLDB_LOG(log,
99a6321a8eSPavel Labath                "Detected kernel support for process_vm_readv syscall. "
100a6321a8eSPavel Labath                "Fast memory reads enabled.");
101df7c6995SPavel Labath     else
102a6321a8eSPavel Labath       LLDB_LOG(log,
103a6321a8eSPavel Labath                "syscall process_vm_readv failed (error: {0}). Fast memory "
104a6321a8eSPavel Labath                "reads disabled.",
10510c41f37SPavel Labath                llvm::sys::StrError());
106df7c6995SPavel Labath   });
107df7c6995SPavel Labath 
108df7c6995SPavel Labath   return is_supported;
109df7c6995SPavel Labath }
110df7c6995SPavel Labath 
11193c1b3caSPavel Labath static void MaybeLogLaunchInfo(const ProcessLaunchInfo &info) {
1124fa1ad05SPavel Labath   Log *log = GetLog(POSIXLog::Process);
1134abe5d69SPavel Labath   if (!log)
1144abe5d69SPavel Labath     return;
1154abe5d69SPavel Labath 
1164abe5d69SPavel Labath   if (const FileAction *action = info.GetFileActionForFD(STDIN_FILENO))
117a6321a8eSPavel Labath     LLDB_LOG(log, "setting STDIN to '{0}'", action->GetFileSpec());
1184abe5d69SPavel Labath   else
119a6321a8eSPavel Labath     LLDB_LOG(log, "leaving STDIN as is");
1204abe5d69SPavel Labath 
1214abe5d69SPavel Labath   if (const FileAction *action = info.GetFileActionForFD(STDOUT_FILENO))
122a6321a8eSPavel Labath     LLDB_LOG(log, "setting STDOUT to '{0}'", action->GetFileSpec());
1234abe5d69SPavel Labath   else
124a6321a8eSPavel Labath     LLDB_LOG(log, "leaving STDOUT as is");
1254abe5d69SPavel Labath 
1264abe5d69SPavel Labath   if (const FileAction *action = info.GetFileActionForFD(STDERR_FILENO))
127a6321a8eSPavel Labath     LLDB_LOG(log, "setting STDERR to '{0}'", action->GetFileSpec());
1284abe5d69SPavel Labath   else
129a6321a8eSPavel Labath     LLDB_LOG(log, "leaving STDERR as is");
1304abe5d69SPavel Labath 
1314abe5d69SPavel Labath   int i = 0;
132b9c1b51eSKate Stone   for (const char **args = info.GetArguments().GetConstArgumentVector(); *args;
133b9c1b51eSKate Stone        ++args, ++i)
134a6321a8eSPavel Labath     LLDB_LOG(log, "arg {0}: '{1}'", i, *args);
1354abe5d69SPavel Labath }
1364abe5d69SPavel Labath 
13793c1b3caSPavel Labath static void DisplayBytes(StreamString &s, void *bytes, uint32_t count) {
138af245d11STodd Fiala   uint8_t *ptr = (uint8_t *)bytes;
139af245d11STodd Fiala   const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
140b9c1b51eSKate Stone   for (uint32_t i = 0; i < loop_count; i++) {
141af245d11STodd Fiala     s.Printf("[%x]", *ptr);
142af245d11STodd Fiala     ptr++;
143af245d11STodd Fiala   }
144af245d11STodd Fiala }
145af245d11STodd Fiala 
14693c1b3caSPavel Labath static void PtraceDisplayBytes(int &req, void *data, size_t data_size) {
1474fa1ad05SPavel Labath   Log *log = GetLog(POSIXLog::Ptrace);
148a6321a8eSPavel Labath   if (!log)
149a6321a8eSPavel Labath     return;
150af245d11STodd Fiala   StreamString buf;
151af245d11STodd Fiala 
152b9c1b51eSKate Stone   switch (req) {
153b9c1b51eSKate Stone   case PTRACE_POKETEXT: {
154af245d11STodd Fiala     DisplayBytes(buf, &data, 8);
155aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_POKETEXT {0}", buf.GetData());
156af245d11STodd Fiala     break;
157af245d11STodd Fiala   }
158b9c1b51eSKate Stone   case PTRACE_POKEDATA: {
159af245d11STodd Fiala     DisplayBytes(buf, &data, 8);
160aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_POKEDATA {0}", buf.GetData());
161af245d11STodd Fiala     break;
162af245d11STodd Fiala   }
163b9c1b51eSKate Stone   case PTRACE_POKEUSER: {
164af245d11STodd Fiala     DisplayBytes(buf, &data, 8);
165aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_POKEUSER {0}", buf.GetData());
166af245d11STodd Fiala     break;
167af245d11STodd Fiala   }
168b9c1b51eSKate Stone   case PTRACE_SETREGS: {
169af245d11STodd Fiala     DisplayBytes(buf, data, data_size);
170aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_SETREGS {0}", buf.GetData());
171af245d11STodd Fiala     break;
172af245d11STodd Fiala   }
173b9c1b51eSKate Stone   case PTRACE_SETFPREGS: {
174af245d11STodd Fiala     DisplayBytes(buf, data, data_size);
175aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_SETFPREGS {0}", buf.GetData());
176af245d11STodd Fiala     break;
177af245d11STodd Fiala   }
178b9c1b51eSKate Stone   case PTRACE_SETSIGINFO: {
179af245d11STodd Fiala     DisplayBytes(buf, data, sizeof(siginfo_t));
180aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_SETSIGINFO {0}", buf.GetData());
181af245d11STodd Fiala     break;
182af245d11STodd Fiala   }
183b9c1b51eSKate Stone   case PTRACE_SETREGSET: {
18411edb4eeSPavel Labath     // Extract iov_base from data, which is a pointer to the struct iovec
185af245d11STodd Fiala     DisplayBytes(buf, *(void **)data, data_size);
186aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_SETREGSET {0}", buf.GetData());
187af245d11STodd Fiala     break;
188af245d11STodd Fiala   }
189b9c1b51eSKate Stone   default: {}
190af245d11STodd Fiala   }
191af245d11STodd Fiala }
192af245d11STodd Fiala 
19319cbe96aSPavel Labath static constexpr unsigned k_ptrace_word_size = sizeof(void *);
194b9c1b51eSKate Stone static_assert(sizeof(long) >= k_ptrace_word_size,
195b9c1b51eSKate Stone               "Size of long must be larger than ptrace word size");
1961107b5a5SPavel Labath 
197bd7cbc5aSPavel Labath // Simple helper function to ensure flags are enabled on the given file
198bd7cbc5aSPavel Labath // descriptor.
19997206d57SZachary Turner static Status EnsureFDFlags(int fd, int flags) {
20097206d57SZachary Turner   Status error;
201bd7cbc5aSPavel Labath 
202bd7cbc5aSPavel Labath   int status = fcntl(fd, F_GETFL);
203b9c1b51eSKate Stone   if (status == -1) {
204bd7cbc5aSPavel Labath     error.SetErrorToErrno();
205bd7cbc5aSPavel Labath     return error;
206bd7cbc5aSPavel Labath   }
207bd7cbc5aSPavel Labath 
208b9c1b51eSKate Stone   if (fcntl(fd, F_SETFL, status | flags) == -1) {
209bd7cbc5aSPavel Labath     error.SetErrorToErrno();
210bd7cbc5aSPavel Labath     return error;
211bd7cbc5aSPavel Labath   }
212bd7cbc5aSPavel Labath 
213bd7cbc5aSPavel Labath   return error;
214bd7cbc5aSPavel Labath }
215bd7cbc5aSPavel Labath 
216af245d11STodd Fiala // Public Static Methods
217af245d11STodd Fiala 
21882abefa4SPavel Labath llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
21996e600fcSPavel Labath NativeProcessLinux::Factory::Launch(ProcessLaunchInfo &launch_info,
22096e600fcSPavel Labath                                     NativeDelegate &native_delegate,
22196e600fcSPavel Labath                                     MainLoop &mainloop) const {
2224fa1ad05SPavel Labath   Log *log = GetLog(POSIXLog::Process);
223af245d11STodd Fiala 
22496e600fcSPavel Labath   MaybeLogLaunchInfo(launch_info);
225af245d11STodd Fiala 
22696e600fcSPavel Labath   Status status;
22796e600fcSPavel Labath   ::pid_t pid = ProcessLauncherPosixFork()
22896e600fcSPavel Labath                     .LaunchProcess(launch_info, status)
22996e600fcSPavel Labath                     .GetProcessId();
23096e600fcSPavel Labath   LLDB_LOG(log, "pid = {0:x}", pid);
23196e600fcSPavel Labath   if (status.Fail()) {
23296e600fcSPavel Labath     LLDB_LOG(log, "failed to launch process: {0}", status);
23396e600fcSPavel Labath     return status.ToError();
234af245d11STodd Fiala   }
235af245d11STodd Fiala 
23696e600fcSPavel Labath   // Wait for the child process to trap on its call to execve.
23796e600fcSPavel Labath   int wstatus;
23896e600fcSPavel Labath   ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0);
23996e600fcSPavel Labath   assert(wpid == pid);
24096e600fcSPavel Labath   (void)wpid;
24196e600fcSPavel Labath   if (!WIFSTOPPED(wstatus)) {
24296e600fcSPavel Labath     LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}",
24396e600fcSPavel Labath              WaitStatus::Decode(wstatus));
24496e600fcSPavel Labath     return llvm::make_error<StringError>("Could not sync with inferior process",
24596e600fcSPavel Labath                                          llvm::inconvertibleErrorCode());
24696e600fcSPavel Labath   }
24796e600fcSPavel Labath   LLDB_LOG(log, "inferior started, now in stopped state");
248af245d11STodd Fiala 
24936e82208SPavel Labath   ProcessInstanceInfo Info;
25036e82208SPavel Labath   if (!Host::GetProcessInfo(pid, Info)) {
25136e82208SPavel Labath     return llvm::make_error<StringError>("Cannot get process architecture",
25236e82208SPavel Labath                                          llvm::inconvertibleErrorCode());
25336e82208SPavel Labath   }
25496e600fcSPavel Labath 
25596e600fcSPavel Labath   // Set the architecture to the exe architecture.
25696e600fcSPavel Labath   LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid,
25736e82208SPavel Labath            Info.GetArchitecture().GetArchitectureName());
25896e600fcSPavel Labath 
25996e600fcSPavel Labath   status = SetDefaultPtraceOpts(pid);
26096e600fcSPavel Labath   if (status.Fail()) {
26196e600fcSPavel Labath     LLDB_LOG(log, "failed to set default ptrace options: {0}", status);
26296e600fcSPavel Labath     return status.ToError();
263af245d11STodd Fiala   }
264af245d11STodd Fiala 
26582abefa4SPavel Labath   return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
26664ec505dSJonas Devlieghere       pid, launch_info.GetPTY().ReleasePrimaryFileDescriptor(), native_delegate,
26736e82208SPavel Labath       Info.GetArchitecture(), mainloop, {pid}));
268af245d11STodd Fiala }
269af245d11STodd Fiala 
27082abefa4SPavel Labath llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
27182abefa4SPavel Labath NativeProcessLinux::Factory::Attach(
272b9c1b51eSKate Stone     lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
27396e600fcSPavel Labath     MainLoop &mainloop) const {
2744fa1ad05SPavel Labath   Log *log = GetLog(POSIXLog::Process);
275a6321a8eSPavel Labath   LLDB_LOG(log, "pid = {0:x}", pid);
276af245d11STodd Fiala 
277af245d11STodd Fiala   // Retrieve the architecture for the running process.
27836e82208SPavel Labath   ProcessInstanceInfo Info;
27936e82208SPavel Labath   if (!Host::GetProcessInfo(pid, Info)) {
28036e82208SPavel Labath     return llvm::make_error<StringError>("Cannot get process architecture",
28136e82208SPavel Labath                                          llvm::inconvertibleErrorCode());
28236e82208SPavel Labath   }
283af245d11STodd Fiala 
28496e600fcSPavel Labath   auto tids_or = NativeProcessLinux::Attach(pid);
28596e600fcSPavel Labath   if (!tids_or)
28696e600fcSPavel Labath     return tids_or.takeError();
287af245d11STodd Fiala 
28882abefa4SPavel Labath   return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
28936e82208SPavel Labath       pid, -1, native_delegate, Info.GetArchitecture(), mainloop, *tids_or));
290af245d11STodd Fiala }
291af245d11STodd Fiala 
292fd0af0cfSMichał Górny NativeProcessLinux::Extension
293fd0af0cfSMichał Górny NativeProcessLinux::Factory::GetSupportedExtensions() const {
2948d58fbd0SDavid Spickett   NativeProcessLinux::Extension supported =
2958d58fbd0SDavid Spickett       Extension::multiprocess | Extension::fork | Extension::vfork |
2961e74e5e9SMichał Górny       Extension::pass_signals | Extension::auxv | Extension::libraries_svr4 |
2971e74e5e9SMichał Górny       Extension::siginfo_read;
2988d58fbd0SDavid Spickett 
2998d58fbd0SDavid Spickett #ifdef __aarch64__
3008d58fbd0SDavid Spickett   // At this point we do not have a process so read auxv directly.
3018d58fbd0SDavid Spickett   if ((getauxval(AT_HWCAP2) & HWCAP2_MTE))
3028d58fbd0SDavid Spickett     supported |= Extension::memory_tagging;
3038d58fbd0SDavid Spickett #endif
3048d58fbd0SDavid Spickett 
3058d58fbd0SDavid Spickett   return supported;
306fd0af0cfSMichał Górny }
307fd0af0cfSMichał Górny 
308af245d11STodd Fiala // Public Instance Methods
309af245d11STodd Fiala 
31096e600fcSPavel Labath NativeProcessLinux::NativeProcessLinux(::pid_t pid, int terminal_fd,
31196e600fcSPavel Labath                                        NativeDelegate &delegate,
31282abefa4SPavel Labath                                        const ArchSpec &arch, MainLoop &mainloop,
31382abefa4SPavel Labath                                        llvm::ArrayRef<::pid_t> tids)
3140b697561SWalter Erquinigo     : NativeProcessELF(pid, terminal_fd, delegate), m_arch(arch),
315*22077627SJakob Johnson       m_main_loop(mainloop), m_intel_pt_collector(pid) {
316b9c1b51eSKate Stone   if (m_terminal_fd != -1) {
31796e600fcSPavel Labath     Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
31896e600fcSPavel Labath     assert(status.Success());
3195ad891f7SPavel Labath   }
320af245d11STodd Fiala 
32196e600fcSPavel Labath   Status status;
32296e600fcSPavel Labath   m_sigchld_handle = mainloop.RegisterSignal(
32396e600fcSPavel Labath       SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status);
32496e600fcSPavel Labath   assert(m_sigchld_handle && status.Success());
32596e600fcSPavel Labath 
32696e600fcSPavel Labath   for (const auto &tid : tids) {
3270b697561SWalter Erquinigo     NativeThreadLinux &thread = AddThread(tid, /*resume*/ false);
328a5be48b3SPavel Labath     ThreadWasCreated(thread);
329af245d11STodd Fiala   }
330af245d11STodd Fiala 
33196e600fcSPavel Labath   // Let our process instance know the thread has stopped.
33296e600fcSPavel Labath   SetCurrentThreadID(tids[0]);
33396e600fcSPavel Labath   SetState(StateType::eStateStopped, false);
33496e600fcSPavel Labath 
33596e600fcSPavel Labath   // Proccess any signals we received before installing our handler
33696e600fcSPavel Labath   SigchldHandler();
33796e600fcSPavel Labath }
33896e600fcSPavel Labath 
33996e600fcSPavel Labath llvm::Expected<std::vector<::pid_t>> NativeProcessLinux::Attach(::pid_t pid) {
3404fa1ad05SPavel Labath   Log *log = GetLog(POSIXLog::Process);
341af245d11STodd Fiala 
34296e600fcSPavel Labath   Status status;
343b9c1b51eSKate Stone   // Use a map to keep track of the threads which we have attached/need to
344b9c1b51eSKate Stone   // attach.
345af245d11STodd Fiala   Host::TidMap tids_to_attach;
346b9c1b51eSKate Stone   while (Host::FindProcessThreads(pid, tids_to_attach)) {
347af245d11STodd Fiala     for (Host::TidMap::iterator it = tids_to_attach.begin();
348b9c1b51eSKate Stone          it != tids_to_attach.end();) {
349b9c1b51eSKate Stone       if (it->second == false) {
350af245d11STodd Fiala         lldb::tid_t tid = it->first;
351af245d11STodd Fiala 
352af245d11STodd Fiala         // Attach to the requested process.
353af245d11STodd Fiala         // An attach will cause the thread to stop with a SIGSTOP.
35496e600fcSPavel Labath         if ((status = PtraceWrapper(PTRACE_ATTACH, tid)).Fail()) {
35505097246SAdrian Prantl           // No such thread. The thread may have exited. More error handling
35605097246SAdrian Prantl           // may be needed.
35796e600fcSPavel Labath           if (status.GetError() == ESRCH) {
358af245d11STodd Fiala             it = tids_to_attach.erase(it);
359af245d11STodd Fiala             continue;
36096e600fcSPavel Labath           }
36196e600fcSPavel Labath           return status.ToError();
362af245d11STodd Fiala         }
363af245d11STodd Fiala 
36496e600fcSPavel Labath         int wpid =
36596e600fcSPavel Labath             llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, nullptr, __WALL);
36605097246SAdrian Prantl         // Need to use __WALL otherwise we receive an error with errno=ECHLD At
36705097246SAdrian Prantl         // this point we should have a thread stopped if waitpid succeeds.
36896e600fcSPavel Labath         if (wpid < 0) {
36905097246SAdrian Prantl           // No such thread. The thread may have exited. More error handling
37005097246SAdrian Prantl           // may be needed.
371b9c1b51eSKate Stone           if (errno == ESRCH) {
372af245d11STodd Fiala             it = tids_to_attach.erase(it);
373af245d11STodd Fiala             continue;
374af245d11STodd Fiala           }
37596e600fcSPavel Labath           return llvm::errorCodeToError(
37696e600fcSPavel Labath               std::error_code(errno, std::generic_category()));
377af245d11STodd Fiala         }
378af245d11STodd Fiala 
37996e600fcSPavel Labath         if ((status = SetDefaultPtraceOpts(tid)).Fail())
38096e600fcSPavel Labath           return status.ToError();
381af245d11STodd Fiala 
382a6321a8eSPavel Labath         LLDB_LOG(log, "adding tid = {0}", tid);
383af245d11STodd Fiala         it->second = true;
384af245d11STodd Fiala       }
385af245d11STodd Fiala 
386af245d11STodd Fiala       // move the loop forward
387af245d11STodd Fiala       ++it;
388af245d11STodd Fiala     }
389af245d11STodd Fiala   }
390af245d11STodd Fiala 
39196e600fcSPavel Labath   size_t tid_count = tids_to_attach.size();
39296e600fcSPavel Labath   if (tid_count == 0)
39396e600fcSPavel Labath     return llvm::make_error<StringError>("No such process",
39496e600fcSPavel Labath                                          llvm::inconvertibleErrorCode());
395af245d11STodd Fiala 
39696e600fcSPavel Labath   std::vector<::pid_t> tids;
39796e600fcSPavel Labath   tids.reserve(tid_count);
39896e600fcSPavel Labath   for (const auto &p : tids_to_attach)
39996e600fcSPavel Labath     tids.push_back(p.first);
40096e600fcSPavel Labath   return std::move(tids);
401af245d11STodd Fiala }
402af245d11STodd Fiala 
40397206d57SZachary Turner Status NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid) {
404af245d11STodd Fiala   long ptrace_opts = 0;
405af245d11STodd Fiala 
406af245d11STodd Fiala   // Have the child raise an event on exit.  This is used to keep the child in
407af245d11STodd Fiala   // limbo until it is destroyed.
408af245d11STodd Fiala   ptrace_opts |= PTRACE_O_TRACEEXIT;
409af245d11STodd Fiala 
410af245d11STodd Fiala   // Have the tracer trace threads which spawn in the inferior process.
411af245d11STodd Fiala   ptrace_opts |= PTRACE_O_TRACECLONE;
412af245d11STodd Fiala 
41305097246SAdrian Prantl   // Have the tracer notify us before execve returns (needed to disable legacy
41405097246SAdrian Prantl   // SIGTRAP generation)
415af245d11STodd Fiala   ptrace_opts |= PTRACE_O_TRACEEXEC;
416af245d11STodd Fiala 
417c8d18cbaSMichał Górny   // Have the tracer trace forked children.
418c8d18cbaSMichał Górny   ptrace_opts |= PTRACE_O_TRACEFORK;
419c8d18cbaSMichał Górny 
420c8d18cbaSMichał Górny   // Have the tracer trace vforks.
421c8d18cbaSMichał Górny   ptrace_opts |= PTRACE_O_TRACEVFORK;
422c8d18cbaSMichał Górny 
423c8d18cbaSMichał Górny   // Have the tracer trace vfork-done in order to restore breakpoints after
424c8d18cbaSMichał Górny   // the child finishes sharing memory.
425c8d18cbaSMichał Górny   ptrace_opts |= PTRACE_O_TRACEVFORKDONE;
426c8d18cbaSMichał Górny 
4274a9babb2SPavel Labath   return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void *)ptrace_opts);
428af245d11STodd Fiala }
429af245d11STodd Fiala 
4301107b5a5SPavel Labath // Handles all waitpid events from the inferior process.
431ca271f4eSPavel Labath void NativeProcessLinux::MonitorCallback(NativeThreadLinux &thread,
432ca271f4eSPavel Labath                                          WaitStatus status) {
433a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Process);
434af245d11STodd Fiala 
435b9c1b51eSKate Stone   // Certain activities differ based on whether the pid is the tid of the main
436b9c1b51eSKate Stone   // thread.
437ca271f4eSPavel Labath   const bool is_main_thread = (thread.GetID() == GetID());
438af245d11STodd Fiala 
439af245d11STodd Fiala   // Handle when the thread exits.
440fdd741ddSPavel Labath   if (status.type == WaitStatus::Exit || status.type == WaitStatus::Signal) {
441d8b3c1a1SPavel Labath     LLDB_LOG(log,
4429303afb3SPavel Labath              "got exit status({0}) , tid = {1} ({2} main thread), process "
443d8b3c1a1SPavel Labath              "state = {3}",
444ca271f4eSPavel Labath              status, thread.GetID(), is_main_thread ? "is" : "is not",
445ca271f4eSPavel Labath              GetState());
446af245d11STodd Fiala 
447af245d11STodd Fiala     // This is a thread that exited.  Ensure we're not tracking it anymore.
448ca271f4eSPavel Labath     StopTrackingThread(thread);
449af245d11STodd Fiala 
450b9c1b51eSKate Stone     if (is_main_thread) {
451af245d11STodd Fiala       // The main thread exited.  We're done monitoring.  Report to delegate.
4523508fc8cSPavel Labath       SetExitStatus(status, true);
453af245d11STodd Fiala 
454af245d11STodd Fiala       // Notify delegate that our process has exited.
4551107b5a5SPavel Labath       SetState(StateType::eStateExited, true);
456af245d11STodd Fiala     }
4571107b5a5SPavel Labath     return;
458af245d11STodd Fiala   }
459af245d11STodd Fiala 
460af245d11STodd Fiala   siginfo_t info;
461ca271f4eSPavel Labath   const auto info_err = GetSignalInfo(thread.GetID(), &info);
462b9cc0c75SPavel Labath 
463b9cc0c75SPavel Labath   // Get details on the signal raised.
464b9c1b51eSKate Stone   if (info_err.Success()) {
465fa03ad2eSChaoren Lin     // We have retrieved the signal info.  Dispatch appropriately.
466fa03ad2eSChaoren Lin     if (info.si_signo == SIGTRAP)
467ca271f4eSPavel Labath       MonitorSIGTRAP(info, thread);
468fa03ad2eSChaoren Lin     else
469ca271f4eSPavel Labath       MonitorSignal(info, thread);
470b9c1b51eSKate Stone   } else {
471b9c1b51eSKate Stone     if (info_err.GetError() == EINVAL) {
47205097246SAdrian Prantl       // This is a group stop reception for this tid. We can reach here if we
47305097246SAdrian Prantl       // reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the tracee,
47405097246SAdrian Prantl       // triggering the group-stop mechanism. Normally receiving these would
47505097246SAdrian Prantl       // stop the process, pending a SIGCONT. Simulating this state in a
47605097246SAdrian Prantl       // debugger is hard and is generally not needed (one use case is
47705097246SAdrian Prantl       // debugging background task being managed by a shell). For general use,
47805097246SAdrian Prantl       // it is sufficient to stop the process in a signal-delivery stop which
47905097246SAdrian Prantl       // happens before the group stop. This done by MonitorSignal and works
48005097246SAdrian Prantl       // correctly for all signals.
481a6321a8eSPavel Labath       LLDB_LOG(log,
482a6321a8eSPavel Labath                "received a group stop for pid {0} tid {1}. Transparent "
483a6321a8eSPavel Labath                "handling of group stops not supported, resuming the "
484a6321a8eSPavel Labath                "thread.",
485ca271f4eSPavel Labath                GetID(), thread.GetID());
486ca271f4eSPavel Labath       ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
487b9c1b51eSKate Stone     } else {
488af245d11STodd Fiala       // ptrace(GETSIGINFO) failed (but not due to group-stop).
489af245d11STodd Fiala 
490df4ad362SPavel Labath       // A return value of ESRCH means the thread/process has died in the mean
491df4ad362SPavel Labath       // time. This can (e.g.) happen when another thread does an exit_group(2)
492df4ad362SPavel Labath       // or the entire process get SIGKILLed.
493df4ad362SPavel Labath       // We can't do anything with this thread anymore, but we keep it around
494df4ad362SPavel Labath       // until we get the WIFEXITED event.
495af245d11STodd Fiala 
496a6321a8eSPavel Labath       LLDB_LOG(log,
497df4ad362SPavel Labath                "GetSignalInfo({0}) failed: {1}, status = {2}, main_thread = "
498df4ad362SPavel Labath                "{3}. Expecting WIFEXITED soon.",
499df4ad362SPavel Labath                thread.GetID(), info_err, status, is_main_thread);
500af245d11STodd Fiala     }
501af245d11STodd Fiala   }
502af245d11STodd Fiala }
503af245d11STodd Fiala 
504c8d18cbaSMichał Górny void NativeProcessLinux::WaitForCloneNotification(::pid_t pid) {
5054fa1ad05SPavel Labath   Log *log = GetLog(POSIXLog::Process);
506426bdf88SPavel Labath 
507c8d18cbaSMichał Górny   // The PID is not tracked yet, let's wait for it to appear.
508426bdf88SPavel Labath   int status = -1;
509a6321a8eSPavel Labath   LLDB_LOG(log,
510c8d18cbaSMichał Górny            "received clone event for pid {0}. pid not tracked yet, "
511c8d18cbaSMichał Górny            "waiting for it to appear...",
512c8d18cbaSMichał Górny            pid);
513c8d18cbaSMichał Górny   ::pid_t wait_pid =
514c8d18cbaSMichał Górny       llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &status, __WALL);
515426bdf88SPavel Labath 
516ca271f4eSPavel Labath   // It's theoretically possible to get other events if the entire process was
517ca271f4eSPavel Labath   // SIGKILLed before we got a chance to check this. In that case, we'll just
518ca271f4eSPavel Labath   // clean everything up when we get the process exit event.
519ca271f4eSPavel Labath 
520ca271f4eSPavel Labath   LLDB_LOG(log,
521ca271f4eSPavel Labath            "waitpid({0}, &status, __WALL) => {1} (errno: {2}, status = {3})",
522ca271f4eSPavel Labath            pid, wait_pid, errno, WaitStatus::Decode(status));
523426bdf88SPavel Labath }
524426bdf88SPavel Labath 
525b9c1b51eSKate Stone void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info,
526b9c1b51eSKate Stone                                         NativeThreadLinux &thread) {
5274fa1ad05SPavel Labath   Log *log = GetLog(POSIXLog::Process);
528b9cc0c75SPavel Labath   const bool is_main_thread = (thread.GetID() == GetID());
529af245d11STodd Fiala 
530b9cc0c75SPavel Labath   assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
531af245d11STodd Fiala 
532b9c1b51eSKate Stone   switch (info.si_code) {
533c8d18cbaSMichał Górny   case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
534c8d18cbaSMichał Górny   case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
535b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): {
536c8d18cbaSMichał Górny     // This can either mean a new thread or a new process spawned via
537c8d18cbaSMichał Górny     // clone(2) without SIGCHLD or CLONE_VFORK flag.  Note that clone(2)
538c8d18cbaSMichał Górny     // can also cause PTRACE_EVENT_FORK and PTRACE_EVENT_VFORK if one
539c8d18cbaSMichał Górny     // of these flags are passed.
540af245d11STodd Fiala 
541af245d11STodd Fiala     unsigned long event_message = 0;
542b9c1b51eSKate Stone     if (GetEventMessage(thread.GetID(), &event_message).Fail()) {
543a6321a8eSPavel Labath       LLDB_LOG(log,
544c8d18cbaSMichał Górny                "pid {0} received clone() event but GetEventMessage failed "
545c8d18cbaSMichał Górny                "so we don't know the new pid/tid",
546a6321a8eSPavel Labath                thread.GetID());
547121cff78SPavel Labath       ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
548c8d18cbaSMichał Górny     } else {
549ca271f4eSPavel Labath       MonitorClone(thread, event_message, info.si_code >> 8);
550c8d18cbaSMichał Górny     }
551c8d18cbaSMichał Górny 
552af245d11STodd Fiala     break;
553af245d11STodd Fiala   }
554af245d11STodd Fiala 
555b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): {
556a6321a8eSPavel Labath     LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP);
557a9882ceeSTodd Fiala 
5581dbc6c9cSPavel Labath     // Exec clears any pending notifications.
5590e1d729bSPavel Labath     m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
560fa03ad2eSChaoren Lin 
561b9c1b51eSKate Stone     // Remove all but the main thread here.  Linux fork creates a new process
562b9c1b51eSKate Stone     // which only copies the main thread.
563a6321a8eSPavel Labath     LLDB_LOG(log, "exec received, stop tracking all but main thread");
564a9882ceeSTodd Fiala 
565ee74c9e5SPavel Labath     llvm::erase_if(m_threads, [&](std::unique_ptr<NativeThreadProtocol> &t) {
566ee74c9e5SPavel Labath       return t->GetID() != GetID();
567ee74c9e5SPavel Labath     });
568a5be48b3SPavel Labath     assert(m_threads.size() == 1);
569a5be48b3SPavel Labath     auto *main_thread = static_cast<NativeThreadLinux *>(m_threads[0].get());
570a9882ceeSTodd Fiala 
571a5be48b3SPavel Labath     SetCurrentThreadID(main_thread->GetID());
572a5be48b3SPavel Labath     main_thread->SetStoppedByExec();
573a9882ceeSTodd Fiala 
574fa03ad2eSChaoren Lin     // Tell coordinator about about the "new" (since exec) stopped main thread.
575a5be48b3SPavel Labath     ThreadWasCreated(*main_thread);
576fa03ad2eSChaoren Lin 
577a9882ceeSTodd Fiala     // Let our delegate know we have just exec'd.
578a9882ceeSTodd Fiala     NotifyDidExec();
579a9882ceeSTodd Fiala 
580fa03ad2eSChaoren Lin     // Let the process know we're stopped.
581a5be48b3SPavel Labath     StopRunningThreads(main_thread->GetID());
582a9882ceeSTodd Fiala 
583af245d11STodd Fiala     break;
584a9882ceeSTodd Fiala   }
585af245d11STodd Fiala 
586b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): {
58705097246SAdrian Prantl     // The inferior process or one of its threads is about to exit. We don't
58805097246SAdrian Prantl     // want to do anything with the thread so we just resume it. In case we
58905097246SAdrian Prantl     // want to implement "break on thread exit" functionality, we would need to
59005097246SAdrian Prantl     // stop here.
591fa03ad2eSChaoren Lin 
592af245d11STodd Fiala     unsigned long data = 0;
593b9cc0c75SPavel Labath     if (GetEventMessage(thread.GetID(), &data).Fail())
594af245d11STodd Fiala       data = -1;
595af245d11STodd Fiala 
596a6321a8eSPavel Labath     LLDB_LOG(log,
597a6321a8eSPavel Labath              "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
598a6321a8eSPavel Labath              "WIFSIGNALED={2}, pid = {3}, main_thread = {4}",
599a6321a8eSPavel Labath              data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(),
600a6321a8eSPavel Labath              is_main_thread);
601af245d11STodd Fiala 
60275f47c3aSTodd Fiala 
60386852d36SPavel Labath     StateType state = thread.GetState();
604b9c1b51eSKate Stone     if (!StateIsRunningState(state)) {
605b9c1b51eSKate Stone       // Due to a kernel bug, we may sometimes get this stop after the inferior
606d8b3c1a1SPavel Labath       // gets a SIGKILL. This confuses our state tracking logic in
607d8b3c1a1SPavel Labath       // ResumeThread(), since normally, we should not be receiving any ptrace
60805097246SAdrian Prantl       // events while the inferior is stopped. This makes sure that the
60905097246SAdrian Prantl       // inferior is resumed and exits normally.
61086852d36SPavel Labath       state = eStateRunning;
61186852d36SPavel Labath     }
61286852d36SPavel Labath     ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
613af245d11STodd Fiala 
614af245d11STodd Fiala     break;
615af245d11STodd Fiala   }
616af245d11STodd Fiala 
617c8d18cbaSMichał Górny   case (SIGTRAP | (PTRACE_EVENT_VFORK_DONE << 8)): {
618fd0af0cfSMichał Górny     if (bool(m_enabled_extensions & Extension::vfork)) {
619fd0af0cfSMichał Górny       thread.SetStoppedByVForkDone();
620fd0af0cfSMichał Górny       StopRunningThreads(thread.GetID());
621fd0af0cfSMichał Górny     }
622fd0af0cfSMichał Górny     else
623c8d18cbaSMichał Górny       ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
624c8d18cbaSMichał Górny     break;
625c8d18cbaSMichał Górny   }
626c8d18cbaSMichał Górny 
627af245d11STodd Fiala   case 0:
628c16f5dcaSChaoren Lin   case TRAP_TRACE:  // We receive this on single stepping.
629c16f5dcaSChaoren Lin   case TRAP_HWBKPT: // We receive this on watchpoint hit
63086fd8e45SChaoren Lin   {
631c16f5dcaSChaoren Lin     // If a watchpoint was hit, report it
632c16f5dcaSChaoren Lin     uint32_t wp_index;
633d37349f3SPavel Labath     Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
634b9c1b51eSKate Stone         wp_index, (uintptr_t)info.si_addr);
635a6321a8eSPavel Labath     if (error.Fail())
636a6321a8eSPavel Labath       LLDB_LOG(log,
637a6321a8eSPavel Labath                "received error while checking for watchpoint hits, pid = "
638a6321a8eSPavel Labath                "{0}, error = {1}",
639a6321a8eSPavel Labath                thread.GetID(), error);
640b9c1b51eSKate Stone     if (wp_index != LLDB_INVALID_INDEX32) {
641b9cc0c75SPavel Labath       MonitorWatchpoint(thread, wp_index);
642c16f5dcaSChaoren Lin       break;
643c16f5dcaSChaoren Lin     }
644b9cc0c75SPavel Labath 
645d5ffbad2SOmair Javaid     // If a breakpoint was hit, report it
646d5ffbad2SOmair Javaid     uint32_t bp_index;
647d37349f3SPavel Labath     error = thread.GetRegisterContext().GetHardwareBreakHitIndex(
648d5ffbad2SOmair Javaid         bp_index, (uintptr_t)info.si_addr);
649d5ffbad2SOmair Javaid     if (error.Fail())
650d5ffbad2SOmair Javaid       LLDB_LOG(log, "received error while checking for hardware "
651d5ffbad2SOmair Javaid                     "breakpoint hits, pid = {0}, error = {1}",
652d5ffbad2SOmair Javaid                thread.GetID(), error);
653d5ffbad2SOmair Javaid     if (bp_index != LLDB_INVALID_INDEX32) {
654d5ffbad2SOmair Javaid       MonitorBreakpoint(thread);
655d5ffbad2SOmair Javaid       break;
656d5ffbad2SOmair Javaid     }
657d5ffbad2SOmair Javaid 
658be379e15STamas Berghammer     // Otherwise, report step over
659be379e15STamas Berghammer     MonitorTrace(thread);
660af245d11STodd Fiala     break;
661b9cc0c75SPavel Labath   }
662af245d11STodd Fiala 
663af245d11STodd Fiala   case SI_KERNEL:
66435799963SMohit K. Bhakkad #if defined __mips__
66505097246SAdrian Prantl     // For mips there is no special signal for watchpoint So we check for
66605097246SAdrian Prantl     // watchpoint in kernel trap
66735799963SMohit K. Bhakkad     {
66835799963SMohit K. Bhakkad       // If a watchpoint was hit, report it
66935799963SMohit K. Bhakkad       uint32_t wp_index;
670d37349f3SPavel Labath       Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
671b9c1b51eSKate Stone           wp_index, LLDB_INVALID_ADDRESS);
672a6321a8eSPavel Labath       if (error.Fail())
673a6321a8eSPavel Labath         LLDB_LOG(log,
674a6321a8eSPavel Labath                  "received error while checking for watchpoint hits, pid = "
675a6321a8eSPavel Labath                  "{0}, error = {1}",
676a6321a8eSPavel Labath                  thread.GetID(), error);
677b9c1b51eSKate Stone       if (wp_index != LLDB_INVALID_INDEX32) {
678b9cc0c75SPavel Labath         MonitorWatchpoint(thread, wp_index);
67935799963SMohit K. Bhakkad         break;
68035799963SMohit K. Bhakkad       }
68135799963SMohit K. Bhakkad     }
68235799963SMohit K. Bhakkad // NO BREAK
68335799963SMohit K. Bhakkad #endif
684af245d11STodd Fiala   case TRAP_BRKPT:
685b9cc0c75SPavel Labath     MonitorBreakpoint(thread);
686af245d11STodd Fiala     break;
687af245d11STodd Fiala 
688af245d11STodd Fiala   case SIGTRAP:
689af245d11STodd Fiala   case (SIGTRAP | 0x80):
690a6321a8eSPavel Labath     LLDB_LOG(
691a6321a8eSPavel Labath         log,
692a6321a8eSPavel Labath         "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",
693a6321a8eSPavel Labath         info.si_code, GetID(), thread.GetID());
694fa03ad2eSChaoren Lin 
695af245d11STodd Fiala     // Ignore these signals until we know more about them.
696b9cc0c75SPavel Labath     ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
697af245d11STodd Fiala     break;
698af245d11STodd Fiala 
699af245d11STodd Fiala   default:
70021a365baSPavel Labath     LLDB_LOG(log, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}",
701a6321a8eSPavel Labath              info.si_code, GetID(), thread.GetID());
702fdd741ddSPavel Labath     MonitorSignal(info, thread);
703af245d11STodd Fiala     break;
704af245d11STodd Fiala   }
705af245d11STodd Fiala }
706af245d11STodd Fiala 
707b9c1b51eSKate Stone void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) {
7084fa1ad05SPavel Labath   Log *log = GetLog(POSIXLog::Process);
709a6321a8eSPavel Labath   LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID());
710c16f5dcaSChaoren Lin 
7110e1d729bSPavel Labath   // This thread is currently stopped.
712b9cc0c75SPavel Labath   thread.SetStoppedByTrace();
713c16f5dcaSChaoren Lin 
714b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
715c16f5dcaSChaoren Lin }
716c16f5dcaSChaoren Lin 
717b9c1b51eSKate Stone void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) {
718a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Process | LLDBLog::Breakpoints);
719a6321a8eSPavel Labath   LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID());
720c16f5dcaSChaoren Lin 
721c16f5dcaSChaoren Lin   // Mark the thread as stopped at breakpoint.
722b9cc0c75SPavel Labath   thread.SetStoppedByBreakpoint();
723aef7908fSPavel Labath   FixupBreakpointPCAsNeeded(thread);
724d8c338d4STamas Berghammer 
725b9c1b51eSKate Stone   if (m_threads_stepping_with_breakpoint.find(thread.GetID()) !=
726b9c1b51eSKate Stone       m_threads_stepping_with_breakpoint.end())
727b9cc0c75SPavel Labath     thread.SetStoppedByTrace();
728c16f5dcaSChaoren Lin 
729b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
730c16f5dcaSChaoren Lin }
731c16f5dcaSChaoren Lin 
732b9c1b51eSKate Stone void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread,
733b9c1b51eSKate Stone                                            uint32_t wp_index) {
734a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Process | LLDBLog::Watchpoints);
735a6321a8eSPavel Labath   LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}",
736a6321a8eSPavel Labath            thread.GetID(), wp_index);
737c16f5dcaSChaoren Lin 
73805097246SAdrian Prantl   // Mark the thread as stopped at watchpoint. The address is at
73905097246SAdrian Prantl   // (lldb::addr_t)info->si_addr if we need it.
740f9077782SPavel Labath   thread.SetStoppedByWatchpoint(wp_index);
741c16f5dcaSChaoren Lin 
742b9c1b51eSKate Stone   // We need to tell all other running threads before we notify the delegate
743b9c1b51eSKate Stone   // about this stop.
744f9077782SPavel Labath   StopRunningThreads(thread.GetID());
745c16f5dcaSChaoren Lin }
746c16f5dcaSChaoren Lin 
747b9c1b51eSKate Stone void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
748fdd741ddSPavel Labath                                        NativeThreadLinux &thread) {
749b9cc0c75SPavel Labath   const int signo = info.si_signo;
750b9cc0c75SPavel Labath   const bool is_from_llgs = info.si_pid == getpid();
751af245d11STodd Fiala 
7524fa1ad05SPavel Labath   Log *log = GetLog(POSIXLog::Process);
753af245d11STodd Fiala 
754af245d11STodd Fiala   // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
75505097246SAdrian Prantl   // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a kill(2)
75605097246SAdrian Prantl   // or raise(3).  Similarly for tgkill(2) on Linux.
757af245d11STodd Fiala   //
758af245d11STodd Fiala   // IOW, user generated signals never generate what we consider to be a
759af245d11STodd Fiala   // "crash".
760af245d11STodd Fiala   //
761af245d11STodd Fiala   // Similarly, ACK signals generated by this monitor.
762af245d11STodd Fiala 
763af245d11STodd Fiala   // Handle the signal.
764a6321a8eSPavel Labath   LLDB_LOG(log,
765a6321a8eSPavel Labath            "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
766a6321a8eSPavel Labath            "waitpid pid = {4})",
767a6321a8eSPavel Labath            Host::GetSignalAsCString(signo), signo, info.si_code,
768b9cc0c75SPavel Labath            thread.GetID());
76958a2f669STodd Fiala 
77058a2f669STodd Fiala   // Check for thread stop notification.
771b9c1b51eSKate Stone   if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) {
772af245d11STodd Fiala     // This is a tgkill()-based stop.
773a6321a8eSPavel Labath     LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID());
774fa03ad2eSChaoren Lin 
77505097246SAdrian Prantl     // Check that we're not already marked with a stop reason. Note this thread
77605097246SAdrian Prantl     // really shouldn't already be marked as stopped - if we were, that would
77705097246SAdrian Prantl     // imply that the kernel signaled us with the thread stopping which we
77805097246SAdrian Prantl     // handled and marked as stopped, and that, without an intervening resume,
77905097246SAdrian Prantl     // we received another stop.  It is more likely that we are missing the
78005097246SAdrian Prantl     // marking of a run state somewhere if we find that the thread was marked
78105097246SAdrian Prantl     // as stopped.
782b9cc0c75SPavel Labath     const StateType thread_state = thread.GetState();
783b9c1b51eSKate Stone     if (!StateIsStoppedState(thread_state, false)) {
784ed89c7feSPavel Labath       // An inferior thread has stopped because of a SIGSTOP we have sent it.
785b9c1b51eSKate Stone       // Generally, these are not important stops and we don't want to report
786a6321a8eSPavel Labath       // them as they are just used to stop other threads when one thread (the
787a6321a8eSPavel Labath       // one with the *real* stop reason) hits a breakpoint (watchpoint,
78805097246SAdrian Prantl       // etc...). However, in the case of an asynchronous Interrupt(), this
78905097246SAdrian Prantl       // *is* the real stop reason, so we leave the signal intact if this is
79005097246SAdrian Prantl       // the thread that was chosen as the triggering thread.
791b9c1b51eSKate Stone       if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
792b9cc0c75SPavel Labath         if (m_pending_notification_tid == thread.GetID())
793b9cc0c75SPavel Labath           thread.SetStoppedBySignal(SIGSTOP, &info);
794ed89c7feSPavel Labath         else
795b9cc0c75SPavel Labath           thread.SetStoppedWithNoReason();
796ed89c7feSPavel Labath 
797b9cc0c75SPavel Labath         SetCurrentThreadID(thread.GetID());
7980e1d729bSPavel Labath         SignalIfAllThreadsStopped();
799b9c1b51eSKate Stone       } else {
8000e1d729bSPavel Labath         // We can end up here if stop was initiated by LLGS but by this time a
8010e1d729bSPavel Labath         // thread stop has occurred - maybe initiated by another event.
80297206d57SZachary Turner         Status error = ResumeThread(thread, thread.GetState(), 0);
803a6321a8eSPavel Labath         if (error.Fail())
804a6321a8eSPavel Labath           LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(),
805a6321a8eSPavel Labath                    error);
8060e1d729bSPavel Labath       }
807b9c1b51eSKate Stone     } else {
808a6321a8eSPavel Labath       LLDB_LOG(log,
809a6321a8eSPavel Labath                "pid {0} tid {1}, thread was already marked as a stopped "
810a6321a8eSPavel Labath                "state (state={2}), leaving stop signal as is",
8118198db30SPavel Labath                GetID(), thread.GetID(), thread_state);
8120e1d729bSPavel Labath       SignalIfAllThreadsStopped();
813af245d11STodd Fiala     }
814af245d11STodd Fiala 
81558a2f669STodd Fiala     // Done handling.
816af245d11STodd Fiala     return;
817af245d11STodd Fiala   }
818af245d11STodd Fiala 
81905097246SAdrian Prantl   // Check if debugger should stop at this signal or just ignore it and resume
82005097246SAdrian Prantl   // the inferior.
82176f0f1ccSKazu Hirata   if (m_signals_to_ignore.contains(signo)) {
8224a705e7eSPavel Labath      ResumeThread(thread, thread.GetState(), signo);
8234a705e7eSPavel Labath      return;
8244a705e7eSPavel Labath   }
8254a705e7eSPavel Labath 
82686fd8e45SChaoren Lin   // This thread is stopped.
827a6321a8eSPavel Labath   LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo));
828b9cc0c75SPavel Labath   thread.SetStoppedBySignal(signo, &info);
82986fd8e45SChaoren Lin 
83086fd8e45SChaoren Lin   // Send a stop to the debugger after we get all other threads to stop.
831b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
832511e5cdcSTodd Fiala }
833af245d11STodd Fiala 
834ca271f4eSPavel Labath bool NativeProcessLinux::MonitorClone(NativeThreadLinux &parent,
835ca271f4eSPavel Labath                                       lldb::pid_t child_pid, int event) {
8364fa1ad05SPavel Labath   Log *log = GetLog(POSIXLog::Process);
837ca271f4eSPavel Labath   LLDB_LOG(log, "parent_tid={0}, child_pid={1}, event={2}", parent.GetID(),
838ca271f4eSPavel Labath            child_pid, event);
839c8d18cbaSMichał Górny 
840ca271f4eSPavel Labath   WaitForCloneNotification(child_pid);
841c8d18cbaSMichał Górny 
842ca271f4eSPavel Labath   switch (event) {
843c8d18cbaSMichał Górny   case PTRACE_EVENT_CLONE: {
844c8d18cbaSMichał Górny     // PTRACE_EVENT_CLONE can either mean a new thread or a new process.
845c8d18cbaSMichał Górny     // Try to grab the new process' PGID to figure out which one it is.
846c8d18cbaSMichał Górny     // If PGID is the same as the PID, then it's a new process.  Otherwise,
847c8d18cbaSMichał Górny     // it's a thread.
848c8d18cbaSMichał Górny     auto tgid_ret = getPIDForTID(child_pid);
849c8d18cbaSMichał Górny     if (tgid_ret != child_pid) {
850c8d18cbaSMichał Górny       // A new thread should have PGID matching our process' PID.
851c8d18cbaSMichał Górny       assert(!tgid_ret || tgid_ret.getValue() == GetID());
852c8d18cbaSMichał Górny 
853c8d18cbaSMichał Górny       NativeThreadLinux &child_thread = AddThread(child_pid, /*resume*/ true);
854c8d18cbaSMichał Górny       ThreadWasCreated(child_thread);
855c8d18cbaSMichał Górny 
856c8d18cbaSMichał Górny       // Resume the parent.
857ca271f4eSPavel Labath       ResumeThread(parent, parent.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
858c8d18cbaSMichał Górny       break;
859c8d18cbaSMichał Górny     }
860c8d18cbaSMichał Górny   }
861c8d18cbaSMichał Górny     LLVM_FALLTHROUGH;
862c8d18cbaSMichał Górny   case PTRACE_EVENT_FORK:
863c8d18cbaSMichał Górny   case PTRACE_EVENT_VFORK: {
864ca271f4eSPavel Labath     bool is_vfork = event == PTRACE_EVENT_VFORK;
865fd0af0cfSMichał Górny     std::unique_ptr<NativeProcessLinux> child_process{new NativeProcessLinux(
866fd0af0cfSMichał Górny         static_cast<::pid_t>(child_pid), m_terminal_fd, m_delegate, m_arch,
867fd0af0cfSMichał Górny         m_main_loop, {static_cast<::pid_t>(child_pid)})};
868fd0af0cfSMichał Górny     if (!is_vfork)
869fd0af0cfSMichał Górny       child_process->m_software_breakpoints = m_software_breakpoints;
870fd0af0cfSMichał Górny 
871fd0af0cfSMichał Górny     Extension expected_ext = is_vfork ? Extension::vfork : Extension::fork;
872fd0af0cfSMichał Górny     if (bool(m_enabled_extensions & expected_ext)) {
873fd0af0cfSMichał Górny       m_delegate.NewSubprocess(this, std::move(child_process));
874fd0af0cfSMichał Górny       // NB: non-vfork clone() is reported as fork
875ca271f4eSPavel Labath       parent.SetStoppedByFork(is_vfork, child_pid);
876ca271f4eSPavel Labath       StopRunningThreads(parent.GetID());
877fd0af0cfSMichał Górny     } else {
878fd0af0cfSMichał Górny       child_process->Detach();
879ca271f4eSPavel Labath       ResumeThread(parent, parent.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
880fd0af0cfSMichał Górny     }
881c8d18cbaSMichał Górny     break;
882c8d18cbaSMichał Górny   }
883c8d18cbaSMichał Górny   default:
884c8d18cbaSMichał Górny     llvm_unreachable("unknown clone_info.event");
885c8d18cbaSMichał Górny   }
886c8d18cbaSMichał Górny 
887c8d18cbaSMichał Górny   return true;
888c8d18cbaSMichał Górny }
889c8d18cbaSMichał Górny 
890b9c1b51eSKate Stone bool NativeProcessLinux::SupportHardwareSingleStepping() const {
891ddb93b63SFangrui Song   if (m_arch.GetMachine() == llvm::Triple::arm || m_arch.IsMIPS())
892cdc22a88SMohit K. Bhakkad     return false;
893cdc22a88SMohit K. Bhakkad   return true;
894e7708688STamas Berghammer }
895e7708688STamas Berghammer 
89697206d57SZachary Turner Status NativeProcessLinux::Resume(const ResumeActionList &resume_actions) {
8974fa1ad05SPavel Labath   Log *log = GetLog(POSIXLog::Process);
898a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0}", GetID());
899af245d11STodd Fiala 
900e7708688STamas Berghammer   bool software_single_step = !SupportHardwareSingleStepping();
901af245d11STodd Fiala 
902b9c1b51eSKate Stone   if (software_single_step) {
903a5be48b3SPavel Labath     for (const auto &thread : m_threads) {
904a5be48b3SPavel Labath       assert(thread && "thread list should not contain NULL threads");
905e7708688STamas Berghammer 
906b9c1b51eSKate Stone       const ResumeAction *const action =
907a5be48b3SPavel Labath           resume_actions.GetActionForThread(thread->GetID(), true);
908e7708688STamas Berghammer       if (action == nullptr)
909e7708688STamas Berghammer         continue;
910e7708688STamas Berghammer 
911b9c1b51eSKate Stone       if (action->state == eStateStepping) {
91297206d57SZachary Turner         Status error = SetupSoftwareSingleStepping(
913a5be48b3SPavel Labath             static_cast<NativeThreadLinux &>(*thread));
914e7708688STamas Berghammer         if (error.Fail())
915e7708688STamas Berghammer           return error;
916e7708688STamas Berghammer       }
917e7708688STamas Berghammer     }
918e7708688STamas Berghammer   }
919e7708688STamas Berghammer 
920a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
921a5be48b3SPavel Labath     assert(thread && "thread list should not contain NULL threads");
922af245d11STodd Fiala 
923b9c1b51eSKate Stone     const ResumeAction *const action =
924a5be48b3SPavel Labath         resume_actions.GetActionForThread(thread->GetID(), true);
9256a196ce6SChaoren Lin 
926b9c1b51eSKate Stone     if (action == nullptr) {
927a6321a8eSPavel Labath       LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
928a5be48b3SPavel Labath                thread->GetID());
9296a196ce6SChaoren Lin       continue;
9306a196ce6SChaoren Lin     }
931af245d11STodd Fiala 
932a6321a8eSPavel Labath     LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}",
933a5be48b3SPavel Labath              action->state, GetID(), thread->GetID());
934af245d11STodd Fiala 
935b9c1b51eSKate Stone     switch (action->state) {
936af245d11STodd Fiala     case eStateRunning:
937b9c1b51eSKate Stone     case eStateStepping: {
938af245d11STodd Fiala       // Run the thread, possibly feeding it the signal.
939fa03ad2eSChaoren Lin       const int signo = action->signal;
940a5be48b3SPavel Labath       ResumeThread(static_cast<NativeThreadLinux &>(*thread), action->state,
941b9c1b51eSKate Stone                    signo);
942af245d11STodd Fiala       break;
943ae29d395SChaoren Lin     }
944af245d11STodd Fiala 
945af245d11STodd Fiala     case eStateSuspended:
946af245d11STodd Fiala     case eStateStopped:
947a6321a8eSPavel Labath       llvm_unreachable("Unexpected state");
948af245d11STodd Fiala 
949af245d11STodd Fiala     default:
95097206d57SZachary Turner       return Status("NativeProcessLinux::%s (): unexpected state %s specified "
951b9c1b51eSKate Stone                     "for pid %" PRIu64 ", tid %" PRIu64,
952b9c1b51eSKate Stone                     __FUNCTION__, StateAsCString(action->state), GetID(),
953a5be48b3SPavel Labath                     thread->GetID());
954af245d11STodd Fiala     }
955af245d11STodd Fiala   }
956af245d11STodd Fiala 
95797206d57SZachary Turner   return Status();
958af245d11STodd Fiala }
959af245d11STodd Fiala 
96097206d57SZachary Turner Status NativeProcessLinux::Halt() {
96197206d57SZachary Turner   Status error;
962af245d11STodd Fiala 
963af245d11STodd Fiala   if (kill(GetID(), SIGSTOP) != 0)
964af245d11STodd Fiala     error.SetErrorToErrno();
965af245d11STodd Fiala 
966af245d11STodd Fiala   return error;
967af245d11STodd Fiala }
968af245d11STodd Fiala 
96997206d57SZachary Turner Status NativeProcessLinux::Detach() {
97097206d57SZachary Turner   Status error;
971af245d11STodd Fiala 
972af245d11STodd Fiala   // Stop monitoring the inferior.
97319cbe96aSPavel Labath   m_sigchld_handle.reset();
974af245d11STodd Fiala 
9757a9495bcSPavel Labath   // Tell ptrace to detach from the process.
9767a9495bcSPavel Labath   if (GetID() == LLDB_INVALID_PROCESS_ID)
9777a9495bcSPavel Labath     return error;
9787a9495bcSPavel Labath 
979a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
980a5be48b3SPavel Labath     Status e = Detach(thread->GetID());
9817a9495bcSPavel Labath     if (e.Fail())
982b9c1b51eSKate Stone       error =
983b9c1b51eSKate Stone           e; // Save the error, but still attempt to detach from other threads.
9847a9495bcSPavel Labath   }
9857a9495bcSPavel Labath 
986*22077627SJakob Johnson   m_intel_pt_collector.Clear();
98799e37695SRavitheja Addepally 
988af245d11STodd Fiala   return error;
989af245d11STodd Fiala }
990af245d11STodd Fiala 
99197206d57SZachary Turner Status NativeProcessLinux::Signal(int signo) {
99297206d57SZachary Turner   Status error;
993af245d11STodd Fiala 
9944fa1ad05SPavel Labath   Log *log = GetLog(POSIXLog::Process);
995a6321a8eSPavel Labath   LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo,
996a6321a8eSPavel Labath            Host::GetSignalAsCString(signo), GetID());
997af245d11STodd Fiala 
998af245d11STodd Fiala   if (kill(GetID(), signo))
999af245d11STodd Fiala     error.SetErrorToErrno();
1000af245d11STodd Fiala 
1001af245d11STodd Fiala   return error;
1002af245d11STodd Fiala }
1003af245d11STodd Fiala 
100497206d57SZachary Turner Status NativeProcessLinux::Interrupt() {
100505097246SAdrian Prantl   // Pick a running thread (or if none, a not-dead stopped thread) as the
100605097246SAdrian Prantl   // chosen thread that will be the stop-reason thread.
10074fa1ad05SPavel Labath   Log *log = GetLog(POSIXLog::Process);
1008e9547b80SChaoren Lin 
1009a5be48b3SPavel Labath   NativeThreadProtocol *running_thread = nullptr;
1010a5be48b3SPavel Labath   NativeThreadProtocol *stopped_thread = nullptr;
1011e9547b80SChaoren Lin 
1012a6321a8eSPavel Labath   LLDB_LOG(log, "selecting running thread for interrupt target");
1013a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
101405097246SAdrian Prantl     // If we have a running or stepping thread, we'll call that the target of
101505097246SAdrian Prantl     // the interrupt.
1016a5be48b3SPavel Labath     const auto thread_state = thread->GetState();
1017b9c1b51eSKate Stone     if (thread_state == eStateRunning || thread_state == eStateStepping) {
1018a5be48b3SPavel Labath       running_thread = thread.get();
1019e9547b80SChaoren Lin       break;
1020a5be48b3SPavel Labath     } else if (!stopped_thread && StateIsStoppedState(thread_state, true)) {
102105097246SAdrian Prantl       // Remember the first non-dead stopped thread.  We'll use that as a
102205097246SAdrian Prantl       // backup if there are no running threads.
1023a5be48b3SPavel Labath       stopped_thread = thread.get();
1024e9547b80SChaoren Lin     }
1025e9547b80SChaoren Lin   }
1026e9547b80SChaoren Lin 
1027a5be48b3SPavel Labath   if (!running_thread && !stopped_thread) {
102897206d57SZachary Turner     Status error("found no running/stepping or live stopped threads as target "
1029b9c1b51eSKate Stone                  "for interrupt");
1030a6321a8eSPavel Labath     LLDB_LOG(log, "skipping due to error: {0}", error);
10315830aa75STamas Berghammer 
1032e9547b80SChaoren Lin     return error;
1033e9547b80SChaoren Lin   }
1034e9547b80SChaoren Lin 
1035a5be48b3SPavel Labath   NativeThreadProtocol *deferred_signal_thread =
1036a5be48b3SPavel Labath       running_thread ? running_thread : stopped_thread;
1037e9547b80SChaoren Lin 
1038a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(),
1039a5be48b3SPavel Labath            running_thread ? "running" : "stopped",
1040a5be48b3SPavel Labath            deferred_signal_thread->GetID());
1041e9547b80SChaoren Lin 
1042a5be48b3SPavel Labath   StopRunningThreads(deferred_signal_thread->GetID());
104345f5cb31SPavel Labath 
104497206d57SZachary Turner   return Status();
1045e9547b80SChaoren Lin }
1046e9547b80SChaoren Lin 
104797206d57SZachary Turner Status NativeProcessLinux::Kill() {
10484fa1ad05SPavel Labath   Log *log = GetLog(POSIXLog::Process);
1049a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0}", GetID());
1050af245d11STodd Fiala 
105197206d57SZachary Turner   Status error;
1052af245d11STodd Fiala 
1053b9c1b51eSKate Stone   switch (m_state) {
1054af245d11STodd Fiala   case StateType::eStateInvalid:
1055af245d11STodd Fiala   case StateType::eStateExited:
1056af245d11STodd Fiala   case StateType::eStateCrashed:
1057af245d11STodd Fiala   case StateType::eStateDetached:
1058af245d11STodd Fiala   case StateType::eStateUnloaded:
1059af245d11STodd Fiala     // Nothing to do - the process is already dead.
1060a6321a8eSPavel Labath     LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
10618198db30SPavel Labath              m_state);
1062af245d11STodd Fiala     return error;
1063af245d11STodd Fiala 
1064af245d11STodd Fiala   case StateType::eStateConnected:
1065af245d11STodd Fiala   case StateType::eStateAttaching:
1066af245d11STodd Fiala   case StateType::eStateLaunching:
1067af245d11STodd Fiala   case StateType::eStateStopped:
1068af245d11STodd Fiala   case StateType::eStateRunning:
1069af245d11STodd Fiala   case StateType::eStateStepping:
1070af245d11STodd Fiala   case StateType::eStateSuspended:
1071af245d11STodd Fiala     // We can try to kill a process in these states.
1072af245d11STodd Fiala     break;
1073af245d11STodd Fiala   }
1074af245d11STodd Fiala 
1075b9c1b51eSKate Stone   if (kill(GetID(), SIGKILL) != 0) {
1076af245d11STodd Fiala     error.SetErrorToErrno();
1077af245d11STodd Fiala     return error;
1078af245d11STodd Fiala   }
1079af245d11STodd Fiala 
1080af245d11STodd Fiala   return error;
1081af245d11STodd Fiala }
1082af245d11STodd Fiala 
108397206d57SZachary Turner Status NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr,
1084b9c1b51eSKate Stone                                                MemoryRegionInfo &range_info) {
1085b9c1b51eSKate Stone   // FIXME review that the final memory region returned extends to the end of
1086b9c1b51eSKate Stone   // the virtual address space,
1087af245d11STodd Fiala   // with no perms if it is not mapped.
1088af245d11STodd Fiala 
108905097246SAdrian Prantl   // Use an approach that reads memory regions from /proc/{pid}/maps. Assume
109005097246SAdrian Prantl   // proc maps entries are in ascending order.
1091af245d11STodd Fiala   // FIXME assert if we find differently.
1092af245d11STodd Fiala 
1093b9c1b51eSKate Stone   if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
1094af245d11STodd Fiala     // We're done.
109597206d57SZachary Turner     return Status("unsupported");
1096af245d11STodd Fiala   }
1097af245d11STodd Fiala 
109897206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
1099b9c1b51eSKate Stone   if (error.Fail()) {
1100af245d11STodd Fiala     return error;
1101af245d11STodd Fiala   }
1102af245d11STodd Fiala 
1103af245d11STodd Fiala   lldb::addr_t prev_base_address = 0;
1104af245d11STodd Fiala 
1105b9c1b51eSKate Stone   // FIXME start by finding the last region that is <= target address using
1106b9c1b51eSKate Stone   // binary search.  Data is sorted.
1107af245d11STodd Fiala   // There can be a ton of regions on pthreads apps with lots of threads.
1108b9c1b51eSKate Stone   for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1109b9c1b51eSKate Stone        ++it) {
1110a6f5795aSTamas Berghammer     MemoryRegionInfo &proc_entry_info = it->first;
1111af245d11STodd Fiala 
1112af245d11STodd Fiala     // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1113b9c1b51eSKate Stone     assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
1114b9c1b51eSKate Stone            "descending /proc/pid/maps entries detected, unexpected");
1115af245d11STodd Fiala     prev_base_address = proc_entry_info.GetRange().GetRangeBase();
1116b1554311SHafiz Abid Qadeer     UNUSED_IF_ASSERT_DISABLED(prev_base_address);
1117af245d11STodd Fiala 
1118b9c1b51eSKate Stone     // If the target address comes before this entry, indicate distance to next
1119b9c1b51eSKate Stone     // region.
1120b9c1b51eSKate Stone     if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1121af245d11STodd Fiala       range_info.GetRange().SetRangeBase(load_addr);
1122b9c1b51eSKate Stone       range_info.GetRange().SetByteSize(
1123b9c1b51eSKate Stone           proc_entry_info.GetRange().GetRangeBase() - load_addr);
1124af245d11STodd Fiala       range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1125af245d11STodd Fiala       range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1126af245d11STodd Fiala       range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1127ad007563SHoward Hellyer       range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1128af245d11STodd Fiala 
1129af245d11STodd Fiala       return error;
1130b9c1b51eSKate Stone     } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1131af245d11STodd Fiala       // The target address is within the memory region we're processing here.
1132af245d11STodd Fiala       range_info = proc_entry_info;
1133af245d11STodd Fiala       return error;
1134af245d11STodd Fiala     }
1135af245d11STodd Fiala 
1136b9c1b51eSKate Stone     // The target memory address comes somewhere after the region we just
1137b9c1b51eSKate Stone     // parsed.
1138af245d11STodd Fiala   }
1139af245d11STodd Fiala 
1140b9c1b51eSKate Stone   // If we made it here, we didn't find an entry that contained the given
114105097246SAdrian Prantl   // address. Return the load_addr as start and the amount of bytes betwwen
114205097246SAdrian Prantl   // load address and the end of the memory as size.
114309839c33STamas Berghammer   range_info.GetRange().SetRangeBase(load_addr);
1144ad007563SHoward Hellyer   range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
114509839c33STamas Berghammer   range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
114609839c33STamas Berghammer   range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
114709839c33STamas Berghammer   range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1148ad007563SHoward Hellyer   range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1149af245d11STodd Fiala   return error;
1150af245d11STodd Fiala }
1151af245d11STodd Fiala 
115297206d57SZachary Turner Status NativeProcessLinux::PopulateMemoryRegionCache() {
11534fa1ad05SPavel Labath   Log *log = GetLog(POSIXLog::Process);
1154a6f5795aSTamas Berghammer 
1155a6f5795aSTamas Berghammer   // If our cache is empty, pull the latest.  There should always be at least
1156a6f5795aSTamas Berghammer   // one memory region if memory region handling is supported.
1157a6f5795aSTamas Berghammer   if (!m_mem_region_cache.empty()) {
1158a6321a8eSPavel Labath     LLDB_LOG(log, "reusing {0} cached memory region entries",
1159a6321a8eSPavel Labath              m_mem_region_cache.size());
116097206d57SZachary Turner     return Status();
1161a6f5795aSTamas Berghammer   }
1162a6f5795aSTamas Berghammer 
116332541685SDavid Spickett   Status Result;
116432541685SDavid Spickett   LinuxMapCallback callback = [&](llvm::Expected<MemoryRegionInfo> Info) {
116532541685SDavid Spickett     if (Info) {
116632541685SDavid Spickett       FileSpec file_spec(Info->GetName().GetCString());
116732541685SDavid Spickett       FileSystem::Instance().Resolve(file_spec);
116832541685SDavid Spickett       m_mem_region_cache.emplace_back(*Info, file_spec);
116932541685SDavid Spickett       return true;
117032541685SDavid Spickett     }
117132541685SDavid Spickett 
117232541685SDavid Spickett     Result = Info.takeError();
117332541685SDavid Spickett     m_supports_mem_region = LazyBool::eLazyBoolNo;
117432541685SDavid Spickett     LLDB_LOG(log, "failed to parse proc maps: {0}", Result);
117532541685SDavid Spickett     return false;
117632541685SDavid Spickett   };
117732541685SDavid Spickett 
117832541685SDavid Spickett   // Linux kernel since 2.6.14 has /proc/{pid}/smaps
117932541685SDavid Spickett   // if CONFIG_PROC_PAGE_MONITOR is enabled
118032541685SDavid Spickett   auto BufferOrError = getProcFile(GetID(), "smaps");
118132541685SDavid Spickett   if (BufferOrError)
118232541685SDavid Spickett     ParseLinuxSMapRegions(BufferOrError.get()->getBuffer(), callback);
118332541685SDavid Spickett   else {
118432541685SDavid Spickett     BufferOrError = getProcFile(GetID(), "maps");
118515930862SPavel Labath     if (!BufferOrError) {
118615930862SPavel Labath       m_supports_mem_region = LazyBool::eLazyBoolNo;
118715930862SPavel Labath       return BufferOrError.getError();
118815930862SPavel Labath     }
118932541685SDavid Spickett 
119032541685SDavid Spickett     ParseLinuxMapRegions(BufferOrError.get()->getBuffer(), callback);
1191a6f5795aSTamas Berghammer   }
119232541685SDavid Spickett 
1193c8e364e8SPavel Labath   if (Result.Fail())
1194c8e364e8SPavel Labath     return Result;
1195a6f5795aSTamas Berghammer 
119615930862SPavel Labath   if (m_mem_region_cache.empty()) {
1197a6f5795aSTamas Berghammer     // No entries after attempting to read them.  This shouldn't happen if
119805097246SAdrian Prantl     // /proc/{pid}/maps is supported. Assume we don't support map entries via
119905097246SAdrian Prantl     // procfs.
120015930862SPavel Labath     m_supports_mem_region = LazyBool::eLazyBoolNo;
1201a6321a8eSPavel Labath     LLDB_LOG(log,
1202a6321a8eSPavel Labath              "failed to find any procfs maps entries, assuming no support "
1203a6321a8eSPavel Labath              "for memory region metadata retrieval");
120497206d57SZachary Turner     return Status("not supported");
1205a6f5795aSTamas Berghammer   }
1206a6f5795aSTamas Berghammer 
1207a6321a8eSPavel Labath   LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps",
1208a6321a8eSPavel Labath            m_mem_region_cache.size(), GetID());
1209a6f5795aSTamas Berghammer 
1210a6f5795aSTamas Berghammer   // We support memory retrieval, remember that.
1211a6f5795aSTamas Berghammer   m_supports_mem_region = LazyBool::eLazyBoolYes;
121297206d57SZachary Turner   return Status();
1213a6f5795aSTamas Berghammer }
1214a6f5795aSTamas Berghammer 
1215b9c1b51eSKate Stone void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
12164fa1ad05SPavel Labath   Log *log = GetLog(POSIXLog::Process);
1217a6321a8eSPavel Labath   LLDB_LOG(log, "newBumpId={0}", newBumpId);
1218a6321a8eSPavel Labath   LLDB_LOG(log, "clearing {0} entries from memory region cache",
1219a6321a8eSPavel Labath            m_mem_region_cache.size());
1220af245d11STodd Fiala   m_mem_region_cache.clear();
1221af245d11STodd Fiala }
1222af245d11STodd Fiala 
12232c4226f8SPavel Labath llvm::Expected<uint64_t>
12242c4226f8SPavel Labath NativeProcessLinux::Syscall(llvm::ArrayRef<uint64_t> args) {
12252c4226f8SPavel Labath   PopulateMemoryRegionCache();
12262c4226f8SPavel Labath   auto region_it = llvm::find_if(m_mem_region_cache, [](const auto &pair) {
12272c4226f8SPavel Labath     return pair.first.GetExecutable() == MemoryRegionInfo::eYes;
12282c4226f8SPavel Labath   });
12292c4226f8SPavel Labath   if (region_it == m_mem_region_cache.end())
12302c4226f8SPavel Labath     return llvm::createStringError(llvm::inconvertibleErrorCode(),
12312c4226f8SPavel Labath                                    "No executable memory region found!");
1232af245d11STodd Fiala 
12332c4226f8SPavel Labath   addr_t exe_addr = region_it->first.GetRange().GetRangeBase();
1234af245d11STodd Fiala 
12352c4226f8SPavel Labath   NativeThreadLinux &thread = *GetThreadByID(GetID());
12362c4226f8SPavel Labath   assert(thread.GetState() == eStateStopped);
12372c4226f8SPavel Labath   NativeRegisterContextLinux &reg_ctx = thread.GetRegisterContext();
12382c4226f8SPavel Labath 
12392c4226f8SPavel Labath   NativeRegisterContextLinux::SyscallData syscall_data =
12402c4226f8SPavel Labath       *reg_ctx.GetSyscallData();
12412c4226f8SPavel Labath 
12422c4226f8SPavel Labath   DataBufferSP registers_sp;
12432c4226f8SPavel Labath   if (llvm::Error Err = reg_ctx.ReadAllRegisterValues(registers_sp).ToError())
12442c4226f8SPavel Labath     return std::move(Err);
12452c4226f8SPavel Labath   auto restore_regs = llvm::make_scope_exit(
12462c4226f8SPavel Labath       [&] { reg_ctx.WriteAllRegisterValues(registers_sp); });
12472c4226f8SPavel Labath 
12482c4226f8SPavel Labath   llvm::SmallVector<uint8_t, 8> memory(syscall_data.Insn.size());
12492c4226f8SPavel Labath   size_t bytes_read;
12502c4226f8SPavel Labath   if (llvm::Error Err =
12512c4226f8SPavel Labath           ReadMemory(exe_addr, memory.data(), memory.size(), bytes_read)
12522c4226f8SPavel Labath               .ToError()) {
12532c4226f8SPavel Labath     return std::move(Err);
1254af245d11STodd Fiala   }
1255af245d11STodd Fiala 
12562c4226f8SPavel Labath   auto restore_mem = llvm::make_scope_exit(
12572c4226f8SPavel Labath       [&] { WriteMemory(exe_addr, memory.data(), memory.size(), bytes_read); });
12582c4226f8SPavel Labath 
12592c4226f8SPavel Labath   if (llvm::Error Err = reg_ctx.SetPC(exe_addr).ToError())
12602c4226f8SPavel Labath     return std::move(Err);
12612c4226f8SPavel Labath 
12622c4226f8SPavel Labath   for (const auto &zip : llvm::zip_first(args, syscall_data.Args)) {
12632c4226f8SPavel Labath     if (llvm::Error Err =
12642c4226f8SPavel Labath             reg_ctx
12652c4226f8SPavel Labath                 .WriteRegisterFromUnsigned(std::get<1>(zip), std::get<0>(zip))
12662c4226f8SPavel Labath                 .ToError()) {
12672c4226f8SPavel Labath       return std::move(Err);
12682c4226f8SPavel Labath     }
12692c4226f8SPavel Labath   }
12702c4226f8SPavel Labath   if (llvm::Error Err = WriteMemory(exe_addr, syscall_data.Insn.data(),
12712c4226f8SPavel Labath                                     syscall_data.Insn.size(), bytes_read)
12722c4226f8SPavel Labath                             .ToError())
12732c4226f8SPavel Labath     return std::move(Err);
12742c4226f8SPavel Labath 
12752c4226f8SPavel Labath   m_mem_region_cache.clear();
12762c4226f8SPavel Labath 
12772c4226f8SPavel Labath   // With software single stepping the syscall insn buffer must also include a
12782c4226f8SPavel Labath   // trap instruction to stop the process.
12792c4226f8SPavel Labath   int req = SupportHardwareSingleStepping() ? PTRACE_SINGLESTEP : PTRACE_CONT;
12802c4226f8SPavel Labath   if (llvm::Error Err =
12812c4226f8SPavel Labath           PtraceWrapper(req, thread.GetID(), nullptr, nullptr).ToError())
12822c4226f8SPavel Labath     return std::move(Err);
12832c4226f8SPavel Labath 
12842c4226f8SPavel Labath   int status;
12852c4226f8SPavel Labath   ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, thread.GetID(),
12862c4226f8SPavel Labath                                                  &status, __WALL);
12872c4226f8SPavel Labath   if (wait_pid == -1) {
12882c4226f8SPavel Labath     return llvm::errorCodeToError(
12892c4226f8SPavel Labath         std::error_code(errno, std::generic_category()));
12902c4226f8SPavel Labath   }
12912c4226f8SPavel Labath   assert((unsigned)wait_pid == thread.GetID());
12922c4226f8SPavel Labath 
12932c4226f8SPavel Labath   uint64_t result = reg_ctx.ReadRegisterAsUnsigned(syscall_data.Result, -ESRCH);
12942c4226f8SPavel Labath 
12952c4226f8SPavel Labath   // Values larger than this are actually negative errno numbers.
12962c4226f8SPavel Labath   uint64_t errno_threshold =
12972c4226f8SPavel Labath       (uint64_t(-1) >> (64 - 8 * m_arch.GetAddressByteSize())) - 0x1000;
12982c4226f8SPavel Labath   if (result > errno_threshold) {
12992c4226f8SPavel Labath     return llvm::errorCodeToError(
13002c4226f8SPavel Labath         std::error_code(-result & 0xfff, std::generic_category()));
13012c4226f8SPavel Labath   }
13022c4226f8SPavel Labath 
13032c4226f8SPavel Labath   return result;
13042c4226f8SPavel Labath }
13052c4226f8SPavel Labath 
13062c4226f8SPavel Labath llvm::Expected<addr_t>
13072c4226f8SPavel Labath NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions) {
13082c4226f8SPavel Labath 
13092c4226f8SPavel Labath   llvm::Optional<NativeRegisterContextLinux::MmapData> mmap_data =
13102c4226f8SPavel Labath       GetCurrentThread()->GetRegisterContext().GetMmapData();
13112c4226f8SPavel Labath   if (!mmap_data)
13122c4226f8SPavel Labath     return llvm::make_error<UnimplementedError>();
13132c4226f8SPavel Labath 
13142c4226f8SPavel Labath   unsigned prot = PROT_NONE;
13152c4226f8SPavel Labath   assert((permissions & (ePermissionsReadable | ePermissionsWritable |
13162c4226f8SPavel Labath                          ePermissionsExecutable)) == permissions &&
13172c4226f8SPavel Labath          "Unknown permission!");
13182c4226f8SPavel Labath   if (permissions & ePermissionsReadable)
13192c4226f8SPavel Labath     prot |= PROT_READ;
13202c4226f8SPavel Labath   if (permissions & ePermissionsWritable)
13212c4226f8SPavel Labath     prot |= PROT_WRITE;
13222c4226f8SPavel Labath   if (permissions & ePermissionsExecutable)
13232c4226f8SPavel Labath     prot |= PROT_EXEC;
13242c4226f8SPavel Labath 
13252c4226f8SPavel Labath   llvm::Expected<uint64_t> Result =
13262c4226f8SPavel Labath       Syscall({mmap_data->SysMmap, 0, size, prot, MAP_ANONYMOUS | MAP_PRIVATE,
13272c4226f8SPavel Labath                uint64_t(-1), 0});
13282c4226f8SPavel Labath   if (Result)
13292c4226f8SPavel Labath     m_allocated_memory.try_emplace(*Result, size);
13302c4226f8SPavel Labath   return Result;
13312c4226f8SPavel Labath }
13322c4226f8SPavel Labath 
13332c4226f8SPavel Labath llvm::Error NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {
13342c4226f8SPavel Labath   llvm::Optional<NativeRegisterContextLinux::MmapData> mmap_data =
13352c4226f8SPavel Labath       GetCurrentThread()->GetRegisterContext().GetMmapData();
13362c4226f8SPavel Labath   if (!mmap_data)
13372c4226f8SPavel Labath     return llvm::make_error<UnimplementedError>();
13382c4226f8SPavel Labath 
13392c4226f8SPavel Labath   auto it = m_allocated_memory.find(addr);
13402c4226f8SPavel Labath   if (it == m_allocated_memory.end())
13412c4226f8SPavel Labath     return llvm::createStringError(llvm::errc::invalid_argument,
13422c4226f8SPavel Labath                                    "Memory not allocated by the debugger.");
13432c4226f8SPavel Labath 
13442c4226f8SPavel Labath   llvm::Expected<uint64_t> Result =
13452c4226f8SPavel Labath       Syscall({mmap_data->SysMunmap, addr, it->second});
13462c4226f8SPavel Labath   if (!Result)
13472c4226f8SPavel Labath     return Result.takeError();
13482c4226f8SPavel Labath 
13492c4226f8SPavel Labath   m_allocated_memory.erase(it);
13502c4226f8SPavel Labath   return llvm::Error::success();
1351af245d11STodd Fiala }
1352af245d11STodd Fiala 
1353da2e614fSDavid Spickett Status NativeProcessLinux::ReadMemoryTags(int32_t type, lldb::addr_t addr,
1354da2e614fSDavid Spickett                                           size_t len,
1355da2e614fSDavid Spickett                                           std::vector<uint8_t> &tags) {
1356da2e614fSDavid Spickett   llvm::Expected<NativeRegisterContextLinux::MemoryTaggingDetails> details =
1357da2e614fSDavid Spickett       GetCurrentThread()->GetRegisterContext().GetMemoryTaggingDetails(type);
1358da2e614fSDavid Spickett   if (!details)
1359da2e614fSDavid Spickett     return Status(details.takeError());
1360da2e614fSDavid Spickett 
1361da2e614fSDavid Spickett   // Ignore 0 length read
1362da2e614fSDavid Spickett   if (!len)
1363da2e614fSDavid Spickett     return Status();
1364da2e614fSDavid Spickett 
1365da2e614fSDavid Spickett   // lldb will align the range it requests but it is not required to by
1366da2e614fSDavid Spickett   // the protocol so we'll do it again just in case.
1367585abe3bSDavid Spickett   // Remove tag bits too. Ptrace calls may work regardless but that
1368da2e614fSDavid Spickett   // is not a guarantee.
1369585abe3bSDavid Spickett   MemoryTagManager::TagRange range(details->manager->RemoveTagBits(addr), len);
1370da2e614fSDavid Spickett   range = details->manager->ExpandToGranule(range);
1371da2e614fSDavid Spickett 
1372da2e614fSDavid Spickett   // Allocate enough space for all tags to be read
1373da2e614fSDavid Spickett   size_t num_tags = range.GetByteSize() / details->manager->GetGranuleSize();
1374da2e614fSDavid Spickett   tags.resize(num_tags * details->manager->GetTagSizeInBytes());
1375da2e614fSDavid Spickett 
1376da2e614fSDavid Spickett   struct iovec tags_iovec;
1377da2e614fSDavid Spickett   uint8_t *dest = tags.data();
1378da2e614fSDavid Spickett   lldb::addr_t read_addr = range.GetRangeBase();
1379da2e614fSDavid Spickett 
1380da2e614fSDavid Spickett   // This call can return partial data so loop until we error or
1381da2e614fSDavid Spickett   // get all tags back.
1382da2e614fSDavid Spickett   while (num_tags) {
1383da2e614fSDavid Spickett     tags_iovec.iov_base = dest;
1384da2e614fSDavid Spickett     tags_iovec.iov_len = num_tags;
1385da2e614fSDavid Spickett 
1386da2e614fSDavid Spickett     Status error = NativeProcessLinux::PtraceWrapper(
1387da2e614fSDavid Spickett         details->ptrace_read_req, GetID(), reinterpret_cast<void *>(read_addr),
1388da2e614fSDavid Spickett         static_cast<void *>(&tags_iovec), 0, nullptr);
1389da2e614fSDavid Spickett 
1390da2e614fSDavid Spickett     if (error.Fail()) {
1391da2e614fSDavid Spickett       // Discard partial reads
1392da2e614fSDavid Spickett       tags.resize(0);
1393da2e614fSDavid Spickett       return error;
1394da2e614fSDavid Spickett     }
1395da2e614fSDavid Spickett 
1396da2e614fSDavid Spickett     size_t tags_read = tags_iovec.iov_len;
1397da2e614fSDavid Spickett     assert(tags_read && (tags_read <= num_tags));
1398da2e614fSDavid Spickett 
1399da2e614fSDavid Spickett     dest += tags_read * details->manager->GetTagSizeInBytes();
1400da2e614fSDavid Spickett     read_addr += details->manager->GetGranuleSize() * tags_read;
1401da2e614fSDavid Spickett     num_tags -= tags_read;
1402da2e614fSDavid Spickett   }
1403da2e614fSDavid Spickett 
1404da2e614fSDavid Spickett   return Status();
1405da2e614fSDavid Spickett }
1406da2e614fSDavid Spickett 
14077d27230dSDavid Spickett Status NativeProcessLinux::WriteMemoryTags(int32_t type, lldb::addr_t addr,
14087d27230dSDavid Spickett                                            size_t len,
14097d27230dSDavid Spickett                                            const std::vector<uint8_t> &tags) {
14107d27230dSDavid Spickett   llvm::Expected<NativeRegisterContextLinux::MemoryTaggingDetails> details =
14117d27230dSDavid Spickett       GetCurrentThread()->GetRegisterContext().GetMemoryTaggingDetails(type);
14127d27230dSDavid Spickett   if (!details)
14137d27230dSDavid Spickett     return Status(details.takeError());
14147d27230dSDavid Spickett 
14157d27230dSDavid Spickett   // Ignore 0 length write
14167d27230dSDavid Spickett   if (!len)
14177d27230dSDavid Spickett     return Status();
14187d27230dSDavid Spickett 
14197d27230dSDavid Spickett   // lldb will align the range it requests but it is not required to by
14207d27230dSDavid Spickett   // the protocol so we'll do it again just in case.
1421585abe3bSDavid Spickett   // Remove tag bits too. Ptrace calls may work regardless but that
14227d27230dSDavid Spickett   // is not a guarantee.
1423585abe3bSDavid Spickett   MemoryTagManager::TagRange range(details->manager->RemoveTagBits(addr), len);
14247d27230dSDavid Spickett   range = details->manager->ExpandToGranule(range);
14257d27230dSDavid Spickett 
14267d27230dSDavid Spickett   // Not checking number of tags here, we may repeat them below
14277d27230dSDavid Spickett   llvm::Expected<std::vector<lldb::addr_t>> unpacked_tags_or_err =
14287d27230dSDavid Spickett       details->manager->UnpackTagsData(tags);
14297d27230dSDavid Spickett   if (!unpacked_tags_or_err)
14307d27230dSDavid Spickett     return Status(unpacked_tags_or_err.takeError());
14317d27230dSDavid Spickett 
14327d27230dSDavid Spickett   llvm::Expected<std::vector<lldb::addr_t>> repeated_tags_or_err =
14337d27230dSDavid Spickett       details->manager->RepeatTagsForRange(*unpacked_tags_or_err, range);
14347d27230dSDavid Spickett   if (!repeated_tags_or_err)
14357d27230dSDavid Spickett     return Status(repeated_tags_or_err.takeError());
14367d27230dSDavid Spickett 
14377d27230dSDavid Spickett   // Repack them for ptrace to use
14387d27230dSDavid Spickett   llvm::Expected<std::vector<uint8_t>> final_tag_data =
14397d27230dSDavid Spickett       details->manager->PackTags(*repeated_tags_or_err);
14407d27230dSDavid Spickett   if (!final_tag_data)
14417d27230dSDavid Spickett     return Status(final_tag_data.takeError());
14427d27230dSDavid Spickett 
14437d27230dSDavid Spickett   struct iovec tags_vec;
14447d27230dSDavid Spickett   uint8_t *src = final_tag_data->data();
14457d27230dSDavid Spickett   lldb::addr_t write_addr = range.GetRangeBase();
14467d27230dSDavid Spickett   // unpacked tags size because the number of bytes per tag might not be 1
14477d27230dSDavid Spickett   size_t num_tags = repeated_tags_or_err->size();
14487d27230dSDavid Spickett 
14497d27230dSDavid Spickett   // This call can partially write tags, so we loop until we
14507d27230dSDavid Spickett   // error or all tags have been written.
14517d27230dSDavid Spickett   while (num_tags > 0) {
14527d27230dSDavid Spickett     tags_vec.iov_base = src;
14537d27230dSDavid Spickett     tags_vec.iov_len = num_tags;
14547d27230dSDavid Spickett 
14557d27230dSDavid Spickett     Status error = NativeProcessLinux::PtraceWrapper(
14567d27230dSDavid Spickett         details->ptrace_write_req, GetID(),
14577d27230dSDavid Spickett         reinterpret_cast<void *>(write_addr), static_cast<void *>(&tags_vec), 0,
14587d27230dSDavid Spickett         nullptr);
14597d27230dSDavid Spickett 
14607d27230dSDavid Spickett     if (error.Fail()) {
14617d27230dSDavid Spickett       // Don't attempt to restore the original values in the case of a partial
14627d27230dSDavid Spickett       // write
14637d27230dSDavid Spickett       return error;
14647d27230dSDavid Spickett     }
14657d27230dSDavid Spickett 
14667d27230dSDavid Spickett     size_t tags_written = tags_vec.iov_len;
14677d27230dSDavid Spickett     assert(tags_written && (tags_written <= num_tags));
14687d27230dSDavid Spickett 
14697d27230dSDavid Spickett     src += tags_written * details->manager->GetTagSizeInBytes();
14707d27230dSDavid Spickett     write_addr += details->manager->GetGranuleSize() * tags_written;
14717d27230dSDavid Spickett     num_tags -= tags_written;
14727d27230dSDavid Spickett   }
14737d27230dSDavid Spickett 
14747d27230dSDavid Spickett   return Status();
14757d27230dSDavid Spickett }
14767d27230dSDavid Spickett 
1477b9c1b51eSKate Stone size_t NativeProcessLinux::UpdateThreads() {
147805097246SAdrian Prantl   // The NativeProcessLinux monitoring threads are always up to date with
147905097246SAdrian Prantl   // respect to thread state and they keep the thread list populated properly.
148005097246SAdrian Prantl   // All this method needs to do is return the thread count.
1481af245d11STodd Fiala   return m_threads.size();
1482af245d11STodd Fiala }
1483af245d11STodd Fiala 
148497206d57SZachary Turner Status NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,
1485b9c1b51eSKate Stone                                          bool hardware) {
1486af245d11STodd Fiala   if (hardware)
1487d5ffbad2SOmair Javaid     return SetHardwareBreakpoint(addr, size);
1488af245d11STodd Fiala   else
1489af245d11STodd Fiala     return SetSoftwareBreakpoint(addr, size);
1490af245d11STodd Fiala }
1491af245d11STodd Fiala 
149297206d57SZachary Turner Status NativeProcessLinux::RemoveBreakpoint(lldb::addr_t addr, bool hardware) {
1493d5ffbad2SOmair Javaid   if (hardware)
1494d5ffbad2SOmair Javaid     return RemoveHardwareBreakpoint(addr);
1495d5ffbad2SOmair Javaid   else
1496d5ffbad2SOmair Javaid     return NativeProcessProtocol::RemoveBreakpoint(addr);
1497d5ffbad2SOmair Javaid }
1498d5ffbad2SOmair Javaid 
1499f8b825f6SPavel Labath llvm::Expected<llvm::ArrayRef<uint8_t>>
1500f8b825f6SPavel Labath NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(size_t size_hint) {
1501be379e15STamas Berghammer   // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1502be379e15STamas Berghammer   // linux kernel does otherwise.
1503f8b825f6SPavel Labath   static const uint8_t g_arm_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1504f8b825f6SPavel Labath   static const uint8_t g_thumb_opcode[] = {0x01, 0xde};
150512286a27SPavel Labath 
1506f8b825f6SPavel Labath   switch (GetArchitecture().GetMachine()) {
150712286a27SPavel Labath   case llvm::Triple::arm:
1508f8b825f6SPavel Labath     switch (size_hint) {
150963c8be95STamas Berghammer     case 2:
15104f545074SPavel Labath       return llvm::makeArrayRef(g_thumb_opcode);
151163c8be95STamas Berghammer     case 4:
15124f545074SPavel Labath       return llvm::makeArrayRef(g_arm_opcode);
151363c8be95STamas Berghammer     default:
1514f8b825f6SPavel Labath       return llvm::createStringError(llvm::inconvertibleErrorCode(),
1515f8b825f6SPavel Labath                                      "Unrecognised trap opcode size hint!");
151663c8be95STamas Berghammer     }
1517af245d11STodd Fiala   default:
1518f8b825f6SPavel Labath     return NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_hint);
1519af245d11STodd Fiala   }
1520af245d11STodd Fiala }
1521af245d11STodd Fiala 
152297206d57SZachary Turner Status NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
1523b9c1b51eSKate Stone                                       size_t &bytes_read) {
1524df7c6995SPavel Labath   if (ProcessVmReadvSupported()) {
1525b9c1b51eSKate Stone     // The process_vm_readv path is about 50 times faster than ptrace api. We
152605097246SAdrian Prantl     // want to use this syscall if it is supported.
1527df7c6995SPavel Labath 
1528df7c6995SPavel Labath     const ::pid_t pid = GetID();
1529df7c6995SPavel Labath 
1530df7c6995SPavel Labath     struct iovec local_iov, remote_iov;
1531df7c6995SPavel Labath     local_iov.iov_base = buf;
1532df7c6995SPavel Labath     local_iov.iov_len = size;
1533df7c6995SPavel Labath     remote_iov.iov_base = reinterpret_cast<void *>(addr);
1534df7c6995SPavel Labath     remote_iov.iov_len = size;
1535df7c6995SPavel Labath 
1536df7c6995SPavel Labath     bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
1537df7c6995SPavel Labath     const bool success = bytes_read == size;
1538df7c6995SPavel Labath 
15394fa1ad05SPavel Labath     Log *log = GetLog(POSIXLog::Process);
1540a6321a8eSPavel Labath     LLDB_LOG(log,
1541a6321a8eSPavel Labath              "using process_vm_readv to read {0} bytes from inferior "
1542a6321a8eSPavel Labath              "address {1:x}: {2}",
154310c41f37SPavel Labath              size, addr, success ? "Success" : llvm::sys::StrError(errno));
1544df7c6995SPavel Labath 
1545df7c6995SPavel Labath     if (success)
154697206d57SZachary Turner       return Status();
1547a6321a8eSPavel Labath     // else the call failed for some reason, let's retry the read using ptrace
1548b9c1b51eSKate Stone     // api.
1549df7c6995SPavel Labath   }
1550df7c6995SPavel Labath 
155119cbe96aSPavel Labath   unsigned char *dst = static_cast<unsigned char *>(buf);
155219cbe96aSPavel Labath   size_t remainder;
155319cbe96aSPavel Labath   long data;
155419cbe96aSPavel Labath 
15554fa1ad05SPavel Labath   Log *log = GetLog(POSIXLog::Memory);
1556a6321a8eSPavel Labath   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
155719cbe96aSPavel Labath 
1558b9c1b51eSKate Stone   for (bytes_read = 0; bytes_read < size; bytes_read += remainder) {
155997206d57SZachary Turner     Status error = NativeProcessLinux::PtraceWrapper(
1560b9c1b51eSKate Stone         PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data);
1561a6321a8eSPavel Labath     if (error.Fail())
156219cbe96aSPavel Labath       return error;
156319cbe96aSPavel Labath 
156419cbe96aSPavel Labath     remainder = size - bytes_read;
156519cbe96aSPavel Labath     remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
156619cbe96aSPavel Labath 
156719cbe96aSPavel Labath     // Copy the data into our buffer
1568f6ef187bSMohit K. Bhakkad     memcpy(dst, &data, remainder);
156919cbe96aSPavel Labath 
1570a6321a8eSPavel Labath     LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
157119cbe96aSPavel Labath     addr += k_ptrace_word_size;
157219cbe96aSPavel Labath     dst += k_ptrace_word_size;
157319cbe96aSPavel Labath   }
157497206d57SZachary Turner   return Status();
1575af245d11STodd Fiala }
1576af245d11STodd Fiala 
157797206d57SZachary Turner Status NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,
1578b9c1b51eSKate Stone                                        size_t size, size_t &bytes_written) {
157919cbe96aSPavel Labath   const unsigned char *src = static_cast<const unsigned char *>(buf);
158019cbe96aSPavel Labath   size_t remainder;
158197206d57SZachary Turner   Status error;
158219cbe96aSPavel Labath 
15834fa1ad05SPavel Labath   Log *log = GetLog(POSIXLog::Memory);
1584a6321a8eSPavel Labath   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
158519cbe96aSPavel Labath 
1586b9c1b51eSKate Stone   for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
158719cbe96aSPavel Labath     remainder = size - bytes_written;
158819cbe96aSPavel Labath     remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
158919cbe96aSPavel Labath 
1590b9c1b51eSKate Stone     if (remainder == k_ptrace_word_size) {
159119cbe96aSPavel Labath       unsigned long data = 0;
1592f6ef187bSMohit K. Bhakkad       memcpy(&data, src, k_ptrace_word_size);
159319cbe96aSPavel Labath 
1594a6321a8eSPavel Labath       LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
1595b9c1b51eSKate Stone       error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(),
1596b9c1b51eSKate Stone                                                 (void *)addr, (void *)data);
1597a6321a8eSPavel Labath       if (error.Fail())
159819cbe96aSPavel Labath         return error;
1599b9c1b51eSKate Stone     } else {
160019cbe96aSPavel Labath       unsigned char buff[8];
160119cbe96aSPavel Labath       size_t bytes_read;
160219cbe96aSPavel Labath       error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
1603a6321a8eSPavel Labath       if (error.Fail())
160419cbe96aSPavel Labath         return error;
160519cbe96aSPavel Labath 
160619cbe96aSPavel Labath       memcpy(buff, src, remainder);
160719cbe96aSPavel Labath 
160819cbe96aSPavel Labath       size_t bytes_written_rec;
160919cbe96aSPavel Labath       error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
1610a6321a8eSPavel Labath       if (error.Fail())
161119cbe96aSPavel Labath         return error;
161219cbe96aSPavel Labath 
1613a6321a8eSPavel Labath       LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src,
1614b9c1b51eSKate Stone                *(unsigned long *)buff);
161519cbe96aSPavel Labath     }
161619cbe96aSPavel Labath 
161719cbe96aSPavel Labath     addr += k_ptrace_word_size;
161819cbe96aSPavel Labath     src += k_ptrace_word_size;
161919cbe96aSPavel Labath   }
162019cbe96aSPavel Labath   return error;
1621af245d11STodd Fiala }
1622af245d11STodd Fiala 
16231e74e5e9SMichał Górny Status NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) const {
162419cbe96aSPavel Labath   return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
1625af245d11STodd Fiala }
1626af245d11STodd Fiala 
162797206d57SZachary Turner Status NativeProcessLinux::GetEventMessage(lldb::tid_t tid,
1628b9c1b51eSKate Stone                                            unsigned long *message) {
162919cbe96aSPavel Labath   return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
1630af245d11STodd Fiala }
1631af245d11STodd Fiala 
163297206d57SZachary Turner Status NativeProcessLinux::Detach(lldb::tid_t tid) {
163397ccc294SChaoren Lin   if (tid == LLDB_INVALID_THREAD_ID)
163497206d57SZachary Turner     return Status();
163597ccc294SChaoren Lin 
163619cbe96aSPavel Labath   return PtraceWrapper(PTRACE_DETACH, tid);
1637af245d11STodd Fiala }
1638af245d11STodd Fiala 
1639b9c1b51eSKate Stone bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {
1640a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
1641a5be48b3SPavel Labath     assert(thread && "thread list should not contain NULL threads");
1642a5be48b3SPavel Labath     if (thread->GetID() == thread_id) {
1643af245d11STodd Fiala       // We have this thread.
1644af245d11STodd Fiala       return true;
1645af245d11STodd Fiala     }
1646af245d11STodd Fiala   }
1647af245d11STodd Fiala 
1648af245d11STodd Fiala   // We don't have this thread.
1649af245d11STodd Fiala   return false;
1650af245d11STodd Fiala }
1651af245d11STodd Fiala 
1652ca271f4eSPavel Labath void NativeProcessLinux::StopTrackingThread(NativeThreadLinux &thread) {
16534fa1ad05SPavel Labath   Log *const log = GetLog(POSIXLog::Thread);
1654ca271f4eSPavel Labath   lldb::tid_t thread_id = thread.GetID();
1655ca271f4eSPavel Labath   LLDB_LOG(log, "tid: {0}", thread_id);
16561dbc6c9cSPavel Labath 
1657ca271f4eSPavel Labath   auto it = llvm::find_if(m_threads, [&](const auto &thread_up) {
1658ca271f4eSPavel Labath     return thread_up.get() == &thread;
1659ca271f4eSPavel Labath   });
1660ca271f4eSPavel Labath   assert(it != m_threads.end());
1661af245d11STodd Fiala   m_threads.erase(it);
1662af245d11STodd Fiala 
16630b697561SWalter Erquinigo   NotifyTracersOfThreadDestroyed(thread_id);
16649eb1ecb9SPavel Labath   SignalIfAllThreadsStopped();
1665af245d11STodd Fiala }
1666af245d11STodd Fiala 
16670b697561SWalter Erquinigo Status NativeProcessLinux::NotifyTracersOfNewThread(lldb::tid_t tid) {
16684fa1ad05SPavel Labath   Log *log = GetLog(POSIXLog::Thread);
1669*22077627SJakob Johnson   Status error(m_intel_pt_collector.OnThreadCreated(tid));
16700b697561SWalter Erquinigo   if (error.Fail())
16710b697561SWalter Erquinigo     LLDB_LOG(log, "Failed to trace a new thread with intel-pt, tid = {0}. {1}",
16720b697561SWalter Erquinigo              tid, error.AsCString());
16730b697561SWalter Erquinigo   return error;
16740b697561SWalter Erquinigo }
16750b697561SWalter Erquinigo 
16760b697561SWalter Erquinigo Status NativeProcessLinux::NotifyTracersOfThreadDestroyed(lldb::tid_t tid) {
16774fa1ad05SPavel Labath   Log *log = GetLog(POSIXLog::Thread);
1678*22077627SJakob Johnson   Status error(m_intel_pt_collector.OnThreadDestroyed(tid));
16790b697561SWalter Erquinigo   if (error.Fail())
16800b697561SWalter Erquinigo     LLDB_LOG(log,
16810b697561SWalter Erquinigo              "Failed to stop a destroyed thread with intel-pt, tid = {0}. {1}",
16820b697561SWalter Erquinigo              tid, error.AsCString());
16830b697561SWalter Erquinigo   return error;
16840b697561SWalter Erquinigo }
16850b697561SWalter Erquinigo 
16860b697561SWalter Erquinigo NativeThreadLinux &NativeProcessLinux::AddThread(lldb::tid_t thread_id,
16870b697561SWalter Erquinigo                                                  bool resume) {
16884fa1ad05SPavel Labath   Log *log = GetLog(POSIXLog::Thread);
1689a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
1690af245d11STodd Fiala 
1691b9c1b51eSKate Stone   assert(!HasThreadNoLock(thread_id) &&
1692b9c1b51eSKate Stone          "attempted to add a thread by id that already exists");
1693af245d11STodd Fiala 
1694af245d11STodd Fiala   // If this is the first thread, save it as the current thread
1695af245d11STodd Fiala   if (m_threads.empty())
1696af245d11STodd Fiala     SetCurrentThreadID(thread_id);
1697af245d11STodd Fiala 
1698a8f3ae7cSJonas Devlieghere   m_threads.push_back(std::make_unique<NativeThreadLinux>(*this, thread_id));
16990b697561SWalter Erquinigo   NativeThreadLinux &thread =
17000b697561SWalter Erquinigo       static_cast<NativeThreadLinux &>(*m_threads.back());
170199e37695SRavitheja Addepally 
17020b697561SWalter Erquinigo   Status tracing_error = NotifyTracersOfNewThread(thread.GetID());
17030b697561SWalter Erquinigo   if (tracing_error.Fail()) {
17040b697561SWalter Erquinigo     thread.SetStoppedByProcessorTrace(tracing_error.AsCString());
17050b697561SWalter Erquinigo     StopRunningThreads(thread.GetID());
17060b697561SWalter Erquinigo   } else if (resume)
17070b697561SWalter Erquinigo     ResumeThread(thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
17080b697561SWalter Erquinigo   else
17090b697561SWalter Erquinigo     thread.SetStoppedBySignal(SIGSTOP);
171099e37695SRavitheja Addepally 
17110b697561SWalter Erquinigo   return thread;
1712af245d11STodd Fiala }
1713af245d11STodd Fiala 
171497206d57SZachary Turner Status NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,
1715b9c1b51eSKate Stone                                                    FileSpec &file_spec) {
171697206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
1717a6f5795aSTamas Berghammer   if (error.Fail())
1718a6f5795aSTamas Berghammer     return error;
1719a6f5795aSTamas Berghammer 
17208f3be7a3SJonas Devlieghere   FileSpec module_file_spec(module_path);
17218f3be7a3SJonas Devlieghere   FileSystem::Instance().Resolve(module_file_spec);
17227cb18bf5STamas Berghammer 
17237cb18bf5STamas Berghammer   file_spec.Clear();
1724a6f5795aSTamas Berghammer   for (const auto &it : m_mem_region_cache) {
1725a6f5795aSTamas Berghammer     if (it.second.GetFilename() == module_file_spec.GetFilename()) {
1726a6f5795aSTamas Berghammer       file_spec = it.second;
172797206d57SZachary Turner       return Status();
1728a6f5795aSTamas Berghammer     }
1729a6f5795aSTamas Berghammer   }
173097206d57SZachary Turner   return Status("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
17317cb18bf5STamas Berghammer                 module_file_spec.GetFilename().AsCString(), GetID());
17327cb18bf5STamas Berghammer }
1733c076559aSPavel Labath 
173497206d57SZachary Turner Status NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
1735b9c1b51eSKate Stone                                               lldb::addr_t &load_addr) {
1736783bfc8cSTamas Berghammer   load_addr = LLDB_INVALID_ADDRESS;
173797206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
1738a6f5795aSTamas Berghammer   if (error.Fail())
1739783bfc8cSTamas Berghammer     return error;
1740a6f5795aSTamas Berghammer 
17418f3be7a3SJonas Devlieghere   FileSpec file(file_name);
1742a6f5795aSTamas Berghammer   for (const auto &it : m_mem_region_cache) {
1743a6f5795aSTamas Berghammer     if (it.second == file) {
1744a6f5795aSTamas Berghammer       load_addr = it.first.GetRange().GetRangeBase();
174597206d57SZachary Turner       return Status();
1746a6f5795aSTamas Berghammer     }
1747a6f5795aSTamas Berghammer   }
174897206d57SZachary Turner   return Status("No load address found for specified file.");
1749783bfc8cSTamas Berghammer }
1750783bfc8cSTamas Berghammer 
1751a5be48b3SPavel Labath NativeThreadLinux *NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {
1752a5be48b3SPavel Labath   return static_cast<NativeThreadLinux *>(
1753b9c1b51eSKate Stone       NativeProcessProtocol::GetThreadByID(tid));
1754f9077782SPavel Labath }
1755f9077782SPavel Labath 
17562c4226f8SPavel Labath NativeThreadLinux *NativeProcessLinux::GetCurrentThread() {
17572c4226f8SPavel Labath   return static_cast<NativeThreadLinux *>(
17582c4226f8SPavel Labath       NativeProcessProtocol::GetCurrentThread());
17592c4226f8SPavel Labath }
17602c4226f8SPavel Labath 
176197206d57SZachary Turner Status NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,
1762b9c1b51eSKate Stone                                         lldb::StateType state, int signo) {
17634fa1ad05SPavel Labath   Log *const log = GetLog(POSIXLog::Thread);
1764a6321a8eSPavel Labath   LLDB_LOG(log, "tid: {0}", thread.GetID());
1765c076559aSPavel Labath 
176605097246SAdrian Prantl   // Before we do the resume below, first check if we have a pending stop
176705097246SAdrian Prantl   // notification that is currently waiting for all threads to stop.  This is
176805097246SAdrian Prantl   // potentially a buggy situation since we're ostensibly waiting for threads
176905097246SAdrian Prantl   // to stop before we send out the pending notification, and here we are
177005097246SAdrian Prantl   // resuming one before we send out the pending stop notification.
1771a6321a8eSPavel Labath   if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
1772a6321a8eSPavel Labath     LLDB_LOG(log,
1773a6321a8eSPavel Labath              "about to resume tid {0} per explicit request but we have a "
1774a6321a8eSPavel Labath              "pending stop notification (tid {1}) that is actively "
1775a6321a8eSPavel Labath              "waiting for this thread to stop. Valid sequence of events?",
1776a6321a8eSPavel Labath              thread.GetID(), m_pending_notification_tid);
1777c076559aSPavel Labath   }
1778c076559aSPavel Labath 
177905097246SAdrian Prantl   // Request a resume.  We expect this to be synchronous and the system to
178005097246SAdrian Prantl   // reflect it is running after this completes.
1781b9c1b51eSKate Stone   switch (state) {
1782b9c1b51eSKate Stone   case eStateRunning: {
1783605b51b8SPavel Labath     const auto resume_result = thread.Resume(signo);
17840e1d729bSPavel Labath     if (resume_result.Success())
17850e1d729bSPavel Labath       SetState(eStateRunning, true);
17860e1d729bSPavel Labath     return resume_result;
1787c076559aSPavel Labath   }
1788b9c1b51eSKate Stone   case eStateStepping: {
1789605b51b8SPavel Labath     const auto step_result = thread.SingleStep(signo);
17900e1d729bSPavel Labath     if (step_result.Success())
17910e1d729bSPavel Labath       SetState(eStateRunning, true);
17920e1d729bSPavel Labath     return step_result;
17930e1d729bSPavel Labath   }
17940e1d729bSPavel Labath   default:
17958198db30SPavel Labath     LLDB_LOG(log, "Unhandled state {0}.", state);
17960e1d729bSPavel Labath     llvm_unreachable("Unhandled state for resume");
17970e1d729bSPavel Labath   }
1798c076559aSPavel Labath }
1799c076559aSPavel Labath 
1800c076559aSPavel Labath //===----------------------------------------------------------------------===//
1801c076559aSPavel Labath 
1802b9c1b51eSKate Stone void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {
18034fa1ad05SPavel Labath   Log *const log = GetLog(POSIXLog::Thread);
1804a6321a8eSPavel Labath   LLDB_LOG(log, "about to process event: (triggering_tid: {0})",
1805a6321a8eSPavel Labath            triggering_tid);
1806c076559aSPavel Labath 
18070e1d729bSPavel Labath   m_pending_notification_tid = triggering_tid;
18080e1d729bSPavel Labath 
180905097246SAdrian Prantl   // Request a stop for all the thread stops that need to be stopped and are
181005097246SAdrian Prantl   // not already known to be stopped.
1811a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
1812a5be48b3SPavel Labath     if (StateIsRunningState(thread->GetState()))
1813a5be48b3SPavel Labath       static_cast<NativeThreadLinux *>(thread.get())->RequestStop();
18140e1d729bSPavel Labath   }
18150e1d729bSPavel Labath 
18160e1d729bSPavel Labath   SignalIfAllThreadsStopped();
1817a6321a8eSPavel Labath   LLDB_LOG(log, "event processing done");
1818c076559aSPavel Labath }
1819c076559aSPavel Labath 
1820b9c1b51eSKate Stone void NativeProcessLinux::SignalIfAllThreadsStopped() {
18210e1d729bSPavel Labath   if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
18220e1d729bSPavel Labath     return; // No pending notification. Nothing to do.
18230e1d729bSPavel Labath 
1824b9c1b51eSKate Stone   for (const auto &thread_sp : m_threads) {
18250e1d729bSPavel Labath     if (StateIsRunningState(thread_sp->GetState()))
18260e1d729bSPavel Labath       return; // Some threads are still running. Don't signal yet.
18270e1d729bSPavel Labath   }
18280e1d729bSPavel Labath 
18290e1d729bSPavel Labath   // We have a pending notification and all threads have stopped.
1830a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Process | LLDBLog::Breakpoints);
18319eb1ecb9SPavel Labath 
1832b9c1b51eSKate Stone   // Clear any temporary breakpoints we used to implement software single
1833b9c1b51eSKate Stone   // stepping.
1834b9c1b51eSKate Stone   for (const auto &thread_info : m_threads_stepping_with_breakpoint) {
183597206d57SZachary Turner     Status error = RemoveBreakpoint(thread_info.second);
18369eb1ecb9SPavel Labath     if (error.Fail())
1837a6321a8eSPavel Labath       LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}",
1838a6321a8eSPavel Labath                thread_info.first, error);
18399eb1ecb9SPavel Labath   }
18409eb1ecb9SPavel Labath   m_threads_stepping_with_breakpoint.clear();
18419eb1ecb9SPavel Labath 
18429eb1ecb9SPavel Labath   // Notify the delegate about the stop
18430e1d729bSPavel Labath   SetCurrentThreadID(m_pending_notification_tid);
1844ed89c7feSPavel Labath   SetState(StateType::eStateStopped, true);
18450e1d729bSPavel Labath   m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
1846c076559aSPavel Labath }
1847c076559aSPavel Labath 
1848b9c1b51eSKate Stone void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {
18494fa1ad05SPavel Labath   Log *const log = GetLog(POSIXLog::Thread);
1850a6321a8eSPavel Labath   LLDB_LOG(log, "tid: {0}", thread.GetID());
18511dbc6c9cSPavel Labath 
1852b9c1b51eSKate Stone   if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID &&
1853b9c1b51eSKate Stone       StateIsRunningState(thread.GetState())) {
1854b9c1b51eSKate Stone     // We will need to wait for this new thread to stop as well before firing
185505097246SAdrian Prantl     // the notification.
1856f9077782SPavel Labath     thread.RequestStop();
1857c076559aSPavel Labath   }
1858c076559aSPavel Labath }
1859068f8a7eSTamas Berghammer 
1860b9c1b51eSKate Stone void NativeProcessLinux::SigchldHandler() {
18614fa1ad05SPavel Labath   Log *log = GetLog(POSIXLog::Process);
1862ca271f4eSPavel Labath 
1863ca271f4eSPavel Labath   // Threads can appear or disappear as a result of event processing, so gather
1864ca271f4eSPavel Labath   // the events upfront.
1865ca271f4eSPavel Labath   llvm::DenseMap<lldb::tid_t, WaitStatus> tid_events;
1866ca271f4eSPavel Labath   for (const auto &thread_up : m_threads) {
186719cbe96aSPavel Labath     int status = -1;
1868ca271f4eSPavel Labath     ::pid_t wait_pid =
1869ca271f4eSPavel Labath         llvm::sys::RetryAfterSignal(-1, ::waitpid, thread_up->GetID(), &status,
1870c1a6b128SPavel Labath                                     __WALL | __WNOTHREAD | WNOHANG);
187119cbe96aSPavel Labath 
187219cbe96aSPavel Labath     if (wait_pid == 0)
1873ca271f4eSPavel Labath       continue; // Nothing to do for this thread.
187419cbe96aSPavel Labath 
1875b9c1b51eSKate Stone     if (wait_pid == -1) {
187697206d57SZachary Turner       Status error(errno, eErrorTypePOSIX);
1877ca271f4eSPavel Labath       LLDB_LOG(log, "waitpid({0}, &status, _) failed: {1}", thread_up->GetID(),
1878ca271f4eSPavel Labath                error);
1879ca271f4eSPavel Labath       continue;
188019cbe96aSPavel Labath     }
188119cbe96aSPavel Labath 
1882ca271f4eSPavel Labath     assert(wait_pid == static_cast<::pid_t>(thread_up->GetID()));
1883ca271f4eSPavel Labath 
18843508fc8cSPavel Labath     WaitStatus wait_status = WaitStatus::Decode(status);
188519cbe96aSPavel Labath 
1886ca271f4eSPavel Labath     LLDB_LOG(log, "waitpid({0})  got status = {1}", thread_up->GetID(),
1887ca271f4eSPavel Labath              wait_status);
1888ca271f4eSPavel Labath     tid_events.try_emplace(thread_up->GetID(), wait_status);
1889ca271f4eSPavel Labath   }
189019cbe96aSPavel Labath 
1891ca271f4eSPavel Labath   for (auto &KV : tid_events) {
1892ca271f4eSPavel Labath     LLDB_LOG(log, "processing {0}({1}) ...", KV.first, KV.second);
1893ca271f4eSPavel Labath     NativeThreadLinux *thread = GetThreadByID(KV.first);
1894ca271f4eSPavel Labath     if (thread) {
1895ca271f4eSPavel Labath       MonitorCallback(*thread, KV.second);
1896ca271f4eSPavel Labath     } else {
1897ca271f4eSPavel Labath       // This can happen if one of the events is an main thread exit.
1898ca271f4eSPavel Labath       LLDB_LOG(log, "... but the thread has disappeared");
1899ca271f4eSPavel Labath     }
190019cbe96aSPavel Labath   }
1901068f8a7eSTamas Berghammer }
1902068f8a7eSTamas Berghammer 
190305097246SAdrian Prantl // Wrapper for ptrace to catch errors and log calls. Note that ptrace sets
190405097246SAdrian Prantl // errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
190597206d57SZachary Turner Status NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
1906b9c1b51eSKate Stone                                          void *data, size_t data_size,
1907b9c1b51eSKate Stone                                          long *result) {
190897206d57SZachary Turner   Status error;
19094a9babb2SPavel Labath   long int ret;
1910068f8a7eSTamas Berghammer 
19114fa1ad05SPavel Labath   Log *log = GetLog(POSIXLog::Ptrace);
1912068f8a7eSTamas Berghammer 
1913068f8a7eSTamas Berghammer   PtraceDisplayBytes(req, data, data_size);
1914068f8a7eSTamas Berghammer 
1915068f8a7eSTamas Berghammer   errno = 0;
1916068f8a7eSTamas Berghammer   if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
1917b9c1b51eSKate Stone     ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
1918b9c1b51eSKate Stone                  *(unsigned int *)addr, data);
1919068f8a7eSTamas Berghammer   else
1920b9c1b51eSKate Stone     ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
1921b9c1b51eSKate Stone                  addr, data);
1922068f8a7eSTamas Berghammer 
19234a9babb2SPavel Labath   if (ret == -1)
1924068f8a7eSTamas Berghammer     error.SetErrorToErrno();
1925068f8a7eSTamas Berghammer 
19264a9babb2SPavel Labath   if (result)
19274a9babb2SPavel Labath     *result = ret;
19284a9babb2SPavel Labath 
192928096200SPavel Labath   LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data,
193028096200SPavel Labath            data_size, ret);
1931068f8a7eSTamas Berghammer 
1932068f8a7eSTamas Berghammer   PtraceDisplayBytes(req, data, data_size);
1933068f8a7eSTamas Berghammer 
1934a6321a8eSPavel Labath   if (error.Fail())
1935a6321a8eSPavel Labath     LLDB_LOG(log, "ptrace() failed: {0}", error);
1936068f8a7eSTamas Berghammer 
19374a9babb2SPavel Labath   return error;
1938068f8a7eSTamas Berghammer }
193999e37695SRavitheja Addepally 
19400b697561SWalter Erquinigo llvm::Expected<TraceSupportedResponse> NativeProcessLinux::TraceSupported() {
1941*22077627SJakob Johnson   if (IntelPTCollector::IsSupported())
19420b697561SWalter Erquinigo     return TraceSupportedResponse{"intel-pt", "Intel Processor Trace"};
19430b697561SWalter Erquinigo   return NativeProcessProtocol::TraceSupported();
194499e37695SRavitheja Addepally }
194599e37695SRavitheja Addepally 
19460b697561SWalter Erquinigo Error NativeProcessLinux::TraceStart(StringRef json_request, StringRef type) {
19470b697561SWalter Erquinigo   if (type == "intel-pt") {
19480b697561SWalter Erquinigo     if (Expected<TraceIntelPTStartRequest> request =
19490b697561SWalter Erquinigo             json::parse<TraceIntelPTStartRequest>(json_request,
19500b697561SWalter Erquinigo                                                   "TraceIntelPTStartRequest")) {
19510b697561SWalter Erquinigo       std::vector<lldb::tid_t> process_threads;
19520b697561SWalter Erquinigo       for (auto &thread : m_threads)
19530b697561SWalter Erquinigo         process_threads.push_back(thread->GetID());
1954*22077627SJakob Johnson       return m_intel_pt_collector.TraceStart(*request, process_threads);
19550b697561SWalter Erquinigo     } else
19560b697561SWalter Erquinigo       return request.takeError();
195799e37695SRavitheja Addepally   }
195899e37695SRavitheja Addepally 
19590b697561SWalter Erquinigo   return NativeProcessProtocol::TraceStart(json_request, type);
196099e37695SRavitheja Addepally }
196199e37695SRavitheja Addepally 
19620b697561SWalter Erquinigo Error NativeProcessLinux::TraceStop(const TraceStopRequest &request) {
19630b697561SWalter Erquinigo   if (request.type == "intel-pt")
1964*22077627SJakob Johnson     return m_intel_pt_collector.TraceStop(request);
19650b697561SWalter Erquinigo   return NativeProcessProtocol::TraceStop(request);
196699e37695SRavitheja Addepally }
196799e37695SRavitheja Addepally 
19680b697561SWalter Erquinigo Expected<json::Value> NativeProcessLinux::TraceGetState(StringRef type) {
19690b697561SWalter Erquinigo   if (type == "intel-pt")
1970*22077627SJakob Johnson     return m_intel_pt_collector.GetState();
19710b697561SWalter Erquinigo   return NativeProcessProtocol::TraceGetState(type);
197299e37695SRavitheja Addepally }
197399e37695SRavitheja Addepally 
19740b697561SWalter Erquinigo Expected<std::vector<uint8_t>> NativeProcessLinux::TraceGetBinaryData(
19750b697561SWalter Erquinigo     const TraceGetBinaryDataRequest &request) {
19760b697561SWalter Erquinigo   if (request.type == "intel-pt")
1977*22077627SJakob Johnson     return m_intel_pt_collector.GetBinaryData(request);
19780b697561SWalter Erquinigo   return NativeProcessProtocol::TraceGetBinaryData(request);
197999e37695SRavitheja Addepally }
1980