1af245d11STodd Fiala //===-- NativeProcessLinux.cpp -------------------------------- -*- C++ -*-===//
2af245d11STodd Fiala //
3af245d11STodd Fiala //                     The LLVM Compiler Infrastructure
4af245d11STodd Fiala //
5af245d11STodd Fiala // This file is distributed under the University of Illinois Open Source
6af245d11STodd Fiala // License. See LICENSE.TXT for details.
7af245d11STodd Fiala //
8af245d11STodd Fiala //===----------------------------------------------------------------------===//
9af245d11STodd Fiala 
10af245d11STodd Fiala #include "NativeProcessLinux.h"
11af245d11STodd Fiala 
12af245d11STodd Fiala // C Includes
13af245d11STodd Fiala #include <errno.h>
14af245d11STodd Fiala #include <stdint.h>
15b9c1b51eSKate Stone #include <string.h>
16af245d11STodd Fiala #include <unistd.h>
17af245d11STodd Fiala 
18af245d11STodd Fiala // C++ Includes
19af245d11STodd Fiala #include <fstream>
20df7c6995SPavel Labath #include <mutex>
21c076559aSPavel Labath #include <sstream>
22af245d11STodd Fiala #include <string>
235b981ab9SPavel Labath #include <unordered_map>
24af245d11STodd Fiala 
25af245d11STodd Fiala // Other libraries and framework includes
26d8c338d4STamas Berghammer #include "lldb/Core/EmulateInstruction.h"
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"
46b9c1b51eSKate Stone #include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
47af245d11STodd Fiala #include "ProcFileReader.h"
481e209fccSTamas Berghammer #include "Procfs.h"
49cacde7dfSTodd Fiala 
50b9c1b51eSKate Stone // System includes - They have to be included after framework includes because
51b9c1b51eSKate 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 
77b9c1b51eSKate 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 
92b9c1b51eSKate Stone     // We shall try if cross-process-memory reads work by attempting to read a
93b9c1b51eSKate 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);
96b9c1b51eSKate Stone     if (log) {
97df7c6995SPavel Labath       if (is_supported)
98b9c1b51eSKate Stone         log->Printf("%s: Detected kernel support for process_vm_readv syscall. "
99b9c1b51eSKate Stone                     "Fast memory reads enabled.",
100df7c6995SPavel Labath                     __FUNCTION__);
101df7c6995SPavel Labath       else
102b9c1b51eSKate Stone         log->Printf("%s: syscall process_vm_readv failed (error: %s). Fast "
103b9c1b51eSKate Stone                     "memory reads disabled.",
104df7c6995SPavel Labath                     __FUNCTION__, strerror(errno));
105df7c6995SPavel Labath     }
106df7c6995SPavel Labath   });
107df7c6995SPavel Labath 
108df7c6995SPavel Labath   return is_supported;
109df7c6995SPavel Labath }
110df7c6995SPavel Labath 
111b9c1b51eSKate Stone namespace {
112b9c1b51eSKate 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))
118b9c1b51eSKate Stone     log->Printf("%s: setting STDIN to '%s'", __FUNCTION__,
119b9c1b51eSKate 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))
124b9c1b51eSKate Stone     log->Printf("%s setting STDOUT to '%s'", __FUNCTION__,
125b9c1b51eSKate 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))
130b9c1b51eSKate Stone     log->Printf("%s setting STDERR to '%s'", __FUNCTION__,
131b9c1b51eSKate Stone                 action->GetFileSpec().GetCString());
1324abe5d69SPavel Labath   else
1334abe5d69SPavel Labath     log->Printf("%s leaving STDERR as is", __FUNCTION__);
1344abe5d69SPavel Labath 
1354abe5d69SPavel Labath   int i = 0;
136b9c1b51eSKate Stone   for (const char **args = info.GetArguments().GetConstArgumentVector(); *args;
137b9c1b51eSKate Stone        ++args, ++i)
138b9c1b51eSKate Stone     log->Printf("%s arg %d: \"%s\"", __FUNCTION__, i,
139b9c1b51eSKate Stone                 *args ? *args : "nullptr");
1404abe5d69SPavel Labath }
1414abe5d69SPavel Labath 
142b9c1b51eSKate 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);
145b9c1b51eSKate 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 
151b9c1b51eSKate 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 
156b9c1b51eSKate Stone   if (verbose_log) {
157b9c1b51eSKate Stone     switch (req) {
158b9c1b51eSKate 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     }
163b9c1b51eSKate 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     }
168b9c1b51eSKate 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     }
173b9c1b51eSKate 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     }
178b9c1b51eSKate 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     }
183b9c1b51eSKate 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     }
188b9c1b51eSKate 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     }
194b9c1b51eSKate Stone     default: {}
195af245d11STodd Fiala     }
196af245d11STodd Fiala   }
197af245d11STodd Fiala }
198af245d11STodd Fiala 
19919cbe96aSPavel Labath static constexpr unsigned k_ptrace_word_size = sizeof(void *);
200b9c1b51eSKate Stone static_assert(sizeof(long) >= k_ptrace_word_size,
201b9c1b51eSKate 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.
206b9c1b51eSKate Stone static Error EnsureFDFlags(int fd, int flags) {
207bd7cbc5aSPavel Labath   Error error;
208bd7cbc5aSPavel Labath 
209bd7cbc5aSPavel Labath   int status = fcntl(fd, F_GETFL);
210b9c1b51eSKate Stone   if (status == -1) {
211bd7cbc5aSPavel Labath     error.SetErrorToErrno();
212bd7cbc5aSPavel Labath     return error;
213bd7cbc5aSPavel Labath   }
214bd7cbc5aSPavel Labath 
215b9c1b51eSKate 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 
227b9c1b51eSKate Stone Error NativeProcessProtocol::Launch(
228db264a6dSTamas Berghammer     ProcessLaunchInfo &launch_info,
229b9c1b51eSKate Stone     NativeProcessProtocol::NativeDelegate &native_delegate, MainLoop &mainloop,
230b9c1b51eSKate 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() ||
239b9c1b51eSKate 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 
248b9c1b51eSKate 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 
254b9c1b51eSKate Stone   error = std::static_pointer_cast<NativeProcessLinux>(native_process_sp)
255b9c1b51eSKate Stone               ->LaunchInferior(mainloop, launch_info);
256af245d11STodd Fiala 
257b9c1b51eSKate Stone   if (error.Fail()) {
258af245d11STodd Fiala     native_process_sp.reset();
259af245d11STodd Fiala     if (log)
260b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s failed to launch process: %s",
261b9c1b51eSKate 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 
270b9c1b51eSKate Stone Error NativeProcessProtocol::Attach(
271b9c1b51eSKate Stone     lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
272b9c1b51eSKate 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 
283b9c1b51eSKate Stone   std::shared_ptr<NativeProcessLinux> native_process_linux_sp(
284b9c1b51eSKate Stone       new NativeProcessLinux());
285af245d11STodd Fiala 
286b9c1b51eSKate 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 
303b9c1b51eSKate Stone NativeProcessLinux::NativeProcessLinux()
304b9c1b51eSKate Stone     : NativeProcessProtocol(LLDB_INVALID_PROCESS_ID), m_arch(),
305b9c1b51eSKate Stone       m_supports_mem_region(eLazyBoolCalculate), m_mem_region_cache(),
306b9c1b51eSKate Stone       m_pending_notification_tid(LLDB_INVALID_THREAD_ID) {}
307af245d11STodd Fiala 
308b9c1b51eSKate Stone void NativeProcessLinux::AttachToInferior(MainLoop &mainloop, lldb::pid_t pid,
309b9c1b51eSKate Stone                                           Error &error) {
310af245d11STodd Fiala   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
311af245d11STodd Fiala   if (log)
312b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__,
313b9c1b51eSKate Stone                 pid);
314af245d11STodd Fiala 
315b9c1b51eSKate Stone   m_sigchld_handle = mainloop.RegisterSignal(
316b9c1b51eSKate 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)
326b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s (pid = %" PRIi64
327b9c1b51eSKate Stone                 ") detected architecture %s",
328b9c1b51eSKate 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 
336b9c1b51eSKate Stone Error NativeProcessLinux::LaunchInferior(MainLoop &mainloop,
337b9c1b51eSKate Stone                                          ProcessLaunchInfo &launch_info) {
3384abe5d69SPavel Labath   Error error;
339b9c1b51eSKate Stone   m_sigchld_handle = mainloop.RegisterSignal(
340b9c1b51eSKate 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 
348b9c1b51eSKate Stone   ::pid_t pid =
349b9c1b51eSKate 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;
358b9c1b51eSKate 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.
365b9c1b51eSKate Stone     // FIXME this could really use a new state - eStateLaunchFailure.  For now,
366b9c1b51eSKate 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)
375b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s inferior started, now in stopped state",
376b9c1b51eSKate Stone                 __FUNCTION__);
377af245d11STodd Fiala 
378bd7cbc5aSPavel Labath   error = SetDefaultPtraceOpts(pid);
379b9c1b51eSKate Stone   if (error.Fail()) {
380af245d11STodd Fiala     if (log)
381b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s inferior failed to set default "
382b9c1b51eSKate Stone                   "ptrace options: %s",
383bd7cbc5aSPavel Labath                   __FUNCTION__, error.AsCString());
384af245d11STodd Fiala 
385af245d11STodd Fiala     // Mark the inferior as invalid.
386b9c1b51eSKate Stone     // FIXME this could really use a new state - eStateLaunchFailure.  For now,
387b9c1b51eSKate 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 
399b9c1b51eSKate Stone   if (m_terminal_fd != -1) {
400bd7cbc5aSPavel Labath     error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
401b9c1b51eSKate Stone     if (error.Fail()) {
402af245d11STodd Fiala       if (log)
403b9c1b51eSKate Stone         log->Printf("NativeProcessLinux::%s inferior EnsureFDFlags failed for "
404b9c1b51eSKate Stone                     "ensuring terminal O_NONBLOCK setting: %s",
405bd7cbc5aSPavel Labath                     __FUNCTION__, error.AsCString());
406af245d11STodd Fiala 
407af245d11STodd Fiala       // Mark the inferior as invalid.
408b9c1b51eSKate Stone       // FIXME this could really use a new state - eStateLaunchFailure.  For
409b9c1b51eSKate 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)
417b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__,
418b9c1b51eSKate 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 
430b9c1b51eSKate Stone   if (log) {
431bd7cbc5aSPavel Labath     if (error.Success())
432b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s inferior launching succeeded",
433b9c1b51eSKate Stone                   __FUNCTION__);
434af245d11STodd Fiala     else
435b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s inferior launching failed: %s",
436b9c1b51eSKate Stone                   __FUNCTION__, error.AsCString());
437af245d11STodd Fiala   }
4384abe5d69SPavel Labath   return error;
439af245d11STodd Fiala }
440af245d11STodd Fiala 
441b9c1b51eSKate Stone ::pid_t NativeProcessLinux::Attach(lldb::pid_t pid, Error &error) {
442af245d11STodd Fiala   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
443af245d11STodd Fiala 
444b9c1b51eSKate Stone   // Use a map to keep track of the threads which we have attached/need to
445b9c1b51eSKate Stone   // attach.
446af245d11STodd Fiala   Host::TidMap tids_to_attach;
447b9c1b51eSKate 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 
453b9c1b51eSKate Stone   while (Host::FindProcessThreads(pid, tids_to_attach)) {
454af245d11STodd Fiala     for (Host::TidMap::iterator it = tids_to_attach.begin();
455b9c1b51eSKate Stone          it != tids_to_attach.end();) {
456b9c1b51eSKate 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);
462b9c1b51eSKate Stone         if (error.Fail()) {
463af245d11STodd Fiala           // No such thread. The thread may have exited.
464af245d11STodd Fiala           // More error handling may be needed.
465b9c1b51eSKate Stone           if (error.GetError() == ESRCH) {
466af245d11STodd Fiala             it = tids_to_attach.erase(it);
467af245d11STodd Fiala             continue;
468b9c1b51eSKate 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.
475b9c1b51eSKate 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.
478b9c1b51eSKate Stone           if (errno == ESRCH) {
479af245d11STodd Fiala             it = tids_to_attach.erase(it);
480af245d11STodd Fiala             continue;
481b9c1b51eSKate 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)
492b9c1b51eSKate Stone           log->Printf("NativeProcessLinux::%s() adding tid = %" PRIu64,
493b9c1b51eSKate 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 
501b9c1b51eSKate Stone         // This will notify this is a new thread and tell the system it is
502b9c1b51eSKate 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 
513b9c1b51eSKate 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);
517b9c1b51eSKate 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 
526b9c1b51eSKate 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 
545b9c1b51eSKate 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;
552b9c1b51eSKate Stone   else {
553af245d11STodd Fiala     // We don't know what this is.
554af245d11STodd Fiala     return ExitType::eExitTypeInvalid;
555af245d11STodd Fiala   }
556af245d11STodd Fiala }
557af245d11STodd Fiala 
558b9c1b51eSKate 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);
565b9c1b51eSKate 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.
572b9c1b51eSKate Stone void NativeProcessLinux::MonitorCallback(lldb::pid_t pid, bool exited,
573b9c1b51eSKate Stone                                          int signal, int status) {
574af245d11STodd Fiala   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
575af245d11STodd Fiala 
576b9c1b51eSKate Stone   // Certain activities differ based on whether the pid is the tid of the main
577b9c1b51eSKate Stone   // thread.
5781107b5a5SPavel Labath   const bool is_main_thread = (pid == GetID());
579af245d11STodd Fiala 
580af245d11STodd Fiala   // Handle when the thread exits.
581b9c1b51eSKate Stone   if (exited) {
582af245d11STodd Fiala     if (log)
583b9c1b51eSKate Stone       log->Printf(
584b9c1b51eSKate Stone           "NativeProcessLinux::%s() got exit signal(%d) , tid = %" PRIu64
585b9c1b51eSKate Stone           " (%s main thread)",
586b9c1b51eSKate 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 
591b9c1b51eSKate Stone     if (is_main_thread) {
592b9c1b51eSKate Stone       // We only set the exit status and notify the delegate if we haven't
593b9c1b51eSKate Stone       // already set the process
594b9c1b51eSKate Stone       // state to an exited state.  We normally should have received a SIGTRAP |
595b9c1b51eSKate Stone       // (PTRACE_EVENT_EXIT << 8)
596af245d11STodd Fiala       // for the main thread.
597b9c1b51eSKate Stone       const bool already_notified = (GetState() == StateType::eStateExited) ||
598b9c1b51eSKate Stone                                     (GetState() == StateType::eStateCrashed);
599b9c1b51eSKate Stone       if (!already_notified) {
600af245d11STodd Fiala         if (log)
601b9c1b51eSKate Stone           log->Printf("NativeProcessLinux::%s() tid = %" PRIu64
602b9c1b51eSKate Stone                       " handling main thread exit (%s), expected exit state "
603b9c1b51eSKate Stone                       "already set but state was %s instead, setting exit "
604b9c1b51eSKate Stone                       "state now",
605b9c1b51eSKate Stone                       __FUNCTION__, pid,
606b9c1b51eSKate Stone                       thread_found ? "stopped tracking thread metadata"
607b9c1b51eSKate Stone                                    : "thread metadata not found",
608b9c1b51eSKate Stone                       StateAsCString(GetState()));
609af245d11STodd Fiala         // The main thread exited.  We're done monitoring.  Report to delegate.
610b9c1b51eSKate Stone         SetExitStatus(convert_pid_status_to_exit_type(status),
611b9c1b51eSKate 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);
615b9c1b51eSKate Stone       } else {
616af245d11STodd Fiala         if (log)
617b9c1b51eSKate Stone           log->Printf("NativeProcessLinux::%s() tid = %" PRIu64
618b9c1b51eSKate Stone                       " main thread now exited (%s)",
619b9c1b51eSKate Stone                       __FUNCTION__, pid,
620b9c1b51eSKate Stone                       thread_found ? "stopped tracking thread metadata"
621b9c1b51eSKate Stone                                    : "thread metadata not found");
622af245d11STodd Fiala       }
623b9c1b51eSKate Stone     } else {
624b9c1b51eSKate Stone       // Do we want to report to the delegate in this case?  I think not.  If
625b9c1b51eSKate Stone       // this was an orderly
626b9c1b51eSKate Stone       // thread exit, we would already have received the SIGTRAP |
627b9c1b51eSKate Stone       // (PTRACE_EVENT_EXIT << 8) signal,
628af245d11STodd Fiala       // and we would have done an all-stop then.
629af245d11STodd Fiala       if (log)
630b9c1b51eSKate Stone         log->Printf("NativeProcessLinux::%s() tid = %" PRIu64
631b9c1b51eSKate Stone                     " handling non-main thread exit (%s)",
632b9c1b51eSKate Stone                     __FUNCTION__, pid,
633b9c1b51eSKate Stone                     thread_found ? "stopped tracking thread metadata"
634b9c1b51eSKate 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 
643b9c1b51eSKate Stone   if (!thread_sp) {
644b9c1b51eSKate Stone     // Normally, the only situation when we cannot find the thread is if we have
645b9c1b51eSKate Stone     // just
646b9c1b51eSKate Stone     // received a new thread notification. This is indicated by GetSignalInfo()
647b9c1b51eSKate Stone     // returning
648b9cc0c75SPavel Labath     // si_code == SI_USER and si_pid == 0
649b9cc0c75SPavel Labath     if (log)
650b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s received notification about an "
651b9c1b51eSKate Stone                   "unknown tid %" PRIu64 ".",
652b9c1b51eSKate Stone                   __FUNCTION__, pid);
653b9cc0c75SPavel Labath 
654b9c1b51eSKate Stone     if (info_err.Fail()) {
655b9cc0c75SPavel Labath       if (log)
656b9c1b51eSKate Stone         log->Printf("NativeProcessLinux::%s (tid %" PRIu64
657b9c1b51eSKate Stone                     ") GetSignalInfo failed (%s). Ingoring this notification.",
658b9c1b51eSKate 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))
663b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s (tid %" PRIu64
664b9c1b51eSKate Stone                   ") unexpected signal info (si_code: %d, si_pid: %d). "
665b9c1b51eSKate Stone                   "Treating as a new thread notification anyway.",
666b9c1b51eSKate 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.
676b9c1b51eSKate 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);
682b9c1b51eSKate Stone   } else {
683b9c1b51eSKate Stone     if (info_err.GetError() == EINVAL) {
684fa03ad2eSChaoren Lin       // This is a group stop reception for this tid.
685b9c1b51eSKate Stone       // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU
686b9c1b51eSKate Stone       // into the
687b9c1b51eSKate Stone       // tracee, triggering the group-stop mechanism. Normally receiving these
688b9c1b51eSKate Stone       // would stop
689b9c1b51eSKate Stone       // the process, pending a SIGCONT. Simulating this state in a debugger is
690b9c1b51eSKate Stone       // hard and is
691b9c1b51eSKate Stone       // generally not needed (one use case is debugging background task being
692b9c1b51eSKate Stone       // managed by a
693b9c1b51eSKate Stone       // shell). For general use, it is sufficient to stop the process in a
694b9c1b51eSKate Stone       // signal-delivery
695b9c1b51eSKate Stone       // stop which happens before the group stop. This done by MonitorSignal
696b9c1b51eSKate Stone       // and works
69739036ac3SPavel Labath       // correctly for all signals.
698fa03ad2eSChaoren Lin       if (log)
699b9c1b51eSKate Stone         log->Printf(
700b9c1b51eSKate Stone             "NativeProcessLinux::%s received a group stop for pid %" PRIu64
701b9c1b51eSKate Stone             " tid %" PRIu64 ". Transparent handling of group stops not "
702b9c1b51eSKate Stone                             "supported, resuming the thread.",
703b9c1b51eSKate Stone             __FUNCTION__, GetID(), pid);
704b9c1b51eSKate Stone       ResumeThread(*thread_sp, thread_sp->GetState(),
705b9c1b51eSKate Stone                    LLDB_INVALID_SIGNAL_NUMBER);
706b9c1b51eSKate Stone     } else {
707af245d11STodd Fiala       // ptrace(GETSIGINFO) failed (but not due to group-stop).
708af245d11STodd Fiala 
709b9c1b51eSKate Stone       // A return value of ESRCH means the thread/process is no longer on the
710b9c1b51eSKate Stone       // system,
711b9c1b51eSKate Stone       // so it was killed somehow outside of our control.  Either way, we can't
712b9c1b51eSKate Stone       // do anything
713af245d11STodd Fiala       // with it anymore.
714af245d11STodd Fiala 
715b9c1b51eSKate Stone       // Stop tracking the metadata for the thread since it's entirely off the
716b9c1b51eSKate Stone       // system now.
7171107b5a5SPavel Labath       const bool thread_found = StopTrackingThread(pid);
718af245d11STodd Fiala 
719af245d11STodd Fiala       if (log)
720b9c1b51eSKate Stone         log->Printf(
721b9c1b51eSKate Stone             "NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64
722b9c1b51eSKate Stone             ", signal = %d, status = %d (%s, %s, %s)",
723b9c1b51eSKate Stone             __FUNCTION__, info_err.AsCString(), pid, signal, status,
724b9c1b51eSKate Stone             info_err.GetError() == ESRCH ? "thread/process killed"
725b9c1b51eSKate Stone                                          : "unknown reason",
726b9c1b51eSKate Stone             is_main_thread ? "is main thread" : "is not main thread",
727b9c1b51eSKate Stone             thread_found ? "thread metadata removed"
728b9c1b51eSKate Stone                          : "thread metadata not found");
729af245d11STodd Fiala 
730b9c1b51eSKate Stone       if (is_main_thread) {
731b9c1b51eSKate Stone         // Notify the delegate - our process is not available but appears to
732b9c1b51eSKate Stone         // have been killed outside
733af245d11STodd Fiala         // our control.  Is eStateExited the right exit state in this case?
734b9c1b51eSKate Stone         SetExitStatus(convert_pid_status_to_exit_type(status),
735b9c1b51eSKate Stone                       convert_pid_status_to_return_code(status), nullptr, true);
7361107b5a5SPavel Labath         SetState(StateType::eStateExited, true);
737b9c1b51eSKate Stone       } else {
738b9c1b51eSKate Stone         // This thread was pulled out from underneath us.  Anything to do here?
739b9c1b51eSKate Stone         // Do we want to do an all stop?
740af245d11STodd Fiala         if (log)
741b9c1b51eSKate Stone           log->Printf("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64
742b9c1b51eSKate Stone                       " non-main thread exit occurred, didn't tell delegate "
743b9c1b51eSKate Stone                       "anything since thread disappeared out from underneath "
744b9c1b51eSKate Stone                       "us",
745b9c1b51eSKate Stone                       __FUNCTION__, GetID(), pid);
746af245d11STodd Fiala       }
747af245d11STodd Fiala     }
748af245d11STodd Fiala   }
749af245d11STodd Fiala }
750af245d11STodd Fiala 
751b9c1b51eSKate 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 
756b9c1b51eSKate Stone   if (new_thread_sp) {
757b9c1b51eSKate Stone     // We are already tracking the thread - we got the event on the new thread
758b9c1b51eSKate 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;
766b9c1b51eSKate Stone   do {
767426bdf88SPavel Labath     if (log)
768b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s() received thread creation event for "
769b9c1b51eSKate Stone                   "tid %" PRIu32
770b9c1b51eSKate Stone                   ". tid not tracked yet, waiting for thread to appear...",
771b9c1b51eSKate Stone                   __FUNCTION__, tid);
772426bdf88SPavel Labath     wait_pid = waitpid(tid, &status, __WALL);
773b9c1b51eSKate Stone   } while (wait_pid == -1 && errno == EINTR);
774b9c1b51eSKate Stone   // Since we are waiting on a specific tid, this must be the creation event.
775b9c1b51eSKate Stone   // But let's do
776426bdf88SPavel Labath   // some checks just in case.
777426bdf88SPavel Labath   if (wait_pid != tid) {
778426bdf88SPavel Labath     if (log)
779b9c1b51eSKate Stone       log->Printf(
780b9c1b51eSKate Stone           "NativeProcessLinux::%s() waiting for tid %" PRIu32
781b9c1b51eSKate Stone           " failed. Assuming the thread has disappeared in the meantime",
782b9c1b51eSKate Stone           __FUNCTION__, tid);
783426bdf88SPavel Labath     // The only way I know of this could happen is if the whole process was
784b9c1b51eSKate Stone     // SIGKILLed in the mean time. In any case, we can't do anything about that
785b9c1b51eSKate Stone     // now.
786426bdf88SPavel Labath     return;
787426bdf88SPavel Labath   }
788b9c1b51eSKate Stone   if (WIFEXITED(status)) {
789426bdf88SPavel Labath     if (log)
790b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s() waiting for tid %" PRIu32
791b9c1b51eSKate Stone                   " returned an 'exited' event. Not tracking the thread.",
792b9c1b51eSKate 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);
799b9c1b51eSKate Stone   if (error.Fail()) {
800426bdf88SPavel Labath     if (log)
801b9c1b51eSKate Stone       log->Printf(
802b9c1b51eSKate Stone           "NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32
803b9c1b51eSKate Stone           " failed. Assuming the thread has disappeared in the meantime.",
804b9c1b51eSKate Stone           __FUNCTION__, tid);
805426bdf88SPavel Labath     return;
806426bdf88SPavel Labath   }
807426bdf88SPavel Labath 
808b9c1b51eSKate Stone   if (((info.si_pid != 0) || (info.si_code != SI_USER)) && log) {
809b9c1b51eSKate Stone     // We should be getting a thread creation signal here, but we received
810b9c1b51eSKate Stone     // something
811b9c1b51eSKate Stone     // else. There isn't much we can do about it now, so we will just log that.
812b9c1b51eSKate Stone     // Since the
813b9c1b51eSKate Stone     // thread is alive and we are receiving events from it, we shall pretend
814b9c1b51eSKate Stone     // that it was
815426bdf88SPavel Labath     // created properly.
816b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32
817b9c1b51eSKate Stone                 " received unexpected signal with code %d from pid %d.",
818b9c1b51eSKate Stone                 __FUNCTION__, tid, info.si_code, info.si_pid);
819426bdf88SPavel Labath   }
820426bdf88SPavel Labath 
821426bdf88SPavel Labath   if (log)
822b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s() pid = %" PRIu64
823b9c1b51eSKate 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 
831b9c1b51eSKate Stone void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info,
832b9c1b51eSKate 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 
838b9c1b51eSKate Stone   switch (info.si_code) {
839b9c1b51eSKate Stone   // TODO: these two cases are required if we want to support tracing of the
840b9c1b51eSKate 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 
844b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): {
845b9c1b51eSKate Stone     // This is the notification on the parent thread which informs us of new
846b9c1b51eSKate Stone     // thread
847426bdf88SPavel Labath     // creation.
848b9c1b51eSKate Stone     // We don't want to do anything with the parent thread so we just resume it.
849b9c1b51eSKate Stone     // In case we
850b9c1b51eSKate Stone     // want to implement "break on thread creation" functionality, we would need
851b9c1b51eSKate Stone     // to stop
852426bdf88SPavel Labath     // here.
853af245d11STodd Fiala 
854af245d11STodd Fiala     unsigned long event_message = 0;
855b9c1b51eSKate Stone     if (GetEventMessage(thread.GetID(), &event_message).Fail()) {
856426bdf88SPavel Labath       if (log)
857b9c1b51eSKate Stone         log->Printf("NativeProcessLinux::%s() pid %" PRIu64
858b9c1b51eSKate Stone                     " received thread creation event but GetEventMessage "
859b9c1b51eSKate Stone                     "failed so we don't know the new tid",
860b9c1b51eSKate 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 
868b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): {
869f9077782SPavel Labath     NativeThreadLinuxSP main_thread_sp;
870af245d11STodd Fiala     if (log)
871b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s() received exec event, code = %d",
872b9c1b51eSKate 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 
877b9c1b51eSKate Stone     // Remove all but the main thread here.  Linux fork creates a new process
878b9c1b51eSKate Stone     // which only copies the main thread.
879a9882ceeSTodd Fiala     if (log)
880b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s exec received, stop tracking all but "
881b9c1b51eSKate Stone                   "main thread",
882b9c1b51eSKate Stone                   __FUNCTION__);
883a9882ceeSTodd Fiala 
884b9c1b51eSKate Stone     for (auto thread_sp : m_threads) {
885a9882ceeSTodd Fiala       const bool is_main_thread = thread_sp && thread_sp->GetID() == GetID();
886b9c1b51eSKate Stone       if (is_main_thread) {
887f9077782SPavel Labath         main_thread_sp = std::static_pointer_cast<NativeThreadLinux>(thread_sp);
888a9882ceeSTodd Fiala         if (log)
889b9c1b51eSKate Stone           log->Printf(
890b9c1b51eSKate Stone               "NativeProcessLinux::%s found main thread with tid %" PRIu64
891b9c1b51eSKate Stone               ", keeping",
892b9c1b51eSKate Stone               __FUNCTION__, main_thread_sp->GetID());
893b9c1b51eSKate Stone       } else {
894a9882ceeSTodd Fiala         if (log)
895b9c1b51eSKate Stone           log->Printf(
896b9c1b51eSKate Stone               "NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64
897b9c1b51eSKate Stone               " due to exec",
898b9c1b51eSKate Stone               __FUNCTION__, thread_sp->GetID());
899a9882ceeSTodd Fiala       }
900a9882ceeSTodd Fiala     }
901a9882ceeSTodd Fiala 
902a9882ceeSTodd Fiala     m_threads.clear();
903a9882ceeSTodd Fiala 
904b9c1b51eSKate 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();
908b9c1b51eSKate Stone     } else {
909a9882ceeSTodd Fiala       SetCurrentThreadID(LLDB_INVALID_THREAD_ID);
910a9882ceeSTodd Fiala       if (log)
911b9c1b51eSKate Stone         log->Printf("NativeProcessLinux::%s pid %" PRIu64
912b9c1b51eSKate Stone                     "no main thread found, discarded all threads, we're in a "
913b9c1b51eSKate Stone                     "no-thread state!",
914b9c1b51eSKate 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.
924b9c1b51eSKate Stone     assert(main_thread_sp && "exec called during ptraced process but no main "
925b9c1b51eSKate 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 
933b9c1b51eSKate Stone   case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): {
934af245d11STodd Fiala     // The inferior process or one of its threads is about to exit.
935b9c1b51eSKate Stone     // We don't want to do anything with the thread so we just resume it. In
936b9c1b51eSKate Stone     // case we
937b9c1b51eSKate Stone     // want to implement "break on thread exit" functionality, we would need to
938b9c1b51eSKate 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 
945b9c1b51eSKate Stone     if (log) {
946b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = "
947b9c1b51eSKate Stone                   "%lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
948b9c1b51eSKate Stone                   __FUNCTION__, data, WIFEXITED(data) ? "true" : "false",
949b9c1b51eSKate Stone                   WIFSIGNALED(data) ? "true" : "false", thread.GetID(),
950af245d11STodd Fiala                   is_main_thread ? "is main thread" : "not main thread");
951af245d11STodd Fiala     }
952af245d11STodd Fiala 
953b9c1b51eSKate Stone     if (is_main_thread) {
954b9c1b51eSKate Stone       SetExitStatus(convert_pid_status_to_exit_type(data),
955b9c1b51eSKate Stone                     convert_pid_status_to_return_code(data), nullptr, true);
95675f47c3aSTodd Fiala     }
95775f47c3aSTodd Fiala 
95886852d36SPavel Labath     StateType state = thread.GetState();
959b9c1b51eSKate Stone     if (!StateIsRunningState(state)) {
960b9c1b51eSKate Stone       // Due to a kernel bug, we may sometimes get this stop after the inferior
961b9c1b51eSKate Stone       // gets a
962b9c1b51eSKate Stone       // SIGKILL. This confuses our state tracking logic in ResumeThread(),
963b9c1b51eSKate Stone       // since normally,
964b9c1b51eSKate Stone       // we should not be receiving any ptrace events while the inferior is
965b9c1b51eSKate 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;
980b9c1b51eSKate Stone     Error error = thread.GetRegisterContext()->GetWatchpointHitIndex(
981b9c1b51eSKate 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());
987b9c1b51eSKate 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;
1004b9c1b51eSKate Stone       Error error = thread.GetRegisterContext()->GetWatchpointHitIndex(
1005b9c1b51eSKate 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());
1011b9c1b51eSKate 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)
1025b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s() received unknown SIGTRAP system "
1026b9c1b51eSKate Stone                   "call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming",
1027b9c1b51eSKate 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)
1036b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s() pid %" PRIu64 "tid %" PRIu64
1037b9c1b51eSKate 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 
1043b9c1b51eSKate Stone void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) {
1044c16f5dcaSChaoren Lin   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1045c16f5dcaSChaoren Lin   if (log)
1046b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64
1047b9c1b51eSKate 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 
1056b9c1b51eSKate Stone void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) {
1057b9c1b51eSKate Stone   Log *log(
1058b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
1059c16f5dcaSChaoren Lin   if (log)
1060b9c1b51eSKate Stone     log->Printf(
1061b9c1b51eSKate 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 
1072b9c1b51eSKate Stone   if (m_threads_stepping_with_breakpoint.find(thread.GetID()) !=
1073b9c1b51eSKate Stone       m_threads_stepping_with_breakpoint.end())
1074b9cc0c75SPavel Labath     thread.SetStoppedByTrace();
1075c16f5dcaSChaoren Lin 
1076b9cc0c75SPavel Labath   StopRunningThreads(thread.GetID());
1077c16f5dcaSChaoren Lin }
1078c16f5dcaSChaoren Lin 
1079b9c1b51eSKate Stone void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread,
1080b9c1b51eSKate Stone                                            uint32_t wp_index) {
1081b9c1b51eSKate Stone   Log *log(
1082b9c1b51eSKate 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 
1092b9c1b51eSKate Stone   // We need to tell all other running threads before we notify the delegate
1093b9c1b51eSKate Stone   // about this stop.
1094f9077782SPavel Labath   StopRunningThreads(thread.GetID());
1095c16f5dcaSChaoren Lin }
1096c16f5dcaSChaoren Lin 
1097b9c1b51eSKate Stone void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
1098b9c1b51eSKate 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.
1114b9c1b51eSKate Stone   if (info.si_code == SI_TKILL || info.si_code == SI_USER) {
1115af245d11STodd Fiala     if (log)
1116b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s() received signal %s (%d) with code "
1117b9c1b51eSKate Stone                   "%s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
1118b9c1b51eSKate Stone                   __FUNCTION__, Host::GetSignalAsCString(signo), signo,
1119b9cc0c75SPavel Labath                   (info.si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
1120b9c1b51eSKate 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.
1125b9c1b51eSKate Stone   if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) {
1126af245d11STodd Fiala     // This is a tgkill()-based stop.
1127fa03ad2eSChaoren Lin     if (log)
1128b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64
1129b9c1b51eSKate Stone                   ", thread stopped",
1130b9c1b51eSKate Stone                   __FUNCTION__, GetID(), thread.GetID());
1131fa03ad2eSChaoren Lin 
1132aab58633SChaoren Lin     // Check that we're not already marked with a stop reason.
1133b9c1b51eSKate Stone     // Note this thread really shouldn't already be marked as stopped - if we
1134b9c1b51eSKate Stone     // were, that would imply that
1135b9c1b51eSKate Stone     // the kernel signaled us with the thread stopping which we handled and
1136b9c1b51eSKate Stone     // marked as stopped,
1137b9c1b51eSKate Stone     // and that, without an intervening resume, we received another stop.  It is
1138b9c1b51eSKate Stone     // more likely
1139b9c1b51eSKate Stone     // that we are missing the marking of a run state somewhere if we find that
1140b9c1b51eSKate Stone     // the thread was
1141aab58633SChaoren Lin     // marked as stopped.
1142b9cc0c75SPavel Labath     const StateType thread_state = thread.GetState();
1143b9c1b51eSKate Stone     if (!StateIsStoppedState(thread_state, false)) {
1144ed89c7feSPavel Labath       // An inferior thread has stopped because of a SIGSTOP we have sent it.
1145b9c1b51eSKate Stone       // Generally, these are not important stops and we don't want to report
1146b9c1b51eSKate Stone       // them as
1147b9c1b51eSKate Stone       // they are just used to stop other threads when one thread (the one with
1148b9c1b51eSKate Stone       // the
1149b9c1b51eSKate Stone       // *real* stop reason) hits a breakpoint (watchpoint, etc...). However, in
1150b9c1b51eSKate Stone       // the
1151b9c1b51eSKate Stone       // case of an asynchronous Interrupt(), this *is* the real stop reason, so
1152b9c1b51eSKate Stone       // we
1153ed89c7feSPavel Labath       // leave the signal intact if this is the thread that was chosen as the
1154ed89c7feSPavel Labath       // triggering thread.
1155b9c1b51eSKate 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();
1163b9c1b51eSKate 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);
1167b9c1b51eSKate Stone         if (error.Fail() && log) {
1168b9c1b51eSKate Stone           log->Printf(
1169b9c1b51eSKate Stone               "NativeProcessLinux::%s failed to resume thread tid  %" PRIu64
1170b9c1b51eSKate Stone               ": %s",
1171b9cc0c75SPavel Labath               __FUNCTION__, thread.GetID(), error.AsCString());
11720e1d729bSPavel Labath         }
11730e1d729bSPavel Labath       }
1174b9c1b51eSKate Stone     } else {
1175b9c1b51eSKate 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);
1179b9c1b51eSKate Stone         const char *signal_name = stopped_by_signal
1180b9c1b51eSKate Stone                                       ? Host::GetSignalAsCString(stop_signo)
1181b9c1b51eSKate Stone                                       : "<not stopped by signal>";
1182aab58633SChaoren Lin         if (!signal_name)
1183aab58633SChaoren Lin           signal_name = "<no-signal-name>";
1184aab58633SChaoren Lin 
1185b9c1b51eSKate Stone         log->Printf("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64
1186b9c1b51eSKate Stone                     ", thread was already marked as a stopped state (state=%s, "
1187b9c1b51eSKate Stone                     "signal=%d (%s)), leaving stop signal as is",
1188b9c1b51eSKate Stone                     __FUNCTION__, GetID(), thread.GetID(),
1189b9c1b51eSKate 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)
1199b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s() received signal %s", __FUNCTION__,
1200b9c1b51eSKate 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 
1211b9c1b51eSKate 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 
1218b9c1b51eSKate Stone   EmulatorBaton(NativeProcessLinux *process, NativeRegisterContext *reg_context)
1219b9c1b51eSKate Stone       : m_process(process), m_reg_context(reg_context) {}
1220e7708688STamas Berghammer };
1221e7708688STamas Berghammer 
1222e7708688STamas Berghammer } // anonymous namespace
1223e7708688STamas Berghammer 
1224b9c1b51eSKate Stone static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
1225e7708688STamas Berghammer                                  const EmulateInstruction::Context &context,
1226b9c1b51eSKate 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 
1234b9c1b51eSKate Stone static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
1235e7708688STamas Berghammer                                  const RegisterInfo *reg_info,
1236b9c1b51eSKate Stone                                  RegisterValue &reg_value) {
1237e7708688STamas Berghammer   EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
1238e7708688STamas Berghammer 
1239b9c1b51eSKate Stone   auto it = emulator_baton->m_register_values.find(
1240b9c1b51eSKate Stone       reg_info->kinds[eRegisterKindDWARF]);
1241b9c1b51eSKate 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.
1249b9c1b51eSKate Stone   const RegisterInfo *full_reg_info =
1250b9c1b51eSKate Stone       emulator_baton->m_reg_context->GetRegisterInfo(
1251e7708688STamas Berghammer           eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
1252e7708688STamas Berghammer 
1253b9c1b51eSKate Stone   Error error =
1254b9c1b51eSKate 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 
1261b9c1b51eSKate Stone static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
1262e7708688STamas Berghammer                                   const EmulateInstruction::Context &context,
1263e7708688STamas Berghammer                                   const RegisterInfo *reg_info,
1264b9c1b51eSKate Stone                                   const RegisterValue &reg_value) {
1265e7708688STamas Berghammer   EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
1266b9c1b51eSKate Stone   emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
1267b9c1b51eSKate Stone       reg_value;
1268e7708688STamas Berghammer   return true;
1269e7708688STamas Berghammer }
1270e7708688STamas Berghammer 
1271b9c1b51eSKate Stone static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
1272e7708688STamas Berghammer                                   const EmulateInstruction::Context &context,
1273b9c1b51eSKate Stone                                   lldb::addr_t addr, const void *dst,
1274b9c1b51eSKate Stone                                   size_t length) {
1275e7708688STamas Berghammer   return length;
1276e7708688STamas Berghammer }
1277e7708688STamas Berghammer 
1278b9c1b51eSKate 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);
1281b9c1b51eSKate Stone   return regsiter_context->ReadRegisterAsUnsigned(flags_info,
1282b9c1b51eSKate Stone                                                   LLDB_INVALID_ADDRESS);
1283e7708688STamas Berghammer }
1284e7708688STamas Berghammer 
1285b9c1b51eSKate Stone Error NativeProcessLinux::SetupSoftwareSingleStepping(
1286b9c1b51eSKate 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(
1291b9c1b51eSKate Stone       EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying,
1292b9c1b51eSKate 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 
1307b9c1b51eSKate Stone   bool emulation_result =
1308b9c1b51eSKate Stone       emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
13096648fcc3SPavel Labath 
1310b9c1b51eSKate Stone   const RegisterInfo *reg_info_pc = register_context_sp->GetRegisterInfo(
1311b9c1b51eSKate Stone       eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1312b9c1b51eSKate Stone   const RegisterInfo *reg_info_flags = register_context_sp->GetRegisterInfo(
1313b9c1b51eSKate Stone       eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
13146648fcc3SPavel Labath 
1315b9c1b51eSKate Stone   auto pc_it =
1316b9c1b51eSKate Stone       baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1317b9c1b51eSKate Stone   auto flags_it =
1318b9c1b51eSKate 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;
1322b9c1b51eSKate Stone   if (emulation_result) {
1323b9c1b51eSKate Stone     assert(pc_it != baton.m_register_values.end() &&
1324b9c1b51eSKate 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());
1331b9c1b51eSKate 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.
1336b9c1b51eSKate Stone     next_pc =
1337b9c1b51eSKate Stone         register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
1338e7708688STamas Berghammer     next_flags = ReadFlags(register_context_sp.get());
1339b9c1b51eSKate 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 
1346b9c1b51eSKate Stone   if (m_arch.GetMachine() == llvm::Triple::arm) {
1347b9c1b51eSKate Stone     if (next_flags & 0x20) {
1348e7708688STamas Berghammer       // Thumb mode
1349e7708688STamas Berghammer       error = SetSoftwareBreakpoint(next_pc, 2);
1350b9c1b51eSKate Stone     } else {
1351e7708688STamas Berghammer       // Arm mode
1352e7708688STamas Berghammer       error = SetSoftwareBreakpoint(next_pc, 4);
1353e7708688STamas Berghammer     }
1354b9c1b51eSKate Stone   } else if (m_arch.GetMachine() == llvm::Triple::mips64 ||
1355b9c1b51eSKate Stone              m_arch.GetMachine() == llvm::Triple::mips64el ||
1356b9c1b51eSKate Stone              m_arch.GetMachine() == llvm::Triple::mips ||
1357b9c1b51eSKate Stone              m_arch.GetMachine() == llvm::Triple::mipsel)
1358cdc22a88SMohit K. Bhakkad     error = SetSoftwareBreakpoint(next_pc, 4);
1359b9c1b51eSKate Stone   else {
1360e7708688STamas Berghammer     // No size hint is given for the next breakpoint
1361e7708688STamas Berghammer     error = SetSoftwareBreakpoint(next_pc, 0);
1362e7708688STamas Berghammer   }
1363e7708688STamas Berghammer 
136442eb6908SPavel Labath   // If setting the breakpoint fails because next_pc is out of
136542eb6908SPavel Labath   // the address space, ignore it and let the debugee segfault.
136642eb6908SPavel Labath   if (error.GetError() == EIO || error.GetError() == EFAULT) {
136742eb6908SPavel Labath     return Error();
136842eb6908SPavel Labath   } else if (error.Fail())
1369e7708688STamas Berghammer     return error;
1370e7708688STamas Berghammer 
1371b9cc0c75SPavel Labath   m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
1372e7708688STamas Berghammer 
1373e7708688STamas Berghammer   return Error();
1374e7708688STamas Berghammer }
1375e7708688STamas Berghammer 
1376b9c1b51eSKate Stone bool NativeProcessLinux::SupportHardwareSingleStepping() const {
1377b9c1b51eSKate Stone   if (m_arch.GetMachine() == llvm::Triple::arm ||
1378b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mips64 ||
1379b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mips64el ||
1380b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mips ||
1381b9c1b51eSKate Stone       m_arch.GetMachine() == llvm::Triple::mipsel)
1382cdc22a88SMohit K. Bhakkad     return false;
1383cdc22a88SMohit K. Bhakkad   return true;
1384e7708688STamas Berghammer }
1385e7708688STamas Berghammer 
1386b9c1b51eSKate Stone Error NativeProcessLinux::Resume(const ResumeActionList &resume_actions) {
1387af245d11STodd Fiala   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1388af245d11STodd Fiala   if (log)
1389b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__,
1390b9c1b51eSKate Stone                 GetID());
1391af245d11STodd Fiala 
1392e7708688STamas Berghammer   bool software_single_step = !SupportHardwareSingleStepping();
1393af245d11STodd Fiala 
1394b9c1b51eSKate Stone   if (software_single_step) {
1395b9c1b51eSKate Stone     for (auto thread_sp : m_threads) {
1396e7708688STamas Berghammer       assert(thread_sp && "thread list should not contain NULL threads");
1397e7708688STamas Berghammer 
1398b9c1b51eSKate Stone       const ResumeAction *const action =
1399b9c1b51eSKate Stone           resume_actions.GetActionForThread(thread_sp->GetID(), true);
1400e7708688STamas Berghammer       if (action == nullptr)
1401e7708688STamas Berghammer         continue;
1402e7708688STamas Berghammer 
1403b9c1b51eSKate Stone       if (action->state == eStateStepping) {
1404b9c1b51eSKate Stone         Error error = SetupSoftwareSingleStepping(
1405b9c1b51eSKate Stone             static_cast<NativeThreadLinux &>(*thread_sp));
1406e7708688STamas Berghammer         if (error.Fail())
1407e7708688STamas Berghammer           return error;
1408e7708688STamas Berghammer       }
1409e7708688STamas Berghammer     }
1410e7708688STamas Berghammer   }
1411e7708688STamas Berghammer 
1412b9c1b51eSKate Stone   for (auto thread_sp : m_threads) {
1413af245d11STodd Fiala     assert(thread_sp && "thread list should not contain NULL threads");
1414af245d11STodd Fiala 
1415b9c1b51eSKate Stone     const ResumeAction *const action =
1416b9c1b51eSKate Stone         resume_actions.GetActionForThread(thread_sp->GetID(), true);
14176a196ce6SChaoren Lin 
1418b9c1b51eSKate Stone     if (action == nullptr) {
14196a196ce6SChaoren Lin       if (log)
1420b9c1b51eSKate Stone         log->Printf(
1421b9c1b51eSKate Stone             "NativeProcessLinux::%s no action specified for pid %" PRIu64
1422b9c1b51eSKate Stone             " tid %" PRIu64,
14236a196ce6SChaoren Lin             __FUNCTION__, GetID(), thread_sp->GetID());
14246a196ce6SChaoren Lin       continue;
14256a196ce6SChaoren Lin     }
1426af245d11STodd Fiala 
1427b9c1b51eSKate Stone     if (log) {
1428b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s processing resume action state %s "
1429b9c1b51eSKate Stone                   "for pid %" PRIu64 " tid %" PRIu64,
1430b9c1b51eSKate Stone                   __FUNCTION__, StateAsCString(action->state), GetID(),
1431b9c1b51eSKate Stone                   thread_sp->GetID());
1432af245d11STodd Fiala     }
1433af245d11STodd Fiala 
1434b9c1b51eSKate Stone     switch (action->state) {
1435af245d11STodd Fiala     case eStateRunning:
1436b9c1b51eSKate Stone     case eStateStepping: {
1437af245d11STodd Fiala       // Run the thread, possibly feeding it the signal.
1438fa03ad2eSChaoren Lin       const int signo = action->signal;
1439b9c1b51eSKate Stone       ResumeThread(static_cast<NativeThreadLinux &>(*thread_sp), action->state,
1440b9c1b51eSKate Stone                    signo);
1441af245d11STodd Fiala       break;
1442ae29d395SChaoren Lin     }
1443af245d11STodd Fiala 
1444af245d11STodd Fiala     case eStateSuspended:
1445af245d11STodd Fiala     case eStateStopped:
1446108c325dSPavel Labath       lldbassert(0 && "Unexpected state");
1447af245d11STodd Fiala 
1448af245d11STodd Fiala     default:
1449b9c1b51eSKate Stone       return Error("NativeProcessLinux::%s (): unexpected state %s specified "
1450b9c1b51eSKate Stone                    "for pid %" PRIu64 ", tid %" PRIu64,
1451b9c1b51eSKate Stone                    __FUNCTION__, StateAsCString(action->state), GetID(),
1452b9c1b51eSKate Stone                    thread_sp->GetID());
1453af245d11STodd Fiala     }
1454af245d11STodd Fiala   }
1455af245d11STodd Fiala 
14565830aa75STamas Berghammer   return Error();
1457af245d11STodd Fiala }
1458af245d11STodd Fiala 
1459b9c1b51eSKate Stone Error NativeProcessLinux::Halt() {
1460af245d11STodd Fiala   Error error;
1461af245d11STodd Fiala 
1462af245d11STodd Fiala   if (kill(GetID(), SIGSTOP) != 0)
1463af245d11STodd Fiala     error.SetErrorToErrno();
1464af245d11STodd Fiala 
1465af245d11STodd Fiala   return error;
1466af245d11STodd Fiala }
1467af245d11STodd Fiala 
1468b9c1b51eSKate Stone Error NativeProcessLinux::Detach() {
1469af245d11STodd Fiala   Error error;
1470af245d11STodd Fiala 
1471af245d11STodd Fiala   // Stop monitoring the inferior.
147219cbe96aSPavel Labath   m_sigchld_handle.reset();
1473af245d11STodd Fiala 
14747a9495bcSPavel Labath   // Tell ptrace to detach from the process.
14757a9495bcSPavel Labath   if (GetID() == LLDB_INVALID_PROCESS_ID)
14767a9495bcSPavel Labath     return error;
14777a9495bcSPavel Labath 
1478b9c1b51eSKate Stone   for (auto thread_sp : m_threads) {
14797a9495bcSPavel Labath     Error e = Detach(thread_sp->GetID());
14807a9495bcSPavel Labath     if (e.Fail())
1481b9c1b51eSKate Stone       error =
1482b9c1b51eSKate Stone           e; // Save the error, but still attempt to detach from other threads.
14837a9495bcSPavel Labath   }
14847a9495bcSPavel Labath 
1485af245d11STodd Fiala   return error;
1486af245d11STodd Fiala }
1487af245d11STodd Fiala 
1488b9c1b51eSKate Stone Error NativeProcessLinux::Signal(int signo) {
1489af245d11STodd Fiala   Error error;
1490af245d11STodd Fiala 
1491af245d11STodd Fiala   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1492af245d11STodd Fiala   if (log)
1493b9c1b51eSKate Stone     log->Printf(
1494b9c1b51eSKate Stone         "NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
149598d0a4b3SChaoren Lin         __FUNCTION__, signo, Host::GetSignalAsCString(signo), GetID());
1496af245d11STodd Fiala 
1497af245d11STodd Fiala   if (kill(GetID(), signo))
1498af245d11STodd Fiala     error.SetErrorToErrno();
1499af245d11STodd Fiala 
1500af245d11STodd Fiala   return error;
1501af245d11STodd Fiala }
1502af245d11STodd Fiala 
1503b9c1b51eSKate Stone Error NativeProcessLinux::Interrupt() {
1504e9547b80SChaoren Lin   // Pick a running thread (or if none, a not-dead stopped thread) as
1505e9547b80SChaoren Lin   // the chosen thread that will be the stop-reason thread.
1506e9547b80SChaoren Lin   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1507e9547b80SChaoren Lin 
1508e9547b80SChaoren Lin   NativeThreadProtocolSP running_thread_sp;
1509e9547b80SChaoren Lin   NativeThreadProtocolSP stopped_thread_sp;
1510e9547b80SChaoren Lin 
1511e9547b80SChaoren Lin   if (log)
1512b9c1b51eSKate Stone     log->Printf(
1513b9c1b51eSKate Stone         "NativeProcessLinux::%s selecting running thread for interrupt target",
1514b9c1b51eSKate Stone         __FUNCTION__);
1515e9547b80SChaoren Lin 
1516b9c1b51eSKate Stone   for (auto thread_sp : m_threads) {
1517e9547b80SChaoren Lin     // The thread shouldn't be null but lets just cover that here.
1518e9547b80SChaoren Lin     if (!thread_sp)
1519e9547b80SChaoren Lin       continue;
1520e9547b80SChaoren Lin 
1521e9547b80SChaoren Lin     // If we have a running or stepping thread, we'll call that the
1522e9547b80SChaoren Lin     // target of the interrupt.
1523e9547b80SChaoren Lin     const auto thread_state = thread_sp->GetState();
1524b9c1b51eSKate Stone     if (thread_state == eStateRunning || thread_state == eStateStepping) {
1525e9547b80SChaoren Lin       running_thread_sp = thread_sp;
1526e9547b80SChaoren Lin       break;
1527b9c1b51eSKate Stone     } else if (!stopped_thread_sp && StateIsStoppedState(thread_state, true)) {
1528b9c1b51eSKate Stone       // Remember the first non-dead stopped thread.  We'll use that as a backup
1529b9c1b51eSKate Stone       // if there are no running threads.
1530e9547b80SChaoren Lin       stopped_thread_sp = thread_sp;
1531e9547b80SChaoren Lin     }
1532e9547b80SChaoren Lin   }
1533e9547b80SChaoren Lin 
1534b9c1b51eSKate Stone   if (!running_thread_sp && !stopped_thread_sp) {
1535b9c1b51eSKate Stone     Error error("found no running/stepping or live stopped threads as target "
1536b9c1b51eSKate Stone                 "for interrupt");
1537e9547b80SChaoren Lin     if (log)
1538b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s skipping due to error: %s",
1539b9c1b51eSKate Stone                   __FUNCTION__, error.AsCString());
15405830aa75STamas Berghammer 
1541e9547b80SChaoren Lin     return error;
1542e9547b80SChaoren Lin   }
1543e9547b80SChaoren Lin 
1544b9c1b51eSKate Stone   NativeThreadProtocolSP deferred_signal_thread_sp =
1545b9c1b51eSKate Stone       running_thread_sp ? running_thread_sp : stopped_thread_sp;
1546e9547b80SChaoren Lin 
1547e9547b80SChaoren Lin   if (log)
1548b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64
1549b9c1b51eSKate Stone                 " chosen for interrupt target",
1550b9c1b51eSKate Stone                 __FUNCTION__, GetID(),
1551e9547b80SChaoren Lin                 running_thread_sp ? "running" : "stopped",
1552e9547b80SChaoren Lin                 deferred_signal_thread_sp->GetID());
1553e9547b80SChaoren Lin 
1554ed89c7feSPavel Labath   StopRunningThreads(deferred_signal_thread_sp->GetID());
155545f5cb31SPavel Labath 
15565830aa75STamas Berghammer   return Error();
1557e9547b80SChaoren Lin }
1558e9547b80SChaoren Lin 
1559b9c1b51eSKate Stone Error NativeProcessLinux::Kill() {
1560af245d11STodd Fiala   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1561af245d11STodd Fiala   if (log)
1562b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__,
1563b9c1b51eSKate Stone                 GetID());
1564af245d11STodd Fiala 
1565af245d11STodd Fiala   Error error;
1566af245d11STodd Fiala 
1567b9c1b51eSKate Stone   switch (m_state) {
1568af245d11STodd Fiala   case StateType::eStateInvalid:
1569af245d11STodd Fiala   case StateType::eStateExited:
1570af245d11STodd Fiala   case StateType::eStateCrashed:
1571af245d11STodd Fiala   case StateType::eStateDetached:
1572af245d11STodd Fiala   case StateType::eStateUnloaded:
1573af245d11STodd Fiala     // Nothing to do - the process is already dead.
1574af245d11STodd Fiala     if (log)
1575b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s ignored for PID %" PRIu64
1576b9c1b51eSKate Stone                   " due to current state: %s",
1577b9c1b51eSKate Stone                   __FUNCTION__, GetID(), StateAsCString(m_state));
1578af245d11STodd Fiala     return error;
1579af245d11STodd Fiala 
1580af245d11STodd Fiala   case StateType::eStateConnected:
1581af245d11STodd Fiala   case StateType::eStateAttaching:
1582af245d11STodd Fiala   case StateType::eStateLaunching:
1583af245d11STodd Fiala   case StateType::eStateStopped:
1584af245d11STodd Fiala   case StateType::eStateRunning:
1585af245d11STodd Fiala   case StateType::eStateStepping:
1586af245d11STodd Fiala   case StateType::eStateSuspended:
1587af245d11STodd Fiala     // We can try to kill a process in these states.
1588af245d11STodd Fiala     break;
1589af245d11STodd Fiala   }
1590af245d11STodd Fiala 
1591b9c1b51eSKate Stone   if (kill(GetID(), SIGKILL) != 0) {
1592af245d11STodd Fiala     error.SetErrorToErrno();
1593af245d11STodd Fiala     return error;
1594af245d11STodd Fiala   }
1595af245d11STodd Fiala 
1596af245d11STodd Fiala   return error;
1597af245d11STodd Fiala }
1598af245d11STodd Fiala 
1599af245d11STodd Fiala static Error
1600b9c1b51eSKate Stone ParseMemoryRegionInfoFromProcMapsLine(const std::string &maps_line,
1601b9c1b51eSKate Stone                                       MemoryRegionInfo &memory_region_info) {
1602af245d11STodd Fiala   memory_region_info.Clear();
1603af245d11STodd Fiala 
1604b9739d40SPavel Labath   StringExtractor line_extractor(maps_line.c_str());
1605af245d11STodd Fiala 
1606b9c1b51eSKate Stone   // Format: {address_start_hex}-{address_end_hex} perms offset  dev   inode
1607b9c1b51eSKate Stone   // pathname
1608b9c1b51eSKate Stone   // perms: rwxp   (letter is present if set, '-' if not, final character is
1609b9c1b51eSKate Stone   // p=private, s=shared).
1610af245d11STodd Fiala 
1611af245d11STodd Fiala   // Parse out the starting address
1612af245d11STodd Fiala   lldb::addr_t start_address = line_extractor.GetHexMaxU64(false, 0);
1613af245d11STodd Fiala 
1614af245d11STodd Fiala   // Parse out hyphen separating start and end address from range.
1615af245d11STodd Fiala   if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != '-'))
1616b9c1b51eSKate Stone     return Error(
1617b9c1b51eSKate Stone         "malformed /proc/{pid}/maps entry, missing dash between address range");
1618af245d11STodd Fiala 
1619af245d11STodd Fiala   // Parse out the ending address
1620af245d11STodd Fiala   lldb::addr_t end_address = line_extractor.GetHexMaxU64(false, start_address);
1621af245d11STodd Fiala 
1622af245d11STodd Fiala   // Parse out the space after the address.
1623af245d11STodd Fiala   if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != ' '))
1624af245d11STodd Fiala     return Error("malformed /proc/{pid}/maps entry, missing space after range");
1625af245d11STodd Fiala 
1626af245d11STodd Fiala   // Save the range.
1627af245d11STodd Fiala   memory_region_info.GetRange().SetRangeBase(start_address);
1628af245d11STodd Fiala   memory_region_info.GetRange().SetRangeEnd(end_address);
1629af245d11STodd Fiala 
1630b9c1b51eSKate Stone   // Any memory region in /proc/{pid}/maps is by definition mapped into the
1631b9c1b51eSKate Stone   // process.
1632ad007563SHoward Hellyer   memory_region_info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
1633ad007563SHoward Hellyer 
1634af245d11STodd Fiala   // Parse out each permission entry.
1635af245d11STodd Fiala   if (line_extractor.GetBytesLeft() < 4)
1636b9c1b51eSKate Stone     return Error("malformed /proc/{pid}/maps entry, missing some portion of "
1637b9c1b51eSKate Stone                  "permissions");
1638af245d11STodd Fiala 
1639af245d11STodd Fiala   // Handle read permission.
1640af245d11STodd Fiala   const char read_perm_char = line_extractor.GetChar();
1641af245d11STodd Fiala   if (read_perm_char == 'r')
1642af245d11STodd Fiala     memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eYes);
1643c73301bbSTamas Berghammer   else if (read_perm_char == '-')
1644af245d11STodd Fiala     memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1645c73301bbSTamas Berghammer   else
1646c73301bbSTamas Berghammer     return Error("unexpected /proc/{pid}/maps read permission char");
1647af245d11STodd Fiala 
1648af245d11STodd Fiala   // Handle write permission.
1649af245d11STodd Fiala   const char write_perm_char = line_extractor.GetChar();
1650af245d11STodd Fiala   if (write_perm_char == 'w')
1651af245d11STodd Fiala     memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eYes);
1652c73301bbSTamas Berghammer   else if (write_perm_char == '-')
1653af245d11STodd Fiala     memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1654c73301bbSTamas Berghammer   else
1655c73301bbSTamas Berghammer     return Error("unexpected /proc/{pid}/maps write permission char");
1656af245d11STodd Fiala 
1657af245d11STodd Fiala   // Handle execute permission.
1658af245d11STodd Fiala   const char exec_perm_char = line_extractor.GetChar();
1659af245d11STodd Fiala   if (exec_perm_char == 'x')
1660af245d11STodd Fiala     memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes);
1661c73301bbSTamas Berghammer   else if (exec_perm_char == '-')
1662af245d11STodd Fiala     memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1663c73301bbSTamas Berghammer   else
1664c73301bbSTamas Berghammer     return Error("unexpected /proc/{pid}/maps exec permission char");
1665af245d11STodd Fiala 
1666d7d69f80STamas Berghammer   line_extractor.GetChar();              // Read the private bit
1667d7d69f80STamas Berghammer   line_extractor.SkipSpaces();           // Skip the separator
1668d7d69f80STamas Berghammer   line_extractor.GetHexMaxU64(false, 0); // Read the offset
1669d7d69f80STamas Berghammer   line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1670d7d69f80STamas Berghammer   line_extractor.GetChar();              // Read the device id separator
1671d7d69f80STamas Berghammer   line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1672d7d69f80STamas Berghammer   line_extractor.SkipSpaces();           // Skip the separator
1673d7d69f80STamas Berghammer   line_extractor.GetU64(0, 10);          // Read the inode number
1674d7d69f80STamas Berghammer 
1675d7d69f80STamas Berghammer   line_extractor.SkipSpaces();
1676b9739d40SPavel Labath   const char *name = line_extractor.Peek();
1677b9739d40SPavel Labath   if (name)
1678b9739d40SPavel Labath     memory_region_info.SetName(name);
1679d7d69f80STamas Berghammer 
1680af245d11STodd Fiala   return Error();
1681af245d11STodd Fiala }
1682af245d11STodd Fiala 
1683b9c1b51eSKate Stone Error NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr,
1684b9c1b51eSKate Stone                                               MemoryRegionInfo &range_info) {
1685b9c1b51eSKate Stone   // FIXME review that the final memory region returned extends to the end of
1686b9c1b51eSKate Stone   // the virtual address space,
1687af245d11STodd Fiala   // with no perms if it is not mapped.
1688af245d11STodd Fiala 
1689af245d11STodd Fiala   // Use an approach that reads memory regions from /proc/{pid}/maps.
1690af245d11STodd Fiala   // Assume proc maps entries are in ascending order.
1691af245d11STodd Fiala   // FIXME assert if we find differently.
1692af245d11STodd Fiala 
1693af245d11STodd Fiala   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1694af245d11STodd Fiala   Error error;
1695af245d11STodd Fiala 
1696b9c1b51eSKate Stone   if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
1697af245d11STodd Fiala     // We're done.
1698af245d11STodd Fiala     error.SetErrorString("unsupported");
1699af245d11STodd Fiala     return error;
1700af245d11STodd Fiala   }
1701af245d11STodd Fiala 
1702b9c1b51eSKate Stone   // If our cache is empty, pull the latest.  There should always be at least
1703b9c1b51eSKate Stone   // one memory region
1704af245d11STodd Fiala   // if memory region handling is supported.
1705b9c1b51eSKate Stone   if (m_mem_region_cache.empty()) {
1706b9c1b51eSKate Stone     error = ProcFileReader::ProcessLineByLine(
1707b9c1b51eSKate Stone         GetID(), "maps", [&](const std::string &line) -> bool {
1708af245d11STodd Fiala           MemoryRegionInfo info;
1709b9c1b51eSKate Stone           const Error parse_error =
1710b9c1b51eSKate Stone               ParseMemoryRegionInfoFromProcMapsLine(line, info);
1711b9c1b51eSKate Stone           if (parse_error.Success()) {
1712af245d11STodd Fiala             m_mem_region_cache.push_back(info);
1713af245d11STodd Fiala             return true;
1714b9c1b51eSKate Stone           } else {
1715af245d11STodd Fiala             if (log)
1716b9c1b51eSKate Stone               log->Printf("NativeProcessLinux::%s failed to parse proc maps "
1717b9c1b51eSKate Stone                           "line '%s': %s",
1718b9c1b51eSKate Stone                           __FUNCTION__, line.c_str(), error.AsCString());
1719af245d11STodd Fiala             return false;
1720af245d11STodd Fiala           }
1721af245d11STodd Fiala         });
1722af245d11STodd Fiala 
1723af245d11STodd Fiala     // If we had an error, we'll mark unsupported.
1724b9c1b51eSKate Stone     if (error.Fail()) {
1725af245d11STodd Fiala       m_supports_mem_region = LazyBool::eLazyBoolNo;
1726af245d11STodd Fiala       return error;
1727b9c1b51eSKate Stone     } else if (m_mem_region_cache.empty()) {
1728b9c1b51eSKate Stone       // No entries after attempting to read them.  This shouldn't happen if
1729b9c1b51eSKate Stone       // /proc/{pid}/maps
1730af245d11STodd Fiala       // is supported.  Assume we don't support map entries via procfs.
1731af245d11STodd Fiala       if (log)
1732b9c1b51eSKate Stone         log->Printf("NativeProcessLinux::%s failed to find any procfs maps "
1733b9c1b51eSKate Stone                     "entries, assuming no support for memory region metadata "
1734b9c1b51eSKate Stone                     "retrieval",
1735b9c1b51eSKate Stone                     __FUNCTION__);
1736af245d11STodd Fiala       m_supports_mem_region = LazyBool::eLazyBoolNo;
1737af245d11STodd Fiala       error.SetErrorString("not supported");
1738af245d11STodd Fiala       return error;
1739af245d11STodd Fiala     }
1740af245d11STodd Fiala 
1741af245d11STodd Fiala     if (log)
1742b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s read %" PRIu64
1743b9c1b51eSKate Stone                   " memory region entries from /proc/%" PRIu64 "/maps",
1744b9c1b51eSKate Stone                   __FUNCTION__,
1745b9c1b51eSKate Stone                   static_cast<uint64_t>(m_mem_region_cache.size()), GetID());
1746af245d11STodd Fiala 
1747af245d11STodd Fiala     // We support memory retrieval, remember that.
1748af245d11STodd Fiala     m_supports_mem_region = LazyBool::eLazyBoolYes;
1749b9c1b51eSKate Stone   } else {
1750af245d11STodd Fiala     if (log)
1751b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s reusing %" PRIu64
1752b9c1b51eSKate Stone                   " cached memory region entries",
1753b9c1b51eSKate Stone                   __FUNCTION__,
1754b9c1b51eSKate Stone                   static_cast<uint64_t>(m_mem_region_cache.size()));
1755af245d11STodd Fiala   }
1756af245d11STodd Fiala 
1757af245d11STodd Fiala   lldb::addr_t prev_base_address = 0;
1758af245d11STodd Fiala 
1759b9c1b51eSKate Stone   // FIXME start by finding the last region that is <= target address using
1760b9c1b51eSKate Stone   // binary search.  Data is sorted.
1761af245d11STodd Fiala   // There can be a ton of regions on pthreads apps with lots of threads.
1762b9c1b51eSKate Stone   for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1763b9c1b51eSKate Stone        ++it) {
1764af245d11STodd Fiala     MemoryRegionInfo &proc_entry_info = *it;
1765af245d11STodd Fiala 
1766af245d11STodd Fiala     // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1767b9c1b51eSKate Stone     assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
1768b9c1b51eSKate Stone            "descending /proc/pid/maps entries detected, unexpected");
1769af245d11STodd Fiala     prev_base_address = proc_entry_info.GetRange().GetRangeBase();
1770af245d11STodd Fiala 
1771b9c1b51eSKate Stone     // If the target address comes before this entry, indicate distance to next
1772b9c1b51eSKate Stone     // region.
1773b9c1b51eSKate Stone     if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1774af245d11STodd Fiala       range_info.GetRange().SetRangeBase(load_addr);
1775b9c1b51eSKate Stone       range_info.GetRange().SetByteSize(
1776b9c1b51eSKate Stone           proc_entry_info.GetRange().GetRangeBase() - load_addr);
1777af245d11STodd Fiala       range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1778af245d11STodd Fiala       range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1779af245d11STodd Fiala       range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1780ad007563SHoward Hellyer       range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1781af245d11STodd Fiala 
1782af245d11STodd Fiala       return error;
1783b9c1b51eSKate Stone     } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1784af245d11STodd Fiala       // The target address is within the memory region we're processing here.
1785af245d11STodd Fiala       range_info = proc_entry_info;
1786af245d11STodd Fiala       return error;
1787af245d11STodd Fiala     }
1788af245d11STodd Fiala 
1789b9c1b51eSKate Stone     // The target memory address comes somewhere after the region we just
1790b9c1b51eSKate Stone     // parsed.
1791af245d11STodd Fiala   }
1792af245d11STodd Fiala 
1793b9c1b51eSKate Stone   // If we made it here, we didn't find an entry that contained the given
1794b9c1b51eSKate Stone   // address. Return the
1795b9c1b51eSKate Stone   // load_addr as start and the amount of bytes betwwen load address and the end
1796b9c1b51eSKate Stone   // of the memory as
179709839c33STamas Berghammer   // size.
179809839c33STamas Berghammer   range_info.GetRange().SetRangeBase(load_addr);
1799ad007563SHoward Hellyer   range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
180009839c33STamas Berghammer   range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
180109839c33STamas Berghammer   range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
180209839c33STamas Berghammer   range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1803ad007563SHoward Hellyer   range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1804af245d11STodd Fiala   return error;
1805af245d11STodd Fiala }
1806af245d11STodd Fiala 
1807b9c1b51eSKate Stone void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
1808af245d11STodd Fiala   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1809af245d11STodd Fiala   if (log)
1810b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called",
1811b9c1b51eSKate Stone                 __FUNCTION__, newBumpId);
1812af245d11STodd Fiala 
1813af245d11STodd Fiala   if (log)
1814b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s clearing %" PRIu64
1815b9c1b51eSKate Stone                 " entries from the cache",
1816b9c1b51eSKate Stone                 __FUNCTION__, static_cast<uint64_t>(m_mem_region_cache.size()));
1817af245d11STodd Fiala   m_mem_region_cache.clear();
1818af245d11STodd Fiala }
1819af245d11STodd Fiala 
1820b9c1b51eSKate Stone Error NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions,
1821b9c1b51eSKate Stone                                          lldb::addr_t &addr) {
1822af245d11STodd Fiala // FIXME implementing this requires the equivalent of
1823af245d11STodd Fiala // InferiorCallPOSIX::InferiorCallMmap, which depends on
1824af245d11STodd Fiala // functional ThreadPlans working with Native*Protocol.
1825af245d11STodd Fiala #if 1
1826af245d11STodd Fiala   return Error("not implemented yet");
1827af245d11STodd Fiala #else
1828af245d11STodd Fiala   addr = LLDB_INVALID_ADDRESS;
1829af245d11STodd Fiala 
1830af245d11STodd Fiala   unsigned prot = 0;
1831af245d11STodd Fiala   if (permissions & lldb::ePermissionsReadable)
1832af245d11STodd Fiala     prot |= eMmapProtRead;
1833af245d11STodd Fiala   if (permissions & lldb::ePermissionsWritable)
1834af245d11STodd Fiala     prot |= eMmapProtWrite;
1835af245d11STodd Fiala   if (permissions & lldb::ePermissionsExecutable)
1836af245d11STodd Fiala     prot |= eMmapProtExec;
1837af245d11STodd Fiala 
1838af245d11STodd Fiala   // TODO implement this directly in NativeProcessLinux
1839af245d11STodd Fiala   // (and lift to NativeProcessPOSIX if/when that class is
1840af245d11STodd Fiala   // refactored out).
1841af245d11STodd Fiala   if (InferiorCallMmap(this, addr, 0, size, prot,
1842af245d11STodd Fiala                        eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
1843af245d11STodd Fiala     m_addr_to_mmap_size[addr] = size;
1844af245d11STodd Fiala     return Error();
1845af245d11STodd Fiala   } else {
1846af245d11STodd Fiala     addr = LLDB_INVALID_ADDRESS;
1847b9c1b51eSKate Stone     return Error("unable to allocate %" PRIu64
1848b9c1b51eSKate Stone                  " bytes of memory with permissions %s",
1849b9c1b51eSKate Stone                  size, GetPermissionsAsCString(permissions));
1850af245d11STodd Fiala   }
1851af245d11STodd Fiala #endif
1852af245d11STodd Fiala }
1853af245d11STodd Fiala 
1854b9c1b51eSKate Stone Error NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {
1855af245d11STodd Fiala   // FIXME see comments in AllocateMemory - required lower-level
1856af245d11STodd Fiala   // bits not in place yet (ThreadPlans)
1857af245d11STodd Fiala   return Error("not implemented");
1858af245d11STodd Fiala }
1859af245d11STodd Fiala 
1860b9c1b51eSKate Stone lldb::addr_t NativeProcessLinux::GetSharedLibraryInfoAddress() {
1861af245d11STodd Fiala   // punt on this for now
1862af245d11STodd Fiala   return LLDB_INVALID_ADDRESS;
1863af245d11STodd Fiala }
1864af245d11STodd Fiala 
1865b9c1b51eSKate Stone size_t NativeProcessLinux::UpdateThreads() {
1866af245d11STodd Fiala   // The NativeProcessLinux monitoring threads are always up to date
1867af245d11STodd Fiala   // with respect to thread state and they keep the thread list
1868af245d11STodd Fiala   // populated properly. All this method needs to do is return the
1869af245d11STodd Fiala   // thread count.
1870af245d11STodd Fiala   return m_threads.size();
1871af245d11STodd Fiala }
1872af245d11STodd Fiala 
1873b9c1b51eSKate Stone bool NativeProcessLinux::GetArchitecture(ArchSpec &arch) const {
1874af245d11STodd Fiala   arch = m_arch;
1875af245d11STodd Fiala   return true;
1876af245d11STodd Fiala }
1877af245d11STodd Fiala 
1878b9c1b51eSKate Stone Error NativeProcessLinux::GetSoftwareBreakpointPCOffset(
1879b9c1b51eSKate Stone     uint32_t &actual_opcode_size) {
1880af245d11STodd Fiala   // FIXME put this behind a breakpoint protocol class that can be
1881af245d11STodd Fiala   // set per architecture.  Need ARM, MIPS support here.
1882af245d11STodd Fiala   static const uint8_t g_i386_opcode[] = {0xCC};
1883bb00d0b6SUlrich Weigand   static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
1884af245d11STodd Fiala 
1885b9c1b51eSKate Stone   switch (m_arch.GetMachine()) {
1886af245d11STodd Fiala   case llvm::Triple::x86:
1887af245d11STodd Fiala   case llvm::Triple::x86_64:
1888af245d11STodd Fiala     actual_opcode_size = static_cast<uint32_t>(sizeof(g_i386_opcode));
1889af245d11STodd Fiala     return Error();
1890af245d11STodd Fiala 
1891bb00d0b6SUlrich Weigand   case llvm::Triple::systemz:
1892bb00d0b6SUlrich Weigand     actual_opcode_size = static_cast<uint32_t>(sizeof(g_s390x_opcode));
1893bb00d0b6SUlrich Weigand     return Error();
1894bb00d0b6SUlrich Weigand 
1895ff7fd900STamas Berghammer   case llvm::Triple::arm:
1896ff7fd900STamas Berghammer   case llvm::Triple::aarch64:
1897e8659b5dSMohit K. Bhakkad   case llvm::Triple::mips64:
1898e8659b5dSMohit K. Bhakkad   case llvm::Triple::mips64el:
1899ce815e45SSagar Thakur   case llvm::Triple::mips:
1900ce815e45SSagar Thakur   case llvm::Triple::mipsel:
1901ff7fd900STamas Berghammer     // On these architectures the PC don't get updated for breakpoint hits
1902c60c9452SJaydeep Patil     actual_opcode_size = 0;
1903e8659b5dSMohit K. Bhakkad     return Error();
1904e8659b5dSMohit K. Bhakkad 
1905af245d11STodd Fiala   default:
1906af245d11STodd Fiala     assert(false && "CPU type not supported!");
1907af245d11STodd Fiala     return Error("CPU type not supported");
1908af245d11STodd Fiala   }
1909af245d11STodd Fiala }
1910af245d11STodd Fiala 
1911b9c1b51eSKate Stone Error NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,
1912b9c1b51eSKate Stone                                         bool hardware) {
1913af245d11STodd Fiala   if (hardware)
1914af245d11STodd Fiala     return Error("NativeProcessLinux does not support hardware breakpoints");
1915af245d11STodd Fiala   else
1916af245d11STodd Fiala     return SetSoftwareBreakpoint(addr, size);
1917af245d11STodd Fiala }
1918af245d11STodd Fiala 
1919b9c1b51eSKate Stone Error NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(
1920b9c1b51eSKate Stone     size_t trap_opcode_size_hint, size_t &actual_opcode_size,
1921b9c1b51eSKate Stone     const uint8_t *&trap_opcode_bytes) {
192263c8be95STamas Berghammer   // FIXME put this behind a breakpoint protocol class that can be set per
192363c8be95STamas Berghammer   // architecture.  Need MIPS support here.
19242afc5966STodd Fiala   static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};
1925be379e15STamas Berghammer   // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1926be379e15STamas Berghammer   // linux kernel does otherwise.
1927be379e15STamas Berghammer   static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1928af245d11STodd Fiala   static const uint8_t g_i386_opcode[] = {0xCC};
19293df471c3SMohit K. Bhakkad   static const uint8_t g_mips64_opcode[] = {0x00, 0x00, 0x00, 0x0d};
19302c2acf96SMohit K. Bhakkad   static const uint8_t g_mips64el_opcode[] = {0x0d, 0x00, 0x00, 0x00};
1931bb00d0b6SUlrich Weigand   static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
1932be379e15STamas Berghammer   static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
1933af245d11STodd Fiala 
1934b9c1b51eSKate Stone   switch (m_arch.GetMachine()) {
19352afc5966STodd Fiala   case llvm::Triple::aarch64:
19362afc5966STodd Fiala     trap_opcode_bytes = g_aarch64_opcode;
19372afc5966STodd Fiala     actual_opcode_size = sizeof(g_aarch64_opcode);
19382afc5966STodd Fiala     return Error();
19392afc5966STodd Fiala 
194063c8be95STamas Berghammer   case llvm::Triple::arm:
1941b9c1b51eSKate Stone     switch (trap_opcode_size_hint) {
194263c8be95STamas Berghammer     case 2:
194363c8be95STamas Berghammer       trap_opcode_bytes = g_thumb_breakpoint_opcode;
194463c8be95STamas Berghammer       actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
194563c8be95STamas Berghammer       return Error();
194663c8be95STamas Berghammer     case 4:
194763c8be95STamas Berghammer       trap_opcode_bytes = g_arm_breakpoint_opcode;
194863c8be95STamas Berghammer       actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
194963c8be95STamas Berghammer       return Error();
195063c8be95STamas Berghammer     default:
195163c8be95STamas Berghammer       assert(false && "Unrecognised trap opcode size hint!");
195263c8be95STamas Berghammer       return Error("Unrecognised trap opcode size hint!");
195363c8be95STamas Berghammer     }
195463c8be95STamas Berghammer 
1955af245d11STodd Fiala   case llvm::Triple::x86:
1956af245d11STodd Fiala   case llvm::Triple::x86_64:
1957af245d11STodd Fiala     trap_opcode_bytes = g_i386_opcode;
1958af245d11STodd Fiala     actual_opcode_size = sizeof(g_i386_opcode);
1959af245d11STodd Fiala     return Error();
1960af245d11STodd Fiala 
1961ce815e45SSagar Thakur   case llvm::Triple::mips:
19623df471c3SMohit K. Bhakkad   case llvm::Triple::mips64:
19633df471c3SMohit K. Bhakkad     trap_opcode_bytes = g_mips64_opcode;
19643df471c3SMohit K. Bhakkad     actual_opcode_size = sizeof(g_mips64_opcode);
19653df471c3SMohit K. Bhakkad     return Error();
19663df471c3SMohit K. Bhakkad 
1967ce815e45SSagar Thakur   case llvm::Triple::mipsel:
19682c2acf96SMohit K. Bhakkad   case llvm::Triple::mips64el:
19692c2acf96SMohit K. Bhakkad     trap_opcode_bytes = g_mips64el_opcode;
19702c2acf96SMohit K. Bhakkad     actual_opcode_size = sizeof(g_mips64el_opcode);
19712c2acf96SMohit K. Bhakkad     return Error();
19722c2acf96SMohit K. Bhakkad 
1973bb00d0b6SUlrich Weigand   case llvm::Triple::systemz:
1974bb00d0b6SUlrich Weigand     trap_opcode_bytes = g_s390x_opcode;
1975bb00d0b6SUlrich Weigand     actual_opcode_size = sizeof(g_s390x_opcode);
1976bb00d0b6SUlrich Weigand     return Error();
1977bb00d0b6SUlrich Weigand 
1978af245d11STodd Fiala   default:
1979af245d11STodd Fiala     assert(false && "CPU type not supported!");
1980af245d11STodd Fiala     return Error("CPU type not supported");
1981af245d11STodd Fiala   }
1982af245d11STodd Fiala }
1983af245d11STodd Fiala 
1984af245d11STodd Fiala #if 0
1985af245d11STodd Fiala ProcessMessage::CrashReason
1986af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
1987af245d11STodd Fiala {
1988af245d11STodd Fiala     ProcessMessage::CrashReason reason;
1989af245d11STodd Fiala     assert(info->si_signo == SIGSEGV);
1990af245d11STodd Fiala 
1991af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
1992af245d11STodd Fiala 
1993af245d11STodd Fiala     switch (info->si_code)
1994af245d11STodd Fiala     {
1995af245d11STodd Fiala     default:
1996af245d11STodd Fiala         assert(false && "unexpected si_code for SIGSEGV");
1997af245d11STodd Fiala         break;
1998af245d11STodd Fiala     case SI_KERNEL:
1999af245d11STodd Fiala         // Linux will occasionally send spurious SI_KERNEL codes.
2000af245d11STodd Fiala         // (this is poorly documented in sigaction)
2001af245d11STodd Fiala         // One way to get this is via unaligned SIMD loads.
2002af245d11STodd Fiala         reason = ProcessMessage::eInvalidAddress; // for lack of anything better
2003af245d11STodd Fiala         break;
2004af245d11STodd Fiala     case SEGV_MAPERR:
2005af245d11STodd Fiala         reason = ProcessMessage::eInvalidAddress;
2006af245d11STodd Fiala         break;
2007af245d11STodd Fiala     case SEGV_ACCERR:
2008af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedAddress;
2009af245d11STodd Fiala         break;
2010af245d11STodd Fiala     }
2011af245d11STodd Fiala 
2012af245d11STodd Fiala     return reason;
2013af245d11STodd Fiala }
2014af245d11STodd Fiala #endif
2015af245d11STodd Fiala 
2016af245d11STodd Fiala #if 0
2017af245d11STodd Fiala ProcessMessage::CrashReason
2018af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
2019af245d11STodd Fiala {
2020af245d11STodd Fiala     ProcessMessage::CrashReason reason;
2021af245d11STodd Fiala     assert(info->si_signo == SIGILL);
2022af245d11STodd Fiala 
2023af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
2024af245d11STodd Fiala 
2025af245d11STodd Fiala     switch (info->si_code)
2026af245d11STodd Fiala     {
2027af245d11STodd Fiala     default:
2028af245d11STodd Fiala         assert(false && "unexpected si_code for SIGILL");
2029af245d11STodd Fiala         break;
2030af245d11STodd Fiala     case ILL_ILLOPC:
2031af245d11STodd Fiala         reason = ProcessMessage::eIllegalOpcode;
2032af245d11STodd Fiala         break;
2033af245d11STodd Fiala     case ILL_ILLOPN:
2034af245d11STodd Fiala         reason = ProcessMessage::eIllegalOperand;
2035af245d11STodd Fiala         break;
2036af245d11STodd Fiala     case ILL_ILLADR:
2037af245d11STodd Fiala         reason = ProcessMessage::eIllegalAddressingMode;
2038af245d11STodd Fiala         break;
2039af245d11STodd Fiala     case ILL_ILLTRP:
2040af245d11STodd Fiala         reason = ProcessMessage::eIllegalTrap;
2041af245d11STodd Fiala         break;
2042af245d11STodd Fiala     case ILL_PRVOPC:
2043af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedOpcode;
2044af245d11STodd Fiala         break;
2045af245d11STodd Fiala     case ILL_PRVREG:
2046af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedRegister;
2047af245d11STodd Fiala         break;
2048af245d11STodd Fiala     case ILL_COPROC:
2049af245d11STodd Fiala         reason = ProcessMessage::eCoprocessorError;
2050af245d11STodd Fiala         break;
2051af245d11STodd Fiala     case ILL_BADSTK:
2052af245d11STodd Fiala         reason = ProcessMessage::eInternalStackError;
2053af245d11STodd Fiala         break;
2054af245d11STodd Fiala     }
2055af245d11STodd Fiala 
2056af245d11STodd Fiala     return reason;
2057af245d11STodd Fiala }
2058af245d11STodd Fiala #endif
2059af245d11STodd Fiala 
2060af245d11STodd Fiala #if 0
2061af245d11STodd Fiala ProcessMessage::CrashReason
2062af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
2063af245d11STodd Fiala {
2064af245d11STodd Fiala     ProcessMessage::CrashReason reason;
2065af245d11STodd Fiala     assert(info->si_signo == SIGFPE);
2066af245d11STodd Fiala 
2067af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
2068af245d11STodd Fiala 
2069af245d11STodd Fiala     switch (info->si_code)
2070af245d11STodd Fiala     {
2071af245d11STodd Fiala     default:
2072af245d11STodd Fiala         assert(false && "unexpected si_code for SIGFPE");
2073af245d11STodd Fiala         break;
2074af245d11STodd Fiala     case FPE_INTDIV:
2075af245d11STodd Fiala         reason = ProcessMessage::eIntegerDivideByZero;
2076af245d11STodd Fiala         break;
2077af245d11STodd Fiala     case FPE_INTOVF:
2078af245d11STodd Fiala         reason = ProcessMessage::eIntegerOverflow;
2079af245d11STodd Fiala         break;
2080af245d11STodd Fiala     case FPE_FLTDIV:
2081af245d11STodd Fiala         reason = ProcessMessage::eFloatDivideByZero;
2082af245d11STodd Fiala         break;
2083af245d11STodd Fiala     case FPE_FLTOVF:
2084af245d11STodd Fiala         reason = ProcessMessage::eFloatOverflow;
2085af245d11STodd Fiala         break;
2086af245d11STodd Fiala     case FPE_FLTUND:
2087af245d11STodd Fiala         reason = ProcessMessage::eFloatUnderflow;
2088af245d11STodd Fiala         break;
2089af245d11STodd Fiala     case FPE_FLTRES:
2090af245d11STodd Fiala         reason = ProcessMessage::eFloatInexactResult;
2091af245d11STodd Fiala         break;
2092af245d11STodd Fiala     case FPE_FLTINV:
2093af245d11STodd Fiala         reason = ProcessMessage::eFloatInvalidOperation;
2094af245d11STodd Fiala         break;
2095af245d11STodd Fiala     case FPE_FLTSUB:
2096af245d11STodd Fiala         reason = ProcessMessage::eFloatSubscriptRange;
2097af245d11STodd Fiala         break;
2098af245d11STodd Fiala     }
2099af245d11STodd Fiala 
2100af245d11STodd Fiala     return reason;
2101af245d11STodd Fiala }
2102af245d11STodd Fiala #endif
2103af245d11STodd Fiala 
2104af245d11STodd Fiala #if 0
2105af245d11STodd Fiala ProcessMessage::CrashReason
2106af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
2107af245d11STodd Fiala {
2108af245d11STodd Fiala     ProcessMessage::CrashReason reason;
2109af245d11STodd Fiala     assert(info->si_signo == SIGBUS);
2110af245d11STodd Fiala 
2111af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
2112af245d11STodd Fiala 
2113af245d11STodd Fiala     switch (info->si_code)
2114af245d11STodd Fiala     {
2115af245d11STodd Fiala     default:
2116af245d11STodd Fiala         assert(false && "unexpected si_code for SIGBUS");
2117af245d11STodd Fiala         break;
2118af245d11STodd Fiala     case BUS_ADRALN:
2119af245d11STodd Fiala         reason = ProcessMessage::eIllegalAlignment;
2120af245d11STodd Fiala         break;
2121af245d11STodd Fiala     case BUS_ADRERR:
2122af245d11STodd Fiala         reason = ProcessMessage::eIllegalAddress;
2123af245d11STodd Fiala         break;
2124af245d11STodd Fiala     case BUS_OBJERR:
2125af245d11STodd Fiala         reason = ProcessMessage::eHardwareError;
2126af245d11STodd Fiala         break;
2127af245d11STodd Fiala     }
2128af245d11STodd Fiala 
2129af245d11STodd Fiala     return reason;
2130af245d11STodd Fiala }
2131af245d11STodd Fiala #endif
2132af245d11STodd Fiala 
2133b9c1b51eSKate Stone Error NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
2134b9c1b51eSKate Stone                                      size_t &bytes_read) {
2135df7c6995SPavel Labath   if (ProcessVmReadvSupported()) {
2136b9c1b51eSKate Stone     // The process_vm_readv path is about 50 times faster than ptrace api. We
2137b9c1b51eSKate Stone     // want to use
2138df7c6995SPavel Labath     // this syscall if it is supported.
2139df7c6995SPavel Labath 
2140df7c6995SPavel Labath     const ::pid_t pid = GetID();
2141df7c6995SPavel Labath 
2142df7c6995SPavel Labath     struct iovec local_iov, remote_iov;
2143df7c6995SPavel Labath     local_iov.iov_base = buf;
2144df7c6995SPavel Labath     local_iov.iov_len = size;
2145df7c6995SPavel Labath     remote_iov.iov_base = reinterpret_cast<void *>(addr);
2146df7c6995SPavel Labath     remote_iov.iov_len = size;
2147df7c6995SPavel Labath 
2148df7c6995SPavel Labath     bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
2149df7c6995SPavel Labath     const bool success = bytes_read == size;
2150df7c6995SPavel Labath 
2151df7c6995SPavel Labath     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2152df7c6995SPavel Labath     if (log)
2153b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s using process_vm_readv to read %zd "
2154b9c1b51eSKate Stone                   "bytes from inferior address 0x%" PRIx64 ": %s",
2155b9c1b51eSKate Stone                   __FUNCTION__, size, addr,
2156b9c1b51eSKate Stone                   success ? "Success" : strerror(errno));
2157df7c6995SPavel Labath 
2158df7c6995SPavel Labath     if (success)
2159df7c6995SPavel Labath       return Error();
2160df7c6995SPavel Labath     // else
2161b9c1b51eSKate Stone     //     the call failed for some reason, let's retry the read using ptrace
2162b9c1b51eSKate Stone     //     api.
2163df7c6995SPavel Labath   }
2164df7c6995SPavel Labath 
216519cbe96aSPavel Labath   unsigned char *dst = static_cast<unsigned char *>(buf);
216619cbe96aSPavel Labath   size_t remainder;
216719cbe96aSPavel Labath   long data;
216819cbe96aSPavel Labath 
216919cbe96aSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_ALL));
217019cbe96aSPavel Labath   if (log)
217119cbe96aSPavel Labath     ProcessPOSIXLog::IncNestLevel();
2172b9c1b51eSKate Stone   if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2173b9c1b51eSKate Stone       log->GetMask().Test(POSIX_LOG_MEMORY))
2174b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s(%p, %p, %zd, _)", __FUNCTION__,
2175b9c1b51eSKate Stone                 (void *)addr, buf, size);
217619cbe96aSPavel Labath 
2177b9c1b51eSKate Stone   for (bytes_read = 0; bytes_read < size; bytes_read += remainder) {
2178b9c1b51eSKate Stone     Error error = NativeProcessLinux::PtraceWrapper(
2179b9c1b51eSKate Stone         PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data);
2180b9c1b51eSKate Stone     if (error.Fail()) {
218119cbe96aSPavel Labath       if (log)
218219cbe96aSPavel Labath         ProcessPOSIXLog::DecNestLevel();
218319cbe96aSPavel Labath       return error;
218419cbe96aSPavel Labath     }
218519cbe96aSPavel Labath 
218619cbe96aSPavel Labath     remainder = size - bytes_read;
218719cbe96aSPavel Labath     remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
218819cbe96aSPavel Labath 
218919cbe96aSPavel Labath     // Copy the data into our buffer
2190f6ef187bSMohit K. Bhakkad     memcpy(dst, &data, remainder);
219119cbe96aSPavel Labath 
219219cbe96aSPavel Labath     if (log && ProcessPOSIXLog::AtTopNestLevel() &&
219319cbe96aSPavel Labath         (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
219419cbe96aSPavel Labath          (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2195b9c1b51eSKate Stone           size <= POSIX_LOG_MEMORY_SHORT_BYTES))) {
219619cbe96aSPavel Labath       uintptr_t print_dst = 0;
219719cbe96aSPavel Labath       // Format bytes from data by moving into print_dst for log output
219819cbe96aSPavel Labath       for (unsigned i = 0; i < remainder; ++i)
219919cbe96aSPavel Labath         print_dst |= (((data >> i * 8) & 0xFF) << i * 8);
2200b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s() [0x%" PRIx64 "]:0x%" PRIx64
2201b9c1b51eSKate Stone                   " (0x%" PRIx64 ")",
220279203995SPavel Labath                   __FUNCTION__, addr, uint64_t(print_dst), uint64_t(data));
220319cbe96aSPavel Labath     }
220419cbe96aSPavel Labath     addr += k_ptrace_word_size;
220519cbe96aSPavel Labath     dst += k_ptrace_word_size;
220619cbe96aSPavel Labath   }
220719cbe96aSPavel Labath 
220819cbe96aSPavel Labath   if (log)
220919cbe96aSPavel Labath     ProcessPOSIXLog::DecNestLevel();
221019cbe96aSPavel Labath   return Error();
2211af245d11STodd Fiala }
2212af245d11STodd Fiala 
2213b9c1b51eSKate Stone Error NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf,
2214b9c1b51eSKate Stone                                                 size_t size,
2215b9c1b51eSKate Stone                                                 size_t &bytes_read) {
22163eb4b458SChaoren Lin   Error error = ReadMemory(addr, buf, size, bytes_read);
2217b9c1b51eSKate Stone   if (error.Fail())
2218b9c1b51eSKate Stone     return error;
22193eb4b458SChaoren Lin   return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
22203eb4b458SChaoren Lin }
22213eb4b458SChaoren Lin 
2222b9c1b51eSKate Stone Error NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,
2223b9c1b51eSKate Stone                                       size_t size, size_t &bytes_written) {
222419cbe96aSPavel Labath   const unsigned char *src = static_cast<const unsigned char *>(buf);
222519cbe96aSPavel Labath   size_t remainder;
222619cbe96aSPavel Labath   Error error;
222719cbe96aSPavel Labath 
222819cbe96aSPavel Labath   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_ALL));
222919cbe96aSPavel Labath   if (log)
223019cbe96aSPavel Labath     ProcessPOSIXLog::IncNestLevel();
2231b9c1b51eSKate Stone   if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2232b9c1b51eSKate Stone       log->GetMask().Test(POSIX_LOG_MEMORY))
2233b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s(0x%" PRIx64 ", %p, %zu)", __FUNCTION__,
2234b9c1b51eSKate Stone                 addr, buf, size);
223519cbe96aSPavel Labath 
2236b9c1b51eSKate Stone   for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
223719cbe96aSPavel Labath     remainder = size - bytes_written;
223819cbe96aSPavel Labath     remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
223919cbe96aSPavel Labath 
2240b9c1b51eSKate Stone     if (remainder == k_ptrace_word_size) {
224119cbe96aSPavel Labath       unsigned long data = 0;
2242f6ef187bSMohit K. Bhakkad       memcpy(&data, src, k_ptrace_word_size);
224319cbe96aSPavel Labath 
224419cbe96aSPavel Labath       if (log && ProcessPOSIXLog::AtTopNestLevel() &&
224519cbe96aSPavel Labath           (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
224619cbe96aSPavel Labath            (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
224719cbe96aSPavel Labath             size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
224819cbe96aSPavel Labath         log->Printf("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
224919cbe96aSPavel Labath                     (void *)addr, *(const unsigned long *)src, data);
225019cbe96aSPavel Labath 
2251b9c1b51eSKate Stone       error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(),
2252b9c1b51eSKate Stone                                                 (void *)addr, (void *)data);
2253b9c1b51eSKate Stone       if (error.Fail()) {
225419cbe96aSPavel Labath         if (log)
225519cbe96aSPavel Labath           ProcessPOSIXLog::DecNestLevel();
225619cbe96aSPavel Labath         return error;
225719cbe96aSPavel Labath       }
2258b9c1b51eSKate Stone     } else {
225919cbe96aSPavel Labath       unsigned char buff[8];
226019cbe96aSPavel Labath       size_t bytes_read;
226119cbe96aSPavel Labath       error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
2262b9c1b51eSKate Stone       if (error.Fail()) {
226319cbe96aSPavel Labath         if (log)
226419cbe96aSPavel Labath           ProcessPOSIXLog::DecNestLevel();
226519cbe96aSPavel Labath         return error;
226619cbe96aSPavel Labath       }
226719cbe96aSPavel Labath 
226819cbe96aSPavel Labath       memcpy(buff, src, remainder);
226919cbe96aSPavel Labath 
227019cbe96aSPavel Labath       size_t bytes_written_rec;
227119cbe96aSPavel Labath       error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
2272b9c1b51eSKate Stone       if (error.Fail()) {
227319cbe96aSPavel Labath         if (log)
227419cbe96aSPavel Labath           ProcessPOSIXLog::DecNestLevel();
227519cbe96aSPavel Labath         return error;
227619cbe96aSPavel Labath       }
227719cbe96aSPavel Labath 
227819cbe96aSPavel Labath       if (log && ProcessPOSIXLog::AtTopNestLevel() &&
227919cbe96aSPavel Labath           (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
228019cbe96aSPavel Labath            (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
228119cbe96aSPavel Labath             size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
228219cbe96aSPavel Labath         log->Printf("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
2283b9c1b51eSKate Stone                     (void *)addr, *(const unsigned long *)src,
2284b9c1b51eSKate Stone                     *(unsigned long *)buff);
228519cbe96aSPavel Labath     }
228619cbe96aSPavel Labath 
228719cbe96aSPavel Labath     addr += k_ptrace_word_size;
228819cbe96aSPavel Labath     src += k_ptrace_word_size;
228919cbe96aSPavel Labath   }
229019cbe96aSPavel Labath   if (log)
229119cbe96aSPavel Labath     ProcessPOSIXLog::DecNestLevel();
229219cbe96aSPavel Labath   return error;
2293af245d11STodd Fiala }
2294af245d11STodd Fiala 
2295b9c1b51eSKate Stone Error NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) {
229619cbe96aSPavel Labath   return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
2297af245d11STodd Fiala }
2298af245d11STodd Fiala 
2299b9c1b51eSKate Stone Error NativeProcessLinux::GetEventMessage(lldb::tid_t tid,
2300b9c1b51eSKate Stone                                           unsigned long *message) {
230119cbe96aSPavel Labath   return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
2302af245d11STodd Fiala }
2303af245d11STodd Fiala 
2304b9c1b51eSKate Stone Error NativeProcessLinux::Detach(lldb::tid_t tid) {
230597ccc294SChaoren Lin   if (tid == LLDB_INVALID_THREAD_ID)
230697ccc294SChaoren Lin     return Error();
230797ccc294SChaoren Lin 
230819cbe96aSPavel Labath   return PtraceWrapper(PTRACE_DETACH, tid);
2309af245d11STodd Fiala }
2310af245d11STodd Fiala 
2311b9c1b51eSKate Stone bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {
2312b9c1b51eSKate Stone   for (auto thread_sp : m_threads) {
2313af245d11STodd Fiala     assert(thread_sp && "thread list should not contain NULL threads");
2314b9c1b51eSKate Stone     if (thread_sp->GetID() == thread_id) {
2315af245d11STodd Fiala       // We have this thread.
2316af245d11STodd Fiala       return true;
2317af245d11STodd Fiala     }
2318af245d11STodd Fiala   }
2319af245d11STodd Fiala 
2320af245d11STodd Fiala   // We don't have this thread.
2321af245d11STodd Fiala   return false;
2322af245d11STodd Fiala }
2323af245d11STodd Fiala 
2324b9c1b51eSKate Stone bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) {
23251dbc6c9cSPavel Labath   Log *const log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD);
23261dbc6c9cSPavel Labath 
23271dbc6c9cSPavel Labath   if (log)
2328b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__,
2329b9c1b51eSKate Stone                 thread_id);
23301dbc6c9cSPavel Labath 
23311dbc6c9cSPavel Labath   bool found = false;
23321dbc6c9cSPavel Labath 
2333b9c1b51eSKate Stone   for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
2334b9c1b51eSKate Stone     if (*it && ((*it)->GetID() == thread_id)) {
2335af245d11STodd Fiala       m_threads.erase(it);
23361dbc6c9cSPavel Labath       found = true;
23371dbc6c9cSPavel Labath       break;
2338af245d11STodd Fiala     }
2339af245d11STodd Fiala   }
2340af245d11STodd Fiala 
23419eb1ecb9SPavel Labath   SignalIfAllThreadsStopped();
23421dbc6c9cSPavel Labath 
23431dbc6c9cSPavel Labath   return found;
2344af245d11STodd Fiala }
2345af245d11STodd Fiala 
2346b9c1b51eSKate Stone NativeThreadLinuxSP NativeProcessLinux::AddThread(lldb::tid_t thread_id) {
2347af245d11STodd Fiala   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD));
2348af245d11STodd Fiala 
2349b9c1b51eSKate Stone   if (log) {
2350b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s pid %" PRIu64
2351b9c1b51eSKate Stone                 " adding thread with tid %" PRIu64,
2352b9c1b51eSKate Stone                 __FUNCTION__, GetID(), thread_id);
2353af245d11STodd Fiala   }
2354af245d11STodd Fiala 
2355b9c1b51eSKate Stone   assert(!HasThreadNoLock(thread_id) &&
2356b9c1b51eSKate Stone          "attempted to add a thread by id that already exists");
2357af245d11STodd Fiala 
2358af245d11STodd Fiala   // If this is the first thread, save it as the current thread
2359af245d11STodd Fiala   if (m_threads.empty())
2360af245d11STodd Fiala     SetCurrentThreadID(thread_id);
2361af245d11STodd Fiala 
2362f9077782SPavel Labath   auto thread_sp = std::make_shared<NativeThreadLinux>(this, thread_id);
2363af245d11STodd Fiala   m_threads.push_back(thread_sp);
2364af245d11STodd Fiala   return thread_sp;
2365af245d11STodd Fiala }
2366af245d11STodd Fiala 
2367b9c1b51eSKate Stone Error NativeProcessLinux::FixupBreakpointPCAsNeeded(NativeThreadLinux &thread) {
236875f47c3aSTodd Fiala   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2369af245d11STodd Fiala 
2370af245d11STodd Fiala   Error error;
2371af245d11STodd Fiala 
2372b9c1b51eSKate Stone   // Find out the size of a breakpoint (might depend on where we are in the
2373b9c1b51eSKate Stone   // code).
2374b9cc0c75SPavel Labath   NativeRegisterContextSP context_sp = thread.GetRegisterContext();
2375b9c1b51eSKate Stone   if (!context_sp) {
2376af245d11STodd Fiala     error.SetErrorString("cannot get a NativeRegisterContext for the thread");
2377af245d11STodd Fiala     if (log)
2378b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s failed: %s", __FUNCTION__,
2379b9c1b51eSKate Stone                   error.AsCString());
2380af245d11STodd Fiala     return error;
2381af245d11STodd Fiala   }
2382af245d11STodd Fiala 
2383af245d11STodd Fiala   uint32_t breakpoint_size = 0;
2384b9cc0c75SPavel Labath   error = GetSoftwareBreakpointPCOffset(breakpoint_size);
2385b9c1b51eSKate Stone   if (error.Fail()) {
2386af245d11STodd Fiala     if (log)
2387b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s GetBreakpointSize() failed: %s",
2388b9c1b51eSKate Stone                   __FUNCTION__, error.AsCString());
2389af245d11STodd Fiala     return error;
2390b9c1b51eSKate Stone   } else {
2391af245d11STodd Fiala     if (log)
2392b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s breakpoint size: %" PRIu32,
2393b9c1b51eSKate Stone                   __FUNCTION__, breakpoint_size);
2394af245d11STodd Fiala   }
2395af245d11STodd Fiala 
2396b9c1b51eSKate Stone   // First try probing for a breakpoint at a software breakpoint location: PC -
2397b9c1b51eSKate Stone   // breakpoint size.
2398b9c1b51eSKate Stone   const lldb::addr_t initial_pc_addr =
2399b9c1b51eSKate Stone       context_sp->GetPCfromBreakpointLocation();
2400af245d11STodd Fiala   lldb::addr_t breakpoint_addr = initial_pc_addr;
2401b9c1b51eSKate Stone   if (breakpoint_size > 0) {
2402af245d11STodd Fiala     // Do not allow breakpoint probe to wrap around.
24033eb4b458SChaoren Lin     if (breakpoint_addr >= breakpoint_size)
24043eb4b458SChaoren Lin       breakpoint_addr -= breakpoint_size;
2405af245d11STodd Fiala   }
2406af245d11STodd Fiala 
2407af245d11STodd Fiala   // Check if we stopped because of a breakpoint.
2408af245d11STodd Fiala   NativeBreakpointSP breakpoint_sp;
2409af245d11STodd Fiala   error = m_breakpoint_list.GetBreakpoint(breakpoint_addr, breakpoint_sp);
2410b9c1b51eSKate Stone   if (!error.Success() || !breakpoint_sp) {
2411af245d11STodd Fiala     // We didn't find one at a software probe location.  Nothing to do.
2412af245d11STodd Fiala     if (log)
2413b9c1b51eSKate Stone       log->Printf(
2414b9c1b51eSKate Stone           "NativeProcessLinux::%s pid %" PRIu64
2415b9c1b51eSKate Stone           " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64,
2416b9c1b51eSKate Stone           __FUNCTION__, GetID(), breakpoint_addr);
2417af245d11STodd Fiala     return Error();
2418af245d11STodd Fiala   }
2419af245d11STodd Fiala 
2420af245d11STodd Fiala   // If the breakpoint is not a software breakpoint, nothing to do.
2421b9c1b51eSKate Stone   if (!breakpoint_sp->IsSoftwareBreakpoint()) {
2422af245d11STodd Fiala     if (log)
2423b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s pid %" PRIu64
2424b9c1b51eSKate Stone                   " breakpoint found at 0x%" PRIx64
2425b9c1b51eSKate Stone                   ", not software, nothing to adjust",
2426b9c1b51eSKate Stone                   __FUNCTION__, GetID(), breakpoint_addr);
2427af245d11STodd Fiala     return Error();
2428af245d11STodd Fiala   }
2429af245d11STodd Fiala 
2430af245d11STodd Fiala   //
2431af245d11STodd Fiala   // We have a software breakpoint and need to adjust the PC.
2432af245d11STodd Fiala   //
2433af245d11STodd Fiala 
2434af245d11STodd Fiala   // Sanity check.
2435b9c1b51eSKate Stone   if (breakpoint_size == 0) {
2436af245d11STodd Fiala     // Nothing to do!  How did we get here?
2437af245d11STodd Fiala     if (log)
2438b9c1b51eSKate Stone       log->Printf(
2439b9c1b51eSKate Stone           "NativeProcessLinux::%s pid %" PRIu64
2440b9c1b51eSKate Stone           " breakpoint found at 0x%" PRIx64
2441b9c1b51eSKate Stone           ", it is software, but the size is zero, nothing to do (unexpected)",
2442b9c1b51eSKate Stone           __FUNCTION__, GetID(), breakpoint_addr);
2443af245d11STodd Fiala     return Error();
2444af245d11STodd Fiala   }
2445af245d11STodd Fiala 
2446af245d11STodd Fiala   // Change the program counter.
2447af245d11STodd Fiala   if (log)
2448b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64
2449b9c1b51eSKate Stone                 ": changing PC from 0x%" PRIx64 " to 0x%" PRIx64,
2450b9c1b51eSKate Stone                 __FUNCTION__, GetID(), thread.GetID(), initial_pc_addr,
2451b9c1b51eSKate Stone                 breakpoint_addr);
2452af245d11STodd Fiala 
2453af245d11STodd Fiala   error = context_sp->SetPC(breakpoint_addr);
2454b9c1b51eSKate Stone   if (error.Fail()) {
2455af245d11STodd Fiala     if (log)
2456b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64
2457b9c1b51eSKate Stone                   ": failed to set PC: %s",
2458b9c1b51eSKate Stone                   __FUNCTION__, GetID(), thread.GetID(), error.AsCString());
2459af245d11STodd Fiala     return error;
2460af245d11STodd Fiala   }
2461af245d11STodd Fiala 
2462af245d11STodd Fiala   return error;
2463af245d11STodd Fiala }
2464fa03ad2eSChaoren Lin 
2465b9c1b51eSKate Stone Error NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,
2466b9c1b51eSKate Stone                                                   FileSpec &file_spec) {
24677cb18bf5STamas Berghammer   FileSpec module_file_spec(module_path, true);
24687cb18bf5STamas Berghammer 
2469162fb8e8SPavel Labath   bool found = false;
24707cb18bf5STamas Berghammer   file_spec.Clear();
2471b9c1b51eSKate Stone   ProcFileReader::ProcessLineByLine(
2472b9c1b51eSKate Stone       GetID(), "maps", [&](const std::string &line) {
2473162fb8e8SPavel Labath         SmallVector<StringRef, 16> columns;
2474162fb8e8SPavel Labath         StringRef(line).split(columns, " ", -1, false);
2475162fb8e8SPavel Labath         if (columns.size() < 6)
2476162fb8e8SPavel Labath           return true; // continue searching
2477162fb8e8SPavel Labath 
2478*771ef6d4SMalcolm Parsons         FileSpec this_file_spec(columns[5].str(), false);
2479162fb8e8SPavel Labath         if (this_file_spec.GetFilename() != module_file_spec.GetFilename())
2480162fb8e8SPavel Labath           return true; // continue searching
2481162fb8e8SPavel Labath 
2482162fb8e8SPavel Labath         file_spec = this_file_spec;
2483162fb8e8SPavel Labath         found = true;
2484162fb8e8SPavel Labath         return false; // we are done
2485162fb8e8SPavel Labath       });
2486162fb8e8SPavel Labath 
2487162fb8e8SPavel Labath   if (!found)
24887cb18bf5STamas Berghammer     return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
24897cb18bf5STamas Berghammer                  module_file_spec.GetFilename().AsCString(), GetID());
2490162fb8e8SPavel Labath 
2491162fb8e8SPavel Labath   return Error();
24927cb18bf5STamas Berghammer }
2493c076559aSPavel Labath 
2494b9c1b51eSKate Stone Error NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
2495b9c1b51eSKate Stone                                              lldb::addr_t &load_addr) {
2496783bfc8cSTamas Berghammer   load_addr = LLDB_INVALID_ADDRESS;
2497b9c1b51eSKate Stone   Error error = ProcFileReader::ProcessLineByLine(
2498b9c1b51eSKate Stone       GetID(), "maps", [&](const std::string &line) -> bool {
2499783bfc8cSTamas Berghammer         StringRef maps_row(line);
2500783bfc8cSTamas Berghammer 
2501783bfc8cSTamas Berghammer         SmallVector<StringRef, 16> maps_columns;
2502783bfc8cSTamas Berghammer         maps_row.split(maps_columns, StringRef(" "), -1, false);
2503783bfc8cSTamas Berghammer 
2504b9c1b51eSKate Stone         if (maps_columns.size() < 6) {
2505783bfc8cSTamas Berghammer           // Return true to continue reading the proc file
2506783bfc8cSTamas Berghammer           return true;
2507783bfc8cSTamas Berghammer         }
2508783bfc8cSTamas Berghammer 
2509b9c1b51eSKate Stone         if (maps_columns[5] == file_name) {
2510783bfc8cSTamas Berghammer           StringExtractor addr_extractor(maps_columns[0].str().c_str());
2511783bfc8cSTamas Berghammer           load_addr = addr_extractor.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2512783bfc8cSTamas Berghammer 
2513783bfc8cSTamas Berghammer           // Return false to stop reading the proc file further
2514783bfc8cSTamas Berghammer           return false;
2515783bfc8cSTamas Berghammer         }
2516783bfc8cSTamas Berghammer 
2517783bfc8cSTamas Berghammer         // Return true to continue reading the proc file
2518783bfc8cSTamas Berghammer         return true;
2519783bfc8cSTamas Berghammer       });
2520783bfc8cSTamas Berghammer   return error;
2521783bfc8cSTamas Berghammer }
2522783bfc8cSTamas Berghammer 
2523b9c1b51eSKate Stone NativeThreadLinuxSP NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {
2524b9c1b51eSKate Stone   return std::static_pointer_cast<NativeThreadLinux>(
2525b9c1b51eSKate Stone       NativeProcessProtocol::GetThreadByID(tid));
2526f9077782SPavel Labath }
2527f9077782SPavel Labath 
2528b9c1b51eSKate Stone Error NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,
2529b9c1b51eSKate Stone                                        lldb::StateType state, int signo) {
25305eb721edSPavel Labath   Log *const log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD);
25315eb721edSPavel Labath 
25321dbc6c9cSPavel Labath   if (log)
2533b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__,
2534b9c1b51eSKate Stone                 thread.GetID());
2535c076559aSPavel Labath 
2536c076559aSPavel Labath   // Before we do the resume below, first check if we have a pending
2537108c325dSPavel Labath   // stop notification that is currently waiting for
25380e1d729bSPavel Labath   // all threads to stop.  This is potentially a buggy situation since
2539c076559aSPavel Labath   // we're ostensibly waiting for threads to stop before we send out the
2540c076559aSPavel Labath   // pending notification, and here we are resuming one before we send
2541c076559aSPavel Labath   // out the pending stop notification.
2542b9c1b51eSKate Stone   if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID && log) {
2543b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s about to resume tid %" PRIu64
2544b9c1b51eSKate Stone                 " per explicit request but we have a pending stop notification "
2545b9c1b51eSKate Stone                 "(tid %" PRIu64 ") that is actively waiting for this thread to "
2546b9c1b51eSKate Stone                                 "stop. Valid sequence of events?",
2547b9c1b51eSKate Stone                 __FUNCTION__, thread.GetID(), m_pending_notification_tid);
2548c076559aSPavel Labath   }
2549c076559aSPavel Labath 
2550c076559aSPavel Labath   // Request a resume.  We expect this to be synchronous and the system
2551c076559aSPavel Labath   // to reflect it is running after this completes.
2552b9c1b51eSKate Stone   switch (state) {
2553b9c1b51eSKate Stone   case eStateRunning: {
2554605b51b8SPavel Labath     const auto resume_result = thread.Resume(signo);
25550e1d729bSPavel Labath     if (resume_result.Success())
25560e1d729bSPavel Labath       SetState(eStateRunning, true);
25570e1d729bSPavel Labath     return resume_result;
2558c076559aSPavel Labath   }
2559b9c1b51eSKate Stone   case eStateStepping: {
2560605b51b8SPavel Labath     const auto step_result = thread.SingleStep(signo);
25610e1d729bSPavel Labath     if (step_result.Success())
25620e1d729bSPavel Labath       SetState(eStateRunning, true);
25630e1d729bSPavel Labath     return step_result;
25640e1d729bSPavel Labath   }
25650e1d729bSPavel Labath   default:
25660e1d729bSPavel Labath     if (log)
2567b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s Unhandled state %s.", __FUNCTION__,
2568b9c1b51eSKate Stone                   StateAsCString(state));
25690e1d729bSPavel Labath     llvm_unreachable("Unhandled state for resume");
25700e1d729bSPavel Labath   }
2571c076559aSPavel Labath }
2572c076559aSPavel Labath 
2573c076559aSPavel Labath //===----------------------------------------------------------------------===//
2574c076559aSPavel Labath 
2575b9c1b51eSKate Stone void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {
25765eb721edSPavel Labath   Log *const log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD);
2577c076559aSPavel Labath 
2578b9c1b51eSKate Stone   if (log) {
2579b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s about to process event: "
2580b9c1b51eSKate Stone                 "(triggering_tid: %" PRIu64 ")",
2581c076559aSPavel Labath                 __FUNCTION__, triggering_tid);
2582c076559aSPavel Labath   }
2583c076559aSPavel Labath 
25840e1d729bSPavel Labath   m_pending_notification_tid = triggering_tid;
25850e1d729bSPavel Labath 
25860e1d729bSPavel Labath   // Request a stop for all the thread stops that need to be stopped
25870e1d729bSPavel Labath   // and are not already known to be stopped.
2588b9c1b51eSKate Stone   for (const auto &thread_sp : m_threads) {
25890e1d729bSPavel Labath     if (StateIsRunningState(thread_sp->GetState()))
25900e1d729bSPavel Labath       static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
25910e1d729bSPavel Labath   }
25920e1d729bSPavel Labath 
25930e1d729bSPavel Labath   SignalIfAllThreadsStopped();
2594c076559aSPavel Labath 
2595b9c1b51eSKate Stone   if (log) {
25965eb721edSPavel Labath     log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
2597c076559aSPavel Labath   }
2598c076559aSPavel Labath }
2599c076559aSPavel Labath 
2600b9c1b51eSKate Stone void NativeProcessLinux::SignalIfAllThreadsStopped() {
26010e1d729bSPavel Labath   if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
26020e1d729bSPavel Labath     return; // No pending notification. Nothing to do.
26030e1d729bSPavel Labath 
2604b9c1b51eSKate Stone   for (const auto &thread_sp : m_threads) {
26050e1d729bSPavel Labath     if (StateIsRunningState(thread_sp->GetState()))
26060e1d729bSPavel Labath       return; // Some threads are still running. Don't signal yet.
26070e1d729bSPavel Labath   }
26080e1d729bSPavel Labath 
26090e1d729bSPavel Labath   // We have a pending notification and all threads have stopped.
2610b9c1b51eSKate Stone   Log *log(
2611b9c1b51eSKate Stone       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
26129eb1ecb9SPavel Labath 
2613b9c1b51eSKate Stone   // Clear any temporary breakpoints we used to implement software single
2614b9c1b51eSKate Stone   // stepping.
2615b9c1b51eSKate Stone   for (const auto &thread_info : m_threads_stepping_with_breakpoint) {
26169eb1ecb9SPavel Labath     Error error = RemoveBreakpoint(thread_info.second);
26179eb1ecb9SPavel Labath     if (error.Fail())
26189eb1ecb9SPavel Labath       if (log)
2619b9c1b51eSKate Stone         log->Printf("NativeProcessLinux::%s() pid = %" PRIu64
2620b9c1b51eSKate Stone                     " remove stepping breakpoint: %s",
26219eb1ecb9SPavel Labath                     __FUNCTION__, thread_info.first, error.AsCString());
26229eb1ecb9SPavel Labath   }
26239eb1ecb9SPavel Labath   m_threads_stepping_with_breakpoint.clear();
26249eb1ecb9SPavel Labath 
26259eb1ecb9SPavel Labath   // Notify the delegate about the stop
26260e1d729bSPavel Labath   SetCurrentThreadID(m_pending_notification_tid);
2627ed89c7feSPavel Labath   SetState(StateType::eStateStopped, true);
26280e1d729bSPavel Labath   m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
2629c076559aSPavel Labath }
2630c076559aSPavel Labath 
2631b9c1b51eSKate Stone void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {
26321dbc6c9cSPavel Labath   Log *const log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD);
26331dbc6c9cSPavel Labath 
26341dbc6c9cSPavel Labath   if (log)
2635b9c1b51eSKate Stone     log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__,
2636b9c1b51eSKate Stone                 thread.GetID());
26371dbc6c9cSPavel Labath 
2638b9c1b51eSKate Stone   if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID &&
2639b9c1b51eSKate Stone       StateIsRunningState(thread.GetState())) {
2640b9c1b51eSKate Stone     // We will need to wait for this new thread to stop as well before firing
2641b9c1b51eSKate Stone     // the
2642c076559aSPavel Labath     // notification.
2643f9077782SPavel Labath     thread.RequestStop();
2644c076559aSPavel Labath   }
2645c076559aSPavel Labath }
2646068f8a7eSTamas Berghammer 
2647b9c1b51eSKate Stone void NativeProcessLinux::SigchldHandler() {
264819cbe96aSPavel Labath   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
264919cbe96aSPavel Labath   // Process all pending waitpid notifications.
2650b9c1b51eSKate Stone   while (true) {
265119cbe96aSPavel Labath     int status = -1;
265219cbe96aSPavel Labath     ::pid_t wait_pid = waitpid(-1, &status, __WALL | __WNOTHREAD | WNOHANG);
265319cbe96aSPavel Labath 
265419cbe96aSPavel Labath     if (wait_pid == 0)
265519cbe96aSPavel Labath       break; // We are done.
265619cbe96aSPavel Labath 
2657b9c1b51eSKate Stone     if (wait_pid == -1) {
265819cbe96aSPavel Labath       if (errno == EINTR)
265919cbe96aSPavel Labath         continue;
266019cbe96aSPavel Labath 
266119cbe96aSPavel Labath       Error error(errno, eErrorTypePOSIX);
266219cbe96aSPavel Labath       if (log)
2663b9c1b51eSKate Stone         log->Printf("NativeProcessLinux::%s waitpid (-1, &status, __WALL | "
2664b9c1b51eSKate Stone                     "__WNOTHREAD | WNOHANG) failed: %s",
266519cbe96aSPavel Labath                     __FUNCTION__, error.AsCString());
266619cbe96aSPavel Labath       break;
266719cbe96aSPavel Labath     }
266819cbe96aSPavel Labath 
266919cbe96aSPavel Labath     bool exited = false;
267019cbe96aSPavel Labath     int signal = 0;
267119cbe96aSPavel Labath     int exit_status = 0;
267219cbe96aSPavel Labath     const char *status_cstr = nullptr;
2673b9c1b51eSKate Stone     if (WIFSTOPPED(status)) {
267419cbe96aSPavel Labath       signal = WSTOPSIG(status);
267519cbe96aSPavel Labath       status_cstr = "STOPPED";
2676b9c1b51eSKate Stone     } else if (WIFEXITED(status)) {
267719cbe96aSPavel Labath       exit_status = WEXITSTATUS(status);
267819cbe96aSPavel Labath       status_cstr = "EXITED";
267919cbe96aSPavel Labath       exited = true;
2680b9c1b51eSKate Stone     } else if (WIFSIGNALED(status)) {
268119cbe96aSPavel Labath       signal = WTERMSIG(status);
268219cbe96aSPavel Labath       status_cstr = "SIGNALED";
268319cbe96aSPavel Labath       if (wait_pid == static_cast<::pid_t>(GetID())) {
268419cbe96aSPavel Labath         exited = true;
268519cbe96aSPavel Labath         exit_status = -1;
268619cbe96aSPavel Labath       }
2687b9c1b51eSKate Stone     } else
268819cbe96aSPavel Labath       status_cstr = "(\?\?\?)";
268919cbe96aSPavel Labath 
269019cbe96aSPavel Labath     if (log)
2691b9c1b51eSKate Stone       log->Printf("NativeProcessLinux::%s: waitpid (-1, &status, __WALL | "
2692b9c1b51eSKate Stone                   "__WNOTHREAD | WNOHANG)"
2693b9c1b51eSKate Stone                   "=> pid = %" PRIi32
2694b9c1b51eSKate Stone                   ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
2695b9c1b51eSKate Stone                   __FUNCTION__, wait_pid, status, status_cstr, signal,
2696b9c1b51eSKate Stone                   exit_status);
269719cbe96aSPavel Labath 
269819cbe96aSPavel Labath     MonitorCallback(wait_pid, exited, signal, exit_status);
269919cbe96aSPavel Labath   }
2700068f8a7eSTamas Berghammer }
2701068f8a7eSTamas Berghammer 
2702068f8a7eSTamas Berghammer // Wrapper for ptrace to catch errors and log calls.
2703b9c1b51eSKate Stone // Note that ptrace sets errno on error because -1 can be a valid result (i.e.
2704b9c1b51eSKate Stone // for PTRACE_PEEK*)
2705b9c1b51eSKate Stone Error NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
2706b9c1b51eSKate Stone                                         void *data, size_t data_size,
2707b9c1b51eSKate Stone                                         long *result) {
27084a9babb2SPavel Labath   Error error;
27094a9babb2SPavel Labath   long int ret;
2710068f8a7eSTamas Berghammer 
2711068f8a7eSTamas Berghammer   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2712068f8a7eSTamas Berghammer 
2713068f8a7eSTamas Berghammer   PtraceDisplayBytes(req, data, data_size);
2714068f8a7eSTamas Berghammer 
2715068f8a7eSTamas Berghammer   errno = 0;
2716068f8a7eSTamas Berghammer   if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
2717b9c1b51eSKate Stone     ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2718b9c1b51eSKate Stone                  *(unsigned int *)addr, data);
2719068f8a7eSTamas Berghammer   else
2720b9c1b51eSKate Stone     ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2721b9c1b51eSKate Stone                  addr, data);
2722068f8a7eSTamas Berghammer 
27234a9babb2SPavel Labath   if (ret == -1)
2724068f8a7eSTamas Berghammer     error.SetErrorToErrno();
2725068f8a7eSTamas Berghammer 
27264a9babb2SPavel Labath   if (result)
27274a9babb2SPavel Labath     *result = ret;
27284a9babb2SPavel Labath 
2729068f8a7eSTamas Berghammer   if (log)
2730b9c1b51eSKate Stone     log->Printf("ptrace(%d, %" PRIu64 ", %p, %p, %zu)=%lX", req, pid, addr,
2731b9c1b51eSKate Stone                 data, data_size, ret);
2732068f8a7eSTamas Berghammer 
2733068f8a7eSTamas Berghammer   PtraceDisplayBytes(req, data, data_size);
2734068f8a7eSTamas Berghammer 
2735b9c1b51eSKate Stone   if (log && error.GetError() != 0) {
2736068f8a7eSTamas Berghammer     const char *str;
2737b9c1b51eSKate Stone     switch (error.GetError()) {
2738b9c1b51eSKate Stone     case ESRCH:
2739b9c1b51eSKate Stone       str = "ESRCH";
2740b9c1b51eSKate Stone       break;
2741b9c1b51eSKate Stone     case EINVAL:
2742b9c1b51eSKate Stone       str = "EINVAL";
2743b9c1b51eSKate Stone       break;
2744b9c1b51eSKate Stone     case EBUSY:
2745b9c1b51eSKate Stone       str = "EBUSY";
2746b9c1b51eSKate Stone       break;
2747b9c1b51eSKate Stone     case EPERM:
2748b9c1b51eSKate Stone       str = "EPERM";
2749b9c1b51eSKate Stone       break;
2750b9c1b51eSKate Stone     default:
2751b9c1b51eSKate Stone       str = error.AsCString();
2752068f8a7eSTamas Berghammer     }
2753068f8a7eSTamas Berghammer     log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
2754068f8a7eSTamas Berghammer   }
2755068f8a7eSTamas Berghammer 
27564a9babb2SPavel Labath   return error;
2757068f8a7eSTamas Berghammer }
2758