1af245d11STodd Fiala //===-- NativeProcessLinux.cpp -------------------------------- -*- C++ -*-===// 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 22d8c338d4STamas Berghammer #include "lldb/Core/EmulateInstruction.h" 236edef204SOleksiy Vyalov #include "lldb/Core/ModuleSpec.h" 24af245d11STodd Fiala #include "lldb/Host/Host.h" 255ad891f7SPavel Labath #include "lldb/Host/HostProcess.h" 26eef758e9SPavel Labath #include "lldb/Host/ProcessLaunchInfo.h" 2724ae6294SZachary Turner #include "lldb/Host/PseudoTerminal.h" 2839de3110SZachary Turner #include "lldb/Host/ThreadLauncher.h" 292a86b555SPavel Labath #include "lldb/Host/common/NativeRegisterContext.h" 304ee1c952SPavel Labath #include "lldb/Host/linux/Ptrace.h" 314ee1c952SPavel Labath #include "lldb/Host/linux/Uio.h" 32816ae4b0SKamil Rytarowski #include "lldb/Host/posix/ProcessLauncherPosixFork.h" 332a86b555SPavel Labath #include "lldb/Symbol/ObjectFile.h" 3490aff47cSZachary Turner #include "lldb/Target/Process.h" 355b981ab9SPavel Labath #include "lldb/Target/Target.h" 36c16f5dcaSChaoren Lin #include "lldb/Utility/LLDBAssert.h" 37d821c997SPavel Labath #include "lldb/Utility/RegisterValue.h" 38d821c997SPavel Labath #include "lldb/Utility/State.h" 3997206d57SZachary Turner #include "lldb/Utility/Status.h" 40f805e190SPavel Labath #include "lldb/Utility/StringExtractor.h" 4110c41f37SPavel Labath #include "llvm/Support/Errno.h" 4210c41f37SPavel Labath #include "llvm/Support/FileSystem.h" 4310c41f37SPavel Labath #include "llvm/Support/Threading.h" 44af245d11STodd Fiala 45af245d11STodd Fiala #include "NativeThreadLinux.h" 46b9c1b51eSKate Stone #include "Plugins/Process/POSIX/ProcessPOSIXLog.h" 47c8e364e8SPavel Labath #include "Plugins/Process/Utility/LinuxProcMaps.h" 481e209fccSTamas Berghammer #include "Procfs.h" 49cacde7dfSTodd 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( 25996e600fcSPavel Labath pid, launch_info.GetPTY().ReleaseMasterFileDescriptor(), 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) 29196e600fcSPavel Labath : NativeProcessProtocol(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 602a5be48b3SPavel Labath for (auto i = m_threads.begin(); i != m_threads.end();) { 603a5be48b3SPavel Labath if ((*i)->GetID() == GetID()) 604a5be48b3SPavel Labath i = m_threads.erase(i); 605a5be48b3SPavel Labath else 606a5be48b3SPavel Labath ++i; 607a9882ceeSTodd Fiala } 608a5be48b3SPavel Labath assert(m_threads.size() == 1); 609a5be48b3SPavel Labath auto *main_thread = static_cast<NativeThreadLinux *>(m_threads[0].get()); 610a9882ceeSTodd Fiala 611a5be48b3SPavel Labath SetCurrentThreadID(main_thread->GetID()); 612a5be48b3SPavel Labath main_thread->SetStoppedByExec(); 613a9882ceeSTodd Fiala 614fa03ad2eSChaoren Lin // Tell coordinator about about the "new" (since exec) stopped main thread. 615a5be48b3SPavel Labath ThreadWasCreated(*main_thread); 616fa03ad2eSChaoren Lin 617a9882ceeSTodd Fiala // Let our delegate know we have just exec'd. 618a9882ceeSTodd Fiala NotifyDidExec(); 619a9882ceeSTodd Fiala 620fa03ad2eSChaoren Lin // Let the process know we're stopped. 621a5be48b3SPavel Labath StopRunningThreads(main_thread->GetID()); 622a9882ceeSTodd Fiala 623af245d11STodd Fiala break; 624a9882ceeSTodd Fiala } 625af245d11STodd Fiala 626b9c1b51eSKate Stone case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): { 62705097246SAdrian Prantl // The inferior process or one of its threads is about to exit. We don't 62805097246SAdrian Prantl // want to do anything with the thread so we just resume it. In case we 62905097246SAdrian Prantl // want to implement "break on thread exit" functionality, we would need to 63005097246SAdrian Prantl // stop here. 631fa03ad2eSChaoren Lin 632af245d11STodd Fiala unsigned long data = 0; 633b9cc0c75SPavel Labath if (GetEventMessage(thread.GetID(), &data).Fail()) 634af245d11STodd Fiala data = -1; 635af245d11STodd Fiala 636a6321a8eSPavel Labath LLDB_LOG(log, 637a6321a8eSPavel Labath "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, " 638a6321a8eSPavel Labath "WIFSIGNALED={2}, pid = {3}, main_thread = {4}", 639a6321a8eSPavel Labath data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(), 640a6321a8eSPavel Labath is_main_thread); 641af245d11STodd Fiala 64275f47c3aSTodd Fiala 64386852d36SPavel Labath StateType state = thread.GetState(); 644b9c1b51eSKate Stone if (!StateIsRunningState(state)) { 645b9c1b51eSKate Stone // Due to a kernel bug, we may sometimes get this stop after the inferior 646d8b3c1a1SPavel Labath // gets a SIGKILL. This confuses our state tracking logic in 647d8b3c1a1SPavel Labath // ResumeThread(), since normally, we should not be receiving any ptrace 64805097246SAdrian Prantl // events while the inferior is stopped. This makes sure that the 64905097246SAdrian Prantl // inferior is resumed and exits normally. 65086852d36SPavel Labath state = eStateRunning; 65186852d36SPavel Labath } 65286852d36SPavel Labath ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER); 653af245d11STodd Fiala 654af245d11STodd Fiala break; 655af245d11STodd Fiala } 656af245d11STodd Fiala 657af245d11STodd Fiala case 0: 658c16f5dcaSChaoren Lin case TRAP_TRACE: // We receive this on single stepping. 659c16f5dcaSChaoren Lin case TRAP_HWBKPT: // We receive this on watchpoint hit 66086fd8e45SChaoren Lin { 661c16f5dcaSChaoren Lin // If a watchpoint was hit, report it 662c16f5dcaSChaoren Lin uint32_t wp_index; 663d37349f3SPavel Labath Status error = thread.GetRegisterContext().GetWatchpointHitIndex( 664b9c1b51eSKate Stone wp_index, (uintptr_t)info.si_addr); 665a6321a8eSPavel Labath if (error.Fail()) 666a6321a8eSPavel Labath LLDB_LOG(log, 667a6321a8eSPavel Labath "received error while checking for watchpoint hits, pid = " 668a6321a8eSPavel Labath "{0}, error = {1}", 669a6321a8eSPavel Labath thread.GetID(), error); 670b9c1b51eSKate Stone if (wp_index != LLDB_INVALID_INDEX32) { 671b9cc0c75SPavel Labath MonitorWatchpoint(thread, wp_index); 672c16f5dcaSChaoren Lin break; 673c16f5dcaSChaoren Lin } 674b9cc0c75SPavel Labath 675d5ffbad2SOmair Javaid // If a breakpoint was hit, report it 676d5ffbad2SOmair Javaid uint32_t bp_index; 677d37349f3SPavel Labath error = thread.GetRegisterContext().GetHardwareBreakHitIndex( 678d5ffbad2SOmair Javaid bp_index, (uintptr_t)info.si_addr); 679d5ffbad2SOmair Javaid if (error.Fail()) 680d5ffbad2SOmair Javaid LLDB_LOG(log, "received error while checking for hardware " 681d5ffbad2SOmair Javaid "breakpoint hits, pid = {0}, error = {1}", 682d5ffbad2SOmair Javaid thread.GetID(), error); 683d5ffbad2SOmair Javaid if (bp_index != LLDB_INVALID_INDEX32) { 684d5ffbad2SOmair Javaid MonitorBreakpoint(thread); 685d5ffbad2SOmair Javaid break; 686d5ffbad2SOmair Javaid } 687d5ffbad2SOmair Javaid 688be379e15STamas Berghammer // Otherwise, report step over 689be379e15STamas Berghammer MonitorTrace(thread); 690af245d11STodd Fiala break; 691b9cc0c75SPavel Labath } 692af245d11STodd Fiala 693af245d11STodd Fiala case SI_KERNEL: 69435799963SMohit K. Bhakkad #if defined __mips__ 69505097246SAdrian Prantl // For mips there is no special signal for watchpoint So we check for 69605097246SAdrian Prantl // watchpoint in kernel trap 69735799963SMohit K. Bhakkad { 69835799963SMohit K. Bhakkad // If a watchpoint was hit, report it 69935799963SMohit K. Bhakkad uint32_t wp_index; 700d37349f3SPavel Labath Status error = thread.GetRegisterContext().GetWatchpointHitIndex( 701b9c1b51eSKate Stone wp_index, LLDB_INVALID_ADDRESS); 702a6321a8eSPavel Labath if (error.Fail()) 703a6321a8eSPavel Labath LLDB_LOG(log, 704a6321a8eSPavel Labath "received error while checking for watchpoint hits, pid = " 705a6321a8eSPavel Labath "{0}, error = {1}", 706a6321a8eSPavel Labath thread.GetID(), error); 707b9c1b51eSKate Stone if (wp_index != LLDB_INVALID_INDEX32) { 708b9cc0c75SPavel Labath MonitorWatchpoint(thread, wp_index); 70935799963SMohit K. Bhakkad break; 71035799963SMohit K. Bhakkad } 71135799963SMohit K. Bhakkad } 71235799963SMohit K. Bhakkad // NO BREAK 71335799963SMohit K. Bhakkad #endif 714af245d11STodd Fiala case TRAP_BRKPT: 715b9cc0c75SPavel Labath MonitorBreakpoint(thread); 716af245d11STodd Fiala break; 717af245d11STodd Fiala 718af245d11STodd Fiala case SIGTRAP: 719af245d11STodd Fiala case (SIGTRAP | 0x80): 720a6321a8eSPavel Labath LLDB_LOG( 721a6321a8eSPavel Labath log, 722a6321a8eSPavel Labath "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming", 723a6321a8eSPavel Labath info.si_code, GetID(), thread.GetID()); 724fa03ad2eSChaoren Lin 725af245d11STodd Fiala // Ignore these signals until we know more about them. 726b9cc0c75SPavel Labath ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER); 727af245d11STodd Fiala break; 728af245d11STodd Fiala 729af245d11STodd Fiala default: 73021a365baSPavel Labath LLDB_LOG(log, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}", 731a6321a8eSPavel Labath info.si_code, GetID(), thread.GetID()); 73221a365baSPavel Labath MonitorSignal(info, thread, false); 733af245d11STodd Fiala break; 734af245d11STodd Fiala } 735af245d11STodd Fiala } 736af245d11STodd Fiala 737b9c1b51eSKate Stone void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) { 738a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 739a6321a8eSPavel Labath LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID()); 740c16f5dcaSChaoren Lin 7410e1d729bSPavel Labath // This thread is currently stopped. 742b9cc0c75SPavel Labath thread.SetStoppedByTrace(); 743c16f5dcaSChaoren Lin 744b9cc0c75SPavel Labath StopRunningThreads(thread.GetID()); 745c16f5dcaSChaoren Lin } 746c16f5dcaSChaoren Lin 747b9c1b51eSKate Stone void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) { 748b9c1b51eSKate Stone Log *log( 749b9c1b51eSKate Stone GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS)); 750a6321a8eSPavel Labath LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID()); 751c16f5dcaSChaoren Lin 752c16f5dcaSChaoren Lin // Mark the thread as stopped at breakpoint. 753b9cc0c75SPavel Labath thread.SetStoppedByBreakpoint(); 754aef7908fSPavel Labath FixupBreakpointPCAsNeeded(thread); 755d8c338d4STamas Berghammer 756b9c1b51eSKate Stone if (m_threads_stepping_with_breakpoint.find(thread.GetID()) != 757b9c1b51eSKate Stone m_threads_stepping_with_breakpoint.end()) 758b9cc0c75SPavel Labath thread.SetStoppedByTrace(); 759c16f5dcaSChaoren Lin 760b9cc0c75SPavel Labath StopRunningThreads(thread.GetID()); 761c16f5dcaSChaoren Lin } 762c16f5dcaSChaoren Lin 763b9c1b51eSKate Stone void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread, 764b9c1b51eSKate Stone uint32_t wp_index) { 765b9c1b51eSKate Stone Log *log( 766b9c1b51eSKate Stone GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS)); 767a6321a8eSPavel Labath LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}", 768a6321a8eSPavel Labath thread.GetID(), wp_index); 769c16f5dcaSChaoren Lin 77005097246SAdrian Prantl // Mark the thread as stopped at watchpoint. The address is at 77105097246SAdrian Prantl // (lldb::addr_t)info->si_addr if we need it. 772f9077782SPavel Labath thread.SetStoppedByWatchpoint(wp_index); 773c16f5dcaSChaoren Lin 774b9c1b51eSKate Stone // We need to tell all other running threads before we notify the delegate 775b9c1b51eSKate Stone // about this stop. 776f9077782SPavel Labath StopRunningThreads(thread.GetID()); 777c16f5dcaSChaoren Lin } 778c16f5dcaSChaoren Lin 779b9c1b51eSKate Stone void NativeProcessLinux::MonitorSignal(const siginfo_t &info, 780b9c1b51eSKate Stone NativeThreadLinux &thread, bool exited) { 781b9cc0c75SPavel Labath const int signo = info.si_signo; 782b9cc0c75SPavel Labath const bool is_from_llgs = info.si_pid == getpid(); 783af245d11STodd Fiala 784a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 785af245d11STodd Fiala 786af245d11STodd Fiala // POSIX says that process behaviour is undefined after it ignores a SIGFPE, 78705097246SAdrian Prantl // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a kill(2) 78805097246SAdrian Prantl // or raise(3). Similarly for tgkill(2) on Linux. 789af245d11STodd Fiala // 790af245d11STodd Fiala // IOW, user generated signals never generate what we consider to be a 791af245d11STodd Fiala // "crash". 792af245d11STodd Fiala // 793af245d11STodd Fiala // Similarly, ACK signals generated by this monitor. 794af245d11STodd Fiala 795af245d11STodd Fiala // Handle the signal. 796a6321a8eSPavel Labath LLDB_LOG(log, 797a6321a8eSPavel Labath "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, " 798a6321a8eSPavel Labath "waitpid pid = {4})", 799a6321a8eSPavel Labath Host::GetSignalAsCString(signo), signo, info.si_code, 800b9cc0c75SPavel Labath thread.GetID()); 80158a2f669STodd Fiala 80258a2f669STodd Fiala // Check for thread stop notification. 803b9c1b51eSKate Stone if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) { 804af245d11STodd Fiala // This is a tgkill()-based stop. 805a6321a8eSPavel Labath LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID()); 806fa03ad2eSChaoren Lin 80705097246SAdrian Prantl // Check that we're not already marked with a stop reason. Note this thread 80805097246SAdrian Prantl // really shouldn't already be marked as stopped - if we were, that would 80905097246SAdrian Prantl // imply that the kernel signaled us with the thread stopping which we 81005097246SAdrian Prantl // handled and marked as stopped, and that, without an intervening resume, 81105097246SAdrian Prantl // we received another stop. It is more likely that we are missing the 81205097246SAdrian Prantl // marking of a run state somewhere if we find that the thread was marked 81305097246SAdrian Prantl // as stopped. 814b9cc0c75SPavel Labath const StateType thread_state = thread.GetState(); 815b9c1b51eSKate Stone if (!StateIsStoppedState(thread_state, false)) { 816ed89c7feSPavel Labath // An inferior thread has stopped because of a SIGSTOP we have sent it. 817b9c1b51eSKate Stone // Generally, these are not important stops and we don't want to report 818a6321a8eSPavel Labath // them as they are just used to stop other threads when one thread (the 819a6321a8eSPavel Labath // one with the *real* stop reason) hits a breakpoint (watchpoint, 82005097246SAdrian Prantl // etc...). However, in the case of an asynchronous Interrupt(), this 82105097246SAdrian Prantl // *is* the real stop reason, so we leave the signal intact if this is 82205097246SAdrian Prantl // the thread that was chosen as the triggering thread. 823b9c1b51eSKate Stone if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) { 824b9cc0c75SPavel Labath if (m_pending_notification_tid == thread.GetID()) 825b9cc0c75SPavel Labath thread.SetStoppedBySignal(SIGSTOP, &info); 826ed89c7feSPavel Labath else 827b9cc0c75SPavel Labath thread.SetStoppedWithNoReason(); 828ed89c7feSPavel Labath 829b9cc0c75SPavel Labath SetCurrentThreadID(thread.GetID()); 8300e1d729bSPavel Labath SignalIfAllThreadsStopped(); 831b9c1b51eSKate Stone } else { 8320e1d729bSPavel Labath // We can end up here if stop was initiated by LLGS but by this time a 8330e1d729bSPavel Labath // thread stop has occurred - maybe initiated by another event. 83497206d57SZachary Turner Status error = ResumeThread(thread, thread.GetState(), 0); 835a6321a8eSPavel Labath if (error.Fail()) 836a6321a8eSPavel Labath LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(), 837a6321a8eSPavel Labath error); 8380e1d729bSPavel Labath } 839b9c1b51eSKate Stone } else { 840a6321a8eSPavel Labath LLDB_LOG(log, 841a6321a8eSPavel Labath "pid {0} tid {1}, thread was already marked as a stopped " 842a6321a8eSPavel Labath "state (state={2}), leaving stop signal as is", 8438198db30SPavel Labath GetID(), thread.GetID(), thread_state); 8440e1d729bSPavel Labath SignalIfAllThreadsStopped(); 845af245d11STodd Fiala } 846af245d11STodd Fiala 84758a2f669STodd Fiala // Done handling. 848af245d11STodd Fiala return; 849af245d11STodd Fiala } 850af245d11STodd Fiala 85105097246SAdrian Prantl // Check if debugger should stop at this signal or just ignore it and resume 85205097246SAdrian Prantl // the inferior. 8534a705e7eSPavel Labath if (m_signals_to_ignore.find(signo) != m_signals_to_ignore.end()) { 8544a705e7eSPavel Labath ResumeThread(thread, thread.GetState(), signo); 8554a705e7eSPavel Labath return; 8564a705e7eSPavel Labath } 8574a705e7eSPavel Labath 85886fd8e45SChaoren Lin // This thread is stopped. 859a6321a8eSPavel Labath LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo)); 860b9cc0c75SPavel Labath thread.SetStoppedBySignal(signo, &info); 86186fd8e45SChaoren Lin 86286fd8e45SChaoren Lin // Send a stop to the debugger after we get all other threads to stop. 863b9cc0c75SPavel Labath StopRunningThreads(thread.GetID()); 864511e5cdcSTodd Fiala } 865af245d11STodd Fiala 866e7708688STamas Berghammer namespace { 867e7708688STamas Berghammer 868b9c1b51eSKate Stone struct EmulatorBaton { 869d37349f3SPavel Labath NativeProcessLinux &m_process; 870d37349f3SPavel Labath NativeRegisterContext &m_reg_context; 8716648fcc3SPavel Labath 8726648fcc3SPavel Labath // eRegisterKindDWARF -> RegsiterValue 8736648fcc3SPavel Labath std::unordered_map<uint32_t, RegisterValue> m_register_values; 874e7708688STamas Berghammer 875d37349f3SPavel Labath EmulatorBaton(NativeProcessLinux &process, NativeRegisterContext ®_context) 876b9c1b51eSKate Stone : m_process(process), m_reg_context(reg_context) {} 877e7708688STamas Berghammer }; 878e7708688STamas Berghammer 879e7708688STamas Berghammer } // anonymous namespace 880e7708688STamas Berghammer 881b9c1b51eSKate Stone static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton, 882e7708688STamas Berghammer const EmulateInstruction::Context &context, 883b9c1b51eSKate Stone lldb::addr_t addr, void *dst, size_t length) { 884e7708688STamas Berghammer EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton); 885e7708688STamas Berghammer 8863eb4b458SChaoren Lin size_t bytes_read; 887d37349f3SPavel Labath emulator_baton->m_process.ReadMemory(addr, dst, length, bytes_read); 888e7708688STamas Berghammer return bytes_read; 889e7708688STamas Berghammer } 890e7708688STamas Berghammer 891b9c1b51eSKate Stone static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton, 892e7708688STamas Berghammer const RegisterInfo *reg_info, 893b9c1b51eSKate Stone RegisterValue ®_value) { 894e7708688STamas Berghammer EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton); 895e7708688STamas Berghammer 896b9c1b51eSKate Stone auto it = emulator_baton->m_register_values.find( 897b9c1b51eSKate Stone reg_info->kinds[eRegisterKindDWARF]); 898b9c1b51eSKate Stone if (it != emulator_baton->m_register_values.end()) { 8996648fcc3SPavel Labath reg_value = it->second; 9006648fcc3SPavel Labath return true; 9016648fcc3SPavel Labath } 9026648fcc3SPavel Labath 90305097246SAdrian Prantl // The emulator only fill in the dwarf regsiter numbers (and in some case the 90405097246SAdrian Prantl // generic register numbers). Get the full register info from the register 90505097246SAdrian Prantl // context based on the dwarf register numbers. 906b9c1b51eSKate Stone const RegisterInfo *full_reg_info = 907d37349f3SPavel Labath emulator_baton->m_reg_context.GetRegisterInfo( 908e7708688STamas Berghammer eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]); 909e7708688STamas Berghammer 91097206d57SZachary Turner Status error = 911d37349f3SPavel Labath emulator_baton->m_reg_context.ReadRegister(full_reg_info, reg_value); 9126648fcc3SPavel Labath if (error.Success()) 9136648fcc3SPavel Labath return true; 914cdc22a88SMohit K. Bhakkad 9156648fcc3SPavel Labath return false; 916e7708688STamas Berghammer } 917e7708688STamas Berghammer 918b9c1b51eSKate Stone static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton, 919e7708688STamas Berghammer const EmulateInstruction::Context &context, 920e7708688STamas Berghammer const RegisterInfo *reg_info, 921b9c1b51eSKate Stone const RegisterValue ®_value) { 922e7708688STamas Berghammer EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton); 923b9c1b51eSKate Stone emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = 924b9c1b51eSKate Stone reg_value; 925e7708688STamas Berghammer return true; 926e7708688STamas Berghammer } 927e7708688STamas Berghammer 928b9c1b51eSKate Stone static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton, 929e7708688STamas Berghammer const EmulateInstruction::Context &context, 930b9c1b51eSKate Stone lldb::addr_t addr, const void *dst, 931b9c1b51eSKate Stone size_t length) { 932e7708688STamas Berghammer return length; 933e7708688STamas Berghammer } 934e7708688STamas Berghammer 935d37349f3SPavel Labath static lldb::addr_t ReadFlags(NativeRegisterContext ®siter_context) { 936d37349f3SPavel Labath const RegisterInfo *flags_info = regsiter_context.GetRegisterInfo( 937e7708688STamas Berghammer eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS); 938d37349f3SPavel Labath return regsiter_context.ReadRegisterAsUnsigned(flags_info, 939b9c1b51eSKate Stone LLDB_INVALID_ADDRESS); 940e7708688STamas Berghammer } 941e7708688STamas Berghammer 94297206d57SZachary Turner Status 94397206d57SZachary Turner NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadLinux &thread) { 94497206d57SZachary Turner Status error; 945d37349f3SPavel Labath NativeRegisterContext& register_context = thread.GetRegisterContext(); 946e7708688STamas Berghammer 947d5b44036SJonas Devlieghere std::unique_ptr<EmulateInstruction> emulator_up( 948b9c1b51eSKate Stone EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, 949b9c1b51eSKate Stone nullptr)); 950e7708688STamas Berghammer 951d5b44036SJonas Devlieghere if (emulator_up == nullptr) 95297206d57SZachary Turner return Status("Instruction emulator not found!"); 953e7708688STamas Berghammer 954d37349f3SPavel Labath EmulatorBaton baton(*this, register_context); 955d5b44036SJonas Devlieghere emulator_up->SetBaton(&baton); 956d5b44036SJonas Devlieghere emulator_up->SetReadMemCallback(&ReadMemoryCallback); 957d5b44036SJonas Devlieghere emulator_up->SetReadRegCallback(&ReadRegisterCallback); 958d5b44036SJonas Devlieghere emulator_up->SetWriteMemCallback(&WriteMemoryCallback); 959d5b44036SJonas Devlieghere emulator_up->SetWriteRegCallback(&WriteRegisterCallback); 960e7708688STamas Berghammer 961d5b44036SJonas Devlieghere if (!emulator_up->ReadInstruction()) 96297206d57SZachary Turner return Status("Read instruction failed!"); 963e7708688STamas Berghammer 964b9c1b51eSKate Stone bool emulation_result = 965d5b44036SJonas Devlieghere emulator_up->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC); 9666648fcc3SPavel Labath 967d37349f3SPavel Labath const RegisterInfo *reg_info_pc = register_context.GetRegisterInfo( 968b9c1b51eSKate Stone eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC); 969d37349f3SPavel Labath const RegisterInfo *reg_info_flags = register_context.GetRegisterInfo( 970b9c1b51eSKate Stone eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS); 9716648fcc3SPavel Labath 972b9c1b51eSKate Stone auto pc_it = 973b9c1b51eSKate Stone baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]); 974b9c1b51eSKate Stone auto flags_it = 975b9c1b51eSKate Stone baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]); 9766648fcc3SPavel Labath 977e7708688STamas Berghammer lldb::addr_t next_pc; 978e7708688STamas Berghammer lldb::addr_t next_flags; 979b9c1b51eSKate Stone if (emulation_result) { 980b9c1b51eSKate Stone assert(pc_it != baton.m_register_values.end() && 981b9c1b51eSKate Stone "Emulation was successfull but PC wasn't updated"); 9826648fcc3SPavel Labath next_pc = pc_it->second.GetAsUInt64(); 9836648fcc3SPavel Labath 9846648fcc3SPavel Labath if (flags_it != baton.m_register_values.end()) 9856648fcc3SPavel Labath next_flags = flags_it->second.GetAsUInt64(); 986e7708688STamas Berghammer else 987d37349f3SPavel Labath next_flags = ReadFlags(register_context); 988b9c1b51eSKate Stone } else if (pc_it == baton.m_register_values.end()) { 98905097246SAdrian Prantl // Emulate instruction failed and it haven't changed PC. Advance PC with 99005097246SAdrian Prantl // the size of the current opcode because the emulation of all 991e7708688STamas Berghammer // PC modifying instruction should be successful. The failure most 992e7708688STamas Berghammer // likely caused by a not supported instruction which don't modify PC. 993d5b44036SJonas Devlieghere next_pc = register_context.GetPC() + emulator_up->GetOpcode().GetByteSize(); 994d37349f3SPavel Labath next_flags = ReadFlags(register_context); 995b9c1b51eSKate Stone } else { 996e7708688STamas Berghammer // The instruction emulation failed after it modified the PC. It is an 997e7708688STamas Berghammer // unknown error where we can't continue because the next instruction is 998e7708688STamas Berghammer // modifying the PC but we don't know how. 99997206d57SZachary Turner return Status("Instruction emulation failed unexpectedly."); 1000e7708688STamas Berghammer } 1001e7708688STamas Berghammer 1002b9c1b51eSKate Stone if (m_arch.GetMachine() == llvm::Triple::arm) { 1003b9c1b51eSKate Stone if (next_flags & 0x20) { 1004e7708688STamas Berghammer // Thumb mode 1005e7708688STamas Berghammer error = SetSoftwareBreakpoint(next_pc, 2); 1006b9c1b51eSKate Stone } else { 1007e7708688STamas Berghammer // Arm mode 1008e7708688STamas Berghammer error = SetSoftwareBreakpoint(next_pc, 4); 1009e7708688STamas Berghammer } 1010*ddb93b63SFangrui Song } else if (m_arch.IsMIPS() || m_arch.GetMachine() == llvm::Triple::ppc64le) 1011cdc22a88SMohit K. Bhakkad error = SetSoftwareBreakpoint(next_pc, 4); 1012b9c1b51eSKate Stone else { 1013e7708688STamas Berghammer // No size hint is given for the next breakpoint 1014e7708688STamas Berghammer error = SetSoftwareBreakpoint(next_pc, 0); 1015e7708688STamas Berghammer } 1016e7708688STamas Berghammer 101705097246SAdrian Prantl // If setting the breakpoint fails because next_pc is out of the address 101805097246SAdrian Prantl // space, ignore it and let the debugee segfault. 101942eb6908SPavel Labath if (error.GetError() == EIO || error.GetError() == EFAULT) { 102097206d57SZachary Turner return Status(); 102142eb6908SPavel Labath } else if (error.Fail()) 1022e7708688STamas Berghammer return error; 1023e7708688STamas Berghammer 1024b9cc0c75SPavel Labath m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc}); 1025e7708688STamas Berghammer 102697206d57SZachary Turner return Status(); 1027e7708688STamas Berghammer } 1028e7708688STamas Berghammer 1029b9c1b51eSKate Stone bool NativeProcessLinux::SupportHardwareSingleStepping() const { 1030*ddb93b63SFangrui Song if (m_arch.GetMachine() == llvm::Triple::arm || m_arch.IsMIPS()) 1031cdc22a88SMohit K. Bhakkad return false; 1032cdc22a88SMohit K. Bhakkad return true; 1033e7708688STamas Berghammer } 1034e7708688STamas Berghammer 103597206d57SZachary Turner Status NativeProcessLinux::Resume(const ResumeActionList &resume_actions) { 1036a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1037a6321a8eSPavel Labath LLDB_LOG(log, "pid {0}", GetID()); 1038af245d11STodd Fiala 1039e7708688STamas Berghammer bool software_single_step = !SupportHardwareSingleStepping(); 1040af245d11STodd Fiala 1041b9c1b51eSKate Stone if (software_single_step) { 1042a5be48b3SPavel Labath for (const auto &thread : m_threads) { 1043a5be48b3SPavel Labath assert(thread && "thread list should not contain NULL threads"); 1044e7708688STamas Berghammer 1045b9c1b51eSKate Stone const ResumeAction *const action = 1046a5be48b3SPavel Labath resume_actions.GetActionForThread(thread->GetID(), true); 1047e7708688STamas Berghammer if (action == nullptr) 1048e7708688STamas Berghammer continue; 1049e7708688STamas Berghammer 1050b9c1b51eSKate Stone if (action->state == eStateStepping) { 105197206d57SZachary Turner Status error = SetupSoftwareSingleStepping( 1052a5be48b3SPavel Labath static_cast<NativeThreadLinux &>(*thread)); 1053e7708688STamas Berghammer if (error.Fail()) 1054e7708688STamas Berghammer return error; 1055e7708688STamas Berghammer } 1056e7708688STamas Berghammer } 1057e7708688STamas Berghammer } 1058e7708688STamas Berghammer 1059a5be48b3SPavel Labath for (const auto &thread : m_threads) { 1060a5be48b3SPavel Labath assert(thread && "thread list should not contain NULL threads"); 1061af245d11STodd Fiala 1062b9c1b51eSKate Stone const ResumeAction *const action = 1063a5be48b3SPavel Labath resume_actions.GetActionForThread(thread->GetID(), true); 10646a196ce6SChaoren Lin 1065b9c1b51eSKate Stone if (action == nullptr) { 1066a6321a8eSPavel Labath LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(), 1067a5be48b3SPavel Labath thread->GetID()); 10686a196ce6SChaoren Lin continue; 10696a196ce6SChaoren Lin } 1070af245d11STodd Fiala 1071a6321a8eSPavel Labath LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}", 1072a5be48b3SPavel Labath action->state, GetID(), thread->GetID()); 1073af245d11STodd Fiala 1074b9c1b51eSKate Stone switch (action->state) { 1075af245d11STodd Fiala case eStateRunning: 1076b9c1b51eSKate Stone case eStateStepping: { 1077af245d11STodd Fiala // Run the thread, possibly feeding it the signal. 1078fa03ad2eSChaoren Lin const int signo = action->signal; 1079a5be48b3SPavel Labath ResumeThread(static_cast<NativeThreadLinux &>(*thread), action->state, 1080b9c1b51eSKate Stone signo); 1081af245d11STodd Fiala break; 1082ae29d395SChaoren Lin } 1083af245d11STodd Fiala 1084af245d11STodd Fiala case eStateSuspended: 1085af245d11STodd Fiala case eStateStopped: 1086a6321a8eSPavel Labath llvm_unreachable("Unexpected state"); 1087af245d11STodd Fiala 1088af245d11STodd Fiala default: 108997206d57SZachary Turner return Status("NativeProcessLinux::%s (): unexpected state %s specified " 1090b9c1b51eSKate Stone "for pid %" PRIu64 ", tid %" PRIu64, 1091b9c1b51eSKate Stone __FUNCTION__, StateAsCString(action->state), GetID(), 1092a5be48b3SPavel Labath thread->GetID()); 1093af245d11STodd Fiala } 1094af245d11STodd Fiala } 1095af245d11STodd Fiala 109697206d57SZachary Turner return Status(); 1097af245d11STodd Fiala } 1098af245d11STodd Fiala 109997206d57SZachary Turner Status NativeProcessLinux::Halt() { 110097206d57SZachary Turner Status error; 1101af245d11STodd Fiala 1102af245d11STodd Fiala if (kill(GetID(), SIGSTOP) != 0) 1103af245d11STodd Fiala error.SetErrorToErrno(); 1104af245d11STodd Fiala 1105af245d11STodd Fiala return error; 1106af245d11STodd Fiala } 1107af245d11STodd Fiala 110897206d57SZachary Turner Status NativeProcessLinux::Detach() { 110997206d57SZachary Turner Status error; 1110af245d11STodd Fiala 1111af245d11STodd Fiala // Stop monitoring the inferior. 111219cbe96aSPavel Labath m_sigchld_handle.reset(); 1113af245d11STodd Fiala 11147a9495bcSPavel Labath // Tell ptrace to detach from the process. 11157a9495bcSPavel Labath if (GetID() == LLDB_INVALID_PROCESS_ID) 11167a9495bcSPavel Labath return error; 11177a9495bcSPavel Labath 1118a5be48b3SPavel Labath for (const auto &thread : m_threads) { 1119a5be48b3SPavel Labath Status e = Detach(thread->GetID()); 11207a9495bcSPavel Labath if (e.Fail()) 1121b9c1b51eSKate Stone error = 1122b9c1b51eSKate Stone e; // Save the error, but still attempt to detach from other threads. 11237a9495bcSPavel Labath } 11247a9495bcSPavel Labath 112599e37695SRavitheja Addepally m_processor_trace_monitor.clear(); 112699e37695SRavitheja Addepally m_pt_proces_trace_id = LLDB_INVALID_UID; 112799e37695SRavitheja Addepally 1128af245d11STodd Fiala return error; 1129af245d11STodd Fiala } 1130af245d11STodd Fiala 113197206d57SZachary Turner Status NativeProcessLinux::Signal(int signo) { 113297206d57SZachary Turner Status error; 1133af245d11STodd Fiala 1134a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1135a6321a8eSPavel Labath LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo, 1136a6321a8eSPavel Labath Host::GetSignalAsCString(signo), GetID()); 1137af245d11STodd Fiala 1138af245d11STodd Fiala if (kill(GetID(), signo)) 1139af245d11STodd Fiala error.SetErrorToErrno(); 1140af245d11STodd Fiala 1141af245d11STodd Fiala return error; 1142af245d11STodd Fiala } 1143af245d11STodd Fiala 114497206d57SZachary Turner Status NativeProcessLinux::Interrupt() { 114505097246SAdrian Prantl // Pick a running thread (or if none, a not-dead stopped thread) as the 114605097246SAdrian Prantl // chosen thread that will be the stop-reason thread. 1147a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1148e9547b80SChaoren Lin 1149a5be48b3SPavel Labath NativeThreadProtocol *running_thread = nullptr; 1150a5be48b3SPavel Labath NativeThreadProtocol *stopped_thread = nullptr; 1151e9547b80SChaoren Lin 1152a6321a8eSPavel Labath LLDB_LOG(log, "selecting running thread for interrupt target"); 1153a5be48b3SPavel Labath for (const auto &thread : m_threads) { 115405097246SAdrian Prantl // If we have a running or stepping thread, we'll call that the target of 115505097246SAdrian Prantl // the interrupt. 1156a5be48b3SPavel Labath const auto thread_state = thread->GetState(); 1157b9c1b51eSKate Stone if (thread_state == eStateRunning || thread_state == eStateStepping) { 1158a5be48b3SPavel Labath running_thread = thread.get(); 1159e9547b80SChaoren Lin break; 1160a5be48b3SPavel Labath } else if (!stopped_thread && StateIsStoppedState(thread_state, true)) { 116105097246SAdrian Prantl // Remember the first non-dead stopped thread. We'll use that as a 116205097246SAdrian Prantl // backup if there are no running threads. 1163a5be48b3SPavel Labath stopped_thread = thread.get(); 1164e9547b80SChaoren Lin } 1165e9547b80SChaoren Lin } 1166e9547b80SChaoren Lin 1167a5be48b3SPavel Labath if (!running_thread && !stopped_thread) { 116897206d57SZachary Turner Status error("found no running/stepping or live stopped threads as target " 1169b9c1b51eSKate Stone "for interrupt"); 1170a6321a8eSPavel Labath LLDB_LOG(log, "skipping due to error: {0}", error); 11715830aa75STamas Berghammer 1172e9547b80SChaoren Lin return error; 1173e9547b80SChaoren Lin } 1174e9547b80SChaoren Lin 1175a5be48b3SPavel Labath NativeThreadProtocol *deferred_signal_thread = 1176a5be48b3SPavel Labath running_thread ? running_thread : stopped_thread; 1177e9547b80SChaoren Lin 1178a6321a8eSPavel Labath LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(), 1179a5be48b3SPavel Labath running_thread ? "running" : "stopped", 1180a5be48b3SPavel Labath deferred_signal_thread->GetID()); 1181e9547b80SChaoren Lin 1182a5be48b3SPavel Labath StopRunningThreads(deferred_signal_thread->GetID()); 118345f5cb31SPavel Labath 118497206d57SZachary Turner return Status(); 1185e9547b80SChaoren Lin } 1186e9547b80SChaoren Lin 118797206d57SZachary Turner Status NativeProcessLinux::Kill() { 1188a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1189a6321a8eSPavel Labath LLDB_LOG(log, "pid {0}", GetID()); 1190af245d11STodd Fiala 119197206d57SZachary Turner Status error; 1192af245d11STodd Fiala 1193b9c1b51eSKate Stone switch (m_state) { 1194af245d11STodd Fiala case StateType::eStateInvalid: 1195af245d11STodd Fiala case StateType::eStateExited: 1196af245d11STodd Fiala case StateType::eStateCrashed: 1197af245d11STodd Fiala case StateType::eStateDetached: 1198af245d11STodd Fiala case StateType::eStateUnloaded: 1199af245d11STodd Fiala // Nothing to do - the process is already dead. 1200a6321a8eSPavel Labath LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(), 12018198db30SPavel Labath m_state); 1202af245d11STodd Fiala return error; 1203af245d11STodd Fiala 1204af245d11STodd Fiala case StateType::eStateConnected: 1205af245d11STodd Fiala case StateType::eStateAttaching: 1206af245d11STodd Fiala case StateType::eStateLaunching: 1207af245d11STodd Fiala case StateType::eStateStopped: 1208af245d11STodd Fiala case StateType::eStateRunning: 1209af245d11STodd Fiala case StateType::eStateStepping: 1210af245d11STodd Fiala case StateType::eStateSuspended: 1211af245d11STodd Fiala // We can try to kill a process in these states. 1212af245d11STodd Fiala break; 1213af245d11STodd Fiala } 1214af245d11STodd Fiala 1215b9c1b51eSKate Stone if (kill(GetID(), SIGKILL) != 0) { 1216af245d11STodd Fiala error.SetErrorToErrno(); 1217af245d11STodd Fiala return error; 1218af245d11STodd Fiala } 1219af245d11STodd Fiala 1220af245d11STodd Fiala return error; 1221af245d11STodd Fiala } 1222af245d11STodd Fiala 122397206d57SZachary Turner Status NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr, 1224b9c1b51eSKate Stone MemoryRegionInfo &range_info) { 1225b9c1b51eSKate Stone // FIXME review that the final memory region returned extends to the end of 1226b9c1b51eSKate Stone // the virtual address space, 1227af245d11STodd Fiala // with no perms if it is not mapped. 1228af245d11STodd Fiala 122905097246SAdrian Prantl // Use an approach that reads memory regions from /proc/{pid}/maps. Assume 123005097246SAdrian Prantl // proc maps entries are in ascending order. 1231af245d11STodd Fiala // FIXME assert if we find differently. 1232af245d11STodd Fiala 1233b9c1b51eSKate Stone if (m_supports_mem_region == LazyBool::eLazyBoolNo) { 1234af245d11STodd Fiala // We're done. 123597206d57SZachary Turner return Status("unsupported"); 1236af245d11STodd Fiala } 1237af245d11STodd Fiala 123897206d57SZachary Turner Status error = PopulateMemoryRegionCache(); 1239b9c1b51eSKate Stone if (error.Fail()) { 1240af245d11STodd Fiala return error; 1241af245d11STodd Fiala } 1242af245d11STodd Fiala 1243af245d11STodd Fiala lldb::addr_t prev_base_address = 0; 1244af245d11STodd Fiala 1245b9c1b51eSKate Stone // FIXME start by finding the last region that is <= target address using 1246b9c1b51eSKate Stone // binary search. Data is sorted. 1247af245d11STodd Fiala // There can be a ton of regions on pthreads apps with lots of threads. 1248b9c1b51eSKate Stone for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end(); 1249b9c1b51eSKate Stone ++it) { 1250a6f5795aSTamas Berghammer MemoryRegionInfo &proc_entry_info = it->first; 1251af245d11STodd Fiala 1252af245d11STodd Fiala // Sanity check assumption that /proc/{pid}/maps entries are ascending. 1253b9c1b51eSKate Stone assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) && 1254b9c1b51eSKate Stone "descending /proc/pid/maps entries detected, unexpected"); 1255af245d11STodd Fiala prev_base_address = proc_entry_info.GetRange().GetRangeBase(); 1256b1554311SHafiz Abid Qadeer UNUSED_IF_ASSERT_DISABLED(prev_base_address); 1257af245d11STodd Fiala 1258b9c1b51eSKate Stone // If the target address comes before this entry, indicate distance to next 1259b9c1b51eSKate Stone // region. 1260b9c1b51eSKate Stone if (load_addr < proc_entry_info.GetRange().GetRangeBase()) { 1261af245d11STodd Fiala range_info.GetRange().SetRangeBase(load_addr); 1262b9c1b51eSKate Stone range_info.GetRange().SetByteSize( 1263b9c1b51eSKate Stone proc_entry_info.GetRange().GetRangeBase() - load_addr); 1264af245d11STodd Fiala range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo); 1265af245d11STodd Fiala range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo); 1266af245d11STodd Fiala range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo); 1267ad007563SHoward Hellyer range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo); 1268af245d11STodd Fiala 1269af245d11STodd Fiala return error; 1270b9c1b51eSKate Stone } else if (proc_entry_info.GetRange().Contains(load_addr)) { 1271af245d11STodd Fiala // The target address is within the memory region we're processing here. 1272af245d11STodd Fiala range_info = proc_entry_info; 1273af245d11STodd Fiala return error; 1274af245d11STodd Fiala } 1275af245d11STodd Fiala 1276b9c1b51eSKate Stone // The target memory address comes somewhere after the region we just 1277b9c1b51eSKate Stone // parsed. 1278af245d11STodd Fiala } 1279af245d11STodd Fiala 1280b9c1b51eSKate Stone // If we made it here, we didn't find an entry that contained the given 128105097246SAdrian Prantl // address. Return the load_addr as start and the amount of bytes betwwen 128205097246SAdrian Prantl // load address and the end of the memory as size. 128309839c33STamas Berghammer range_info.GetRange().SetRangeBase(load_addr); 1284ad007563SHoward Hellyer range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS); 128509839c33STamas Berghammer range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo); 128609839c33STamas Berghammer range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo); 128709839c33STamas Berghammer range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo); 1288ad007563SHoward Hellyer range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo); 1289af245d11STodd Fiala return error; 1290af245d11STodd Fiala } 1291af245d11STodd Fiala 129297206d57SZachary Turner Status NativeProcessLinux::PopulateMemoryRegionCache() { 1293a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1294a6f5795aSTamas Berghammer 1295a6f5795aSTamas Berghammer // If our cache is empty, pull the latest. There should always be at least 1296a6f5795aSTamas Berghammer // one memory region if memory region handling is supported. 1297a6f5795aSTamas Berghammer if (!m_mem_region_cache.empty()) { 1298a6321a8eSPavel Labath LLDB_LOG(log, "reusing {0} cached memory region entries", 1299a6321a8eSPavel Labath m_mem_region_cache.size()); 130097206d57SZachary Turner return Status(); 1301a6f5795aSTamas Berghammer } 1302a6f5795aSTamas Berghammer 130315930862SPavel Labath auto BufferOrError = getProcFile(GetID(), "maps"); 130415930862SPavel Labath if (!BufferOrError) { 130515930862SPavel Labath m_supports_mem_region = LazyBool::eLazyBoolNo; 130615930862SPavel Labath return BufferOrError.getError(); 130715930862SPavel Labath } 1308c8e364e8SPavel Labath Status Result; 1309c8e364e8SPavel Labath ParseLinuxMapRegions(BufferOrError.get()->getBuffer(), 1310c8e364e8SPavel Labath [&](const MemoryRegionInfo &Info, const Status &ST) { 1311c8e364e8SPavel Labath if (ST.Success()) { 1312c8e364e8SPavel Labath FileSpec file_spec(Info.GetName().GetCString()); 13138f3be7a3SJonas Devlieghere FileSystem::Instance().Resolve(file_spec); 1314c8e364e8SPavel Labath m_mem_region_cache.emplace_back(Info, file_spec); 1315c8e364e8SPavel Labath return true; 1316c8e364e8SPavel Labath } else { 1317c8e364e8SPavel Labath m_supports_mem_region = LazyBool::eLazyBoolNo; 1318c8e364e8SPavel Labath LLDB_LOG(log, "failed to parse proc maps: {0}", ST); 1319c8e364e8SPavel Labath Result = ST; 1320c8e364e8SPavel Labath return false; 1321a6f5795aSTamas Berghammer } 1322c8e364e8SPavel Labath }); 1323c8e364e8SPavel Labath if (Result.Fail()) 1324c8e364e8SPavel Labath return Result; 1325a6f5795aSTamas Berghammer 132615930862SPavel Labath if (m_mem_region_cache.empty()) { 1327a6f5795aSTamas Berghammer // No entries after attempting to read them. This shouldn't happen if 132805097246SAdrian Prantl // /proc/{pid}/maps is supported. Assume we don't support map entries via 132905097246SAdrian Prantl // procfs. 133015930862SPavel Labath m_supports_mem_region = LazyBool::eLazyBoolNo; 1331a6321a8eSPavel Labath LLDB_LOG(log, 1332a6321a8eSPavel Labath "failed to find any procfs maps entries, assuming no support " 1333a6321a8eSPavel Labath "for memory region metadata retrieval"); 133497206d57SZachary Turner return Status("not supported"); 1335a6f5795aSTamas Berghammer } 1336a6f5795aSTamas Berghammer 1337a6321a8eSPavel Labath LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps", 1338a6321a8eSPavel Labath m_mem_region_cache.size(), GetID()); 1339a6f5795aSTamas Berghammer 1340a6f5795aSTamas Berghammer // We support memory retrieval, remember that. 1341a6f5795aSTamas Berghammer m_supports_mem_region = LazyBool::eLazyBoolYes; 134297206d57SZachary Turner return Status(); 1343a6f5795aSTamas Berghammer } 1344a6f5795aSTamas Berghammer 1345b9c1b51eSKate Stone void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) { 1346a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1347a6321a8eSPavel Labath LLDB_LOG(log, "newBumpId={0}", newBumpId); 1348a6321a8eSPavel Labath LLDB_LOG(log, "clearing {0} entries from memory region cache", 1349a6321a8eSPavel Labath m_mem_region_cache.size()); 1350af245d11STodd Fiala m_mem_region_cache.clear(); 1351af245d11STodd Fiala } 1352af245d11STodd Fiala 135397206d57SZachary Turner Status NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, 1354b9c1b51eSKate Stone lldb::addr_t &addr) { 1355af245d11STodd Fiala // FIXME implementing this requires the equivalent of 135605097246SAdrian Prantl // InferiorCallPOSIX::InferiorCallMmap, which depends on functional ThreadPlans 135705097246SAdrian Prantl // working with Native*Protocol. 1358af245d11STodd Fiala #if 1 135997206d57SZachary Turner return Status("not implemented yet"); 1360af245d11STodd Fiala #else 1361af245d11STodd Fiala addr = LLDB_INVALID_ADDRESS; 1362af245d11STodd Fiala 1363af245d11STodd Fiala unsigned prot = 0; 1364af245d11STodd Fiala if (permissions & lldb::ePermissionsReadable) 1365af245d11STodd Fiala prot |= eMmapProtRead; 1366af245d11STodd Fiala if (permissions & lldb::ePermissionsWritable) 1367af245d11STodd Fiala prot |= eMmapProtWrite; 1368af245d11STodd Fiala if (permissions & lldb::ePermissionsExecutable) 1369af245d11STodd Fiala prot |= eMmapProtExec; 1370af245d11STodd Fiala 1371af245d11STodd Fiala // TODO implement this directly in NativeProcessLinux 137205097246SAdrian Prantl // (and lift to NativeProcessPOSIX if/when that class is refactored out). 1373af245d11STodd Fiala if (InferiorCallMmap(this, addr, 0, size, prot, 1374af245d11STodd Fiala eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) { 1375af245d11STodd Fiala m_addr_to_mmap_size[addr] = size; 137697206d57SZachary Turner return Status(); 1377af245d11STodd Fiala } else { 1378af245d11STodd Fiala addr = LLDB_INVALID_ADDRESS; 137997206d57SZachary Turner return Status("unable to allocate %" PRIu64 1380b9c1b51eSKate Stone " bytes of memory with permissions %s", 1381b9c1b51eSKate Stone size, GetPermissionsAsCString(permissions)); 1382af245d11STodd Fiala } 1383af245d11STodd Fiala #endif 1384af245d11STodd Fiala } 1385af245d11STodd Fiala 138697206d57SZachary Turner Status NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) { 1387af245d11STodd Fiala // FIXME see comments in AllocateMemory - required lower-level 1388af245d11STodd Fiala // bits not in place yet (ThreadPlans) 138997206d57SZachary Turner return Status("not implemented"); 1390af245d11STodd Fiala } 1391af245d11STodd Fiala 1392b9c1b51eSKate Stone lldb::addr_t NativeProcessLinux::GetSharedLibraryInfoAddress() { 1393af245d11STodd Fiala // punt on this for now 1394af245d11STodd Fiala return LLDB_INVALID_ADDRESS; 1395af245d11STodd Fiala } 1396af245d11STodd Fiala 1397b9c1b51eSKate Stone size_t NativeProcessLinux::UpdateThreads() { 139805097246SAdrian Prantl // The NativeProcessLinux monitoring threads are always up to date with 139905097246SAdrian Prantl // respect to thread state and they keep the thread list populated properly. 140005097246SAdrian Prantl // All this method needs to do is return the thread count. 1401af245d11STodd Fiala return m_threads.size(); 1402af245d11STodd Fiala } 1403af245d11STodd Fiala 140497206d57SZachary Turner Status NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size, 1405b9c1b51eSKate Stone bool hardware) { 1406af245d11STodd Fiala if (hardware) 1407d5ffbad2SOmair Javaid return SetHardwareBreakpoint(addr, size); 1408af245d11STodd Fiala else 1409af245d11STodd Fiala return SetSoftwareBreakpoint(addr, size); 1410af245d11STodd Fiala } 1411af245d11STodd Fiala 141297206d57SZachary Turner Status NativeProcessLinux::RemoveBreakpoint(lldb::addr_t addr, bool hardware) { 1413d5ffbad2SOmair Javaid if (hardware) 1414d5ffbad2SOmair Javaid return RemoveHardwareBreakpoint(addr); 1415d5ffbad2SOmair Javaid else 1416d5ffbad2SOmair Javaid return NativeProcessProtocol::RemoveBreakpoint(addr); 1417d5ffbad2SOmair Javaid } 1418d5ffbad2SOmair Javaid 1419f8b825f6SPavel Labath llvm::Expected<llvm::ArrayRef<uint8_t>> 1420f8b825f6SPavel Labath NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(size_t size_hint) { 1421be379e15STamas Berghammer // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the 1422be379e15STamas Berghammer // linux kernel does otherwise. 1423f8b825f6SPavel Labath static const uint8_t g_arm_opcode[] = {0xf0, 0x01, 0xf0, 0xe7}; 1424f8b825f6SPavel Labath static const uint8_t g_thumb_opcode[] = {0x01, 0xde}; 142512286a27SPavel Labath 1426f8b825f6SPavel Labath switch (GetArchitecture().GetMachine()) { 142712286a27SPavel Labath case llvm::Triple::arm: 1428f8b825f6SPavel Labath switch (size_hint) { 142963c8be95STamas Berghammer case 2: 14304f545074SPavel Labath return llvm::makeArrayRef(g_thumb_opcode); 143163c8be95STamas Berghammer case 4: 14324f545074SPavel Labath return llvm::makeArrayRef(g_arm_opcode); 143363c8be95STamas Berghammer default: 1434f8b825f6SPavel Labath return llvm::createStringError(llvm::inconvertibleErrorCode(), 1435f8b825f6SPavel Labath "Unrecognised trap opcode size hint!"); 143663c8be95STamas Berghammer } 1437af245d11STodd Fiala default: 1438f8b825f6SPavel Labath return NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_hint); 1439af245d11STodd Fiala } 1440af245d11STodd Fiala } 1441af245d11STodd Fiala 144297206d57SZachary Turner Status NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size, 1443b9c1b51eSKate Stone size_t &bytes_read) { 1444df7c6995SPavel Labath if (ProcessVmReadvSupported()) { 1445b9c1b51eSKate Stone // The process_vm_readv path is about 50 times faster than ptrace api. We 144605097246SAdrian Prantl // want to use this syscall if it is supported. 1447df7c6995SPavel Labath 1448df7c6995SPavel Labath const ::pid_t pid = GetID(); 1449df7c6995SPavel Labath 1450df7c6995SPavel Labath struct iovec local_iov, remote_iov; 1451df7c6995SPavel Labath local_iov.iov_base = buf; 1452df7c6995SPavel Labath local_iov.iov_len = size; 1453df7c6995SPavel Labath remote_iov.iov_base = reinterpret_cast<void *>(addr); 1454df7c6995SPavel Labath remote_iov.iov_len = size; 1455df7c6995SPavel Labath 1456df7c6995SPavel Labath bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0); 1457df7c6995SPavel Labath const bool success = bytes_read == size; 1458df7c6995SPavel Labath 1459a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1460a6321a8eSPavel Labath LLDB_LOG(log, 1461a6321a8eSPavel Labath "using process_vm_readv to read {0} bytes from inferior " 1462a6321a8eSPavel Labath "address {1:x}: {2}", 146310c41f37SPavel Labath size, addr, success ? "Success" : llvm::sys::StrError(errno)); 1464df7c6995SPavel Labath 1465df7c6995SPavel Labath if (success) 146697206d57SZachary Turner return Status(); 1467a6321a8eSPavel Labath // else the call failed for some reason, let's retry the read using ptrace 1468b9c1b51eSKate Stone // api. 1469df7c6995SPavel Labath } 1470df7c6995SPavel Labath 147119cbe96aSPavel Labath unsigned char *dst = static_cast<unsigned char *>(buf); 147219cbe96aSPavel Labath size_t remainder; 147319cbe96aSPavel Labath long data; 147419cbe96aSPavel Labath 1475a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY)); 1476a6321a8eSPavel Labath LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size); 147719cbe96aSPavel Labath 1478b9c1b51eSKate Stone for (bytes_read = 0; bytes_read < size; bytes_read += remainder) { 147997206d57SZachary Turner Status error = NativeProcessLinux::PtraceWrapper( 1480b9c1b51eSKate Stone PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data); 1481a6321a8eSPavel Labath if (error.Fail()) 148219cbe96aSPavel Labath return error; 148319cbe96aSPavel Labath 148419cbe96aSPavel Labath remainder = size - bytes_read; 148519cbe96aSPavel Labath remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder; 148619cbe96aSPavel Labath 148719cbe96aSPavel Labath // Copy the data into our buffer 1488f6ef187bSMohit K. Bhakkad memcpy(dst, &data, remainder); 148919cbe96aSPavel Labath 1490a6321a8eSPavel Labath LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data); 149119cbe96aSPavel Labath addr += k_ptrace_word_size; 149219cbe96aSPavel Labath dst += k_ptrace_word_size; 149319cbe96aSPavel Labath } 149497206d57SZachary Turner return Status(); 1495af245d11STodd Fiala } 1496af245d11STodd Fiala 149797206d57SZachary Turner Status NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, 1498b9c1b51eSKate Stone size_t size, size_t &bytes_written) { 149919cbe96aSPavel Labath const unsigned char *src = static_cast<const unsigned char *>(buf); 150019cbe96aSPavel Labath size_t remainder; 150197206d57SZachary Turner Status error; 150219cbe96aSPavel Labath 1503a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY)); 1504a6321a8eSPavel Labath LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size); 150519cbe96aSPavel Labath 1506b9c1b51eSKate Stone for (bytes_written = 0; bytes_written < size; bytes_written += remainder) { 150719cbe96aSPavel Labath remainder = size - bytes_written; 150819cbe96aSPavel Labath remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder; 150919cbe96aSPavel Labath 1510b9c1b51eSKate Stone if (remainder == k_ptrace_word_size) { 151119cbe96aSPavel Labath unsigned long data = 0; 1512f6ef187bSMohit K. Bhakkad memcpy(&data, src, k_ptrace_word_size); 151319cbe96aSPavel Labath 1514a6321a8eSPavel Labath LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data); 1515b9c1b51eSKate Stone error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(), 1516b9c1b51eSKate Stone (void *)addr, (void *)data); 1517a6321a8eSPavel Labath if (error.Fail()) 151819cbe96aSPavel Labath return error; 1519b9c1b51eSKate Stone } else { 152019cbe96aSPavel Labath unsigned char buff[8]; 152119cbe96aSPavel Labath size_t bytes_read; 152219cbe96aSPavel Labath error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read); 1523a6321a8eSPavel Labath if (error.Fail()) 152419cbe96aSPavel Labath return error; 152519cbe96aSPavel Labath 152619cbe96aSPavel Labath memcpy(buff, src, remainder); 152719cbe96aSPavel Labath 152819cbe96aSPavel Labath size_t bytes_written_rec; 152919cbe96aSPavel Labath error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec); 1530a6321a8eSPavel Labath if (error.Fail()) 153119cbe96aSPavel Labath return error; 153219cbe96aSPavel Labath 1533a6321a8eSPavel Labath LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src, 1534b9c1b51eSKate Stone *(unsigned long *)buff); 153519cbe96aSPavel Labath } 153619cbe96aSPavel Labath 153719cbe96aSPavel Labath addr += k_ptrace_word_size; 153819cbe96aSPavel Labath src += k_ptrace_word_size; 153919cbe96aSPavel Labath } 154019cbe96aSPavel Labath return error; 1541af245d11STodd Fiala } 1542af245d11STodd Fiala 154397206d57SZachary Turner Status NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) { 154419cbe96aSPavel Labath return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo); 1545af245d11STodd Fiala } 1546af245d11STodd Fiala 154797206d57SZachary Turner Status NativeProcessLinux::GetEventMessage(lldb::tid_t tid, 1548b9c1b51eSKate Stone unsigned long *message) { 154919cbe96aSPavel Labath return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message); 1550af245d11STodd Fiala } 1551af245d11STodd Fiala 155297206d57SZachary Turner Status NativeProcessLinux::Detach(lldb::tid_t tid) { 155397ccc294SChaoren Lin if (tid == LLDB_INVALID_THREAD_ID) 155497206d57SZachary Turner return Status(); 155597ccc294SChaoren Lin 155619cbe96aSPavel Labath return PtraceWrapper(PTRACE_DETACH, tid); 1557af245d11STodd Fiala } 1558af245d11STodd Fiala 1559b9c1b51eSKate Stone bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) { 1560a5be48b3SPavel Labath for (const auto &thread : m_threads) { 1561a5be48b3SPavel Labath assert(thread && "thread list should not contain NULL threads"); 1562a5be48b3SPavel Labath if (thread->GetID() == thread_id) { 1563af245d11STodd Fiala // We have this thread. 1564af245d11STodd Fiala return true; 1565af245d11STodd Fiala } 1566af245d11STodd Fiala } 1567af245d11STodd Fiala 1568af245d11STodd Fiala // We don't have this thread. 1569af245d11STodd Fiala return false; 1570af245d11STodd Fiala } 1571af245d11STodd Fiala 1572b9c1b51eSKate Stone bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) { 1573a6321a8eSPavel Labath Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD); 1574a6321a8eSPavel Labath LLDB_LOG(log, "tid: {0})", thread_id); 15751dbc6c9cSPavel Labath 15761dbc6c9cSPavel Labath bool found = false; 1577b9c1b51eSKate Stone for (auto it = m_threads.begin(); it != m_threads.end(); ++it) { 1578b9c1b51eSKate Stone if (*it && ((*it)->GetID() == thread_id)) { 1579af245d11STodd Fiala m_threads.erase(it); 15801dbc6c9cSPavel Labath found = true; 15811dbc6c9cSPavel Labath break; 1582af245d11STodd Fiala } 1583af245d11STodd Fiala } 1584af245d11STodd Fiala 158599e37695SRavitheja Addepally if (found) 158699e37695SRavitheja Addepally StopTracingForThread(thread_id); 15879eb1ecb9SPavel Labath SignalIfAllThreadsStopped(); 15881dbc6c9cSPavel Labath return found; 1589af245d11STodd Fiala } 1590af245d11STodd Fiala 1591a5be48b3SPavel Labath NativeThreadLinux &NativeProcessLinux::AddThread(lldb::tid_t thread_id) { 1592a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD)); 1593a6321a8eSPavel Labath LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id); 1594af245d11STodd Fiala 1595b9c1b51eSKate Stone assert(!HasThreadNoLock(thread_id) && 1596b9c1b51eSKate Stone "attempted to add a thread by id that already exists"); 1597af245d11STodd Fiala 1598af245d11STodd Fiala // If this is the first thread, save it as the current thread 1599af245d11STodd Fiala if (m_threads.empty()) 1600af245d11STodd Fiala SetCurrentThreadID(thread_id); 1601af245d11STodd Fiala 1602a5be48b3SPavel Labath m_threads.push_back(llvm::make_unique<NativeThreadLinux>(*this, thread_id)); 160399e37695SRavitheja Addepally 160499e37695SRavitheja Addepally if (m_pt_proces_trace_id != LLDB_INVALID_UID) { 160599e37695SRavitheja Addepally auto traceMonitor = ProcessorTraceMonitor::Create( 160699e37695SRavitheja Addepally GetID(), thread_id, m_pt_process_trace_config, true); 160799e37695SRavitheja Addepally if (traceMonitor) { 160899e37695SRavitheja Addepally m_pt_traced_thread_group.insert(thread_id); 160999e37695SRavitheja Addepally m_processor_trace_monitor.insert( 161099e37695SRavitheja Addepally std::make_pair(thread_id, std::move(*traceMonitor))); 161199e37695SRavitheja Addepally } else { 161299e37695SRavitheja Addepally LLDB_LOG(log, "failed to start trace on thread {0}", thread_id); 161399e37695SRavitheja Addepally Status error(traceMonitor.takeError()); 161499e37695SRavitheja Addepally LLDB_LOG(log, "error {0}", error); 161599e37695SRavitheja Addepally } 161699e37695SRavitheja Addepally } 161799e37695SRavitheja Addepally 1618a5be48b3SPavel Labath return static_cast<NativeThreadLinux &>(*m_threads.back()); 1619af245d11STodd Fiala } 1620af245d11STodd Fiala 162197206d57SZachary Turner Status NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path, 1622b9c1b51eSKate Stone FileSpec &file_spec) { 162397206d57SZachary Turner Status error = PopulateMemoryRegionCache(); 1624a6f5795aSTamas Berghammer if (error.Fail()) 1625a6f5795aSTamas Berghammer return error; 1626a6f5795aSTamas Berghammer 16278f3be7a3SJonas Devlieghere FileSpec module_file_spec(module_path); 16288f3be7a3SJonas Devlieghere FileSystem::Instance().Resolve(module_file_spec); 16297cb18bf5STamas Berghammer 16307cb18bf5STamas Berghammer file_spec.Clear(); 1631a6f5795aSTamas Berghammer for (const auto &it : m_mem_region_cache) { 1632a6f5795aSTamas Berghammer if (it.second.GetFilename() == module_file_spec.GetFilename()) { 1633a6f5795aSTamas Berghammer file_spec = it.second; 163497206d57SZachary Turner return Status(); 1635a6f5795aSTamas Berghammer } 1636a6f5795aSTamas Berghammer } 163797206d57SZachary Turner return Status("Module file (%s) not found in /proc/%" PRIu64 "/maps file!", 16387cb18bf5STamas Berghammer module_file_spec.GetFilename().AsCString(), GetID()); 16397cb18bf5STamas Berghammer } 1640c076559aSPavel Labath 164197206d57SZachary Turner Status NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name, 1642b9c1b51eSKate Stone lldb::addr_t &load_addr) { 1643783bfc8cSTamas Berghammer load_addr = LLDB_INVALID_ADDRESS; 164497206d57SZachary Turner Status error = PopulateMemoryRegionCache(); 1645a6f5795aSTamas Berghammer if (error.Fail()) 1646783bfc8cSTamas Berghammer return error; 1647a6f5795aSTamas Berghammer 16488f3be7a3SJonas Devlieghere FileSpec file(file_name); 1649a6f5795aSTamas Berghammer for (const auto &it : m_mem_region_cache) { 1650a6f5795aSTamas Berghammer if (it.second == file) { 1651a6f5795aSTamas Berghammer load_addr = it.first.GetRange().GetRangeBase(); 165297206d57SZachary Turner return Status(); 1653a6f5795aSTamas Berghammer } 1654a6f5795aSTamas Berghammer } 165597206d57SZachary Turner return Status("No load address found for specified file."); 1656783bfc8cSTamas Berghammer } 1657783bfc8cSTamas Berghammer 1658a5be48b3SPavel Labath NativeThreadLinux *NativeProcessLinux::GetThreadByID(lldb::tid_t tid) { 1659a5be48b3SPavel Labath return static_cast<NativeThreadLinux *>( 1660b9c1b51eSKate Stone NativeProcessProtocol::GetThreadByID(tid)); 1661f9077782SPavel Labath } 1662f9077782SPavel Labath 166397206d57SZachary Turner Status NativeProcessLinux::ResumeThread(NativeThreadLinux &thread, 1664b9c1b51eSKate Stone lldb::StateType state, int signo) { 1665a6321a8eSPavel Labath Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD); 1666a6321a8eSPavel Labath LLDB_LOG(log, "tid: {0}", thread.GetID()); 1667c076559aSPavel Labath 166805097246SAdrian Prantl // Before we do the resume below, first check if we have a pending stop 166905097246SAdrian Prantl // notification that is currently waiting for all threads to stop. This is 167005097246SAdrian Prantl // potentially a buggy situation since we're ostensibly waiting for threads 167105097246SAdrian Prantl // to stop before we send out the pending notification, and here we are 167205097246SAdrian Prantl // resuming one before we send out the pending stop notification. 1673a6321a8eSPavel Labath if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) { 1674a6321a8eSPavel Labath LLDB_LOG(log, 1675a6321a8eSPavel Labath "about to resume tid {0} per explicit request but we have a " 1676a6321a8eSPavel Labath "pending stop notification (tid {1}) that is actively " 1677a6321a8eSPavel Labath "waiting for this thread to stop. Valid sequence of events?", 1678a6321a8eSPavel Labath thread.GetID(), m_pending_notification_tid); 1679c076559aSPavel Labath } 1680c076559aSPavel Labath 168105097246SAdrian Prantl // Request a resume. We expect this to be synchronous and the system to 168205097246SAdrian Prantl // reflect it is running after this completes. 1683b9c1b51eSKate Stone switch (state) { 1684b9c1b51eSKate Stone case eStateRunning: { 1685605b51b8SPavel Labath const auto resume_result = thread.Resume(signo); 16860e1d729bSPavel Labath if (resume_result.Success()) 16870e1d729bSPavel Labath SetState(eStateRunning, true); 16880e1d729bSPavel Labath return resume_result; 1689c076559aSPavel Labath } 1690b9c1b51eSKate Stone case eStateStepping: { 1691605b51b8SPavel Labath const auto step_result = thread.SingleStep(signo); 16920e1d729bSPavel Labath if (step_result.Success()) 16930e1d729bSPavel Labath SetState(eStateRunning, true); 16940e1d729bSPavel Labath return step_result; 16950e1d729bSPavel Labath } 16960e1d729bSPavel Labath default: 16978198db30SPavel Labath LLDB_LOG(log, "Unhandled state {0}.", state); 16980e1d729bSPavel Labath llvm_unreachable("Unhandled state for resume"); 16990e1d729bSPavel Labath } 1700c076559aSPavel Labath } 1701c076559aSPavel Labath 1702c076559aSPavel Labath //===----------------------------------------------------------------------===// 1703c076559aSPavel Labath 1704b9c1b51eSKate Stone void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) { 1705a6321a8eSPavel Labath Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD); 1706a6321a8eSPavel Labath LLDB_LOG(log, "about to process event: (triggering_tid: {0})", 1707a6321a8eSPavel Labath triggering_tid); 1708c076559aSPavel Labath 17090e1d729bSPavel Labath m_pending_notification_tid = triggering_tid; 17100e1d729bSPavel Labath 171105097246SAdrian Prantl // Request a stop for all the thread stops that need to be stopped and are 171205097246SAdrian Prantl // not already known to be stopped. 1713a5be48b3SPavel Labath for (const auto &thread : m_threads) { 1714a5be48b3SPavel Labath if (StateIsRunningState(thread->GetState())) 1715a5be48b3SPavel Labath static_cast<NativeThreadLinux *>(thread.get())->RequestStop(); 17160e1d729bSPavel Labath } 17170e1d729bSPavel Labath 17180e1d729bSPavel Labath SignalIfAllThreadsStopped(); 1719a6321a8eSPavel Labath LLDB_LOG(log, "event processing done"); 1720c076559aSPavel Labath } 1721c076559aSPavel Labath 1722b9c1b51eSKate Stone void NativeProcessLinux::SignalIfAllThreadsStopped() { 17230e1d729bSPavel Labath if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID) 17240e1d729bSPavel Labath return; // No pending notification. Nothing to do. 17250e1d729bSPavel Labath 1726b9c1b51eSKate Stone for (const auto &thread_sp : m_threads) { 17270e1d729bSPavel Labath if (StateIsRunningState(thread_sp->GetState())) 17280e1d729bSPavel Labath return; // Some threads are still running. Don't signal yet. 17290e1d729bSPavel Labath } 17300e1d729bSPavel Labath 17310e1d729bSPavel Labath // We have a pending notification and all threads have stopped. 1732b9c1b51eSKate Stone Log *log( 1733b9c1b51eSKate Stone GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS)); 17349eb1ecb9SPavel Labath 1735b9c1b51eSKate Stone // Clear any temporary breakpoints we used to implement software single 1736b9c1b51eSKate Stone // stepping. 1737b9c1b51eSKate Stone for (const auto &thread_info : m_threads_stepping_with_breakpoint) { 173897206d57SZachary Turner Status error = RemoveBreakpoint(thread_info.second); 17399eb1ecb9SPavel Labath if (error.Fail()) 1740a6321a8eSPavel Labath LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}", 1741a6321a8eSPavel Labath thread_info.first, error); 17429eb1ecb9SPavel Labath } 17439eb1ecb9SPavel Labath m_threads_stepping_with_breakpoint.clear(); 17449eb1ecb9SPavel Labath 17459eb1ecb9SPavel Labath // Notify the delegate about the stop 17460e1d729bSPavel Labath SetCurrentThreadID(m_pending_notification_tid); 1747ed89c7feSPavel Labath SetState(StateType::eStateStopped, true); 17480e1d729bSPavel Labath m_pending_notification_tid = LLDB_INVALID_THREAD_ID; 1749c076559aSPavel Labath } 1750c076559aSPavel Labath 1751b9c1b51eSKate Stone void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) { 1752a6321a8eSPavel Labath Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD); 1753a6321a8eSPavel Labath LLDB_LOG(log, "tid: {0}", thread.GetID()); 17541dbc6c9cSPavel Labath 1755b9c1b51eSKate Stone if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID && 1756b9c1b51eSKate Stone StateIsRunningState(thread.GetState())) { 1757b9c1b51eSKate Stone // We will need to wait for this new thread to stop as well before firing 175805097246SAdrian Prantl // the notification. 1759f9077782SPavel Labath thread.RequestStop(); 1760c076559aSPavel Labath } 1761c076559aSPavel Labath } 1762068f8a7eSTamas Berghammer 1763b9c1b51eSKate Stone void NativeProcessLinux::SigchldHandler() { 1764a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 176519cbe96aSPavel Labath // Process all pending waitpid notifications. 1766b9c1b51eSKate Stone while (true) { 176719cbe96aSPavel Labath int status = -1; 1768c1a6b128SPavel Labath ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, -1, &status, 1769c1a6b128SPavel Labath __WALL | __WNOTHREAD | WNOHANG); 177019cbe96aSPavel Labath 177119cbe96aSPavel Labath if (wait_pid == 0) 177219cbe96aSPavel Labath break; // We are done. 177319cbe96aSPavel Labath 1774b9c1b51eSKate Stone if (wait_pid == -1) { 177597206d57SZachary Turner Status error(errno, eErrorTypePOSIX); 1776a6321a8eSPavel Labath LLDB_LOG(log, "waitpid (-1, &status, _) failed: {0}", error); 177719cbe96aSPavel Labath break; 177819cbe96aSPavel Labath } 177919cbe96aSPavel Labath 17803508fc8cSPavel Labath WaitStatus wait_status = WaitStatus::Decode(status); 17813508fc8cSPavel Labath bool exited = wait_status.type == WaitStatus::Exit || 17823508fc8cSPavel Labath (wait_status.type == WaitStatus::Signal && 17833508fc8cSPavel Labath wait_pid == static_cast<::pid_t>(GetID())); 178419cbe96aSPavel Labath 17853508fc8cSPavel Labath LLDB_LOG( 17863508fc8cSPavel Labath log, 17873508fc8cSPavel Labath "waitpid (-1, &status, _) => pid = {0}, status = {1}, exited = {2}", 17883508fc8cSPavel Labath wait_pid, wait_status, exited); 178919cbe96aSPavel Labath 17903508fc8cSPavel Labath MonitorCallback(wait_pid, exited, wait_status); 179119cbe96aSPavel Labath } 1792068f8a7eSTamas Berghammer } 1793068f8a7eSTamas Berghammer 179405097246SAdrian Prantl // Wrapper for ptrace to catch errors and log calls. Note that ptrace sets 179505097246SAdrian Prantl // errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*) 179697206d57SZachary Turner Status NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr, 1797b9c1b51eSKate Stone void *data, size_t data_size, 1798b9c1b51eSKate Stone long *result) { 179997206d57SZachary Turner Status error; 18004a9babb2SPavel Labath long int ret; 1801068f8a7eSTamas Berghammer 1802068f8a7eSTamas Berghammer Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 1803068f8a7eSTamas Berghammer 1804068f8a7eSTamas Berghammer PtraceDisplayBytes(req, data, data_size); 1805068f8a7eSTamas Berghammer 1806068f8a7eSTamas Berghammer errno = 0; 1807068f8a7eSTamas Berghammer if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET) 1808b9c1b51eSKate Stone ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid), 1809b9c1b51eSKate Stone *(unsigned int *)addr, data); 1810068f8a7eSTamas Berghammer else 1811b9c1b51eSKate Stone ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid), 1812b9c1b51eSKate Stone addr, data); 1813068f8a7eSTamas Berghammer 18144a9babb2SPavel Labath if (ret == -1) 1815068f8a7eSTamas Berghammer error.SetErrorToErrno(); 1816068f8a7eSTamas Berghammer 18174a9babb2SPavel Labath if (result) 18184a9babb2SPavel Labath *result = ret; 18194a9babb2SPavel Labath 182028096200SPavel Labath LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data, 182128096200SPavel Labath data_size, ret); 1822068f8a7eSTamas Berghammer 1823068f8a7eSTamas Berghammer PtraceDisplayBytes(req, data, data_size); 1824068f8a7eSTamas Berghammer 1825a6321a8eSPavel Labath if (error.Fail()) 1826a6321a8eSPavel Labath LLDB_LOG(log, "ptrace() failed: {0}", error); 1827068f8a7eSTamas Berghammer 18284a9babb2SPavel Labath return error; 1829068f8a7eSTamas Berghammer } 183099e37695SRavitheja Addepally 183199e37695SRavitheja Addepally llvm::Expected<ProcessorTraceMonitor &> 183299e37695SRavitheja Addepally NativeProcessLinux::LookupProcessorTraceInstance(lldb::user_id_t traceid, 183399e37695SRavitheja Addepally lldb::tid_t thread) { 183499e37695SRavitheja Addepally Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 183599e37695SRavitheja Addepally if (thread == LLDB_INVALID_THREAD_ID && traceid == m_pt_proces_trace_id) { 183699e37695SRavitheja Addepally LLDB_LOG(log, "thread not specified: {0}", traceid); 183799e37695SRavitheja Addepally return Status("tracing not active thread not specified").ToError(); 183899e37695SRavitheja Addepally } 183999e37695SRavitheja Addepally 184099e37695SRavitheja Addepally for (auto& iter : m_processor_trace_monitor) { 184199e37695SRavitheja Addepally if (traceid == iter.second->GetTraceID() && 184299e37695SRavitheja Addepally (thread == iter.first || thread == LLDB_INVALID_THREAD_ID)) 184399e37695SRavitheja Addepally return *(iter.second); 184499e37695SRavitheja Addepally } 184599e37695SRavitheja Addepally 184699e37695SRavitheja Addepally LLDB_LOG(log, "traceid not being traced: {0}", traceid); 184799e37695SRavitheja Addepally return Status("tracing not active for this thread").ToError(); 184899e37695SRavitheja Addepally } 184999e37695SRavitheja Addepally 185099e37695SRavitheja Addepally Status NativeProcessLinux::GetMetaData(lldb::user_id_t traceid, 185199e37695SRavitheja Addepally lldb::tid_t thread, 185299e37695SRavitheja Addepally llvm::MutableArrayRef<uint8_t> &buffer, 185399e37695SRavitheja Addepally size_t offset) { 185499e37695SRavitheja Addepally TraceOptions trace_options; 185599e37695SRavitheja Addepally Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 185699e37695SRavitheja Addepally Status error; 185799e37695SRavitheja Addepally 185899e37695SRavitheja Addepally LLDB_LOG(log, "traceid {0}", traceid); 185999e37695SRavitheja Addepally 186099e37695SRavitheja Addepally auto perf_monitor = LookupProcessorTraceInstance(traceid, thread); 186199e37695SRavitheja Addepally if (!perf_monitor) { 186299e37695SRavitheja Addepally LLDB_LOG(log, "traceid not being traced: {0}", traceid); 186399e37695SRavitheja Addepally buffer = buffer.slice(buffer.size()); 186499e37695SRavitheja Addepally error = perf_monitor.takeError(); 186599e37695SRavitheja Addepally return error; 186699e37695SRavitheja Addepally } 186799e37695SRavitheja Addepally return (*perf_monitor).ReadPerfTraceData(buffer, offset); 186899e37695SRavitheja Addepally } 186999e37695SRavitheja Addepally 187099e37695SRavitheja Addepally Status NativeProcessLinux::GetData(lldb::user_id_t traceid, lldb::tid_t thread, 187199e37695SRavitheja Addepally llvm::MutableArrayRef<uint8_t> &buffer, 187299e37695SRavitheja Addepally size_t offset) { 187399e37695SRavitheja Addepally Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 187499e37695SRavitheja Addepally Status error; 187599e37695SRavitheja Addepally 187699e37695SRavitheja Addepally LLDB_LOG(log, "traceid {0}", traceid); 187799e37695SRavitheja Addepally 187899e37695SRavitheja Addepally auto perf_monitor = LookupProcessorTraceInstance(traceid, thread); 187999e37695SRavitheja Addepally if (!perf_monitor) { 188099e37695SRavitheja Addepally LLDB_LOG(log, "traceid not being traced: {0}", traceid); 188199e37695SRavitheja Addepally buffer = buffer.slice(buffer.size()); 188299e37695SRavitheja Addepally error = perf_monitor.takeError(); 188399e37695SRavitheja Addepally return error; 188499e37695SRavitheja Addepally } 188599e37695SRavitheja Addepally return (*perf_monitor).ReadPerfTraceAux(buffer, offset); 188699e37695SRavitheja Addepally } 188799e37695SRavitheja Addepally 188899e37695SRavitheja Addepally Status NativeProcessLinux::GetTraceConfig(lldb::user_id_t traceid, 188999e37695SRavitheja Addepally TraceOptions &config) { 189099e37695SRavitheja Addepally Status error; 189199e37695SRavitheja Addepally if (config.getThreadID() == LLDB_INVALID_THREAD_ID && 189299e37695SRavitheja Addepally m_pt_proces_trace_id == traceid) { 189399e37695SRavitheja Addepally if (m_pt_proces_trace_id == LLDB_INVALID_UID) { 189499e37695SRavitheja Addepally error.SetErrorString("tracing not active for this process"); 189599e37695SRavitheja Addepally return error; 189699e37695SRavitheja Addepally } 189799e37695SRavitheja Addepally config = m_pt_process_trace_config; 189899e37695SRavitheja Addepally } else { 189999e37695SRavitheja Addepally auto perf_monitor = 190099e37695SRavitheja Addepally LookupProcessorTraceInstance(traceid, config.getThreadID()); 190199e37695SRavitheja Addepally if (!perf_monitor) { 190299e37695SRavitheja Addepally error = perf_monitor.takeError(); 190399e37695SRavitheja Addepally return error; 190499e37695SRavitheja Addepally } 190599e37695SRavitheja Addepally error = (*perf_monitor).GetTraceConfig(config); 190699e37695SRavitheja Addepally } 190799e37695SRavitheja Addepally return error; 190899e37695SRavitheja Addepally } 190999e37695SRavitheja Addepally 191099e37695SRavitheja Addepally lldb::user_id_t 191199e37695SRavitheja Addepally NativeProcessLinux::StartTraceGroup(const TraceOptions &config, 191299e37695SRavitheja Addepally Status &error) { 191399e37695SRavitheja Addepally 191499e37695SRavitheja Addepally Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 191599e37695SRavitheja Addepally if (config.getType() != TraceType::eTraceTypeProcessorTrace) 191699e37695SRavitheja Addepally return LLDB_INVALID_UID; 191799e37695SRavitheja Addepally 191899e37695SRavitheja Addepally if (m_pt_proces_trace_id != LLDB_INVALID_UID) { 191999e37695SRavitheja Addepally error.SetErrorString("tracing already active on this process"); 192099e37695SRavitheja Addepally return m_pt_proces_trace_id; 192199e37695SRavitheja Addepally } 192299e37695SRavitheja Addepally 192399e37695SRavitheja Addepally for (const auto &thread_sp : m_threads) { 192499e37695SRavitheja Addepally if (auto traceInstance = ProcessorTraceMonitor::Create( 192599e37695SRavitheja Addepally GetID(), thread_sp->GetID(), config, true)) { 192699e37695SRavitheja Addepally m_pt_traced_thread_group.insert(thread_sp->GetID()); 192799e37695SRavitheja Addepally m_processor_trace_monitor.insert( 192899e37695SRavitheja Addepally std::make_pair(thread_sp->GetID(), std::move(*traceInstance))); 192999e37695SRavitheja Addepally } 193099e37695SRavitheja Addepally } 193199e37695SRavitheja Addepally 193299e37695SRavitheja Addepally m_pt_process_trace_config = config; 193399e37695SRavitheja Addepally error = ProcessorTraceMonitor::GetCPUType(m_pt_process_trace_config); 193499e37695SRavitheja Addepally 193599e37695SRavitheja Addepally // Trace on Complete process will have traceid of 0 193699e37695SRavitheja Addepally m_pt_proces_trace_id = 0; 193799e37695SRavitheja Addepally 193899e37695SRavitheja Addepally LLDB_LOG(log, "Process Trace ID {0}", m_pt_proces_trace_id); 193999e37695SRavitheja Addepally return m_pt_proces_trace_id; 194099e37695SRavitheja Addepally } 194199e37695SRavitheja Addepally 194299e37695SRavitheja Addepally lldb::user_id_t NativeProcessLinux::StartTrace(const TraceOptions &config, 194399e37695SRavitheja Addepally Status &error) { 194499e37695SRavitheja Addepally if (config.getType() != TraceType::eTraceTypeProcessorTrace) 194599e37695SRavitheja Addepally return NativeProcessProtocol::StartTrace(config, error); 194699e37695SRavitheja Addepally 194799e37695SRavitheja Addepally Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 194899e37695SRavitheja Addepally 194999e37695SRavitheja Addepally lldb::tid_t threadid = config.getThreadID(); 195099e37695SRavitheja Addepally 195199e37695SRavitheja Addepally if (threadid == LLDB_INVALID_THREAD_ID) 195299e37695SRavitheja Addepally return StartTraceGroup(config, error); 195399e37695SRavitheja Addepally 195499e37695SRavitheja Addepally auto thread_sp = GetThreadByID(threadid); 195599e37695SRavitheja Addepally if (!thread_sp) { 195699e37695SRavitheja Addepally // Thread not tracked by lldb so don't trace. 195799e37695SRavitheja Addepally error.SetErrorString("invalid thread id"); 195899e37695SRavitheja Addepally return LLDB_INVALID_UID; 195999e37695SRavitheja Addepally } 196099e37695SRavitheja Addepally 196199e37695SRavitheja Addepally const auto &iter = m_processor_trace_monitor.find(threadid); 196299e37695SRavitheja Addepally if (iter != m_processor_trace_monitor.end()) { 196399e37695SRavitheja Addepally LLDB_LOG(log, "Thread already being traced"); 196499e37695SRavitheja Addepally error.SetErrorString("tracing already active on this thread"); 196599e37695SRavitheja Addepally return LLDB_INVALID_UID; 196699e37695SRavitheja Addepally } 196799e37695SRavitheja Addepally 196899e37695SRavitheja Addepally auto traceMonitor = 196999e37695SRavitheja Addepally ProcessorTraceMonitor::Create(GetID(), threadid, config, false); 197099e37695SRavitheja Addepally if (!traceMonitor) { 197199e37695SRavitheja Addepally error = traceMonitor.takeError(); 197299e37695SRavitheja Addepally LLDB_LOG(log, "error {0}", error); 197399e37695SRavitheja Addepally return LLDB_INVALID_UID; 197499e37695SRavitheja Addepally } 197599e37695SRavitheja Addepally lldb::user_id_t ret_trace_id = (*traceMonitor)->GetTraceID(); 197699e37695SRavitheja Addepally m_processor_trace_monitor.insert( 197799e37695SRavitheja Addepally std::make_pair(threadid, std::move(*traceMonitor))); 197899e37695SRavitheja Addepally return ret_trace_id; 197999e37695SRavitheja Addepally } 198099e37695SRavitheja Addepally 198199e37695SRavitheja Addepally Status NativeProcessLinux::StopTracingForThread(lldb::tid_t thread) { 198299e37695SRavitheja Addepally Status error; 198399e37695SRavitheja Addepally Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 198499e37695SRavitheja Addepally LLDB_LOG(log, "Thread {0}", thread); 198599e37695SRavitheja Addepally 198699e37695SRavitheja Addepally const auto& iter = m_processor_trace_monitor.find(thread); 198799e37695SRavitheja Addepally if (iter == m_processor_trace_monitor.end()) { 198899e37695SRavitheja Addepally error.SetErrorString("tracing not active for this thread"); 198999e37695SRavitheja Addepally return error; 199099e37695SRavitheja Addepally } 199199e37695SRavitheja Addepally 199299e37695SRavitheja Addepally if (iter->second->GetTraceID() == m_pt_proces_trace_id) { 199305097246SAdrian Prantl // traceid maps to the whole process so we have to erase it from the thread 199405097246SAdrian Prantl // group. 199599e37695SRavitheja Addepally LLDB_LOG(log, "traceid maps to process"); 199699e37695SRavitheja Addepally m_pt_traced_thread_group.erase(thread); 199799e37695SRavitheja Addepally } 199899e37695SRavitheja Addepally m_processor_trace_monitor.erase(iter); 199999e37695SRavitheja Addepally 200099e37695SRavitheja Addepally return error; 200199e37695SRavitheja Addepally } 200299e37695SRavitheja Addepally 200399e37695SRavitheja Addepally Status NativeProcessLinux::StopTrace(lldb::user_id_t traceid, 200499e37695SRavitheja Addepally lldb::tid_t thread) { 200599e37695SRavitheja Addepally Status error; 200699e37695SRavitheja Addepally 200799e37695SRavitheja Addepally TraceOptions trace_options; 200899e37695SRavitheja Addepally trace_options.setThreadID(thread); 200999e37695SRavitheja Addepally error = NativeProcessLinux::GetTraceConfig(traceid, trace_options); 201099e37695SRavitheja Addepally 201199e37695SRavitheja Addepally if (error.Fail()) 201299e37695SRavitheja Addepally return error; 201399e37695SRavitheja Addepally 201499e37695SRavitheja Addepally switch (trace_options.getType()) { 201599e37695SRavitheja Addepally case lldb::TraceType::eTraceTypeProcessorTrace: 201699e37695SRavitheja Addepally if (traceid == m_pt_proces_trace_id && 201799e37695SRavitheja Addepally thread == LLDB_INVALID_THREAD_ID) 201899e37695SRavitheja Addepally StopProcessorTracingOnProcess(); 201999e37695SRavitheja Addepally else 202099e37695SRavitheja Addepally error = StopProcessorTracingOnThread(traceid, thread); 202199e37695SRavitheja Addepally break; 202299e37695SRavitheja Addepally default: 202399e37695SRavitheja Addepally error.SetErrorString("trace not supported"); 202499e37695SRavitheja Addepally break; 202599e37695SRavitheja Addepally } 202699e37695SRavitheja Addepally 202799e37695SRavitheja Addepally return error; 202899e37695SRavitheja Addepally } 202999e37695SRavitheja Addepally 203099e37695SRavitheja Addepally void NativeProcessLinux::StopProcessorTracingOnProcess() { 203199e37695SRavitheja Addepally for (auto thread_id_iter : m_pt_traced_thread_group) 203299e37695SRavitheja Addepally m_processor_trace_monitor.erase(thread_id_iter); 203399e37695SRavitheja Addepally m_pt_traced_thread_group.clear(); 203499e37695SRavitheja Addepally m_pt_proces_trace_id = LLDB_INVALID_UID; 203599e37695SRavitheja Addepally } 203699e37695SRavitheja Addepally 203799e37695SRavitheja Addepally Status NativeProcessLinux::StopProcessorTracingOnThread(lldb::user_id_t traceid, 203899e37695SRavitheja Addepally lldb::tid_t thread) { 203999e37695SRavitheja Addepally Status error; 204099e37695SRavitheja Addepally Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 204199e37695SRavitheja Addepally 204299e37695SRavitheja Addepally if (thread == LLDB_INVALID_THREAD_ID) { 204399e37695SRavitheja Addepally for (auto& iter : m_processor_trace_monitor) { 204499e37695SRavitheja Addepally if (iter.second->GetTraceID() == traceid) { 204505097246SAdrian Prantl // Stopping a trace instance for an individual thread hence there will 204605097246SAdrian Prantl // only be one traceid that can match. 204799e37695SRavitheja Addepally m_processor_trace_monitor.erase(iter.first); 204899e37695SRavitheja Addepally return error; 204999e37695SRavitheja Addepally } 205099e37695SRavitheja Addepally LLDB_LOG(log, "Trace ID {0}", iter.second->GetTraceID()); 205199e37695SRavitheja Addepally } 205299e37695SRavitheja Addepally 205399e37695SRavitheja Addepally LLDB_LOG(log, "Invalid TraceID"); 205499e37695SRavitheja Addepally error.SetErrorString("invalid trace id"); 205599e37695SRavitheja Addepally return error; 205699e37695SRavitheja Addepally } 205799e37695SRavitheja Addepally 205899e37695SRavitheja Addepally // thread is specified so we can use find function on the map. 205999e37695SRavitheja Addepally const auto& iter = m_processor_trace_monitor.find(thread); 206099e37695SRavitheja Addepally if (iter == m_processor_trace_monitor.end()) { 206199e37695SRavitheja Addepally // thread not found in our map. 206299e37695SRavitheja Addepally LLDB_LOG(log, "thread not being traced"); 206399e37695SRavitheja Addepally error.SetErrorString("tracing not active for this thread"); 206499e37695SRavitheja Addepally return error; 206599e37695SRavitheja Addepally } 206699e37695SRavitheja Addepally if (iter->second->GetTraceID() != traceid) { 206799e37695SRavitheja Addepally // traceid did not match so it has to be invalid. 206899e37695SRavitheja Addepally LLDB_LOG(log, "Invalid TraceID"); 206999e37695SRavitheja Addepally error.SetErrorString("invalid trace id"); 207099e37695SRavitheja Addepally return error; 207199e37695SRavitheja Addepally } 207299e37695SRavitheja Addepally 207399e37695SRavitheja Addepally LLDB_LOG(log, "UID - {0} , Thread -{1}", traceid, thread); 207499e37695SRavitheja Addepally 207599e37695SRavitheja Addepally if (traceid == m_pt_proces_trace_id) { 207605097246SAdrian Prantl // traceid maps to the whole process so we have to erase it from the thread 207705097246SAdrian Prantl // group. 207899e37695SRavitheja Addepally LLDB_LOG(log, "traceid maps to process"); 207999e37695SRavitheja Addepally m_pt_traced_thread_group.erase(thread); 208099e37695SRavitheja Addepally } 208199e37695SRavitheja Addepally m_processor_trace_monitor.erase(iter); 208299e37695SRavitheja Addepally 208399e37695SRavitheja Addepally return error; 208499e37695SRavitheja Addepally } 2085