180814287SRaphael Isemann //===-- NativeProcessLinux.cpp --------------------------------------------===// 2af245d11STodd Fiala // 32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information. 52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6af245d11STodd Fiala // 7af245d11STodd Fiala //===----------------------------------------------------------------------===// 8af245d11STodd Fiala 9af245d11STodd Fiala #include "NativeProcessLinux.h" 10af245d11STodd Fiala 1176e47d48SRaphael Isemann #include <cerrno> 1276e47d48SRaphael Isemann #include <cstdint> 1376e47d48SRaphael Isemann #include <cstring> 14af245d11STodd Fiala #include <unistd.h> 15af245d11STodd Fiala 16af245d11STodd Fiala #include <fstream> 17df7c6995SPavel Labath #include <mutex> 18c076559aSPavel Labath #include <sstream> 19af245d11STodd Fiala #include <string> 205b981ab9SPavel Labath #include <unordered_map> 21af245d11STodd Fiala 222c4226f8SPavel Labath #include "NativeThreadLinux.h" 232c4226f8SPavel Labath #include "Plugins/Process/POSIX/ProcessPOSIXLog.h" 242c4226f8SPavel Labath #include "Plugins/Process/Utility/LinuxProcMaps.h" 252c4226f8SPavel Labath #include "Procfs.h" 266edef204SOleksiy Vyalov #include "lldb/Core/ModuleSpec.h" 27af245d11STodd Fiala #include "lldb/Host/Host.h" 285ad891f7SPavel Labath #include "lldb/Host/HostProcess.h" 29eef758e9SPavel Labath #include "lldb/Host/ProcessLaunchInfo.h" 3024ae6294SZachary Turner #include "lldb/Host/PseudoTerminal.h" 3139de3110SZachary Turner #include "lldb/Host/ThreadLauncher.h" 322a86b555SPavel Labath #include "lldb/Host/common/NativeRegisterContext.h" 33c8d18cbaSMichał Górny #include "lldb/Host/linux/Host.h" 344ee1c952SPavel Labath #include "lldb/Host/linux/Ptrace.h" 354ee1c952SPavel Labath #include "lldb/Host/linux/Uio.h" 36816ae4b0SKamil Rytarowski #include "lldb/Host/posix/ProcessLauncherPosixFork.h" 372a86b555SPavel Labath #include "lldb/Symbol/ObjectFile.h" 3890aff47cSZachary Turner #include "lldb/Target/Process.h" 395b981ab9SPavel Labath #include "lldb/Target/Target.h" 40c16f5dcaSChaoren Lin #include "lldb/Utility/LLDBAssert.h" 41d821c997SPavel Labath #include "lldb/Utility/State.h" 4297206d57SZachary Turner #include "lldb/Utility/Status.h" 43f805e190SPavel Labath #include "lldb/Utility/StringExtractor.h" 442c4226f8SPavel Labath #include "llvm/ADT/ScopeExit.h" 4510c41f37SPavel Labath #include "llvm/Support/Errno.h" 4610c41f37SPavel Labath #include "llvm/Support/FileSystem.h" 4710c41f37SPavel Labath #include "llvm/Support/Threading.h" 48af245d11STodd Fiala 49d858487eSTamas Berghammer #include <linux/unistd.h> 50d858487eSTamas Berghammer #include <sys/socket.h> 51df7c6995SPavel Labath #include <sys/syscall.h> 52d858487eSTamas Berghammer #include <sys/types.h> 53d858487eSTamas Berghammer #include <sys/user.h> 54d858487eSTamas Berghammer #include <sys/wait.h> 55d858487eSTamas Berghammer 56*8d58fbd0SDavid Spickett #ifdef __aarch64__ 57*8d58fbd0SDavid Spickett #include <asm/hwcap.h> 58*8d58fbd0SDavid Spickett #include <sys/auxv.h> 59*8d58fbd0SDavid Spickett #endif 60*8d58fbd0SDavid Spickett 61af245d11STodd Fiala // Support hardware breakpoints in case it has not been defined 62af245d11STodd Fiala #ifndef TRAP_HWBKPT 63af245d11STodd Fiala #define TRAP_HWBKPT 4 64af245d11STodd Fiala #endif 65af245d11STodd Fiala 66*8d58fbd0SDavid Spickett #ifndef HWCAP2_MTE 67*8d58fbd0SDavid Spickett #define HWCAP2_MTE (1 << 18) 68*8d58fbd0SDavid Spickett #endif 69*8d58fbd0SDavid Spickett 707cb18bf5STamas Berghammer using namespace lldb; 717cb18bf5STamas Berghammer using namespace lldb_private; 72db264a6dSTamas Berghammer using namespace lldb_private::process_linux; 737cb18bf5STamas Berghammer using namespace llvm; 747cb18bf5STamas Berghammer 75af245d11STodd Fiala // Private bits we only need internally. 76df7c6995SPavel Labath 77b9c1b51eSKate Stone static bool ProcessVmReadvSupported() { 78df7c6995SPavel Labath static bool is_supported; 79c5f28e2aSKamil Rytarowski static llvm::once_flag flag; 80df7c6995SPavel Labath 81c5f28e2aSKamil Rytarowski llvm::call_once(flag, [] { 82a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 83df7c6995SPavel Labath 84df7c6995SPavel Labath uint32_t source = 0x47424742; 85df7c6995SPavel Labath uint32_t dest = 0; 86df7c6995SPavel Labath 87df7c6995SPavel Labath struct iovec local, remote; 88df7c6995SPavel Labath remote.iov_base = &source; 89df7c6995SPavel Labath local.iov_base = &dest; 90df7c6995SPavel Labath remote.iov_len = local.iov_len = sizeof source; 91df7c6995SPavel Labath 92b9c1b51eSKate Stone // We shall try if cross-process-memory reads work by attempting to read a 93b9c1b51eSKate Stone // value from our own process. 94df7c6995SPavel Labath ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0); 95df7c6995SPavel Labath is_supported = (res == sizeof(source) && source == dest); 96df7c6995SPavel Labath if (is_supported) 97a6321a8eSPavel Labath LLDB_LOG(log, 98a6321a8eSPavel Labath "Detected kernel support for process_vm_readv syscall. " 99a6321a8eSPavel Labath "Fast memory reads enabled."); 100df7c6995SPavel Labath else 101a6321a8eSPavel Labath LLDB_LOG(log, 102a6321a8eSPavel Labath "syscall process_vm_readv failed (error: {0}). Fast memory " 103a6321a8eSPavel Labath "reads disabled.", 10410c41f37SPavel Labath llvm::sys::StrError()); 105df7c6995SPavel Labath }); 106df7c6995SPavel Labath 107df7c6995SPavel Labath return is_supported; 108df7c6995SPavel Labath } 109df7c6995SPavel Labath 110b9c1b51eSKate Stone namespace { 111b9c1b51eSKate Stone void MaybeLogLaunchInfo(const ProcessLaunchInfo &info) { 112a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_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 137b9c1b51eSKate Stone 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 146b9c1b51eSKate Stone void PtraceDisplayBytes(int &req, void *data, size_t data_size) { 147aafe053cSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_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 } // end of anonymous namespace 1971107b5a5SPavel Labath 198bd7cbc5aSPavel Labath // Simple helper function to ensure flags are enabled on the given file 199bd7cbc5aSPavel Labath // descriptor. 20097206d57SZachary Turner static Status EnsureFDFlags(int fd, int flags) { 20197206d57SZachary Turner Status error; 202bd7cbc5aSPavel Labath 203bd7cbc5aSPavel Labath int status = fcntl(fd, F_GETFL); 204b9c1b51eSKate Stone if (status == -1) { 205bd7cbc5aSPavel Labath error.SetErrorToErrno(); 206bd7cbc5aSPavel Labath return error; 207bd7cbc5aSPavel Labath } 208bd7cbc5aSPavel Labath 209b9c1b51eSKate Stone if (fcntl(fd, F_SETFL, status | flags) == -1) { 210bd7cbc5aSPavel Labath error.SetErrorToErrno(); 211bd7cbc5aSPavel Labath return error; 212bd7cbc5aSPavel Labath } 213bd7cbc5aSPavel Labath 214bd7cbc5aSPavel Labath return error; 215bd7cbc5aSPavel Labath } 216bd7cbc5aSPavel Labath 217af245d11STodd Fiala // Public Static Methods 218af245d11STodd Fiala 21982abefa4SPavel Labath llvm::Expected<std::unique_ptr<NativeProcessProtocol>> 22096e600fcSPavel Labath NativeProcessLinux::Factory::Launch(ProcessLaunchInfo &launch_info, 22196e600fcSPavel Labath NativeDelegate &native_delegate, 22296e600fcSPavel Labath MainLoop &mainloop) const { 223a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 224af245d11STodd Fiala 22596e600fcSPavel Labath MaybeLogLaunchInfo(launch_info); 226af245d11STodd Fiala 22796e600fcSPavel Labath Status status; 22896e600fcSPavel Labath ::pid_t pid = ProcessLauncherPosixFork() 22996e600fcSPavel Labath .LaunchProcess(launch_info, status) 23096e600fcSPavel Labath .GetProcessId(); 23196e600fcSPavel Labath LLDB_LOG(log, "pid = {0:x}", pid); 23296e600fcSPavel Labath if (status.Fail()) { 23396e600fcSPavel Labath LLDB_LOG(log, "failed to launch process: {0}", status); 23496e600fcSPavel Labath return status.ToError(); 235af245d11STodd Fiala } 236af245d11STodd Fiala 23796e600fcSPavel Labath // Wait for the child process to trap on its call to execve. 23896e600fcSPavel Labath int wstatus; 23996e600fcSPavel Labath ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0); 24096e600fcSPavel Labath assert(wpid == pid); 24196e600fcSPavel Labath (void)wpid; 24296e600fcSPavel Labath if (!WIFSTOPPED(wstatus)) { 24396e600fcSPavel Labath LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}", 24496e600fcSPavel Labath WaitStatus::Decode(wstatus)); 24596e600fcSPavel Labath return llvm::make_error<StringError>("Could not sync with inferior process", 24696e600fcSPavel Labath llvm::inconvertibleErrorCode()); 24796e600fcSPavel Labath } 24896e600fcSPavel Labath LLDB_LOG(log, "inferior started, now in stopped state"); 249af245d11STodd Fiala 25036e82208SPavel Labath ProcessInstanceInfo Info; 25136e82208SPavel Labath if (!Host::GetProcessInfo(pid, Info)) { 25236e82208SPavel Labath return llvm::make_error<StringError>("Cannot get process architecture", 25336e82208SPavel Labath llvm::inconvertibleErrorCode()); 25436e82208SPavel Labath } 25596e600fcSPavel Labath 25696e600fcSPavel Labath // Set the architecture to the exe architecture. 25796e600fcSPavel Labath LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid, 25836e82208SPavel Labath Info.GetArchitecture().GetArchitectureName()); 25996e600fcSPavel Labath 26096e600fcSPavel Labath status = SetDefaultPtraceOpts(pid); 26196e600fcSPavel Labath if (status.Fail()) { 26296e600fcSPavel Labath LLDB_LOG(log, "failed to set default ptrace options: {0}", status); 26396e600fcSPavel Labath return status.ToError(); 264af245d11STodd Fiala } 265af245d11STodd Fiala 26682abefa4SPavel Labath return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux( 26764ec505dSJonas Devlieghere pid, launch_info.GetPTY().ReleasePrimaryFileDescriptor(), native_delegate, 26836e82208SPavel Labath Info.GetArchitecture(), mainloop, {pid})); 269af245d11STodd Fiala } 270af245d11STodd Fiala 27182abefa4SPavel Labath llvm::Expected<std::unique_ptr<NativeProcessProtocol>> 27282abefa4SPavel Labath NativeProcessLinux::Factory::Attach( 273b9c1b51eSKate Stone lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate, 27496e600fcSPavel Labath MainLoop &mainloop) const { 275a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 276a6321a8eSPavel Labath LLDB_LOG(log, "pid = {0:x}", pid); 277af245d11STodd Fiala 278af245d11STodd Fiala // Retrieve the architecture for the running process. 27936e82208SPavel Labath ProcessInstanceInfo Info; 28036e82208SPavel Labath if (!Host::GetProcessInfo(pid, Info)) { 28136e82208SPavel Labath return llvm::make_error<StringError>("Cannot get process architecture", 28236e82208SPavel Labath llvm::inconvertibleErrorCode()); 28336e82208SPavel Labath } 284af245d11STodd Fiala 28596e600fcSPavel Labath auto tids_or = NativeProcessLinux::Attach(pid); 28696e600fcSPavel Labath if (!tids_or) 28796e600fcSPavel Labath return tids_or.takeError(); 288af245d11STodd Fiala 28982abefa4SPavel Labath return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux( 29036e82208SPavel Labath pid, -1, native_delegate, Info.GetArchitecture(), mainloop, *tids_or)); 291af245d11STodd Fiala } 292af245d11STodd Fiala 293fd0af0cfSMichał Górny NativeProcessLinux::Extension 294fd0af0cfSMichał Górny NativeProcessLinux::Factory::GetSupportedExtensions() const { 295*8d58fbd0SDavid Spickett NativeProcessLinux::Extension supported = 296*8d58fbd0SDavid Spickett Extension::multiprocess | Extension::fork | Extension::vfork | 297ca7824c2SMichał Górny Extension::pass_signals | Extension::auxv | Extension::libraries_svr4; 298*8d58fbd0SDavid Spickett 299*8d58fbd0SDavid Spickett #ifdef __aarch64__ 300*8d58fbd0SDavid Spickett // At this point we do not have a process so read auxv directly. 301*8d58fbd0SDavid Spickett if ((getauxval(AT_HWCAP2) & HWCAP2_MTE)) 302*8d58fbd0SDavid Spickett supported |= Extension::memory_tagging; 303*8d58fbd0SDavid Spickett #endif 304*8d58fbd0SDavid Spickett 305*8d58fbd0SDavid 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), 315fd0af0cfSMichał Górny m_main_loop(mainloop), m_intel_pt_manager(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) { 340a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_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. 431b9c1b51eSKate Stone void NativeProcessLinux::MonitorCallback(lldb::pid_t pid, bool exited, 4323508fc8cSPavel Labath WaitStatus status) { 433af245d11STodd Fiala Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 434af245d11STodd Fiala 435b9c1b51eSKate Stone // Certain activities differ based on whether the pid is the tid of the main 436b9c1b51eSKate Stone // thread. 4371107b5a5SPavel Labath const bool is_main_thread = (pid == GetID()); 438af245d11STodd Fiala 439af245d11STodd Fiala // Handle when the thread exits. 440b9c1b51eSKate Stone if (exited) { 441d8b3c1a1SPavel Labath LLDB_LOG(log, 4429303afb3SPavel Labath "got exit status({0}) , tid = {1} ({2} main thread), process " 443d8b3c1a1SPavel Labath "state = {3}", 4449303afb3SPavel Labath status, pid, is_main_thread ? "is" : "is not", GetState()); 445af245d11STodd Fiala 446af245d11STodd Fiala // This is a thread that exited. Ensure we're not tracking it anymore. 447d8b3c1a1SPavel Labath StopTrackingThread(pid); 448af245d11STodd Fiala 449b9c1b51eSKate Stone if (is_main_thread) { 450af245d11STodd Fiala // The main thread exited. We're done monitoring. Report to delegate. 4513508fc8cSPavel Labath SetExitStatus(status, true); 452af245d11STodd Fiala 453af245d11STodd Fiala // Notify delegate that our process has exited. 4541107b5a5SPavel Labath SetState(StateType::eStateExited, true); 455af245d11STodd Fiala } 4561107b5a5SPavel Labath return; 457af245d11STodd Fiala } 458af245d11STodd Fiala 459af245d11STodd Fiala siginfo_t info; 460b9cc0c75SPavel Labath const auto info_err = GetSignalInfo(pid, &info); 461b9cc0c75SPavel Labath auto thread_sp = GetThreadByID(pid); 462b9cc0c75SPavel Labath 463b9c1b51eSKate Stone if (!thread_sp) { 46405097246SAdrian Prantl // Normally, the only situation when we cannot find the thread is if we 46505097246SAdrian Prantl // have just received a new thread notification. This is indicated by 466a6321a8eSPavel Labath // GetSignalInfo() returning si_code == SI_USER and si_pid == 0 467a6321a8eSPavel Labath LLDB_LOG(log, "received notification about an unknown tid {0}.", pid); 468b9cc0c75SPavel Labath 469b9c1b51eSKate Stone if (info_err.Fail()) { 470a6321a8eSPavel Labath LLDB_LOG(log, 471a6321a8eSPavel Labath "(tid {0}) GetSignalInfo failed ({1}). " 472a6321a8eSPavel Labath "Ingoring this notification.", 473a6321a8eSPavel Labath pid, info_err); 474b9cc0c75SPavel Labath return; 475b9cc0c75SPavel Labath } 476b9cc0c75SPavel Labath 477a6321a8eSPavel Labath LLDB_LOG(log, "tid {0}, si_code: {1}, si_pid: {2}", pid, info.si_code, 478a6321a8eSPavel Labath info.si_pid); 479b9cc0c75SPavel Labath 480c8d18cbaSMichał Górny MonitorClone(pid, llvm::None); 481b9cc0c75SPavel Labath return; 482b9cc0c75SPavel Labath } 483b9cc0c75SPavel Labath 484b9cc0c75SPavel Labath // Get details on the signal raised. 485b9c1b51eSKate Stone if (info_err.Success()) { 486fa03ad2eSChaoren Lin // We have retrieved the signal info. Dispatch appropriately. 487fa03ad2eSChaoren Lin if (info.si_signo == SIGTRAP) 488b9cc0c75SPavel Labath MonitorSIGTRAP(info, *thread_sp); 489fa03ad2eSChaoren Lin else 490b9cc0c75SPavel Labath MonitorSignal(info, *thread_sp, exited); 491b9c1b51eSKate Stone } else { 492b9c1b51eSKate Stone if (info_err.GetError() == EINVAL) { 49305097246SAdrian Prantl // This is a group stop reception for this tid. We can reach here if we 49405097246SAdrian Prantl // reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the tracee, 49505097246SAdrian Prantl // triggering the group-stop mechanism. Normally receiving these would 49605097246SAdrian Prantl // stop the process, pending a SIGCONT. Simulating this state in a 49705097246SAdrian Prantl // debugger is hard and is generally not needed (one use case is 49805097246SAdrian Prantl // debugging background task being managed by a shell). For general use, 49905097246SAdrian Prantl // it is sufficient to stop the process in a signal-delivery stop which 50005097246SAdrian Prantl // happens before the group stop. This done by MonitorSignal and works 50105097246SAdrian Prantl // correctly for all signals. 502a6321a8eSPavel Labath LLDB_LOG(log, 503a6321a8eSPavel Labath "received a group stop for pid {0} tid {1}. Transparent " 504a6321a8eSPavel Labath "handling of group stops not supported, resuming the " 505a6321a8eSPavel Labath "thread.", 506a6321a8eSPavel Labath GetID(), pid); 507b9c1b51eSKate Stone ResumeThread(*thread_sp, thread_sp->GetState(), 508b9c1b51eSKate Stone LLDB_INVALID_SIGNAL_NUMBER); 509b9c1b51eSKate Stone } else { 510af245d11STodd Fiala // ptrace(GETSIGINFO) failed (but not due to group-stop). 511af245d11STodd Fiala 512b9c1b51eSKate Stone // A return value of ESRCH means the thread/process is no longer on the 513a6321a8eSPavel Labath // system, so it was killed somehow outside of our control. Either way, 514a6321a8eSPavel Labath // we can't do anything with it anymore. 515af245d11STodd Fiala 516b9c1b51eSKate Stone // Stop tracking the metadata for the thread since it's entirely off the 517b9c1b51eSKate Stone // system now. 5181107b5a5SPavel Labath const bool thread_found = StopTrackingThread(pid); 519af245d11STodd Fiala 520a6321a8eSPavel Labath LLDB_LOG(log, 5219303afb3SPavel Labath "GetSignalInfo failed: {0}, tid = {1}, status = {2}, " 522a6321a8eSPavel Labath "status = {3}, main_thread = {4}, thread_found: {5}", 5239303afb3SPavel Labath info_err, pid, status, status, is_main_thread, thread_found); 524af245d11STodd Fiala 525b9c1b51eSKate Stone if (is_main_thread) { 526b9c1b51eSKate Stone // Notify the delegate - our process is not available but appears to 52705097246SAdrian Prantl // have been killed outside our control. Is eStateExited the right 52805097246SAdrian Prantl // exit state in this case? 5293508fc8cSPavel Labath SetExitStatus(status, true); 5301107b5a5SPavel Labath SetState(StateType::eStateExited, true); 531b9c1b51eSKate Stone } else { 532b9c1b51eSKate Stone // This thread was pulled out from underneath us. Anything to do here? 533b9c1b51eSKate Stone // Do we want to do an all stop? 534a6321a8eSPavel Labath LLDB_LOG(log, 535a6321a8eSPavel Labath "pid {0} tid {1} non-main thread exit occurred, didn't " 536a6321a8eSPavel Labath "tell delegate anything since thread disappeared out " 537a6321a8eSPavel Labath "from underneath us", 538a6321a8eSPavel Labath GetID(), pid); 539af245d11STodd Fiala } 540af245d11STodd Fiala } 541af245d11STodd Fiala } 542af245d11STodd Fiala } 543af245d11STodd Fiala 544c8d18cbaSMichał Górny void NativeProcessLinux::WaitForCloneNotification(::pid_t pid) { 545a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 546426bdf88SPavel Labath 547c8d18cbaSMichał Górny // The PID is not tracked yet, let's wait for it to appear. 548426bdf88SPavel Labath int status = -1; 549a6321a8eSPavel Labath LLDB_LOG(log, 550c8d18cbaSMichał Górny "received clone event for pid {0}. pid not tracked yet, " 551c8d18cbaSMichał Górny "waiting for it to appear...", 552c8d18cbaSMichał Górny pid); 553c8d18cbaSMichał Górny ::pid_t wait_pid = 554c8d18cbaSMichał Górny llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &status, __WALL); 555c8d18cbaSMichał Górny // Since we are waiting on a specific pid, this must be the creation event. 556a6321a8eSPavel Labath // But let's do some checks just in case. 557c8d18cbaSMichał Górny if (wait_pid != pid) { 558a6321a8eSPavel Labath LLDB_LOG(log, 559c8d18cbaSMichał Górny "waiting for pid {0} failed. Assuming the pid has " 560a6321a8eSPavel Labath "disappeared in the meantime", 561c8d18cbaSMichał Górny pid); 562426bdf88SPavel Labath // The only way I know of this could happen is if the whole process was 563b9c1b51eSKate Stone // SIGKILLed in the mean time. In any case, we can't do anything about that 564b9c1b51eSKate Stone // now. 565426bdf88SPavel Labath return; 566426bdf88SPavel Labath } 567b9c1b51eSKate Stone if (WIFEXITED(status)) { 568a6321a8eSPavel Labath LLDB_LOG(log, 569c8d18cbaSMichał Górny "waiting for pid {0} returned an 'exited' event. Not " 570c8d18cbaSMichał Górny "tracking it.", 571c8d18cbaSMichał Górny pid); 572426bdf88SPavel Labath // Also a very improbable event. 573c8d18cbaSMichał Górny m_pending_pid_map.erase(pid); 574426bdf88SPavel Labath return; 575426bdf88SPavel Labath } 576426bdf88SPavel Labath 577c8d18cbaSMichał Górny MonitorClone(pid, llvm::None); 578426bdf88SPavel Labath } 579426bdf88SPavel Labath 580b9c1b51eSKate Stone void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info, 581b9c1b51eSKate Stone NativeThreadLinux &thread) { 582a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 583b9cc0c75SPavel Labath const bool is_main_thread = (thread.GetID() == GetID()); 584af245d11STodd Fiala 585b9cc0c75SPavel Labath assert(info.si_signo == SIGTRAP && "Unexpected child signal!"); 586af245d11STodd Fiala 587b9c1b51eSKate Stone switch (info.si_code) { 588c8d18cbaSMichał Górny case (SIGTRAP | (PTRACE_EVENT_FORK << 8)): 589c8d18cbaSMichał Górny case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)): 590b9c1b51eSKate Stone case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): { 591c8d18cbaSMichał Górny // This can either mean a new thread or a new process spawned via 592c8d18cbaSMichał Górny // clone(2) without SIGCHLD or CLONE_VFORK flag. Note that clone(2) 593c8d18cbaSMichał Górny // can also cause PTRACE_EVENT_FORK and PTRACE_EVENT_VFORK if one 594c8d18cbaSMichał Górny // of these flags are passed. 595af245d11STodd Fiala 596af245d11STodd Fiala unsigned long event_message = 0; 597b9c1b51eSKate Stone if (GetEventMessage(thread.GetID(), &event_message).Fail()) { 598a6321a8eSPavel Labath LLDB_LOG(log, 599c8d18cbaSMichał Górny "pid {0} received clone() event but GetEventMessage failed " 600c8d18cbaSMichał Górny "so we don't know the new pid/tid", 601a6321a8eSPavel Labath thread.GetID()); 602121cff78SPavel Labath ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER); 603c8d18cbaSMichał Górny } else { 604c8d18cbaSMichał Górny if (!MonitorClone(event_message, {{(info.si_code >> 8), thread.GetID()}})) 605c8d18cbaSMichał Górny WaitForCloneNotification(event_message); 606c8d18cbaSMichał Górny } 607c8d18cbaSMichał Górny 608af245d11STodd Fiala break; 609af245d11STodd Fiala } 610af245d11STodd Fiala 611b9c1b51eSKate Stone case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): { 612a6321a8eSPavel Labath LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP); 613a9882ceeSTodd Fiala 6141dbc6c9cSPavel Labath // Exec clears any pending notifications. 6150e1d729bSPavel Labath m_pending_notification_tid = LLDB_INVALID_THREAD_ID; 616fa03ad2eSChaoren Lin 617b9c1b51eSKate Stone // Remove all but the main thread here. Linux fork creates a new process 618b9c1b51eSKate Stone // which only copies the main thread. 619a6321a8eSPavel Labath LLDB_LOG(log, "exec received, stop tracking all but main thread"); 620a9882ceeSTodd Fiala 621ee74c9e5SPavel Labath llvm::erase_if(m_threads, [&](std::unique_ptr<NativeThreadProtocol> &t) { 622ee74c9e5SPavel Labath return t->GetID() != GetID(); 623ee74c9e5SPavel Labath }); 624a5be48b3SPavel Labath assert(m_threads.size() == 1); 625a5be48b3SPavel Labath auto *main_thread = static_cast<NativeThreadLinux *>(m_threads[0].get()); 626a9882ceeSTodd Fiala 627a5be48b3SPavel Labath SetCurrentThreadID(main_thread->GetID()); 628a5be48b3SPavel Labath main_thread->SetStoppedByExec(); 629a9882ceeSTodd Fiala 630fa03ad2eSChaoren Lin // Tell coordinator about about the "new" (since exec) stopped main thread. 631a5be48b3SPavel Labath ThreadWasCreated(*main_thread); 632fa03ad2eSChaoren Lin 633a9882ceeSTodd Fiala // Let our delegate know we have just exec'd. 634a9882ceeSTodd Fiala NotifyDidExec(); 635a9882ceeSTodd Fiala 636fa03ad2eSChaoren Lin // Let the process know we're stopped. 637a5be48b3SPavel Labath StopRunningThreads(main_thread->GetID()); 638a9882ceeSTodd Fiala 639af245d11STodd Fiala break; 640a9882ceeSTodd Fiala } 641af245d11STodd Fiala 642b9c1b51eSKate Stone case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): { 64305097246SAdrian Prantl // The inferior process or one of its threads is about to exit. We don't 64405097246SAdrian Prantl // want to do anything with the thread so we just resume it. In case we 64505097246SAdrian Prantl // want to implement "break on thread exit" functionality, we would need to 64605097246SAdrian Prantl // stop here. 647fa03ad2eSChaoren Lin 648af245d11STodd Fiala unsigned long data = 0; 649b9cc0c75SPavel Labath if (GetEventMessage(thread.GetID(), &data).Fail()) 650af245d11STodd Fiala data = -1; 651af245d11STodd Fiala 652a6321a8eSPavel Labath LLDB_LOG(log, 653a6321a8eSPavel Labath "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, " 654a6321a8eSPavel Labath "WIFSIGNALED={2}, pid = {3}, main_thread = {4}", 655a6321a8eSPavel Labath data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(), 656a6321a8eSPavel Labath is_main_thread); 657af245d11STodd Fiala 65875f47c3aSTodd Fiala 65986852d36SPavel Labath StateType state = thread.GetState(); 660b9c1b51eSKate Stone if (!StateIsRunningState(state)) { 661b9c1b51eSKate Stone // Due to a kernel bug, we may sometimes get this stop after the inferior 662d8b3c1a1SPavel Labath // gets a SIGKILL. This confuses our state tracking logic in 663d8b3c1a1SPavel Labath // ResumeThread(), since normally, we should not be receiving any ptrace 66405097246SAdrian Prantl // events while the inferior is stopped. This makes sure that the 66505097246SAdrian Prantl // inferior is resumed and exits normally. 66686852d36SPavel Labath state = eStateRunning; 66786852d36SPavel Labath } 66886852d36SPavel Labath ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER); 669af245d11STodd Fiala 670af245d11STodd Fiala break; 671af245d11STodd Fiala } 672af245d11STodd Fiala 673c8d18cbaSMichał Górny case (SIGTRAP | (PTRACE_EVENT_VFORK_DONE << 8)): { 674fd0af0cfSMichał Górny if (bool(m_enabled_extensions & Extension::vfork)) { 675fd0af0cfSMichał Górny thread.SetStoppedByVForkDone(); 676fd0af0cfSMichał Górny StopRunningThreads(thread.GetID()); 677fd0af0cfSMichał Górny } 678fd0af0cfSMichał Górny else 679c8d18cbaSMichał Górny ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER); 680c8d18cbaSMichał Górny break; 681c8d18cbaSMichał Górny } 682c8d18cbaSMichał Górny 683af245d11STodd Fiala case 0: 684c16f5dcaSChaoren Lin case TRAP_TRACE: // We receive this on single stepping. 685c16f5dcaSChaoren Lin case TRAP_HWBKPT: // We receive this on watchpoint hit 68686fd8e45SChaoren Lin { 687c16f5dcaSChaoren Lin // If a watchpoint was hit, report it 688c16f5dcaSChaoren Lin uint32_t wp_index; 689d37349f3SPavel Labath Status error = thread.GetRegisterContext().GetWatchpointHitIndex( 690b9c1b51eSKate Stone wp_index, (uintptr_t)info.si_addr); 691a6321a8eSPavel Labath if (error.Fail()) 692a6321a8eSPavel Labath LLDB_LOG(log, 693a6321a8eSPavel Labath "received error while checking for watchpoint hits, pid = " 694a6321a8eSPavel Labath "{0}, error = {1}", 695a6321a8eSPavel Labath thread.GetID(), error); 696b9c1b51eSKate Stone if (wp_index != LLDB_INVALID_INDEX32) { 697b9cc0c75SPavel Labath MonitorWatchpoint(thread, wp_index); 698c16f5dcaSChaoren Lin break; 699c16f5dcaSChaoren Lin } 700b9cc0c75SPavel Labath 701d5ffbad2SOmair Javaid // If a breakpoint was hit, report it 702d5ffbad2SOmair Javaid uint32_t bp_index; 703d37349f3SPavel Labath error = thread.GetRegisterContext().GetHardwareBreakHitIndex( 704d5ffbad2SOmair Javaid bp_index, (uintptr_t)info.si_addr); 705d5ffbad2SOmair Javaid if (error.Fail()) 706d5ffbad2SOmair Javaid LLDB_LOG(log, "received error while checking for hardware " 707d5ffbad2SOmair Javaid "breakpoint hits, pid = {0}, error = {1}", 708d5ffbad2SOmair Javaid thread.GetID(), error); 709d5ffbad2SOmair Javaid if (bp_index != LLDB_INVALID_INDEX32) { 710d5ffbad2SOmair Javaid MonitorBreakpoint(thread); 711d5ffbad2SOmair Javaid break; 712d5ffbad2SOmair Javaid } 713d5ffbad2SOmair Javaid 714be379e15STamas Berghammer // Otherwise, report step over 715be379e15STamas Berghammer MonitorTrace(thread); 716af245d11STodd Fiala break; 717b9cc0c75SPavel Labath } 718af245d11STodd Fiala 719af245d11STodd Fiala case SI_KERNEL: 72035799963SMohit K. Bhakkad #if defined __mips__ 72105097246SAdrian Prantl // For mips there is no special signal for watchpoint So we check for 72205097246SAdrian Prantl // watchpoint in kernel trap 72335799963SMohit K. Bhakkad { 72435799963SMohit K. Bhakkad // If a watchpoint was hit, report it 72535799963SMohit K. Bhakkad uint32_t wp_index; 726d37349f3SPavel Labath Status error = thread.GetRegisterContext().GetWatchpointHitIndex( 727b9c1b51eSKate Stone wp_index, LLDB_INVALID_ADDRESS); 728a6321a8eSPavel Labath if (error.Fail()) 729a6321a8eSPavel Labath LLDB_LOG(log, 730a6321a8eSPavel Labath "received error while checking for watchpoint hits, pid = " 731a6321a8eSPavel Labath "{0}, error = {1}", 732a6321a8eSPavel Labath thread.GetID(), error); 733b9c1b51eSKate Stone if (wp_index != LLDB_INVALID_INDEX32) { 734b9cc0c75SPavel Labath MonitorWatchpoint(thread, wp_index); 73535799963SMohit K. Bhakkad break; 73635799963SMohit K. Bhakkad } 73735799963SMohit K. Bhakkad } 73835799963SMohit K. Bhakkad // NO BREAK 73935799963SMohit K. Bhakkad #endif 740af245d11STodd Fiala case TRAP_BRKPT: 741b9cc0c75SPavel Labath MonitorBreakpoint(thread); 742af245d11STodd Fiala break; 743af245d11STodd Fiala 744af245d11STodd Fiala case SIGTRAP: 745af245d11STodd Fiala case (SIGTRAP | 0x80): 746a6321a8eSPavel Labath LLDB_LOG( 747a6321a8eSPavel Labath log, 748a6321a8eSPavel Labath "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming", 749a6321a8eSPavel Labath info.si_code, GetID(), thread.GetID()); 750fa03ad2eSChaoren Lin 751af245d11STodd Fiala // Ignore these signals until we know more about them. 752b9cc0c75SPavel Labath ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER); 753af245d11STodd Fiala break; 754af245d11STodd Fiala 755af245d11STodd Fiala default: 75621a365baSPavel Labath LLDB_LOG(log, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}", 757a6321a8eSPavel Labath info.si_code, GetID(), thread.GetID()); 75821a365baSPavel Labath MonitorSignal(info, thread, false); 759af245d11STodd Fiala break; 760af245d11STodd Fiala } 761af245d11STodd Fiala } 762af245d11STodd Fiala 763b9c1b51eSKate Stone void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) { 764a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 765a6321a8eSPavel Labath LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID()); 766c16f5dcaSChaoren Lin 7670e1d729bSPavel Labath // This thread is currently stopped. 768b9cc0c75SPavel Labath thread.SetStoppedByTrace(); 769c16f5dcaSChaoren Lin 770b9cc0c75SPavel Labath StopRunningThreads(thread.GetID()); 771c16f5dcaSChaoren Lin } 772c16f5dcaSChaoren Lin 773b9c1b51eSKate Stone void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) { 774b9c1b51eSKate Stone Log *log( 775b9c1b51eSKate Stone GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS)); 776a6321a8eSPavel Labath LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID()); 777c16f5dcaSChaoren Lin 778c16f5dcaSChaoren Lin // Mark the thread as stopped at breakpoint. 779b9cc0c75SPavel Labath thread.SetStoppedByBreakpoint(); 780aef7908fSPavel Labath FixupBreakpointPCAsNeeded(thread); 781d8c338d4STamas Berghammer 782b9c1b51eSKate Stone if (m_threads_stepping_with_breakpoint.find(thread.GetID()) != 783b9c1b51eSKate Stone m_threads_stepping_with_breakpoint.end()) 784b9cc0c75SPavel Labath thread.SetStoppedByTrace(); 785c16f5dcaSChaoren Lin 786b9cc0c75SPavel Labath StopRunningThreads(thread.GetID()); 787c16f5dcaSChaoren Lin } 788c16f5dcaSChaoren Lin 789b9c1b51eSKate Stone void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread, 790b9c1b51eSKate Stone uint32_t wp_index) { 791b9c1b51eSKate Stone Log *log( 792b9c1b51eSKate Stone GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS)); 793a6321a8eSPavel Labath LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}", 794a6321a8eSPavel Labath thread.GetID(), wp_index); 795c16f5dcaSChaoren Lin 79605097246SAdrian Prantl // Mark the thread as stopped at watchpoint. The address is at 79705097246SAdrian Prantl // (lldb::addr_t)info->si_addr if we need it. 798f9077782SPavel Labath thread.SetStoppedByWatchpoint(wp_index); 799c16f5dcaSChaoren Lin 800b9c1b51eSKate Stone // We need to tell all other running threads before we notify the delegate 801b9c1b51eSKate Stone // about this stop. 802f9077782SPavel Labath StopRunningThreads(thread.GetID()); 803c16f5dcaSChaoren Lin } 804c16f5dcaSChaoren Lin 805b9c1b51eSKate Stone void NativeProcessLinux::MonitorSignal(const siginfo_t &info, 806b9c1b51eSKate Stone NativeThreadLinux &thread, bool exited) { 807b9cc0c75SPavel Labath const int signo = info.si_signo; 808b9cc0c75SPavel Labath const bool is_from_llgs = info.si_pid == getpid(); 809af245d11STodd Fiala 810a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 811af245d11STodd Fiala 812af245d11STodd Fiala // POSIX says that process behaviour is undefined after it ignores a SIGFPE, 81305097246SAdrian Prantl // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a kill(2) 81405097246SAdrian Prantl // or raise(3). Similarly for tgkill(2) on Linux. 815af245d11STodd Fiala // 816af245d11STodd Fiala // IOW, user generated signals never generate what we consider to be a 817af245d11STodd Fiala // "crash". 818af245d11STodd Fiala // 819af245d11STodd Fiala // Similarly, ACK signals generated by this monitor. 820af245d11STodd Fiala 821af245d11STodd Fiala // Handle the signal. 822a6321a8eSPavel Labath LLDB_LOG(log, 823a6321a8eSPavel Labath "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, " 824a6321a8eSPavel Labath "waitpid pid = {4})", 825a6321a8eSPavel Labath Host::GetSignalAsCString(signo), signo, info.si_code, 826b9cc0c75SPavel Labath thread.GetID()); 82758a2f669STodd Fiala 82858a2f669STodd Fiala // Check for thread stop notification. 829b9c1b51eSKate Stone if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) { 830af245d11STodd Fiala // This is a tgkill()-based stop. 831a6321a8eSPavel Labath LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID()); 832fa03ad2eSChaoren Lin 83305097246SAdrian Prantl // Check that we're not already marked with a stop reason. Note this thread 83405097246SAdrian Prantl // really shouldn't already be marked as stopped - if we were, that would 83505097246SAdrian Prantl // imply that the kernel signaled us with the thread stopping which we 83605097246SAdrian Prantl // handled and marked as stopped, and that, without an intervening resume, 83705097246SAdrian Prantl // we received another stop. It is more likely that we are missing the 83805097246SAdrian Prantl // marking of a run state somewhere if we find that the thread was marked 83905097246SAdrian Prantl // as stopped. 840b9cc0c75SPavel Labath const StateType thread_state = thread.GetState(); 841b9c1b51eSKate Stone if (!StateIsStoppedState(thread_state, false)) { 842ed89c7feSPavel Labath // An inferior thread has stopped because of a SIGSTOP we have sent it. 843b9c1b51eSKate Stone // Generally, these are not important stops and we don't want to report 844a6321a8eSPavel Labath // them as they are just used to stop other threads when one thread (the 845a6321a8eSPavel Labath // one with the *real* stop reason) hits a breakpoint (watchpoint, 84605097246SAdrian Prantl // etc...). However, in the case of an asynchronous Interrupt(), this 84705097246SAdrian Prantl // *is* the real stop reason, so we leave the signal intact if this is 84805097246SAdrian Prantl // the thread that was chosen as the triggering thread. 849b9c1b51eSKate Stone if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) { 850b9cc0c75SPavel Labath if (m_pending_notification_tid == thread.GetID()) 851b9cc0c75SPavel Labath thread.SetStoppedBySignal(SIGSTOP, &info); 852ed89c7feSPavel Labath else 853b9cc0c75SPavel Labath thread.SetStoppedWithNoReason(); 854ed89c7feSPavel Labath 855b9cc0c75SPavel Labath SetCurrentThreadID(thread.GetID()); 8560e1d729bSPavel Labath SignalIfAllThreadsStopped(); 857b9c1b51eSKate Stone } else { 8580e1d729bSPavel Labath // We can end up here if stop was initiated by LLGS but by this time a 8590e1d729bSPavel Labath // thread stop has occurred - maybe initiated by another event. 86097206d57SZachary Turner Status error = ResumeThread(thread, thread.GetState(), 0); 861a6321a8eSPavel Labath if (error.Fail()) 862a6321a8eSPavel Labath LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(), 863a6321a8eSPavel Labath error); 8640e1d729bSPavel Labath } 865b9c1b51eSKate Stone } else { 866a6321a8eSPavel Labath LLDB_LOG(log, 867a6321a8eSPavel Labath "pid {0} tid {1}, thread was already marked as a stopped " 868a6321a8eSPavel Labath "state (state={2}), leaving stop signal as is", 8698198db30SPavel Labath GetID(), thread.GetID(), thread_state); 8700e1d729bSPavel Labath SignalIfAllThreadsStopped(); 871af245d11STodd Fiala } 872af245d11STodd Fiala 87358a2f669STodd Fiala // Done handling. 874af245d11STodd Fiala return; 875af245d11STodd Fiala } 876af245d11STodd Fiala 87705097246SAdrian Prantl // Check if debugger should stop at this signal or just ignore it and resume 87805097246SAdrian Prantl // the inferior. 8794a705e7eSPavel Labath if (m_signals_to_ignore.find(signo) != m_signals_to_ignore.end()) { 8804a705e7eSPavel Labath ResumeThread(thread, thread.GetState(), signo); 8814a705e7eSPavel Labath return; 8824a705e7eSPavel Labath } 8834a705e7eSPavel Labath 88486fd8e45SChaoren Lin // This thread is stopped. 885a6321a8eSPavel Labath LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo)); 886b9cc0c75SPavel Labath thread.SetStoppedBySignal(signo, &info); 88786fd8e45SChaoren Lin 88886fd8e45SChaoren Lin // Send a stop to the debugger after we get all other threads to stop. 889b9cc0c75SPavel Labath StopRunningThreads(thread.GetID()); 890511e5cdcSTodd Fiala } 891af245d11STodd Fiala 892c8d18cbaSMichał Górny bool NativeProcessLinux::MonitorClone( 893c8d18cbaSMichał Górny lldb::pid_t child_pid, 894c8d18cbaSMichał Górny llvm::Optional<NativeProcessLinux::CloneInfo> clone_info) { 895c8d18cbaSMichał Górny Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 896c8d18cbaSMichał Górny LLDB_LOG(log, "clone, child_pid={0}, clone info?={1}", child_pid, 897c8d18cbaSMichał Górny clone_info.hasValue()); 898c8d18cbaSMichał Górny 899c8d18cbaSMichał Górny auto find_it = m_pending_pid_map.find(child_pid); 900c8d18cbaSMichał Górny if (find_it == m_pending_pid_map.end()) { 901c8d18cbaSMichał Górny // not in the map, so this is the first signal for the PID 902c8d18cbaSMichał Górny m_pending_pid_map.insert({child_pid, clone_info}); 903c8d18cbaSMichał Górny return false; 904c8d18cbaSMichał Górny } 905c8d18cbaSMichał Górny m_pending_pid_map.erase(find_it); 906c8d18cbaSMichał Górny 907c8d18cbaSMichał Górny // second signal for the pid 908c8d18cbaSMichał Górny assert(clone_info.hasValue() != find_it->second.hasValue()); 909c8d18cbaSMichał Górny if (!clone_info) { 910c8d18cbaSMichał Górny // child signal does not indicate the event, so grab the one stored 911c8d18cbaSMichał Górny // earlier 912c8d18cbaSMichał Górny clone_info = find_it->second; 913c8d18cbaSMichał Górny } 914c8d18cbaSMichał Górny 915c8d18cbaSMichał Górny LLDB_LOG(log, "second signal for child_pid={0}, parent_tid={1}, event={2}", 916c8d18cbaSMichał Górny child_pid, clone_info->parent_tid, clone_info->event); 917c8d18cbaSMichał Górny 918c8d18cbaSMichał Górny auto *parent_thread = GetThreadByID(clone_info->parent_tid); 919c8d18cbaSMichał Górny assert(parent_thread); 920c8d18cbaSMichał Górny 921c8d18cbaSMichał Górny switch (clone_info->event) { 922c8d18cbaSMichał Górny case PTRACE_EVENT_CLONE: { 923c8d18cbaSMichał Górny // PTRACE_EVENT_CLONE can either mean a new thread or a new process. 924c8d18cbaSMichał Górny // Try to grab the new process' PGID to figure out which one it is. 925c8d18cbaSMichał Górny // If PGID is the same as the PID, then it's a new process. Otherwise, 926c8d18cbaSMichał Górny // it's a thread. 927c8d18cbaSMichał Górny auto tgid_ret = getPIDForTID(child_pid); 928c8d18cbaSMichał Górny if (tgid_ret != child_pid) { 929c8d18cbaSMichał Górny // A new thread should have PGID matching our process' PID. 930c8d18cbaSMichał Górny assert(!tgid_ret || tgid_ret.getValue() == GetID()); 931c8d18cbaSMichał Górny 932c8d18cbaSMichał Górny NativeThreadLinux &child_thread = AddThread(child_pid, /*resume*/ true); 933c8d18cbaSMichał Górny ThreadWasCreated(child_thread); 934c8d18cbaSMichał Górny 935c8d18cbaSMichał Górny // Resume the parent. 936c8d18cbaSMichał Górny ResumeThread(*parent_thread, parent_thread->GetState(), 937c8d18cbaSMichał Górny LLDB_INVALID_SIGNAL_NUMBER); 938c8d18cbaSMichał Górny break; 939c8d18cbaSMichał Górny } 940c8d18cbaSMichał Górny } 941c8d18cbaSMichał Górny LLVM_FALLTHROUGH; 942c8d18cbaSMichał Górny case PTRACE_EVENT_FORK: 943c8d18cbaSMichał Górny case PTRACE_EVENT_VFORK: { 944fd0af0cfSMichał Górny bool is_vfork = clone_info->event == PTRACE_EVENT_VFORK; 945fd0af0cfSMichał Górny std::unique_ptr<NativeProcessLinux> child_process{new NativeProcessLinux( 946fd0af0cfSMichał Górny static_cast<::pid_t>(child_pid), m_terminal_fd, m_delegate, m_arch, 947fd0af0cfSMichał Górny m_main_loop, {static_cast<::pid_t>(child_pid)})}; 948fd0af0cfSMichał Górny if (!is_vfork) 949fd0af0cfSMichał Górny child_process->m_software_breakpoints = m_software_breakpoints; 950fd0af0cfSMichał Górny 951fd0af0cfSMichał Górny Extension expected_ext = is_vfork ? Extension::vfork : Extension::fork; 952fd0af0cfSMichał Górny if (bool(m_enabled_extensions & expected_ext)) { 953fd0af0cfSMichał Górny m_delegate.NewSubprocess(this, std::move(child_process)); 954fd0af0cfSMichał Górny // NB: non-vfork clone() is reported as fork 955fd0af0cfSMichał Górny parent_thread->SetStoppedByFork(is_vfork, child_pid); 956fd0af0cfSMichał Górny StopRunningThreads(parent_thread->GetID()); 957fd0af0cfSMichał Górny } else { 958fd0af0cfSMichał Górny child_process->Detach(); 959c8d18cbaSMichał Górny ResumeThread(*parent_thread, parent_thread->GetState(), 960c8d18cbaSMichał Górny LLDB_INVALID_SIGNAL_NUMBER); 961fd0af0cfSMichał Górny } 962c8d18cbaSMichał Górny break; 963c8d18cbaSMichał Górny } 964c8d18cbaSMichał Górny default: 965c8d18cbaSMichał Górny llvm_unreachable("unknown clone_info.event"); 966c8d18cbaSMichał Górny } 967c8d18cbaSMichał Górny 968c8d18cbaSMichał Górny return true; 969c8d18cbaSMichał Górny } 970c8d18cbaSMichał Górny 971b9c1b51eSKate Stone bool NativeProcessLinux::SupportHardwareSingleStepping() const { 972ddb93b63SFangrui Song if (m_arch.GetMachine() == llvm::Triple::arm || m_arch.IsMIPS()) 973cdc22a88SMohit K. Bhakkad return false; 974cdc22a88SMohit K. Bhakkad return true; 975e7708688STamas Berghammer } 976e7708688STamas Berghammer 97797206d57SZachary Turner Status NativeProcessLinux::Resume(const ResumeActionList &resume_actions) { 978a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 979a6321a8eSPavel Labath LLDB_LOG(log, "pid {0}", GetID()); 980af245d11STodd Fiala 981e7708688STamas Berghammer bool software_single_step = !SupportHardwareSingleStepping(); 982af245d11STodd Fiala 983b9c1b51eSKate Stone if (software_single_step) { 984a5be48b3SPavel Labath for (const auto &thread : m_threads) { 985a5be48b3SPavel Labath assert(thread && "thread list should not contain NULL threads"); 986e7708688STamas Berghammer 987b9c1b51eSKate Stone const ResumeAction *const action = 988a5be48b3SPavel Labath resume_actions.GetActionForThread(thread->GetID(), true); 989e7708688STamas Berghammer if (action == nullptr) 990e7708688STamas Berghammer continue; 991e7708688STamas Berghammer 992b9c1b51eSKate Stone if (action->state == eStateStepping) { 99397206d57SZachary Turner Status error = SetupSoftwareSingleStepping( 994a5be48b3SPavel Labath static_cast<NativeThreadLinux &>(*thread)); 995e7708688STamas Berghammer if (error.Fail()) 996e7708688STamas Berghammer return error; 997e7708688STamas Berghammer } 998e7708688STamas Berghammer } 999e7708688STamas Berghammer } 1000e7708688STamas Berghammer 1001a5be48b3SPavel Labath for (const auto &thread : m_threads) { 1002a5be48b3SPavel Labath assert(thread && "thread list should not contain NULL threads"); 1003af245d11STodd Fiala 1004b9c1b51eSKate Stone const ResumeAction *const action = 1005a5be48b3SPavel Labath resume_actions.GetActionForThread(thread->GetID(), true); 10066a196ce6SChaoren Lin 1007b9c1b51eSKate Stone if (action == nullptr) { 1008a6321a8eSPavel Labath LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(), 1009a5be48b3SPavel Labath thread->GetID()); 10106a196ce6SChaoren Lin continue; 10116a196ce6SChaoren Lin } 1012af245d11STodd Fiala 1013a6321a8eSPavel Labath LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}", 1014a5be48b3SPavel Labath action->state, GetID(), thread->GetID()); 1015af245d11STodd Fiala 1016b9c1b51eSKate Stone switch (action->state) { 1017af245d11STodd Fiala case eStateRunning: 1018b9c1b51eSKate Stone case eStateStepping: { 1019af245d11STodd Fiala // Run the thread, possibly feeding it the signal. 1020fa03ad2eSChaoren Lin const int signo = action->signal; 1021a5be48b3SPavel Labath ResumeThread(static_cast<NativeThreadLinux &>(*thread), action->state, 1022b9c1b51eSKate Stone signo); 1023af245d11STodd Fiala break; 1024ae29d395SChaoren Lin } 1025af245d11STodd Fiala 1026af245d11STodd Fiala case eStateSuspended: 1027af245d11STodd Fiala case eStateStopped: 1028a6321a8eSPavel Labath llvm_unreachable("Unexpected state"); 1029af245d11STodd Fiala 1030af245d11STodd Fiala default: 103197206d57SZachary Turner return Status("NativeProcessLinux::%s (): unexpected state %s specified " 1032b9c1b51eSKate Stone "for pid %" PRIu64 ", tid %" PRIu64, 1033b9c1b51eSKate Stone __FUNCTION__, StateAsCString(action->state), GetID(), 1034a5be48b3SPavel Labath thread->GetID()); 1035af245d11STodd Fiala } 1036af245d11STodd Fiala } 1037af245d11STodd Fiala 103897206d57SZachary Turner return Status(); 1039af245d11STodd Fiala } 1040af245d11STodd Fiala 104197206d57SZachary Turner Status NativeProcessLinux::Halt() { 104297206d57SZachary Turner Status error; 1043af245d11STodd Fiala 1044af245d11STodd Fiala if (kill(GetID(), SIGSTOP) != 0) 1045af245d11STodd Fiala error.SetErrorToErrno(); 1046af245d11STodd Fiala 1047af245d11STodd Fiala return error; 1048af245d11STodd Fiala } 1049af245d11STodd Fiala 105097206d57SZachary Turner Status NativeProcessLinux::Detach() { 105197206d57SZachary Turner Status error; 1052af245d11STodd Fiala 1053af245d11STodd Fiala // Stop monitoring the inferior. 105419cbe96aSPavel Labath m_sigchld_handle.reset(); 1055af245d11STodd Fiala 10567a9495bcSPavel Labath // Tell ptrace to detach from the process. 10577a9495bcSPavel Labath if (GetID() == LLDB_INVALID_PROCESS_ID) 10587a9495bcSPavel Labath return error; 10597a9495bcSPavel Labath 1060a5be48b3SPavel Labath for (const auto &thread : m_threads) { 1061a5be48b3SPavel Labath Status e = Detach(thread->GetID()); 10627a9495bcSPavel Labath if (e.Fail()) 1063b9c1b51eSKate Stone error = 1064b9c1b51eSKate Stone e; // Save the error, but still attempt to detach from other threads. 10657a9495bcSPavel Labath } 10667a9495bcSPavel Labath 10670b697561SWalter Erquinigo m_intel_pt_manager.Clear(); 106899e37695SRavitheja Addepally 1069af245d11STodd Fiala return error; 1070af245d11STodd Fiala } 1071af245d11STodd Fiala 107297206d57SZachary Turner Status NativeProcessLinux::Signal(int signo) { 107397206d57SZachary Turner Status error; 1074af245d11STodd Fiala 1075a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1076a6321a8eSPavel Labath LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo, 1077a6321a8eSPavel Labath Host::GetSignalAsCString(signo), GetID()); 1078af245d11STodd Fiala 1079af245d11STodd Fiala if (kill(GetID(), signo)) 1080af245d11STodd Fiala error.SetErrorToErrno(); 1081af245d11STodd Fiala 1082af245d11STodd Fiala return error; 1083af245d11STodd Fiala } 1084af245d11STodd Fiala 108597206d57SZachary Turner Status NativeProcessLinux::Interrupt() { 108605097246SAdrian Prantl // Pick a running thread (or if none, a not-dead stopped thread) as the 108705097246SAdrian Prantl // chosen thread that will be the stop-reason thread. 1088a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1089e9547b80SChaoren Lin 1090a5be48b3SPavel Labath NativeThreadProtocol *running_thread = nullptr; 1091a5be48b3SPavel Labath NativeThreadProtocol *stopped_thread = nullptr; 1092e9547b80SChaoren Lin 1093a6321a8eSPavel Labath LLDB_LOG(log, "selecting running thread for interrupt target"); 1094a5be48b3SPavel Labath for (const auto &thread : m_threads) { 109505097246SAdrian Prantl // If we have a running or stepping thread, we'll call that the target of 109605097246SAdrian Prantl // the interrupt. 1097a5be48b3SPavel Labath const auto thread_state = thread->GetState(); 1098b9c1b51eSKate Stone if (thread_state == eStateRunning || thread_state == eStateStepping) { 1099a5be48b3SPavel Labath running_thread = thread.get(); 1100e9547b80SChaoren Lin break; 1101a5be48b3SPavel Labath } else if (!stopped_thread && StateIsStoppedState(thread_state, true)) { 110205097246SAdrian Prantl // Remember the first non-dead stopped thread. We'll use that as a 110305097246SAdrian Prantl // backup if there are no running threads. 1104a5be48b3SPavel Labath stopped_thread = thread.get(); 1105e9547b80SChaoren Lin } 1106e9547b80SChaoren Lin } 1107e9547b80SChaoren Lin 1108a5be48b3SPavel Labath if (!running_thread && !stopped_thread) { 110997206d57SZachary Turner Status error("found no running/stepping or live stopped threads as target " 1110b9c1b51eSKate Stone "for interrupt"); 1111a6321a8eSPavel Labath LLDB_LOG(log, "skipping due to error: {0}", error); 11125830aa75STamas Berghammer 1113e9547b80SChaoren Lin return error; 1114e9547b80SChaoren Lin } 1115e9547b80SChaoren Lin 1116a5be48b3SPavel Labath NativeThreadProtocol *deferred_signal_thread = 1117a5be48b3SPavel Labath running_thread ? running_thread : stopped_thread; 1118e9547b80SChaoren Lin 1119a6321a8eSPavel Labath LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(), 1120a5be48b3SPavel Labath running_thread ? "running" : "stopped", 1121a5be48b3SPavel Labath deferred_signal_thread->GetID()); 1122e9547b80SChaoren Lin 1123a5be48b3SPavel Labath StopRunningThreads(deferred_signal_thread->GetID()); 112445f5cb31SPavel Labath 112597206d57SZachary Turner return Status(); 1126e9547b80SChaoren Lin } 1127e9547b80SChaoren Lin 112897206d57SZachary Turner Status NativeProcessLinux::Kill() { 1129a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1130a6321a8eSPavel Labath LLDB_LOG(log, "pid {0}", GetID()); 1131af245d11STodd Fiala 113297206d57SZachary Turner Status error; 1133af245d11STodd Fiala 1134b9c1b51eSKate Stone switch (m_state) { 1135af245d11STodd Fiala case StateType::eStateInvalid: 1136af245d11STodd Fiala case StateType::eStateExited: 1137af245d11STodd Fiala case StateType::eStateCrashed: 1138af245d11STodd Fiala case StateType::eStateDetached: 1139af245d11STodd Fiala case StateType::eStateUnloaded: 1140af245d11STodd Fiala // Nothing to do - the process is already dead. 1141a6321a8eSPavel Labath LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(), 11428198db30SPavel Labath m_state); 1143af245d11STodd Fiala return error; 1144af245d11STodd Fiala 1145af245d11STodd Fiala case StateType::eStateConnected: 1146af245d11STodd Fiala case StateType::eStateAttaching: 1147af245d11STodd Fiala case StateType::eStateLaunching: 1148af245d11STodd Fiala case StateType::eStateStopped: 1149af245d11STodd Fiala case StateType::eStateRunning: 1150af245d11STodd Fiala case StateType::eStateStepping: 1151af245d11STodd Fiala case StateType::eStateSuspended: 1152af245d11STodd Fiala // We can try to kill a process in these states. 1153af245d11STodd Fiala break; 1154af245d11STodd Fiala } 1155af245d11STodd Fiala 1156b9c1b51eSKate Stone if (kill(GetID(), SIGKILL) != 0) { 1157af245d11STodd Fiala error.SetErrorToErrno(); 1158af245d11STodd Fiala return error; 1159af245d11STodd Fiala } 1160af245d11STodd Fiala 1161af245d11STodd Fiala return error; 1162af245d11STodd Fiala } 1163af245d11STodd Fiala 116497206d57SZachary Turner Status NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr, 1165b9c1b51eSKate Stone MemoryRegionInfo &range_info) { 1166b9c1b51eSKate Stone // FIXME review that the final memory region returned extends to the end of 1167b9c1b51eSKate Stone // the virtual address space, 1168af245d11STodd Fiala // with no perms if it is not mapped. 1169af245d11STodd Fiala 117005097246SAdrian Prantl // Use an approach that reads memory regions from /proc/{pid}/maps. Assume 117105097246SAdrian Prantl // proc maps entries are in ascending order. 1172af245d11STodd Fiala // FIXME assert if we find differently. 1173af245d11STodd Fiala 1174b9c1b51eSKate Stone if (m_supports_mem_region == LazyBool::eLazyBoolNo) { 1175af245d11STodd Fiala // We're done. 117697206d57SZachary Turner return Status("unsupported"); 1177af245d11STodd Fiala } 1178af245d11STodd Fiala 117997206d57SZachary Turner Status error = PopulateMemoryRegionCache(); 1180b9c1b51eSKate Stone if (error.Fail()) { 1181af245d11STodd Fiala return error; 1182af245d11STodd Fiala } 1183af245d11STodd Fiala 1184af245d11STodd Fiala lldb::addr_t prev_base_address = 0; 1185af245d11STodd Fiala 1186b9c1b51eSKate Stone // FIXME start by finding the last region that is <= target address using 1187b9c1b51eSKate Stone // binary search. Data is sorted. 1188af245d11STodd Fiala // There can be a ton of regions on pthreads apps with lots of threads. 1189b9c1b51eSKate Stone for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end(); 1190b9c1b51eSKate Stone ++it) { 1191a6f5795aSTamas Berghammer MemoryRegionInfo &proc_entry_info = it->first; 1192af245d11STodd Fiala 1193af245d11STodd Fiala // Sanity check assumption that /proc/{pid}/maps entries are ascending. 1194b9c1b51eSKate Stone assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) && 1195b9c1b51eSKate Stone "descending /proc/pid/maps entries detected, unexpected"); 1196af245d11STodd Fiala prev_base_address = proc_entry_info.GetRange().GetRangeBase(); 1197b1554311SHafiz Abid Qadeer UNUSED_IF_ASSERT_DISABLED(prev_base_address); 1198af245d11STodd Fiala 1199b9c1b51eSKate Stone // If the target address comes before this entry, indicate distance to next 1200b9c1b51eSKate Stone // region. 1201b9c1b51eSKate Stone if (load_addr < proc_entry_info.GetRange().GetRangeBase()) { 1202af245d11STodd Fiala range_info.GetRange().SetRangeBase(load_addr); 1203b9c1b51eSKate Stone range_info.GetRange().SetByteSize( 1204b9c1b51eSKate Stone proc_entry_info.GetRange().GetRangeBase() - load_addr); 1205af245d11STodd Fiala range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo); 1206af245d11STodd Fiala range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo); 1207af245d11STodd Fiala range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo); 1208ad007563SHoward Hellyer range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo); 1209af245d11STodd Fiala 1210af245d11STodd Fiala return error; 1211b9c1b51eSKate Stone } else if (proc_entry_info.GetRange().Contains(load_addr)) { 1212af245d11STodd Fiala // The target address is within the memory region we're processing here. 1213af245d11STodd Fiala range_info = proc_entry_info; 1214af245d11STodd Fiala return error; 1215af245d11STodd Fiala } 1216af245d11STodd Fiala 1217b9c1b51eSKate Stone // The target memory address comes somewhere after the region we just 1218b9c1b51eSKate Stone // parsed. 1219af245d11STodd Fiala } 1220af245d11STodd Fiala 1221b9c1b51eSKate Stone // If we made it here, we didn't find an entry that contained the given 122205097246SAdrian Prantl // address. Return the load_addr as start and the amount of bytes betwwen 122305097246SAdrian Prantl // load address and the end of the memory as size. 122409839c33STamas Berghammer range_info.GetRange().SetRangeBase(load_addr); 1225ad007563SHoward Hellyer range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS); 122609839c33STamas Berghammer range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo); 122709839c33STamas Berghammer range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo); 122809839c33STamas Berghammer range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo); 1229ad007563SHoward Hellyer range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo); 1230af245d11STodd Fiala return error; 1231af245d11STodd Fiala } 1232af245d11STodd Fiala 123397206d57SZachary Turner Status NativeProcessLinux::PopulateMemoryRegionCache() { 1234a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1235a6f5795aSTamas Berghammer 1236a6f5795aSTamas Berghammer // If our cache is empty, pull the latest. There should always be at least 1237a6f5795aSTamas Berghammer // one memory region if memory region handling is supported. 1238a6f5795aSTamas Berghammer if (!m_mem_region_cache.empty()) { 1239a6321a8eSPavel Labath LLDB_LOG(log, "reusing {0} cached memory region entries", 1240a6321a8eSPavel Labath m_mem_region_cache.size()); 124197206d57SZachary Turner return Status(); 1242a6f5795aSTamas Berghammer } 1243a6f5795aSTamas Berghammer 124432541685SDavid Spickett Status Result; 124532541685SDavid Spickett LinuxMapCallback callback = [&](llvm::Expected<MemoryRegionInfo> Info) { 124632541685SDavid Spickett if (Info) { 124732541685SDavid Spickett FileSpec file_spec(Info->GetName().GetCString()); 124832541685SDavid Spickett FileSystem::Instance().Resolve(file_spec); 124932541685SDavid Spickett m_mem_region_cache.emplace_back(*Info, file_spec); 125032541685SDavid Spickett return true; 125132541685SDavid Spickett } 125232541685SDavid Spickett 125332541685SDavid Spickett Result = Info.takeError(); 125432541685SDavid Spickett m_supports_mem_region = LazyBool::eLazyBoolNo; 125532541685SDavid Spickett LLDB_LOG(log, "failed to parse proc maps: {0}", Result); 125632541685SDavid Spickett return false; 125732541685SDavid Spickett }; 125832541685SDavid Spickett 125932541685SDavid Spickett // Linux kernel since 2.6.14 has /proc/{pid}/smaps 126032541685SDavid Spickett // if CONFIG_PROC_PAGE_MONITOR is enabled 126132541685SDavid Spickett auto BufferOrError = getProcFile(GetID(), "smaps"); 126232541685SDavid Spickett if (BufferOrError) 126332541685SDavid Spickett ParseLinuxSMapRegions(BufferOrError.get()->getBuffer(), callback); 126432541685SDavid Spickett else { 126532541685SDavid Spickett BufferOrError = getProcFile(GetID(), "maps"); 126615930862SPavel Labath if (!BufferOrError) { 126715930862SPavel Labath m_supports_mem_region = LazyBool::eLazyBoolNo; 126815930862SPavel Labath return BufferOrError.getError(); 126915930862SPavel Labath } 127032541685SDavid Spickett 127132541685SDavid Spickett ParseLinuxMapRegions(BufferOrError.get()->getBuffer(), callback); 1272a6f5795aSTamas Berghammer } 127332541685SDavid Spickett 1274c8e364e8SPavel Labath if (Result.Fail()) 1275c8e364e8SPavel Labath return Result; 1276a6f5795aSTamas Berghammer 127715930862SPavel Labath if (m_mem_region_cache.empty()) { 1278a6f5795aSTamas Berghammer // No entries after attempting to read them. This shouldn't happen if 127905097246SAdrian Prantl // /proc/{pid}/maps is supported. Assume we don't support map entries via 128005097246SAdrian Prantl // procfs. 128115930862SPavel Labath m_supports_mem_region = LazyBool::eLazyBoolNo; 1282a6321a8eSPavel Labath LLDB_LOG(log, 1283a6321a8eSPavel Labath "failed to find any procfs maps entries, assuming no support " 1284a6321a8eSPavel Labath "for memory region metadata retrieval"); 128597206d57SZachary Turner return Status("not supported"); 1286a6f5795aSTamas Berghammer } 1287a6f5795aSTamas Berghammer 1288a6321a8eSPavel Labath LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps", 1289a6321a8eSPavel Labath m_mem_region_cache.size(), GetID()); 1290a6f5795aSTamas Berghammer 1291a6f5795aSTamas Berghammer // We support memory retrieval, remember that. 1292a6f5795aSTamas Berghammer m_supports_mem_region = LazyBool::eLazyBoolYes; 129397206d57SZachary Turner return Status(); 1294a6f5795aSTamas Berghammer } 1295a6f5795aSTamas Berghammer 1296b9c1b51eSKate Stone void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) { 1297a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1298a6321a8eSPavel Labath LLDB_LOG(log, "newBumpId={0}", newBumpId); 1299a6321a8eSPavel Labath LLDB_LOG(log, "clearing {0} entries from memory region cache", 1300a6321a8eSPavel Labath m_mem_region_cache.size()); 1301af245d11STodd Fiala m_mem_region_cache.clear(); 1302af245d11STodd Fiala } 1303af245d11STodd Fiala 13042c4226f8SPavel Labath llvm::Expected<uint64_t> 13052c4226f8SPavel Labath NativeProcessLinux::Syscall(llvm::ArrayRef<uint64_t> args) { 13062c4226f8SPavel Labath PopulateMemoryRegionCache(); 13072c4226f8SPavel Labath auto region_it = llvm::find_if(m_mem_region_cache, [](const auto &pair) { 13082c4226f8SPavel Labath return pair.first.GetExecutable() == MemoryRegionInfo::eYes; 13092c4226f8SPavel Labath }); 13102c4226f8SPavel Labath if (region_it == m_mem_region_cache.end()) 13112c4226f8SPavel Labath return llvm::createStringError(llvm::inconvertibleErrorCode(), 13122c4226f8SPavel Labath "No executable memory region found!"); 1313af245d11STodd Fiala 13142c4226f8SPavel Labath addr_t exe_addr = region_it->first.GetRange().GetRangeBase(); 1315af245d11STodd Fiala 13162c4226f8SPavel Labath NativeThreadLinux &thread = *GetThreadByID(GetID()); 13172c4226f8SPavel Labath assert(thread.GetState() == eStateStopped); 13182c4226f8SPavel Labath NativeRegisterContextLinux ®_ctx = thread.GetRegisterContext(); 13192c4226f8SPavel Labath 13202c4226f8SPavel Labath NativeRegisterContextLinux::SyscallData syscall_data = 13212c4226f8SPavel Labath *reg_ctx.GetSyscallData(); 13222c4226f8SPavel Labath 13232c4226f8SPavel Labath DataBufferSP registers_sp; 13242c4226f8SPavel Labath if (llvm::Error Err = reg_ctx.ReadAllRegisterValues(registers_sp).ToError()) 13252c4226f8SPavel Labath return std::move(Err); 13262c4226f8SPavel Labath auto restore_regs = llvm::make_scope_exit( 13272c4226f8SPavel Labath [&] { reg_ctx.WriteAllRegisterValues(registers_sp); }); 13282c4226f8SPavel Labath 13292c4226f8SPavel Labath llvm::SmallVector<uint8_t, 8> memory(syscall_data.Insn.size()); 13302c4226f8SPavel Labath size_t bytes_read; 13312c4226f8SPavel Labath if (llvm::Error Err = 13322c4226f8SPavel Labath ReadMemory(exe_addr, memory.data(), memory.size(), bytes_read) 13332c4226f8SPavel Labath .ToError()) { 13342c4226f8SPavel Labath return std::move(Err); 1335af245d11STodd Fiala } 1336af245d11STodd Fiala 13372c4226f8SPavel Labath auto restore_mem = llvm::make_scope_exit( 13382c4226f8SPavel Labath [&] { WriteMemory(exe_addr, memory.data(), memory.size(), bytes_read); }); 13392c4226f8SPavel Labath 13402c4226f8SPavel Labath if (llvm::Error Err = reg_ctx.SetPC(exe_addr).ToError()) 13412c4226f8SPavel Labath return std::move(Err); 13422c4226f8SPavel Labath 13432c4226f8SPavel Labath for (const auto &zip : llvm::zip_first(args, syscall_data.Args)) { 13442c4226f8SPavel Labath if (llvm::Error Err = 13452c4226f8SPavel Labath reg_ctx 13462c4226f8SPavel Labath .WriteRegisterFromUnsigned(std::get<1>(zip), std::get<0>(zip)) 13472c4226f8SPavel Labath .ToError()) { 13482c4226f8SPavel Labath return std::move(Err); 13492c4226f8SPavel Labath } 13502c4226f8SPavel Labath } 13512c4226f8SPavel Labath if (llvm::Error Err = WriteMemory(exe_addr, syscall_data.Insn.data(), 13522c4226f8SPavel Labath syscall_data.Insn.size(), bytes_read) 13532c4226f8SPavel Labath .ToError()) 13542c4226f8SPavel Labath return std::move(Err); 13552c4226f8SPavel Labath 13562c4226f8SPavel Labath m_mem_region_cache.clear(); 13572c4226f8SPavel Labath 13582c4226f8SPavel Labath // With software single stepping the syscall insn buffer must also include a 13592c4226f8SPavel Labath // trap instruction to stop the process. 13602c4226f8SPavel Labath int req = SupportHardwareSingleStepping() ? PTRACE_SINGLESTEP : PTRACE_CONT; 13612c4226f8SPavel Labath if (llvm::Error Err = 13622c4226f8SPavel Labath PtraceWrapper(req, thread.GetID(), nullptr, nullptr).ToError()) 13632c4226f8SPavel Labath return std::move(Err); 13642c4226f8SPavel Labath 13652c4226f8SPavel Labath int status; 13662c4226f8SPavel Labath ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, thread.GetID(), 13672c4226f8SPavel Labath &status, __WALL); 13682c4226f8SPavel Labath if (wait_pid == -1) { 13692c4226f8SPavel Labath return llvm::errorCodeToError( 13702c4226f8SPavel Labath std::error_code(errno, std::generic_category())); 13712c4226f8SPavel Labath } 13722c4226f8SPavel Labath assert((unsigned)wait_pid == thread.GetID()); 13732c4226f8SPavel Labath 13742c4226f8SPavel Labath uint64_t result = reg_ctx.ReadRegisterAsUnsigned(syscall_data.Result, -ESRCH); 13752c4226f8SPavel Labath 13762c4226f8SPavel Labath // Values larger than this are actually negative errno numbers. 13772c4226f8SPavel Labath uint64_t errno_threshold = 13782c4226f8SPavel Labath (uint64_t(-1) >> (64 - 8 * m_arch.GetAddressByteSize())) - 0x1000; 13792c4226f8SPavel Labath if (result > errno_threshold) { 13802c4226f8SPavel Labath return llvm::errorCodeToError( 13812c4226f8SPavel Labath std::error_code(-result & 0xfff, std::generic_category())); 13822c4226f8SPavel Labath } 13832c4226f8SPavel Labath 13842c4226f8SPavel Labath return result; 13852c4226f8SPavel Labath } 13862c4226f8SPavel Labath 13872c4226f8SPavel Labath llvm::Expected<addr_t> 13882c4226f8SPavel Labath NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions) { 13892c4226f8SPavel Labath 13902c4226f8SPavel Labath llvm::Optional<NativeRegisterContextLinux::MmapData> mmap_data = 13912c4226f8SPavel Labath GetCurrentThread()->GetRegisterContext().GetMmapData(); 13922c4226f8SPavel Labath if (!mmap_data) 13932c4226f8SPavel Labath return llvm::make_error<UnimplementedError>(); 13942c4226f8SPavel Labath 13952c4226f8SPavel Labath unsigned prot = PROT_NONE; 13962c4226f8SPavel Labath assert((permissions & (ePermissionsReadable | ePermissionsWritable | 13972c4226f8SPavel Labath ePermissionsExecutable)) == permissions && 13982c4226f8SPavel Labath "Unknown permission!"); 13992c4226f8SPavel Labath if (permissions & ePermissionsReadable) 14002c4226f8SPavel Labath prot |= PROT_READ; 14012c4226f8SPavel Labath if (permissions & ePermissionsWritable) 14022c4226f8SPavel Labath prot |= PROT_WRITE; 14032c4226f8SPavel Labath if (permissions & ePermissionsExecutable) 14042c4226f8SPavel Labath prot |= PROT_EXEC; 14052c4226f8SPavel Labath 14062c4226f8SPavel Labath llvm::Expected<uint64_t> Result = 14072c4226f8SPavel Labath Syscall({mmap_data->SysMmap, 0, size, prot, MAP_ANONYMOUS | MAP_PRIVATE, 14082c4226f8SPavel Labath uint64_t(-1), 0}); 14092c4226f8SPavel Labath if (Result) 14102c4226f8SPavel Labath m_allocated_memory.try_emplace(*Result, size); 14112c4226f8SPavel Labath return Result; 14122c4226f8SPavel Labath } 14132c4226f8SPavel Labath 14142c4226f8SPavel Labath llvm::Error NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) { 14152c4226f8SPavel Labath llvm::Optional<NativeRegisterContextLinux::MmapData> mmap_data = 14162c4226f8SPavel Labath GetCurrentThread()->GetRegisterContext().GetMmapData(); 14172c4226f8SPavel Labath if (!mmap_data) 14182c4226f8SPavel Labath return llvm::make_error<UnimplementedError>(); 14192c4226f8SPavel Labath 14202c4226f8SPavel Labath auto it = m_allocated_memory.find(addr); 14212c4226f8SPavel Labath if (it == m_allocated_memory.end()) 14222c4226f8SPavel Labath return llvm::createStringError(llvm::errc::invalid_argument, 14232c4226f8SPavel Labath "Memory not allocated by the debugger."); 14242c4226f8SPavel Labath 14252c4226f8SPavel Labath llvm::Expected<uint64_t> Result = 14262c4226f8SPavel Labath Syscall({mmap_data->SysMunmap, addr, it->second}); 14272c4226f8SPavel Labath if (!Result) 14282c4226f8SPavel Labath return Result.takeError(); 14292c4226f8SPavel Labath 14302c4226f8SPavel Labath m_allocated_memory.erase(it); 14312c4226f8SPavel Labath return llvm::Error::success(); 1432af245d11STodd Fiala } 1433af245d11STodd Fiala 1434b9c1b51eSKate Stone size_t NativeProcessLinux::UpdateThreads() { 143505097246SAdrian Prantl // The NativeProcessLinux monitoring threads are always up to date with 143605097246SAdrian Prantl // respect to thread state and they keep the thread list populated properly. 143705097246SAdrian Prantl // All this method needs to do is return the thread count. 1438af245d11STodd Fiala return m_threads.size(); 1439af245d11STodd Fiala } 1440af245d11STodd Fiala 144197206d57SZachary Turner Status NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size, 1442b9c1b51eSKate Stone bool hardware) { 1443af245d11STodd Fiala if (hardware) 1444d5ffbad2SOmair Javaid return SetHardwareBreakpoint(addr, size); 1445af245d11STodd Fiala else 1446af245d11STodd Fiala return SetSoftwareBreakpoint(addr, size); 1447af245d11STodd Fiala } 1448af245d11STodd Fiala 144997206d57SZachary Turner Status NativeProcessLinux::RemoveBreakpoint(lldb::addr_t addr, bool hardware) { 1450d5ffbad2SOmair Javaid if (hardware) 1451d5ffbad2SOmair Javaid return RemoveHardwareBreakpoint(addr); 1452d5ffbad2SOmair Javaid else 1453d5ffbad2SOmair Javaid return NativeProcessProtocol::RemoveBreakpoint(addr); 1454d5ffbad2SOmair Javaid } 1455d5ffbad2SOmair Javaid 1456f8b825f6SPavel Labath llvm::Expected<llvm::ArrayRef<uint8_t>> 1457f8b825f6SPavel Labath NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(size_t size_hint) { 1458be379e15STamas Berghammer // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the 1459be379e15STamas Berghammer // linux kernel does otherwise. 1460f8b825f6SPavel Labath static const uint8_t g_arm_opcode[] = {0xf0, 0x01, 0xf0, 0xe7}; 1461f8b825f6SPavel Labath static const uint8_t g_thumb_opcode[] = {0x01, 0xde}; 146212286a27SPavel Labath 1463f8b825f6SPavel Labath switch (GetArchitecture().GetMachine()) { 146412286a27SPavel Labath case llvm::Triple::arm: 1465f8b825f6SPavel Labath switch (size_hint) { 146663c8be95STamas Berghammer case 2: 14674f545074SPavel Labath return llvm::makeArrayRef(g_thumb_opcode); 146863c8be95STamas Berghammer case 4: 14694f545074SPavel Labath return llvm::makeArrayRef(g_arm_opcode); 147063c8be95STamas Berghammer default: 1471f8b825f6SPavel Labath return llvm::createStringError(llvm::inconvertibleErrorCode(), 1472f8b825f6SPavel Labath "Unrecognised trap opcode size hint!"); 147363c8be95STamas Berghammer } 1474af245d11STodd Fiala default: 1475f8b825f6SPavel Labath return NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_hint); 1476af245d11STodd Fiala } 1477af245d11STodd Fiala } 1478af245d11STodd Fiala 147997206d57SZachary Turner Status NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size, 1480b9c1b51eSKate Stone size_t &bytes_read) { 1481df7c6995SPavel Labath if (ProcessVmReadvSupported()) { 1482b9c1b51eSKate Stone // The process_vm_readv path is about 50 times faster than ptrace api. We 148305097246SAdrian Prantl // want to use this syscall if it is supported. 1484df7c6995SPavel Labath 1485df7c6995SPavel Labath const ::pid_t pid = GetID(); 1486df7c6995SPavel Labath 1487df7c6995SPavel Labath struct iovec local_iov, remote_iov; 1488df7c6995SPavel Labath local_iov.iov_base = buf; 1489df7c6995SPavel Labath local_iov.iov_len = size; 1490df7c6995SPavel Labath remote_iov.iov_base = reinterpret_cast<void *>(addr); 1491df7c6995SPavel Labath remote_iov.iov_len = size; 1492df7c6995SPavel Labath 1493df7c6995SPavel Labath bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0); 1494df7c6995SPavel Labath const bool success = bytes_read == size; 1495df7c6995SPavel Labath 1496a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1497a6321a8eSPavel Labath LLDB_LOG(log, 1498a6321a8eSPavel Labath "using process_vm_readv to read {0} bytes from inferior " 1499a6321a8eSPavel Labath "address {1:x}: {2}", 150010c41f37SPavel Labath size, addr, success ? "Success" : llvm::sys::StrError(errno)); 1501df7c6995SPavel Labath 1502df7c6995SPavel Labath if (success) 150397206d57SZachary Turner return Status(); 1504a6321a8eSPavel Labath // else the call failed for some reason, let's retry the read using ptrace 1505b9c1b51eSKate Stone // api. 1506df7c6995SPavel Labath } 1507df7c6995SPavel Labath 150819cbe96aSPavel Labath unsigned char *dst = static_cast<unsigned char *>(buf); 150919cbe96aSPavel Labath size_t remainder; 151019cbe96aSPavel Labath long data; 151119cbe96aSPavel Labath 1512a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY)); 1513a6321a8eSPavel Labath LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size); 151419cbe96aSPavel Labath 1515b9c1b51eSKate Stone for (bytes_read = 0; bytes_read < size; bytes_read += remainder) { 151697206d57SZachary Turner Status error = NativeProcessLinux::PtraceWrapper( 1517b9c1b51eSKate Stone PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data); 1518a6321a8eSPavel Labath if (error.Fail()) 151919cbe96aSPavel Labath return error; 152019cbe96aSPavel Labath 152119cbe96aSPavel Labath remainder = size - bytes_read; 152219cbe96aSPavel Labath remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder; 152319cbe96aSPavel Labath 152419cbe96aSPavel Labath // Copy the data into our buffer 1525f6ef187bSMohit K. Bhakkad memcpy(dst, &data, remainder); 152619cbe96aSPavel Labath 1527a6321a8eSPavel Labath LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data); 152819cbe96aSPavel Labath addr += k_ptrace_word_size; 152919cbe96aSPavel Labath dst += k_ptrace_word_size; 153019cbe96aSPavel Labath } 153197206d57SZachary Turner return Status(); 1532af245d11STodd Fiala } 1533af245d11STodd Fiala 153497206d57SZachary Turner Status NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, 1535b9c1b51eSKate Stone size_t size, size_t &bytes_written) { 153619cbe96aSPavel Labath const unsigned char *src = static_cast<const unsigned char *>(buf); 153719cbe96aSPavel Labath size_t remainder; 153897206d57SZachary Turner Status error; 153919cbe96aSPavel Labath 1540a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY)); 1541a6321a8eSPavel Labath LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size); 154219cbe96aSPavel Labath 1543b9c1b51eSKate Stone for (bytes_written = 0; bytes_written < size; bytes_written += remainder) { 154419cbe96aSPavel Labath remainder = size - bytes_written; 154519cbe96aSPavel Labath remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder; 154619cbe96aSPavel Labath 1547b9c1b51eSKate Stone if (remainder == k_ptrace_word_size) { 154819cbe96aSPavel Labath unsigned long data = 0; 1549f6ef187bSMohit K. Bhakkad memcpy(&data, src, k_ptrace_word_size); 155019cbe96aSPavel Labath 1551a6321a8eSPavel Labath LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data); 1552b9c1b51eSKate Stone error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(), 1553b9c1b51eSKate Stone (void *)addr, (void *)data); 1554a6321a8eSPavel Labath if (error.Fail()) 155519cbe96aSPavel Labath return error; 1556b9c1b51eSKate Stone } else { 155719cbe96aSPavel Labath unsigned char buff[8]; 155819cbe96aSPavel Labath size_t bytes_read; 155919cbe96aSPavel Labath error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read); 1560a6321a8eSPavel Labath if (error.Fail()) 156119cbe96aSPavel Labath return error; 156219cbe96aSPavel Labath 156319cbe96aSPavel Labath memcpy(buff, src, remainder); 156419cbe96aSPavel Labath 156519cbe96aSPavel Labath size_t bytes_written_rec; 156619cbe96aSPavel Labath error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec); 1567a6321a8eSPavel Labath if (error.Fail()) 156819cbe96aSPavel Labath return error; 156919cbe96aSPavel Labath 1570a6321a8eSPavel Labath LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src, 1571b9c1b51eSKate Stone *(unsigned long *)buff); 157219cbe96aSPavel Labath } 157319cbe96aSPavel Labath 157419cbe96aSPavel Labath addr += k_ptrace_word_size; 157519cbe96aSPavel Labath src += k_ptrace_word_size; 157619cbe96aSPavel Labath } 157719cbe96aSPavel Labath return error; 1578af245d11STodd Fiala } 1579af245d11STodd Fiala 158097206d57SZachary Turner Status NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) { 158119cbe96aSPavel Labath return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo); 1582af245d11STodd Fiala } 1583af245d11STodd Fiala 158497206d57SZachary Turner Status NativeProcessLinux::GetEventMessage(lldb::tid_t tid, 1585b9c1b51eSKate Stone unsigned long *message) { 158619cbe96aSPavel Labath return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message); 1587af245d11STodd Fiala } 1588af245d11STodd Fiala 158997206d57SZachary Turner Status NativeProcessLinux::Detach(lldb::tid_t tid) { 159097ccc294SChaoren Lin if (tid == LLDB_INVALID_THREAD_ID) 159197206d57SZachary Turner return Status(); 159297ccc294SChaoren Lin 159319cbe96aSPavel Labath return PtraceWrapper(PTRACE_DETACH, tid); 1594af245d11STodd Fiala } 1595af245d11STodd Fiala 1596b9c1b51eSKate Stone bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) { 1597a5be48b3SPavel Labath for (const auto &thread : m_threads) { 1598a5be48b3SPavel Labath assert(thread && "thread list should not contain NULL threads"); 1599a5be48b3SPavel Labath if (thread->GetID() == thread_id) { 1600af245d11STodd Fiala // We have this thread. 1601af245d11STodd Fiala return true; 1602af245d11STodd Fiala } 1603af245d11STodd Fiala } 1604af245d11STodd Fiala 1605af245d11STodd Fiala // We don't have this thread. 1606af245d11STodd Fiala return false; 1607af245d11STodd Fiala } 1608af245d11STodd Fiala 1609b9c1b51eSKate Stone bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) { 1610a6321a8eSPavel Labath Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD); 1611a6321a8eSPavel Labath LLDB_LOG(log, "tid: {0})", thread_id); 16121dbc6c9cSPavel Labath 16131dbc6c9cSPavel Labath bool found = false; 1614b9c1b51eSKate Stone for (auto it = m_threads.begin(); it != m_threads.end(); ++it) { 1615b9c1b51eSKate Stone if (*it && ((*it)->GetID() == thread_id)) { 1616af245d11STodd Fiala m_threads.erase(it); 16171dbc6c9cSPavel Labath found = true; 16181dbc6c9cSPavel Labath break; 1619af245d11STodd Fiala } 1620af245d11STodd Fiala } 1621af245d11STodd Fiala 162299e37695SRavitheja Addepally if (found) 16230b697561SWalter Erquinigo NotifyTracersOfThreadDestroyed(thread_id); 16240b697561SWalter Erquinigo 16259eb1ecb9SPavel Labath SignalIfAllThreadsStopped(); 16261dbc6c9cSPavel Labath return found; 1627af245d11STodd Fiala } 1628af245d11STodd Fiala 16290b697561SWalter Erquinigo Status NativeProcessLinux::NotifyTracersOfNewThread(lldb::tid_t tid) { 16300b697561SWalter Erquinigo Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD)); 16310b697561SWalter Erquinigo Status error(m_intel_pt_manager.OnThreadCreated(tid)); 16320b697561SWalter Erquinigo if (error.Fail()) 16330b697561SWalter Erquinigo LLDB_LOG(log, "Failed to trace a new thread with intel-pt, tid = {0}. {1}", 16340b697561SWalter Erquinigo tid, error.AsCString()); 16350b697561SWalter Erquinigo return error; 16360b697561SWalter Erquinigo } 16370b697561SWalter Erquinigo 16380b697561SWalter Erquinigo Status NativeProcessLinux::NotifyTracersOfThreadDestroyed(lldb::tid_t tid) { 16390b697561SWalter Erquinigo Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD)); 16400b697561SWalter Erquinigo Status error(m_intel_pt_manager.OnThreadDestroyed(tid)); 16410b697561SWalter Erquinigo if (error.Fail()) 16420b697561SWalter Erquinigo LLDB_LOG(log, 16430b697561SWalter Erquinigo "Failed to stop a destroyed thread with intel-pt, tid = {0}. {1}", 16440b697561SWalter Erquinigo tid, error.AsCString()); 16450b697561SWalter Erquinigo return error; 16460b697561SWalter Erquinigo } 16470b697561SWalter Erquinigo 16480b697561SWalter Erquinigo NativeThreadLinux &NativeProcessLinux::AddThread(lldb::tid_t thread_id, 16490b697561SWalter Erquinigo bool resume) { 1650a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD)); 1651a6321a8eSPavel Labath LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id); 1652af245d11STodd Fiala 1653b9c1b51eSKate Stone assert(!HasThreadNoLock(thread_id) && 1654b9c1b51eSKate Stone "attempted to add a thread by id that already exists"); 1655af245d11STodd Fiala 1656af245d11STodd Fiala // If this is the first thread, save it as the current thread 1657af245d11STodd Fiala if (m_threads.empty()) 1658af245d11STodd Fiala SetCurrentThreadID(thread_id); 1659af245d11STodd Fiala 1660a8f3ae7cSJonas Devlieghere m_threads.push_back(std::make_unique<NativeThreadLinux>(*this, thread_id)); 16610b697561SWalter Erquinigo NativeThreadLinux &thread = 16620b697561SWalter Erquinigo static_cast<NativeThreadLinux &>(*m_threads.back()); 166399e37695SRavitheja Addepally 16640b697561SWalter Erquinigo Status tracing_error = NotifyTracersOfNewThread(thread.GetID()); 16650b697561SWalter Erquinigo if (tracing_error.Fail()) { 16660b697561SWalter Erquinigo thread.SetStoppedByProcessorTrace(tracing_error.AsCString()); 16670b697561SWalter Erquinigo StopRunningThreads(thread.GetID()); 16680b697561SWalter Erquinigo } else if (resume) 16690b697561SWalter Erquinigo ResumeThread(thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER); 16700b697561SWalter Erquinigo else 16710b697561SWalter Erquinigo thread.SetStoppedBySignal(SIGSTOP); 167299e37695SRavitheja Addepally 16730b697561SWalter Erquinigo return thread; 1674af245d11STodd Fiala } 1675af245d11STodd Fiala 167697206d57SZachary Turner Status NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path, 1677b9c1b51eSKate Stone FileSpec &file_spec) { 167897206d57SZachary Turner Status error = PopulateMemoryRegionCache(); 1679a6f5795aSTamas Berghammer if (error.Fail()) 1680a6f5795aSTamas Berghammer return error; 1681a6f5795aSTamas Berghammer 16828f3be7a3SJonas Devlieghere FileSpec module_file_spec(module_path); 16838f3be7a3SJonas Devlieghere FileSystem::Instance().Resolve(module_file_spec); 16847cb18bf5STamas Berghammer 16857cb18bf5STamas Berghammer file_spec.Clear(); 1686a6f5795aSTamas Berghammer for (const auto &it : m_mem_region_cache) { 1687a6f5795aSTamas Berghammer if (it.second.GetFilename() == module_file_spec.GetFilename()) { 1688a6f5795aSTamas Berghammer file_spec = it.second; 168997206d57SZachary Turner return Status(); 1690a6f5795aSTamas Berghammer } 1691a6f5795aSTamas Berghammer } 169297206d57SZachary Turner return Status("Module file (%s) not found in /proc/%" PRIu64 "/maps file!", 16937cb18bf5STamas Berghammer module_file_spec.GetFilename().AsCString(), GetID()); 16947cb18bf5STamas Berghammer } 1695c076559aSPavel Labath 169697206d57SZachary Turner Status NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name, 1697b9c1b51eSKate Stone lldb::addr_t &load_addr) { 1698783bfc8cSTamas Berghammer load_addr = LLDB_INVALID_ADDRESS; 169997206d57SZachary Turner Status error = PopulateMemoryRegionCache(); 1700a6f5795aSTamas Berghammer if (error.Fail()) 1701783bfc8cSTamas Berghammer return error; 1702a6f5795aSTamas Berghammer 17038f3be7a3SJonas Devlieghere FileSpec file(file_name); 1704a6f5795aSTamas Berghammer for (const auto &it : m_mem_region_cache) { 1705a6f5795aSTamas Berghammer if (it.second == file) { 1706a6f5795aSTamas Berghammer load_addr = it.first.GetRange().GetRangeBase(); 170797206d57SZachary Turner return Status(); 1708a6f5795aSTamas Berghammer } 1709a6f5795aSTamas Berghammer } 171097206d57SZachary Turner return Status("No load address found for specified file."); 1711783bfc8cSTamas Berghammer } 1712783bfc8cSTamas Berghammer 1713a5be48b3SPavel Labath NativeThreadLinux *NativeProcessLinux::GetThreadByID(lldb::tid_t tid) { 1714a5be48b3SPavel Labath return static_cast<NativeThreadLinux *>( 1715b9c1b51eSKate Stone NativeProcessProtocol::GetThreadByID(tid)); 1716f9077782SPavel Labath } 1717f9077782SPavel Labath 17182c4226f8SPavel Labath NativeThreadLinux *NativeProcessLinux::GetCurrentThread() { 17192c4226f8SPavel Labath return static_cast<NativeThreadLinux *>( 17202c4226f8SPavel Labath NativeProcessProtocol::GetCurrentThread()); 17212c4226f8SPavel Labath } 17222c4226f8SPavel Labath 172397206d57SZachary Turner Status NativeProcessLinux::ResumeThread(NativeThreadLinux &thread, 1724b9c1b51eSKate Stone lldb::StateType state, int signo) { 1725a6321a8eSPavel Labath Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD); 1726a6321a8eSPavel Labath LLDB_LOG(log, "tid: {0}", thread.GetID()); 1727c076559aSPavel Labath 172805097246SAdrian Prantl // Before we do the resume below, first check if we have a pending stop 172905097246SAdrian Prantl // notification that is currently waiting for all threads to stop. This is 173005097246SAdrian Prantl // potentially a buggy situation since we're ostensibly waiting for threads 173105097246SAdrian Prantl // to stop before we send out the pending notification, and here we are 173205097246SAdrian Prantl // resuming one before we send out the pending stop notification. 1733a6321a8eSPavel Labath if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) { 1734a6321a8eSPavel Labath LLDB_LOG(log, 1735a6321a8eSPavel Labath "about to resume tid {0} per explicit request but we have a " 1736a6321a8eSPavel Labath "pending stop notification (tid {1}) that is actively " 1737a6321a8eSPavel Labath "waiting for this thread to stop. Valid sequence of events?", 1738a6321a8eSPavel Labath thread.GetID(), m_pending_notification_tid); 1739c076559aSPavel Labath } 1740c076559aSPavel Labath 174105097246SAdrian Prantl // Request a resume. We expect this to be synchronous and the system to 174205097246SAdrian Prantl // reflect it is running after this completes. 1743b9c1b51eSKate Stone switch (state) { 1744b9c1b51eSKate Stone case eStateRunning: { 1745605b51b8SPavel Labath const auto resume_result = thread.Resume(signo); 17460e1d729bSPavel Labath if (resume_result.Success()) 17470e1d729bSPavel Labath SetState(eStateRunning, true); 17480e1d729bSPavel Labath return resume_result; 1749c076559aSPavel Labath } 1750b9c1b51eSKate Stone case eStateStepping: { 1751605b51b8SPavel Labath const auto step_result = thread.SingleStep(signo); 17520e1d729bSPavel Labath if (step_result.Success()) 17530e1d729bSPavel Labath SetState(eStateRunning, true); 17540e1d729bSPavel Labath return step_result; 17550e1d729bSPavel Labath } 17560e1d729bSPavel Labath default: 17578198db30SPavel Labath LLDB_LOG(log, "Unhandled state {0}.", state); 17580e1d729bSPavel Labath llvm_unreachable("Unhandled state for resume"); 17590e1d729bSPavel Labath } 1760c076559aSPavel Labath } 1761c076559aSPavel Labath 1762c076559aSPavel Labath //===----------------------------------------------------------------------===// 1763c076559aSPavel Labath 1764b9c1b51eSKate Stone void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) { 1765a6321a8eSPavel Labath Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD); 1766a6321a8eSPavel Labath LLDB_LOG(log, "about to process event: (triggering_tid: {0})", 1767a6321a8eSPavel Labath triggering_tid); 1768c076559aSPavel Labath 17690e1d729bSPavel Labath m_pending_notification_tid = triggering_tid; 17700e1d729bSPavel Labath 177105097246SAdrian Prantl // Request a stop for all the thread stops that need to be stopped and are 177205097246SAdrian Prantl // not already known to be stopped. 1773a5be48b3SPavel Labath for (const auto &thread : m_threads) { 1774a5be48b3SPavel Labath if (StateIsRunningState(thread->GetState())) 1775a5be48b3SPavel Labath static_cast<NativeThreadLinux *>(thread.get())->RequestStop(); 17760e1d729bSPavel Labath } 17770e1d729bSPavel Labath 17780e1d729bSPavel Labath SignalIfAllThreadsStopped(); 1779a6321a8eSPavel Labath LLDB_LOG(log, "event processing done"); 1780c076559aSPavel Labath } 1781c076559aSPavel Labath 1782b9c1b51eSKate Stone void NativeProcessLinux::SignalIfAllThreadsStopped() { 17830e1d729bSPavel Labath if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID) 17840e1d729bSPavel Labath return; // No pending notification. Nothing to do. 17850e1d729bSPavel Labath 1786b9c1b51eSKate Stone for (const auto &thread_sp : m_threads) { 17870e1d729bSPavel Labath if (StateIsRunningState(thread_sp->GetState())) 17880e1d729bSPavel Labath return; // Some threads are still running. Don't signal yet. 17890e1d729bSPavel Labath } 17900e1d729bSPavel Labath 17910e1d729bSPavel Labath // We have a pending notification and all threads have stopped. 1792b9c1b51eSKate Stone Log *log( 1793b9c1b51eSKate Stone GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS)); 17949eb1ecb9SPavel Labath 1795b9c1b51eSKate Stone // Clear any temporary breakpoints we used to implement software single 1796b9c1b51eSKate Stone // stepping. 1797b9c1b51eSKate Stone for (const auto &thread_info : m_threads_stepping_with_breakpoint) { 179897206d57SZachary Turner Status error = RemoveBreakpoint(thread_info.second); 17999eb1ecb9SPavel Labath if (error.Fail()) 1800a6321a8eSPavel Labath LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}", 1801a6321a8eSPavel Labath thread_info.first, error); 18029eb1ecb9SPavel Labath } 18039eb1ecb9SPavel Labath m_threads_stepping_with_breakpoint.clear(); 18049eb1ecb9SPavel Labath 18059eb1ecb9SPavel Labath // Notify the delegate about the stop 18060e1d729bSPavel Labath SetCurrentThreadID(m_pending_notification_tid); 1807ed89c7feSPavel Labath SetState(StateType::eStateStopped, true); 18080e1d729bSPavel Labath m_pending_notification_tid = LLDB_INVALID_THREAD_ID; 1809c076559aSPavel Labath } 1810c076559aSPavel Labath 1811b9c1b51eSKate Stone void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) { 1812a6321a8eSPavel Labath Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD); 1813a6321a8eSPavel Labath LLDB_LOG(log, "tid: {0}", thread.GetID()); 18141dbc6c9cSPavel Labath 1815b9c1b51eSKate Stone if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID && 1816b9c1b51eSKate Stone StateIsRunningState(thread.GetState())) { 1817b9c1b51eSKate Stone // We will need to wait for this new thread to stop as well before firing 181805097246SAdrian Prantl // the notification. 1819f9077782SPavel Labath thread.RequestStop(); 1820c076559aSPavel Labath } 1821c076559aSPavel Labath } 1822068f8a7eSTamas Berghammer 1823b9c1b51eSKate Stone void NativeProcessLinux::SigchldHandler() { 1824a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 182519cbe96aSPavel Labath // Process all pending waitpid notifications. 1826b9c1b51eSKate Stone while (true) { 182719cbe96aSPavel Labath int status = -1; 1828c1a6b128SPavel Labath ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, -1, &status, 1829c1a6b128SPavel Labath __WALL | __WNOTHREAD | WNOHANG); 183019cbe96aSPavel Labath 183119cbe96aSPavel Labath if (wait_pid == 0) 183219cbe96aSPavel Labath break; // We are done. 183319cbe96aSPavel Labath 1834b9c1b51eSKate Stone if (wait_pid == -1) { 183597206d57SZachary Turner Status error(errno, eErrorTypePOSIX); 1836a6321a8eSPavel Labath LLDB_LOG(log, "waitpid (-1, &status, _) failed: {0}", error); 183719cbe96aSPavel Labath break; 183819cbe96aSPavel Labath } 183919cbe96aSPavel Labath 18403508fc8cSPavel Labath WaitStatus wait_status = WaitStatus::Decode(status); 18413508fc8cSPavel Labath bool exited = wait_status.type == WaitStatus::Exit || 18423508fc8cSPavel Labath (wait_status.type == WaitStatus::Signal && 18433508fc8cSPavel Labath wait_pid == static_cast<::pid_t>(GetID())); 184419cbe96aSPavel Labath 18453508fc8cSPavel Labath LLDB_LOG( 18463508fc8cSPavel Labath log, 18473508fc8cSPavel Labath "waitpid (-1, &status, _) => pid = {0}, status = {1}, exited = {2}", 18483508fc8cSPavel Labath wait_pid, wait_status, exited); 184919cbe96aSPavel Labath 18503508fc8cSPavel Labath MonitorCallback(wait_pid, exited, wait_status); 185119cbe96aSPavel Labath } 1852068f8a7eSTamas Berghammer } 1853068f8a7eSTamas Berghammer 185405097246SAdrian Prantl // Wrapper for ptrace to catch errors and log calls. Note that ptrace sets 185505097246SAdrian Prantl // errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*) 185697206d57SZachary Turner Status NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr, 1857b9c1b51eSKate Stone void *data, size_t data_size, 1858b9c1b51eSKate Stone long *result) { 185997206d57SZachary Turner Status error; 18604a9babb2SPavel Labath long int ret; 1861068f8a7eSTamas Berghammer 1862068f8a7eSTamas Berghammer Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 1863068f8a7eSTamas Berghammer 1864068f8a7eSTamas Berghammer PtraceDisplayBytes(req, data, data_size); 1865068f8a7eSTamas Berghammer 1866068f8a7eSTamas Berghammer errno = 0; 1867068f8a7eSTamas Berghammer if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET) 1868b9c1b51eSKate Stone ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid), 1869b9c1b51eSKate Stone *(unsigned int *)addr, data); 1870068f8a7eSTamas Berghammer else 1871b9c1b51eSKate Stone ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid), 1872b9c1b51eSKate Stone addr, data); 1873068f8a7eSTamas Berghammer 18744a9babb2SPavel Labath if (ret == -1) 1875068f8a7eSTamas Berghammer error.SetErrorToErrno(); 1876068f8a7eSTamas Berghammer 18774a9babb2SPavel Labath if (result) 18784a9babb2SPavel Labath *result = ret; 18794a9babb2SPavel Labath 188028096200SPavel Labath LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data, 188128096200SPavel Labath data_size, ret); 1882068f8a7eSTamas Berghammer 1883068f8a7eSTamas Berghammer PtraceDisplayBytes(req, data, data_size); 1884068f8a7eSTamas Berghammer 1885a6321a8eSPavel Labath if (error.Fail()) 1886a6321a8eSPavel Labath LLDB_LOG(log, "ptrace() failed: {0}", error); 1887068f8a7eSTamas Berghammer 18884a9babb2SPavel Labath return error; 1889068f8a7eSTamas Berghammer } 189099e37695SRavitheja Addepally 18910b697561SWalter Erquinigo llvm::Expected<TraceSupportedResponse> NativeProcessLinux::TraceSupported() { 18920b697561SWalter Erquinigo if (IntelPTManager::IsSupported()) 18930b697561SWalter Erquinigo return TraceSupportedResponse{"intel-pt", "Intel Processor Trace"}; 18940b697561SWalter Erquinigo return NativeProcessProtocol::TraceSupported(); 189599e37695SRavitheja Addepally } 189699e37695SRavitheja Addepally 18970b697561SWalter Erquinigo Error NativeProcessLinux::TraceStart(StringRef json_request, StringRef type) { 18980b697561SWalter Erquinigo if (type == "intel-pt") { 18990b697561SWalter Erquinigo if (Expected<TraceIntelPTStartRequest> request = 19000b697561SWalter Erquinigo json::parse<TraceIntelPTStartRequest>(json_request, 19010b697561SWalter Erquinigo "TraceIntelPTStartRequest")) { 19020b697561SWalter Erquinigo std::vector<lldb::tid_t> process_threads; 19030b697561SWalter Erquinigo for (auto &thread : m_threads) 19040b697561SWalter Erquinigo process_threads.push_back(thread->GetID()); 19050b697561SWalter Erquinigo return m_intel_pt_manager.TraceStart(*request, process_threads); 19060b697561SWalter Erquinigo } else 19070b697561SWalter Erquinigo return request.takeError(); 190899e37695SRavitheja Addepally } 190999e37695SRavitheja Addepally 19100b697561SWalter Erquinigo return NativeProcessProtocol::TraceStart(json_request, type); 191199e37695SRavitheja Addepally } 191299e37695SRavitheja Addepally 19130b697561SWalter Erquinigo Error NativeProcessLinux::TraceStop(const TraceStopRequest &request) { 19140b697561SWalter Erquinigo if (request.type == "intel-pt") 19150b697561SWalter Erquinigo return m_intel_pt_manager.TraceStop(request); 19160b697561SWalter Erquinigo return NativeProcessProtocol::TraceStop(request); 191799e37695SRavitheja Addepally } 191899e37695SRavitheja Addepally 19190b697561SWalter Erquinigo Expected<json::Value> NativeProcessLinux::TraceGetState(StringRef type) { 19200b697561SWalter Erquinigo if (type == "intel-pt") 19210b697561SWalter Erquinigo return m_intel_pt_manager.GetState(); 19220b697561SWalter Erquinigo return NativeProcessProtocol::TraceGetState(type); 192399e37695SRavitheja Addepally } 192499e37695SRavitheja Addepally 19250b697561SWalter Erquinigo Expected<std::vector<uint8_t>> NativeProcessLinux::TraceGetBinaryData( 19260b697561SWalter Erquinigo const TraceGetBinaryDataRequest &request) { 19270b697561SWalter Erquinigo if (request.type == "intel-pt") 19280b697561SWalter Erquinigo return m_intel_pt_manager.GetBinaryData(request); 19290b697561SWalter Erquinigo return NativeProcessProtocol::TraceGetBinaryData(request); 193099e37695SRavitheja Addepally } 1931