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>
15*b9c1b51eSKate 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"
27af245d11STodd Fiala #include "lldb/Core/Error.h"
286edef204SOleksiy Vyalov #include "lldb/Core/ModuleSpec.h"
29af245d11STodd Fiala #include "lldb/Core/RegisterValue.h"
30af245d11STodd Fiala #include "lldb/Core/State.h"
31af245d11STodd Fiala #include "lldb/Host/Host.h"
325ad891f7SPavel Labath #include "lldb/Host/HostProcess.h"
3339de3110SZachary Turner #include "lldb/Host/ThreadLauncher.h"
342a86b555SPavel Labath #include "lldb/Host/common/NativeBreakpoint.h"
352a86b555SPavel Labath #include "lldb/Host/common/NativeRegisterContext.h"
365ad891f7SPavel Labath #include "lldb/Host/linux/ProcessLauncherLinux.h"
372a86b555SPavel Labath #include "lldb/Symbol/ObjectFile.h"
3890aff47cSZachary Turner #include "lldb/Target/Process.h"
39af245d11STodd Fiala #include "lldb/Target/ProcessLaunchInfo.h"
405b981ab9SPavel Labath #include "lldb/Target/Target.h"
41c16f5dcaSChaoren Lin #include "lldb/Utility/LLDBAssert.h"
42af245d11STodd Fiala #include "lldb/Utility/PseudoTerminal.h"
43f805e190SPavel Labath #include "lldb/Utility/StringExtractor.h"
44af245d11STodd Fiala 
45af245d11STodd Fiala #include "NativeThreadLinux.h"
46*b9c1b51eSKate Stone #include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
47af245d11STodd Fiala #include "ProcFileReader.h"
481e209fccSTamas Berghammer #include "Procfs.h"
49cacde7dfSTodd Fiala 
50*b9c1b51eSKate Stone // System includes - They have to be included after framework includes because
51*b9c1b51eSKate Stone // they define some
52d858487eSTamas Berghammer // macros which collide with variable names in other modules
53d858487eSTamas Berghammer #include <linux/unistd.h>
54d858487eSTamas Berghammer #include <sys/socket.h>
558b335671SVince Harron 
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 
618b335671SVince Harron #include "lldb/Host/linux/Personality.h"
628b335671SVince Harron #include "lldb/Host/linux/Ptrace.h"
63df7c6995SPavel Labath #include "lldb/Host/linux/Uio.h"
64af245d11STodd Fiala 
65af245d11STodd Fiala // Support hardware breakpoints in case it has not been defined
66af245d11STodd Fiala #ifndef TRAP_HWBKPT
67af245d11STodd Fiala #define TRAP_HWBKPT 4
68af245d11STodd Fiala #endif
69af245d11STodd Fiala 
707cb18bf5STamas Berghammer using namespace lldb;
717cb18bf5STamas Berghammer using namespace lldb_private;
72db264a6dSTamas Berghammer using namespace lldb_private::process_linux;
737cb18bf5STamas Berghammer using namespace llvm;
747cb18bf5STamas Berghammer 
75af245d11STodd Fiala // Private bits we only need internally.
76df7c6995SPavel Labath 
77*b9c1b51eSKate Stone static bool ProcessVmReadvSupported() {
78df7c6995SPavel Labath   static bool is_supported;
79df7c6995SPavel Labath   static std::once_flag flag;
80df7c6995SPavel Labath 
81df7c6995SPavel Labath   std::call_once(flag, [] {
82df7c6995SPavel Labath     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
83df7c6995SPavel Labath 
84df7c6995SPavel Labath     uint32_t source = 0x47424742;
85df7c6995SPavel Labath     uint32_t dest = 0;
86df7c6995SPavel Labath 
87df7c6995SPavel Labath     struct iovec local, remote;
88df7c6995SPavel Labath     remote.iov_base = &source;
89df7c6995SPavel Labath     local.iov_base = &dest;
90df7c6995SPavel Labath     remote.iov_len = local.iov_len = sizeof source;
91df7c6995SPavel Labath 
92*b9c1b51eSKate Stone     // We shall try if cross-process-memory reads work by attempting to read a
93*b9c1b51eSKate Stone     // value from our own process.
94df7c6995SPavel Labath     ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
95df7c6995SPavel Labath     is_supported = (res == sizeof(source) && source == dest);
96*b9c1b51eSKate Stone     if (log) {
97df7c6995SPavel Labath       if (is_supported)
98*b9c1b51eSKate Stone         log->Printf("%s: Detected kernel support for process_vm_readv syscall. "
99*b9c1b51eSKate Stone                     "Fast memory reads enabled.",
100df7c6995SPavel Labath                     __FUNCTION__);
101df7c6995SPavel Labath       else
102*b9c1b51eSKate Stone         log->Printf("%s: syscall process_vm_readv failed (error: %s). Fast "
103*b9c1b51eSKate Stone                     "memory reads disabled.",
104df7c6995SPavel Labath                     __FUNCTION__, strerror(errno));
105df7c6995SPavel Labath     }
106df7c6995SPavel Labath   });
107df7c6995SPavel Labath 
108df7c6995SPavel Labath   return is_supported;
109df7c6995SPavel Labath }
110df7c6995SPavel Labath 
111*b9c1b51eSKate Stone namespace {
112*b9c1b51eSKate Stone void MaybeLogLaunchInfo(const ProcessLaunchInfo &info) {
1134abe5d69SPavel Labath   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1144abe5d69SPavel Labath   if (!log)
1154abe5d69SPavel Labath     return;
1164abe5d69SPavel Labath 
1174abe5d69SPavel Labath   if (const FileAction *action = info.GetFileActionForFD(STDIN_FILENO))
118*b9c1b51eSKate Stone     log->Printf("%s: setting STDIN to '%s'", __FUNCTION__,
119*b9c1b51eSKate Stone                 action->GetFileSpec().GetCString());
1204abe5d69SPavel Labath   else
1214abe5d69SPavel Labath     log->Printf("%s leaving STDIN as is", __FUNCTION__);
1224abe5d69SPavel Labath 
1234abe5d69SPavel Labath   if (const FileAction *action = info.GetFileActionForFD(STDOUT_FILENO))
124*b9c1b51eSKate Stone     log->Printf("%s setting STDOUT to '%s'", __FUNCTION__,
125*b9c1b51eSKate Stone                 action->GetFileSpec().GetCString());
1264abe5d69SPavel Labath   else
1274abe5d69SPavel Labath     log->Printf("%s leaving STDOUT as is", __FUNCTION__);
1284abe5d69SPavel Labath 
1294abe5d69SPavel Labath   if (const FileAction *action = info.GetFileActionForFD(STDERR_FILENO))
130*b9c1b51eSKate Stone     log->Printf("%s setting STDERR to '%s'", __FUNCTION__,
131*b9c1b51eSKate Stone                 action->GetFileSpec().GetCString());
1324abe5d69SPavel Labath   else
1334abe5d69SPavel Labath     log->Printf("%s leaving STDERR as is", __FUNCTION__);
1344abe5d69SPavel Labath 
1354abe5d69SPavel Labath   int i = 0;
136*b9c1b51eSKate Stone   for (const char **args = info.GetArguments().GetConstArgumentVector(); *args;
137*b9c1b51eSKate Stone        ++args, ++i)
138*b9c1b51eSKate Stone     log->Printf("%s arg %d: \"%s\"", __FUNCTION__, i,
139*b9c1b51eSKate Stone                 *args ? *args : "nullptr");
1404abe5d69SPavel Labath }
1414abe5d69SPavel Labath 
142*b9c1b51eSKate Stone void DisplayBytes(StreamString &s, void *bytes, uint32_t count) {
143af245d11STodd Fiala   uint8_t *ptr = (uint8_t *)bytes;
144af245d11STodd Fiala   const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
145*b9c1b51eSKate Stone   for (uint32_t i = 0; i < loop_count; i++) {
146af245d11STodd Fiala     s.Printf("[%x]", *ptr);
147af245d11STodd Fiala     ptr++;
148af245d11STodd Fiala   }
149af245d11STodd Fiala }
150af245d11STodd Fiala 
151*b9c1b51eSKate Stone void PtraceDisplayBytes(int &req, void *data, size_t data_size) {
152af245d11STodd Fiala   StreamString buf;
153af245d11STodd Fiala   Log *verbose_log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(
154af245d11STodd Fiala       POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
155af245d11STodd Fiala 
156*b9c1b51eSKate Stone   if (verbose_log) {
157*b9c1b51eSKate Stone     switch (req) {
158*b9c1b51eSKate Stone     case PTRACE_POKETEXT: {
159af245d11STodd Fiala       DisplayBytes(buf, &data, 8);
160af245d11STodd Fiala       verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
161af245d11STodd Fiala       break;
162af245d11STodd Fiala     }
163*b9c1b51eSKate Stone     case PTRACE_POKEDATA: {
164af245d11STodd Fiala       DisplayBytes(buf, &data, 8);
165af245d11STodd Fiala       verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
166af245d11STodd Fiala       break;
167af245d11STodd Fiala     }
168*b9c1b51eSKate Stone     case PTRACE_POKEUSER: {
169af245d11STodd Fiala       DisplayBytes(buf, &data, 8);
170af245d11STodd Fiala       verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
171af245d11STodd Fiala       break;
172af245d11STodd Fiala     }
173*b9c1b51eSKate Stone     case PTRACE_SETREGS: {
174af245d11STodd Fiala       DisplayBytes(buf, data, data_size);
175af245d11STodd Fiala       verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
176af245d11STodd Fiala       break;
177af245d11STodd Fiala     }
178*b9c1b51eSKate Stone     case PTRACE_SETFPREGS: {
179af245d11STodd Fiala       DisplayBytes(buf, data, data_size);
180af245d11STodd Fiala       verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
181af245d11STodd Fiala       break;
182af245d11STodd Fiala     }
183*b9c1b51eSKate Stone     case PTRACE_SETSIGINFO: {
184af245d11STodd Fiala       DisplayBytes(buf, data, sizeof(siginfo_t));
185af245d11STodd Fiala       verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
186af245d11STodd Fiala       break;
187af245d11STodd Fiala     }
188*b9c1b51eSKate Stone     case PTRACE_SETREGSET: {
189af245d11STodd Fiala       // Extract iov_base from data, which is a pointer to the struct IOVEC
190af245d11STodd Fiala       DisplayBytes(buf, *(void **)data, data_size);
191af245d11STodd Fiala       verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
192af245d11STodd Fiala       break;
193af245d11STodd Fiala     }
194*b9c1b51eSKate Stone     default: {}
195af245d11STodd Fiala     }
196af245d11STodd Fiala   }
197af245d11STodd Fiala }
198af245d11STodd Fiala 
19919cbe96aSPavel Labath static constexpr unsigned k_ptrace_word_size = sizeof(void *);
200*b9c1b51eSKate Stone static_assert(sizeof(long) >= k_ptrace_word_size,
201*b9c1b51eSKate Stone               "Size of long must be larger than ptrace word size");
2021107b5a5SPavel Labath } // end of anonymous namespace
2031107b5a5SPavel Labath 
204bd7cbc5aSPavel Labath // Simple helper function to ensure flags are enabled on the given file
205bd7cbc5aSPavel Labath // descriptor.
206*b9c1b51eSKate Stone static Error EnsureFDFlags(int fd, int flags) {
207bd7cbc5aSPavel Labath   Error error;
208bd7cbc5aSPavel Labath 
209bd7cbc5aSPavel Labath   int status = fcntl(fd, F_GETFL);
210*b9c1b51eSKate Stone   if (status == -1) {
211bd7cbc5aSPavel Labath     error.SetErrorToErrno();
212bd7cbc5aSPavel Labath     return error;
213bd7cbc5aSPavel Labath   }
214bd7cbc5aSPavel Labath 
215*b9c1b51eSKate Stone   if (fcntl(fd, F_SETFL, status | flags) == -1) {
216bd7cbc5aSPavel Labath     error.SetErrorToErrno();
217bd7cbc5aSPavel Labath     return error;
218bd7cbc5aSPavel Labath   }
219bd7cbc5aSPavel Labath 
220bd7cbc5aSPavel Labath   return error;
221bd7cbc5aSPavel Labath }
222bd7cbc5aSPavel Labath 
223af245d11STodd Fiala // -----------------------------------------------------------------------------
224af245d11STodd Fiala // Public Static Methods
225af245d11STodd Fiala // -----------------------------------------------------------------------------
226af245d11STodd Fiala 
227*b9c1b51eSKate Stone Error NativeProcessProtocol::Launch(
228db264a6dSTamas Berghammer     ProcessLaunchInfo &launch_info,
229*b9c1b51eSKate Stone     NativeProcessProtocol::NativeDelegate &native_delegate, MainLoop &mainloop,
230*b9c1b51eSKate Stone     NativeProcessProtocolSP &native_process_sp) {
231af245d11STodd Fiala   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
232af245d11STodd Fiala 
2332a86b555SPavel Labath   Error error;
234af245d11STodd Fiala 
235af245d11STodd Fiala   // Verify the working directory is valid if one was specified.
236d3173f34SChaoren Lin   FileSpec working_dir{launch_info.GetWorkingDirectory()};
237d3173f34SChaoren Lin   if (working_dir &&
238d3173f34SChaoren Lin       (!working_dir.ResolvePath() ||
239*b9c1b51eSKate Stone        working_dir.GetFileType() != FileSpec::eFileTypeDirectory)) {
240d3173f34SChaoren Lin     error.SetErrorStringWithFormat("No such file or directory: %s",
241d3173f34SChaoren Lin                                    working_dir.GetCString());
242af245d11STodd Fiala     return error;
243af245d11STodd Fiala   }
244af245d11STodd Fiala 
245af245d11STodd Fiala   // Create the NativeProcessLinux in launch mode.
246af245d11STodd Fiala   native_process_sp.reset(new NativeProcessLinux());
247af245d11STodd Fiala 
248*b9c1b51eSKate Stone   if (!native_process_sp->RegisterNativeDelegate(native_delegate)) {
249af245d11STodd Fiala     native_process_sp.reset();
250af245d11STodd Fiala     error.SetErrorStringWithFormat("failed to register the native delegate");
251af245d11STodd Fiala     return error;
252af245d11STodd Fiala   }
253af245d11STodd Fiala 
254*b9c1b51eSKate Stone   error = std::static_pointer_cast<NativeProcessLinux>(native_process_sp)
255*b9c1b51eSKate Stone               ->LaunchInferior(mainloop, launch_info);
256af245d11STodd Fiala 
257*b9c1b51eSKate Stone   if (error.Fail()) {
258af245d11STodd Fiala     native_process_sp.reset();
259af245d11STodd Fiala     if (log)
260*b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s failed to launch process: %s",
261*b9c1b51eSKate Stone                   __FUNCTION__, error.AsCString());
262af245d11STodd Fiala     return error;
263af245d11STodd Fiala   }
264af245d11STodd Fiala 
265af245d11STodd Fiala   launch_info.SetProcessID(native_process_sp->GetID());
266af245d11STodd Fiala 
267af245d11STodd Fiala   return error;
268af245d11STodd Fiala }
269af245d11STodd Fiala 
270*b9c1b51eSKate Stone Error NativeProcessProtocol::Attach(
271*b9c1b51eSKate Stone     lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
272*b9c1b51eSKate Stone     MainLoop &mainloop, NativeProcessProtocolSP &native_process_sp) {
273af245d11STodd Fiala   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
274af245d11STodd Fiala   if (log && log->GetMask().Test(POSIX_LOG_VERBOSE))
275af245d11STodd Fiala     log->Printf("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
276af245d11STodd Fiala 
277af245d11STodd Fiala   // Retrieve the architecture for the running process.
278af245d11STodd Fiala   ArchSpec process_arch;
2792a86b555SPavel Labath   Error error = ResolveProcessArchitecture(pid, process_arch);
280af245d11STodd Fiala   if (!error.Success())
281af245d11STodd Fiala     return error;
282af245d11STodd Fiala 
283*b9c1b51eSKate Stone   std::shared_ptr<NativeProcessLinux> native_process_linux_sp(
284*b9c1b51eSKate Stone       new NativeProcessLinux());
285af245d11STodd Fiala 
286*b9c1b51eSKate Stone   if (!native_process_linux_sp->RegisterNativeDelegate(native_delegate)) {
287af245d11STodd Fiala     error.SetErrorStringWithFormat("failed to register the native delegate");
288af245d11STodd Fiala     return error;
289af245d11STodd Fiala   }
290af245d11STodd Fiala 
29119cbe96aSPavel Labath   native_process_linux_sp->AttachToInferior(mainloop, pid, error);
292af245d11STodd Fiala   if (!error.Success())
293af245d11STodd Fiala     return error;
294af245d11STodd Fiala 
2951339b5e8SOleksiy Vyalov   native_process_sp = native_process_linux_sp;
296af245d11STodd Fiala   return error;
297af245d11STodd Fiala }
298af245d11STodd Fiala 
299af245d11STodd Fiala // -----------------------------------------------------------------------------
300af245d11STodd Fiala // Public Instance Methods
301af245d11STodd Fiala // -----------------------------------------------------------------------------
302af245d11STodd Fiala 
303*b9c1b51eSKate Stone NativeProcessLinux::NativeProcessLinux()
304*b9c1b51eSKate Stone     : NativeProcessProtocol(LLDB_INVALID_PROCESS_ID), m_arch(),
305*b9c1b51eSKate Stone       m_supports_mem_region(eLazyBoolCalculate), m_mem_region_cache(),
306*b9c1b51eSKate Stone       m_pending_notification_tid(LLDB_INVALID_THREAD_ID) {}
307af245d11STodd Fiala 
308*b9c1b51eSKate Stone void NativeProcessLinux::AttachToInferior(MainLoop &mainloop, lldb::pid_t pid,
309*b9c1b51eSKate Stone                                           Error &error) {
310af245d11STodd Fiala   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
311af245d11STodd Fiala   if (log)
312*b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__,
313*b9c1b51eSKate Stone                 pid);
314af245d11STodd Fiala 
315*b9c1b51eSKate Stone   m_sigchld_handle = mainloop.RegisterSignal(
316*b9c1b51eSKate Stone       SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, error);
31719cbe96aSPavel Labath   if (!m_sigchld_handle)
31819cbe96aSPavel Labath     return;
31919cbe96aSPavel Labath 
3202a86b555SPavel Labath   error = ResolveProcessArchitecture(pid, m_arch);
321af245d11STodd Fiala   if (!error.Success())
322af245d11STodd Fiala     return;
323af245d11STodd Fiala 
324af245d11STodd Fiala   // Set the architecture to the exe architecture.
325af245d11STodd Fiala   if (log)
326*b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s (pid = %" PRIi64
327*b9c1b51eSKate Stone                 ") detected architecture %s",
328*b9c1b51eSKate Stone                 __FUNCTION__, pid, m_arch.GetArchitectureName());
329af245d11STodd Fiala 
330af245d11STodd Fiala   m_pid = pid;
331af245d11STodd Fiala   SetState(eStateAttaching);
332af245d11STodd Fiala 
33319cbe96aSPavel Labath   Attach(pid, error);
334af245d11STodd Fiala }
335af245d11STodd Fiala 
336*b9c1b51eSKate Stone Error NativeProcessLinux::LaunchInferior(MainLoop &mainloop,
337*b9c1b51eSKate Stone                                          ProcessLaunchInfo &launch_info) {
3384abe5d69SPavel Labath   Error error;
339*b9c1b51eSKate Stone   m_sigchld_handle = mainloop.RegisterSignal(
340*b9c1b51eSKate Stone       SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, error);
3414abe5d69SPavel Labath   if (!m_sigchld_handle)
3424abe5d69SPavel Labath     return error;
3434abe5d69SPavel Labath 
3444abe5d69SPavel Labath   SetState(eStateLaunching);
3450c4f01d4SPavel Labath 
3464abe5d69SPavel Labath   MaybeLogLaunchInfo(launch_info);
3474abe5d69SPavel Labath 
348*b9c1b51eSKate Stone   ::pid_t pid =
349*b9c1b51eSKate Stone       ProcessLauncherLinux().LaunchProcess(launch_info, error).GetProcessId();
3505ad891f7SPavel Labath   if (error.Fail())
3514abe5d69SPavel Labath     return error;
3520c4f01d4SPavel Labath 
35375f47c3aSTodd Fiala   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
35475f47c3aSTodd Fiala 
355af245d11STodd Fiala   // Wait for the child process to trap on its call to execve.
356af245d11STodd Fiala   ::pid_t wpid;
357af245d11STodd Fiala   int status;
358*b9c1b51eSKate Stone   if ((wpid = waitpid(pid, &status, 0)) < 0) {
359bd7cbc5aSPavel Labath     error.SetErrorToErrno();
360af245d11STodd Fiala     if (log)
361bd7cbc5aSPavel Labath       log->Printf("NativeProcessLinux::%s waitpid for inferior failed with %s",
362bd7cbc5aSPavel Labath                   __FUNCTION__, error.AsCString());
363af245d11STodd Fiala 
364af245d11STodd Fiala     // Mark the inferior as invalid.
365*b9c1b51eSKate Stone     // FIXME this could really use a new state - eStateLaunchFailure.  For now,
366*b9c1b51eSKate Stone     // using eStateInvalid.
367bd7cbc5aSPavel Labath     SetState(StateType::eStateInvalid);
368af245d11STodd Fiala 
3694abe5d69SPavel Labath     return error;
370af245d11STodd Fiala   }
371af245d11STodd Fiala   assert(WIFSTOPPED(status) && (wpid == static_cast<::pid_t>(pid)) &&
372af245d11STodd Fiala          "Could not sync with inferior process.");
373af245d11STodd Fiala 
374af245d11STodd Fiala   if (log)
375*b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s inferior started, now in stopped state",
376*b9c1b51eSKate Stone                 __FUNCTION__);
377af245d11STodd Fiala 
378bd7cbc5aSPavel Labath   error = SetDefaultPtraceOpts(pid);
379*b9c1b51eSKate Stone   if (error.Fail()) {
380af245d11STodd Fiala     if (log)
381*b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s inferior failed to set default "
382*b9c1b51eSKate Stone                   "ptrace options: %s",
383bd7cbc5aSPavel Labath                   __FUNCTION__, error.AsCString());
384af245d11STodd Fiala 
385af245d11STodd Fiala     // Mark the inferior as invalid.
386*b9c1b51eSKate Stone     // FIXME this could really use a new state - eStateLaunchFailure.  For now,
387*b9c1b51eSKate Stone     // using eStateInvalid.
388bd7cbc5aSPavel Labath     SetState(StateType::eStateInvalid);
389af245d11STodd Fiala 
3904abe5d69SPavel Labath     return error;
391af245d11STodd Fiala   }
392af245d11STodd Fiala 
393af245d11STodd Fiala   // Release the master terminal descriptor and pass it off to the
394af245d11STodd Fiala   // NativeProcessLinux instance.  Similarly stash the inferior pid.
3955ad891f7SPavel Labath   m_terminal_fd = launch_info.GetPTY().ReleaseMasterFileDescriptor();
396bd7cbc5aSPavel Labath   m_pid = pid;
3974abe5d69SPavel Labath   launch_info.SetProcessID(pid);
398af245d11STodd Fiala 
399*b9c1b51eSKate Stone   if (m_terminal_fd != -1) {
400bd7cbc5aSPavel Labath     error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
401*b9c1b51eSKate Stone     if (error.Fail()) {
402af245d11STodd Fiala       if (log)
403*b9c1b51eSKate Stone         log->Printf("NativeProcessLinux::%s inferior EnsureFDFlags failed for "
404*b9c1b51eSKate Stone                     "ensuring terminal O_NONBLOCK setting: %s",
405bd7cbc5aSPavel Labath                     __FUNCTION__, error.AsCString());
406af245d11STodd Fiala 
407af245d11STodd Fiala       // Mark the inferior as invalid.
408*b9c1b51eSKate Stone       // FIXME this could really use a new state - eStateLaunchFailure.  For
409*b9c1b51eSKate Stone       // now, using eStateInvalid.
410bd7cbc5aSPavel Labath       SetState(StateType::eStateInvalid);
411af245d11STodd Fiala 
4124abe5d69SPavel Labath       return error;
413af245d11STodd Fiala     }
4145ad891f7SPavel Labath   }
415af245d11STodd Fiala 
416af245d11STodd Fiala   if (log)
417*b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__,
418*b9c1b51eSKate Stone                 uint64_t(pid));
419af245d11STodd Fiala 
4202a86b555SPavel Labath   ResolveProcessArchitecture(m_pid, m_arch);
421f9077782SPavel Labath   NativeThreadLinuxSP thread_sp = AddThread(pid);
422af245d11STodd Fiala   assert(thread_sp && "AddThread() returned a nullptr thread");
423f9077782SPavel Labath   thread_sp->SetStoppedBySignal(SIGSTOP);
424f9077782SPavel Labath   ThreadWasCreated(*thread_sp);
425af245d11STodd Fiala 
426af245d11STodd Fiala   // Let our process instance know the thread has stopped.
427bd7cbc5aSPavel Labath   SetCurrentThreadID(thread_sp->GetID());
428bd7cbc5aSPavel Labath   SetState(StateType::eStateStopped);
429af245d11STodd Fiala 
430*b9c1b51eSKate Stone   if (log) {
431bd7cbc5aSPavel Labath     if (error.Success())
432*b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s inferior launching succeeded",
433*b9c1b51eSKate Stone                   __FUNCTION__);
434af245d11STodd Fiala     else
435*b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s inferior launching failed: %s",
436*b9c1b51eSKate Stone                   __FUNCTION__, error.AsCString());
437af245d11STodd Fiala   }
4384abe5d69SPavel Labath   return error;
439af245d11STodd Fiala }
440af245d11STodd Fiala 
441*b9c1b51eSKate Stone ::pid_t NativeProcessLinux::Attach(lldb::pid_t pid, Error &error) {
442af245d11STodd Fiala   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
443af245d11STodd Fiala 
444*b9c1b51eSKate Stone   // Use a map to keep track of the threads which we have attached/need to
445*b9c1b51eSKate Stone   // attach.
446af245d11STodd Fiala   Host::TidMap tids_to_attach;
447*b9c1b51eSKate Stone   if (pid <= 1) {
448bd7cbc5aSPavel Labath     error.SetErrorToGenericError();
449bd7cbc5aSPavel Labath     error.SetErrorString("Attaching to process 1 is not allowed.");
450bd7cbc5aSPavel Labath     return -1;
451af245d11STodd Fiala   }
452af245d11STodd Fiala 
453*b9c1b51eSKate Stone   while (Host::FindProcessThreads(pid, tids_to_attach)) {
454af245d11STodd Fiala     for (Host::TidMap::iterator it = tids_to_attach.begin();
455*b9c1b51eSKate Stone          it != tids_to_attach.end();) {
456*b9c1b51eSKate Stone       if (it->second == false) {
457af245d11STodd Fiala         lldb::tid_t tid = it->first;
458af245d11STodd Fiala 
459af245d11STodd Fiala         // Attach to the requested process.
460af245d11STodd Fiala         // An attach will cause the thread to stop with a SIGSTOP.
4614a9babb2SPavel Labath         error = PtraceWrapper(PTRACE_ATTACH, tid);
462*b9c1b51eSKate Stone         if (error.Fail()) {
463af245d11STodd Fiala           // No such thread. The thread may have exited.
464af245d11STodd Fiala           // More error handling may be needed.
465*b9c1b51eSKate Stone           if (error.GetError() == ESRCH) {
466af245d11STodd Fiala             it = tids_to_attach.erase(it);
467af245d11STodd Fiala             continue;
468*b9c1b51eSKate Stone           } else
469bd7cbc5aSPavel Labath             return -1;
470af245d11STodd Fiala         }
471af245d11STodd Fiala 
472af245d11STodd Fiala         int status;
473af245d11STodd Fiala         // Need to use __WALL otherwise we receive an error with errno=ECHLD
474af245d11STodd Fiala         // At this point we should have a thread stopped if waitpid succeeds.
475*b9c1b51eSKate Stone         if ((status = waitpid(tid, NULL, __WALL)) < 0) {
476af245d11STodd Fiala           // No such thread. The thread may have exited.
477af245d11STodd Fiala           // More error handling may be needed.
478*b9c1b51eSKate Stone           if (errno == ESRCH) {
479af245d11STodd Fiala             it = tids_to_attach.erase(it);
480af245d11STodd Fiala             continue;
481*b9c1b51eSKate Stone           } else {
482bd7cbc5aSPavel Labath             error.SetErrorToErrno();
483bd7cbc5aSPavel Labath             return -1;
484af245d11STodd Fiala           }
485af245d11STodd Fiala         }
486af245d11STodd Fiala 
487bd7cbc5aSPavel Labath         error = SetDefaultPtraceOpts(tid);
488bd7cbc5aSPavel Labath         if (error.Fail())
489bd7cbc5aSPavel Labath           return -1;
490af245d11STodd Fiala 
491af245d11STodd Fiala         if (log)
492*b9c1b51eSKate Stone           log->Printf("NativeProcessLinux::%s() adding tid = %" PRIu64,
493*b9c1b51eSKate Stone                       __FUNCTION__, tid);
494af245d11STodd Fiala 
495af245d11STodd Fiala         it->second = true;
496af245d11STodd Fiala 
497af245d11STodd Fiala         // Create the thread, mark it as stopped.
498f9077782SPavel Labath         NativeThreadLinuxSP thread_sp(AddThread(static_cast<lldb::tid_t>(tid)));
499af245d11STodd Fiala         assert(thread_sp && "AddThread() returned a nullptr");
500fa03ad2eSChaoren Lin 
501*b9c1b51eSKate Stone         // This will notify this is a new thread and tell the system it is
502*b9c1b51eSKate Stone         // stopped.
503f9077782SPavel Labath         thread_sp->SetStoppedBySignal(SIGSTOP);
504f9077782SPavel Labath         ThreadWasCreated(*thread_sp);
505bd7cbc5aSPavel Labath         SetCurrentThreadID(thread_sp->GetID());
506af245d11STodd Fiala       }
507af245d11STodd Fiala 
508af245d11STodd Fiala       // move the loop forward
509af245d11STodd Fiala       ++it;
510af245d11STodd Fiala     }
511af245d11STodd Fiala   }
512af245d11STodd Fiala 
513*b9c1b51eSKate Stone   if (tids_to_attach.size() > 0) {
514bd7cbc5aSPavel Labath     m_pid = pid;
515af245d11STodd Fiala     // Let our process instance know the thread has stopped.
516bd7cbc5aSPavel Labath     SetState(StateType::eStateStopped);
517*b9c1b51eSKate Stone   } else {
518bd7cbc5aSPavel Labath     error.SetErrorToGenericError();
519bd7cbc5aSPavel Labath     error.SetErrorString("No such process.");
520bd7cbc5aSPavel Labath     return -1;
521af245d11STodd Fiala   }
522af245d11STodd Fiala 
523bd7cbc5aSPavel Labath   return pid;
524af245d11STodd Fiala }
525af245d11STodd Fiala 
526*b9c1b51eSKate Stone Error NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid) {
527af245d11STodd Fiala   long ptrace_opts = 0;
528af245d11STodd Fiala 
529af245d11STodd Fiala   // Have the child raise an event on exit.  This is used to keep the child in
530af245d11STodd Fiala   // limbo until it is destroyed.
531af245d11STodd Fiala   ptrace_opts |= PTRACE_O_TRACEEXIT;
532af245d11STodd Fiala 
533af245d11STodd Fiala   // Have the tracer trace threads which spawn in the inferior process.
534af245d11STodd Fiala   // TODO: if we want to support tracing the inferiors' child, add the
535af245d11STodd Fiala   // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
536af245d11STodd Fiala   ptrace_opts |= PTRACE_O_TRACECLONE;
537af245d11STodd Fiala 
538af245d11STodd Fiala   // Have the tracer notify us before execve returns
539af245d11STodd Fiala   // (needed to disable legacy SIGTRAP generation)
540af245d11STodd Fiala   ptrace_opts |= PTRACE_O_TRACEEXEC;
541af245d11STodd Fiala 
5424a9babb2SPavel Labath   return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void *)ptrace_opts);
543af245d11STodd Fiala }
544af245d11STodd Fiala 
545*b9c1b51eSKate Stone static ExitType convert_pid_status_to_exit_type(int status) {
546af245d11STodd Fiala   if (WIFEXITED(status))
547af245d11STodd Fiala     return ExitType::eExitTypeExit;
548af245d11STodd Fiala   else if (WIFSIGNALED(status))
549af245d11STodd Fiala     return ExitType::eExitTypeSignal;
550af245d11STodd Fiala   else if (WIFSTOPPED(status))
551af245d11STodd Fiala     return ExitType::eExitTypeStop;
552*b9c1b51eSKate Stone   else {
553af245d11STodd Fiala     // We don't know what this is.
554af245d11STodd Fiala     return ExitType::eExitTypeInvalid;
555af245d11STodd Fiala   }
556af245d11STodd Fiala }
557af245d11STodd Fiala 
558*b9c1b51eSKate Stone static int convert_pid_status_to_return_code(int status) {
559af245d11STodd Fiala   if (WIFEXITED(status))
560af245d11STodd Fiala     return WEXITSTATUS(status);
561af245d11STodd Fiala   else if (WIFSIGNALED(status))
562af245d11STodd Fiala     return WTERMSIG(status);
563af245d11STodd Fiala   else if (WIFSTOPPED(status))
564af245d11STodd Fiala     return WSTOPSIG(status);
565*b9c1b51eSKate Stone   else {
566af245d11STodd Fiala     // We don't know what this is.
567af245d11STodd Fiala     return ExitType::eExitTypeInvalid;
568af245d11STodd Fiala   }
569af245d11STodd Fiala }
570af245d11STodd Fiala 
5711107b5a5SPavel Labath // Handles all waitpid events from the inferior process.
572*b9c1b51eSKate Stone void NativeProcessLinux::MonitorCallback(lldb::pid_t pid, bool exited,
573*b9c1b51eSKate Stone                                          int signal, int status) {
574af245d11STodd Fiala   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
575af245d11STodd Fiala 
576*b9c1b51eSKate Stone   // Certain activities differ based on whether the pid is the tid of the main
577*b9c1b51eSKate Stone   // thread.
5781107b5a5SPavel Labath   const bool is_main_thread = (pid == GetID());
579af245d11STodd Fiala 
580af245d11STodd Fiala   // Handle when the thread exits.
581*b9c1b51eSKate Stone   if (exited) {
582af245d11STodd Fiala     if (log)
583*b9c1b51eSKate Stone       log->Printf(
584*b9c1b51eSKate Stone           "NativeProcessLinux::%s() got exit signal(%d) , tid = %" PRIu64
585*b9c1b51eSKate Stone           " (%s main thread)",
586*b9c1b51eSKate Stone           __FUNCTION__, signal, pid, is_main_thread ? "is" : "is not");
587af245d11STodd Fiala 
588af245d11STodd Fiala     // This is a thread that exited.  Ensure we're not tracking it anymore.
5891107b5a5SPavel Labath     const bool thread_found = StopTrackingThread(pid);
590af245d11STodd Fiala 
591*b9c1b51eSKate Stone     if (is_main_thread) {
592*b9c1b51eSKate Stone       // We only set the exit status and notify the delegate if we haven't
593*b9c1b51eSKate Stone       // already set the process
594*b9c1b51eSKate Stone       // state to an exited state.  We normally should have received a SIGTRAP |
595*b9c1b51eSKate Stone       // (PTRACE_EVENT_EXIT << 8)
596af245d11STodd Fiala       // for the main thread.
597*b9c1b51eSKate Stone       const bool already_notified = (GetState() == StateType::eStateExited) ||
598*b9c1b51eSKate Stone                                     (GetState() == StateType::eStateCrashed);
599*b9c1b51eSKate Stone       if (!already_notified) {
600af245d11STodd Fiala         if (log)
601*b9c1b51eSKate Stone           log->Printf("NativeProcessLinux::%s() tid = %" PRIu64
602*b9c1b51eSKate Stone                       " handling main thread exit (%s), expected exit state "
603*b9c1b51eSKate Stone                       "already set but state was %s instead, setting exit "
604*b9c1b51eSKate Stone                       "state now",
605*b9c1b51eSKate Stone                       __FUNCTION__, pid,
606*b9c1b51eSKate Stone                       thread_found ? "stopped tracking thread metadata"
607*b9c1b51eSKate Stone                                    : "thread metadata not found",
608*b9c1b51eSKate Stone                       StateAsCString(GetState()));
609af245d11STodd Fiala         // The main thread exited.  We're done monitoring.  Report to delegate.
610*b9c1b51eSKate Stone         SetExitStatus(convert_pid_status_to_exit_type(status),
611*b9c1b51eSKate Stone                       convert_pid_status_to_return_code(status), nullptr, true);
612af245d11STodd Fiala 
613af245d11STodd Fiala         // Notify delegate that our process has exited.
6141107b5a5SPavel Labath         SetState(StateType::eStateExited, true);
615*b9c1b51eSKate Stone       } else {
616af245d11STodd Fiala         if (log)
617*b9c1b51eSKate Stone           log->Printf("NativeProcessLinux::%s() tid = %" PRIu64
618*b9c1b51eSKate Stone                       " main thread now exited (%s)",
619*b9c1b51eSKate Stone                       __FUNCTION__, pid,
620*b9c1b51eSKate Stone                       thread_found ? "stopped tracking thread metadata"
621*b9c1b51eSKate Stone                                    : "thread metadata not found");
622af245d11STodd Fiala       }
623*b9c1b51eSKate Stone     } else {
624*b9c1b51eSKate Stone       // Do we want to report to the delegate in this case?  I think not.  If
625*b9c1b51eSKate Stone       // this was an orderly
626*b9c1b51eSKate Stone       // thread exit, we would already have received the SIGTRAP |
627*b9c1b51eSKate Stone       // (PTRACE_EVENT_EXIT << 8) signal,
628af245d11STodd Fiala       // and we would have done an all-stop then.
629af245d11STodd Fiala       if (log)
630*b9c1b51eSKate Stone         log->Printf("NativeProcessLinux::%s() tid = %" PRIu64
631*b9c1b51eSKate Stone                     " handling non-main thread exit (%s)",
632*b9c1b51eSKate Stone                     __FUNCTION__, pid,
633*b9c1b51eSKate Stone                     thread_found ? "stopped tracking thread metadata"
634*b9c1b51eSKate Stone                                  : "thread metadata not found");
635af245d11STodd Fiala     }
6361107b5a5SPavel Labath     return;
637af245d11STodd Fiala   }
638af245d11STodd Fiala 
639af245d11STodd Fiala   siginfo_t info;
640b9cc0c75SPavel Labath   const auto info_err = GetSignalInfo(pid, &info);
641b9cc0c75SPavel Labath   auto thread_sp = GetThreadByID(pid);
642b9cc0c75SPavel Labath 
643*b9c1b51eSKate Stone   if (!thread_sp) {
644*b9c1b51eSKate Stone     // Normally, the only situation when we cannot find the thread is if we have
645*b9c1b51eSKate Stone     // just
646*b9c1b51eSKate Stone     // received a new thread notification. This is indicated by GetSignalInfo()
647*b9c1b51eSKate Stone     // returning
648b9cc0c75SPavel Labath     // si_code == SI_USER and si_pid == 0
649b9cc0c75SPavel Labath     if (log)
650*b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s received notification about an "
651*b9c1b51eSKate Stone                   "unknown tid %" PRIu64 ".",
652*b9c1b51eSKate Stone                   __FUNCTION__, pid);
653b9cc0c75SPavel Labath 
654*b9c1b51eSKate Stone     if (info_err.Fail()) {
655b9cc0c75SPavel Labath       if (log)
656*b9c1b51eSKate Stone         log->Printf("NativeProcessLinux::%s (tid %" PRIu64
657*b9c1b51eSKate Stone                     ") GetSignalInfo failed (%s). Ingoring this notification.",
658*b9c1b51eSKate Stone                     __FUNCTION__, pid, info_err.AsCString());
659b9cc0c75SPavel Labath       return;
660b9cc0c75SPavel Labath     }
661b9cc0c75SPavel Labath 
662b9cc0c75SPavel Labath     if (log && (info.si_code != SI_USER || info.si_pid != 0))
663*b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s (tid %" PRIu64
664*b9c1b51eSKate Stone                   ") unexpected signal info (si_code: %d, si_pid: %d). "
665*b9c1b51eSKate Stone                   "Treating as a new thread notification anyway.",
666*b9c1b51eSKate Stone                   __FUNCTION__, pid, info.si_code, info.si_pid);
667b9cc0c75SPavel Labath 
668b9cc0c75SPavel Labath     auto thread_sp = AddThread(pid);
669b9cc0c75SPavel Labath     // Resume the newly created thread.
670b9cc0c75SPavel Labath     ResumeThread(*thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
671b9cc0c75SPavel Labath     ThreadWasCreated(*thread_sp);
672b9cc0c75SPavel Labath     return;
673b9cc0c75SPavel Labath   }
674b9cc0c75SPavel Labath 
675b9cc0c75SPavel Labath   // Get details on the signal raised.
676*b9c1b51eSKate Stone   if (info_err.Success()) {
677fa03ad2eSChaoren Lin     // We have retrieved the signal info.  Dispatch appropriately.
678fa03ad2eSChaoren Lin     if (info.si_signo == SIGTRAP)
679b9cc0c75SPavel Labath       MonitorSIGTRAP(info, *thread_sp);
680fa03ad2eSChaoren Lin     else
681b9cc0c75SPavel Labath       MonitorSignal(info, *thread_sp, exited);
682*b9c1b51eSKate Stone   } else {
683*b9c1b51eSKate Stone     if (info_err.GetError() == EINVAL) {
684fa03ad2eSChaoren Lin       // This is a group stop reception for this tid.
685*b9c1b51eSKate Stone       // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU
686*b9c1b51eSKate Stone       // into the
687*b9c1b51eSKate Stone       // tracee, triggering the group-stop mechanism. Normally receiving these
688*b9c1b51eSKate Stone       // would stop
689*b9c1b51eSKate Stone       // the process, pending a SIGCONT. Simulating this state in a debugger is
690*b9c1b51eSKate Stone       // hard and is
691*b9c1b51eSKate Stone       // generally not needed (one use case is debugging background task being
692*b9c1b51eSKate Stone       // managed by a
693*b9c1b51eSKate Stone       // shell). For general use, it is sufficient to stop the process in a
694*b9c1b51eSKate Stone       // signal-delivery
695*b9c1b51eSKate Stone       // stop which happens before the group stop. This done by MonitorSignal
696*b9c1b51eSKate Stone       // and works
69739036ac3SPavel Labath       // correctly for all signals.
698fa03ad2eSChaoren Lin       if (log)
699*b9c1b51eSKate Stone         log->Printf(
700*b9c1b51eSKate Stone             "NativeProcessLinux::%s received a group stop for pid %" PRIu64
701*b9c1b51eSKate Stone             " tid %" PRIu64 ". Transparent handling of group stops not "
702*b9c1b51eSKate Stone                             "supported, resuming the thread.",
703*b9c1b51eSKate Stone             __FUNCTION__, GetID(), pid);
704*b9c1b51eSKate Stone       ResumeThread(*thread_sp, thread_sp->GetState(),
705*b9c1b51eSKate Stone                    LLDB_INVALID_SIGNAL_NUMBER);
706*b9c1b51eSKate Stone     } else {
707af245d11STodd Fiala       // ptrace(GETSIGINFO) failed (but not due to group-stop).
708af245d11STodd Fiala 
709*b9c1b51eSKate Stone       // A return value of ESRCH means the thread/process is no longer on the
710*b9c1b51eSKate Stone       // system,
711*b9c1b51eSKate Stone       // so it was killed somehow outside of our control.  Either way, we can't
712*b9c1b51eSKate Stone       // do anything
713af245d11STodd Fiala       // with it anymore.
714af245d11STodd Fiala 
715*b9c1b51eSKate Stone       // Stop tracking the metadata for the thread since it's entirely off the
716*b9c1b51eSKate Stone       // system now.
7171107b5a5SPavel Labath       const bool thread_found = StopTrackingThread(pid);
718af245d11STodd Fiala 
719af245d11STodd Fiala       if (log)
720*b9c1b51eSKate Stone         log->Printf(
721*b9c1b51eSKate Stone             "NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64
722*b9c1b51eSKate Stone             ", signal = %d, status = %d (%s, %s, %s)",
723*b9c1b51eSKate Stone             __FUNCTION__, info_err.AsCString(), pid, signal, status,
724*b9c1b51eSKate Stone             info_err.GetError() == ESRCH ? "thread/process killed"
725*b9c1b51eSKate Stone                                          : "unknown reason",
726*b9c1b51eSKate Stone             is_main_thread ? "is main thread" : "is not main thread",
727*b9c1b51eSKate Stone             thread_found ? "thread metadata removed"
728*b9c1b51eSKate Stone                          : "thread metadata not found");
729af245d11STodd Fiala 
730*b9c1b51eSKate Stone       if (is_main_thread) {
731*b9c1b51eSKate Stone         // Notify the delegate - our process is not available but appears to
732*b9c1b51eSKate Stone         // have been killed outside
733af245d11STodd Fiala         // our control.  Is eStateExited the right exit state in this case?
734*b9c1b51eSKate Stone         SetExitStatus(convert_pid_status_to_exit_type(status),
735*b9c1b51eSKate Stone                       convert_pid_status_to_return_code(status), nullptr, true);
7361107b5a5SPavel Labath         SetState(StateType::eStateExited, true);
737*b9c1b51eSKate Stone       } else {
738*b9c1b51eSKate Stone         // This thread was pulled out from underneath us.  Anything to do here?
739*b9c1b51eSKate Stone         // Do we want to do an all stop?
740af245d11STodd Fiala         if (log)
741*b9c1b51eSKate Stone           log->Printf("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64
742*b9c1b51eSKate Stone                       " non-main thread exit occurred, didn't tell delegate "
743*b9c1b51eSKate Stone                       "anything since thread disappeared out from underneath "
744*b9c1b51eSKate Stone                       "us",
745*b9c1b51eSKate Stone                       __FUNCTION__, GetID(), pid);
746af245d11STodd Fiala       }
747af245d11STodd Fiala     }
748af245d11STodd Fiala   }
749af245d11STodd Fiala }
750af245d11STodd Fiala 
751*b9c1b51eSKate Stone void NativeProcessLinux::WaitForNewThread(::pid_t tid) {
752426bdf88SPavel Labath   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
753426bdf88SPavel Labath 
754f9077782SPavel Labath   NativeThreadLinuxSP new_thread_sp = GetThreadByID(tid);
755426bdf88SPavel Labath 
756*b9c1b51eSKate Stone   if (new_thread_sp) {
757*b9c1b51eSKate Stone     // We are already tracking the thread - we got the event on the new thread
758*b9c1b51eSKate Stone     // (see
759426bdf88SPavel Labath     // MonitorSignal) before this one. We are done.
760426bdf88SPavel Labath     return;
761426bdf88SPavel Labath   }
762426bdf88SPavel Labath 
763426bdf88SPavel Labath   // The thread is not tracked yet, let's wait for it to appear.
764426bdf88SPavel Labath   int status = -1;
765426bdf88SPavel Labath   ::pid_t wait_pid;
766*b9c1b51eSKate Stone   do {
767426bdf88SPavel Labath     if (log)
768*b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s() received thread creation event for "
769*b9c1b51eSKate Stone                   "tid %" PRIu32
770*b9c1b51eSKate Stone                   ". tid not tracked yet, waiting for thread to appear...",
771*b9c1b51eSKate Stone                   __FUNCTION__, tid);
772426bdf88SPavel Labath     wait_pid = waitpid(tid, &status, __WALL);
773*b9c1b51eSKate Stone   } while (wait_pid == -1 && errno == EINTR);
774*b9c1b51eSKate Stone   // Since we are waiting on a specific tid, this must be the creation event.
775*b9c1b51eSKate Stone   // But let's do
776426bdf88SPavel Labath   // some checks just in case.
777426bdf88SPavel Labath   if (wait_pid != tid) {
778426bdf88SPavel Labath     if (log)
779*b9c1b51eSKate Stone       log->Printf(
780*b9c1b51eSKate Stone           "NativeProcessLinux::%s() waiting for tid %" PRIu32
781*b9c1b51eSKate Stone           " failed. Assuming the thread has disappeared in the meantime",
782*b9c1b51eSKate Stone           __FUNCTION__, tid);
783426bdf88SPavel Labath     // The only way I know of this could happen is if the whole process was
784*b9c1b51eSKate Stone     // SIGKILLed in the mean time. In any case, we can't do anything about that
785*b9c1b51eSKate Stone     // now.
786426bdf88SPavel Labath     return;
787426bdf88SPavel Labath   }
788*b9c1b51eSKate Stone   if (WIFEXITED(status)) {
789426bdf88SPavel Labath     if (log)
790*b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s() waiting for tid %" PRIu32
791*b9c1b51eSKate Stone                   " returned an 'exited' event. Not tracking the thread.",
792*b9c1b51eSKate Stone                   __FUNCTION__, tid);
793426bdf88SPavel Labath     // Also a very improbable event.
794426bdf88SPavel Labath     return;
795426bdf88SPavel Labath   }
796426bdf88SPavel Labath 
797426bdf88SPavel Labath   siginfo_t info;
798426bdf88SPavel Labath   Error error = GetSignalInfo(tid, &info);
799*b9c1b51eSKate Stone   if (error.Fail()) {
800426bdf88SPavel Labath     if (log)
801*b9c1b51eSKate Stone       log->Printf(
802*b9c1b51eSKate Stone           "NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32
803*b9c1b51eSKate Stone           " failed. Assuming the thread has disappeared in the meantime.",
804*b9c1b51eSKate Stone           __FUNCTION__, tid);
805426bdf88SPavel Labath     return;
806426bdf88SPavel Labath   }
807426bdf88SPavel Labath 
808*b9c1b51eSKate Stone   if (((info.si_pid != 0) || (info.si_code != SI_USER)) && log) {
809*b9c1b51eSKate Stone     // We should be getting a thread creation signal here, but we received
810*b9c1b51eSKate Stone     // something
811*b9c1b51eSKate Stone     // else. There isn't much we can do about it now, so we will just log that.
812*b9c1b51eSKate Stone     // Since the
813*b9c1b51eSKate Stone     // thread is alive and we are receiving events from it, we shall pretend
814*b9c1b51eSKate Stone     // that it was
815426bdf88SPavel Labath     // created properly.
816*b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32
817*b9c1b51eSKate Stone                 " received unexpected signal with code %d from pid %d.",
818*b9c1b51eSKate Stone                 __FUNCTION__, tid, info.si_code, info.si_pid);
819426bdf88SPavel Labath   }
820426bdf88SPavel Labath 
821426bdf88SPavel Labath   if (log)
822*b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s() pid = %" PRIu64
823*b9c1b51eSKate Stone                 ": tracking new thread tid %" PRIu32,
824426bdf88SPavel Labath                 __FUNCTION__, GetID(), tid);
825426bdf88SPavel Labath 
826f9077782SPavel Labath   new_thread_sp = AddThread(tid);
827b9cc0c75SPavel Labath   ResumeThread(*new_thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
828f9077782SPavel Labath   ThreadWasCreated(*new_thread_sp);
829426bdf88SPavel Labath }
830426bdf88SPavel Labath 
831*b9c1b51eSKate Stone void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info,
832*b9c1b51eSKate Stone                                         NativeThreadLinux &thread) {
833af245d11STodd Fiala   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
834b9cc0c75SPavel Labath   const bool is_main_thread = (thread.GetID() == GetID());
835af245d11STodd Fiala 
836b9cc0c75SPavel Labath   assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
837af245d11STodd Fiala 
838*b9c1b51eSKate Stone   switch (info.si_code) {
839*b9c1b51eSKate Stone   // TODO: these two cases are required if we want to support tracing of the
840*b9c1b51eSKate Stone   // inferiors' children.  We'd need this to debug a monitor.
841af245d11STodd Fiala   // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
842af245d11STodd Fiala   // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
843af245d11STodd Fiala 
844*b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): {
845*b9c1b51eSKate Stone     // This is the notification on the parent thread which informs us of new
846*b9c1b51eSKate Stone     // thread
847426bdf88SPavel Labath     // creation.
848*b9c1b51eSKate Stone     // We don't want to do anything with the parent thread so we just resume it.
849*b9c1b51eSKate Stone     // In case we
850*b9c1b51eSKate Stone     // want to implement "break on thread creation" functionality, we would need
851*b9c1b51eSKate Stone     // to stop
852426bdf88SPavel Labath     // here.
853af245d11STodd Fiala 
854af245d11STodd Fiala     unsigned long event_message = 0;
855*b9c1b51eSKate Stone     if (GetEventMessage(thread.GetID(), &event_message).Fail()) {
856426bdf88SPavel Labath       if (log)
857*b9c1b51eSKate Stone         log->Printf("NativeProcessLinux::%s() pid %" PRIu64
858*b9c1b51eSKate Stone                     " received thread creation event but GetEventMessage "
859*b9c1b51eSKate Stone                     "failed so we don't know the new tid",
860*b9c1b51eSKate Stone                     __FUNCTION__, thread.GetID());
861426bdf88SPavel Labath     } else
862426bdf88SPavel Labath       WaitForNewThread(event_message);
863af245d11STodd Fiala 
864b9cc0c75SPavel Labath     ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
865af245d11STodd Fiala     break;
866af245d11STodd Fiala   }
867af245d11STodd Fiala 
868*b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): {
869f9077782SPavel Labath     NativeThreadLinuxSP main_thread_sp;
870af245d11STodd Fiala     if (log)
871*b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s() received exec event, code = %d",
872*b9c1b51eSKate Stone                   __FUNCTION__, info.si_code ^ SIGTRAP);
873a9882ceeSTodd Fiala 
8741dbc6c9cSPavel Labath     // Exec clears any pending notifications.
8750e1d729bSPavel Labath     m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
876fa03ad2eSChaoren Lin 
877*b9c1b51eSKate Stone     // Remove all but the main thread here.  Linux fork creates a new process
878*b9c1b51eSKate Stone     // which only copies the main thread.
879a9882ceeSTodd Fiala     if (log)
880*b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s exec received, stop tracking all but "
881*b9c1b51eSKate Stone                   "main thread",
882*b9c1b51eSKate Stone                   __FUNCTION__);
883a9882ceeSTodd Fiala 
884*b9c1b51eSKate Stone     for (auto thread_sp : m_threads) {
885a9882ceeSTodd Fiala       const bool is_main_thread = thread_sp && thread_sp->GetID() == GetID();
886*b9c1b51eSKate Stone       if (is_main_thread) {
887f9077782SPavel Labath         main_thread_sp = std::static_pointer_cast<NativeThreadLinux>(thread_sp);
888a9882ceeSTodd Fiala         if (log)
889*b9c1b51eSKate Stone           log->Printf(
890*b9c1b51eSKate Stone               "NativeProcessLinux::%s found main thread with tid %" PRIu64
891*b9c1b51eSKate Stone               ", keeping",
892*b9c1b51eSKate Stone               __FUNCTION__, main_thread_sp->GetID());
893*b9c1b51eSKate Stone       } else {
894a9882ceeSTodd Fiala         if (log)
895*b9c1b51eSKate Stone           log->Printf(
896*b9c1b51eSKate Stone               "NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64
897*b9c1b51eSKate Stone               " due to exec",
898*b9c1b51eSKate Stone               __FUNCTION__, thread_sp->GetID());
899a9882ceeSTodd Fiala       }
900a9882ceeSTodd Fiala     }
901a9882ceeSTodd Fiala 
902a9882ceeSTodd Fiala     m_threads.clear();
903a9882ceeSTodd Fiala 
904*b9c1b51eSKate Stone     if (main_thread_sp) {
905a9882ceeSTodd Fiala       m_threads.push_back(main_thread_sp);
906a9882ceeSTodd Fiala       SetCurrentThreadID(main_thread_sp->GetID());
907f9077782SPavel Labath       main_thread_sp->SetStoppedByExec();
908*b9c1b51eSKate Stone     } else {
909a9882ceeSTodd Fiala       SetCurrentThreadID(LLDB_INVALID_THREAD_ID);
910a9882ceeSTodd Fiala       if (log)
911*b9c1b51eSKate Stone         log->Printf("NativeProcessLinux::%s pid %" PRIu64
912*b9c1b51eSKate Stone                     "no main thread found, discarded all threads, we're in a "
913*b9c1b51eSKate Stone                     "no-thread state!",
914*b9c1b51eSKate Stone                     __FUNCTION__, GetID());
915a9882ceeSTodd Fiala     }
916a9882ceeSTodd Fiala 
917fa03ad2eSChaoren Lin     // Tell coordinator about about the "new" (since exec) stopped main thread.
918f9077782SPavel Labath     ThreadWasCreated(*main_thread_sp);
919fa03ad2eSChaoren Lin 
920a9882ceeSTodd Fiala     // Let our delegate know we have just exec'd.
921a9882ceeSTodd Fiala     NotifyDidExec();
922a9882ceeSTodd Fiala 
923a9882ceeSTodd Fiala     // If we have a main thread, indicate we are stopped.
924*b9c1b51eSKate Stone     assert(main_thread_sp && "exec called during ptraced process but no main "
925*b9c1b51eSKate Stone                              "thread metadata tracked");
926fa03ad2eSChaoren Lin 
927fa03ad2eSChaoren Lin     // Let the process know we're stopped.
928b9cc0c75SPavel Labath     StopRunningThreads(main_thread_sp->GetID());
929a9882ceeSTodd Fiala 
930af245d11STodd Fiala     break;
931a9882ceeSTodd Fiala   }
932af245d11STodd Fiala 
933*b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): {
934af245d11STodd Fiala     // The inferior process or one of its threads is about to exit.
935*b9c1b51eSKate Stone     // We don't want to do anything with the thread so we just resume it. In
936*b9c1b51eSKate Stone     // case we
937*b9c1b51eSKate Stone     // want to implement "break on thread exit" functionality, we would need to
938*b9c1b51eSKate Stone     // stop
9396e35163cSPavel Labath     // here.
940fa03ad2eSChaoren Lin 
941af245d11STodd Fiala     unsigned long data = 0;
942b9cc0c75SPavel Labath     if (GetEventMessage(thread.GetID(), &data).Fail())
943af245d11STodd Fiala       data = -1;
944af245d11STodd Fiala 
945*b9c1b51eSKate Stone     if (log) {
946*b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = "
947*b9c1b51eSKate Stone                   "%lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
948*b9c1b51eSKate Stone                   __FUNCTION__, data, WIFEXITED(data) ? "true" : "false",
949*b9c1b51eSKate Stone                   WIFSIGNALED(data) ? "true" : "false", thread.GetID(),
950af245d11STodd Fiala                   is_main_thread ? "is main thread" : "not main thread");
951af245d11STodd Fiala     }
952af245d11STodd Fiala 
953*b9c1b51eSKate Stone     if (is_main_thread) {
954*b9c1b51eSKate Stone       SetExitStatus(convert_pid_status_to_exit_type(data),
955*b9c1b51eSKate Stone                     convert_pid_status_to_return_code(data), nullptr, true);
95675f47c3aSTodd Fiala     }
95775f47c3aSTodd Fiala 
95886852d36SPavel Labath     StateType state = thread.GetState();
959*b9c1b51eSKate Stone     if (!StateIsRunningState(state)) {
960*b9c1b51eSKate Stone       // Due to a kernel bug, we may sometimes get this stop after the inferior
961*b9c1b51eSKate Stone       // gets a
962*b9c1b51eSKate Stone       // SIGKILL. This confuses our state tracking logic in ResumeThread(),
963*b9c1b51eSKate Stone       // since normally,
964*b9c1b51eSKate Stone       // we should not be receiving any ptrace events while the inferior is
965*b9c1b51eSKate Stone       // stopped. This
96686852d36SPavel Labath       // makes sure that the inferior is resumed and exits normally.
96786852d36SPavel Labath       state = eStateRunning;
96886852d36SPavel Labath     }
96986852d36SPavel Labath     ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
970af245d11STodd Fiala 
971af245d11STodd Fiala     break;
972af245d11STodd Fiala   }
973af245d11STodd Fiala 
974af245d11STodd Fiala   case 0:
975c16f5dcaSChaoren Lin   case TRAP_TRACE:  // We receive this on single stepping.
976c16f5dcaSChaoren Lin   case TRAP_HWBKPT: // We receive this on watchpoint hit
97786fd8e45SChaoren Lin   {
978c16f5dcaSChaoren Lin     // If a watchpoint was hit, report it
979c16f5dcaSChaoren Lin     uint32_t wp_index;
980*b9c1b51eSKate Stone     Error error = thread.GetRegisterContext()->GetWatchpointHitIndex(
981*b9c1b51eSKate Stone         wp_index, (uintptr_t)info.si_addr);
982c16f5dcaSChaoren Lin     if (error.Fail() && log)
983c16f5dcaSChaoren Lin       log->Printf("NativeProcessLinux::%s() "
984c16f5dcaSChaoren Lin                   "received error while checking for watchpoint hits, "
985c16f5dcaSChaoren Lin                   "pid = %" PRIu64 " error = %s",
986b9cc0c75SPavel Labath                   __FUNCTION__, thread.GetID(), error.AsCString());
987*b9c1b51eSKate Stone     if (wp_index != LLDB_INVALID_INDEX32) {
988b9cc0c75SPavel Labath       MonitorWatchpoint(thread, wp_index);
989c16f5dcaSChaoren Lin       break;
990c16f5dcaSChaoren Lin     }
991b9cc0c75SPavel Labath 
992be379e15STamas Berghammer     // Otherwise, report step over
993be379e15STamas Berghammer     MonitorTrace(thread);
994af245d11STodd Fiala     break;
995b9cc0c75SPavel Labath   }
996af245d11STodd Fiala 
997af245d11STodd Fiala   case SI_KERNEL:
99835799963SMohit K. Bhakkad #if defined __mips__
99935799963SMohit K. Bhakkad     // For mips there is no special signal for watchpoint
100035799963SMohit K. Bhakkad     // So we check for watchpoint in kernel trap
100135799963SMohit K. Bhakkad     {
100235799963SMohit K. Bhakkad       // If a watchpoint was hit, report it
100335799963SMohit K. Bhakkad       uint32_t wp_index;
1004*b9c1b51eSKate Stone       Error error = thread.GetRegisterContext()->GetWatchpointHitIndex(
1005*b9c1b51eSKate Stone           wp_index, LLDB_INVALID_ADDRESS);
100635799963SMohit K. Bhakkad       if (error.Fail() && log)
100735799963SMohit K. Bhakkad         log->Printf("NativeProcessLinux::%s() "
100835799963SMohit K. Bhakkad                     "received error while checking for watchpoint hits, "
100935799963SMohit K. Bhakkad                     "pid = %" PRIu64 " error = %s",
101016ad0321SMohit K. Bhakkad                     __FUNCTION__, thread.GetID(), error.AsCString());
1011*b9c1b51eSKate Stone       if (wp_index != LLDB_INVALID_INDEX32) {
1012b9cc0c75SPavel Labath         MonitorWatchpoint(thread, wp_index);
101335799963SMohit K. Bhakkad         break;
101435799963SMohit K. Bhakkad       }
101535799963SMohit K. Bhakkad     }
101635799963SMohit K. Bhakkad // NO BREAK
101735799963SMohit K. Bhakkad #endif
1018af245d11STodd Fiala   case TRAP_BRKPT:
1019b9cc0c75SPavel Labath     MonitorBreakpoint(thread);
1020af245d11STodd Fiala     break;
1021af245d11STodd Fiala 
1022af245d11STodd Fiala   case SIGTRAP:
1023af245d11STodd Fiala   case (SIGTRAP | 0x80):
1024af245d11STodd Fiala     if (log)
1025*b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s() received unknown SIGTRAP system "
1026*b9c1b51eSKate Stone                   "call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming",
1027*b9c1b51eSKate Stone                   __FUNCTION__, GetID(), thread.GetID());
1028fa03ad2eSChaoren Lin 
1029af245d11STodd Fiala     // Ignore these signals until we know more about them.
1030b9cc0c75SPavel Labath     ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
1031af245d11STodd Fiala     break;
1032af245d11STodd Fiala 
1033af245d11STodd Fiala   default:
1034af245d11STodd Fiala     assert(false && "Unexpected SIGTRAP code!");
1035af245d11STodd Fiala     if (log)
1036*b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s() pid %" PRIu64 "tid %" PRIu64
1037*b9c1b51eSKate Stone                   " received unhandled SIGTRAP code: 0x%d",
1038b9cc0c75SPavel Labath                   __FUNCTION__, GetID(), thread.GetID(), info.si_code);
1039af245d11STodd Fiala     break;
1040af245d11STodd Fiala   }
1041af245d11STodd Fiala }
1042af245d11STodd Fiala 
1043*b9c1b51eSKate Stone void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) {
1044c16f5dcaSChaoren Lin   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1045c16f5dcaSChaoren Lin   if (log)
1046*b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64
1047*b9c1b51eSKate Stone                 " (single stepping)",
1048b9cc0c75SPavel Labath                 __FUNCTION__, thread.GetID());
1049c16f5dcaSChaoren Lin 
10500e1d729bSPavel Labath   // This thread is currently stopped.
1051b9cc0c75SPavel Labath   thread.SetStoppedByTrace();
1052c16f5dcaSChaoren Lin 
1053b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
1054c16f5dcaSChaoren Lin }
1055c16f5dcaSChaoren Lin 
1056*b9c1b51eSKate Stone void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) {
1057*b9c1b51eSKate Stone   Log *log(
1058*b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
1059c16f5dcaSChaoren Lin   if (log)
1060*b9c1b51eSKate Stone     log->Printf(
1061*b9c1b51eSKate Stone         "NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
1062b9cc0c75SPavel Labath         __FUNCTION__, thread.GetID());
1063c16f5dcaSChaoren Lin 
1064c16f5dcaSChaoren Lin   // Mark the thread as stopped at breakpoint.
1065b9cc0c75SPavel Labath   thread.SetStoppedByBreakpoint();
1066b9cc0c75SPavel Labath   Error error = FixupBreakpointPCAsNeeded(thread);
1067c16f5dcaSChaoren Lin   if (error.Fail())
1068c16f5dcaSChaoren Lin     if (log)
1069c16f5dcaSChaoren Lin       log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
1070b9cc0c75SPavel Labath                   __FUNCTION__, thread.GetID(), error.AsCString());
1071d8c338d4STamas Berghammer 
1072*b9c1b51eSKate Stone   if (m_threads_stepping_with_breakpoint.find(thread.GetID()) !=
1073*b9c1b51eSKate Stone       m_threads_stepping_with_breakpoint.end())
1074b9cc0c75SPavel Labath     thread.SetStoppedByTrace();
1075c16f5dcaSChaoren Lin 
1076b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
1077c16f5dcaSChaoren Lin }
1078c16f5dcaSChaoren Lin 
1079*b9c1b51eSKate Stone void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread,
1080*b9c1b51eSKate Stone                                            uint32_t wp_index) {
1081*b9c1b51eSKate Stone   Log *log(
1082*b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
1083c16f5dcaSChaoren Lin   if (log)
1084c16f5dcaSChaoren Lin     log->Printf("NativeProcessLinux::%s() received watchpoint event, "
1085c16f5dcaSChaoren Lin                 "pid = %" PRIu64 ", wp_index = %" PRIu32,
1086f9077782SPavel Labath                 __FUNCTION__, thread.GetID(), wp_index);
1087c16f5dcaSChaoren Lin 
1088c16f5dcaSChaoren Lin   // Mark the thread as stopped at watchpoint.
1089c16f5dcaSChaoren Lin   // The address is at (lldb::addr_t)info->si_addr if we need it.
1090f9077782SPavel Labath   thread.SetStoppedByWatchpoint(wp_index);
1091c16f5dcaSChaoren Lin 
1092*b9c1b51eSKate Stone   // We need to tell all other running threads before we notify the delegate
1093*b9c1b51eSKate Stone   // about this stop.
1094f9077782SPavel Labath   StopRunningThreads(thread.GetID());
1095c16f5dcaSChaoren Lin }
1096c16f5dcaSChaoren Lin 
1097*b9c1b51eSKate Stone void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
1098*b9c1b51eSKate Stone                                        NativeThreadLinux &thread, bool exited) {
1099b9cc0c75SPavel Labath   const int signo = info.si_signo;
1100b9cc0c75SPavel Labath   const bool is_from_llgs = info.si_pid == getpid();
1101af245d11STodd Fiala 
1102af245d11STodd Fiala   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1103af245d11STodd Fiala 
1104af245d11STodd Fiala   // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1105af245d11STodd Fiala   // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1106af245d11STodd Fiala   // kill(2) or raise(3).  Similarly for tgkill(2) on Linux.
1107af245d11STodd Fiala   //
1108af245d11STodd Fiala   // IOW, user generated signals never generate what we consider to be a
1109af245d11STodd Fiala   // "crash".
1110af245d11STodd Fiala   //
1111af245d11STodd Fiala   // Similarly, ACK signals generated by this monitor.
1112af245d11STodd Fiala 
1113af245d11STodd Fiala   // Handle the signal.
1114*b9c1b51eSKate Stone   if (info.si_code == SI_TKILL || info.si_code == SI_USER) {
1115af245d11STodd Fiala     if (log)
1116*b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s() received signal %s (%d) with code "
1117*b9c1b51eSKate Stone                   "%s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
1118*b9c1b51eSKate Stone                   __FUNCTION__, Host::GetSignalAsCString(signo), signo,
1119b9cc0c75SPavel Labath                   (info.si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
1120*b9c1b51eSKate Stone                   info.si_pid, is_from_llgs ? "from llgs" : "not from llgs",
1121b9cc0c75SPavel Labath                   thread.GetID());
1122af245d11STodd Fiala   }
112358a2f669STodd Fiala 
112458a2f669STodd Fiala   // Check for thread stop notification.
1125*b9c1b51eSKate Stone   if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) {
1126af245d11STodd Fiala     // This is a tgkill()-based stop.
1127fa03ad2eSChaoren Lin     if (log)
1128*b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64
1129*b9c1b51eSKate Stone                   ", thread stopped",
1130*b9c1b51eSKate Stone                   __FUNCTION__, GetID(), thread.GetID());
1131fa03ad2eSChaoren Lin 
1132aab58633SChaoren Lin     // Check that we're not already marked with a stop reason.
1133*b9c1b51eSKate Stone     // Note this thread really shouldn't already be marked as stopped - if we
1134*b9c1b51eSKate Stone     // were, that would imply that
1135*b9c1b51eSKate Stone     // the kernel signaled us with the thread stopping which we handled and
1136*b9c1b51eSKate Stone     // marked as stopped,
1137*b9c1b51eSKate Stone     // and that, without an intervening resume, we received another stop.  It is
1138*b9c1b51eSKate Stone     // more likely
1139*b9c1b51eSKate Stone     // that we are missing the marking of a run state somewhere if we find that
1140*b9c1b51eSKate Stone     // the thread was
1141aab58633SChaoren Lin     // marked as stopped.
1142b9cc0c75SPavel Labath     const StateType thread_state = thread.GetState();
1143*b9c1b51eSKate Stone     if (!StateIsStoppedState(thread_state, false)) {
1144ed89c7feSPavel Labath       // An inferior thread has stopped because of a SIGSTOP we have sent it.
1145*b9c1b51eSKate Stone       // Generally, these are not important stops and we don't want to report
1146*b9c1b51eSKate Stone       // them as
1147*b9c1b51eSKate Stone       // they are just used to stop other threads when one thread (the one with
1148*b9c1b51eSKate Stone       // the
1149*b9c1b51eSKate Stone       // *real* stop reason) hits a breakpoint (watchpoint, etc...). However, in
1150*b9c1b51eSKate Stone       // the
1151*b9c1b51eSKate Stone       // case of an asynchronous Interrupt(), this *is* the real stop reason, so
1152*b9c1b51eSKate Stone       // we
1153ed89c7feSPavel Labath       // leave the signal intact if this is the thread that was chosen as the
1154ed89c7feSPavel Labath       // triggering thread.
1155*b9c1b51eSKate Stone       if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
1156b9cc0c75SPavel Labath         if (m_pending_notification_tid == thread.GetID())
1157b9cc0c75SPavel Labath           thread.SetStoppedBySignal(SIGSTOP, &info);
1158ed89c7feSPavel Labath         else
1159b9cc0c75SPavel Labath           thread.SetStoppedWithNoReason();
1160ed89c7feSPavel Labath 
1161b9cc0c75SPavel Labath         SetCurrentThreadID(thread.GetID());
11620e1d729bSPavel Labath         SignalIfAllThreadsStopped();
1163*b9c1b51eSKate Stone       } else {
11640e1d729bSPavel Labath         // We can end up here if stop was initiated by LLGS but by this time a
11650e1d729bSPavel Labath         // thread stop has occurred - maybe initiated by another event.
1166b9cc0c75SPavel Labath         Error error = ResumeThread(thread, thread.GetState(), 0);
1167*b9c1b51eSKate Stone         if (error.Fail() && log) {
1168*b9c1b51eSKate Stone           log->Printf(
1169*b9c1b51eSKate Stone               "NativeProcessLinux::%s failed to resume thread tid  %" PRIu64
1170*b9c1b51eSKate Stone               ": %s",
1171b9cc0c75SPavel Labath               __FUNCTION__, thread.GetID(), error.AsCString());
11720e1d729bSPavel Labath         }
11730e1d729bSPavel Labath       }
1174*b9c1b51eSKate Stone     } else {
1175*b9c1b51eSKate Stone       if (log) {
1176aab58633SChaoren Lin         // Retrieve the signal name if the thread was stopped by a signal.
1177aab58633SChaoren Lin         int stop_signo = 0;
1178b9cc0c75SPavel Labath         const bool stopped_by_signal = thread.IsStopped(&stop_signo);
1179*b9c1b51eSKate Stone         const char *signal_name = stopped_by_signal
1180*b9c1b51eSKate Stone                                       ? Host::GetSignalAsCString(stop_signo)
1181*b9c1b51eSKate Stone                                       : "<not stopped by signal>";
1182aab58633SChaoren Lin         if (!signal_name)
1183aab58633SChaoren Lin           signal_name = "<no-signal-name>";
1184aab58633SChaoren Lin 
1185*b9c1b51eSKate Stone         log->Printf("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64
1186*b9c1b51eSKate Stone                     ", thread was already marked as a stopped state (state=%s, "
1187*b9c1b51eSKate Stone                     "signal=%d (%s)), leaving stop signal as is",
1188*b9c1b51eSKate Stone                     __FUNCTION__, GetID(), thread.GetID(),
1189*b9c1b51eSKate Stone                     StateAsCString(thread_state), stop_signo, signal_name);
1190aab58633SChaoren Lin       }
11910e1d729bSPavel Labath       SignalIfAllThreadsStopped();
1192af245d11STodd Fiala     }
1193af245d11STodd Fiala 
119458a2f669STodd Fiala     // Done handling.
1195af245d11STodd Fiala     return;
1196af245d11STodd Fiala   }
1197af245d11STodd Fiala 
1198af245d11STodd Fiala   if (log)
1199*b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s() received signal %s", __FUNCTION__,
1200*b9c1b51eSKate Stone                 Host::GetSignalAsCString(signo));
1201af245d11STodd Fiala 
120286fd8e45SChaoren Lin   // This thread is stopped.
1203b9cc0c75SPavel Labath   thread.SetStoppedBySignal(signo, &info);
120486fd8e45SChaoren Lin 
120586fd8e45SChaoren Lin   // Send a stop to the debugger after we get all other threads to stop.
1206b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
1207511e5cdcSTodd Fiala }
1208af245d11STodd Fiala 
1209e7708688STamas Berghammer namespace {
1210e7708688STamas Berghammer 
1211*b9c1b51eSKate Stone struct EmulatorBaton {
1212e7708688STamas Berghammer   NativeProcessLinux *m_process;
1213e7708688STamas Berghammer   NativeRegisterContext *m_reg_context;
12146648fcc3SPavel Labath 
12156648fcc3SPavel Labath   // eRegisterKindDWARF -> RegsiterValue
12166648fcc3SPavel Labath   std::unordered_map<uint32_t, RegisterValue> m_register_values;
1217e7708688STamas Berghammer 
1218*b9c1b51eSKate Stone   EmulatorBaton(NativeProcessLinux *process, NativeRegisterContext *reg_context)
1219*b9c1b51eSKate Stone       : m_process(process), m_reg_context(reg_context) {}
1220e7708688STamas Berghammer };
1221e7708688STamas Berghammer 
1222e7708688STamas Berghammer } // anonymous namespace
1223e7708688STamas Berghammer 
1224*b9c1b51eSKate Stone static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
1225e7708688STamas Berghammer                                  const EmulateInstruction::Context &context,
1226*b9c1b51eSKate Stone                                  lldb::addr_t addr, void *dst, size_t length) {
1227e7708688STamas Berghammer   EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
1228e7708688STamas Berghammer 
12293eb4b458SChaoren Lin   size_t bytes_read;
1230e7708688STamas Berghammer   emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
1231e7708688STamas Berghammer   return bytes_read;
1232e7708688STamas Berghammer }
1233e7708688STamas Berghammer 
1234*b9c1b51eSKate Stone static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
1235e7708688STamas Berghammer                                  const RegisterInfo *reg_info,
1236*b9c1b51eSKate Stone                                  RegisterValue &reg_value) {
1237e7708688STamas Berghammer   EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
1238e7708688STamas Berghammer 
1239*b9c1b51eSKate Stone   auto it = emulator_baton->m_register_values.find(
1240*b9c1b51eSKate Stone       reg_info->kinds[eRegisterKindDWARF]);
1241*b9c1b51eSKate Stone   if (it != emulator_baton->m_register_values.end()) {
12426648fcc3SPavel Labath     reg_value = it->second;
12436648fcc3SPavel Labath     return true;
12446648fcc3SPavel Labath   }
12456648fcc3SPavel Labath 
1246e7708688STamas Berghammer   // The emulator only fill in the dwarf regsiter numbers (and in some case
1247e7708688STamas Berghammer   // the generic register numbers). Get the full register info from the
1248e7708688STamas Berghammer   // register context based on the dwarf register numbers.
1249*b9c1b51eSKate Stone   const RegisterInfo *full_reg_info =
1250*b9c1b51eSKate Stone       emulator_baton->m_reg_context->GetRegisterInfo(
1251e7708688STamas Berghammer           eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
1252e7708688STamas Berghammer 
1253*b9c1b51eSKate Stone   Error error =
1254*b9c1b51eSKate Stone       emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
12556648fcc3SPavel Labath   if (error.Success())
12566648fcc3SPavel Labath     return true;
1257cdc22a88SMohit K. Bhakkad 
12586648fcc3SPavel Labath   return false;
1259e7708688STamas Berghammer }
1260e7708688STamas Berghammer 
1261*b9c1b51eSKate Stone static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
1262e7708688STamas Berghammer                                   const EmulateInstruction::Context &context,
1263e7708688STamas Berghammer                                   const RegisterInfo *reg_info,
1264*b9c1b51eSKate Stone                                   const RegisterValue &reg_value) {
1265e7708688STamas Berghammer   EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
1266*b9c1b51eSKate Stone   emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
1267*b9c1b51eSKate Stone       reg_value;
1268e7708688STamas Berghammer   return true;
1269e7708688STamas Berghammer }
1270e7708688STamas Berghammer 
1271*b9c1b51eSKate Stone static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
1272e7708688STamas Berghammer                                   const EmulateInstruction::Context &context,
1273*b9c1b51eSKate Stone                                   lldb::addr_t addr, const void *dst,
1274*b9c1b51eSKate Stone                                   size_t length) {
1275e7708688STamas Berghammer   return length;
1276e7708688STamas Berghammer }
1277e7708688STamas Berghammer 
1278*b9c1b51eSKate Stone static lldb::addr_t ReadFlags(NativeRegisterContext *regsiter_context) {
1279e7708688STamas Berghammer   const RegisterInfo *flags_info = regsiter_context->GetRegisterInfo(
1280e7708688STamas Berghammer       eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1281*b9c1b51eSKate Stone   return regsiter_context->ReadRegisterAsUnsigned(flags_info,
1282*b9c1b51eSKate Stone                                                   LLDB_INVALID_ADDRESS);
1283e7708688STamas Berghammer }
1284e7708688STamas Berghammer 
1285*b9c1b51eSKate Stone Error NativeProcessLinux::SetupSoftwareSingleStepping(
1286*b9c1b51eSKate Stone     NativeThreadLinux &thread) {
1287e7708688STamas Berghammer   Error error;
1288b9cc0c75SPavel Labath   NativeRegisterContextSP register_context_sp = thread.GetRegisterContext();
1289e7708688STamas Berghammer 
1290e7708688STamas Berghammer   std::unique_ptr<EmulateInstruction> emulator_ap(
1291*b9c1b51eSKate Stone       EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying,
1292*b9c1b51eSKate Stone                                      nullptr));
1293e7708688STamas Berghammer 
1294e7708688STamas Berghammer   if (emulator_ap == nullptr)
1295e7708688STamas Berghammer     return Error("Instruction emulator not found!");
1296e7708688STamas Berghammer 
1297e7708688STamas Berghammer   EmulatorBaton baton(this, register_context_sp.get());
1298e7708688STamas Berghammer   emulator_ap->SetBaton(&baton);
1299e7708688STamas Berghammer   emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
1300e7708688STamas Berghammer   emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
1301e7708688STamas Berghammer   emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
1302e7708688STamas Berghammer   emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
1303e7708688STamas Berghammer 
1304e7708688STamas Berghammer   if (!emulator_ap->ReadInstruction())
1305e7708688STamas Berghammer     return Error("Read instruction failed!");
1306e7708688STamas Berghammer 
1307*b9c1b51eSKate Stone   bool emulation_result =
1308*b9c1b51eSKate Stone       emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
13096648fcc3SPavel Labath 
1310*b9c1b51eSKate Stone   const RegisterInfo *reg_info_pc = register_context_sp->GetRegisterInfo(
1311*b9c1b51eSKate Stone       eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1312*b9c1b51eSKate Stone   const RegisterInfo *reg_info_flags = register_context_sp->GetRegisterInfo(
1313*b9c1b51eSKate Stone       eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
13146648fcc3SPavel Labath 
1315*b9c1b51eSKate Stone   auto pc_it =
1316*b9c1b51eSKate Stone       baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1317*b9c1b51eSKate Stone   auto flags_it =
1318*b9c1b51eSKate Stone       baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
13196648fcc3SPavel Labath 
1320e7708688STamas Berghammer   lldb::addr_t next_pc;
1321e7708688STamas Berghammer   lldb::addr_t next_flags;
1322*b9c1b51eSKate Stone   if (emulation_result) {
1323*b9c1b51eSKate Stone     assert(pc_it != baton.m_register_values.end() &&
1324*b9c1b51eSKate Stone            "Emulation was successfull but PC wasn't updated");
13256648fcc3SPavel Labath     next_pc = pc_it->second.GetAsUInt64();
13266648fcc3SPavel Labath 
13276648fcc3SPavel Labath     if (flags_it != baton.m_register_values.end())
13286648fcc3SPavel Labath       next_flags = flags_it->second.GetAsUInt64();
1329e7708688STamas Berghammer     else
1330e7708688STamas Berghammer       next_flags = ReadFlags(register_context_sp.get());
1331*b9c1b51eSKate Stone   } else if (pc_it == baton.m_register_values.end()) {
1332e7708688STamas Berghammer     // Emulate instruction failed and it haven't changed PC. Advance PC
1333e7708688STamas Berghammer     // with the size of the current opcode because the emulation of all
1334e7708688STamas Berghammer     // PC modifying instruction should be successful. The failure most
1335e7708688STamas Berghammer     // likely caused by a not supported instruction which don't modify PC.
1336*b9c1b51eSKate Stone     next_pc =
1337*b9c1b51eSKate Stone         register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
1338e7708688STamas Berghammer     next_flags = ReadFlags(register_context_sp.get());
1339*b9c1b51eSKate Stone   } else {
1340e7708688STamas Berghammer     // The instruction emulation failed after it modified the PC. It is an
1341e7708688STamas Berghammer     // unknown error where we can't continue because the next instruction is
1342e7708688STamas Berghammer     // modifying the PC but we don't  know how.
1343e7708688STamas Berghammer     return Error("Instruction emulation failed unexpectedly.");
1344e7708688STamas Berghammer   }
1345e7708688STamas Berghammer 
1346*b9c1b51eSKate Stone   if (m_arch.GetMachine() == llvm::Triple::arm) {
1347*b9c1b51eSKate Stone     if (next_flags & 0x20) {
1348e7708688STamas Berghammer       // Thumb mode
1349e7708688STamas Berghammer       error = SetSoftwareBreakpoint(next_pc, 2);
1350*b9c1b51eSKate Stone     } else {
1351e7708688STamas Berghammer       // Arm mode
1352e7708688STamas Berghammer       error = SetSoftwareBreakpoint(next_pc, 4);
1353e7708688STamas Berghammer     }
1354*b9c1b51eSKate Stone   } else if (m_arch.GetMachine() == llvm::Triple::mips64 ||
1355*b9c1b51eSKate Stone              m_arch.GetMachine() == llvm::Triple::mips64el ||
1356*b9c1b51eSKate Stone              m_arch.GetMachine() == llvm::Triple::mips ||
1357*b9c1b51eSKate Stone              m_arch.GetMachine() == llvm::Triple::mipsel)
1358cdc22a88SMohit K. Bhakkad     error = SetSoftwareBreakpoint(next_pc, 4);
1359*b9c1b51eSKate Stone   else {
1360e7708688STamas Berghammer     // No size hint is given for the next breakpoint
1361e7708688STamas Berghammer     error = SetSoftwareBreakpoint(next_pc, 0);
1362e7708688STamas Berghammer   }
1363e7708688STamas Berghammer 
1364e7708688STamas Berghammer   if (error.Fail())
1365e7708688STamas Berghammer     return error;
1366e7708688STamas Berghammer 
1367b9cc0c75SPavel Labath   m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
1368e7708688STamas Berghammer 
1369e7708688STamas Berghammer   return Error();
1370e7708688STamas Berghammer }
1371e7708688STamas Berghammer 
1372*b9c1b51eSKate Stone bool NativeProcessLinux::SupportHardwareSingleStepping() const {
1373*b9c1b51eSKate Stone   if (m_arch.GetMachine() == llvm::Triple::arm ||
1374*b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mips64 ||
1375*b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mips64el ||
1376*b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mips ||
1377*b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mipsel)
1378cdc22a88SMohit K. Bhakkad     return false;
1379cdc22a88SMohit K. Bhakkad   return true;
1380e7708688STamas Berghammer }
1381e7708688STamas Berghammer 
1382*b9c1b51eSKate Stone Error NativeProcessLinux::Resume(const ResumeActionList &resume_actions) {
1383af245d11STodd Fiala   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1384af245d11STodd Fiala   if (log)
1385*b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__,
1386*b9c1b51eSKate Stone                 GetID());
1387af245d11STodd Fiala 
1388e7708688STamas Berghammer   bool software_single_step = !SupportHardwareSingleStepping();
1389af245d11STodd Fiala 
1390*b9c1b51eSKate Stone   if (software_single_step) {
1391*b9c1b51eSKate Stone     for (auto thread_sp : m_threads) {
1392e7708688STamas Berghammer       assert(thread_sp && "thread list should not contain NULL threads");
1393e7708688STamas Berghammer 
1394*b9c1b51eSKate Stone       const ResumeAction *const action =
1395*b9c1b51eSKate Stone           resume_actions.GetActionForThread(thread_sp->GetID(), true);
1396e7708688STamas Berghammer       if (action == nullptr)
1397e7708688STamas Berghammer         continue;
1398e7708688STamas Berghammer 
1399*b9c1b51eSKate Stone       if (action->state == eStateStepping) {
1400*b9c1b51eSKate Stone         Error error = SetupSoftwareSingleStepping(
1401*b9c1b51eSKate Stone             static_cast<NativeThreadLinux &>(*thread_sp));
1402e7708688STamas Berghammer         if (error.Fail())
1403e7708688STamas Berghammer           return error;
1404e7708688STamas Berghammer       }
1405e7708688STamas Berghammer     }
1406e7708688STamas Berghammer   }
1407e7708688STamas Berghammer 
1408*b9c1b51eSKate Stone   for (auto thread_sp : m_threads) {
1409af245d11STodd Fiala     assert(thread_sp && "thread list should not contain NULL threads");
1410af245d11STodd Fiala 
1411*b9c1b51eSKate Stone     const ResumeAction *const action =
1412*b9c1b51eSKate Stone         resume_actions.GetActionForThread(thread_sp->GetID(), true);
14136a196ce6SChaoren Lin 
1414*b9c1b51eSKate Stone     if (action == nullptr) {
14156a196ce6SChaoren Lin       if (log)
1416*b9c1b51eSKate Stone         log->Printf(
1417*b9c1b51eSKate Stone             "NativeProcessLinux::%s no action specified for pid %" PRIu64
1418*b9c1b51eSKate Stone             " tid %" PRIu64,
14196a196ce6SChaoren Lin             __FUNCTION__, GetID(), thread_sp->GetID());
14206a196ce6SChaoren Lin       continue;
14216a196ce6SChaoren Lin     }
1422af245d11STodd Fiala 
1423*b9c1b51eSKate Stone     if (log) {
1424*b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s processing resume action state %s "
1425*b9c1b51eSKate Stone                   "for pid %" PRIu64 " tid %" PRIu64,
1426*b9c1b51eSKate Stone                   __FUNCTION__, StateAsCString(action->state), GetID(),
1427*b9c1b51eSKate Stone                   thread_sp->GetID());
1428af245d11STodd Fiala     }
1429af245d11STodd Fiala 
1430*b9c1b51eSKate Stone     switch (action->state) {
1431af245d11STodd Fiala     case eStateRunning:
1432*b9c1b51eSKate Stone     case eStateStepping: {
1433af245d11STodd Fiala       // Run the thread, possibly feeding it the signal.
1434fa03ad2eSChaoren Lin       const int signo = action->signal;
1435*b9c1b51eSKate Stone       ResumeThread(static_cast<NativeThreadLinux &>(*thread_sp), action->state,
1436*b9c1b51eSKate Stone                    signo);
1437af245d11STodd Fiala       break;
1438ae29d395SChaoren Lin     }
1439af245d11STodd Fiala 
1440af245d11STodd Fiala     case eStateSuspended:
1441af245d11STodd Fiala     case eStateStopped:
1442108c325dSPavel Labath       lldbassert(0 && "Unexpected state");
1443af245d11STodd Fiala 
1444af245d11STodd Fiala     default:
1445*b9c1b51eSKate Stone       return Error("NativeProcessLinux::%s (): unexpected state %s specified "
1446*b9c1b51eSKate Stone                    "for pid %" PRIu64 ", tid %" PRIu64,
1447*b9c1b51eSKate Stone                    __FUNCTION__, StateAsCString(action->state), GetID(),
1448*b9c1b51eSKate Stone                    thread_sp->GetID());
1449af245d11STodd Fiala     }
1450af245d11STodd Fiala   }
1451af245d11STodd Fiala 
14525830aa75STamas Berghammer   return Error();
1453af245d11STodd Fiala }
1454af245d11STodd Fiala 
1455*b9c1b51eSKate Stone Error NativeProcessLinux::Halt() {
1456af245d11STodd Fiala   Error error;
1457af245d11STodd Fiala 
1458af245d11STodd Fiala   if (kill(GetID(), SIGSTOP) != 0)
1459af245d11STodd Fiala     error.SetErrorToErrno();
1460af245d11STodd Fiala 
1461af245d11STodd Fiala   return error;
1462af245d11STodd Fiala }
1463af245d11STodd Fiala 
1464*b9c1b51eSKate Stone Error NativeProcessLinux::Detach() {
1465af245d11STodd Fiala   Error error;
1466af245d11STodd Fiala 
1467af245d11STodd Fiala   // Stop monitoring the inferior.
146819cbe96aSPavel Labath   m_sigchld_handle.reset();
1469af245d11STodd Fiala 
14707a9495bcSPavel Labath   // Tell ptrace to detach from the process.
14717a9495bcSPavel Labath   if (GetID() == LLDB_INVALID_PROCESS_ID)
14727a9495bcSPavel Labath     return error;
14737a9495bcSPavel Labath 
1474*b9c1b51eSKate Stone   for (auto thread_sp : m_threads) {
14757a9495bcSPavel Labath     Error e = Detach(thread_sp->GetID());
14767a9495bcSPavel Labath     if (e.Fail())
1477*b9c1b51eSKate Stone       error =
1478*b9c1b51eSKate Stone           e; // Save the error, but still attempt to detach from other threads.
14797a9495bcSPavel Labath   }
14807a9495bcSPavel Labath 
1481af245d11STodd Fiala   return error;
1482af245d11STodd Fiala }
1483af245d11STodd Fiala 
1484*b9c1b51eSKate Stone Error NativeProcessLinux::Signal(int signo) {
1485af245d11STodd Fiala   Error error;
1486af245d11STodd Fiala 
1487af245d11STodd Fiala   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1488af245d11STodd Fiala   if (log)
1489*b9c1b51eSKate Stone     log->Printf(
1490*b9c1b51eSKate Stone         "NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
149198d0a4b3SChaoren Lin         __FUNCTION__, signo, Host::GetSignalAsCString(signo), GetID());
1492af245d11STodd Fiala 
1493af245d11STodd Fiala   if (kill(GetID(), signo))
1494af245d11STodd Fiala     error.SetErrorToErrno();
1495af245d11STodd Fiala 
1496af245d11STodd Fiala   return error;
1497af245d11STodd Fiala }
1498af245d11STodd Fiala 
1499*b9c1b51eSKate Stone Error NativeProcessLinux::Interrupt() {
1500e9547b80SChaoren Lin   // Pick a running thread (or if none, a not-dead stopped thread) as
1501e9547b80SChaoren Lin   // the chosen thread that will be the stop-reason thread.
1502e9547b80SChaoren Lin   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1503e9547b80SChaoren Lin 
1504e9547b80SChaoren Lin   NativeThreadProtocolSP running_thread_sp;
1505e9547b80SChaoren Lin   NativeThreadProtocolSP stopped_thread_sp;
1506e9547b80SChaoren Lin 
1507e9547b80SChaoren Lin   if (log)
1508*b9c1b51eSKate Stone     log->Printf(
1509*b9c1b51eSKate Stone         "NativeProcessLinux::%s selecting running thread for interrupt target",
1510*b9c1b51eSKate Stone         __FUNCTION__);
1511e9547b80SChaoren Lin 
1512*b9c1b51eSKate Stone   for (auto thread_sp : m_threads) {
1513e9547b80SChaoren Lin     // The thread shouldn't be null but lets just cover that here.
1514e9547b80SChaoren Lin     if (!thread_sp)
1515e9547b80SChaoren Lin       continue;
1516e9547b80SChaoren Lin 
1517e9547b80SChaoren Lin     // If we have a running or stepping thread, we'll call that the
1518e9547b80SChaoren Lin     // target of the interrupt.
1519e9547b80SChaoren Lin     const auto thread_state = thread_sp->GetState();
1520*b9c1b51eSKate Stone     if (thread_state == eStateRunning || thread_state == eStateStepping) {
1521e9547b80SChaoren Lin       running_thread_sp = thread_sp;
1522e9547b80SChaoren Lin       break;
1523*b9c1b51eSKate Stone     } else if (!stopped_thread_sp && StateIsStoppedState(thread_state, true)) {
1524*b9c1b51eSKate Stone       // Remember the first non-dead stopped thread.  We'll use that as a backup
1525*b9c1b51eSKate Stone       // if there are no running threads.
1526e9547b80SChaoren Lin       stopped_thread_sp = thread_sp;
1527e9547b80SChaoren Lin     }
1528e9547b80SChaoren Lin   }
1529e9547b80SChaoren Lin 
1530*b9c1b51eSKate Stone   if (!running_thread_sp && !stopped_thread_sp) {
1531*b9c1b51eSKate Stone     Error error("found no running/stepping or live stopped threads as target "
1532*b9c1b51eSKate Stone                 "for interrupt");
1533e9547b80SChaoren Lin     if (log)
1534*b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s skipping due to error: %s",
1535*b9c1b51eSKate Stone                   __FUNCTION__, error.AsCString());
15365830aa75STamas Berghammer 
1537e9547b80SChaoren Lin     return error;
1538e9547b80SChaoren Lin   }
1539e9547b80SChaoren Lin 
1540*b9c1b51eSKate Stone   NativeThreadProtocolSP deferred_signal_thread_sp =
1541*b9c1b51eSKate Stone       running_thread_sp ? running_thread_sp : stopped_thread_sp;
1542e9547b80SChaoren Lin 
1543e9547b80SChaoren Lin   if (log)
1544*b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64
1545*b9c1b51eSKate Stone                 " chosen for interrupt target",
1546*b9c1b51eSKate Stone                 __FUNCTION__, GetID(),
1547e9547b80SChaoren Lin                 running_thread_sp ? "running" : "stopped",
1548e9547b80SChaoren Lin                 deferred_signal_thread_sp->GetID());
1549e9547b80SChaoren Lin 
1550ed89c7feSPavel Labath   StopRunningThreads(deferred_signal_thread_sp->GetID());
155145f5cb31SPavel Labath 
15525830aa75STamas Berghammer   return Error();
1553e9547b80SChaoren Lin }
1554e9547b80SChaoren Lin 
1555*b9c1b51eSKate Stone Error NativeProcessLinux::Kill() {
1556af245d11STodd Fiala   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1557af245d11STodd Fiala   if (log)
1558*b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__,
1559*b9c1b51eSKate Stone                 GetID());
1560af245d11STodd Fiala 
1561af245d11STodd Fiala   Error error;
1562af245d11STodd Fiala 
1563*b9c1b51eSKate Stone   switch (m_state) {
1564af245d11STodd Fiala   case StateType::eStateInvalid:
1565af245d11STodd Fiala   case StateType::eStateExited:
1566af245d11STodd Fiala   case StateType::eStateCrashed:
1567af245d11STodd Fiala   case StateType::eStateDetached:
1568af245d11STodd Fiala   case StateType::eStateUnloaded:
1569af245d11STodd Fiala     // Nothing to do - the process is already dead.
1570af245d11STodd Fiala     if (log)
1571*b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s ignored for PID %" PRIu64
1572*b9c1b51eSKate Stone                   " due to current state: %s",
1573*b9c1b51eSKate Stone                   __FUNCTION__, GetID(), StateAsCString(m_state));
1574af245d11STodd Fiala     return error;
1575af245d11STodd Fiala 
1576af245d11STodd Fiala   case StateType::eStateConnected:
1577af245d11STodd Fiala   case StateType::eStateAttaching:
1578af245d11STodd Fiala   case StateType::eStateLaunching:
1579af245d11STodd Fiala   case StateType::eStateStopped:
1580af245d11STodd Fiala   case StateType::eStateRunning:
1581af245d11STodd Fiala   case StateType::eStateStepping:
1582af245d11STodd Fiala   case StateType::eStateSuspended:
1583af245d11STodd Fiala     // We can try to kill a process in these states.
1584af245d11STodd Fiala     break;
1585af245d11STodd Fiala   }
1586af245d11STodd Fiala 
1587*b9c1b51eSKate Stone   if (kill(GetID(), SIGKILL) != 0) {
1588af245d11STodd Fiala     error.SetErrorToErrno();
1589af245d11STodd Fiala     return error;
1590af245d11STodd Fiala   }
1591af245d11STodd Fiala 
1592af245d11STodd Fiala   return error;
1593af245d11STodd Fiala }
1594af245d11STodd Fiala 
1595af245d11STodd Fiala static Error
1596*b9c1b51eSKate Stone ParseMemoryRegionInfoFromProcMapsLine(const std::string &maps_line,
1597*b9c1b51eSKate Stone                                       MemoryRegionInfo &memory_region_info) {
1598af245d11STodd Fiala   memory_region_info.Clear();
1599af245d11STodd Fiala 
1600b9739d40SPavel Labath   StringExtractor line_extractor(maps_line.c_str());
1601af245d11STodd Fiala 
1602*b9c1b51eSKate Stone   // Format: {address_start_hex}-{address_end_hex} perms offset  dev   inode
1603*b9c1b51eSKate Stone   // pathname
1604*b9c1b51eSKate Stone   // perms: rwxp   (letter is present if set, '-' if not, final character is
1605*b9c1b51eSKate Stone   // p=private, s=shared).
1606af245d11STodd Fiala 
1607af245d11STodd Fiala   // Parse out the starting address
1608af245d11STodd Fiala   lldb::addr_t start_address = line_extractor.GetHexMaxU64(false, 0);
1609af245d11STodd Fiala 
1610af245d11STodd Fiala   // Parse out hyphen separating start and end address from range.
1611af245d11STodd Fiala   if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != '-'))
1612*b9c1b51eSKate Stone     return Error(
1613*b9c1b51eSKate Stone         "malformed /proc/{pid}/maps entry, missing dash between address range");
1614af245d11STodd Fiala 
1615af245d11STodd Fiala   // Parse out the ending address
1616af245d11STodd Fiala   lldb::addr_t end_address = line_extractor.GetHexMaxU64(false, start_address);
1617af245d11STodd Fiala 
1618af245d11STodd Fiala   // Parse out the space after the address.
1619af245d11STodd Fiala   if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != ' '))
1620af245d11STodd Fiala     return Error("malformed /proc/{pid}/maps entry, missing space after range");
1621af245d11STodd Fiala 
1622af245d11STodd Fiala   // Save the range.
1623af245d11STodd Fiala   memory_region_info.GetRange().SetRangeBase(start_address);
1624af245d11STodd Fiala   memory_region_info.GetRange().SetRangeEnd(end_address);
1625af245d11STodd Fiala 
1626*b9c1b51eSKate Stone   // Any memory region in /proc/{pid}/maps is by definition mapped into the
1627*b9c1b51eSKate Stone   // process.
1628ad007563SHoward Hellyer   memory_region_info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
1629ad007563SHoward Hellyer 
1630af245d11STodd Fiala   // Parse out each permission entry.
1631af245d11STodd Fiala   if (line_extractor.GetBytesLeft() < 4)
1632*b9c1b51eSKate Stone     return Error("malformed /proc/{pid}/maps entry, missing some portion of "
1633*b9c1b51eSKate Stone                  "permissions");
1634af245d11STodd Fiala 
1635af245d11STodd Fiala   // Handle read permission.
1636af245d11STodd Fiala   const char read_perm_char = line_extractor.GetChar();
1637af245d11STodd Fiala   if (read_perm_char == 'r')
1638af245d11STodd Fiala     memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eYes);
1639c73301bbSTamas Berghammer   else if (read_perm_char == '-')
1640af245d11STodd Fiala     memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1641c73301bbSTamas Berghammer   else
1642c73301bbSTamas Berghammer     return Error("unexpected /proc/{pid}/maps read permission char");
1643af245d11STodd Fiala 
1644af245d11STodd Fiala   // Handle write permission.
1645af245d11STodd Fiala   const char write_perm_char = line_extractor.GetChar();
1646af245d11STodd Fiala   if (write_perm_char == 'w')
1647af245d11STodd Fiala     memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eYes);
1648c73301bbSTamas Berghammer   else if (write_perm_char == '-')
1649af245d11STodd Fiala     memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1650c73301bbSTamas Berghammer   else
1651c73301bbSTamas Berghammer     return Error("unexpected /proc/{pid}/maps write permission char");
1652af245d11STodd Fiala 
1653af245d11STodd Fiala   // Handle execute permission.
1654af245d11STodd Fiala   const char exec_perm_char = line_extractor.GetChar();
1655af245d11STodd Fiala   if (exec_perm_char == 'x')
1656af245d11STodd Fiala     memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes);
1657c73301bbSTamas Berghammer   else if (exec_perm_char == '-')
1658af245d11STodd Fiala     memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1659c73301bbSTamas Berghammer   else
1660c73301bbSTamas Berghammer     return Error("unexpected /proc/{pid}/maps exec permission char");
1661af245d11STodd Fiala 
1662d7d69f80STamas Berghammer   line_extractor.GetChar();              // Read the private bit
1663d7d69f80STamas Berghammer   line_extractor.SkipSpaces();           // Skip the separator
1664d7d69f80STamas Berghammer   line_extractor.GetHexMaxU64(false, 0); // Read the offset
1665d7d69f80STamas Berghammer   line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1666d7d69f80STamas Berghammer   line_extractor.GetChar();              // Read the device id separator
1667d7d69f80STamas Berghammer   line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1668d7d69f80STamas Berghammer   line_extractor.SkipSpaces();           // Skip the separator
1669d7d69f80STamas Berghammer   line_extractor.GetU64(0, 10);          // Read the inode number
1670d7d69f80STamas Berghammer 
1671d7d69f80STamas Berghammer   line_extractor.SkipSpaces();
1672b9739d40SPavel Labath   const char *name = line_extractor.Peek();
1673b9739d40SPavel Labath   if (name)
1674b9739d40SPavel Labath     memory_region_info.SetName(name);
1675d7d69f80STamas Berghammer 
1676af245d11STodd Fiala   return Error();
1677af245d11STodd Fiala }
1678af245d11STodd Fiala 
1679*b9c1b51eSKate Stone Error NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr,
1680*b9c1b51eSKate Stone                                               MemoryRegionInfo &range_info) {
1681*b9c1b51eSKate Stone   // FIXME review that the final memory region returned extends to the end of
1682*b9c1b51eSKate Stone   // the virtual address space,
1683af245d11STodd Fiala   // with no perms if it is not mapped.
1684af245d11STodd Fiala 
1685af245d11STodd Fiala   // Use an approach that reads memory regions from /proc/{pid}/maps.
1686af245d11STodd Fiala   // Assume proc maps entries are in ascending order.
1687af245d11STodd Fiala   // FIXME assert if we find differently.
1688af245d11STodd Fiala 
1689af245d11STodd Fiala   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1690af245d11STodd Fiala   Error error;
1691af245d11STodd Fiala 
1692*b9c1b51eSKate Stone   if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
1693af245d11STodd Fiala     // We're done.
1694af245d11STodd Fiala     error.SetErrorString("unsupported");
1695af245d11STodd Fiala     return error;
1696af245d11STodd Fiala   }
1697af245d11STodd Fiala 
1698*b9c1b51eSKate Stone   // If our cache is empty, pull the latest.  There should always be at least
1699*b9c1b51eSKate Stone   // one memory region
1700af245d11STodd Fiala   // if memory region handling is supported.
1701*b9c1b51eSKate Stone   if (m_mem_region_cache.empty()) {
1702*b9c1b51eSKate Stone     error = ProcFileReader::ProcessLineByLine(
1703*b9c1b51eSKate Stone         GetID(), "maps", [&](const std::string &line) -> bool {
1704af245d11STodd Fiala           MemoryRegionInfo info;
1705*b9c1b51eSKate Stone           const Error parse_error =
1706*b9c1b51eSKate Stone               ParseMemoryRegionInfoFromProcMapsLine(line, info);
1707*b9c1b51eSKate Stone           if (parse_error.Success()) {
1708af245d11STodd Fiala             m_mem_region_cache.push_back(info);
1709af245d11STodd Fiala             return true;
1710*b9c1b51eSKate Stone           } else {
1711af245d11STodd Fiala             if (log)
1712*b9c1b51eSKate Stone               log->Printf("NativeProcessLinux::%s failed to parse proc maps "
1713*b9c1b51eSKate Stone                           "line '%s': %s",
1714*b9c1b51eSKate Stone                           __FUNCTION__, line.c_str(), error.AsCString());
1715af245d11STodd Fiala             return false;
1716af245d11STodd Fiala           }
1717af245d11STodd Fiala         });
1718af245d11STodd Fiala 
1719af245d11STodd Fiala     // If we had an error, we'll mark unsupported.
1720*b9c1b51eSKate Stone     if (error.Fail()) {
1721af245d11STodd Fiala       m_supports_mem_region = LazyBool::eLazyBoolNo;
1722af245d11STodd Fiala       return error;
1723*b9c1b51eSKate Stone     } else if (m_mem_region_cache.empty()) {
1724*b9c1b51eSKate Stone       // No entries after attempting to read them.  This shouldn't happen if
1725*b9c1b51eSKate Stone       // /proc/{pid}/maps
1726af245d11STodd Fiala       // is supported.  Assume we don't support map entries via procfs.
1727af245d11STodd Fiala       if (log)
1728*b9c1b51eSKate Stone         log->Printf("NativeProcessLinux::%s failed to find any procfs maps "
1729*b9c1b51eSKate Stone                     "entries, assuming no support for memory region metadata "
1730*b9c1b51eSKate Stone                     "retrieval",
1731*b9c1b51eSKate Stone                     __FUNCTION__);
1732af245d11STodd Fiala       m_supports_mem_region = LazyBool::eLazyBoolNo;
1733af245d11STodd Fiala       error.SetErrorString("not supported");
1734af245d11STodd Fiala       return error;
1735af245d11STodd Fiala     }
1736af245d11STodd Fiala 
1737af245d11STodd Fiala     if (log)
1738*b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s read %" PRIu64
1739*b9c1b51eSKate Stone                   " memory region entries from /proc/%" PRIu64 "/maps",
1740*b9c1b51eSKate Stone                   __FUNCTION__,
1741*b9c1b51eSKate Stone                   static_cast<uint64_t>(m_mem_region_cache.size()), GetID());
1742af245d11STodd Fiala 
1743af245d11STodd Fiala     // We support memory retrieval, remember that.
1744af245d11STodd Fiala     m_supports_mem_region = LazyBool::eLazyBoolYes;
1745*b9c1b51eSKate Stone   } else {
1746af245d11STodd Fiala     if (log)
1747*b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s reusing %" PRIu64
1748*b9c1b51eSKate Stone                   " cached memory region entries",
1749*b9c1b51eSKate Stone                   __FUNCTION__,
1750*b9c1b51eSKate Stone                   static_cast<uint64_t>(m_mem_region_cache.size()));
1751af245d11STodd Fiala   }
1752af245d11STodd Fiala 
1753af245d11STodd Fiala   lldb::addr_t prev_base_address = 0;
1754af245d11STodd Fiala 
1755*b9c1b51eSKate Stone   // FIXME start by finding the last region that is <= target address using
1756*b9c1b51eSKate Stone   // binary search.  Data is sorted.
1757af245d11STodd Fiala   // There can be a ton of regions on pthreads apps with lots of threads.
1758*b9c1b51eSKate Stone   for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1759*b9c1b51eSKate Stone        ++it) {
1760af245d11STodd Fiala     MemoryRegionInfo &proc_entry_info = *it;
1761af245d11STodd Fiala 
1762af245d11STodd Fiala     // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1763*b9c1b51eSKate Stone     assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
1764*b9c1b51eSKate Stone            "descending /proc/pid/maps entries detected, unexpected");
1765af245d11STodd Fiala     prev_base_address = proc_entry_info.GetRange().GetRangeBase();
1766af245d11STodd Fiala 
1767*b9c1b51eSKate Stone     // If the target address comes before this entry, indicate distance to next
1768*b9c1b51eSKate Stone     // region.
1769*b9c1b51eSKate Stone     if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1770af245d11STodd Fiala       range_info.GetRange().SetRangeBase(load_addr);
1771*b9c1b51eSKate Stone       range_info.GetRange().SetByteSize(
1772*b9c1b51eSKate Stone           proc_entry_info.GetRange().GetRangeBase() - load_addr);
1773af245d11STodd Fiala       range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1774af245d11STodd Fiala       range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1775af245d11STodd Fiala       range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1776ad007563SHoward Hellyer       range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1777af245d11STodd Fiala 
1778af245d11STodd Fiala       return error;
1779*b9c1b51eSKate Stone     } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1780af245d11STodd Fiala       // The target address is within the memory region we're processing here.
1781af245d11STodd Fiala       range_info = proc_entry_info;
1782af245d11STodd Fiala       return error;
1783af245d11STodd Fiala     }
1784af245d11STodd Fiala 
1785*b9c1b51eSKate Stone     // The target memory address comes somewhere after the region we just
1786*b9c1b51eSKate Stone     // parsed.
1787af245d11STodd Fiala   }
1788af245d11STodd Fiala 
1789*b9c1b51eSKate Stone   // If we made it here, we didn't find an entry that contained the given
1790*b9c1b51eSKate Stone   // address. Return the
1791*b9c1b51eSKate Stone   // load_addr as start and the amount of bytes betwwen load address and the end
1792*b9c1b51eSKate Stone   // of the memory as
179309839c33STamas Berghammer   // size.
179409839c33STamas Berghammer   range_info.GetRange().SetRangeBase(load_addr);
1795ad007563SHoward Hellyer   range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
179609839c33STamas Berghammer   range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
179709839c33STamas Berghammer   range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
179809839c33STamas Berghammer   range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1799ad007563SHoward Hellyer   range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1800af245d11STodd Fiala   return error;
1801af245d11STodd Fiala }
1802af245d11STodd Fiala 
1803*b9c1b51eSKate Stone void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
1804af245d11STodd Fiala   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1805af245d11STodd Fiala   if (log)
1806*b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called",
1807*b9c1b51eSKate Stone                 __FUNCTION__, newBumpId);
1808af245d11STodd Fiala 
1809af245d11STodd Fiala   if (log)
1810*b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s clearing %" PRIu64
1811*b9c1b51eSKate Stone                 " entries from the cache",
1812*b9c1b51eSKate Stone                 __FUNCTION__, static_cast<uint64_t>(m_mem_region_cache.size()));
1813af245d11STodd Fiala   m_mem_region_cache.clear();
1814af245d11STodd Fiala }
1815af245d11STodd Fiala 
1816*b9c1b51eSKate Stone Error NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions,
1817*b9c1b51eSKate Stone                                          lldb::addr_t &addr) {
1818af245d11STodd Fiala // FIXME implementing this requires the equivalent of
1819af245d11STodd Fiala // InferiorCallPOSIX::InferiorCallMmap, which depends on
1820af245d11STodd Fiala // functional ThreadPlans working with Native*Protocol.
1821af245d11STodd Fiala #if 1
1822af245d11STodd Fiala   return Error("not implemented yet");
1823af245d11STodd Fiala #else
1824af245d11STodd Fiala   addr = LLDB_INVALID_ADDRESS;
1825af245d11STodd Fiala 
1826af245d11STodd Fiala   unsigned prot = 0;
1827af245d11STodd Fiala   if (permissions & lldb::ePermissionsReadable)
1828af245d11STodd Fiala     prot |= eMmapProtRead;
1829af245d11STodd Fiala   if (permissions & lldb::ePermissionsWritable)
1830af245d11STodd Fiala     prot |= eMmapProtWrite;
1831af245d11STodd Fiala   if (permissions & lldb::ePermissionsExecutable)
1832af245d11STodd Fiala     prot |= eMmapProtExec;
1833af245d11STodd Fiala 
1834af245d11STodd Fiala   // TODO implement this directly in NativeProcessLinux
1835af245d11STodd Fiala   // (and lift to NativeProcessPOSIX if/when that class is
1836af245d11STodd Fiala   // refactored out).
1837af245d11STodd Fiala   if (InferiorCallMmap(this, addr, 0, size, prot,
1838af245d11STodd Fiala                        eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
1839af245d11STodd Fiala     m_addr_to_mmap_size[addr] = size;
1840af245d11STodd Fiala     return Error();
1841af245d11STodd Fiala   } else {
1842af245d11STodd Fiala     addr = LLDB_INVALID_ADDRESS;
1843*b9c1b51eSKate Stone     return Error("unable to allocate %" PRIu64
1844*b9c1b51eSKate Stone                  " bytes of memory with permissions %s",
1845*b9c1b51eSKate Stone                  size, GetPermissionsAsCString(permissions));
1846af245d11STodd Fiala   }
1847af245d11STodd Fiala #endif
1848af245d11STodd Fiala }
1849af245d11STodd Fiala 
1850*b9c1b51eSKate Stone Error NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {
1851af245d11STodd Fiala   // FIXME see comments in AllocateMemory - required lower-level
1852af245d11STodd Fiala   // bits not in place yet (ThreadPlans)
1853af245d11STodd Fiala   return Error("not implemented");
1854af245d11STodd Fiala }
1855af245d11STodd Fiala 
1856*b9c1b51eSKate Stone lldb::addr_t NativeProcessLinux::GetSharedLibraryInfoAddress() {
1857af245d11STodd Fiala   // punt on this for now
1858af245d11STodd Fiala   return LLDB_INVALID_ADDRESS;
1859af245d11STodd Fiala }
1860af245d11STodd Fiala 
1861*b9c1b51eSKate Stone size_t NativeProcessLinux::UpdateThreads() {
1862af245d11STodd Fiala   // The NativeProcessLinux monitoring threads are always up to date
1863af245d11STodd Fiala   // with respect to thread state and they keep the thread list
1864af245d11STodd Fiala   // populated properly. All this method needs to do is return the
1865af245d11STodd Fiala   // thread count.
1866af245d11STodd Fiala   return m_threads.size();
1867af245d11STodd Fiala }
1868af245d11STodd Fiala 
1869*b9c1b51eSKate Stone bool NativeProcessLinux::GetArchitecture(ArchSpec &arch) const {
1870af245d11STodd Fiala   arch = m_arch;
1871af245d11STodd Fiala   return true;
1872af245d11STodd Fiala }
1873af245d11STodd Fiala 
1874*b9c1b51eSKate Stone Error NativeProcessLinux::GetSoftwareBreakpointPCOffset(
1875*b9c1b51eSKate Stone     uint32_t &actual_opcode_size) {
1876af245d11STodd Fiala   // FIXME put this behind a breakpoint protocol class that can be
1877af245d11STodd Fiala   // set per architecture.  Need ARM, MIPS support here.
1878af245d11STodd Fiala   static const uint8_t g_i386_opcode[] = {0xCC};
1879bb00d0b6SUlrich Weigand   static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
1880af245d11STodd Fiala 
1881*b9c1b51eSKate Stone   switch (m_arch.GetMachine()) {
1882af245d11STodd Fiala   case llvm::Triple::x86:
1883af245d11STodd Fiala   case llvm::Triple::x86_64:
1884af245d11STodd Fiala     actual_opcode_size = static_cast<uint32_t>(sizeof(g_i386_opcode));
1885af245d11STodd Fiala     return Error();
1886af245d11STodd Fiala 
1887bb00d0b6SUlrich Weigand   case llvm::Triple::systemz:
1888bb00d0b6SUlrich Weigand     actual_opcode_size = static_cast<uint32_t>(sizeof(g_s390x_opcode));
1889bb00d0b6SUlrich Weigand     return Error();
1890bb00d0b6SUlrich Weigand 
1891ff7fd900STamas Berghammer   case llvm::Triple::arm:
1892ff7fd900STamas Berghammer   case llvm::Triple::aarch64:
1893e8659b5dSMohit K. Bhakkad   case llvm::Triple::mips64:
1894e8659b5dSMohit K. Bhakkad   case llvm::Triple::mips64el:
1895ce815e45SSagar Thakur   case llvm::Triple::mips:
1896ce815e45SSagar Thakur   case llvm::Triple::mipsel:
1897ff7fd900STamas Berghammer     // On these architectures the PC don't get updated for breakpoint hits
1898c60c9452SJaydeep Patil     actual_opcode_size = 0;
1899e8659b5dSMohit K. Bhakkad     return Error();
1900e8659b5dSMohit K. Bhakkad 
1901af245d11STodd Fiala   default:
1902af245d11STodd Fiala     assert(false && "CPU type not supported!");
1903af245d11STodd Fiala     return Error("CPU type not supported");
1904af245d11STodd Fiala   }
1905af245d11STodd Fiala }
1906af245d11STodd Fiala 
1907*b9c1b51eSKate Stone Error NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,
1908*b9c1b51eSKate Stone                                         bool hardware) {
1909af245d11STodd Fiala   if (hardware)
1910af245d11STodd Fiala     return Error("NativeProcessLinux does not support hardware breakpoints");
1911af245d11STodd Fiala   else
1912af245d11STodd Fiala     return SetSoftwareBreakpoint(addr, size);
1913af245d11STodd Fiala }
1914af245d11STodd Fiala 
1915*b9c1b51eSKate Stone Error NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(
1916*b9c1b51eSKate Stone     size_t trap_opcode_size_hint, size_t &actual_opcode_size,
1917*b9c1b51eSKate Stone     const uint8_t *&trap_opcode_bytes) {
191863c8be95STamas Berghammer   // FIXME put this behind a breakpoint protocol class that can be set per
191963c8be95STamas Berghammer   // architecture.  Need MIPS support here.
19202afc5966STodd Fiala   static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};
1921be379e15STamas Berghammer   // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1922be379e15STamas Berghammer   // linux kernel does otherwise.
1923be379e15STamas Berghammer   static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1924af245d11STodd Fiala   static const uint8_t g_i386_opcode[] = {0xCC};
19253df471c3SMohit K. Bhakkad   static const uint8_t g_mips64_opcode[] = {0x00, 0x00, 0x00, 0x0d};
19262c2acf96SMohit K. Bhakkad   static const uint8_t g_mips64el_opcode[] = {0x0d, 0x00, 0x00, 0x00};
1927bb00d0b6SUlrich Weigand   static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
1928be379e15STamas Berghammer   static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
1929af245d11STodd Fiala 
1930*b9c1b51eSKate Stone   switch (m_arch.GetMachine()) {
19312afc5966STodd Fiala   case llvm::Triple::aarch64:
19322afc5966STodd Fiala     trap_opcode_bytes = g_aarch64_opcode;
19332afc5966STodd Fiala     actual_opcode_size = sizeof(g_aarch64_opcode);
19342afc5966STodd Fiala     return Error();
19352afc5966STodd Fiala 
193663c8be95STamas Berghammer   case llvm::Triple::arm:
1937*b9c1b51eSKate Stone     switch (trap_opcode_size_hint) {
193863c8be95STamas Berghammer     case 2:
193963c8be95STamas Berghammer       trap_opcode_bytes = g_thumb_breakpoint_opcode;
194063c8be95STamas Berghammer       actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
194163c8be95STamas Berghammer       return Error();
194263c8be95STamas Berghammer     case 4:
194363c8be95STamas Berghammer       trap_opcode_bytes = g_arm_breakpoint_opcode;
194463c8be95STamas Berghammer       actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
194563c8be95STamas Berghammer       return Error();
194663c8be95STamas Berghammer     default:
194763c8be95STamas Berghammer       assert(false && "Unrecognised trap opcode size hint!");
194863c8be95STamas Berghammer       return Error("Unrecognised trap opcode size hint!");
194963c8be95STamas Berghammer     }
195063c8be95STamas Berghammer 
1951af245d11STodd Fiala   case llvm::Triple::x86:
1952af245d11STodd Fiala   case llvm::Triple::x86_64:
1953af245d11STodd Fiala     trap_opcode_bytes = g_i386_opcode;
1954af245d11STodd Fiala     actual_opcode_size = sizeof(g_i386_opcode);
1955af245d11STodd Fiala     return Error();
1956af245d11STodd Fiala 
1957ce815e45SSagar Thakur   case llvm::Triple::mips:
19583df471c3SMohit K. Bhakkad   case llvm::Triple::mips64:
19593df471c3SMohit K. Bhakkad     trap_opcode_bytes = g_mips64_opcode;
19603df471c3SMohit K. Bhakkad     actual_opcode_size = sizeof(g_mips64_opcode);
19613df471c3SMohit K. Bhakkad     return Error();
19623df471c3SMohit K. Bhakkad 
1963ce815e45SSagar Thakur   case llvm::Triple::mipsel:
19642c2acf96SMohit K. Bhakkad   case llvm::Triple::mips64el:
19652c2acf96SMohit K. Bhakkad     trap_opcode_bytes = g_mips64el_opcode;
19662c2acf96SMohit K. Bhakkad     actual_opcode_size = sizeof(g_mips64el_opcode);
19672c2acf96SMohit K. Bhakkad     return Error();
19682c2acf96SMohit K. Bhakkad 
1969bb00d0b6SUlrich Weigand   case llvm::Triple::systemz:
1970bb00d0b6SUlrich Weigand     trap_opcode_bytes = g_s390x_opcode;
1971bb00d0b6SUlrich Weigand     actual_opcode_size = sizeof(g_s390x_opcode);
1972bb00d0b6SUlrich Weigand     return Error();
1973bb00d0b6SUlrich Weigand 
1974af245d11STodd Fiala   default:
1975af245d11STodd Fiala     assert(false && "CPU type not supported!");
1976af245d11STodd Fiala     return Error("CPU type not supported");
1977af245d11STodd Fiala   }
1978af245d11STodd Fiala }
1979af245d11STodd Fiala 
1980af245d11STodd Fiala #if 0
1981af245d11STodd Fiala ProcessMessage::CrashReason
1982af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
1983af245d11STodd Fiala {
1984af245d11STodd Fiala     ProcessMessage::CrashReason reason;
1985af245d11STodd Fiala     assert(info->si_signo == SIGSEGV);
1986af245d11STodd Fiala 
1987af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
1988af245d11STodd Fiala 
1989af245d11STodd Fiala     switch (info->si_code)
1990af245d11STodd Fiala     {
1991af245d11STodd Fiala     default:
1992af245d11STodd Fiala         assert(false && "unexpected si_code for SIGSEGV");
1993af245d11STodd Fiala         break;
1994af245d11STodd Fiala     case SI_KERNEL:
1995af245d11STodd Fiala         // Linux will occasionally send spurious SI_KERNEL codes.
1996af245d11STodd Fiala         // (this is poorly documented in sigaction)
1997af245d11STodd Fiala         // One way to get this is via unaligned SIMD loads.
1998af245d11STodd Fiala         reason = ProcessMessage::eInvalidAddress; // for lack of anything better
1999af245d11STodd Fiala         break;
2000af245d11STodd Fiala     case SEGV_MAPERR:
2001af245d11STodd Fiala         reason = ProcessMessage::eInvalidAddress;
2002af245d11STodd Fiala         break;
2003af245d11STodd Fiala     case SEGV_ACCERR:
2004af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedAddress;
2005af245d11STodd Fiala         break;
2006af245d11STodd Fiala     }
2007af245d11STodd Fiala 
2008af245d11STodd Fiala     return reason;
2009af245d11STodd Fiala }
2010af245d11STodd Fiala #endif
2011af245d11STodd Fiala 
2012af245d11STodd Fiala #if 0
2013af245d11STodd Fiala ProcessMessage::CrashReason
2014af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
2015af245d11STodd Fiala {
2016af245d11STodd Fiala     ProcessMessage::CrashReason reason;
2017af245d11STodd Fiala     assert(info->si_signo == SIGILL);
2018af245d11STodd Fiala 
2019af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
2020af245d11STodd Fiala 
2021af245d11STodd Fiala     switch (info->si_code)
2022af245d11STodd Fiala     {
2023af245d11STodd Fiala     default:
2024af245d11STodd Fiala         assert(false && "unexpected si_code for SIGILL");
2025af245d11STodd Fiala         break;
2026af245d11STodd Fiala     case ILL_ILLOPC:
2027af245d11STodd Fiala         reason = ProcessMessage::eIllegalOpcode;
2028af245d11STodd Fiala         break;
2029af245d11STodd Fiala     case ILL_ILLOPN:
2030af245d11STodd Fiala         reason = ProcessMessage::eIllegalOperand;
2031af245d11STodd Fiala         break;
2032af245d11STodd Fiala     case ILL_ILLADR:
2033af245d11STodd Fiala         reason = ProcessMessage::eIllegalAddressingMode;
2034af245d11STodd Fiala         break;
2035af245d11STodd Fiala     case ILL_ILLTRP:
2036af245d11STodd Fiala         reason = ProcessMessage::eIllegalTrap;
2037af245d11STodd Fiala         break;
2038af245d11STodd Fiala     case ILL_PRVOPC:
2039af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedOpcode;
2040af245d11STodd Fiala         break;
2041af245d11STodd Fiala     case ILL_PRVREG:
2042af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedRegister;
2043af245d11STodd Fiala         break;
2044af245d11STodd Fiala     case ILL_COPROC:
2045af245d11STodd Fiala         reason = ProcessMessage::eCoprocessorError;
2046af245d11STodd Fiala         break;
2047af245d11STodd Fiala     case ILL_BADSTK:
2048af245d11STodd Fiala         reason = ProcessMessage::eInternalStackError;
2049af245d11STodd Fiala         break;
2050af245d11STodd Fiala     }
2051af245d11STodd Fiala 
2052af245d11STodd Fiala     return reason;
2053af245d11STodd Fiala }
2054af245d11STodd Fiala #endif
2055af245d11STodd Fiala 
2056af245d11STodd Fiala #if 0
2057af245d11STodd Fiala ProcessMessage::CrashReason
2058af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
2059af245d11STodd Fiala {
2060af245d11STodd Fiala     ProcessMessage::CrashReason reason;
2061af245d11STodd Fiala     assert(info->si_signo == SIGFPE);
2062af245d11STodd Fiala 
2063af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
2064af245d11STodd Fiala 
2065af245d11STodd Fiala     switch (info->si_code)
2066af245d11STodd Fiala     {
2067af245d11STodd Fiala     default:
2068af245d11STodd Fiala         assert(false && "unexpected si_code for SIGFPE");
2069af245d11STodd Fiala         break;
2070af245d11STodd Fiala     case FPE_INTDIV:
2071af245d11STodd Fiala         reason = ProcessMessage::eIntegerDivideByZero;
2072af245d11STodd Fiala         break;
2073af245d11STodd Fiala     case FPE_INTOVF:
2074af245d11STodd Fiala         reason = ProcessMessage::eIntegerOverflow;
2075af245d11STodd Fiala         break;
2076af245d11STodd Fiala     case FPE_FLTDIV:
2077af245d11STodd Fiala         reason = ProcessMessage::eFloatDivideByZero;
2078af245d11STodd Fiala         break;
2079af245d11STodd Fiala     case FPE_FLTOVF:
2080af245d11STodd Fiala         reason = ProcessMessage::eFloatOverflow;
2081af245d11STodd Fiala         break;
2082af245d11STodd Fiala     case FPE_FLTUND:
2083af245d11STodd Fiala         reason = ProcessMessage::eFloatUnderflow;
2084af245d11STodd Fiala         break;
2085af245d11STodd Fiala     case FPE_FLTRES:
2086af245d11STodd Fiala         reason = ProcessMessage::eFloatInexactResult;
2087af245d11STodd Fiala         break;
2088af245d11STodd Fiala     case FPE_FLTINV:
2089af245d11STodd Fiala         reason = ProcessMessage::eFloatInvalidOperation;
2090af245d11STodd Fiala         break;
2091af245d11STodd Fiala     case FPE_FLTSUB:
2092af245d11STodd Fiala         reason = ProcessMessage::eFloatSubscriptRange;
2093af245d11STodd Fiala         break;
2094af245d11STodd Fiala     }
2095af245d11STodd Fiala 
2096af245d11STodd Fiala     return reason;
2097af245d11STodd Fiala }
2098af245d11STodd Fiala #endif
2099af245d11STodd Fiala 
2100af245d11STodd Fiala #if 0
2101af245d11STodd Fiala ProcessMessage::CrashReason
2102af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
2103af245d11STodd Fiala {
2104af245d11STodd Fiala     ProcessMessage::CrashReason reason;
2105af245d11STodd Fiala     assert(info->si_signo == SIGBUS);
2106af245d11STodd Fiala 
2107af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
2108af245d11STodd Fiala 
2109af245d11STodd Fiala     switch (info->si_code)
2110af245d11STodd Fiala     {
2111af245d11STodd Fiala     default:
2112af245d11STodd Fiala         assert(false && "unexpected si_code for SIGBUS");
2113af245d11STodd Fiala         break;
2114af245d11STodd Fiala     case BUS_ADRALN:
2115af245d11STodd Fiala         reason = ProcessMessage::eIllegalAlignment;
2116af245d11STodd Fiala         break;
2117af245d11STodd Fiala     case BUS_ADRERR:
2118af245d11STodd Fiala         reason = ProcessMessage::eIllegalAddress;
2119af245d11STodd Fiala         break;
2120af245d11STodd Fiala     case BUS_OBJERR:
2121af245d11STodd Fiala         reason = ProcessMessage::eHardwareError;
2122af245d11STodd Fiala         break;
2123af245d11STodd Fiala     }
2124af245d11STodd Fiala 
2125af245d11STodd Fiala     return reason;
2126af245d11STodd Fiala }
2127af245d11STodd Fiala #endif
2128af245d11STodd Fiala 
2129*b9c1b51eSKate Stone Error NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
2130*b9c1b51eSKate Stone                                      size_t &bytes_read) {
2131df7c6995SPavel Labath   if (ProcessVmReadvSupported()) {
2132*b9c1b51eSKate Stone     // The process_vm_readv path is about 50 times faster than ptrace api. We
2133*b9c1b51eSKate Stone     // want to use
2134df7c6995SPavel Labath     // this syscall if it is supported.
2135df7c6995SPavel Labath 
2136df7c6995SPavel Labath     const ::pid_t pid = GetID();
2137df7c6995SPavel Labath 
2138df7c6995SPavel Labath     struct iovec local_iov, remote_iov;
2139df7c6995SPavel Labath     local_iov.iov_base = buf;
2140df7c6995SPavel Labath     local_iov.iov_len = size;
2141df7c6995SPavel Labath     remote_iov.iov_base = reinterpret_cast<void *>(addr);
2142df7c6995SPavel Labath     remote_iov.iov_len = size;
2143df7c6995SPavel Labath 
2144df7c6995SPavel Labath     bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
2145df7c6995SPavel Labath     const bool success = bytes_read == size;
2146df7c6995SPavel Labath 
2147df7c6995SPavel Labath     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2148df7c6995SPavel Labath     if (log)
2149*b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s using process_vm_readv to read %zd "
2150*b9c1b51eSKate Stone                   "bytes from inferior address 0x%" PRIx64 ": %s",
2151*b9c1b51eSKate Stone                   __FUNCTION__, size, addr,
2152*b9c1b51eSKate Stone                   success ? "Success" : strerror(errno));
2153df7c6995SPavel Labath 
2154df7c6995SPavel Labath     if (success)
2155df7c6995SPavel Labath       return Error();
2156df7c6995SPavel Labath     // else
2157*b9c1b51eSKate Stone     //     the call failed for some reason, let's retry the read using ptrace
2158*b9c1b51eSKate Stone     //     api.
2159df7c6995SPavel Labath   }
2160df7c6995SPavel Labath 
216119cbe96aSPavel Labath   unsigned char *dst = static_cast<unsigned char *>(buf);
216219cbe96aSPavel Labath   size_t remainder;
216319cbe96aSPavel Labath   long data;
216419cbe96aSPavel Labath 
216519cbe96aSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_ALL));
216619cbe96aSPavel Labath   if (log)
216719cbe96aSPavel Labath     ProcessPOSIXLog::IncNestLevel();
2168*b9c1b51eSKate Stone   if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2169*b9c1b51eSKate Stone       log->GetMask().Test(POSIX_LOG_MEMORY))
2170*b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s(%p, %p, %zd, _)", __FUNCTION__,
2171*b9c1b51eSKate Stone                 (void *)addr, buf, size);
217219cbe96aSPavel Labath 
2173*b9c1b51eSKate Stone   for (bytes_read = 0; bytes_read < size; bytes_read += remainder) {
2174*b9c1b51eSKate Stone     Error error = NativeProcessLinux::PtraceWrapper(
2175*b9c1b51eSKate Stone         PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data);
2176*b9c1b51eSKate Stone     if (error.Fail()) {
217719cbe96aSPavel Labath       if (log)
217819cbe96aSPavel Labath         ProcessPOSIXLog::DecNestLevel();
217919cbe96aSPavel Labath       return error;
218019cbe96aSPavel Labath     }
218119cbe96aSPavel Labath 
218219cbe96aSPavel Labath     remainder = size - bytes_read;
218319cbe96aSPavel Labath     remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
218419cbe96aSPavel Labath 
218519cbe96aSPavel Labath     // Copy the data into our buffer
2186f6ef187bSMohit K. Bhakkad     memcpy(dst, &data, remainder);
218719cbe96aSPavel Labath 
218819cbe96aSPavel Labath     if (log && ProcessPOSIXLog::AtTopNestLevel() &&
218919cbe96aSPavel Labath         (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
219019cbe96aSPavel Labath          (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2191*b9c1b51eSKate Stone           size <= POSIX_LOG_MEMORY_SHORT_BYTES))) {
219219cbe96aSPavel Labath       uintptr_t print_dst = 0;
219319cbe96aSPavel Labath       // Format bytes from data by moving into print_dst for log output
219419cbe96aSPavel Labath       for (unsigned i = 0; i < remainder; ++i)
219519cbe96aSPavel Labath         print_dst |= (((data >> i * 8) & 0xFF) << i * 8);
2196*b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s() [0x%" PRIx64 "]:0x%" PRIx64
2197*b9c1b51eSKate Stone                   " (0x%" PRIx64 ")",
219879203995SPavel Labath                   __FUNCTION__, addr, uint64_t(print_dst), uint64_t(data));
219919cbe96aSPavel Labath     }
220019cbe96aSPavel Labath     addr += k_ptrace_word_size;
220119cbe96aSPavel Labath     dst += k_ptrace_word_size;
220219cbe96aSPavel Labath   }
220319cbe96aSPavel Labath 
220419cbe96aSPavel Labath   if (log)
220519cbe96aSPavel Labath     ProcessPOSIXLog::DecNestLevel();
220619cbe96aSPavel Labath   return Error();
2207af245d11STodd Fiala }
2208af245d11STodd Fiala 
2209*b9c1b51eSKate Stone Error NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf,
2210*b9c1b51eSKate Stone                                                 size_t size,
2211*b9c1b51eSKate Stone                                                 size_t &bytes_read) {
22123eb4b458SChaoren Lin   Error error = ReadMemory(addr, buf, size, bytes_read);
2213*b9c1b51eSKate Stone   if (error.Fail())
2214*b9c1b51eSKate Stone     return error;
22153eb4b458SChaoren Lin   return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
22163eb4b458SChaoren Lin }
22173eb4b458SChaoren Lin 
2218*b9c1b51eSKate Stone Error NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,
2219*b9c1b51eSKate Stone                                       size_t size, size_t &bytes_written) {
222019cbe96aSPavel Labath   const unsigned char *src = static_cast<const unsigned char *>(buf);
222119cbe96aSPavel Labath   size_t remainder;
222219cbe96aSPavel Labath   Error error;
222319cbe96aSPavel Labath 
222419cbe96aSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_ALL));
222519cbe96aSPavel Labath   if (log)
222619cbe96aSPavel Labath     ProcessPOSIXLog::IncNestLevel();
2227*b9c1b51eSKate Stone   if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2228*b9c1b51eSKate Stone       log->GetMask().Test(POSIX_LOG_MEMORY))
2229*b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s(0x%" PRIx64 ", %p, %zu)", __FUNCTION__,
2230*b9c1b51eSKate Stone                 addr, buf, size);
223119cbe96aSPavel Labath 
2232*b9c1b51eSKate Stone   for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
223319cbe96aSPavel Labath     remainder = size - bytes_written;
223419cbe96aSPavel Labath     remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
223519cbe96aSPavel Labath 
2236*b9c1b51eSKate Stone     if (remainder == k_ptrace_word_size) {
223719cbe96aSPavel Labath       unsigned long data = 0;
2238f6ef187bSMohit K. Bhakkad       memcpy(&data, src, k_ptrace_word_size);
223919cbe96aSPavel Labath 
224019cbe96aSPavel Labath       if (log && ProcessPOSIXLog::AtTopNestLevel() &&
224119cbe96aSPavel Labath           (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
224219cbe96aSPavel Labath            (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
224319cbe96aSPavel Labath             size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
224419cbe96aSPavel Labath         log->Printf("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
224519cbe96aSPavel Labath                     (void *)addr, *(const unsigned long *)src, data);
224619cbe96aSPavel Labath 
2247*b9c1b51eSKate Stone       error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(),
2248*b9c1b51eSKate Stone                                                 (void *)addr, (void *)data);
2249*b9c1b51eSKate Stone       if (error.Fail()) {
225019cbe96aSPavel Labath         if (log)
225119cbe96aSPavel Labath           ProcessPOSIXLog::DecNestLevel();
225219cbe96aSPavel Labath         return error;
225319cbe96aSPavel Labath       }
2254*b9c1b51eSKate Stone     } else {
225519cbe96aSPavel Labath       unsigned char buff[8];
225619cbe96aSPavel Labath       size_t bytes_read;
225719cbe96aSPavel Labath       error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
2258*b9c1b51eSKate Stone       if (error.Fail()) {
225919cbe96aSPavel Labath         if (log)
226019cbe96aSPavel Labath           ProcessPOSIXLog::DecNestLevel();
226119cbe96aSPavel Labath         return error;
226219cbe96aSPavel Labath       }
226319cbe96aSPavel Labath 
226419cbe96aSPavel Labath       memcpy(buff, src, remainder);
226519cbe96aSPavel Labath 
226619cbe96aSPavel Labath       size_t bytes_written_rec;
226719cbe96aSPavel Labath       error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
2268*b9c1b51eSKate Stone       if (error.Fail()) {
226919cbe96aSPavel Labath         if (log)
227019cbe96aSPavel Labath           ProcessPOSIXLog::DecNestLevel();
227119cbe96aSPavel Labath         return error;
227219cbe96aSPavel Labath       }
227319cbe96aSPavel Labath 
227419cbe96aSPavel Labath       if (log && ProcessPOSIXLog::AtTopNestLevel() &&
227519cbe96aSPavel Labath           (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
227619cbe96aSPavel Labath            (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
227719cbe96aSPavel Labath             size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
227819cbe96aSPavel Labath         log->Printf("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
2279*b9c1b51eSKate Stone                     (void *)addr, *(const unsigned long *)src,
2280*b9c1b51eSKate Stone                     *(unsigned long *)buff);
228119cbe96aSPavel Labath     }
228219cbe96aSPavel Labath 
228319cbe96aSPavel Labath     addr += k_ptrace_word_size;
228419cbe96aSPavel Labath     src += k_ptrace_word_size;
228519cbe96aSPavel Labath   }
228619cbe96aSPavel Labath   if (log)
228719cbe96aSPavel Labath     ProcessPOSIXLog::DecNestLevel();
228819cbe96aSPavel Labath   return error;
2289af245d11STodd Fiala }
2290af245d11STodd Fiala 
2291*b9c1b51eSKate Stone Error NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) {
229219cbe96aSPavel Labath   return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
2293af245d11STodd Fiala }
2294af245d11STodd Fiala 
2295*b9c1b51eSKate Stone Error NativeProcessLinux::GetEventMessage(lldb::tid_t tid,
2296*b9c1b51eSKate Stone                                           unsigned long *message) {
229719cbe96aSPavel Labath   return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
2298af245d11STodd Fiala }
2299af245d11STodd Fiala 
2300*b9c1b51eSKate Stone Error NativeProcessLinux::Detach(lldb::tid_t tid) {
230197ccc294SChaoren Lin   if (tid == LLDB_INVALID_THREAD_ID)
230297ccc294SChaoren Lin     return Error();
230397ccc294SChaoren Lin 
230419cbe96aSPavel Labath   return PtraceWrapper(PTRACE_DETACH, tid);
2305af245d11STodd Fiala }
2306af245d11STodd Fiala 
2307*b9c1b51eSKate Stone bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {
2308*b9c1b51eSKate Stone   for (auto thread_sp : m_threads) {
2309af245d11STodd Fiala     assert(thread_sp && "thread list should not contain NULL threads");
2310*b9c1b51eSKate Stone     if (thread_sp->GetID() == thread_id) {
2311af245d11STodd Fiala       // We have this thread.
2312af245d11STodd Fiala       return true;
2313af245d11STodd Fiala     }
2314af245d11STodd Fiala   }
2315af245d11STodd Fiala 
2316af245d11STodd Fiala   // We don't have this thread.
2317af245d11STodd Fiala   return false;
2318af245d11STodd Fiala }
2319af245d11STodd Fiala 
2320*b9c1b51eSKate Stone bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) {
23211dbc6c9cSPavel Labath   Log *const log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD);
23221dbc6c9cSPavel Labath 
23231dbc6c9cSPavel Labath   if (log)
2324*b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__,
2325*b9c1b51eSKate Stone                 thread_id);
23261dbc6c9cSPavel Labath 
23271dbc6c9cSPavel Labath   bool found = false;
23281dbc6c9cSPavel Labath 
2329*b9c1b51eSKate Stone   for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
2330*b9c1b51eSKate Stone     if (*it && ((*it)->GetID() == thread_id)) {
2331af245d11STodd Fiala       m_threads.erase(it);
23321dbc6c9cSPavel Labath       found = true;
23331dbc6c9cSPavel Labath       break;
2334af245d11STodd Fiala     }
2335af245d11STodd Fiala   }
2336af245d11STodd Fiala 
23379eb1ecb9SPavel Labath   SignalIfAllThreadsStopped();
23381dbc6c9cSPavel Labath 
23391dbc6c9cSPavel Labath   return found;
2340af245d11STodd Fiala }
2341af245d11STodd Fiala 
2342*b9c1b51eSKate Stone NativeThreadLinuxSP NativeProcessLinux::AddThread(lldb::tid_t thread_id) {
2343af245d11STodd Fiala   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD));
2344af245d11STodd Fiala 
2345*b9c1b51eSKate Stone   if (log) {
2346*b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s pid %" PRIu64
2347*b9c1b51eSKate Stone                 " adding thread with tid %" PRIu64,
2348*b9c1b51eSKate Stone                 __FUNCTION__, GetID(), thread_id);
2349af245d11STodd Fiala   }
2350af245d11STodd Fiala 
2351*b9c1b51eSKate Stone   assert(!HasThreadNoLock(thread_id) &&
2352*b9c1b51eSKate Stone          "attempted to add a thread by id that already exists");
2353af245d11STodd Fiala 
2354af245d11STodd Fiala   // If this is the first thread, save it as the current thread
2355af245d11STodd Fiala   if (m_threads.empty())
2356af245d11STodd Fiala     SetCurrentThreadID(thread_id);
2357af245d11STodd Fiala 
2358f9077782SPavel Labath   auto thread_sp = std::make_shared<NativeThreadLinux>(this, thread_id);
2359af245d11STodd Fiala   m_threads.push_back(thread_sp);
2360af245d11STodd Fiala   return thread_sp;
2361af245d11STodd Fiala }
2362af245d11STodd Fiala 
2363*b9c1b51eSKate Stone Error NativeProcessLinux::FixupBreakpointPCAsNeeded(NativeThreadLinux &thread) {
236475f47c3aSTodd Fiala   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2365af245d11STodd Fiala 
2366af245d11STodd Fiala   Error error;
2367af245d11STodd Fiala 
2368*b9c1b51eSKate Stone   // Find out the size of a breakpoint (might depend on where we are in the
2369*b9c1b51eSKate Stone   // code).
2370b9cc0c75SPavel Labath   NativeRegisterContextSP context_sp = thread.GetRegisterContext();
2371*b9c1b51eSKate Stone   if (!context_sp) {
2372af245d11STodd Fiala     error.SetErrorString("cannot get a NativeRegisterContext for the thread");
2373af245d11STodd Fiala     if (log)
2374*b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s failed: %s", __FUNCTION__,
2375*b9c1b51eSKate Stone                   error.AsCString());
2376af245d11STodd Fiala     return error;
2377af245d11STodd Fiala   }
2378af245d11STodd Fiala 
2379af245d11STodd Fiala   uint32_t breakpoint_size = 0;
2380b9cc0c75SPavel Labath   error = GetSoftwareBreakpointPCOffset(breakpoint_size);
2381*b9c1b51eSKate Stone   if (error.Fail()) {
2382af245d11STodd Fiala     if (log)
2383*b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s GetBreakpointSize() failed: %s",
2384*b9c1b51eSKate Stone                   __FUNCTION__, error.AsCString());
2385af245d11STodd Fiala     return error;
2386*b9c1b51eSKate Stone   } else {
2387af245d11STodd Fiala     if (log)
2388*b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s breakpoint size: %" PRIu32,
2389*b9c1b51eSKate Stone                   __FUNCTION__, breakpoint_size);
2390af245d11STodd Fiala   }
2391af245d11STodd Fiala 
2392*b9c1b51eSKate Stone   // First try probing for a breakpoint at a software breakpoint location: PC -
2393*b9c1b51eSKate Stone   // breakpoint size.
2394*b9c1b51eSKate Stone   const lldb::addr_t initial_pc_addr =
2395*b9c1b51eSKate Stone       context_sp->GetPCfromBreakpointLocation();
2396af245d11STodd Fiala   lldb::addr_t breakpoint_addr = initial_pc_addr;
2397*b9c1b51eSKate Stone   if (breakpoint_size > 0) {
2398af245d11STodd Fiala     // Do not allow breakpoint probe to wrap around.
23993eb4b458SChaoren Lin     if (breakpoint_addr >= breakpoint_size)
24003eb4b458SChaoren Lin       breakpoint_addr -= breakpoint_size;
2401af245d11STodd Fiala   }
2402af245d11STodd Fiala 
2403af245d11STodd Fiala   // Check if we stopped because of a breakpoint.
2404af245d11STodd Fiala   NativeBreakpointSP breakpoint_sp;
2405af245d11STodd Fiala   error = m_breakpoint_list.GetBreakpoint(breakpoint_addr, breakpoint_sp);
2406*b9c1b51eSKate Stone   if (!error.Success() || !breakpoint_sp) {
2407af245d11STodd Fiala     // We didn't find one at a software probe location.  Nothing to do.
2408af245d11STodd Fiala     if (log)
2409*b9c1b51eSKate Stone       log->Printf(
2410*b9c1b51eSKate Stone           "NativeProcessLinux::%s pid %" PRIu64
2411*b9c1b51eSKate Stone           " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64,
2412*b9c1b51eSKate Stone           __FUNCTION__, GetID(), breakpoint_addr);
2413af245d11STodd Fiala     return Error();
2414af245d11STodd Fiala   }
2415af245d11STodd Fiala 
2416af245d11STodd Fiala   // If the breakpoint is not a software breakpoint, nothing to do.
2417*b9c1b51eSKate Stone   if (!breakpoint_sp->IsSoftwareBreakpoint()) {
2418af245d11STodd Fiala     if (log)
2419*b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s pid %" PRIu64
2420*b9c1b51eSKate Stone                   " breakpoint found at 0x%" PRIx64
2421*b9c1b51eSKate Stone                   ", not software, nothing to adjust",
2422*b9c1b51eSKate Stone                   __FUNCTION__, GetID(), breakpoint_addr);
2423af245d11STodd Fiala     return Error();
2424af245d11STodd Fiala   }
2425af245d11STodd Fiala 
2426af245d11STodd Fiala   //
2427af245d11STodd Fiala   // We have a software breakpoint and need to adjust the PC.
2428af245d11STodd Fiala   //
2429af245d11STodd Fiala 
2430af245d11STodd Fiala   // Sanity check.
2431*b9c1b51eSKate Stone   if (breakpoint_size == 0) {
2432af245d11STodd Fiala     // Nothing to do!  How did we get here?
2433af245d11STodd Fiala     if (log)
2434*b9c1b51eSKate Stone       log->Printf(
2435*b9c1b51eSKate Stone           "NativeProcessLinux::%s pid %" PRIu64
2436*b9c1b51eSKate Stone           " breakpoint found at 0x%" PRIx64
2437*b9c1b51eSKate Stone           ", it is software, but the size is zero, nothing to do (unexpected)",
2438*b9c1b51eSKate Stone           __FUNCTION__, GetID(), breakpoint_addr);
2439af245d11STodd Fiala     return Error();
2440af245d11STodd Fiala   }
2441af245d11STodd Fiala 
2442af245d11STodd Fiala   // Change the program counter.
2443af245d11STodd Fiala   if (log)
2444*b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64
2445*b9c1b51eSKate Stone                 ": changing PC from 0x%" PRIx64 " to 0x%" PRIx64,
2446*b9c1b51eSKate Stone                 __FUNCTION__, GetID(), thread.GetID(), initial_pc_addr,
2447*b9c1b51eSKate Stone                 breakpoint_addr);
2448af245d11STodd Fiala 
2449af245d11STodd Fiala   error = context_sp->SetPC(breakpoint_addr);
2450*b9c1b51eSKate Stone   if (error.Fail()) {
2451af245d11STodd Fiala     if (log)
2452*b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64
2453*b9c1b51eSKate Stone                   ": failed to set PC: %s",
2454*b9c1b51eSKate Stone                   __FUNCTION__, GetID(), thread.GetID(), error.AsCString());
2455af245d11STodd Fiala     return error;
2456af245d11STodd Fiala   }
2457af245d11STodd Fiala 
2458af245d11STodd Fiala   return error;
2459af245d11STodd Fiala }
2460fa03ad2eSChaoren Lin 
2461*b9c1b51eSKate Stone Error NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,
2462*b9c1b51eSKate Stone                                                   FileSpec &file_spec) {
24637cb18bf5STamas Berghammer   FileSpec module_file_spec(module_path, true);
24647cb18bf5STamas Berghammer 
2465162fb8e8SPavel Labath   bool found = false;
24667cb18bf5STamas Berghammer   file_spec.Clear();
2467*b9c1b51eSKate Stone   ProcFileReader::ProcessLineByLine(
2468*b9c1b51eSKate Stone       GetID(), "maps", [&](const std::string &line) {
2469162fb8e8SPavel Labath         SmallVector<StringRef, 16> columns;
2470162fb8e8SPavel Labath         StringRef(line).split(columns, " ", -1, false);
2471162fb8e8SPavel Labath         if (columns.size() < 6)
2472162fb8e8SPavel Labath           return true; // continue searching
2473162fb8e8SPavel Labath 
2474162fb8e8SPavel Labath         FileSpec this_file_spec(columns[5].str().c_str(), false);
2475162fb8e8SPavel Labath         if (this_file_spec.GetFilename() != module_file_spec.GetFilename())
2476162fb8e8SPavel Labath           return true; // continue searching
2477162fb8e8SPavel Labath 
2478162fb8e8SPavel Labath         file_spec = this_file_spec;
2479162fb8e8SPavel Labath         found = true;
2480162fb8e8SPavel Labath         return false; // we are done
2481162fb8e8SPavel Labath       });
2482162fb8e8SPavel Labath 
2483162fb8e8SPavel Labath   if (!found)
24847cb18bf5STamas Berghammer     return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
24857cb18bf5STamas Berghammer                  module_file_spec.GetFilename().AsCString(), GetID());
2486162fb8e8SPavel Labath 
2487162fb8e8SPavel Labath   return Error();
24887cb18bf5STamas Berghammer }
2489c076559aSPavel Labath 
2490*b9c1b51eSKate Stone Error NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
2491*b9c1b51eSKate Stone                                              lldb::addr_t &load_addr) {
2492783bfc8cSTamas Berghammer   load_addr = LLDB_INVALID_ADDRESS;
2493*b9c1b51eSKate Stone   Error error = ProcFileReader::ProcessLineByLine(
2494*b9c1b51eSKate Stone       GetID(), "maps", [&](const std::string &line) -> bool {
2495783bfc8cSTamas Berghammer         StringRef maps_row(line);
2496783bfc8cSTamas Berghammer 
2497783bfc8cSTamas Berghammer         SmallVector<StringRef, 16> maps_columns;
2498783bfc8cSTamas Berghammer         maps_row.split(maps_columns, StringRef(" "), -1, false);
2499783bfc8cSTamas Berghammer 
2500*b9c1b51eSKate Stone         if (maps_columns.size() < 6) {
2501783bfc8cSTamas Berghammer           // Return true to continue reading the proc file
2502783bfc8cSTamas Berghammer           return true;
2503783bfc8cSTamas Berghammer         }
2504783bfc8cSTamas Berghammer 
2505*b9c1b51eSKate Stone         if (maps_columns[5] == file_name) {
2506783bfc8cSTamas Berghammer           StringExtractor addr_extractor(maps_columns[0].str().c_str());
2507783bfc8cSTamas Berghammer           load_addr = addr_extractor.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2508783bfc8cSTamas Berghammer 
2509783bfc8cSTamas Berghammer           // Return false to stop reading the proc file further
2510783bfc8cSTamas Berghammer           return false;
2511783bfc8cSTamas Berghammer         }
2512783bfc8cSTamas Berghammer 
2513783bfc8cSTamas Berghammer         // Return true to continue reading the proc file
2514783bfc8cSTamas Berghammer         return true;
2515783bfc8cSTamas Berghammer       });
2516783bfc8cSTamas Berghammer   return error;
2517783bfc8cSTamas Berghammer }
2518783bfc8cSTamas Berghammer 
2519*b9c1b51eSKate Stone NativeThreadLinuxSP NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {
2520*b9c1b51eSKate Stone   return std::static_pointer_cast<NativeThreadLinux>(
2521*b9c1b51eSKate Stone       NativeProcessProtocol::GetThreadByID(tid));
2522f9077782SPavel Labath }
2523f9077782SPavel Labath 
2524*b9c1b51eSKate Stone Error NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,
2525*b9c1b51eSKate Stone                                        lldb::StateType state, int signo) {
25265eb721edSPavel Labath   Log *const log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD);
25275eb721edSPavel Labath 
25281dbc6c9cSPavel Labath   if (log)
2529*b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__,
2530*b9c1b51eSKate Stone                 thread.GetID());
2531c076559aSPavel Labath 
2532c076559aSPavel Labath   // Before we do the resume below, first check if we have a pending
2533108c325dSPavel Labath   // stop notification that is currently waiting for
25340e1d729bSPavel Labath   // all threads to stop.  This is potentially a buggy situation since
2535c076559aSPavel Labath   // we're ostensibly waiting for threads to stop before we send out the
2536c076559aSPavel Labath   // pending notification, and here we are resuming one before we send
2537c076559aSPavel Labath   // out the pending stop notification.
2538*b9c1b51eSKate Stone   if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID && log) {
2539*b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s about to resume tid %" PRIu64
2540*b9c1b51eSKate Stone                 " per explicit request but we have a pending stop notification "
2541*b9c1b51eSKate Stone                 "(tid %" PRIu64 ") that is actively waiting for this thread to "
2542*b9c1b51eSKate Stone                                 "stop. Valid sequence of events?",
2543*b9c1b51eSKate Stone                 __FUNCTION__, thread.GetID(), m_pending_notification_tid);
2544c076559aSPavel Labath   }
2545c076559aSPavel Labath 
2546c076559aSPavel Labath   // Request a resume.  We expect this to be synchronous and the system
2547c076559aSPavel Labath   // to reflect it is running after this completes.
2548*b9c1b51eSKate Stone   switch (state) {
2549*b9c1b51eSKate Stone   case eStateRunning: {
2550605b51b8SPavel Labath     const auto resume_result = thread.Resume(signo);
25510e1d729bSPavel Labath     if (resume_result.Success())
25520e1d729bSPavel Labath       SetState(eStateRunning, true);
25530e1d729bSPavel Labath     return resume_result;
2554c076559aSPavel Labath   }
2555*b9c1b51eSKate Stone   case eStateStepping: {
2556605b51b8SPavel Labath     const auto step_result = thread.SingleStep(signo);
25570e1d729bSPavel Labath     if (step_result.Success())
25580e1d729bSPavel Labath       SetState(eStateRunning, true);
25590e1d729bSPavel Labath     return step_result;
25600e1d729bSPavel Labath   }
25610e1d729bSPavel Labath   default:
25620e1d729bSPavel Labath     if (log)
2563*b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s Unhandled state %s.", __FUNCTION__,
2564*b9c1b51eSKate Stone                   StateAsCString(state));
25650e1d729bSPavel Labath     llvm_unreachable("Unhandled state for resume");
25660e1d729bSPavel Labath   }
2567c076559aSPavel Labath }
2568c076559aSPavel Labath 
2569c076559aSPavel Labath //===----------------------------------------------------------------------===//
2570c076559aSPavel Labath 
2571*b9c1b51eSKate Stone void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {
25725eb721edSPavel Labath   Log *const log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD);
2573c076559aSPavel Labath 
2574*b9c1b51eSKate Stone   if (log) {
2575*b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s about to process event: "
2576*b9c1b51eSKate Stone                 "(triggering_tid: %" PRIu64 ")",
2577c076559aSPavel Labath                 __FUNCTION__, triggering_tid);
2578c076559aSPavel Labath   }
2579c076559aSPavel Labath 
25800e1d729bSPavel Labath   m_pending_notification_tid = triggering_tid;
25810e1d729bSPavel Labath 
25820e1d729bSPavel Labath   // Request a stop for all the thread stops that need to be stopped
25830e1d729bSPavel Labath   // and are not already known to be stopped.
2584*b9c1b51eSKate Stone   for (const auto &thread_sp : m_threads) {
25850e1d729bSPavel Labath     if (StateIsRunningState(thread_sp->GetState()))
25860e1d729bSPavel Labath       static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
25870e1d729bSPavel Labath   }
25880e1d729bSPavel Labath 
25890e1d729bSPavel Labath   SignalIfAllThreadsStopped();
2590c076559aSPavel Labath 
2591*b9c1b51eSKate Stone   if (log) {
25925eb721edSPavel Labath     log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
2593c076559aSPavel Labath   }
2594c076559aSPavel Labath }
2595c076559aSPavel Labath 
2596*b9c1b51eSKate Stone void NativeProcessLinux::SignalIfAllThreadsStopped() {
25970e1d729bSPavel Labath   if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
25980e1d729bSPavel Labath     return; // No pending notification. Nothing to do.
25990e1d729bSPavel Labath 
2600*b9c1b51eSKate Stone   for (const auto &thread_sp : m_threads) {
26010e1d729bSPavel Labath     if (StateIsRunningState(thread_sp->GetState()))
26020e1d729bSPavel Labath       return; // Some threads are still running. Don't signal yet.
26030e1d729bSPavel Labath   }
26040e1d729bSPavel Labath 
26050e1d729bSPavel Labath   // We have a pending notification and all threads have stopped.
2606*b9c1b51eSKate Stone   Log *log(
2607*b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
26089eb1ecb9SPavel Labath 
2609*b9c1b51eSKate Stone   // Clear any temporary breakpoints we used to implement software single
2610*b9c1b51eSKate Stone   // stepping.
2611*b9c1b51eSKate Stone   for (const auto &thread_info : m_threads_stepping_with_breakpoint) {
26129eb1ecb9SPavel Labath     Error error = RemoveBreakpoint(thread_info.second);
26139eb1ecb9SPavel Labath     if (error.Fail())
26149eb1ecb9SPavel Labath       if (log)
2615*b9c1b51eSKate Stone         log->Printf("NativeProcessLinux::%s() pid = %" PRIu64
2616*b9c1b51eSKate Stone                     " remove stepping breakpoint: %s",
26179eb1ecb9SPavel Labath                     __FUNCTION__, thread_info.first, error.AsCString());
26189eb1ecb9SPavel Labath   }
26199eb1ecb9SPavel Labath   m_threads_stepping_with_breakpoint.clear();
26209eb1ecb9SPavel Labath 
26219eb1ecb9SPavel Labath   // Notify the delegate about the stop
26220e1d729bSPavel Labath   SetCurrentThreadID(m_pending_notification_tid);
2623ed89c7feSPavel Labath   SetState(StateType::eStateStopped, true);
26240e1d729bSPavel Labath   m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
2625c076559aSPavel Labath }
2626c076559aSPavel Labath 
2627*b9c1b51eSKate Stone void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {
26281dbc6c9cSPavel Labath   Log *const log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD);
26291dbc6c9cSPavel Labath 
26301dbc6c9cSPavel Labath   if (log)
2631*b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__,
2632*b9c1b51eSKate Stone                 thread.GetID());
26331dbc6c9cSPavel Labath 
2634*b9c1b51eSKate Stone   if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID &&
2635*b9c1b51eSKate Stone       StateIsRunningState(thread.GetState())) {
2636*b9c1b51eSKate Stone     // We will need to wait for this new thread to stop as well before firing
2637*b9c1b51eSKate Stone     // the
2638c076559aSPavel Labath     // notification.
2639f9077782SPavel Labath     thread.RequestStop();
2640c076559aSPavel Labath   }
2641c076559aSPavel Labath }
2642068f8a7eSTamas Berghammer 
2643*b9c1b51eSKate Stone void NativeProcessLinux::SigchldHandler() {
264419cbe96aSPavel Labath   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
264519cbe96aSPavel Labath   // Process all pending waitpid notifications.
2646*b9c1b51eSKate Stone   while (true) {
264719cbe96aSPavel Labath     int status = -1;
264819cbe96aSPavel Labath     ::pid_t wait_pid = waitpid(-1, &status, __WALL | __WNOTHREAD | WNOHANG);
264919cbe96aSPavel Labath 
265019cbe96aSPavel Labath     if (wait_pid == 0)
265119cbe96aSPavel Labath       break; // We are done.
265219cbe96aSPavel Labath 
2653*b9c1b51eSKate Stone     if (wait_pid == -1) {
265419cbe96aSPavel Labath       if (errno == EINTR)
265519cbe96aSPavel Labath         continue;
265619cbe96aSPavel Labath 
265719cbe96aSPavel Labath       Error error(errno, eErrorTypePOSIX);
265819cbe96aSPavel Labath       if (log)
2659*b9c1b51eSKate Stone         log->Printf("NativeProcessLinux::%s waitpid (-1, &status, __WALL | "
2660*b9c1b51eSKate Stone                     "__WNOTHREAD | WNOHANG) failed: %s",
266119cbe96aSPavel Labath                     __FUNCTION__, error.AsCString());
266219cbe96aSPavel Labath       break;
266319cbe96aSPavel Labath     }
266419cbe96aSPavel Labath 
266519cbe96aSPavel Labath     bool exited = false;
266619cbe96aSPavel Labath     int signal = 0;
266719cbe96aSPavel Labath     int exit_status = 0;
266819cbe96aSPavel Labath     const char *status_cstr = nullptr;
2669*b9c1b51eSKate Stone     if (WIFSTOPPED(status)) {
267019cbe96aSPavel Labath       signal = WSTOPSIG(status);
267119cbe96aSPavel Labath       status_cstr = "STOPPED";
2672*b9c1b51eSKate Stone     } else if (WIFEXITED(status)) {
267319cbe96aSPavel Labath       exit_status = WEXITSTATUS(status);
267419cbe96aSPavel Labath       status_cstr = "EXITED";
267519cbe96aSPavel Labath       exited = true;
2676*b9c1b51eSKate Stone     } else if (WIFSIGNALED(status)) {
267719cbe96aSPavel Labath       signal = WTERMSIG(status);
267819cbe96aSPavel Labath       status_cstr = "SIGNALED";
267919cbe96aSPavel Labath       if (wait_pid == static_cast<::pid_t>(GetID())) {
268019cbe96aSPavel Labath         exited = true;
268119cbe96aSPavel Labath         exit_status = -1;
268219cbe96aSPavel Labath       }
2683*b9c1b51eSKate Stone     } else
268419cbe96aSPavel Labath       status_cstr = "(\?\?\?)";
268519cbe96aSPavel Labath 
268619cbe96aSPavel Labath     if (log)
2687*b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s: waitpid (-1, &status, __WALL | "
2688*b9c1b51eSKate Stone                   "__WNOTHREAD | WNOHANG)"
2689*b9c1b51eSKate Stone                   "=> pid = %" PRIi32
2690*b9c1b51eSKate Stone                   ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
2691*b9c1b51eSKate Stone                   __FUNCTION__, wait_pid, status, status_cstr, signal,
2692*b9c1b51eSKate Stone                   exit_status);
269319cbe96aSPavel Labath 
269419cbe96aSPavel Labath     MonitorCallback(wait_pid, exited, signal, exit_status);
269519cbe96aSPavel Labath   }
2696068f8a7eSTamas Berghammer }
2697068f8a7eSTamas Berghammer 
2698068f8a7eSTamas Berghammer // Wrapper for ptrace to catch errors and log calls.
2699*b9c1b51eSKate Stone // Note that ptrace sets errno on error because -1 can be a valid result (i.e.
2700*b9c1b51eSKate Stone // for PTRACE_PEEK*)
2701*b9c1b51eSKate Stone Error NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
2702*b9c1b51eSKate Stone                                         void *data, size_t data_size,
2703*b9c1b51eSKate Stone                                         long *result) {
27044a9babb2SPavel Labath   Error error;
27054a9babb2SPavel Labath   long int ret;
2706068f8a7eSTamas Berghammer 
2707068f8a7eSTamas Berghammer   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2708068f8a7eSTamas Berghammer 
2709068f8a7eSTamas Berghammer   PtraceDisplayBytes(req, data, data_size);
2710068f8a7eSTamas Berghammer 
2711068f8a7eSTamas Berghammer   errno = 0;
2712068f8a7eSTamas Berghammer   if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
2713*b9c1b51eSKate Stone     ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2714*b9c1b51eSKate Stone                  *(unsigned int *)addr, data);
2715068f8a7eSTamas Berghammer   else
2716*b9c1b51eSKate Stone     ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2717*b9c1b51eSKate Stone                  addr, data);
2718068f8a7eSTamas Berghammer 
27194a9babb2SPavel Labath   if (ret == -1)
2720068f8a7eSTamas Berghammer     error.SetErrorToErrno();
2721068f8a7eSTamas Berghammer 
27224a9babb2SPavel Labath   if (result)
27234a9babb2SPavel Labath     *result = ret;
27244a9babb2SPavel Labath 
2725068f8a7eSTamas Berghammer   if (log)
2726*b9c1b51eSKate Stone     log->Printf("ptrace(%d, %" PRIu64 ", %p, %p, %zu)=%lX", req, pid, addr,
2727*b9c1b51eSKate Stone                 data, data_size, ret);
2728068f8a7eSTamas Berghammer 
2729068f8a7eSTamas Berghammer   PtraceDisplayBytes(req, data, data_size);
2730068f8a7eSTamas Berghammer 
2731*b9c1b51eSKate Stone   if (log && error.GetError() != 0) {
2732068f8a7eSTamas Berghammer     const char *str;
2733*b9c1b51eSKate Stone     switch (error.GetError()) {
2734*b9c1b51eSKate Stone     case ESRCH:
2735*b9c1b51eSKate Stone       str = "ESRCH";
2736*b9c1b51eSKate Stone       break;
2737*b9c1b51eSKate Stone     case EINVAL:
2738*b9c1b51eSKate Stone       str = "EINVAL";
2739*b9c1b51eSKate Stone       break;
2740*b9c1b51eSKate Stone     case EBUSY:
2741*b9c1b51eSKate Stone       str = "EBUSY";
2742*b9c1b51eSKate Stone       break;
2743*b9c1b51eSKate Stone     case EPERM:
2744*b9c1b51eSKate Stone       str = "EPERM";
2745*b9c1b51eSKate Stone       break;
2746*b9c1b51eSKate Stone     default:
2747*b9c1b51eSKate Stone       str = error.AsCString();
2748068f8a7eSTamas Berghammer     }
2749068f8a7eSTamas Berghammer     log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
2750068f8a7eSTamas Berghammer   }
2751068f8a7eSTamas Berghammer 
27524a9babb2SPavel Labath   return error;
2753068f8a7eSTamas Berghammer }
2754