1af245d11STodd Fiala //===-- NativeProcessLinux.cpp -------------------------------- -*- C++ -*-===//
2af245d11STodd Fiala //
3af245d11STodd Fiala //                     The LLVM Compiler Infrastructure
4af245d11STodd Fiala //
5af245d11STodd Fiala // This file is distributed under the University of Illinois Open Source
6af245d11STodd Fiala // License. See LICENSE.TXT for details.
7af245d11STodd Fiala //
8af245d11STodd Fiala //===----------------------------------------------------------------------===//
9af245d11STodd Fiala 
10af245d11STodd Fiala #include "NativeProcessLinux.h"
11af245d11STodd Fiala 
12af245d11STodd Fiala // C Includes
13af245d11STodd Fiala #include <errno.h>
14af245d11STodd Fiala #include <stdint.h>
15b9c1b51eSKate Stone #include <string.h>
16af245d11STodd Fiala #include <unistd.h>
17af245d11STodd Fiala 
18af245d11STodd Fiala // C++ Includes
19af245d11STodd Fiala #include <fstream>
20df7c6995SPavel Labath #include <mutex>
21c076559aSPavel Labath #include <sstream>
22af245d11STodd Fiala #include <string>
235b981ab9SPavel Labath #include <unordered_map>
24af245d11STodd Fiala 
25af245d11STodd Fiala // Other libraries and framework includes
26d8c338d4STamas Berghammer #include "lldb/Core/EmulateInstruction.h"
276edef204SOleksiy Vyalov #include "lldb/Core/ModuleSpec.h"
28af245d11STodd Fiala #include "lldb/Core/RegisterValue.h"
29af245d11STodd Fiala #include "lldb/Core/State.h"
30af245d11STodd Fiala #include "lldb/Host/Host.h"
315ad891f7SPavel Labath #include "lldb/Host/HostProcess.h"
3224ae6294SZachary Turner #include "lldb/Host/PseudoTerminal.h"
3339de3110SZachary Turner #include "lldb/Host/ThreadLauncher.h"
342a86b555SPavel Labath #include "lldb/Host/common/NativeBreakpoint.h"
352a86b555SPavel Labath #include "lldb/Host/common/NativeRegisterContext.h"
364ee1c952SPavel Labath #include "lldb/Host/linux/Ptrace.h"
374ee1c952SPavel Labath #include "lldb/Host/linux/Uio.h"
38816ae4b0SKamil Rytarowski #include "lldb/Host/posix/ProcessLauncherPosixFork.h"
392a86b555SPavel Labath #include "lldb/Symbol/ObjectFile.h"
4090aff47cSZachary Turner #include "lldb/Target/Process.h"
41af245d11STodd Fiala #include "lldb/Target/ProcessLaunchInfo.h"
425b981ab9SPavel Labath #include "lldb/Target/Target.h"
43c16f5dcaSChaoren Lin #include "lldb/Utility/LLDBAssert.h"
4497206d57SZachary Turner #include "lldb/Utility/Status.h"
45f805e190SPavel Labath #include "lldb/Utility/StringExtractor.h"
4610c41f37SPavel Labath #include "llvm/Support/Errno.h"
4710c41f37SPavel Labath #include "llvm/Support/FileSystem.h"
4810c41f37SPavel Labath #include "llvm/Support/Threading.h"
49af245d11STodd Fiala 
50af245d11STodd Fiala #include "NativeThreadLinux.h"
51b9c1b51eSKate Stone #include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
521e209fccSTamas Berghammer #include "Procfs.h"
53cacde7dfSTodd Fiala 
54d858487eSTamas Berghammer #include <linux/unistd.h>
55d858487eSTamas Berghammer #include <sys/socket.h>
56df7c6995SPavel Labath #include <sys/syscall.h>
57d858487eSTamas Berghammer #include <sys/types.h>
58d858487eSTamas Berghammer #include <sys/user.h>
59d858487eSTamas Berghammer #include <sys/wait.h>
60d858487eSTamas Berghammer 
61af245d11STodd Fiala // Support hardware breakpoints in case it has not been defined
62af245d11STodd Fiala #ifndef TRAP_HWBKPT
63af245d11STodd Fiala #define TRAP_HWBKPT 4
64af245d11STodd Fiala #endif
65af245d11STodd Fiala 
667cb18bf5STamas Berghammer using namespace lldb;
677cb18bf5STamas Berghammer using namespace lldb_private;
68db264a6dSTamas Berghammer using namespace lldb_private::process_linux;
697cb18bf5STamas Berghammer using namespace llvm;
707cb18bf5STamas Berghammer 
71af245d11STodd Fiala // Private bits we only need internally.
72df7c6995SPavel Labath 
73b9c1b51eSKate Stone static bool ProcessVmReadvSupported() {
74df7c6995SPavel Labath   static bool is_supported;
75c5f28e2aSKamil Rytarowski   static llvm::once_flag flag;
76df7c6995SPavel Labath 
77c5f28e2aSKamil Rytarowski   llvm::call_once(flag, [] {
78a6321a8eSPavel Labath     Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
79df7c6995SPavel Labath 
80df7c6995SPavel Labath     uint32_t source = 0x47424742;
81df7c6995SPavel Labath     uint32_t dest = 0;
82df7c6995SPavel Labath 
83df7c6995SPavel Labath     struct iovec local, remote;
84df7c6995SPavel Labath     remote.iov_base = &source;
85df7c6995SPavel Labath     local.iov_base = &dest;
86df7c6995SPavel Labath     remote.iov_len = local.iov_len = sizeof source;
87df7c6995SPavel Labath 
88b9c1b51eSKate Stone     // We shall try if cross-process-memory reads work by attempting to read a
89b9c1b51eSKate Stone     // value from our own process.
90df7c6995SPavel Labath     ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
91df7c6995SPavel Labath     is_supported = (res == sizeof(source) && source == dest);
92df7c6995SPavel Labath     if (is_supported)
93a6321a8eSPavel Labath       LLDB_LOG(log,
94a6321a8eSPavel Labath                "Detected kernel support for process_vm_readv syscall. "
95a6321a8eSPavel Labath                "Fast memory reads enabled.");
96df7c6995SPavel Labath     else
97a6321a8eSPavel Labath       LLDB_LOG(log,
98a6321a8eSPavel Labath                "syscall process_vm_readv failed (error: {0}). Fast memory "
99a6321a8eSPavel Labath                "reads disabled.",
10010c41f37SPavel Labath                llvm::sys::StrError());
101df7c6995SPavel Labath   });
102df7c6995SPavel Labath 
103df7c6995SPavel Labath   return is_supported;
104df7c6995SPavel Labath }
105df7c6995SPavel Labath 
106b9c1b51eSKate Stone namespace {
107b9c1b51eSKate Stone void MaybeLogLaunchInfo(const ProcessLaunchInfo &info) {
108a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1094abe5d69SPavel Labath   if (!log)
1104abe5d69SPavel Labath     return;
1114abe5d69SPavel Labath 
1124abe5d69SPavel Labath   if (const FileAction *action = info.GetFileActionForFD(STDIN_FILENO))
113a6321a8eSPavel Labath     LLDB_LOG(log, "setting STDIN to '{0}'", action->GetFileSpec());
1144abe5d69SPavel Labath   else
115a6321a8eSPavel Labath     LLDB_LOG(log, "leaving STDIN as is");
1164abe5d69SPavel Labath 
1174abe5d69SPavel Labath   if (const FileAction *action = info.GetFileActionForFD(STDOUT_FILENO))
118a6321a8eSPavel Labath     LLDB_LOG(log, "setting STDOUT to '{0}'", action->GetFileSpec());
1194abe5d69SPavel Labath   else
120a6321a8eSPavel Labath     LLDB_LOG(log, "leaving STDOUT as is");
1214abe5d69SPavel Labath 
1224abe5d69SPavel Labath   if (const FileAction *action = info.GetFileActionForFD(STDERR_FILENO))
123a6321a8eSPavel Labath     LLDB_LOG(log, "setting STDERR to '{0}'", action->GetFileSpec());
1244abe5d69SPavel Labath   else
125a6321a8eSPavel Labath     LLDB_LOG(log, "leaving STDERR as is");
1264abe5d69SPavel Labath 
1274abe5d69SPavel Labath   int i = 0;
128b9c1b51eSKate Stone   for (const char **args = info.GetArguments().GetConstArgumentVector(); *args;
129b9c1b51eSKate Stone        ++args, ++i)
130a6321a8eSPavel Labath     LLDB_LOG(log, "arg {0}: '{1}'", i, *args);
1314abe5d69SPavel Labath }
1324abe5d69SPavel Labath 
133b9c1b51eSKate Stone void DisplayBytes(StreamString &s, void *bytes, uint32_t count) {
134af245d11STodd Fiala   uint8_t *ptr = (uint8_t *)bytes;
135af245d11STodd Fiala   const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
136b9c1b51eSKate Stone   for (uint32_t i = 0; i < loop_count; i++) {
137af245d11STodd Fiala     s.Printf("[%x]", *ptr);
138af245d11STodd Fiala     ptr++;
139af245d11STodd Fiala   }
140af245d11STodd Fiala }
141af245d11STodd Fiala 
142b9c1b51eSKate Stone void PtraceDisplayBytes(int &req, void *data, size_t data_size) {
143aafe053cSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
144a6321a8eSPavel Labath   if (!log)
145a6321a8eSPavel Labath     return;
146af245d11STodd Fiala   StreamString buf;
147af245d11STodd Fiala 
148b9c1b51eSKate Stone   switch (req) {
149b9c1b51eSKate Stone   case PTRACE_POKETEXT: {
150af245d11STodd Fiala     DisplayBytes(buf, &data, 8);
151aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_POKETEXT {0}", buf.GetData());
152af245d11STodd Fiala     break;
153af245d11STodd Fiala   }
154b9c1b51eSKate Stone   case PTRACE_POKEDATA: {
155af245d11STodd Fiala     DisplayBytes(buf, &data, 8);
156aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_POKEDATA {0}", buf.GetData());
157af245d11STodd Fiala     break;
158af245d11STodd Fiala   }
159b9c1b51eSKate Stone   case PTRACE_POKEUSER: {
160af245d11STodd Fiala     DisplayBytes(buf, &data, 8);
161aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_POKEUSER {0}", buf.GetData());
162af245d11STodd Fiala     break;
163af245d11STodd Fiala   }
164b9c1b51eSKate Stone   case PTRACE_SETREGS: {
165af245d11STodd Fiala     DisplayBytes(buf, data, data_size);
166aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_SETREGS {0}", buf.GetData());
167af245d11STodd Fiala     break;
168af245d11STodd Fiala   }
169b9c1b51eSKate Stone   case PTRACE_SETFPREGS: {
170af245d11STodd Fiala     DisplayBytes(buf, data, data_size);
171aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_SETFPREGS {0}", buf.GetData());
172af245d11STodd Fiala     break;
173af245d11STodd Fiala   }
174b9c1b51eSKate Stone   case PTRACE_SETSIGINFO: {
175af245d11STodd Fiala     DisplayBytes(buf, data, sizeof(siginfo_t));
176aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_SETSIGINFO {0}", buf.GetData());
177af245d11STodd Fiala     break;
178af245d11STodd Fiala   }
179b9c1b51eSKate Stone   case PTRACE_SETREGSET: {
180af245d11STodd Fiala     // Extract iov_base from data, which is a pointer to the struct IOVEC
181af245d11STodd Fiala     DisplayBytes(buf, *(void **)data, data_size);
182aafe053cSPavel Labath     LLDB_LOGV(log, "PTRACE_SETREGSET {0}", buf.GetData());
183af245d11STodd Fiala     break;
184af245d11STodd Fiala   }
185b9c1b51eSKate Stone   default: {}
186af245d11STodd Fiala   }
187af245d11STodd Fiala }
188af245d11STodd Fiala 
18919cbe96aSPavel Labath static constexpr unsigned k_ptrace_word_size = sizeof(void *);
190b9c1b51eSKate Stone static_assert(sizeof(long) >= k_ptrace_word_size,
191b9c1b51eSKate Stone               "Size of long must be larger than ptrace word size");
1921107b5a5SPavel Labath } // end of anonymous namespace
1931107b5a5SPavel Labath 
194bd7cbc5aSPavel Labath // Simple helper function to ensure flags are enabled on the given file
195bd7cbc5aSPavel Labath // descriptor.
19697206d57SZachary Turner static Status EnsureFDFlags(int fd, int flags) {
19797206d57SZachary Turner   Status error;
198bd7cbc5aSPavel Labath 
199bd7cbc5aSPavel Labath   int status = fcntl(fd, F_GETFL);
200b9c1b51eSKate Stone   if (status == -1) {
201bd7cbc5aSPavel Labath     error.SetErrorToErrno();
202bd7cbc5aSPavel Labath     return error;
203bd7cbc5aSPavel Labath   }
204bd7cbc5aSPavel Labath 
205b9c1b51eSKate Stone   if (fcntl(fd, F_SETFL, status | flags) == -1) {
206bd7cbc5aSPavel Labath     error.SetErrorToErrno();
207bd7cbc5aSPavel Labath     return error;
208bd7cbc5aSPavel Labath   }
209bd7cbc5aSPavel Labath 
210bd7cbc5aSPavel Labath   return error;
211bd7cbc5aSPavel Labath }
212bd7cbc5aSPavel Labath 
213af245d11STodd Fiala // -----------------------------------------------------------------------------
214af245d11STodd Fiala // Public Static Methods
215af245d11STodd Fiala // -----------------------------------------------------------------------------
216af245d11STodd Fiala 
21797206d57SZachary Turner Status NativeProcessProtocol::Launch(
218db264a6dSTamas Berghammer     ProcessLaunchInfo &launch_info,
219b9c1b51eSKate Stone     NativeProcessProtocol::NativeDelegate &native_delegate, MainLoop &mainloop,
220b9c1b51eSKate Stone     NativeProcessProtocolSP &native_process_sp) {
221a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
222af245d11STodd Fiala 
22397206d57SZachary Turner   Status error;
224af245d11STodd Fiala 
225af245d11STodd Fiala   // Verify the working directory is valid if one was specified.
226d3173f34SChaoren Lin   FileSpec working_dir{launch_info.GetWorkingDirectory()};
2277d86ee5aSZachary Turner   if (working_dir && (!working_dir.ResolvePath() ||
2287d86ee5aSZachary Turner                       !llvm::sys::fs::is_directory(working_dir.GetPath()))) {
229d3173f34SChaoren Lin     error.SetErrorStringWithFormat("No such file or directory: %s",
230d3173f34SChaoren Lin                                    working_dir.GetCString());
231af245d11STodd Fiala     return error;
232af245d11STodd Fiala   }
233af245d11STodd Fiala 
234af245d11STodd Fiala   // Create the NativeProcessLinux in launch mode.
235af245d11STodd Fiala   native_process_sp.reset(new NativeProcessLinux());
236af245d11STodd Fiala 
237b9c1b51eSKate Stone   if (!native_process_sp->RegisterNativeDelegate(native_delegate)) {
238af245d11STodd Fiala     native_process_sp.reset();
239af245d11STodd Fiala     error.SetErrorStringWithFormat("failed to register the native delegate");
240af245d11STodd Fiala     return error;
241af245d11STodd Fiala   }
242af245d11STodd Fiala 
243b9c1b51eSKate Stone   error = std::static_pointer_cast<NativeProcessLinux>(native_process_sp)
244b9c1b51eSKate Stone               ->LaunchInferior(mainloop, launch_info);
245af245d11STodd Fiala 
246b9c1b51eSKate Stone   if (error.Fail()) {
247af245d11STodd Fiala     native_process_sp.reset();
248a6321a8eSPavel Labath     LLDB_LOG(log, "failed to launch process: {0}", error);
249af245d11STodd Fiala     return error;
250af245d11STodd Fiala   }
251af245d11STodd Fiala 
252af245d11STodd Fiala   launch_info.SetProcessID(native_process_sp->GetID());
253af245d11STodd Fiala 
254af245d11STodd Fiala   return error;
255af245d11STodd Fiala }
256af245d11STodd Fiala 
25797206d57SZachary Turner Status NativeProcessProtocol::Attach(
258b9c1b51eSKate Stone     lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
259b9c1b51eSKate Stone     MainLoop &mainloop, NativeProcessProtocolSP &native_process_sp) {
260a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
261a6321a8eSPavel Labath   LLDB_LOG(log, "pid = {0:x}", pid);
262af245d11STodd Fiala 
263af245d11STodd Fiala   // Retrieve the architecture for the running process.
264af245d11STodd Fiala   ArchSpec process_arch;
26597206d57SZachary Turner   Status error = ResolveProcessArchitecture(pid, process_arch);
266af245d11STodd Fiala   if (!error.Success())
267af245d11STodd Fiala     return error;
268af245d11STodd Fiala 
269b9c1b51eSKate Stone   std::shared_ptr<NativeProcessLinux> native_process_linux_sp(
270b9c1b51eSKate Stone       new NativeProcessLinux());
271af245d11STodd Fiala 
272b9c1b51eSKate Stone   if (!native_process_linux_sp->RegisterNativeDelegate(native_delegate)) {
273af245d11STodd Fiala     error.SetErrorStringWithFormat("failed to register the native delegate");
274af245d11STodd Fiala     return error;
275af245d11STodd Fiala   }
276af245d11STodd Fiala 
27719cbe96aSPavel Labath   native_process_linux_sp->AttachToInferior(mainloop, pid, error);
278af245d11STodd Fiala   if (!error.Success())
279af245d11STodd Fiala     return error;
280af245d11STodd Fiala 
2811339b5e8SOleksiy Vyalov   native_process_sp = native_process_linux_sp;
282af245d11STodd Fiala   return error;
283af245d11STodd Fiala }
284af245d11STodd Fiala 
285af245d11STodd Fiala // -----------------------------------------------------------------------------
286af245d11STodd Fiala // Public Instance Methods
287af245d11STodd Fiala // -----------------------------------------------------------------------------
288af245d11STodd Fiala 
289b9c1b51eSKate Stone NativeProcessLinux::NativeProcessLinux()
290b9c1b51eSKate Stone     : NativeProcessProtocol(LLDB_INVALID_PROCESS_ID), m_arch(),
291b9c1b51eSKate Stone       m_supports_mem_region(eLazyBoolCalculate), m_mem_region_cache(),
292*99e37695SRavitheja Addepally       m_pending_notification_tid(LLDB_INVALID_THREAD_ID),
293*99e37695SRavitheja Addepally       m_pt_proces_trace_id(LLDB_INVALID_UID) {}
294af245d11STodd Fiala 
295b9c1b51eSKate Stone void NativeProcessLinux::AttachToInferior(MainLoop &mainloop, lldb::pid_t pid,
29697206d57SZachary Turner                                           Status &error) {
297a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
298a6321a8eSPavel Labath   LLDB_LOG(log, "pid = {0:x}", pid);
299af245d11STodd Fiala 
300b9c1b51eSKate Stone   m_sigchld_handle = mainloop.RegisterSignal(
301b9c1b51eSKate Stone       SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, error);
30219cbe96aSPavel Labath   if (!m_sigchld_handle)
30319cbe96aSPavel Labath     return;
30419cbe96aSPavel Labath 
3052a86b555SPavel Labath   error = ResolveProcessArchitecture(pid, m_arch);
306af245d11STodd Fiala   if (!error.Success())
307af245d11STodd Fiala     return;
308af245d11STodd Fiala 
309af245d11STodd Fiala   // Set the architecture to the exe architecture.
310a6321a8eSPavel Labath   LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid,
311a6321a8eSPavel Labath            m_arch.GetArchitectureName());
312af245d11STodd Fiala   m_pid = pid;
313af245d11STodd Fiala   SetState(eStateAttaching);
314af245d11STodd Fiala 
31519cbe96aSPavel Labath   Attach(pid, error);
316af245d11STodd Fiala }
317af245d11STodd Fiala 
31897206d57SZachary Turner Status NativeProcessLinux::LaunchInferior(MainLoop &mainloop,
319b9c1b51eSKate Stone                                           ProcessLaunchInfo &launch_info) {
32097206d57SZachary Turner   Status error;
321b9c1b51eSKate Stone   m_sigchld_handle = mainloop.RegisterSignal(
322b9c1b51eSKate Stone       SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, error);
3234abe5d69SPavel Labath   if (!m_sigchld_handle)
3244abe5d69SPavel Labath     return error;
3254abe5d69SPavel Labath 
3264abe5d69SPavel Labath   SetState(eStateLaunching);
3270c4f01d4SPavel Labath 
3284abe5d69SPavel Labath   MaybeLogLaunchInfo(launch_info);
3294abe5d69SPavel Labath 
330b9c1b51eSKate Stone   ::pid_t pid =
331816ae4b0SKamil Rytarowski       ProcessLauncherPosixFork().LaunchProcess(launch_info, error).GetProcessId();
3325ad891f7SPavel Labath   if (error.Fail())
3334abe5d69SPavel Labath     return error;
3340c4f01d4SPavel Labath 
335a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
33675f47c3aSTodd Fiala 
337af245d11STodd Fiala   // Wait for the child process to trap on its call to execve.
338af245d11STodd Fiala   ::pid_t wpid;
339af245d11STodd Fiala   int status;
340b9c1b51eSKate Stone   if ((wpid = waitpid(pid, &status, 0)) < 0) {
341bd7cbc5aSPavel Labath     error.SetErrorToErrno();
342a6321a8eSPavel Labath     LLDB_LOG(log, "waitpid for inferior failed with %s", error);
343af245d11STodd Fiala 
344af245d11STodd Fiala     // Mark the inferior as invalid.
345b9c1b51eSKate Stone     // FIXME this could really use a new state - eStateLaunchFailure.  For now,
346b9c1b51eSKate Stone     // using eStateInvalid.
347bd7cbc5aSPavel Labath     SetState(StateType::eStateInvalid);
348af245d11STodd Fiala 
3494abe5d69SPavel Labath     return error;
350af245d11STodd Fiala   }
351af245d11STodd Fiala   assert(WIFSTOPPED(status) && (wpid == static_cast<::pid_t>(pid)) &&
352af245d11STodd Fiala          "Could not sync with inferior process.");
353af245d11STodd Fiala 
354a6321a8eSPavel Labath   LLDB_LOG(log, "inferior started, now in stopped state");
355bd7cbc5aSPavel Labath   error = SetDefaultPtraceOpts(pid);
356b9c1b51eSKate Stone   if (error.Fail()) {
357a6321a8eSPavel Labath     LLDB_LOG(log, "failed to set default ptrace options: {0}", error);
358af245d11STodd Fiala 
359af245d11STodd Fiala     // Mark the inferior as invalid.
360b9c1b51eSKate Stone     // FIXME this could really use a new state - eStateLaunchFailure.  For now,
361b9c1b51eSKate Stone     // using eStateInvalid.
362bd7cbc5aSPavel Labath     SetState(StateType::eStateInvalid);
363af245d11STodd Fiala 
3644abe5d69SPavel Labath     return error;
365af245d11STodd Fiala   }
366af245d11STodd Fiala 
367af245d11STodd Fiala   // Release the master terminal descriptor and pass it off to the
368af245d11STodd Fiala   // NativeProcessLinux instance.  Similarly stash the inferior pid.
3695ad891f7SPavel Labath   m_terminal_fd = launch_info.GetPTY().ReleaseMasterFileDescriptor();
370bd7cbc5aSPavel Labath   m_pid = pid;
3714abe5d69SPavel Labath   launch_info.SetProcessID(pid);
372af245d11STodd Fiala 
373b9c1b51eSKate Stone   if (m_terminal_fd != -1) {
374bd7cbc5aSPavel Labath     error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
375b9c1b51eSKate Stone     if (error.Fail()) {
376a6321a8eSPavel Labath       LLDB_LOG(log,
377a6321a8eSPavel Labath                "inferior EnsureFDFlags failed for ensuring terminal "
378a6321a8eSPavel Labath                "O_NONBLOCK setting: {0}",
379a6321a8eSPavel Labath                error);
380af245d11STodd Fiala 
381af245d11STodd Fiala       // Mark the inferior as invalid.
382b9c1b51eSKate Stone       // FIXME this could really use a new state - eStateLaunchFailure.  For
383b9c1b51eSKate Stone       // now, using eStateInvalid.
384bd7cbc5aSPavel Labath       SetState(StateType::eStateInvalid);
385af245d11STodd Fiala 
3864abe5d69SPavel Labath       return error;
387af245d11STodd Fiala     }
3885ad891f7SPavel Labath   }
389af245d11STodd Fiala 
390a6321a8eSPavel Labath   LLDB_LOG(log, "adding pid = {0}", pid);
3912a86b555SPavel Labath   ResolveProcessArchitecture(m_pid, m_arch);
392f9077782SPavel Labath   NativeThreadLinuxSP thread_sp = AddThread(pid);
393af245d11STodd Fiala   assert(thread_sp && "AddThread() returned a nullptr thread");
394f9077782SPavel Labath   thread_sp->SetStoppedBySignal(SIGSTOP);
395f9077782SPavel Labath   ThreadWasCreated(*thread_sp);
396af245d11STodd Fiala 
397af245d11STodd Fiala   // Let our process instance know the thread has stopped.
398bd7cbc5aSPavel Labath   SetCurrentThreadID(thread_sp->GetID());
399bd7cbc5aSPavel Labath   SetState(StateType::eStateStopped);
400af245d11STodd Fiala 
401a6321a8eSPavel Labath   if (error.Fail())
402a6321a8eSPavel Labath     LLDB_LOG(log, "inferior launching failed {0}", error);
4034abe5d69SPavel Labath   return error;
404af245d11STodd Fiala }
405af245d11STodd Fiala 
40697206d57SZachary Turner ::pid_t NativeProcessLinux::Attach(lldb::pid_t pid, Status &error) {
407a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
408af245d11STodd Fiala 
409b9c1b51eSKate Stone   // Use a map to keep track of the threads which we have attached/need to
410b9c1b51eSKate Stone   // attach.
411af245d11STodd Fiala   Host::TidMap tids_to_attach;
412b9c1b51eSKate Stone   if (pid <= 1) {
413bd7cbc5aSPavel Labath     error.SetErrorToGenericError();
414bd7cbc5aSPavel Labath     error.SetErrorString("Attaching to process 1 is not allowed.");
415bd7cbc5aSPavel Labath     return -1;
416af245d11STodd Fiala   }
417af245d11STodd Fiala 
418b9c1b51eSKate Stone   while (Host::FindProcessThreads(pid, tids_to_attach)) {
419af245d11STodd Fiala     for (Host::TidMap::iterator it = tids_to_attach.begin();
420b9c1b51eSKate Stone          it != tids_to_attach.end();) {
421b9c1b51eSKate Stone       if (it->second == false) {
422af245d11STodd Fiala         lldb::tid_t tid = it->first;
423af245d11STodd Fiala 
424af245d11STodd Fiala         // Attach to the requested process.
425af245d11STodd Fiala         // An attach will cause the thread to stop with a SIGSTOP.
4264a9babb2SPavel Labath         error = PtraceWrapper(PTRACE_ATTACH, tid);
427b9c1b51eSKate Stone         if (error.Fail()) {
428af245d11STodd Fiala           // No such thread. The thread may have exited.
429af245d11STodd Fiala           // More error handling may be needed.
430b9c1b51eSKate Stone           if (error.GetError() == ESRCH) {
431af245d11STodd Fiala             it = tids_to_attach.erase(it);
432af245d11STodd Fiala             continue;
433b9c1b51eSKate Stone           } else
434bd7cbc5aSPavel Labath             return -1;
435af245d11STodd Fiala         }
436af245d11STodd Fiala 
437af245d11STodd Fiala         int status;
438af245d11STodd Fiala         // Need to use __WALL otherwise we receive an error with errno=ECHLD
439af245d11STodd Fiala         // At this point we should have a thread stopped if waitpid succeeds.
440b9c1b51eSKate Stone         if ((status = waitpid(tid, NULL, __WALL)) < 0) {
441af245d11STodd Fiala           // No such thread. The thread may have exited.
442af245d11STodd Fiala           // More error handling may be needed.
443b9c1b51eSKate Stone           if (errno == ESRCH) {
444af245d11STodd Fiala             it = tids_to_attach.erase(it);
445af245d11STodd Fiala             continue;
446b9c1b51eSKate Stone           } else {
447bd7cbc5aSPavel Labath             error.SetErrorToErrno();
448bd7cbc5aSPavel Labath             return -1;
449af245d11STodd Fiala           }
450af245d11STodd Fiala         }
451af245d11STodd Fiala 
452bd7cbc5aSPavel Labath         error = SetDefaultPtraceOpts(tid);
453bd7cbc5aSPavel Labath         if (error.Fail())
454bd7cbc5aSPavel Labath           return -1;
455af245d11STodd Fiala 
456a6321a8eSPavel Labath         LLDB_LOG(log, "adding tid = {0}", tid);
457af245d11STodd Fiala         it->second = true;
458af245d11STodd Fiala 
459af245d11STodd Fiala         // Create the thread, mark it as stopped.
460f9077782SPavel Labath         NativeThreadLinuxSP thread_sp(AddThread(static_cast<lldb::tid_t>(tid)));
461af245d11STodd Fiala         assert(thread_sp && "AddThread() returned a nullptr");
462fa03ad2eSChaoren Lin 
463b9c1b51eSKate Stone         // This will notify this is a new thread and tell the system it is
464b9c1b51eSKate Stone         // stopped.
465f9077782SPavel Labath         thread_sp->SetStoppedBySignal(SIGSTOP);
466f9077782SPavel Labath         ThreadWasCreated(*thread_sp);
467bd7cbc5aSPavel Labath         SetCurrentThreadID(thread_sp->GetID());
468af245d11STodd Fiala       }
469af245d11STodd Fiala 
470af245d11STodd Fiala       // move the loop forward
471af245d11STodd Fiala       ++it;
472af245d11STodd Fiala     }
473af245d11STodd Fiala   }
474af245d11STodd Fiala 
475b9c1b51eSKate Stone   if (tids_to_attach.size() > 0) {
476bd7cbc5aSPavel Labath     m_pid = pid;
477af245d11STodd Fiala     // Let our process instance know the thread has stopped.
478bd7cbc5aSPavel Labath     SetState(StateType::eStateStopped);
479b9c1b51eSKate Stone   } else {
480bd7cbc5aSPavel Labath     error.SetErrorToGenericError();
481bd7cbc5aSPavel Labath     error.SetErrorString("No such process.");
482bd7cbc5aSPavel Labath     return -1;
483af245d11STodd Fiala   }
484af245d11STodd Fiala 
485bd7cbc5aSPavel Labath   return pid;
486af245d11STodd Fiala }
487af245d11STodd Fiala 
48897206d57SZachary Turner Status NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid) {
489af245d11STodd Fiala   long ptrace_opts = 0;
490af245d11STodd Fiala 
491af245d11STodd Fiala   // Have the child raise an event on exit.  This is used to keep the child in
492af245d11STodd Fiala   // limbo until it is destroyed.
493af245d11STodd Fiala   ptrace_opts |= PTRACE_O_TRACEEXIT;
494af245d11STodd Fiala 
495af245d11STodd Fiala   // Have the tracer trace threads which spawn in the inferior process.
496af245d11STodd Fiala   // TODO: if we want to support tracing the inferiors' child, add the
497af245d11STodd Fiala   // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
498af245d11STodd Fiala   ptrace_opts |= PTRACE_O_TRACECLONE;
499af245d11STodd Fiala 
500af245d11STodd Fiala   // Have the tracer notify us before execve returns
501af245d11STodd Fiala   // (needed to disable legacy SIGTRAP generation)
502af245d11STodd Fiala   ptrace_opts |= PTRACE_O_TRACEEXEC;
503af245d11STodd Fiala 
5044a9babb2SPavel Labath   return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void *)ptrace_opts);
505af245d11STodd Fiala }
506af245d11STodd Fiala 
5071107b5a5SPavel Labath // Handles all waitpid events from the inferior process.
508b9c1b51eSKate Stone void NativeProcessLinux::MonitorCallback(lldb::pid_t pid, bool exited,
5093508fc8cSPavel Labath                                          WaitStatus status) {
510af245d11STodd Fiala   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
511af245d11STodd Fiala 
512b9c1b51eSKate Stone   // Certain activities differ based on whether the pid is the tid of the main
513b9c1b51eSKate Stone   // thread.
5141107b5a5SPavel Labath   const bool is_main_thread = (pid == GetID());
515af245d11STodd Fiala 
516af245d11STodd Fiala   // Handle when the thread exits.
517b9c1b51eSKate Stone   if (exited) {
518a6321a8eSPavel Labath     LLDB_LOG(log, "got exit signal({0}) , tid = {1} ({2} main thread)", signal,
519a6321a8eSPavel Labath              pid, is_main_thread ? "is" : "is not");
520af245d11STodd Fiala 
521af245d11STodd Fiala     // This is a thread that exited.  Ensure we're not tracking it anymore.
5221107b5a5SPavel Labath     const bool thread_found = StopTrackingThread(pid);
523af245d11STodd Fiala 
524b9c1b51eSKate Stone     if (is_main_thread) {
525b9c1b51eSKate Stone       // We only set the exit status and notify the delegate if we haven't
526b9c1b51eSKate Stone       // already set the process
527b9c1b51eSKate Stone       // state to an exited state.  We normally should have received a SIGTRAP |
528b9c1b51eSKate Stone       // (PTRACE_EVENT_EXIT << 8)
529af245d11STodd Fiala       // for the main thread.
530b9c1b51eSKate Stone       const bool already_notified = (GetState() == StateType::eStateExited) ||
531b9c1b51eSKate Stone                                     (GetState() == StateType::eStateCrashed);
532b9c1b51eSKate Stone       if (!already_notified) {
533a6321a8eSPavel Labath         LLDB_LOG(
534a6321a8eSPavel Labath             log,
535a6321a8eSPavel Labath             "tid = {0} handling main thread exit ({1}), expected exit state "
536a6321a8eSPavel Labath             "already set but state was {2} instead, setting exit state now",
537a6321a8eSPavel Labath             pid,
538b9c1b51eSKate Stone             thread_found ? "stopped tracking thread metadata"
539b9c1b51eSKate Stone                          : "thread metadata not found",
5408198db30SPavel Labath             GetState());
541af245d11STodd Fiala         // The main thread exited.  We're done monitoring.  Report to delegate.
5423508fc8cSPavel Labath         SetExitStatus(status, true);
543af245d11STodd Fiala 
544af245d11STodd Fiala         // Notify delegate that our process has exited.
5451107b5a5SPavel Labath         SetState(StateType::eStateExited, true);
546a6321a8eSPavel Labath       } else
547a6321a8eSPavel Labath         LLDB_LOG(log, "tid = {0} main thread now exited (%s)", pid,
548b9c1b51eSKate Stone                  thread_found ? "stopped tracking thread metadata"
549b9c1b51eSKate Stone                               : "thread metadata not found");
550b9c1b51eSKate Stone     } else {
551b9c1b51eSKate Stone       // Do we want to report to the delegate in this case?  I think not.  If
552a6321a8eSPavel Labath       // this was an orderly thread exit, we would already have received the
553a6321a8eSPavel Labath       // SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal, and we would have done an
554a6321a8eSPavel Labath       // all-stop then.
555a6321a8eSPavel Labath       LLDB_LOG(log, "tid = {0} handling non-main thread exit (%s)", pid,
556b9c1b51eSKate Stone                thread_found ? "stopped tracking thread metadata"
557b9c1b51eSKate Stone                             : "thread metadata not found");
558af245d11STodd Fiala     }
5591107b5a5SPavel Labath     return;
560af245d11STodd Fiala   }
561af245d11STodd Fiala 
562af245d11STodd Fiala   siginfo_t info;
563b9cc0c75SPavel Labath   const auto info_err = GetSignalInfo(pid, &info);
564b9cc0c75SPavel Labath   auto thread_sp = GetThreadByID(pid);
565b9cc0c75SPavel Labath 
566b9c1b51eSKate Stone   if (!thread_sp) {
567b9c1b51eSKate Stone     // Normally, the only situation when we cannot find the thread is if we have
568a6321a8eSPavel Labath     // just received a new thread notification. This is indicated by
569a6321a8eSPavel Labath     // GetSignalInfo() returning si_code == SI_USER and si_pid == 0
570a6321a8eSPavel Labath     LLDB_LOG(log, "received notification about an unknown tid {0}.", pid);
571b9cc0c75SPavel Labath 
572b9c1b51eSKate Stone     if (info_err.Fail()) {
573a6321a8eSPavel Labath       LLDB_LOG(log,
574a6321a8eSPavel Labath                "(tid {0}) GetSignalInfo failed ({1}). "
575a6321a8eSPavel Labath                "Ingoring this notification.",
576a6321a8eSPavel Labath                pid, info_err);
577b9cc0c75SPavel Labath       return;
578b9cc0c75SPavel Labath     }
579b9cc0c75SPavel Labath 
580a6321a8eSPavel Labath     LLDB_LOG(log, "tid {0}, si_code: {1}, si_pid: {2}", pid, info.si_code,
581a6321a8eSPavel Labath              info.si_pid);
582b9cc0c75SPavel Labath 
583b9cc0c75SPavel Labath     auto thread_sp = AddThread(pid);
584*99e37695SRavitheja Addepally 
585b9cc0c75SPavel Labath     // Resume the newly created thread.
586b9cc0c75SPavel Labath     ResumeThread(*thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
587b9cc0c75SPavel Labath     ThreadWasCreated(*thread_sp);
588b9cc0c75SPavel Labath     return;
589b9cc0c75SPavel Labath   }
590b9cc0c75SPavel Labath 
591b9cc0c75SPavel Labath   // Get details on the signal raised.
592b9c1b51eSKate Stone   if (info_err.Success()) {
593fa03ad2eSChaoren Lin     // We have retrieved the signal info.  Dispatch appropriately.
594fa03ad2eSChaoren Lin     if (info.si_signo == SIGTRAP)
595b9cc0c75SPavel Labath       MonitorSIGTRAP(info, *thread_sp);
596fa03ad2eSChaoren Lin     else
597b9cc0c75SPavel Labath       MonitorSignal(info, *thread_sp, exited);
598b9c1b51eSKate Stone   } else {
599b9c1b51eSKate Stone     if (info_err.GetError() == EINVAL) {
600fa03ad2eSChaoren Lin       // This is a group stop reception for this tid.
601b9c1b51eSKate Stone       // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU
602a6321a8eSPavel Labath       // into the tracee, triggering the group-stop mechanism. Normally
603a6321a8eSPavel Labath       // receiving these would stop the process, pending a SIGCONT. Simulating
604a6321a8eSPavel Labath       // this state in a debugger is hard and is generally not needed (one use
605a6321a8eSPavel Labath       // case is debugging background task being managed by a shell). For
606a6321a8eSPavel Labath       // general use, it is sufficient to stop the process in a signal-delivery
607b9c1b51eSKate Stone       // stop which happens before the group stop. This done by MonitorSignal
608a6321a8eSPavel Labath       // and works correctly for all signals.
609a6321a8eSPavel Labath       LLDB_LOG(log,
610a6321a8eSPavel Labath                "received a group stop for pid {0} tid {1}. Transparent "
611a6321a8eSPavel Labath                "handling of group stops not supported, resuming the "
612a6321a8eSPavel Labath                "thread.",
613a6321a8eSPavel Labath                GetID(), pid);
614b9c1b51eSKate Stone       ResumeThread(*thread_sp, thread_sp->GetState(),
615b9c1b51eSKate Stone                    LLDB_INVALID_SIGNAL_NUMBER);
616b9c1b51eSKate Stone     } else {
617af245d11STodd Fiala       // ptrace(GETSIGINFO) failed (but not due to group-stop).
618af245d11STodd Fiala 
619b9c1b51eSKate Stone       // A return value of ESRCH means the thread/process is no longer on the
620a6321a8eSPavel Labath       // system, so it was killed somehow outside of our control.  Either way,
621a6321a8eSPavel Labath       // we can't do anything with it anymore.
622af245d11STodd Fiala 
623b9c1b51eSKate Stone       // Stop tracking the metadata for the thread since it's entirely off the
624b9c1b51eSKate Stone       // system now.
6251107b5a5SPavel Labath       const bool thread_found = StopTrackingThread(pid);
626af245d11STodd Fiala 
627a6321a8eSPavel Labath       LLDB_LOG(log,
628a6321a8eSPavel Labath                "GetSignalInfo failed: {0}, tid = {1}, signal = {2}, "
629a6321a8eSPavel Labath                "status = {3}, main_thread = {4}, thread_found: {5}",
630a6321a8eSPavel Labath                info_err, pid, signal, status, is_main_thread, thread_found);
631af245d11STodd Fiala 
632b9c1b51eSKate Stone       if (is_main_thread) {
633b9c1b51eSKate Stone         // Notify the delegate - our process is not available but appears to
634b9c1b51eSKate Stone         // have been killed outside
635af245d11STodd Fiala         // our control.  Is eStateExited the right exit state in this case?
6363508fc8cSPavel Labath         SetExitStatus(status, true);
6371107b5a5SPavel Labath         SetState(StateType::eStateExited, true);
638b9c1b51eSKate Stone       } else {
639b9c1b51eSKate Stone         // This thread was pulled out from underneath us.  Anything to do here?
640b9c1b51eSKate Stone         // Do we want to do an all stop?
641a6321a8eSPavel Labath         LLDB_LOG(log,
642a6321a8eSPavel Labath                  "pid {0} tid {1} non-main thread exit occurred, didn't "
643a6321a8eSPavel Labath                  "tell delegate anything since thread disappeared out "
644a6321a8eSPavel Labath                  "from underneath us",
645a6321a8eSPavel Labath                  GetID(), pid);
646af245d11STodd Fiala       }
647af245d11STodd Fiala     }
648af245d11STodd Fiala   }
649af245d11STodd Fiala }
650af245d11STodd Fiala 
651b9c1b51eSKate Stone void NativeProcessLinux::WaitForNewThread(::pid_t tid) {
652a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
653426bdf88SPavel Labath 
654f9077782SPavel Labath   NativeThreadLinuxSP new_thread_sp = GetThreadByID(tid);
655426bdf88SPavel Labath 
656b9c1b51eSKate Stone   if (new_thread_sp) {
657b9c1b51eSKate Stone     // We are already tracking the thread - we got the event on the new thread
658b9c1b51eSKate Stone     // (see
659426bdf88SPavel Labath     // MonitorSignal) before this one. We are done.
660426bdf88SPavel Labath     return;
661426bdf88SPavel Labath   }
662426bdf88SPavel Labath 
663426bdf88SPavel Labath   // The thread is not tracked yet, let's wait for it to appear.
664426bdf88SPavel Labath   int status = -1;
665426bdf88SPavel Labath   ::pid_t wait_pid;
666b9c1b51eSKate Stone   do {
667a6321a8eSPavel Labath     LLDB_LOG(log,
668a6321a8eSPavel Labath              "received thread creation event for tid {0}. tid not tracked "
669a6321a8eSPavel Labath              "yet, waiting for thread to appear...",
670a6321a8eSPavel Labath              tid);
671426bdf88SPavel Labath     wait_pid = waitpid(tid, &status, __WALL);
672b9c1b51eSKate Stone   } while (wait_pid == -1 && errno == EINTR);
673b9c1b51eSKate Stone   // Since we are waiting on a specific tid, this must be the creation event.
674a6321a8eSPavel Labath   // But let's do some checks just in case.
675426bdf88SPavel Labath   if (wait_pid != tid) {
676a6321a8eSPavel Labath     LLDB_LOG(log,
677a6321a8eSPavel Labath              "waiting for tid {0} failed. Assuming the thread has "
678a6321a8eSPavel Labath              "disappeared in the meantime",
679a6321a8eSPavel Labath              tid);
680426bdf88SPavel Labath     // The only way I know of this could happen is if the whole process was
681b9c1b51eSKate Stone     // SIGKILLed in the mean time. In any case, we can't do anything about that
682b9c1b51eSKate Stone     // now.
683426bdf88SPavel Labath     return;
684426bdf88SPavel Labath   }
685b9c1b51eSKate Stone   if (WIFEXITED(status)) {
686a6321a8eSPavel Labath     LLDB_LOG(log,
687a6321a8eSPavel Labath              "waiting for tid {0} returned an 'exited' event. Not "
688a6321a8eSPavel Labath              "tracking the thread.",
689a6321a8eSPavel Labath              tid);
690426bdf88SPavel Labath     // Also a very improbable event.
691426bdf88SPavel Labath     return;
692426bdf88SPavel Labath   }
693426bdf88SPavel Labath 
694a6321a8eSPavel Labath   LLDB_LOG(log, "pid = {0}: tracking new thread tid {1}", GetID(), tid);
695f9077782SPavel Labath   new_thread_sp = AddThread(tid);
696*99e37695SRavitheja Addepally 
697b9cc0c75SPavel Labath   ResumeThread(*new_thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
698f9077782SPavel Labath   ThreadWasCreated(*new_thread_sp);
699426bdf88SPavel Labath }
700426bdf88SPavel Labath 
701b9c1b51eSKate Stone void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info,
702b9c1b51eSKate Stone                                         NativeThreadLinux &thread) {
703a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
704b9cc0c75SPavel Labath   const bool is_main_thread = (thread.GetID() == GetID());
705af245d11STodd Fiala 
706b9cc0c75SPavel Labath   assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
707af245d11STodd Fiala 
708b9c1b51eSKate Stone   switch (info.si_code) {
709b9c1b51eSKate Stone   // TODO: these two cases are required if we want to support tracing of the
710b9c1b51eSKate Stone   // inferiors' children.  We'd need this to debug a monitor.
711af245d11STodd Fiala   // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
712af245d11STodd Fiala   // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
713af245d11STodd Fiala 
714b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): {
715b9c1b51eSKate Stone     // This is the notification on the parent thread which informs us of new
716b9c1b51eSKate Stone     // thread
717426bdf88SPavel Labath     // creation.
718b9c1b51eSKate Stone     // We don't want to do anything with the parent thread so we just resume it.
719b9c1b51eSKate Stone     // In case we
720b9c1b51eSKate Stone     // want to implement "break on thread creation" functionality, we would need
721b9c1b51eSKate Stone     // to stop
722426bdf88SPavel Labath     // here.
723af245d11STodd Fiala 
724af245d11STodd Fiala     unsigned long event_message = 0;
725b9c1b51eSKate Stone     if (GetEventMessage(thread.GetID(), &event_message).Fail()) {
726a6321a8eSPavel Labath       LLDB_LOG(log,
727a6321a8eSPavel Labath                "pid {0} received thread creation event but "
728a6321a8eSPavel Labath                "GetEventMessage failed so we don't know the new tid",
729a6321a8eSPavel Labath                thread.GetID());
730426bdf88SPavel Labath     } else
731426bdf88SPavel Labath       WaitForNewThread(event_message);
732af245d11STodd Fiala 
733b9cc0c75SPavel Labath     ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
734af245d11STodd Fiala     break;
735af245d11STodd Fiala   }
736af245d11STodd Fiala 
737b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): {
738f9077782SPavel Labath     NativeThreadLinuxSP main_thread_sp;
739a6321a8eSPavel Labath     LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP);
740a9882ceeSTodd Fiala 
7411dbc6c9cSPavel Labath     // Exec clears any pending notifications.
7420e1d729bSPavel Labath     m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
743fa03ad2eSChaoren Lin 
744b9c1b51eSKate Stone     // Remove all but the main thread here.  Linux fork creates a new process
745b9c1b51eSKate Stone     // which only copies the main thread.
746a6321a8eSPavel Labath     LLDB_LOG(log, "exec received, stop tracking all but main thread");
747a9882ceeSTodd Fiala 
748b9c1b51eSKate Stone     for (auto thread_sp : m_threads) {
749a9882ceeSTodd Fiala       const bool is_main_thread = thread_sp && thread_sp->GetID() == GetID();
750b9c1b51eSKate Stone       if (is_main_thread) {
751f9077782SPavel Labath         main_thread_sp = std::static_pointer_cast<NativeThreadLinux>(thread_sp);
752a6321a8eSPavel Labath         LLDB_LOG(log, "found main thread with tid {0}, keeping",
753a6321a8eSPavel Labath                  main_thread_sp->GetID());
754b9c1b51eSKate Stone       } else {
755a6321a8eSPavel Labath         LLDB_LOG(log, "discarding non-main-thread tid {0} due to exec",
756a6321a8eSPavel Labath                  thread_sp->GetID());
757a9882ceeSTodd Fiala       }
758a9882ceeSTodd Fiala     }
759a9882ceeSTodd Fiala 
760a9882ceeSTodd Fiala     m_threads.clear();
761a9882ceeSTodd Fiala 
762b9c1b51eSKate Stone     if (main_thread_sp) {
763a9882ceeSTodd Fiala       m_threads.push_back(main_thread_sp);
764a9882ceeSTodd Fiala       SetCurrentThreadID(main_thread_sp->GetID());
765f9077782SPavel Labath       main_thread_sp->SetStoppedByExec();
766b9c1b51eSKate Stone     } else {
767a9882ceeSTodd Fiala       SetCurrentThreadID(LLDB_INVALID_THREAD_ID);
768a6321a8eSPavel Labath       LLDB_LOG(log,
769a6321a8eSPavel Labath                "pid {0} no main thread found, discarded all threads, "
770a6321a8eSPavel Labath                "we're in a no-thread state!",
771a6321a8eSPavel Labath                GetID());
772a9882ceeSTodd Fiala     }
773a9882ceeSTodd Fiala 
774fa03ad2eSChaoren Lin     // Tell coordinator about about the "new" (since exec) stopped main thread.
775f9077782SPavel Labath     ThreadWasCreated(*main_thread_sp);
776fa03ad2eSChaoren Lin 
777a9882ceeSTodd Fiala     // Let our delegate know we have just exec'd.
778a9882ceeSTodd Fiala     NotifyDidExec();
779a9882ceeSTodd Fiala 
780a9882ceeSTodd Fiala     // If we have a main thread, indicate we are stopped.
781b9c1b51eSKate Stone     assert(main_thread_sp && "exec called during ptraced process but no main "
782b9c1b51eSKate Stone                              "thread metadata tracked");
783fa03ad2eSChaoren Lin 
784fa03ad2eSChaoren Lin     // Let the process know we're stopped.
785b9cc0c75SPavel Labath     StopRunningThreads(main_thread_sp->GetID());
786a9882ceeSTodd Fiala 
787af245d11STodd Fiala     break;
788a9882ceeSTodd Fiala   }
789af245d11STodd Fiala 
790b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): {
791af245d11STodd Fiala     // The inferior process or one of its threads is about to exit.
792b9c1b51eSKate Stone     // We don't want to do anything with the thread so we just resume it. In
793b9c1b51eSKate Stone     // case we
794b9c1b51eSKate Stone     // want to implement "break on thread exit" functionality, we would need to
795b9c1b51eSKate Stone     // stop
7966e35163cSPavel Labath     // here.
797fa03ad2eSChaoren Lin 
798af245d11STodd Fiala     unsigned long data = 0;
799b9cc0c75SPavel Labath     if (GetEventMessage(thread.GetID(), &data).Fail())
800af245d11STodd Fiala       data = -1;
801af245d11STodd Fiala 
802a6321a8eSPavel Labath     LLDB_LOG(log,
803a6321a8eSPavel Labath              "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
804a6321a8eSPavel Labath              "WIFSIGNALED={2}, pid = {3}, main_thread = {4}",
805a6321a8eSPavel Labath              data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(),
806a6321a8eSPavel Labath              is_main_thread);
807af245d11STodd Fiala 
8083508fc8cSPavel Labath     if (is_main_thread)
8093508fc8cSPavel Labath       SetExitStatus(WaitStatus::Decode(data), true);
81075f47c3aSTodd Fiala 
81186852d36SPavel Labath     StateType state = thread.GetState();
812b9c1b51eSKate Stone     if (!StateIsRunningState(state)) {
813b9c1b51eSKate Stone       // Due to a kernel bug, we may sometimes get this stop after the inferior
814b9c1b51eSKate Stone       // gets a
815b9c1b51eSKate Stone       // SIGKILL. This confuses our state tracking logic in ResumeThread(),
816b9c1b51eSKate Stone       // since normally,
817b9c1b51eSKate Stone       // we should not be receiving any ptrace events while the inferior is
818b9c1b51eSKate Stone       // stopped. This
81986852d36SPavel Labath       // makes sure that the inferior is resumed and exits normally.
82086852d36SPavel Labath       state = eStateRunning;
82186852d36SPavel Labath     }
82286852d36SPavel Labath     ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
823af245d11STodd Fiala 
824af245d11STodd Fiala     break;
825af245d11STodd Fiala   }
826af245d11STodd Fiala 
827af245d11STodd Fiala   case 0:
828c16f5dcaSChaoren Lin   case TRAP_TRACE:  // We receive this on single stepping.
829c16f5dcaSChaoren Lin   case TRAP_HWBKPT: // We receive this on watchpoint hit
83086fd8e45SChaoren Lin   {
831c16f5dcaSChaoren Lin     // If a watchpoint was hit, report it
832c16f5dcaSChaoren Lin     uint32_t wp_index;
83397206d57SZachary Turner     Status error = thread.GetRegisterContext()->GetWatchpointHitIndex(
834b9c1b51eSKate Stone         wp_index, (uintptr_t)info.si_addr);
835a6321a8eSPavel Labath     if (error.Fail())
836a6321a8eSPavel Labath       LLDB_LOG(log,
837a6321a8eSPavel Labath                "received error while checking for watchpoint hits, pid = "
838a6321a8eSPavel Labath                "{0}, error = {1}",
839a6321a8eSPavel Labath                thread.GetID(), error);
840b9c1b51eSKate Stone     if (wp_index != LLDB_INVALID_INDEX32) {
841b9cc0c75SPavel Labath       MonitorWatchpoint(thread, wp_index);
842c16f5dcaSChaoren Lin       break;
843c16f5dcaSChaoren Lin     }
844b9cc0c75SPavel Labath 
845d5ffbad2SOmair Javaid     // If a breakpoint was hit, report it
846d5ffbad2SOmair Javaid     uint32_t bp_index;
847d5ffbad2SOmair Javaid     error = thread.GetRegisterContext()->GetHardwareBreakHitIndex(
848d5ffbad2SOmair Javaid         bp_index, (uintptr_t)info.si_addr);
849d5ffbad2SOmair Javaid     if (error.Fail())
850d5ffbad2SOmair Javaid       LLDB_LOG(log, "received error while checking for hardware "
851d5ffbad2SOmair Javaid                     "breakpoint hits, pid = {0}, error = {1}",
852d5ffbad2SOmair Javaid                thread.GetID(), error);
853d5ffbad2SOmair Javaid     if (bp_index != LLDB_INVALID_INDEX32) {
854d5ffbad2SOmair Javaid       MonitorBreakpoint(thread);
855d5ffbad2SOmair Javaid       break;
856d5ffbad2SOmair Javaid     }
857d5ffbad2SOmair Javaid 
858be379e15STamas Berghammer     // Otherwise, report step over
859be379e15STamas Berghammer     MonitorTrace(thread);
860af245d11STodd Fiala     break;
861b9cc0c75SPavel Labath   }
862af245d11STodd Fiala 
863af245d11STodd Fiala   case SI_KERNEL:
86435799963SMohit K. Bhakkad #if defined __mips__
86535799963SMohit K. Bhakkad     // For mips there is no special signal for watchpoint
86635799963SMohit K. Bhakkad     // So we check for watchpoint in kernel trap
86735799963SMohit K. Bhakkad     {
86835799963SMohit K. Bhakkad       // If a watchpoint was hit, report it
86935799963SMohit K. Bhakkad       uint32_t wp_index;
87097206d57SZachary Turner       Status error = thread.GetRegisterContext()->GetWatchpointHitIndex(
871b9c1b51eSKate Stone           wp_index, LLDB_INVALID_ADDRESS);
872a6321a8eSPavel Labath       if (error.Fail())
873a6321a8eSPavel Labath         LLDB_LOG(log,
874a6321a8eSPavel Labath                  "received error while checking for watchpoint hits, pid = "
875a6321a8eSPavel Labath                  "{0}, error = {1}",
876a6321a8eSPavel Labath                  thread.GetID(), error);
877b9c1b51eSKate Stone       if (wp_index != LLDB_INVALID_INDEX32) {
878b9cc0c75SPavel Labath         MonitorWatchpoint(thread, wp_index);
87935799963SMohit K. Bhakkad         break;
88035799963SMohit K. Bhakkad       }
88135799963SMohit K. Bhakkad     }
88235799963SMohit K. Bhakkad // NO BREAK
88335799963SMohit K. Bhakkad #endif
884af245d11STodd Fiala   case TRAP_BRKPT:
885b9cc0c75SPavel Labath     MonitorBreakpoint(thread);
886af245d11STodd Fiala     break;
887af245d11STodd Fiala 
888af245d11STodd Fiala   case SIGTRAP:
889af245d11STodd Fiala   case (SIGTRAP | 0x80):
890a6321a8eSPavel Labath     LLDB_LOG(
891a6321a8eSPavel Labath         log,
892a6321a8eSPavel Labath         "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",
893a6321a8eSPavel Labath         info.si_code, GetID(), thread.GetID());
894fa03ad2eSChaoren Lin 
895af245d11STodd Fiala     // Ignore these signals until we know more about them.
896b9cc0c75SPavel Labath     ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
897af245d11STodd Fiala     break;
898af245d11STodd Fiala 
899af245d11STodd Fiala   default:
900a6321a8eSPavel Labath     LLDB_LOG(
901a6321a8eSPavel Labath         log,
902a6321a8eSPavel Labath         "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",
903a6321a8eSPavel Labath         info.si_code, GetID(), thread.GetID());
904a6321a8eSPavel Labath     llvm_unreachable("Unexpected SIGTRAP code!");
905af245d11STodd Fiala     break;
906af245d11STodd Fiala   }
907af245d11STodd Fiala }
908af245d11STodd Fiala 
909b9c1b51eSKate Stone void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) {
910a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
911a6321a8eSPavel Labath   LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID());
912c16f5dcaSChaoren Lin 
9130e1d729bSPavel Labath   // This thread is currently stopped.
914b9cc0c75SPavel Labath   thread.SetStoppedByTrace();
915c16f5dcaSChaoren Lin 
916b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
917c16f5dcaSChaoren Lin }
918c16f5dcaSChaoren Lin 
919b9c1b51eSKate Stone void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) {
920b9c1b51eSKate Stone   Log *log(
921b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
922a6321a8eSPavel Labath   LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID());
923c16f5dcaSChaoren Lin 
924c16f5dcaSChaoren Lin   // Mark the thread as stopped at breakpoint.
925b9cc0c75SPavel Labath   thread.SetStoppedByBreakpoint();
92697206d57SZachary Turner   Status error = FixupBreakpointPCAsNeeded(thread);
927c16f5dcaSChaoren Lin   if (error.Fail())
928a6321a8eSPavel Labath     LLDB_LOG(log, "pid = {0} fixup: {1}", thread.GetID(), error);
929d8c338d4STamas Berghammer 
930b9c1b51eSKate Stone   if (m_threads_stepping_with_breakpoint.find(thread.GetID()) !=
931b9c1b51eSKate Stone       m_threads_stepping_with_breakpoint.end())
932b9cc0c75SPavel Labath     thread.SetStoppedByTrace();
933c16f5dcaSChaoren Lin 
934b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
935c16f5dcaSChaoren Lin }
936c16f5dcaSChaoren Lin 
937b9c1b51eSKate Stone void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread,
938b9c1b51eSKate Stone                                            uint32_t wp_index) {
939b9c1b51eSKate Stone   Log *log(
940b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
941a6321a8eSPavel Labath   LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}",
942a6321a8eSPavel Labath            thread.GetID(), wp_index);
943c16f5dcaSChaoren Lin 
944c16f5dcaSChaoren Lin   // Mark the thread as stopped at watchpoint.
945c16f5dcaSChaoren Lin   // The address is at (lldb::addr_t)info->si_addr if we need it.
946f9077782SPavel Labath   thread.SetStoppedByWatchpoint(wp_index);
947c16f5dcaSChaoren Lin 
948b9c1b51eSKate Stone   // We need to tell all other running threads before we notify the delegate
949b9c1b51eSKate Stone   // about this stop.
950f9077782SPavel Labath   StopRunningThreads(thread.GetID());
951c16f5dcaSChaoren Lin }
952c16f5dcaSChaoren Lin 
953b9c1b51eSKate Stone void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
954b9c1b51eSKate Stone                                        NativeThreadLinux &thread, bool exited) {
955b9cc0c75SPavel Labath   const int signo = info.si_signo;
956b9cc0c75SPavel Labath   const bool is_from_llgs = info.si_pid == getpid();
957af245d11STodd Fiala 
958a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
959af245d11STodd Fiala 
960af245d11STodd Fiala   // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
961af245d11STodd Fiala   // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
962af245d11STodd Fiala   // kill(2) or raise(3).  Similarly for tgkill(2) on Linux.
963af245d11STodd Fiala   //
964af245d11STodd Fiala   // IOW, user generated signals never generate what we consider to be a
965af245d11STodd Fiala   // "crash".
966af245d11STodd Fiala   //
967af245d11STodd Fiala   // Similarly, ACK signals generated by this monitor.
968af245d11STodd Fiala 
969af245d11STodd Fiala   // Handle the signal.
970a6321a8eSPavel Labath   LLDB_LOG(log,
971a6321a8eSPavel Labath            "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
972a6321a8eSPavel Labath            "waitpid pid = {4})",
973a6321a8eSPavel Labath            Host::GetSignalAsCString(signo), signo, info.si_code,
974b9cc0c75SPavel Labath            thread.GetID());
97558a2f669STodd Fiala 
97658a2f669STodd Fiala   // Check for thread stop notification.
977b9c1b51eSKate Stone   if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) {
978af245d11STodd Fiala     // This is a tgkill()-based stop.
979a6321a8eSPavel Labath     LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID());
980fa03ad2eSChaoren Lin 
981aab58633SChaoren Lin     // Check that we're not already marked with a stop reason.
982b9c1b51eSKate Stone     // Note this thread really shouldn't already be marked as stopped - if we
983a6321a8eSPavel Labath     // were, that would imply that the kernel signaled us with the thread
984a6321a8eSPavel Labath     // stopping which we handled and marked as stopped, and that, without an
985a6321a8eSPavel Labath     // intervening resume, we received another stop.  It is more likely that we
986a6321a8eSPavel Labath     // are missing the marking of a run state somewhere if we find that the
987a6321a8eSPavel Labath     // thread was marked as stopped.
988b9cc0c75SPavel Labath     const StateType thread_state = thread.GetState();
989b9c1b51eSKate Stone     if (!StateIsStoppedState(thread_state, false)) {
990ed89c7feSPavel Labath       // An inferior thread has stopped because of a SIGSTOP we have sent it.
991b9c1b51eSKate Stone       // Generally, these are not important stops and we don't want to report
992a6321a8eSPavel Labath       // them as they are just used to stop other threads when one thread (the
993a6321a8eSPavel Labath       // one with the *real* stop reason) hits a breakpoint (watchpoint,
994a6321a8eSPavel Labath       // etc...). However, in the case of an asynchronous Interrupt(), this *is*
995a6321a8eSPavel Labath       // the real stop reason, so we leave the signal intact if this is the
996a6321a8eSPavel Labath       // thread that was chosen as the triggering thread.
997b9c1b51eSKate Stone       if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
998b9cc0c75SPavel Labath         if (m_pending_notification_tid == thread.GetID())
999b9cc0c75SPavel Labath           thread.SetStoppedBySignal(SIGSTOP, &info);
1000ed89c7feSPavel Labath         else
1001b9cc0c75SPavel Labath           thread.SetStoppedWithNoReason();
1002ed89c7feSPavel Labath 
1003b9cc0c75SPavel Labath         SetCurrentThreadID(thread.GetID());
10040e1d729bSPavel Labath         SignalIfAllThreadsStopped();
1005b9c1b51eSKate Stone       } else {
10060e1d729bSPavel Labath         // We can end up here if stop was initiated by LLGS but by this time a
10070e1d729bSPavel Labath         // thread stop has occurred - maybe initiated by another event.
100897206d57SZachary Turner         Status error = ResumeThread(thread, thread.GetState(), 0);
1009a6321a8eSPavel Labath         if (error.Fail())
1010a6321a8eSPavel Labath           LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(),
1011a6321a8eSPavel Labath                    error);
10120e1d729bSPavel Labath       }
1013b9c1b51eSKate Stone     } else {
1014a6321a8eSPavel Labath       LLDB_LOG(log,
1015a6321a8eSPavel Labath                "pid {0} tid {1}, thread was already marked as a stopped "
1016a6321a8eSPavel Labath                "state (state={2}), leaving stop signal as is",
10178198db30SPavel Labath                GetID(), thread.GetID(), thread_state);
10180e1d729bSPavel Labath       SignalIfAllThreadsStopped();
1019af245d11STodd Fiala     }
1020af245d11STodd Fiala 
102158a2f669STodd Fiala     // Done handling.
1022af245d11STodd Fiala     return;
1023af245d11STodd Fiala   }
1024af245d11STodd Fiala 
10254a705e7eSPavel Labath   // Check if debugger should stop at this signal or just ignore it
10264a705e7eSPavel Labath   // and resume the inferior.
10274a705e7eSPavel Labath   if (m_signals_to_ignore.find(signo) != m_signals_to_ignore.end()) {
10284a705e7eSPavel Labath      ResumeThread(thread, thread.GetState(), signo);
10294a705e7eSPavel Labath      return;
10304a705e7eSPavel Labath   }
10314a705e7eSPavel Labath 
103286fd8e45SChaoren Lin   // This thread is stopped.
1033a6321a8eSPavel Labath   LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo));
1034b9cc0c75SPavel Labath   thread.SetStoppedBySignal(signo, &info);
103586fd8e45SChaoren Lin 
103686fd8e45SChaoren Lin   // Send a stop to the debugger after we get all other threads to stop.
1037b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
1038511e5cdcSTodd Fiala }
1039af245d11STodd Fiala 
1040e7708688STamas Berghammer namespace {
1041e7708688STamas Berghammer 
1042b9c1b51eSKate Stone struct EmulatorBaton {
1043e7708688STamas Berghammer   NativeProcessLinux *m_process;
1044e7708688STamas Berghammer   NativeRegisterContext *m_reg_context;
10456648fcc3SPavel Labath 
10466648fcc3SPavel Labath   // eRegisterKindDWARF -> RegsiterValue
10476648fcc3SPavel Labath   std::unordered_map<uint32_t, RegisterValue> m_register_values;
1048e7708688STamas Berghammer 
1049b9c1b51eSKate Stone   EmulatorBaton(NativeProcessLinux *process, NativeRegisterContext *reg_context)
1050b9c1b51eSKate Stone       : m_process(process), m_reg_context(reg_context) {}
1051e7708688STamas Berghammer };
1052e7708688STamas Berghammer 
1053e7708688STamas Berghammer } // anonymous namespace
1054e7708688STamas Berghammer 
1055b9c1b51eSKate Stone static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
1056e7708688STamas Berghammer                                  const EmulateInstruction::Context &context,
1057b9c1b51eSKate Stone                                  lldb::addr_t addr, void *dst, size_t length) {
1058e7708688STamas Berghammer   EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
1059e7708688STamas Berghammer 
10603eb4b458SChaoren Lin   size_t bytes_read;
1061e7708688STamas Berghammer   emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
1062e7708688STamas Berghammer   return bytes_read;
1063e7708688STamas Berghammer }
1064e7708688STamas Berghammer 
1065b9c1b51eSKate Stone static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
1066e7708688STamas Berghammer                                  const RegisterInfo *reg_info,
1067b9c1b51eSKate Stone                                  RegisterValue &reg_value) {
1068e7708688STamas Berghammer   EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
1069e7708688STamas Berghammer 
1070b9c1b51eSKate Stone   auto it = emulator_baton->m_register_values.find(
1071b9c1b51eSKate Stone       reg_info->kinds[eRegisterKindDWARF]);
1072b9c1b51eSKate Stone   if (it != emulator_baton->m_register_values.end()) {
10736648fcc3SPavel Labath     reg_value = it->second;
10746648fcc3SPavel Labath     return true;
10756648fcc3SPavel Labath   }
10766648fcc3SPavel Labath 
1077e7708688STamas Berghammer   // The emulator only fill in the dwarf regsiter numbers (and in some case
1078e7708688STamas Berghammer   // the generic register numbers). Get the full register info from the
1079e7708688STamas Berghammer   // register context based on the dwarf register numbers.
1080b9c1b51eSKate Stone   const RegisterInfo *full_reg_info =
1081b9c1b51eSKate Stone       emulator_baton->m_reg_context->GetRegisterInfo(
1082e7708688STamas Berghammer           eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
1083e7708688STamas Berghammer 
108497206d57SZachary Turner   Status error =
1085b9c1b51eSKate Stone       emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
10866648fcc3SPavel Labath   if (error.Success())
10876648fcc3SPavel Labath     return true;
1088cdc22a88SMohit K. Bhakkad 
10896648fcc3SPavel Labath   return false;
1090e7708688STamas Berghammer }
1091e7708688STamas Berghammer 
1092b9c1b51eSKate Stone static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
1093e7708688STamas Berghammer                                   const EmulateInstruction::Context &context,
1094e7708688STamas Berghammer                                   const RegisterInfo *reg_info,
1095b9c1b51eSKate Stone                                   const RegisterValue &reg_value) {
1096e7708688STamas Berghammer   EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
1097b9c1b51eSKate Stone   emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
1098b9c1b51eSKate Stone       reg_value;
1099e7708688STamas Berghammer   return true;
1100e7708688STamas Berghammer }
1101e7708688STamas Berghammer 
1102b9c1b51eSKate Stone static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
1103e7708688STamas Berghammer                                   const EmulateInstruction::Context &context,
1104b9c1b51eSKate Stone                                   lldb::addr_t addr, const void *dst,
1105b9c1b51eSKate Stone                                   size_t length) {
1106e7708688STamas Berghammer   return length;
1107e7708688STamas Berghammer }
1108e7708688STamas Berghammer 
1109b9c1b51eSKate Stone static lldb::addr_t ReadFlags(NativeRegisterContext *regsiter_context) {
1110e7708688STamas Berghammer   const RegisterInfo *flags_info = regsiter_context->GetRegisterInfo(
1111e7708688STamas Berghammer       eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1112b9c1b51eSKate Stone   return regsiter_context->ReadRegisterAsUnsigned(flags_info,
1113b9c1b51eSKate Stone                                                   LLDB_INVALID_ADDRESS);
1114e7708688STamas Berghammer }
1115e7708688STamas Berghammer 
111697206d57SZachary Turner Status
111797206d57SZachary Turner NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadLinux &thread) {
111897206d57SZachary Turner   Status error;
1119b9cc0c75SPavel Labath   NativeRegisterContextSP register_context_sp = thread.GetRegisterContext();
1120e7708688STamas Berghammer 
1121e7708688STamas Berghammer   std::unique_ptr<EmulateInstruction> emulator_ap(
1122b9c1b51eSKate Stone       EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying,
1123b9c1b51eSKate Stone                                      nullptr));
1124e7708688STamas Berghammer 
1125e7708688STamas Berghammer   if (emulator_ap == nullptr)
112697206d57SZachary Turner     return Status("Instruction emulator not found!");
1127e7708688STamas Berghammer 
1128e7708688STamas Berghammer   EmulatorBaton baton(this, register_context_sp.get());
1129e7708688STamas Berghammer   emulator_ap->SetBaton(&baton);
1130e7708688STamas Berghammer   emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
1131e7708688STamas Berghammer   emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
1132e7708688STamas Berghammer   emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
1133e7708688STamas Berghammer   emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
1134e7708688STamas Berghammer 
1135e7708688STamas Berghammer   if (!emulator_ap->ReadInstruction())
113697206d57SZachary Turner     return Status("Read instruction failed!");
1137e7708688STamas Berghammer 
1138b9c1b51eSKate Stone   bool emulation_result =
1139b9c1b51eSKate Stone       emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
11406648fcc3SPavel Labath 
1141b9c1b51eSKate Stone   const RegisterInfo *reg_info_pc = register_context_sp->GetRegisterInfo(
1142b9c1b51eSKate Stone       eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1143b9c1b51eSKate Stone   const RegisterInfo *reg_info_flags = register_context_sp->GetRegisterInfo(
1144b9c1b51eSKate Stone       eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
11456648fcc3SPavel Labath 
1146b9c1b51eSKate Stone   auto pc_it =
1147b9c1b51eSKate Stone       baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1148b9c1b51eSKate Stone   auto flags_it =
1149b9c1b51eSKate Stone       baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
11506648fcc3SPavel Labath 
1151e7708688STamas Berghammer   lldb::addr_t next_pc;
1152e7708688STamas Berghammer   lldb::addr_t next_flags;
1153b9c1b51eSKate Stone   if (emulation_result) {
1154b9c1b51eSKate Stone     assert(pc_it != baton.m_register_values.end() &&
1155b9c1b51eSKate Stone            "Emulation was successfull but PC wasn't updated");
11566648fcc3SPavel Labath     next_pc = pc_it->second.GetAsUInt64();
11576648fcc3SPavel Labath 
11586648fcc3SPavel Labath     if (flags_it != baton.m_register_values.end())
11596648fcc3SPavel Labath       next_flags = flags_it->second.GetAsUInt64();
1160e7708688STamas Berghammer     else
1161e7708688STamas Berghammer       next_flags = ReadFlags(register_context_sp.get());
1162b9c1b51eSKate Stone   } else if (pc_it == baton.m_register_values.end()) {
1163e7708688STamas Berghammer     // Emulate instruction failed and it haven't changed PC. Advance PC
1164e7708688STamas Berghammer     // with the size of the current opcode because the emulation of all
1165e7708688STamas Berghammer     // PC modifying instruction should be successful. The failure most
1166e7708688STamas Berghammer     // likely caused by a not supported instruction which don't modify PC.
1167b9c1b51eSKate Stone     next_pc =
1168b9c1b51eSKate Stone         register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
1169e7708688STamas Berghammer     next_flags = ReadFlags(register_context_sp.get());
1170b9c1b51eSKate Stone   } else {
1171e7708688STamas Berghammer     // The instruction emulation failed after it modified the PC. It is an
1172e7708688STamas Berghammer     // unknown error where we can't continue because the next instruction is
1173e7708688STamas Berghammer     // modifying the PC but we don't  know how.
117497206d57SZachary Turner     return Status("Instruction emulation failed unexpectedly.");
1175e7708688STamas Berghammer   }
1176e7708688STamas Berghammer 
1177b9c1b51eSKate Stone   if (m_arch.GetMachine() == llvm::Triple::arm) {
1178b9c1b51eSKate Stone     if (next_flags & 0x20) {
1179e7708688STamas Berghammer       // Thumb mode
1180e7708688STamas Berghammer       error = SetSoftwareBreakpoint(next_pc, 2);
1181b9c1b51eSKate Stone     } else {
1182e7708688STamas Berghammer       // Arm mode
1183e7708688STamas Berghammer       error = SetSoftwareBreakpoint(next_pc, 4);
1184e7708688STamas Berghammer     }
1185b9c1b51eSKate Stone   } else if (m_arch.GetMachine() == llvm::Triple::mips64 ||
1186b9c1b51eSKate Stone              m_arch.GetMachine() == llvm::Triple::mips64el ||
1187b9c1b51eSKate Stone              m_arch.GetMachine() == llvm::Triple::mips ||
1188b9c1b51eSKate Stone              m_arch.GetMachine() == llvm::Triple::mipsel)
1189cdc22a88SMohit K. Bhakkad     error = SetSoftwareBreakpoint(next_pc, 4);
1190b9c1b51eSKate Stone   else {
1191e7708688STamas Berghammer     // No size hint is given for the next breakpoint
1192e7708688STamas Berghammer     error = SetSoftwareBreakpoint(next_pc, 0);
1193e7708688STamas Berghammer   }
1194e7708688STamas Berghammer 
119542eb6908SPavel Labath   // If setting the breakpoint fails because next_pc is out of
119642eb6908SPavel Labath   // the address space, ignore it and let the debugee segfault.
119742eb6908SPavel Labath   if (error.GetError() == EIO || error.GetError() == EFAULT) {
119897206d57SZachary Turner     return Status();
119942eb6908SPavel Labath   } else if (error.Fail())
1200e7708688STamas Berghammer     return error;
1201e7708688STamas Berghammer 
1202b9cc0c75SPavel Labath   m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
1203e7708688STamas Berghammer 
120497206d57SZachary Turner   return Status();
1205e7708688STamas Berghammer }
1206e7708688STamas Berghammer 
1207b9c1b51eSKate Stone bool NativeProcessLinux::SupportHardwareSingleStepping() const {
1208b9c1b51eSKate Stone   if (m_arch.GetMachine() == llvm::Triple::arm ||
1209b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mips64 ||
1210b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mips64el ||
1211b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mips ||
1212b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mipsel)
1213cdc22a88SMohit K. Bhakkad     return false;
1214cdc22a88SMohit K. Bhakkad   return true;
1215e7708688STamas Berghammer }
1216e7708688STamas Berghammer 
121797206d57SZachary Turner Status NativeProcessLinux::Resume(const ResumeActionList &resume_actions) {
1218a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1219a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0}", GetID());
1220af245d11STodd Fiala 
1221e7708688STamas Berghammer   bool software_single_step = !SupportHardwareSingleStepping();
1222af245d11STodd Fiala 
1223b9c1b51eSKate Stone   if (software_single_step) {
1224b9c1b51eSKate Stone     for (auto thread_sp : m_threads) {
1225e7708688STamas Berghammer       assert(thread_sp && "thread list should not contain NULL threads");
1226e7708688STamas Berghammer 
1227b9c1b51eSKate Stone       const ResumeAction *const action =
1228b9c1b51eSKate Stone           resume_actions.GetActionForThread(thread_sp->GetID(), true);
1229e7708688STamas Berghammer       if (action == nullptr)
1230e7708688STamas Berghammer         continue;
1231e7708688STamas Berghammer 
1232b9c1b51eSKate Stone       if (action->state == eStateStepping) {
123397206d57SZachary Turner         Status error = SetupSoftwareSingleStepping(
1234b9c1b51eSKate Stone             static_cast<NativeThreadLinux &>(*thread_sp));
1235e7708688STamas Berghammer         if (error.Fail())
1236e7708688STamas Berghammer           return error;
1237e7708688STamas Berghammer       }
1238e7708688STamas Berghammer     }
1239e7708688STamas Berghammer   }
1240e7708688STamas Berghammer 
1241b9c1b51eSKate Stone   for (auto thread_sp : m_threads) {
1242af245d11STodd Fiala     assert(thread_sp && "thread list should not contain NULL threads");
1243af245d11STodd Fiala 
1244b9c1b51eSKate Stone     const ResumeAction *const action =
1245b9c1b51eSKate Stone         resume_actions.GetActionForThread(thread_sp->GetID(), true);
12466a196ce6SChaoren Lin 
1247b9c1b51eSKate Stone     if (action == nullptr) {
1248a6321a8eSPavel Labath       LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
1249a6321a8eSPavel Labath                thread_sp->GetID());
12506a196ce6SChaoren Lin       continue;
12516a196ce6SChaoren Lin     }
1252af245d11STodd Fiala 
1253a6321a8eSPavel Labath     LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}",
12548198db30SPavel Labath              action->state, GetID(), thread_sp->GetID());
1255af245d11STodd Fiala 
1256b9c1b51eSKate Stone     switch (action->state) {
1257af245d11STodd Fiala     case eStateRunning:
1258b9c1b51eSKate Stone     case eStateStepping: {
1259af245d11STodd Fiala       // Run the thread, possibly feeding it the signal.
1260fa03ad2eSChaoren Lin       const int signo = action->signal;
1261b9c1b51eSKate Stone       ResumeThread(static_cast<NativeThreadLinux &>(*thread_sp), action->state,
1262b9c1b51eSKate Stone                    signo);
1263af245d11STodd Fiala       break;
1264ae29d395SChaoren Lin     }
1265af245d11STodd Fiala 
1266af245d11STodd Fiala     case eStateSuspended:
1267af245d11STodd Fiala     case eStateStopped:
1268a6321a8eSPavel Labath       llvm_unreachable("Unexpected state");
1269af245d11STodd Fiala 
1270af245d11STodd Fiala     default:
127197206d57SZachary Turner       return Status("NativeProcessLinux::%s (): unexpected state %s specified "
1272b9c1b51eSKate Stone                     "for pid %" PRIu64 ", tid %" PRIu64,
1273b9c1b51eSKate Stone                     __FUNCTION__, StateAsCString(action->state), GetID(),
1274b9c1b51eSKate Stone                     thread_sp->GetID());
1275af245d11STodd Fiala     }
1276af245d11STodd Fiala   }
1277af245d11STodd Fiala 
127897206d57SZachary Turner   return Status();
1279af245d11STodd Fiala }
1280af245d11STodd Fiala 
128197206d57SZachary Turner Status NativeProcessLinux::Halt() {
128297206d57SZachary Turner   Status error;
1283af245d11STodd Fiala 
1284af245d11STodd Fiala   if (kill(GetID(), SIGSTOP) != 0)
1285af245d11STodd Fiala     error.SetErrorToErrno();
1286af245d11STodd Fiala 
1287af245d11STodd Fiala   return error;
1288af245d11STodd Fiala }
1289af245d11STodd Fiala 
129097206d57SZachary Turner Status NativeProcessLinux::Detach() {
129197206d57SZachary Turner   Status error;
1292af245d11STodd Fiala 
1293af245d11STodd Fiala   // Stop monitoring the inferior.
129419cbe96aSPavel Labath   m_sigchld_handle.reset();
1295af245d11STodd Fiala 
12967a9495bcSPavel Labath   // Tell ptrace to detach from the process.
12977a9495bcSPavel Labath   if (GetID() == LLDB_INVALID_PROCESS_ID)
12987a9495bcSPavel Labath     return error;
12997a9495bcSPavel Labath 
1300b9c1b51eSKate Stone   for (auto thread_sp : m_threads) {
130197206d57SZachary Turner     Status e = Detach(thread_sp->GetID());
13027a9495bcSPavel Labath     if (e.Fail())
1303b9c1b51eSKate Stone       error =
1304b9c1b51eSKate Stone           e; // Save the error, but still attempt to detach from other threads.
13057a9495bcSPavel Labath   }
13067a9495bcSPavel Labath 
1307*99e37695SRavitheja Addepally   m_processor_trace_monitor.clear();
1308*99e37695SRavitheja Addepally   m_pt_proces_trace_id = LLDB_INVALID_UID;
1309*99e37695SRavitheja Addepally 
1310af245d11STodd Fiala   return error;
1311af245d11STodd Fiala }
1312af245d11STodd Fiala 
131397206d57SZachary Turner Status NativeProcessLinux::Signal(int signo) {
131497206d57SZachary Turner   Status error;
1315af245d11STodd Fiala 
1316a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1317a6321a8eSPavel Labath   LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo,
1318a6321a8eSPavel Labath            Host::GetSignalAsCString(signo), GetID());
1319af245d11STodd Fiala 
1320af245d11STodd Fiala   if (kill(GetID(), signo))
1321af245d11STodd Fiala     error.SetErrorToErrno();
1322af245d11STodd Fiala 
1323af245d11STodd Fiala   return error;
1324af245d11STodd Fiala }
1325af245d11STodd Fiala 
132697206d57SZachary Turner Status NativeProcessLinux::Interrupt() {
1327e9547b80SChaoren Lin   // Pick a running thread (or if none, a not-dead stopped thread) as
1328e9547b80SChaoren Lin   // the chosen thread that will be the stop-reason thread.
1329a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1330e9547b80SChaoren Lin 
1331e9547b80SChaoren Lin   NativeThreadProtocolSP running_thread_sp;
1332e9547b80SChaoren Lin   NativeThreadProtocolSP stopped_thread_sp;
1333e9547b80SChaoren Lin 
1334a6321a8eSPavel Labath   LLDB_LOG(log, "selecting running thread for interrupt target");
1335b9c1b51eSKate Stone   for (auto thread_sp : m_threads) {
1336e9547b80SChaoren Lin     // The thread shouldn't be null but lets just cover that here.
1337e9547b80SChaoren Lin     if (!thread_sp)
1338e9547b80SChaoren Lin       continue;
1339e9547b80SChaoren Lin 
1340e9547b80SChaoren Lin     // If we have a running or stepping thread, we'll call that the
1341e9547b80SChaoren Lin     // target of the interrupt.
1342e9547b80SChaoren Lin     const auto thread_state = thread_sp->GetState();
1343b9c1b51eSKate Stone     if (thread_state == eStateRunning || thread_state == eStateStepping) {
1344e9547b80SChaoren Lin       running_thread_sp = thread_sp;
1345e9547b80SChaoren Lin       break;
1346b9c1b51eSKate Stone     } else if (!stopped_thread_sp && StateIsStoppedState(thread_state, true)) {
1347b9c1b51eSKate Stone       // Remember the first non-dead stopped thread.  We'll use that as a backup
1348b9c1b51eSKate Stone       // if there are no running threads.
1349e9547b80SChaoren Lin       stopped_thread_sp = thread_sp;
1350e9547b80SChaoren Lin     }
1351e9547b80SChaoren Lin   }
1352e9547b80SChaoren Lin 
1353b9c1b51eSKate Stone   if (!running_thread_sp && !stopped_thread_sp) {
135497206d57SZachary Turner     Status error("found no running/stepping or live stopped threads as target "
1355b9c1b51eSKate Stone                  "for interrupt");
1356a6321a8eSPavel Labath     LLDB_LOG(log, "skipping due to error: {0}", error);
13575830aa75STamas Berghammer 
1358e9547b80SChaoren Lin     return error;
1359e9547b80SChaoren Lin   }
1360e9547b80SChaoren Lin 
1361b9c1b51eSKate Stone   NativeThreadProtocolSP deferred_signal_thread_sp =
1362b9c1b51eSKate Stone       running_thread_sp ? running_thread_sp : stopped_thread_sp;
1363e9547b80SChaoren Lin 
1364a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(),
1365e9547b80SChaoren Lin            running_thread_sp ? "running" : "stopped",
1366e9547b80SChaoren Lin            deferred_signal_thread_sp->GetID());
1367e9547b80SChaoren Lin 
1368ed89c7feSPavel Labath   StopRunningThreads(deferred_signal_thread_sp->GetID());
136945f5cb31SPavel Labath 
137097206d57SZachary Turner   return Status();
1371e9547b80SChaoren Lin }
1372e9547b80SChaoren Lin 
137397206d57SZachary Turner Status NativeProcessLinux::Kill() {
1374a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1375a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0}", GetID());
1376af245d11STodd Fiala 
137797206d57SZachary Turner   Status error;
1378af245d11STodd Fiala 
1379b9c1b51eSKate Stone   switch (m_state) {
1380af245d11STodd Fiala   case StateType::eStateInvalid:
1381af245d11STodd Fiala   case StateType::eStateExited:
1382af245d11STodd Fiala   case StateType::eStateCrashed:
1383af245d11STodd Fiala   case StateType::eStateDetached:
1384af245d11STodd Fiala   case StateType::eStateUnloaded:
1385af245d11STodd Fiala     // Nothing to do - the process is already dead.
1386a6321a8eSPavel Labath     LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
13878198db30SPavel Labath              m_state);
1388af245d11STodd Fiala     return error;
1389af245d11STodd Fiala 
1390af245d11STodd Fiala   case StateType::eStateConnected:
1391af245d11STodd Fiala   case StateType::eStateAttaching:
1392af245d11STodd Fiala   case StateType::eStateLaunching:
1393af245d11STodd Fiala   case StateType::eStateStopped:
1394af245d11STodd Fiala   case StateType::eStateRunning:
1395af245d11STodd Fiala   case StateType::eStateStepping:
1396af245d11STodd Fiala   case StateType::eStateSuspended:
1397af245d11STodd Fiala     // We can try to kill a process in these states.
1398af245d11STodd Fiala     break;
1399af245d11STodd Fiala   }
1400af245d11STodd Fiala 
1401b9c1b51eSKate Stone   if (kill(GetID(), SIGKILL) != 0) {
1402af245d11STodd Fiala     error.SetErrorToErrno();
1403af245d11STodd Fiala     return error;
1404af245d11STodd Fiala   }
1405af245d11STodd Fiala 
1406af245d11STodd Fiala   return error;
1407af245d11STodd Fiala }
1408af245d11STodd Fiala 
140997206d57SZachary Turner static Status
141015930862SPavel Labath ParseMemoryRegionInfoFromProcMapsLine(llvm::StringRef &maps_line,
1411b9c1b51eSKate Stone                                       MemoryRegionInfo &memory_region_info) {
1412af245d11STodd Fiala   memory_region_info.Clear();
1413af245d11STodd Fiala 
141415930862SPavel Labath   StringExtractor line_extractor(maps_line);
1415af245d11STodd Fiala 
1416b9c1b51eSKate Stone   // Format: {address_start_hex}-{address_end_hex} perms offset  dev   inode
1417b9c1b51eSKate Stone   // pathname
1418b9c1b51eSKate Stone   // perms: rwxp   (letter is present if set, '-' if not, final character is
1419b9c1b51eSKate Stone   // p=private, s=shared).
1420af245d11STodd Fiala 
1421af245d11STodd Fiala   // Parse out the starting address
1422af245d11STodd Fiala   lldb::addr_t start_address = line_extractor.GetHexMaxU64(false, 0);
1423af245d11STodd Fiala 
1424af245d11STodd Fiala   // Parse out hyphen separating start and end address from range.
1425af245d11STodd Fiala   if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != '-'))
142697206d57SZachary Turner     return Status(
1427b9c1b51eSKate Stone         "malformed /proc/{pid}/maps entry, missing dash between address range");
1428af245d11STodd Fiala 
1429af245d11STodd Fiala   // Parse out the ending address
1430af245d11STodd Fiala   lldb::addr_t end_address = line_extractor.GetHexMaxU64(false, start_address);
1431af245d11STodd Fiala 
1432af245d11STodd Fiala   // Parse out the space after the address.
1433af245d11STodd Fiala   if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != ' '))
143497206d57SZachary Turner     return Status(
143597206d57SZachary Turner         "malformed /proc/{pid}/maps entry, missing space after range");
1436af245d11STodd Fiala 
1437af245d11STodd Fiala   // Save the range.
1438af245d11STodd Fiala   memory_region_info.GetRange().SetRangeBase(start_address);
1439af245d11STodd Fiala   memory_region_info.GetRange().SetRangeEnd(end_address);
1440af245d11STodd Fiala 
1441b9c1b51eSKate Stone   // Any memory region in /proc/{pid}/maps is by definition mapped into the
1442b9c1b51eSKate Stone   // process.
1443ad007563SHoward Hellyer   memory_region_info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
1444ad007563SHoward Hellyer 
1445af245d11STodd Fiala   // Parse out each permission entry.
1446af245d11STodd Fiala   if (line_extractor.GetBytesLeft() < 4)
144797206d57SZachary Turner     return Status("malformed /proc/{pid}/maps entry, missing some portion of "
1448b9c1b51eSKate Stone                   "permissions");
1449af245d11STodd Fiala 
1450af245d11STodd Fiala   // Handle read permission.
1451af245d11STodd Fiala   const char read_perm_char = line_extractor.GetChar();
1452af245d11STodd Fiala   if (read_perm_char == 'r')
1453af245d11STodd Fiala     memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eYes);
1454c73301bbSTamas Berghammer   else if (read_perm_char == '-')
1455af245d11STodd Fiala     memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1456c73301bbSTamas Berghammer   else
145797206d57SZachary Turner     return Status("unexpected /proc/{pid}/maps read permission char");
1458af245d11STodd Fiala 
1459af245d11STodd Fiala   // Handle write permission.
1460af245d11STodd Fiala   const char write_perm_char = line_extractor.GetChar();
1461af245d11STodd Fiala   if (write_perm_char == 'w')
1462af245d11STodd Fiala     memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eYes);
1463c73301bbSTamas Berghammer   else if (write_perm_char == '-')
1464af245d11STodd Fiala     memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1465c73301bbSTamas Berghammer   else
146697206d57SZachary Turner     return Status("unexpected /proc/{pid}/maps write permission char");
1467af245d11STodd Fiala 
1468af245d11STodd Fiala   // Handle execute permission.
1469af245d11STodd Fiala   const char exec_perm_char = line_extractor.GetChar();
1470af245d11STodd Fiala   if (exec_perm_char == 'x')
1471af245d11STodd Fiala     memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes);
1472c73301bbSTamas Berghammer   else if (exec_perm_char == '-')
1473af245d11STodd Fiala     memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1474c73301bbSTamas Berghammer   else
147597206d57SZachary Turner     return Status("unexpected /proc/{pid}/maps exec permission char");
1476af245d11STodd Fiala 
1477d7d69f80STamas Berghammer   line_extractor.GetChar();              // Read the private bit
1478d7d69f80STamas Berghammer   line_extractor.SkipSpaces();           // Skip the separator
1479d7d69f80STamas Berghammer   line_extractor.GetHexMaxU64(false, 0); // Read the offset
1480d7d69f80STamas Berghammer   line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1481d7d69f80STamas Berghammer   line_extractor.GetChar();              // Read the device id separator
1482d7d69f80STamas Berghammer   line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1483d7d69f80STamas Berghammer   line_extractor.SkipSpaces();           // Skip the separator
1484d7d69f80STamas Berghammer   line_extractor.GetU64(0, 10);          // Read the inode number
1485d7d69f80STamas Berghammer 
1486d7d69f80STamas Berghammer   line_extractor.SkipSpaces();
1487b9739d40SPavel Labath   const char *name = line_extractor.Peek();
1488b9739d40SPavel Labath   if (name)
1489b9739d40SPavel Labath     memory_region_info.SetName(name);
1490d7d69f80STamas Berghammer 
149197206d57SZachary Turner   return Status();
1492af245d11STodd Fiala }
1493af245d11STodd Fiala 
149497206d57SZachary Turner Status NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr,
1495b9c1b51eSKate Stone                                                MemoryRegionInfo &range_info) {
1496b9c1b51eSKate Stone   // FIXME review that the final memory region returned extends to the end of
1497b9c1b51eSKate Stone   // the virtual address space,
1498af245d11STodd Fiala   // with no perms if it is not mapped.
1499af245d11STodd Fiala 
1500af245d11STodd Fiala   // Use an approach that reads memory regions from /proc/{pid}/maps.
1501af245d11STodd Fiala   // Assume proc maps entries are in ascending order.
1502af245d11STodd Fiala   // FIXME assert if we find differently.
1503af245d11STodd Fiala 
1504b9c1b51eSKate Stone   if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
1505af245d11STodd Fiala     // We're done.
150697206d57SZachary Turner     return Status("unsupported");
1507af245d11STodd Fiala   }
1508af245d11STodd Fiala 
150997206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
1510b9c1b51eSKate Stone   if (error.Fail()) {
1511af245d11STodd Fiala     return error;
1512af245d11STodd Fiala   }
1513af245d11STodd Fiala 
1514af245d11STodd Fiala   lldb::addr_t prev_base_address = 0;
1515af245d11STodd Fiala 
1516b9c1b51eSKate Stone   // FIXME start by finding the last region that is <= target address using
1517b9c1b51eSKate Stone   // binary search.  Data is sorted.
1518af245d11STodd Fiala   // There can be a ton of regions on pthreads apps with lots of threads.
1519b9c1b51eSKate Stone   for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1520b9c1b51eSKate Stone        ++it) {
1521a6f5795aSTamas Berghammer     MemoryRegionInfo &proc_entry_info = it->first;
1522af245d11STodd Fiala 
1523af245d11STodd Fiala     // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1524b9c1b51eSKate Stone     assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
1525b9c1b51eSKate Stone            "descending /proc/pid/maps entries detected, unexpected");
1526af245d11STodd Fiala     prev_base_address = proc_entry_info.GetRange().GetRangeBase();
1527b1554311SHafiz Abid Qadeer     UNUSED_IF_ASSERT_DISABLED(prev_base_address);
1528af245d11STodd Fiala 
1529b9c1b51eSKate Stone     // If the target address comes before this entry, indicate distance to next
1530b9c1b51eSKate Stone     // region.
1531b9c1b51eSKate Stone     if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1532af245d11STodd Fiala       range_info.GetRange().SetRangeBase(load_addr);
1533b9c1b51eSKate Stone       range_info.GetRange().SetByteSize(
1534b9c1b51eSKate Stone           proc_entry_info.GetRange().GetRangeBase() - load_addr);
1535af245d11STodd Fiala       range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1536af245d11STodd Fiala       range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1537af245d11STodd Fiala       range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1538ad007563SHoward Hellyer       range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1539af245d11STodd Fiala 
1540af245d11STodd Fiala       return error;
1541b9c1b51eSKate Stone     } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1542af245d11STodd Fiala       // The target address is within the memory region we're processing here.
1543af245d11STodd Fiala       range_info = proc_entry_info;
1544af245d11STodd Fiala       return error;
1545af245d11STodd Fiala     }
1546af245d11STodd Fiala 
1547b9c1b51eSKate Stone     // The target memory address comes somewhere after the region we just
1548b9c1b51eSKate Stone     // parsed.
1549af245d11STodd Fiala   }
1550af245d11STodd Fiala 
1551b9c1b51eSKate Stone   // If we made it here, we didn't find an entry that contained the given
1552b9c1b51eSKate Stone   // address. Return the
1553b9c1b51eSKate Stone   // load_addr as start and the amount of bytes betwwen load address and the end
1554b9c1b51eSKate Stone   // of the memory as
155509839c33STamas Berghammer   // size.
155609839c33STamas Berghammer   range_info.GetRange().SetRangeBase(load_addr);
1557ad007563SHoward Hellyer   range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
155809839c33STamas Berghammer   range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
155909839c33STamas Berghammer   range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
156009839c33STamas Berghammer   range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1561ad007563SHoward Hellyer   range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1562af245d11STodd Fiala   return error;
1563af245d11STodd Fiala }
1564af245d11STodd Fiala 
156597206d57SZachary Turner Status NativeProcessLinux::PopulateMemoryRegionCache() {
1566a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1567a6f5795aSTamas Berghammer 
1568a6f5795aSTamas Berghammer   // If our cache is empty, pull the latest.  There should always be at least
1569a6f5795aSTamas Berghammer   // one memory region if memory region handling is supported.
1570a6f5795aSTamas Berghammer   if (!m_mem_region_cache.empty()) {
1571a6321a8eSPavel Labath     LLDB_LOG(log, "reusing {0} cached memory region entries",
1572a6321a8eSPavel Labath              m_mem_region_cache.size());
157397206d57SZachary Turner     return Status();
1574a6f5795aSTamas Berghammer   }
1575a6f5795aSTamas Berghammer 
157615930862SPavel Labath   auto BufferOrError = getProcFile(GetID(), "maps");
157715930862SPavel Labath   if (!BufferOrError) {
157815930862SPavel Labath     m_supports_mem_region = LazyBool::eLazyBoolNo;
157915930862SPavel Labath     return BufferOrError.getError();
158015930862SPavel Labath   }
158115930862SPavel Labath   StringRef Rest = BufferOrError.get()->getBuffer();
158215930862SPavel Labath   while (! Rest.empty()) {
158315930862SPavel Labath     StringRef Line;
158415930862SPavel Labath     std::tie(Line, Rest) = Rest.split('\n');
1585a6f5795aSTamas Berghammer     MemoryRegionInfo info;
158697206d57SZachary Turner     const Status parse_error =
158797206d57SZachary Turner         ParseMemoryRegionInfoFromProcMapsLine(Line, info);
158815930862SPavel Labath     if (parse_error.Fail()) {
158915930862SPavel Labath       LLDB_LOG(log, "failed to parse proc maps line '{0}': {1}", Line,
159015930862SPavel Labath                parse_error);
159115930862SPavel Labath       m_supports_mem_region = LazyBool::eLazyBoolNo;
159215930862SPavel Labath       return parse_error;
159315930862SPavel Labath     }
1594a6f5795aSTamas Berghammer     m_mem_region_cache.emplace_back(
1595a6f5795aSTamas Berghammer         info, FileSpec(info.GetName().GetCString(), true));
1596a6f5795aSTamas Berghammer   }
1597a6f5795aSTamas Berghammer 
159815930862SPavel Labath   if (m_mem_region_cache.empty()) {
1599a6f5795aSTamas Berghammer     // No entries after attempting to read them.  This shouldn't happen if
1600a6f5795aSTamas Berghammer     // /proc/{pid}/maps is supported. Assume we don't support map entries
1601a6f5795aSTamas Berghammer     // via procfs.
160215930862SPavel Labath     m_supports_mem_region = LazyBool::eLazyBoolNo;
1603a6321a8eSPavel Labath     LLDB_LOG(log,
1604a6321a8eSPavel Labath              "failed to find any procfs maps entries, assuming no support "
1605a6321a8eSPavel Labath              "for memory region metadata retrieval");
160697206d57SZachary Turner     return Status("not supported");
1607a6f5795aSTamas Berghammer   }
1608a6f5795aSTamas Berghammer 
1609a6321a8eSPavel Labath   LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps",
1610a6321a8eSPavel Labath            m_mem_region_cache.size(), GetID());
1611a6f5795aSTamas Berghammer 
1612a6f5795aSTamas Berghammer   // We support memory retrieval, remember that.
1613a6f5795aSTamas Berghammer   m_supports_mem_region = LazyBool::eLazyBoolYes;
161497206d57SZachary Turner   return Status();
1615a6f5795aSTamas Berghammer }
1616a6f5795aSTamas Berghammer 
1617b9c1b51eSKate Stone void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
1618a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1619a6321a8eSPavel Labath   LLDB_LOG(log, "newBumpId={0}", newBumpId);
1620a6321a8eSPavel Labath   LLDB_LOG(log, "clearing {0} entries from memory region cache",
1621a6321a8eSPavel Labath            m_mem_region_cache.size());
1622af245d11STodd Fiala   m_mem_region_cache.clear();
1623af245d11STodd Fiala }
1624af245d11STodd Fiala 
162597206d57SZachary Turner Status NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions,
1626b9c1b51eSKate Stone                                           lldb::addr_t &addr) {
1627af245d11STodd Fiala // FIXME implementing this requires the equivalent of
1628af245d11STodd Fiala // InferiorCallPOSIX::InferiorCallMmap, which depends on
1629af245d11STodd Fiala // functional ThreadPlans working with Native*Protocol.
1630af245d11STodd Fiala #if 1
163197206d57SZachary Turner   return Status("not implemented yet");
1632af245d11STodd Fiala #else
1633af245d11STodd Fiala   addr = LLDB_INVALID_ADDRESS;
1634af245d11STodd Fiala 
1635af245d11STodd Fiala   unsigned prot = 0;
1636af245d11STodd Fiala   if (permissions & lldb::ePermissionsReadable)
1637af245d11STodd Fiala     prot |= eMmapProtRead;
1638af245d11STodd Fiala   if (permissions & lldb::ePermissionsWritable)
1639af245d11STodd Fiala     prot |= eMmapProtWrite;
1640af245d11STodd Fiala   if (permissions & lldb::ePermissionsExecutable)
1641af245d11STodd Fiala     prot |= eMmapProtExec;
1642af245d11STodd Fiala 
1643af245d11STodd Fiala   // TODO implement this directly in NativeProcessLinux
1644af245d11STodd Fiala   // (and lift to NativeProcessPOSIX if/when that class is
1645af245d11STodd Fiala   // refactored out).
1646af245d11STodd Fiala   if (InferiorCallMmap(this, addr, 0, size, prot,
1647af245d11STodd Fiala                        eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
1648af245d11STodd Fiala     m_addr_to_mmap_size[addr] = size;
164997206d57SZachary Turner     return Status();
1650af245d11STodd Fiala   } else {
1651af245d11STodd Fiala     addr = LLDB_INVALID_ADDRESS;
165297206d57SZachary Turner     return Status("unable to allocate %" PRIu64
1653b9c1b51eSKate Stone                   " bytes of memory with permissions %s",
1654b9c1b51eSKate Stone                   size, GetPermissionsAsCString(permissions));
1655af245d11STodd Fiala   }
1656af245d11STodd Fiala #endif
1657af245d11STodd Fiala }
1658af245d11STodd Fiala 
165997206d57SZachary Turner Status NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {
1660af245d11STodd Fiala   // FIXME see comments in AllocateMemory - required lower-level
1661af245d11STodd Fiala   // bits not in place yet (ThreadPlans)
166297206d57SZachary Turner   return Status("not implemented");
1663af245d11STodd Fiala }
1664af245d11STodd Fiala 
1665b9c1b51eSKate Stone lldb::addr_t NativeProcessLinux::GetSharedLibraryInfoAddress() {
1666af245d11STodd Fiala   // punt on this for now
1667af245d11STodd Fiala   return LLDB_INVALID_ADDRESS;
1668af245d11STodd Fiala }
1669af245d11STodd Fiala 
1670b9c1b51eSKate Stone size_t NativeProcessLinux::UpdateThreads() {
1671af245d11STodd Fiala   // The NativeProcessLinux monitoring threads are always up to date
1672af245d11STodd Fiala   // with respect to thread state and they keep the thread list
1673af245d11STodd Fiala   // populated properly. All this method needs to do is return the
1674af245d11STodd Fiala   // thread count.
1675af245d11STodd Fiala   return m_threads.size();
1676af245d11STodd Fiala }
1677af245d11STodd Fiala 
1678b9c1b51eSKate Stone bool NativeProcessLinux::GetArchitecture(ArchSpec &arch) const {
1679af245d11STodd Fiala   arch = m_arch;
1680af245d11STodd Fiala   return true;
1681af245d11STodd Fiala }
1682af245d11STodd Fiala 
168397206d57SZachary Turner Status NativeProcessLinux::GetSoftwareBreakpointPCOffset(
1684b9c1b51eSKate Stone     uint32_t &actual_opcode_size) {
1685af245d11STodd Fiala   // FIXME put this behind a breakpoint protocol class that can be
1686af245d11STodd Fiala   // set per architecture.  Need ARM, MIPS support here.
1687af245d11STodd Fiala   static const uint8_t g_i386_opcode[] = {0xCC};
1688bb00d0b6SUlrich Weigand   static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
1689af245d11STodd Fiala 
1690b9c1b51eSKate Stone   switch (m_arch.GetMachine()) {
1691af245d11STodd Fiala   case llvm::Triple::x86:
1692af245d11STodd Fiala   case llvm::Triple::x86_64:
1693af245d11STodd Fiala     actual_opcode_size = static_cast<uint32_t>(sizeof(g_i386_opcode));
169497206d57SZachary Turner     return Status();
1695af245d11STodd Fiala 
1696bb00d0b6SUlrich Weigand   case llvm::Triple::systemz:
1697bb00d0b6SUlrich Weigand     actual_opcode_size = static_cast<uint32_t>(sizeof(g_s390x_opcode));
169897206d57SZachary Turner     return Status();
1699bb00d0b6SUlrich Weigand 
1700ff7fd900STamas Berghammer   case llvm::Triple::arm:
1701ff7fd900STamas Berghammer   case llvm::Triple::aarch64:
1702e8659b5dSMohit K. Bhakkad   case llvm::Triple::mips64:
1703e8659b5dSMohit K. Bhakkad   case llvm::Triple::mips64el:
1704ce815e45SSagar Thakur   case llvm::Triple::mips:
1705ce815e45SSagar Thakur   case llvm::Triple::mipsel:
1706ff7fd900STamas Berghammer     // On these architectures the PC don't get updated for breakpoint hits
1707c60c9452SJaydeep Patil     actual_opcode_size = 0;
170897206d57SZachary Turner     return Status();
1709e8659b5dSMohit K. Bhakkad 
1710af245d11STodd Fiala   default:
1711af245d11STodd Fiala     assert(false && "CPU type not supported!");
171297206d57SZachary Turner     return Status("CPU type not supported");
1713af245d11STodd Fiala   }
1714af245d11STodd Fiala }
1715af245d11STodd Fiala 
171697206d57SZachary Turner Status NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,
1717b9c1b51eSKate Stone                                          bool hardware) {
1718af245d11STodd Fiala   if (hardware)
1719d5ffbad2SOmair Javaid     return SetHardwareBreakpoint(addr, size);
1720af245d11STodd Fiala   else
1721af245d11STodd Fiala     return SetSoftwareBreakpoint(addr, size);
1722af245d11STodd Fiala }
1723af245d11STodd Fiala 
172497206d57SZachary Turner Status NativeProcessLinux::RemoveBreakpoint(lldb::addr_t addr, bool hardware) {
1725d5ffbad2SOmair Javaid   if (hardware)
1726d5ffbad2SOmair Javaid     return RemoveHardwareBreakpoint(addr);
1727d5ffbad2SOmair Javaid   else
1728d5ffbad2SOmair Javaid     return NativeProcessProtocol::RemoveBreakpoint(addr);
1729d5ffbad2SOmair Javaid }
1730d5ffbad2SOmair Javaid 
173197206d57SZachary Turner Status NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(
1732b9c1b51eSKate Stone     size_t trap_opcode_size_hint, size_t &actual_opcode_size,
1733b9c1b51eSKate Stone     const uint8_t *&trap_opcode_bytes) {
173463c8be95STamas Berghammer   // FIXME put this behind a breakpoint protocol class that can be set per
173563c8be95STamas Berghammer   // architecture.  Need MIPS support here.
17362afc5966STodd Fiala   static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};
1737be379e15STamas Berghammer   // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1738be379e15STamas Berghammer   // linux kernel does otherwise.
1739be379e15STamas Berghammer   static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1740af245d11STodd Fiala   static const uint8_t g_i386_opcode[] = {0xCC};
17413df471c3SMohit K. Bhakkad   static const uint8_t g_mips64_opcode[] = {0x00, 0x00, 0x00, 0x0d};
17422c2acf96SMohit K. Bhakkad   static const uint8_t g_mips64el_opcode[] = {0x0d, 0x00, 0x00, 0x00};
1743bb00d0b6SUlrich Weigand   static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
1744be379e15STamas Berghammer   static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
1745af245d11STodd Fiala 
1746b9c1b51eSKate Stone   switch (m_arch.GetMachine()) {
17472afc5966STodd Fiala   case llvm::Triple::aarch64:
17482afc5966STodd Fiala     trap_opcode_bytes = g_aarch64_opcode;
17492afc5966STodd Fiala     actual_opcode_size = sizeof(g_aarch64_opcode);
175097206d57SZachary Turner     return Status();
17512afc5966STodd Fiala 
175263c8be95STamas Berghammer   case llvm::Triple::arm:
1753b9c1b51eSKate Stone     switch (trap_opcode_size_hint) {
175463c8be95STamas Berghammer     case 2:
175563c8be95STamas Berghammer       trap_opcode_bytes = g_thumb_breakpoint_opcode;
175663c8be95STamas Berghammer       actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
175797206d57SZachary Turner       return Status();
175863c8be95STamas Berghammer     case 4:
175963c8be95STamas Berghammer       trap_opcode_bytes = g_arm_breakpoint_opcode;
176063c8be95STamas Berghammer       actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
176197206d57SZachary Turner       return Status();
176263c8be95STamas Berghammer     default:
176363c8be95STamas Berghammer       assert(false && "Unrecognised trap opcode size hint!");
176497206d57SZachary Turner       return Status("Unrecognised trap opcode size hint!");
176563c8be95STamas Berghammer     }
176663c8be95STamas Berghammer 
1767af245d11STodd Fiala   case llvm::Triple::x86:
1768af245d11STodd Fiala   case llvm::Triple::x86_64:
1769af245d11STodd Fiala     trap_opcode_bytes = g_i386_opcode;
1770af245d11STodd Fiala     actual_opcode_size = sizeof(g_i386_opcode);
177197206d57SZachary Turner     return Status();
1772af245d11STodd Fiala 
1773ce815e45SSagar Thakur   case llvm::Triple::mips:
17743df471c3SMohit K. Bhakkad   case llvm::Triple::mips64:
17753df471c3SMohit K. Bhakkad     trap_opcode_bytes = g_mips64_opcode;
17763df471c3SMohit K. Bhakkad     actual_opcode_size = sizeof(g_mips64_opcode);
177797206d57SZachary Turner     return Status();
17783df471c3SMohit K. Bhakkad 
1779ce815e45SSagar Thakur   case llvm::Triple::mipsel:
17802c2acf96SMohit K. Bhakkad   case llvm::Triple::mips64el:
17812c2acf96SMohit K. Bhakkad     trap_opcode_bytes = g_mips64el_opcode;
17822c2acf96SMohit K. Bhakkad     actual_opcode_size = sizeof(g_mips64el_opcode);
178397206d57SZachary Turner     return Status();
17842c2acf96SMohit K. Bhakkad 
1785bb00d0b6SUlrich Weigand   case llvm::Triple::systemz:
1786bb00d0b6SUlrich Weigand     trap_opcode_bytes = g_s390x_opcode;
1787bb00d0b6SUlrich Weigand     actual_opcode_size = sizeof(g_s390x_opcode);
178897206d57SZachary Turner     return Status();
1789bb00d0b6SUlrich Weigand 
1790af245d11STodd Fiala   default:
1791af245d11STodd Fiala     assert(false && "CPU type not supported!");
179297206d57SZachary Turner     return Status("CPU type not supported");
1793af245d11STodd Fiala   }
1794af245d11STodd Fiala }
1795af245d11STodd Fiala 
1796af245d11STodd Fiala #if 0
1797af245d11STodd Fiala ProcessMessage::CrashReason
1798af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
1799af245d11STodd Fiala {
1800af245d11STodd Fiala     ProcessMessage::CrashReason reason;
1801af245d11STodd Fiala     assert(info->si_signo == SIGSEGV);
1802af245d11STodd Fiala 
1803af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
1804af245d11STodd Fiala 
1805af245d11STodd Fiala     switch (info->si_code)
1806af245d11STodd Fiala     {
1807af245d11STodd Fiala     default:
1808af245d11STodd Fiala         assert(false && "unexpected si_code for SIGSEGV");
1809af245d11STodd Fiala         break;
1810af245d11STodd Fiala     case SI_KERNEL:
1811af245d11STodd Fiala         // Linux will occasionally send spurious SI_KERNEL codes.
1812af245d11STodd Fiala         // (this is poorly documented in sigaction)
1813af245d11STodd Fiala         // One way to get this is via unaligned SIMD loads.
1814af245d11STodd Fiala         reason = ProcessMessage::eInvalidAddress; // for lack of anything better
1815af245d11STodd Fiala         break;
1816af245d11STodd Fiala     case SEGV_MAPERR:
1817af245d11STodd Fiala         reason = ProcessMessage::eInvalidAddress;
1818af245d11STodd Fiala         break;
1819af245d11STodd Fiala     case SEGV_ACCERR:
1820af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedAddress;
1821af245d11STodd Fiala         break;
1822af245d11STodd Fiala     }
1823af245d11STodd Fiala 
1824af245d11STodd Fiala     return reason;
1825af245d11STodd Fiala }
1826af245d11STodd Fiala #endif
1827af245d11STodd Fiala 
1828af245d11STodd Fiala #if 0
1829af245d11STodd Fiala ProcessMessage::CrashReason
1830af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
1831af245d11STodd Fiala {
1832af245d11STodd Fiala     ProcessMessage::CrashReason reason;
1833af245d11STodd Fiala     assert(info->si_signo == SIGILL);
1834af245d11STodd Fiala 
1835af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
1836af245d11STodd Fiala 
1837af245d11STodd Fiala     switch (info->si_code)
1838af245d11STodd Fiala     {
1839af245d11STodd Fiala     default:
1840af245d11STodd Fiala         assert(false && "unexpected si_code for SIGILL");
1841af245d11STodd Fiala         break;
1842af245d11STodd Fiala     case ILL_ILLOPC:
1843af245d11STodd Fiala         reason = ProcessMessage::eIllegalOpcode;
1844af245d11STodd Fiala         break;
1845af245d11STodd Fiala     case ILL_ILLOPN:
1846af245d11STodd Fiala         reason = ProcessMessage::eIllegalOperand;
1847af245d11STodd Fiala         break;
1848af245d11STodd Fiala     case ILL_ILLADR:
1849af245d11STodd Fiala         reason = ProcessMessage::eIllegalAddressingMode;
1850af245d11STodd Fiala         break;
1851af245d11STodd Fiala     case ILL_ILLTRP:
1852af245d11STodd Fiala         reason = ProcessMessage::eIllegalTrap;
1853af245d11STodd Fiala         break;
1854af245d11STodd Fiala     case ILL_PRVOPC:
1855af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedOpcode;
1856af245d11STodd Fiala         break;
1857af245d11STodd Fiala     case ILL_PRVREG:
1858af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedRegister;
1859af245d11STodd Fiala         break;
1860af245d11STodd Fiala     case ILL_COPROC:
1861af245d11STodd Fiala         reason = ProcessMessage::eCoprocessorError;
1862af245d11STodd Fiala         break;
1863af245d11STodd Fiala     case ILL_BADSTK:
1864af245d11STodd Fiala         reason = ProcessMessage::eInternalStackError;
1865af245d11STodd Fiala         break;
1866af245d11STodd Fiala     }
1867af245d11STodd Fiala 
1868af245d11STodd Fiala     return reason;
1869af245d11STodd Fiala }
1870af245d11STodd Fiala #endif
1871af245d11STodd Fiala 
1872af245d11STodd Fiala #if 0
1873af245d11STodd Fiala ProcessMessage::CrashReason
1874af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
1875af245d11STodd Fiala {
1876af245d11STodd Fiala     ProcessMessage::CrashReason reason;
1877af245d11STodd Fiala     assert(info->si_signo == SIGFPE);
1878af245d11STodd Fiala 
1879af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
1880af245d11STodd Fiala 
1881af245d11STodd Fiala     switch (info->si_code)
1882af245d11STodd Fiala     {
1883af245d11STodd Fiala     default:
1884af245d11STodd Fiala         assert(false && "unexpected si_code for SIGFPE");
1885af245d11STodd Fiala         break;
1886af245d11STodd Fiala     case FPE_INTDIV:
1887af245d11STodd Fiala         reason = ProcessMessage::eIntegerDivideByZero;
1888af245d11STodd Fiala         break;
1889af245d11STodd Fiala     case FPE_INTOVF:
1890af245d11STodd Fiala         reason = ProcessMessage::eIntegerOverflow;
1891af245d11STodd Fiala         break;
1892af245d11STodd Fiala     case FPE_FLTDIV:
1893af245d11STodd Fiala         reason = ProcessMessage::eFloatDivideByZero;
1894af245d11STodd Fiala         break;
1895af245d11STodd Fiala     case FPE_FLTOVF:
1896af245d11STodd Fiala         reason = ProcessMessage::eFloatOverflow;
1897af245d11STodd Fiala         break;
1898af245d11STodd Fiala     case FPE_FLTUND:
1899af245d11STodd Fiala         reason = ProcessMessage::eFloatUnderflow;
1900af245d11STodd Fiala         break;
1901af245d11STodd Fiala     case FPE_FLTRES:
1902af245d11STodd Fiala         reason = ProcessMessage::eFloatInexactResult;
1903af245d11STodd Fiala         break;
1904af245d11STodd Fiala     case FPE_FLTINV:
1905af245d11STodd Fiala         reason = ProcessMessage::eFloatInvalidOperation;
1906af245d11STodd Fiala         break;
1907af245d11STodd Fiala     case FPE_FLTSUB:
1908af245d11STodd Fiala         reason = ProcessMessage::eFloatSubscriptRange;
1909af245d11STodd Fiala         break;
1910af245d11STodd Fiala     }
1911af245d11STodd Fiala 
1912af245d11STodd Fiala     return reason;
1913af245d11STodd Fiala }
1914af245d11STodd Fiala #endif
1915af245d11STodd Fiala 
1916af245d11STodd Fiala #if 0
1917af245d11STodd Fiala ProcessMessage::CrashReason
1918af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
1919af245d11STodd Fiala {
1920af245d11STodd Fiala     ProcessMessage::CrashReason reason;
1921af245d11STodd Fiala     assert(info->si_signo == SIGBUS);
1922af245d11STodd Fiala 
1923af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
1924af245d11STodd Fiala 
1925af245d11STodd Fiala     switch (info->si_code)
1926af245d11STodd Fiala     {
1927af245d11STodd Fiala     default:
1928af245d11STodd Fiala         assert(false && "unexpected si_code for SIGBUS");
1929af245d11STodd Fiala         break;
1930af245d11STodd Fiala     case BUS_ADRALN:
1931af245d11STodd Fiala         reason = ProcessMessage::eIllegalAlignment;
1932af245d11STodd Fiala         break;
1933af245d11STodd Fiala     case BUS_ADRERR:
1934af245d11STodd Fiala         reason = ProcessMessage::eIllegalAddress;
1935af245d11STodd Fiala         break;
1936af245d11STodd Fiala     case BUS_OBJERR:
1937af245d11STodd Fiala         reason = ProcessMessage::eHardwareError;
1938af245d11STodd Fiala         break;
1939af245d11STodd Fiala     }
1940af245d11STodd Fiala 
1941af245d11STodd Fiala     return reason;
1942af245d11STodd Fiala }
1943af245d11STodd Fiala #endif
1944af245d11STodd Fiala 
194597206d57SZachary Turner Status NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
1946b9c1b51eSKate Stone                                       size_t &bytes_read) {
1947df7c6995SPavel Labath   if (ProcessVmReadvSupported()) {
1948b9c1b51eSKate Stone     // The process_vm_readv path is about 50 times faster than ptrace api. We
1949b9c1b51eSKate Stone     // want to use
1950df7c6995SPavel Labath     // this syscall if it is supported.
1951df7c6995SPavel Labath 
1952df7c6995SPavel Labath     const ::pid_t pid = GetID();
1953df7c6995SPavel Labath 
1954df7c6995SPavel Labath     struct iovec local_iov, remote_iov;
1955df7c6995SPavel Labath     local_iov.iov_base = buf;
1956df7c6995SPavel Labath     local_iov.iov_len = size;
1957df7c6995SPavel Labath     remote_iov.iov_base = reinterpret_cast<void *>(addr);
1958df7c6995SPavel Labath     remote_iov.iov_len = size;
1959df7c6995SPavel Labath 
1960df7c6995SPavel Labath     bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
1961df7c6995SPavel Labath     const bool success = bytes_read == size;
1962df7c6995SPavel Labath 
1963a6321a8eSPavel Labath     Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1964a6321a8eSPavel Labath     LLDB_LOG(log,
1965a6321a8eSPavel Labath              "using process_vm_readv to read {0} bytes from inferior "
1966a6321a8eSPavel Labath              "address {1:x}: {2}",
196710c41f37SPavel Labath              size, addr, success ? "Success" : llvm::sys::StrError(errno));
1968df7c6995SPavel Labath 
1969df7c6995SPavel Labath     if (success)
197097206d57SZachary Turner       return Status();
1971a6321a8eSPavel Labath     // else the call failed for some reason, let's retry the read using ptrace
1972b9c1b51eSKate Stone     // api.
1973df7c6995SPavel Labath   }
1974df7c6995SPavel Labath 
197519cbe96aSPavel Labath   unsigned char *dst = static_cast<unsigned char *>(buf);
197619cbe96aSPavel Labath   size_t remainder;
197719cbe96aSPavel Labath   long data;
197819cbe96aSPavel Labath 
1979a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1980a6321a8eSPavel Labath   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
198119cbe96aSPavel Labath 
1982b9c1b51eSKate Stone   for (bytes_read = 0; bytes_read < size; bytes_read += remainder) {
198397206d57SZachary Turner     Status error = NativeProcessLinux::PtraceWrapper(
1984b9c1b51eSKate Stone         PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data);
1985a6321a8eSPavel Labath     if (error.Fail())
198619cbe96aSPavel Labath       return error;
198719cbe96aSPavel Labath 
198819cbe96aSPavel Labath     remainder = size - bytes_read;
198919cbe96aSPavel Labath     remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
199019cbe96aSPavel Labath 
199119cbe96aSPavel Labath     // Copy the data into our buffer
1992f6ef187bSMohit K. Bhakkad     memcpy(dst, &data, remainder);
199319cbe96aSPavel Labath 
1994a6321a8eSPavel Labath     LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
199519cbe96aSPavel Labath     addr += k_ptrace_word_size;
199619cbe96aSPavel Labath     dst += k_ptrace_word_size;
199719cbe96aSPavel Labath   }
199897206d57SZachary Turner   return Status();
1999af245d11STodd Fiala }
2000af245d11STodd Fiala 
200197206d57SZachary Turner Status NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf,
2002b9c1b51eSKate Stone                                                  size_t size,
2003b9c1b51eSKate Stone                                                  size_t &bytes_read) {
200497206d57SZachary Turner   Status error = ReadMemory(addr, buf, size, bytes_read);
2005b9c1b51eSKate Stone   if (error.Fail())
2006b9c1b51eSKate Stone     return error;
20073eb4b458SChaoren Lin   return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
20083eb4b458SChaoren Lin }
20093eb4b458SChaoren Lin 
201097206d57SZachary Turner Status NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,
2011b9c1b51eSKate Stone                                        size_t size, size_t &bytes_written) {
201219cbe96aSPavel Labath   const unsigned char *src = static_cast<const unsigned char *>(buf);
201319cbe96aSPavel Labath   size_t remainder;
201497206d57SZachary Turner   Status error;
201519cbe96aSPavel Labath 
2016a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
2017a6321a8eSPavel Labath   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
201819cbe96aSPavel Labath 
2019b9c1b51eSKate Stone   for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
202019cbe96aSPavel Labath     remainder = size - bytes_written;
202119cbe96aSPavel Labath     remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
202219cbe96aSPavel Labath 
2023b9c1b51eSKate Stone     if (remainder == k_ptrace_word_size) {
202419cbe96aSPavel Labath       unsigned long data = 0;
2025f6ef187bSMohit K. Bhakkad       memcpy(&data, src, k_ptrace_word_size);
202619cbe96aSPavel Labath 
2027a6321a8eSPavel Labath       LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
2028b9c1b51eSKate Stone       error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(),
2029b9c1b51eSKate Stone                                                 (void *)addr, (void *)data);
2030a6321a8eSPavel Labath       if (error.Fail())
203119cbe96aSPavel Labath         return error;
2032b9c1b51eSKate Stone     } else {
203319cbe96aSPavel Labath       unsigned char buff[8];
203419cbe96aSPavel Labath       size_t bytes_read;
203519cbe96aSPavel Labath       error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
2036a6321a8eSPavel Labath       if (error.Fail())
203719cbe96aSPavel Labath         return error;
203819cbe96aSPavel Labath 
203919cbe96aSPavel Labath       memcpy(buff, src, remainder);
204019cbe96aSPavel Labath 
204119cbe96aSPavel Labath       size_t bytes_written_rec;
204219cbe96aSPavel Labath       error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
2043a6321a8eSPavel Labath       if (error.Fail())
204419cbe96aSPavel Labath         return error;
204519cbe96aSPavel Labath 
2046a6321a8eSPavel Labath       LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src,
2047b9c1b51eSKate Stone                *(unsigned long *)buff);
204819cbe96aSPavel Labath     }
204919cbe96aSPavel Labath 
205019cbe96aSPavel Labath     addr += k_ptrace_word_size;
205119cbe96aSPavel Labath     src += k_ptrace_word_size;
205219cbe96aSPavel Labath   }
205319cbe96aSPavel Labath   return error;
2054af245d11STodd Fiala }
2055af245d11STodd Fiala 
205697206d57SZachary Turner Status NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) {
205719cbe96aSPavel Labath   return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
2058af245d11STodd Fiala }
2059af245d11STodd Fiala 
206097206d57SZachary Turner Status NativeProcessLinux::GetEventMessage(lldb::tid_t tid,
2061b9c1b51eSKate Stone                                            unsigned long *message) {
206219cbe96aSPavel Labath   return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
2063af245d11STodd Fiala }
2064af245d11STodd Fiala 
206597206d57SZachary Turner Status NativeProcessLinux::Detach(lldb::tid_t tid) {
206697ccc294SChaoren Lin   if (tid == LLDB_INVALID_THREAD_ID)
206797206d57SZachary Turner     return Status();
206897ccc294SChaoren Lin 
206919cbe96aSPavel Labath   return PtraceWrapper(PTRACE_DETACH, tid);
2070af245d11STodd Fiala }
2071af245d11STodd Fiala 
2072b9c1b51eSKate Stone bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {
2073b9c1b51eSKate Stone   for (auto thread_sp : m_threads) {
2074af245d11STodd Fiala     assert(thread_sp && "thread list should not contain NULL threads");
2075b9c1b51eSKate Stone     if (thread_sp->GetID() == thread_id) {
2076af245d11STodd Fiala       // We have this thread.
2077af245d11STodd Fiala       return true;
2078af245d11STodd Fiala     }
2079af245d11STodd Fiala   }
2080af245d11STodd Fiala 
2081af245d11STodd Fiala   // We don't have this thread.
2082af245d11STodd Fiala   return false;
2083af245d11STodd Fiala }
2084af245d11STodd Fiala 
2085b9c1b51eSKate Stone bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) {
2086a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2087a6321a8eSPavel Labath   LLDB_LOG(log, "tid: {0})", thread_id);
20881dbc6c9cSPavel Labath 
20891dbc6c9cSPavel Labath   bool found = false;
2090b9c1b51eSKate Stone   for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
2091b9c1b51eSKate Stone     if (*it && ((*it)->GetID() == thread_id)) {
2092af245d11STodd Fiala       m_threads.erase(it);
20931dbc6c9cSPavel Labath       found = true;
20941dbc6c9cSPavel Labath       break;
2095af245d11STodd Fiala     }
2096af245d11STodd Fiala   }
2097af245d11STodd Fiala 
2098*99e37695SRavitheja Addepally   if (found)
2099*99e37695SRavitheja Addepally     StopTracingForThread(thread_id);
21009eb1ecb9SPavel Labath   SignalIfAllThreadsStopped();
21011dbc6c9cSPavel Labath   return found;
2102af245d11STodd Fiala }
2103af245d11STodd Fiala 
2104b9c1b51eSKate Stone NativeThreadLinuxSP NativeProcessLinux::AddThread(lldb::tid_t thread_id) {
2105a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
2106a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
2107af245d11STodd Fiala 
2108b9c1b51eSKate Stone   assert(!HasThreadNoLock(thread_id) &&
2109b9c1b51eSKate Stone          "attempted to add a thread by id that already exists");
2110af245d11STodd Fiala 
2111af245d11STodd Fiala   // If this is the first thread, save it as the current thread
2112af245d11STodd Fiala   if (m_threads.empty())
2113af245d11STodd Fiala     SetCurrentThreadID(thread_id);
2114af245d11STodd Fiala 
2115f9077782SPavel Labath   auto thread_sp = std::make_shared<NativeThreadLinux>(this, thread_id);
2116af245d11STodd Fiala   m_threads.push_back(thread_sp);
2117*99e37695SRavitheja Addepally 
2118*99e37695SRavitheja Addepally   if (m_pt_proces_trace_id != LLDB_INVALID_UID) {
2119*99e37695SRavitheja Addepally     auto traceMonitor = ProcessorTraceMonitor::Create(
2120*99e37695SRavitheja Addepally         GetID(), thread_id, m_pt_process_trace_config, true);
2121*99e37695SRavitheja Addepally     if (traceMonitor) {
2122*99e37695SRavitheja Addepally       m_pt_traced_thread_group.insert(thread_id);
2123*99e37695SRavitheja Addepally       m_processor_trace_monitor.insert(
2124*99e37695SRavitheja Addepally           std::make_pair(thread_id, std::move(*traceMonitor)));
2125*99e37695SRavitheja Addepally     } else {
2126*99e37695SRavitheja Addepally       LLDB_LOG(log, "failed to start trace on thread {0}", thread_id);
2127*99e37695SRavitheja Addepally       Status error(traceMonitor.takeError());
2128*99e37695SRavitheja Addepally       LLDB_LOG(log, "error {0}", error);
2129*99e37695SRavitheja Addepally     }
2130*99e37695SRavitheja Addepally   }
2131*99e37695SRavitheja Addepally 
2132af245d11STodd Fiala   return thread_sp;
2133af245d11STodd Fiala }
2134af245d11STodd Fiala 
213597206d57SZachary Turner Status
213697206d57SZachary Turner NativeProcessLinux::FixupBreakpointPCAsNeeded(NativeThreadLinux &thread) {
2137a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_BREAKPOINTS));
2138af245d11STodd Fiala 
213997206d57SZachary Turner   Status error;
2140af245d11STodd Fiala 
2141b9c1b51eSKate Stone   // Find out the size of a breakpoint (might depend on where we are in the
2142b9c1b51eSKate Stone   // code).
2143b9cc0c75SPavel Labath   NativeRegisterContextSP context_sp = thread.GetRegisterContext();
2144b9c1b51eSKate Stone   if (!context_sp) {
2145af245d11STodd Fiala     error.SetErrorString("cannot get a NativeRegisterContext for the thread");
2146a6321a8eSPavel Labath     LLDB_LOG(log, "failed: {0}", error);
2147af245d11STodd Fiala     return error;
2148af245d11STodd Fiala   }
2149af245d11STodd Fiala 
2150af245d11STodd Fiala   uint32_t breakpoint_size = 0;
2151b9cc0c75SPavel Labath   error = GetSoftwareBreakpointPCOffset(breakpoint_size);
2152b9c1b51eSKate Stone   if (error.Fail()) {
2153a6321a8eSPavel Labath     LLDB_LOG(log, "GetBreakpointSize() failed: {0}", error);
2154af245d11STodd Fiala     return error;
2155a6321a8eSPavel Labath   } else
2156a6321a8eSPavel Labath     LLDB_LOG(log, "breakpoint size: {0}", breakpoint_size);
2157af245d11STodd Fiala 
2158b9c1b51eSKate Stone   // First try probing for a breakpoint at a software breakpoint location: PC -
2159b9c1b51eSKate Stone   // breakpoint size.
2160b9c1b51eSKate Stone   const lldb::addr_t initial_pc_addr =
2161b9c1b51eSKate Stone       context_sp->GetPCfromBreakpointLocation();
2162af245d11STodd Fiala   lldb::addr_t breakpoint_addr = initial_pc_addr;
2163b9c1b51eSKate Stone   if (breakpoint_size > 0) {
2164af245d11STodd Fiala     // Do not allow breakpoint probe to wrap around.
21653eb4b458SChaoren Lin     if (breakpoint_addr >= breakpoint_size)
21663eb4b458SChaoren Lin       breakpoint_addr -= breakpoint_size;
2167af245d11STodd Fiala   }
2168af245d11STodd Fiala 
2169af245d11STodd Fiala   // Check if we stopped because of a breakpoint.
2170af245d11STodd Fiala   NativeBreakpointSP breakpoint_sp;
2171af245d11STodd Fiala   error = m_breakpoint_list.GetBreakpoint(breakpoint_addr, breakpoint_sp);
2172b9c1b51eSKate Stone   if (!error.Success() || !breakpoint_sp) {
2173af245d11STodd Fiala     // We didn't find one at a software probe location.  Nothing to do.
2174a6321a8eSPavel Labath     LLDB_LOG(log,
2175a6321a8eSPavel Labath              "pid {0} no lldb breakpoint found at current pc with "
2176a6321a8eSPavel Labath              "adjustment: {1}",
2177a6321a8eSPavel Labath              GetID(), breakpoint_addr);
217897206d57SZachary Turner     return Status();
2179af245d11STodd Fiala   }
2180af245d11STodd Fiala 
2181af245d11STodd Fiala   // If the breakpoint is not a software breakpoint, nothing to do.
2182b9c1b51eSKate Stone   if (!breakpoint_sp->IsSoftwareBreakpoint()) {
2183a6321a8eSPavel Labath     LLDB_LOG(
2184a6321a8eSPavel Labath         log,
2185a6321a8eSPavel Labath         "pid {0} breakpoint found at {1:x}, not software, nothing to adjust",
2186a6321a8eSPavel Labath         GetID(), breakpoint_addr);
218797206d57SZachary Turner     return Status();
2188af245d11STodd Fiala   }
2189af245d11STodd Fiala 
2190af245d11STodd Fiala   //
2191af245d11STodd Fiala   // We have a software breakpoint and need to adjust the PC.
2192af245d11STodd Fiala   //
2193af245d11STodd Fiala 
2194af245d11STodd Fiala   // Sanity check.
2195b9c1b51eSKate Stone   if (breakpoint_size == 0) {
2196af245d11STodd Fiala     // Nothing to do!  How did we get here?
2197a6321a8eSPavel Labath     LLDB_LOG(log,
2198a6321a8eSPavel Labath              "pid {0} breakpoint found at {1:x}, it is software, but the "
2199a6321a8eSPavel Labath              "size is zero, nothing to do (unexpected)",
2200a6321a8eSPavel Labath              GetID(), breakpoint_addr);
220197206d57SZachary Turner     return Status();
2202af245d11STodd Fiala   }
2203af245d11STodd Fiala 
2204af245d11STodd Fiala   // Change the program counter.
2205a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0} tid {1}: changing PC from {2:x} to {3:x}", GetID(),
2206a6321a8eSPavel Labath            thread.GetID(), initial_pc_addr, breakpoint_addr);
2207af245d11STodd Fiala 
2208af245d11STodd Fiala   error = context_sp->SetPC(breakpoint_addr);
2209b9c1b51eSKate Stone   if (error.Fail()) {
2210a6321a8eSPavel Labath     LLDB_LOG(log, "pid {0} tid {1}: failed to set PC: {2}", GetID(),
2211a6321a8eSPavel Labath              thread.GetID(), error);
2212af245d11STodd Fiala     return error;
2213af245d11STodd Fiala   }
2214af245d11STodd Fiala 
2215af245d11STodd Fiala   return error;
2216af245d11STodd Fiala }
2217fa03ad2eSChaoren Lin 
221897206d57SZachary Turner Status NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,
2219b9c1b51eSKate Stone                                                    FileSpec &file_spec) {
222097206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
2221a6f5795aSTamas Berghammer   if (error.Fail())
2222a6f5795aSTamas Berghammer     return error;
2223a6f5795aSTamas Berghammer 
22247cb18bf5STamas Berghammer   FileSpec module_file_spec(module_path, true);
22257cb18bf5STamas Berghammer 
22267cb18bf5STamas Berghammer   file_spec.Clear();
2227a6f5795aSTamas Berghammer   for (const auto &it : m_mem_region_cache) {
2228a6f5795aSTamas Berghammer     if (it.second.GetFilename() == module_file_spec.GetFilename()) {
2229a6f5795aSTamas Berghammer       file_spec = it.second;
223097206d57SZachary Turner       return Status();
2231a6f5795aSTamas Berghammer     }
2232a6f5795aSTamas Berghammer   }
223397206d57SZachary Turner   return Status("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
22347cb18bf5STamas Berghammer                 module_file_spec.GetFilename().AsCString(), GetID());
22357cb18bf5STamas Berghammer }
2236c076559aSPavel Labath 
223797206d57SZachary Turner Status NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
2238b9c1b51eSKate Stone                                               lldb::addr_t &load_addr) {
2239783bfc8cSTamas Berghammer   load_addr = LLDB_INVALID_ADDRESS;
224097206d57SZachary Turner   Status error = PopulateMemoryRegionCache();
2241a6f5795aSTamas Berghammer   if (error.Fail())
2242783bfc8cSTamas Berghammer     return error;
2243a6f5795aSTamas Berghammer 
2244a6f5795aSTamas Berghammer   FileSpec file(file_name, false);
2245a6f5795aSTamas Berghammer   for (const auto &it : m_mem_region_cache) {
2246a6f5795aSTamas Berghammer     if (it.second == file) {
2247a6f5795aSTamas Berghammer       load_addr = it.first.GetRange().GetRangeBase();
224897206d57SZachary Turner       return Status();
2249a6f5795aSTamas Berghammer     }
2250a6f5795aSTamas Berghammer   }
225197206d57SZachary Turner   return Status("No load address found for specified file.");
2252783bfc8cSTamas Berghammer }
2253783bfc8cSTamas Berghammer 
2254b9c1b51eSKate Stone NativeThreadLinuxSP NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {
2255b9c1b51eSKate Stone   return std::static_pointer_cast<NativeThreadLinux>(
2256b9c1b51eSKate Stone       NativeProcessProtocol::GetThreadByID(tid));
2257f9077782SPavel Labath }
2258f9077782SPavel Labath 
225997206d57SZachary Turner Status NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,
2260b9c1b51eSKate Stone                                         lldb::StateType state, int signo) {
2261a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2262a6321a8eSPavel Labath   LLDB_LOG(log, "tid: {0}", thread.GetID());
2263c076559aSPavel Labath 
2264c076559aSPavel Labath   // Before we do the resume below, first check if we have a pending
2265108c325dSPavel Labath   // stop notification that is currently waiting for
22660e1d729bSPavel Labath   // all threads to stop.  This is potentially a buggy situation since
2267c076559aSPavel Labath   // we're ostensibly waiting for threads to stop before we send out the
2268c076559aSPavel Labath   // pending notification, and here we are resuming one before we send
2269c076559aSPavel Labath   // out the pending stop notification.
2270a6321a8eSPavel Labath   if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
2271a6321a8eSPavel Labath     LLDB_LOG(log,
2272a6321a8eSPavel Labath              "about to resume tid {0} per explicit request but we have a "
2273a6321a8eSPavel Labath              "pending stop notification (tid {1}) that is actively "
2274a6321a8eSPavel Labath              "waiting for this thread to stop. Valid sequence of events?",
2275a6321a8eSPavel Labath              thread.GetID(), m_pending_notification_tid);
2276c076559aSPavel Labath   }
2277c076559aSPavel Labath 
2278c076559aSPavel Labath   // Request a resume.  We expect this to be synchronous and the system
2279c076559aSPavel Labath   // to reflect it is running after this completes.
2280b9c1b51eSKate Stone   switch (state) {
2281b9c1b51eSKate Stone   case eStateRunning: {
2282605b51b8SPavel Labath     const auto resume_result = thread.Resume(signo);
22830e1d729bSPavel Labath     if (resume_result.Success())
22840e1d729bSPavel Labath       SetState(eStateRunning, true);
22850e1d729bSPavel Labath     return resume_result;
2286c076559aSPavel Labath   }
2287b9c1b51eSKate Stone   case eStateStepping: {
2288605b51b8SPavel Labath     const auto step_result = thread.SingleStep(signo);
22890e1d729bSPavel Labath     if (step_result.Success())
22900e1d729bSPavel Labath       SetState(eStateRunning, true);
22910e1d729bSPavel Labath     return step_result;
22920e1d729bSPavel Labath   }
22930e1d729bSPavel Labath   default:
22948198db30SPavel Labath     LLDB_LOG(log, "Unhandled state {0}.", state);
22950e1d729bSPavel Labath     llvm_unreachable("Unhandled state for resume");
22960e1d729bSPavel Labath   }
2297c076559aSPavel Labath }
2298c076559aSPavel Labath 
2299c076559aSPavel Labath //===----------------------------------------------------------------------===//
2300c076559aSPavel Labath 
2301b9c1b51eSKate Stone void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {
2302a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2303a6321a8eSPavel Labath   LLDB_LOG(log, "about to process event: (triggering_tid: {0})",
2304a6321a8eSPavel Labath            triggering_tid);
2305c076559aSPavel Labath 
23060e1d729bSPavel Labath   m_pending_notification_tid = triggering_tid;
23070e1d729bSPavel Labath 
23080e1d729bSPavel Labath   // Request a stop for all the thread stops that need to be stopped
23090e1d729bSPavel Labath   // and are not already known to be stopped.
2310b9c1b51eSKate Stone   for (const auto &thread_sp : m_threads) {
23110e1d729bSPavel Labath     if (StateIsRunningState(thread_sp->GetState()))
23120e1d729bSPavel Labath       static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
23130e1d729bSPavel Labath   }
23140e1d729bSPavel Labath 
23150e1d729bSPavel Labath   SignalIfAllThreadsStopped();
2316a6321a8eSPavel Labath   LLDB_LOG(log, "event processing done");
2317c076559aSPavel Labath }
2318c076559aSPavel Labath 
2319b9c1b51eSKate Stone void NativeProcessLinux::SignalIfAllThreadsStopped() {
23200e1d729bSPavel Labath   if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
23210e1d729bSPavel Labath     return; // No pending notification. Nothing to do.
23220e1d729bSPavel Labath 
2323b9c1b51eSKate Stone   for (const auto &thread_sp : m_threads) {
23240e1d729bSPavel Labath     if (StateIsRunningState(thread_sp->GetState()))
23250e1d729bSPavel Labath       return; // Some threads are still running. Don't signal yet.
23260e1d729bSPavel Labath   }
23270e1d729bSPavel Labath 
23280e1d729bSPavel Labath   // We have a pending notification and all threads have stopped.
2329b9c1b51eSKate Stone   Log *log(
2330b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
23319eb1ecb9SPavel Labath 
2332b9c1b51eSKate Stone   // Clear any temporary breakpoints we used to implement software single
2333b9c1b51eSKate Stone   // stepping.
2334b9c1b51eSKate Stone   for (const auto &thread_info : m_threads_stepping_with_breakpoint) {
233597206d57SZachary Turner     Status error = RemoveBreakpoint(thread_info.second);
23369eb1ecb9SPavel Labath     if (error.Fail())
2337a6321a8eSPavel Labath       LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}",
2338a6321a8eSPavel Labath                thread_info.first, error);
23399eb1ecb9SPavel Labath   }
23409eb1ecb9SPavel Labath   m_threads_stepping_with_breakpoint.clear();
23419eb1ecb9SPavel Labath 
23429eb1ecb9SPavel Labath   // Notify the delegate about the stop
23430e1d729bSPavel Labath   SetCurrentThreadID(m_pending_notification_tid);
2344ed89c7feSPavel Labath   SetState(StateType::eStateStopped, true);
23450e1d729bSPavel Labath   m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
2346c076559aSPavel Labath }
2347c076559aSPavel Labath 
2348b9c1b51eSKate Stone void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {
2349a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2350a6321a8eSPavel Labath   LLDB_LOG(log, "tid: {0}", thread.GetID());
23511dbc6c9cSPavel Labath 
2352b9c1b51eSKate Stone   if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID &&
2353b9c1b51eSKate Stone       StateIsRunningState(thread.GetState())) {
2354b9c1b51eSKate Stone     // We will need to wait for this new thread to stop as well before firing
2355b9c1b51eSKate Stone     // the
2356c076559aSPavel Labath     // notification.
2357f9077782SPavel Labath     thread.RequestStop();
2358c076559aSPavel Labath   }
2359c076559aSPavel Labath }
2360068f8a7eSTamas Berghammer 
2361b9c1b51eSKate Stone void NativeProcessLinux::SigchldHandler() {
2362a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
236319cbe96aSPavel Labath   // Process all pending waitpid notifications.
2364b9c1b51eSKate Stone   while (true) {
236519cbe96aSPavel Labath     int status = -1;
236619cbe96aSPavel Labath     ::pid_t wait_pid = waitpid(-1, &status, __WALL | __WNOTHREAD | WNOHANG);
236719cbe96aSPavel Labath 
236819cbe96aSPavel Labath     if (wait_pid == 0)
236919cbe96aSPavel Labath       break; // We are done.
237019cbe96aSPavel Labath 
2371b9c1b51eSKate Stone     if (wait_pid == -1) {
237219cbe96aSPavel Labath       if (errno == EINTR)
237319cbe96aSPavel Labath         continue;
237419cbe96aSPavel Labath 
237597206d57SZachary Turner       Status error(errno, eErrorTypePOSIX);
2376a6321a8eSPavel Labath       LLDB_LOG(log, "waitpid (-1, &status, _) failed: {0}", error);
237719cbe96aSPavel Labath       break;
237819cbe96aSPavel Labath     }
237919cbe96aSPavel Labath 
23803508fc8cSPavel Labath     WaitStatus wait_status = WaitStatus::Decode(status);
23813508fc8cSPavel Labath     bool exited = wait_status.type == WaitStatus::Exit ||
23823508fc8cSPavel Labath                   (wait_status.type == WaitStatus::Signal &&
23833508fc8cSPavel Labath                    wait_pid == static_cast<::pid_t>(GetID()));
238419cbe96aSPavel Labath 
23853508fc8cSPavel Labath     LLDB_LOG(
23863508fc8cSPavel Labath         log,
23873508fc8cSPavel Labath         "waitpid (-1, &status, _) => pid = {0}, status = {1}, exited = {2}",
23883508fc8cSPavel Labath         wait_pid, wait_status, exited);
238919cbe96aSPavel Labath 
23903508fc8cSPavel Labath     MonitorCallback(wait_pid, exited, wait_status);
239119cbe96aSPavel Labath   }
2392068f8a7eSTamas Berghammer }
2393068f8a7eSTamas Berghammer 
2394068f8a7eSTamas Berghammer // Wrapper for ptrace to catch errors and log calls.
2395b9c1b51eSKate Stone // Note that ptrace sets errno on error because -1 can be a valid result (i.e.
2396b9c1b51eSKate Stone // for PTRACE_PEEK*)
239797206d57SZachary Turner Status NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
2398b9c1b51eSKate Stone                                          void *data, size_t data_size,
2399b9c1b51eSKate Stone                                          long *result) {
240097206d57SZachary Turner   Status error;
24014a9babb2SPavel Labath   long int ret;
2402068f8a7eSTamas Berghammer 
2403068f8a7eSTamas Berghammer   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2404068f8a7eSTamas Berghammer 
2405068f8a7eSTamas Berghammer   PtraceDisplayBytes(req, data, data_size);
2406068f8a7eSTamas Berghammer 
2407068f8a7eSTamas Berghammer   errno = 0;
2408068f8a7eSTamas Berghammer   if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
2409b9c1b51eSKate Stone     ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2410b9c1b51eSKate Stone                  *(unsigned int *)addr, data);
2411068f8a7eSTamas Berghammer   else
2412b9c1b51eSKate Stone     ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2413b9c1b51eSKate Stone                  addr, data);
2414068f8a7eSTamas Berghammer 
24154a9babb2SPavel Labath   if (ret == -1)
2416068f8a7eSTamas Berghammer     error.SetErrorToErrno();
2417068f8a7eSTamas Berghammer 
24184a9babb2SPavel Labath   if (result)
24194a9babb2SPavel Labath     *result = ret;
24204a9babb2SPavel Labath 
242128096200SPavel Labath   LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data,
242228096200SPavel Labath            data_size, ret);
2423068f8a7eSTamas Berghammer 
2424068f8a7eSTamas Berghammer   PtraceDisplayBytes(req, data, data_size);
2425068f8a7eSTamas Berghammer 
2426a6321a8eSPavel Labath   if (error.Fail())
2427a6321a8eSPavel Labath     LLDB_LOG(log, "ptrace() failed: {0}", error);
2428068f8a7eSTamas Berghammer 
24294a9babb2SPavel Labath   return error;
2430068f8a7eSTamas Berghammer }
2431*99e37695SRavitheja Addepally 
2432*99e37695SRavitheja Addepally llvm::Expected<ProcessorTraceMonitor &>
2433*99e37695SRavitheja Addepally NativeProcessLinux::LookupProcessorTraceInstance(lldb::user_id_t traceid,
2434*99e37695SRavitheja Addepally                                                  lldb::tid_t thread) {
2435*99e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2436*99e37695SRavitheja Addepally   if (thread == LLDB_INVALID_THREAD_ID && traceid == m_pt_proces_trace_id) {
2437*99e37695SRavitheja Addepally     LLDB_LOG(log, "thread not specified: {0}", traceid);
2438*99e37695SRavitheja Addepally     return Status("tracing not active thread not specified").ToError();
2439*99e37695SRavitheja Addepally   }
2440*99e37695SRavitheja Addepally 
2441*99e37695SRavitheja Addepally   for (auto& iter : m_processor_trace_monitor) {
2442*99e37695SRavitheja Addepally     if (traceid == iter.second->GetTraceID() &&
2443*99e37695SRavitheja Addepally         (thread == iter.first || thread == LLDB_INVALID_THREAD_ID))
2444*99e37695SRavitheja Addepally       return *(iter.second);
2445*99e37695SRavitheja Addepally   }
2446*99e37695SRavitheja Addepally 
2447*99e37695SRavitheja Addepally   LLDB_LOG(log, "traceid not being traced: {0}", traceid);
2448*99e37695SRavitheja Addepally   return Status("tracing not active for this thread").ToError();
2449*99e37695SRavitheja Addepally }
2450*99e37695SRavitheja Addepally 
2451*99e37695SRavitheja Addepally Status NativeProcessLinux::GetMetaData(lldb::user_id_t traceid,
2452*99e37695SRavitheja Addepally                                        lldb::tid_t thread,
2453*99e37695SRavitheja Addepally                                        llvm::MutableArrayRef<uint8_t> &buffer,
2454*99e37695SRavitheja Addepally                                        size_t offset) {
2455*99e37695SRavitheja Addepally   TraceOptions trace_options;
2456*99e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2457*99e37695SRavitheja Addepally   Status error;
2458*99e37695SRavitheja Addepally 
2459*99e37695SRavitheja Addepally   LLDB_LOG(log, "traceid {0}", traceid);
2460*99e37695SRavitheja Addepally 
2461*99e37695SRavitheja Addepally   auto perf_monitor = LookupProcessorTraceInstance(traceid, thread);
2462*99e37695SRavitheja Addepally   if (!perf_monitor) {
2463*99e37695SRavitheja Addepally     LLDB_LOG(log, "traceid not being traced: {0}", traceid);
2464*99e37695SRavitheja Addepally     buffer = buffer.slice(buffer.size());
2465*99e37695SRavitheja Addepally     error = perf_monitor.takeError();
2466*99e37695SRavitheja Addepally     return error;
2467*99e37695SRavitheja Addepally   }
2468*99e37695SRavitheja Addepally   return (*perf_monitor).ReadPerfTraceData(buffer, offset);
2469*99e37695SRavitheja Addepally }
2470*99e37695SRavitheja Addepally 
2471*99e37695SRavitheja Addepally Status NativeProcessLinux::GetData(lldb::user_id_t traceid, lldb::tid_t thread,
2472*99e37695SRavitheja Addepally                                    llvm::MutableArrayRef<uint8_t> &buffer,
2473*99e37695SRavitheja Addepally                                    size_t offset) {
2474*99e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2475*99e37695SRavitheja Addepally   Status error;
2476*99e37695SRavitheja Addepally 
2477*99e37695SRavitheja Addepally   LLDB_LOG(log, "traceid {0}", traceid);
2478*99e37695SRavitheja Addepally 
2479*99e37695SRavitheja Addepally   auto perf_monitor = LookupProcessorTraceInstance(traceid, thread);
2480*99e37695SRavitheja Addepally   if (!perf_monitor) {
2481*99e37695SRavitheja Addepally     LLDB_LOG(log, "traceid not being traced: {0}", traceid);
2482*99e37695SRavitheja Addepally     buffer = buffer.slice(buffer.size());
2483*99e37695SRavitheja Addepally     error = perf_monitor.takeError();
2484*99e37695SRavitheja Addepally     return error;
2485*99e37695SRavitheja Addepally   }
2486*99e37695SRavitheja Addepally   return (*perf_monitor).ReadPerfTraceAux(buffer, offset);
2487*99e37695SRavitheja Addepally }
2488*99e37695SRavitheja Addepally 
2489*99e37695SRavitheja Addepally Status NativeProcessLinux::GetTraceConfig(lldb::user_id_t traceid,
2490*99e37695SRavitheja Addepally                                           TraceOptions &config) {
2491*99e37695SRavitheja Addepally   Status error;
2492*99e37695SRavitheja Addepally   if (config.getThreadID() == LLDB_INVALID_THREAD_ID &&
2493*99e37695SRavitheja Addepally       m_pt_proces_trace_id == traceid) {
2494*99e37695SRavitheja Addepally     if (m_pt_proces_trace_id == LLDB_INVALID_UID) {
2495*99e37695SRavitheja Addepally       error.SetErrorString("tracing not active for this process");
2496*99e37695SRavitheja Addepally       return error;
2497*99e37695SRavitheja Addepally     }
2498*99e37695SRavitheja Addepally     config = m_pt_process_trace_config;
2499*99e37695SRavitheja Addepally   } else {
2500*99e37695SRavitheja Addepally     auto perf_monitor =
2501*99e37695SRavitheja Addepally         LookupProcessorTraceInstance(traceid, config.getThreadID());
2502*99e37695SRavitheja Addepally     if (!perf_monitor) {
2503*99e37695SRavitheja Addepally       error = perf_monitor.takeError();
2504*99e37695SRavitheja Addepally       return error;
2505*99e37695SRavitheja Addepally     }
2506*99e37695SRavitheja Addepally     error = (*perf_monitor).GetTraceConfig(config);
2507*99e37695SRavitheja Addepally   }
2508*99e37695SRavitheja Addepally   return error;
2509*99e37695SRavitheja Addepally }
2510*99e37695SRavitheja Addepally 
2511*99e37695SRavitheja Addepally lldb::user_id_t
2512*99e37695SRavitheja Addepally NativeProcessLinux::StartTraceGroup(const TraceOptions &config,
2513*99e37695SRavitheja Addepally                                            Status &error) {
2514*99e37695SRavitheja Addepally 
2515*99e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2516*99e37695SRavitheja Addepally   if (config.getType() != TraceType::eTraceTypeProcessorTrace)
2517*99e37695SRavitheja Addepally     return LLDB_INVALID_UID;
2518*99e37695SRavitheja Addepally 
2519*99e37695SRavitheja Addepally   if (m_pt_proces_trace_id != LLDB_INVALID_UID) {
2520*99e37695SRavitheja Addepally     error.SetErrorString("tracing already active on this process");
2521*99e37695SRavitheja Addepally     return m_pt_proces_trace_id;
2522*99e37695SRavitheja Addepally   }
2523*99e37695SRavitheja Addepally 
2524*99e37695SRavitheja Addepally   for (const auto &thread_sp : m_threads) {
2525*99e37695SRavitheja Addepally     if (auto traceInstance = ProcessorTraceMonitor::Create(
2526*99e37695SRavitheja Addepally             GetID(), thread_sp->GetID(), config, true)) {
2527*99e37695SRavitheja Addepally       m_pt_traced_thread_group.insert(thread_sp->GetID());
2528*99e37695SRavitheja Addepally       m_processor_trace_monitor.insert(
2529*99e37695SRavitheja Addepally           std::make_pair(thread_sp->GetID(), std::move(*traceInstance)));
2530*99e37695SRavitheja Addepally     }
2531*99e37695SRavitheja Addepally   }
2532*99e37695SRavitheja Addepally 
2533*99e37695SRavitheja Addepally   m_pt_process_trace_config = config;
2534*99e37695SRavitheja Addepally   error = ProcessorTraceMonitor::GetCPUType(m_pt_process_trace_config);
2535*99e37695SRavitheja Addepally 
2536*99e37695SRavitheja Addepally   // Trace on Complete process will have traceid of 0
2537*99e37695SRavitheja Addepally   m_pt_proces_trace_id = 0;
2538*99e37695SRavitheja Addepally 
2539*99e37695SRavitheja Addepally   LLDB_LOG(log, "Process Trace ID {0}", m_pt_proces_trace_id);
2540*99e37695SRavitheja Addepally   return m_pt_proces_trace_id;
2541*99e37695SRavitheja Addepally }
2542*99e37695SRavitheja Addepally 
2543*99e37695SRavitheja Addepally lldb::user_id_t NativeProcessLinux::StartTrace(const TraceOptions &config,
2544*99e37695SRavitheja Addepally                                                Status &error) {
2545*99e37695SRavitheja Addepally   if (config.getType() != TraceType::eTraceTypeProcessorTrace)
2546*99e37695SRavitheja Addepally     return NativeProcessProtocol::StartTrace(config, error);
2547*99e37695SRavitheja Addepally 
2548*99e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2549*99e37695SRavitheja Addepally 
2550*99e37695SRavitheja Addepally   lldb::tid_t threadid = config.getThreadID();
2551*99e37695SRavitheja Addepally 
2552*99e37695SRavitheja Addepally   if (threadid == LLDB_INVALID_THREAD_ID)
2553*99e37695SRavitheja Addepally     return StartTraceGroup(config, error);
2554*99e37695SRavitheja Addepally 
2555*99e37695SRavitheja Addepally   auto thread_sp = GetThreadByID(threadid);
2556*99e37695SRavitheja Addepally   if (!thread_sp) {
2557*99e37695SRavitheja Addepally     // Thread not tracked by lldb so don't trace.
2558*99e37695SRavitheja Addepally     error.SetErrorString("invalid thread id");
2559*99e37695SRavitheja Addepally     return LLDB_INVALID_UID;
2560*99e37695SRavitheja Addepally   }
2561*99e37695SRavitheja Addepally 
2562*99e37695SRavitheja Addepally   const auto &iter = m_processor_trace_monitor.find(threadid);
2563*99e37695SRavitheja Addepally   if (iter != m_processor_trace_monitor.end()) {
2564*99e37695SRavitheja Addepally     LLDB_LOG(log, "Thread already being traced");
2565*99e37695SRavitheja Addepally     error.SetErrorString("tracing already active on this thread");
2566*99e37695SRavitheja Addepally     return LLDB_INVALID_UID;
2567*99e37695SRavitheja Addepally   }
2568*99e37695SRavitheja Addepally 
2569*99e37695SRavitheja Addepally   auto traceMonitor =
2570*99e37695SRavitheja Addepally       ProcessorTraceMonitor::Create(GetID(), threadid, config, false);
2571*99e37695SRavitheja Addepally   if (!traceMonitor) {
2572*99e37695SRavitheja Addepally     error = traceMonitor.takeError();
2573*99e37695SRavitheja Addepally     LLDB_LOG(log, "error {0}", error);
2574*99e37695SRavitheja Addepally     return LLDB_INVALID_UID;
2575*99e37695SRavitheja Addepally   }
2576*99e37695SRavitheja Addepally   lldb::user_id_t ret_trace_id = (*traceMonitor)->GetTraceID();
2577*99e37695SRavitheja Addepally   m_processor_trace_monitor.insert(
2578*99e37695SRavitheja Addepally       std::make_pair(threadid, std::move(*traceMonitor)));
2579*99e37695SRavitheja Addepally   return ret_trace_id;
2580*99e37695SRavitheja Addepally }
2581*99e37695SRavitheja Addepally 
2582*99e37695SRavitheja Addepally Status NativeProcessLinux::StopTracingForThread(lldb::tid_t thread) {
2583*99e37695SRavitheja Addepally   Status error;
2584*99e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2585*99e37695SRavitheja Addepally   LLDB_LOG(log, "Thread {0}", thread);
2586*99e37695SRavitheja Addepally 
2587*99e37695SRavitheja Addepally   const auto& iter = m_processor_trace_monitor.find(thread);
2588*99e37695SRavitheja Addepally   if (iter == m_processor_trace_monitor.end()) {
2589*99e37695SRavitheja Addepally     error.SetErrorString("tracing not active for this thread");
2590*99e37695SRavitheja Addepally     return error;
2591*99e37695SRavitheja Addepally   }
2592*99e37695SRavitheja Addepally 
2593*99e37695SRavitheja Addepally   if (iter->second->GetTraceID() == m_pt_proces_trace_id) {
2594*99e37695SRavitheja Addepally     // traceid maps to the whole process so we have to erase it from the
2595*99e37695SRavitheja Addepally     // thread group.
2596*99e37695SRavitheja Addepally     LLDB_LOG(log, "traceid maps to process");
2597*99e37695SRavitheja Addepally     m_pt_traced_thread_group.erase(thread);
2598*99e37695SRavitheja Addepally   }
2599*99e37695SRavitheja Addepally   m_processor_trace_monitor.erase(iter);
2600*99e37695SRavitheja Addepally 
2601*99e37695SRavitheja Addepally   return error;
2602*99e37695SRavitheja Addepally }
2603*99e37695SRavitheja Addepally 
2604*99e37695SRavitheja Addepally Status NativeProcessLinux::StopTrace(lldb::user_id_t traceid,
2605*99e37695SRavitheja Addepally                                      lldb::tid_t thread) {
2606*99e37695SRavitheja Addepally   Status error;
2607*99e37695SRavitheja Addepally 
2608*99e37695SRavitheja Addepally   TraceOptions trace_options;
2609*99e37695SRavitheja Addepally   trace_options.setThreadID(thread);
2610*99e37695SRavitheja Addepally   error = NativeProcessLinux::GetTraceConfig(traceid, trace_options);
2611*99e37695SRavitheja Addepally 
2612*99e37695SRavitheja Addepally   if (error.Fail())
2613*99e37695SRavitheja Addepally     return error;
2614*99e37695SRavitheja Addepally 
2615*99e37695SRavitheja Addepally   switch (trace_options.getType()) {
2616*99e37695SRavitheja Addepally   case lldb::TraceType::eTraceTypeProcessorTrace:
2617*99e37695SRavitheja Addepally     if (traceid == m_pt_proces_trace_id &&
2618*99e37695SRavitheja Addepally         thread == LLDB_INVALID_THREAD_ID)
2619*99e37695SRavitheja Addepally       StopProcessorTracingOnProcess();
2620*99e37695SRavitheja Addepally     else
2621*99e37695SRavitheja Addepally       error = StopProcessorTracingOnThread(traceid, thread);
2622*99e37695SRavitheja Addepally     break;
2623*99e37695SRavitheja Addepally   default:
2624*99e37695SRavitheja Addepally     error.SetErrorString("trace not supported");
2625*99e37695SRavitheja Addepally     break;
2626*99e37695SRavitheja Addepally   }
2627*99e37695SRavitheja Addepally 
2628*99e37695SRavitheja Addepally   return error;
2629*99e37695SRavitheja Addepally }
2630*99e37695SRavitheja Addepally 
2631*99e37695SRavitheja Addepally void NativeProcessLinux::StopProcessorTracingOnProcess() {
2632*99e37695SRavitheja Addepally   for (auto thread_id_iter : m_pt_traced_thread_group)
2633*99e37695SRavitheja Addepally     m_processor_trace_monitor.erase(thread_id_iter);
2634*99e37695SRavitheja Addepally   m_pt_traced_thread_group.clear();
2635*99e37695SRavitheja Addepally   m_pt_proces_trace_id = LLDB_INVALID_UID;
2636*99e37695SRavitheja Addepally }
2637*99e37695SRavitheja Addepally 
2638*99e37695SRavitheja Addepally Status NativeProcessLinux::StopProcessorTracingOnThread(lldb::user_id_t traceid,
2639*99e37695SRavitheja Addepally                                                         lldb::tid_t thread) {
2640*99e37695SRavitheja Addepally   Status error;
2641*99e37695SRavitheja Addepally   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2642*99e37695SRavitheja Addepally 
2643*99e37695SRavitheja Addepally   if (thread == LLDB_INVALID_THREAD_ID) {
2644*99e37695SRavitheja Addepally     for (auto& iter : m_processor_trace_monitor) {
2645*99e37695SRavitheja Addepally       if (iter.second->GetTraceID() == traceid) {
2646*99e37695SRavitheja Addepally         // Stopping a trace instance for an individual thread
2647*99e37695SRavitheja Addepally         // hence there will only be one traceid that can match.
2648*99e37695SRavitheja Addepally         m_processor_trace_monitor.erase(iter.first);
2649*99e37695SRavitheja Addepally         return error;
2650*99e37695SRavitheja Addepally       }
2651*99e37695SRavitheja Addepally       LLDB_LOG(log, "Trace ID {0}", iter.second->GetTraceID());
2652*99e37695SRavitheja Addepally     }
2653*99e37695SRavitheja Addepally 
2654*99e37695SRavitheja Addepally     LLDB_LOG(log, "Invalid TraceID");
2655*99e37695SRavitheja Addepally     error.SetErrorString("invalid trace id");
2656*99e37695SRavitheja Addepally     return error;
2657*99e37695SRavitheja Addepally   }
2658*99e37695SRavitheja Addepally 
2659*99e37695SRavitheja Addepally   // thread is specified so we can use find function on the map.
2660*99e37695SRavitheja Addepally   const auto& iter = m_processor_trace_monitor.find(thread);
2661*99e37695SRavitheja Addepally   if (iter == m_processor_trace_monitor.end()) {
2662*99e37695SRavitheja Addepally     // thread not found in our map.
2663*99e37695SRavitheja Addepally     LLDB_LOG(log, "thread not being traced");
2664*99e37695SRavitheja Addepally     error.SetErrorString("tracing not active for this thread");
2665*99e37695SRavitheja Addepally     return error;
2666*99e37695SRavitheja Addepally   }
2667*99e37695SRavitheja Addepally   if (iter->second->GetTraceID() != traceid) {
2668*99e37695SRavitheja Addepally     // traceid did not match so it has to be invalid.
2669*99e37695SRavitheja Addepally     LLDB_LOG(log, "Invalid TraceID");
2670*99e37695SRavitheja Addepally     error.SetErrorString("invalid trace id");
2671*99e37695SRavitheja Addepally     return error;
2672*99e37695SRavitheja Addepally   }
2673*99e37695SRavitheja Addepally 
2674*99e37695SRavitheja Addepally   LLDB_LOG(log, "UID - {0} , Thread -{1}", traceid, thread);
2675*99e37695SRavitheja Addepally 
2676*99e37695SRavitheja Addepally   if (traceid == m_pt_proces_trace_id) {
2677*99e37695SRavitheja Addepally     // traceid maps to the whole process so we have to erase it from the
2678*99e37695SRavitheja Addepally     // thread group.
2679*99e37695SRavitheja Addepally     LLDB_LOG(log, "traceid maps to process");
2680*99e37695SRavitheja Addepally     m_pt_traced_thread_group.erase(thread);
2681*99e37695SRavitheja Addepally   }
2682*99e37695SRavitheja Addepally   m_processor_trace_monitor.erase(iter);
2683*99e37695SRavitheja Addepally 
2684*99e37695SRavitheja Addepally   return error;
2685*99e37695SRavitheja Addepally }
2686