180814287SRaphael Isemann //===-- NativeProcessLinux.cpp --------------------------------------------===//
2af245d11STodd Fiala //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6af245d11STodd Fiala //
7af245d11STodd Fiala //===----------------------------------------------------------------------===//
8af245d11STodd Fiala 
9af245d11STodd Fiala #include "NativeProcessLinux.h"
10af245d11STodd Fiala 
11af245d11STodd Fiala #include <errno.h>
12af245d11STodd Fiala #include <stdint.h>
13b9c1b51eSKate Stone #include <string.h>
14af245d11STodd Fiala #include <unistd.h>
15af245d11STodd Fiala 
16af245d11STodd Fiala #include <fstream>
17df7c6995SPavel Labath #include <mutex>
18c076559aSPavel Labath #include <sstream>
19af245d11STodd Fiala #include <string>
205b981ab9SPavel Labath #include <unordered_map>
21af245d11STodd Fiala 
222c4226f8SPavel Labath #include "NativeThreadLinux.h"
232c4226f8SPavel Labath #include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
242c4226f8SPavel Labath #include "Plugins/Process/Utility/LinuxProcMaps.h"
252c4226f8SPavel Labath #include "Procfs.h"
266edef204SOleksiy Vyalov #include "lldb/Core/ModuleSpec.h"
27af245d11STodd Fiala #include "lldb/Host/Host.h"
285ad891f7SPavel Labath #include "lldb/Host/HostProcess.h"
29eef758e9SPavel Labath #include "lldb/Host/ProcessLaunchInfo.h"
3024ae6294SZachary Turner #include "lldb/Host/PseudoTerminal.h"
3139de3110SZachary Turner #include "lldb/Host/ThreadLauncher.h"
322a86b555SPavel Labath #include "lldb/Host/common/NativeRegisterContext.h"
33*c8d18cbaSMichał Górny #include "lldb/Host/linux/Host.h"
344ee1c952SPavel Labath #include "lldb/Host/linux/Ptrace.h"
354ee1c952SPavel Labath #include "lldb/Host/linux/Uio.h"
36816ae4b0SKamil Rytarowski #include "lldb/Host/posix/ProcessLauncherPosixFork.h"
372a86b555SPavel Labath #include "lldb/Symbol/ObjectFile.h"
3890aff47cSZachary Turner #include "lldb/Target/Process.h"
395b981ab9SPavel Labath #include "lldb/Target/Target.h"
40c16f5dcaSChaoren Lin #include "lldb/Utility/LLDBAssert.h"
41d821c997SPavel Labath #include "lldb/Utility/State.h"
4297206d57SZachary Turner #include "lldb/Utility/Status.h"
43f805e190SPavel Labath #include "lldb/Utility/StringExtractor.h"
442c4226f8SPavel Labath #include "llvm/ADT/ScopeExit.h"
4510c41f37SPavel Labath #include "llvm/Support/Errno.h"
4610c41f37SPavel Labath #include "llvm/Support/FileSystem.h"
4710c41f37SPavel Labath #include "llvm/Support/Threading.h"
48af245d11STodd Fiala 
49d858487eSTamas Berghammer #include <linux/unistd.h>
50d858487eSTamas Berghammer #include <sys/socket.h>
51df7c6995SPavel Labath #include <sys/syscall.h>
52d858487eSTamas Berghammer #include <sys/types.h>
53d858487eSTamas Berghammer #include <sys/user.h>
54d858487eSTamas Berghammer #include <sys/wait.h>
55d858487eSTamas Berghammer 
56af245d11STodd Fiala // Support hardware breakpoints in case it has not been defined
57af245d11STodd Fiala #ifndef TRAP_HWBKPT
58af245d11STodd Fiala #define TRAP_HWBKPT 4
59af245d11STodd Fiala #endif
60af245d11STodd Fiala 
617cb18bf5STamas Berghammer using namespace lldb;
627cb18bf5STamas Berghammer using namespace lldb_private;
63db264a6dSTamas Berghammer using namespace lldb_private::process_linux;
647cb18bf5STamas Berghammer using namespace llvm;
657cb18bf5STamas Berghammer 
66af245d11STodd Fiala // Private bits we only need internally.
67df7c6995SPavel Labath 
68b9c1b51eSKate Stone static bool ProcessVmReadvSupported() {
69df7c6995SPavel Labath   static bool is_supported;
70c5f28e2aSKamil Rytarowski   static llvm::once_flag flag;
71df7c6995SPavel Labath 
72c5f28e2aSKamil Rytarowski   llvm::call_once(flag, [] {
73a6321a8eSPavel Labath     Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
74df7c6995SPavel Labath 
75df7c6995SPavel Labath     uint32_t source = 0x47424742;
76df7c6995SPavel Labath     uint32_t dest = 0;
77df7c6995SPavel Labath 
78df7c6995SPavel Labath     struct iovec local, remote;
79df7c6995SPavel Labath     remote.iov_base = &source;
80df7c6995SPavel Labath     local.iov_base = &dest;
81df7c6995SPavel Labath     remote.iov_len = local.iov_len = sizeof source;
82df7c6995SPavel Labath 
83b9c1b51eSKate Stone     // We shall try if cross-process-memory reads work by attempting to read a
84b9c1b51eSKate Stone     // value from our own process.
85df7c6995SPavel Labath     ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
86df7c6995SPavel Labath     is_supported = (res == sizeof(source) && source == dest);
87df7c6995SPavel Labath     if (is_supported)
88a6321a8eSPavel Labath       LLDB_LOG(log,
89a6321a8eSPavel Labath                "Detected kernel support for process_vm_readv syscall. "
90a6321a8eSPavel Labath                "Fast memory reads enabled.");
91df7c6995SPavel Labath     else
92a6321a8eSPavel Labath       LLDB_LOG(log,
93a6321a8eSPavel Labath                "syscall process_vm_readv failed (error: {0}). Fast memory "
94a6321a8eSPavel Labath                "reads disabled.",
9510c41f37SPavel Labath                llvm::sys::StrError());
96df7c6995SPavel Labath   });
97df7c6995SPavel Labath 
98df7c6995SPavel Labath   return is_supported;
99df7c6995SPavel Labath }
100df7c6995SPavel Labath 
101b9c1b51eSKate Stone namespace {
102b9c1b51eSKate Stone void MaybeLogLaunchInfo(const ProcessLaunchInfo &info) {
103a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1044abe5d69SPavel Labath   if (!log)
1054abe5d69SPavel Labath     return;
1064abe5d69SPavel Labath 
1074abe5d69SPavel Labath   if (const FileAction *action = info.GetFileActionForFD(STDIN_FILENO))
108a6321a8eSPavel Labath     LLDB_LOG(log, "setting STDIN to '{0}'", action->GetFileSpec());
1094abe5d69SPavel Labath   else
110a6321a8eSPavel Labath     LLDB_LOG(log, "leaving STDIN as is");
1114abe5d69SPavel Labath 
1124abe5d69SPavel Labath   if (const FileAction *action = info.GetFileActionForFD(STDOUT_FILENO))
113a6321a8eSPavel Labath     LLDB_LOG(log, "setting STDOUT to '{0}'", action->GetFileSpec());
1144abe5d69SPavel Labath   else
115a6321a8eSPavel Labath     LLDB_LOG(log, "leaving STDOUT as is");
1164abe5d69SPavel Labath 
1174abe5d69SPavel Labath   if (const FileAction *action = info.GetFileActionForFD(STDERR_FILENO))
118a6321a8eSPavel Labath     LLDB_LOG(log, "setting STDERR to '{0}'", action->GetFileSpec());
1194abe5d69SPavel Labath   else
120a6321a8eSPavel Labath     LLDB_LOG(log, "leaving STDERR as is");
1214abe5d69SPavel Labath 
1224abe5d69SPavel Labath   int i = 0;
123b9c1b51eSKate Stone   for (const char **args = info.GetArguments().GetConstArgumentVector(); *args;
124b9c1b51eSKate Stone        ++args, ++i)
125a6321a8eSPavel Labath     LLDB_LOG(log, "arg {0}: '{1}'", i, *args);
1264abe5d69SPavel Labath }
1274abe5d69SPavel Labath 
128b9c1b51eSKate Stone void DisplayBytes(StreamString &s, void *bytes, uint32_t count) {
129af245d11STodd Fiala   uint8_t *ptr = (uint8_t *)bytes;
130af245d11STodd Fiala   const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
131b9c1b51eSKate Stone   for (uint32_t i = 0; i < loop_count; i++) {
132af245d11STodd Fiala     s.Printf("[%x]", *ptr);
133af245d11STodd Fiala     ptr++;
134af245d11STodd Fiala   }
135af245d11STodd Fiala }
136af245d11STodd Fiala 
137b9c1b51eSKate Stone void PtraceDisplayBytes(int &req, void *data, size_t data_size) {
138aafe053cSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
139a6321a8eSPavel Labath   if (!log)
140a6321a8eSPavel Labath     return;
141af245d11STodd Fiala   StreamString buf;
142af245d11STodd Fiala 
143b9c1b51eSKate Stone   switch (req) {
144b9c1b51eSKate Stone   case PTRACE_POKETEXT: {
145af245d11STodd Fiala     DisplayBytes(buf, &data, 8);
146aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_POKETEXT {0}", buf.GetData());
147af245d11STodd Fiala     break;
148af245d11STodd Fiala   }
149b9c1b51eSKate Stone   case PTRACE_POKEDATA: {
150af245d11STodd Fiala     DisplayBytes(buf, &data, 8);
151aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_POKEDATA {0}", buf.GetData());
152af245d11STodd Fiala     break;
153af245d11STodd Fiala   }
154b9c1b51eSKate Stone   case PTRACE_POKEUSER: {
155af245d11STodd Fiala     DisplayBytes(buf, &data, 8);
156aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_POKEUSER {0}", buf.GetData());
157af245d11STodd Fiala     break;
158af245d11STodd Fiala   }
159b9c1b51eSKate Stone   case PTRACE_SETREGS: {
160af245d11STodd Fiala     DisplayBytes(buf, data, data_size);
161aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_SETREGS {0}", buf.GetData());
162af245d11STodd Fiala     break;
163af245d11STodd Fiala   }
164b9c1b51eSKate Stone   case PTRACE_SETFPREGS: {
165af245d11STodd Fiala     DisplayBytes(buf, data, data_size);
166aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_SETFPREGS {0}", buf.GetData());
167af245d11STodd Fiala     break;
168af245d11STodd Fiala   }
169b9c1b51eSKate Stone   case PTRACE_SETSIGINFO: {
170af245d11STodd Fiala     DisplayBytes(buf, data, sizeof(siginfo_t));
171aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_SETSIGINFO {0}", buf.GetData());
172af245d11STodd Fiala     break;
173af245d11STodd Fiala   }
174b9c1b51eSKate Stone   case PTRACE_SETREGSET: {
17511edb4eeSPavel Labath     // Extract iov_base from data, which is a pointer to the struct iovec
176af245d11STodd Fiala     DisplayBytes(buf, *(void **)data, data_size);
177aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_SETREGSET {0}", buf.GetData());
178af245d11STodd Fiala     break;
179af245d11STodd Fiala   }
180b9c1b51eSKate Stone   default: {}
181af245d11STodd Fiala   }
182af245d11STodd Fiala }
183af245d11STodd Fiala 
18419cbe96aSPavel Labath static constexpr unsigned k_ptrace_word_size = sizeof(void *);
185b9c1b51eSKate Stone static_assert(sizeof(long) >= k_ptrace_word_size,
186b9c1b51eSKate Stone               "Size of long must be larger than ptrace word size");
1871107b5a5SPavel Labath } // end of anonymous namespace
1881107b5a5SPavel Labath 
189bd7cbc5aSPavel Labath // Simple helper function to ensure flags are enabled on the given file
190bd7cbc5aSPavel Labath // descriptor.
19197206d57SZachary Turner static Status EnsureFDFlags(int fd, int flags) {
19297206d57SZachary Turner   Status error;
193bd7cbc5aSPavel Labath 
194bd7cbc5aSPavel Labath   int status = fcntl(fd, F_GETFL);
195b9c1b51eSKate Stone   if (status == -1) {
196bd7cbc5aSPavel Labath     error.SetErrorToErrno();
197bd7cbc5aSPavel Labath     return error;
198bd7cbc5aSPavel Labath   }
199bd7cbc5aSPavel Labath 
200b9c1b51eSKate Stone   if (fcntl(fd, F_SETFL, status | flags) == -1) {
201bd7cbc5aSPavel Labath     error.SetErrorToErrno();
202bd7cbc5aSPavel Labath     return error;
203bd7cbc5aSPavel Labath   }
204bd7cbc5aSPavel Labath 
205bd7cbc5aSPavel Labath   return error;
206bd7cbc5aSPavel Labath }
207bd7cbc5aSPavel Labath 
208af245d11STodd Fiala // Public Static Methods
209af245d11STodd Fiala 
21082abefa4SPavel Labath llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
21196e600fcSPavel Labath NativeProcessLinux::Factory::Launch(ProcessLaunchInfo &launch_info,
21296e600fcSPavel Labath                                     NativeDelegate &native_delegate,
21396e600fcSPavel Labath                                     MainLoop &mainloop) const {
214a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
215af245d11STodd Fiala 
21696e600fcSPavel Labath   MaybeLogLaunchInfo(launch_info);
217af245d11STodd Fiala 
21896e600fcSPavel Labath   Status status;
21996e600fcSPavel Labath   ::pid_t pid = ProcessLauncherPosixFork()
22096e600fcSPavel Labath                     .LaunchProcess(launch_info, status)
22196e600fcSPavel Labath                     .GetProcessId();
22296e600fcSPavel Labath   LLDB_LOG(log, "pid = {0:x}", pid);
22396e600fcSPavel Labath   if (status.Fail()) {
22496e600fcSPavel Labath     LLDB_LOG(log, "failed to launch process: {0}", status);
22596e600fcSPavel Labath     return status.ToError();
226af245d11STodd Fiala   }
227af245d11STodd Fiala 
22896e600fcSPavel Labath   // Wait for the child process to trap on its call to execve.
22996e600fcSPavel Labath   int wstatus;
23096e600fcSPavel Labath   ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0);
23196e600fcSPavel Labath   assert(wpid == pid);
23296e600fcSPavel Labath   (void)wpid;
23396e600fcSPavel Labath   if (!WIFSTOPPED(wstatus)) {
23496e600fcSPavel Labath     LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}",
23596e600fcSPavel Labath              WaitStatus::Decode(wstatus));
23696e600fcSPavel Labath     return llvm::make_error<StringError>("Could not sync with inferior process",
23796e600fcSPavel Labath                                          llvm::inconvertibleErrorCode());
23896e600fcSPavel Labath   }
23996e600fcSPavel Labath   LLDB_LOG(log, "inferior started, now in stopped state");
240af245d11STodd Fiala 
24136e82208SPavel Labath   ProcessInstanceInfo Info;
24236e82208SPavel Labath   if (!Host::GetProcessInfo(pid, Info)) {
24336e82208SPavel Labath     return llvm::make_error<StringError>("Cannot get process architecture",
24436e82208SPavel Labath                                          llvm::inconvertibleErrorCode());
24536e82208SPavel Labath   }
24696e600fcSPavel Labath 
24796e600fcSPavel Labath   // Set the architecture to the exe architecture.
24896e600fcSPavel Labath   LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid,
24936e82208SPavel Labath            Info.GetArchitecture().GetArchitectureName());
25096e600fcSPavel Labath 
25196e600fcSPavel Labath   status = SetDefaultPtraceOpts(pid);
25296e600fcSPavel Labath   if (status.Fail()) {
25396e600fcSPavel Labath     LLDB_LOG(log, "failed to set default ptrace options: {0}", status);
25496e600fcSPavel Labath     return status.ToError();
255af245d11STodd Fiala   }
256af245d11STodd Fiala 
25782abefa4SPavel Labath   return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
25864ec505dSJonas Devlieghere       pid, launch_info.GetPTY().ReleasePrimaryFileDescriptor(), native_delegate,
25936e82208SPavel Labath       Info.GetArchitecture(), mainloop, {pid}));
260af245d11STodd Fiala }
261af245d11STodd Fiala 
26282abefa4SPavel Labath llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
26382abefa4SPavel Labath NativeProcessLinux::Factory::Attach(
264b9c1b51eSKate Stone     lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
26596e600fcSPavel Labath     MainLoop &mainloop) const {
266a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
267a6321a8eSPavel Labath   LLDB_LOG(log, "pid = {0:x}", pid);
268af245d11STodd Fiala 
269af245d11STodd Fiala   // Retrieve the architecture for the running process.
27036e82208SPavel Labath   ProcessInstanceInfo Info;
27136e82208SPavel Labath   if (!Host::GetProcessInfo(pid, Info)) {
27236e82208SPavel Labath     return llvm::make_error<StringError>("Cannot get process architecture",
27336e82208SPavel Labath                                          llvm::inconvertibleErrorCode());
27436e82208SPavel Labath   }
275af245d11STodd Fiala 
27696e600fcSPavel Labath   auto tids_or = NativeProcessLinux::Attach(pid);
27796e600fcSPavel Labath   if (!tids_or)
27896e600fcSPavel Labath     return tids_or.takeError();
279af245d11STodd Fiala 
28082abefa4SPavel Labath   return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
28136e82208SPavel Labath       pid, -1, native_delegate, Info.GetArchitecture(), mainloop, *tids_or));
282af245d11STodd Fiala }
283af245d11STodd Fiala 
284af245d11STodd Fiala // Public Instance Methods
285af245d11STodd Fiala 
28696e600fcSPavel Labath NativeProcessLinux::NativeProcessLinux(::pid_t pid, int terminal_fd,
28796e600fcSPavel Labath                                        NativeDelegate &delegate,
28882abefa4SPavel Labath                                        const ArchSpec &arch, MainLoop &mainloop,
28982abefa4SPavel Labath                                        llvm::ArrayRef<::pid_t> tids)
2900b697561SWalter Erquinigo     : NativeProcessELF(pid, terminal_fd, delegate), m_arch(arch),
2910b697561SWalter Erquinigo       m_intel_pt_manager(pid) {
292b9c1b51eSKate Stone   if (m_terminal_fd != -1) {
29396e600fcSPavel Labath     Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
29496e600fcSPavel Labath     assert(status.Success());
2955ad891f7SPavel Labath   }
296af245d11STodd Fiala 
29796e600fcSPavel Labath   Status status;
29896e600fcSPavel Labath   m_sigchld_handle = mainloop.RegisterSignal(
29996e600fcSPavel Labath       SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status);
30096e600fcSPavel Labath   assert(m_sigchld_handle && status.Success());
30196e600fcSPavel Labath 
30296e600fcSPavel Labath   for (const auto &tid : tids) {
3030b697561SWalter Erquinigo     NativeThreadLinux &thread = AddThread(tid, /*resume*/ false);
304a5be48b3SPavel Labath     ThreadWasCreated(thread);
305af245d11STodd Fiala   }
306af245d11STodd Fiala 
30796e600fcSPavel Labath   // Let our process instance know the thread has stopped.
30896e600fcSPavel Labath   SetCurrentThreadID(tids[0]);
30996e600fcSPavel Labath   SetState(StateType::eStateStopped, false);
31096e600fcSPavel Labath 
31196e600fcSPavel Labath   // Proccess any signals we received before installing our handler
31296e600fcSPavel Labath   SigchldHandler();
31396e600fcSPavel Labath }
31496e600fcSPavel Labath 
31596e600fcSPavel Labath llvm::Expected<std::vector<::pid_t>> NativeProcessLinux::Attach(::pid_t pid) {
316a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
317af245d11STodd Fiala 
31896e600fcSPavel Labath   Status status;
319b9c1b51eSKate Stone   // Use a map to keep track of the threads which we have attached/need to
320b9c1b51eSKate Stone   // attach.
321af245d11STodd Fiala   Host::TidMap tids_to_attach;
322b9c1b51eSKate Stone   while (Host::FindProcessThreads(pid, tids_to_attach)) {
323af245d11STodd Fiala     for (Host::TidMap::iterator it = tids_to_attach.begin();
324b9c1b51eSKate Stone          it != tids_to_attach.end();) {
325b9c1b51eSKate Stone       if (it->second == false) {
326af245d11STodd Fiala         lldb::tid_t tid = it->first;
327af245d11STodd Fiala 
328af245d11STodd Fiala         // Attach to the requested process.
329af245d11STodd Fiala         // An attach will cause the thread to stop with a SIGSTOP.
33096e600fcSPavel Labath         if ((status = PtraceWrapper(PTRACE_ATTACH, tid)).Fail()) {
33105097246SAdrian Prantl           // No such thread. The thread may have exited. More error handling
33205097246SAdrian Prantl           // may be needed.
33396e600fcSPavel Labath           if (status.GetError() == ESRCH) {
334af245d11STodd Fiala             it = tids_to_attach.erase(it);
335af245d11STodd Fiala             continue;
33696e600fcSPavel Labath           }
33796e600fcSPavel Labath           return status.ToError();
338af245d11STodd Fiala         }
339af245d11STodd Fiala 
34096e600fcSPavel Labath         int wpid =
34196e600fcSPavel Labath             llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, nullptr, __WALL);
34205097246SAdrian Prantl         // Need to use __WALL otherwise we receive an error with errno=ECHLD At
34305097246SAdrian Prantl         // this point we should have a thread stopped if waitpid succeeds.
34496e600fcSPavel Labath         if (wpid < 0) {
34505097246SAdrian Prantl           // No such thread. The thread may have exited. More error handling
34605097246SAdrian Prantl           // may be needed.
347b9c1b51eSKate Stone           if (errno == ESRCH) {
348af245d11STodd Fiala             it = tids_to_attach.erase(it);
349af245d11STodd Fiala             continue;
350af245d11STodd Fiala           }
35196e600fcSPavel Labath           return llvm::errorCodeToError(
35296e600fcSPavel Labath               std::error_code(errno, std::generic_category()));
353af245d11STodd Fiala         }
354af245d11STodd Fiala 
35596e600fcSPavel Labath         if ((status = SetDefaultPtraceOpts(tid)).Fail())
35696e600fcSPavel Labath           return status.ToError();
357af245d11STodd Fiala 
358a6321a8eSPavel Labath         LLDB_LOG(log, "adding tid = {0}", tid);
359af245d11STodd Fiala         it->second = true;
360af245d11STodd Fiala       }
361af245d11STodd Fiala 
362af245d11STodd Fiala       // move the loop forward
363af245d11STodd Fiala       ++it;
364af245d11STodd Fiala     }
365af245d11STodd Fiala   }
366af245d11STodd Fiala 
36796e600fcSPavel Labath   size_t tid_count = tids_to_attach.size();
36896e600fcSPavel Labath   if (tid_count == 0)
36996e600fcSPavel Labath     return llvm::make_error<StringError>("No such process",
37096e600fcSPavel Labath                                          llvm::inconvertibleErrorCode());
371af245d11STodd Fiala 
37296e600fcSPavel Labath   std::vector<::pid_t> tids;
37396e600fcSPavel Labath   tids.reserve(tid_count);
37496e600fcSPavel Labath   for (const auto &p : tids_to_attach)
37596e600fcSPavel Labath     tids.push_back(p.first);
37696e600fcSPavel Labath   return std::move(tids);
377af245d11STodd Fiala }
378af245d11STodd Fiala 
37997206d57SZachary Turner Status NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid) {
380af245d11STodd Fiala   long ptrace_opts = 0;
381af245d11STodd Fiala 
382af245d11STodd Fiala   // Have the child raise an event on exit.  This is used to keep the child in
383af245d11STodd Fiala   // limbo until it is destroyed.
384af245d11STodd Fiala   ptrace_opts |= PTRACE_O_TRACEEXIT;
385af245d11STodd Fiala 
386af245d11STodd Fiala   // Have the tracer trace threads which spawn in the inferior process.
387af245d11STodd Fiala   ptrace_opts |= PTRACE_O_TRACECLONE;
388af245d11STodd Fiala 
38905097246SAdrian Prantl   // Have the tracer notify us before execve returns (needed to disable legacy
39005097246SAdrian Prantl   // SIGTRAP generation)
391af245d11STodd Fiala   ptrace_opts |= PTRACE_O_TRACEEXEC;
392af245d11STodd Fiala 
393*c8d18cbaSMichał Górny   // Have the tracer trace forked children.
394*c8d18cbaSMichał Górny   ptrace_opts |= PTRACE_O_TRACEFORK;
395*c8d18cbaSMichał Górny 
396*c8d18cbaSMichał Górny   // Have the tracer trace vforks.
397*c8d18cbaSMichał Górny   ptrace_opts |= PTRACE_O_TRACEVFORK;
398*c8d18cbaSMichał Górny 
399*c8d18cbaSMichał Górny   // Have the tracer trace vfork-done in order to restore breakpoints after
400*c8d18cbaSMichał Górny   // the child finishes sharing memory.
401*c8d18cbaSMichał Górny   ptrace_opts |= PTRACE_O_TRACEVFORKDONE;
402*c8d18cbaSMichał Górny 
4034a9babb2SPavel Labath   return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void *)ptrace_opts);
404af245d11STodd Fiala }
405af245d11STodd Fiala 
4061107b5a5SPavel Labath // Handles all waitpid events from the inferior process.
407b9c1b51eSKate Stone void NativeProcessLinux::MonitorCallback(lldb::pid_t pid, bool exited,
4083508fc8cSPavel Labath                                          WaitStatus status) {
409af245d11STodd Fiala   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
410af245d11STodd Fiala 
411b9c1b51eSKate Stone   // Certain activities differ based on whether the pid is the tid of the main
412b9c1b51eSKate Stone   // thread.
4131107b5a5SPavel Labath   const bool is_main_thread = (pid == GetID());
414af245d11STodd Fiala 
415af245d11STodd Fiala   // Handle when the thread exits.
416b9c1b51eSKate Stone   if (exited) {
417d8b3c1a1SPavel Labath     LLDB_LOG(log,
4189303afb3SPavel Labath              "got exit status({0}) , tid = {1} ({2} main thread), process "
419d8b3c1a1SPavel Labath              "state = {3}",
4209303afb3SPavel Labath              status, pid, is_main_thread ? "is" : "is not", GetState());
421af245d11STodd Fiala 
422af245d11STodd Fiala     // This is a thread that exited.  Ensure we're not tracking it anymore.
423d8b3c1a1SPavel Labath     StopTrackingThread(pid);
424af245d11STodd Fiala 
425b9c1b51eSKate Stone     if (is_main_thread) {
426af245d11STodd Fiala       // The main thread exited.  We're done monitoring.  Report to delegate.
4273508fc8cSPavel Labath       SetExitStatus(status, true);
428af245d11STodd Fiala 
429af245d11STodd Fiala       // Notify delegate that our process has exited.
4301107b5a5SPavel Labath       SetState(StateType::eStateExited, true);
431af245d11STodd Fiala     }
4321107b5a5SPavel Labath     return;
433af245d11STodd Fiala   }
434af245d11STodd Fiala 
435af245d11STodd Fiala   siginfo_t info;
436b9cc0c75SPavel Labath   const auto info_err = GetSignalInfo(pid, &info);
437b9cc0c75SPavel Labath   auto thread_sp = GetThreadByID(pid);
438b9cc0c75SPavel Labath 
439b9c1b51eSKate Stone   if (!thread_sp) {
44005097246SAdrian Prantl     // Normally, the only situation when we cannot find the thread is if we
44105097246SAdrian Prantl     // have just received a new thread notification. This is indicated by
442a6321a8eSPavel Labath     // GetSignalInfo() returning si_code == SI_USER and si_pid == 0
443a6321a8eSPavel Labath     LLDB_LOG(log, "received notification about an unknown tid {0}.", pid);
444b9cc0c75SPavel Labath 
445b9c1b51eSKate Stone     if (info_err.Fail()) {
446a6321a8eSPavel Labath       LLDB_LOG(log,
447a6321a8eSPavel Labath                "(tid {0}) GetSignalInfo failed ({1}). "
448a6321a8eSPavel Labath                "Ingoring this notification.",
449a6321a8eSPavel Labath                pid, info_err);
450b9cc0c75SPavel Labath       return;
451b9cc0c75SPavel Labath     }
452b9cc0c75SPavel Labath 
453a6321a8eSPavel Labath     LLDB_LOG(log, "tid {0}, si_code: {1}, si_pid: {2}", pid, info.si_code,
454a6321a8eSPavel Labath              info.si_pid);
455b9cc0c75SPavel Labath 
456*c8d18cbaSMichał Górny     MonitorClone(pid, llvm::None);
457b9cc0c75SPavel Labath     return;
458b9cc0c75SPavel Labath   }
459b9cc0c75SPavel Labath 
460b9cc0c75SPavel Labath   // Get details on the signal raised.
461b9c1b51eSKate Stone   if (info_err.Success()) {
462fa03ad2eSChaoren Lin     // We have retrieved the signal info.  Dispatch appropriately.
463fa03ad2eSChaoren Lin     if (info.si_signo == SIGTRAP)
464b9cc0c75SPavel Labath       MonitorSIGTRAP(info, *thread_sp);
465fa03ad2eSChaoren Lin     else
466b9cc0c75SPavel Labath       MonitorSignal(info, *thread_sp, exited);
467b9c1b51eSKate Stone   } else {
468b9c1b51eSKate Stone     if (info_err.GetError() == EINVAL) {
46905097246SAdrian Prantl       // This is a group stop reception for this tid. We can reach here if we
47005097246SAdrian Prantl       // reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the tracee,
47105097246SAdrian Prantl       // triggering the group-stop mechanism. Normally receiving these would
47205097246SAdrian Prantl       // stop the process, pending a SIGCONT. Simulating this state in a
47305097246SAdrian Prantl       // debugger is hard and is generally not needed (one use case is
47405097246SAdrian Prantl       // debugging background task being managed by a shell). For general use,
47505097246SAdrian Prantl       // it is sufficient to stop the process in a signal-delivery stop which
47605097246SAdrian Prantl       // happens before the group stop. This done by MonitorSignal and works
47705097246SAdrian Prantl       // correctly for all signals.
478a6321a8eSPavel Labath       LLDB_LOG(log,
479a6321a8eSPavel Labath                "received a group stop for pid {0} tid {1}. Transparent "
480a6321a8eSPavel Labath                "handling of group stops not supported, resuming the "
481a6321a8eSPavel Labath                "thread.",
482a6321a8eSPavel Labath                GetID(), pid);
483b9c1b51eSKate Stone       ResumeThread(*thread_sp, thread_sp->GetState(),
484b9c1b51eSKate Stone                    LLDB_INVALID_SIGNAL_NUMBER);
485b9c1b51eSKate Stone     } else {
486af245d11STodd Fiala       // ptrace(GETSIGINFO) failed (but not due to group-stop).
487af245d11STodd Fiala 
488b9c1b51eSKate Stone       // A return value of ESRCH means the thread/process is no longer on the
489a6321a8eSPavel Labath       // system, so it was killed somehow outside of our control.  Either way,
490a6321a8eSPavel Labath       // we can't do anything with it anymore.
491af245d11STodd Fiala 
492b9c1b51eSKate Stone       // Stop tracking the metadata for the thread since it's entirely off the
493b9c1b51eSKate Stone       // system now.
4941107b5a5SPavel Labath       const bool thread_found = StopTrackingThread(pid);
495af245d11STodd Fiala 
496a6321a8eSPavel Labath       LLDB_LOG(log,
4979303afb3SPavel Labath                "GetSignalInfo failed: {0}, tid = {1}, status = {2}, "
498a6321a8eSPavel Labath                "status = {3}, main_thread = {4}, thread_found: {5}",
4999303afb3SPavel Labath                info_err, pid, status, status, is_main_thread, thread_found);
500af245d11STodd Fiala 
501b9c1b51eSKate Stone       if (is_main_thread) {
502b9c1b51eSKate Stone         // Notify the delegate - our process is not available but appears to
50305097246SAdrian Prantl         // have been killed outside our control.  Is eStateExited the right
50405097246SAdrian Prantl         // exit state in this case?
5053508fc8cSPavel Labath         SetExitStatus(status, true);
5061107b5a5SPavel Labath         SetState(StateType::eStateExited, true);
507b9c1b51eSKate Stone       } else {
508b9c1b51eSKate Stone         // This thread was pulled out from underneath us.  Anything to do here?
509b9c1b51eSKate Stone         // Do we want to do an all stop?
510a6321a8eSPavel Labath         LLDB_LOG(log,
511a6321a8eSPavel Labath                  "pid {0} tid {1} non-main thread exit occurred, didn't "
512a6321a8eSPavel Labath                  "tell delegate anything since thread disappeared out "
513a6321a8eSPavel Labath                  "from underneath us",
514a6321a8eSPavel Labath                  GetID(), pid);
515af245d11STodd Fiala       }
516af245d11STodd Fiala     }
517af245d11STodd Fiala   }
518af245d11STodd Fiala }
519af245d11STodd Fiala 
520*c8d18cbaSMichał Górny void NativeProcessLinux::WaitForCloneNotification(::pid_t pid) {
521a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
522426bdf88SPavel Labath 
523*c8d18cbaSMichał Górny   // The PID is not tracked yet, let's wait for it to appear.
524426bdf88SPavel Labath   int status = -1;
525a6321a8eSPavel Labath   LLDB_LOG(log,
526*c8d18cbaSMichał Górny            "received clone event for pid {0}. pid not tracked yet, "
527*c8d18cbaSMichał Górny            "waiting for it to appear...",
528*c8d18cbaSMichał Górny            pid);
529*c8d18cbaSMichał Górny   ::pid_t wait_pid =
530*c8d18cbaSMichał Górny       llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &status, __WALL);
531*c8d18cbaSMichał Górny   // Since we are waiting on a specific pid, this must be the creation event.
532a6321a8eSPavel Labath   // But let's do some checks just in case.
533*c8d18cbaSMichał Górny   if (wait_pid != pid) {
534a6321a8eSPavel Labath     LLDB_LOG(log,
535*c8d18cbaSMichał Górny              "waiting for pid {0} failed. Assuming the pid has "
536a6321a8eSPavel Labath              "disappeared in the meantime",
537*c8d18cbaSMichał Górny              pid);
538426bdf88SPavel Labath     // The only way I know of this could happen is if the whole process was
539b9c1b51eSKate Stone     // SIGKILLed in the mean time. In any case, we can't do anything about that
540b9c1b51eSKate Stone     // now.
541426bdf88SPavel Labath     return;
542426bdf88SPavel Labath   }
543b9c1b51eSKate Stone   if (WIFEXITED(status)) {
544a6321a8eSPavel Labath     LLDB_LOG(log,
545*c8d18cbaSMichał Górny              "waiting for pid {0} returned an 'exited' event. Not "
546*c8d18cbaSMichał Górny              "tracking it.",
547*c8d18cbaSMichał Górny              pid);
548426bdf88SPavel Labath     // Also a very improbable event.
549*c8d18cbaSMichał Górny     m_pending_pid_map.erase(pid);
550426bdf88SPavel Labath     return;
551426bdf88SPavel Labath   }
552426bdf88SPavel Labath 
553*c8d18cbaSMichał Górny   MonitorClone(pid, llvm::None);
554426bdf88SPavel Labath }
555426bdf88SPavel Labath 
556b9c1b51eSKate Stone void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info,
557b9c1b51eSKate Stone                                         NativeThreadLinux &thread) {
558a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
559b9cc0c75SPavel Labath   const bool is_main_thread = (thread.GetID() == GetID());
560af245d11STodd Fiala 
561b9cc0c75SPavel Labath   assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
562af245d11STodd Fiala 
563b9c1b51eSKate Stone   switch (info.si_code) {
564*c8d18cbaSMichał Górny   case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
565*c8d18cbaSMichał Górny   case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
566b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): {
567*c8d18cbaSMichał Górny     // This can either mean a new thread or a new process spawned via
568*c8d18cbaSMichał Górny     // clone(2) without SIGCHLD or CLONE_VFORK flag.  Note that clone(2)
569*c8d18cbaSMichał Górny     // can also cause PTRACE_EVENT_FORK and PTRACE_EVENT_VFORK if one
570*c8d18cbaSMichał Górny     // of these flags are passed.
571af245d11STodd Fiala 
572af245d11STodd Fiala     unsigned long event_message = 0;
573b9c1b51eSKate Stone     if (GetEventMessage(thread.GetID(), &event_message).Fail()) {
574a6321a8eSPavel Labath       LLDB_LOG(log,
575*c8d18cbaSMichał Górny                "pid {0} received clone() event but GetEventMessage failed "
576*c8d18cbaSMichał Górny                "so we don't know the new pid/tid",
577a6321a8eSPavel Labath                thread.GetID());
578121cff78SPavel Labath       ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
579*c8d18cbaSMichał Górny     } else {
580*c8d18cbaSMichał Górny       if (!MonitorClone(event_message, {{(info.si_code >> 8), thread.GetID()}}))
581*c8d18cbaSMichał Górny         WaitForCloneNotification(event_message);
582*c8d18cbaSMichał Górny     }
583*c8d18cbaSMichał Górny 
584af245d11STodd Fiala     break;
585af245d11STodd Fiala   }
586af245d11STodd Fiala 
587b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): {
588a6321a8eSPavel Labath     LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP);
589a9882ceeSTodd Fiala 
5901dbc6c9cSPavel Labath     // Exec clears any pending notifications.
5910e1d729bSPavel Labath     m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
592fa03ad2eSChaoren Lin 
593b9c1b51eSKate Stone     // Remove all but the main thread here.  Linux fork creates a new process
594b9c1b51eSKate Stone     // which only copies the main thread.
595a6321a8eSPavel Labath     LLDB_LOG(log, "exec received, stop tracking all but main thread");
596a9882ceeSTodd Fiala 
597ee74c9e5SPavel Labath     llvm::erase_if(m_threads, [&](std::unique_ptr<NativeThreadProtocol> &t) {
598ee74c9e5SPavel Labath       return t->GetID() != GetID();
599ee74c9e5SPavel Labath     });
600a5be48b3SPavel Labath     assert(m_threads.size() == 1);
601a5be48b3SPavel Labath     auto *main_thread = static_cast<NativeThreadLinux *>(m_threads[0].get());
602a9882ceeSTodd Fiala 
603a5be48b3SPavel Labath     SetCurrentThreadID(main_thread->GetID());
604a5be48b3SPavel Labath     main_thread->SetStoppedByExec();
605a9882ceeSTodd Fiala 
606fa03ad2eSChaoren Lin     // Tell coordinator about about the "new" (since exec) stopped main thread.
607a5be48b3SPavel Labath     ThreadWasCreated(*main_thread);
608fa03ad2eSChaoren Lin 
609a9882ceeSTodd Fiala     // Let our delegate know we have just exec'd.
610a9882ceeSTodd Fiala     NotifyDidExec();
611a9882ceeSTodd Fiala 
612fa03ad2eSChaoren Lin     // Let the process know we're stopped.
613a5be48b3SPavel Labath     StopRunningThreads(main_thread->GetID());
614a9882ceeSTodd Fiala 
615af245d11STodd Fiala     break;
616a9882ceeSTodd Fiala   }
617af245d11STodd Fiala 
618b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): {
61905097246SAdrian Prantl     // The inferior process or one of its threads is about to exit. We don't
62005097246SAdrian Prantl     // want to do anything with the thread so we just resume it. In case we
62105097246SAdrian Prantl     // want to implement "break on thread exit" functionality, we would need to
62205097246SAdrian Prantl     // stop here.
623fa03ad2eSChaoren Lin 
624af245d11STodd Fiala     unsigned long data = 0;
625b9cc0c75SPavel Labath     if (GetEventMessage(thread.GetID(), &data).Fail())
626af245d11STodd Fiala       data = -1;
627af245d11STodd Fiala 
628a6321a8eSPavel Labath     LLDB_LOG(log,
629a6321a8eSPavel Labath              "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
630a6321a8eSPavel Labath              "WIFSIGNALED={2}, pid = {3}, main_thread = {4}",
631a6321a8eSPavel Labath              data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(),
632a6321a8eSPavel Labath              is_main_thread);
633af245d11STodd Fiala 
63475f47c3aSTodd Fiala 
63586852d36SPavel Labath     StateType state = thread.GetState();
636b9c1b51eSKate Stone     if (!StateIsRunningState(state)) {
637b9c1b51eSKate Stone       // Due to a kernel bug, we may sometimes get this stop after the inferior
638d8b3c1a1SPavel Labath       // gets a SIGKILL. This confuses our state tracking logic in
639d8b3c1a1SPavel Labath       // ResumeThread(), since normally, we should not be receiving any ptrace
64005097246SAdrian Prantl       // events while the inferior is stopped. This makes sure that the
64105097246SAdrian Prantl       // inferior is resumed and exits normally.
64286852d36SPavel Labath       state = eStateRunning;
64386852d36SPavel Labath     }
64486852d36SPavel Labath     ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
645af245d11STodd Fiala 
646af245d11STodd Fiala     break;
647af245d11STodd Fiala   }
648af245d11STodd Fiala 
649*c8d18cbaSMichał Górny   case (SIGTRAP | (PTRACE_EVENT_VFORK_DONE << 8)): {
650*c8d18cbaSMichał Górny     ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
651*c8d18cbaSMichał Górny     break;
652*c8d18cbaSMichał Górny   }
653*c8d18cbaSMichał Górny 
654af245d11STodd Fiala   case 0:
655c16f5dcaSChaoren Lin   case TRAP_TRACE:  // We receive this on single stepping.
656c16f5dcaSChaoren Lin   case TRAP_HWBKPT: // We receive this on watchpoint hit
65786fd8e45SChaoren Lin   {
658c16f5dcaSChaoren Lin     // If a watchpoint was hit, report it
659c16f5dcaSChaoren Lin     uint32_t wp_index;
660d37349f3SPavel Labath     Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
661b9c1b51eSKate Stone         wp_index, (uintptr_t)info.si_addr);
662a6321a8eSPavel Labath     if (error.Fail())
663a6321a8eSPavel Labath       LLDB_LOG(log,
664a6321a8eSPavel Labath                "received error while checking for watchpoint hits, pid = "
665a6321a8eSPavel Labath                "{0}, error = {1}",
666a6321a8eSPavel Labath                thread.GetID(), error);
667b9c1b51eSKate Stone     if (wp_index != LLDB_INVALID_INDEX32) {
668b9cc0c75SPavel Labath       MonitorWatchpoint(thread, wp_index);
669c16f5dcaSChaoren Lin       break;
670c16f5dcaSChaoren Lin     }
671b9cc0c75SPavel Labath 
672d5ffbad2SOmair Javaid     // If a breakpoint was hit, report it
673d5ffbad2SOmair Javaid     uint32_t bp_index;
674d37349f3SPavel Labath     error = thread.GetRegisterContext().GetHardwareBreakHitIndex(
675d5ffbad2SOmair Javaid         bp_index, (uintptr_t)info.si_addr);
676d5ffbad2SOmair Javaid     if (error.Fail())
677d5ffbad2SOmair Javaid       LLDB_LOG(log, "received error while checking for hardware "
678d5ffbad2SOmair Javaid                     "breakpoint hits, pid = {0}, error = {1}",
679d5ffbad2SOmair Javaid                thread.GetID(), error);
680d5ffbad2SOmair Javaid     if (bp_index != LLDB_INVALID_INDEX32) {
681d5ffbad2SOmair Javaid       MonitorBreakpoint(thread);
682d5ffbad2SOmair Javaid       break;
683d5ffbad2SOmair Javaid     }
684d5ffbad2SOmair Javaid 
685be379e15STamas Berghammer     // Otherwise, report step over
686be379e15STamas Berghammer     MonitorTrace(thread);
687af245d11STodd Fiala     break;
688b9cc0c75SPavel Labath   }
689af245d11STodd Fiala 
690af245d11STodd Fiala   case SI_KERNEL:
69135799963SMohit K. Bhakkad #if defined __mips__
69205097246SAdrian Prantl     // For mips there is no special signal for watchpoint So we check for
69305097246SAdrian Prantl     // watchpoint in kernel trap
69435799963SMohit K. Bhakkad     {
69535799963SMohit K. Bhakkad       // If a watchpoint was hit, report it
69635799963SMohit K. Bhakkad       uint32_t wp_index;
697d37349f3SPavel Labath       Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
698b9c1b51eSKate Stone           wp_index, LLDB_INVALID_ADDRESS);
699a6321a8eSPavel Labath       if (error.Fail())
700a6321a8eSPavel Labath         LLDB_LOG(log,
701a6321a8eSPavel Labath                  "received error while checking for watchpoint hits, pid = "
702a6321a8eSPavel Labath                  "{0}, error = {1}",
703a6321a8eSPavel Labath                  thread.GetID(), error);
704b9c1b51eSKate Stone       if (wp_index != LLDB_INVALID_INDEX32) {
705b9cc0c75SPavel Labath         MonitorWatchpoint(thread, wp_index);
70635799963SMohit K. Bhakkad         break;
70735799963SMohit K. Bhakkad       }
70835799963SMohit K. Bhakkad     }
70935799963SMohit K. Bhakkad // NO BREAK
71035799963SMohit K. Bhakkad #endif
711af245d11STodd Fiala   case TRAP_BRKPT:
712b9cc0c75SPavel Labath     MonitorBreakpoint(thread);
713af245d11STodd Fiala     break;
714af245d11STodd Fiala 
715af245d11STodd Fiala   case SIGTRAP:
716af245d11STodd Fiala   case (SIGTRAP | 0x80):
717a6321a8eSPavel Labath     LLDB_LOG(
718a6321a8eSPavel Labath         log,
719a6321a8eSPavel Labath         "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",
720a6321a8eSPavel Labath         info.si_code, GetID(), thread.GetID());
721fa03ad2eSChaoren Lin 
722af245d11STodd Fiala     // Ignore these signals until we know more about them.
723b9cc0c75SPavel Labath     ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
724af245d11STodd Fiala     break;
725af245d11STodd Fiala 
726af245d11STodd Fiala   default:
72721a365baSPavel Labath     LLDB_LOG(log, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}",
728a6321a8eSPavel Labath              info.si_code, GetID(), thread.GetID());
72921a365baSPavel Labath     MonitorSignal(info, thread, false);
730af245d11STodd Fiala     break;
731af245d11STodd Fiala   }
732af245d11STodd Fiala }
733af245d11STodd Fiala 
734b9c1b51eSKate Stone void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) {
735a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
736a6321a8eSPavel Labath   LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID());
737c16f5dcaSChaoren Lin 
7380e1d729bSPavel Labath   // This thread is currently stopped.
739b9cc0c75SPavel Labath   thread.SetStoppedByTrace();
740c16f5dcaSChaoren Lin 
741b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
742c16f5dcaSChaoren Lin }
743c16f5dcaSChaoren Lin 
744b9c1b51eSKate Stone void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) {
745b9c1b51eSKate Stone   Log *log(
746b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
747a6321a8eSPavel Labath   LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID());
748c16f5dcaSChaoren Lin 
749c16f5dcaSChaoren Lin   // Mark the thread as stopped at breakpoint.
750b9cc0c75SPavel Labath   thread.SetStoppedByBreakpoint();
751aef7908fSPavel Labath   FixupBreakpointPCAsNeeded(thread);
752d8c338d4STamas Berghammer 
753b9c1b51eSKate Stone   if (m_threads_stepping_with_breakpoint.find(thread.GetID()) !=
754b9c1b51eSKate Stone       m_threads_stepping_with_breakpoint.end())
755b9cc0c75SPavel Labath     thread.SetStoppedByTrace();
756c16f5dcaSChaoren Lin 
757b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
758c16f5dcaSChaoren Lin }
759c16f5dcaSChaoren Lin 
760b9c1b51eSKate Stone void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread,
761b9c1b51eSKate Stone                                            uint32_t wp_index) {
762b9c1b51eSKate Stone   Log *log(
763b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
764a6321a8eSPavel Labath   LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}",
765a6321a8eSPavel Labath            thread.GetID(), wp_index);
766c16f5dcaSChaoren Lin 
76705097246SAdrian Prantl   // Mark the thread as stopped at watchpoint. The address is at
76805097246SAdrian Prantl   // (lldb::addr_t)info->si_addr if we need it.
769f9077782SPavel Labath   thread.SetStoppedByWatchpoint(wp_index);
770c16f5dcaSChaoren Lin 
771b9c1b51eSKate Stone   // We need to tell all other running threads before we notify the delegate
772b9c1b51eSKate Stone   // about this stop.
773f9077782SPavel Labath   StopRunningThreads(thread.GetID());
774c16f5dcaSChaoren Lin }
775c16f5dcaSChaoren Lin 
776b9c1b51eSKate Stone void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
777b9c1b51eSKate Stone                                        NativeThreadLinux &thread, bool exited) {
778b9cc0c75SPavel Labath   const int signo = info.si_signo;
779b9cc0c75SPavel Labath   const bool is_from_llgs = info.si_pid == getpid();
780af245d11STodd Fiala 
781a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
782af245d11STodd Fiala 
783af245d11STodd Fiala   // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
78405097246SAdrian Prantl   // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a kill(2)
78505097246SAdrian Prantl   // or raise(3).  Similarly for tgkill(2) on Linux.
786af245d11STodd Fiala   //
787af245d11STodd Fiala   // IOW, user generated signals never generate what we consider to be a
788af245d11STodd Fiala   // "crash".
789af245d11STodd Fiala   //
790af245d11STodd Fiala   // Similarly, ACK signals generated by this monitor.
791af245d11STodd Fiala 
792af245d11STodd Fiala   // Handle the signal.
793a6321a8eSPavel Labath   LLDB_LOG(log,
794a6321a8eSPavel Labath            "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
795a6321a8eSPavel Labath            "waitpid pid = {4})",
796a6321a8eSPavel Labath            Host::GetSignalAsCString(signo), signo, info.si_code,
797b9cc0c75SPavel Labath            thread.GetID());
79858a2f669STodd Fiala 
79958a2f669STodd Fiala   // Check for thread stop notification.
800b9c1b51eSKate Stone   if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) {
801af245d11STodd Fiala     // This is a tgkill()-based stop.
802a6321a8eSPavel Labath     LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID());
803fa03ad2eSChaoren Lin 
80405097246SAdrian Prantl     // Check that we're not already marked with a stop reason. Note this thread
80505097246SAdrian Prantl     // really shouldn't already be marked as stopped - if we were, that would
80605097246SAdrian Prantl     // imply that the kernel signaled us with the thread stopping which we
80705097246SAdrian Prantl     // handled and marked as stopped, and that, without an intervening resume,
80805097246SAdrian Prantl     // we received another stop.  It is more likely that we are missing the
80905097246SAdrian Prantl     // marking of a run state somewhere if we find that the thread was marked
81005097246SAdrian Prantl     // as stopped.
811b9cc0c75SPavel Labath     const StateType thread_state = thread.GetState();
812b9c1b51eSKate Stone     if (!StateIsStoppedState(thread_state, false)) {
813ed89c7feSPavel Labath       // An inferior thread has stopped because of a SIGSTOP we have sent it.
814b9c1b51eSKate Stone       // Generally, these are not important stops and we don't want to report
815a6321a8eSPavel Labath       // them as they are just used to stop other threads when one thread (the
816a6321a8eSPavel Labath       // one with the *real* stop reason) hits a breakpoint (watchpoint,
81705097246SAdrian Prantl       // etc...). However, in the case of an asynchronous Interrupt(), this
81805097246SAdrian Prantl       // *is* the real stop reason, so we leave the signal intact if this is
81905097246SAdrian Prantl       // the thread that was chosen as the triggering thread.
820b9c1b51eSKate Stone       if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
821b9cc0c75SPavel Labath         if (m_pending_notification_tid == thread.GetID())
822b9cc0c75SPavel Labath           thread.SetStoppedBySignal(SIGSTOP, &info);
823ed89c7feSPavel Labath         else
824b9cc0c75SPavel Labath           thread.SetStoppedWithNoReason();
825ed89c7feSPavel Labath 
826b9cc0c75SPavel Labath         SetCurrentThreadID(thread.GetID());
8270e1d729bSPavel Labath         SignalIfAllThreadsStopped();
828b9c1b51eSKate Stone       } else {
8290e1d729bSPavel Labath         // We can end up here if stop was initiated by LLGS but by this time a
8300e1d729bSPavel Labath         // thread stop has occurred - maybe initiated by another event.
83197206d57SZachary Turner         Status error = ResumeThread(thread, thread.GetState(), 0);
832a6321a8eSPavel Labath         if (error.Fail())
833a6321a8eSPavel Labath           LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(),
834a6321a8eSPavel Labath                    error);
8350e1d729bSPavel Labath       }
836b9c1b51eSKate Stone     } else {
837a6321a8eSPavel Labath       LLDB_LOG(log,
838a6321a8eSPavel Labath                "pid {0} tid {1}, thread was already marked as a stopped "
839a6321a8eSPavel Labath                "state (state={2}), leaving stop signal as is",
8408198db30SPavel Labath                GetID(), thread.GetID(), thread_state);
8410e1d729bSPavel Labath       SignalIfAllThreadsStopped();
842af245d11STodd Fiala     }
843af245d11STodd Fiala 
84458a2f669STodd Fiala     // Done handling.
845af245d11STodd Fiala     return;
846af245d11STodd Fiala   }
847af245d11STodd Fiala 
84805097246SAdrian Prantl   // Check if debugger should stop at this signal or just ignore it and resume
84905097246SAdrian Prantl   // the inferior.
8504a705e7eSPavel Labath   if (m_signals_to_ignore.find(signo) != m_signals_to_ignore.end()) {
8514a705e7eSPavel Labath      ResumeThread(thread, thread.GetState(), signo);
8524a705e7eSPavel Labath      return;
8534a705e7eSPavel Labath   }
8544a705e7eSPavel Labath 
85586fd8e45SChaoren Lin   // This thread is stopped.
856a6321a8eSPavel Labath   LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo));
857b9cc0c75SPavel Labath   thread.SetStoppedBySignal(signo, &info);
85886fd8e45SChaoren Lin 
85986fd8e45SChaoren Lin   // Send a stop to the debugger after we get all other threads to stop.
860b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
861511e5cdcSTodd Fiala }
862af245d11STodd Fiala 
863*c8d18cbaSMichał Górny bool NativeProcessLinux::MonitorClone(
864*c8d18cbaSMichał Górny     lldb::pid_t child_pid,
865*c8d18cbaSMichał Górny     llvm::Optional<NativeProcessLinux::CloneInfo> clone_info) {
866*c8d18cbaSMichał Górny   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
867*c8d18cbaSMichał Górny   LLDB_LOG(log, "clone, child_pid={0}, clone info?={1}", child_pid,
868*c8d18cbaSMichał Górny            clone_info.hasValue());
869*c8d18cbaSMichał Górny 
870*c8d18cbaSMichał Górny   auto find_it = m_pending_pid_map.find(child_pid);
871*c8d18cbaSMichał Górny   if (find_it == m_pending_pid_map.end()) {
872*c8d18cbaSMichał Górny     // not in the map, so this is the first signal for the PID
873*c8d18cbaSMichał Górny     m_pending_pid_map.insert({child_pid, clone_info});
874*c8d18cbaSMichał Górny     return false;
875*c8d18cbaSMichał Górny   }
876*c8d18cbaSMichał Górny   m_pending_pid_map.erase(find_it);
877*c8d18cbaSMichał Górny 
878*c8d18cbaSMichał Górny   // second signal for the pid
879*c8d18cbaSMichał Górny   assert(clone_info.hasValue() != find_it->second.hasValue());
880*c8d18cbaSMichał Górny   if (!clone_info) {
881*c8d18cbaSMichał Górny     // child signal does not indicate the event, so grab the one stored
882*c8d18cbaSMichał Górny     // earlier
883*c8d18cbaSMichał Górny     clone_info = find_it->second;
884*c8d18cbaSMichał Górny   }
885*c8d18cbaSMichał Górny 
886*c8d18cbaSMichał Górny   LLDB_LOG(log, "second signal for child_pid={0}, parent_tid={1}, event={2}",
887*c8d18cbaSMichał Górny            child_pid, clone_info->parent_tid, clone_info->event);
888*c8d18cbaSMichał Górny 
889*c8d18cbaSMichał Górny   auto *parent_thread = GetThreadByID(clone_info->parent_tid);
890*c8d18cbaSMichał Górny   assert(parent_thread);
891*c8d18cbaSMichał Górny 
892*c8d18cbaSMichał Górny   switch (clone_info->event) {
893*c8d18cbaSMichał Górny   case PTRACE_EVENT_CLONE: {
894*c8d18cbaSMichał Górny     // PTRACE_EVENT_CLONE can either mean a new thread or a new process.
895*c8d18cbaSMichał Górny     // Try to grab the new process' PGID to figure out which one it is.
896*c8d18cbaSMichał Górny     // If PGID is the same as the PID, then it's a new process.  Otherwise,
897*c8d18cbaSMichał Górny     // it's a thread.
898*c8d18cbaSMichał Górny     auto tgid_ret = getPIDForTID(child_pid);
899*c8d18cbaSMichał Górny     if (tgid_ret != child_pid) {
900*c8d18cbaSMichał Górny       // A new thread should have PGID matching our process' PID.
901*c8d18cbaSMichał Górny       assert(!tgid_ret || tgid_ret.getValue() == GetID());
902*c8d18cbaSMichał Górny 
903*c8d18cbaSMichał Górny       NativeThreadLinux &child_thread = AddThread(child_pid, /*resume*/ true);
904*c8d18cbaSMichał Górny       ThreadWasCreated(child_thread);
905*c8d18cbaSMichał Górny 
906*c8d18cbaSMichał Górny       // Resume the parent.
907*c8d18cbaSMichał Górny       ResumeThread(*parent_thread, parent_thread->GetState(),
908*c8d18cbaSMichał Górny                    LLDB_INVALID_SIGNAL_NUMBER);
909*c8d18cbaSMichał Górny       break;
910*c8d18cbaSMichał Górny     }
911*c8d18cbaSMichał Górny   }
912*c8d18cbaSMichał Górny     LLVM_FALLTHROUGH;
913*c8d18cbaSMichał Górny   case PTRACE_EVENT_FORK:
914*c8d18cbaSMichał Górny   case PTRACE_EVENT_VFORK: {
915*c8d18cbaSMichał Górny     MainLoop unused_loop;
916*c8d18cbaSMichał Górny     NativeProcessLinux child_process{static_cast<::pid_t>(child_pid),
917*c8d18cbaSMichał Górny                                      m_terminal_fd,
918*c8d18cbaSMichał Górny                                      m_delegate,
919*c8d18cbaSMichał Górny                                      m_arch,
920*c8d18cbaSMichał Górny                                      unused_loop,
921*c8d18cbaSMichał Górny                                      {static_cast<::pid_t>(child_pid)}};
922*c8d18cbaSMichał Górny     child_process.Detach();
923*c8d18cbaSMichał Górny     ResumeThread(*parent_thread, parent_thread->GetState(),
924*c8d18cbaSMichał Górny                  LLDB_INVALID_SIGNAL_NUMBER);
925*c8d18cbaSMichał Górny     break;
926*c8d18cbaSMichał Górny   }
927*c8d18cbaSMichał Górny   default:
928*c8d18cbaSMichał Górny     llvm_unreachable("unknown clone_info.event");
929*c8d18cbaSMichał Górny   }
930*c8d18cbaSMichał Górny 
931*c8d18cbaSMichał Górny   return true;
932*c8d18cbaSMichał Górny }
933*c8d18cbaSMichał Górny 
934b9c1b51eSKate Stone bool NativeProcessLinux::SupportHardwareSingleStepping() const {
935ddb93b63SFangrui Song   if (m_arch.GetMachine() == llvm::Triple::arm || m_arch.IsMIPS())
936cdc22a88SMohit K. Bhakkad     return false;
937cdc22a88SMohit K. Bhakkad   return true;
938e7708688STamas Berghammer }
939e7708688STamas Berghammer 
94097206d57SZachary Turner Status NativeProcessLinux::Resume(const ResumeActionList &resume_actions) {
941a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
942a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0}", GetID());
943af245d11STodd Fiala 
944e7708688STamas Berghammer   bool software_single_step = !SupportHardwareSingleStepping();
945af245d11STodd Fiala 
946b9c1b51eSKate Stone   if (software_single_step) {
947a5be48b3SPavel Labath     for (const auto &thread : m_threads) {
948a5be48b3SPavel Labath       assert(thread && "thread list should not contain NULL threads");
949e7708688STamas Berghammer 
950b9c1b51eSKate Stone       const ResumeAction *const action =
951a5be48b3SPavel Labath           resume_actions.GetActionForThread(thread->GetID(), true);
952e7708688STamas Berghammer       if (action == nullptr)
953e7708688STamas Berghammer         continue;
954e7708688STamas Berghammer 
955b9c1b51eSKate Stone       if (action->state == eStateStepping) {
95697206d57SZachary Turner         Status error = SetupSoftwareSingleStepping(
957a5be48b3SPavel Labath             static_cast<NativeThreadLinux &>(*thread));
958e7708688STamas Berghammer         if (error.Fail())
959e7708688STamas Berghammer           return error;
960e7708688STamas Berghammer       }
961e7708688STamas Berghammer     }
962e7708688STamas Berghammer   }
963e7708688STamas Berghammer 
964a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
965a5be48b3SPavel Labath     assert(thread && "thread list should not contain NULL threads");
966af245d11STodd Fiala 
967b9c1b51eSKate Stone     const ResumeAction *const action =
968a5be48b3SPavel Labath         resume_actions.GetActionForThread(thread->GetID(), true);
9696a196ce6SChaoren Lin 
970b9c1b51eSKate Stone     if (action == nullptr) {
971a6321a8eSPavel Labath       LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
972a5be48b3SPavel Labath                thread->GetID());
9736a196ce6SChaoren Lin       continue;
9746a196ce6SChaoren Lin     }
975af245d11STodd Fiala 
976a6321a8eSPavel Labath     LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}",
977a5be48b3SPavel Labath              action->state, GetID(), thread->GetID());
978af245d11STodd Fiala 
979b9c1b51eSKate Stone     switch (action->state) {
980af245d11STodd Fiala     case eStateRunning:
981b9c1b51eSKate Stone     case eStateStepping: {
982af245d11STodd Fiala       // Run the thread, possibly feeding it the signal.
983fa03ad2eSChaoren Lin       const int signo = action->signal;
984a5be48b3SPavel Labath       ResumeThread(static_cast<NativeThreadLinux &>(*thread), action->state,
985b9c1b51eSKate Stone                    signo);
986af245d11STodd Fiala       break;
987ae29d395SChaoren Lin     }
988af245d11STodd Fiala 
989af245d11STodd Fiala     case eStateSuspended:
990af245d11STodd Fiala     case eStateStopped:
991a6321a8eSPavel Labath       llvm_unreachable("Unexpected state");
992af245d11STodd Fiala 
993af245d11STodd Fiala     default:
99497206d57SZachary Turner       return Status("NativeProcessLinux::%s (): unexpected state %s specified "
995b9c1b51eSKate Stone                     "for pid %" PRIu64 ", tid %" PRIu64,
996b9c1b51eSKate Stone                     __FUNCTION__, StateAsCString(action->state), GetID(),
997a5be48b3SPavel Labath                     thread->GetID());
998af245d11STodd Fiala     }
999af245d11STodd Fiala   }
1000af245d11STodd Fiala 
100197206d57SZachary Turner   return Status();
1002af245d11STodd Fiala }
1003af245d11STodd Fiala 
100497206d57SZachary Turner Status NativeProcessLinux::Halt() {
100597206d57SZachary Turner   Status error;
1006af245d11STodd Fiala 
1007af245d11STodd Fiala   if (kill(GetID(), SIGSTOP) != 0)
1008af245d11STodd Fiala     error.SetErrorToErrno();
1009af245d11STodd Fiala 
1010af245d11STodd Fiala   return error;
1011af245d11STodd Fiala }
1012af245d11STodd Fiala 
101397206d57SZachary Turner Status NativeProcessLinux::Detach() {
101497206d57SZachary Turner   Status error;
1015af245d11STodd Fiala 
1016af245d11STodd Fiala   // Stop monitoring the inferior.
101719cbe96aSPavel Labath   m_sigchld_handle.reset();
1018af245d11STodd Fiala 
10197a9495bcSPavel Labath   // Tell ptrace to detach from the process.
10207a9495bcSPavel Labath   if (GetID() == LLDB_INVALID_PROCESS_ID)
10217a9495bcSPavel Labath     return error;
10227a9495bcSPavel Labath 
1023a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
1024a5be48b3SPavel Labath     Status e = Detach(thread->GetID());
10257a9495bcSPavel Labath     if (e.Fail())
1026b9c1b51eSKate Stone       error =
1027b9c1b51eSKate Stone           e; // Save the error, but still attempt to detach from other threads.
10287a9495bcSPavel Labath   }
10297a9495bcSPavel Labath 
10300b697561SWalter Erquinigo   m_intel_pt_manager.Clear();
103199e37695SRavitheja Addepally 
1032af245d11STodd Fiala   return error;
1033af245d11STodd Fiala }
1034af245d11STodd Fiala 
103597206d57SZachary Turner Status NativeProcessLinux::Signal(int signo) {
103697206d57SZachary Turner   Status error;
1037af245d11STodd Fiala 
1038a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1039a6321a8eSPavel Labath   LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo,
1040a6321a8eSPavel Labath            Host::GetSignalAsCString(signo), GetID());
1041af245d11STodd Fiala 
1042af245d11STodd Fiala   if (kill(GetID(), signo))
1043af245d11STodd Fiala     error.SetErrorToErrno();
1044af245d11STodd Fiala 
1045af245d11STodd Fiala   return error;
1046af245d11STodd Fiala }
1047af245d11STodd Fiala 
104897206d57SZachary Turner Status NativeProcessLinux::Interrupt() {
104905097246SAdrian Prantl   // Pick a running thread (or if none, a not-dead stopped thread) as the
105005097246SAdrian Prantl   // chosen thread that will be the stop-reason thread.
1051a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1052e9547b80SChaoren Lin 
1053a5be48b3SPavel Labath   NativeThreadProtocol *running_thread = nullptr;
1054a5be48b3SPavel Labath   NativeThreadProtocol *stopped_thread = nullptr;
1055e9547b80SChaoren Lin 
1056a6321a8eSPavel Labath   LLDB_LOG(log, "selecting running thread for interrupt target");
1057a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
105805097246SAdrian Prantl     // If we have a running or stepping thread, we'll call that the target of
105905097246SAdrian Prantl     // the interrupt.
1060a5be48b3SPavel Labath     const auto thread_state = thread->GetState();
1061b9c1b51eSKate Stone     if (thread_state == eStateRunning || thread_state == eStateStepping) {
1062a5be48b3SPavel Labath       running_thread = thread.get();
1063e9547b80SChaoren Lin       break;
1064a5be48b3SPavel Labath     } else if (!stopped_thread && StateIsStoppedState(thread_state, true)) {
106505097246SAdrian Prantl       // Remember the first non-dead stopped thread.  We'll use that as a
106605097246SAdrian Prantl       // backup if there are no running threads.
1067a5be48b3SPavel Labath       stopped_thread = thread.get();
1068e9547b80SChaoren Lin     }
1069e9547b80SChaoren Lin   }
1070e9547b80SChaoren Lin 
1071a5be48b3SPavel Labath   if (!running_thread && !stopped_thread) {
107297206d57SZachary Turner     Status error("found no running/stepping or live stopped threads as target "
1073b9c1b51eSKate Stone                  "for interrupt");
1074a6321a8eSPavel Labath     LLDB_LOG(log, "skipping due to error: {0}", error);
10755830aa75STamas Berghammer 
1076e9547b80SChaoren Lin     return error;
1077e9547b80SChaoren Lin   }
1078e9547b80SChaoren Lin 
1079a5be48b3SPavel Labath   NativeThreadProtocol *deferred_signal_thread =
1080a5be48b3SPavel Labath       running_thread ? running_thread : stopped_thread;
1081e9547b80SChaoren Lin 
1082a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(),
1083a5be48b3SPavel Labath            running_thread ? "running" : "stopped",
1084a5be48b3SPavel Labath            deferred_signal_thread->GetID());
1085e9547b80SChaoren Lin 
1086a5be48b3SPavel Labath   StopRunningThreads(deferred_signal_thread->GetID());
108745f5cb31SPavel Labath 
108897206d57SZachary Turner   return Status();
1089e9547b80SChaoren Lin }
1090e9547b80SChaoren Lin 
109197206d57SZachary Turner Status NativeProcessLinux::Kill() {
1092a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1093a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0}", GetID());
1094af245d11STodd Fiala 
109597206d57SZachary Turner   Status error;
1096af245d11STodd Fiala 
1097b9c1b51eSKate Stone   switch (m_state) {
1098af245d11STodd Fiala   case StateType::eStateInvalid:
1099af245d11STodd Fiala   case StateType::eStateExited:
1100af245d11STodd Fiala   case StateType::eStateCrashed:
1101af245d11STodd Fiala   case StateType::eStateDetached:
1102af245d11STodd Fiala   case StateType::eStateUnloaded:
1103af245d11STodd Fiala     // Nothing to do - the process is already dead.
1104a6321a8eSPavel Labath     LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
11058198db30SPavel Labath              m_state);
1106af245d11STodd Fiala     return error;
1107af245d11STodd Fiala 
1108af245d11STodd Fiala   case StateType::eStateConnected:
1109af245d11STodd Fiala   case StateType::eStateAttaching:
1110af245d11STodd Fiala   case StateType::eStateLaunching:
1111af245d11STodd Fiala   case StateType::eStateStopped:
1112af245d11STodd Fiala   case StateType::eStateRunning:
1113af245d11STodd Fiala   case StateType::eStateStepping:
1114af245d11STodd Fiala   case StateType::eStateSuspended:
1115af245d11STodd Fiala     // We can try to kill a process in these states.
1116af245d11STodd Fiala     break;
1117af245d11STodd Fiala   }
1118af245d11STodd Fiala 
1119b9c1b51eSKate Stone   if (kill(GetID(), SIGKILL) != 0) {
1120af245d11STodd Fiala     error.SetErrorToErrno();
1121af245d11STodd Fiala     return error;
1122af245d11STodd Fiala   }
1123af245d11STodd Fiala 
1124af245d11STodd Fiala   return error;
1125af245d11STodd Fiala }
1126af245d11STodd Fiala 
112797206d57SZachary Turner Status NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr,
1128b9c1b51eSKate Stone                                                MemoryRegionInfo &range_info) {
1129b9c1b51eSKate Stone   // FIXME review that the final memory region returned extends to the end of
1130b9c1b51eSKate Stone   // the virtual address space,
1131af245d11STodd Fiala   // with no perms if it is not mapped.
1132af245d11STodd Fiala 
113305097246SAdrian Prantl   // Use an approach that reads memory regions from /proc/{pid}/maps. Assume
113405097246SAdrian Prantl   // proc maps entries are in ascending order.
1135af245d11STodd Fiala   // FIXME assert if we find differently.
1136af245d11STodd Fiala 
1137b9c1b51eSKate Stone   if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
1138af245d11STodd Fiala     // We're done.
113997206d57SZachary Turner     return Status("unsupported");
1140af245d11STodd Fiala   }
1141af245d11STodd Fiala 
114297206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
1143b9c1b51eSKate Stone   if (error.Fail()) {
1144af245d11STodd Fiala     return error;
1145af245d11STodd Fiala   }
1146af245d11STodd Fiala 
1147af245d11STodd Fiala   lldb::addr_t prev_base_address = 0;
1148af245d11STodd Fiala 
1149b9c1b51eSKate Stone   // FIXME start by finding the last region that is <= target address using
1150b9c1b51eSKate Stone   // binary search.  Data is sorted.
1151af245d11STodd Fiala   // There can be a ton of regions on pthreads apps with lots of threads.
1152b9c1b51eSKate Stone   for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1153b9c1b51eSKate Stone        ++it) {
1154a6f5795aSTamas Berghammer     MemoryRegionInfo &proc_entry_info = it->first;
1155af245d11STodd Fiala 
1156af245d11STodd Fiala     // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1157b9c1b51eSKate Stone     assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
1158b9c1b51eSKate Stone            "descending /proc/pid/maps entries detected, unexpected");
1159af245d11STodd Fiala     prev_base_address = proc_entry_info.GetRange().GetRangeBase();
1160b1554311SHafiz Abid Qadeer     UNUSED_IF_ASSERT_DISABLED(prev_base_address);
1161af245d11STodd Fiala 
1162b9c1b51eSKate Stone     // If the target address comes before this entry, indicate distance to next
1163b9c1b51eSKate Stone     // region.
1164b9c1b51eSKate Stone     if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1165af245d11STodd Fiala       range_info.GetRange().SetRangeBase(load_addr);
1166b9c1b51eSKate Stone       range_info.GetRange().SetByteSize(
1167b9c1b51eSKate Stone           proc_entry_info.GetRange().GetRangeBase() - load_addr);
1168af245d11STodd Fiala       range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1169af245d11STodd Fiala       range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1170af245d11STodd Fiala       range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1171ad007563SHoward Hellyer       range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1172af245d11STodd Fiala 
1173af245d11STodd Fiala       return error;
1174b9c1b51eSKate Stone     } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1175af245d11STodd Fiala       // The target address is within the memory region we're processing here.
1176af245d11STodd Fiala       range_info = proc_entry_info;
1177af245d11STodd Fiala       return error;
1178af245d11STodd Fiala     }
1179af245d11STodd Fiala 
1180b9c1b51eSKate Stone     // The target memory address comes somewhere after the region we just
1181b9c1b51eSKate Stone     // parsed.
1182af245d11STodd Fiala   }
1183af245d11STodd Fiala 
1184b9c1b51eSKate Stone   // If we made it here, we didn't find an entry that contained the given
118505097246SAdrian Prantl   // address. Return the load_addr as start and the amount of bytes betwwen
118605097246SAdrian Prantl   // load address and the end of the memory as size.
118709839c33STamas Berghammer   range_info.GetRange().SetRangeBase(load_addr);
1188ad007563SHoward Hellyer   range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
118909839c33STamas Berghammer   range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
119009839c33STamas Berghammer   range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
119109839c33STamas Berghammer   range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1192ad007563SHoward Hellyer   range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1193af245d11STodd Fiala   return error;
1194af245d11STodd Fiala }
1195af245d11STodd Fiala 
119697206d57SZachary Turner Status NativeProcessLinux::PopulateMemoryRegionCache() {
1197a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1198a6f5795aSTamas Berghammer 
1199a6f5795aSTamas Berghammer   // If our cache is empty, pull the latest.  There should always be at least
1200a6f5795aSTamas Berghammer   // one memory region if memory region handling is supported.
1201a6f5795aSTamas Berghammer   if (!m_mem_region_cache.empty()) {
1202a6321a8eSPavel Labath     LLDB_LOG(log, "reusing {0} cached memory region entries",
1203a6321a8eSPavel Labath              m_mem_region_cache.size());
120497206d57SZachary Turner     return Status();
1205a6f5795aSTamas Berghammer   }
1206a6f5795aSTamas Berghammer 
120732541685SDavid Spickett   Status Result;
120832541685SDavid Spickett   LinuxMapCallback callback = [&](llvm::Expected<MemoryRegionInfo> Info) {
120932541685SDavid Spickett     if (Info) {
121032541685SDavid Spickett       FileSpec file_spec(Info->GetName().GetCString());
121132541685SDavid Spickett       FileSystem::Instance().Resolve(file_spec);
121232541685SDavid Spickett       m_mem_region_cache.emplace_back(*Info, file_spec);
121332541685SDavid Spickett       return true;
121432541685SDavid Spickett     }
121532541685SDavid Spickett 
121632541685SDavid Spickett     Result = Info.takeError();
121732541685SDavid Spickett     m_supports_mem_region = LazyBool::eLazyBoolNo;
121832541685SDavid Spickett     LLDB_LOG(log, "failed to parse proc maps: {0}", Result);
121932541685SDavid Spickett     return false;
122032541685SDavid Spickett   };
122132541685SDavid Spickett 
122232541685SDavid Spickett   // Linux kernel since 2.6.14 has /proc/{pid}/smaps
122332541685SDavid Spickett   // if CONFIG_PROC_PAGE_MONITOR is enabled
122432541685SDavid Spickett   auto BufferOrError = getProcFile(GetID(), "smaps");
122532541685SDavid Spickett   if (BufferOrError)
122632541685SDavid Spickett     ParseLinuxSMapRegions(BufferOrError.get()->getBuffer(), callback);
122732541685SDavid Spickett   else {
122832541685SDavid Spickett     BufferOrError = getProcFile(GetID(), "maps");
122915930862SPavel Labath     if (!BufferOrError) {
123015930862SPavel Labath       m_supports_mem_region = LazyBool::eLazyBoolNo;
123115930862SPavel Labath       return BufferOrError.getError();
123215930862SPavel Labath     }
123332541685SDavid Spickett 
123432541685SDavid Spickett     ParseLinuxMapRegions(BufferOrError.get()->getBuffer(), callback);
1235a6f5795aSTamas Berghammer   }
123632541685SDavid Spickett 
1237c8e364e8SPavel Labath   if (Result.Fail())
1238c8e364e8SPavel Labath     return Result;
1239a6f5795aSTamas Berghammer 
124015930862SPavel Labath   if (m_mem_region_cache.empty()) {
1241a6f5795aSTamas Berghammer     // No entries after attempting to read them.  This shouldn't happen if
124205097246SAdrian Prantl     // /proc/{pid}/maps is supported. Assume we don't support map entries via
124305097246SAdrian Prantl     // procfs.
124415930862SPavel Labath     m_supports_mem_region = LazyBool::eLazyBoolNo;
1245a6321a8eSPavel Labath     LLDB_LOG(log,
1246a6321a8eSPavel Labath              "failed to find any procfs maps entries, assuming no support "
1247a6321a8eSPavel Labath              "for memory region metadata retrieval");
124897206d57SZachary Turner     return Status("not supported");
1249a6f5795aSTamas Berghammer   }
1250a6f5795aSTamas Berghammer 
1251a6321a8eSPavel Labath   LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps",
1252a6321a8eSPavel Labath            m_mem_region_cache.size(), GetID());
1253a6f5795aSTamas Berghammer 
1254a6f5795aSTamas Berghammer   // We support memory retrieval, remember that.
1255a6f5795aSTamas Berghammer   m_supports_mem_region = LazyBool::eLazyBoolYes;
125697206d57SZachary Turner   return Status();
1257a6f5795aSTamas Berghammer }
1258a6f5795aSTamas Berghammer 
1259b9c1b51eSKate Stone void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
1260a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1261a6321a8eSPavel Labath   LLDB_LOG(log, "newBumpId={0}", newBumpId);
1262a6321a8eSPavel Labath   LLDB_LOG(log, "clearing {0} entries from memory region cache",
1263a6321a8eSPavel Labath            m_mem_region_cache.size());
1264af245d11STodd Fiala   m_mem_region_cache.clear();
1265af245d11STodd Fiala }
1266af245d11STodd Fiala 
12672c4226f8SPavel Labath llvm::Expected<uint64_t>
12682c4226f8SPavel Labath NativeProcessLinux::Syscall(llvm::ArrayRef<uint64_t> args) {
12692c4226f8SPavel Labath   PopulateMemoryRegionCache();
12702c4226f8SPavel Labath   auto region_it = llvm::find_if(m_mem_region_cache, [](const auto &pair) {
12712c4226f8SPavel Labath     return pair.first.GetExecutable() == MemoryRegionInfo::eYes;
12722c4226f8SPavel Labath   });
12732c4226f8SPavel Labath   if (region_it == m_mem_region_cache.end())
12742c4226f8SPavel Labath     return llvm::createStringError(llvm::inconvertibleErrorCode(),
12752c4226f8SPavel Labath                                    "No executable memory region found!");
1276af245d11STodd Fiala 
12772c4226f8SPavel Labath   addr_t exe_addr = region_it->first.GetRange().GetRangeBase();
1278af245d11STodd Fiala 
12792c4226f8SPavel Labath   NativeThreadLinux &thread = *GetThreadByID(GetID());
12802c4226f8SPavel Labath   assert(thread.GetState() == eStateStopped);
12812c4226f8SPavel Labath   NativeRegisterContextLinux &reg_ctx = thread.GetRegisterContext();
12822c4226f8SPavel Labath 
12832c4226f8SPavel Labath   NativeRegisterContextLinux::SyscallData syscall_data =
12842c4226f8SPavel Labath       *reg_ctx.GetSyscallData();
12852c4226f8SPavel Labath 
12862c4226f8SPavel Labath   DataBufferSP registers_sp;
12872c4226f8SPavel Labath   if (llvm::Error Err = reg_ctx.ReadAllRegisterValues(registers_sp).ToError())
12882c4226f8SPavel Labath     return std::move(Err);
12892c4226f8SPavel Labath   auto restore_regs = llvm::make_scope_exit(
12902c4226f8SPavel Labath       [&] { reg_ctx.WriteAllRegisterValues(registers_sp); });
12912c4226f8SPavel Labath 
12922c4226f8SPavel Labath   llvm::SmallVector<uint8_t, 8> memory(syscall_data.Insn.size());
12932c4226f8SPavel Labath   size_t bytes_read;
12942c4226f8SPavel Labath   if (llvm::Error Err =
12952c4226f8SPavel Labath           ReadMemory(exe_addr, memory.data(), memory.size(), bytes_read)
12962c4226f8SPavel Labath               .ToError()) {
12972c4226f8SPavel Labath     return std::move(Err);
1298af245d11STodd Fiala   }
1299af245d11STodd Fiala 
13002c4226f8SPavel Labath   auto restore_mem = llvm::make_scope_exit(
13012c4226f8SPavel Labath       [&] { WriteMemory(exe_addr, memory.data(), memory.size(), bytes_read); });
13022c4226f8SPavel Labath 
13032c4226f8SPavel Labath   if (llvm::Error Err = reg_ctx.SetPC(exe_addr).ToError())
13042c4226f8SPavel Labath     return std::move(Err);
13052c4226f8SPavel Labath 
13062c4226f8SPavel Labath   for (const auto &zip : llvm::zip_first(args, syscall_data.Args)) {
13072c4226f8SPavel Labath     if (llvm::Error Err =
13082c4226f8SPavel Labath             reg_ctx
13092c4226f8SPavel Labath                 .WriteRegisterFromUnsigned(std::get<1>(zip), std::get<0>(zip))
13102c4226f8SPavel Labath                 .ToError()) {
13112c4226f8SPavel Labath       return std::move(Err);
13122c4226f8SPavel Labath     }
13132c4226f8SPavel Labath   }
13142c4226f8SPavel Labath   if (llvm::Error Err = WriteMemory(exe_addr, syscall_data.Insn.data(),
13152c4226f8SPavel Labath                                     syscall_data.Insn.size(), bytes_read)
13162c4226f8SPavel Labath                             .ToError())
13172c4226f8SPavel Labath     return std::move(Err);
13182c4226f8SPavel Labath 
13192c4226f8SPavel Labath   m_mem_region_cache.clear();
13202c4226f8SPavel Labath 
13212c4226f8SPavel Labath   // With software single stepping the syscall insn buffer must also include a
13222c4226f8SPavel Labath   // trap instruction to stop the process.
13232c4226f8SPavel Labath   int req = SupportHardwareSingleStepping() ? PTRACE_SINGLESTEP : PTRACE_CONT;
13242c4226f8SPavel Labath   if (llvm::Error Err =
13252c4226f8SPavel Labath           PtraceWrapper(req, thread.GetID(), nullptr, nullptr).ToError())
13262c4226f8SPavel Labath     return std::move(Err);
13272c4226f8SPavel Labath 
13282c4226f8SPavel Labath   int status;
13292c4226f8SPavel Labath   ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, thread.GetID(),
13302c4226f8SPavel Labath                                                  &status, __WALL);
13312c4226f8SPavel Labath   if (wait_pid == -1) {
13322c4226f8SPavel Labath     return llvm::errorCodeToError(
13332c4226f8SPavel Labath         std::error_code(errno, std::generic_category()));
13342c4226f8SPavel Labath   }
13352c4226f8SPavel Labath   assert((unsigned)wait_pid == thread.GetID());
13362c4226f8SPavel Labath 
13372c4226f8SPavel Labath   uint64_t result = reg_ctx.ReadRegisterAsUnsigned(syscall_data.Result, -ESRCH);
13382c4226f8SPavel Labath 
13392c4226f8SPavel Labath   // Values larger than this are actually negative errno numbers.
13402c4226f8SPavel Labath   uint64_t errno_threshold =
13412c4226f8SPavel Labath       (uint64_t(-1) >> (64 - 8 * m_arch.GetAddressByteSize())) - 0x1000;
13422c4226f8SPavel Labath   if (result > errno_threshold) {
13432c4226f8SPavel Labath     return llvm::errorCodeToError(
13442c4226f8SPavel Labath         std::error_code(-result & 0xfff, std::generic_category()));
13452c4226f8SPavel Labath   }
13462c4226f8SPavel Labath 
13472c4226f8SPavel Labath   return result;
13482c4226f8SPavel Labath }
13492c4226f8SPavel Labath 
13502c4226f8SPavel Labath llvm::Expected<addr_t>
13512c4226f8SPavel Labath NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions) {
13522c4226f8SPavel Labath 
13532c4226f8SPavel Labath   llvm::Optional<NativeRegisterContextLinux::MmapData> mmap_data =
13542c4226f8SPavel Labath       GetCurrentThread()->GetRegisterContext().GetMmapData();
13552c4226f8SPavel Labath   if (!mmap_data)
13562c4226f8SPavel Labath     return llvm::make_error<UnimplementedError>();
13572c4226f8SPavel Labath 
13582c4226f8SPavel Labath   unsigned prot = PROT_NONE;
13592c4226f8SPavel Labath   assert((permissions & (ePermissionsReadable | ePermissionsWritable |
13602c4226f8SPavel Labath                          ePermissionsExecutable)) == permissions &&
13612c4226f8SPavel Labath          "Unknown permission!");
13622c4226f8SPavel Labath   if (permissions & ePermissionsReadable)
13632c4226f8SPavel Labath     prot |= PROT_READ;
13642c4226f8SPavel Labath   if (permissions & ePermissionsWritable)
13652c4226f8SPavel Labath     prot |= PROT_WRITE;
13662c4226f8SPavel Labath   if (permissions & ePermissionsExecutable)
13672c4226f8SPavel Labath     prot |= PROT_EXEC;
13682c4226f8SPavel Labath 
13692c4226f8SPavel Labath   llvm::Expected<uint64_t> Result =
13702c4226f8SPavel Labath       Syscall({mmap_data->SysMmap, 0, size, prot, MAP_ANONYMOUS | MAP_PRIVATE,
13712c4226f8SPavel Labath                uint64_t(-1), 0});
13722c4226f8SPavel Labath   if (Result)
13732c4226f8SPavel Labath     m_allocated_memory.try_emplace(*Result, size);
13742c4226f8SPavel Labath   return Result;
13752c4226f8SPavel Labath }
13762c4226f8SPavel Labath 
13772c4226f8SPavel Labath llvm::Error NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {
13782c4226f8SPavel Labath   llvm::Optional<NativeRegisterContextLinux::MmapData> mmap_data =
13792c4226f8SPavel Labath       GetCurrentThread()->GetRegisterContext().GetMmapData();
13802c4226f8SPavel Labath   if (!mmap_data)
13812c4226f8SPavel Labath     return llvm::make_error<UnimplementedError>();
13822c4226f8SPavel Labath 
13832c4226f8SPavel Labath   auto it = m_allocated_memory.find(addr);
13842c4226f8SPavel Labath   if (it == m_allocated_memory.end())
13852c4226f8SPavel Labath     return llvm::createStringError(llvm::errc::invalid_argument,
13862c4226f8SPavel Labath                                    "Memory not allocated by the debugger.");
13872c4226f8SPavel Labath 
13882c4226f8SPavel Labath   llvm::Expected<uint64_t> Result =
13892c4226f8SPavel Labath       Syscall({mmap_data->SysMunmap, addr, it->second});
13902c4226f8SPavel Labath   if (!Result)
13912c4226f8SPavel Labath     return Result.takeError();
13922c4226f8SPavel Labath 
13932c4226f8SPavel Labath   m_allocated_memory.erase(it);
13942c4226f8SPavel Labath   return llvm::Error::success();
1395af245d11STodd Fiala }
1396af245d11STodd Fiala 
1397b9c1b51eSKate Stone size_t NativeProcessLinux::UpdateThreads() {
139805097246SAdrian Prantl   // The NativeProcessLinux monitoring threads are always up to date with
139905097246SAdrian Prantl   // respect to thread state and they keep the thread list populated properly.
140005097246SAdrian Prantl   // All this method needs to do is return the thread count.
1401af245d11STodd Fiala   return m_threads.size();
1402af245d11STodd Fiala }
1403af245d11STodd Fiala 
140497206d57SZachary Turner Status NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,
1405b9c1b51eSKate Stone                                          bool hardware) {
1406af245d11STodd Fiala   if (hardware)
1407d5ffbad2SOmair Javaid     return SetHardwareBreakpoint(addr, size);
1408af245d11STodd Fiala   else
1409af245d11STodd Fiala     return SetSoftwareBreakpoint(addr, size);
1410af245d11STodd Fiala }
1411af245d11STodd Fiala 
141297206d57SZachary Turner Status NativeProcessLinux::RemoveBreakpoint(lldb::addr_t addr, bool hardware) {
1413d5ffbad2SOmair Javaid   if (hardware)
1414d5ffbad2SOmair Javaid     return RemoveHardwareBreakpoint(addr);
1415d5ffbad2SOmair Javaid   else
1416d5ffbad2SOmair Javaid     return NativeProcessProtocol::RemoveBreakpoint(addr);
1417d5ffbad2SOmair Javaid }
1418d5ffbad2SOmair Javaid 
1419f8b825f6SPavel Labath llvm::Expected<llvm::ArrayRef<uint8_t>>
1420f8b825f6SPavel Labath NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(size_t size_hint) {
1421be379e15STamas Berghammer   // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1422be379e15STamas Berghammer   // linux kernel does otherwise.
1423f8b825f6SPavel Labath   static const uint8_t g_arm_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1424f8b825f6SPavel Labath   static const uint8_t g_thumb_opcode[] = {0x01, 0xde};
142512286a27SPavel Labath 
1426f8b825f6SPavel Labath   switch (GetArchitecture().GetMachine()) {
142712286a27SPavel Labath   case llvm::Triple::arm:
1428f8b825f6SPavel Labath     switch (size_hint) {
142963c8be95STamas Berghammer     case 2:
14304f545074SPavel Labath       return llvm::makeArrayRef(g_thumb_opcode);
143163c8be95STamas Berghammer     case 4:
14324f545074SPavel Labath       return llvm::makeArrayRef(g_arm_opcode);
143363c8be95STamas Berghammer     default:
1434f8b825f6SPavel Labath       return llvm::createStringError(llvm::inconvertibleErrorCode(),
1435f8b825f6SPavel Labath                                      "Unrecognised trap opcode size hint!");
143663c8be95STamas Berghammer     }
1437af245d11STodd Fiala   default:
1438f8b825f6SPavel Labath     return NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_hint);
1439af245d11STodd Fiala   }
1440af245d11STodd Fiala }
1441af245d11STodd Fiala 
144297206d57SZachary Turner Status NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
1443b9c1b51eSKate Stone                                       size_t &bytes_read) {
1444df7c6995SPavel Labath   if (ProcessVmReadvSupported()) {
1445b9c1b51eSKate Stone     // The process_vm_readv path is about 50 times faster than ptrace api. We
144605097246SAdrian Prantl     // want to use this syscall if it is supported.
1447df7c6995SPavel Labath 
1448df7c6995SPavel Labath     const ::pid_t pid = GetID();
1449df7c6995SPavel Labath 
1450df7c6995SPavel Labath     struct iovec local_iov, remote_iov;
1451df7c6995SPavel Labath     local_iov.iov_base = buf;
1452df7c6995SPavel Labath     local_iov.iov_len = size;
1453df7c6995SPavel Labath     remote_iov.iov_base = reinterpret_cast<void *>(addr);
1454df7c6995SPavel Labath     remote_iov.iov_len = size;
1455df7c6995SPavel Labath 
1456df7c6995SPavel Labath     bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
1457df7c6995SPavel Labath     const bool success = bytes_read == size;
1458df7c6995SPavel Labath 
1459a6321a8eSPavel Labath     Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1460a6321a8eSPavel Labath     LLDB_LOG(log,
1461a6321a8eSPavel Labath              "using process_vm_readv to read {0} bytes from inferior "
1462a6321a8eSPavel Labath              "address {1:x}: {2}",
146310c41f37SPavel Labath              size, addr, success ? "Success" : llvm::sys::StrError(errno));
1464df7c6995SPavel Labath 
1465df7c6995SPavel Labath     if (success)
146697206d57SZachary Turner       return Status();
1467a6321a8eSPavel Labath     // else the call failed for some reason, let's retry the read using ptrace
1468b9c1b51eSKate Stone     // api.
1469df7c6995SPavel Labath   }
1470df7c6995SPavel Labath 
147119cbe96aSPavel Labath   unsigned char *dst = static_cast<unsigned char *>(buf);
147219cbe96aSPavel Labath   size_t remainder;
147319cbe96aSPavel Labath   long data;
147419cbe96aSPavel Labath 
1475a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1476a6321a8eSPavel Labath   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
147719cbe96aSPavel Labath 
1478b9c1b51eSKate Stone   for (bytes_read = 0; bytes_read < size; bytes_read += remainder) {
147997206d57SZachary Turner     Status error = NativeProcessLinux::PtraceWrapper(
1480b9c1b51eSKate Stone         PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data);
1481a6321a8eSPavel Labath     if (error.Fail())
148219cbe96aSPavel Labath       return error;
148319cbe96aSPavel Labath 
148419cbe96aSPavel Labath     remainder = size - bytes_read;
148519cbe96aSPavel Labath     remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
148619cbe96aSPavel Labath 
148719cbe96aSPavel Labath     // Copy the data into our buffer
1488f6ef187bSMohit K. Bhakkad     memcpy(dst, &data, remainder);
148919cbe96aSPavel Labath 
1490a6321a8eSPavel Labath     LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
149119cbe96aSPavel Labath     addr += k_ptrace_word_size;
149219cbe96aSPavel Labath     dst += k_ptrace_word_size;
149319cbe96aSPavel Labath   }
149497206d57SZachary Turner   return Status();
1495af245d11STodd Fiala }
1496af245d11STodd Fiala 
149797206d57SZachary Turner Status NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,
1498b9c1b51eSKate Stone                                        size_t size, size_t &bytes_written) {
149919cbe96aSPavel Labath   const unsigned char *src = static_cast<const unsigned char *>(buf);
150019cbe96aSPavel Labath   size_t remainder;
150197206d57SZachary Turner   Status error;
150219cbe96aSPavel Labath 
1503a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1504a6321a8eSPavel Labath   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
150519cbe96aSPavel Labath 
1506b9c1b51eSKate Stone   for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
150719cbe96aSPavel Labath     remainder = size - bytes_written;
150819cbe96aSPavel Labath     remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
150919cbe96aSPavel Labath 
1510b9c1b51eSKate Stone     if (remainder == k_ptrace_word_size) {
151119cbe96aSPavel Labath       unsigned long data = 0;
1512f6ef187bSMohit K. Bhakkad       memcpy(&data, src, k_ptrace_word_size);
151319cbe96aSPavel Labath 
1514a6321a8eSPavel Labath       LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
1515b9c1b51eSKate Stone       error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(),
1516b9c1b51eSKate Stone                                                 (void *)addr, (void *)data);
1517a6321a8eSPavel Labath       if (error.Fail())
151819cbe96aSPavel Labath         return error;
1519b9c1b51eSKate Stone     } else {
152019cbe96aSPavel Labath       unsigned char buff[8];
152119cbe96aSPavel Labath       size_t bytes_read;
152219cbe96aSPavel Labath       error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
1523a6321a8eSPavel Labath       if (error.Fail())
152419cbe96aSPavel Labath         return error;
152519cbe96aSPavel Labath 
152619cbe96aSPavel Labath       memcpy(buff, src, remainder);
152719cbe96aSPavel Labath 
152819cbe96aSPavel Labath       size_t bytes_written_rec;
152919cbe96aSPavel Labath       error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
1530a6321a8eSPavel Labath       if (error.Fail())
153119cbe96aSPavel Labath         return error;
153219cbe96aSPavel Labath 
1533a6321a8eSPavel Labath       LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src,
1534b9c1b51eSKate Stone                *(unsigned long *)buff);
153519cbe96aSPavel Labath     }
153619cbe96aSPavel Labath 
153719cbe96aSPavel Labath     addr += k_ptrace_word_size;
153819cbe96aSPavel Labath     src += k_ptrace_word_size;
153919cbe96aSPavel Labath   }
154019cbe96aSPavel Labath   return error;
1541af245d11STodd Fiala }
1542af245d11STodd Fiala 
154397206d57SZachary Turner Status NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) {
154419cbe96aSPavel Labath   return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
1545af245d11STodd Fiala }
1546af245d11STodd Fiala 
154797206d57SZachary Turner Status NativeProcessLinux::GetEventMessage(lldb::tid_t tid,
1548b9c1b51eSKate Stone                                            unsigned long *message) {
154919cbe96aSPavel Labath   return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
1550af245d11STodd Fiala }
1551af245d11STodd Fiala 
155297206d57SZachary Turner Status NativeProcessLinux::Detach(lldb::tid_t tid) {
155397ccc294SChaoren Lin   if (tid == LLDB_INVALID_THREAD_ID)
155497206d57SZachary Turner     return Status();
155597ccc294SChaoren Lin 
155619cbe96aSPavel Labath   return PtraceWrapper(PTRACE_DETACH, tid);
1557af245d11STodd Fiala }
1558af245d11STodd Fiala 
1559b9c1b51eSKate Stone bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {
1560a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
1561a5be48b3SPavel Labath     assert(thread && "thread list should not contain NULL threads");
1562a5be48b3SPavel Labath     if (thread->GetID() == thread_id) {
1563af245d11STodd Fiala       // We have this thread.
1564af245d11STodd Fiala       return true;
1565af245d11STodd Fiala     }
1566af245d11STodd Fiala   }
1567af245d11STodd Fiala 
1568af245d11STodd Fiala   // We don't have this thread.
1569af245d11STodd Fiala   return false;
1570af245d11STodd Fiala }
1571af245d11STodd Fiala 
1572b9c1b51eSKate Stone bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) {
1573a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1574a6321a8eSPavel Labath   LLDB_LOG(log, "tid: {0})", thread_id);
15751dbc6c9cSPavel Labath 
15761dbc6c9cSPavel Labath   bool found = false;
1577b9c1b51eSKate Stone   for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
1578b9c1b51eSKate Stone     if (*it && ((*it)->GetID() == thread_id)) {
1579af245d11STodd Fiala       m_threads.erase(it);
15801dbc6c9cSPavel Labath       found = true;
15811dbc6c9cSPavel Labath       break;
1582af245d11STodd Fiala     }
1583af245d11STodd Fiala   }
1584af245d11STodd Fiala 
158599e37695SRavitheja Addepally   if (found)
15860b697561SWalter Erquinigo     NotifyTracersOfThreadDestroyed(thread_id);
15870b697561SWalter Erquinigo 
15889eb1ecb9SPavel Labath   SignalIfAllThreadsStopped();
15891dbc6c9cSPavel Labath   return found;
1590af245d11STodd Fiala }
1591af245d11STodd Fiala 
15920b697561SWalter Erquinigo Status NativeProcessLinux::NotifyTracersOfNewThread(lldb::tid_t tid) {
15930b697561SWalter Erquinigo   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
15940b697561SWalter Erquinigo   Status error(m_intel_pt_manager.OnThreadCreated(tid));
15950b697561SWalter Erquinigo   if (error.Fail())
15960b697561SWalter Erquinigo     LLDB_LOG(log, "Failed to trace a new thread with intel-pt, tid = {0}. {1}",
15970b697561SWalter Erquinigo              tid, error.AsCString());
15980b697561SWalter Erquinigo   return error;
15990b697561SWalter Erquinigo }
16000b697561SWalter Erquinigo 
16010b697561SWalter Erquinigo Status NativeProcessLinux::NotifyTracersOfThreadDestroyed(lldb::tid_t tid) {
16020b697561SWalter Erquinigo   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
16030b697561SWalter Erquinigo   Status error(m_intel_pt_manager.OnThreadDestroyed(tid));
16040b697561SWalter Erquinigo   if (error.Fail())
16050b697561SWalter Erquinigo     LLDB_LOG(log,
16060b697561SWalter Erquinigo              "Failed to stop a destroyed thread with intel-pt, tid = {0}. {1}",
16070b697561SWalter Erquinigo              tid, error.AsCString());
16080b697561SWalter Erquinigo   return error;
16090b697561SWalter Erquinigo }
16100b697561SWalter Erquinigo 
16110b697561SWalter Erquinigo NativeThreadLinux &NativeProcessLinux::AddThread(lldb::tid_t thread_id,
16120b697561SWalter Erquinigo                                                  bool resume) {
1613a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
1614a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
1615af245d11STodd Fiala 
1616b9c1b51eSKate Stone   assert(!HasThreadNoLock(thread_id) &&
1617b9c1b51eSKate Stone          "attempted to add a thread by id that already exists");
1618af245d11STodd Fiala 
1619af245d11STodd Fiala   // If this is the first thread, save it as the current thread
1620af245d11STodd Fiala   if (m_threads.empty())
1621af245d11STodd Fiala     SetCurrentThreadID(thread_id);
1622af245d11STodd Fiala 
1623a8f3ae7cSJonas Devlieghere   m_threads.push_back(std::make_unique<NativeThreadLinux>(*this, thread_id));
16240b697561SWalter Erquinigo   NativeThreadLinux &thread =
16250b697561SWalter Erquinigo       static_cast<NativeThreadLinux &>(*m_threads.back());
162699e37695SRavitheja Addepally 
16270b697561SWalter Erquinigo   Status tracing_error = NotifyTracersOfNewThread(thread.GetID());
16280b697561SWalter Erquinigo   if (tracing_error.Fail()) {
16290b697561SWalter Erquinigo     thread.SetStoppedByProcessorTrace(tracing_error.AsCString());
16300b697561SWalter Erquinigo     StopRunningThreads(thread.GetID());
16310b697561SWalter Erquinigo   } else if (resume)
16320b697561SWalter Erquinigo     ResumeThread(thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
16330b697561SWalter Erquinigo   else
16340b697561SWalter Erquinigo     thread.SetStoppedBySignal(SIGSTOP);
163599e37695SRavitheja Addepally 
16360b697561SWalter Erquinigo   return thread;
1637af245d11STodd Fiala }
1638af245d11STodd Fiala 
163997206d57SZachary Turner Status NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,
1640b9c1b51eSKate Stone                                                    FileSpec &file_spec) {
164197206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
1642a6f5795aSTamas Berghammer   if (error.Fail())
1643a6f5795aSTamas Berghammer     return error;
1644a6f5795aSTamas Berghammer 
16458f3be7a3SJonas Devlieghere   FileSpec module_file_spec(module_path);
16468f3be7a3SJonas Devlieghere   FileSystem::Instance().Resolve(module_file_spec);
16477cb18bf5STamas Berghammer 
16487cb18bf5STamas Berghammer   file_spec.Clear();
1649a6f5795aSTamas Berghammer   for (const auto &it : m_mem_region_cache) {
1650a6f5795aSTamas Berghammer     if (it.second.GetFilename() == module_file_spec.GetFilename()) {
1651a6f5795aSTamas Berghammer       file_spec = it.second;
165297206d57SZachary Turner       return Status();
1653a6f5795aSTamas Berghammer     }
1654a6f5795aSTamas Berghammer   }
165597206d57SZachary Turner   return Status("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
16567cb18bf5STamas Berghammer                 module_file_spec.GetFilename().AsCString(), GetID());
16577cb18bf5STamas Berghammer }
1658c076559aSPavel Labath 
165997206d57SZachary Turner Status NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
1660b9c1b51eSKate Stone                                               lldb::addr_t &load_addr) {
1661783bfc8cSTamas Berghammer   load_addr = LLDB_INVALID_ADDRESS;
166297206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
1663a6f5795aSTamas Berghammer   if (error.Fail())
1664783bfc8cSTamas Berghammer     return error;
1665a6f5795aSTamas Berghammer 
16668f3be7a3SJonas Devlieghere   FileSpec file(file_name);
1667a6f5795aSTamas Berghammer   for (const auto &it : m_mem_region_cache) {
1668a6f5795aSTamas Berghammer     if (it.second == file) {
1669a6f5795aSTamas Berghammer       load_addr = it.first.GetRange().GetRangeBase();
167097206d57SZachary Turner       return Status();
1671a6f5795aSTamas Berghammer     }
1672a6f5795aSTamas Berghammer   }
167397206d57SZachary Turner   return Status("No load address found for specified file.");
1674783bfc8cSTamas Berghammer }
1675783bfc8cSTamas Berghammer 
1676a5be48b3SPavel Labath NativeThreadLinux *NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {
1677a5be48b3SPavel Labath   return static_cast<NativeThreadLinux *>(
1678b9c1b51eSKate Stone       NativeProcessProtocol::GetThreadByID(tid));
1679f9077782SPavel Labath }
1680f9077782SPavel Labath 
16812c4226f8SPavel Labath NativeThreadLinux *NativeProcessLinux::GetCurrentThread() {
16822c4226f8SPavel Labath   return static_cast<NativeThreadLinux *>(
16832c4226f8SPavel Labath       NativeProcessProtocol::GetCurrentThread());
16842c4226f8SPavel Labath }
16852c4226f8SPavel Labath 
168697206d57SZachary Turner Status NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,
1687b9c1b51eSKate Stone                                         lldb::StateType state, int signo) {
1688a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1689a6321a8eSPavel Labath   LLDB_LOG(log, "tid: {0}", thread.GetID());
1690c076559aSPavel Labath 
169105097246SAdrian Prantl   // Before we do the resume below, first check if we have a pending stop
169205097246SAdrian Prantl   // notification that is currently waiting for all threads to stop.  This is
169305097246SAdrian Prantl   // potentially a buggy situation since we're ostensibly waiting for threads
169405097246SAdrian Prantl   // to stop before we send out the pending notification, and here we are
169505097246SAdrian Prantl   // resuming one before we send out the pending stop notification.
1696a6321a8eSPavel Labath   if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
1697a6321a8eSPavel Labath     LLDB_LOG(log,
1698a6321a8eSPavel Labath              "about to resume tid {0} per explicit request but we have a "
1699a6321a8eSPavel Labath              "pending stop notification (tid {1}) that is actively "
1700a6321a8eSPavel Labath              "waiting for this thread to stop. Valid sequence of events?",
1701a6321a8eSPavel Labath              thread.GetID(), m_pending_notification_tid);
1702c076559aSPavel Labath   }
1703c076559aSPavel Labath 
170405097246SAdrian Prantl   // Request a resume.  We expect this to be synchronous and the system to
170505097246SAdrian Prantl   // reflect it is running after this completes.
1706b9c1b51eSKate Stone   switch (state) {
1707b9c1b51eSKate Stone   case eStateRunning: {
1708605b51b8SPavel Labath     const auto resume_result = thread.Resume(signo);
17090e1d729bSPavel Labath     if (resume_result.Success())
17100e1d729bSPavel Labath       SetState(eStateRunning, true);
17110e1d729bSPavel Labath     return resume_result;
1712c076559aSPavel Labath   }
1713b9c1b51eSKate Stone   case eStateStepping: {
1714605b51b8SPavel Labath     const auto step_result = thread.SingleStep(signo);
17150e1d729bSPavel Labath     if (step_result.Success())
17160e1d729bSPavel Labath       SetState(eStateRunning, true);
17170e1d729bSPavel Labath     return step_result;
17180e1d729bSPavel Labath   }
17190e1d729bSPavel Labath   default:
17208198db30SPavel Labath     LLDB_LOG(log, "Unhandled state {0}.", state);
17210e1d729bSPavel Labath     llvm_unreachable("Unhandled state for resume");
17220e1d729bSPavel Labath   }
1723c076559aSPavel Labath }
1724c076559aSPavel Labath 
1725c076559aSPavel Labath //===----------------------------------------------------------------------===//
1726c076559aSPavel Labath 
1727b9c1b51eSKate Stone void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {
1728a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1729a6321a8eSPavel Labath   LLDB_LOG(log, "about to process event: (triggering_tid: {0})",
1730a6321a8eSPavel Labath            triggering_tid);
1731c076559aSPavel Labath 
17320e1d729bSPavel Labath   m_pending_notification_tid = triggering_tid;
17330e1d729bSPavel Labath 
173405097246SAdrian Prantl   // Request a stop for all the thread stops that need to be stopped and are
173505097246SAdrian Prantl   // not already known to be stopped.
1736a5be48b3SPavel Labath   for (const auto &thread : m_threads) {
1737a5be48b3SPavel Labath     if (StateIsRunningState(thread->GetState()))
1738a5be48b3SPavel Labath       static_cast<NativeThreadLinux *>(thread.get())->RequestStop();
17390e1d729bSPavel Labath   }
17400e1d729bSPavel Labath 
17410e1d729bSPavel Labath   SignalIfAllThreadsStopped();
1742a6321a8eSPavel Labath   LLDB_LOG(log, "event processing done");
1743c076559aSPavel Labath }
1744c076559aSPavel Labath 
1745b9c1b51eSKate Stone void NativeProcessLinux::SignalIfAllThreadsStopped() {
17460e1d729bSPavel Labath   if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
17470e1d729bSPavel Labath     return; // No pending notification. Nothing to do.
17480e1d729bSPavel Labath 
1749b9c1b51eSKate Stone   for (const auto &thread_sp : m_threads) {
17500e1d729bSPavel Labath     if (StateIsRunningState(thread_sp->GetState()))
17510e1d729bSPavel Labath       return; // Some threads are still running. Don't signal yet.
17520e1d729bSPavel Labath   }
17530e1d729bSPavel Labath 
17540e1d729bSPavel Labath   // We have a pending notification and all threads have stopped.
1755b9c1b51eSKate Stone   Log *log(
1756b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
17579eb1ecb9SPavel Labath 
1758b9c1b51eSKate Stone   // Clear any temporary breakpoints we used to implement software single
1759b9c1b51eSKate Stone   // stepping.
1760b9c1b51eSKate Stone   for (const auto &thread_info : m_threads_stepping_with_breakpoint) {
176197206d57SZachary Turner     Status error = RemoveBreakpoint(thread_info.second);
17629eb1ecb9SPavel Labath     if (error.Fail())
1763a6321a8eSPavel Labath       LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}",
1764a6321a8eSPavel Labath                thread_info.first, error);
17659eb1ecb9SPavel Labath   }
17669eb1ecb9SPavel Labath   m_threads_stepping_with_breakpoint.clear();
17679eb1ecb9SPavel Labath 
17689eb1ecb9SPavel Labath   // Notify the delegate about the stop
17690e1d729bSPavel Labath   SetCurrentThreadID(m_pending_notification_tid);
1770ed89c7feSPavel Labath   SetState(StateType::eStateStopped, true);
17710e1d729bSPavel Labath   m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
1772c076559aSPavel Labath }
1773c076559aSPavel Labath 
1774b9c1b51eSKate Stone void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {
1775a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1776a6321a8eSPavel Labath   LLDB_LOG(log, "tid: {0}", thread.GetID());
17771dbc6c9cSPavel Labath 
1778b9c1b51eSKate Stone   if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID &&
1779b9c1b51eSKate Stone       StateIsRunningState(thread.GetState())) {
1780b9c1b51eSKate Stone     // We will need to wait for this new thread to stop as well before firing
178105097246SAdrian Prantl     // the notification.
1782f9077782SPavel Labath     thread.RequestStop();
1783c076559aSPavel Labath   }
1784c076559aSPavel Labath }
1785068f8a7eSTamas Berghammer 
1786b9c1b51eSKate Stone void NativeProcessLinux::SigchldHandler() {
1787a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
178819cbe96aSPavel Labath   // Process all pending waitpid notifications.
1789b9c1b51eSKate Stone   while (true) {
179019cbe96aSPavel Labath     int status = -1;
1791c1a6b128SPavel Labath     ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, -1, &status,
1792c1a6b128SPavel Labath                                           __WALL | __WNOTHREAD | WNOHANG);
179319cbe96aSPavel Labath 
179419cbe96aSPavel Labath     if (wait_pid == 0)
179519cbe96aSPavel Labath       break; // We are done.
179619cbe96aSPavel Labath 
1797b9c1b51eSKate Stone     if (wait_pid == -1) {
179897206d57SZachary Turner       Status error(errno, eErrorTypePOSIX);
1799a6321a8eSPavel Labath       LLDB_LOG(log, "waitpid (-1, &status, _) failed: {0}", error);
180019cbe96aSPavel Labath       break;
180119cbe96aSPavel Labath     }
180219cbe96aSPavel Labath 
18033508fc8cSPavel Labath     WaitStatus wait_status = WaitStatus::Decode(status);
18043508fc8cSPavel Labath     bool exited = wait_status.type == WaitStatus::Exit ||
18053508fc8cSPavel Labath                   (wait_status.type == WaitStatus::Signal &&
18063508fc8cSPavel Labath                    wait_pid == static_cast<::pid_t>(GetID()));
180719cbe96aSPavel Labath 
18083508fc8cSPavel Labath     LLDB_LOG(
18093508fc8cSPavel Labath         log,
18103508fc8cSPavel Labath         "waitpid (-1, &status, _) => pid = {0}, status = {1}, exited = {2}",
18113508fc8cSPavel Labath         wait_pid, wait_status, exited);
181219cbe96aSPavel Labath 
18133508fc8cSPavel Labath     MonitorCallback(wait_pid, exited, wait_status);
181419cbe96aSPavel Labath   }
1815068f8a7eSTamas Berghammer }
1816068f8a7eSTamas Berghammer 
181705097246SAdrian Prantl // Wrapper for ptrace to catch errors and log calls. Note that ptrace sets
181805097246SAdrian Prantl // errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
181997206d57SZachary Turner Status NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
1820b9c1b51eSKate Stone                                          void *data, size_t data_size,
1821b9c1b51eSKate Stone                                          long *result) {
182297206d57SZachary Turner   Status error;
18234a9babb2SPavel Labath   long int ret;
1824068f8a7eSTamas Berghammer 
1825068f8a7eSTamas Berghammer   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
1826068f8a7eSTamas Berghammer 
1827068f8a7eSTamas Berghammer   PtraceDisplayBytes(req, data, data_size);
1828068f8a7eSTamas Berghammer 
1829068f8a7eSTamas Berghammer   errno = 0;
1830068f8a7eSTamas Berghammer   if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
1831b9c1b51eSKate Stone     ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
1832b9c1b51eSKate Stone                  *(unsigned int *)addr, data);
1833068f8a7eSTamas Berghammer   else
1834b9c1b51eSKate Stone     ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
1835b9c1b51eSKate Stone                  addr, data);
1836068f8a7eSTamas Berghammer 
18374a9babb2SPavel Labath   if (ret == -1)
1838068f8a7eSTamas Berghammer     error.SetErrorToErrno();
1839068f8a7eSTamas Berghammer 
18404a9babb2SPavel Labath   if (result)
18414a9babb2SPavel Labath     *result = ret;
18424a9babb2SPavel Labath 
184328096200SPavel Labath   LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data,
184428096200SPavel Labath            data_size, ret);
1845068f8a7eSTamas Berghammer 
1846068f8a7eSTamas Berghammer   PtraceDisplayBytes(req, data, data_size);
1847068f8a7eSTamas Berghammer 
1848a6321a8eSPavel Labath   if (error.Fail())
1849a6321a8eSPavel Labath     LLDB_LOG(log, "ptrace() failed: {0}", error);
1850068f8a7eSTamas Berghammer 
18514a9babb2SPavel Labath   return error;
1852068f8a7eSTamas Berghammer }
185399e37695SRavitheja Addepally 
18540b697561SWalter Erquinigo llvm::Expected<TraceSupportedResponse> NativeProcessLinux::TraceSupported() {
18550b697561SWalter Erquinigo   if (IntelPTManager::IsSupported())
18560b697561SWalter Erquinigo     return TraceSupportedResponse{"intel-pt", "Intel Processor Trace"};
18570b697561SWalter Erquinigo   return NativeProcessProtocol::TraceSupported();
185899e37695SRavitheja Addepally }
185999e37695SRavitheja Addepally 
18600b697561SWalter Erquinigo Error NativeProcessLinux::TraceStart(StringRef json_request, StringRef type) {
18610b697561SWalter Erquinigo   if (type == "intel-pt") {
18620b697561SWalter Erquinigo     if (Expected<TraceIntelPTStartRequest> request =
18630b697561SWalter Erquinigo             json::parse<TraceIntelPTStartRequest>(json_request,
18640b697561SWalter Erquinigo                                                   "TraceIntelPTStartRequest")) {
18650b697561SWalter Erquinigo       std::vector<lldb::tid_t> process_threads;
18660b697561SWalter Erquinigo       for (auto &thread : m_threads)
18670b697561SWalter Erquinigo         process_threads.push_back(thread->GetID());
18680b697561SWalter Erquinigo       return m_intel_pt_manager.TraceStart(*request, process_threads);
18690b697561SWalter Erquinigo     } else
18700b697561SWalter Erquinigo       return request.takeError();
187199e37695SRavitheja Addepally   }
187299e37695SRavitheja Addepally 
18730b697561SWalter Erquinigo   return NativeProcessProtocol::TraceStart(json_request, type);
187499e37695SRavitheja Addepally }
187599e37695SRavitheja Addepally 
18760b697561SWalter Erquinigo Error NativeProcessLinux::TraceStop(const TraceStopRequest &request) {
18770b697561SWalter Erquinigo   if (request.type == "intel-pt")
18780b697561SWalter Erquinigo     return m_intel_pt_manager.TraceStop(request);
18790b697561SWalter Erquinigo   return NativeProcessProtocol::TraceStop(request);
188099e37695SRavitheja Addepally }
188199e37695SRavitheja Addepally 
18820b697561SWalter Erquinigo Expected<json::Value> NativeProcessLinux::TraceGetState(StringRef type) {
18830b697561SWalter Erquinigo   if (type == "intel-pt")
18840b697561SWalter Erquinigo     return m_intel_pt_manager.GetState();
18850b697561SWalter Erquinigo   return NativeProcessProtocol::TraceGetState(type);
188699e37695SRavitheja Addepally }
188799e37695SRavitheja Addepally 
18880b697561SWalter Erquinigo Expected<std::vector<uint8_t>> NativeProcessLinux::TraceGetBinaryData(
18890b697561SWalter Erquinigo     const TraceGetBinaryDataRequest &request) {
18900b697561SWalter Erquinigo   if (request.type == "intel-pt")
18910b697561SWalter Erquinigo     return m_intel_pt_manager.GetBinaryData(request);
18920b697561SWalter Erquinigo   return NativeProcessProtocol::TraceGetBinaryData(request);
189399e37695SRavitheja Addepally }
1894