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"
43bf9a7730SZachary Turner #include "lldb/Utility/Error.h"
44c16f5dcaSChaoren Lin #include "lldb/Utility/LLDBAssert.h"
45f805e190SPavel Labath #include "lldb/Utility/StringExtractor.h"
46af245d11STodd Fiala 
47af245d11STodd Fiala #include "NativeThreadLinux.h"
48b9c1b51eSKate Stone #include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
491e209fccSTamas Berghammer #include "Procfs.h"
50cacde7dfSTodd Fiala 
517d86ee5aSZachary Turner #include "llvm/Support/FileSystem.h"
524ee1c952SPavel Labath #include "llvm/Support/Threading.h"
534ee1c952SPavel Labath 
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.",
100a6321a8eSPavel Labath                strerror(errno));
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.
196b9c1b51eSKate Stone static Error EnsureFDFlags(int fd, int flags) {
197bd7cbc5aSPavel Labath   Error 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 
217b9c1b51eSKate Stone Error 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 
2232a86b555SPavel Labath   Error 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 
257b9c1b51eSKate Stone Error 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;
2652a86b555SPavel Labath   Error 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(),
292b9c1b51eSKate Stone       m_pending_notification_tid(LLDB_INVALID_THREAD_ID) {}
293af245d11STodd Fiala 
294b9c1b51eSKate Stone void NativeProcessLinux::AttachToInferior(MainLoop &mainloop, lldb::pid_t pid,
295b9c1b51eSKate Stone                                           Error &error) {
296a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
297a6321a8eSPavel Labath   LLDB_LOG(log, "pid = {0:x}", pid);
298af245d11STodd Fiala 
299b9c1b51eSKate Stone   m_sigchld_handle = mainloop.RegisterSignal(
300b9c1b51eSKate Stone       SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, error);
30119cbe96aSPavel Labath   if (!m_sigchld_handle)
30219cbe96aSPavel Labath     return;
30319cbe96aSPavel Labath 
3042a86b555SPavel Labath   error = ResolveProcessArchitecture(pid, m_arch);
305af245d11STodd Fiala   if (!error.Success())
306af245d11STodd Fiala     return;
307af245d11STodd Fiala 
308af245d11STodd Fiala   // Set the architecture to the exe architecture.
309a6321a8eSPavel Labath   LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid,
310a6321a8eSPavel Labath            m_arch.GetArchitectureName());
311af245d11STodd Fiala   m_pid = pid;
312af245d11STodd Fiala   SetState(eStateAttaching);
313af245d11STodd Fiala 
31419cbe96aSPavel Labath   Attach(pid, error);
315af245d11STodd Fiala }
316af245d11STodd Fiala 
317b9c1b51eSKate Stone Error NativeProcessLinux::LaunchInferior(MainLoop &mainloop,
318b9c1b51eSKate Stone                                          ProcessLaunchInfo &launch_info) {
3194abe5d69SPavel Labath   Error error;
320b9c1b51eSKate Stone   m_sigchld_handle = mainloop.RegisterSignal(
321b9c1b51eSKate Stone       SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, error);
3224abe5d69SPavel Labath   if (!m_sigchld_handle)
3234abe5d69SPavel Labath     return error;
3244abe5d69SPavel Labath 
3254abe5d69SPavel Labath   SetState(eStateLaunching);
3260c4f01d4SPavel Labath 
3274abe5d69SPavel Labath   MaybeLogLaunchInfo(launch_info);
3284abe5d69SPavel Labath 
329b9c1b51eSKate Stone   ::pid_t pid =
330816ae4b0SKamil Rytarowski       ProcessLauncherPosixFork().LaunchProcess(launch_info, error).GetProcessId();
3315ad891f7SPavel Labath   if (error.Fail())
3324abe5d69SPavel Labath     return error;
3330c4f01d4SPavel Labath 
334a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
33575f47c3aSTodd Fiala 
336af245d11STodd Fiala   // Wait for the child process to trap on its call to execve.
337af245d11STodd Fiala   ::pid_t wpid;
338af245d11STodd Fiala   int status;
339b9c1b51eSKate Stone   if ((wpid = waitpid(pid, &status, 0)) < 0) {
340bd7cbc5aSPavel Labath     error.SetErrorToErrno();
341a6321a8eSPavel Labath     LLDB_LOG(log, "waitpid for inferior failed with %s", error);
342af245d11STodd Fiala 
343af245d11STodd Fiala     // Mark the inferior as invalid.
344b9c1b51eSKate Stone     // FIXME this could really use a new state - eStateLaunchFailure.  For now,
345b9c1b51eSKate Stone     // using eStateInvalid.
346bd7cbc5aSPavel Labath     SetState(StateType::eStateInvalid);
347af245d11STodd Fiala 
3484abe5d69SPavel Labath     return error;
349af245d11STodd Fiala   }
350af245d11STodd Fiala   assert(WIFSTOPPED(status) && (wpid == static_cast<::pid_t>(pid)) &&
351af245d11STodd Fiala          "Could not sync with inferior process.");
352af245d11STodd Fiala 
353a6321a8eSPavel Labath   LLDB_LOG(log, "inferior started, now in stopped state");
354bd7cbc5aSPavel Labath   error = SetDefaultPtraceOpts(pid);
355b9c1b51eSKate Stone   if (error.Fail()) {
356a6321a8eSPavel Labath     LLDB_LOG(log, "failed to set default ptrace options: {0}", error);
357af245d11STodd Fiala 
358af245d11STodd Fiala     // Mark the inferior as invalid.
359b9c1b51eSKate Stone     // FIXME this could really use a new state - eStateLaunchFailure.  For now,
360b9c1b51eSKate Stone     // using eStateInvalid.
361bd7cbc5aSPavel Labath     SetState(StateType::eStateInvalid);
362af245d11STodd Fiala 
3634abe5d69SPavel Labath     return error;
364af245d11STodd Fiala   }
365af245d11STodd Fiala 
366af245d11STodd Fiala   // Release the master terminal descriptor and pass it off to the
367af245d11STodd Fiala   // NativeProcessLinux instance.  Similarly stash the inferior pid.
3685ad891f7SPavel Labath   m_terminal_fd = launch_info.GetPTY().ReleaseMasterFileDescriptor();
369bd7cbc5aSPavel Labath   m_pid = pid;
3704abe5d69SPavel Labath   launch_info.SetProcessID(pid);
371af245d11STodd Fiala 
372b9c1b51eSKate Stone   if (m_terminal_fd != -1) {
373bd7cbc5aSPavel Labath     error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
374b9c1b51eSKate Stone     if (error.Fail()) {
375a6321a8eSPavel Labath       LLDB_LOG(log,
376a6321a8eSPavel Labath                "inferior EnsureFDFlags failed for ensuring terminal "
377a6321a8eSPavel Labath                "O_NONBLOCK setting: {0}",
378a6321a8eSPavel Labath                error);
379af245d11STodd Fiala 
380af245d11STodd Fiala       // Mark the inferior as invalid.
381b9c1b51eSKate Stone       // FIXME this could really use a new state - eStateLaunchFailure.  For
382b9c1b51eSKate Stone       // now, using eStateInvalid.
383bd7cbc5aSPavel Labath       SetState(StateType::eStateInvalid);
384af245d11STodd Fiala 
3854abe5d69SPavel Labath       return error;
386af245d11STodd Fiala     }
3875ad891f7SPavel Labath   }
388af245d11STodd Fiala 
389a6321a8eSPavel Labath   LLDB_LOG(log, "adding pid = {0}", pid);
3902a86b555SPavel Labath   ResolveProcessArchitecture(m_pid, m_arch);
391f9077782SPavel Labath   NativeThreadLinuxSP thread_sp = AddThread(pid);
392af245d11STodd Fiala   assert(thread_sp && "AddThread() returned a nullptr thread");
393f9077782SPavel Labath   thread_sp->SetStoppedBySignal(SIGSTOP);
394f9077782SPavel Labath   ThreadWasCreated(*thread_sp);
395af245d11STodd Fiala 
396af245d11STodd Fiala   // Let our process instance know the thread has stopped.
397bd7cbc5aSPavel Labath   SetCurrentThreadID(thread_sp->GetID());
398bd7cbc5aSPavel Labath   SetState(StateType::eStateStopped);
399af245d11STodd Fiala 
400a6321a8eSPavel Labath   if (error.Fail())
401a6321a8eSPavel Labath     LLDB_LOG(log, "inferior launching failed {0}", error);
4024abe5d69SPavel Labath   return error;
403af245d11STodd Fiala }
404af245d11STodd Fiala 
405b9c1b51eSKate Stone ::pid_t NativeProcessLinux::Attach(lldb::pid_t pid, Error &error) {
406a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
407af245d11STodd Fiala 
408b9c1b51eSKate Stone   // Use a map to keep track of the threads which we have attached/need to
409b9c1b51eSKate Stone   // attach.
410af245d11STodd Fiala   Host::TidMap tids_to_attach;
411b9c1b51eSKate Stone   if (pid <= 1) {
412bd7cbc5aSPavel Labath     error.SetErrorToGenericError();
413bd7cbc5aSPavel Labath     error.SetErrorString("Attaching to process 1 is not allowed.");
414bd7cbc5aSPavel Labath     return -1;
415af245d11STodd Fiala   }
416af245d11STodd Fiala 
417b9c1b51eSKate Stone   while (Host::FindProcessThreads(pid, tids_to_attach)) {
418af245d11STodd Fiala     for (Host::TidMap::iterator it = tids_to_attach.begin();
419b9c1b51eSKate Stone          it != tids_to_attach.end();) {
420b9c1b51eSKate Stone       if (it->second == false) {
421af245d11STodd Fiala         lldb::tid_t tid = it->first;
422af245d11STodd Fiala 
423af245d11STodd Fiala         // Attach to the requested process.
424af245d11STodd Fiala         // An attach will cause the thread to stop with a SIGSTOP.
4254a9babb2SPavel Labath         error = PtraceWrapper(PTRACE_ATTACH, tid);
426b9c1b51eSKate Stone         if (error.Fail()) {
427af245d11STodd Fiala           // No such thread. The thread may have exited.
428af245d11STodd Fiala           // More error handling may be needed.
429b9c1b51eSKate Stone           if (error.GetError() == ESRCH) {
430af245d11STodd Fiala             it = tids_to_attach.erase(it);
431af245d11STodd Fiala             continue;
432b9c1b51eSKate Stone           } else
433bd7cbc5aSPavel Labath             return -1;
434af245d11STodd Fiala         }
435af245d11STodd Fiala 
436af245d11STodd Fiala         int status;
437af245d11STodd Fiala         // Need to use __WALL otherwise we receive an error with errno=ECHLD
438af245d11STodd Fiala         // At this point we should have a thread stopped if waitpid succeeds.
439b9c1b51eSKate Stone         if ((status = waitpid(tid, NULL, __WALL)) < 0) {
440af245d11STodd Fiala           // No such thread. The thread may have exited.
441af245d11STodd Fiala           // More error handling may be needed.
442b9c1b51eSKate Stone           if (errno == ESRCH) {
443af245d11STodd Fiala             it = tids_to_attach.erase(it);
444af245d11STodd Fiala             continue;
445b9c1b51eSKate Stone           } else {
446bd7cbc5aSPavel Labath             error.SetErrorToErrno();
447bd7cbc5aSPavel Labath             return -1;
448af245d11STodd Fiala           }
449af245d11STodd Fiala         }
450af245d11STodd Fiala 
451bd7cbc5aSPavel Labath         error = SetDefaultPtraceOpts(tid);
452bd7cbc5aSPavel Labath         if (error.Fail())
453bd7cbc5aSPavel Labath           return -1;
454af245d11STodd Fiala 
455a6321a8eSPavel Labath         LLDB_LOG(log, "adding tid = {0}", tid);
456af245d11STodd Fiala         it->second = true;
457af245d11STodd Fiala 
458af245d11STodd Fiala         // Create the thread, mark it as stopped.
459f9077782SPavel Labath         NativeThreadLinuxSP thread_sp(AddThread(static_cast<lldb::tid_t>(tid)));
460af245d11STodd Fiala         assert(thread_sp && "AddThread() returned a nullptr");
461fa03ad2eSChaoren Lin 
462b9c1b51eSKate Stone         // This will notify this is a new thread and tell the system it is
463b9c1b51eSKate Stone         // stopped.
464f9077782SPavel Labath         thread_sp->SetStoppedBySignal(SIGSTOP);
465f9077782SPavel Labath         ThreadWasCreated(*thread_sp);
466bd7cbc5aSPavel Labath         SetCurrentThreadID(thread_sp->GetID());
467af245d11STodd Fiala       }
468af245d11STodd Fiala 
469af245d11STodd Fiala       // move the loop forward
470af245d11STodd Fiala       ++it;
471af245d11STodd Fiala     }
472af245d11STodd Fiala   }
473af245d11STodd Fiala 
474b9c1b51eSKate Stone   if (tids_to_attach.size() > 0) {
475bd7cbc5aSPavel Labath     m_pid = pid;
476af245d11STodd Fiala     // Let our process instance know the thread has stopped.
477bd7cbc5aSPavel Labath     SetState(StateType::eStateStopped);
478b9c1b51eSKate Stone   } else {
479bd7cbc5aSPavel Labath     error.SetErrorToGenericError();
480bd7cbc5aSPavel Labath     error.SetErrorString("No such process.");
481bd7cbc5aSPavel Labath     return -1;
482af245d11STodd Fiala   }
483af245d11STodd Fiala 
484bd7cbc5aSPavel Labath   return pid;
485af245d11STodd Fiala }
486af245d11STodd Fiala 
487b9c1b51eSKate Stone Error NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid) {
488af245d11STodd Fiala   long ptrace_opts = 0;
489af245d11STodd Fiala 
490af245d11STodd Fiala   // Have the child raise an event on exit.  This is used to keep the child in
491af245d11STodd Fiala   // limbo until it is destroyed.
492af245d11STodd Fiala   ptrace_opts |= PTRACE_O_TRACEEXIT;
493af245d11STodd Fiala 
494af245d11STodd Fiala   // Have the tracer trace threads which spawn in the inferior process.
495af245d11STodd Fiala   // TODO: if we want to support tracing the inferiors' child, add the
496af245d11STodd Fiala   // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
497af245d11STodd Fiala   ptrace_opts |= PTRACE_O_TRACECLONE;
498af245d11STodd Fiala 
499af245d11STodd Fiala   // Have the tracer notify us before execve returns
500af245d11STodd Fiala   // (needed to disable legacy SIGTRAP generation)
501af245d11STodd Fiala   ptrace_opts |= PTRACE_O_TRACEEXEC;
502af245d11STodd Fiala 
5034a9babb2SPavel Labath   return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void *)ptrace_opts);
504af245d11STodd Fiala }
505af245d11STodd Fiala 
506b9c1b51eSKate Stone static ExitType convert_pid_status_to_exit_type(int status) {
507af245d11STodd Fiala   if (WIFEXITED(status))
508af245d11STodd Fiala     return ExitType::eExitTypeExit;
509af245d11STodd Fiala   else if (WIFSIGNALED(status))
510af245d11STodd Fiala     return ExitType::eExitTypeSignal;
511af245d11STodd Fiala   else if (WIFSTOPPED(status))
512af245d11STodd Fiala     return ExitType::eExitTypeStop;
513b9c1b51eSKate Stone   else {
514af245d11STodd Fiala     // We don't know what this is.
515af245d11STodd Fiala     return ExitType::eExitTypeInvalid;
516af245d11STodd Fiala   }
517af245d11STodd Fiala }
518af245d11STodd Fiala 
519b9c1b51eSKate Stone static int convert_pid_status_to_return_code(int status) {
520af245d11STodd Fiala   if (WIFEXITED(status))
521af245d11STodd Fiala     return WEXITSTATUS(status);
522af245d11STodd Fiala   else if (WIFSIGNALED(status))
523af245d11STodd Fiala     return WTERMSIG(status);
524af245d11STodd Fiala   else if (WIFSTOPPED(status))
525af245d11STodd Fiala     return WSTOPSIG(status);
526b9c1b51eSKate Stone   else {
527af245d11STodd Fiala     // We don't know what this is.
528af245d11STodd Fiala     return ExitType::eExitTypeInvalid;
529af245d11STodd Fiala   }
530af245d11STodd Fiala }
531af245d11STodd Fiala 
5321107b5a5SPavel Labath // Handles all waitpid events from the inferior process.
533b9c1b51eSKate Stone void NativeProcessLinux::MonitorCallback(lldb::pid_t pid, bool exited,
534b9c1b51eSKate Stone                                          int signal, int status) {
535af245d11STodd Fiala   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
536af245d11STodd Fiala 
537b9c1b51eSKate Stone   // Certain activities differ based on whether the pid is the tid of the main
538b9c1b51eSKate Stone   // thread.
5391107b5a5SPavel Labath   const bool is_main_thread = (pid == GetID());
540af245d11STodd Fiala 
541af245d11STodd Fiala   // Handle when the thread exits.
542b9c1b51eSKate Stone   if (exited) {
543a6321a8eSPavel Labath     LLDB_LOG(log, "got exit signal({0}) , tid = {1} ({2} main thread)", signal,
544a6321a8eSPavel Labath              pid, is_main_thread ? "is" : "is not");
545af245d11STodd Fiala 
546af245d11STodd Fiala     // This is a thread that exited.  Ensure we're not tracking it anymore.
5471107b5a5SPavel Labath     const bool thread_found = StopTrackingThread(pid);
548af245d11STodd Fiala 
549b9c1b51eSKate Stone     if (is_main_thread) {
550b9c1b51eSKate Stone       // We only set the exit status and notify the delegate if we haven't
551b9c1b51eSKate Stone       // already set the process
552b9c1b51eSKate Stone       // state to an exited state.  We normally should have received a SIGTRAP |
553b9c1b51eSKate Stone       // (PTRACE_EVENT_EXIT << 8)
554af245d11STodd Fiala       // for the main thread.
555b9c1b51eSKate Stone       const bool already_notified = (GetState() == StateType::eStateExited) ||
556b9c1b51eSKate Stone                                     (GetState() == StateType::eStateCrashed);
557b9c1b51eSKate Stone       if (!already_notified) {
558a6321a8eSPavel Labath         LLDB_LOG(
559a6321a8eSPavel Labath             log,
560a6321a8eSPavel Labath             "tid = {0} handling main thread exit ({1}), expected exit state "
561a6321a8eSPavel Labath             "already set but state was {2} instead, setting exit state now",
562a6321a8eSPavel Labath             pid,
563b9c1b51eSKate Stone             thread_found ? "stopped tracking thread metadata"
564b9c1b51eSKate Stone                          : "thread metadata not found",
5658198db30SPavel Labath             GetState());
566af245d11STodd Fiala         // The main thread exited.  We're done monitoring.  Report to delegate.
567b9c1b51eSKate Stone         SetExitStatus(convert_pid_status_to_exit_type(status),
568b9c1b51eSKate Stone                       convert_pid_status_to_return_code(status), nullptr, true);
569af245d11STodd Fiala 
570af245d11STodd Fiala         // Notify delegate that our process has exited.
5711107b5a5SPavel Labath         SetState(StateType::eStateExited, true);
572a6321a8eSPavel Labath       } else
573a6321a8eSPavel Labath         LLDB_LOG(log, "tid = {0} main thread now exited (%s)", pid,
574b9c1b51eSKate Stone                  thread_found ? "stopped tracking thread metadata"
575b9c1b51eSKate Stone                               : "thread metadata not found");
576b9c1b51eSKate Stone     } else {
577b9c1b51eSKate Stone       // Do we want to report to the delegate in this case?  I think not.  If
578a6321a8eSPavel Labath       // this was an orderly thread exit, we would already have received the
579a6321a8eSPavel Labath       // SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal, and we would have done an
580a6321a8eSPavel Labath       // all-stop then.
581a6321a8eSPavel Labath       LLDB_LOG(log, "tid = {0} handling non-main thread exit (%s)", pid,
582b9c1b51eSKate Stone                thread_found ? "stopped tracking thread metadata"
583b9c1b51eSKate Stone                             : "thread metadata not found");
584af245d11STodd Fiala     }
5851107b5a5SPavel Labath     return;
586af245d11STodd Fiala   }
587af245d11STodd Fiala 
588af245d11STodd Fiala   siginfo_t info;
589b9cc0c75SPavel Labath   const auto info_err = GetSignalInfo(pid, &info);
590b9cc0c75SPavel Labath   auto thread_sp = GetThreadByID(pid);
591b9cc0c75SPavel Labath 
592b9c1b51eSKate Stone   if (!thread_sp) {
593b9c1b51eSKate Stone     // Normally, the only situation when we cannot find the thread is if we have
594a6321a8eSPavel Labath     // just received a new thread notification. This is indicated by
595a6321a8eSPavel Labath     // GetSignalInfo() returning si_code == SI_USER and si_pid == 0
596a6321a8eSPavel Labath     LLDB_LOG(log, "received notification about an unknown tid {0}.", pid);
597b9cc0c75SPavel Labath 
598b9c1b51eSKate Stone     if (info_err.Fail()) {
599a6321a8eSPavel Labath       LLDB_LOG(log,
600a6321a8eSPavel Labath                "(tid {0}) GetSignalInfo failed ({1}). "
601a6321a8eSPavel Labath                "Ingoring this notification.",
602a6321a8eSPavel Labath                pid, info_err);
603b9cc0c75SPavel Labath       return;
604b9cc0c75SPavel Labath     }
605b9cc0c75SPavel Labath 
606a6321a8eSPavel Labath     LLDB_LOG(log, "tid {0}, si_code: {1}, si_pid: {2}", pid, info.si_code,
607a6321a8eSPavel Labath              info.si_pid);
608b9cc0c75SPavel Labath 
609b9cc0c75SPavel Labath     auto thread_sp = AddThread(pid);
610b9cc0c75SPavel Labath     // Resume the newly created thread.
611b9cc0c75SPavel Labath     ResumeThread(*thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
612b9cc0c75SPavel Labath     ThreadWasCreated(*thread_sp);
613b9cc0c75SPavel Labath     return;
614b9cc0c75SPavel Labath   }
615b9cc0c75SPavel Labath 
616b9cc0c75SPavel Labath   // Get details on the signal raised.
617b9c1b51eSKate Stone   if (info_err.Success()) {
618fa03ad2eSChaoren Lin     // We have retrieved the signal info.  Dispatch appropriately.
619fa03ad2eSChaoren Lin     if (info.si_signo == SIGTRAP)
620b9cc0c75SPavel Labath       MonitorSIGTRAP(info, *thread_sp);
621fa03ad2eSChaoren Lin     else
622b9cc0c75SPavel Labath       MonitorSignal(info, *thread_sp, exited);
623b9c1b51eSKate Stone   } else {
624b9c1b51eSKate Stone     if (info_err.GetError() == EINVAL) {
625fa03ad2eSChaoren Lin       // This is a group stop reception for this tid.
626b9c1b51eSKate Stone       // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU
627a6321a8eSPavel Labath       // into the tracee, triggering the group-stop mechanism. Normally
628a6321a8eSPavel Labath       // receiving these would stop the process, pending a SIGCONT. Simulating
629a6321a8eSPavel Labath       // this state in a debugger is hard and is generally not needed (one use
630a6321a8eSPavel Labath       // case is debugging background task being managed by a shell). For
631a6321a8eSPavel Labath       // general use, it is sufficient to stop the process in a signal-delivery
632b9c1b51eSKate Stone       // stop which happens before the group stop. This done by MonitorSignal
633a6321a8eSPavel Labath       // and works correctly for all signals.
634a6321a8eSPavel Labath       LLDB_LOG(log,
635a6321a8eSPavel Labath                "received a group stop for pid {0} tid {1}. Transparent "
636a6321a8eSPavel Labath                "handling of group stops not supported, resuming the "
637a6321a8eSPavel Labath                "thread.",
638a6321a8eSPavel Labath                GetID(), pid);
639b9c1b51eSKate Stone       ResumeThread(*thread_sp, thread_sp->GetState(),
640b9c1b51eSKate Stone                    LLDB_INVALID_SIGNAL_NUMBER);
641b9c1b51eSKate Stone     } else {
642af245d11STodd Fiala       // ptrace(GETSIGINFO) failed (but not due to group-stop).
643af245d11STodd Fiala 
644b9c1b51eSKate Stone       // A return value of ESRCH means the thread/process is no longer on the
645a6321a8eSPavel Labath       // system, so it was killed somehow outside of our control.  Either way,
646a6321a8eSPavel Labath       // we can't do anything with it anymore.
647af245d11STodd Fiala 
648b9c1b51eSKate Stone       // Stop tracking the metadata for the thread since it's entirely off the
649b9c1b51eSKate Stone       // system now.
6501107b5a5SPavel Labath       const bool thread_found = StopTrackingThread(pid);
651af245d11STodd Fiala 
652a6321a8eSPavel Labath       LLDB_LOG(log,
653a6321a8eSPavel Labath                "GetSignalInfo failed: {0}, tid = {1}, signal = {2}, "
654a6321a8eSPavel Labath                "status = {3}, main_thread = {4}, thread_found: {5}",
655a6321a8eSPavel Labath                info_err, pid, signal, status, is_main_thread, thread_found);
656af245d11STodd Fiala 
657b9c1b51eSKate Stone       if (is_main_thread) {
658b9c1b51eSKate Stone         // Notify the delegate - our process is not available but appears to
659b9c1b51eSKate Stone         // have been killed outside
660af245d11STodd Fiala         // our control.  Is eStateExited the right exit state in this case?
661b9c1b51eSKate Stone         SetExitStatus(convert_pid_status_to_exit_type(status),
662b9c1b51eSKate Stone                       convert_pid_status_to_return_code(status), nullptr, true);
6631107b5a5SPavel Labath         SetState(StateType::eStateExited, true);
664b9c1b51eSKate Stone       } else {
665b9c1b51eSKate Stone         // This thread was pulled out from underneath us.  Anything to do here?
666b9c1b51eSKate Stone         // Do we want to do an all stop?
667a6321a8eSPavel Labath         LLDB_LOG(log,
668a6321a8eSPavel Labath                  "pid {0} tid {1} non-main thread exit occurred, didn't "
669a6321a8eSPavel Labath                  "tell delegate anything since thread disappeared out "
670a6321a8eSPavel Labath                  "from underneath us",
671a6321a8eSPavel Labath                  GetID(), pid);
672af245d11STodd Fiala       }
673af245d11STodd Fiala     }
674af245d11STodd Fiala   }
675af245d11STodd Fiala }
676af245d11STodd Fiala 
677b9c1b51eSKate Stone void NativeProcessLinux::WaitForNewThread(::pid_t tid) {
678a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
679426bdf88SPavel Labath 
680f9077782SPavel Labath   NativeThreadLinuxSP new_thread_sp = GetThreadByID(tid);
681426bdf88SPavel Labath 
682b9c1b51eSKate Stone   if (new_thread_sp) {
683b9c1b51eSKate Stone     // We are already tracking the thread - we got the event on the new thread
684b9c1b51eSKate Stone     // (see
685426bdf88SPavel Labath     // MonitorSignal) before this one. We are done.
686426bdf88SPavel Labath     return;
687426bdf88SPavel Labath   }
688426bdf88SPavel Labath 
689426bdf88SPavel Labath   // The thread is not tracked yet, let's wait for it to appear.
690426bdf88SPavel Labath   int status = -1;
691426bdf88SPavel Labath   ::pid_t wait_pid;
692b9c1b51eSKate Stone   do {
693a6321a8eSPavel Labath     LLDB_LOG(log,
694a6321a8eSPavel Labath              "received thread creation event for tid {0}. tid not tracked "
695a6321a8eSPavel Labath              "yet, waiting for thread to appear...",
696a6321a8eSPavel Labath              tid);
697426bdf88SPavel Labath     wait_pid = waitpid(tid, &status, __WALL);
698b9c1b51eSKate Stone   } while (wait_pid == -1 && errno == EINTR);
699b9c1b51eSKate Stone   // Since we are waiting on a specific tid, this must be the creation event.
700a6321a8eSPavel Labath   // But let's do some checks just in case.
701426bdf88SPavel Labath   if (wait_pid != tid) {
702a6321a8eSPavel Labath     LLDB_LOG(log,
703a6321a8eSPavel Labath              "waiting for tid {0} failed. Assuming the thread has "
704a6321a8eSPavel Labath              "disappeared in the meantime",
705a6321a8eSPavel Labath              tid);
706426bdf88SPavel Labath     // The only way I know of this could happen is if the whole process was
707b9c1b51eSKate Stone     // SIGKILLed in the mean time. In any case, we can't do anything about that
708b9c1b51eSKate Stone     // now.
709426bdf88SPavel Labath     return;
710426bdf88SPavel Labath   }
711b9c1b51eSKate Stone   if (WIFEXITED(status)) {
712a6321a8eSPavel Labath     LLDB_LOG(log,
713a6321a8eSPavel Labath              "waiting for tid {0} returned an 'exited' event. Not "
714a6321a8eSPavel Labath              "tracking the thread.",
715a6321a8eSPavel Labath              tid);
716426bdf88SPavel Labath     // Also a very improbable event.
717426bdf88SPavel Labath     return;
718426bdf88SPavel Labath   }
719426bdf88SPavel Labath 
720a6321a8eSPavel Labath   LLDB_LOG(log, "pid = {0}: tracking new thread tid {1}", GetID(), tid);
721f9077782SPavel Labath   new_thread_sp = AddThread(tid);
722b9cc0c75SPavel Labath   ResumeThread(*new_thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
723f9077782SPavel Labath   ThreadWasCreated(*new_thread_sp);
724426bdf88SPavel Labath }
725426bdf88SPavel Labath 
726b9c1b51eSKate Stone void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info,
727b9c1b51eSKate Stone                                         NativeThreadLinux &thread) {
728a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
729b9cc0c75SPavel Labath   const bool is_main_thread = (thread.GetID() == GetID());
730af245d11STodd Fiala 
731b9cc0c75SPavel Labath   assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
732af245d11STodd Fiala 
733b9c1b51eSKate Stone   switch (info.si_code) {
734b9c1b51eSKate Stone   // TODO: these two cases are required if we want to support tracing of the
735b9c1b51eSKate Stone   // inferiors' children.  We'd need this to debug a monitor.
736af245d11STodd Fiala   // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
737af245d11STodd Fiala   // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
738af245d11STodd Fiala 
739b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): {
740b9c1b51eSKate Stone     // This is the notification on the parent thread which informs us of new
741b9c1b51eSKate Stone     // thread
742426bdf88SPavel Labath     // creation.
743b9c1b51eSKate Stone     // We don't want to do anything with the parent thread so we just resume it.
744b9c1b51eSKate Stone     // In case we
745b9c1b51eSKate Stone     // want to implement "break on thread creation" functionality, we would need
746b9c1b51eSKate Stone     // to stop
747426bdf88SPavel Labath     // here.
748af245d11STodd Fiala 
749af245d11STodd Fiala     unsigned long event_message = 0;
750b9c1b51eSKate Stone     if (GetEventMessage(thread.GetID(), &event_message).Fail()) {
751a6321a8eSPavel Labath       LLDB_LOG(log,
752a6321a8eSPavel Labath                "pid {0} received thread creation event but "
753a6321a8eSPavel Labath                "GetEventMessage failed so we don't know the new tid",
754a6321a8eSPavel Labath                thread.GetID());
755426bdf88SPavel Labath     } else
756426bdf88SPavel Labath       WaitForNewThread(event_message);
757af245d11STodd Fiala 
758b9cc0c75SPavel Labath     ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
759af245d11STodd Fiala     break;
760af245d11STodd Fiala   }
761af245d11STodd Fiala 
762b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): {
763f9077782SPavel Labath     NativeThreadLinuxSP main_thread_sp;
764a6321a8eSPavel Labath     LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP);
765a9882ceeSTodd Fiala 
7661dbc6c9cSPavel Labath     // Exec clears any pending notifications.
7670e1d729bSPavel Labath     m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
768fa03ad2eSChaoren Lin 
769b9c1b51eSKate Stone     // Remove all but the main thread here.  Linux fork creates a new process
770b9c1b51eSKate Stone     // which only copies the main thread.
771a6321a8eSPavel Labath     LLDB_LOG(log, "exec received, stop tracking all but main thread");
772a9882ceeSTodd Fiala 
773b9c1b51eSKate Stone     for (auto thread_sp : m_threads) {
774a9882ceeSTodd Fiala       const bool is_main_thread = thread_sp && thread_sp->GetID() == GetID();
775b9c1b51eSKate Stone       if (is_main_thread) {
776f9077782SPavel Labath         main_thread_sp = std::static_pointer_cast<NativeThreadLinux>(thread_sp);
777a6321a8eSPavel Labath         LLDB_LOG(log, "found main thread with tid {0}, keeping",
778a6321a8eSPavel Labath                  main_thread_sp->GetID());
779b9c1b51eSKate Stone       } else {
780a6321a8eSPavel Labath         LLDB_LOG(log, "discarding non-main-thread tid {0} due to exec",
781a6321a8eSPavel Labath                  thread_sp->GetID());
782a9882ceeSTodd Fiala       }
783a9882ceeSTodd Fiala     }
784a9882ceeSTodd Fiala 
785a9882ceeSTodd Fiala     m_threads.clear();
786a9882ceeSTodd Fiala 
787b9c1b51eSKate Stone     if (main_thread_sp) {
788a9882ceeSTodd Fiala       m_threads.push_back(main_thread_sp);
789a9882ceeSTodd Fiala       SetCurrentThreadID(main_thread_sp->GetID());
790f9077782SPavel Labath       main_thread_sp->SetStoppedByExec();
791b9c1b51eSKate Stone     } else {
792a9882ceeSTodd Fiala       SetCurrentThreadID(LLDB_INVALID_THREAD_ID);
793a6321a8eSPavel Labath       LLDB_LOG(log,
794a6321a8eSPavel Labath                "pid {0} no main thread found, discarded all threads, "
795a6321a8eSPavel Labath                "we're in a no-thread state!",
796a6321a8eSPavel Labath                GetID());
797a9882ceeSTodd Fiala     }
798a9882ceeSTodd Fiala 
799fa03ad2eSChaoren Lin     // Tell coordinator about about the "new" (since exec) stopped main thread.
800f9077782SPavel Labath     ThreadWasCreated(*main_thread_sp);
801fa03ad2eSChaoren Lin 
802a9882ceeSTodd Fiala     // Let our delegate know we have just exec'd.
803a9882ceeSTodd Fiala     NotifyDidExec();
804a9882ceeSTodd Fiala 
805a9882ceeSTodd Fiala     // If we have a main thread, indicate we are stopped.
806b9c1b51eSKate Stone     assert(main_thread_sp && "exec called during ptraced process but no main "
807b9c1b51eSKate Stone                              "thread metadata tracked");
808fa03ad2eSChaoren Lin 
809fa03ad2eSChaoren Lin     // Let the process know we're stopped.
810b9cc0c75SPavel Labath     StopRunningThreads(main_thread_sp->GetID());
811a9882ceeSTodd Fiala 
812af245d11STodd Fiala     break;
813a9882ceeSTodd Fiala   }
814af245d11STodd Fiala 
815b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): {
816af245d11STodd Fiala     // The inferior process or one of its threads is about to exit.
817b9c1b51eSKate Stone     // We don't want to do anything with the thread so we just resume it. In
818b9c1b51eSKate Stone     // case we
819b9c1b51eSKate Stone     // want to implement "break on thread exit" functionality, we would need to
820b9c1b51eSKate Stone     // stop
8216e35163cSPavel Labath     // here.
822fa03ad2eSChaoren Lin 
823af245d11STodd Fiala     unsigned long data = 0;
824b9cc0c75SPavel Labath     if (GetEventMessage(thread.GetID(), &data).Fail())
825af245d11STodd Fiala       data = -1;
826af245d11STodd Fiala 
827a6321a8eSPavel Labath     LLDB_LOG(log,
828a6321a8eSPavel Labath              "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
829a6321a8eSPavel Labath              "WIFSIGNALED={2}, pid = {3}, main_thread = {4}",
830a6321a8eSPavel Labath              data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(),
831a6321a8eSPavel Labath              is_main_thread);
832af245d11STodd Fiala 
833b9c1b51eSKate Stone     if (is_main_thread) {
834b9c1b51eSKate Stone       SetExitStatus(convert_pid_status_to_exit_type(data),
835b9c1b51eSKate Stone                     convert_pid_status_to_return_code(data), nullptr, true);
83675f47c3aSTodd Fiala     }
83775f47c3aSTodd Fiala 
83886852d36SPavel Labath     StateType state = thread.GetState();
839b9c1b51eSKate Stone     if (!StateIsRunningState(state)) {
840b9c1b51eSKate Stone       // Due to a kernel bug, we may sometimes get this stop after the inferior
841b9c1b51eSKate Stone       // gets a
842b9c1b51eSKate Stone       // SIGKILL. This confuses our state tracking logic in ResumeThread(),
843b9c1b51eSKate Stone       // since normally,
844b9c1b51eSKate Stone       // we should not be receiving any ptrace events while the inferior is
845b9c1b51eSKate Stone       // stopped. This
84686852d36SPavel Labath       // makes sure that the inferior is resumed and exits normally.
84786852d36SPavel Labath       state = eStateRunning;
84886852d36SPavel Labath     }
84986852d36SPavel Labath     ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
850af245d11STodd Fiala 
851af245d11STodd Fiala     break;
852af245d11STodd Fiala   }
853af245d11STodd Fiala 
854af245d11STodd Fiala   case 0:
855c16f5dcaSChaoren Lin   case TRAP_TRACE:  // We receive this on single stepping.
856c16f5dcaSChaoren Lin   case TRAP_HWBKPT: // We receive this on watchpoint hit
85786fd8e45SChaoren Lin   {
858c16f5dcaSChaoren Lin     // If a watchpoint was hit, report it
859c16f5dcaSChaoren Lin     uint32_t wp_index;
860b9c1b51eSKate Stone     Error error = thread.GetRegisterContext()->GetWatchpointHitIndex(
861b9c1b51eSKate Stone         wp_index, (uintptr_t)info.si_addr);
862a6321a8eSPavel Labath     if (error.Fail())
863a6321a8eSPavel Labath       LLDB_LOG(log,
864a6321a8eSPavel Labath                "received error while checking for watchpoint hits, pid = "
865a6321a8eSPavel Labath                "{0}, error = {1}",
866a6321a8eSPavel Labath                thread.GetID(), error);
867b9c1b51eSKate Stone     if (wp_index != LLDB_INVALID_INDEX32) {
868b9cc0c75SPavel Labath       MonitorWatchpoint(thread, wp_index);
869c16f5dcaSChaoren Lin       break;
870c16f5dcaSChaoren Lin     }
871b9cc0c75SPavel Labath 
872d5ffbad2SOmair Javaid     // If a breakpoint was hit, report it
873d5ffbad2SOmair Javaid     uint32_t bp_index;
874d5ffbad2SOmair Javaid     error = thread.GetRegisterContext()->GetHardwareBreakHitIndex(
875d5ffbad2SOmair Javaid         bp_index, (uintptr_t)info.si_addr);
876d5ffbad2SOmair Javaid     if (error.Fail())
877d5ffbad2SOmair Javaid       LLDB_LOG(log, "received error while checking for hardware "
878d5ffbad2SOmair Javaid                     "breakpoint hits, pid = {0}, error = {1}",
879d5ffbad2SOmair Javaid                thread.GetID(), error);
880d5ffbad2SOmair Javaid     if (bp_index != LLDB_INVALID_INDEX32) {
881d5ffbad2SOmair Javaid       MonitorBreakpoint(thread);
882d5ffbad2SOmair Javaid       break;
883d5ffbad2SOmair Javaid     }
884d5ffbad2SOmair Javaid 
885be379e15STamas Berghammer     // Otherwise, report step over
886be379e15STamas Berghammer     MonitorTrace(thread);
887af245d11STodd Fiala     break;
888b9cc0c75SPavel Labath   }
889af245d11STodd Fiala 
890af245d11STodd Fiala   case SI_KERNEL:
89135799963SMohit K. Bhakkad #if defined __mips__
89235799963SMohit K. Bhakkad     // For mips there is no special signal for watchpoint
89335799963SMohit K. Bhakkad     // So we check for watchpoint in kernel trap
89435799963SMohit K. Bhakkad     {
89535799963SMohit K. Bhakkad       // If a watchpoint was hit, report it
89635799963SMohit K. Bhakkad       uint32_t wp_index;
897b9c1b51eSKate Stone       Error error = thread.GetRegisterContext()->GetWatchpointHitIndex(
898b9c1b51eSKate Stone           wp_index, LLDB_INVALID_ADDRESS);
899a6321a8eSPavel Labath       if (error.Fail())
900a6321a8eSPavel Labath         LLDB_LOG(log,
901a6321a8eSPavel Labath                  "received error while checking for watchpoint hits, pid = "
902a6321a8eSPavel Labath                  "{0}, error = {1}",
903a6321a8eSPavel Labath                  thread.GetID(), error);
904b9c1b51eSKate Stone       if (wp_index != LLDB_INVALID_INDEX32) {
905b9cc0c75SPavel Labath         MonitorWatchpoint(thread, wp_index);
90635799963SMohit K. Bhakkad         break;
90735799963SMohit K. Bhakkad       }
90835799963SMohit K. Bhakkad     }
90935799963SMohit K. Bhakkad // NO BREAK
91035799963SMohit K. Bhakkad #endif
911af245d11STodd Fiala   case TRAP_BRKPT:
912b9cc0c75SPavel Labath     MonitorBreakpoint(thread);
913af245d11STodd Fiala     break;
914af245d11STodd Fiala 
915af245d11STodd Fiala   case SIGTRAP:
916af245d11STodd Fiala   case (SIGTRAP | 0x80):
917a6321a8eSPavel Labath     LLDB_LOG(
918a6321a8eSPavel Labath         log,
919a6321a8eSPavel Labath         "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",
920a6321a8eSPavel Labath         info.si_code, GetID(), thread.GetID());
921fa03ad2eSChaoren Lin 
922af245d11STodd Fiala     // Ignore these signals until we know more about them.
923b9cc0c75SPavel Labath     ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
924af245d11STodd Fiala     break;
925af245d11STodd Fiala 
926af245d11STodd Fiala   default:
927a6321a8eSPavel Labath     LLDB_LOG(
928a6321a8eSPavel Labath         log,
929a6321a8eSPavel Labath         "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",
930a6321a8eSPavel Labath         info.si_code, GetID(), thread.GetID());
931a6321a8eSPavel Labath     llvm_unreachable("Unexpected SIGTRAP code!");
932af245d11STodd Fiala     break;
933af245d11STodd Fiala   }
934af245d11STodd Fiala }
935af245d11STodd Fiala 
936b9c1b51eSKate Stone void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) {
937a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
938a6321a8eSPavel Labath   LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID());
939c16f5dcaSChaoren Lin 
9400e1d729bSPavel Labath   // This thread is currently stopped.
941b9cc0c75SPavel Labath   thread.SetStoppedByTrace();
942c16f5dcaSChaoren Lin 
943b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
944c16f5dcaSChaoren Lin }
945c16f5dcaSChaoren Lin 
946b9c1b51eSKate Stone void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) {
947b9c1b51eSKate Stone   Log *log(
948b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
949a6321a8eSPavel Labath   LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID());
950c16f5dcaSChaoren Lin 
951c16f5dcaSChaoren Lin   // Mark the thread as stopped at breakpoint.
952b9cc0c75SPavel Labath   thread.SetStoppedByBreakpoint();
953b9cc0c75SPavel Labath   Error error = FixupBreakpointPCAsNeeded(thread);
954c16f5dcaSChaoren Lin   if (error.Fail())
955a6321a8eSPavel Labath     LLDB_LOG(log, "pid = {0} fixup: {1}", thread.GetID(), error);
956d8c338d4STamas Berghammer 
957b9c1b51eSKate Stone   if (m_threads_stepping_with_breakpoint.find(thread.GetID()) !=
958b9c1b51eSKate Stone       m_threads_stepping_with_breakpoint.end())
959b9cc0c75SPavel Labath     thread.SetStoppedByTrace();
960c16f5dcaSChaoren Lin 
961b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
962c16f5dcaSChaoren Lin }
963c16f5dcaSChaoren Lin 
964b9c1b51eSKate Stone void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread,
965b9c1b51eSKate Stone                                            uint32_t wp_index) {
966b9c1b51eSKate Stone   Log *log(
967b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
968a6321a8eSPavel Labath   LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}",
969a6321a8eSPavel Labath            thread.GetID(), wp_index);
970c16f5dcaSChaoren Lin 
971c16f5dcaSChaoren Lin   // Mark the thread as stopped at watchpoint.
972c16f5dcaSChaoren Lin   // The address is at (lldb::addr_t)info->si_addr if we need it.
973f9077782SPavel Labath   thread.SetStoppedByWatchpoint(wp_index);
974c16f5dcaSChaoren Lin 
975b9c1b51eSKate Stone   // We need to tell all other running threads before we notify the delegate
976b9c1b51eSKate Stone   // about this stop.
977f9077782SPavel Labath   StopRunningThreads(thread.GetID());
978c16f5dcaSChaoren Lin }
979c16f5dcaSChaoren Lin 
980b9c1b51eSKate Stone void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
981b9c1b51eSKate Stone                                        NativeThreadLinux &thread, bool exited) {
982b9cc0c75SPavel Labath   const int signo = info.si_signo;
983b9cc0c75SPavel Labath   const bool is_from_llgs = info.si_pid == getpid();
984af245d11STodd Fiala 
985a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
986af245d11STodd Fiala 
987af245d11STodd Fiala   // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
988af245d11STodd Fiala   // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
989af245d11STodd Fiala   // kill(2) or raise(3).  Similarly for tgkill(2) on Linux.
990af245d11STodd Fiala   //
991af245d11STodd Fiala   // IOW, user generated signals never generate what we consider to be a
992af245d11STodd Fiala   // "crash".
993af245d11STodd Fiala   //
994af245d11STodd Fiala   // Similarly, ACK signals generated by this monitor.
995af245d11STodd Fiala 
996af245d11STodd Fiala   // Handle the signal.
997a6321a8eSPavel Labath   LLDB_LOG(log,
998a6321a8eSPavel Labath            "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
999a6321a8eSPavel Labath            "waitpid pid = {4})",
1000a6321a8eSPavel Labath            Host::GetSignalAsCString(signo), signo, info.si_code,
1001b9cc0c75SPavel Labath            thread.GetID());
100258a2f669STodd Fiala 
100358a2f669STodd Fiala   // Check for thread stop notification.
1004b9c1b51eSKate Stone   if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) {
1005af245d11STodd Fiala     // This is a tgkill()-based stop.
1006a6321a8eSPavel Labath     LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID());
1007fa03ad2eSChaoren Lin 
1008aab58633SChaoren Lin     // Check that we're not already marked with a stop reason.
1009b9c1b51eSKate Stone     // Note this thread really shouldn't already be marked as stopped - if we
1010a6321a8eSPavel Labath     // were, that would imply that the kernel signaled us with the thread
1011a6321a8eSPavel Labath     // stopping which we handled and marked as stopped, and that, without an
1012a6321a8eSPavel Labath     // intervening resume, we received another stop.  It is more likely that we
1013a6321a8eSPavel Labath     // are missing the marking of a run state somewhere if we find that the
1014a6321a8eSPavel Labath     // thread was marked as stopped.
1015b9cc0c75SPavel Labath     const StateType thread_state = thread.GetState();
1016b9c1b51eSKate Stone     if (!StateIsStoppedState(thread_state, false)) {
1017ed89c7feSPavel Labath       // An inferior thread has stopped because of a SIGSTOP we have sent it.
1018b9c1b51eSKate Stone       // Generally, these are not important stops and we don't want to report
1019a6321a8eSPavel Labath       // them as they are just used to stop other threads when one thread (the
1020a6321a8eSPavel Labath       // one with the *real* stop reason) hits a breakpoint (watchpoint,
1021a6321a8eSPavel Labath       // etc...). However, in the case of an asynchronous Interrupt(), this *is*
1022a6321a8eSPavel Labath       // the real stop reason, so we leave the signal intact if this is the
1023a6321a8eSPavel Labath       // thread that was chosen as the triggering thread.
1024b9c1b51eSKate Stone       if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
1025b9cc0c75SPavel Labath         if (m_pending_notification_tid == thread.GetID())
1026b9cc0c75SPavel Labath           thread.SetStoppedBySignal(SIGSTOP, &info);
1027ed89c7feSPavel Labath         else
1028b9cc0c75SPavel Labath           thread.SetStoppedWithNoReason();
1029ed89c7feSPavel Labath 
1030b9cc0c75SPavel Labath         SetCurrentThreadID(thread.GetID());
10310e1d729bSPavel Labath         SignalIfAllThreadsStopped();
1032b9c1b51eSKate Stone       } else {
10330e1d729bSPavel Labath         // We can end up here if stop was initiated by LLGS but by this time a
10340e1d729bSPavel Labath         // thread stop has occurred - maybe initiated by another event.
1035b9cc0c75SPavel Labath         Error error = ResumeThread(thread, thread.GetState(), 0);
1036a6321a8eSPavel Labath         if (error.Fail())
1037a6321a8eSPavel Labath           LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(),
1038a6321a8eSPavel Labath                    error);
10390e1d729bSPavel Labath       }
1040b9c1b51eSKate Stone     } else {
1041a6321a8eSPavel Labath       LLDB_LOG(log,
1042a6321a8eSPavel Labath                "pid {0} tid {1}, thread was already marked as a stopped "
1043a6321a8eSPavel Labath                "state (state={2}), leaving stop signal as is",
10448198db30SPavel Labath                GetID(), thread.GetID(), thread_state);
10450e1d729bSPavel Labath       SignalIfAllThreadsStopped();
1046af245d11STodd Fiala     }
1047af245d11STodd Fiala 
104858a2f669STodd Fiala     // Done handling.
1049af245d11STodd Fiala     return;
1050af245d11STodd Fiala   }
1051af245d11STodd Fiala 
10524a705e7eSPavel Labath   // Check if debugger should stop at this signal or just ignore it
10534a705e7eSPavel Labath   // and resume the inferior.
10544a705e7eSPavel Labath   if (m_signals_to_ignore.find(signo) != m_signals_to_ignore.end()) {
10554a705e7eSPavel Labath      ResumeThread(thread, thread.GetState(), signo);
10564a705e7eSPavel Labath      return;
10574a705e7eSPavel Labath   }
10584a705e7eSPavel Labath 
105986fd8e45SChaoren Lin   // This thread is stopped.
1060a6321a8eSPavel Labath   LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo));
1061b9cc0c75SPavel Labath   thread.SetStoppedBySignal(signo, &info);
106286fd8e45SChaoren Lin 
106386fd8e45SChaoren Lin   // Send a stop to the debugger after we get all other threads to stop.
1064b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
1065511e5cdcSTodd Fiala }
1066af245d11STodd Fiala 
1067e7708688STamas Berghammer namespace {
1068e7708688STamas Berghammer 
1069b9c1b51eSKate Stone struct EmulatorBaton {
1070e7708688STamas Berghammer   NativeProcessLinux *m_process;
1071e7708688STamas Berghammer   NativeRegisterContext *m_reg_context;
10726648fcc3SPavel Labath 
10736648fcc3SPavel Labath   // eRegisterKindDWARF -> RegsiterValue
10746648fcc3SPavel Labath   std::unordered_map<uint32_t, RegisterValue> m_register_values;
1075e7708688STamas Berghammer 
1076b9c1b51eSKate Stone   EmulatorBaton(NativeProcessLinux *process, NativeRegisterContext *reg_context)
1077b9c1b51eSKate Stone       : m_process(process), m_reg_context(reg_context) {}
1078e7708688STamas Berghammer };
1079e7708688STamas Berghammer 
1080e7708688STamas Berghammer } // anonymous namespace
1081e7708688STamas Berghammer 
1082b9c1b51eSKate Stone static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
1083e7708688STamas Berghammer                                  const EmulateInstruction::Context &context,
1084b9c1b51eSKate Stone                                  lldb::addr_t addr, void *dst, size_t length) {
1085e7708688STamas Berghammer   EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
1086e7708688STamas Berghammer 
10873eb4b458SChaoren Lin   size_t bytes_read;
1088e7708688STamas Berghammer   emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
1089e7708688STamas Berghammer   return bytes_read;
1090e7708688STamas Berghammer }
1091e7708688STamas Berghammer 
1092b9c1b51eSKate Stone static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
1093e7708688STamas Berghammer                                  const RegisterInfo *reg_info,
1094b9c1b51eSKate Stone                                  RegisterValue &reg_value) {
1095e7708688STamas Berghammer   EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
1096e7708688STamas Berghammer 
1097b9c1b51eSKate Stone   auto it = emulator_baton->m_register_values.find(
1098b9c1b51eSKate Stone       reg_info->kinds[eRegisterKindDWARF]);
1099b9c1b51eSKate Stone   if (it != emulator_baton->m_register_values.end()) {
11006648fcc3SPavel Labath     reg_value = it->second;
11016648fcc3SPavel Labath     return true;
11026648fcc3SPavel Labath   }
11036648fcc3SPavel Labath 
1104e7708688STamas Berghammer   // The emulator only fill in the dwarf regsiter numbers (and in some case
1105e7708688STamas Berghammer   // the generic register numbers). Get the full register info from the
1106e7708688STamas Berghammer   // register context based on the dwarf register numbers.
1107b9c1b51eSKate Stone   const RegisterInfo *full_reg_info =
1108b9c1b51eSKate Stone       emulator_baton->m_reg_context->GetRegisterInfo(
1109e7708688STamas Berghammer           eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
1110e7708688STamas Berghammer 
1111b9c1b51eSKate Stone   Error error =
1112b9c1b51eSKate Stone       emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
11136648fcc3SPavel Labath   if (error.Success())
11146648fcc3SPavel Labath     return true;
1115cdc22a88SMohit K. Bhakkad 
11166648fcc3SPavel Labath   return false;
1117e7708688STamas Berghammer }
1118e7708688STamas Berghammer 
1119b9c1b51eSKate Stone static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
1120e7708688STamas Berghammer                                   const EmulateInstruction::Context &context,
1121e7708688STamas Berghammer                                   const RegisterInfo *reg_info,
1122b9c1b51eSKate Stone                                   const RegisterValue &reg_value) {
1123e7708688STamas Berghammer   EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
1124b9c1b51eSKate Stone   emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
1125b9c1b51eSKate Stone       reg_value;
1126e7708688STamas Berghammer   return true;
1127e7708688STamas Berghammer }
1128e7708688STamas Berghammer 
1129b9c1b51eSKate Stone static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
1130e7708688STamas Berghammer                                   const EmulateInstruction::Context &context,
1131b9c1b51eSKate Stone                                   lldb::addr_t addr, const void *dst,
1132b9c1b51eSKate Stone                                   size_t length) {
1133e7708688STamas Berghammer   return length;
1134e7708688STamas Berghammer }
1135e7708688STamas Berghammer 
1136b9c1b51eSKate Stone static lldb::addr_t ReadFlags(NativeRegisterContext *regsiter_context) {
1137e7708688STamas Berghammer   const RegisterInfo *flags_info = regsiter_context->GetRegisterInfo(
1138e7708688STamas Berghammer       eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1139b9c1b51eSKate Stone   return regsiter_context->ReadRegisterAsUnsigned(flags_info,
1140b9c1b51eSKate Stone                                                   LLDB_INVALID_ADDRESS);
1141e7708688STamas Berghammer }
1142e7708688STamas Berghammer 
1143b9c1b51eSKate Stone Error NativeProcessLinux::SetupSoftwareSingleStepping(
1144b9c1b51eSKate Stone     NativeThreadLinux &thread) {
1145e7708688STamas Berghammer   Error error;
1146b9cc0c75SPavel Labath   NativeRegisterContextSP register_context_sp = thread.GetRegisterContext();
1147e7708688STamas Berghammer 
1148e7708688STamas Berghammer   std::unique_ptr<EmulateInstruction> emulator_ap(
1149b9c1b51eSKate Stone       EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying,
1150b9c1b51eSKate Stone                                      nullptr));
1151e7708688STamas Berghammer 
1152e7708688STamas Berghammer   if (emulator_ap == nullptr)
1153e7708688STamas Berghammer     return Error("Instruction emulator not found!");
1154e7708688STamas Berghammer 
1155e7708688STamas Berghammer   EmulatorBaton baton(this, register_context_sp.get());
1156e7708688STamas Berghammer   emulator_ap->SetBaton(&baton);
1157e7708688STamas Berghammer   emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
1158e7708688STamas Berghammer   emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
1159e7708688STamas Berghammer   emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
1160e7708688STamas Berghammer   emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
1161e7708688STamas Berghammer 
1162e7708688STamas Berghammer   if (!emulator_ap->ReadInstruction())
1163e7708688STamas Berghammer     return Error("Read instruction failed!");
1164e7708688STamas Berghammer 
1165b9c1b51eSKate Stone   bool emulation_result =
1166b9c1b51eSKate Stone       emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
11676648fcc3SPavel Labath 
1168b9c1b51eSKate Stone   const RegisterInfo *reg_info_pc = register_context_sp->GetRegisterInfo(
1169b9c1b51eSKate Stone       eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1170b9c1b51eSKate Stone   const RegisterInfo *reg_info_flags = register_context_sp->GetRegisterInfo(
1171b9c1b51eSKate Stone       eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
11726648fcc3SPavel Labath 
1173b9c1b51eSKate Stone   auto pc_it =
1174b9c1b51eSKate Stone       baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1175b9c1b51eSKate Stone   auto flags_it =
1176b9c1b51eSKate Stone       baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
11776648fcc3SPavel Labath 
1178e7708688STamas Berghammer   lldb::addr_t next_pc;
1179e7708688STamas Berghammer   lldb::addr_t next_flags;
1180b9c1b51eSKate Stone   if (emulation_result) {
1181b9c1b51eSKate Stone     assert(pc_it != baton.m_register_values.end() &&
1182b9c1b51eSKate Stone            "Emulation was successfull but PC wasn't updated");
11836648fcc3SPavel Labath     next_pc = pc_it->second.GetAsUInt64();
11846648fcc3SPavel Labath 
11856648fcc3SPavel Labath     if (flags_it != baton.m_register_values.end())
11866648fcc3SPavel Labath       next_flags = flags_it->second.GetAsUInt64();
1187e7708688STamas Berghammer     else
1188e7708688STamas Berghammer       next_flags = ReadFlags(register_context_sp.get());
1189b9c1b51eSKate Stone   } else if (pc_it == baton.m_register_values.end()) {
1190e7708688STamas Berghammer     // Emulate instruction failed and it haven't changed PC. Advance PC
1191e7708688STamas Berghammer     // with the size of the current opcode because the emulation of all
1192e7708688STamas Berghammer     // PC modifying instruction should be successful. The failure most
1193e7708688STamas Berghammer     // likely caused by a not supported instruction which don't modify PC.
1194b9c1b51eSKate Stone     next_pc =
1195b9c1b51eSKate Stone         register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
1196e7708688STamas Berghammer     next_flags = ReadFlags(register_context_sp.get());
1197b9c1b51eSKate Stone   } else {
1198e7708688STamas Berghammer     // The instruction emulation failed after it modified the PC. It is an
1199e7708688STamas Berghammer     // unknown error where we can't continue because the next instruction is
1200e7708688STamas Berghammer     // modifying the PC but we don't  know how.
1201e7708688STamas Berghammer     return Error("Instruction emulation failed unexpectedly.");
1202e7708688STamas Berghammer   }
1203e7708688STamas Berghammer 
1204b9c1b51eSKate Stone   if (m_arch.GetMachine() == llvm::Triple::arm) {
1205b9c1b51eSKate Stone     if (next_flags & 0x20) {
1206e7708688STamas Berghammer       // Thumb mode
1207e7708688STamas Berghammer       error = SetSoftwareBreakpoint(next_pc, 2);
1208b9c1b51eSKate Stone     } else {
1209e7708688STamas Berghammer       // Arm mode
1210e7708688STamas Berghammer       error = SetSoftwareBreakpoint(next_pc, 4);
1211e7708688STamas Berghammer     }
1212b9c1b51eSKate Stone   } else if (m_arch.GetMachine() == llvm::Triple::mips64 ||
1213b9c1b51eSKate Stone              m_arch.GetMachine() == llvm::Triple::mips64el ||
1214b9c1b51eSKate Stone              m_arch.GetMachine() == llvm::Triple::mips ||
1215b9c1b51eSKate Stone              m_arch.GetMachine() == llvm::Triple::mipsel)
1216cdc22a88SMohit K. Bhakkad     error = SetSoftwareBreakpoint(next_pc, 4);
1217b9c1b51eSKate Stone   else {
1218e7708688STamas Berghammer     // No size hint is given for the next breakpoint
1219e7708688STamas Berghammer     error = SetSoftwareBreakpoint(next_pc, 0);
1220e7708688STamas Berghammer   }
1221e7708688STamas Berghammer 
122242eb6908SPavel Labath   // If setting the breakpoint fails because next_pc is out of
122342eb6908SPavel Labath   // the address space, ignore it and let the debugee segfault.
122442eb6908SPavel Labath   if (error.GetError() == EIO || error.GetError() == EFAULT) {
1225665be50eSMehdi Amini     return Error();
122642eb6908SPavel Labath   } else if (error.Fail())
1227e7708688STamas Berghammer     return error;
1228e7708688STamas Berghammer 
1229b9cc0c75SPavel Labath   m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
1230e7708688STamas Berghammer 
1231665be50eSMehdi Amini   return Error();
1232e7708688STamas Berghammer }
1233e7708688STamas Berghammer 
1234b9c1b51eSKate Stone bool NativeProcessLinux::SupportHardwareSingleStepping() const {
1235b9c1b51eSKate Stone   if (m_arch.GetMachine() == llvm::Triple::arm ||
1236b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mips64 ||
1237b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mips64el ||
1238b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mips ||
1239b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mipsel)
1240cdc22a88SMohit K. Bhakkad     return false;
1241cdc22a88SMohit K. Bhakkad   return true;
1242e7708688STamas Berghammer }
1243e7708688STamas Berghammer 
1244b9c1b51eSKate Stone Error NativeProcessLinux::Resume(const ResumeActionList &resume_actions) {
1245a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1246a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0}", GetID());
1247af245d11STodd Fiala 
1248e7708688STamas Berghammer   bool software_single_step = !SupportHardwareSingleStepping();
1249af245d11STodd Fiala 
1250b9c1b51eSKate Stone   if (software_single_step) {
1251b9c1b51eSKate Stone     for (auto thread_sp : m_threads) {
1252e7708688STamas Berghammer       assert(thread_sp && "thread list should not contain NULL threads");
1253e7708688STamas Berghammer 
1254b9c1b51eSKate Stone       const ResumeAction *const action =
1255b9c1b51eSKate Stone           resume_actions.GetActionForThread(thread_sp->GetID(), true);
1256e7708688STamas Berghammer       if (action == nullptr)
1257e7708688STamas Berghammer         continue;
1258e7708688STamas Berghammer 
1259b9c1b51eSKate Stone       if (action->state == eStateStepping) {
1260b9c1b51eSKate Stone         Error error = SetupSoftwareSingleStepping(
1261b9c1b51eSKate Stone             static_cast<NativeThreadLinux &>(*thread_sp));
1262e7708688STamas Berghammer         if (error.Fail())
1263e7708688STamas Berghammer           return error;
1264e7708688STamas Berghammer       }
1265e7708688STamas Berghammer     }
1266e7708688STamas Berghammer   }
1267e7708688STamas Berghammer 
1268b9c1b51eSKate Stone   for (auto thread_sp : m_threads) {
1269af245d11STodd Fiala     assert(thread_sp && "thread list should not contain NULL threads");
1270af245d11STodd Fiala 
1271b9c1b51eSKate Stone     const ResumeAction *const action =
1272b9c1b51eSKate Stone         resume_actions.GetActionForThread(thread_sp->GetID(), true);
12736a196ce6SChaoren Lin 
1274b9c1b51eSKate Stone     if (action == nullptr) {
1275a6321a8eSPavel Labath       LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
1276a6321a8eSPavel Labath                thread_sp->GetID());
12776a196ce6SChaoren Lin       continue;
12786a196ce6SChaoren Lin     }
1279af245d11STodd Fiala 
1280a6321a8eSPavel Labath     LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}",
12818198db30SPavel Labath              action->state, GetID(), thread_sp->GetID());
1282af245d11STodd Fiala 
1283b9c1b51eSKate Stone     switch (action->state) {
1284af245d11STodd Fiala     case eStateRunning:
1285b9c1b51eSKate Stone     case eStateStepping: {
1286af245d11STodd Fiala       // Run the thread, possibly feeding it the signal.
1287fa03ad2eSChaoren Lin       const int signo = action->signal;
1288b9c1b51eSKate Stone       ResumeThread(static_cast<NativeThreadLinux &>(*thread_sp), action->state,
1289b9c1b51eSKate Stone                    signo);
1290af245d11STodd Fiala       break;
1291ae29d395SChaoren Lin     }
1292af245d11STodd Fiala 
1293af245d11STodd Fiala     case eStateSuspended:
1294af245d11STodd Fiala     case eStateStopped:
1295a6321a8eSPavel Labath       llvm_unreachable("Unexpected state");
1296af245d11STodd Fiala 
1297af245d11STodd Fiala     default:
1298b9c1b51eSKate Stone       return Error("NativeProcessLinux::%s (): unexpected state %s specified "
1299b9c1b51eSKate Stone                    "for pid %" PRIu64 ", tid %" PRIu64,
1300b9c1b51eSKate Stone                    __FUNCTION__, StateAsCString(action->state), GetID(),
1301b9c1b51eSKate Stone                    thread_sp->GetID());
1302af245d11STodd Fiala     }
1303af245d11STodd Fiala   }
1304af245d11STodd Fiala 
1305665be50eSMehdi Amini   return Error();
1306af245d11STodd Fiala }
1307af245d11STodd Fiala 
1308b9c1b51eSKate Stone Error NativeProcessLinux::Halt() {
1309af245d11STodd Fiala   Error error;
1310af245d11STodd Fiala 
1311af245d11STodd Fiala   if (kill(GetID(), SIGSTOP) != 0)
1312af245d11STodd Fiala     error.SetErrorToErrno();
1313af245d11STodd Fiala 
1314af245d11STodd Fiala   return error;
1315af245d11STodd Fiala }
1316af245d11STodd Fiala 
1317b9c1b51eSKate Stone Error NativeProcessLinux::Detach() {
1318af245d11STodd Fiala   Error error;
1319af245d11STodd Fiala 
1320af245d11STodd Fiala   // Stop monitoring the inferior.
132119cbe96aSPavel Labath   m_sigchld_handle.reset();
1322af245d11STodd Fiala 
13237a9495bcSPavel Labath   // Tell ptrace to detach from the process.
13247a9495bcSPavel Labath   if (GetID() == LLDB_INVALID_PROCESS_ID)
13257a9495bcSPavel Labath     return error;
13267a9495bcSPavel Labath 
1327b9c1b51eSKate Stone   for (auto thread_sp : m_threads) {
13287a9495bcSPavel Labath     Error e = Detach(thread_sp->GetID());
13297a9495bcSPavel Labath     if (e.Fail())
1330b9c1b51eSKate Stone       error =
1331b9c1b51eSKate Stone           e; // Save the error, but still attempt to detach from other threads.
13327a9495bcSPavel Labath   }
13337a9495bcSPavel Labath 
1334af245d11STodd Fiala   return error;
1335af245d11STodd Fiala }
1336af245d11STodd Fiala 
1337b9c1b51eSKate Stone Error NativeProcessLinux::Signal(int signo) {
1338af245d11STodd Fiala   Error error;
1339af245d11STodd Fiala 
1340a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1341a6321a8eSPavel Labath   LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo,
1342a6321a8eSPavel Labath            Host::GetSignalAsCString(signo), GetID());
1343af245d11STodd Fiala 
1344af245d11STodd Fiala   if (kill(GetID(), signo))
1345af245d11STodd Fiala     error.SetErrorToErrno();
1346af245d11STodd Fiala 
1347af245d11STodd Fiala   return error;
1348af245d11STodd Fiala }
1349af245d11STodd Fiala 
1350b9c1b51eSKate Stone Error NativeProcessLinux::Interrupt() {
1351e9547b80SChaoren Lin   // Pick a running thread (or if none, a not-dead stopped thread) as
1352e9547b80SChaoren Lin   // the chosen thread that will be the stop-reason thread.
1353a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1354e9547b80SChaoren Lin 
1355e9547b80SChaoren Lin   NativeThreadProtocolSP running_thread_sp;
1356e9547b80SChaoren Lin   NativeThreadProtocolSP stopped_thread_sp;
1357e9547b80SChaoren Lin 
1358a6321a8eSPavel Labath   LLDB_LOG(log, "selecting running thread for interrupt target");
1359b9c1b51eSKate Stone   for (auto thread_sp : m_threads) {
1360e9547b80SChaoren Lin     // The thread shouldn't be null but lets just cover that here.
1361e9547b80SChaoren Lin     if (!thread_sp)
1362e9547b80SChaoren Lin       continue;
1363e9547b80SChaoren Lin 
1364e9547b80SChaoren Lin     // If we have a running or stepping thread, we'll call that the
1365e9547b80SChaoren Lin     // target of the interrupt.
1366e9547b80SChaoren Lin     const auto thread_state = thread_sp->GetState();
1367b9c1b51eSKate Stone     if (thread_state == eStateRunning || thread_state == eStateStepping) {
1368e9547b80SChaoren Lin       running_thread_sp = thread_sp;
1369e9547b80SChaoren Lin       break;
1370b9c1b51eSKate Stone     } else if (!stopped_thread_sp && StateIsStoppedState(thread_state, true)) {
1371b9c1b51eSKate Stone       // Remember the first non-dead stopped thread.  We'll use that as a backup
1372b9c1b51eSKate Stone       // if there are no running threads.
1373e9547b80SChaoren Lin       stopped_thread_sp = thread_sp;
1374e9547b80SChaoren Lin     }
1375e9547b80SChaoren Lin   }
1376e9547b80SChaoren Lin 
1377b9c1b51eSKate Stone   if (!running_thread_sp && !stopped_thread_sp) {
1378b9c1b51eSKate Stone     Error error("found no running/stepping or live stopped threads as target "
1379b9c1b51eSKate Stone                 "for interrupt");
1380a6321a8eSPavel Labath     LLDB_LOG(log, "skipping due to error: {0}", error);
13815830aa75STamas Berghammer 
1382e9547b80SChaoren Lin     return error;
1383e9547b80SChaoren Lin   }
1384e9547b80SChaoren Lin 
1385b9c1b51eSKate Stone   NativeThreadProtocolSP deferred_signal_thread_sp =
1386b9c1b51eSKate Stone       running_thread_sp ? running_thread_sp : stopped_thread_sp;
1387e9547b80SChaoren Lin 
1388a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(),
1389e9547b80SChaoren Lin            running_thread_sp ? "running" : "stopped",
1390e9547b80SChaoren Lin            deferred_signal_thread_sp->GetID());
1391e9547b80SChaoren Lin 
1392ed89c7feSPavel Labath   StopRunningThreads(deferred_signal_thread_sp->GetID());
139345f5cb31SPavel Labath 
1394665be50eSMehdi Amini   return Error();
1395e9547b80SChaoren Lin }
1396e9547b80SChaoren Lin 
1397b9c1b51eSKate Stone Error NativeProcessLinux::Kill() {
1398a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1399a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0}", GetID());
1400af245d11STodd Fiala 
1401af245d11STodd Fiala   Error error;
1402af245d11STodd Fiala 
1403b9c1b51eSKate Stone   switch (m_state) {
1404af245d11STodd Fiala   case StateType::eStateInvalid:
1405af245d11STodd Fiala   case StateType::eStateExited:
1406af245d11STodd Fiala   case StateType::eStateCrashed:
1407af245d11STodd Fiala   case StateType::eStateDetached:
1408af245d11STodd Fiala   case StateType::eStateUnloaded:
1409af245d11STodd Fiala     // Nothing to do - the process is already dead.
1410a6321a8eSPavel Labath     LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
14118198db30SPavel Labath              m_state);
1412af245d11STodd Fiala     return error;
1413af245d11STodd Fiala 
1414af245d11STodd Fiala   case StateType::eStateConnected:
1415af245d11STodd Fiala   case StateType::eStateAttaching:
1416af245d11STodd Fiala   case StateType::eStateLaunching:
1417af245d11STodd Fiala   case StateType::eStateStopped:
1418af245d11STodd Fiala   case StateType::eStateRunning:
1419af245d11STodd Fiala   case StateType::eStateStepping:
1420af245d11STodd Fiala   case StateType::eStateSuspended:
1421af245d11STodd Fiala     // We can try to kill a process in these states.
1422af245d11STodd Fiala     break;
1423af245d11STodd Fiala   }
1424af245d11STodd Fiala 
1425b9c1b51eSKate Stone   if (kill(GetID(), SIGKILL) != 0) {
1426af245d11STodd Fiala     error.SetErrorToErrno();
1427af245d11STodd Fiala     return error;
1428af245d11STodd Fiala   }
1429af245d11STodd Fiala 
1430af245d11STodd Fiala   return error;
1431af245d11STodd Fiala }
1432af245d11STodd Fiala 
1433af245d11STodd Fiala static Error
1434*15930862SPavel Labath ParseMemoryRegionInfoFromProcMapsLine(llvm::StringRef &maps_line,
1435b9c1b51eSKate Stone                                       MemoryRegionInfo &memory_region_info) {
1436af245d11STodd Fiala   memory_region_info.Clear();
1437af245d11STodd Fiala 
1438*15930862SPavel Labath   StringExtractor line_extractor(maps_line);
1439af245d11STodd Fiala 
1440b9c1b51eSKate Stone   // Format: {address_start_hex}-{address_end_hex} perms offset  dev   inode
1441b9c1b51eSKate Stone   // pathname
1442b9c1b51eSKate Stone   // perms: rwxp   (letter is present if set, '-' if not, final character is
1443b9c1b51eSKate Stone   // p=private, s=shared).
1444af245d11STodd Fiala 
1445af245d11STodd Fiala   // Parse out the starting address
1446af245d11STodd Fiala   lldb::addr_t start_address = line_extractor.GetHexMaxU64(false, 0);
1447af245d11STodd Fiala 
1448af245d11STodd Fiala   // Parse out hyphen separating start and end address from range.
1449af245d11STodd Fiala   if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != '-'))
1450b9c1b51eSKate Stone     return Error(
1451b9c1b51eSKate Stone         "malformed /proc/{pid}/maps entry, missing dash between address range");
1452af245d11STodd Fiala 
1453af245d11STodd Fiala   // Parse out the ending address
1454af245d11STodd Fiala   lldb::addr_t end_address = line_extractor.GetHexMaxU64(false, start_address);
1455af245d11STodd Fiala 
1456af245d11STodd Fiala   // Parse out the space after the address.
1457af245d11STodd Fiala   if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != ' '))
1458af245d11STodd Fiala     return Error("malformed /proc/{pid}/maps entry, missing space after range");
1459af245d11STodd Fiala 
1460af245d11STodd Fiala   // Save the range.
1461af245d11STodd Fiala   memory_region_info.GetRange().SetRangeBase(start_address);
1462af245d11STodd Fiala   memory_region_info.GetRange().SetRangeEnd(end_address);
1463af245d11STodd Fiala 
1464b9c1b51eSKate Stone   // Any memory region in /proc/{pid}/maps is by definition mapped into the
1465b9c1b51eSKate Stone   // process.
1466ad007563SHoward Hellyer   memory_region_info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
1467ad007563SHoward Hellyer 
1468af245d11STodd Fiala   // Parse out each permission entry.
1469af245d11STodd Fiala   if (line_extractor.GetBytesLeft() < 4)
1470b9c1b51eSKate Stone     return Error("malformed /proc/{pid}/maps entry, missing some portion of "
1471b9c1b51eSKate Stone                  "permissions");
1472af245d11STodd Fiala 
1473af245d11STodd Fiala   // Handle read permission.
1474af245d11STodd Fiala   const char read_perm_char = line_extractor.GetChar();
1475af245d11STodd Fiala   if (read_perm_char == 'r')
1476af245d11STodd Fiala     memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eYes);
1477c73301bbSTamas Berghammer   else if (read_perm_char == '-')
1478af245d11STodd Fiala     memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1479c73301bbSTamas Berghammer   else
1480c73301bbSTamas Berghammer     return Error("unexpected /proc/{pid}/maps read permission char");
1481af245d11STodd Fiala 
1482af245d11STodd Fiala   // Handle write permission.
1483af245d11STodd Fiala   const char write_perm_char = line_extractor.GetChar();
1484af245d11STodd Fiala   if (write_perm_char == 'w')
1485af245d11STodd Fiala     memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eYes);
1486c73301bbSTamas Berghammer   else if (write_perm_char == '-')
1487af245d11STodd Fiala     memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1488c73301bbSTamas Berghammer   else
1489c73301bbSTamas Berghammer     return Error("unexpected /proc/{pid}/maps write permission char");
1490af245d11STodd Fiala 
1491af245d11STodd Fiala   // Handle execute permission.
1492af245d11STodd Fiala   const char exec_perm_char = line_extractor.GetChar();
1493af245d11STodd Fiala   if (exec_perm_char == 'x')
1494af245d11STodd Fiala     memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes);
1495c73301bbSTamas Berghammer   else if (exec_perm_char == '-')
1496af245d11STodd Fiala     memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1497c73301bbSTamas Berghammer   else
1498c73301bbSTamas Berghammer     return Error("unexpected /proc/{pid}/maps exec permission char");
1499af245d11STodd Fiala 
1500d7d69f80STamas Berghammer   line_extractor.GetChar();              // Read the private bit
1501d7d69f80STamas Berghammer   line_extractor.SkipSpaces();           // Skip the separator
1502d7d69f80STamas Berghammer   line_extractor.GetHexMaxU64(false, 0); // Read the offset
1503d7d69f80STamas Berghammer   line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1504d7d69f80STamas Berghammer   line_extractor.GetChar();              // Read the device id separator
1505d7d69f80STamas Berghammer   line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1506d7d69f80STamas Berghammer   line_extractor.SkipSpaces();           // Skip the separator
1507d7d69f80STamas Berghammer   line_extractor.GetU64(0, 10);          // Read the inode number
1508d7d69f80STamas Berghammer 
1509d7d69f80STamas Berghammer   line_extractor.SkipSpaces();
1510b9739d40SPavel Labath   const char *name = line_extractor.Peek();
1511b9739d40SPavel Labath   if (name)
1512b9739d40SPavel Labath     memory_region_info.SetName(name);
1513d7d69f80STamas Berghammer 
1514665be50eSMehdi Amini   return Error();
1515af245d11STodd Fiala }
1516af245d11STodd Fiala 
1517b9c1b51eSKate Stone Error NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr,
1518b9c1b51eSKate Stone                                               MemoryRegionInfo &range_info) {
1519b9c1b51eSKate Stone   // FIXME review that the final memory region returned extends to the end of
1520b9c1b51eSKate Stone   // the virtual address space,
1521af245d11STodd Fiala   // with no perms if it is not mapped.
1522af245d11STodd Fiala 
1523af245d11STodd Fiala   // Use an approach that reads memory regions from /proc/{pid}/maps.
1524af245d11STodd Fiala   // Assume proc maps entries are in ascending order.
1525af245d11STodd Fiala   // FIXME assert if we find differently.
1526af245d11STodd Fiala 
1527b9c1b51eSKate Stone   if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
1528af245d11STodd Fiala     // We're done.
1529a6f5795aSTamas Berghammer     return Error("unsupported");
1530af245d11STodd Fiala   }
1531af245d11STodd Fiala 
1532a6f5795aSTamas Berghammer   Error error = PopulateMemoryRegionCache();
1533b9c1b51eSKate Stone   if (error.Fail()) {
1534af245d11STodd Fiala     return error;
1535af245d11STodd Fiala   }
1536af245d11STodd Fiala 
1537af245d11STodd Fiala   lldb::addr_t prev_base_address = 0;
1538af245d11STodd Fiala 
1539b9c1b51eSKate Stone   // FIXME start by finding the last region that is <= target address using
1540b9c1b51eSKate Stone   // binary search.  Data is sorted.
1541af245d11STodd Fiala   // There can be a ton of regions on pthreads apps with lots of threads.
1542b9c1b51eSKate Stone   for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1543b9c1b51eSKate Stone        ++it) {
1544a6f5795aSTamas Berghammer     MemoryRegionInfo &proc_entry_info = it->first;
1545af245d11STodd Fiala 
1546af245d11STodd Fiala     // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1547b9c1b51eSKate Stone     assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
1548b9c1b51eSKate Stone            "descending /proc/pid/maps entries detected, unexpected");
1549af245d11STodd Fiala     prev_base_address = proc_entry_info.GetRange().GetRangeBase();
1550b1554311SHafiz Abid Qadeer     UNUSED_IF_ASSERT_DISABLED(prev_base_address);
1551af245d11STodd Fiala 
1552b9c1b51eSKate Stone     // If the target address comes before this entry, indicate distance to next
1553b9c1b51eSKate Stone     // region.
1554b9c1b51eSKate Stone     if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1555af245d11STodd Fiala       range_info.GetRange().SetRangeBase(load_addr);
1556b9c1b51eSKate Stone       range_info.GetRange().SetByteSize(
1557b9c1b51eSKate Stone           proc_entry_info.GetRange().GetRangeBase() - load_addr);
1558af245d11STodd Fiala       range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1559af245d11STodd Fiala       range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1560af245d11STodd Fiala       range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1561ad007563SHoward Hellyer       range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1562af245d11STodd Fiala 
1563af245d11STodd Fiala       return error;
1564b9c1b51eSKate Stone     } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1565af245d11STodd Fiala       // The target address is within the memory region we're processing here.
1566af245d11STodd Fiala       range_info = proc_entry_info;
1567af245d11STodd Fiala       return error;
1568af245d11STodd Fiala     }
1569af245d11STodd Fiala 
1570b9c1b51eSKate Stone     // The target memory address comes somewhere after the region we just
1571b9c1b51eSKate Stone     // parsed.
1572af245d11STodd Fiala   }
1573af245d11STodd Fiala 
1574b9c1b51eSKate Stone   // If we made it here, we didn't find an entry that contained the given
1575b9c1b51eSKate Stone   // address. Return the
1576b9c1b51eSKate Stone   // load_addr as start and the amount of bytes betwwen load address and the end
1577b9c1b51eSKate Stone   // of the memory as
157809839c33STamas Berghammer   // size.
157909839c33STamas Berghammer   range_info.GetRange().SetRangeBase(load_addr);
1580ad007563SHoward Hellyer   range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
158109839c33STamas Berghammer   range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
158209839c33STamas Berghammer   range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
158309839c33STamas Berghammer   range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1584ad007563SHoward Hellyer   range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1585af245d11STodd Fiala   return error;
1586af245d11STodd Fiala }
1587af245d11STodd Fiala 
1588a6f5795aSTamas Berghammer Error NativeProcessLinux::PopulateMemoryRegionCache() {
1589a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1590a6f5795aSTamas Berghammer 
1591a6f5795aSTamas Berghammer   // If our cache is empty, pull the latest.  There should always be at least
1592a6f5795aSTamas Berghammer   // one memory region if memory region handling is supported.
1593a6f5795aSTamas Berghammer   if (!m_mem_region_cache.empty()) {
1594a6321a8eSPavel Labath     LLDB_LOG(log, "reusing {0} cached memory region entries",
1595a6321a8eSPavel Labath              m_mem_region_cache.size());
1596a6f5795aSTamas Berghammer     return Error();
1597a6f5795aSTamas Berghammer   }
1598a6f5795aSTamas Berghammer 
1599*15930862SPavel Labath   auto BufferOrError = getProcFile(GetID(), "maps");
1600*15930862SPavel Labath   if (!BufferOrError) {
1601*15930862SPavel Labath     m_supports_mem_region = LazyBool::eLazyBoolNo;
1602*15930862SPavel Labath     return BufferOrError.getError();
1603*15930862SPavel Labath   }
1604*15930862SPavel Labath   StringRef Rest = BufferOrError.get()->getBuffer();
1605*15930862SPavel Labath   while (! Rest.empty()) {
1606*15930862SPavel Labath     StringRef Line;
1607*15930862SPavel Labath     std::tie(Line, Rest) = Rest.split('\n');
1608a6f5795aSTamas Berghammer     MemoryRegionInfo info;
1609*15930862SPavel Labath     const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine(Line, info);
1610*15930862SPavel Labath     if (parse_error.Fail()) {
1611*15930862SPavel Labath       LLDB_LOG(log, "failed to parse proc maps line '{0}': {1}", Line,
1612*15930862SPavel Labath                parse_error);
1613*15930862SPavel Labath       m_supports_mem_region = LazyBool::eLazyBoolNo;
1614*15930862SPavel Labath       return parse_error;
1615*15930862SPavel Labath     }
1616a6f5795aSTamas Berghammer     m_mem_region_cache.emplace_back(
1617a6f5795aSTamas Berghammer         info, FileSpec(info.GetName().GetCString(), true));
1618a6f5795aSTamas Berghammer   }
1619a6f5795aSTamas Berghammer 
1620*15930862SPavel Labath   if (m_mem_region_cache.empty()) {
1621a6f5795aSTamas Berghammer     // No entries after attempting to read them.  This shouldn't happen if
1622a6f5795aSTamas Berghammer     // /proc/{pid}/maps is supported. Assume we don't support map entries
1623a6f5795aSTamas Berghammer     // via procfs.
1624*15930862SPavel Labath     m_supports_mem_region = LazyBool::eLazyBoolNo;
1625a6321a8eSPavel Labath     LLDB_LOG(log,
1626a6321a8eSPavel Labath              "failed to find any procfs maps entries, assuming no support "
1627a6321a8eSPavel Labath              "for memory region metadata retrieval");
1628*15930862SPavel Labath     return Error("not supported");
1629a6f5795aSTamas Berghammer   }
1630a6f5795aSTamas Berghammer 
1631a6321a8eSPavel Labath   LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps",
1632a6321a8eSPavel Labath            m_mem_region_cache.size(), GetID());
1633a6f5795aSTamas Berghammer 
1634a6f5795aSTamas Berghammer   // We support memory retrieval, remember that.
1635a6f5795aSTamas Berghammer   m_supports_mem_region = LazyBool::eLazyBoolYes;
1636a6f5795aSTamas Berghammer   return Error();
1637a6f5795aSTamas Berghammer }
1638a6f5795aSTamas Berghammer 
1639b9c1b51eSKate Stone void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
1640a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1641a6321a8eSPavel Labath   LLDB_LOG(log, "newBumpId={0}", newBumpId);
1642a6321a8eSPavel Labath   LLDB_LOG(log, "clearing {0} entries from memory region cache",
1643a6321a8eSPavel Labath            m_mem_region_cache.size());
1644af245d11STodd Fiala   m_mem_region_cache.clear();
1645af245d11STodd Fiala }
1646af245d11STodd Fiala 
1647b9c1b51eSKate Stone Error NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions,
1648b9c1b51eSKate Stone                                          lldb::addr_t &addr) {
1649af245d11STodd Fiala // FIXME implementing this requires the equivalent of
1650af245d11STodd Fiala // InferiorCallPOSIX::InferiorCallMmap, which depends on
1651af245d11STodd Fiala // functional ThreadPlans working with Native*Protocol.
1652af245d11STodd Fiala #if 1
1653af245d11STodd Fiala   return Error("not implemented yet");
1654af245d11STodd Fiala #else
1655af245d11STodd Fiala   addr = LLDB_INVALID_ADDRESS;
1656af245d11STodd Fiala 
1657af245d11STodd Fiala   unsigned prot = 0;
1658af245d11STodd Fiala   if (permissions & lldb::ePermissionsReadable)
1659af245d11STodd Fiala     prot |= eMmapProtRead;
1660af245d11STodd Fiala   if (permissions & lldb::ePermissionsWritable)
1661af245d11STodd Fiala     prot |= eMmapProtWrite;
1662af245d11STodd Fiala   if (permissions & lldb::ePermissionsExecutable)
1663af245d11STodd Fiala     prot |= eMmapProtExec;
1664af245d11STodd Fiala 
1665af245d11STodd Fiala   // TODO implement this directly in NativeProcessLinux
1666af245d11STodd Fiala   // (and lift to NativeProcessPOSIX if/when that class is
1667af245d11STodd Fiala   // refactored out).
1668af245d11STodd Fiala   if (InferiorCallMmap(this, addr, 0, size, prot,
1669af245d11STodd Fiala                        eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
1670af245d11STodd Fiala     m_addr_to_mmap_size[addr] = size;
1671665be50eSMehdi Amini     return Error();
1672af245d11STodd Fiala   } else {
1673af245d11STodd Fiala     addr = LLDB_INVALID_ADDRESS;
1674b9c1b51eSKate Stone     return Error("unable to allocate %" PRIu64
1675b9c1b51eSKate Stone                  " bytes of memory with permissions %s",
1676b9c1b51eSKate Stone                  size, GetPermissionsAsCString(permissions));
1677af245d11STodd Fiala   }
1678af245d11STodd Fiala #endif
1679af245d11STodd Fiala }
1680af245d11STodd Fiala 
1681b9c1b51eSKate Stone Error NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {
1682af245d11STodd Fiala   // FIXME see comments in AllocateMemory - required lower-level
1683af245d11STodd Fiala   // bits not in place yet (ThreadPlans)
1684af245d11STodd Fiala   return Error("not implemented");
1685af245d11STodd Fiala }
1686af245d11STodd Fiala 
1687b9c1b51eSKate Stone lldb::addr_t NativeProcessLinux::GetSharedLibraryInfoAddress() {
1688af245d11STodd Fiala   // punt on this for now
1689af245d11STodd Fiala   return LLDB_INVALID_ADDRESS;
1690af245d11STodd Fiala }
1691af245d11STodd Fiala 
1692b9c1b51eSKate Stone size_t NativeProcessLinux::UpdateThreads() {
1693af245d11STodd Fiala   // The NativeProcessLinux monitoring threads are always up to date
1694af245d11STodd Fiala   // with respect to thread state and they keep the thread list
1695af245d11STodd Fiala   // populated properly. All this method needs to do is return the
1696af245d11STodd Fiala   // thread count.
1697af245d11STodd Fiala   return m_threads.size();
1698af245d11STodd Fiala }
1699af245d11STodd Fiala 
1700b9c1b51eSKate Stone bool NativeProcessLinux::GetArchitecture(ArchSpec &arch) const {
1701af245d11STodd Fiala   arch = m_arch;
1702af245d11STodd Fiala   return true;
1703af245d11STodd Fiala }
1704af245d11STodd Fiala 
1705b9c1b51eSKate Stone Error NativeProcessLinux::GetSoftwareBreakpointPCOffset(
1706b9c1b51eSKate Stone     uint32_t &actual_opcode_size) {
1707af245d11STodd Fiala   // FIXME put this behind a breakpoint protocol class that can be
1708af245d11STodd Fiala   // set per architecture.  Need ARM, MIPS support here.
1709af245d11STodd Fiala   static const uint8_t g_i386_opcode[] = {0xCC};
1710bb00d0b6SUlrich Weigand   static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
1711af245d11STodd Fiala 
1712b9c1b51eSKate Stone   switch (m_arch.GetMachine()) {
1713af245d11STodd Fiala   case llvm::Triple::x86:
1714af245d11STodd Fiala   case llvm::Triple::x86_64:
1715af245d11STodd Fiala     actual_opcode_size = static_cast<uint32_t>(sizeof(g_i386_opcode));
1716665be50eSMehdi Amini     return Error();
1717af245d11STodd Fiala 
1718bb00d0b6SUlrich Weigand   case llvm::Triple::systemz:
1719bb00d0b6SUlrich Weigand     actual_opcode_size = static_cast<uint32_t>(sizeof(g_s390x_opcode));
1720665be50eSMehdi Amini     return Error();
1721bb00d0b6SUlrich Weigand 
1722ff7fd900STamas Berghammer   case llvm::Triple::arm:
1723ff7fd900STamas Berghammer   case llvm::Triple::aarch64:
1724e8659b5dSMohit K. Bhakkad   case llvm::Triple::mips64:
1725e8659b5dSMohit K. Bhakkad   case llvm::Triple::mips64el:
1726ce815e45SSagar Thakur   case llvm::Triple::mips:
1727ce815e45SSagar Thakur   case llvm::Triple::mipsel:
1728ff7fd900STamas Berghammer     // On these architectures the PC don't get updated for breakpoint hits
1729c60c9452SJaydeep Patil     actual_opcode_size = 0;
1730665be50eSMehdi Amini     return Error();
1731e8659b5dSMohit K. Bhakkad 
1732af245d11STodd Fiala   default:
1733af245d11STodd Fiala     assert(false && "CPU type not supported!");
1734af245d11STodd Fiala     return Error("CPU type not supported");
1735af245d11STodd Fiala   }
1736af245d11STodd Fiala }
1737af245d11STodd Fiala 
1738b9c1b51eSKate Stone Error NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,
1739b9c1b51eSKate Stone                                         bool hardware) {
1740af245d11STodd Fiala   if (hardware)
1741d5ffbad2SOmair Javaid     return SetHardwareBreakpoint(addr, size);
1742af245d11STodd Fiala   else
1743af245d11STodd Fiala     return SetSoftwareBreakpoint(addr, size);
1744af245d11STodd Fiala }
1745af245d11STodd Fiala 
1746d5ffbad2SOmair Javaid Error NativeProcessLinux::RemoveBreakpoint(lldb::addr_t addr, bool hardware) {
1747d5ffbad2SOmair Javaid   if (hardware)
1748d5ffbad2SOmair Javaid     return RemoveHardwareBreakpoint(addr);
1749d5ffbad2SOmair Javaid   else
1750d5ffbad2SOmair Javaid     return NativeProcessProtocol::RemoveBreakpoint(addr);
1751d5ffbad2SOmair Javaid }
1752d5ffbad2SOmair Javaid 
1753b9c1b51eSKate Stone Error NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(
1754b9c1b51eSKate Stone     size_t trap_opcode_size_hint, size_t &actual_opcode_size,
1755b9c1b51eSKate Stone     const uint8_t *&trap_opcode_bytes) {
175663c8be95STamas Berghammer   // FIXME put this behind a breakpoint protocol class that can be set per
175763c8be95STamas Berghammer   // architecture.  Need MIPS support here.
17582afc5966STodd Fiala   static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};
1759be379e15STamas Berghammer   // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1760be379e15STamas Berghammer   // linux kernel does otherwise.
1761be379e15STamas Berghammer   static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1762af245d11STodd Fiala   static const uint8_t g_i386_opcode[] = {0xCC};
17633df471c3SMohit K. Bhakkad   static const uint8_t g_mips64_opcode[] = {0x00, 0x00, 0x00, 0x0d};
17642c2acf96SMohit K. Bhakkad   static const uint8_t g_mips64el_opcode[] = {0x0d, 0x00, 0x00, 0x00};
1765bb00d0b6SUlrich Weigand   static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
1766be379e15STamas Berghammer   static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
1767af245d11STodd Fiala 
1768b9c1b51eSKate Stone   switch (m_arch.GetMachine()) {
17692afc5966STodd Fiala   case llvm::Triple::aarch64:
17702afc5966STodd Fiala     trap_opcode_bytes = g_aarch64_opcode;
17712afc5966STodd Fiala     actual_opcode_size = sizeof(g_aarch64_opcode);
1772665be50eSMehdi Amini     return Error();
17732afc5966STodd Fiala 
177463c8be95STamas Berghammer   case llvm::Triple::arm:
1775b9c1b51eSKate Stone     switch (trap_opcode_size_hint) {
177663c8be95STamas Berghammer     case 2:
177763c8be95STamas Berghammer       trap_opcode_bytes = g_thumb_breakpoint_opcode;
177863c8be95STamas Berghammer       actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
1779665be50eSMehdi Amini       return Error();
178063c8be95STamas Berghammer     case 4:
178163c8be95STamas Berghammer       trap_opcode_bytes = g_arm_breakpoint_opcode;
178263c8be95STamas Berghammer       actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
1783665be50eSMehdi Amini       return Error();
178463c8be95STamas Berghammer     default:
178563c8be95STamas Berghammer       assert(false && "Unrecognised trap opcode size hint!");
178663c8be95STamas Berghammer       return Error("Unrecognised trap opcode size hint!");
178763c8be95STamas Berghammer     }
178863c8be95STamas Berghammer 
1789af245d11STodd Fiala   case llvm::Triple::x86:
1790af245d11STodd Fiala   case llvm::Triple::x86_64:
1791af245d11STodd Fiala     trap_opcode_bytes = g_i386_opcode;
1792af245d11STodd Fiala     actual_opcode_size = sizeof(g_i386_opcode);
1793665be50eSMehdi Amini     return Error();
1794af245d11STodd Fiala 
1795ce815e45SSagar Thakur   case llvm::Triple::mips:
17963df471c3SMohit K. Bhakkad   case llvm::Triple::mips64:
17973df471c3SMohit K. Bhakkad     trap_opcode_bytes = g_mips64_opcode;
17983df471c3SMohit K. Bhakkad     actual_opcode_size = sizeof(g_mips64_opcode);
1799665be50eSMehdi Amini     return Error();
18003df471c3SMohit K. Bhakkad 
1801ce815e45SSagar Thakur   case llvm::Triple::mipsel:
18022c2acf96SMohit K. Bhakkad   case llvm::Triple::mips64el:
18032c2acf96SMohit K. Bhakkad     trap_opcode_bytes = g_mips64el_opcode;
18042c2acf96SMohit K. Bhakkad     actual_opcode_size = sizeof(g_mips64el_opcode);
1805665be50eSMehdi Amini     return Error();
18062c2acf96SMohit K. Bhakkad 
1807bb00d0b6SUlrich Weigand   case llvm::Triple::systemz:
1808bb00d0b6SUlrich Weigand     trap_opcode_bytes = g_s390x_opcode;
1809bb00d0b6SUlrich Weigand     actual_opcode_size = sizeof(g_s390x_opcode);
1810665be50eSMehdi Amini     return Error();
1811bb00d0b6SUlrich Weigand 
1812af245d11STodd Fiala   default:
1813af245d11STodd Fiala     assert(false && "CPU type not supported!");
1814af245d11STodd Fiala     return Error("CPU type not supported");
1815af245d11STodd Fiala   }
1816af245d11STodd Fiala }
1817af245d11STodd Fiala 
1818af245d11STodd Fiala #if 0
1819af245d11STodd Fiala ProcessMessage::CrashReason
1820af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
1821af245d11STodd Fiala {
1822af245d11STodd Fiala     ProcessMessage::CrashReason reason;
1823af245d11STodd Fiala     assert(info->si_signo == SIGSEGV);
1824af245d11STodd Fiala 
1825af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
1826af245d11STodd Fiala 
1827af245d11STodd Fiala     switch (info->si_code)
1828af245d11STodd Fiala     {
1829af245d11STodd Fiala     default:
1830af245d11STodd Fiala         assert(false && "unexpected si_code for SIGSEGV");
1831af245d11STodd Fiala         break;
1832af245d11STodd Fiala     case SI_KERNEL:
1833af245d11STodd Fiala         // Linux will occasionally send spurious SI_KERNEL codes.
1834af245d11STodd Fiala         // (this is poorly documented in sigaction)
1835af245d11STodd Fiala         // One way to get this is via unaligned SIMD loads.
1836af245d11STodd Fiala         reason = ProcessMessage::eInvalidAddress; // for lack of anything better
1837af245d11STodd Fiala         break;
1838af245d11STodd Fiala     case SEGV_MAPERR:
1839af245d11STodd Fiala         reason = ProcessMessage::eInvalidAddress;
1840af245d11STodd Fiala         break;
1841af245d11STodd Fiala     case SEGV_ACCERR:
1842af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedAddress;
1843af245d11STodd Fiala         break;
1844af245d11STodd Fiala     }
1845af245d11STodd Fiala 
1846af245d11STodd Fiala     return reason;
1847af245d11STodd Fiala }
1848af245d11STodd Fiala #endif
1849af245d11STodd Fiala 
1850af245d11STodd Fiala #if 0
1851af245d11STodd Fiala ProcessMessage::CrashReason
1852af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
1853af245d11STodd Fiala {
1854af245d11STodd Fiala     ProcessMessage::CrashReason reason;
1855af245d11STodd Fiala     assert(info->si_signo == SIGILL);
1856af245d11STodd Fiala 
1857af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
1858af245d11STodd Fiala 
1859af245d11STodd Fiala     switch (info->si_code)
1860af245d11STodd Fiala     {
1861af245d11STodd Fiala     default:
1862af245d11STodd Fiala         assert(false && "unexpected si_code for SIGILL");
1863af245d11STodd Fiala         break;
1864af245d11STodd Fiala     case ILL_ILLOPC:
1865af245d11STodd Fiala         reason = ProcessMessage::eIllegalOpcode;
1866af245d11STodd Fiala         break;
1867af245d11STodd Fiala     case ILL_ILLOPN:
1868af245d11STodd Fiala         reason = ProcessMessage::eIllegalOperand;
1869af245d11STodd Fiala         break;
1870af245d11STodd Fiala     case ILL_ILLADR:
1871af245d11STodd Fiala         reason = ProcessMessage::eIllegalAddressingMode;
1872af245d11STodd Fiala         break;
1873af245d11STodd Fiala     case ILL_ILLTRP:
1874af245d11STodd Fiala         reason = ProcessMessage::eIllegalTrap;
1875af245d11STodd Fiala         break;
1876af245d11STodd Fiala     case ILL_PRVOPC:
1877af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedOpcode;
1878af245d11STodd Fiala         break;
1879af245d11STodd Fiala     case ILL_PRVREG:
1880af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedRegister;
1881af245d11STodd Fiala         break;
1882af245d11STodd Fiala     case ILL_COPROC:
1883af245d11STodd Fiala         reason = ProcessMessage::eCoprocessorError;
1884af245d11STodd Fiala         break;
1885af245d11STodd Fiala     case ILL_BADSTK:
1886af245d11STodd Fiala         reason = ProcessMessage::eInternalStackError;
1887af245d11STodd Fiala         break;
1888af245d11STodd Fiala     }
1889af245d11STodd Fiala 
1890af245d11STodd Fiala     return reason;
1891af245d11STodd Fiala }
1892af245d11STodd Fiala #endif
1893af245d11STodd Fiala 
1894af245d11STodd Fiala #if 0
1895af245d11STodd Fiala ProcessMessage::CrashReason
1896af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
1897af245d11STodd Fiala {
1898af245d11STodd Fiala     ProcessMessage::CrashReason reason;
1899af245d11STodd Fiala     assert(info->si_signo == SIGFPE);
1900af245d11STodd Fiala 
1901af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
1902af245d11STodd Fiala 
1903af245d11STodd Fiala     switch (info->si_code)
1904af245d11STodd Fiala     {
1905af245d11STodd Fiala     default:
1906af245d11STodd Fiala         assert(false && "unexpected si_code for SIGFPE");
1907af245d11STodd Fiala         break;
1908af245d11STodd Fiala     case FPE_INTDIV:
1909af245d11STodd Fiala         reason = ProcessMessage::eIntegerDivideByZero;
1910af245d11STodd Fiala         break;
1911af245d11STodd Fiala     case FPE_INTOVF:
1912af245d11STodd Fiala         reason = ProcessMessage::eIntegerOverflow;
1913af245d11STodd Fiala         break;
1914af245d11STodd Fiala     case FPE_FLTDIV:
1915af245d11STodd Fiala         reason = ProcessMessage::eFloatDivideByZero;
1916af245d11STodd Fiala         break;
1917af245d11STodd Fiala     case FPE_FLTOVF:
1918af245d11STodd Fiala         reason = ProcessMessage::eFloatOverflow;
1919af245d11STodd Fiala         break;
1920af245d11STodd Fiala     case FPE_FLTUND:
1921af245d11STodd Fiala         reason = ProcessMessage::eFloatUnderflow;
1922af245d11STodd Fiala         break;
1923af245d11STodd Fiala     case FPE_FLTRES:
1924af245d11STodd Fiala         reason = ProcessMessage::eFloatInexactResult;
1925af245d11STodd Fiala         break;
1926af245d11STodd Fiala     case FPE_FLTINV:
1927af245d11STodd Fiala         reason = ProcessMessage::eFloatInvalidOperation;
1928af245d11STodd Fiala         break;
1929af245d11STodd Fiala     case FPE_FLTSUB:
1930af245d11STodd Fiala         reason = ProcessMessage::eFloatSubscriptRange;
1931af245d11STodd Fiala         break;
1932af245d11STodd Fiala     }
1933af245d11STodd Fiala 
1934af245d11STodd Fiala     return reason;
1935af245d11STodd Fiala }
1936af245d11STodd Fiala #endif
1937af245d11STodd Fiala 
1938af245d11STodd Fiala #if 0
1939af245d11STodd Fiala ProcessMessage::CrashReason
1940af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
1941af245d11STodd Fiala {
1942af245d11STodd Fiala     ProcessMessage::CrashReason reason;
1943af245d11STodd Fiala     assert(info->si_signo == SIGBUS);
1944af245d11STodd Fiala 
1945af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
1946af245d11STodd Fiala 
1947af245d11STodd Fiala     switch (info->si_code)
1948af245d11STodd Fiala     {
1949af245d11STodd Fiala     default:
1950af245d11STodd Fiala         assert(false && "unexpected si_code for SIGBUS");
1951af245d11STodd Fiala         break;
1952af245d11STodd Fiala     case BUS_ADRALN:
1953af245d11STodd Fiala         reason = ProcessMessage::eIllegalAlignment;
1954af245d11STodd Fiala         break;
1955af245d11STodd Fiala     case BUS_ADRERR:
1956af245d11STodd Fiala         reason = ProcessMessage::eIllegalAddress;
1957af245d11STodd Fiala         break;
1958af245d11STodd Fiala     case BUS_OBJERR:
1959af245d11STodd Fiala         reason = ProcessMessage::eHardwareError;
1960af245d11STodd Fiala         break;
1961af245d11STodd Fiala     }
1962af245d11STodd Fiala 
1963af245d11STodd Fiala     return reason;
1964af245d11STodd Fiala }
1965af245d11STodd Fiala #endif
1966af245d11STodd Fiala 
1967b9c1b51eSKate Stone Error NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
1968b9c1b51eSKate Stone                                      size_t &bytes_read) {
1969df7c6995SPavel Labath   if (ProcessVmReadvSupported()) {
1970b9c1b51eSKate Stone     // The process_vm_readv path is about 50 times faster than ptrace api. We
1971b9c1b51eSKate Stone     // want to use
1972df7c6995SPavel Labath     // this syscall if it is supported.
1973df7c6995SPavel Labath 
1974df7c6995SPavel Labath     const ::pid_t pid = GetID();
1975df7c6995SPavel Labath 
1976df7c6995SPavel Labath     struct iovec local_iov, remote_iov;
1977df7c6995SPavel Labath     local_iov.iov_base = buf;
1978df7c6995SPavel Labath     local_iov.iov_len = size;
1979df7c6995SPavel Labath     remote_iov.iov_base = reinterpret_cast<void *>(addr);
1980df7c6995SPavel Labath     remote_iov.iov_len = size;
1981df7c6995SPavel Labath 
1982df7c6995SPavel Labath     bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
1983df7c6995SPavel Labath     const bool success = bytes_read == size;
1984df7c6995SPavel Labath 
1985a6321a8eSPavel Labath     Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1986a6321a8eSPavel Labath     LLDB_LOG(log,
1987a6321a8eSPavel Labath              "using process_vm_readv to read {0} bytes from inferior "
1988a6321a8eSPavel Labath              "address {1:x}: {2}",
1989a6321a8eSPavel Labath              size, addr, success ? "Success" : strerror(errno));
1990df7c6995SPavel Labath 
1991df7c6995SPavel Labath     if (success)
1992665be50eSMehdi Amini       return Error();
1993a6321a8eSPavel Labath     // else the call failed for some reason, let's retry the read using ptrace
1994b9c1b51eSKate Stone     // api.
1995df7c6995SPavel Labath   }
1996df7c6995SPavel Labath 
199719cbe96aSPavel Labath   unsigned char *dst = static_cast<unsigned char *>(buf);
199819cbe96aSPavel Labath   size_t remainder;
199919cbe96aSPavel Labath   long data;
200019cbe96aSPavel Labath 
2001a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
2002a6321a8eSPavel Labath   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
200319cbe96aSPavel Labath 
2004b9c1b51eSKate Stone   for (bytes_read = 0; bytes_read < size; bytes_read += remainder) {
2005b9c1b51eSKate Stone     Error error = NativeProcessLinux::PtraceWrapper(
2006b9c1b51eSKate Stone         PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data);
2007a6321a8eSPavel Labath     if (error.Fail())
200819cbe96aSPavel Labath       return error;
200919cbe96aSPavel Labath 
201019cbe96aSPavel Labath     remainder = size - bytes_read;
201119cbe96aSPavel Labath     remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
201219cbe96aSPavel Labath 
201319cbe96aSPavel Labath     // Copy the data into our buffer
2014f6ef187bSMohit K. Bhakkad     memcpy(dst, &data, remainder);
201519cbe96aSPavel Labath 
2016a6321a8eSPavel Labath     LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
201719cbe96aSPavel Labath     addr += k_ptrace_word_size;
201819cbe96aSPavel Labath     dst += k_ptrace_word_size;
201919cbe96aSPavel Labath   }
2020665be50eSMehdi Amini   return Error();
2021af245d11STodd Fiala }
2022af245d11STodd Fiala 
2023b9c1b51eSKate Stone Error NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf,
2024b9c1b51eSKate Stone                                                 size_t size,
2025b9c1b51eSKate Stone                                                 size_t &bytes_read) {
20263eb4b458SChaoren Lin   Error error = ReadMemory(addr, buf, size, bytes_read);
2027b9c1b51eSKate Stone   if (error.Fail())
2028b9c1b51eSKate Stone     return error;
20293eb4b458SChaoren Lin   return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
20303eb4b458SChaoren Lin }
20313eb4b458SChaoren Lin 
2032b9c1b51eSKate Stone Error NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,
2033b9c1b51eSKate Stone                                       size_t size, size_t &bytes_written) {
203419cbe96aSPavel Labath   const unsigned char *src = static_cast<const unsigned char *>(buf);
203519cbe96aSPavel Labath   size_t remainder;
203619cbe96aSPavel Labath   Error error;
203719cbe96aSPavel Labath 
2038a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
2039a6321a8eSPavel Labath   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
204019cbe96aSPavel Labath 
2041b9c1b51eSKate Stone   for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
204219cbe96aSPavel Labath     remainder = size - bytes_written;
204319cbe96aSPavel Labath     remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
204419cbe96aSPavel Labath 
2045b9c1b51eSKate Stone     if (remainder == k_ptrace_word_size) {
204619cbe96aSPavel Labath       unsigned long data = 0;
2047f6ef187bSMohit K. Bhakkad       memcpy(&data, src, k_ptrace_word_size);
204819cbe96aSPavel Labath 
2049a6321a8eSPavel Labath       LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
2050b9c1b51eSKate Stone       error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(),
2051b9c1b51eSKate Stone                                                 (void *)addr, (void *)data);
2052a6321a8eSPavel Labath       if (error.Fail())
205319cbe96aSPavel Labath         return error;
2054b9c1b51eSKate Stone     } else {
205519cbe96aSPavel Labath       unsigned char buff[8];
205619cbe96aSPavel Labath       size_t bytes_read;
205719cbe96aSPavel Labath       error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
2058a6321a8eSPavel Labath       if (error.Fail())
205919cbe96aSPavel Labath         return error;
206019cbe96aSPavel Labath 
206119cbe96aSPavel Labath       memcpy(buff, src, remainder);
206219cbe96aSPavel Labath 
206319cbe96aSPavel Labath       size_t bytes_written_rec;
206419cbe96aSPavel Labath       error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
2065a6321a8eSPavel Labath       if (error.Fail())
206619cbe96aSPavel Labath         return error;
206719cbe96aSPavel Labath 
2068a6321a8eSPavel Labath       LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src,
2069b9c1b51eSKate Stone                *(unsigned long *)buff);
207019cbe96aSPavel Labath     }
207119cbe96aSPavel Labath 
207219cbe96aSPavel Labath     addr += k_ptrace_word_size;
207319cbe96aSPavel Labath     src += k_ptrace_word_size;
207419cbe96aSPavel Labath   }
207519cbe96aSPavel Labath   return error;
2076af245d11STodd Fiala }
2077af245d11STodd Fiala 
2078b9c1b51eSKate Stone Error NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) {
207919cbe96aSPavel Labath   return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
2080af245d11STodd Fiala }
2081af245d11STodd Fiala 
2082b9c1b51eSKate Stone Error NativeProcessLinux::GetEventMessage(lldb::tid_t tid,
2083b9c1b51eSKate Stone                                           unsigned long *message) {
208419cbe96aSPavel Labath   return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
2085af245d11STodd Fiala }
2086af245d11STodd Fiala 
2087b9c1b51eSKate Stone Error NativeProcessLinux::Detach(lldb::tid_t tid) {
208897ccc294SChaoren Lin   if (tid == LLDB_INVALID_THREAD_ID)
2089665be50eSMehdi Amini     return Error();
209097ccc294SChaoren Lin 
209119cbe96aSPavel Labath   return PtraceWrapper(PTRACE_DETACH, tid);
2092af245d11STodd Fiala }
2093af245d11STodd Fiala 
2094b9c1b51eSKate Stone bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {
2095b9c1b51eSKate Stone   for (auto thread_sp : m_threads) {
2096af245d11STodd Fiala     assert(thread_sp && "thread list should not contain NULL threads");
2097b9c1b51eSKate Stone     if (thread_sp->GetID() == thread_id) {
2098af245d11STodd Fiala       // We have this thread.
2099af245d11STodd Fiala       return true;
2100af245d11STodd Fiala     }
2101af245d11STodd Fiala   }
2102af245d11STodd Fiala 
2103af245d11STodd Fiala   // We don't have this thread.
2104af245d11STodd Fiala   return false;
2105af245d11STodd Fiala }
2106af245d11STodd Fiala 
2107b9c1b51eSKate Stone bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) {
2108a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2109a6321a8eSPavel Labath   LLDB_LOG(log, "tid: {0})", thread_id);
21101dbc6c9cSPavel Labath 
21111dbc6c9cSPavel Labath   bool found = false;
2112b9c1b51eSKate Stone   for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
2113b9c1b51eSKate Stone     if (*it && ((*it)->GetID() == thread_id)) {
2114af245d11STodd Fiala       m_threads.erase(it);
21151dbc6c9cSPavel Labath       found = true;
21161dbc6c9cSPavel Labath       break;
2117af245d11STodd Fiala     }
2118af245d11STodd Fiala   }
2119af245d11STodd Fiala 
21209eb1ecb9SPavel Labath   SignalIfAllThreadsStopped();
21211dbc6c9cSPavel Labath   return found;
2122af245d11STodd Fiala }
2123af245d11STodd Fiala 
2124b9c1b51eSKate Stone NativeThreadLinuxSP NativeProcessLinux::AddThread(lldb::tid_t thread_id) {
2125a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
2126a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
2127af245d11STodd Fiala 
2128b9c1b51eSKate Stone   assert(!HasThreadNoLock(thread_id) &&
2129b9c1b51eSKate Stone          "attempted to add a thread by id that already exists");
2130af245d11STodd Fiala 
2131af245d11STodd Fiala   // If this is the first thread, save it as the current thread
2132af245d11STodd Fiala   if (m_threads.empty())
2133af245d11STodd Fiala     SetCurrentThreadID(thread_id);
2134af245d11STodd Fiala 
2135f9077782SPavel Labath   auto thread_sp = std::make_shared<NativeThreadLinux>(this, thread_id);
2136af245d11STodd Fiala   m_threads.push_back(thread_sp);
2137af245d11STodd Fiala   return thread_sp;
2138af245d11STodd Fiala }
2139af245d11STodd Fiala 
2140b9c1b51eSKate Stone Error NativeProcessLinux::FixupBreakpointPCAsNeeded(NativeThreadLinux &thread) {
2141a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_BREAKPOINTS));
2142af245d11STodd Fiala 
2143af245d11STodd Fiala   Error error;
2144af245d11STodd Fiala 
2145b9c1b51eSKate Stone   // Find out the size of a breakpoint (might depend on where we are in the
2146b9c1b51eSKate Stone   // code).
2147b9cc0c75SPavel Labath   NativeRegisterContextSP context_sp = thread.GetRegisterContext();
2148b9c1b51eSKate Stone   if (!context_sp) {
2149af245d11STodd Fiala     error.SetErrorString("cannot get a NativeRegisterContext for the thread");
2150a6321a8eSPavel Labath     LLDB_LOG(log, "failed: {0}", error);
2151af245d11STodd Fiala     return error;
2152af245d11STodd Fiala   }
2153af245d11STodd Fiala 
2154af245d11STodd Fiala   uint32_t breakpoint_size = 0;
2155b9cc0c75SPavel Labath   error = GetSoftwareBreakpointPCOffset(breakpoint_size);
2156b9c1b51eSKate Stone   if (error.Fail()) {
2157a6321a8eSPavel Labath     LLDB_LOG(log, "GetBreakpointSize() failed: {0}", error);
2158af245d11STodd Fiala     return error;
2159a6321a8eSPavel Labath   } else
2160a6321a8eSPavel Labath     LLDB_LOG(log, "breakpoint size: {0}", breakpoint_size);
2161af245d11STodd Fiala 
2162b9c1b51eSKate Stone   // First try probing for a breakpoint at a software breakpoint location: PC -
2163b9c1b51eSKate Stone   // breakpoint size.
2164b9c1b51eSKate Stone   const lldb::addr_t initial_pc_addr =
2165b9c1b51eSKate Stone       context_sp->GetPCfromBreakpointLocation();
2166af245d11STodd Fiala   lldb::addr_t breakpoint_addr = initial_pc_addr;
2167b9c1b51eSKate Stone   if (breakpoint_size > 0) {
2168af245d11STodd Fiala     // Do not allow breakpoint probe to wrap around.
21693eb4b458SChaoren Lin     if (breakpoint_addr >= breakpoint_size)
21703eb4b458SChaoren Lin       breakpoint_addr -= breakpoint_size;
2171af245d11STodd Fiala   }
2172af245d11STodd Fiala 
2173af245d11STodd Fiala   // Check if we stopped because of a breakpoint.
2174af245d11STodd Fiala   NativeBreakpointSP breakpoint_sp;
2175af245d11STodd Fiala   error = m_breakpoint_list.GetBreakpoint(breakpoint_addr, breakpoint_sp);
2176b9c1b51eSKate Stone   if (!error.Success() || !breakpoint_sp) {
2177af245d11STodd Fiala     // We didn't find one at a software probe location.  Nothing to do.
2178a6321a8eSPavel Labath     LLDB_LOG(log,
2179a6321a8eSPavel Labath              "pid {0} no lldb breakpoint found at current pc with "
2180a6321a8eSPavel Labath              "adjustment: {1}",
2181a6321a8eSPavel Labath              GetID(), breakpoint_addr);
2182665be50eSMehdi Amini     return Error();
2183af245d11STodd Fiala   }
2184af245d11STodd Fiala 
2185af245d11STodd Fiala   // If the breakpoint is not a software breakpoint, nothing to do.
2186b9c1b51eSKate Stone   if (!breakpoint_sp->IsSoftwareBreakpoint()) {
2187a6321a8eSPavel Labath     LLDB_LOG(
2188a6321a8eSPavel Labath         log,
2189a6321a8eSPavel Labath         "pid {0} breakpoint found at {1:x}, not software, nothing to adjust",
2190a6321a8eSPavel Labath         GetID(), breakpoint_addr);
2191665be50eSMehdi Amini     return Error();
2192af245d11STodd Fiala   }
2193af245d11STodd Fiala 
2194af245d11STodd Fiala   //
2195af245d11STodd Fiala   // We have a software breakpoint and need to adjust the PC.
2196af245d11STodd Fiala   //
2197af245d11STodd Fiala 
2198af245d11STodd Fiala   // Sanity check.
2199b9c1b51eSKate Stone   if (breakpoint_size == 0) {
2200af245d11STodd Fiala     // Nothing to do!  How did we get here?
2201a6321a8eSPavel Labath     LLDB_LOG(log,
2202a6321a8eSPavel Labath              "pid {0} breakpoint found at {1:x}, it is software, but the "
2203a6321a8eSPavel Labath              "size is zero, nothing to do (unexpected)",
2204a6321a8eSPavel Labath              GetID(), breakpoint_addr);
2205665be50eSMehdi Amini     return Error();
2206af245d11STodd Fiala   }
2207af245d11STodd Fiala 
2208af245d11STodd Fiala   // Change the program counter.
2209a6321a8eSPavel Labath   LLDB_LOG(log, "pid {0} tid {1}: changing PC from {2:x} to {3:x}", GetID(),
2210a6321a8eSPavel Labath            thread.GetID(), initial_pc_addr, breakpoint_addr);
2211af245d11STodd Fiala 
2212af245d11STodd Fiala   error = context_sp->SetPC(breakpoint_addr);
2213b9c1b51eSKate Stone   if (error.Fail()) {
2214a6321a8eSPavel Labath     LLDB_LOG(log, "pid {0} tid {1}: failed to set PC: {2}", GetID(),
2215a6321a8eSPavel Labath              thread.GetID(), error);
2216af245d11STodd Fiala     return error;
2217af245d11STodd Fiala   }
2218af245d11STodd Fiala 
2219af245d11STodd Fiala   return error;
2220af245d11STodd Fiala }
2221fa03ad2eSChaoren Lin 
2222b9c1b51eSKate Stone Error NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,
2223b9c1b51eSKate Stone                                                   FileSpec &file_spec) {
2224a6f5795aSTamas Berghammer   Error error = PopulateMemoryRegionCache();
2225a6f5795aSTamas Berghammer   if (error.Fail())
2226a6f5795aSTamas Berghammer     return error;
2227a6f5795aSTamas Berghammer 
22287cb18bf5STamas Berghammer   FileSpec module_file_spec(module_path, true);
22297cb18bf5STamas Berghammer 
22307cb18bf5STamas Berghammer   file_spec.Clear();
2231a6f5795aSTamas Berghammer   for (const auto &it : m_mem_region_cache) {
2232a6f5795aSTamas Berghammer     if (it.second.GetFilename() == module_file_spec.GetFilename()) {
2233a6f5795aSTamas Berghammer       file_spec = it.second;
2234a6f5795aSTamas Berghammer       return Error();
2235a6f5795aSTamas Berghammer     }
2236a6f5795aSTamas Berghammer   }
22377cb18bf5STamas Berghammer   return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
22387cb18bf5STamas Berghammer                module_file_spec.GetFilename().AsCString(), GetID());
22397cb18bf5STamas Berghammer }
2240c076559aSPavel Labath 
2241b9c1b51eSKate Stone Error NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
2242b9c1b51eSKate Stone                                              lldb::addr_t &load_addr) {
2243783bfc8cSTamas Berghammer   load_addr = LLDB_INVALID_ADDRESS;
2244a6f5795aSTamas Berghammer   Error error = PopulateMemoryRegionCache();
2245a6f5795aSTamas Berghammer   if (error.Fail())
2246783bfc8cSTamas Berghammer     return error;
2247a6f5795aSTamas Berghammer 
2248a6f5795aSTamas Berghammer   FileSpec file(file_name, false);
2249a6f5795aSTamas Berghammer   for (const auto &it : m_mem_region_cache) {
2250a6f5795aSTamas Berghammer     if (it.second == file) {
2251a6f5795aSTamas Berghammer       load_addr = it.first.GetRange().GetRangeBase();
2252a6f5795aSTamas Berghammer       return Error();
2253a6f5795aSTamas Berghammer     }
2254a6f5795aSTamas Berghammer   }
2255a6f5795aSTamas Berghammer   return Error("No load address found for specified file.");
2256783bfc8cSTamas Berghammer }
2257783bfc8cSTamas Berghammer 
2258b9c1b51eSKate Stone NativeThreadLinuxSP NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {
2259b9c1b51eSKate Stone   return std::static_pointer_cast<NativeThreadLinux>(
2260b9c1b51eSKate Stone       NativeProcessProtocol::GetThreadByID(tid));
2261f9077782SPavel Labath }
2262f9077782SPavel Labath 
2263b9c1b51eSKate Stone Error NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,
2264b9c1b51eSKate Stone                                        lldb::StateType state, int signo) {
2265a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2266a6321a8eSPavel Labath   LLDB_LOG(log, "tid: {0}", thread.GetID());
2267c076559aSPavel Labath 
2268c076559aSPavel Labath   // Before we do the resume below, first check if we have a pending
2269108c325dSPavel Labath   // stop notification that is currently waiting for
22700e1d729bSPavel Labath   // all threads to stop.  This is potentially a buggy situation since
2271c076559aSPavel Labath   // we're ostensibly waiting for threads to stop before we send out the
2272c076559aSPavel Labath   // pending notification, and here we are resuming one before we send
2273c076559aSPavel Labath   // out the pending stop notification.
2274a6321a8eSPavel Labath   if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
2275a6321a8eSPavel Labath     LLDB_LOG(log,
2276a6321a8eSPavel Labath              "about to resume tid {0} per explicit request but we have a "
2277a6321a8eSPavel Labath              "pending stop notification (tid {1}) that is actively "
2278a6321a8eSPavel Labath              "waiting for this thread to stop. Valid sequence of events?",
2279a6321a8eSPavel Labath              thread.GetID(), m_pending_notification_tid);
2280c076559aSPavel Labath   }
2281c076559aSPavel Labath 
2282c076559aSPavel Labath   // Request a resume.  We expect this to be synchronous and the system
2283c076559aSPavel Labath   // to reflect it is running after this completes.
2284b9c1b51eSKate Stone   switch (state) {
2285b9c1b51eSKate Stone   case eStateRunning: {
2286605b51b8SPavel Labath     const auto resume_result = thread.Resume(signo);
22870e1d729bSPavel Labath     if (resume_result.Success())
22880e1d729bSPavel Labath       SetState(eStateRunning, true);
22890e1d729bSPavel Labath     return resume_result;
2290c076559aSPavel Labath   }
2291b9c1b51eSKate Stone   case eStateStepping: {
2292605b51b8SPavel Labath     const auto step_result = thread.SingleStep(signo);
22930e1d729bSPavel Labath     if (step_result.Success())
22940e1d729bSPavel Labath       SetState(eStateRunning, true);
22950e1d729bSPavel Labath     return step_result;
22960e1d729bSPavel Labath   }
22970e1d729bSPavel Labath   default:
22988198db30SPavel Labath     LLDB_LOG(log, "Unhandled state {0}.", state);
22990e1d729bSPavel Labath     llvm_unreachable("Unhandled state for resume");
23000e1d729bSPavel Labath   }
2301c076559aSPavel Labath }
2302c076559aSPavel Labath 
2303c076559aSPavel Labath //===----------------------------------------------------------------------===//
2304c076559aSPavel Labath 
2305b9c1b51eSKate Stone void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {
2306a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2307a6321a8eSPavel Labath   LLDB_LOG(log, "about to process event: (triggering_tid: {0})",
2308a6321a8eSPavel Labath            triggering_tid);
2309c076559aSPavel Labath 
23100e1d729bSPavel Labath   m_pending_notification_tid = triggering_tid;
23110e1d729bSPavel Labath 
23120e1d729bSPavel Labath   // Request a stop for all the thread stops that need to be stopped
23130e1d729bSPavel Labath   // and are not already known to be stopped.
2314b9c1b51eSKate Stone   for (const auto &thread_sp : m_threads) {
23150e1d729bSPavel Labath     if (StateIsRunningState(thread_sp->GetState()))
23160e1d729bSPavel Labath       static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
23170e1d729bSPavel Labath   }
23180e1d729bSPavel Labath 
23190e1d729bSPavel Labath   SignalIfAllThreadsStopped();
2320a6321a8eSPavel Labath   LLDB_LOG(log, "event processing done");
2321c076559aSPavel Labath }
2322c076559aSPavel Labath 
2323b9c1b51eSKate Stone void NativeProcessLinux::SignalIfAllThreadsStopped() {
23240e1d729bSPavel Labath   if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
23250e1d729bSPavel Labath     return; // No pending notification. Nothing to do.
23260e1d729bSPavel Labath 
2327b9c1b51eSKate Stone   for (const auto &thread_sp : m_threads) {
23280e1d729bSPavel Labath     if (StateIsRunningState(thread_sp->GetState()))
23290e1d729bSPavel Labath       return; // Some threads are still running. Don't signal yet.
23300e1d729bSPavel Labath   }
23310e1d729bSPavel Labath 
23320e1d729bSPavel Labath   // We have a pending notification and all threads have stopped.
2333b9c1b51eSKate Stone   Log *log(
2334b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
23359eb1ecb9SPavel Labath 
2336b9c1b51eSKate Stone   // Clear any temporary breakpoints we used to implement software single
2337b9c1b51eSKate Stone   // stepping.
2338b9c1b51eSKate Stone   for (const auto &thread_info : m_threads_stepping_with_breakpoint) {
23399eb1ecb9SPavel Labath     Error error = RemoveBreakpoint(thread_info.second);
23409eb1ecb9SPavel Labath     if (error.Fail())
2341a6321a8eSPavel Labath       LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}",
2342a6321a8eSPavel Labath                thread_info.first, error);
23439eb1ecb9SPavel Labath   }
23449eb1ecb9SPavel Labath   m_threads_stepping_with_breakpoint.clear();
23459eb1ecb9SPavel Labath 
23469eb1ecb9SPavel Labath   // Notify the delegate about the stop
23470e1d729bSPavel Labath   SetCurrentThreadID(m_pending_notification_tid);
2348ed89c7feSPavel Labath   SetState(StateType::eStateStopped, true);
23490e1d729bSPavel Labath   m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
2350c076559aSPavel Labath }
2351c076559aSPavel Labath 
2352b9c1b51eSKate Stone void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {
2353a6321a8eSPavel Labath   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2354a6321a8eSPavel Labath   LLDB_LOG(log, "tid: {0}", thread.GetID());
23551dbc6c9cSPavel Labath 
2356b9c1b51eSKate Stone   if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID &&
2357b9c1b51eSKate Stone       StateIsRunningState(thread.GetState())) {
2358b9c1b51eSKate Stone     // We will need to wait for this new thread to stop as well before firing
2359b9c1b51eSKate Stone     // the
2360c076559aSPavel Labath     // notification.
2361f9077782SPavel Labath     thread.RequestStop();
2362c076559aSPavel Labath   }
2363c076559aSPavel Labath }
2364068f8a7eSTamas Berghammer 
2365b9c1b51eSKate Stone void NativeProcessLinux::SigchldHandler() {
2366a6321a8eSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
236719cbe96aSPavel Labath   // Process all pending waitpid notifications.
2368b9c1b51eSKate Stone   while (true) {
236919cbe96aSPavel Labath     int status = -1;
237019cbe96aSPavel Labath     ::pid_t wait_pid = waitpid(-1, &status, __WALL | __WNOTHREAD | WNOHANG);
237119cbe96aSPavel Labath 
237219cbe96aSPavel Labath     if (wait_pid == 0)
237319cbe96aSPavel Labath       break; // We are done.
237419cbe96aSPavel Labath 
2375b9c1b51eSKate Stone     if (wait_pid == -1) {
237619cbe96aSPavel Labath       if (errno == EINTR)
237719cbe96aSPavel Labath         continue;
237819cbe96aSPavel Labath 
237919cbe96aSPavel Labath       Error error(errno, eErrorTypePOSIX);
2380a6321a8eSPavel Labath       LLDB_LOG(log, "waitpid (-1, &status, _) failed: {0}", error);
238119cbe96aSPavel Labath       break;
238219cbe96aSPavel Labath     }
238319cbe96aSPavel Labath 
238419cbe96aSPavel Labath     bool exited = false;
238519cbe96aSPavel Labath     int signal = 0;
238619cbe96aSPavel Labath     int exit_status = 0;
238719cbe96aSPavel Labath     const char *status_cstr = nullptr;
2388b9c1b51eSKate Stone     if (WIFSTOPPED(status)) {
238919cbe96aSPavel Labath       signal = WSTOPSIG(status);
239019cbe96aSPavel Labath       status_cstr = "STOPPED";
2391b9c1b51eSKate Stone     } else if (WIFEXITED(status)) {
239219cbe96aSPavel Labath       exit_status = WEXITSTATUS(status);
239319cbe96aSPavel Labath       status_cstr = "EXITED";
239419cbe96aSPavel Labath       exited = true;
2395b9c1b51eSKate Stone     } else if (WIFSIGNALED(status)) {
239619cbe96aSPavel Labath       signal = WTERMSIG(status);
239719cbe96aSPavel Labath       status_cstr = "SIGNALED";
239819cbe96aSPavel Labath       if (wait_pid == static_cast<::pid_t>(GetID())) {
239919cbe96aSPavel Labath         exited = true;
240019cbe96aSPavel Labath         exit_status = -1;
240119cbe96aSPavel Labath       }
2402b9c1b51eSKate Stone     } else
240319cbe96aSPavel Labath       status_cstr = "(\?\?\?)";
240419cbe96aSPavel Labath 
2405a6321a8eSPavel Labath     LLDB_LOG(log,
2406a6321a8eSPavel Labath              "waitpid (-1, &status, _) => pid = {0}, status = {1:x} "
2407a6321a8eSPavel Labath              "({2}), signal = {3}, exit_state = {4}",
2408a6321a8eSPavel Labath              wait_pid, status, status_cstr, signal, exit_status);
240919cbe96aSPavel Labath 
241019cbe96aSPavel Labath     MonitorCallback(wait_pid, exited, signal, exit_status);
241119cbe96aSPavel Labath   }
2412068f8a7eSTamas Berghammer }
2413068f8a7eSTamas Berghammer 
2414068f8a7eSTamas Berghammer // Wrapper for ptrace to catch errors and log calls.
2415b9c1b51eSKate Stone // Note that ptrace sets errno on error because -1 can be a valid result (i.e.
2416b9c1b51eSKate Stone // for PTRACE_PEEK*)
2417b9c1b51eSKate Stone Error NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
2418b9c1b51eSKate Stone                                         void *data, size_t data_size,
2419b9c1b51eSKate Stone                                         long *result) {
24204a9babb2SPavel Labath   Error error;
24214a9babb2SPavel Labath   long int ret;
2422068f8a7eSTamas Berghammer 
2423068f8a7eSTamas Berghammer   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2424068f8a7eSTamas Berghammer 
2425068f8a7eSTamas Berghammer   PtraceDisplayBytes(req, data, data_size);
2426068f8a7eSTamas Berghammer 
2427068f8a7eSTamas Berghammer   errno = 0;
2428068f8a7eSTamas Berghammer   if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
2429b9c1b51eSKate Stone     ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2430b9c1b51eSKate Stone                  *(unsigned int *)addr, data);
2431068f8a7eSTamas Berghammer   else
2432b9c1b51eSKate Stone     ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2433b9c1b51eSKate Stone                  addr, data);
2434068f8a7eSTamas Berghammer 
24354a9babb2SPavel Labath   if (ret == -1)
2436068f8a7eSTamas Berghammer     error.SetErrorToErrno();
2437068f8a7eSTamas Berghammer 
24384a9babb2SPavel Labath   if (result)
24394a9babb2SPavel Labath     *result = ret;
24404a9babb2SPavel Labath 
244128096200SPavel Labath   LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data,
244228096200SPavel Labath            data_size, ret);
2443068f8a7eSTamas Berghammer 
2444068f8a7eSTamas Berghammer   PtraceDisplayBytes(req, data, data_size);
2445068f8a7eSTamas Berghammer 
2446a6321a8eSPavel Labath   if (error.Fail())
2447a6321a8eSPavel Labath     LLDB_LOG(log, "ptrace() failed: {0}", error);
2448068f8a7eSTamas Berghammer 
24494a9babb2SPavel Labath   return error;
2450068f8a7eSTamas Berghammer }
2451