180814287SRaphael Isemann //===-- NativeProcessLinux.cpp --------------------------------------------===// 2af245d11STodd Fiala // 32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information. 52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6af245d11STodd Fiala // 7af245d11STodd Fiala //===----------------------------------------------------------------------===// 8af245d11STodd Fiala 9af245d11STodd Fiala #include "NativeProcessLinux.h" 10af245d11STodd Fiala 11af245d11STodd Fiala #include <errno.h> 12af245d11STodd Fiala #include <stdint.h> 13b9c1b51eSKate Stone #include <string.h> 14af245d11STodd Fiala #include <unistd.h> 15af245d11STodd Fiala 16af245d11STodd Fiala #include <fstream> 17df7c6995SPavel Labath #include <mutex> 18c076559aSPavel Labath #include <sstream> 19af245d11STodd Fiala #include <string> 205b981ab9SPavel Labath #include <unordered_map> 21af245d11STodd Fiala 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( 259*64ec505dSJonas Devlieghere pid, launch_info.GetPTY().ReleasePrimaryFileDescriptor(), native_delegate, 26036e82208SPavel Labath Info.GetArchitecture(), mainloop, {pid})); 261af245d11STodd Fiala } 262af245d11STodd Fiala 26382abefa4SPavel Labath llvm::Expected<std::unique_ptr<NativeProcessProtocol>> 26482abefa4SPavel Labath NativeProcessLinux::Factory::Attach( 265b9c1b51eSKate Stone lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate, 26696e600fcSPavel Labath MainLoop &mainloop) const { 267a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 268a6321a8eSPavel Labath LLDB_LOG(log, "pid = {0:x}", pid); 269af245d11STodd Fiala 270af245d11STodd Fiala // Retrieve the architecture for the running process. 27136e82208SPavel Labath ProcessInstanceInfo Info; 27236e82208SPavel Labath if (!Host::GetProcessInfo(pid, Info)) { 27336e82208SPavel Labath return llvm::make_error<StringError>("Cannot get process architecture", 27436e82208SPavel Labath llvm::inconvertibleErrorCode()); 27536e82208SPavel Labath } 276af245d11STodd Fiala 27796e600fcSPavel Labath auto tids_or = NativeProcessLinux::Attach(pid); 27896e600fcSPavel Labath if (!tids_or) 27996e600fcSPavel Labath return tids_or.takeError(); 280af245d11STodd Fiala 28182abefa4SPavel Labath return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux( 28236e82208SPavel Labath pid, -1, native_delegate, Info.GetArchitecture(), mainloop, *tids_or)); 283af245d11STodd Fiala } 284af245d11STodd Fiala 285af245d11STodd Fiala // Public Instance Methods 286af245d11STodd Fiala 28796e600fcSPavel Labath NativeProcessLinux::NativeProcessLinux(::pid_t pid, int terminal_fd, 28896e600fcSPavel Labath NativeDelegate &delegate, 28982abefa4SPavel Labath const ArchSpec &arch, MainLoop &mainloop, 29082abefa4SPavel Labath llvm::ArrayRef<::pid_t> tids) 291f4335b8eSAntonio Afonso : NativeProcessELF(pid, terminal_fd, delegate), m_arch(arch) { 292b9c1b51eSKate Stone if (m_terminal_fd != -1) { 29396e600fcSPavel Labath Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK); 29496e600fcSPavel Labath assert(status.Success()); 2955ad891f7SPavel Labath } 296af245d11STodd Fiala 29796e600fcSPavel Labath Status status; 29896e600fcSPavel Labath m_sigchld_handle = mainloop.RegisterSignal( 29996e600fcSPavel Labath SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status); 30096e600fcSPavel Labath assert(m_sigchld_handle && status.Success()); 30196e600fcSPavel Labath 30296e600fcSPavel Labath for (const auto &tid : tids) { 303a5be48b3SPavel Labath NativeThreadLinux &thread = AddThread(tid); 304a5be48b3SPavel Labath thread.SetStoppedBySignal(SIGSTOP); 305a5be48b3SPavel Labath ThreadWasCreated(thread); 306af245d11STodd Fiala } 307af245d11STodd Fiala 30896e600fcSPavel Labath // Let our process instance know the thread has stopped. 30996e600fcSPavel Labath SetCurrentThreadID(tids[0]); 31096e600fcSPavel Labath SetState(StateType::eStateStopped, false); 31196e600fcSPavel Labath 31296e600fcSPavel Labath // Proccess any signals we received before installing our handler 31396e600fcSPavel Labath SigchldHandler(); 31496e600fcSPavel Labath } 31596e600fcSPavel Labath 31696e600fcSPavel Labath llvm::Expected<std::vector<::pid_t>> NativeProcessLinux::Attach(::pid_t pid) { 317a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 318af245d11STodd Fiala 31996e600fcSPavel Labath Status status; 320b9c1b51eSKate Stone // Use a map to keep track of the threads which we have attached/need to 321b9c1b51eSKate Stone // attach. 322af245d11STodd Fiala Host::TidMap tids_to_attach; 323b9c1b51eSKate Stone while (Host::FindProcessThreads(pid, tids_to_attach)) { 324af245d11STodd Fiala for (Host::TidMap::iterator it = tids_to_attach.begin(); 325b9c1b51eSKate Stone it != tids_to_attach.end();) { 326b9c1b51eSKate Stone if (it->second == false) { 327af245d11STodd Fiala lldb::tid_t tid = it->first; 328af245d11STodd Fiala 329af245d11STodd Fiala // Attach to the requested process. 330af245d11STodd Fiala // An attach will cause the thread to stop with a SIGSTOP. 33196e600fcSPavel Labath if ((status = PtraceWrapper(PTRACE_ATTACH, tid)).Fail()) { 33205097246SAdrian Prantl // No such thread. The thread may have exited. More error handling 33305097246SAdrian Prantl // may be needed. 33496e600fcSPavel Labath if (status.GetError() == ESRCH) { 335af245d11STodd Fiala it = tids_to_attach.erase(it); 336af245d11STodd Fiala continue; 33796e600fcSPavel Labath } 33896e600fcSPavel Labath return status.ToError(); 339af245d11STodd Fiala } 340af245d11STodd Fiala 34196e600fcSPavel Labath int wpid = 34296e600fcSPavel Labath llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, nullptr, __WALL); 34305097246SAdrian Prantl // Need to use __WALL otherwise we receive an error with errno=ECHLD At 34405097246SAdrian Prantl // this point we should have a thread stopped if waitpid succeeds. 34596e600fcSPavel Labath if (wpid < 0) { 34605097246SAdrian Prantl // No such thread. The thread may have exited. More error handling 34705097246SAdrian Prantl // may be needed. 348b9c1b51eSKate Stone if (errno == ESRCH) { 349af245d11STodd Fiala it = tids_to_attach.erase(it); 350af245d11STodd Fiala continue; 351af245d11STodd Fiala } 35296e600fcSPavel Labath return llvm::errorCodeToError( 35396e600fcSPavel Labath std::error_code(errno, std::generic_category())); 354af245d11STodd Fiala } 355af245d11STodd Fiala 35696e600fcSPavel Labath if ((status = SetDefaultPtraceOpts(tid)).Fail()) 35796e600fcSPavel Labath return status.ToError(); 358af245d11STodd Fiala 359a6321a8eSPavel Labath LLDB_LOG(log, "adding tid = {0}", tid); 360af245d11STodd Fiala it->second = true; 361af245d11STodd Fiala } 362af245d11STodd Fiala 363af245d11STodd Fiala // move the loop forward 364af245d11STodd Fiala ++it; 365af245d11STodd Fiala } 366af245d11STodd Fiala } 367af245d11STodd Fiala 36896e600fcSPavel Labath size_t tid_count = tids_to_attach.size(); 36996e600fcSPavel Labath if (tid_count == 0) 37096e600fcSPavel Labath return llvm::make_error<StringError>("No such process", 37196e600fcSPavel Labath llvm::inconvertibleErrorCode()); 372af245d11STodd Fiala 37396e600fcSPavel Labath std::vector<::pid_t> tids; 37496e600fcSPavel Labath tids.reserve(tid_count); 37596e600fcSPavel Labath for (const auto &p : tids_to_attach) 37696e600fcSPavel Labath tids.push_back(p.first); 37796e600fcSPavel Labath return std::move(tids); 378af245d11STodd Fiala } 379af245d11STodd Fiala 38097206d57SZachary Turner Status NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid) { 381af245d11STodd Fiala long ptrace_opts = 0; 382af245d11STodd Fiala 383af245d11STodd Fiala // Have the child raise an event on exit. This is used to keep the child in 384af245d11STodd Fiala // limbo until it is destroyed. 385af245d11STodd Fiala ptrace_opts |= PTRACE_O_TRACEEXIT; 386af245d11STodd Fiala 387af245d11STodd Fiala // Have the tracer trace threads which spawn in the inferior process. 388af245d11STodd Fiala // TODO: if we want to support tracing the inferiors' child, add the 389af245d11STodd Fiala // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK) 390af245d11STodd Fiala ptrace_opts |= PTRACE_O_TRACECLONE; 391af245d11STodd Fiala 39205097246SAdrian Prantl // Have the tracer notify us before execve returns (needed to disable legacy 39305097246SAdrian Prantl // SIGTRAP generation) 394af245d11STodd Fiala ptrace_opts |= PTRACE_O_TRACEEXEC; 395af245d11STodd Fiala 3964a9babb2SPavel Labath return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void *)ptrace_opts); 397af245d11STodd Fiala } 398af245d11STodd Fiala 3991107b5a5SPavel Labath // Handles all waitpid events from the inferior process. 400b9c1b51eSKate Stone void NativeProcessLinux::MonitorCallback(lldb::pid_t pid, bool exited, 4013508fc8cSPavel Labath WaitStatus status) { 402af245d11STodd Fiala Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 403af245d11STodd Fiala 404b9c1b51eSKate Stone // Certain activities differ based on whether the pid is the tid of the main 405b9c1b51eSKate Stone // thread. 4061107b5a5SPavel Labath const bool is_main_thread = (pid == GetID()); 407af245d11STodd Fiala 408af245d11STodd Fiala // Handle when the thread exits. 409b9c1b51eSKate Stone if (exited) { 410d8b3c1a1SPavel Labath LLDB_LOG(log, 4119303afb3SPavel Labath "got exit status({0}) , tid = {1} ({2} main thread), process " 412d8b3c1a1SPavel Labath "state = {3}", 4139303afb3SPavel Labath status, pid, is_main_thread ? "is" : "is not", GetState()); 414af245d11STodd Fiala 415af245d11STodd Fiala // This is a thread that exited. Ensure we're not tracking it anymore. 416d8b3c1a1SPavel Labath StopTrackingThread(pid); 417af245d11STodd Fiala 418b9c1b51eSKate Stone if (is_main_thread) { 419af245d11STodd Fiala // The main thread exited. We're done monitoring. Report to delegate. 4203508fc8cSPavel Labath SetExitStatus(status, true); 421af245d11STodd Fiala 422af245d11STodd Fiala // Notify delegate that our process has exited. 4231107b5a5SPavel Labath SetState(StateType::eStateExited, true); 424af245d11STodd Fiala } 4251107b5a5SPavel Labath return; 426af245d11STodd Fiala } 427af245d11STodd Fiala 428af245d11STodd Fiala siginfo_t info; 429b9cc0c75SPavel Labath const auto info_err = GetSignalInfo(pid, &info); 430b9cc0c75SPavel Labath auto thread_sp = GetThreadByID(pid); 431b9cc0c75SPavel Labath 432b9c1b51eSKate Stone if (!thread_sp) { 43305097246SAdrian Prantl // Normally, the only situation when we cannot find the thread is if we 43405097246SAdrian Prantl // have just received a new thread notification. This is indicated by 435a6321a8eSPavel Labath // GetSignalInfo() returning si_code == SI_USER and si_pid == 0 436a6321a8eSPavel Labath LLDB_LOG(log, "received notification about an unknown tid {0}.", pid); 437b9cc0c75SPavel Labath 438b9c1b51eSKate Stone if (info_err.Fail()) { 439a6321a8eSPavel Labath LLDB_LOG(log, 440a6321a8eSPavel Labath "(tid {0}) GetSignalInfo failed ({1}). " 441a6321a8eSPavel Labath "Ingoring this notification.", 442a6321a8eSPavel Labath pid, info_err); 443b9cc0c75SPavel Labath return; 444b9cc0c75SPavel Labath } 445b9cc0c75SPavel Labath 446a6321a8eSPavel Labath LLDB_LOG(log, "tid {0}, si_code: {1}, si_pid: {2}", pid, info.si_code, 447a6321a8eSPavel Labath info.si_pid); 448b9cc0c75SPavel Labath 449a5be48b3SPavel Labath NativeThreadLinux &thread = AddThread(pid); 45099e37695SRavitheja Addepally 451b9cc0c75SPavel Labath // Resume the newly created thread. 452a5be48b3SPavel Labath ResumeThread(thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER); 453a5be48b3SPavel Labath ThreadWasCreated(thread); 454b9cc0c75SPavel Labath return; 455b9cc0c75SPavel Labath } 456b9cc0c75SPavel Labath 457b9cc0c75SPavel Labath // Get details on the signal raised. 458b9c1b51eSKate Stone if (info_err.Success()) { 459fa03ad2eSChaoren Lin // We have retrieved the signal info. Dispatch appropriately. 460fa03ad2eSChaoren Lin if (info.si_signo == SIGTRAP) 461b9cc0c75SPavel Labath MonitorSIGTRAP(info, *thread_sp); 462fa03ad2eSChaoren Lin else 463b9cc0c75SPavel Labath MonitorSignal(info, *thread_sp, exited); 464b9c1b51eSKate Stone } else { 465b9c1b51eSKate Stone if (info_err.GetError() == EINVAL) { 46605097246SAdrian Prantl // This is a group stop reception for this tid. We can reach here if we 46705097246SAdrian Prantl // reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the tracee, 46805097246SAdrian Prantl // triggering the group-stop mechanism. Normally receiving these would 46905097246SAdrian Prantl // stop the process, pending a SIGCONT. Simulating this state in a 47005097246SAdrian Prantl // debugger is hard and is generally not needed (one use case is 47105097246SAdrian Prantl // debugging background task being managed by a shell). For general use, 47205097246SAdrian Prantl // it is sufficient to stop the process in a signal-delivery stop which 47305097246SAdrian Prantl // happens before the group stop. This done by MonitorSignal and works 47405097246SAdrian Prantl // correctly for all signals. 475a6321a8eSPavel Labath LLDB_LOG(log, 476a6321a8eSPavel Labath "received a group stop for pid {0} tid {1}. Transparent " 477a6321a8eSPavel Labath "handling of group stops not supported, resuming the " 478a6321a8eSPavel Labath "thread.", 479a6321a8eSPavel Labath GetID(), pid); 480b9c1b51eSKate Stone ResumeThread(*thread_sp, thread_sp->GetState(), 481b9c1b51eSKate Stone LLDB_INVALID_SIGNAL_NUMBER); 482b9c1b51eSKate Stone } else { 483af245d11STodd Fiala // ptrace(GETSIGINFO) failed (but not due to group-stop). 484af245d11STodd Fiala 485b9c1b51eSKate Stone // A return value of ESRCH means the thread/process is no longer on the 486a6321a8eSPavel Labath // system, so it was killed somehow outside of our control. Either way, 487a6321a8eSPavel Labath // we can't do anything with it anymore. 488af245d11STodd Fiala 489b9c1b51eSKate Stone // Stop tracking the metadata for the thread since it's entirely off the 490b9c1b51eSKate Stone // system now. 4911107b5a5SPavel Labath const bool thread_found = StopTrackingThread(pid); 492af245d11STodd Fiala 493a6321a8eSPavel Labath LLDB_LOG(log, 4949303afb3SPavel Labath "GetSignalInfo failed: {0}, tid = {1}, status = {2}, " 495a6321a8eSPavel Labath "status = {3}, main_thread = {4}, thread_found: {5}", 4969303afb3SPavel Labath info_err, pid, status, status, is_main_thread, thread_found); 497af245d11STodd Fiala 498b9c1b51eSKate Stone if (is_main_thread) { 499b9c1b51eSKate Stone // Notify the delegate - our process is not available but appears to 50005097246SAdrian Prantl // have been killed outside our control. Is eStateExited the right 50105097246SAdrian Prantl // exit state in this case? 5023508fc8cSPavel Labath SetExitStatus(status, true); 5031107b5a5SPavel Labath SetState(StateType::eStateExited, true); 504b9c1b51eSKate Stone } else { 505b9c1b51eSKate Stone // This thread was pulled out from underneath us. Anything to do here? 506b9c1b51eSKate Stone // Do we want to do an all stop? 507a6321a8eSPavel Labath LLDB_LOG(log, 508a6321a8eSPavel Labath "pid {0} tid {1} non-main thread exit occurred, didn't " 509a6321a8eSPavel Labath "tell delegate anything since thread disappeared out " 510a6321a8eSPavel Labath "from underneath us", 511a6321a8eSPavel Labath GetID(), pid); 512af245d11STodd Fiala } 513af245d11STodd Fiala } 514af245d11STodd Fiala } 515af245d11STodd Fiala } 516af245d11STodd Fiala 517b9c1b51eSKate Stone void NativeProcessLinux::WaitForNewThread(::pid_t tid) { 518a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 519426bdf88SPavel Labath 520a5be48b3SPavel Labath if (GetThreadByID(tid)) { 521b9c1b51eSKate Stone // We are already tracking the thread - we got the event on the new thread 522a5be48b3SPavel Labath // (see MonitorSignal) before this one. We are done. 523426bdf88SPavel Labath return; 524426bdf88SPavel Labath } 525426bdf88SPavel Labath 526426bdf88SPavel Labath // The thread is not tracked yet, let's wait for it to appear. 527426bdf88SPavel Labath int status = -1; 528a6321a8eSPavel Labath LLDB_LOG(log, 529a6321a8eSPavel Labath "received thread creation event for tid {0}. tid not tracked " 530a6321a8eSPavel Labath "yet, waiting for thread to appear...", 531a6321a8eSPavel Labath tid); 532c1a6b128SPavel Labath ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, &status, __WALL); 533b9c1b51eSKate Stone // Since we are waiting on a specific tid, this must be the creation event. 534a6321a8eSPavel Labath // But let's do some checks just in case. 535426bdf88SPavel Labath if (wait_pid != tid) { 536a6321a8eSPavel Labath LLDB_LOG(log, 537a6321a8eSPavel Labath "waiting for tid {0} failed. Assuming the thread has " 538a6321a8eSPavel Labath "disappeared in the meantime", 539a6321a8eSPavel Labath tid); 540426bdf88SPavel Labath // The only way I know of this could happen is if the whole process was 541b9c1b51eSKate Stone // SIGKILLed in the mean time. In any case, we can't do anything about that 542b9c1b51eSKate Stone // now. 543426bdf88SPavel Labath return; 544426bdf88SPavel Labath } 545b9c1b51eSKate Stone if (WIFEXITED(status)) { 546a6321a8eSPavel Labath LLDB_LOG(log, 547a6321a8eSPavel Labath "waiting for tid {0} returned an 'exited' event. Not " 548a6321a8eSPavel Labath "tracking the thread.", 549a6321a8eSPavel Labath tid); 550426bdf88SPavel Labath // Also a very improbable event. 551426bdf88SPavel Labath return; 552426bdf88SPavel Labath } 553426bdf88SPavel Labath 554a6321a8eSPavel Labath LLDB_LOG(log, "pid = {0}: tracking new thread tid {1}", GetID(), tid); 555a5be48b3SPavel Labath NativeThreadLinux &new_thread = AddThread(tid); 55699e37695SRavitheja Addepally 557a5be48b3SPavel Labath ResumeThread(new_thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER); 558a5be48b3SPavel Labath ThreadWasCreated(new_thread); 559426bdf88SPavel Labath } 560426bdf88SPavel Labath 561b9c1b51eSKate Stone void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info, 562b9c1b51eSKate Stone NativeThreadLinux &thread) { 563a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 564b9cc0c75SPavel Labath const bool is_main_thread = (thread.GetID() == GetID()); 565af245d11STodd Fiala 566b9cc0c75SPavel Labath assert(info.si_signo == SIGTRAP && "Unexpected child signal!"); 567af245d11STodd Fiala 568b9c1b51eSKate Stone switch (info.si_code) { 569b9c1b51eSKate Stone // TODO: these two cases are required if we want to support tracing of the 57005097246SAdrian Prantl // inferiors' children. We'd need this to debug a monitor. case (SIGTRAP | 57105097246SAdrian Prantl // (PTRACE_EVENT_FORK << 8)): case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)): 572af245d11STodd Fiala 573b9c1b51eSKate Stone case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): { 574b9c1b51eSKate Stone // This is the notification on the parent thread which informs us of new 57505097246SAdrian Prantl // thread creation. We don't want to do anything with the parent thread so 57605097246SAdrian Prantl // we just resume it. In case we want to implement "break on thread 57705097246SAdrian Prantl // creation" functionality, we would need to stop here. 578af245d11STodd Fiala 579af245d11STodd Fiala unsigned long event_message = 0; 580b9c1b51eSKate Stone if (GetEventMessage(thread.GetID(), &event_message).Fail()) { 581a6321a8eSPavel Labath LLDB_LOG(log, 582a6321a8eSPavel Labath "pid {0} received thread creation event but " 583a6321a8eSPavel Labath "GetEventMessage failed so we don't know the new tid", 584a6321a8eSPavel Labath thread.GetID()); 585426bdf88SPavel Labath } else 586426bdf88SPavel Labath WaitForNewThread(event_message); 587af245d11STodd Fiala 588b9cc0c75SPavel Labath ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER); 589af245d11STodd Fiala break; 590af245d11STodd Fiala } 591af245d11STodd Fiala 592b9c1b51eSKate Stone case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): { 593a6321a8eSPavel Labath LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP); 594a9882ceeSTodd Fiala 5951dbc6c9cSPavel Labath // Exec clears any pending notifications. 5960e1d729bSPavel Labath m_pending_notification_tid = LLDB_INVALID_THREAD_ID; 597fa03ad2eSChaoren Lin 598b9c1b51eSKate Stone // Remove all but the main thread here. Linux fork creates a new process 599b9c1b51eSKate Stone // which only copies the main thread. 600a6321a8eSPavel Labath LLDB_LOG(log, "exec received, stop tracking all but main thread"); 601a9882ceeSTodd Fiala 602ee74c9e5SPavel Labath llvm::erase_if(m_threads, [&](std::unique_ptr<NativeThreadProtocol> &t) { 603ee74c9e5SPavel Labath return t->GetID() != GetID(); 604ee74c9e5SPavel Labath }); 605a5be48b3SPavel Labath assert(m_threads.size() == 1); 606a5be48b3SPavel Labath auto *main_thread = static_cast<NativeThreadLinux *>(m_threads[0].get()); 607a9882ceeSTodd Fiala 608a5be48b3SPavel Labath SetCurrentThreadID(main_thread->GetID()); 609a5be48b3SPavel Labath main_thread->SetStoppedByExec(); 610a9882ceeSTodd Fiala 611fa03ad2eSChaoren Lin // Tell coordinator about about the "new" (since exec) stopped main thread. 612a5be48b3SPavel Labath ThreadWasCreated(*main_thread); 613fa03ad2eSChaoren Lin 614a9882ceeSTodd Fiala // Let our delegate know we have just exec'd. 615a9882ceeSTodd Fiala NotifyDidExec(); 616a9882ceeSTodd Fiala 617fa03ad2eSChaoren Lin // Let the process know we're stopped. 618a5be48b3SPavel Labath StopRunningThreads(main_thread->GetID()); 619a9882ceeSTodd Fiala 620af245d11STodd Fiala break; 621a9882ceeSTodd Fiala } 622af245d11STodd Fiala 623b9c1b51eSKate Stone case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): { 62405097246SAdrian Prantl // The inferior process or one of its threads is about to exit. We don't 62505097246SAdrian Prantl // want to do anything with the thread so we just resume it. In case we 62605097246SAdrian Prantl // want to implement "break on thread exit" functionality, we would need to 62705097246SAdrian Prantl // stop here. 628fa03ad2eSChaoren Lin 629af245d11STodd Fiala unsigned long data = 0; 630b9cc0c75SPavel Labath if (GetEventMessage(thread.GetID(), &data).Fail()) 631af245d11STodd Fiala data = -1; 632af245d11STodd Fiala 633a6321a8eSPavel Labath LLDB_LOG(log, 634a6321a8eSPavel Labath "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, " 635a6321a8eSPavel Labath "WIFSIGNALED={2}, pid = {3}, main_thread = {4}", 636a6321a8eSPavel Labath data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(), 637a6321a8eSPavel Labath is_main_thread); 638af245d11STodd Fiala 63975f47c3aSTodd Fiala 64086852d36SPavel Labath StateType state = thread.GetState(); 641b9c1b51eSKate Stone if (!StateIsRunningState(state)) { 642b9c1b51eSKate Stone // Due to a kernel bug, we may sometimes get this stop after the inferior 643d8b3c1a1SPavel Labath // gets a SIGKILL. This confuses our state tracking logic in 644d8b3c1a1SPavel Labath // ResumeThread(), since normally, we should not be receiving any ptrace 64505097246SAdrian Prantl // events while the inferior is stopped. This makes sure that the 64605097246SAdrian Prantl // inferior is resumed and exits normally. 64786852d36SPavel Labath state = eStateRunning; 64886852d36SPavel Labath } 64986852d36SPavel Labath ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER); 650af245d11STodd Fiala 651af245d11STodd Fiala break; 652af245d11STodd Fiala } 653af245d11STodd Fiala 654af245d11STodd Fiala case 0: 655c16f5dcaSChaoren Lin case TRAP_TRACE: // We receive this on single stepping. 656c16f5dcaSChaoren Lin case TRAP_HWBKPT: // We receive this on watchpoint hit 65786fd8e45SChaoren Lin { 658c16f5dcaSChaoren Lin // If a watchpoint was hit, report it 659c16f5dcaSChaoren Lin uint32_t wp_index; 660d37349f3SPavel Labath Status error = thread.GetRegisterContext().GetWatchpointHitIndex( 661b9c1b51eSKate Stone wp_index, (uintptr_t)info.si_addr); 662a6321a8eSPavel Labath if (error.Fail()) 663a6321a8eSPavel Labath LLDB_LOG(log, 664a6321a8eSPavel Labath "received error while checking for watchpoint hits, pid = " 665a6321a8eSPavel Labath "{0}, error = {1}", 666a6321a8eSPavel Labath thread.GetID(), error); 667b9c1b51eSKate Stone if (wp_index != LLDB_INVALID_INDEX32) { 668b9cc0c75SPavel Labath MonitorWatchpoint(thread, wp_index); 669c16f5dcaSChaoren Lin break; 670c16f5dcaSChaoren Lin } 671b9cc0c75SPavel Labath 672d5ffbad2SOmair Javaid // If a breakpoint was hit, report it 673d5ffbad2SOmair Javaid uint32_t bp_index; 674d37349f3SPavel Labath error = thread.GetRegisterContext().GetHardwareBreakHitIndex( 675d5ffbad2SOmair Javaid bp_index, (uintptr_t)info.si_addr); 676d5ffbad2SOmair Javaid if (error.Fail()) 677d5ffbad2SOmair Javaid LLDB_LOG(log, "received error while checking for hardware " 678d5ffbad2SOmair Javaid "breakpoint hits, pid = {0}, error = {1}", 679d5ffbad2SOmair Javaid thread.GetID(), error); 680d5ffbad2SOmair Javaid if (bp_index != LLDB_INVALID_INDEX32) { 681d5ffbad2SOmair Javaid MonitorBreakpoint(thread); 682d5ffbad2SOmair Javaid break; 683d5ffbad2SOmair Javaid } 684d5ffbad2SOmair Javaid 685be379e15STamas Berghammer // Otherwise, report step over 686be379e15STamas Berghammer MonitorTrace(thread); 687af245d11STodd Fiala break; 688b9cc0c75SPavel Labath } 689af245d11STodd Fiala 690af245d11STodd Fiala case SI_KERNEL: 69135799963SMohit K. Bhakkad #if defined __mips__ 69205097246SAdrian Prantl // For mips there is no special signal for watchpoint So we check for 69305097246SAdrian Prantl // watchpoint in kernel trap 69435799963SMohit K. Bhakkad { 69535799963SMohit K. Bhakkad // If a watchpoint was hit, report it 69635799963SMohit K. Bhakkad uint32_t wp_index; 697d37349f3SPavel Labath Status error = thread.GetRegisterContext().GetWatchpointHitIndex( 698b9c1b51eSKate Stone wp_index, LLDB_INVALID_ADDRESS); 699a6321a8eSPavel Labath if (error.Fail()) 700a6321a8eSPavel Labath LLDB_LOG(log, 701a6321a8eSPavel Labath "received error while checking for watchpoint hits, pid = " 702a6321a8eSPavel Labath "{0}, error = {1}", 703a6321a8eSPavel Labath thread.GetID(), error); 704b9c1b51eSKate Stone if (wp_index != LLDB_INVALID_INDEX32) { 705b9cc0c75SPavel Labath MonitorWatchpoint(thread, wp_index); 70635799963SMohit K. Bhakkad break; 70735799963SMohit K. Bhakkad } 70835799963SMohit K. Bhakkad } 70935799963SMohit K. Bhakkad // NO BREAK 71035799963SMohit K. Bhakkad #endif 711af245d11STodd Fiala case TRAP_BRKPT: 712b9cc0c75SPavel Labath MonitorBreakpoint(thread); 713af245d11STodd Fiala break; 714af245d11STodd Fiala 715af245d11STodd Fiala case SIGTRAP: 716af245d11STodd Fiala case (SIGTRAP | 0x80): 717a6321a8eSPavel Labath LLDB_LOG( 718a6321a8eSPavel Labath log, 719a6321a8eSPavel Labath "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming", 720a6321a8eSPavel Labath info.si_code, GetID(), thread.GetID()); 721fa03ad2eSChaoren Lin 722af245d11STodd Fiala // Ignore these signals until we know more about them. 723b9cc0c75SPavel Labath ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER); 724af245d11STodd Fiala break; 725af245d11STodd Fiala 726af245d11STodd Fiala default: 72721a365baSPavel Labath LLDB_LOG(log, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}", 728a6321a8eSPavel Labath info.si_code, GetID(), thread.GetID()); 72921a365baSPavel Labath MonitorSignal(info, thread, false); 730af245d11STodd Fiala break; 731af245d11STodd Fiala } 732af245d11STodd Fiala } 733af245d11STodd Fiala 734b9c1b51eSKate Stone void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) { 735a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 736a6321a8eSPavel Labath LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID()); 737c16f5dcaSChaoren Lin 7380e1d729bSPavel Labath // This thread is currently stopped. 739b9cc0c75SPavel Labath thread.SetStoppedByTrace(); 740c16f5dcaSChaoren Lin 741b9cc0c75SPavel Labath StopRunningThreads(thread.GetID()); 742c16f5dcaSChaoren Lin } 743c16f5dcaSChaoren Lin 744b9c1b51eSKate Stone void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) { 745b9c1b51eSKate Stone Log *log( 746b9c1b51eSKate Stone GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS)); 747a6321a8eSPavel Labath LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID()); 748c16f5dcaSChaoren Lin 749c16f5dcaSChaoren Lin // Mark the thread as stopped at breakpoint. 750b9cc0c75SPavel Labath thread.SetStoppedByBreakpoint(); 751aef7908fSPavel Labath FixupBreakpointPCAsNeeded(thread); 752d8c338d4STamas Berghammer 753b9c1b51eSKate Stone if (m_threads_stepping_with_breakpoint.find(thread.GetID()) != 754b9c1b51eSKate Stone m_threads_stepping_with_breakpoint.end()) 755b9cc0c75SPavel Labath thread.SetStoppedByTrace(); 756c16f5dcaSChaoren Lin 757b9cc0c75SPavel Labath StopRunningThreads(thread.GetID()); 758c16f5dcaSChaoren Lin } 759c16f5dcaSChaoren Lin 760b9c1b51eSKate Stone void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread, 761b9c1b51eSKate Stone uint32_t wp_index) { 762b9c1b51eSKate Stone Log *log( 763b9c1b51eSKate Stone GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS)); 764a6321a8eSPavel Labath LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}", 765a6321a8eSPavel Labath thread.GetID(), wp_index); 766c16f5dcaSChaoren Lin 76705097246SAdrian Prantl // Mark the thread as stopped at watchpoint. The address is at 76805097246SAdrian Prantl // (lldb::addr_t)info->si_addr if we need it. 769f9077782SPavel Labath thread.SetStoppedByWatchpoint(wp_index); 770c16f5dcaSChaoren Lin 771b9c1b51eSKate Stone // We need to tell all other running threads before we notify the delegate 772b9c1b51eSKate Stone // about this stop. 773f9077782SPavel Labath StopRunningThreads(thread.GetID()); 774c16f5dcaSChaoren Lin } 775c16f5dcaSChaoren Lin 776b9c1b51eSKate Stone void NativeProcessLinux::MonitorSignal(const siginfo_t &info, 777b9c1b51eSKate Stone NativeThreadLinux &thread, bool exited) { 778b9cc0c75SPavel Labath const int signo = info.si_signo; 779b9cc0c75SPavel Labath const bool is_from_llgs = info.si_pid == getpid(); 780af245d11STodd Fiala 781a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 782af245d11STodd Fiala 783af245d11STodd Fiala // POSIX says that process behaviour is undefined after it ignores a SIGFPE, 78405097246SAdrian Prantl // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a kill(2) 78505097246SAdrian Prantl // or raise(3). Similarly for tgkill(2) on Linux. 786af245d11STodd Fiala // 787af245d11STodd Fiala // IOW, user generated signals never generate what we consider to be a 788af245d11STodd Fiala // "crash". 789af245d11STodd Fiala // 790af245d11STodd Fiala // Similarly, ACK signals generated by this monitor. 791af245d11STodd Fiala 792af245d11STodd Fiala // Handle the signal. 793a6321a8eSPavel Labath LLDB_LOG(log, 794a6321a8eSPavel Labath "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, " 795a6321a8eSPavel Labath "waitpid pid = {4})", 796a6321a8eSPavel Labath Host::GetSignalAsCString(signo), signo, info.si_code, 797b9cc0c75SPavel Labath thread.GetID()); 79858a2f669STodd Fiala 79958a2f669STodd Fiala // Check for thread stop notification. 800b9c1b51eSKate Stone if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) { 801af245d11STodd Fiala // This is a tgkill()-based stop. 802a6321a8eSPavel Labath LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID()); 803fa03ad2eSChaoren Lin 80405097246SAdrian Prantl // Check that we're not already marked with a stop reason. Note this thread 80505097246SAdrian Prantl // really shouldn't already be marked as stopped - if we were, that would 80605097246SAdrian Prantl // imply that the kernel signaled us with the thread stopping which we 80705097246SAdrian Prantl // handled and marked as stopped, and that, without an intervening resume, 80805097246SAdrian Prantl // we received another stop. It is more likely that we are missing the 80905097246SAdrian Prantl // marking of a run state somewhere if we find that the thread was marked 81005097246SAdrian Prantl // as stopped. 811b9cc0c75SPavel Labath const StateType thread_state = thread.GetState(); 812b9c1b51eSKate Stone if (!StateIsStoppedState(thread_state, false)) { 813ed89c7feSPavel Labath // An inferior thread has stopped because of a SIGSTOP we have sent it. 814b9c1b51eSKate Stone // Generally, these are not important stops and we don't want to report 815a6321a8eSPavel Labath // them as they are just used to stop other threads when one thread (the 816a6321a8eSPavel Labath // one with the *real* stop reason) hits a breakpoint (watchpoint, 81705097246SAdrian Prantl // etc...). However, in the case of an asynchronous Interrupt(), this 81805097246SAdrian Prantl // *is* the real stop reason, so we leave the signal intact if this is 81905097246SAdrian Prantl // the thread that was chosen as the triggering thread. 820b9c1b51eSKate Stone if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) { 821b9cc0c75SPavel Labath if (m_pending_notification_tid == thread.GetID()) 822b9cc0c75SPavel Labath thread.SetStoppedBySignal(SIGSTOP, &info); 823ed89c7feSPavel Labath else 824b9cc0c75SPavel Labath thread.SetStoppedWithNoReason(); 825ed89c7feSPavel Labath 826b9cc0c75SPavel Labath SetCurrentThreadID(thread.GetID()); 8270e1d729bSPavel Labath SignalIfAllThreadsStopped(); 828b9c1b51eSKate Stone } else { 8290e1d729bSPavel Labath // We can end up here if stop was initiated by LLGS but by this time a 8300e1d729bSPavel Labath // thread stop has occurred - maybe initiated by another event. 83197206d57SZachary Turner Status error = ResumeThread(thread, thread.GetState(), 0); 832a6321a8eSPavel Labath if (error.Fail()) 833a6321a8eSPavel Labath LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(), 834a6321a8eSPavel Labath error); 8350e1d729bSPavel Labath } 836b9c1b51eSKate Stone } else { 837a6321a8eSPavel Labath LLDB_LOG(log, 838a6321a8eSPavel Labath "pid {0} tid {1}, thread was already marked as a stopped " 839a6321a8eSPavel Labath "state (state={2}), leaving stop signal as is", 8408198db30SPavel Labath GetID(), thread.GetID(), thread_state); 8410e1d729bSPavel Labath SignalIfAllThreadsStopped(); 842af245d11STodd Fiala } 843af245d11STodd Fiala 84458a2f669STodd Fiala // Done handling. 845af245d11STodd Fiala return; 846af245d11STodd Fiala } 847af245d11STodd Fiala 84805097246SAdrian Prantl // Check if debugger should stop at this signal or just ignore it and resume 84905097246SAdrian Prantl // the inferior. 8504a705e7eSPavel Labath if (m_signals_to_ignore.find(signo) != m_signals_to_ignore.end()) { 8514a705e7eSPavel Labath ResumeThread(thread, thread.GetState(), signo); 8524a705e7eSPavel Labath return; 8534a705e7eSPavel Labath } 8544a705e7eSPavel Labath 85586fd8e45SChaoren Lin // This thread is stopped. 856a6321a8eSPavel Labath LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo)); 857b9cc0c75SPavel Labath thread.SetStoppedBySignal(signo, &info); 85886fd8e45SChaoren Lin 85986fd8e45SChaoren Lin // Send a stop to the debugger after we get all other threads to stop. 860b9cc0c75SPavel Labath StopRunningThreads(thread.GetID()); 861511e5cdcSTodd Fiala } 862af245d11STodd Fiala 863e7708688STamas Berghammer namespace { 864e7708688STamas Berghammer 865b9c1b51eSKate Stone struct EmulatorBaton { 866d37349f3SPavel Labath NativeProcessLinux &m_process; 867d37349f3SPavel Labath NativeRegisterContext &m_reg_context; 8686648fcc3SPavel Labath 8696648fcc3SPavel Labath // eRegisterKindDWARF -> RegsiterValue 8706648fcc3SPavel Labath std::unordered_map<uint32_t, RegisterValue> m_register_values; 871e7708688STamas Berghammer 872d37349f3SPavel Labath EmulatorBaton(NativeProcessLinux &process, NativeRegisterContext ®_context) 873b9c1b51eSKate Stone : m_process(process), m_reg_context(reg_context) {} 874e7708688STamas Berghammer }; 875e7708688STamas Berghammer 876e7708688STamas Berghammer } // anonymous namespace 877e7708688STamas Berghammer 878b9c1b51eSKate Stone static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton, 879e7708688STamas Berghammer const EmulateInstruction::Context &context, 880b9c1b51eSKate Stone lldb::addr_t addr, void *dst, size_t length) { 881e7708688STamas Berghammer EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton); 882e7708688STamas Berghammer 8833eb4b458SChaoren Lin size_t bytes_read; 884d37349f3SPavel Labath emulator_baton->m_process.ReadMemory(addr, dst, length, bytes_read); 885e7708688STamas Berghammer return bytes_read; 886e7708688STamas Berghammer } 887e7708688STamas Berghammer 888b9c1b51eSKate Stone static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton, 889e7708688STamas Berghammer const RegisterInfo *reg_info, 890b9c1b51eSKate Stone RegisterValue ®_value) { 891e7708688STamas Berghammer EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton); 892e7708688STamas Berghammer 893b9c1b51eSKate Stone auto it = emulator_baton->m_register_values.find( 894b9c1b51eSKate Stone reg_info->kinds[eRegisterKindDWARF]); 895b9c1b51eSKate Stone if (it != emulator_baton->m_register_values.end()) { 8966648fcc3SPavel Labath reg_value = it->second; 8976648fcc3SPavel Labath return true; 8986648fcc3SPavel Labath } 8996648fcc3SPavel Labath 90005097246SAdrian Prantl // The emulator only fill in the dwarf regsiter numbers (and in some case the 90105097246SAdrian Prantl // generic register numbers). Get the full register info from the register 90205097246SAdrian Prantl // context based on the dwarf register numbers. 903b9c1b51eSKate Stone const RegisterInfo *full_reg_info = 904d37349f3SPavel Labath emulator_baton->m_reg_context.GetRegisterInfo( 905e7708688STamas Berghammer eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]); 906e7708688STamas Berghammer 90797206d57SZachary Turner Status error = 908d37349f3SPavel Labath emulator_baton->m_reg_context.ReadRegister(full_reg_info, reg_value); 9096648fcc3SPavel Labath if (error.Success()) 9106648fcc3SPavel Labath return true; 911cdc22a88SMohit K. Bhakkad 9126648fcc3SPavel Labath return false; 913e7708688STamas Berghammer } 914e7708688STamas Berghammer 915b9c1b51eSKate Stone static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton, 916e7708688STamas Berghammer const EmulateInstruction::Context &context, 917e7708688STamas Berghammer const RegisterInfo *reg_info, 918b9c1b51eSKate Stone const RegisterValue ®_value) { 919e7708688STamas Berghammer EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton); 920b9c1b51eSKate Stone emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = 921b9c1b51eSKate Stone reg_value; 922e7708688STamas Berghammer return true; 923e7708688STamas Berghammer } 924e7708688STamas Berghammer 925b9c1b51eSKate Stone static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton, 926e7708688STamas Berghammer const EmulateInstruction::Context &context, 927b9c1b51eSKate Stone lldb::addr_t addr, const void *dst, 928b9c1b51eSKate Stone size_t length) { 929e7708688STamas Berghammer return length; 930e7708688STamas Berghammer } 931e7708688STamas Berghammer 932d37349f3SPavel Labath static lldb::addr_t ReadFlags(NativeRegisterContext ®siter_context) { 933d37349f3SPavel Labath const RegisterInfo *flags_info = regsiter_context.GetRegisterInfo( 934e7708688STamas Berghammer eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS); 935d37349f3SPavel Labath return regsiter_context.ReadRegisterAsUnsigned(flags_info, 936b9c1b51eSKate Stone LLDB_INVALID_ADDRESS); 937e7708688STamas Berghammer } 938e7708688STamas Berghammer 93997206d57SZachary Turner Status 94097206d57SZachary Turner NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadLinux &thread) { 94197206d57SZachary Turner Status error; 942d37349f3SPavel Labath NativeRegisterContext& register_context = thread.GetRegisterContext(); 943e7708688STamas Berghammer 944d5b44036SJonas Devlieghere std::unique_ptr<EmulateInstruction> emulator_up( 945b9c1b51eSKate Stone EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, 946b9c1b51eSKate Stone nullptr)); 947e7708688STamas Berghammer 948d5b44036SJonas Devlieghere if (emulator_up == nullptr) 94997206d57SZachary Turner return Status("Instruction emulator not found!"); 950e7708688STamas Berghammer 951d37349f3SPavel Labath EmulatorBaton baton(*this, register_context); 952d5b44036SJonas Devlieghere emulator_up->SetBaton(&baton); 953d5b44036SJonas Devlieghere emulator_up->SetReadMemCallback(&ReadMemoryCallback); 954d5b44036SJonas Devlieghere emulator_up->SetReadRegCallback(&ReadRegisterCallback); 955d5b44036SJonas Devlieghere emulator_up->SetWriteMemCallback(&WriteMemoryCallback); 956d5b44036SJonas Devlieghere emulator_up->SetWriteRegCallback(&WriteRegisterCallback); 957e7708688STamas Berghammer 958d5b44036SJonas Devlieghere if (!emulator_up->ReadInstruction()) 95997206d57SZachary Turner return Status("Read instruction failed!"); 960e7708688STamas Berghammer 961b9c1b51eSKate Stone bool emulation_result = 962d5b44036SJonas Devlieghere emulator_up->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC); 9636648fcc3SPavel Labath 964d37349f3SPavel Labath const RegisterInfo *reg_info_pc = register_context.GetRegisterInfo( 965b9c1b51eSKate Stone eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC); 966d37349f3SPavel Labath const RegisterInfo *reg_info_flags = register_context.GetRegisterInfo( 967b9c1b51eSKate Stone eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS); 9686648fcc3SPavel Labath 969b9c1b51eSKate Stone auto pc_it = 970b9c1b51eSKate Stone baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]); 971b9c1b51eSKate Stone auto flags_it = 972b9c1b51eSKate Stone baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]); 9736648fcc3SPavel Labath 974e7708688STamas Berghammer lldb::addr_t next_pc; 975e7708688STamas Berghammer lldb::addr_t next_flags; 976b9c1b51eSKate Stone if (emulation_result) { 977b9c1b51eSKate Stone assert(pc_it != baton.m_register_values.end() && 978b9c1b51eSKate Stone "Emulation was successfull but PC wasn't updated"); 9796648fcc3SPavel Labath next_pc = pc_it->second.GetAsUInt64(); 9806648fcc3SPavel Labath 9816648fcc3SPavel Labath if (flags_it != baton.m_register_values.end()) 9826648fcc3SPavel Labath next_flags = flags_it->second.GetAsUInt64(); 983e7708688STamas Berghammer else 984d37349f3SPavel Labath next_flags = ReadFlags(register_context); 985b9c1b51eSKate Stone } else if (pc_it == baton.m_register_values.end()) { 98605097246SAdrian Prantl // Emulate instruction failed and it haven't changed PC. Advance PC with 98705097246SAdrian Prantl // the size of the current opcode because the emulation of all 988e7708688STamas Berghammer // PC modifying instruction should be successful. The failure most 989e7708688STamas Berghammer // likely caused by a not supported instruction which don't modify PC. 990d5b44036SJonas Devlieghere next_pc = register_context.GetPC() + emulator_up->GetOpcode().GetByteSize(); 991d37349f3SPavel Labath next_flags = ReadFlags(register_context); 992b9c1b51eSKate Stone } else { 993e7708688STamas Berghammer // The instruction emulation failed after it modified the PC. It is an 994e7708688STamas Berghammer // unknown error where we can't continue because the next instruction is 995e7708688STamas Berghammer // modifying the PC but we don't know how. 99697206d57SZachary Turner return Status("Instruction emulation failed unexpectedly."); 997e7708688STamas Berghammer } 998e7708688STamas Berghammer 999b9c1b51eSKate Stone if (m_arch.GetMachine() == llvm::Triple::arm) { 1000b9c1b51eSKate Stone if (next_flags & 0x20) { 1001e7708688STamas Berghammer // Thumb mode 1002e7708688STamas Berghammer error = SetSoftwareBreakpoint(next_pc, 2); 1003b9c1b51eSKate Stone } else { 1004e7708688STamas Berghammer // Arm mode 1005e7708688STamas Berghammer error = SetSoftwareBreakpoint(next_pc, 4); 1006e7708688STamas Berghammer } 10072f677ab0SFangrui Song } else if (m_arch.IsMIPS() || m_arch.GetTriple().isPPC64()) 1008cdc22a88SMohit K. Bhakkad error = SetSoftwareBreakpoint(next_pc, 4); 1009b9c1b51eSKate Stone else { 1010e7708688STamas Berghammer // No size hint is given for the next breakpoint 1011e7708688STamas Berghammer error = SetSoftwareBreakpoint(next_pc, 0); 1012e7708688STamas Berghammer } 1013e7708688STamas Berghammer 101405097246SAdrian Prantl // If setting the breakpoint fails because next_pc is out of the address 101505097246SAdrian Prantl // space, ignore it and let the debugee segfault. 101642eb6908SPavel Labath if (error.GetError() == EIO || error.GetError() == EFAULT) { 101797206d57SZachary Turner return Status(); 101842eb6908SPavel Labath } else if (error.Fail()) 1019e7708688STamas Berghammer return error; 1020e7708688STamas Berghammer 1021b9cc0c75SPavel Labath m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc}); 1022e7708688STamas Berghammer 102397206d57SZachary Turner return Status(); 1024e7708688STamas Berghammer } 1025e7708688STamas Berghammer 1026b9c1b51eSKate Stone bool NativeProcessLinux::SupportHardwareSingleStepping() const { 1027ddb93b63SFangrui Song if (m_arch.GetMachine() == llvm::Triple::arm || m_arch.IsMIPS()) 1028cdc22a88SMohit K. Bhakkad return false; 1029cdc22a88SMohit K. Bhakkad return true; 1030e7708688STamas Berghammer } 1031e7708688STamas Berghammer 103297206d57SZachary Turner Status NativeProcessLinux::Resume(const ResumeActionList &resume_actions) { 1033a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1034a6321a8eSPavel Labath LLDB_LOG(log, "pid {0}", GetID()); 1035af245d11STodd Fiala 1036e7708688STamas Berghammer bool software_single_step = !SupportHardwareSingleStepping(); 1037af245d11STodd Fiala 1038b9c1b51eSKate Stone if (software_single_step) { 1039a5be48b3SPavel Labath for (const auto &thread : m_threads) { 1040a5be48b3SPavel Labath assert(thread && "thread list should not contain NULL threads"); 1041e7708688STamas Berghammer 1042b9c1b51eSKate Stone const ResumeAction *const action = 1043a5be48b3SPavel Labath resume_actions.GetActionForThread(thread->GetID(), true); 1044e7708688STamas Berghammer if (action == nullptr) 1045e7708688STamas Berghammer continue; 1046e7708688STamas Berghammer 1047b9c1b51eSKate Stone if (action->state == eStateStepping) { 104897206d57SZachary Turner Status error = SetupSoftwareSingleStepping( 1049a5be48b3SPavel Labath static_cast<NativeThreadLinux &>(*thread)); 1050e7708688STamas Berghammer if (error.Fail()) 1051e7708688STamas Berghammer return error; 1052e7708688STamas Berghammer } 1053e7708688STamas Berghammer } 1054e7708688STamas Berghammer } 1055e7708688STamas Berghammer 1056a5be48b3SPavel Labath for (const auto &thread : m_threads) { 1057a5be48b3SPavel Labath assert(thread && "thread list should not contain NULL threads"); 1058af245d11STodd Fiala 1059b9c1b51eSKate Stone const ResumeAction *const action = 1060a5be48b3SPavel Labath resume_actions.GetActionForThread(thread->GetID(), true); 10616a196ce6SChaoren Lin 1062b9c1b51eSKate Stone if (action == nullptr) { 1063a6321a8eSPavel Labath LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(), 1064a5be48b3SPavel Labath thread->GetID()); 10656a196ce6SChaoren Lin continue; 10666a196ce6SChaoren Lin } 1067af245d11STodd Fiala 1068a6321a8eSPavel Labath LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}", 1069a5be48b3SPavel Labath action->state, GetID(), thread->GetID()); 1070af245d11STodd Fiala 1071b9c1b51eSKate Stone switch (action->state) { 1072af245d11STodd Fiala case eStateRunning: 1073b9c1b51eSKate Stone case eStateStepping: { 1074af245d11STodd Fiala // Run the thread, possibly feeding it the signal. 1075fa03ad2eSChaoren Lin const int signo = action->signal; 1076a5be48b3SPavel Labath ResumeThread(static_cast<NativeThreadLinux &>(*thread), action->state, 1077b9c1b51eSKate Stone signo); 1078af245d11STodd Fiala break; 1079ae29d395SChaoren Lin } 1080af245d11STodd Fiala 1081af245d11STodd Fiala case eStateSuspended: 1082af245d11STodd Fiala case eStateStopped: 1083a6321a8eSPavel Labath llvm_unreachable("Unexpected state"); 1084af245d11STodd Fiala 1085af245d11STodd Fiala default: 108697206d57SZachary Turner return Status("NativeProcessLinux::%s (): unexpected state %s specified " 1087b9c1b51eSKate Stone "for pid %" PRIu64 ", tid %" PRIu64, 1088b9c1b51eSKate Stone __FUNCTION__, StateAsCString(action->state), GetID(), 1089a5be48b3SPavel Labath thread->GetID()); 1090af245d11STodd Fiala } 1091af245d11STodd Fiala } 1092af245d11STodd Fiala 109397206d57SZachary Turner return Status(); 1094af245d11STodd Fiala } 1095af245d11STodd Fiala 109697206d57SZachary Turner Status NativeProcessLinux::Halt() { 109797206d57SZachary Turner Status error; 1098af245d11STodd Fiala 1099af245d11STodd Fiala if (kill(GetID(), SIGSTOP) != 0) 1100af245d11STodd Fiala error.SetErrorToErrno(); 1101af245d11STodd Fiala 1102af245d11STodd Fiala return error; 1103af245d11STodd Fiala } 1104af245d11STodd Fiala 110597206d57SZachary Turner Status NativeProcessLinux::Detach() { 110697206d57SZachary Turner Status error; 1107af245d11STodd Fiala 1108af245d11STodd Fiala // Stop monitoring the inferior. 110919cbe96aSPavel Labath m_sigchld_handle.reset(); 1110af245d11STodd Fiala 11117a9495bcSPavel Labath // Tell ptrace to detach from the process. 11127a9495bcSPavel Labath if (GetID() == LLDB_INVALID_PROCESS_ID) 11137a9495bcSPavel Labath return error; 11147a9495bcSPavel Labath 1115a5be48b3SPavel Labath for (const auto &thread : m_threads) { 1116a5be48b3SPavel Labath Status e = Detach(thread->GetID()); 11177a9495bcSPavel Labath if (e.Fail()) 1118b9c1b51eSKate Stone error = 1119b9c1b51eSKate Stone e; // Save the error, but still attempt to detach from other threads. 11207a9495bcSPavel Labath } 11217a9495bcSPavel Labath 112299e37695SRavitheja Addepally m_processor_trace_monitor.clear(); 112399e37695SRavitheja Addepally m_pt_proces_trace_id = LLDB_INVALID_UID; 112499e37695SRavitheja Addepally 1125af245d11STodd Fiala return error; 1126af245d11STodd Fiala } 1127af245d11STodd Fiala 112897206d57SZachary Turner Status NativeProcessLinux::Signal(int signo) { 112997206d57SZachary Turner Status error; 1130af245d11STodd Fiala 1131a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1132a6321a8eSPavel Labath LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo, 1133a6321a8eSPavel Labath Host::GetSignalAsCString(signo), GetID()); 1134af245d11STodd Fiala 1135af245d11STodd Fiala if (kill(GetID(), signo)) 1136af245d11STodd Fiala error.SetErrorToErrno(); 1137af245d11STodd Fiala 1138af245d11STodd Fiala return error; 1139af245d11STodd Fiala } 1140af245d11STodd Fiala 114197206d57SZachary Turner Status NativeProcessLinux::Interrupt() { 114205097246SAdrian Prantl // Pick a running thread (or if none, a not-dead stopped thread) as the 114305097246SAdrian Prantl // chosen thread that will be the stop-reason thread. 1144a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1145e9547b80SChaoren Lin 1146a5be48b3SPavel Labath NativeThreadProtocol *running_thread = nullptr; 1147a5be48b3SPavel Labath NativeThreadProtocol *stopped_thread = nullptr; 1148e9547b80SChaoren Lin 1149a6321a8eSPavel Labath LLDB_LOG(log, "selecting running thread for interrupt target"); 1150a5be48b3SPavel Labath for (const auto &thread : m_threads) { 115105097246SAdrian Prantl // If we have a running or stepping thread, we'll call that the target of 115205097246SAdrian Prantl // the interrupt. 1153a5be48b3SPavel Labath const auto thread_state = thread->GetState(); 1154b9c1b51eSKate Stone if (thread_state == eStateRunning || thread_state == eStateStepping) { 1155a5be48b3SPavel Labath running_thread = thread.get(); 1156e9547b80SChaoren Lin break; 1157a5be48b3SPavel Labath } else if (!stopped_thread && StateIsStoppedState(thread_state, true)) { 115805097246SAdrian Prantl // Remember the first non-dead stopped thread. We'll use that as a 115905097246SAdrian Prantl // backup if there are no running threads. 1160a5be48b3SPavel Labath stopped_thread = thread.get(); 1161e9547b80SChaoren Lin } 1162e9547b80SChaoren Lin } 1163e9547b80SChaoren Lin 1164a5be48b3SPavel Labath if (!running_thread && !stopped_thread) { 116597206d57SZachary Turner Status error("found no running/stepping or live stopped threads as target " 1166b9c1b51eSKate Stone "for interrupt"); 1167a6321a8eSPavel Labath LLDB_LOG(log, "skipping due to error: {0}", error); 11685830aa75STamas Berghammer 1169e9547b80SChaoren Lin return error; 1170e9547b80SChaoren Lin } 1171e9547b80SChaoren Lin 1172a5be48b3SPavel Labath NativeThreadProtocol *deferred_signal_thread = 1173a5be48b3SPavel Labath running_thread ? running_thread : stopped_thread; 1174e9547b80SChaoren Lin 1175a6321a8eSPavel Labath LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(), 1176a5be48b3SPavel Labath running_thread ? "running" : "stopped", 1177a5be48b3SPavel Labath deferred_signal_thread->GetID()); 1178e9547b80SChaoren Lin 1179a5be48b3SPavel Labath StopRunningThreads(deferred_signal_thread->GetID()); 118045f5cb31SPavel Labath 118197206d57SZachary Turner return Status(); 1182e9547b80SChaoren Lin } 1183e9547b80SChaoren Lin 118497206d57SZachary Turner Status NativeProcessLinux::Kill() { 1185a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1186a6321a8eSPavel Labath LLDB_LOG(log, "pid {0}", GetID()); 1187af245d11STodd Fiala 118897206d57SZachary Turner Status error; 1189af245d11STodd Fiala 1190b9c1b51eSKate Stone switch (m_state) { 1191af245d11STodd Fiala case StateType::eStateInvalid: 1192af245d11STodd Fiala case StateType::eStateExited: 1193af245d11STodd Fiala case StateType::eStateCrashed: 1194af245d11STodd Fiala case StateType::eStateDetached: 1195af245d11STodd Fiala case StateType::eStateUnloaded: 1196af245d11STodd Fiala // Nothing to do - the process is already dead. 1197a6321a8eSPavel Labath LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(), 11988198db30SPavel Labath m_state); 1199af245d11STodd Fiala return error; 1200af245d11STodd Fiala 1201af245d11STodd Fiala case StateType::eStateConnected: 1202af245d11STodd Fiala case StateType::eStateAttaching: 1203af245d11STodd Fiala case StateType::eStateLaunching: 1204af245d11STodd Fiala case StateType::eStateStopped: 1205af245d11STodd Fiala case StateType::eStateRunning: 1206af245d11STodd Fiala case StateType::eStateStepping: 1207af245d11STodd Fiala case StateType::eStateSuspended: 1208af245d11STodd Fiala // We can try to kill a process in these states. 1209af245d11STodd Fiala break; 1210af245d11STodd Fiala } 1211af245d11STodd Fiala 1212b9c1b51eSKate Stone if (kill(GetID(), SIGKILL) != 0) { 1213af245d11STodd Fiala error.SetErrorToErrno(); 1214af245d11STodd Fiala return error; 1215af245d11STodd Fiala } 1216af245d11STodd Fiala 1217af245d11STodd Fiala return error; 1218af245d11STodd Fiala } 1219af245d11STodd Fiala 122097206d57SZachary Turner Status NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr, 1221b9c1b51eSKate Stone MemoryRegionInfo &range_info) { 1222b9c1b51eSKate Stone // FIXME review that the final memory region returned extends to the end of 1223b9c1b51eSKate Stone // the virtual address space, 1224af245d11STodd Fiala // with no perms if it is not mapped. 1225af245d11STodd Fiala 122605097246SAdrian Prantl // Use an approach that reads memory regions from /proc/{pid}/maps. Assume 122705097246SAdrian Prantl // proc maps entries are in ascending order. 1228af245d11STodd Fiala // FIXME assert if we find differently. 1229af245d11STodd Fiala 1230b9c1b51eSKate Stone if (m_supports_mem_region == LazyBool::eLazyBoolNo) { 1231af245d11STodd Fiala // We're done. 123297206d57SZachary Turner return Status("unsupported"); 1233af245d11STodd Fiala } 1234af245d11STodd Fiala 123597206d57SZachary Turner Status error = PopulateMemoryRegionCache(); 1236b9c1b51eSKate Stone if (error.Fail()) { 1237af245d11STodd Fiala return error; 1238af245d11STodd Fiala } 1239af245d11STodd Fiala 1240af245d11STodd Fiala lldb::addr_t prev_base_address = 0; 1241af245d11STodd Fiala 1242b9c1b51eSKate Stone // FIXME start by finding the last region that is <= target address using 1243b9c1b51eSKate Stone // binary search. Data is sorted. 1244af245d11STodd Fiala // There can be a ton of regions on pthreads apps with lots of threads. 1245b9c1b51eSKate Stone for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end(); 1246b9c1b51eSKate Stone ++it) { 1247a6f5795aSTamas Berghammer MemoryRegionInfo &proc_entry_info = it->first; 1248af245d11STodd Fiala 1249af245d11STodd Fiala // Sanity check assumption that /proc/{pid}/maps entries are ascending. 1250b9c1b51eSKate Stone assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) && 1251b9c1b51eSKate Stone "descending /proc/pid/maps entries detected, unexpected"); 1252af245d11STodd Fiala prev_base_address = proc_entry_info.GetRange().GetRangeBase(); 1253b1554311SHafiz Abid Qadeer UNUSED_IF_ASSERT_DISABLED(prev_base_address); 1254af245d11STodd Fiala 1255b9c1b51eSKate Stone // If the target address comes before this entry, indicate distance to next 1256b9c1b51eSKate Stone // region. 1257b9c1b51eSKate Stone if (load_addr < proc_entry_info.GetRange().GetRangeBase()) { 1258af245d11STodd Fiala range_info.GetRange().SetRangeBase(load_addr); 1259b9c1b51eSKate Stone range_info.GetRange().SetByteSize( 1260b9c1b51eSKate Stone proc_entry_info.GetRange().GetRangeBase() - load_addr); 1261af245d11STodd Fiala range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo); 1262af245d11STodd Fiala range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo); 1263af245d11STodd Fiala range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo); 1264ad007563SHoward Hellyer range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo); 1265af245d11STodd Fiala 1266af245d11STodd Fiala return error; 1267b9c1b51eSKate Stone } else if (proc_entry_info.GetRange().Contains(load_addr)) { 1268af245d11STodd Fiala // The target address is within the memory region we're processing here. 1269af245d11STodd Fiala range_info = proc_entry_info; 1270af245d11STodd Fiala return error; 1271af245d11STodd Fiala } 1272af245d11STodd Fiala 1273b9c1b51eSKate Stone // The target memory address comes somewhere after the region we just 1274b9c1b51eSKate Stone // parsed. 1275af245d11STodd Fiala } 1276af245d11STodd Fiala 1277b9c1b51eSKate Stone // If we made it here, we didn't find an entry that contained the given 127805097246SAdrian Prantl // address. Return the load_addr as start and the amount of bytes betwwen 127905097246SAdrian Prantl // load address and the end of the memory as size. 128009839c33STamas Berghammer range_info.GetRange().SetRangeBase(load_addr); 1281ad007563SHoward Hellyer range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS); 128209839c33STamas Berghammer range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo); 128309839c33STamas Berghammer range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo); 128409839c33STamas Berghammer range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo); 1285ad007563SHoward Hellyer range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo); 1286af245d11STodd Fiala return error; 1287af245d11STodd Fiala } 1288af245d11STodd Fiala 128997206d57SZachary Turner Status NativeProcessLinux::PopulateMemoryRegionCache() { 1290a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1291a6f5795aSTamas Berghammer 1292a6f5795aSTamas Berghammer // If our cache is empty, pull the latest. There should always be at least 1293a6f5795aSTamas Berghammer // one memory region if memory region handling is supported. 1294a6f5795aSTamas Berghammer if (!m_mem_region_cache.empty()) { 1295a6321a8eSPavel Labath LLDB_LOG(log, "reusing {0} cached memory region entries", 1296a6321a8eSPavel Labath m_mem_region_cache.size()); 129797206d57SZachary Turner return Status(); 1298a6f5795aSTamas Berghammer } 1299a6f5795aSTamas Berghammer 130015930862SPavel Labath auto BufferOrError = getProcFile(GetID(), "maps"); 130115930862SPavel Labath if (!BufferOrError) { 130215930862SPavel Labath m_supports_mem_region = LazyBool::eLazyBoolNo; 130315930862SPavel Labath return BufferOrError.getError(); 130415930862SPavel Labath } 1305c8e364e8SPavel Labath Status Result; 1306c8e364e8SPavel Labath ParseLinuxMapRegions(BufferOrError.get()->getBuffer(), 1307c8e364e8SPavel Labath [&](const MemoryRegionInfo &Info, const Status &ST) { 1308c8e364e8SPavel Labath if (ST.Success()) { 1309c8e364e8SPavel Labath FileSpec file_spec(Info.GetName().GetCString()); 13108f3be7a3SJonas Devlieghere FileSystem::Instance().Resolve(file_spec); 1311c8e364e8SPavel Labath m_mem_region_cache.emplace_back(Info, file_spec); 1312c8e364e8SPavel Labath return true; 1313c8e364e8SPavel Labath } else { 1314c8e364e8SPavel Labath m_supports_mem_region = LazyBool::eLazyBoolNo; 1315c8e364e8SPavel Labath LLDB_LOG(log, "failed to parse proc maps: {0}", ST); 1316c8e364e8SPavel Labath Result = ST; 1317c8e364e8SPavel Labath return false; 1318a6f5795aSTamas Berghammer } 1319c8e364e8SPavel Labath }); 1320c8e364e8SPavel Labath if (Result.Fail()) 1321c8e364e8SPavel Labath return Result; 1322a6f5795aSTamas Berghammer 132315930862SPavel Labath if (m_mem_region_cache.empty()) { 1324a6f5795aSTamas Berghammer // No entries after attempting to read them. This shouldn't happen if 132505097246SAdrian Prantl // /proc/{pid}/maps is supported. Assume we don't support map entries via 132605097246SAdrian Prantl // procfs. 132715930862SPavel Labath m_supports_mem_region = LazyBool::eLazyBoolNo; 1328a6321a8eSPavel Labath LLDB_LOG(log, 1329a6321a8eSPavel Labath "failed to find any procfs maps entries, assuming no support " 1330a6321a8eSPavel Labath "for memory region metadata retrieval"); 133197206d57SZachary Turner return Status("not supported"); 1332a6f5795aSTamas Berghammer } 1333a6f5795aSTamas Berghammer 1334a6321a8eSPavel Labath LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps", 1335a6321a8eSPavel Labath m_mem_region_cache.size(), GetID()); 1336a6f5795aSTamas Berghammer 1337a6f5795aSTamas Berghammer // We support memory retrieval, remember that. 1338a6f5795aSTamas Berghammer m_supports_mem_region = LazyBool::eLazyBoolYes; 133997206d57SZachary Turner return Status(); 1340a6f5795aSTamas Berghammer } 1341a6f5795aSTamas Berghammer 1342b9c1b51eSKate Stone void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) { 1343a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1344a6321a8eSPavel Labath LLDB_LOG(log, "newBumpId={0}", newBumpId); 1345a6321a8eSPavel Labath LLDB_LOG(log, "clearing {0} entries from memory region cache", 1346a6321a8eSPavel Labath m_mem_region_cache.size()); 1347af245d11STodd Fiala m_mem_region_cache.clear(); 1348af245d11STodd Fiala } 1349af245d11STodd Fiala 135097206d57SZachary Turner Status NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, 1351b9c1b51eSKate Stone lldb::addr_t &addr) { 1352af245d11STodd Fiala // FIXME implementing this requires the equivalent of 135305097246SAdrian Prantl // InferiorCallPOSIX::InferiorCallMmap, which depends on functional ThreadPlans 135405097246SAdrian Prantl // working with Native*Protocol. 1355af245d11STodd Fiala #if 1 135697206d57SZachary Turner return Status("not implemented yet"); 1357af245d11STodd Fiala #else 1358af245d11STodd Fiala addr = LLDB_INVALID_ADDRESS; 1359af245d11STodd Fiala 1360af245d11STodd Fiala unsigned prot = 0; 1361af245d11STodd Fiala if (permissions & lldb::ePermissionsReadable) 1362af245d11STodd Fiala prot |= eMmapProtRead; 1363af245d11STodd Fiala if (permissions & lldb::ePermissionsWritable) 1364af245d11STodd Fiala prot |= eMmapProtWrite; 1365af245d11STodd Fiala if (permissions & lldb::ePermissionsExecutable) 1366af245d11STodd Fiala prot |= eMmapProtExec; 1367af245d11STodd Fiala 1368af245d11STodd Fiala // TODO implement this directly in NativeProcessLinux 136905097246SAdrian Prantl // (and lift to NativeProcessPOSIX if/when that class is refactored out). 1370af245d11STodd Fiala if (InferiorCallMmap(this, addr, 0, size, prot, 1371af245d11STodd Fiala eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) { 1372af245d11STodd Fiala m_addr_to_mmap_size[addr] = size; 137397206d57SZachary Turner return Status(); 1374af245d11STodd Fiala } else { 1375af245d11STodd Fiala addr = LLDB_INVALID_ADDRESS; 137697206d57SZachary Turner return Status("unable to allocate %" PRIu64 1377b9c1b51eSKate Stone " bytes of memory with permissions %s", 1378b9c1b51eSKate Stone size, GetPermissionsAsCString(permissions)); 1379af245d11STodd Fiala } 1380af245d11STodd Fiala #endif 1381af245d11STodd Fiala } 1382af245d11STodd Fiala 138397206d57SZachary Turner Status NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) { 1384af245d11STodd Fiala // FIXME see comments in AllocateMemory - required lower-level 1385af245d11STodd Fiala // bits not in place yet (ThreadPlans) 138697206d57SZachary Turner return Status("not implemented"); 1387af245d11STodd Fiala } 1388af245d11STodd Fiala 1389b9c1b51eSKate Stone size_t NativeProcessLinux::UpdateThreads() { 139005097246SAdrian Prantl // The NativeProcessLinux monitoring threads are always up to date with 139105097246SAdrian Prantl // respect to thread state and they keep the thread list populated properly. 139205097246SAdrian Prantl // All this method needs to do is return the thread count. 1393af245d11STodd Fiala return m_threads.size(); 1394af245d11STodd Fiala } 1395af245d11STodd Fiala 139697206d57SZachary Turner Status NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size, 1397b9c1b51eSKate Stone bool hardware) { 1398af245d11STodd Fiala if (hardware) 1399d5ffbad2SOmair Javaid return SetHardwareBreakpoint(addr, size); 1400af245d11STodd Fiala else 1401af245d11STodd Fiala return SetSoftwareBreakpoint(addr, size); 1402af245d11STodd Fiala } 1403af245d11STodd Fiala 140497206d57SZachary Turner Status NativeProcessLinux::RemoveBreakpoint(lldb::addr_t addr, bool hardware) { 1405d5ffbad2SOmair Javaid if (hardware) 1406d5ffbad2SOmair Javaid return RemoveHardwareBreakpoint(addr); 1407d5ffbad2SOmair Javaid else 1408d5ffbad2SOmair Javaid return NativeProcessProtocol::RemoveBreakpoint(addr); 1409d5ffbad2SOmair Javaid } 1410d5ffbad2SOmair Javaid 1411f8b825f6SPavel Labath llvm::Expected<llvm::ArrayRef<uint8_t>> 1412f8b825f6SPavel Labath NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(size_t size_hint) { 1413be379e15STamas Berghammer // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the 1414be379e15STamas Berghammer // linux kernel does otherwise. 1415f8b825f6SPavel Labath static const uint8_t g_arm_opcode[] = {0xf0, 0x01, 0xf0, 0xe7}; 1416f8b825f6SPavel Labath static const uint8_t g_thumb_opcode[] = {0x01, 0xde}; 141712286a27SPavel Labath 1418f8b825f6SPavel Labath switch (GetArchitecture().GetMachine()) { 141912286a27SPavel Labath case llvm::Triple::arm: 1420f8b825f6SPavel Labath switch (size_hint) { 142163c8be95STamas Berghammer case 2: 14224f545074SPavel Labath return llvm::makeArrayRef(g_thumb_opcode); 142363c8be95STamas Berghammer case 4: 14244f545074SPavel Labath return llvm::makeArrayRef(g_arm_opcode); 142563c8be95STamas Berghammer default: 1426f8b825f6SPavel Labath return llvm::createStringError(llvm::inconvertibleErrorCode(), 1427f8b825f6SPavel Labath "Unrecognised trap opcode size hint!"); 142863c8be95STamas Berghammer } 1429af245d11STodd Fiala default: 1430f8b825f6SPavel Labath return NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_hint); 1431af245d11STodd Fiala } 1432af245d11STodd Fiala } 1433af245d11STodd Fiala 143497206d57SZachary Turner Status NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size, 1435b9c1b51eSKate Stone size_t &bytes_read) { 1436df7c6995SPavel Labath if (ProcessVmReadvSupported()) { 1437b9c1b51eSKate Stone // The process_vm_readv path is about 50 times faster than ptrace api. We 143805097246SAdrian Prantl // want to use this syscall if it is supported. 1439df7c6995SPavel Labath 1440df7c6995SPavel Labath const ::pid_t pid = GetID(); 1441df7c6995SPavel Labath 1442df7c6995SPavel Labath struct iovec local_iov, remote_iov; 1443df7c6995SPavel Labath local_iov.iov_base = buf; 1444df7c6995SPavel Labath local_iov.iov_len = size; 1445df7c6995SPavel Labath remote_iov.iov_base = reinterpret_cast<void *>(addr); 1446df7c6995SPavel Labath remote_iov.iov_len = size; 1447df7c6995SPavel Labath 1448df7c6995SPavel Labath bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0); 1449df7c6995SPavel Labath const bool success = bytes_read == size; 1450df7c6995SPavel Labath 1451a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1452a6321a8eSPavel Labath LLDB_LOG(log, 1453a6321a8eSPavel Labath "using process_vm_readv to read {0} bytes from inferior " 1454a6321a8eSPavel Labath "address {1:x}: {2}", 145510c41f37SPavel Labath size, addr, success ? "Success" : llvm::sys::StrError(errno)); 1456df7c6995SPavel Labath 1457df7c6995SPavel Labath if (success) 145897206d57SZachary Turner return Status(); 1459a6321a8eSPavel Labath // else the call failed for some reason, let's retry the read using ptrace 1460b9c1b51eSKate Stone // api. 1461df7c6995SPavel Labath } 1462df7c6995SPavel Labath 146319cbe96aSPavel Labath unsigned char *dst = static_cast<unsigned char *>(buf); 146419cbe96aSPavel Labath size_t remainder; 146519cbe96aSPavel Labath long data; 146619cbe96aSPavel Labath 1467a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY)); 1468a6321a8eSPavel Labath LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size); 146919cbe96aSPavel Labath 1470b9c1b51eSKate Stone for (bytes_read = 0; bytes_read < size; bytes_read += remainder) { 147197206d57SZachary Turner Status error = NativeProcessLinux::PtraceWrapper( 1472b9c1b51eSKate Stone PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data); 1473a6321a8eSPavel Labath if (error.Fail()) 147419cbe96aSPavel Labath return error; 147519cbe96aSPavel Labath 147619cbe96aSPavel Labath remainder = size - bytes_read; 147719cbe96aSPavel Labath remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder; 147819cbe96aSPavel Labath 147919cbe96aSPavel Labath // Copy the data into our buffer 1480f6ef187bSMohit K. Bhakkad memcpy(dst, &data, remainder); 148119cbe96aSPavel Labath 1482a6321a8eSPavel Labath LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data); 148319cbe96aSPavel Labath addr += k_ptrace_word_size; 148419cbe96aSPavel Labath dst += k_ptrace_word_size; 148519cbe96aSPavel Labath } 148697206d57SZachary Turner return Status(); 1487af245d11STodd Fiala } 1488af245d11STodd Fiala 148997206d57SZachary Turner Status NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, 1490b9c1b51eSKate Stone size_t size, size_t &bytes_written) { 149119cbe96aSPavel Labath const unsigned char *src = static_cast<const unsigned char *>(buf); 149219cbe96aSPavel Labath size_t remainder; 149397206d57SZachary Turner Status error; 149419cbe96aSPavel Labath 1495a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY)); 1496a6321a8eSPavel Labath LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size); 149719cbe96aSPavel Labath 1498b9c1b51eSKate Stone for (bytes_written = 0; bytes_written < size; bytes_written += remainder) { 149919cbe96aSPavel Labath remainder = size - bytes_written; 150019cbe96aSPavel Labath remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder; 150119cbe96aSPavel Labath 1502b9c1b51eSKate Stone if (remainder == k_ptrace_word_size) { 150319cbe96aSPavel Labath unsigned long data = 0; 1504f6ef187bSMohit K. Bhakkad memcpy(&data, src, k_ptrace_word_size); 150519cbe96aSPavel Labath 1506a6321a8eSPavel Labath LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data); 1507b9c1b51eSKate Stone error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(), 1508b9c1b51eSKate Stone (void *)addr, (void *)data); 1509a6321a8eSPavel Labath if (error.Fail()) 151019cbe96aSPavel Labath return error; 1511b9c1b51eSKate Stone } else { 151219cbe96aSPavel Labath unsigned char buff[8]; 151319cbe96aSPavel Labath size_t bytes_read; 151419cbe96aSPavel Labath error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read); 1515a6321a8eSPavel Labath if (error.Fail()) 151619cbe96aSPavel Labath return error; 151719cbe96aSPavel Labath 151819cbe96aSPavel Labath memcpy(buff, src, remainder); 151919cbe96aSPavel Labath 152019cbe96aSPavel Labath size_t bytes_written_rec; 152119cbe96aSPavel Labath error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec); 1522a6321a8eSPavel Labath if (error.Fail()) 152319cbe96aSPavel Labath return error; 152419cbe96aSPavel Labath 1525a6321a8eSPavel Labath LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src, 1526b9c1b51eSKate Stone *(unsigned long *)buff); 152719cbe96aSPavel Labath } 152819cbe96aSPavel Labath 152919cbe96aSPavel Labath addr += k_ptrace_word_size; 153019cbe96aSPavel Labath src += k_ptrace_word_size; 153119cbe96aSPavel Labath } 153219cbe96aSPavel Labath return error; 1533af245d11STodd Fiala } 1534af245d11STodd Fiala 153597206d57SZachary Turner Status NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) { 153619cbe96aSPavel Labath return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo); 1537af245d11STodd Fiala } 1538af245d11STodd Fiala 153997206d57SZachary Turner Status NativeProcessLinux::GetEventMessage(lldb::tid_t tid, 1540b9c1b51eSKate Stone unsigned long *message) { 154119cbe96aSPavel Labath return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message); 1542af245d11STodd Fiala } 1543af245d11STodd Fiala 154497206d57SZachary Turner Status NativeProcessLinux::Detach(lldb::tid_t tid) { 154597ccc294SChaoren Lin if (tid == LLDB_INVALID_THREAD_ID) 154697206d57SZachary Turner return Status(); 154797ccc294SChaoren Lin 154819cbe96aSPavel Labath return PtraceWrapper(PTRACE_DETACH, tid); 1549af245d11STodd Fiala } 1550af245d11STodd Fiala 1551b9c1b51eSKate Stone bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) { 1552a5be48b3SPavel Labath for (const auto &thread : m_threads) { 1553a5be48b3SPavel Labath assert(thread && "thread list should not contain NULL threads"); 1554a5be48b3SPavel Labath if (thread->GetID() == thread_id) { 1555af245d11STodd Fiala // We have this thread. 1556af245d11STodd Fiala return true; 1557af245d11STodd Fiala } 1558af245d11STodd Fiala } 1559af245d11STodd Fiala 1560af245d11STodd Fiala // We don't have this thread. 1561af245d11STodd Fiala return false; 1562af245d11STodd Fiala } 1563af245d11STodd Fiala 1564b9c1b51eSKate Stone bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) { 1565a6321a8eSPavel Labath Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD); 1566a6321a8eSPavel Labath LLDB_LOG(log, "tid: {0})", thread_id); 15671dbc6c9cSPavel Labath 15681dbc6c9cSPavel Labath bool found = false; 1569b9c1b51eSKate Stone for (auto it = m_threads.begin(); it != m_threads.end(); ++it) { 1570b9c1b51eSKate Stone if (*it && ((*it)->GetID() == thread_id)) { 1571af245d11STodd Fiala m_threads.erase(it); 15721dbc6c9cSPavel Labath found = true; 15731dbc6c9cSPavel Labath break; 1574af245d11STodd Fiala } 1575af245d11STodd Fiala } 1576af245d11STodd Fiala 157799e37695SRavitheja Addepally if (found) 157899e37695SRavitheja Addepally StopTracingForThread(thread_id); 15799eb1ecb9SPavel Labath SignalIfAllThreadsStopped(); 15801dbc6c9cSPavel Labath return found; 1581af245d11STodd Fiala } 1582af245d11STodd Fiala 1583a5be48b3SPavel Labath NativeThreadLinux &NativeProcessLinux::AddThread(lldb::tid_t thread_id) { 1584a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD)); 1585a6321a8eSPavel Labath LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id); 1586af245d11STodd Fiala 1587b9c1b51eSKate Stone assert(!HasThreadNoLock(thread_id) && 1588b9c1b51eSKate Stone "attempted to add a thread by id that already exists"); 1589af245d11STodd Fiala 1590af245d11STodd Fiala // If this is the first thread, save it as the current thread 1591af245d11STodd Fiala if (m_threads.empty()) 1592af245d11STodd Fiala SetCurrentThreadID(thread_id); 1593af245d11STodd Fiala 1594a8f3ae7cSJonas Devlieghere m_threads.push_back(std::make_unique<NativeThreadLinux>(*this, thread_id)); 159599e37695SRavitheja Addepally 159699e37695SRavitheja Addepally if (m_pt_proces_trace_id != LLDB_INVALID_UID) { 159799e37695SRavitheja Addepally auto traceMonitor = ProcessorTraceMonitor::Create( 159899e37695SRavitheja Addepally GetID(), thread_id, m_pt_process_trace_config, true); 159999e37695SRavitheja Addepally if (traceMonitor) { 160099e37695SRavitheja Addepally m_pt_traced_thread_group.insert(thread_id); 160199e37695SRavitheja Addepally m_processor_trace_monitor.insert( 160299e37695SRavitheja Addepally std::make_pair(thread_id, std::move(*traceMonitor))); 160399e37695SRavitheja Addepally } else { 160499e37695SRavitheja Addepally LLDB_LOG(log, "failed to start trace on thread {0}", thread_id); 160599e37695SRavitheja Addepally Status error(traceMonitor.takeError()); 160699e37695SRavitheja Addepally LLDB_LOG(log, "error {0}", error); 160799e37695SRavitheja Addepally } 160899e37695SRavitheja Addepally } 160999e37695SRavitheja Addepally 1610a5be48b3SPavel Labath return static_cast<NativeThreadLinux &>(*m_threads.back()); 1611af245d11STodd Fiala } 1612af245d11STodd Fiala 161397206d57SZachary Turner Status NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path, 1614b9c1b51eSKate Stone FileSpec &file_spec) { 161597206d57SZachary Turner Status error = PopulateMemoryRegionCache(); 1616a6f5795aSTamas Berghammer if (error.Fail()) 1617a6f5795aSTamas Berghammer return error; 1618a6f5795aSTamas Berghammer 16198f3be7a3SJonas Devlieghere FileSpec module_file_spec(module_path); 16208f3be7a3SJonas Devlieghere FileSystem::Instance().Resolve(module_file_spec); 16217cb18bf5STamas Berghammer 16227cb18bf5STamas Berghammer file_spec.Clear(); 1623a6f5795aSTamas Berghammer for (const auto &it : m_mem_region_cache) { 1624a6f5795aSTamas Berghammer if (it.second.GetFilename() == module_file_spec.GetFilename()) { 1625a6f5795aSTamas Berghammer file_spec = it.second; 162697206d57SZachary Turner return Status(); 1627a6f5795aSTamas Berghammer } 1628a6f5795aSTamas Berghammer } 162997206d57SZachary Turner return Status("Module file (%s) not found in /proc/%" PRIu64 "/maps file!", 16307cb18bf5STamas Berghammer module_file_spec.GetFilename().AsCString(), GetID()); 16317cb18bf5STamas Berghammer } 1632c076559aSPavel Labath 163397206d57SZachary Turner Status NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name, 1634b9c1b51eSKate Stone lldb::addr_t &load_addr) { 1635783bfc8cSTamas Berghammer load_addr = LLDB_INVALID_ADDRESS; 163697206d57SZachary Turner Status error = PopulateMemoryRegionCache(); 1637a6f5795aSTamas Berghammer if (error.Fail()) 1638783bfc8cSTamas Berghammer return error; 1639a6f5795aSTamas Berghammer 16408f3be7a3SJonas Devlieghere FileSpec file(file_name); 1641a6f5795aSTamas Berghammer for (const auto &it : m_mem_region_cache) { 1642a6f5795aSTamas Berghammer if (it.second == file) { 1643a6f5795aSTamas Berghammer load_addr = it.first.GetRange().GetRangeBase(); 164497206d57SZachary Turner return Status(); 1645a6f5795aSTamas Berghammer } 1646a6f5795aSTamas Berghammer } 164797206d57SZachary Turner return Status("No load address found for specified file."); 1648783bfc8cSTamas Berghammer } 1649783bfc8cSTamas Berghammer 1650a5be48b3SPavel Labath NativeThreadLinux *NativeProcessLinux::GetThreadByID(lldb::tid_t tid) { 1651a5be48b3SPavel Labath return static_cast<NativeThreadLinux *>( 1652b9c1b51eSKate Stone NativeProcessProtocol::GetThreadByID(tid)); 1653f9077782SPavel Labath } 1654f9077782SPavel Labath 165597206d57SZachary Turner Status NativeProcessLinux::ResumeThread(NativeThreadLinux &thread, 1656b9c1b51eSKate Stone lldb::StateType state, int signo) { 1657a6321a8eSPavel Labath Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD); 1658a6321a8eSPavel Labath LLDB_LOG(log, "tid: {0}", thread.GetID()); 1659c076559aSPavel Labath 166005097246SAdrian Prantl // Before we do the resume below, first check if we have a pending stop 166105097246SAdrian Prantl // notification that is currently waiting for all threads to stop. This is 166205097246SAdrian Prantl // potentially a buggy situation since we're ostensibly waiting for threads 166305097246SAdrian Prantl // to stop before we send out the pending notification, and here we are 166405097246SAdrian Prantl // resuming one before we send out the pending stop notification. 1665a6321a8eSPavel Labath if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) { 1666a6321a8eSPavel Labath LLDB_LOG(log, 1667a6321a8eSPavel Labath "about to resume tid {0} per explicit request but we have a " 1668a6321a8eSPavel Labath "pending stop notification (tid {1}) that is actively " 1669a6321a8eSPavel Labath "waiting for this thread to stop. Valid sequence of events?", 1670a6321a8eSPavel Labath thread.GetID(), m_pending_notification_tid); 1671c076559aSPavel Labath } 1672c076559aSPavel Labath 167305097246SAdrian Prantl // Request a resume. We expect this to be synchronous and the system to 167405097246SAdrian Prantl // reflect it is running after this completes. 1675b9c1b51eSKate Stone switch (state) { 1676b9c1b51eSKate Stone case eStateRunning: { 1677605b51b8SPavel Labath const auto resume_result = thread.Resume(signo); 16780e1d729bSPavel Labath if (resume_result.Success()) 16790e1d729bSPavel Labath SetState(eStateRunning, true); 16800e1d729bSPavel Labath return resume_result; 1681c076559aSPavel Labath } 1682b9c1b51eSKate Stone case eStateStepping: { 1683605b51b8SPavel Labath const auto step_result = thread.SingleStep(signo); 16840e1d729bSPavel Labath if (step_result.Success()) 16850e1d729bSPavel Labath SetState(eStateRunning, true); 16860e1d729bSPavel Labath return step_result; 16870e1d729bSPavel Labath } 16880e1d729bSPavel Labath default: 16898198db30SPavel Labath LLDB_LOG(log, "Unhandled state {0}.", state); 16900e1d729bSPavel Labath llvm_unreachable("Unhandled state for resume"); 16910e1d729bSPavel Labath } 1692c076559aSPavel Labath } 1693c076559aSPavel Labath 1694c076559aSPavel Labath //===----------------------------------------------------------------------===// 1695c076559aSPavel Labath 1696b9c1b51eSKate Stone void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) { 1697a6321a8eSPavel Labath Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD); 1698a6321a8eSPavel Labath LLDB_LOG(log, "about to process event: (triggering_tid: {0})", 1699a6321a8eSPavel Labath triggering_tid); 1700c076559aSPavel Labath 17010e1d729bSPavel Labath m_pending_notification_tid = triggering_tid; 17020e1d729bSPavel Labath 170305097246SAdrian Prantl // Request a stop for all the thread stops that need to be stopped and are 170405097246SAdrian Prantl // not already known to be stopped. 1705a5be48b3SPavel Labath for (const auto &thread : m_threads) { 1706a5be48b3SPavel Labath if (StateIsRunningState(thread->GetState())) 1707a5be48b3SPavel Labath static_cast<NativeThreadLinux *>(thread.get())->RequestStop(); 17080e1d729bSPavel Labath } 17090e1d729bSPavel Labath 17100e1d729bSPavel Labath SignalIfAllThreadsStopped(); 1711a6321a8eSPavel Labath LLDB_LOG(log, "event processing done"); 1712c076559aSPavel Labath } 1713c076559aSPavel Labath 1714b9c1b51eSKate Stone void NativeProcessLinux::SignalIfAllThreadsStopped() { 17150e1d729bSPavel Labath if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID) 17160e1d729bSPavel Labath return; // No pending notification. Nothing to do. 17170e1d729bSPavel Labath 1718b9c1b51eSKate Stone for (const auto &thread_sp : m_threads) { 17190e1d729bSPavel Labath if (StateIsRunningState(thread_sp->GetState())) 17200e1d729bSPavel Labath return; // Some threads are still running. Don't signal yet. 17210e1d729bSPavel Labath } 17220e1d729bSPavel Labath 17230e1d729bSPavel Labath // We have a pending notification and all threads have stopped. 1724b9c1b51eSKate Stone Log *log( 1725b9c1b51eSKate Stone GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS)); 17269eb1ecb9SPavel Labath 1727b9c1b51eSKate Stone // Clear any temporary breakpoints we used to implement software single 1728b9c1b51eSKate Stone // stepping. 1729b9c1b51eSKate Stone for (const auto &thread_info : m_threads_stepping_with_breakpoint) { 173097206d57SZachary Turner Status error = RemoveBreakpoint(thread_info.second); 17319eb1ecb9SPavel Labath if (error.Fail()) 1732a6321a8eSPavel Labath LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}", 1733a6321a8eSPavel Labath thread_info.first, error); 17349eb1ecb9SPavel Labath } 17359eb1ecb9SPavel Labath m_threads_stepping_with_breakpoint.clear(); 17369eb1ecb9SPavel Labath 17379eb1ecb9SPavel Labath // Notify the delegate about the stop 17380e1d729bSPavel Labath SetCurrentThreadID(m_pending_notification_tid); 1739ed89c7feSPavel Labath SetState(StateType::eStateStopped, true); 17400e1d729bSPavel Labath m_pending_notification_tid = LLDB_INVALID_THREAD_ID; 1741c076559aSPavel Labath } 1742c076559aSPavel Labath 1743b9c1b51eSKate Stone void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) { 1744a6321a8eSPavel Labath Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD); 1745a6321a8eSPavel Labath LLDB_LOG(log, "tid: {0}", thread.GetID()); 17461dbc6c9cSPavel Labath 1747b9c1b51eSKate Stone if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID && 1748b9c1b51eSKate Stone StateIsRunningState(thread.GetState())) { 1749b9c1b51eSKate Stone // We will need to wait for this new thread to stop as well before firing 175005097246SAdrian Prantl // the notification. 1751f9077782SPavel Labath thread.RequestStop(); 1752c076559aSPavel Labath } 1753c076559aSPavel Labath } 1754068f8a7eSTamas Berghammer 1755b9c1b51eSKate Stone void NativeProcessLinux::SigchldHandler() { 1756a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 175719cbe96aSPavel Labath // Process all pending waitpid notifications. 1758b9c1b51eSKate Stone while (true) { 175919cbe96aSPavel Labath int status = -1; 1760c1a6b128SPavel Labath ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, -1, &status, 1761c1a6b128SPavel Labath __WALL | __WNOTHREAD | WNOHANG); 176219cbe96aSPavel Labath 176319cbe96aSPavel Labath if (wait_pid == 0) 176419cbe96aSPavel Labath break; // We are done. 176519cbe96aSPavel Labath 1766b9c1b51eSKate Stone if (wait_pid == -1) { 176797206d57SZachary Turner Status error(errno, eErrorTypePOSIX); 1768a6321a8eSPavel Labath LLDB_LOG(log, "waitpid (-1, &status, _) failed: {0}", error); 176919cbe96aSPavel Labath break; 177019cbe96aSPavel Labath } 177119cbe96aSPavel Labath 17723508fc8cSPavel Labath WaitStatus wait_status = WaitStatus::Decode(status); 17733508fc8cSPavel Labath bool exited = wait_status.type == WaitStatus::Exit || 17743508fc8cSPavel Labath (wait_status.type == WaitStatus::Signal && 17753508fc8cSPavel Labath wait_pid == static_cast<::pid_t>(GetID())); 177619cbe96aSPavel Labath 17773508fc8cSPavel Labath LLDB_LOG( 17783508fc8cSPavel Labath log, 17793508fc8cSPavel Labath "waitpid (-1, &status, _) => pid = {0}, status = {1}, exited = {2}", 17803508fc8cSPavel Labath wait_pid, wait_status, exited); 178119cbe96aSPavel Labath 17823508fc8cSPavel Labath MonitorCallback(wait_pid, exited, wait_status); 178319cbe96aSPavel Labath } 1784068f8a7eSTamas Berghammer } 1785068f8a7eSTamas Berghammer 178605097246SAdrian Prantl // Wrapper for ptrace to catch errors and log calls. Note that ptrace sets 178705097246SAdrian Prantl // errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*) 178897206d57SZachary Turner Status NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr, 1789b9c1b51eSKate Stone void *data, size_t data_size, 1790b9c1b51eSKate Stone long *result) { 179197206d57SZachary Turner Status error; 17924a9babb2SPavel Labath long int ret; 1793068f8a7eSTamas Berghammer 1794068f8a7eSTamas Berghammer Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 1795068f8a7eSTamas Berghammer 1796068f8a7eSTamas Berghammer PtraceDisplayBytes(req, data, data_size); 1797068f8a7eSTamas Berghammer 1798068f8a7eSTamas Berghammer errno = 0; 1799068f8a7eSTamas Berghammer if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET) 1800b9c1b51eSKate Stone ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid), 1801b9c1b51eSKate Stone *(unsigned int *)addr, data); 1802068f8a7eSTamas Berghammer else 1803b9c1b51eSKate Stone ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid), 1804b9c1b51eSKate Stone addr, data); 1805068f8a7eSTamas Berghammer 18064a9babb2SPavel Labath if (ret == -1) 1807068f8a7eSTamas Berghammer error.SetErrorToErrno(); 1808068f8a7eSTamas Berghammer 18094a9babb2SPavel Labath if (result) 18104a9babb2SPavel Labath *result = ret; 18114a9babb2SPavel Labath 181228096200SPavel Labath LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data, 181328096200SPavel Labath data_size, ret); 1814068f8a7eSTamas Berghammer 1815068f8a7eSTamas Berghammer PtraceDisplayBytes(req, data, data_size); 1816068f8a7eSTamas Berghammer 1817a6321a8eSPavel Labath if (error.Fail()) 1818a6321a8eSPavel Labath LLDB_LOG(log, "ptrace() failed: {0}", error); 1819068f8a7eSTamas Berghammer 18204a9babb2SPavel Labath return error; 1821068f8a7eSTamas Berghammer } 182299e37695SRavitheja Addepally 182399e37695SRavitheja Addepally llvm::Expected<ProcessorTraceMonitor &> 182499e37695SRavitheja Addepally NativeProcessLinux::LookupProcessorTraceInstance(lldb::user_id_t traceid, 182599e37695SRavitheja Addepally lldb::tid_t thread) { 182699e37695SRavitheja Addepally Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 182799e37695SRavitheja Addepally if (thread == LLDB_INVALID_THREAD_ID && traceid == m_pt_proces_trace_id) { 182899e37695SRavitheja Addepally LLDB_LOG(log, "thread not specified: {0}", traceid); 182999e37695SRavitheja Addepally return Status("tracing not active thread not specified").ToError(); 183099e37695SRavitheja Addepally } 183199e37695SRavitheja Addepally 183299e37695SRavitheja Addepally for (auto& iter : m_processor_trace_monitor) { 183399e37695SRavitheja Addepally if (traceid == iter.second->GetTraceID() && 183499e37695SRavitheja Addepally (thread == iter.first || thread == LLDB_INVALID_THREAD_ID)) 183599e37695SRavitheja Addepally return *(iter.second); 183699e37695SRavitheja Addepally } 183799e37695SRavitheja Addepally 183899e37695SRavitheja Addepally LLDB_LOG(log, "traceid not being traced: {0}", traceid); 183999e37695SRavitheja Addepally return Status("tracing not active for this thread").ToError(); 184099e37695SRavitheja Addepally } 184199e37695SRavitheja Addepally 184299e37695SRavitheja Addepally Status NativeProcessLinux::GetMetaData(lldb::user_id_t traceid, 184399e37695SRavitheja Addepally lldb::tid_t thread, 184499e37695SRavitheja Addepally llvm::MutableArrayRef<uint8_t> &buffer, 184599e37695SRavitheja Addepally size_t offset) { 184699e37695SRavitheja Addepally TraceOptions trace_options; 184799e37695SRavitheja Addepally Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 184899e37695SRavitheja Addepally Status error; 184999e37695SRavitheja Addepally 185099e37695SRavitheja Addepally LLDB_LOG(log, "traceid {0}", traceid); 185199e37695SRavitheja Addepally 185299e37695SRavitheja Addepally auto perf_monitor = LookupProcessorTraceInstance(traceid, thread); 185399e37695SRavitheja Addepally if (!perf_monitor) { 185499e37695SRavitheja Addepally LLDB_LOG(log, "traceid not being traced: {0}", traceid); 185599e37695SRavitheja Addepally buffer = buffer.slice(buffer.size()); 185699e37695SRavitheja Addepally error = perf_monitor.takeError(); 185799e37695SRavitheja Addepally return error; 185899e37695SRavitheja Addepally } 185999e37695SRavitheja Addepally return (*perf_monitor).ReadPerfTraceData(buffer, offset); 186099e37695SRavitheja Addepally } 186199e37695SRavitheja Addepally 186299e37695SRavitheja Addepally Status NativeProcessLinux::GetData(lldb::user_id_t traceid, lldb::tid_t thread, 186399e37695SRavitheja Addepally llvm::MutableArrayRef<uint8_t> &buffer, 186499e37695SRavitheja Addepally size_t offset) { 186599e37695SRavitheja Addepally Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 186699e37695SRavitheja Addepally Status error; 186799e37695SRavitheja Addepally 186899e37695SRavitheja Addepally LLDB_LOG(log, "traceid {0}", traceid); 186999e37695SRavitheja Addepally 187099e37695SRavitheja Addepally auto perf_monitor = LookupProcessorTraceInstance(traceid, thread); 187199e37695SRavitheja Addepally if (!perf_monitor) { 187299e37695SRavitheja Addepally LLDB_LOG(log, "traceid not being traced: {0}", traceid); 187399e37695SRavitheja Addepally buffer = buffer.slice(buffer.size()); 187499e37695SRavitheja Addepally error = perf_monitor.takeError(); 187599e37695SRavitheja Addepally return error; 187699e37695SRavitheja Addepally } 187799e37695SRavitheja Addepally return (*perf_monitor).ReadPerfTraceAux(buffer, offset); 187899e37695SRavitheja Addepally } 187999e37695SRavitheja Addepally 188099e37695SRavitheja Addepally Status NativeProcessLinux::GetTraceConfig(lldb::user_id_t traceid, 188199e37695SRavitheja Addepally TraceOptions &config) { 188299e37695SRavitheja Addepally Status error; 188399e37695SRavitheja Addepally if (config.getThreadID() == LLDB_INVALID_THREAD_ID && 188499e37695SRavitheja Addepally m_pt_proces_trace_id == traceid) { 188599e37695SRavitheja Addepally if (m_pt_proces_trace_id == LLDB_INVALID_UID) { 188699e37695SRavitheja Addepally error.SetErrorString("tracing not active for this process"); 188799e37695SRavitheja Addepally return error; 188899e37695SRavitheja Addepally } 188999e37695SRavitheja Addepally config = m_pt_process_trace_config; 189099e37695SRavitheja Addepally } else { 189199e37695SRavitheja Addepally auto perf_monitor = 189299e37695SRavitheja Addepally LookupProcessorTraceInstance(traceid, config.getThreadID()); 189399e37695SRavitheja Addepally if (!perf_monitor) { 189499e37695SRavitheja Addepally error = perf_monitor.takeError(); 189599e37695SRavitheja Addepally return error; 189699e37695SRavitheja Addepally } 189799e37695SRavitheja Addepally error = (*perf_monitor).GetTraceConfig(config); 189899e37695SRavitheja Addepally } 189999e37695SRavitheja Addepally return error; 190099e37695SRavitheja Addepally } 190199e37695SRavitheja Addepally 190299e37695SRavitheja Addepally lldb::user_id_t 190399e37695SRavitheja Addepally NativeProcessLinux::StartTraceGroup(const TraceOptions &config, 190499e37695SRavitheja Addepally Status &error) { 190599e37695SRavitheja Addepally 190699e37695SRavitheja Addepally Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 190799e37695SRavitheja Addepally if (config.getType() != TraceType::eTraceTypeProcessorTrace) 190899e37695SRavitheja Addepally return LLDB_INVALID_UID; 190999e37695SRavitheja Addepally 191099e37695SRavitheja Addepally if (m_pt_proces_trace_id != LLDB_INVALID_UID) { 191199e37695SRavitheja Addepally error.SetErrorString("tracing already active on this process"); 191299e37695SRavitheja Addepally return m_pt_proces_trace_id; 191399e37695SRavitheja Addepally } 191499e37695SRavitheja Addepally 191599e37695SRavitheja Addepally for (const auto &thread_sp : m_threads) { 191699e37695SRavitheja Addepally if (auto traceInstance = ProcessorTraceMonitor::Create( 191799e37695SRavitheja Addepally GetID(), thread_sp->GetID(), config, true)) { 191899e37695SRavitheja Addepally m_pt_traced_thread_group.insert(thread_sp->GetID()); 191999e37695SRavitheja Addepally m_processor_trace_monitor.insert( 192099e37695SRavitheja Addepally std::make_pair(thread_sp->GetID(), std::move(*traceInstance))); 192199e37695SRavitheja Addepally } 192299e37695SRavitheja Addepally } 192399e37695SRavitheja Addepally 192499e37695SRavitheja Addepally m_pt_process_trace_config = config; 192599e37695SRavitheja Addepally error = ProcessorTraceMonitor::GetCPUType(m_pt_process_trace_config); 192699e37695SRavitheja Addepally 192799e37695SRavitheja Addepally // Trace on Complete process will have traceid of 0 192899e37695SRavitheja Addepally m_pt_proces_trace_id = 0; 192999e37695SRavitheja Addepally 193099e37695SRavitheja Addepally LLDB_LOG(log, "Process Trace ID {0}", m_pt_proces_trace_id); 193199e37695SRavitheja Addepally return m_pt_proces_trace_id; 193299e37695SRavitheja Addepally } 193399e37695SRavitheja Addepally 193499e37695SRavitheja Addepally lldb::user_id_t NativeProcessLinux::StartTrace(const TraceOptions &config, 193599e37695SRavitheja Addepally Status &error) { 193699e37695SRavitheja Addepally if (config.getType() != TraceType::eTraceTypeProcessorTrace) 193799e37695SRavitheja Addepally return NativeProcessProtocol::StartTrace(config, error); 193899e37695SRavitheja Addepally 193999e37695SRavitheja Addepally Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 194099e37695SRavitheja Addepally 194199e37695SRavitheja Addepally lldb::tid_t threadid = config.getThreadID(); 194299e37695SRavitheja Addepally 194399e37695SRavitheja Addepally if (threadid == LLDB_INVALID_THREAD_ID) 194499e37695SRavitheja Addepally return StartTraceGroup(config, error); 194599e37695SRavitheja Addepally 194699e37695SRavitheja Addepally auto thread_sp = GetThreadByID(threadid); 194799e37695SRavitheja Addepally if (!thread_sp) { 194899e37695SRavitheja Addepally // Thread not tracked by lldb so don't trace. 194999e37695SRavitheja Addepally error.SetErrorString("invalid thread id"); 195099e37695SRavitheja Addepally return LLDB_INVALID_UID; 195199e37695SRavitheja Addepally } 195299e37695SRavitheja Addepally 195399e37695SRavitheja Addepally const auto &iter = m_processor_trace_monitor.find(threadid); 195499e37695SRavitheja Addepally if (iter != m_processor_trace_monitor.end()) { 195599e37695SRavitheja Addepally LLDB_LOG(log, "Thread already being traced"); 195699e37695SRavitheja Addepally error.SetErrorString("tracing already active on this thread"); 195799e37695SRavitheja Addepally return LLDB_INVALID_UID; 195899e37695SRavitheja Addepally } 195999e37695SRavitheja Addepally 196099e37695SRavitheja Addepally auto traceMonitor = 196199e37695SRavitheja Addepally ProcessorTraceMonitor::Create(GetID(), threadid, config, false); 196299e37695SRavitheja Addepally if (!traceMonitor) { 196399e37695SRavitheja Addepally error = traceMonitor.takeError(); 196499e37695SRavitheja Addepally LLDB_LOG(log, "error {0}", error); 196599e37695SRavitheja Addepally return LLDB_INVALID_UID; 196699e37695SRavitheja Addepally } 196799e37695SRavitheja Addepally lldb::user_id_t ret_trace_id = (*traceMonitor)->GetTraceID(); 196899e37695SRavitheja Addepally m_processor_trace_monitor.insert( 196999e37695SRavitheja Addepally std::make_pair(threadid, std::move(*traceMonitor))); 197099e37695SRavitheja Addepally return ret_trace_id; 197199e37695SRavitheja Addepally } 197299e37695SRavitheja Addepally 197399e37695SRavitheja Addepally Status NativeProcessLinux::StopTracingForThread(lldb::tid_t thread) { 197499e37695SRavitheja Addepally Status error; 197599e37695SRavitheja Addepally Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 197699e37695SRavitheja Addepally LLDB_LOG(log, "Thread {0}", thread); 197799e37695SRavitheja Addepally 197899e37695SRavitheja Addepally const auto& iter = m_processor_trace_monitor.find(thread); 197999e37695SRavitheja Addepally if (iter == m_processor_trace_monitor.end()) { 198099e37695SRavitheja Addepally error.SetErrorString("tracing not active for this thread"); 198199e37695SRavitheja Addepally return error; 198299e37695SRavitheja Addepally } 198399e37695SRavitheja Addepally 198499e37695SRavitheja Addepally if (iter->second->GetTraceID() == m_pt_proces_trace_id) { 198505097246SAdrian Prantl // traceid maps to the whole process so we have to erase it from the thread 198605097246SAdrian Prantl // group. 198799e37695SRavitheja Addepally LLDB_LOG(log, "traceid maps to process"); 198899e37695SRavitheja Addepally m_pt_traced_thread_group.erase(thread); 198999e37695SRavitheja Addepally } 199099e37695SRavitheja Addepally m_processor_trace_monitor.erase(iter); 199199e37695SRavitheja Addepally 199299e37695SRavitheja Addepally return error; 199399e37695SRavitheja Addepally } 199499e37695SRavitheja Addepally 199599e37695SRavitheja Addepally Status NativeProcessLinux::StopTrace(lldb::user_id_t traceid, 199699e37695SRavitheja Addepally lldb::tid_t thread) { 199799e37695SRavitheja Addepally Status error; 199899e37695SRavitheja Addepally 199999e37695SRavitheja Addepally TraceOptions trace_options; 200099e37695SRavitheja Addepally trace_options.setThreadID(thread); 200199e37695SRavitheja Addepally error = NativeProcessLinux::GetTraceConfig(traceid, trace_options); 200299e37695SRavitheja Addepally 200399e37695SRavitheja Addepally if (error.Fail()) 200499e37695SRavitheja Addepally return error; 200599e37695SRavitheja Addepally 200699e37695SRavitheja Addepally switch (trace_options.getType()) { 200799e37695SRavitheja Addepally case lldb::TraceType::eTraceTypeProcessorTrace: 200899e37695SRavitheja Addepally if (traceid == m_pt_proces_trace_id && 200999e37695SRavitheja Addepally thread == LLDB_INVALID_THREAD_ID) 201099e37695SRavitheja Addepally StopProcessorTracingOnProcess(); 201199e37695SRavitheja Addepally else 201299e37695SRavitheja Addepally error = StopProcessorTracingOnThread(traceid, thread); 201399e37695SRavitheja Addepally break; 201499e37695SRavitheja Addepally default: 201599e37695SRavitheja Addepally error.SetErrorString("trace not supported"); 201699e37695SRavitheja Addepally break; 201799e37695SRavitheja Addepally } 201899e37695SRavitheja Addepally 201999e37695SRavitheja Addepally return error; 202099e37695SRavitheja Addepally } 202199e37695SRavitheja Addepally 202299e37695SRavitheja Addepally void NativeProcessLinux::StopProcessorTracingOnProcess() { 202399e37695SRavitheja Addepally for (auto thread_id_iter : m_pt_traced_thread_group) 202499e37695SRavitheja Addepally m_processor_trace_monitor.erase(thread_id_iter); 202599e37695SRavitheja Addepally m_pt_traced_thread_group.clear(); 202699e37695SRavitheja Addepally m_pt_proces_trace_id = LLDB_INVALID_UID; 202799e37695SRavitheja Addepally } 202899e37695SRavitheja Addepally 202999e37695SRavitheja Addepally Status NativeProcessLinux::StopProcessorTracingOnThread(lldb::user_id_t traceid, 203099e37695SRavitheja Addepally lldb::tid_t thread) { 203199e37695SRavitheja Addepally Status error; 203299e37695SRavitheja Addepally Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 203399e37695SRavitheja Addepally 203499e37695SRavitheja Addepally if (thread == LLDB_INVALID_THREAD_ID) { 203599e37695SRavitheja Addepally for (auto& iter : m_processor_trace_monitor) { 203699e37695SRavitheja Addepally if (iter.second->GetTraceID() == traceid) { 203705097246SAdrian Prantl // Stopping a trace instance for an individual thread hence there will 203805097246SAdrian Prantl // only be one traceid that can match. 203999e37695SRavitheja Addepally m_processor_trace_monitor.erase(iter.first); 204099e37695SRavitheja Addepally return error; 204199e37695SRavitheja Addepally } 204299e37695SRavitheja Addepally LLDB_LOG(log, "Trace ID {0}", iter.second->GetTraceID()); 204399e37695SRavitheja Addepally } 204499e37695SRavitheja Addepally 204599e37695SRavitheja Addepally LLDB_LOG(log, "Invalid TraceID"); 204699e37695SRavitheja Addepally error.SetErrorString("invalid trace id"); 204799e37695SRavitheja Addepally return error; 204899e37695SRavitheja Addepally } 204999e37695SRavitheja Addepally 205099e37695SRavitheja Addepally // thread is specified so we can use find function on the map. 205199e37695SRavitheja Addepally const auto& iter = m_processor_trace_monitor.find(thread); 205299e37695SRavitheja Addepally if (iter == m_processor_trace_monitor.end()) { 205399e37695SRavitheja Addepally // thread not found in our map. 205499e37695SRavitheja Addepally LLDB_LOG(log, "thread not being traced"); 205599e37695SRavitheja Addepally error.SetErrorString("tracing not active for this thread"); 205699e37695SRavitheja Addepally return error; 205799e37695SRavitheja Addepally } 205899e37695SRavitheja Addepally if (iter->second->GetTraceID() != traceid) { 205999e37695SRavitheja Addepally // traceid did not match so it has to be invalid. 206099e37695SRavitheja Addepally LLDB_LOG(log, "Invalid TraceID"); 206199e37695SRavitheja Addepally error.SetErrorString("invalid trace id"); 206299e37695SRavitheja Addepally return error; 206399e37695SRavitheja Addepally } 206499e37695SRavitheja Addepally 206599e37695SRavitheja Addepally LLDB_LOG(log, "UID - {0} , Thread -{1}", traceid, thread); 206699e37695SRavitheja Addepally 206799e37695SRavitheja Addepally if (traceid == m_pt_proces_trace_id) { 206805097246SAdrian Prantl // traceid maps to the whole process so we have to erase it from the thread 206905097246SAdrian Prantl // group. 207099e37695SRavitheja Addepally LLDB_LOG(log, "traceid maps to process"); 207199e37695SRavitheja Addepally m_pt_traced_thread_group.erase(thread); 207299e37695SRavitheja Addepally } 207399e37695SRavitheja Addepally m_processor_trace_monitor.erase(iter); 207499e37695SRavitheja Addepally 207599e37695SRavitheja Addepally return error; 207699e37695SRavitheja Addepally } 2077