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 11af245d11STodd Fiala #include <errno.h> 12af245d11STodd Fiala #include <stdint.h> 13b9c1b51eSKate Stone #include <string.h> 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" 26d8c338d4STamas Berghammer #include "lldb/Core/EmulateInstruction.h" 276edef204SOleksiy Vyalov #include "lldb/Core/ModuleSpec.h" 28af245d11STodd Fiala #include "lldb/Host/Host.h" 295ad891f7SPavel Labath #include "lldb/Host/HostProcess.h" 30eef758e9SPavel Labath #include "lldb/Host/ProcessLaunchInfo.h" 3124ae6294SZachary Turner #include "lldb/Host/PseudoTerminal.h" 3239de3110SZachary Turner #include "lldb/Host/ThreadLauncher.h" 332a86b555SPavel Labath #include "lldb/Host/common/NativeRegisterContext.h" 344ee1c952SPavel Labath #include "lldb/Host/linux/Ptrace.h" 354ee1c952SPavel Labath #include "lldb/Host/linux/Uio.h" 36816ae4b0SKamil Rytarowski #include "lldb/Host/posix/ProcessLauncherPosixFork.h" 372a86b555SPavel Labath #include "lldb/Symbol/ObjectFile.h" 3890aff47cSZachary Turner #include "lldb/Target/Process.h" 395b981ab9SPavel Labath #include "lldb/Target/Target.h" 40c16f5dcaSChaoren Lin #include "lldb/Utility/LLDBAssert.h" 41d821c997SPavel Labath #include "lldb/Utility/RegisterValue.h" 42d821c997SPavel Labath #include "lldb/Utility/State.h" 4397206d57SZachary Turner #include "lldb/Utility/Status.h" 44f805e190SPavel Labath #include "lldb/Utility/StringExtractor.h" 452c4226f8SPavel Labath #include "llvm/ADT/ScopeExit.h" 4610c41f37SPavel Labath #include "llvm/Support/Errno.h" 4710c41f37SPavel Labath #include "llvm/Support/FileSystem.h" 4810c41f37SPavel Labath #include "llvm/Support/Threading.h" 49af245d11STodd Fiala 50d858487eSTamas Berghammer #include <linux/unistd.h> 51d858487eSTamas Berghammer #include <sys/socket.h> 52df7c6995SPavel Labath #include <sys/syscall.h> 53d858487eSTamas Berghammer #include <sys/types.h> 54d858487eSTamas Berghammer #include <sys/user.h> 55d858487eSTamas Berghammer #include <sys/wait.h> 56d858487eSTamas Berghammer 57af245d11STodd Fiala // Support hardware breakpoints in case it has not been defined 58af245d11STodd Fiala #ifndef TRAP_HWBKPT 59af245d11STodd Fiala #define TRAP_HWBKPT 4 60af245d11STodd Fiala #endif 61af245d11STodd Fiala 627cb18bf5STamas Berghammer using namespace lldb; 637cb18bf5STamas Berghammer using namespace lldb_private; 64db264a6dSTamas Berghammer using namespace lldb_private::process_linux; 657cb18bf5STamas Berghammer using namespace llvm; 667cb18bf5STamas Berghammer 67af245d11STodd Fiala // Private bits we only need internally. 68df7c6995SPavel Labath 69b9c1b51eSKate Stone static bool ProcessVmReadvSupported() { 70df7c6995SPavel Labath static bool is_supported; 71c5f28e2aSKamil Rytarowski static llvm::once_flag flag; 72df7c6995SPavel Labath 73c5f28e2aSKamil Rytarowski llvm::call_once(flag, [] { 74a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 75df7c6995SPavel Labath 76df7c6995SPavel Labath uint32_t source = 0x47424742; 77df7c6995SPavel Labath uint32_t dest = 0; 78df7c6995SPavel Labath 79df7c6995SPavel Labath struct iovec local, remote; 80df7c6995SPavel Labath remote.iov_base = &source; 81df7c6995SPavel Labath local.iov_base = &dest; 82df7c6995SPavel Labath remote.iov_len = local.iov_len = sizeof source; 83df7c6995SPavel Labath 84b9c1b51eSKate Stone // We shall try if cross-process-memory reads work by attempting to read a 85b9c1b51eSKate Stone // value from our own process. 86df7c6995SPavel Labath ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0); 87df7c6995SPavel Labath is_supported = (res == sizeof(source) && source == dest); 88df7c6995SPavel Labath if (is_supported) 89a6321a8eSPavel Labath LLDB_LOG(log, 90a6321a8eSPavel Labath "Detected kernel support for process_vm_readv syscall. " 91a6321a8eSPavel Labath "Fast memory reads enabled."); 92df7c6995SPavel Labath else 93a6321a8eSPavel Labath LLDB_LOG(log, 94a6321a8eSPavel Labath "syscall process_vm_readv failed (error: {0}). Fast memory " 95a6321a8eSPavel Labath "reads disabled.", 9610c41f37SPavel Labath llvm::sys::StrError()); 97df7c6995SPavel Labath }); 98df7c6995SPavel Labath 99df7c6995SPavel Labath return is_supported; 100df7c6995SPavel Labath } 101df7c6995SPavel Labath 102b9c1b51eSKate Stone namespace { 103b9c1b51eSKate Stone void MaybeLogLaunchInfo(const ProcessLaunchInfo &info) { 104a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1054abe5d69SPavel Labath if (!log) 1064abe5d69SPavel Labath return; 1074abe5d69SPavel Labath 1084abe5d69SPavel Labath if (const FileAction *action = info.GetFileActionForFD(STDIN_FILENO)) 109a6321a8eSPavel Labath LLDB_LOG(log, "setting STDIN to '{0}'", action->GetFileSpec()); 1104abe5d69SPavel Labath else 111a6321a8eSPavel Labath LLDB_LOG(log, "leaving STDIN as is"); 1124abe5d69SPavel Labath 1134abe5d69SPavel Labath if (const FileAction *action = info.GetFileActionForFD(STDOUT_FILENO)) 114a6321a8eSPavel Labath LLDB_LOG(log, "setting STDOUT to '{0}'", action->GetFileSpec()); 1154abe5d69SPavel Labath else 116a6321a8eSPavel Labath LLDB_LOG(log, "leaving STDOUT as is"); 1174abe5d69SPavel Labath 1184abe5d69SPavel Labath if (const FileAction *action = info.GetFileActionForFD(STDERR_FILENO)) 119a6321a8eSPavel Labath LLDB_LOG(log, "setting STDERR to '{0}'", action->GetFileSpec()); 1204abe5d69SPavel Labath else 121a6321a8eSPavel Labath LLDB_LOG(log, "leaving STDERR as is"); 1224abe5d69SPavel Labath 1234abe5d69SPavel Labath int i = 0; 124b9c1b51eSKate Stone for (const char **args = info.GetArguments().GetConstArgumentVector(); *args; 125b9c1b51eSKate Stone ++args, ++i) 126a6321a8eSPavel Labath LLDB_LOG(log, "arg {0}: '{1}'", i, *args); 1274abe5d69SPavel Labath } 1284abe5d69SPavel Labath 129b9c1b51eSKate Stone void DisplayBytes(StreamString &s, void *bytes, uint32_t count) { 130af245d11STodd Fiala uint8_t *ptr = (uint8_t *)bytes; 131af245d11STodd Fiala const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count); 132b9c1b51eSKate Stone for (uint32_t i = 0; i < loop_count; i++) { 133af245d11STodd Fiala s.Printf("[%x]", *ptr); 134af245d11STodd Fiala ptr++; 135af245d11STodd Fiala } 136af245d11STodd Fiala } 137af245d11STodd Fiala 138b9c1b51eSKate Stone void PtraceDisplayBytes(int &req, void *data, size_t data_size) { 139aafe053cSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 140a6321a8eSPavel Labath if (!log) 141a6321a8eSPavel Labath return; 142af245d11STodd Fiala StreamString buf; 143af245d11STodd Fiala 144b9c1b51eSKate Stone switch (req) { 145b9c1b51eSKate Stone case PTRACE_POKETEXT: { 146af245d11STodd Fiala DisplayBytes(buf, &data, 8); 147aafe053cSPavel Labath LLDB_LOGV(log, "PTRACE_POKETEXT {0}", buf.GetData()); 148af245d11STodd Fiala break; 149af245d11STodd Fiala } 150b9c1b51eSKate Stone case PTRACE_POKEDATA: { 151af245d11STodd Fiala DisplayBytes(buf, &data, 8); 152aafe053cSPavel Labath LLDB_LOGV(log, "PTRACE_POKEDATA {0}", buf.GetData()); 153af245d11STodd Fiala break; 154af245d11STodd Fiala } 155b9c1b51eSKate Stone case PTRACE_POKEUSER: { 156af245d11STodd Fiala DisplayBytes(buf, &data, 8); 157aafe053cSPavel Labath LLDB_LOGV(log, "PTRACE_POKEUSER {0}", buf.GetData()); 158af245d11STodd Fiala break; 159af245d11STodd Fiala } 160b9c1b51eSKate Stone case PTRACE_SETREGS: { 161af245d11STodd Fiala DisplayBytes(buf, data, data_size); 162aafe053cSPavel Labath LLDB_LOGV(log, "PTRACE_SETREGS {0}", buf.GetData()); 163af245d11STodd Fiala break; 164af245d11STodd Fiala } 165b9c1b51eSKate Stone case PTRACE_SETFPREGS: { 166af245d11STodd Fiala DisplayBytes(buf, data, data_size); 167aafe053cSPavel Labath LLDB_LOGV(log, "PTRACE_SETFPREGS {0}", buf.GetData()); 168af245d11STodd Fiala break; 169af245d11STodd Fiala } 170b9c1b51eSKate Stone case PTRACE_SETSIGINFO: { 171af245d11STodd Fiala DisplayBytes(buf, data, sizeof(siginfo_t)); 172aafe053cSPavel Labath LLDB_LOGV(log, "PTRACE_SETSIGINFO {0}", buf.GetData()); 173af245d11STodd Fiala break; 174af245d11STodd Fiala } 175b9c1b51eSKate Stone case PTRACE_SETREGSET: { 17611edb4eeSPavel Labath // Extract iov_base from data, which is a pointer to the struct iovec 177af245d11STodd Fiala DisplayBytes(buf, *(void **)data, data_size); 178aafe053cSPavel Labath LLDB_LOGV(log, "PTRACE_SETREGSET {0}", buf.GetData()); 179af245d11STodd Fiala break; 180af245d11STodd Fiala } 181b9c1b51eSKate Stone default: {} 182af245d11STodd Fiala } 183af245d11STodd Fiala } 184af245d11STodd Fiala 18519cbe96aSPavel Labath static constexpr unsigned k_ptrace_word_size = sizeof(void *); 186b9c1b51eSKate Stone static_assert(sizeof(long) >= k_ptrace_word_size, 187b9c1b51eSKate Stone "Size of long must be larger than ptrace word size"); 1881107b5a5SPavel Labath } // end of anonymous namespace 1891107b5a5SPavel Labath 190bd7cbc5aSPavel Labath // Simple helper function to ensure flags are enabled on the given file 191bd7cbc5aSPavel Labath // descriptor. 19297206d57SZachary Turner static Status EnsureFDFlags(int fd, int flags) { 19397206d57SZachary Turner Status error; 194bd7cbc5aSPavel Labath 195bd7cbc5aSPavel Labath int status = fcntl(fd, F_GETFL); 196b9c1b51eSKate Stone if (status == -1) { 197bd7cbc5aSPavel Labath error.SetErrorToErrno(); 198bd7cbc5aSPavel Labath return error; 199bd7cbc5aSPavel Labath } 200bd7cbc5aSPavel Labath 201b9c1b51eSKate Stone if (fcntl(fd, F_SETFL, status | flags) == -1) { 202bd7cbc5aSPavel Labath error.SetErrorToErrno(); 203bd7cbc5aSPavel Labath return error; 204bd7cbc5aSPavel Labath } 205bd7cbc5aSPavel Labath 206bd7cbc5aSPavel Labath return error; 207bd7cbc5aSPavel Labath } 208bd7cbc5aSPavel Labath 209af245d11STodd Fiala // Public Static Methods 210af245d11STodd Fiala 21182abefa4SPavel Labath llvm::Expected<std::unique_ptr<NativeProcessProtocol>> 21296e600fcSPavel Labath NativeProcessLinux::Factory::Launch(ProcessLaunchInfo &launch_info, 21396e600fcSPavel Labath NativeDelegate &native_delegate, 21496e600fcSPavel Labath MainLoop &mainloop) const { 215a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 216af245d11STodd Fiala 21796e600fcSPavel Labath MaybeLogLaunchInfo(launch_info); 218af245d11STodd Fiala 21996e600fcSPavel Labath Status status; 22096e600fcSPavel Labath ::pid_t pid = ProcessLauncherPosixFork() 22196e600fcSPavel Labath .LaunchProcess(launch_info, status) 22296e600fcSPavel Labath .GetProcessId(); 22396e600fcSPavel Labath LLDB_LOG(log, "pid = {0:x}", pid); 22496e600fcSPavel Labath if (status.Fail()) { 22596e600fcSPavel Labath LLDB_LOG(log, "failed to launch process: {0}", status); 22696e600fcSPavel Labath return status.ToError(); 227af245d11STodd Fiala } 228af245d11STodd Fiala 22996e600fcSPavel Labath // Wait for the child process to trap on its call to execve. 23096e600fcSPavel Labath int wstatus; 23196e600fcSPavel Labath ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0); 23296e600fcSPavel Labath assert(wpid == pid); 23396e600fcSPavel Labath (void)wpid; 23496e600fcSPavel Labath if (!WIFSTOPPED(wstatus)) { 23596e600fcSPavel Labath LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}", 23696e600fcSPavel Labath WaitStatus::Decode(wstatus)); 23796e600fcSPavel Labath return llvm::make_error<StringError>("Could not sync with inferior process", 23896e600fcSPavel Labath llvm::inconvertibleErrorCode()); 23996e600fcSPavel Labath } 24096e600fcSPavel Labath LLDB_LOG(log, "inferior started, now in stopped state"); 241af245d11STodd Fiala 24236e82208SPavel Labath ProcessInstanceInfo Info; 24336e82208SPavel Labath if (!Host::GetProcessInfo(pid, Info)) { 24436e82208SPavel Labath return llvm::make_error<StringError>("Cannot get process architecture", 24536e82208SPavel Labath llvm::inconvertibleErrorCode()); 24636e82208SPavel Labath } 24796e600fcSPavel Labath 24896e600fcSPavel Labath // Set the architecture to the exe architecture. 24996e600fcSPavel Labath LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid, 25036e82208SPavel Labath Info.GetArchitecture().GetArchitectureName()); 25196e600fcSPavel Labath 25296e600fcSPavel Labath status = SetDefaultPtraceOpts(pid); 25396e600fcSPavel Labath if (status.Fail()) { 25496e600fcSPavel Labath LLDB_LOG(log, "failed to set default ptrace options: {0}", status); 25596e600fcSPavel Labath return status.ToError(); 256af245d11STodd Fiala } 257af245d11STodd Fiala 25882abefa4SPavel Labath return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux( 25964ec505dSJonas Devlieghere pid, launch_info.GetPTY().ReleasePrimaryFileDescriptor(), native_delegate, 26036e82208SPavel Labath Info.GetArchitecture(), mainloop, {pid})); 261af245d11STodd Fiala } 262af245d11STodd Fiala 26382abefa4SPavel Labath llvm::Expected<std::unique_ptr<NativeProcessProtocol>> 26482abefa4SPavel Labath NativeProcessLinux::Factory::Attach( 265b9c1b51eSKate Stone lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate, 26696e600fcSPavel Labath MainLoop &mainloop) const { 267a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 268a6321a8eSPavel Labath LLDB_LOG(log, "pid = {0:x}", pid); 269af245d11STodd Fiala 270af245d11STodd Fiala // Retrieve the architecture for the running process. 27136e82208SPavel Labath ProcessInstanceInfo Info; 27236e82208SPavel Labath if (!Host::GetProcessInfo(pid, Info)) { 27336e82208SPavel Labath return llvm::make_error<StringError>("Cannot get process architecture", 27436e82208SPavel Labath llvm::inconvertibleErrorCode()); 27536e82208SPavel Labath } 276af245d11STodd Fiala 27796e600fcSPavel Labath auto tids_or = NativeProcessLinux::Attach(pid); 27896e600fcSPavel Labath if (!tids_or) 27996e600fcSPavel Labath return tids_or.takeError(); 280af245d11STodd Fiala 28182abefa4SPavel Labath return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux( 28236e82208SPavel Labath pid, -1, native_delegate, Info.GetArchitecture(), mainloop, *tids_or)); 283af245d11STodd Fiala } 284af245d11STodd Fiala 285af245d11STodd Fiala // Public Instance Methods 286af245d11STodd Fiala 28796e600fcSPavel Labath NativeProcessLinux::NativeProcessLinux(::pid_t pid, int terminal_fd, 28896e600fcSPavel Labath NativeDelegate &delegate, 28982abefa4SPavel Labath const ArchSpec &arch, MainLoop &mainloop, 29082abefa4SPavel Labath llvm::ArrayRef<::pid_t> tids) 291f4335b8eSAntonio Afonso : NativeProcessELF(pid, terminal_fd, delegate), m_arch(arch) { 292b9c1b51eSKate Stone if (m_terminal_fd != -1) { 29396e600fcSPavel Labath Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK); 29496e600fcSPavel Labath assert(status.Success()); 2955ad891f7SPavel Labath } 296af245d11STodd Fiala 29796e600fcSPavel Labath Status status; 29896e600fcSPavel Labath m_sigchld_handle = mainloop.RegisterSignal( 29996e600fcSPavel Labath SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status); 30096e600fcSPavel Labath assert(m_sigchld_handle && status.Success()); 30196e600fcSPavel Labath 30296e600fcSPavel Labath for (const auto &tid : tids) { 303a5be48b3SPavel Labath NativeThreadLinux &thread = AddThread(tid); 304a5be48b3SPavel Labath thread.SetStoppedBySignal(SIGSTOP); 305a5be48b3SPavel Labath ThreadWasCreated(thread); 306af245d11STodd Fiala } 307af245d11STodd Fiala 30896e600fcSPavel Labath // Let our process instance know the thread has stopped. 30996e600fcSPavel Labath SetCurrentThreadID(tids[0]); 31096e600fcSPavel Labath SetState(StateType::eStateStopped, false); 31196e600fcSPavel Labath 31296e600fcSPavel Labath // Proccess any signals we received before installing our handler 31396e600fcSPavel Labath SigchldHandler(); 31496e600fcSPavel Labath } 31596e600fcSPavel Labath 31696e600fcSPavel Labath llvm::Expected<std::vector<::pid_t>> NativeProcessLinux::Attach(::pid_t pid) { 317a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 318af245d11STodd Fiala 31996e600fcSPavel Labath Status status; 320b9c1b51eSKate Stone // Use a map to keep track of the threads which we have attached/need to 321b9c1b51eSKate Stone // attach. 322af245d11STodd Fiala Host::TidMap tids_to_attach; 323b9c1b51eSKate Stone while (Host::FindProcessThreads(pid, tids_to_attach)) { 324af245d11STodd Fiala for (Host::TidMap::iterator it = tids_to_attach.begin(); 325b9c1b51eSKate Stone it != tids_to_attach.end();) { 326b9c1b51eSKate Stone if (it->second == false) { 327af245d11STodd Fiala lldb::tid_t tid = it->first; 328af245d11STodd Fiala 329af245d11STodd Fiala // Attach to the requested process. 330af245d11STodd Fiala // An attach will cause the thread to stop with a SIGSTOP. 33196e600fcSPavel Labath if ((status = PtraceWrapper(PTRACE_ATTACH, tid)).Fail()) { 33205097246SAdrian Prantl // No such thread. The thread may have exited. More error handling 33305097246SAdrian Prantl // may be needed. 33496e600fcSPavel Labath if (status.GetError() == ESRCH) { 335af245d11STodd Fiala it = tids_to_attach.erase(it); 336af245d11STodd Fiala continue; 33796e600fcSPavel Labath } 33896e600fcSPavel Labath return status.ToError(); 339af245d11STodd Fiala } 340af245d11STodd Fiala 34196e600fcSPavel Labath int wpid = 34296e600fcSPavel Labath llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, nullptr, __WALL); 34305097246SAdrian Prantl // Need to use __WALL otherwise we receive an error with errno=ECHLD At 34405097246SAdrian Prantl // this point we should have a thread stopped if waitpid succeeds. 34596e600fcSPavel Labath if (wpid < 0) { 34605097246SAdrian Prantl // No such thread. The thread may have exited. More error handling 34705097246SAdrian Prantl // may be needed. 348b9c1b51eSKate Stone if (errno == ESRCH) { 349af245d11STodd Fiala it = tids_to_attach.erase(it); 350af245d11STodd Fiala continue; 351af245d11STodd Fiala } 35296e600fcSPavel Labath return llvm::errorCodeToError( 35396e600fcSPavel Labath std::error_code(errno, std::generic_category())); 354af245d11STodd Fiala } 355af245d11STodd Fiala 35696e600fcSPavel Labath if ((status = SetDefaultPtraceOpts(tid)).Fail()) 35796e600fcSPavel Labath return status.ToError(); 358af245d11STodd Fiala 359a6321a8eSPavel Labath LLDB_LOG(log, "adding tid = {0}", tid); 360af245d11STodd Fiala it->second = true; 361af245d11STodd Fiala } 362af245d11STodd Fiala 363af245d11STodd Fiala // move the loop forward 364af245d11STodd Fiala ++it; 365af245d11STodd Fiala } 366af245d11STodd Fiala } 367af245d11STodd Fiala 36896e600fcSPavel Labath size_t tid_count = tids_to_attach.size(); 36996e600fcSPavel Labath if (tid_count == 0) 37096e600fcSPavel Labath return llvm::make_error<StringError>("No such process", 37196e600fcSPavel Labath llvm::inconvertibleErrorCode()); 372af245d11STodd Fiala 37396e600fcSPavel Labath std::vector<::pid_t> tids; 37496e600fcSPavel Labath tids.reserve(tid_count); 37596e600fcSPavel Labath for (const auto &p : tids_to_attach) 37696e600fcSPavel Labath tids.push_back(p.first); 37796e600fcSPavel Labath return std::move(tids); 378af245d11STodd Fiala } 379af245d11STodd Fiala 38097206d57SZachary Turner Status NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid) { 381af245d11STodd Fiala long ptrace_opts = 0; 382af245d11STodd Fiala 383af245d11STodd Fiala // Have the child raise an event on exit. This is used to keep the child in 384af245d11STodd Fiala // limbo until it is destroyed. 385af245d11STodd Fiala ptrace_opts |= PTRACE_O_TRACEEXIT; 386af245d11STodd Fiala 387af245d11STodd Fiala // Have the tracer trace threads which spawn in the inferior process. 388af245d11STodd Fiala // TODO: if we want to support tracing the inferiors' child, add the 389af245d11STodd Fiala // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK) 390af245d11STodd Fiala ptrace_opts |= PTRACE_O_TRACECLONE; 391af245d11STodd Fiala 39205097246SAdrian Prantl // Have the tracer notify us before execve returns (needed to disable legacy 39305097246SAdrian Prantl // SIGTRAP generation) 394af245d11STodd Fiala ptrace_opts |= PTRACE_O_TRACEEXEC; 395af245d11STodd Fiala 3964a9babb2SPavel Labath return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void *)ptrace_opts); 397af245d11STodd Fiala } 398af245d11STodd Fiala 3991107b5a5SPavel Labath // Handles all waitpid events from the inferior process. 400b9c1b51eSKate Stone void NativeProcessLinux::MonitorCallback(lldb::pid_t pid, bool exited, 4013508fc8cSPavel Labath WaitStatus status) { 402af245d11STodd Fiala Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 403af245d11STodd Fiala 404b9c1b51eSKate Stone // Certain activities differ based on whether the pid is the tid of the main 405b9c1b51eSKate Stone // thread. 4061107b5a5SPavel Labath const bool is_main_thread = (pid == GetID()); 407af245d11STodd Fiala 408af245d11STodd Fiala // Handle when the thread exits. 409b9c1b51eSKate Stone if (exited) { 410d8b3c1a1SPavel Labath LLDB_LOG(log, 4119303afb3SPavel Labath "got exit status({0}) , tid = {1} ({2} main thread), process " 412d8b3c1a1SPavel Labath "state = {3}", 4139303afb3SPavel Labath status, pid, is_main_thread ? "is" : "is not", GetState()); 414af245d11STodd Fiala 415af245d11STodd Fiala // This is a thread that exited. Ensure we're not tracking it anymore. 416d8b3c1a1SPavel Labath StopTrackingThread(pid); 417af245d11STodd Fiala 418b9c1b51eSKate Stone if (is_main_thread) { 419af245d11STodd Fiala // The main thread exited. We're done monitoring. Report to delegate. 4203508fc8cSPavel Labath SetExitStatus(status, true); 421af245d11STodd Fiala 422af245d11STodd Fiala // Notify delegate that our process has exited. 4231107b5a5SPavel Labath SetState(StateType::eStateExited, true); 424af245d11STodd Fiala } 4251107b5a5SPavel Labath return; 426af245d11STodd Fiala } 427af245d11STodd Fiala 428af245d11STodd Fiala siginfo_t info; 429b9cc0c75SPavel Labath const auto info_err = GetSignalInfo(pid, &info); 430b9cc0c75SPavel Labath auto thread_sp = GetThreadByID(pid); 431b9cc0c75SPavel Labath 432b9c1b51eSKate Stone if (!thread_sp) { 43305097246SAdrian Prantl // Normally, the only situation when we cannot find the thread is if we 43405097246SAdrian Prantl // have just received a new thread notification. This is indicated by 435a6321a8eSPavel Labath // GetSignalInfo() returning si_code == SI_USER and si_pid == 0 436a6321a8eSPavel Labath LLDB_LOG(log, "received notification about an unknown tid {0}.", pid); 437b9cc0c75SPavel Labath 438b9c1b51eSKate Stone if (info_err.Fail()) { 439a6321a8eSPavel Labath LLDB_LOG(log, 440a6321a8eSPavel Labath "(tid {0}) GetSignalInfo failed ({1}). " 441a6321a8eSPavel Labath "Ingoring this notification.", 442a6321a8eSPavel Labath pid, info_err); 443b9cc0c75SPavel Labath return; 444b9cc0c75SPavel Labath } 445b9cc0c75SPavel Labath 446a6321a8eSPavel Labath LLDB_LOG(log, "tid {0}, si_code: {1}, si_pid: {2}", pid, info.si_code, 447a6321a8eSPavel Labath info.si_pid); 448b9cc0c75SPavel Labath 449a5be48b3SPavel Labath NativeThreadLinux &thread = AddThread(pid); 45099e37695SRavitheja Addepally 451b9cc0c75SPavel Labath // Resume the newly created thread. 452a5be48b3SPavel Labath ResumeThread(thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER); 453a5be48b3SPavel Labath ThreadWasCreated(thread); 454b9cc0c75SPavel Labath return; 455b9cc0c75SPavel Labath } 456b9cc0c75SPavel Labath 457b9cc0c75SPavel Labath // Get details on the signal raised. 458b9c1b51eSKate Stone if (info_err.Success()) { 459fa03ad2eSChaoren Lin // We have retrieved the signal info. Dispatch appropriately. 460fa03ad2eSChaoren Lin if (info.si_signo == SIGTRAP) 461b9cc0c75SPavel Labath MonitorSIGTRAP(info, *thread_sp); 462fa03ad2eSChaoren Lin else 463b9cc0c75SPavel Labath MonitorSignal(info, *thread_sp, exited); 464b9c1b51eSKate Stone } else { 465b9c1b51eSKate Stone if (info_err.GetError() == EINVAL) { 46605097246SAdrian Prantl // This is a group stop reception for this tid. We can reach here if we 46705097246SAdrian Prantl // reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the tracee, 46805097246SAdrian Prantl // triggering the group-stop mechanism. Normally receiving these would 46905097246SAdrian Prantl // stop the process, pending a SIGCONT. Simulating this state in a 47005097246SAdrian Prantl // debugger is hard and is generally not needed (one use case is 47105097246SAdrian Prantl // debugging background task being managed by a shell). For general use, 47205097246SAdrian Prantl // it is sufficient to stop the process in a signal-delivery stop which 47305097246SAdrian Prantl // happens before the group stop. This done by MonitorSignal and works 47405097246SAdrian Prantl // correctly for all signals. 475a6321a8eSPavel Labath LLDB_LOG(log, 476a6321a8eSPavel Labath "received a group stop for pid {0} tid {1}. Transparent " 477a6321a8eSPavel Labath "handling of group stops not supported, resuming the " 478a6321a8eSPavel Labath "thread.", 479a6321a8eSPavel Labath GetID(), pid); 480b9c1b51eSKate Stone ResumeThread(*thread_sp, thread_sp->GetState(), 481b9c1b51eSKate Stone LLDB_INVALID_SIGNAL_NUMBER); 482b9c1b51eSKate Stone } else { 483af245d11STodd Fiala // ptrace(GETSIGINFO) failed (but not due to group-stop). 484af245d11STodd Fiala 485b9c1b51eSKate Stone // A return value of ESRCH means the thread/process is no longer on the 486a6321a8eSPavel Labath // system, so it was killed somehow outside of our control. Either way, 487a6321a8eSPavel Labath // we can't do anything with it anymore. 488af245d11STodd Fiala 489b9c1b51eSKate Stone // Stop tracking the metadata for the thread since it's entirely off the 490b9c1b51eSKate Stone // system now. 4911107b5a5SPavel Labath const bool thread_found = StopTrackingThread(pid); 492af245d11STodd Fiala 493a6321a8eSPavel Labath LLDB_LOG(log, 4949303afb3SPavel Labath "GetSignalInfo failed: {0}, tid = {1}, status = {2}, " 495a6321a8eSPavel Labath "status = {3}, main_thread = {4}, thread_found: {5}", 4969303afb3SPavel Labath info_err, pid, status, status, is_main_thread, thread_found); 497af245d11STodd Fiala 498b9c1b51eSKate Stone if (is_main_thread) { 499b9c1b51eSKate Stone // Notify the delegate - our process is not available but appears to 50005097246SAdrian Prantl // have been killed outside our control. Is eStateExited the right 50105097246SAdrian Prantl // exit state in this case? 5023508fc8cSPavel Labath SetExitStatus(status, true); 5031107b5a5SPavel Labath SetState(StateType::eStateExited, true); 504b9c1b51eSKate Stone } else { 505b9c1b51eSKate Stone // This thread was pulled out from underneath us. Anything to do here? 506b9c1b51eSKate Stone // Do we want to do an all stop? 507a6321a8eSPavel Labath LLDB_LOG(log, 508a6321a8eSPavel Labath "pid {0} tid {1} non-main thread exit occurred, didn't " 509a6321a8eSPavel Labath "tell delegate anything since thread disappeared out " 510a6321a8eSPavel Labath "from underneath us", 511a6321a8eSPavel Labath GetID(), pid); 512af245d11STodd Fiala } 513af245d11STodd Fiala } 514af245d11STodd Fiala } 515af245d11STodd Fiala } 516af245d11STodd Fiala 517b9c1b51eSKate Stone void NativeProcessLinux::WaitForNewThread(::pid_t tid) { 518a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 519426bdf88SPavel Labath 520a5be48b3SPavel Labath if (GetThreadByID(tid)) { 521b9c1b51eSKate Stone // We are already tracking the thread - we got the event on the new thread 522a5be48b3SPavel Labath // (see MonitorSignal) before this one. We are done. 523426bdf88SPavel Labath return; 524426bdf88SPavel Labath } 525426bdf88SPavel Labath 526426bdf88SPavel Labath // The thread is not tracked yet, let's wait for it to appear. 527426bdf88SPavel Labath int status = -1; 528a6321a8eSPavel Labath LLDB_LOG(log, 529a6321a8eSPavel Labath "received thread creation event for tid {0}. tid not tracked " 530a6321a8eSPavel Labath "yet, waiting for thread to appear...", 531a6321a8eSPavel Labath tid); 532c1a6b128SPavel Labath ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, &status, __WALL); 533b9c1b51eSKate Stone // Since we are waiting on a specific tid, this must be the creation event. 534a6321a8eSPavel Labath // But let's do some checks just in case. 535426bdf88SPavel Labath if (wait_pid != tid) { 536a6321a8eSPavel Labath LLDB_LOG(log, 537a6321a8eSPavel Labath "waiting for tid {0} failed. Assuming the thread has " 538a6321a8eSPavel Labath "disappeared in the meantime", 539a6321a8eSPavel Labath tid); 540426bdf88SPavel Labath // The only way I know of this could happen is if the whole process was 541b9c1b51eSKate Stone // SIGKILLed in the mean time. In any case, we can't do anything about that 542b9c1b51eSKate Stone // now. 543426bdf88SPavel Labath return; 544426bdf88SPavel Labath } 545b9c1b51eSKate Stone if (WIFEXITED(status)) { 546a6321a8eSPavel Labath LLDB_LOG(log, 547a6321a8eSPavel Labath "waiting for tid {0} returned an 'exited' event. Not " 548a6321a8eSPavel Labath "tracking the thread.", 549a6321a8eSPavel Labath tid); 550426bdf88SPavel Labath // Also a very improbable event. 551426bdf88SPavel Labath return; 552426bdf88SPavel Labath } 553426bdf88SPavel Labath 554a6321a8eSPavel Labath LLDB_LOG(log, "pid = {0}: tracking new thread tid {1}", GetID(), tid); 555a5be48b3SPavel Labath NativeThreadLinux &new_thread = AddThread(tid); 55699e37695SRavitheja Addepally 557a5be48b3SPavel Labath ResumeThread(new_thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER); 558a5be48b3SPavel Labath ThreadWasCreated(new_thread); 559426bdf88SPavel Labath } 560426bdf88SPavel Labath 561b9c1b51eSKate Stone void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info, 562b9c1b51eSKate Stone NativeThreadLinux &thread) { 563a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 564b9cc0c75SPavel Labath const bool is_main_thread = (thread.GetID() == GetID()); 565af245d11STodd Fiala 566b9cc0c75SPavel Labath assert(info.si_signo == SIGTRAP && "Unexpected child signal!"); 567af245d11STodd Fiala 568b9c1b51eSKate Stone switch (info.si_code) { 569b9c1b51eSKate Stone // TODO: these two cases are required if we want to support tracing of the 57005097246SAdrian Prantl // inferiors' children. We'd need this to debug a monitor. case (SIGTRAP | 57105097246SAdrian Prantl // (PTRACE_EVENT_FORK << 8)): case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)): 572af245d11STodd Fiala 573b9c1b51eSKate Stone case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): { 574b9c1b51eSKate Stone // This is the notification on the parent thread which informs us of new 57505097246SAdrian Prantl // thread creation. We don't want to do anything with the parent thread so 57605097246SAdrian Prantl // we just resume it. In case we want to implement "break on thread 57705097246SAdrian Prantl // creation" functionality, we would need to stop here. 578af245d11STodd Fiala 579af245d11STodd Fiala unsigned long event_message = 0; 580b9c1b51eSKate Stone if (GetEventMessage(thread.GetID(), &event_message).Fail()) { 581a6321a8eSPavel Labath LLDB_LOG(log, 582a6321a8eSPavel Labath "pid {0} received thread creation event but " 583a6321a8eSPavel Labath "GetEventMessage failed so we don't know the new tid", 584a6321a8eSPavel Labath thread.GetID()); 585426bdf88SPavel Labath } else 586426bdf88SPavel Labath WaitForNewThread(event_message); 587af245d11STodd Fiala 588b9cc0c75SPavel Labath ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER); 589af245d11STodd Fiala break; 590af245d11STodd Fiala } 591af245d11STodd Fiala 592b9c1b51eSKate Stone case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): { 593a6321a8eSPavel Labath LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP); 594a9882ceeSTodd Fiala 5951dbc6c9cSPavel Labath // Exec clears any pending notifications. 5960e1d729bSPavel Labath m_pending_notification_tid = LLDB_INVALID_THREAD_ID; 597fa03ad2eSChaoren Lin 598b9c1b51eSKate Stone // Remove all but the main thread here. Linux fork creates a new process 599b9c1b51eSKate Stone // which only copies the main thread. 600a6321a8eSPavel Labath LLDB_LOG(log, "exec received, stop tracking all but main thread"); 601a9882ceeSTodd Fiala 602ee74c9e5SPavel Labath llvm::erase_if(m_threads, [&](std::unique_ptr<NativeThreadProtocol> &t) { 603ee74c9e5SPavel Labath return t->GetID() != GetID(); 604ee74c9e5SPavel Labath }); 605a5be48b3SPavel Labath assert(m_threads.size() == 1); 606a5be48b3SPavel Labath auto *main_thread = static_cast<NativeThreadLinux *>(m_threads[0].get()); 607a9882ceeSTodd Fiala 608a5be48b3SPavel Labath SetCurrentThreadID(main_thread->GetID()); 609a5be48b3SPavel Labath main_thread->SetStoppedByExec(); 610a9882ceeSTodd Fiala 611fa03ad2eSChaoren Lin // Tell coordinator about about the "new" (since exec) stopped main thread. 612a5be48b3SPavel Labath ThreadWasCreated(*main_thread); 613fa03ad2eSChaoren Lin 614a9882ceeSTodd Fiala // Let our delegate know we have just exec'd. 615a9882ceeSTodd Fiala NotifyDidExec(); 616a9882ceeSTodd Fiala 617fa03ad2eSChaoren Lin // Let the process know we're stopped. 618a5be48b3SPavel Labath StopRunningThreads(main_thread->GetID()); 619a9882ceeSTodd Fiala 620af245d11STodd Fiala break; 621a9882ceeSTodd Fiala } 622af245d11STodd Fiala 623b9c1b51eSKate Stone case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): { 62405097246SAdrian Prantl // The inferior process or one of its threads is about to exit. We don't 62505097246SAdrian Prantl // want to do anything with the thread so we just resume it. In case we 62605097246SAdrian Prantl // want to implement "break on thread exit" functionality, we would need to 62705097246SAdrian Prantl // stop here. 628fa03ad2eSChaoren Lin 629af245d11STodd Fiala unsigned long data = 0; 630b9cc0c75SPavel Labath if (GetEventMessage(thread.GetID(), &data).Fail()) 631af245d11STodd Fiala data = -1; 632af245d11STodd Fiala 633a6321a8eSPavel Labath LLDB_LOG(log, 634a6321a8eSPavel Labath "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, " 635a6321a8eSPavel Labath "WIFSIGNALED={2}, pid = {3}, main_thread = {4}", 636a6321a8eSPavel Labath data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(), 637a6321a8eSPavel Labath is_main_thread); 638af245d11STodd Fiala 63975f47c3aSTodd Fiala 64086852d36SPavel Labath StateType state = thread.GetState(); 641b9c1b51eSKate Stone if (!StateIsRunningState(state)) { 642b9c1b51eSKate Stone // Due to a kernel bug, we may sometimes get this stop after the inferior 643d8b3c1a1SPavel Labath // gets a SIGKILL. This confuses our state tracking logic in 644d8b3c1a1SPavel Labath // ResumeThread(), since normally, we should not be receiving any ptrace 64505097246SAdrian Prantl // events while the inferior is stopped. This makes sure that the 64605097246SAdrian Prantl // inferior is resumed and exits normally. 64786852d36SPavel Labath state = eStateRunning; 64886852d36SPavel Labath } 64986852d36SPavel Labath ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER); 650af245d11STodd Fiala 651af245d11STodd Fiala break; 652af245d11STodd Fiala } 653af245d11STodd Fiala 654af245d11STodd Fiala case 0: 655c16f5dcaSChaoren Lin case TRAP_TRACE: // We receive this on single stepping. 656c16f5dcaSChaoren Lin case TRAP_HWBKPT: // We receive this on watchpoint hit 65786fd8e45SChaoren Lin { 658c16f5dcaSChaoren Lin // If a watchpoint was hit, report it 659c16f5dcaSChaoren Lin uint32_t wp_index; 660d37349f3SPavel Labath Status error = thread.GetRegisterContext().GetWatchpointHitIndex( 661b9c1b51eSKate Stone wp_index, (uintptr_t)info.si_addr); 662a6321a8eSPavel Labath if (error.Fail()) 663a6321a8eSPavel Labath LLDB_LOG(log, 664a6321a8eSPavel Labath "received error while checking for watchpoint hits, pid = " 665a6321a8eSPavel Labath "{0}, error = {1}", 666a6321a8eSPavel Labath thread.GetID(), error); 667b9c1b51eSKate Stone if (wp_index != LLDB_INVALID_INDEX32) { 668b9cc0c75SPavel Labath MonitorWatchpoint(thread, wp_index); 669c16f5dcaSChaoren Lin break; 670c16f5dcaSChaoren Lin } 671b9cc0c75SPavel Labath 672d5ffbad2SOmair Javaid // If a breakpoint was hit, report it 673d5ffbad2SOmair Javaid uint32_t bp_index; 674d37349f3SPavel Labath error = thread.GetRegisterContext().GetHardwareBreakHitIndex( 675d5ffbad2SOmair Javaid bp_index, (uintptr_t)info.si_addr); 676d5ffbad2SOmair Javaid if (error.Fail()) 677d5ffbad2SOmair Javaid LLDB_LOG(log, "received error while checking for hardware " 678d5ffbad2SOmair Javaid "breakpoint hits, pid = {0}, error = {1}", 679d5ffbad2SOmair Javaid thread.GetID(), error); 680d5ffbad2SOmair Javaid if (bp_index != LLDB_INVALID_INDEX32) { 681d5ffbad2SOmair Javaid MonitorBreakpoint(thread); 682d5ffbad2SOmair Javaid break; 683d5ffbad2SOmair Javaid } 684d5ffbad2SOmair Javaid 685be379e15STamas Berghammer // Otherwise, report step over 686be379e15STamas Berghammer MonitorTrace(thread); 687af245d11STodd Fiala break; 688b9cc0c75SPavel Labath } 689af245d11STodd Fiala 690af245d11STodd Fiala case SI_KERNEL: 69135799963SMohit K. Bhakkad #if defined __mips__ 69205097246SAdrian Prantl // For mips there is no special signal for watchpoint So we check for 69305097246SAdrian Prantl // watchpoint in kernel trap 69435799963SMohit K. Bhakkad { 69535799963SMohit K. Bhakkad // If a watchpoint was hit, report it 69635799963SMohit K. Bhakkad uint32_t wp_index; 697d37349f3SPavel Labath Status error = thread.GetRegisterContext().GetWatchpointHitIndex( 698b9c1b51eSKate Stone wp_index, LLDB_INVALID_ADDRESS); 699a6321a8eSPavel Labath if (error.Fail()) 700a6321a8eSPavel Labath LLDB_LOG(log, 701a6321a8eSPavel Labath "received error while checking for watchpoint hits, pid = " 702a6321a8eSPavel Labath "{0}, error = {1}", 703a6321a8eSPavel Labath thread.GetID(), error); 704b9c1b51eSKate Stone if (wp_index != LLDB_INVALID_INDEX32) { 705b9cc0c75SPavel Labath MonitorWatchpoint(thread, wp_index); 70635799963SMohit K. Bhakkad break; 70735799963SMohit K. Bhakkad } 70835799963SMohit K. Bhakkad } 70935799963SMohit K. Bhakkad // NO BREAK 71035799963SMohit K. Bhakkad #endif 711af245d11STodd Fiala case TRAP_BRKPT: 712b9cc0c75SPavel Labath MonitorBreakpoint(thread); 713af245d11STodd Fiala break; 714af245d11STodd Fiala 715af245d11STodd Fiala case SIGTRAP: 716af245d11STodd Fiala case (SIGTRAP | 0x80): 717a6321a8eSPavel Labath LLDB_LOG( 718a6321a8eSPavel Labath log, 719a6321a8eSPavel Labath "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming", 720a6321a8eSPavel Labath info.si_code, GetID(), thread.GetID()); 721fa03ad2eSChaoren Lin 722af245d11STodd Fiala // Ignore these signals until we know more about them. 723b9cc0c75SPavel Labath ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER); 724af245d11STodd Fiala break; 725af245d11STodd Fiala 726af245d11STodd Fiala default: 72721a365baSPavel Labath LLDB_LOG(log, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}", 728a6321a8eSPavel Labath info.si_code, GetID(), thread.GetID()); 72921a365baSPavel Labath MonitorSignal(info, thread, false); 730af245d11STodd Fiala break; 731af245d11STodd Fiala } 732af245d11STodd Fiala } 733af245d11STodd Fiala 734b9c1b51eSKate Stone void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) { 735a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 736a6321a8eSPavel Labath LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID()); 737c16f5dcaSChaoren Lin 7380e1d729bSPavel Labath // This thread is currently stopped. 739b9cc0c75SPavel Labath thread.SetStoppedByTrace(); 740c16f5dcaSChaoren Lin 741b9cc0c75SPavel Labath StopRunningThreads(thread.GetID()); 742c16f5dcaSChaoren Lin } 743c16f5dcaSChaoren Lin 744b9c1b51eSKate Stone void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) { 745b9c1b51eSKate Stone Log *log( 746b9c1b51eSKate Stone GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS)); 747a6321a8eSPavel Labath LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID()); 748c16f5dcaSChaoren Lin 749c16f5dcaSChaoren Lin // Mark the thread as stopped at breakpoint. 750b9cc0c75SPavel Labath thread.SetStoppedByBreakpoint(); 751aef7908fSPavel Labath FixupBreakpointPCAsNeeded(thread); 752d8c338d4STamas Berghammer 753b9c1b51eSKate Stone if (m_threads_stepping_with_breakpoint.find(thread.GetID()) != 754b9c1b51eSKate Stone m_threads_stepping_with_breakpoint.end()) 755b9cc0c75SPavel Labath thread.SetStoppedByTrace(); 756c16f5dcaSChaoren Lin 757b9cc0c75SPavel Labath StopRunningThreads(thread.GetID()); 758c16f5dcaSChaoren Lin } 759c16f5dcaSChaoren Lin 760b9c1b51eSKate Stone void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread, 761b9c1b51eSKate Stone uint32_t wp_index) { 762b9c1b51eSKate Stone Log *log( 763b9c1b51eSKate Stone GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS)); 764a6321a8eSPavel Labath LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}", 765a6321a8eSPavel Labath thread.GetID(), wp_index); 766c16f5dcaSChaoren Lin 76705097246SAdrian Prantl // Mark the thread as stopped at watchpoint. The address is at 76805097246SAdrian Prantl // (lldb::addr_t)info->si_addr if we need it. 769f9077782SPavel Labath thread.SetStoppedByWatchpoint(wp_index); 770c16f5dcaSChaoren Lin 771b9c1b51eSKate Stone // We need to tell all other running threads before we notify the delegate 772b9c1b51eSKate Stone // about this stop. 773f9077782SPavel Labath StopRunningThreads(thread.GetID()); 774c16f5dcaSChaoren Lin } 775c16f5dcaSChaoren Lin 776b9c1b51eSKate Stone void NativeProcessLinux::MonitorSignal(const siginfo_t &info, 777b9c1b51eSKate Stone NativeThreadLinux &thread, bool exited) { 778b9cc0c75SPavel Labath const int signo = info.si_signo; 779b9cc0c75SPavel Labath const bool is_from_llgs = info.si_pid == getpid(); 780af245d11STodd Fiala 781a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 782af245d11STodd Fiala 783af245d11STodd Fiala // POSIX says that process behaviour is undefined after it ignores a SIGFPE, 78405097246SAdrian Prantl // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a kill(2) 78505097246SAdrian Prantl // or raise(3). Similarly for tgkill(2) on Linux. 786af245d11STodd Fiala // 787af245d11STodd Fiala // IOW, user generated signals never generate what we consider to be a 788af245d11STodd Fiala // "crash". 789af245d11STodd Fiala // 790af245d11STodd Fiala // Similarly, ACK signals generated by this monitor. 791af245d11STodd Fiala 792af245d11STodd Fiala // Handle the signal. 793a6321a8eSPavel Labath LLDB_LOG(log, 794a6321a8eSPavel Labath "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, " 795a6321a8eSPavel Labath "waitpid pid = {4})", 796a6321a8eSPavel Labath Host::GetSignalAsCString(signo), signo, info.si_code, 797b9cc0c75SPavel Labath thread.GetID()); 79858a2f669STodd Fiala 79958a2f669STodd Fiala // Check for thread stop notification. 800b9c1b51eSKate Stone if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) { 801af245d11STodd Fiala // This is a tgkill()-based stop. 802a6321a8eSPavel Labath LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID()); 803fa03ad2eSChaoren Lin 80405097246SAdrian Prantl // Check that we're not already marked with a stop reason. Note this thread 80505097246SAdrian Prantl // really shouldn't already be marked as stopped - if we were, that would 80605097246SAdrian Prantl // imply that the kernel signaled us with the thread stopping which we 80705097246SAdrian Prantl // handled and marked as stopped, and that, without an intervening resume, 80805097246SAdrian Prantl // we received another stop. It is more likely that we are missing the 80905097246SAdrian Prantl // marking of a run state somewhere if we find that the thread was marked 81005097246SAdrian Prantl // as stopped. 811b9cc0c75SPavel Labath const StateType thread_state = thread.GetState(); 812b9c1b51eSKate Stone if (!StateIsStoppedState(thread_state, false)) { 813ed89c7feSPavel Labath // An inferior thread has stopped because of a SIGSTOP we have sent it. 814b9c1b51eSKate Stone // Generally, these are not important stops and we don't want to report 815a6321a8eSPavel Labath // them as they are just used to stop other threads when one thread (the 816a6321a8eSPavel Labath // one with the *real* stop reason) hits a breakpoint (watchpoint, 81705097246SAdrian Prantl // etc...). However, in the case of an asynchronous Interrupt(), this 81805097246SAdrian Prantl // *is* the real stop reason, so we leave the signal intact if this is 81905097246SAdrian Prantl // the thread that was chosen as the triggering thread. 820b9c1b51eSKate Stone if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) { 821b9cc0c75SPavel Labath if (m_pending_notification_tid == thread.GetID()) 822b9cc0c75SPavel Labath thread.SetStoppedBySignal(SIGSTOP, &info); 823ed89c7feSPavel Labath else 824b9cc0c75SPavel Labath thread.SetStoppedWithNoReason(); 825ed89c7feSPavel Labath 826b9cc0c75SPavel Labath SetCurrentThreadID(thread.GetID()); 8270e1d729bSPavel Labath SignalIfAllThreadsStopped(); 828b9c1b51eSKate Stone } else { 8290e1d729bSPavel Labath // We can end up here if stop was initiated by LLGS but by this time a 8300e1d729bSPavel Labath // thread stop has occurred - maybe initiated by another event. 83197206d57SZachary Turner Status error = ResumeThread(thread, thread.GetState(), 0); 832a6321a8eSPavel Labath if (error.Fail()) 833a6321a8eSPavel Labath LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(), 834a6321a8eSPavel Labath error); 8350e1d729bSPavel Labath } 836b9c1b51eSKate Stone } else { 837a6321a8eSPavel Labath LLDB_LOG(log, 838a6321a8eSPavel Labath "pid {0} tid {1}, thread was already marked as a stopped " 839a6321a8eSPavel Labath "state (state={2}), leaving stop signal as is", 8408198db30SPavel Labath GetID(), thread.GetID(), thread_state); 8410e1d729bSPavel Labath SignalIfAllThreadsStopped(); 842af245d11STodd Fiala } 843af245d11STodd Fiala 84458a2f669STodd Fiala // Done handling. 845af245d11STodd Fiala return; 846af245d11STodd Fiala } 847af245d11STodd Fiala 84805097246SAdrian Prantl // Check if debugger should stop at this signal or just ignore it and resume 84905097246SAdrian Prantl // the inferior. 8504a705e7eSPavel Labath if (m_signals_to_ignore.find(signo) != m_signals_to_ignore.end()) { 8514a705e7eSPavel Labath ResumeThread(thread, thread.GetState(), signo); 8524a705e7eSPavel Labath return; 8534a705e7eSPavel Labath } 8544a705e7eSPavel Labath 85586fd8e45SChaoren Lin // This thread is stopped. 856a6321a8eSPavel Labath LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo)); 857b9cc0c75SPavel Labath thread.SetStoppedBySignal(signo, &info); 85886fd8e45SChaoren Lin 85986fd8e45SChaoren Lin // Send a stop to the debugger after we get all other threads to stop. 860b9cc0c75SPavel Labath StopRunningThreads(thread.GetID()); 861511e5cdcSTodd Fiala } 862af245d11STodd Fiala 863e7708688STamas Berghammer namespace { 864e7708688STamas Berghammer 865b9c1b51eSKate Stone struct EmulatorBaton { 866d37349f3SPavel Labath NativeProcessLinux &m_process; 867d37349f3SPavel Labath NativeRegisterContext &m_reg_context; 8686648fcc3SPavel Labath 8696648fcc3SPavel Labath // eRegisterKindDWARF -> RegsiterValue 8706648fcc3SPavel Labath std::unordered_map<uint32_t, RegisterValue> m_register_values; 871e7708688STamas Berghammer 872d37349f3SPavel Labath EmulatorBaton(NativeProcessLinux &process, NativeRegisterContext ®_context) 873b9c1b51eSKate Stone : m_process(process), m_reg_context(reg_context) {} 874e7708688STamas Berghammer }; 875e7708688STamas Berghammer 876e7708688STamas Berghammer } // anonymous namespace 877e7708688STamas Berghammer 878b9c1b51eSKate Stone static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton, 879e7708688STamas Berghammer const EmulateInstruction::Context &context, 880b9c1b51eSKate Stone lldb::addr_t addr, void *dst, size_t length) { 881e7708688STamas Berghammer EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton); 882e7708688STamas Berghammer 8833eb4b458SChaoren Lin size_t bytes_read; 884d37349f3SPavel Labath emulator_baton->m_process.ReadMemory(addr, dst, length, bytes_read); 885e7708688STamas Berghammer return bytes_read; 886e7708688STamas Berghammer } 887e7708688STamas Berghammer 888b9c1b51eSKate Stone static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton, 889e7708688STamas Berghammer const RegisterInfo *reg_info, 890b9c1b51eSKate Stone RegisterValue ®_value) { 891e7708688STamas Berghammer EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton); 892e7708688STamas Berghammer 893b9c1b51eSKate Stone auto it = emulator_baton->m_register_values.find( 894b9c1b51eSKate Stone reg_info->kinds[eRegisterKindDWARF]); 895b9c1b51eSKate Stone if (it != emulator_baton->m_register_values.end()) { 8966648fcc3SPavel Labath reg_value = it->second; 8976648fcc3SPavel Labath return true; 8986648fcc3SPavel Labath } 8996648fcc3SPavel Labath 90005097246SAdrian Prantl // The emulator only fill in the dwarf regsiter numbers (and in some case the 90105097246SAdrian Prantl // generic register numbers). Get the full register info from the register 90205097246SAdrian Prantl // context based on the dwarf register numbers. 903b9c1b51eSKate Stone const RegisterInfo *full_reg_info = 904d37349f3SPavel Labath emulator_baton->m_reg_context.GetRegisterInfo( 905e7708688STamas Berghammer eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]); 906e7708688STamas Berghammer 90797206d57SZachary Turner Status error = 908d37349f3SPavel Labath emulator_baton->m_reg_context.ReadRegister(full_reg_info, reg_value); 9096648fcc3SPavel Labath if (error.Success()) 9106648fcc3SPavel Labath return true; 911cdc22a88SMohit K. Bhakkad 9126648fcc3SPavel Labath return false; 913e7708688STamas Berghammer } 914e7708688STamas Berghammer 915b9c1b51eSKate Stone static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton, 916e7708688STamas Berghammer const EmulateInstruction::Context &context, 917e7708688STamas Berghammer const RegisterInfo *reg_info, 918b9c1b51eSKate Stone const RegisterValue ®_value) { 919e7708688STamas Berghammer EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton); 920b9c1b51eSKate Stone emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = 921b9c1b51eSKate Stone reg_value; 922e7708688STamas Berghammer return true; 923e7708688STamas Berghammer } 924e7708688STamas Berghammer 925b9c1b51eSKate Stone static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton, 926e7708688STamas Berghammer const EmulateInstruction::Context &context, 927b9c1b51eSKate Stone lldb::addr_t addr, const void *dst, 928b9c1b51eSKate Stone size_t length) { 929e7708688STamas Berghammer return length; 930e7708688STamas Berghammer } 931e7708688STamas Berghammer 932d37349f3SPavel Labath static lldb::addr_t ReadFlags(NativeRegisterContext ®siter_context) { 933d37349f3SPavel Labath const RegisterInfo *flags_info = regsiter_context.GetRegisterInfo( 934e7708688STamas Berghammer eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS); 935d37349f3SPavel Labath return regsiter_context.ReadRegisterAsUnsigned(flags_info, 936b9c1b51eSKate Stone LLDB_INVALID_ADDRESS); 937e7708688STamas Berghammer } 938e7708688STamas Berghammer 93997206d57SZachary Turner Status 94097206d57SZachary Turner NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadLinux &thread) { 94197206d57SZachary Turner Status error; 942d37349f3SPavel Labath NativeRegisterContext& register_context = thread.GetRegisterContext(); 943e7708688STamas Berghammer 944d5b44036SJonas Devlieghere std::unique_ptr<EmulateInstruction> emulator_up( 945b9c1b51eSKate Stone EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, 946b9c1b51eSKate Stone nullptr)); 947e7708688STamas Berghammer 948d5b44036SJonas Devlieghere if (emulator_up == nullptr) 94997206d57SZachary Turner return Status("Instruction emulator not found!"); 950e7708688STamas Berghammer 951d37349f3SPavel Labath EmulatorBaton baton(*this, register_context); 952d5b44036SJonas Devlieghere emulator_up->SetBaton(&baton); 953d5b44036SJonas Devlieghere emulator_up->SetReadMemCallback(&ReadMemoryCallback); 954d5b44036SJonas Devlieghere emulator_up->SetReadRegCallback(&ReadRegisterCallback); 955d5b44036SJonas Devlieghere emulator_up->SetWriteMemCallback(&WriteMemoryCallback); 956d5b44036SJonas Devlieghere emulator_up->SetWriteRegCallback(&WriteRegisterCallback); 957e7708688STamas Berghammer 958d5b44036SJonas Devlieghere if (!emulator_up->ReadInstruction()) 95997206d57SZachary Turner return Status("Read instruction failed!"); 960e7708688STamas Berghammer 961b9c1b51eSKate Stone bool emulation_result = 962d5b44036SJonas Devlieghere emulator_up->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC); 9636648fcc3SPavel Labath 964d37349f3SPavel Labath const RegisterInfo *reg_info_pc = register_context.GetRegisterInfo( 965b9c1b51eSKate Stone eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC); 966d37349f3SPavel Labath const RegisterInfo *reg_info_flags = register_context.GetRegisterInfo( 967b9c1b51eSKate Stone eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS); 9686648fcc3SPavel Labath 969b9c1b51eSKate Stone auto pc_it = 970b9c1b51eSKate Stone baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]); 971b9c1b51eSKate Stone auto flags_it = 972b9c1b51eSKate Stone baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]); 9736648fcc3SPavel Labath 974e7708688STamas Berghammer lldb::addr_t next_pc; 975e7708688STamas Berghammer lldb::addr_t next_flags; 976b9c1b51eSKate Stone if (emulation_result) { 977b9c1b51eSKate Stone assert(pc_it != baton.m_register_values.end() && 978b9c1b51eSKate Stone "Emulation was successfull but PC wasn't updated"); 9796648fcc3SPavel Labath next_pc = pc_it->second.GetAsUInt64(); 9806648fcc3SPavel Labath 9816648fcc3SPavel Labath if (flags_it != baton.m_register_values.end()) 9826648fcc3SPavel Labath next_flags = flags_it->second.GetAsUInt64(); 983e7708688STamas Berghammer else 984d37349f3SPavel Labath next_flags = ReadFlags(register_context); 985b9c1b51eSKate Stone } else if (pc_it == baton.m_register_values.end()) { 98605097246SAdrian Prantl // Emulate instruction failed and it haven't changed PC. Advance PC with 98705097246SAdrian Prantl // the size of the current opcode because the emulation of all 988e7708688STamas Berghammer // PC modifying instruction should be successful. The failure most 989e7708688STamas Berghammer // likely caused by a not supported instruction which don't modify PC. 990d5b44036SJonas Devlieghere next_pc = register_context.GetPC() + emulator_up->GetOpcode().GetByteSize(); 991d37349f3SPavel Labath next_flags = ReadFlags(register_context); 992b9c1b51eSKate Stone } else { 993e7708688STamas Berghammer // The instruction emulation failed after it modified the PC. It is an 994e7708688STamas Berghammer // unknown error where we can't continue because the next instruction is 995e7708688STamas Berghammer // modifying the PC but we don't know how. 99697206d57SZachary Turner return Status("Instruction emulation failed unexpectedly."); 997e7708688STamas Berghammer } 998e7708688STamas Berghammer 999b9c1b51eSKate Stone if (m_arch.GetMachine() == llvm::Triple::arm) { 1000b9c1b51eSKate Stone if (next_flags & 0x20) { 1001e7708688STamas Berghammer // Thumb mode 1002e7708688STamas Berghammer error = SetSoftwareBreakpoint(next_pc, 2); 1003b9c1b51eSKate Stone } else { 1004e7708688STamas Berghammer // Arm mode 1005e7708688STamas Berghammer error = SetSoftwareBreakpoint(next_pc, 4); 1006e7708688STamas Berghammer } 10072f677ab0SFangrui Song } else if (m_arch.IsMIPS() || m_arch.GetTriple().isPPC64()) 1008cdc22a88SMohit K. Bhakkad error = SetSoftwareBreakpoint(next_pc, 4); 1009b9c1b51eSKate Stone else { 1010e7708688STamas Berghammer // No size hint is given for the next breakpoint 1011e7708688STamas Berghammer error = SetSoftwareBreakpoint(next_pc, 0); 1012e7708688STamas Berghammer } 1013e7708688STamas Berghammer 101405097246SAdrian Prantl // If setting the breakpoint fails because next_pc is out of the address 101505097246SAdrian Prantl // space, ignore it and let the debugee segfault. 101642eb6908SPavel Labath if (error.GetError() == EIO || error.GetError() == EFAULT) { 101797206d57SZachary Turner return Status(); 101842eb6908SPavel Labath } else if (error.Fail()) 1019e7708688STamas Berghammer return error; 1020e7708688STamas Berghammer 1021b9cc0c75SPavel Labath m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc}); 1022e7708688STamas Berghammer 102397206d57SZachary Turner return Status(); 1024e7708688STamas Berghammer } 1025e7708688STamas Berghammer 1026b9c1b51eSKate Stone bool NativeProcessLinux::SupportHardwareSingleStepping() const { 1027ddb93b63SFangrui Song if (m_arch.GetMachine() == llvm::Triple::arm || m_arch.IsMIPS()) 1028cdc22a88SMohit K. Bhakkad return false; 1029cdc22a88SMohit K. Bhakkad return true; 1030e7708688STamas Berghammer } 1031e7708688STamas Berghammer 103297206d57SZachary Turner Status NativeProcessLinux::Resume(const ResumeActionList &resume_actions) { 1033a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1034a6321a8eSPavel Labath LLDB_LOG(log, "pid {0}", GetID()); 1035af245d11STodd Fiala 1036e7708688STamas Berghammer bool software_single_step = !SupportHardwareSingleStepping(); 1037af245d11STodd Fiala 1038b9c1b51eSKate Stone if (software_single_step) { 1039a5be48b3SPavel Labath for (const auto &thread : m_threads) { 1040a5be48b3SPavel Labath assert(thread && "thread list should not contain NULL threads"); 1041e7708688STamas Berghammer 1042b9c1b51eSKate Stone const ResumeAction *const action = 1043a5be48b3SPavel Labath resume_actions.GetActionForThread(thread->GetID(), true); 1044e7708688STamas Berghammer if (action == nullptr) 1045e7708688STamas Berghammer continue; 1046e7708688STamas Berghammer 1047b9c1b51eSKate Stone if (action->state == eStateStepping) { 104897206d57SZachary Turner Status error = SetupSoftwareSingleStepping( 1049a5be48b3SPavel Labath static_cast<NativeThreadLinux &>(*thread)); 1050e7708688STamas Berghammer if (error.Fail()) 1051e7708688STamas Berghammer return error; 1052e7708688STamas Berghammer } 1053e7708688STamas Berghammer } 1054e7708688STamas Berghammer } 1055e7708688STamas Berghammer 1056a5be48b3SPavel Labath for (const auto &thread : m_threads) { 1057a5be48b3SPavel Labath assert(thread && "thread list should not contain NULL threads"); 1058af245d11STodd Fiala 1059b9c1b51eSKate Stone const ResumeAction *const action = 1060a5be48b3SPavel Labath resume_actions.GetActionForThread(thread->GetID(), true); 10616a196ce6SChaoren Lin 1062b9c1b51eSKate Stone if (action == nullptr) { 1063a6321a8eSPavel Labath LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(), 1064a5be48b3SPavel Labath thread->GetID()); 10656a196ce6SChaoren Lin continue; 10666a196ce6SChaoren Lin } 1067af245d11STodd Fiala 1068a6321a8eSPavel Labath LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}", 1069a5be48b3SPavel Labath action->state, GetID(), thread->GetID()); 1070af245d11STodd Fiala 1071b9c1b51eSKate Stone switch (action->state) { 1072af245d11STodd Fiala case eStateRunning: 1073b9c1b51eSKate Stone case eStateStepping: { 1074af245d11STodd Fiala // Run the thread, possibly feeding it the signal. 1075fa03ad2eSChaoren Lin const int signo = action->signal; 1076a5be48b3SPavel Labath ResumeThread(static_cast<NativeThreadLinux &>(*thread), action->state, 1077b9c1b51eSKate Stone signo); 1078af245d11STodd Fiala break; 1079ae29d395SChaoren Lin } 1080af245d11STodd Fiala 1081af245d11STodd Fiala case eStateSuspended: 1082af245d11STodd Fiala case eStateStopped: 1083a6321a8eSPavel Labath llvm_unreachable("Unexpected state"); 1084af245d11STodd Fiala 1085af245d11STodd Fiala default: 108697206d57SZachary Turner return Status("NativeProcessLinux::%s (): unexpected state %s specified " 1087b9c1b51eSKate Stone "for pid %" PRIu64 ", tid %" PRIu64, 1088b9c1b51eSKate Stone __FUNCTION__, StateAsCString(action->state), GetID(), 1089a5be48b3SPavel Labath thread->GetID()); 1090af245d11STodd Fiala } 1091af245d11STodd Fiala } 1092af245d11STodd Fiala 109397206d57SZachary Turner return Status(); 1094af245d11STodd Fiala } 1095af245d11STodd Fiala 109697206d57SZachary Turner Status NativeProcessLinux::Halt() { 109797206d57SZachary Turner Status error; 1098af245d11STodd Fiala 1099af245d11STodd Fiala if (kill(GetID(), SIGSTOP) != 0) 1100af245d11STodd Fiala error.SetErrorToErrno(); 1101af245d11STodd Fiala 1102af245d11STodd Fiala return error; 1103af245d11STodd Fiala } 1104af245d11STodd Fiala 110597206d57SZachary Turner Status NativeProcessLinux::Detach() { 110697206d57SZachary Turner Status error; 1107af245d11STodd Fiala 1108af245d11STodd Fiala // Stop monitoring the inferior. 110919cbe96aSPavel Labath m_sigchld_handle.reset(); 1110af245d11STodd Fiala 11117a9495bcSPavel Labath // Tell ptrace to detach from the process. 11127a9495bcSPavel Labath if (GetID() == LLDB_INVALID_PROCESS_ID) 11137a9495bcSPavel Labath return error; 11147a9495bcSPavel Labath 1115a5be48b3SPavel Labath for (const auto &thread : m_threads) { 1116a5be48b3SPavel Labath Status e = Detach(thread->GetID()); 11177a9495bcSPavel Labath if (e.Fail()) 1118b9c1b51eSKate Stone error = 1119b9c1b51eSKate Stone e; // Save the error, but still attempt to detach from other threads. 11207a9495bcSPavel Labath } 11217a9495bcSPavel Labath 112299e37695SRavitheja Addepally m_processor_trace_monitor.clear(); 112399e37695SRavitheja Addepally m_pt_proces_trace_id = LLDB_INVALID_UID; 112499e37695SRavitheja Addepally 1125af245d11STodd Fiala return error; 1126af245d11STodd Fiala } 1127af245d11STodd Fiala 112897206d57SZachary Turner Status NativeProcessLinux::Signal(int signo) { 112997206d57SZachary Turner Status error; 1130af245d11STodd Fiala 1131a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1132a6321a8eSPavel Labath LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo, 1133a6321a8eSPavel Labath Host::GetSignalAsCString(signo), GetID()); 1134af245d11STodd Fiala 1135af245d11STodd Fiala if (kill(GetID(), signo)) 1136af245d11STodd Fiala error.SetErrorToErrno(); 1137af245d11STodd Fiala 1138af245d11STodd Fiala return error; 1139af245d11STodd Fiala } 1140af245d11STodd Fiala 114197206d57SZachary Turner Status NativeProcessLinux::Interrupt() { 114205097246SAdrian Prantl // Pick a running thread (or if none, a not-dead stopped thread) as the 114305097246SAdrian Prantl // chosen thread that will be the stop-reason thread. 1144a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1145e9547b80SChaoren Lin 1146a5be48b3SPavel Labath NativeThreadProtocol *running_thread = nullptr; 1147a5be48b3SPavel Labath NativeThreadProtocol *stopped_thread = nullptr; 1148e9547b80SChaoren Lin 1149a6321a8eSPavel Labath LLDB_LOG(log, "selecting running thread for interrupt target"); 1150a5be48b3SPavel Labath for (const auto &thread : m_threads) { 115105097246SAdrian Prantl // If we have a running or stepping thread, we'll call that the target of 115205097246SAdrian Prantl // the interrupt. 1153a5be48b3SPavel Labath const auto thread_state = thread->GetState(); 1154b9c1b51eSKate Stone if (thread_state == eStateRunning || thread_state == eStateStepping) { 1155a5be48b3SPavel Labath running_thread = thread.get(); 1156e9547b80SChaoren Lin break; 1157a5be48b3SPavel Labath } else if (!stopped_thread && StateIsStoppedState(thread_state, true)) { 115805097246SAdrian Prantl // Remember the first non-dead stopped thread. We'll use that as a 115905097246SAdrian Prantl // backup if there are no running threads. 1160a5be48b3SPavel Labath stopped_thread = thread.get(); 1161e9547b80SChaoren Lin } 1162e9547b80SChaoren Lin } 1163e9547b80SChaoren Lin 1164a5be48b3SPavel Labath if (!running_thread && !stopped_thread) { 116597206d57SZachary Turner Status error("found no running/stepping or live stopped threads as target " 1166b9c1b51eSKate Stone "for interrupt"); 1167a6321a8eSPavel Labath LLDB_LOG(log, "skipping due to error: {0}", error); 11685830aa75STamas Berghammer 1169e9547b80SChaoren Lin return error; 1170e9547b80SChaoren Lin } 1171e9547b80SChaoren Lin 1172a5be48b3SPavel Labath NativeThreadProtocol *deferred_signal_thread = 1173a5be48b3SPavel Labath running_thread ? running_thread : stopped_thread; 1174e9547b80SChaoren Lin 1175a6321a8eSPavel Labath LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(), 1176a5be48b3SPavel Labath running_thread ? "running" : "stopped", 1177a5be48b3SPavel Labath deferred_signal_thread->GetID()); 1178e9547b80SChaoren Lin 1179a5be48b3SPavel Labath StopRunningThreads(deferred_signal_thread->GetID()); 118045f5cb31SPavel Labath 118197206d57SZachary Turner return Status(); 1182e9547b80SChaoren Lin } 1183e9547b80SChaoren Lin 118497206d57SZachary Turner Status NativeProcessLinux::Kill() { 1185a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1186a6321a8eSPavel Labath LLDB_LOG(log, "pid {0}", GetID()); 1187af245d11STodd Fiala 118897206d57SZachary Turner Status error; 1189af245d11STodd Fiala 1190b9c1b51eSKate Stone switch (m_state) { 1191af245d11STodd Fiala case StateType::eStateInvalid: 1192af245d11STodd Fiala case StateType::eStateExited: 1193af245d11STodd Fiala case StateType::eStateCrashed: 1194af245d11STodd Fiala case StateType::eStateDetached: 1195af245d11STodd Fiala case StateType::eStateUnloaded: 1196af245d11STodd Fiala // Nothing to do - the process is already dead. 1197a6321a8eSPavel Labath LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(), 11988198db30SPavel Labath m_state); 1199af245d11STodd Fiala return error; 1200af245d11STodd Fiala 1201af245d11STodd Fiala case StateType::eStateConnected: 1202af245d11STodd Fiala case StateType::eStateAttaching: 1203af245d11STodd Fiala case StateType::eStateLaunching: 1204af245d11STodd Fiala case StateType::eStateStopped: 1205af245d11STodd Fiala case StateType::eStateRunning: 1206af245d11STodd Fiala case StateType::eStateStepping: 1207af245d11STodd Fiala case StateType::eStateSuspended: 1208af245d11STodd Fiala // We can try to kill a process in these states. 1209af245d11STodd Fiala break; 1210af245d11STodd Fiala } 1211af245d11STodd Fiala 1212b9c1b51eSKate Stone if (kill(GetID(), SIGKILL) != 0) { 1213af245d11STodd Fiala error.SetErrorToErrno(); 1214af245d11STodd Fiala return error; 1215af245d11STodd Fiala } 1216af245d11STodd Fiala 1217af245d11STodd Fiala return error; 1218af245d11STodd Fiala } 1219af245d11STodd Fiala 122097206d57SZachary Turner Status NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr, 1221b9c1b51eSKate Stone MemoryRegionInfo &range_info) { 1222b9c1b51eSKate Stone // FIXME review that the final memory region returned extends to the end of 1223b9c1b51eSKate Stone // the virtual address space, 1224af245d11STodd Fiala // with no perms if it is not mapped. 1225af245d11STodd Fiala 122605097246SAdrian Prantl // Use an approach that reads memory regions from /proc/{pid}/maps. Assume 122705097246SAdrian Prantl // proc maps entries are in ascending order. 1228af245d11STodd Fiala // FIXME assert if we find differently. 1229af245d11STodd Fiala 1230b9c1b51eSKate Stone if (m_supports_mem_region == LazyBool::eLazyBoolNo) { 1231af245d11STodd Fiala // We're done. 123297206d57SZachary Turner return Status("unsupported"); 1233af245d11STodd Fiala } 1234af245d11STodd Fiala 123597206d57SZachary Turner Status error = PopulateMemoryRegionCache(); 1236b9c1b51eSKate Stone if (error.Fail()) { 1237af245d11STodd Fiala return error; 1238af245d11STodd Fiala } 1239af245d11STodd Fiala 1240af245d11STodd Fiala lldb::addr_t prev_base_address = 0; 1241af245d11STodd Fiala 1242b9c1b51eSKate Stone // FIXME start by finding the last region that is <= target address using 1243b9c1b51eSKate Stone // binary search. Data is sorted. 1244af245d11STodd Fiala // There can be a ton of regions on pthreads apps with lots of threads. 1245b9c1b51eSKate Stone for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end(); 1246b9c1b51eSKate Stone ++it) { 1247a6f5795aSTamas Berghammer MemoryRegionInfo &proc_entry_info = it->first; 1248af245d11STodd Fiala 1249af245d11STodd Fiala // Sanity check assumption that /proc/{pid}/maps entries are ascending. 1250b9c1b51eSKate Stone assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) && 1251b9c1b51eSKate Stone "descending /proc/pid/maps entries detected, unexpected"); 1252af245d11STodd Fiala prev_base_address = proc_entry_info.GetRange().GetRangeBase(); 1253b1554311SHafiz Abid Qadeer UNUSED_IF_ASSERT_DISABLED(prev_base_address); 1254af245d11STodd Fiala 1255b9c1b51eSKate Stone // If the target address comes before this entry, indicate distance to next 1256b9c1b51eSKate Stone // region. 1257b9c1b51eSKate Stone if (load_addr < proc_entry_info.GetRange().GetRangeBase()) { 1258af245d11STodd Fiala range_info.GetRange().SetRangeBase(load_addr); 1259b9c1b51eSKate Stone range_info.GetRange().SetByteSize( 1260b9c1b51eSKate Stone proc_entry_info.GetRange().GetRangeBase() - load_addr); 1261af245d11STodd Fiala range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo); 1262af245d11STodd Fiala range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo); 1263af245d11STodd Fiala range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo); 1264ad007563SHoward Hellyer range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo); 1265af245d11STodd Fiala 1266af245d11STodd Fiala return error; 1267b9c1b51eSKate Stone } else if (proc_entry_info.GetRange().Contains(load_addr)) { 1268af245d11STodd Fiala // The target address is within the memory region we're processing here. 1269af245d11STodd Fiala range_info = proc_entry_info; 1270af245d11STodd Fiala return error; 1271af245d11STodd Fiala } 1272af245d11STodd Fiala 1273b9c1b51eSKate Stone // The target memory address comes somewhere after the region we just 1274b9c1b51eSKate Stone // parsed. 1275af245d11STodd Fiala } 1276af245d11STodd Fiala 1277b9c1b51eSKate Stone // If we made it here, we didn't find an entry that contained the given 127805097246SAdrian Prantl // address. Return the load_addr as start and the amount of bytes betwwen 127905097246SAdrian Prantl // load address and the end of the memory as size. 128009839c33STamas Berghammer range_info.GetRange().SetRangeBase(load_addr); 1281ad007563SHoward Hellyer range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS); 128209839c33STamas Berghammer range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo); 128309839c33STamas Berghammer range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo); 128409839c33STamas Berghammer range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo); 1285ad007563SHoward Hellyer range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo); 1286af245d11STodd Fiala return error; 1287af245d11STodd Fiala } 1288af245d11STodd Fiala 128997206d57SZachary Turner Status NativeProcessLinux::PopulateMemoryRegionCache() { 1290a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1291a6f5795aSTamas Berghammer 1292a6f5795aSTamas Berghammer // If our cache is empty, pull the latest. There should always be at least 1293a6f5795aSTamas Berghammer // one memory region if memory region handling is supported. 1294a6f5795aSTamas Berghammer if (!m_mem_region_cache.empty()) { 1295a6321a8eSPavel Labath LLDB_LOG(log, "reusing {0} cached memory region entries", 1296a6321a8eSPavel Labath m_mem_region_cache.size()); 129797206d57SZachary Turner return Status(); 1298a6f5795aSTamas Berghammer } 1299a6f5795aSTamas Berghammer 1300*32541685SDavid Spickett Status Result; 1301*32541685SDavid Spickett LinuxMapCallback callback = [&](llvm::Expected<MemoryRegionInfo> Info) { 1302*32541685SDavid Spickett if (Info) { 1303*32541685SDavid Spickett FileSpec file_spec(Info->GetName().GetCString()); 1304*32541685SDavid Spickett FileSystem::Instance().Resolve(file_spec); 1305*32541685SDavid Spickett m_mem_region_cache.emplace_back(*Info, file_spec); 1306*32541685SDavid Spickett return true; 1307*32541685SDavid Spickett } 1308*32541685SDavid Spickett 1309*32541685SDavid Spickett Result = Info.takeError(); 1310*32541685SDavid Spickett m_supports_mem_region = LazyBool::eLazyBoolNo; 1311*32541685SDavid Spickett LLDB_LOG(log, "failed to parse proc maps: {0}", Result); 1312*32541685SDavid Spickett return false; 1313*32541685SDavid Spickett }; 1314*32541685SDavid Spickett 1315*32541685SDavid Spickett // Linux kernel since 2.6.14 has /proc/{pid}/smaps 1316*32541685SDavid Spickett // if CONFIG_PROC_PAGE_MONITOR is enabled 1317*32541685SDavid Spickett auto BufferOrError = getProcFile(GetID(), "smaps"); 1318*32541685SDavid Spickett if (BufferOrError) 1319*32541685SDavid Spickett ParseLinuxSMapRegions(BufferOrError.get()->getBuffer(), callback); 1320*32541685SDavid Spickett else { 1321*32541685SDavid Spickett BufferOrError = getProcFile(GetID(), "maps"); 132215930862SPavel Labath if (!BufferOrError) { 132315930862SPavel Labath m_supports_mem_region = LazyBool::eLazyBoolNo; 132415930862SPavel Labath return BufferOrError.getError(); 132515930862SPavel Labath } 1326*32541685SDavid Spickett 1327*32541685SDavid Spickett ParseLinuxMapRegions(BufferOrError.get()->getBuffer(), callback); 1328a6f5795aSTamas Berghammer } 1329*32541685SDavid Spickett 1330c8e364e8SPavel Labath if (Result.Fail()) 1331c8e364e8SPavel Labath return Result; 1332a6f5795aSTamas Berghammer 133315930862SPavel Labath if (m_mem_region_cache.empty()) { 1334a6f5795aSTamas Berghammer // No entries after attempting to read them. This shouldn't happen if 133505097246SAdrian Prantl // /proc/{pid}/maps is supported. Assume we don't support map entries via 133605097246SAdrian Prantl // procfs. 133715930862SPavel Labath m_supports_mem_region = LazyBool::eLazyBoolNo; 1338a6321a8eSPavel Labath LLDB_LOG(log, 1339a6321a8eSPavel Labath "failed to find any procfs maps entries, assuming no support " 1340a6321a8eSPavel Labath "for memory region metadata retrieval"); 134197206d57SZachary Turner return Status("not supported"); 1342a6f5795aSTamas Berghammer } 1343a6f5795aSTamas Berghammer 1344a6321a8eSPavel Labath LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps", 1345a6321a8eSPavel Labath m_mem_region_cache.size(), GetID()); 1346a6f5795aSTamas Berghammer 1347a6f5795aSTamas Berghammer // We support memory retrieval, remember that. 1348a6f5795aSTamas Berghammer m_supports_mem_region = LazyBool::eLazyBoolYes; 134997206d57SZachary Turner return Status(); 1350a6f5795aSTamas Berghammer } 1351a6f5795aSTamas Berghammer 1352b9c1b51eSKate Stone void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) { 1353a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1354a6321a8eSPavel Labath LLDB_LOG(log, "newBumpId={0}", newBumpId); 1355a6321a8eSPavel Labath LLDB_LOG(log, "clearing {0} entries from memory region cache", 1356a6321a8eSPavel Labath m_mem_region_cache.size()); 1357af245d11STodd Fiala m_mem_region_cache.clear(); 1358af245d11STodd Fiala } 1359af245d11STodd Fiala 13602c4226f8SPavel Labath llvm::Expected<uint64_t> 13612c4226f8SPavel Labath NativeProcessLinux::Syscall(llvm::ArrayRef<uint64_t> args) { 13622c4226f8SPavel Labath PopulateMemoryRegionCache(); 13632c4226f8SPavel Labath auto region_it = llvm::find_if(m_mem_region_cache, [](const auto &pair) { 13642c4226f8SPavel Labath return pair.first.GetExecutable() == MemoryRegionInfo::eYes; 13652c4226f8SPavel Labath }); 13662c4226f8SPavel Labath if (region_it == m_mem_region_cache.end()) 13672c4226f8SPavel Labath return llvm::createStringError(llvm::inconvertibleErrorCode(), 13682c4226f8SPavel Labath "No executable memory region found!"); 1369af245d11STodd Fiala 13702c4226f8SPavel Labath addr_t exe_addr = region_it->first.GetRange().GetRangeBase(); 1371af245d11STodd Fiala 13722c4226f8SPavel Labath NativeThreadLinux &thread = *GetThreadByID(GetID()); 13732c4226f8SPavel Labath assert(thread.GetState() == eStateStopped); 13742c4226f8SPavel Labath NativeRegisterContextLinux ®_ctx = thread.GetRegisterContext(); 13752c4226f8SPavel Labath 13762c4226f8SPavel Labath NativeRegisterContextLinux::SyscallData syscall_data = 13772c4226f8SPavel Labath *reg_ctx.GetSyscallData(); 13782c4226f8SPavel Labath 13792c4226f8SPavel Labath DataBufferSP registers_sp; 13802c4226f8SPavel Labath if (llvm::Error Err = reg_ctx.ReadAllRegisterValues(registers_sp).ToError()) 13812c4226f8SPavel Labath return std::move(Err); 13822c4226f8SPavel Labath auto restore_regs = llvm::make_scope_exit( 13832c4226f8SPavel Labath [&] { reg_ctx.WriteAllRegisterValues(registers_sp); }); 13842c4226f8SPavel Labath 13852c4226f8SPavel Labath llvm::SmallVector<uint8_t, 8> memory(syscall_data.Insn.size()); 13862c4226f8SPavel Labath size_t bytes_read; 13872c4226f8SPavel Labath if (llvm::Error Err = 13882c4226f8SPavel Labath ReadMemory(exe_addr, memory.data(), memory.size(), bytes_read) 13892c4226f8SPavel Labath .ToError()) { 13902c4226f8SPavel Labath return std::move(Err); 1391af245d11STodd Fiala } 1392af245d11STodd Fiala 13932c4226f8SPavel Labath auto restore_mem = llvm::make_scope_exit( 13942c4226f8SPavel Labath [&] { WriteMemory(exe_addr, memory.data(), memory.size(), bytes_read); }); 13952c4226f8SPavel Labath 13962c4226f8SPavel Labath if (llvm::Error Err = reg_ctx.SetPC(exe_addr).ToError()) 13972c4226f8SPavel Labath return std::move(Err); 13982c4226f8SPavel Labath 13992c4226f8SPavel Labath for (const auto &zip : llvm::zip_first(args, syscall_data.Args)) { 14002c4226f8SPavel Labath if (llvm::Error Err = 14012c4226f8SPavel Labath reg_ctx 14022c4226f8SPavel Labath .WriteRegisterFromUnsigned(std::get<1>(zip), std::get<0>(zip)) 14032c4226f8SPavel Labath .ToError()) { 14042c4226f8SPavel Labath return std::move(Err); 14052c4226f8SPavel Labath } 14062c4226f8SPavel Labath } 14072c4226f8SPavel Labath if (llvm::Error Err = WriteMemory(exe_addr, syscall_data.Insn.data(), 14082c4226f8SPavel Labath syscall_data.Insn.size(), bytes_read) 14092c4226f8SPavel Labath .ToError()) 14102c4226f8SPavel Labath return std::move(Err); 14112c4226f8SPavel Labath 14122c4226f8SPavel Labath m_mem_region_cache.clear(); 14132c4226f8SPavel Labath 14142c4226f8SPavel Labath // With software single stepping the syscall insn buffer must also include a 14152c4226f8SPavel Labath // trap instruction to stop the process. 14162c4226f8SPavel Labath int req = SupportHardwareSingleStepping() ? PTRACE_SINGLESTEP : PTRACE_CONT; 14172c4226f8SPavel Labath if (llvm::Error Err = 14182c4226f8SPavel Labath PtraceWrapper(req, thread.GetID(), nullptr, nullptr).ToError()) 14192c4226f8SPavel Labath return std::move(Err); 14202c4226f8SPavel Labath 14212c4226f8SPavel Labath int status; 14222c4226f8SPavel Labath ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, thread.GetID(), 14232c4226f8SPavel Labath &status, __WALL); 14242c4226f8SPavel Labath if (wait_pid == -1) { 14252c4226f8SPavel Labath return llvm::errorCodeToError( 14262c4226f8SPavel Labath std::error_code(errno, std::generic_category())); 14272c4226f8SPavel Labath } 14282c4226f8SPavel Labath assert((unsigned)wait_pid == thread.GetID()); 14292c4226f8SPavel Labath 14302c4226f8SPavel Labath uint64_t result = reg_ctx.ReadRegisterAsUnsigned(syscall_data.Result, -ESRCH); 14312c4226f8SPavel Labath 14322c4226f8SPavel Labath // Values larger than this are actually negative errno numbers. 14332c4226f8SPavel Labath uint64_t errno_threshold = 14342c4226f8SPavel Labath (uint64_t(-1) >> (64 - 8 * m_arch.GetAddressByteSize())) - 0x1000; 14352c4226f8SPavel Labath if (result > errno_threshold) { 14362c4226f8SPavel Labath return llvm::errorCodeToError( 14372c4226f8SPavel Labath std::error_code(-result & 0xfff, std::generic_category())); 14382c4226f8SPavel Labath } 14392c4226f8SPavel Labath 14402c4226f8SPavel Labath return result; 14412c4226f8SPavel Labath } 14422c4226f8SPavel Labath 14432c4226f8SPavel Labath llvm::Expected<addr_t> 14442c4226f8SPavel Labath NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions) { 14452c4226f8SPavel Labath 14462c4226f8SPavel Labath llvm::Optional<NativeRegisterContextLinux::MmapData> mmap_data = 14472c4226f8SPavel Labath GetCurrentThread()->GetRegisterContext().GetMmapData(); 14482c4226f8SPavel Labath if (!mmap_data) 14492c4226f8SPavel Labath return llvm::make_error<UnimplementedError>(); 14502c4226f8SPavel Labath 14512c4226f8SPavel Labath unsigned prot = PROT_NONE; 14522c4226f8SPavel Labath assert((permissions & (ePermissionsReadable | ePermissionsWritable | 14532c4226f8SPavel Labath ePermissionsExecutable)) == permissions && 14542c4226f8SPavel Labath "Unknown permission!"); 14552c4226f8SPavel Labath if (permissions & ePermissionsReadable) 14562c4226f8SPavel Labath prot |= PROT_READ; 14572c4226f8SPavel Labath if (permissions & ePermissionsWritable) 14582c4226f8SPavel Labath prot |= PROT_WRITE; 14592c4226f8SPavel Labath if (permissions & ePermissionsExecutable) 14602c4226f8SPavel Labath prot |= PROT_EXEC; 14612c4226f8SPavel Labath 14622c4226f8SPavel Labath llvm::Expected<uint64_t> Result = 14632c4226f8SPavel Labath Syscall({mmap_data->SysMmap, 0, size, prot, MAP_ANONYMOUS | MAP_PRIVATE, 14642c4226f8SPavel Labath uint64_t(-1), 0}); 14652c4226f8SPavel Labath if (Result) 14662c4226f8SPavel Labath m_allocated_memory.try_emplace(*Result, size); 14672c4226f8SPavel Labath return Result; 14682c4226f8SPavel Labath } 14692c4226f8SPavel Labath 14702c4226f8SPavel Labath llvm::Error NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) { 14712c4226f8SPavel Labath llvm::Optional<NativeRegisterContextLinux::MmapData> mmap_data = 14722c4226f8SPavel Labath GetCurrentThread()->GetRegisterContext().GetMmapData(); 14732c4226f8SPavel Labath if (!mmap_data) 14742c4226f8SPavel Labath return llvm::make_error<UnimplementedError>(); 14752c4226f8SPavel Labath 14762c4226f8SPavel Labath auto it = m_allocated_memory.find(addr); 14772c4226f8SPavel Labath if (it == m_allocated_memory.end()) 14782c4226f8SPavel Labath return llvm::createStringError(llvm::errc::invalid_argument, 14792c4226f8SPavel Labath "Memory not allocated by the debugger."); 14802c4226f8SPavel Labath 14812c4226f8SPavel Labath llvm::Expected<uint64_t> Result = 14822c4226f8SPavel Labath Syscall({mmap_data->SysMunmap, addr, it->second}); 14832c4226f8SPavel Labath if (!Result) 14842c4226f8SPavel Labath return Result.takeError(); 14852c4226f8SPavel Labath 14862c4226f8SPavel Labath m_allocated_memory.erase(it); 14872c4226f8SPavel Labath return llvm::Error::success(); 1488af245d11STodd Fiala } 1489af245d11STodd Fiala 1490b9c1b51eSKate Stone size_t NativeProcessLinux::UpdateThreads() { 149105097246SAdrian Prantl // The NativeProcessLinux monitoring threads are always up to date with 149205097246SAdrian Prantl // respect to thread state and they keep the thread list populated properly. 149305097246SAdrian Prantl // All this method needs to do is return the thread count. 1494af245d11STodd Fiala return m_threads.size(); 1495af245d11STodd Fiala } 1496af245d11STodd Fiala 149797206d57SZachary Turner Status NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size, 1498b9c1b51eSKate Stone bool hardware) { 1499af245d11STodd Fiala if (hardware) 1500d5ffbad2SOmair Javaid return SetHardwareBreakpoint(addr, size); 1501af245d11STodd Fiala else 1502af245d11STodd Fiala return SetSoftwareBreakpoint(addr, size); 1503af245d11STodd Fiala } 1504af245d11STodd Fiala 150597206d57SZachary Turner Status NativeProcessLinux::RemoveBreakpoint(lldb::addr_t addr, bool hardware) { 1506d5ffbad2SOmair Javaid if (hardware) 1507d5ffbad2SOmair Javaid return RemoveHardwareBreakpoint(addr); 1508d5ffbad2SOmair Javaid else 1509d5ffbad2SOmair Javaid return NativeProcessProtocol::RemoveBreakpoint(addr); 1510d5ffbad2SOmair Javaid } 1511d5ffbad2SOmair Javaid 1512f8b825f6SPavel Labath llvm::Expected<llvm::ArrayRef<uint8_t>> 1513f8b825f6SPavel Labath NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(size_t size_hint) { 1514be379e15STamas Berghammer // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the 1515be379e15STamas Berghammer // linux kernel does otherwise. 1516f8b825f6SPavel Labath static const uint8_t g_arm_opcode[] = {0xf0, 0x01, 0xf0, 0xe7}; 1517f8b825f6SPavel Labath static const uint8_t g_thumb_opcode[] = {0x01, 0xde}; 151812286a27SPavel Labath 1519f8b825f6SPavel Labath switch (GetArchitecture().GetMachine()) { 152012286a27SPavel Labath case llvm::Triple::arm: 1521f8b825f6SPavel Labath switch (size_hint) { 152263c8be95STamas Berghammer case 2: 15234f545074SPavel Labath return llvm::makeArrayRef(g_thumb_opcode); 152463c8be95STamas Berghammer case 4: 15254f545074SPavel Labath return llvm::makeArrayRef(g_arm_opcode); 152663c8be95STamas Berghammer default: 1527f8b825f6SPavel Labath return llvm::createStringError(llvm::inconvertibleErrorCode(), 1528f8b825f6SPavel Labath "Unrecognised trap opcode size hint!"); 152963c8be95STamas Berghammer } 1530af245d11STodd Fiala default: 1531f8b825f6SPavel Labath return NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_hint); 1532af245d11STodd Fiala } 1533af245d11STodd Fiala } 1534af245d11STodd Fiala 153597206d57SZachary Turner Status NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size, 1536b9c1b51eSKate Stone size_t &bytes_read) { 1537df7c6995SPavel Labath if (ProcessVmReadvSupported()) { 1538b9c1b51eSKate Stone // The process_vm_readv path is about 50 times faster than ptrace api. We 153905097246SAdrian Prantl // want to use this syscall if it is supported. 1540df7c6995SPavel Labath 1541df7c6995SPavel Labath const ::pid_t pid = GetID(); 1542df7c6995SPavel Labath 1543df7c6995SPavel Labath struct iovec local_iov, remote_iov; 1544df7c6995SPavel Labath local_iov.iov_base = buf; 1545df7c6995SPavel Labath local_iov.iov_len = size; 1546df7c6995SPavel Labath remote_iov.iov_base = reinterpret_cast<void *>(addr); 1547df7c6995SPavel Labath remote_iov.iov_len = size; 1548df7c6995SPavel Labath 1549df7c6995SPavel Labath bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0); 1550df7c6995SPavel Labath const bool success = bytes_read == size; 1551df7c6995SPavel Labath 1552a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1553a6321a8eSPavel Labath LLDB_LOG(log, 1554a6321a8eSPavel Labath "using process_vm_readv to read {0} bytes from inferior " 1555a6321a8eSPavel Labath "address {1:x}: {2}", 155610c41f37SPavel Labath size, addr, success ? "Success" : llvm::sys::StrError(errno)); 1557df7c6995SPavel Labath 1558df7c6995SPavel Labath if (success) 155997206d57SZachary Turner return Status(); 1560a6321a8eSPavel Labath // else the call failed for some reason, let's retry the read using ptrace 1561b9c1b51eSKate Stone // api. 1562df7c6995SPavel Labath } 1563df7c6995SPavel Labath 156419cbe96aSPavel Labath unsigned char *dst = static_cast<unsigned char *>(buf); 156519cbe96aSPavel Labath size_t remainder; 156619cbe96aSPavel Labath long data; 156719cbe96aSPavel Labath 1568a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY)); 1569a6321a8eSPavel Labath LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size); 157019cbe96aSPavel Labath 1571b9c1b51eSKate Stone for (bytes_read = 0; bytes_read < size; bytes_read += remainder) { 157297206d57SZachary Turner Status error = NativeProcessLinux::PtraceWrapper( 1573b9c1b51eSKate Stone PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data); 1574a6321a8eSPavel Labath if (error.Fail()) 157519cbe96aSPavel Labath return error; 157619cbe96aSPavel Labath 157719cbe96aSPavel Labath remainder = size - bytes_read; 157819cbe96aSPavel Labath remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder; 157919cbe96aSPavel Labath 158019cbe96aSPavel Labath // Copy the data into our buffer 1581f6ef187bSMohit K. Bhakkad memcpy(dst, &data, remainder); 158219cbe96aSPavel Labath 1583a6321a8eSPavel Labath LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data); 158419cbe96aSPavel Labath addr += k_ptrace_word_size; 158519cbe96aSPavel Labath dst += k_ptrace_word_size; 158619cbe96aSPavel Labath } 158797206d57SZachary Turner return Status(); 1588af245d11STodd Fiala } 1589af245d11STodd Fiala 159097206d57SZachary Turner Status NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, 1591b9c1b51eSKate Stone size_t size, size_t &bytes_written) { 159219cbe96aSPavel Labath const unsigned char *src = static_cast<const unsigned char *>(buf); 159319cbe96aSPavel Labath size_t remainder; 159497206d57SZachary Turner Status error; 159519cbe96aSPavel Labath 1596a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY)); 1597a6321a8eSPavel Labath LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size); 159819cbe96aSPavel Labath 1599b9c1b51eSKate Stone for (bytes_written = 0; bytes_written < size; bytes_written += remainder) { 160019cbe96aSPavel Labath remainder = size - bytes_written; 160119cbe96aSPavel Labath remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder; 160219cbe96aSPavel Labath 1603b9c1b51eSKate Stone if (remainder == k_ptrace_word_size) { 160419cbe96aSPavel Labath unsigned long data = 0; 1605f6ef187bSMohit K. Bhakkad memcpy(&data, src, k_ptrace_word_size); 160619cbe96aSPavel Labath 1607a6321a8eSPavel Labath LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data); 1608b9c1b51eSKate Stone error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(), 1609b9c1b51eSKate Stone (void *)addr, (void *)data); 1610a6321a8eSPavel Labath if (error.Fail()) 161119cbe96aSPavel Labath return error; 1612b9c1b51eSKate Stone } else { 161319cbe96aSPavel Labath unsigned char buff[8]; 161419cbe96aSPavel Labath size_t bytes_read; 161519cbe96aSPavel Labath error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read); 1616a6321a8eSPavel Labath if (error.Fail()) 161719cbe96aSPavel Labath return error; 161819cbe96aSPavel Labath 161919cbe96aSPavel Labath memcpy(buff, src, remainder); 162019cbe96aSPavel Labath 162119cbe96aSPavel Labath size_t bytes_written_rec; 162219cbe96aSPavel Labath error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec); 1623a6321a8eSPavel Labath if (error.Fail()) 162419cbe96aSPavel Labath return error; 162519cbe96aSPavel Labath 1626a6321a8eSPavel Labath LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src, 1627b9c1b51eSKate Stone *(unsigned long *)buff); 162819cbe96aSPavel Labath } 162919cbe96aSPavel Labath 163019cbe96aSPavel Labath addr += k_ptrace_word_size; 163119cbe96aSPavel Labath src += k_ptrace_word_size; 163219cbe96aSPavel Labath } 163319cbe96aSPavel Labath return error; 1634af245d11STodd Fiala } 1635af245d11STodd Fiala 163697206d57SZachary Turner Status NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) { 163719cbe96aSPavel Labath return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo); 1638af245d11STodd Fiala } 1639af245d11STodd Fiala 164097206d57SZachary Turner Status NativeProcessLinux::GetEventMessage(lldb::tid_t tid, 1641b9c1b51eSKate Stone unsigned long *message) { 164219cbe96aSPavel Labath return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message); 1643af245d11STodd Fiala } 1644af245d11STodd Fiala 164597206d57SZachary Turner Status NativeProcessLinux::Detach(lldb::tid_t tid) { 164697ccc294SChaoren Lin if (tid == LLDB_INVALID_THREAD_ID) 164797206d57SZachary Turner return Status(); 164897ccc294SChaoren Lin 164919cbe96aSPavel Labath return PtraceWrapper(PTRACE_DETACH, tid); 1650af245d11STodd Fiala } 1651af245d11STodd Fiala 1652b9c1b51eSKate Stone bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) { 1653a5be48b3SPavel Labath for (const auto &thread : m_threads) { 1654a5be48b3SPavel Labath assert(thread && "thread list should not contain NULL threads"); 1655a5be48b3SPavel Labath if (thread->GetID() == thread_id) { 1656af245d11STodd Fiala // We have this thread. 1657af245d11STodd Fiala return true; 1658af245d11STodd Fiala } 1659af245d11STodd Fiala } 1660af245d11STodd Fiala 1661af245d11STodd Fiala // We don't have this thread. 1662af245d11STodd Fiala return false; 1663af245d11STodd Fiala } 1664af245d11STodd Fiala 1665b9c1b51eSKate Stone bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) { 1666a6321a8eSPavel Labath Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD); 1667a6321a8eSPavel Labath LLDB_LOG(log, "tid: {0})", thread_id); 16681dbc6c9cSPavel Labath 16691dbc6c9cSPavel Labath bool found = false; 1670b9c1b51eSKate Stone for (auto it = m_threads.begin(); it != m_threads.end(); ++it) { 1671b9c1b51eSKate Stone if (*it && ((*it)->GetID() == thread_id)) { 1672af245d11STodd Fiala m_threads.erase(it); 16731dbc6c9cSPavel Labath found = true; 16741dbc6c9cSPavel Labath break; 1675af245d11STodd Fiala } 1676af245d11STodd Fiala } 1677af245d11STodd Fiala 167899e37695SRavitheja Addepally if (found) 167999e37695SRavitheja Addepally StopTracingForThread(thread_id); 16809eb1ecb9SPavel Labath SignalIfAllThreadsStopped(); 16811dbc6c9cSPavel Labath return found; 1682af245d11STodd Fiala } 1683af245d11STodd Fiala 1684a5be48b3SPavel Labath NativeThreadLinux &NativeProcessLinux::AddThread(lldb::tid_t thread_id) { 1685a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD)); 1686a6321a8eSPavel Labath LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id); 1687af245d11STodd Fiala 1688b9c1b51eSKate Stone assert(!HasThreadNoLock(thread_id) && 1689b9c1b51eSKate Stone "attempted to add a thread by id that already exists"); 1690af245d11STodd Fiala 1691af245d11STodd Fiala // If this is the first thread, save it as the current thread 1692af245d11STodd Fiala if (m_threads.empty()) 1693af245d11STodd Fiala SetCurrentThreadID(thread_id); 1694af245d11STodd Fiala 1695a8f3ae7cSJonas Devlieghere m_threads.push_back(std::make_unique<NativeThreadLinux>(*this, thread_id)); 169699e37695SRavitheja Addepally 169799e37695SRavitheja Addepally if (m_pt_proces_trace_id != LLDB_INVALID_UID) { 169899e37695SRavitheja Addepally auto traceMonitor = ProcessorTraceMonitor::Create( 169999e37695SRavitheja Addepally GetID(), thread_id, m_pt_process_trace_config, true); 170099e37695SRavitheja Addepally if (traceMonitor) { 170199e37695SRavitheja Addepally m_pt_traced_thread_group.insert(thread_id); 170299e37695SRavitheja Addepally m_processor_trace_monitor.insert( 170399e37695SRavitheja Addepally std::make_pair(thread_id, std::move(*traceMonitor))); 170499e37695SRavitheja Addepally } else { 170599e37695SRavitheja Addepally LLDB_LOG(log, "failed to start trace on thread {0}", thread_id); 170699e37695SRavitheja Addepally Status error(traceMonitor.takeError()); 170799e37695SRavitheja Addepally LLDB_LOG(log, "error {0}", error); 170899e37695SRavitheja Addepally } 170999e37695SRavitheja Addepally } 171099e37695SRavitheja Addepally 1711a5be48b3SPavel Labath return static_cast<NativeThreadLinux &>(*m_threads.back()); 1712af245d11STodd Fiala } 1713af245d11STodd Fiala 171497206d57SZachary Turner Status NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path, 1715b9c1b51eSKate Stone FileSpec &file_spec) { 171697206d57SZachary Turner Status error = PopulateMemoryRegionCache(); 1717a6f5795aSTamas Berghammer if (error.Fail()) 1718a6f5795aSTamas Berghammer return error; 1719a6f5795aSTamas Berghammer 17208f3be7a3SJonas Devlieghere FileSpec module_file_spec(module_path); 17218f3be7a3SJonas Devlieghere FileSystem::Instance().Resolve(module_file_spec); 17227cb18bf5STamas Berghammer 17237cb18bf5STamas Berghammer file_spec.Clear(); 1724a6f5795aSTamas Berghammer for (const auto &it : m_mem_region_cache) { 1725a6f5795aSTamas Berghammer if (it.second.GetFilename() == module_file_spec.GetFilename()) { 1726a6f5795aSTamas Berghammer file_spec = it.second; 172797206d57SZachary Turner return Status(); 1728a6f5795aSTamas Berghammer } 1729a6f5795aSTamas Berghammer } 173097206d57SZachary Turner return Status("Module file (%s) not found in /proc/%" PRIu64 "/maps file!", 17317cb18bf5STamas Berghammer module_file_spec.GetFilename().AsCString(), GetID()); 17327cb18bf5STamas Berghammer } 1733c076559aSPavel Labath 173497206d57SZachary Turner Status NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name, 1735b9c1b51eSKate Stone lldb::addr_t &load_addr) { 1736783bfc8cSTamas Berghammer load_addr = LLDB_INVALID_ADDRESS; 173797206d57SZachary Turner Status error = PopulateMemoryRegionCache(); 1738a6f5795aSTamas Berghammer if (error.Fail()) 1739783bfc8cSTamas Berghammer return error; 1740a6f5795aSTamas Berghammer 17418f3be7a3SJonas Devlieghere FileSpec file(file_name); 1742a6f5795aSTamas Berghammer for (const auto &it : m_mem_region_cache) { 1743a6f5795aSTamas Berghammer if (it.second == file) { 1744a6f5795aSTamas Berghammer load_addr = it.first.GetRange().GetRangeBase(); 174597206d57SZachary Turner return Status(); 1746a6f5795aSTamas Berghammer } 1747a6f5795aSTamas Berghammer } 174897206d57SZachary Turner return Status("No load address found for specified file."); 1749783bfc8cSTamas Berghammer } 1750783bfc8cSTamas Berghammer 1751a5be48b3SPavel Labath NativeThreadLinux *NativeProcessLinux::GetThreadByID(lldb::tid_t tid) { 1752a5be48b3SPavel Labath return static_cast<NativeThreadLinux *>( 1753b9c1b51eSKate Stone NativeProcessProtocol::GetThreadByID(tid)); 1754f9077782SPavel Labath } 1755f9077782SPavel Labath 17562c4226f8SPavel Labath NativeThreadLinux *NativeProcessLinux::GetCurrentThread() { 17572c4226f8SPavel Labath return static_cast<NativeThreadLinux *>( 17582c4226f8SPavel Labath NativeProcessProtocol::GetCurrentThread()); 17592c4226f8SPavel Labath } 17602c4226f8SPavel Labath 176197206d57SZachary Turner Status NativeProcessLinux::ResumeThread(NativeThreadLinux &thread, 1762b9c1b51eSKate Stone lldb::StateType state, int signo) { 1763a6321a8eSPavel Labath Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD); 1764a6321a8eSPavel Labath LLDB_LOG(log, "tid: {0}", thread.GetID()); 1765c076559aSPavel Labath 176605097246SAdrian Prantl // Before we do the resume below, first check if we have a pending stop 176705097246SAdrian Prantl // notification that is currently waiting for all threads to stop. This is 176805097246SAdrian Prantl // potentially a buggy situation since we're ostensibly waiting for threads 176905097246SAdrian Prantl // to stop before we send out the pending notification, and here we are 177005097246SAdrian Prantl // resuming one before we send out the pending stop notification. 1771a6321a8eSPavel Labath if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) { 1772a6321a8eSPavel Labath LLDB_LOG(log, 1773a6321a8eSPavel Labath "about to resume tid {0} per explicit request but we have a " 1774a6321a8eSPavel Labath "pending stop notification (tid {1}) that is actively " 1775a6321a8eSPavel Labath "waiting for this thread to stop. Valid sequence of events?", 1776a6321a8eSPavel Labath thread.GetID(), m_pending_notification_tid); 1777c076559aSPavel Labath } 1778c076559aSPavel Labath 177905097246SAdrian Prantl // Request a resume. We expect this to be synchronous and the system to 178005097246SAdrian Prantl // reflect it is running after this completes. 1781b9c1b51eSKate Stone switch (state) { 1782b9c1b51eSKate Stone case eStateRunning: { 1783605b51b8SPavel Labath const auto resume_result = thread.Resume(signo); 17840e1d729bSPavel Labath if (resume_result.Success()) 17850e1d729bSPavel Labath SetState(eStateRunning, true); 17860e1d729bSPavel Labath return resume_result; 1787c076559aSPavel Labath } 1788b9c1b51eSKate Stone case eStateStepping: { 1789605b51b8SPavel Labath const auto step_result = thread.SingleStep(signo); 17900e1d729bSPavel Labath if (step_result.Success()) 17910e1d729bSPavel Labath SetState(eStateRunning, true); 17920e1d729bSPavel Labath return step_result; 17930e1d729bSPavel Labath } 17940e1d729bSPavel Labath default: 17958198db30SPavel Labath LLDB_LOG(log, "Unhandled state {0}.", state); 17960e1d729bSPavel Labath llvm_unreachable("Unhandled state for resume"); 17970e1d729bSPavel Labath } 1798c076559aSPavel Labath } 1799c076559aSPavel Labath 1800c076559aSPavel Labath //===----------------------------------------------------------------------===// 1801c076559aSPavel Labath 1802b9c1b51eSKate Stone void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) { 1803a6321a8eSPavel Labath Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD); 1804a6321a8eSPavel Labath LLDB_LOG(log, "about to process event: (triggering_tid: {0})", 1805a6321a8eSPavel Labath triggering_tid); 1806c076559aSPavel Labath 18070e1d729bSPavel Labath m_pending_notification_tid = triggering_tid; 18080e1d729bSPavel Labath 180905097246SAdrian Prantl // Request a stop for all the thread stops that need to be stopped and are 181005097246SAdrian Prantl // not already known to be stopped. 1811a5be48b3SPavel Labath for (const auto &thread : m_threads) { 1812a5be48b3SPavel Labath if (StateIsRunningState(thread->GetState())) 1813a5be48b3SPavel Labath static_cast<NativeThreadLinux *>(thread.get())->RequestStop(); 18140e1d729bSPavel Labath } 18150e1d729bSPavel Labath 18160e1d729bSPavel Labath SignalIfAllThreadsStopped(); 1817a6321a8eSPavel Labath LLDB_LOG(log, "event processing done"); 1818c076559aSPavel Labath } 1819c076559aSPavel Labath 1820b9c1b51eSKate Stone void NativeProcessLinux::SignalIfAllThreadsStopped() { 18210e1d729bSPavel Labath if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID) 18220e1d729bSPavel Labath return; // No pending notification. Nothing to do. 18230e1d729bSPavel Labath 1824b9c1b51eSKate Stone for (const auto &thread_sp : m_threads) { 18250e1d729bSPavel Labath if (StateIsRunningState(thread_sp->GetState())) 18260e1d729bSPavel Labath return; // Some threads are still running. Don't signal yet. 18270e1d729bSPavel Labath } 18280e1d729bSPavel Labath 18290e1d729bSPavel Labath // We have a pending notification and all threads have stopped. 1830b9c1b51eSKate Stone Log *log( 1831b9c1b51eSKate Stone GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS)); 18329eb1ecb9SPavel Labath 1833b9c1b51eSKate Stone // Clear any temporary breakpoints we used to implement software single 1834b9c1b51eSKate Stone // stepping. 1835b9c1b51eSKate Stone for (const auto &thread_info : m_threads_stepping_with_breakpoint) { 183697206d57SZachary Turner Status error = RemoveBreakpoint(thread_info.second); 18379eb1ecb9SPavel Labath if (error.Fail()) 1838a6321a8eSPavel Labath LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}", 1839a6321a8eSPavel Labath thread_info.first, error); 18409eb1ecb9SPavel Labath } 18419eb1ecb9SPavel Labath m_threads_stepping_with_breakpoint.clear(); 18429eb1ecb9SPavel Labath 18439eb1ecb9SPavel Labath // Notify the delegate about the stop 18440e1d729bSPavel Labath SetCurrentThreadID(m_pending_notification_tid); 1845ed89c7feSPavel Labath SetState(StateType::eStateStopped, true); 18460e1d729bSPavel Labath m_pending_notification_tid = LLDB_INVALID_THREAD_ID; 1847c076559aSPavel Labath } 1848c076559aSPavel Labath 1849b9c1b51eSKate Stone void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) { 1850a6321a8eSPavel Labath Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD); 1851a6321a8eSPavel Labath LLDB_LOG(log, "tid: {0}", thread.GetID()); 18521dbc6c9cSPavel Labath 1853b9c1b51eSKate Stone if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID && 1854b9c1b51eSKate Stone StateIsRunningState(thread.GetState())) { 1855b9c1b51eSKate Stone // We will need to wait for this new thread to stop as well before firing 185605097246SAdrian Prantl // the notification. 1857f9077782SPavel Labath thread.RequestStop(); 1858c076559aSPavel Labath } 1859c076559aSPavel Labath } 1860068f8a7eSTamas Berghammer 1861b9c1b51eSKate Stone void NativeProcessLinux::SigchldHandler() { 1862a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 186319cbe96aSPavel Labath // Process all pending waitpid notifications. 1864b9c1b51eSKate Stone while (true) { 186519cbe96aSPavel Labath int status = -1; 1866c1a6b128SPavel Labath ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, -1, &status, 1867c1a6b128SPavel Labath __WALL | __WNOTHREAD | WNOHANG); 186819cbe96aSPavel Labath 186919cbe96aSPavel Labath if (wait_pid == 0) 187019cbe96aSPavel Labath break; // We are done. 187119cbe96aSPavel Labath 1872b9c1b51eSKate Stone if (wait_pid == -1) { 187397206d57SZachary Turner Status error(errno, eErrorTypePOSIX); 1874a6321a8eSPavel Labath LLDB_LOG(log, "waitpid (-1, &status, _) failed: {0}", error); 187519cbe96aSPavel Labath break; 187619cbe96aSPavel Labath } 187719cbe96aSPavel Labath 18783508fc8cSPavel Labath WaitStatus wait_status = WaitStatus::Decode(status); 18793508fc8cSPavel Labath bool exited = wait_status.type == WaitStatus::Exit || 18803508fc8cSPavel Labath (wait_status.type == WaitStatus::Signal && 18813508fc8cSPavel Labath wait_pid == static_cast<::pid_t>(GetID())); 188219cbe96aSPavel Labath 18833508fc8cSPavel Labath LLDB_LOG( 18843508fc8cSPavel Labath log, 18853508fc8cSPavel Labath "waitpid (-1, &status, _) => pid = {0}, status = {1}, exited = {2}", 18863508fc8cSPavel Labath wait_pid, wait_status, exited); 188719cbe96aSPavel Labath 18883508fc8cSPavel Labath MonitorCallback(wait_pid, exited, wait_status); 188919cbe96aSPavel Labath } 1890068f8a7eSTamas Berghammer } 1891068f8a7eSTamas Berghammer 189205097246SAdrian Prantl // Wrapper for ptrace to catch errors and log calls. Note that ptrace sets 189305097246SAdrian Prantl // errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*) 189497206d57SZachary Turner Status NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr, 1895b9c1b51eSKate Stone void *data, size_t data_size, 1896b9c1b51eSKate Stone long *result) { 189797206d57SZachary Turner Status error; 18984a9babb2SPavel Labath long int ret; 1899068f8a7eSTamas Berghammer 1900068f8a7eSTamas Berghammer Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 1901068f8a7eSTamas Berghammer 1902068f8a7eSTamas Berghammer PtraceDisplayBytes(req, data, data_size); 1903068f8a7eSTamas Berghammer 1904068f8a7eSTamas Berghammer errno = 0; 1905068f8a7eSTamas Berghammer if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET) 1906b9c1b51eSKate Stone ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid), 1907b9c1b51eSKate Stone *(unsigned int *)addr, data); 1908068f8a7eSTamas Berghammer else 1909b9c1b51eSKate Stone ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid), 1910b9c1b51eSKate Stone addr, data); 1911068f8a7eSTamas Berghammer 19124a9babb2SPavel Labath if (ret == -1) 1913068f8a7eSTamas Berghammer error.SetErrorToErrno(); 1914068f8a7eSTamas Berghammer 19154a9babb2SPavel Labath if (result) 19164a9babb2SPavel Labath *result = ret; 19174a9babb2SPavel Labath 191828096200SPavel Labath LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data, 191928096200SPavel Labath data_size, ret); 1920068f8a7eSTamas Berghammer 1921068f8a7eSTamas Berghammer PtraceDisplayBytes(req, data, data_size); 1922068f8a7eSTamas Berghammer 1923a6321a8eSPavel Labath if (error.Fail()) 1924a6321a8eSPavel Labath LLDB_LOG(log, "ptrace() failed: {0}", error); 1925068f8a7eSTamas Berghammer 19264a9babb2SPavel Labath return error; 1927068f8a7eSTamas Berghammer } 192899e37695SRavitheja Addepally 192999e37695SRavitheja Addepally llvm::Expected<ProcessorTraceMonitor &> 193099e37695SRavitheja Addepally NativeProcessLinux::LookupProcessorTraceInstance(lldb::user_id_t traceid, 193199e37695SRavitheja Addepally lldb::tid_t thread) { 193299e37695SRavitheja Addepally Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 193399e37695SRavitheja Addepally if (thread == LLDB_INVALID_THREAD_ID && traceid == m_pt_proces_trace_id) { 193499e37695SRavitheja Addepally LLDB_LOG(log, "thread not specified: {0}", traceid); 193599e37695SRavitheja Addepally return Status("tracing not active thread not specified").ToError(); 193699e37695SRavitheja Addepally } 193799e37695SRavitheja Addepally 193899e37695SRavitheja Addepally for (auto& iter : m_processor_trace_monitor) { 193999e37695SRavitheja Addepally if (traceid == iter.second->GetTraceID() && 194099e37695SRavitheja Addepally (thread == iter.first || thread == LLDB_INVALID_THREAD_ID)) 194199e37695SRavitheja Addepally return *(iter.second); 194299e37695SRavitheja Addepally } 194399e37695SRavitheja Addepally 194499e37695SRavitheja Addepally LLDB_LOG(log, "traceid not being traced: {0}", traceid); 194599e37695SRavitheja Addepally return Status("tracing not active for this thread").ToError(); 194699e37695SRavitheja Addepally } 194799e37695SRavitheja Addepally 194899e37695SRavitheja Addepally Status NativeProcessLinux::GetMetaData(lldb::user_id_t traceid, 194999e37695SRavitheja Addepally lldb::tid_t thread, 195099e37695SRavitheja Addepally llvm::MutableArrayRef<uint8_t> &buffer, 195199e37695SRavitheja Addepally size_t offset) { 195299e37695SRavitheja Addepally TraceOptions trace_options; 195399e37695SRavitheja Addepally Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 195499e37695SRavitheja Addepally Status error; 195599e37695SRavitheja Addepally 195699e37695SRavitheja Addepally LLDB_LOG(log, "traceid {0}", traceid); 195799e37695SRavitheja Addepally 195899e37695SRavitheja Addepally auto perf_monitor = LookupProcessorTraceInstance(traceid, thread); 195999e37695SRavitheja Addepally if (!perf_monitor) { 196099e37695SRavitheja Addepally LLDB_LOG(log, "traceid not being traced: {0}", traceid); 196199e37695SRavitheja Addepally buffer = buffer.slice(buffer.size()); 196299e37695SRavitheja Addepally error = perf_monitor.takeError(); 196399e37695SRavitheja Addepally return error; 196499e37695SRavitheja Addepally } 196599e37695SRavitheja Addepally return (*perf_monitor).ReadPerfTraceData(buffer, offset); 196699e37695SRavitheja Addepally } 196799e37695SRavitheja Addepally 196899e37695SRavitheja Addepally Status NativeProcessLinux::GetData(lldb::user_id_t traceid, lldb::tid_t thread, 196999e37695SRavitheja Addepally llvm::MutableArrayRef<uint8_t> &buffer, 197099e37695SRavitheja Addepally size_t offset) { 197199e37695SRavitheja Addepally Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 197299e37695SRavitheja Addepally Status error; 197399e37695SRavitheja Addepally 197499e37695SRavitheja Addepally LLDB_LOG(log, "traceid {0}", traceid); 197599e37695SRavitheja Addepally 197699e37695SRavitheja Addepally auto perf_monitor = LookupProcessorTraceInstance(traceid, thread); 197799e37695SRavitheja Addepally if (!perf_monitor) { 197899e37695SRavitheja Addepally LLDB_LOG(log, "traceid not being traced: {0}", traceid); 197999e37695SRavitheja Addepally buffer = buffer.slice(buffer.size()); 198099e37695SRavitheja Addepally error = perf_monitor.takeError(); 198199e37695SRavitheja Addepally return error; 198299e37695SRavitheja Addepally } 198399e37695SRavitheja Addepally return (*perf_monitor).ReadPerfTraceAux(buffer, offset); 198499e37695SRavitheja Addepally } 198599e37695SRavitheja Addepally 198699e37695SRavitheja Addepally Status NativeProcessLinux::GetTraceConfig(lldb::user_id_t traceid, 198799e37695SRavitheja Addepally TraceOptions &config) { 198899e37695SRavitheja Addepally Status error; 198999e37695SRavitheja Addepally if (config.getThreadID() == LLDB_INVALID_THREAD_ID && 199099e37695SRavitheja Addepally m_pt_proces_trace_id == traceid) { 199199e37695SRavitheja Addepally if (m_pt_proces_trace_id == LLDB_INVALID_UID) { 199299e37695SRavitheja Addepally error.SetErrorString("tracing not active for this process"); 199399e37695SRavitheja Addepally return error; 199499e37695SRavitheja Addepally } 199599e37695SRavitheja Addepally config = m_pt_process_trace_config; 199699e37695SRavitheja Addepally } else { 199799e37695SRavitheja Addepally auto perf_monitor = 199899e37695SRavitheja Addepally LookupProcessorTraceInstance(traceid, config.getThreadID()); 199999e37695SRavitheja Addepally if (!perf_monitor) { 200099e37695SRavitheja Addepally error = perf_monitor.takeError(); 200199e37695SRavitheja Addepally return error; 200299e37695SRavitheja Addepally } 200399e37695SRavitheja Addepally error = (*perf_monitor).GetTraceConfig(config); 200499e37695SRavitheja Addepally } 200599e37695SRavitheja Addepally return error; 200699e37695SRavitheja Addepally } 200799e37695SRavitheja Addepally 200821555fffSWalter Erquinigo llvm::Expected<TraceTypeInfo> NativeProcessLinux::GetSupportedTraceType() { 200921555fffSWalter Erquinigo if (ProcessorTraceMonitor::IsSupported()) 201021555fffSWalter Erquinigo return TraceTypeInfo{"intel-pt", "Intel Processor Trace"}; 201121555fffSWalter Erquinigo return NativeProcessProtocol::GetSupportedTraceType(); 201221555fffSWalter Erquinigo } 201321555fffSWalter Erquinigo 201499e37695SRavitheja Addepally lldb::user_id_t 201599e37695SRavitheja Addepally NativeProcessLinux::StartTraceGroup(const TraceOptions &config, 201699e37695SRavitheja Addepally Status &error) { 201799e37695SRavitheja Addepally 201899e37695SRavitheja Addepally Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 201999e37695SRavitheja Addepally if (config.getType() != TraceType::eTraceTypeProcessorTrace) 202099e37695SRavitheja Addepally return LLDB_INVALID_UID; 202199e37695SRavitheja Addepally 202299e37695SRavitheja Addepally if (m_pt_proces_trace_id != LLDB_INVALID_UID) { 202399e37695SRavitheja Addepally error.SetErrorString("tracing already active on this process"); 202499e37695SRavitheja Addepally return m_pt_proces_trace_id; 202599e37695SRavitheja Addepally } 202699e37695SRavitheja Addepally 202799e37695SRavitheja Addepally for (const auto &thread_sp : m_threads) { 202899e37695SRavitheja Addepally if (auto traceInstance = ProcessorTraceMonitor::Create( 202999e37695SRavitheja Addepally GetID(), thread_sp->GetID(), config, true)) { 203099e37695SRavitheja Addepally m_pt_traced_thread_group.insert(thread_sp->GetID()); 203199e37695SRavitheja Addepally m_processor_trace_monitor.insert( 203299e37695SRavitheja Addepally std::make_pair(thread_sp->GetID(), std::move(*traceInstance))); 203399e37695SRavitheja Addepally } 203499e37695SRavitheja Addepally } 203599e37695SRavitheja Addepally 203699e37695SRavitheja Addepally m_pt_process_trace_config = config; 203799e37695SRavitheja Addepally error = ProcessorTraceMonitor::GetCPUType(m_pt_process_trace_config); 203899e37695SRavitheja Addepally 203999e37695SRavitheja Addepally // Trace on Complete process will have traceid of 0 204099e37695SRavitheja Addepally m_pt_proces_trace_id = 0; 204199e37695SRavitheja Addepally 204299e37695SRavitheja Addepally LLDB_LOG(log, "Process Trace ID {0}", m_pt_proces_trace_id); 204399e37695SRavitheja Addepally return m_pt_proces_trace_id; 204499e37695SRavitheja Addepally } 204599e37695SRavitheja Addepally 204699e37695SRavitheja Addepally lldb::user_id_t NativeProcessLinux::StartTrace(const TraceOptions &config, 204799e37695SRavitheja Addepally Status &error) { 204899e37695SRavitheja Addepally if (config.getType() != TraceType::eTraceTypeProcessorTrace) 204999e37695SRavitheja Addepally return NativeProcessProtocol::StartTrace(config, error); 205099e37695SRavitheja Addepally 205199e37695SRavitheja Addepally Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 205299e37695SRavitheja Addepally 205399e37695SRavitheja Addepally lldb::tid_t threadid = config.getThreadID(); 205499e37695SRavitheja Addepally 205599e37695SRavitheja Addepally if (threadid == LLDB_INVALID_THREAD_ID) 205699e37695SRavitheja Addepally return StartTraceGroup(config, error); 205799e37695SRavitheja Addepally 205899e37695SRavitheja Addepally auto thread_sp = GetThreadByID(threadid); 205999e37695SRavitheja Addepally if (!thread_sp) { 206099e37695SRavitheja Addepally // Thread not tracked by lldb so don't trace. 206199e37695SRavitheja Addepally error.SetErrorString("invalid thread id"); 206299e37695SRavitheja Addepally return LLDB_INVALID_UID; 206399e37695SRavitheja Addepally } 206499e37695SRavitheja Addepally 206599e37695SRavitheja Addepally const auto &iter = m_processor_trace_monitor.find(threadid); 206699e37695SRavitheja Addepally if (iter != m_processor_trace_monitor.end()) { 206799e37695SRavitheja Addepally LLDB_LOG(log, "Thread already being traced"); 206899e37695SRavitheja Addepally error.SetErrorString("tracing already active on this thread"); 206999e37695SRavitheja Addepally return LLDB_INVALID_UID; 207099e37695SRavitheja Addepally } 207199e37695SRavitheja Addepally 207299e37695SRavitheja Addepally auto traceMonitor = 207399e37695SRavitheja Addepally ProcessorTraceMonitor::Create(GetID(), threadid, config, false); 207499e37695SRavitheja Addepally if (!traceMonitor) { 207599e37695SRavitheja Addepally error = traceMonitor.takeError(); 207699e37695SRavitheja Addepally LLDB_LOG(log, "error {0}", error); 207799e37695SRavitheja Addepally return LLDB_INVALID_UID; 207899e37695SRavitheja Addepally } 207999e37695SRavitheja Addepally lldb::user_id_t ret_trace_id = (*traceMonitor)->GetTraceID(); 208099e37695SRavitheja Addepally m_processor_trace_monitor.insert( 208199e37695SRavitheja Addepally std::make_pair(threadid, std::move(*traceMonitor))); 208299e37695SRavitheja Addepally return ret_trace_id; 208399e37695SRavitheja Addepally } 208499e37695SRavitheja Addepally 208599e37695SRavitheja Addepally Status NativeProcessLinux::StopTracingForThread(lldb::tid_t thread) { 208699e37695SRavitheja Addepally Status error; 208799e37695SRavitheja Addepally Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 208899e37695SRavitheja Addepally LLDB_LOG(log, "Thread {0}", thread); 208999e37695SRavitheja Addepally 209099e37695SRavitheja Addepally const auto& iter = m_processor_trace_monitor.find(thread); 209199e37695SRavitheja Addepally if (iter == m_processor_trace_monitor.end()) { 209299e37695SRavitheja Addepally error.SetErrorString("tracing not active for this thread"); 209399e37695SRavitheja Addepally return error; 209499e37695SRavitheja Addepally } 209599e37695SRavitheja Addepally 209699e37695SRavitheja Addepally if (iter->second->GetTraceID() == m_pt_proces_trace_id) { 209705097246SAdrian Prantl // traceid maps to the whole process so we have to erase it from the thread 209805097246SAdrian Prantl // group. 209999e37695SRavitheja Addepally LLDB_LOG(log, "traceid maps to process"); 210099e37695SRavitheja Addepally m_pt_traced_thread_group.erase(thread); 210199e37695SRavitheja Addepally } 210299e37695SRavitheja Addepally m_processor_trace_monitor.erase(iter); 210399e37695SRavitheja Addepally 210499e37695SRavitheja Addepally return error; 210599e37695SRavitheja Addepally } 210699e37695SRavitheja Addepally 210799e37695SRavitheja Addepally Status NativeProcessLinux::StopTrace(lldb::user_id_t traceid, 210899e37695SRavitheja Addepally lldb::tid_t thread) { 210999e37695SRavitheja Addepally Status error; 211099e37695SRavitheja Addepally 211199e37695SRavitheja Addepally TraceOptions trace_options; 211299e37695SRavitheja Addepally trace_options.setThreadID(thread); 211399e37695SRavitheja Addepally error = NativeProcessLinux::GetTraceConfig(traceid, trace_options); 211499e37695SRavitheja Addepally 211599e37695SRavitheja Addepally if (error.Fail()) 211699e37695SRavitheja Addepally return error; 211799e37695SRavitheja Addepally 211899e37695SRavitheja Addepally switch (trace_options.getType()) { 211999e37695SRavitheja Addepally case lldb::TraceType::eTraceTypeProcessorTrace: 212099e37695SRavitheja Addepally if (traceid == m_pt_proces_trace_id && 212199e37695SRavitheja Addepally thread == LLDB_INVALID_THREAD_ID) 212299e37695SRavitheja Addepally StopProcessorTracingOnProcess(); 212399e37695SRavitheja Addepally else 212499e37695SRavitheja Addepally error = StopProcessorTracingOnThread(traceid, thread); 212599e37695SRavitheja Addepally break; 212699e37695SRavitheja Addepally default: 212799e37695SRavitheja Addepally error.SetErrorString("trace not supported"); 212899e37695SRavitheja Addepally break; 212999e37695SRavitheja Addepally } 213099e37695SRavitheja Addepally 213199e37695SRavitheja Addepally return error; 213299e37695SRavitheja Addepally } 213399e37695SRavitheja Addepally 213499e37695SRavitheja Addepally void NativeProcessLinux::StopProcessorTracingOnProcess() { 213599e37695SRavitheja Addepally for (auto thread_id_iter : m_pt_traced_thread_group) 213699e37695SRavitheja Addepally m_processor_trace_monitor.erase(thread_id_iter); 213799e37695SRavitheja Addepally m_pt_traced_thread_group.clear(); 213899e37695SRavitheja Addepally m_pt_proces_trace_id = LLDB_INVALID_UID; 213999e37695SRavitheja Addepally } 214099e37695SRavitheja Addepally 214199e37695SRavitheja Addepally Status NativeProcessLinux::StopProcessorTracingOnThread(lldb::user_id_t traceid, 214299e37695SRavitheja Addepally lldb::tid_t thread) { 214399e37695SRavitheja Addepally Status error; 214499e37695SRavitheja Addepally Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 214599e37695SRavitheja Addepally 214699e37695SRavitheja Addepally if (thread == LLDB_INVALID_THREAD_ID) { 214799e37695SRavitheja Addepally for (auto& iter : m_processor_trace_monitor) { 214899e37695SRavitheja Addepally if (iter.second->GetTraceID() == traceid) { 214905097246SAdrian Prantl // Stopping a trace instance for an individual thread hence there will 215005097246SAdrian Prantl // only be one traceid that can match. 215199e37695SRavitheja Addepally m_processor_trace_monitor.erase(iter.first); 215299e37695SRavitheja Addepally return error; 215399e37695SRavitheja Addepally } 215499e37695SRavitheja Addepally LLDB_LOG(log, "Trace ID {0}", iter.second->GetTraceID()); 215599e37695SRavitheja Addepally } 215699e37695SRavitheja Addepally 215799e37695SRavitheja Addepally LLDB_LOG(log, "Invalid TraceID"); 215899e37695SRavitheja Addepally error.SetErrorString("invalid trace id"); 215999e37695SRavitheja Addepally return error; 216099e37695SRavitheja Addepally } 216199e37695SRavitheja Addepally 216299e37695SRavitheja Addepally // thread is specified so we can use find function on the map. 216399e37695SRavitheja Addepally const auto& iter = m_processor_trace_monitor.find(thread); 216499e37695SRavitheja Addepally if (iter == m_processor_trace_monitor.end()) { 216599e37695SRavitheja Addepally // thread not found in our map. 216699e37695SRavitheja Addepally LLDB_LOG(log, "thread not being traced"); 216799e37695SRavitheja Addepally error.SetErrorString("tracing not active for this thread"); 216899e37695SRavitheja Addepally return error; 216999e37695SRavitheja Addepally } 217099e37695SRavitheja Addepally if (iter->second->GetTraceID() != traceid) { 217199e37695SRavitheja Addepally // traceid did not match so it has to be invalid. 217299e37695SRavitheja Addepally LLDB_LOG(log, "Invalid TraceID"); 217399e37695SRavitheja Addepally error.SetErrorString("invalid trace id"); 217499e37695SRavitheja Addepally return error; 217599e37695SRavitheja Addepally } 217699e37695SRavitheja Addepally 217799e37695SRavitheja Addepally LLDB_LOG(log, "UID - {0} , Thread -{1}", traceid, thread); 217899e37695SRavitheja Addepally 217999e37695SRavitheja Addepally if (traceid == m_pt_proces_trace_id) { 218005097246SAdrian Prantl // traceid maps to the whole process so we have to erase it from the thread 218105097246SAdrian Prantl // group. 218299e37695SRavitheja Addepally LLDB_LOG(log, "traceid maps to process"); 218399e37695SRavitheja Addepally m_pt_traced_thread_group.erase(thread); 218499e37695SRavitheja Addepally } 218599e37695SRavitheja Addepally m_processor_trace_monitor.erase(iter); 218699e37695SRavitheja Addepally 218799e37695SRavitheja Addepally return error; 218899e37695SRavitheja Addepally } 2189