1af245d11STodd Fiala //===-- NativeProcessLinux.cpp -------------------------------- -*- C++ -*-===// 2af245d11STodd Fiala // 32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information. 52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6af245d11STodd Fiala // 7af245d11STodd Fiala //===----------------------------------------------------------------------===// 8af245d11STodd Fiala 9af245d11STodd Fiala #include "NativeProcessLinux.h" 10af245d11STodd Fiala 11af245d11STodd Fiala #include <errno.h> 12af245d11STodd Fiala #include <stdint.h> 13b9c1b51eSKate Stone #include <string.h> 14af245d11STodd Fiala #include <unistd.h> 15af245d11STodd Fiala 16af245d11STodd Fiala #include <fstream> 17df7c6995SPavel Labath #include <mutex> 18c076559aSPavel Labath #include <sstream> 19af245d11STodd Fiala #include <string> 205b981ab9SPavel Labath #include <unordered_map> 21af245d11STodd Fiala 22d8c338d4STamas Berghammer #include "lldb/Core/EmulateInstruction.h" 236edef204SOleksiy Vyalov #include "lldb/Core/ModuleSpec.h" 24af245d11STodd Fiala #include "lldb/Host/Host.h" 255ad891f7SPavel Labath #include "lldb/Host/HostProcess.h" 26eef758e9SPavel Labath #include "lldb/Host/ProcessLaunchInfo.h" 2724ae6294SZachary Turner #include "lldb/Host/PseudoTerminal.h" 2839de3110SZachary Turner #include "lldb/Host/ThreadLauncher.h" 292a86b555SPavel Labath #include "lldb/Host/common/NativeRegisterContext.h" 304ee1c952SPavel Labath #include "lldb/Host/linux/Ptrace.h" 314ee1c952SPavel Labath #include "lldb/Host/linux/Uio.h" 32816ae4b0SKamil Rytarowski #include "lldb/Host/posix/ProcessLauncherPosixFork.h" 332a86b555SPavel Labath #include "lldb/Symbol/ObjectFile.h" 3490aff47cSZachary Turner #include "lldb/Target/Process.h" 355b981ab9SPavel Labath #include "lldb/Target/Target.h" 36c16f5dcaSChaoren Lin #include "lldb/Utility/LLDBAssert.h" 37d821c997SPavel Labath #include "lldb/Utility/RegisterValue.h" 38d821c997SPavel Labath #include "lldb/Utility/State.h" 3997206d57SZachary Turner #include "lldb/Utility/Status.h" 40f805e190SPavel Labath #include "lldb/Utility/StringExtractor.h" 4110c41f37SPavel Labath #include "llvm/Support/Errno.h" 4210c41f37SPavel Labath #include "llvm/Support/FileSystem.h" 4310c41f37SPavel Labath #include "llvm/Support/Threading.h" 44af245d11STodd Fiala 45af245d11STodd Fiala #include "NativeThreadLinux.h" 46b9c1b51eSKate Stone #include "Plugins/Process/POSIX/ProcessPOSIXLog.h" 47c8e364e8SPavel Labath #include "Plugins/Process/Utility/LinuxProcMaps.h" 481e209fccSTamas Berghammer #include "Procfs.h" 49cacde7dfSTodd Fiala 50d858487eSTamas Berghammer #include <linux/unistd.h> 51d858487eSTamas Berghammer #include <sys/socket.h> 52df7c6995SPavel Labath #include <sys/syscall.h> 53d858487eSTamas Berghammer #include <sys/types.h> 54d858487eSTamas Berghammer #include <sys/user.h> 55d858487eSTamas Berghammer #include <sys/wait.h> 56d858487eSTamas Berghammer 57af245d11STodd Fiala // Support hardware breakpoints in case it has not been defined 58af245d11STodd Fiala #ifndef TRAP_HWBKPT 59af245d11STodd Fiala #define TRAP_HWBKPT 4 60af245d11STodd Fiala #endif 61af245d11STodd Fiala 627cb18bf5STamas Berghammer using namespace lldb; 637cb18bf5STamas Berghammer using namespace lldb_private; 64db264a6dSTamas Berghammer using namespace lldb_private::process_linux; 657cb18bf5STamas Berghammer using namespace llvm; 667cb18bf5STamas Berghammer 67af245d11STodd Fiala // Private bits we only need internally. 68df7c6995SPavel Labath 69b9c1b51eSKate Stone static bool ProcessVmReadvSupported() { 70df7c6995SPavel Labath static bool is_supported; 71c5f28e2aSKamil Rytarowski static llvm::once_flag flag; 72df7c6995SPavel Labath 73c5f28e2aSKamil Rytarowski llvm::call_once(flag, [] { 74a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 75df7c6995SPavel Labath 76df7c6995SPavel Labath uint32_t source = 0x47424742; 77df7c6995SPavel Labath uint32_t dest = 0; 78df7c6995SPavel Labath 79df7c6995SPavel Labath struct iovec local, remote; 80df7c6995SPavel Labath remote.iov_base = &source; 81df7c6995SPavel Labath local.iov_base = &dest; 82df7c6995SPavel Labath remote.iov_len = local.iov_len = sizeof source; 83df7c6995SPavel Labath 84b9c1b51eSKate Stone // We shall try if cross-process-memory reads work by attempting to read a 85b9c1b51eSKate Stone // value from our own process. 86df7c6995SPavel Labath ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0); 87df7c6995SPavel Labath is_supported = (res == sizeof(source) && source == dest); 88df7c6995SPavel Labath if (is_supported) 89a6321a8eSPavel Labath LLDB_LOG(log, 90a6321a8eSPavel Labath "Detected kernel support for process_vm_readv syscall. " 91a6321a8eSPavel Labath "Fast memory reads enabled."); 92df7c6995SPavel Labath else 93a6321a8eSPavel Labath LLDB_LOG(log, 94a6321a8eSPavel Labath "syscall process_vm_readv failed (error: {0}). Fast memory " 95a6321a8eSPavel Labath "reads disabled.", 9610c41f37SPavel Labath llvm::sys::StrError()); 97df7c6995SPavel Labath }); 98df7c6995SPavel Labath 99df7c6995SPavel Labath return is_supported; 100df7c6995SPavel Labath } 101df7c6995SPavel Labath 102b9c1b51eSKate Stone namespace { 103b9c1b51eSKate Stone void MaybeLogLaunchInfo(const ProcessLaunchInfo &info) { 104a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1054abe5d69SPavel Labath if (!log) 1064abe5d69SPavel Labath return; 1074abe5d69SPavel Labath 1084abe5d69SPavel Labath if (const FileAction *action = info.GetFileActionForFD(STDIN_FILENO)) 109a6321a8eSPavel Labath LLDB_LOG(log, "setting STDIN to '{0}'", action->GetFileSpec()); 1104abe5d69SPavel Labath else 111a6321a8eSPavel Labath LLDB_LOG(log, "leaving STDIN as is"); 1124abe5d69SPavel Labath 1134abe5d69SPavel Labath if (const FileAction *action = info.GetFileActionForFD(STDOUT_FILENO)) 114a6321a8eSPavel Labath LLDB_LOG(log, "setting STDOUT to '{0}'", action->GetFileSpec()); 1154abe5d69SPavel Labath else 116a6321a8eSPavel Labath LLDB_LOG(log, "leaving STDOUT as is"); 1174abe5d69SPavel Labath 1184abe5d69SPavel Labath if (const FileAction *action = info.GetFileActionForFD(STDERR_FILENO)) 119a6321a8eSPavel Labath LLDB_LOG(log, "setting STDERR to '{0}'", action->GetFileSpec()); 1204abe5d69SPavel Labath else 121a6321a8eSPavel Labath LLDB_LOG(log, "leaving STDERR as is"); 1224abe5d69SPavel Labath 1234abe5d69SPavel Labath int i = 0; 124b9c1b51eSKate Stone for (const char **args = info.GetArguments().GetConstArgumentVector(); *args; 125b9c1b51eSKate Stone ++args, ++i) 126a6321a8eSPavel Labath LLDB_LOG(log, "arg {0}: '{1}'", i, *args); 1274abe5d69SPavel Labath } 1284abe5d69SPavel Labath 129b9c1b51eSKate Stone void DisplayBytes(StreamString &s, void *bytes, uint32_t count) { 130af245d11STodd Fiala uint8_t *ptr = (uint8_t *)bytes; 131af245d11STodd Fiala const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count); 132b9c1b51eSKate Stone for (uint32_t i = 0; i < loop_count; i++) { 133af245d11STodd Fiala s.Printf("[%x]", *ptr); 134af245d11STodd Fiala ptr++; 135af245d11STodd Fiala } 136af245d11STodd Fiala } 137af245d11STodd Fiala 138b9c1b51eSKate Stone void PtraceDisplayBytes(int &req, void *data, size_t data_size) { 139aafe053cSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 140a6321a8eSPavel Labath if (!log) 141a6321a8eSPavel Labath return; 142af245d11STodd Fiala StreamString buf; 143af245d11STodd Fiala 144b9c1b51eSKate Stone switch (req) { 145b9c1b51eSKate Stone case PTRACE_POKETEXT: { 146af245d11STodd Fiala DisplayBytes(buf, &data, 8); 147aafe053cSPavel Labath LLDB_LOGV(log, "PTRACE_POKETEXT {0}", buf.GetData()); 148af245d11STodd Fiala break; 149af245d11STodd Fiala } 150b9c1b51eSKate Stone case PTRACE_POKEDATA: { 151af245d11STodd Fiala DisplayBytes(buf, &data, 8); 152aafe053cSPavel Labath LLDB_LOGV(log, "PTRACE_POKEDATA {0}", buf.GetData()); 153af245d11STodd Fiala break; 154af245d11STodd Fiala } 155b9c1b51eSKate Stone case PTRACE_POKEUSER: { 156af245d11STodd Fiala DisplayBytes(buf, &data, 8); 157aafe053cSPavel Labath LLDB_LOGV(log, "PTRACE_POKEUSER {0}", buf.GetData()); 158af245d11STodd Fiala break; 159af245d11STodd Fiala } 160b9c1b51eSKate Stone case PTRACE_SETREGS: { 161af245d11STodd Fiala DisplayBytes(buf, data, data_size); 162aafe053cSPavel Labath LLDB_LOGV(log, "PTRACE_SETREGS {0}", buf.GetData()); 163af245d11STodd Fiala break; 164af245d11STodd Fiala } 165b9c1b51eSKate Stone case PTRACE_SETFPREGS: { 166af245d11STodd Fiala DisplayBytes(buf, data, data_size); 167aafe053cSPavel Labath LLDB_LOGV(log, "PTRACE_SETFPREGS {0}", buf.GetData()); 168af245d11STodd Fiala break; 169af245d11STodd Fiala } 170b9c1b51eSKate Stone case PTRACE_SETSIGINFO: { 171af245d11STodd Fiala DisplayBytes(buf, data, sizeof(siginfo_t)); 172aafe053cSPavel Labath LLDB_LOGV(log, "PTRACE_SETSIGINFO {0}", buf.GetData()); 173af245d11STodd Fiala break; 174af245d11STodd Fiala } 175b9c1b51eSKate Stone case PTRACE_SETREGSET: { 17611edb4eeSPavel Labath // Extract iov_base from data, which is a pointer to the struct iovec 177af245d11STodd Fiala DisplayBytes(buf, *(void **)data, data_size); 178aafe053cSPavel Labath LLDB_LOGV(log, "PTRACE_SETREGSET {0}", buf.GetData()); 179af245d11STodd Fiala break; 180af245d11STodd Fiala } 181b9c1b51eSKate Stone default: {} 182af245d11STodd Fiala } 183af245d11STodd Fiala } 184af245d11STodd Fiala 18519cbe96aSPavel Labath static constexpr unsigned k_ptrace_word_size = sizeof(void *); 186b9c1b51eSKate Stone static_assert(sizeof(long) >= k_ptrace_word_size, 187b9c1b51eSKate Stone "Size of long must be larger than ptrace word size"); 1881107b5a5SPavel Labath } // end of anonymous namespace 1891107b5a5SPavel Labath 190bd7cbc5aSPavel Labath // Simple helper function to ensure flags are enabled on the given file 191bd7cbc5aSPavel Labath // descriptor. 19297206d57SZachary Turner static Status EnsureFDFlags(int fd, int flags) { 19397206d57SZachary Turner Status error; 194bd7cbc5aSPavel Labath 195bd7cbc5aSPavel Labath int status = fcntl(fd, F_GETFL); 196b9c1b51eSKate Stone if (status == -1) { 197bd7cbc5aSPavel Labath error.SetErrorToErrno(); 198bd7cbc5aSPavel Labath return error; 199bd7cbc5aSPavel Labath } 200bd7cbc5aSPavel Labath 201b9c1b51eSKate Stone if (fcntl(fd, F_SETFL, status | flags) == -1) { 202bd7cbc5aSPavel Labath error.SetErrorToErrno(); 203bd7cbc5aSPavel Labath return error; 204bd7cbc5aSPavel Labath } 205bd7cbc5aSPavel Labath 206bd7cbc5aSPavel Labath return error; 207bd7cbc5aSPavel Labath } 208bd7cbc5aSPavel Labath 209af245d11STodd Fiala // ----------------------------------------------------------------------------- 210af245d11STodd Fiala // Public Static Methods 211af245d11STodd Fiala // ----------------------------------------------------------------------------- 212af245d11STodd Fiala 21382abefa4SPavel Labath llvm::Expected<std::unique_ptr<NativeProcessProtocol>> 21496e600fcSPavel Labath NativeProcessLinux::Factory::Launch(ProcessLaunchInfo &launch_info, 21596e600fcSPavel Labath NativeDelegate &native_delegate, 21696e600fcSPavel Labath MainLoop &mainloop) const { 217a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 218af245d11STodd Fiala 21996e600fcSPavel Labath MaybeLogLaunchInfo(launch_info); 220af245d11STodd Fiala 22196e600fcSPavel Labath Status status; 22296e600fcSPavel Labath ::pid_t pid = ProcessLauncherPosixFork() 22396e600fcSPavel Labath .LaunchProcess(launch_info, status) 22496e600fcSPavel Labath .GetProcessId(); 22596e600fcSPavel Labath LLDB_LOG(log, "pid = {0:x}", pid); 22696e600fcSPavel Labath if (status.Fail()) { 22796e600fcSPavel Labath LLDB_LOG(log, "failed to launch process: {0}", status); 22896e600fcSPavel Labath return status.ToError(); 229af245d11STodd Fiala } 230af245d11STodd Fiala 23196e600fcSPavel Labath // Wait for the child process to trap on its call to execve. 23296e600fcSPavel Labath int wstatus; 23396e600fcSPavel Labath ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0); 23496e600fcSPavel Labath assert(wpid == pid); 23596e600fcSPavel Labath (void)wpid; 23696e600fcSPavel Labath if (!WIFSTOPPED(wstatus)) { 23796e600fcSPavel Labath LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}", 23896e600fcSPavel Labath WaitStatus::Decode(wstatus)); 23996e600fcSPavel Labath return llvm::make_error<StringError>("Could not sync with inferior process", 24096e600fcSPavel Labath llvm::inconvertibleErrorCode()); 24196e600fcSPavel Labath } 24296e600fcSPavel Labath LLDB_LOG(log, "inferior started, now in stopped state"); 243af245d11STodd Fiala 24436e82208SPavel Labath ProcessInstanceInfo Info; 24536e82208SPavel Labath if (!Host::GetProcessInfo(pid, Info)) { 24636e82208SPavel Labath return llvm::make_error<StringError>("Cannot get process architecture", 24736e82208SPavel Labath llvm::inconvertibleErrorCode()); 24836e82208SPavel Labath } 24996e600fcSPavel Labath 25096e600fcSPavel Labath // Set the architecture to the exe architecture. 25196e600fcSPavel Labath LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid, 25236e82208SPavel Labath Info.GetArchitecture().GetArchitectureName()); 25396e600fcSPavel Labath 25496e600fcSPavel Labath status = SetDefaultPtraceOpts(pid); 25596e600fcSPavel Labath if (status.Fail()) { 25696e600fcSPavel Labath LLDB_LOG(log, "failed to set default ptrace options: {0}", status); 25796e600fcSPavel Labath return status.ToError(); 258af245d11STodd Fiala } 259af245d11STodd Fiala 26082abefa4SPavel Labath return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux( 26196e600fcSPavel Labath pid, launch_info.GetPTY().ReleaseMasterFileDescriptor(), native_delegate, 26236e82208SPavel Labath Info.GetArchitecture(), mainloop, {pid})); 263af245d11STodd Fiala } 264af245d11STodd Fiala 26582abefa4SPavel Labath llvm::Expected<std::unique_ptr<NativeProcessProtocol>> 26682abefa4SPavel Labath NativeProcessLinux::Factory::Attach( 267b9c1b51eSKate Stone lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate, 26896e600fcSPavel Labath MainLoop &mainloop) const { 269a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 270a6321a8eSPavel Labath LLDB_LOG(log, "pid = {0:x}", pid); 271af245d11STodd Fiala 272af245d11STodd Fiala // Retrieve the architecture for the running process. 27336e82208SPavel Labath ProcessInstanceInfo Info; 27436e82208SPavel Labath if (!Host::GetProcessInfo(pid, Info)) { 27536e82208SPavel Labath return llvm::make_error<StringError>("Cannot get process architecture", 27636e82208SPavel Labath llvm::inconvertibleErrorCode()); 27736e82208SPavel Labath } 278af245d11STodd Fiala 27996e600fcSPavel Labath auto tids_or = NativeProcessLinux::Attach(pid); 28096e600fcSPavel Labath if (!tids_or) 28196e600fcSPavel Labath return tids_or.takeError(); 282af245d11STodd Fiala 28382abefa4SPavel Labath return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux( 28436e82208SPavel Labath pid, -1, native_delegate, Info.GetArchitecture(), mainloop, *tids_or)); 285af245d11STodd Fiala } 286af245d11STodd Fiala 287af245d11STodd Fiala // ----------------------------------------------------------------------------- 288af245d11STodd Fiala // Public Instance Methods 289af245d11STodd Fiala // ----------------------------------------------------------------------------- 290af245d11STodd Fiala 29196e600fcSPavel Labath NativeProcessLinux::NativeProcessLinux(::pid_t pid, int terminal_fd, 29296e600fcSPavel Labath NativeDelegate &delegate, 29382abefa4SPavel Labath const ArchSpec &arch, MainLoop &mainloop, 29482abefa4SPavel Labath llvm::ArrayRef<::pid_t> tids) 29596e600fcSPavel Labath : NativeProcessProtocol(pid, terminal_fd, delegate), m_arch(arch) { 296b9c1b51eSKate Stone if (m_terminal_fd != -1) { 29796e600fcSPavel Labath Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK); 29896e600fcSPavel Labath assert(status.Success()); 2995ad891f7SPavel Labath } 300af245d11STodd Fiala 30196e600fcSPavel Labath Status status; 30296e600fcSPavel Labath m_sigchld_handle = mainloop.RegisterSignal( 30396e600fcSPavel Labath SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status); 30496e600fcSPavel Labath assert(m_sigchld_handle && status.Success()); 30596e600fcSPavel Labath 30696e600fcSPavel Labath for (const auto &tid : tids) { 307a5be48b3SPavel Labath NativeThreadLinux &thread = AddThread(tid); 308a5be48b3SPavel Labath thread.SetStoppedBySignal(SIGSTOP); 309a5be48b3SPavel Labath ThreadWasCreated(thread); 310af245d11STodd Fiala } 311af245d11STodd Fiala 31296e600fcSPavel Labath // Let our process instance know the thread has stopped. 31396e600fcSPavel Labath SetCurrentThreadID(tids[0]); 31496e600fcSPavel Labath SetState(StateType::eStateStopped, false); 31596e600fcSPavel Labath 31696e600fcSPavel Labath // Proccess any signals we received before installing our handler 31796e600fcSPavel Labath SigchldHandler(); 31896e600fcSPavel Labath } 31996e600fcSPavel Labath 32096e600fcSPavel Labath llvm::Expected<std::vector<::pid_t>> NativeProcessLinux::Attach(::pid_t pid) { 321a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 322af245d11STodd Fiala 32396e600fcSPavel Labath Status status; 324b9c1b51eSKate Stone // Use a map to keep track of the threads which we have attached/need to 325b9c1b51eSKate Stone // attach. 326af245d11STodd Fiala Host::TidMap tids_to_attach; 327b9c1b51eSKate Stone while (Host::FindProcessThreads(pid, tids_to_attach)) { 328af245d11STodd Fiala for (Host::TidMap::iterator it = tids_to_attach.begin(); 329b9c1b51eSKate Stone it != tids_to_attach.end();) { 330b9c1b51eSKate Stone if (it->second == false) { 331af245d11STodd Fiala lldb::tid_t tid = it->first; 332af245d11STodd Fiala 333af245d11STodd Fiala // Attach to the requested process. 334af245d11STodd Fiala // An attach will cause the thread to stop with a SIGSTOP. 33596e600fcSPavel Labath if ((status = PtraceWrapper(PTRACE_ATTACH, tid)).Fail()) { 33605097246SAdrian Prantl // No such thread. The thread may have exited. More error handling 33705097246SAdrian Prantl // may be needed. 33896e600fcSPavel Labath if (status.GetError() == ESRCH) { 339af245d11STodd Fiala it = tids_to_attach.erase(it); 340af245d11STodd Fiala continue; 34196e600fcSPavel Labath } 34296e600fcSPavel Labath return status.ToError(); 343af245d11STodd Fiala } 344af245d11STodd Fiala 34596e600fcSPavel Labath int wpid = 34696e600fcSPavel Labath llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, nullptr, __WALL); 34705097246SAdrian Prantl // Need to use __WALL otherwise we receive an error with errno=ECHLD At 34805097246SAdrian Prantl // this point we should have a thread stopped if waitpid succeeds. 34996e600fcSPavel Labath if (wpid < 0) { 35005097246SAdrian Prantl // No such thread. The thread may have exited. More error handling 35105097246SAdrian Prantl // may be needed. 352b9c1b51eSKate Stone if (errno == ESRCH) { 353af245d11STodd Fiala it = tids_to_attach.erase(it); 354af245d11STodd Fiala continue; 355af245d11STodd Fiala } 35696e600fcSPavel Labath return llvm::errorCodeToError( 35796e600fcSPavel Labath std::error_code(errno, std::generic_category())); 358af245d11STodd Fiala } 359af245d11STodd Fiala 36096e600fcSPavel Labath if ((status = SetDefaultPtraceOpts(tid)).Fail()) 36196e600fcSPavel Labath return status.ToError(); 362af245d11STodd Fiala 363a6321a8eSPavel Labath LLDB_LOG(log, "adding tid = {0}", tid); 364af245d11STodd Fiala it->second = true; 365af245d11STodd Fiala } 366af245d11STodd Fiala 367af245d11STodd Fiala // move the loop forward 368af245d11STodd Fiala ++it; 369af245d11STodd Fiala } 370af245d11STodd Fiala } 371af245d11STodd Fiala 37296e600fcSPavel Labath size_t tid_count = tids_to_attach.size(); 37396e600fcSPavel Labath if (tid_count == 0) 37496e600fcSPavel Labath return llvm::make_error<StringError>("No such process", 37596e600fcSPavel Labath llvm::inconvertibleErrorCode()); 376af245d11STodd Fiala 37796e600fcSPavel Labath std::vector<::pid_t> tids; 37896e600fcSPavel Labath tids.reserve(tid_count); 37996e600fcSPavel Labath for (const auto &p : tids_to_attach) 38096e600fcSPavel Labath tids.push_back(p.first); 38196e600fcSPavel Labath return std::move(tids); 382af245d11STodd Fiala } 383af245d11STodd Fiala 38497206d57SZachary Turner Status NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid) { 385af245d11STodd Fiala long ptrace_opts = 0; 386af245d11STodd Fiala 387af245d11STodd Fiala // Have the child raise an event on exit. This is used to keep the child in 388af245d11STodd Fiala // limbo until it is destroyed. 389af245d11STodd Fiala ptrace_opts |= PTRACE_O_TRACEEXIT; 390af245d11STodd Fiala 391af245d11STodd Fiala // Have the tracer trace threads which spawn in the inferior process. 392af245d11STodd Fiala // TODO: if we want to support tracing the inferiors' child, add the 393af245d11STodd Fiala // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK) 394af245d11STodd Fiala ptrace_opts |= PTRACE_O_TRACECLONE; 395af245d11STodd Fiala 39605097246SAdrian Prantl // Have the tracer notify us before execve returns (needed to disable legacy 39705097246SAdrian Prantl // SIGTRAP generation) 398af245d11STodd Fiala ptrace_opts |= PTRACE_O_TRACEEXEC; 399af245d11STodd Fiala 4004a9babb2SPavel Labath return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void *)ptrace_opts); 401af245d11STodd Fiala } 402af245d11STodd Fiala 4031107b5a5SPavel Labath // Handles all waitpid events from the inferior process. 404b9c1b51eSKate Stone void NativeProcessLinux::MonitorCallback(lldb::pid_t pid, bool exited, 4053508fc8cSPavel Labath WaitStatus status) { 406af245d11STodd Fiala Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 407af245d11STodd Fiala 408b9c1b51eSKate Stone // Certain activities differ based on whether the pid is the tid of the main 409b9c1b51eSKate Stone // thread. 4101107b5a5SPavel Labath const bool is_main_thread = (pid == GetID()); 411af245d11STodd Fiala 412af245d11STodd Fiala // Handle when the thread exits. 413b9c1b51eSKate Stone if (exited) { 414d8b3c1a1SPavel Labath LLDB_LOG(log, 415*9303afb3SPavel Labath "got exit status({0}) , tid = {1} ({2} main thread), process " 416d8b3c1a1SPavel Labath "state = {3}", 417*9303afb3SPavel Labath status, pid, is_main_thread ? "is" : "is not", GetState()); 418af245d11STodd Fiala 419af245d11STodd Fiala // This is a thread that exited. Ensure we're not tracking it anymore. 420d8b3c1a1SPavel Labath StopTrackingThread(pid); 421af245d11STodd Fiala 422b9c1b51eSKate Stone if (is_main_thread) { 423af245d11STodd Fiala // The main thread exited. We're done monitoring. Report to delegate. 4243508fc8cSPavel Labath SetExitStatus(status, true); 425af245d11STodd Fiala 426af245d11STodd Fiala // Notify delegate that our process has exited. 4271107b5a5SPavel Labath SetState(StateType::eStateExited, true); 428af245d11STodd Fiala } 4291107b5a5SPavel Labath return; 430af245d11STodd Fiala } 431af245d11STodd Fiala 432af245d11STodd Fiala siginfo_t info; 433b9cc0c75SPavel Labath const auto info_err = GetSignalInfo(pid, &info); 434b9cc0c75SPavel Labath auto thread_sp = GetThreadByID(pid); 435b9cc0c75SPavel Labath 436b9c1b51eSKate Stone if (!thread_sp) { 43705097246SAdrian Prantl // Normally, the only situation when we cannot find the thread is if we 43805097246SAdrian Prantl // have just received a new thread notification. This is indicated by 439a6321a8eSPavel Labath // GetSignalInfo() returning si_code == SI_USER and si_pid == 0 440a6321a8eSPavel Labath LLDB_LOG(log, "received notification about an unknown tid {0}.", pid); 441b9cc0c75SPavel Labath 442b9c1b51eSKate Stone if (info_err.Fail()) { 443a6321a8eSPavel Labath LLDB_LOG(log, 444a6321a8eSPavel Labath "(tid {0}) GetSignalInfo failed ({1}). " 445a6321a8eSPavel Labath "Ingoring this notification.", 446a6321a8eSPavel Labath pid, info_err); 447b9cc0c75SPavel Labath return; 448b9cc0c75SPavel Labath } 449b9cc0c75SPavel Labath 450a6321a8eSPavel Labath LLDB_LOG(log, "tid {0}, si_code: {1}, si_pid: {2}", pid, info.si_code, 451a6321a8eSPavel Labath info.si_pid); 452b9cc0c75SPavel Labath 453a5be48b3SPavel Labath NativeThreadLinux &thread = AddThread(pid); 45499e37695SRavitheja Addepally 455b9cc0c75SPavel Labath // Resume the newly created thread. 456a5be48b3SPavel Labath ResumeThread(thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER); 457a5be48b3SPavel Labath ThreadWasCreated(thread); 458b9cc0c75SPavel Labath return; 459b9cc0c75SPavel Labath } 460b9cc0c75SPavel Labath 461b9cc0c75SPavel Labath // Get details on the signal raised. 462b9c1b51eSKate Stone if (info_err.Success()) { 463fa03ad2eSChaoren Lin // We have retrieved the signal info. Dispatch appropriately. 464fa03ad2eSChaoren Lin if (info.si_signo == SIGTRAP) 465b9cc0c75SPavel Labath MonitorSIGTRAP(info, *thread_sp); 466fa03ad2eSChaoren Lin else 467b9cc0c75SPavel Labath MonitorSignal(info, *thread_sp, exited); 468b9c1b51eSKate Stone } else { 469b9c1b51eSKate Stone if (info_err.GetError() == EINVAL) { 47005097246SAdrian Prantl // This is a group stop reception for this tid. We can reach here if we 47105097246SAdrian Prantl // reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the tracee, 47205097246SAdrian Prantl // triggering the group-stop mechanism. Normally receiving these would 47305097246SAdrian Prantl // stop the process, pending a SIGCONT. Simulating this state in a 47405097246SAdrian Prantl // debugger is hard and is generally not needed (one use case is 47505097246SAdrian Prantl // debugging background task being managed by a shell). For general use, 47605097246SAdrian Prantl // it is sufficient to stop the process in a signal-delivery stop which 47705097246SAdrian Prantl // happens before the group stop. This done by MonitorSignal and works 47805097246SAdrian Prantl // correctly for all signals. 479a6321a8eSPavel Labath LLDB_LOG(log, 480a6321a8eSPavel Labath "received a group stop for pid {0} tid {1}. Transparent " 481a6321a8eSPavel Labath "handling of group stops not supported, resuming the " 482a6321a8eSPavel Labath "thread.", 483a6321a8eSPavel Labath GetID(), pid); 484b9c1b51eSKate Stone ResumeThread(*thread_sp, thread_sp->GetState(), 485b9c1b51eSKate Stone LLDB_INVALID_SIGNAL_NUMBER); 486b9c1b51eSKate Stone } else { 487af245d11STodd Fiala // ptrace(GETSIGINFO) failed (but not due to group-stop). 488af245d11STodd Fiala 489b9c1b51eSKate Stone // A return value of ESRCH means the thread/process is no longer on the 490a6321a8eSPavel Labath // system, so it was killed somehow outside of our control. Either way, 491a6321a8eSPavel Labath // we can't do anything with it anymore. 492af245d11STodd Fiala 493b9c1b51eSKate Stone // Stop tracking the metadata for the thread since it's entirely off the 494b9c1b51eSKate Stone // system now. 4951107b5a5SPavel Labath const bool thread_found = StopTrackingThread(pid); 496af245d11STodd Fiala 497a6321a8eSPavel Labath LLDB_LOG(log, 498*9303afb3SPavel Labath "GetSignalInfo failed: {0}, tid = {1}, status = {2}, " 499a6321a8eSPavel Labath "status = {3}, main_thread = {4}, thread_found: {5}", 500*9303afb3SPavel Labath info_err, pid, status, status, is_main_thread, thread_found); 501af245d11STodd Fiala 502b9c1b51eSKate Stone if (is_main_thread) { 503b9c1b51eSKate Stone // Notify the delegate - our process is not available but appears to 50405097246SAdrian Prantl // have been killed outside our control. Is eStateExited the right 50505097246SAdrian Prantl // exit state in this case? 5063508fc8cSPavel Labath SetExitStatus(status, true); 5071107b5a5SPavel Labath SetState(StateType::eStateExited, true); 508b9c1b51eSKate Stone } else { 509b9c1b51eSKate Stone // This thread was pulled out from underneath us. Anything to do here? 510b9c1b51eSKate Stone // Do we want to do an all stop? 511a6321a8eSPavel Labath LLDB_LOG(log, 512a6321a8eSPavel Labath "pid {0} tid {1} non-main thread exit occurred, didn't " 513a6321a8eSPavel Labath "tell delegate anything since thread disappeared out " 514a6321a8eSPavel Labath "from underneath us", 515a6321a8eSPavel Labath GetID(), pid); 516af245d11STodd Fiala } 517af245d11STodd Fiala } 518af245d11STodd Fiala } 519af245d11STodd Fiala } 520af245d11STodd Fiala 521b9c1b51eSKate Stone void NativeProcessLinux::WaitForNewThread(::pid_t tid) { 522a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 523426bdf88SPavel Labath 524a5be48b3SPavel Labath if (GetThreadByID(tid)) { 525b9c1b51eSKate Stone // We are already tracking the thread - we got the event on the new thread 526a5be48b3SPavel Labath // (see MonitorSignal) before this one. We are done. 527426bdf88SPavel Labath return; 528426bdf88SPavel Labath } 529426bdf88SPavel Labath 530426bdf88SPavel Labath // The thread is not tracked yet, let's wait for it to appear. 531426bdf88SPavel Labath int status = -1; 532a6321a8eSPavel Labath LLDB_LOG(log, 533a6321a8eSPavel Labath "received thread creation event for tid {0}. tid not tracked " 534a6321a8eSPavel Labath "yet, waiting for thread to appear...", 535a6321a8eSPavel Labath tid); 536c1a6b128SPavel Labath ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, &status, __WALL); 537b9c1b51eSKate Stone // Since we are waiting on a specific tid, this must be the creation event. 538a6321a8eSPavel Labath // But let's do some checks just in case. 539426bdf88SPavel Labath if (wait_pid != tid) { 540a6321a8eSPavel Labath LLDB_LOG(log, 541a6321a8eSPavel Labath "waiting for tid {0} failed. Assuming the thread has " 542a6321a8eSPavel Labath "disappeared in the meantime", 543a6321a8eSPavel Labath tid); 544426bdf88SPavel Labath // The only way I know of this could happen is if the whole process was 545b9c1b51eSKate Stone // SIGKILLed in the mean time. In any case, we can't do anything about that 546b9c1b51eSKate Stone // now. 547426bdf88SPavel Labath return; 548426bdf88SPavel Labath } 549b9c1b51eSKate Stone if (WIFEXITED(status)) { 550a6321a8eSPavel Labath LLDB_LOG(log, 551a6321a8eSPavel Labath "waiting for tid {0} returned an 'exited' event. Not " 552a6321a8eSPavel Labath "tracking the thread.", 553a6321a8eSPavel Labath tid); 554426bdf88SPavel Labath // Also a very improbable event. 555426bdf88SPavel Labath return; 556426bdf88SPavel Labath } 557426bdf88SPavel Labath 558a6321a8eSPavel Labath LLDB_LOG(log, "pid = {0}: tracking new thread tid {1}", GetID(), tid); 559a5be48b3SPavel Labath NativeThreadLinux &new_thread = AddThread(tid); 56099e37695SRavitheja Addepally 561a5be48b3SPavel Labath ResumeThread(new_thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER); 562a5be48b3SPavel Labath ThreadWasCreated(new_thread); 563426bdf88SPavel Labath } 564426bdf88SPavel Labath 565b9c1b51eSKate Stone void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info, 566b9c1b51eSKate Stone NativeThreadLinux &thread) { 567a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 568b9cc0c75SPavel Labath const bool is_main_thread = (thread.GetID() == GetID()); 569af245d11STodd Fiala 570b9cc0c75SPavel Labath assert(info.si_signo == SIGTRAP && "Unexpected child signal!"); 571af245d11STodd Fiala 572b9c1b51eSKate Stone switch (info.si_code) { 573b9c1b51eSKate Stone // TODO: these two cases are required if we want to support tracing of the 57405097246SAdrian Prantl // inferiors' children. We'd need this to debug a monitor. case (SIGTRAP | 57505097246SAdrian Prantl // (PTRACE_EVENT_FORK << 8)): case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)): 576af245d11STodd Fiala 577b9c1b51eSKate Stone case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): { 578b9c1b51eSKate Stone // This is the notification on the parent thread which informs us of new 57905097246SAdrian Prantl // thread creation. We don't want to do anything with the parent thread so 58005097246SAdrian Prantl // we just resume it. In case we want to implement "break on thread 58105097246SAdrian Prantl // creation" functionality, we would need to stop here. 582af245d11STodd Fiala 583af245d11STodd Fiala unsigned long event_message = 0; 584b9c1b51eSKate Stone if (GetEventMessage(thread.GetID(), &event_message).Fail()) { 585a6321a8eSPavel Labath LLDB_LOG(log, 586a6321a8eSPavel Labath "pid {0} received thread creation event but " 587a6321a8eSPavel Labath "GetEventMessage failed so we don't know the new tid", 588a6321a8eSPavel Labath thread.GetID()); 589426bdf88SPavel Labath } else 590426bdf88SPavel Labath WaitForNewThread(event_message); 591af245d11STodd Fiala 592b9cc0c75SPavel Labath ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER); 593af245d11STodd Fiala break; 594af245d11STodd Fiala } 595af245d11STodd Fiala 596b9c1b51eSKate Stone case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): { 597a6321a8eSPavel Labath LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP); 598a9882ceeSTodd Fiala 5991dbc6c9cSPavel Labath // Exec clears any pending notifications. 6000e1d729bSPavel Labath m_pending_notification_tid = LLDB_INVALID_THREAD_ID; 601fa03ad2eSChaoren Lin 602b9c1b51eSKate Stone // Remove all but the main thread here. Linux fork creates a new process 603b9c1b51eSKate Stone // which only copies the main thread. 604a6321a8eSPavel Labath LLDB_LOG(log, "exec received, stop tracking all but main thread"); 605a9882ceeSTodd Fiala 606a5be48b3SPavel Labath for (auto i = m_threads.begin(); i != m_threads.end();) { 607a5be48b3SPavel Labath if ((*i)->GetID() == GetID()) 608a5be48b3SPavel Labath i = m_threads.erase(i); 609a5be48b3SPavel Labath else 610a5be48b3SPavel Labath ++i; 611a9882ceeSTodd Fiala } 612a5be48b3SPavel Labath assert(m_threads.size() == 1); 613a5be48b3SPavel Labath auto *main_thread = static_cast<NativeThreadLinux *>(m_threads[0].get()); 614a9882ceeSTodd Fiala 615a5be48b3SPavel Labath SetCurrentThreadID(main_thread->GetID()); 616a5be48b3SPavel Labath main_thread->SetStoppedByExec(); 617a9882ceeSTodd Fiala 618fa03ad2eSChaoren Lin // Tell coordinator about about the "new" (since exec) stopped main thread. 619a5be48b3SPavel Labath ThreadWasCreated(*main_thread); 620fa03ad2eSChaoren Lin 621a9882ceeSTodd Fiala // Let our delegate know we have just exec'd. 622a9882ceeSTodd Fiala NotifyDidExec(); 623a9882ceeSTodd Fiala 624fa03ad2eSChaoren Lin // Let the process know we're stopped. 625a5be48b3SPavel Labath StopRunningThreads(main_thread->GetID()); 626a9882ceeSTodd Fiala 627af245d11STodd Fiala break; 628a9882ceeSTodd Fiala } 629af245d11STodd Fiala 630b9c1b51eSKate Stone case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): { 63105097246SAdrian Prantl // The inferior process or one of its threads is about to exit. We don't 63205097246SAdrian Prantl // want to do anything with the thread so we just resume it. In case we 63305097246SAdrian Prantl // want to implement "break on thread exit" functionality, we would need to 63405097246SAdrian Prantl // stop here. 635fa03ad2eSChaoren Lin 636af245d11STodd Fiala unsigned long data = 0; 637b9cc0c75SPavel Labath if (GetEventMessage(thread.GetID(), &data).Fail()) 638af245d11STodd Fiala data = -1; 639af245d11STodd Fiala 640a6321a8eSPavel Labath LLDB_LOG(log, 641a6321a8eSPavel Labath "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, " 642a6321a8eSPavel Labath "WIFSIGNALED={2}, pid = {3}, main_thread = {4}", 643a6321a8eSPavel Labath data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(), 644a6321a8eSPavel Labath is_main_thread); 645af245d11STodd Fiala 64675f47c3aSTodd Fiala 64786852d36SPavel Labath StateType state = thread.GetState(); 648b9c1b51eSKate Stone if (!StateIsRunningState(state)) { 649b9c1b51eSKate Stone // Due to a kernel bug, we may sometimes get this stop after the inferior 650d8b3c1a1SPavel Labath // gets a SIGKILL. This confuses our state tracking logic in 651d8b3c1a1SPavel Labath // ResumeThread(), since normally, we should not be receiving any ptrace 65205097246SAdrian Prantl // events while the inferior is stopped. This makes sure that the 65305097246SAdrian Prantl // inferior is resumed and exits normally. 65486852d36SPavel Labath state = eStateRunning; 65586852d36SPavel Labath } 65686852d36SPavel Labath ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER); 657af245d11STodd Fiala 658af245d11STodd Fiala break; 659af245d11STodd Fiala } 660af245d11STodd Fiala 661af245d11STodd Fiala case 0: 662c16f5dcaSChaoren Lin case TRAP_TRACE: // We receive this on single stepping. 663c16f5dcaSChaoren Lin case TRAP_HWBKPT: // We receive this on watchpoint hit 66486fd8e45SChaoren Lin { 665c16f5dcaSChaoren Lin // If a watchpoint was hit, report it 666c16f5dcaSChaoren Lin uint32_t wp_index; 667d37349f3SPavel Labath Status error = thread.GetRegisterContext().GetWatchpointHitIndex( 668b9c1b51eSKate Stone wp_index, (uintptr_t)info.si_addr); 669a6321a8eSPavel Labath if (error.Fail()) 670a6321a8eSPavel Labath LLDB_LOG(log, 671a6321a8eSPavel Labath "received error while checking for watchpoint hits, pid = " 672a6321a8eSPavel Labath "{0}, error = {1}", 673a6321a8eSPavel Labath thread.GetID(), error); 674b9c1b51eSKate Stone if (wp_index != LLDB_INVALID_INDEX32) { 675b9cc0c75SPavel Labath MonitorWatchpoint(thread, wp_index); 676c16f5dcaSChaoren Lin break; 677c16f5dcaSChaoren Lin } 678b9cc0c75SPavel Labath 679d5ffbad2SOmair Javaid // If a breakpoint was hit, report it 680d5ffbad2SOmair Javaid uint32_t bp_index; 681d37349f3SPavel Labath error = thread.GetRegisterContext().GetHardwareBreakHitIndex( 682d5ffbad2SOmair Javaid bp_index, (uintptr_t)info.si_addr); 683d5ffbad2SOmair Javaid if (error.Fail()) 684d5ffbad2SOmair Javaid LLDB_LOG(log, "received error while checking for hardware " 685d5ffbad2SOmair Javaid "breakpoint hits, pid = {0}, error = {1}", 686d5ffbad2SOmair Javaid thread.GetID(), error); 687d5ffbad2SOmair Javaid if (bp_index != LLDB_INVALID_INDEX32) { 688d5ffbad2SOmair Javaid MonitorBreakpoint(thread); 689d5ffbad2SOmair Javaid break; 690d5ffbad2SOmair Javaid } 691d5ffbad2SOmair Javaid 692be379e15STamas Berghammer // Otherwise, report step over 693be379e15STamas Berghammer MonitorTrace(thread); 694af245d11STodd Fiala break; 695b9cc0c75SPavel Labath } 696af245d11STodd Fiala 697af245d11STodd Fiala case SI_KERNEL: 69835799963SMohit K. Bhakkad #if defined __mips__ 69905097246SAdrian Prantl // For mips there is no special signal for watchpoint So we check for 70005097246SAdrian Prantl // watchpoint in kernel trap 70135799963SMohit K. Bhakkad { 70235799963SMohit K. Bhakkad // If a watchpoint was hit, report it 70335799963SMohit K. Bhakkad uint32_t wp_index; 704d37349f3SPavel Labath Status error = thread.GetRegisterContext().GetWatchpointHitIndex( 705b9c1b51eSKate Stone wp_index, LLDB_INVALID_ADDRESS); 706a6321a8eSPavel Labath if (error.Fail()) 707a6321a8eSPavel Labath LLDB_LOG(log, 708a6321a8eSPavel Labath "received error while checking for watchpoint hits, pid = " 709a6321a8eSPavel Labath "{0}, error = {1}", 710a6321a8eSPavel Labath thread.GetID(), error); 711b9c1b51eSKate Stone if (wp_index != LLDB_INVALID_INDEX32) { 712b9cc0c75SPavel Labath MonitorWatchpoint(thread, wp_index); 71335799963SMohit K. Bhakkad break; 71435799963SMohit K. Bhakkad } 71535799963SMohit K. Bhakkad } 71635799963SMohit K. Bhakkad // NO BREAK 71735799963SMohit K. Bhakkad #endif 718af245d11STodd Fiala case TRAP_BRKPT: 719b9cc0c75SPavel Labath MonitorBreakpoint(thread); 720af245d11STodd Fiala break; 721af245d11STodd Fiala 722af245d11STodd Fiala case SIGTRAP: 723af245d11STodd Fiala case (SIGTRAP | 0x80): 724a6321a8eSPavel Labath LLDB_LOG( 725a6321a8eSPavel Labath log, 726a6321a8eSPavel Labath "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming", 727a6321a8eSPavel Labath info.si_code, GetID(), thread.GetID()); 728fa03ad2eSChaoren Lin 729af245d11STodd Fiala // Ignore these signals until we know more about them. 730b9cc0c75SPavel Labath ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER); 731af245d11STodd Fiala break; 732af245d11STodd Fiala 733af245d11STodd Fiala default: 73421a365baSPavel Labath LLDB_LOG(log, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}", 735a6321a8eSPavel Labath info.si_code, GetID(), thread.GetID()); 73621a365baSPavel Labath MonitorSignal(info, thread, false); 737af245d11STodd Fiala break; 738af245d11STodd Fiala } 739af245d11STodd Fiala } 740af245d11STodd Fiala 741b9c1b51eSKate Stone void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) { 742a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 743a6321a8eSPavel Labath LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID()); 744c16f5dcaSChaoren Lin 7450e1d729bSPavel Labath // This thread is currently stopped. 746b9cc0c75SPavel Labath thread.SetStoppedByTrace(); 747c16f5dcaSChaoren Lin 748b9cc0c75SPavel Labath StopRunningThreads(thread.GetID()); 749c16f5dcaSChaoren Lin } 750c16f5dcaSChaoren Lin 751b9c1b51eSKate Stone void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) { 752b9c1b51eSKate Stone Log *log( 753b9c1b51eSKate Stone GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS)); 754a6321a8eSPavel Labath LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID()); 755c16f5dcaSChaoren Lin 756c16f5dcaSChaoren Lin // Mark the thread as stopped at breakpoint. 757b9cc0c75SPavel Labath thread.SetStoppedByBreakpoint(); 758aef7908fSPavel Labath FixupBreakpointPCAsNeeded(thread); 759d8c338d4STamas Berghammer 760b9c1b51eSKate Stone if (m_threads_stepping_with_breakpoint.find(thread.GetID()) != 761b9c1b51eSKate Stone m_threads_stepping_with_breakpoint.end()) 762b9cc0c75SPavel Labath thread.SetStoppedByTrace(); 763c16f5dcaSChaoren Lin 764b9cc0c75SPavel Labath StopRunningThreads(thread.GetID()); 765c16f5dcaSChaoren Lin } 766c16f5dcaSChaoren Lin 767b9c1b51eSKate Stone void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread, 768b9c1b51eSKate Stone uint32_t wp_index) { 769b9c1b51eSKate Stone Log *log( 770b9c1b51eSKate Stone GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS)); 771a6321a8eSPavel Labath LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}", 772a6321a8eSPavel Labath thread.GetID(), wp_index); 773c16f5dcaSChaoren Lin 77405097246SAdrian Prantl // Mark the thread as stopped at watchpoint. The address is at 77505097246SAdrian Prantl // (lldb::addr_t)info->si_addr if we need it. 776f9077782SPavel Labath thread.SetStoppedByWatchpoint(wp_index); 777c16f5dcaSChaoren Lin 778b9c1b51eSKate Stone // We need to tell all other running threads before we notify the delegate 779b9c1b51eSKate Stone // about this stop. 780f9077782SPavel Labath StopRunningThreads(thread.GetID()); 781c16f5dcaSChaoren Lin } 782c16f5dcaSChaoren Lin 783b9c1b51eSKate Stone void NativeProcessLinux::MonitorSignal(const siginfo_t &info, 784b9c1b51eSKate Stone NativeThreadLinux &thread, bool exited) { 785b9cc0c75SPavel Labath const int signo = info.si_signo; 786b9cc0c75SPavel Labath const bool is_from_llgs = info.si_pid == getpid(); 787af245d11STodd Fiala 788a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 789af245d11STodd Fiala 790af245d11STodd Fiala // POSIX says that process behaviour is undefined after it ignores a SIGFPE, 79105097246SAdrian Prantl // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a kill(2) 79205097246SAdrian Prantl // or raise(3). Similarly for tgkill(2) on Linux. 793af245d11STodd Fiala // 794af245d11STodd Fiala // IOW, user generated signals never generate what we consider to be a 795af245d11STodd Fiala // "crash". 796af245d11STodd Fiala // 797af245d11STodd Fiala // Similarly, ACK signals generated by this monitor. 798af245d11STodd Fiala 799af245d11STodd Fiala // Handle the signal. 800a6321a8eSPavel Labath LLDB_LOG(log, 801a6321a8eSPavel Labath "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, " 802a6321a8eSPavel Labath "waitpid pid = {4})", 803a6321a8eSPavel Labath Host::GetSignalAsCString(signo), signo, info.si_code, 804b9cc0c75SPavel Labath thread.GetID()); 80558a2f669STodd Fiala 80658a2f669STodd Fiala // Check for thread stop notification. 807b9c1b51eSKate Stone if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) { 808af245d11STodd Fiala // This is a tgkill()-based stop. 809a6321a8eSPavel Labath LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID()); 810fa03ad2eSChaoren Lin 81105097246SAdrian Prantl // Check that we're not already marked with a stop reason. Note this thread 81205097246SAdrian Prantl // really shouldn't already be marked as stopped - if we were, that would 81305097246SAdrian Prantl // imply that the kernel signaled us with the thread stopping which we 81405097246SAdrian Prantl // handled and marked as stopped, and that, without an intervening resume, 81505097246SAdrian Prantl // we received another stop. It is more likely that we are missing the 81605097246SAdrian Prantl // marking of a run state somewhere if we find that the thread was marked 81705097246SAdrian Prantl // as stopped. 818b9cc0c75SPavel Labath const StateType thread_state = thread.GetState(); 819b9c1b51eSKate Stone if (!StateIsStoppedState(thread_state, false)) { 820ed89c7feSPavel Labath // An inferior thread has stopped because of a SIGSTOP we have sent it. 821b9c1b51eSKate Stone // Generally, these are not important stops and we don't want to report 822a6321a8eSPavel Labath // them as they are just used to stop other threads when one thread (the 823a6321a8eSPavel Labath // one with the *real* stop reason) hits a breakpoint (watchpoint, 82405097246SAdrian Prantl // etc...). However, in the case of an asynchronous Interrupt(), this 82505097246SAdrian Prantl // *is* the real stop reason, so we leave the signal intact if this is 82605097246SAdrian Prantl // the thread that was chosen as the triggering thread. 827b9c1b51eSKate Stone if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) { 828b9cc0c75SPavel Labath if (m_pending_notification_tid == thread.GetID()) 829b9cc0c75SPavel Labath thread.SetStoppedBySignal(SIGSTOP, &info); 830ed89c7feSPavel Labath else 831b9cc0c75SPavel Labath thread.SetStoppedWithNoReason(); 832ed89c7feSPavel Labath 833b9cc0c75SPavel Labath SetCurrentThreadID(thread.GetID()); 8340e1d729bSPavel Labath SignalIfAllThreadsStopped(); 835b9c1b51eSKate Stone } else { 8360e1d729bSPavel Labath // We can end up here if stop was initiated by LLGS but by this time a 8370e1d729bSPavel Labath // thread stop has occurred - maybe initiated by another event. 83897206d57SZachary Turner Status error = ResumeThread(thread, thread.GetState(), 0); 839a6321a8eSPavel Labath if (error.Fail()) 840a6321a8eSPavel Labath LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(), 841a6321a8eSPavel Labath error); 8420e1d729bSPavel Labath } 843b9c1b51eSKate Stone } else { 844a6321a8eSPavel Labath LLDB_LOG(log, 845a6321a8eSPavel Labath "pid {0} tid {1}, thread was already marked as a stopped " 846a6321a8eSPavel Labath "state (state={2}), leaving stop signal as is", 8478198db30SPavel Labath GetID(), thread.GetID(), thread_state); 8480e1d729bSPavel Labath SignalIfAllThreadsStopped(); 849af245d11STodd Fiala } 850af245d11STodd Fiala 85158a2f669STodd Fiala // Done handling. 852af245d11STodd Fiala return; 853af245d11STodd Fiala } 854af245d11STodd Fiala 85505097246SAdrian Prantl // Check if debugger should stop at this signal or just ignore it and resume 85605097246SAdrian Prantl // the inferior. 8574a705e7eSPavel Labath if (m_signals_to_ignore.find(signo) != m_signals_to_ignore.end()) { 8584a705e7eSPavel Labath ResumeThread(thread, thread.GetState(), signo); 8594a705e7eSPavel Labath return; 8604a705e7eSPavel Labath } 8614a705e7eSPavel Labath 86286fd8e45SChaoren Lin // This thread is stopped. 863a6321a8eSPavel Labath LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo)); 864b9cc0c75SPavel Labath thread.SetStoppedBySignal(signo, &info); 86586fd8e45SChaoren Lin 86686fd8e45SChaoren Lin // Send a stop to the debugger after we get all other threads to stop. 867b9cc0c75SPavel Labath StopRunningThreads(thread.GetID()); 868511e5cdcSTodd Fiala } 869af245d11STodd Fiala 870e7708688STamas Berghammer namespace { 871e7708688STamas Berghammer 872b9c1b51eSKate Stone struct EmulatorBaton { 873d37349f3SPavel Labath NativeProcessLinux &m_process; 874d37349f3SPavel Labath NativeRegisterContext &m_reg_context; 8756648fcc3SPavel Labath 8766648fcc3SPavel Labath // eRegisterKindDWARF -> RegsiterValue 8776648fcc3SPavel Labath std::unordered_map<uint32_t, RegisterValue> m_register_values; 878e7708688STamas Berghammer 879d37349f3SPavel Labath EmulatorBaton(NativeProcessLinux &process, NativeRegisterContext ®_context) 880b9c1b51eSKate Stone : m_process(process), m_reg_context(reg_context) {} 881e7708688STamas Berghammer }; 882e7708688STamas Berghammer 883e7708688STamas Berghammer } // anonymous namespace 884e7708688STamas Berghammer 885b9c1b51eSKate Stone static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton, 886e7708688STamas Berghammer const EmulateInstruction::Context &context, 887b9c1b51eSKate Stone lldb::addr_t addr, void *dst, size_t length) { 888e7708688STamas Berghammer EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton); 889e7708688STamas Berghammer 8903eb4b458SChaoren Lin size_t bytes_read; 891d37349f3SPavel Labath emulator_baton->m_process.ReadMemory(addr, dst, length, bytes_read); 892e7708688STamas Berghammer return bytes_read; 893e7708688STamas Berghammer } 894e7708688STamas Berghammer 895b9c1b51eSKate Stone static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton, 896e7708688STamas Berghammer const RegisterInfo *reg_info, 897b9c1b51eSKate Stone RegisterValue ®_value) { 898e7708688STamas Berghammer EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton); 899e7708688STamas Berghammer 900b9c1b51eSKate Stone auto it = emulator_baton->m_register_values.find( 901b9c1b51eSKate Stone reg_info->kinds[eRegisterKindDWARF]); 902b9c1b51eSKate Stone if (it != emulator_baton->m_register_values.end()) { 9036648fcc3SPavel Labath reg_value = it->second; 9046648fcc3SPavel Labath return true; 9056648fcc3SPavel Labath } 9066648fcc3SPavel Labath 90705097246SAdrian Prantl // The emulator only fill in the dwarf regsiter numbers (and in some case the 90805097246SAdrian Prantl // generic register numbers). Get the full register info from the register 90905097246SAdrian Prantl // context based on the dwarf register numbers. 910b9c1b51eSKate Stone const RegisterInfo *full_reg_info = 911d37349f3SPavel Labath emulator_baton->m_reg_context.GetRegisterInfo( 912e7708688STamas Berghammer eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]); 913e7708688STamas Berghammer 91497206d57SZachary Turner Status error = 915d37349f3SPavel Labath emulator_baton->m_reg_context.ReadRegister(full_reg_info, reg_value); 9166648fcc3SPavel Labath if (error.Success()) 9176648fcc3SPavel Labath return true; 918cdc22a88SMohit K. Bhakkad 9196648fcc3SPavel Labath return false; 920e7708688STamas Berghammer } 921e7708688STamas Berghammer 922b9c1b51eSKate Stone static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton, 923e7708688STamas Berghammer const EmulateInstruction::Context &context, 924e7708688STamas Berghammer const RegisterInfo *reg_info, 925b9c1b51eSKate Stone const RegisterValue ®_value) { 926e7708688STamas Berghammer EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton); 927b9c1b51eSKate Stone emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = 928b9c1b51eSKate Stone reg_value; 929e7708688STamas Berghammer return true; 930e7708688STamas Berghammer } 931e7708688STamas Berghammer 932b9c1b51eSKate Stone static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton, 933e7708688STamas Berghammer const EmulateInstruction::Context &context, 934b9c1b51eSKate Stone lldb::addr_t addr, const void *dst, 935b9c1b51eSKate Stone size_t length) { 936e7708688STamas Berghammer return length; 937e7708688STamas Berghammer } 938e7708688STamas Berghammer 939d37349f3SPavel Labath static lldb::addr_t ReadFlags(NativeRegisterContext ®siter_context) { 940d37349f3SPavel Labath const RegisterInfo *flags_info = regsiter_context.GetRegisterInfo( 941e7708688STamas Berghammer eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS); 942d37349f3SPavel Labath return regsiter_context.ReadRegisterAsUnsigned(flags_info, 943b9c1b51eSKate Stone LLDB_INVALID_ADDRESS); 944e7708688STamas Berghammer } 945e7708688STamas Berghammer 94697206d57SZachary Turner Status 94797206d57SZachary Turner NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadLinux &thread) { 94897206d57SZachary Turner Status error; 949d37349f3SPavel Labath NativeRegisterContext& register_context = thread.GetRegisterContext(); 950e7708688STamas Berghammer 951e7708688STamas Berghammer std::unique_ptr<EmulateInstruction> emulator_ap( 952b9c1b51eSKate Stone EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, 953b9c1b51eSKate Stone nullptr)); 954e7708688STamas Berghammer 955e7708688STamas Berghammer if (emulator_ap == nullptr) 95697206d57SZachary Turner return Status("Instruction emulator not found!"); 957e7708688STamas Berghammer 958d37349f3SPavel Labath EmulatorBaton baton(*this, register_context); 959e7708688STamas Berghammer emulator_ap->SetBaton(&baton); 960e7708688STamas Berghammer emulator_ap->SetReadMemCallback(&ReadMemoryCallback); 961e7708688STamas Berghammer emulator_ap->SetReadRegCallback(&ReadRegisterCallback); 962e7708688STamas Berghammer emulator_ap->SetWriteMemCallback(&WriteMemoryCallback); 963e7708688STamas Berghammer emulator_ap->SetWriteRegCallback(&WriteRegisterCallback); 964e7708688STamas Berghammer 965e7708688STamas Berghammer if (!emulator_ap->ReadInstruction()) 96697206d57SZachary Turner return Status("Read instruction failed!"); 967e7708688STamas Berghammer 968b9c1b51eSKate Stone bool emulation_result = 969b9c1b51eSKate Stone emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC); 9706648fcc3SPavel Labath 971d37349f3SPavel Labath const RegisterInfo *reg_info_pc = register_context.GetRegisterInfo( 972b9c1b51eSKate Stone eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC); 973d37349f3SPavel Labath const RegisterInfo *reg_info_flags = register_context.GetRegisterInfo( 974b9c1b51eSKate Stone eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS); 9756648fcc3SPavel Labath 976b9c1b51eSKate Stone auto pc_it = 977b9c1b51eSKate Stone baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]); 978b9c1b51eSKate Stone auto flags_it = 979b9c1b51eSKate Stone baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]); 9806648fcc3SPavel Labath 981e7708688STamas Berghammer lldb::addr_t next_pc; 982e7708688STamas Berghammer lldb::addr_t next_flags; 983b9c1b51eSKate Stone if (emulation_result) { 984b9c1b51eSKate Stone assert(pc_it != baton.m_register_values.end() && 985b9c1b51eSKate Stone "Emulation was successfull but PC wasn't updated"); 9866648fcc3SPavel Labath next_pc = pc_it->second.GetAsUInt64(); 9876648fcc3SPavel Labath 9886648fcc3SPavel Labath if (flags_it != baton.m_register_values.end()) 9896648fcc3SPavel Labath next_flags = flags_it->second.GetAsUInt64(); 990e7708688STamas Berghammer else 991d37349f3SPavel Labath next_flags = ReadFlags(register_context); 992b9c1b51eSKate Stone } else if (pc_it == baton.m_register_values.end()) { 99305097246SAdrian Prantl // Emulate instruction failed and it haven't changed PC. Advance PC with 99405097246SAdrian Prantl // the size of the current opcode because the emulation of all 995e7708688STamas Berghammer // PC modifying instruction should be successful. The failure most 996e7708688STamas Berghammer // likely caused by a not supported instruction which don't modify PC. 997d37349f3SPavel Labath next_pc = register_context.GetPC() + emulator_ap->GetOpcode().GetByteSize(); 998d37349f3SPavel Labath next_flags = ReadFlags(register_context); 999b9c1b51eSKate Stone } else { 1000e7708688STamas Berghammer // The instruction emulation failed after it modified the PC. It is an 1001e7708688STamas Berghammer // unknown error where we can't continue because the next instruction is 1002e7708688STamas Berghammer // modifying the PC but we don't know how. 100397206d57SZachary Turner return Status("Instruction emulation failed unexpectedly."); 1004e7708688STamas Berghammer } 1005e7708688STamas Berghammer 1006b9c1b51eSKate Stone if (m_arch.GetMachine() == llvm::Triple::arm) { 1007b9c1b51eSKate Stone if (next_flags & 0x20) { 1008e7708688STamas Berghammer // Thumb mode 1009e7708688STamas Berghammer error = SetSoftwareBreakpoint(next_pc, 2); 1010b9c1b51eSKate Stone } else { 1011e7708688STamas Berghammer // Arm mode 1012e7708688STamas Berghammer error = SetSoftwareBreakpoint(next_pc, 4); 1013e7708688STamas Berghammer } 1014b9c1b51eSKate Stone } else if (m_arch.GetMachine() == llvm::Triple::mips64 || 1015b9c1b51eSKate Stone m_arch.GetMachine() == llvm::Triple::mips64el || 1016b9c1b51eSKate Stone m_arch.GetMachine() == llvm::Triple::mips || 1017aae0a752SEugene Zemtsov m_arch.GetMachine() == llvm::Triple::mipsel || 1018aae0a752SEugene Zemtsov m_arch.GetMachine() == llvm::Triple::ppc64le) 1019cdc22a88SMohit K. Bhakkad error = SetSoftwareBreakpoint(next_pc, 4); 1020b9c1b51eSKate Stone else { 1021e7708688STamas Berghammer // No size hint is given for the next breakpoint 1022e7708688STamas Berghammer error = SetSoftwareBreakpoint(next_pc, 0); 1023e7708688STamas Berghammer } 1024e7708688STamas Berghammer 102505097246SAdrian Prantl // If setting the breakpoint fails because next_pc is out of the address 102605097246SAdrian Prantl // space, ignore it and let the debugee segfault. 102742eb6908SPavel Labath if (error.GetError() == EIO || error.GetError() == EFAULT) { 102897206d57SZachary Turner return Status(); 102942eb6908SPavel Labath } else if (error.Fail()) 1030e7708688STamas Berghammer return error; 1031e7708688STamas Berghammer 1032b9cc0c75SPavel Labath m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc}); 1033e7708688STamas Berghammer 103497206d57SZachary Turner return Status(); 1035e7708688STamas Berghammer } 1036e7708688STamas Berghammer 1037b9c1b51eSKate Stone bool NativeProcessLinux::SupportHardwareSingleStepping() const { 1038b9c1b51eSKate Stone if (m_arch.GetMachine() == llvm::Triple::arm || 1039b9c1b51eSKate Stone m_arch.GetMachine() == llvm::Triple::mips64 || 1040b9c1b51eSKate Stone m_arch.GetMachine() == llvm::Triple::mips64el || 1041b9c1b51eSKate Stone m_arch.GetMachine() == llvm::Triple::mips || 1042b9c1b51eSKate Stone m_arch.GetMachine() == llvm::Triple::mipsel) 1043cdc22a88SMohit K. Bhakkad return false; 1044cdc22a88SMohit K. Bhakkad return true; 1045e7708688STamas Berghammer } 1046e7708688STamas Berghammer 104797206d57SZachary Turner Status NativeProcessLinux::Resume(const ResumeActionList &resume_actions) { 1048a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1049a6321a8eSPavel Labath LLDB_LOG(log, "pid {0}", GetID()); 1050af245d11STodd Fiala 1051e7708688STamas Berghammer bool software_single_step = !SupportHardwareSingleStepping(); 1052af245d11STodd Fiala 1053b9c1b51eSKate Stone if (software_single_step) { 1054a5be48b3SPavel Labath for (const auto &thread : m_threads) { 1055a5be48b3SPavel Labath assert(thread && "thread list should not contain NULL threads"); 1056e7708688STamas Berghammer 1057b9c1b51eSKate Stone const ResumeAction *const action = 1058a5be48b3SPavel Labath resume_actions.GetActionForThread(thread->GetID(), true); 1059e7708688STamas Berghammer if (action == nullptr) 1060e7708688STamas Berghammer continue; 1061e7708688STamas Berghammer 1062b9c1b51eSKate Stone if (action->state == eStateStepping) { 106397206d57SZachary Turner Status error = SetupSoftwareSingleStepping( 1064a5be48b3SPavel Labath static_cast<NativeThreadLinux &>(*thread)); 1065e7708688STamas Berghammer if (error.Fail()) 1066e7708688STamas Berghammer return error; 1067e7708688STamas Berghammer } 1068e7708688STamas Berghammer } 1069e7708688STamas Berghammer } 1070e7708688STamas Berghammer 1071a5be48b3SPavel Labath for (const auto &thread : m_threads) { 1072a5be48b3SPavel Labath assert(thread && "thread list should not contain NULL threads"); 1073af245d11STodd Fiala 1074b9c1b51eSKate Stone const ResumeAction *const action = 1075a5be48b3SPavel Labath resume_actions.GetActionForThread(thread->GetID(), true); 10766a196ce6SChaoren Lin 1077b9c1b51eSKate Stone if (action == nullptr) { 1078a6321a8eSPavel Labath LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(), 1079a5be48b3SPavel Labath thread->GetID()); 10806a196ce6SChaoren Lin continue; 10816a196ce6SChaoren Lin } 1082af245d11STodd Fiala 1083a6321a8eSPavel Labath LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}", 1084a5be48b3SPavel Labath action->state, GetID(), thread->GetID()); 1085af245d11STodd Fiala 1086b9c1b51eSKate Stone switch (action->state) { 1087af245d11STodd Fiala case eStateRunning: 1088b9c1b51eSKate Stone case eStateStepping: { 1089af245d11STodd Fiala // Run the thread, possibly feeding it the signal. 1090fa03ad2eSChaoren Lin const int signo = action->signal; 1091a5be48b3SPavel Labath ResumeThread(static_cast<NativeThreadLinux &>(*thread), action->state, 1092b9c1b51eSKate Stone signo); 1093af245d11STodd Fiala break; 1094ae29d395SChaoren Lin } 1095af245d11STodd Fiala 1096af245d11STodd Fiala case eStateSuspended: 1097af245d11STodd Fiala case eStateStopped: 1098a6321a8eSPavel Labath llvm_unreachable("Unexpected state"); 1099af245d11STodd Fiala 1100af245d11STodd Fiala default: 110197206d57SZachary Turner return Status("NativeProcessLinux::%s (): unexpected state %s specified " 1102b9c1b51eSKate Stone "for pid %" PRIu64 ", tid %" PRIu64, 1103b9c1b51eSKate Stone __FUNCTION__, StateAsCString(action->state), GetID(), 1104a5be48b3SPavel Labath thread->GetID()); 1105af245d11STodd Fiala } 1106af245d11STodd Fiala } 1107af245d11STodd Fiala 110897206d57SZachary Turner return Status(); 1109af245d11STodd Fiala } 1110af245d11STodd Fiala 111197206d57SZachary Turner Status NativeProcessLinux::Halt() { 111297206d57SZachary Turner Status error; 1113af245d11STodd Fiala 1114af245d11STodd Fiala if (kill(GetID(), SIGSTOP) != 0) 1115af245d11STodd Fiala error.SetErrorToErrno(); 1116af245d11STodd Fiala 1117af245d11STodd Fiala return error; 1118af245d11STodd Fiala } 1119af245d11STodd Fiala 112097206d57SZachary Turner Status NativeProcessLinux::Detach() { 112197206d57SZachary Turner Status error; 1122af245d11STodd Fiala 1123af245d11STodd Fiala // Stop monitoring the inferior. 112419cbe96aSPavel Labath m_sigchld_handle.reset(); 1125af245d11STodd Fiala 11267a9495bcSPavel Labath // Tell ptrace to detach from the process. 11277a9495bcSPavel Labath if (GetID() == LLDB_INVALID_PROCESS_ID) 11287a9495bcSPavel Labath return error; 11297a9495bcSPavel Labath 1130a5be48b3SPavel Labath for (const auto &thread : m_threads) { 1131a5be48b3SPavel Labath Status e = Detach(thread->GetID()); 11327a9495bcSPavel Labath if (e.Fail()) 1133b9c1b51eSKate Stone error = 1134b9c1b51eSKate Stone e; // Save the error, but still attempt to detach from other threads. 11357a9495bcSPavel Labath } 11367a9495bcSPavel Labath 113799e37695SRavitheja Addepally m_processor_trace_monitor.clear(); 113899e37695SRavitheja Addepally m_pt_proces_trace_id = LLDB_INVALID_UID; 113999e37695SRavitheja Addepally 1140af245d11STodd Fiala return error; 1141af245d11STodd Fiala } 1142af245d11STodd Fiala 114397206d57SZachary Turner Status NativeProcessLinux::Signal(int signo) { 114497206d57SZachary Turner Status error; 1145af245d11STodd Fiala 1146a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1147a6321a8eSPavel Labath LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo, 1148a6321a8eSPavel Labath Host::GetSignalAsCString(signo), GetID()); 1149af245d11STodd Fiala 1150af245d11STodd Fiala if (kill(GetID(), signo)) 1151af245d11STodd Fiala error.SetErrorToErrno(); 1152af245d11STodd Fiala 1153af245d11STodd Fiala return error; 1154af245d11STodd Fiala } 1155af245d11STodd Fiala 115697206d57SZachary Turner Status NativeProcessLinux::Interrupt() { 115705097246SAdrian Prantl // Pick a running thread (or if none, a not-dead stopped thread) as the 115805097246SAdrian Prantl // chosen thread that will be the stop-reason thread. 1159a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1160e9547b80SChaoren Lin 1161a5be48b3SPavel Labath NativeThreadProtocol *running_thread = nullptr; 1162a5be48b3SPavel Labath NativeThreadProtocol *stopped_thread = nullptr; 1163e9547b80SChaoren Lin 1164a6321a8eSPavel Labath LLDB_LOG(log, "selecting running thread for interrupt target"); 1165a5be48b3SPavel Labath for (const auto &thread : m_threads) { 116605097246SAdrian Prantl // If we have a running or stepping thread, we'll call that the target of 116705097246SAdrian Prantl // the interrupt. 1168a5be48b3SPavel Labath const auto thread_state = thread->GetState(); 1169b9c1b51eSKate Stone if (thread_state == eStateRunning || thread_state == eStateStepping) { 1170a5be48b3SPavel Labath running_thread = thread.get(); 1171e9547b80SChaoren Lin break; 1172a5be48b3SPavel Labath } else if (!stopped_thread && StateIsStoppedState(thread_state, true)) { 117305097246SAdrian Prantl // Remember the first non-dead stopped thread. We'll use that as a 117405097246SAdrian Prantl // backup if there are no running threads. 1175a5be48b3SPavel Labath stopped_thread = thread.get(); 1176e9547b80SChaoren Lin } 1177e9547b80SChaoren Lin } 1178e9547b80SChaoren Lin 1179a5be48b3SPavel Labath if (!running_thread && !stopped_thread) { 118097206d57SZachary Turner Status error("found no running/stepping or live stopped threads as target " 1181b9c1b51eSKate Stone "for interrupt"); 1182a6321a8eSPavel Labath LLDB_LOG(log, "skipping due to error: {0}", error); 11835830aa75STamas Berghammer 1184e9547b80SChaoren Lin return error; 1185e9547b80SChaoren Lin } 1186e9547b80SChaoren Lin 1187a5be48b3SPavel Labath NativeThreadProtocol *deferred_signal_thread = 1188a5be48b3SPavel Labath running_thread ? running_thread : stopped_thread; 1189e9547b80SChaoren Lin 1190a6321a8eSPavel Labath LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(), 1191a5be48b3SPavel Labath running_thread ? "running" : "stopped", 1192a5be48b3SPavel Labath deferred_signal_thread->GetID()); 1193e9547b80SChaoren Lin 1194a5be48b3SPavel Labath StopRunningThreads(deferred_signal_thread->GetID()); 119545f5cb31SPavel Labath 119697206d57SZachary Turner return Status(); 1197e9547b80SChaoren Lin } 1198e9547b80SChaoren Lin 119997206d57SZachary Turner Status NativeProcessLinux::Kill() { 1200a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1201a6321a8eSPavel Labath LLDB_LOG(log, "pid {0}", GetID()); 1202af245d11STodd Fiala 120397206d57SZachary Turner Status error; 1204af245d11STodd Fiala 1205b9c1b51eSKate Stone switch (m_state) { 1206af245d11STodd Fiala case StateType::eStateInvalid: 1207af245d11STodd Fiala case StateType::eStateExited: 1208af245d11STodd Fiala case StateType::eStateCrashed: 1209af245d11STodd Fiala case StateType::eStateDetached: 1210af245d11STodd Fiala case StateType::eStateUnloaded: 1211af245d11STodd Fiala // Nothing to do - the process is already dead. 1212a6321a8eSPavel Labath LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(), 12138198db30SPavel Labath m_state); 1214af245d11STodd Fiala return error; 1215af245d11STodd Fiala 1216af245d11STodd Fiala case StateType::eStateConnected: 1217af245d11STodd Fiala case StateType::eStateAttaching: 1218af245d11STodd Fiala case StateType::eStateLaunching: 1219af245d11STodd Fiala case StateType::eStateStopped: 1220af245d11STodd Fiala case StateType::eStateRunning: 1221af245d11STodd Fiala case StateType::eStateStepping: 1222af245d11STodd Fiala case StateType::eStateSuspended: 1223af245d11STodd Fiala // We can try to kill a process in these states. 1224af245d11STodd Fiala break; 1225af245d11STodd Fiala } 1226af245d11STodd Fiala 1227b9c1b51eSKate Stone if (kill(GetID(), SIGKILL) != 0) { 1228af245d11STodd Fiala error.SetErrorToErrno(); 1229af245d11STodd Fiala return error; 1230af245d11STodd Fiala } 1231af245d11STodd Fiala 1232af245d11STodd Fiala return error; 1233af245d11STodd Fiala } 1234af245d11STodd Fiala 123597206d57SZachary Turner Status NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr, 1236b9c1b51eSKate Stone MemoryRegionInfo &range_info) { 1237b9c1b51eSKate Stone // FIXME review that the final memory region returned extends to the end of 1238b9c1b51eSKate Stone // the virtual address space, 1239af245d11STodd Fiala // with no perms if it is not mapped. 1240af245d11STodd Fiala 124105097246SAdrian Prantl // Use an approach that reads memory regions from /proc/{pid}/maps. Assume 124205097246SAdrian Prantl // proc maps entries are in ascending order. 1243af245d11STodd Fiala // FIXME assert if we find differently. 1244af245d11STodd Fiala 1245b9c1b51eSKate Stone if (m_supports_mem_region == LazyBool::eLazyBoolNo) { 1246af245d11STodd Fiala // We're done. 124797206d57SZachary Turner return Status("unsupported"); 1248af245d11STodd Fiala } 1249af245d11STodd Fiala 125097206d57SZachary Turner Status error = PopulateMemoryRegionCache(); 1251b9c1b51eSKate Stone if (error.Fail()) { 1252af245d11STodd Fiala return error; 1253af245d11STodd Fiala } 1254af245d11STodd Fiala 1255af245d11STodd Fiala lldb::addr_t prev_base_address = 0; 1256af245d11STodd Fiala 1257b9c1b51eSKate Stone // FIXME start by finding the last region that is <= target address using 1258b9c1b51eSKate Stone // binary search. Data is sorted. 1259af245d11STodd Fiala // There can be a ton of regions on pthreads apps with lots of threads. 1260b9c1b51eSKate Stone for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end(); 1261b9c1b51eSKate Stone ++it) { 1262a6f5795aSTamas Berghammer MemoryRegionInfo &proc_entry_info = it->first; 1263af245d11STodd Fiala 1264af245d11STodd Fiala // Sanity check assumption that /proc/{pid}/maps entries are ascending. 1265b9c1b51eSKate Stone assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) && 1266b9c1b51eSKate Stone "descending /proc/pid/maps entries detected, unexpected"); 1267af245d11STodd Fiala prev_base_address = proc_entry_info.GetRange().GetRangeBase(); 1268b1554311SHafiz Abid Qadeer UNUSED_IF_ASSERT_DISABLED(prev_base_address); 1269af245d11STodd Fiala 1270b9c1b51eSKate Stone // If the target address comes before this entry, indicate distance to next 1271b9c1b51eSKate Stone // region. 1272b9c1b51eSKate Stone if (load_addr < proc_entry_info.GetRange().GetRangeBase()) { 1273af245d11STodd Fiala range_info.GetRange().SetRangeBase(load_addr); 1274b9c1b51eSKate Stone range_info.GetRange().SetByteSize( 1275b9c1b51eSKate Stone proc_entry_info.GetRange().GetRangeBase() - load_addr); 1276af245d11STodd Fiala range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo); 1277af245d11STodd Fiala range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo); 1278af245d11STodd Fiala range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo); 1279ad007563SHoward Hellyer range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo); 1280af245d11STodd Fiala 1281af245d11STodd Fiala return error; 1282b9c1b51eSKate Stone } else if (proc_entry_info.GetRange().Contains(load_addr)) { 1283af245d11STodd Fiala // The target address is within the memory region we're processing here. 1284af245d11STodd Fiala range_info = proc_entry_info; 1285af245d11STodd Fiala return error; 1286af245d11STodd Fiala } 1287af245d11STodd Fiala 1288b9c1b51eSKate Stone // The target memory address comes somewhere after the region we just 1289b9c1b51eSKate Stone // parsed. 1290af245d11STodd Fiala } 1291af245d11STodd Fiala 1292b9c1b51eSKate Stone // If we made it here, we didn't find an entry that contained the given 129305097246SAdrian Prantl // address. Return the load_addr as start and the amount of bytes betwwen 129405097246SAdrian Prantl // load address and the end of the memory as size. 129509839c33STamas Berghammer range_info.GetRange().SetRangeBase(load_addr); 1296ad007563SHoward Hellyer range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS); 129709839c33STamas Berghammer range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo); 129809839c33STamas Berghammer range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo); 129909839c33STamas Berghammer range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo); 1300ad007563SHoward Hellyer range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo); 1301af245d11STodd Fiala return error; 1302af245d11STodd Fiala } 1303af245d11STodd Fiala 130497206d57SZachary Turner Status NativeProcessLinux::PopulateMemoryRegionCache() { 1305a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1306a6f5795aSTamas Berghammer 1307a6f5795aSTamas Berghammer // If our cache is empty, pull the latest. There should always be at least 1308a6f5795aSTamas Berghammer // one memory region if memory region handling is supported. 1309a6f5795aSTamas Berghammer if (!m_mem_region_cache.empty()) { 1310a6321a8eSPavel Labath LLDB_LOG(log, "reusing {0} cached memory region entries", 1311a6321a8eSPavel Labath m_mem_region_cache.size()); 131297206d57SZachary Turner return Status(); 1313a6f5795aSTamas Berghammer } 1314a6f5795aSTamas Berghammer 131515930862SPavel Labath auto BufferOrError = getProcFile(GetID(), "maps"); 131615930862SPavel Labath if (!BufferOrError) { 131715930862SPavel Labath m_supports_mem_region = LazyBool::eLazyBoolNo; 131815930862SPavel Labath return BufferOrError.getError(); 131915930862SPavel Labath } 1320c8e364e8SPavel Labath Status Result; 1321c8e364e8SPavel Labath ParseLinuxMapRegions(BufferOrError.get()->getBuffer(), 1322c8e364e8SPavel Labath [&](const MemoryRegionInfo &Info, const Status &ST) { 1323c8e364e8SPavel Labath if (ST.Success()) { 1324c8e364e8SPavel Labath FileSpec file_spec(Info.GetName().GetCString()); 13258f3be7a3SJonas Devlieghere FileSystem::Instance().Resolve(file_spec); 1326c8e364e8SPavel Labath m_mem_region_cache.emplace_back(Info, file_spec); 1327c8e364e8SPavel Labath return true; 1328c8e364e8SPavel Labath } else { 1329c8e364e8SPavel Labath m_supports_mem_region = LazyBool::eLazyBoolNo; 1330c8e364e8SPavel Labath LLDB_LOG(log, "failed to parse proc maps: {0}", ST); 1331c8e364e8SPavel Labath Result = ST; 1332c8e364e8SPavel Labath return false; 1333a6f5795aSTamas Berghammer } 1334c8e364e8SPavel Labath }); 1335c8e364e8SPavel Labath if (Result.Fail()) 1336c8e364e8SPavel Labath return Result; 1337a6f5795aSTamas Berghammer 133815930862SPavel Labath if (m_mem_region_cache.empty()) { 1339a6f5795aSTamas Berghammer // No entries after attempting to read them. This shouldn't happen if 134005097246SAdrian Prantl // /proc/{pid}/maps is supported. Assume we don't support map entries via 134105097246SAdrian Prantl // procfs. 134215930862SPavel Labath m_supports_mem_region = LazyBool::eLazyBoolNo; 1343a6321a8eSPavel Labath LLDB_LOG(log, 1344a6321a8eSPavel Labath "failed to find any procfs maps entries, assuming no support " 1345a6321a8eSPavel Labath "for memory region metadata retrieval"); 134697206d57SZachary Turner return Status("not supported"); 1347a6f5795aSTamas Berghammer } 1348a6f5795aSTamas Berghammer 1349a6321a8eSPavel Labath LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps", 1350a6321a8eSPavel Labath m_mem_region_cache.size(), GetID()); 1351a6f5795aSTamas Berghammer 1352a6f5795aSTamas Berghammer // We support memory retrieval, remember that. 1353a6f5795aSTamas Berghammer m_supports_mem_region = LazyBool::eLazyBoolYes; 135497206d57SZachary Turner return Status(); 1355a6f5795aSTamas Berghammer } 1356a6f5795aSTamas Berghammer 1357b9c1b51eSKate Stone void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) { 1358a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1359a6321a8eSPavel Labath LLDB_LOG(log, "newBumpId={0}", newBumpId); 1360a6321a8eSPavel Labath LLDB_LOG(log, "clearing {0} entries from memory region cache", 1361a6321a8eSPavel Labath m_mem_region_cache.size()); 1362af245d11STodd Fiala m_mem_region_cache.clear(); 1363af245d11STodd Fiala } 1364af245d11STodd Fiala 136597206d57SZachary Turner Status NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, 1366b9c1b51eSKate Stone lldb::addr_t &addr) { 1367af245d11STodd Fiala // FIXME implementing this requires the equivalent of 136805097246SAdrian Prantl // InferiorCallPOSIX::InferiorCallMmap, which depends on functional ThreadPlans 136905097246SAdrian Prantl // working with Native*Protocol. 1370af245d11STodd Fiala #if 1 137197206d57SZachary Turner return Status("not implemented yet"); 1372af245d11STodd Fiala #else 1373af245d11STodd Fiala addr = LLDB_INVALID_ADDRESS; 1374af245d11STodd Fiala 1375af245d11STodd Fiala unsigned prot = 0; 1376af245d11STodd Fiala if (permissions & lldb::ePermissionsReadable) 1377af245d11STodd Fiala prot |= eMmapProtRead; 1378af245d11STodd Fiala if (permissions & lldb::ePermissionsWritable) 1379af245d11STodd Fiala prot |= eMmapProtWrite; 1380af245d11STodd Fiala if (permissions & lldb::ePermissionsExecutable) 1381af245d11STodd Fiala prot |= eMmapProtExec; 1382af245d11STodd Fiala 1383af245d11STodd Fiala // TODO implement this directly in NativeProcessLinux 138405097246SAdrian Prantl // (and lift to NativeProcessPOSIX if/when that class is refactored out). 1385af245d11STodd Fiala if (InferiorCallMmap(this, addr, 0, size, prot, 1386af245d11STodd Fiala eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) { 1387af245d11STodd Fiala m_addr_to_mmap_size[addr] = size; 138897206d57SZachary Turner return Status(); 1389af245d11STodd Fiala } else { 1390af245d11STodd Fiala addr = LLDB_INVALID_ADDRESS; 139197206d57SZachary Turner return Status("unable to allocate %" PRIu64 1392b9c1b51eSKate Stone " bytes of memory with permissions %s", 1393b9c1b51eSKate Stone size, GetPermissionsAsCString(permissions)); 1394af245d11STodd Fiala } 1395af245d11STodd Fiala #endif 1396af245d11STodd Fiala } 1397af245d11STodd Fiala 139897206d57SZachary Turner Status NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) { 1399af245d11STodd Fiala // FIXME see comments in AllocateMemory - required lower-level 1400af245d11STodd Fiala // bits not in place yet (ThreadPlans) 140197206d57SZachary Turner return Status("not implemented"); 1402af245d11STodd Fiala } 1403af245d11STodd Fiala 1404b9c1b51eSKate Stone lldb::addr_t NativeProcessLinux::GetSharedLibraryInfoAddress() { 1405af245d11STodd Fiala // punt on this for now 1406af245d11STodd Fiala return LLDB_INVALID_ADDRESS; 1407af245d11STodd Fiala } 1408af245d11STodd Fiala 1409b9c1b51eSKate Stone size_t NativeProcessLinux::UpdateThreads() { 141005097246SAdrian Prantl // The NativeProcessLinux monitoring threads are always up to date with 141105097246SAdrian Prantl // respect to thread state and they keep the thread list populated properly. 141205097246SAdrian Prantl // All this method needs to do is return the thread count. 1413af245d11STodd Fiala return m_threads.size(); 1414af245d11STodd Fiala } 1415af245d11STodd Fiala 141697206d57SZachary Turner Status NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size, 1417b9c1b51eSKate Stone bool hardware) { 1418af245d11STodd Fiala if (hardware) 1419d5ffbad2SOmair Javaid return SetHardwareBreakpoint(addr, size); 1420af245d11STodd Fiala else 1421af245d11STodd Fiala return SetSoftwareBreakpoint(addr, size); 1422af245d11STodd Fiala } 1423af245d11STodd Fiala 142497206d57SZachary Turner Status NativeProcessLinux::RemoveBreakpoint(lldb::addr_t addr, bool hardware) { 1425d5ffbad2SOmair Javaid if (hardware) 1426d5ffbad2SOmair Javaid return RemoveHardwareBreakpoint(addr); 1427d5ffbad2SOmair Javaid else 1428d5ffbad2SOmair Javaid return NativeProcessProtocol::RemoveBreakpoint(addr); 1429d5ffbad2SOmair Javaid } 1430d5ffbad2SOmair Javaid 1431f8b825f6SPavel Labath llvm::Expected<llvm::ArrayRef<uint8_t>> 1432f8b825f6SPavel Labath NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(size_t size_hint) { 1433be379e15STamas Berghammer // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the 1434be379e15STamas Berghammer // linux kernel does otherwise. 1435f8b825f6SPavel Labath static const uint8_t g_arm_opcode[] = {0xf0, 0x01, 0xf0, 0xe7}; 1436f8b825f6SPavel Labath static const uint8_t g_thumb_opcode[] = {0x01, 0xde}; 143712286a27SPavel Labath 1438f8b825f6SPavel Labath switch (GetArchitecture().GetMachine()) { 143912286a27SPavel Labath case llvm::Triple::arm: 1440f8b825f6SPavel Labath switch (size_hint) { 144163c8be95STamas Berghammer case 2: 14424f545074SPavel Labath return llvm::makeArrayRef(g_thumb_opcode); 144363c8be95STamas Berghammer case 4: 14444f545074SPavel Labath return llvm::makeArrayRef(g_arm_opcode); 144563c8be95STamas Berghammer default: 1446f8b825f6SPavel Labath return llvm::createStringError(llvm::inconvertibleErrorCode(), 1447f8b825f6SPavel Labath "Unrecognised trap opcode size hint!"); 144863c8be95STamas Berghammer } 1449af245d11STodd Fiala default: 1450f8b825f6SPavel Labath return NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_hint); 1451af245d11STodd Fiala } 1452af245d11STodd Fiala } 1453af245d11STodd Fiala 145497206d57SZachary Turner Status NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size, 1455b9c1b51eSKate Stone size_t &bytes_read) { 1456df7c6995SPavel Labath if (ProcessVmReadvSupported()) { 1457b9c1b51eSKate Stone // The process_vm_readv path is about 50 times faster than ptrace api. We 145805097246SAdrian Prantl // want to use this syscall if it is supported. 1459df7c6995SPavel Labath 1460df7c6995SPavel Labath const ::pid_t pid = GetID(); 1461df7c6995SPavel Labath 1462df7c6995SPavel Labath struct iovec local_iov, remote_iov; 1463df7c6995SPavel Labath local_iov.iov_base = buf; 1464df7c6995SPavel Labath local_iov.iov_len = size; 1465df7c6995SPavel Labath remote_iov.iov_base = reinterpret_cast<void *>(addr); 1466df7c6995SPavel Labath remote_iov.iov_len = size; 1467df7c6995SPavel Labath 1468df7c6995SPavel Labath bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0); 1469df7c6995SPavel Labath const bool success = bytes_read == size; 1470df7c6995SPavel Labath 1471a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1472a6321a8eSPavel Labath LLDB_LOG(log, 1473a6321a8eSPavel Labath "using process_vm_readv to read {0} bytes from inferior " 1474a6321a8eSPavel Labath "address {1:x}: {2}", 147510c41f37SPavel Labath size, addr, success ? "Success" : llvm::sys::StrError(errno)); 1476df7c6995SPavel Labath 1477df7c6995SPavel Labath if (success) 147897206d57SZachary Turner return Status(); 1479a6321a8eSPavel Labath // else the call failed for some reason, let's retry the read using ptrace 1480b9c1b51eSKate Stone // api. 1481df7c6995SPavel Labath } 1482df7c6995SPavel Labath 148319cbe96aSPavel Labath unsigned char *dst = static_cast<unsigned char *>(buf); 148419cbe96aSPavel Labath size_t remainder; 148519cbe96aSPavel Labath long data; 148619cbe96aSPavel Labath 1487a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY)); 1488a6321a8eSPavel Labath LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size); 148919cbe96aSPavel Labath 1490b9c1b51eSKate Stone for (bytes_read = 0; bytes_read < size; bytes_read += remainder) { 149197206d57SZachary Turner Status error = NativeProcessLinux::PtraceWrapper( 1492b9c1b51eSKate Stone PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data); 1493a6321a8eSPavel Labath if (error.Fail()) 149419cbe96aSPavel Labath return error; 149519cbe96aSPavel Labath 149619cbe96aSPavel Labath remainder = size - bytes_read; 149719cbe96aSPavel Labath remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder; 149819cbe96aSPavel Labath 149919cbe96aSPavel Labath // Copy the data into our buffer 1500f6ef187bSMohit K. Bhakkad memcpy(dst, &data, remainder); 150119cbe96aSPavel Labath 1502a6321a8eSPavel Labath LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data); 150319cbe96aSPavel Labath addr += k_ptrace_word_size; 150419cbe96aSPavel Labath dst += k_ptrace_word_size; 150519cbe96aSPavel Labath } 150697206d57SZachary Turner return Status(); 1507af245d11STodd Fiala } 1508af245d11STodd Fiala 150997206d57SZachary Turner Status NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, 1510b9c1b51eSKate Stone size_t size, size_t &bytes_written) { 151119cbe96aSPavel Labath const unsigned char *src = static_cast<const unsigned char *>(buf); 151219cbe96aSPavel Labath size_t remainder; 151397206d57SZachary Turner Status error; 151419cbe96aSPavel Labath 1515a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY)); 1516a6321a8eSPavel Labath LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size); 151719cbe96aSPavel Labath 1518b9c1b51eSKate Stone for (bytes_written = 0; bytes_written < size; bytes_written += remainder) { 151919cbe96aSPavel Labath remainder = size - bytes_written; 152019cbe96aSPavel Labath remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder; 152119cbe96aSPavel Labath 1522b9c1b51eSKate Stone if (remainder == k_ptrace_word_size) { 152319cbe96aSPavel Labath unsigned long data = 0; 1524f6ef187bSMohit K. Bhakkad memcpy(&data, src, k_ptrace_word_size); 152519cbe96aSPavel Labath 1526a6321a8eSPavel Labath LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data); 1527b9c1b51eSKate Stone error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(), 1528b9c1b51eSKate Stone (void *)addr, (void *)data); 1529a6321a8eSPavel Labath if (error.Fail()) 153019cbe96aSPavel Labath return error; 1531b9c1b51eSKate Stone } else { 153219cbe96aSPavel Labath unsigned char buff[8]; 153319cbe96aSPavel Labath size_t bytes_read; 153419cbe96aSPavel Labath error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read); 1535a6321a8eSPavel Labath if (error.Fail()) 153619cbe96aSPavel Labath return error; 153719cbe96aSPavel Labath 153819cbe96aSPavel Labath memcpy(buff, src, remainder); 153919cbe96aSPavel Labath 154019cbe96aSPavel Labath size_t bytes_written_rec; 154119cbe96aSPavel Labath error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec); 1542a6321a8eSPavel Labath if (error.Fail()) 154319cbe96aSPavel Labath return error; 154419cbe96aSPavel Labath 1545a6321a8eSPavel Labath LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src, 1546b9c1b51eSKate Stone *(unsigned long *)buff); 154719cbe96aSPavel Labath } 154819cbe96aSPavel Labath 154919cbe96aSPavel Labath addr += k_ptrace_word_size; 155019cbe96aSPavel Labath src += k_ptrace_word_size; 155119cbe96aSPavel Labath } 155219cbe96aSPavel Labath return error; 1553af245d11STodd Fiala } 1554af245d11STodd Fiala 155597206d57SZachary Turner Status NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) { 155619cbe96aSPavel Labath return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo); 1557af245d11STodd Fiala } 1558af245d11STodd Fiala 155997206d57SZachary Turner Status NativeProcessLinux::GetEventMessage(lldb::tid_t tid, 1560b9c1b51eSKate Stone unsigned long *message) { 156119cbe96aSPavel Labath return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message); 1562af245d11STodd Fiala } 1563af245d11STodd Fiala 156497206d57SZachary Turner Status NativeProcessLinux::Detach(lldb::tid_t tid) { 156597ccc294SChaoren Lin if (tid == LLDB_INVALID_THREAD_ID) 156697206d57SZachary Turner return Status(); 156797ccc294SChaoren Lin 156819cbe96aSPavel Labath return PtraceWrapper(PTRACE_DETACH, tid); 1569af245d11STodd Fiala } 1570af245d11STodd Fiala 1571b9c1b51eSKate Stone bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) { 1572a5be48b3SPavel Labath for (const auto &thread : m_threads) { 1573a5be48b3SPavel Labath assert(thread && "thread list should not contain NULL threads"); 1574a5be48b3SPavel Labath if (thread->GetID() == thread_id) { 1575af245d11STodd Fiala // We have this thread. 1576af245d11STodd Fiala return true; 1577af245d11STodd Fiala } 1578af245d11STodd Fiala } 1579af245d11STodd Fiala 1580af245d11STodd Fiala // We don't have this thread. 1581af245d11STodd Fiala return false; 1582af245d11STodd Fiala } 1583af245d11STodd Fiala 1584b9c1b51eSKate Stone bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) { 1585a6321a8eSPavel Labath Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD); 1586a6321a8eSPavel Labath LLDB_LOG(log, "tid: {0})", thread_id); 15871dbc6c9cSPavel Labath 15881dbc6c9cSPavel Labath bool found = false; 1589b9c1b51eSKate Stone for (auto it = m_threads.begin(); it != m_threads.end(); ++it) { 1590b9c1b51eSKate Stone if (*it && ((*it)->GetID() == thread_id)) { 1591af245d11STodd Fiala m_threads.erase(it); 15921dbc6c9cSPavel Labath found = true; 15931dbc6c9cSPavel Labath break; 1594af245d11STodd Fiala } 1595af245d11STodd Fiala } 1596af245d11STodd Fiala 159799e37695SRavitheja Addepally if (found) 159899e37695SRavitheja Addepally StopTracingForThread(thread_id); 15999eb1ecb9SPavel Labath SignalIfAllThreadsStopped(); 16001dbc6c9cSPavel Labath return found; 1601af245d11STodd Fiala } 1602af245d11STodd Fiala 1603a5be48b3SPavel Labath NativeThreadLinux &NativeProcessLinux::AddThread(lldb::tid_t thread_id) { 1604a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD)); 1605a6321a8eSPavel Labath LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id); 1606af245d11STodd Fiala 1607b9c1b51eSKate Stone assert(!HasThreadNoLock(thread_id) && 1608b9c1b51eSKate Stone "attempted to add a thread by id that already exists"); 1609af245d11STodd Fiala 1610af245d11STodd Fiala // If this is the first thread, save it as the current thread 1611af245d11STodd Fiala if (m_threads.empty()) 1612af245d11STodd Fiala SetCurrentThreadID(thread_id); 1613af245d11STodd Fiala 1614a5be48b3SPavel Labath m_threads.push_back(llvm::make_unique<NativeThreadLinux>(*this, thread_id)); 161599e37695SRavitheja Addepally 161699e37695SRavitheja Addepally if (m_pt_proces_trace_id != LLDB_INVALID_UID) { 161799e37695SRavitheja Addepally auto traceMonitor = ProcessorTraceMonitor::Create( 161899e37695SRavitheja Addepally GetID(), thread_id, m_pt_process_trace_config, true); 161999e37695SRavitheja Addepally if (traceMonitor) { 162099e37695SRavitheja Addepally m_pt_traced_thread_group.insert(thread_id); 162199e37695SRavitheja Addepally m_processor_trace_monitor.insert( 162299e37695SRavitheja Addepally std::make_pair(thread_id, std::move(*traceMonitor))); 162399e37695SRavitheja Addepally } else { 162499e37695SRavitheja Addepally LLDB_LOG(log, "failed to start trace on thread {0}", thread_id); 162599e37695SRavitheja Addepally Status error(traceMonitor.takeError()); 162699e37695SRavitheja Addepally LLDB_LOG(log, "error {0}", error); 162799e37695SRavitheja Addepally } 162899e37695SRavitheja Addepally } 162999e37695SRavitheja Addepally 1630a5be48b3SPavel Labath return static_cast<NativeThreadLinux &>(*m_threads.back()); 1631af245d11STodd Fiala } 1632af245d11STodd Fiala 163397206d57SZachary Turner Status NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path, 1634b9c1b51eSKate Stone FileSpec &file_spec) { 163597206d57SZachary Turner Status error = PopulateMemoryRegionCache(); 1636a6f5795aSTamas Berghammer if (error.Fail()) 1637a6f5795aSTamas Berghammer return error; 1638a6f5795aSTamas Berghammer 16398f3be7a3SJonas Devlieghere FileSpec module_file_spec(module_path); 16408f3be7a3SJonas Devlieghere FileSystem::Instance().Resolve(module_file_spec); 16417cb18bf5STamas Berghammer 16427cb18bf5STamas Berghammer file_spec.Clear(); 1643a6f5795aSTamas Berghammer for (const auto &it : m_mem_region_cache) { 1644a6f5795aSTamas Berghammer if (it.second.GetFilename() == module_file_spec.GetFilename()) { 1645a6f5795aSTamas Berghammer file_spec = it.second; 164697206d57SZachary Turner return Status(); 1647a6f5795aSTamas Berghammer } 1648a6f5795aSTamas Berghammer } 164997206d57SZachary Turner return Status("Module file (%s) not found in /proc/%" PRIu64 "/maps file!", 16507cb18bf5STamas Berghammer module_file_spec.GetFilename().AsCString(), GetID()); 16517cb18bf5STamas Berghammer } 1652c076559aSPavel Labath 165397206d57SZachary Turner Status NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name, 1654b9c1b51eSKate Stone lldb::addr_t &load_addr) { 1655783bfc8cSTamas Berghammer load_addr = LLDB_INVALID_ADDRESS; 165697206d57SZachary Turner Status error = PopulateMemoryRegionCache(); 1657a6f5795aSTamas Berghammer if (error.Fail()) 1658783bfc8cSTamas Berghammer return error; 1659a6f5795aSTamas Berghammer 16608f3be7a3SJonas Devlieghere FileSpec file(file_name); 1661a6f5795aSTamas Berghammer for (const auto &it : m_mem_region_cache) { 1662a6f5795aSTamas Berghammer if (it.second == file) { 1663a6f5795aSTamas Berghammer load_addr = it.first.GetRange().GetRangeBase(); 166497206d57SZachary Turner return Status(); 1665a6f5795aSTamas Berghammer } 1666a6f5795aSTamas Berghammer } 166797206d57SZachary Turner return Status("No load address found for specified file."); 1668783bfc8cSTamas Berghammer } 1669783bfc8cSTamas Berghammer 1670a5be48b3SPavel Labath NativeThreadLinux *NativeProcessLinux::GetThreadByID(lldb::tid_t tid) { 1671a5be48b3SPavel Labath return static_cast<NativeThreadLinux *>( 1672b9c1b51eSKate Stone NativeProcessProtocol::GetThreadByID(tid)); 1673f9077782SPavel Labath } 1674f9077782SPavel Labath 167597206d57SZachary Turner Status NativeProcessLinux::ResumeThread(NativeThreadLinux &thread, 1676b9c1b51eSKate Stone lldb::StateType state, int signo) { 1677a6321a8eSPavel Labath Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD); 1678a6321a8eSPavel Labath LLDB_LOG(log, "tid: {0}", thread.GetID()); 1679c076559aSPavel Labath 168005097246SAdrian Prantl // Before we do the resume below, first check if we have a pending stop 168105097246SAdrian Prantl // notification that is currently waiting for all threads to stop. This is 168205097246SAdrian Prantl // potentially a buggy situation since we're ostensibly waiting for threads 168305097246SAdrian Prantl // to stop before we send out the pending notification, and here we are 168405097246SAdrian Prantl // resuming one before we send out the pending stop notification. 1685a6321a8eSPavel Labath if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) { 1686a6321a8eSPavel Labath LLDB_LOG(log, 1687a6321a8eSPavel Labath "about to resume tid {0} per explicit request but we have a " 1688a6321a8eSPavel Labath "pending stop notification (tid {1}) that is actively " 1689a6321a8eSPavel Labath "waiting for this thread to stop. Valid sequence of events?", 1690a6321a8eSPavel Labath thread.GetID(), m_pending_notification_tid); 1691c076559aSPavel Labath } 1692c076559aSPavel Labath 169305097246SAdrian Prantl // Request a resume. We expect this to be synchronous and the system to 169405097246SAdrian Prantl // reflect it is running after this completes. 1695b9c1b51eSKate Stone switch (state) { 1696b9c1b51eSKate Stone case eStateRunning: { 1697605b51b8SPavel Labath const auto resume_result = thread.Resume(signo); 16980e1d729bSPavel Labath if (resume_result.Success()) 16990e1d729bSPavel Labath SetState(eStateRunning, true); 17000e1d729bSPavel Labath return resume_result; 1701c076559aSPavel Labath } 1702b9c1b51eSKate Stone case eStateStepping: { 1703605b51b8SPavel Labath const auto step_result = thread.SingleStep(signo); 17040e1d729bSPavel Labath if (step_result.Success()) 17050e1d729bSPavel Labath SetState(eStateRunning, true); 17060e1d729bSPavel Labath return step_result; 17070e1d729bSPavel Labath } 17080e1d729bSPavel Labath default: 17098198db30SPavel Labath LLDB_LOG(log, "Unhandled state {0}.", state); 17100e1d729bSPavel Labath llvm_unreachable("Unhandled state for resume"); 17110e1d729bSPavel Labath } 1712c076559aSPavel Labath } 1713c076559aSPavel Labath 1714c076559aSPavel Labath //===----------------------------------------------------------------------===// 1715c076559aSPavel Labath 1716b9c1b51eSKate Stone void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) { 1717a6321a8eSPavel Labath Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD); 1718a6321a8eSPavel Labath LLDB_LOG(log, "about to process event: (triggering_tid: {0})", 1719a6321a8eSPavel Labath triggering_tid); 1720c076559aSPavel Labath 17210e1d729bSPavel Labath m_pending_notification_tid = triggering_tid; 17220e1d729bSPavel Labath 172305097246SAdrian Prantl // Request a stop for all the thread stops that need to be stopped and are 172405097246SAdrian Prantl // not already known to be stopped. 1725a5be48b3SPavel Labath for (const auto &thread : m_threads) { 1726a5be48b3SPavel Labath if (StateIsRunningState(thread->GetState())) 1727a5be48b3SPavel Labath static_cast<NativeThreadLinux *>(thread.get())->RequestStop(); 17280e1d729bSPavel Labath } 17290e1d729bSPavel Labath 17300e1d729bSPavel Labath SignalIfAllThreadsStopped(); 1731a6321a8eSPavel Labath LLDB_LOG(log, "event processing done"); 1732c076559aSPavel Labath } 1733c076559aSPavel Labath 1734b9c1b51eSKate Stone void NativeProcessLinux::SignalIfAllThreadsStopped() { 17350e1d729bSPavel Labath if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID) 17360e1d729bSPavel Labath return; // No pending notification. Nothing to do. 17370e1d729bSPavel Labath 1738b9c1b51eSKate Stone for (const auto &thread_sp : m_threads) { 17390e1d729bSPavel Labath if (StateIsRunningState(thread_sp->GetState())) 17400e1d729bSPavel Labath return; // Some threads are still running. Don't signal yet. 17410e1d729bSPavel Labath } 17420e1d729bSPavel Labath 17430e1d729bSPavel Labath // We have a pending notification and all threads have stopped. 1744b9c1b51eSKate Stone Log *log( 1745b9c1b51eSKate Stone GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS)); 17469eb1ecb9SPavel Labath 1747b9c1b51eSKate Stone // Clear any temporary breakpoints we used to implement software single 1748b9c1b51eSKate Stone // stepping. 1749b9c1b51eSKate Stone for (const auto &thread_info : m_threads_stepping_with_breakpoint) { 175097206d57SZachary Turner Status error = RemoveBreakpoint(thread_info.second); 17519eb1ecb9SPavel Labath if (error.Fail()) 1752a6321a8eSPavel Labath LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}", 1753a6321a8eSPavel Labath thread_info.first, error); 17549eb1ecb9SPavel Labath } 17559eb1ecb9SPavel Labath m_threads_stepping_with_breakpoint.clear(); 17569eb1ecb9SPavel Labath 17579eb1ecb9SPavel Labath // Notify the delegate about the stop 17580e1d729bSPavel Labath SetCurrentThreadID(m_pending_notification_tid); 1759ed89c7feSPavel Labath SetState(StateType::eStateStopped, true); 17600e1d729bSPavel Labath m_pending_notification_tid = LLDB_INVALID_THREAD_ID; 1761c076559aSPavel Labath } 1762c076559aSPavel Labath 1763b9c1b51eSKate Stone void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) { 1764a6321a8eSPavel Labath Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD); 1765a6321a8eSPavel Labath LLDB_LOG(log, "tid: {0}", thread.GetID()); 17661dbc6c9cSPavel Labath 1767b9c1b51eSKate Stone if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID && 1768b9c1b51eSKate Stone StateIsRunningState(thread.GetState())) { 1769b9c1b51eSKate Stone // We will need to wait for this new thread to stop as well before firing 177005097246SAdrian Prantl // the notification. 1771f9077782SPavel Labath thread.RequestStop(); 1772c076559aSPavel Labath } 1773c076559aSPavel Labath } 1774068f8a7eSTamas Berghammer 1775b9c1b51eSKate Stone void NativeProcessLinux::SigchldHandler() { 1776a6321a8eSPavel Labath Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 177719cbe96aSPavel Labath // Process all pending waitpid notifications. 1778b9c1b51eSKate Stone while (true) { 177919cbe96aSPavel Labath int status = -1; 1780c1a6b128SPavel Labath ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, -1, &status, 1781c1a6b128SPavel Labath __WALL | __WNOTHREAD | WNOHANG); 178219cbe96aSPavel Labath 178319cbe96aSPavel Labath if (wait_pid == 0) 178419cbe96aSPavel Labath break; // We are done. 178519cbe96aSPavel Labath 1786b9c1b51eSKate Stone if (wait_pid == -1) { 178797206d57SZachary Turner Status error(errno, eErrorTypePOSIX); 1788a6321a8eSPavel Labath LLDB_LOG(log, "waitpid (-1, &status, _) failed: {0}", error); 178919cbe96aSPavel Labath break; 179019cbe96aSPavel Labath } 179119cbe96aSPavel Labath 17923508fc8cSPavel Labath WaitStatus wait_status = WaitStatus::Decode(status); 17933508fc8cSPavel Labath bool exited = wait_status.type == WaitStatus::Exit || 17943508fc8cSPavel Labath (wait_status.type == WaitStatus::Signal && 17953508fc8cSPavel Labath wait_pid == static_cast<::pid_t>(GetID())); 179619cbe96aSPavel Labath 17973508fc8cSPavel Labath LLDB_LOG( 17983508fc8cSPavel Labath log, 17993508fc8cSPavel Labath "waitpid (-1, &status, _) => pid = {0}, status = {1}, exited = {2}", 18003508fc8cSPavel Labath wait_pid, wait_status, exited); 180119cbe96aSPavel Labath 18023508fc8cSPavel Labath MonitorCallback(wait_pid, exited, wait_status); 180319cbe96aSPavel Labath } 1804068f8a7eSTamas Berghammer } 1805068f8a7eSTamas Berghammer 180605097246SAdrian Prantl // Wrapper for ptrace to catch errors and log calls. Note that ptrace sets 180705097246SAdrian Prantl // errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*) 180897206d57SZachary Turner Status NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr, 1809b9c1b51eSKate Stone void *data, size_t data_size, 1810b9c1b51eSKate Stone long *result) { 181197206d57SZachary Turner Status error; 18124a9babb2SPavel Labath long int ret; 1813068f8a7eSTamas Berghammer 1814068f8a7eSTamas Berghammer Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 1815068f8a7eSTamas Berghammer 1816068f8a7eSTamas Berghammer PtraceDisplayBytes(req, data, data_size); 1817068f8a7eSTamas Berghammer 1818068f8a7eSTamas Berghammer errno = 0; 1819068f8a7eSTamas Berghammer if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET) 1820b9c1b51eSKate Stone ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid), 1821b9c1b51eSKate Stone *(unsigned int *)addr, data); 1822068f8a7eSTamas Berghammer else 1823b9c1b51eSKate Stone ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid), 1824b9c1b51eSKate Stone addr, data); 1825068f8a7eSTamas Berghammer 18264a9babb2SPavel Labath if (ret == -1) 1827068f8a7eSTamas Berghammer error.SetErrorToErrno(); 1828068f8a7eSTamas Berghammer 18294a9babb2SPavel Labath if (result) 18304a9babb2SPavel Labath *result = ret; 18314a9babb2SPavel Labath 183228096200SPavel Labath LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data, 183328096200SPavel Labath data_size, ret); 1834068f8a7eSTamas Berghammer 1835068f8a7eSTamas Berghammer PtraceDisplayBytes(req, data, data_size); 1836068f8a7eSTamas Berghammer 1837a6321a8eSPavel Labath if (error.Fail()) 1838a6321a8eSPavel Labath LLDB_LOG(log, "ptrace() failed: {0}", error); 1839068f8a7eSTamas Berghammer 18404a9babb2SPavel Labath return error; 1841068f8a7eSTamas Berghammer } 184299e37695SRavitheja Addepally 184399e37695SRavitheja Addepally llvm::Expected<ProcessorTraceMonitor &> 184499e37695SRavitheja Addepally NativeProcessLinux::LookupProcessorTraceInstance(lldb::user_id_t traceid, 184599e37695SRavitheja Addepally lldb::tid_t thread) { 184699e37695SRavitheja Addepally Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 184799e37695SRavitheja Addepally if (thread == LLDB_INVALID_THREAD_ID && traceid == m_pt_proces_trace_id) { 184899e37695SRavitheja Addepally LLDB_LOG(log, "thread not specified: {0}", traceid); 184999e37695SRavitheja Addepally return Status("tracing not active thread not specified").ToError(); 185099e37695SRavitheja Addepally } 185199e37695SRavitheja Addepally 185299e37695SRavitheja Addepally for (auto& iter : m_processor_trace_monitor) { 185399e37695SRavitheja Addepally if (traceid == iter.second->GetTraceID() && 185499e37695SRavitheja Addepally (thread == iter.first || thread == LLDB_INVALID_THREAD_ID)) 185599e37695SRavitheja Addepally return *(iter.second); 185699e37695SRavitheja Addepally } 185799e37695SRavitheja Addepally 185899e37695SRavitheja Addepally LLDB_LOG(log, "traceid not being traced: {0}", traceid); 185999e37695SRavitheja Addepally return Status("tracing not active for this thread").ToError(); 186099e37695SRavitheja Addepally } 186199e37695SRavitheja Addepally 186299e37695SRavitheja Addepally Status NativeProcessLinux::GetMetaData(lldb::user_id_t traceid, 186399e37695SRavitheja Addepally lldb::tid_t thread, 186499e37695SRavitheja Addepally llvm::MutableArrayRef<uint8_t> &buffer, 186599e37695SRavitheja Addepally size_t offset) { 186699e37695SRavitheja Addepally TraceOptions trace_options; 186799e37695SRavitheja Addepally Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 186899e37695SRavitheja Addepally Status error; 186999e37695SRavitheja Addepally 187099e37695SRavitheja Addepally LLDB_LOG(log, "traceid {0}", traceid); 187199e37695SRavitheja Addepally 187299e37695SRavitheja Addepally auto perf_monitor = LookupProcessorTraceInstance(traceid, thread); 187399e37695SRavitheja Addepally if (!perf_monitor) { 187499e37695SRavitheja Addepally LLDB_LOG(log, "traceid not being traced: {0}", traceid); 187599e37695SRavitheja Addepally buffer = buffer.slice(buffer.size()); 187699e37695SRavitheja Addepally error = perf_monitor.takeError(); 187799e37695SRavitheja Addepally return error; 187899e37695SRavitheja Addepally } 187999e37695SRavitheja Addepally return (*perf_monitor).ReadPerfTraceData(buffer, offset); 188099e37695SRavitheja Addepally } 188199e37695SRavitheja Addepally 188299e37695SRavitheja Addepally Status NativeProcessLinux::GetData(lldb::user_id_t traceid, lldb::tid_t thread, 188399e37695SRavitheja Addepally llvm::MutableArrayRef<uint8_t> &buffer, 188499e37695SRavitheja Addepally size_t offset) { 188599e37695SRavitheja Addepally Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 188699e37695SRavitheja Addepally Status error; 188799e37695SRavitheja Addepally 188899e37695SRavitheja Addepally LLDB_LOG(log, "traceid {0}", traceid); 188999e37695SRavitheja Addepally 189099e37695SRavitheja Addepally auto perf_monitor = LookupProcessorTraceInstance(traceid, thread); 189199e37695SRavitheja Addepally if (!perf_monitor) { 189299e37695SRavitheja Addepally LLDB_LOG(log, "traceid not being traced: {0}", traceid); 189399e37695SRavitheja Addepally buffer = buffer.slice(buffer.size()); 189499e37695SRavitheja Addepally error = perf_monitor.takeError(); 189599e37695SRavitheja Addepally return error; 189699e37695SRavitheja Addepally } 189799e37695SRavitheja Addepally return (*perf_monitor).ReadPerfTraceAux(buffer, offset); 189899e37695SRavitheja Addepally } 189999e37695SRavitheja Addepally 190099e37695SRavitheja Addepally Status NativeProcessLinux::GetTraceConfig(lldb::user_id_t traceid, 190199e37695SRavitheja Addepally TraceOptions &config) { 190299e37695SRavitheja Addepally Status error; 190399e37695SRavitheja Addepally if (config.getThreadID() == LLDB_INVALID_THREAD_ID && 190499e37695SRavitheja Addepally m_pt_proces_trace_id == traceid) { 190599e37695SRavitheja Addepally if (m_pt_proces_trace_id == LLDB_INVALID_UID) { 190699e37695SRavitheja Addepally error.SetErrorString("tracing not active for this process"); 190799e37695SRavitheja Addepally return error; 190899e37695SRavitheja Addepally } 190999e37695SRavitheja Addepally config = m_pt_process_trace_config; 191099e37695SRavitheja Addepally } else { 191199e37695SRavitheja Addepally auto perf_monitor = 191299e37695SRavitheja Addepally LookupProcessorTraceInstance(traceid, config.getThreadID()); 191399e37695SRavitheja Addepally if (!perf_monitor) { 191499e37695SRavitheja Addepally error = perf_monitor.takeError(); 191599e37695SRavitheja Addepally return error; 191699e37695SRavitheja Addepally } 191799e37695SRavitheja Addepally error = (*perf_monitor).GetTraceConfig(config); 191899e37695SRavitheja Addepally } 191999e37695SRavitheja Addepally return error; 192099e37695SRavitheja Addepally } 192199e37695SRavitheja Addepally 192299e37695SRavitheja Addepally lldb::user_id_t 192399e37695SRavitheja Addepally NativeProcessLinux::StartTraceGroup(const TraceOptions &config, 192499e37695SRavitheja Addepally Status &error) { 192599e37695SRavitheja Addepally 192699e37695SRavitheja Addepally Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 192799e37695SRavitheja Addepally if (config.getType() != TraceType::eTraceTypeProcessorTrace) 192899e37695SRavitheja Addepally return LLDB_INVALID_UID; 192999e37695SRavitheja Addepally 193099e37695SRavitheja Addepally if (m_pt_proces_trace_id != LLDB_INVALID_UID) { 193199e37695SRavitheja Addepally error.SetErrorString("tracing already active on this process"); 193299e37695SRavitheja Addepally return m_pt_proces_trace_id; 193399e37695SRavitheja Addepally } 193499e37695SRavitheja Addepally 193599e37695SRavitheja Addepally for (const auto &thread_sp : m_threads) { 193699e37695SRavitheja Addepally if (auto traceInstance = ProcessorTraceMonitor::Create( 193799e37695SRavitheja Addepally GetID(), thread_sp->GetID(), config, true)) { 193899e37695SRavitheja Addepally m_pt_traced_thread_group.insert(thread_sp->GetID()); 193999e37695SRavitheja Addepally m_processor_trace_monitor.insert( 194099e37695SRavitheja Addepally std::make_pair(thread_sp->GetID(), std::move(*traceInstance))); 194199e37695SRavitheja Addepally } 194299e37695SRavitheja Addepally } 194399e37695SRavitheja Addepally 194499e37695SRavitheja Addepally m_pt_process_trace_config = config; 194599e37695SRavitheja Addepally error = ProcessorTraceMonitor::GetCPUType(m_pt_process_trace_config); 194699e37695SRavitheja Addepally 194799e37695SRavitheja Addepally // Trace on Complete process will have traceid of 0 194899e37695SRavitheja Addepally m_pt_proces_trace_id = 0; 194999e37695SRavitheja Addepally 195099e37695SRavitheja Addepally LLDB_LOG(log, "Process Trace ID {0}", m_pt_proces_trace_id); 195199e37695SRavitheja Addepally return m_pt_proces_trace_id; 195299e37695SRavitheja Addepally } 195399e37695SRavitheja Addepally 195499e37695SRavitheja Addepally lldb::user_id_t NativeProcessLinux::StartTrace(const TraceOptions &config, 195599e37695SRavitheja Addepally Status &error) { 195699e37695SRavitheja Addepally if (config.getType() != TraceType::eTraceTypeProcessorTrace) 195799e37695SRavitheja Addepally return NativeProcessProtocol::StartTrace(config, error); 195899e37695SRavitheja Addepally 195999e37695SRavitheja Addepally Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 196099e37695SRavitheja Addepally 196199e37695SRavitheja Addepally lldb::tid_t threadid = config.getThreadID(); 196299e37695SRavitheja Addepally 196399e37695SRavitheja Addepally if (threadid == LLDB_INVALID_THREAD_ID) 196499e37695SRavitheja Addepally return StartTraceGroup(config, error); 196599e37695SRavitheja Addepally 196699e37695SRavitheja Addepally auto thread_sp = GetThreadByID(threadid); 196799e37695SRavitheja Addepally if (!thread_sp) { 196899e37695SRavitheja Addepally // Thread not tracked by lldb so don't trace. 196999e37695SRavitheja Addepally error.SetErrorString("invalid thread id"); 197099e37695SRavitheja Addepally return LLDB_INVALID_UID; 197199e37695SRavitheja Addepally } 197299e37695SRavitheja Addepally 197399e37695SRavitheja Addepally const auto &iter = m_processor_trace_monitor.find(threadid); 197499e37695SRavitheja Addepally if (iter != m_processor_trace_monitor.end()) { 197599e37695SRavitheja Addepally LLDB_LOG(log, "Thread already being traced"); 197699e37695SRavitheja Addepally error.SetErrorString("tracing already active on this thread"); 197799e37695SRavitheja Addepally return LLDB_INVALID_UID; 197899e37695SRavitheja Addepally } 197999e37695SRavitheja Addepally 198099e37695SRavitheja Addepally auto traceMonitor = 198199e37695SRavitheja Addepally ProcessorTraceMonitor::Create(GetID(), threadid, config, false); 198299e37695SRavitheja Addepally if (!traceMonitor) { 198399e37695SRavitheja Addepally error = traceMonitor.takeError(); 198499e37695SRavitheja Addepally LLDB_LOG(log, "error {0}", error); 198599e37695SRavitheja Addepally return LLDB_INVALID_UID; 198699e37695SRavitheja Addepally } 198799e37695SRavitheja Addepally lldb::user_id_t ret_trace_id = (*traceMonitor)->GetTraceID(); 198899e37695SRavitheja Addepally m_processor_trace_monitor.insert( 198999e37695SRavitheja Addepally std::make_pair(threadid, std::move(*traceMonitor))); 199099e37695SRavitheja Addepally return ret_trace_id; 199199e37695SRavitheja Addepally } 199299e37695SRavitheja Addepally 199399e37695SRavitheja Addepally Status NativeProcessLinux::StopTracingForThread(lldb::tid_t thread) { 199499e37695SRavitheja Addepally Status error; 199599e37695SRavitheja Addepally Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 199699e37695SRavitheja Addepally LLDB_LOG(log, "Thread {0}", thread); 199799e37695SRavitheja Addepally 199899e37695SRavitheja Addepally const auto& iter = m_processor_trace_monitor.find(thread); 199999e37695SRavitheja Addepally if (iter == m_processor_trace_monitor.end()) { 200099e37695SRavitheja Addepally error.SetErrorString("tracing not active for this thread"); 200199e37695SRavitheja Addepally return error; 200299e37695SRavitheja Addepally } 200399e37695SRavitheja Addepally 200499e37695SRavitheja Addepally if (iter->second->GetTraceID() == m_pt_proces_trace_id) { 200505097246SAdrian Prantl // traceid maps to the whole process so we have to erase it from the thread 200605097246SAdrian Prantl // group. 200799e37695SRavitheja Addepally LLDB_LOG(log, "traceid maps to process"); 200899e37695SRavitheja Addepally m_pt_traced_thread_group.erase(thread); 200999e37695SRavitheja Addepally } 201099e37695SRavitheja Addepally m_processor_trace_monitor.erase(iter); 201199e37695SRavitheja Addepally 201299e37695SRavitheja Addepally return error; 201399e37695SRavitheja Addepally } 201499e37695SRavitheja Addepally 201599e37695SRavitheja Addepally Status NativeProcessLinux::StopTrace(lldb::user_id_t traceid, 201699e37695SRavitheja Addepally lldb::tid_t thread) { 201799e37695SRavitheja Addepally Status error; 201899e37695SRavitheja Addepally 201999e37695SRavitheja Addepally TraceOptions trace_options; 202099e37695SRavitheja Addepally trace_options.setThreadID(thread); 202199e37695SRavitheja Addepally error = NativeProcessLinux::GetTraceConfig(traceid, trace_options); 202299e37695SRavitheja Addepally 202399e37695SRavitheja Addepally if (error.Fail()) 202499e37695SRavitheja Addepally return error; 202599e37695SRavitheja Addepally 202699e37695SRavitheja Addepally switch (trace_options.getType()) { 202799e37695SRavitheja Addepally case lldb::TraceType::eTraceTypeProcessorTrace: 202899e37695SRavitheja Addepally if (traceid == m_pt_proces_trace_id && 202999e37695SRavitheja Addepally thread == LLDB_INVALID_THREAD_ID) 203099e37695SRavitheja Addepally StopProcessorTracingOnProcess(); 203199e37695SRavitheja Addepally else 203299e37695SRavitheja Addepally error = StopProcessorTracingOnThread(traceid, thread); 203399e37695SRavitheja Addepally break; 203499e37695SRavitheja Addepally default: 203599e37695SRavitheja Addepally error.SetErrorString("trace not supported"); 203699e37695SRavitheja Addepally break; 203799e37695SRavitheja Addepally } 203899e37695SRavitheja Addepally 203999e37695SRavitheja Addepally return error; 204099e37695SRavitheja Addepally } 204199e37695SRavitheja Addepally 204299e37695SRavitheja Addepally void NativeProcessLinux::StopProcessorTracingOnProcess() { 204399e37695SRavitheja Addepally for (auto thread_id_iter : m_pt_traced_thread_group) 204499e37695SRavitheja Addepally m_processor_trace_monitor.erase(thread_id_iter); 204599e37695SRavitheja Addepally m_pt_traced_thread_group.clear(); 204699e37695SRavitheja Addepally m_pt_proces_trace_id = LLDB_INVALID_UID; 204799e37695SRavitheja Addepally } 204899e37695SRavitheja Addepally 204999e37695SRavitheja Addepally Status NativeProcessLinux::StopProcessorTracingOnThread(lldb::user_id_t traceid, 205099e37695SRavitheja Addepally lldb::tid_t thread) { 205199e37695SRavitheja Addepally Status error; 205299e37695SRavitheja Addepally Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 205399e37695SRavitheja Addepally 205499e37695SRavitheja Addepally if (thread == LLDB_INVALID_THREAD_ID) { 205599e37695SRavitheja Addepally for (auto& iter : m_processor_trace_monitor) { 205699e37695SRavitheja Addepally if (iter.second->GetTraceID() == traceid) { 205705097246SAdrian Prantl // Stopping a trace instance for an individual thread hence there will 205805097246SAdrian Prantl // only be one traceid that can match. 205999e37695SRavitheja Addepally m_processor_trace_monitor.erase(iter.first); 206099e37695SRavitheja Addepally return error; 206199e37695SRavitheja Addepally } 206299e37695SRavitheja Addepally LLDB_LOG(log, "Trace ID {0}", iter.second->GetTraceID()); 206399e37695SRavitheja Addepally } 206499e37695SRavitheja Addepally 206599e37695SRavitheja Addepally LLDB_LOG(log, "Invalid TraceID"); 206699e37695SRavitheja Addepally error.SetErrorString("invalid trace id"); 206799e37695SRavitheja Addepally return error; 206899e37695SRavitheja Addepally } 206999e37695SRavitheja Addepally 207099e37695SRavitheja Addepally // thread is specified so we can use find function on the map. 207199e37695SRavitheja Addepally const auto& iter = m_processor_trace_monitor.find(thread); 207299e37695SRavitheja Addepally if (iter == m_processor_trace_monitor.end()) { 207399e37695SRavitheja Addepally // thread not found in our map. 207499e37695SRavitheja Addepally LLDB_LOG(log, "thread not being traced"); 207599e37695SRavitheja Addepally error.SetErrorString("tracing not active for this thread"); 207699e37695SRavitheja Addepally return error; 207799e37695SRavitheja Addepally } 207899e37695SRavitheja Addepally if (iter->second->GetTraceID() != traceid) { 207999e37695SRavitheja Addepally // traceid did not match so it has to be invalid. 208099e37695SRavitheja Addepally LLDB_LOG(log, "Invalid TraceID"); 208199e37695SRavitheja Addepally error.SetErrorString("invalid trace id"); 208299e37695SRavitheja Addepally return error; 208399e37695SRavitheja Addepally } 208499e37695SRavitheja Addepally 208599e37695SRavitheja Addepally LLDB_LOG(log, "UID - {0} , Thread -{1}", traceid, thread); 208699e37695SRavitheja Addepally 208799e37695SRavitheja Addepally if (traceid == m_pt_proces_trace_id) { 208805097246SAdrian Prantl // traceid maps to the whole process so we have to erase it from the thread 208905097246SAdrian Prantl // group. 209099e37695SRavitheja Addepally LLDB_LOG(log, "traceid maps to process"); 209199e37695SRavitheja Addepally m_pt_traced_thread_group.erase(thread); 209299e37695SRavitheja Addepally } 209399e37695SRavitheja Addepally m_processor_trace_monitor.erase(iter); 209499e37695SRavitheja Addepally 209599e37695SRavitheja Addepally return error; 209699e37695SRavitheja Addepally } 2097