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 "lldb/lldb-python.h"
11af245d11STodd Fiala 
12af245d11STodd Fiala #include "NativeProcessLinux.h"
13af245d11STodd Fiala 
14af245d11STodd Fiala // C Includes
15af245d11STodd Fiala #include <errno.h>
16af245d11STodd Fiala #include <poll.h>
17af245d11STodd Fiala #include <string.h>
18af245d11STodd Fiala #include <stdint.h>
19af245d11STodd Fiala #include <unistd.h>
20af245d11STodd Fiala 
21af245d11STodd Fiala // C++ Includes
22af245d11STodd Fiala #include <fstream>
23c076559aSPavel Labath #include <sstream>
24af245d11STodd Fiala #include <string>
25af245d11STodd Fiala 
26af245d11STodd Fiala // Other libraries and framework includes
27af245d11STodd Fiala #include "lldb/Core/Debugger.h"
28d8c338d4STamas Berghammer #include "lldb/Core/EmulateInstruction.h"
29af245d11STodd Fiala #include "lldb/Core/Error.h"
30af245d11STodd Fiala #include "lldb/Core/Module.h"
316edef204SOleksiy Vyalov #include "lldb/Core/ModuleSpec.h"
32af245d11STodd Fiala #include "lldb/Core/RegisterValue.h"
33af245d11STodd Fiala #include "lldb/Core/Scalar.h"
34af245d11STodd Fiala #include "lldb/Core/State.h"
351e209fccSTamas Berghammer #include "lldb/Host/common/NativeBreakpoint.h"
360cbf0b13STamas Berghammer #include "lldb/Host/common/NativeRegisterContext.h"
37af245d11STodd Fiala #include "lldb/Host/Host.h"
3813b18261SZachary Turner #include "lldb/Host/HostInfo.h"
390cbf0b13STamas Berghammer #include "lldb/Host/HostNativeThread.h"
4039de3110SZachary Turner #include "lldb/Host/ThreadLauncher.h"
41af245d11STodd Fiala #include "lldb/Symbol/ObjectFile.h"
4290aff47cSZachary Turner #include "lldb/Target/Process.h"
43af245d11STodd Fiala #include "lldb/Target/ProcessLaunchInfo.h"
44c16f5dcaSChaoren Lin #include "lldb/Utility/LLDBAssert.h"
45af245d11STodd Fiala #include "lldb/Utility/PseudoTerminal.h"
46af245d11STodd Fiala 
471e209fccSTamas Berghammer #include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
48af245d11STodd Fiala #include "Plugins/Process/Utility/LinuxSignals.h"
491e209fccSTamas Berghammer #include "Utility/StringExtractor.h"
50af245d11STodd Fiala #include "NativeThreadLinux.h"
51af245d11STodd Fiala #include "ProcFileReader.h"
521e209fccSTamas Berghammer #include "Procfs.h"
53cacde7dfSTodd Fiala 
54d858487eSTamas Berghammer // System includes - They have to be included after framework includes because they define some
55d858487eSTamas Berghammer // macros which collide with variable names in other modules
56d858487eSTamas Berghammer #include <linux/unistd.h>
57d858487eSTamas Berghammer #include <sys/socket.h>
58*8b335671SVince Harron 
59d858487eSTamas Berghammer #include <sys/types.h>
60d858487eSTamas Berghammer #include <sys/uio.h>
61d858487eSTamas Berghammer #include <sys/user.h>
62d858487eSTamas Berghammer #include <sys/wait.h>
63d858487eSTamas Berghammer 
641e209fccSTamas Berghammer #if defined (__arm64__) || defined (__aarch64__)
651e209fccSTamas Berghammer // NT_PRSTATUS and NT_FPREGSET definition
661e209fccSTamas Berghammer #include <elf.h>
671e209fccSTamas Berghammer #endif
681e209fccSTamas Berghammer 
69*8b335671SVince Harron #include "lldb/Host/linux/Personality.h"
70*8b335671SVince Harron #include "lldb/Host/linux/Ptrace.h"
71*8b335671SVince Harron #include "lldb/Host/linux/Signalfd.h"
72*8b335671SVince Harron #include "lldb/Host/android/Android.h"
73af245d11STodd Fiala 
740bce1b67STodd Fiala #define LLDB_PERSONALITY_GET_CURRENT_SETTINGS  0xffffffff
75af245d11STodd Fiala 
76af245d11STodd Fiala // Support hardware breakpoints in case it has not been defined
77af245d11STodd Fiala #ifndef TRAP_HWBKPT
78af245d11STodd Fiala   #define TRAP_HWBKPT 4
79af245d11STodd Fiala #endif
80af245d11STodd Fiala 
81af245d11STodd Fiala // We disable the tracing of ptrace calls for integration builds to
82af245d11STodd Fiala // avoid the additional indirection and checks.
83af245d11STodd Fiala #ifndef LLDB_CONFIGURATION_BUILDANDINTEGRATION
8497ccc294SChaoren Lin #define PTRACE(req, pid, addr, data, data_size, error) \
8597ccc294SChaoren Lin     PtraceWrapper((req), (pid), (addr), (data), (data_size), (error), #req, __FILE__, __LINE__)
86af245d11STodd Fiala #else
8797ccc294SChaoren Lin #define PTRACE(req, pid, addr, data, data_size, error) \
8897ccc294SChaoren Lin     PtraceWrapper((req), (pid), (addr), (data), (data_size), (error))
89af245d11STodd Fiala #endif
90af245d11STodd Fiala 
917cb18bf5STamas Berghammer using namespace lldb;
927cb18bf5STamas Berghammer using namespace lldb_private;
93db264a6dSTamas Berghammer using namespace lldb_private::process_linux;
947cb18bf5STamas Berghammer using namespace llvm;
957cb18bf5STamas Berghammer 
96af245d11STodd Fiala // Private bits we only need internally.
97af245d11STodd Fiala namespace
98af245d11STodd Fiala {
99af245d11STodd Fiala     const UnixSignals&
100af245d11STodd Fiala     GetUnixSignals ()
101af245d11STodd Fiala     {
102af245d11STodd Fiala         static process_linux::LinuxSignals signals;
103af245d11STodd Fiala         return signals;
104af245d11STodd Fiala     }
105af245d11STodd Fiala 
106af245d11STodd Fiala     Error
107af245d11STodd Fiala     ResolveProcessArchitecture (lldb::pid_t pid, Platform &platform, ArchSpec &arch)
108af245d11STodd Fiala     {
109af245d11STodd Fiala         // Grab process info for the running process.
110af245d11STodd Fiala         ProcessInstanceInfo process_info;
111af245d11STodd Fiala         if (!platform.GetProcessInfo (pid, process_info))
112db264a6dSTamas Berghammer             return Error("failed to get process info");
113af245d11STodd Fiala 
114af245d11STodd Fiala         // Resolve the executable module.
115af245d11STodd Fiala         ModuleSP exe_module_sp;
116e56f6dceSChaoren Lin         ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
117af245d11STodd Fiala         FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths ());
118af245d11STodd Fiala         Error error = platform.ResolveExecutable(
11954539338SOleksiy Vyalov             exe_module_spec,
120af245d11STodd Fiala             exe_module_sp,
121af245d11STodd Fiala             executable_search_paths.GetSize () ? &executable_search_paths : NULL);
122af245d11STodd Fiala 
123af245d11STodd Fiala         if (!error.Success ())
124af245d11STodd Fiala             return error;
125af245d11STodd Fiala 
126af245d11STodd Fiala         // Check if we've got our architecture from the exe_module.
127af245d11STodd Fiala         arch = exe_module_sp->GetArchitecture ();
128af245d11STodd Fiala         if (arch.IsValid ())
129af245d11STodd Fiala             return Error();
130af245d11STodd Fiala         else
131af245d11STodd Fiala             return Error("failed to retrieve a valid architecture from the exe module");
132af245d11STodd Fiala     }
133af245d11STodd Fiala 
134af245d11STodd Fiala     void
135db264a6dSTamas Berghammer     DisplayBytes (StreamString &s, void *bytes, uint32_t count)
136af245d11STodd Fiala     {
137af245d11STodd Fiala         uint8_t *ptr = (uint8_t *)bytes;
138af245d11STodd Fiala         const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
139af245d11STodd Fiala         for(uint32_t i=0; i<loop_count; i++)
140af245d11STodd Fiala         {
141af245d11STodd Fiala             s.Printf ("[%x]", *ptr);
142af245d11STodd Fiala             ptr++;
143af245d11STodd Fiala         }
144af245d11STodd Fiala     }
145af245d11STodd Fiala 
146af245d11STodd Fiala     void
147af245d11STodd Fiala     PtraceDisplayBytes(int &req, void *data, size_t data_size)
148af245d11STodd Fiala     {
149af245d11STodd Fiala         StreamString buf;
150af245d11STodd Fiala         Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
151af245d11STodd Fiala                     POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
152af245d11STodd Fiala 
153af245d11STodd Fiala         if (verbose_log)
154af245d11STodd Fiala         {
155af245d11STodd Fiala             switch(req)
156af245d11STodd Fiala             {
157af245d11STodd Fiala             case PTRACE_POKETEXT:
158af245d11STodd Fiala             {
159af245d11STodd Fiala                 DisplayBytes(buf, &data, 8);
160af245d11STodd Fiala                 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
161af245d11STodd Fiala                 break;
162af245d11STodd Fiala             }
163af245d11STodd Fiala             case PTRACE_POKEDATA:
164af245d11STodd Fiala             {
165af245d11STodd Fiala                 DisplayBytes(buf, &data, 8);
166af245d11STodd Fiala                 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
167af245d11STodd Fiala                 break;
168af245d11STodd Fiala             }
169af245d11STodd Fiala             case PTRACE_POKEUSER:
170af245d11STodd Fiala             {
171af245d11STodd Fiala                 DisplayBytes(buf, &data, 8);
172af245d11STodd Fiala                 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
173af245d11STodd Fiala                 break;
174af245d11STodd Fiala             }
175af245d11STodd Fiala             case PTRACE_SETREGS:
176af245d11STodd Fiala             {
177af245d11STodd Fiala                 DisplayBytes(buf, data, data_size);
178af245d11STodd Fiala                 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
179af245d11STodd Fiala                 break;
180af245d11STodd Fiala             }
181af245d11STodd Fiala             case PTRACE_SETFPREGS:
182af245d11STodd Fiala             {
183af245d11STodd Fiala                 DisplayBytes(buf, data, data_size);
184af245d11STodd Fiala                 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
185af245d11STodd Fiala                 break;
186af245d11STodd Fiala             }
187af245d11STodd Fiala             case PTRACE_SETSIGINFO:
188af245d11STodd Fiala             {
189af245d11STodd Fiala                 DisplayBytes(buf, data, sizeof(siginfo_t));
190af245d11STodd Fiala                 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
191af245d11STodd Fiala                 break;
192af245d11STodd Fiala             }
193af245d11STodd Fiala             case PTRACE_SETREGSET:
194af245d11STodd Fiala             {
195af245d11STodd Fiala                 // Extract iov_base from data, which is a pointer to the struct IOVEC
196af245d11STodd Fiala                 DisplayBytes(buf, *(void **)data, data_size);
197af245d11STodd Fiala                 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
198af245d11STodd Fiala                 break;
199af245d11STodd Fiala             }
200af245d11STodd Fiala             default:
201af245d11STodd Fiala             {
202af245d11STodd Fiala             }
203af245d11STodd Fiala             }
204af245d11STodd Fiala         }
205af245d11STodd Fiala     }
206af245d11STodd Fiala 
207af245d11STodd Fiala     // Wrapper for ptrace to catch errors and log calls.
208af245d11STodd Fiala     // Note that ptrace sets errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
209af245d11STodd Fiala     long
21097ccc294SChaoren Lin     PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, Error& error,
211af245d11STodd Fiala                   const char* reqName, const char* file, int line)
212af245d11STodd Fiala     {
213af245d11STodd Fiala         long int result;
214af245d11STodd Fiala 
215af245d11STodd Fiala         Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
216af245d11STodd Fiala 
217af245d11STodd Fiala         PtraceDisplayBytes(req, data, data_size);
218af245d11STodd Fiala 
21997ccc294SChaoren Lin         error.Clear();
220af245d11STodd Fiala         errno = 0;
221af245d11STodd Fiala         if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
222af245d11STodd Fiala             result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
223af245d11STodd Fiala         else
224af245d11STodd Fiala             result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
225af245d11STodd Fiala 
22697ccc294SChaoren Lin         if (result == -1)
22797ccc294SChaoren Lin             error.SetErrorToErrno();
22897ccc294SChaoren Lin 
229af245d11STodd Fiala         if (log)
230af245d11STodd Fiala             log->Printf("ptrace(%s, %" PRIu64 ", %p, %p, %zu)=%lX called from file %s line %d",
231af245d11STodd Fiala                     reqName, pid, addr, data, data_size, result, file, line);
232af245d11STodd Fiala 
233af245d11STodd Fiala         PtraceDisplayBytes(req, data, data_size);
234af245d11STodd Fiala 
23597ccc294SChaoren Lin         if (log && error.GetError() != 0)
236af245d11STodd Fiala         {
237af245d11STodd Fiala             const char* str;
23897ccc294SChaoren Lin             switch (error.GetError())
239af245d11STodd Fiala             {
240af245d11STodd Fiala             case ESRCH:  str = "ESRCH"; break;
241af245d11STodd Fiala             case EINVAL: str = "EINVAL"; break;
242af245d11STodd Fiala             case EBUSY:  str = "EBUSY"; break;
243af245d11STodd Fiala             case EPERM:  str = "EPERM"; break;
24497ccc294SChaoren Lin             default:     str = error.AsCString();
245af245d11STodd Fiala             }
24697ccc294SChaoren Lin             log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
247af245d11STodd Fiala         }
248af245d11STodd Fiala 
249af245d11STodd Fiala         return result;
250af245d11STodd Fiala     }
251af245d11STodd Fiala 
252af245d11STodd Fiala #ifdef LLDB_CONFIGURATION_BUILDANDINTEGRATION
253af245d11STodd Fiala     // Wrapper for ptrace when logging is not required.
254af245d11STodd Fiala     // Sets errno to 0 prior to calling ptrace.
255af245d11STodd Fiala     long
25697ccc294SChaoren Lin     PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, Error& error)
257af245d11STodd Fiala     {
258af245d11STodd Fiala         long result = 0;
25997ccc294SChaoren Lin 
26097ccc294SChaoren Lin         error.Clear();
261af245d11STodd Fiala         errno = 0;
262af245d11STodd Fiala         if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
263af245d11STodd Fiala             result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
264af245d11STodd Fiala         else
265af245d11STodd Fiala             result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
26697ccc294SChaoren Lin 
26797ccc294SChaoren Lin         if (result == -1)
26897ccc294SChaoren Lin             error.SetErrorToErrno();
269af245d11STodd Fiala         return result;
270af245d11STodd Fiala     }
271af245d11STodd Fiala #endif
272af245d11STodd Fiala 
273af245d11STodd Fiala     //------------------------------------------------------------------------------
274af245d11STodd Fiala     // Static implementations of NativeProcessLinux::ReadMemory and
275af245d11STodd Fiala     // NativeProcessLinux::WriteMemory.  This enables mutual recursion between these
276af245d11STodd Fiala     // functions without needed to go thru the thread funnel.
277af245d11STodd Fiala 
2783eb4b458SChaoren Lin     size_t
279af245d11STodd Fiala     DoReadMemory(
280af245d11STodd Fiala         lldb::pid_t pid,
281af245d11STodd Fiala         lldb::addr_t vm_addr,
282af245d11STodd Fiala         void *buf,
2833eb4b458SChaoren Lin         size_t size,
284af245d11STodd Fiala         Error &error)
285af245d11STodd Fiala     {
286af245d11STodd Fiala         // ptrace word size is determined by the host, not the child
287af245d11STodd Fiala         static const unsigned word_size = sizeof(void*);
288af245d11STodd Fiala         unsigned char *dst = static_cast<unsigned char*>(buf);
2893eb4b458SChaoren Lin         size_t bytes_read;
2903eb4b458SChaoren Lin         size_t remainder;
291af245d11STodd Fiala         long data;
292af245d11STodd Fiala 
293af245d11STodd Fiala         Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
294af245d11STodd Fiala         if (log)
295af245d11STodd Fiala             ProcessPOSIXLog::IncNestLevel();
296af245d11STodd Fiala         if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
297af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
298af245d11STodd Fiala                     pid, word_size, (void*)vm_addr, buf, size);
299af245d11STodd Fiala 
300af245d11STodd Fiala         assert(sizeof(data) >= word_size);
301af245d11STodd Fiala         for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
302af245d11STodd Fiala         {
30397ccc294SChaoren Lin             data = PTRACE(PTRACE_PEEKDATA, pid, (void*)vm_addr, nullptr, 0, error);
30497ccc294SChaoren Lin             if (error.Fail())
305af245d11STodd Fiala             {
306af245d11STodd Fiala                 if (log)
307af245d11STodd Fiala                     ProcessPOSIXLog::DecNestLevel();
308af245d11STodd Fiala                 return bytes_read;
309af245d11STodd Fiala             }
310af245d11STodd Fiala 
311af245d11STodd Fiala             remainder = size - bytes_read;
312af245d11STodd Fiala             remainder = remainder > word_size ? word_size : remainder;
313af245d11STodd Fiala 
314af245d11STodd Fiala             // Copy the data into our buffer
315af245d11STodd Fiala             for (unsigned i = 0; i < remainder; ++i)
316af245d11STodd Fiala                 dst[i] = ((data >> i*8) & 0xFF);
317af245d11STodd Fiala 
318af245d11STodd Fiala             if (log && ProcessPOSIXLog::AtTopNestLevel() &&
319af245d11STodd Fiala                     (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
320af245d11STodd Fiala                             (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
321af245d11STodd Fiala                                     size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
322af245d11STodd Fiala             {
323af245d11STodd Fiala                 uintptr_t print_dst = 0;
324af245d11STodd Fiala                 // Format bytes from data by moving into print_dst for log output
325af245d11STodd Fiala                 for (unsigned i = 0; i < remainder; ++i)
326af245d11STodd Fiala                     print_dst |= (((data >> i*8) & 0xFF) << i*8);
327af245d11STodd Fiala                 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
328af245d11STodd Fiala                         (void*)vm_addr, print_dst, (unsigned long)data);
329af245d11STodd Fiala             }
330af245d11STodd Fiala 
331af245d11STodd Fiala             vm_addr += word_size;
332af245d11STodd Fiala             dst += word_size;
333af245d11STodd Fiala         }
334af245d11STodd Fiala 
335af245d11STodd Fiala         if (log)
336af245d11STodd Fiala             ProcessPOSIXLog::DecNestLevel();
337af245d11STodd Fiala         return bytes_read;
338af245d11STodd Fiala     }
339af245d11STodd Fiala 
3403eb4b458SChaoren Lin     size_t
341af245d11STodd Fiala     DoWriteMemory(
342af245d11STodd Fiala         lldb::pid_t pid,
343af245d11STodd Fiala         lldb::addr_t vm_addr,
344af245d11STodd Fiala         const void *buf,
3453eb4b458SChaoren Lin         size_t size,
346af245d11STodd Fiala         Error &error)
347af245d11STodd Fiala     {
348af245d11STodd Fiala         // ptrace word size is determined by the host, not the child
349af245d11STodd Fiala         static const unsigned word_size = sizeof(void*);
350af245d11STodd Fiala         const unsigned char *src = static_cast<const unsigned char*>(buf);
3513eb4b458SChaoren Lin         size_t bytes_written = 0;
3523eb4b458SChaoren Lin         size_t remainder;
353af245d11STodd Fiala 
354af245d11STodd Fiala         Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
355af245d11STodd Fiala         if (log)
356af245d11STodd Fiala             ProcessPOSIXLog::IncNestLevel();
357af245d11STodd Fiala         if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
358af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %u, %p, %p, %" PRIu64 ")", __FUNCTION__,
359af245d11STodd Fiala                     pid, word_size, (void*)vm_addr, buf, size);
360af245d11STodd Fiala 
361af245d11STodd Fiala         for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
362af245d11STodd Fiala         {
363af245d11STodd Fiala             remainder = size - bytes_written;
364af245d11STodd Fiala             remainder = remainder > word_size ? word_size : remainder;
365af245d11STodd Fiala 
366af245d11STodd Fiala             if (remainder == word_size)
367af245d11STodd Fiala             {
368af245d11STodd Fiala                 unsigned long data = 0;
369af245d11STodd Fiala                 assert(sizeof(data) >= word_size);
370af245d11STodd Fiala                 for (unsigned i = 0; i < word_size; ++i)
371af245d11STodd Fiala                     data |= (unsigned long)src[i] << i*8;
372af245d11STodd Fiala 
373af245d11STodd Fiala                 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
374af245d11STodd Fiala                         (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
375af245d11STodd Fiala                                 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
376af245d11STodd Fiala                                         size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
377af245d11STodd Fiala                     log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
3781e209fccSTamas Berghammer                             (void*)vm_addr, *(const unsigned long*)src, data);
379af245d11STodd Fiala 
38097ccc294SChaoren Lin                 if (PTRACE(PTRACE_POKEDATA, pid, (void*)vm_addr, (void*)data, 0, error))
381af245d11STodd Fiala                 {
382af245d11STodd Fiala                     if (log)
383af245d11STodd Fiala                         ProcessPOSIXLog::DecNestLevel();
384af245d11STodd Fiala                     return bytes_written;
385af245d11STodd Fiala                 }
386af245d11STodd Fiala             }
387af245d11STodd Fiala             else
388af245d11STodd Fiala             {
389af245d11STodd Fiala                 unsigned char buff[8];
390af245d11STodd Fiala                 if (DoReadMemory(pid, vm_addr,
391af245d11STodd Fiala                                 buff, word_size, error) != word_size)
392af245d11STodd Fiala                 {
393af245d11STodd Fiala                     if (log)
394af245d11STodd Fiala                         ProcessPOSIXLog::DecNestLevel();
395af245d11STodd Fiala                     return bytes_written;
396af245d11STodd Fiala                 }
397af245d11STodd Fiala 
398af245d11STodd Fiala                 memcpy(buff, src, remainder);
399af245d11STodd Fiala 
400af245d11STodd Fiala                 if (DoWriteMemory(pid, vm_addr,
401af245d11STodd Fiala                                 buff, word_size, error) != word_size)
402af245d11STodd Fiala                 {
403af245d11STodd Fiala                     if (log)
404af245d11STodd Fiala                         ProcessPOSIXLog::DecNestLevel();
405af245d11STodd Fiala                     return bytes_written;
406af245d11STodd Fiala                 }
407af245d11STodd Fiala 
408af245d11STodd Fiala                 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
409af245d11STodd Fiala                         (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
410af245d11STodd Fiala                                 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
411af245d11STodd Fiala                                         size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
412af245d11STodd Fiala                     log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
4131e209fccSTamas Berghammer                             (void*)vm_addr, *(const unsigned long*)src, *(unsigned long*)buff);
414af245d11STodd Fiala             }
415af245d11STodd Fiala 
416af245d11STodd Fiala             vm_addr += word_size;
417af245d11STodd Fiala             src += word_size;
418af245d11STodd Fiala         }
419af245d11STodd Fiala         if (log)
420af245d11STodd Fiala             ProcessPOSIXLog::DecNestLevel();
421af245d11STodd Fiala         return bytes_written;
422af245d11STodd Fiala     }
423af245d11STodd Fiala 
424af245d11STodd Fiala     //------------------------------------------------------------------------------
425af245d11STodd Fiala     /// @class Operation
426af245d11STodd Fiala     /// @brief Represents a NativeProcessLinux operation.
427af245d11STodd Fiala     ///
428af245d11STodd Fiala     /// Under Linux, it is not possible to ptrace() from any other thread but the
429af245d11STodd Fiala     /// one that spawned or attached to the process from the start.  Therefore, when
430af245d11STodd Fiala     /// a NativeProcessLinux is asked to deliver or change the state of an inferior
431af245d11STodd Fiala     /// process the operation must be "funneled" to a specific thread to perform the
432af245d11STodd Fiala     /// task.  The Operation class provides an abstract base for all services the
433af245d11STodd Fiala     /// NativeProcessLinux must perform via the single virtual function Execute, thus
434af245d11STodd Fiala     /// encapsulating the code that needs to run in the privileged context.
435af245d11STodd Fiala     class Operation
436af245d11STodd Fiala     {
437af245d11STodd Fiala     public:
438af245d11STodd Fiala         Operation () : m_error() { }
439af245d11STodd Fiala 
440af245d11STodd Fiala         virtual
441af245d11STodd Fiala         ~Operation() {}
442af245d11STodd Fiala 
443af245d11STodd Fiala         virtual void
444af245d11STodd Fiala         Execute (NativeProcessLinux *process) = 0;
445af245d11STodd Fiala 
446af245d11STodd Fiala         const Error &
447af245d11STodd Fiala         GetError () const { return m_error; }
448af245d11STodd Fiala 
449af245d11STodd Fiala     protected:
450af245d11STodd Fiala         Error m_error;
451af245d11STodd Fiala     };
452af245d11STodd Fiala 
453af245d11STodd Fiala     //------------------------------------------------------------------------------
454af245d11STodd Fiala     /// @class ReadOperation
455af245d11STodd Fiala     /// @brief Implements NativeProcessLinux::ReadMemory.
456af245d11STodd Fiala     class ReadOperation : public Operation
457af245d11STodd Fiala     {
458af245d11STodd Fiala     public:
459af245d11STodd Fiala         ReadOperation(
460af245d11STodd Fiala             lldb::addr_t addr,
461af245d11STodd Fiala             void *buff,
4623eb4b458SChaoren Lin             size_t size,
4633eb4b458SChaoren Lin             size_t &result) :
464af245d11STodd Fiala             Operation (),
465af245d11STodd Fiala             m_addr (addr),
466af245d11STodd Fiala             m_buff (buff),
467af245d11STodd Fiala             m_size (size),
468af245d11STodd Fiala             m_result (result)
469af245d11STodd Fiala             {
470af245d11STodd Fiala             }
471af245d11STodd Fiala 
472af245d11STodd Fiala         void Execute (NativeProcessLinux *process) override;
473af245d11STodd Fiala 
474af245d11STodd Fiala     private:
475af245d11STodd Fiala         lldb::addr_t m_addr;
476af245d11STodd Fiala         void *m_buff;
4773eb4b458SChaoren Lin         size_t m_size;
4783eb4b458SChaoren Lin         size_t &m_result;
479af245d11STodd Fiala     };
480af245d11STodd Fiala 
481af245d11STodd Fiala     void
482af245d11STodd Fiala     ReadOperation::Execute (NativeProcessLinux *process)
483af245d11STodd Fiala     {
484af245d11STodd Fiala         m_result = DoReadMemory (process->GetID (), m_addr, m_buff, m_size, m_error);
485af245d11STodd Fiala     }
486af245d11STodd Fiala 
487af245d11STodd Fiala     //------------------------------------------------------------------------------
488af245d11STodd Fiala     /// @class WriteOperation
489af245d11STodd Fiala     /// @brief Implements NativeProcessLinux::WriteMemory.
490af245d11STodd Fiala     class WriteOperation : public Operation
491af245d11STodd Fiala     {
492af245d11STodd Fiala     public:
493af245d11STodd Fiala         WriteOperation(
494af245d11STodd Fiala             lldb::addr_t addr,
495af245d11STodd Fiala             const void *buff,
4963eb4b458SChaoren Lin             size_t size,
4973eb4b458SChaoren Lin             size_t &result) :
498af245d11STodd Fiala             Operation (),
499af245d11STodd Fiala             m_addr (addr),
500af245d11STodd Fiala             m_buff (buff),
501af245d11STodd Fiala             m_size (size),
502af245d11STodd Fiala             m_result (result)
503af245d11STodd Fiala             {
504af245d11STodd Fiala             }
505af245d11STodd Fiala 
506af245d11STodd Fiala         void Execute (NativeProcessLinux *process) override;
507af245d11STodd Fiala 
508af245d11STodd Fiala     private:
509af245d11STodd Fiala         lldb::addr_t m_addr;
510af245d11STodd Fiala         const void *m_buff;
5113eb4b458SChaoren Lin         size_t m_size;
5123eb4b458SChaoren Lin         size_t &m_result;
513af245d11STodd Fiala     };
514af245d11STodd Fiala 
515af245d11STodd Fiala     void
516af245d11STodd Fiala     WriteOperation::Execute(NativeProcessLinux *process)
517af245d11STodd Fiala     {
518af245d11STodd Fiala         m_result = DoWriteMemory (process->GetID (), m_addr, m_buff, m_size, m_error);
519af245d11STodd Fiala     }
520af245d11STodd Fiala 
521af245d11STodd Fiala     //------------------------------------------------------------------------------
522af245d11STodd Fiala     /// @class ReadRegOperation
523af245d11STodd Fiala     /// @brief Implements NativeProcessLinux::ReadRegisterValue.
524af245d11STodd Fiala     class ReadRegOperation : public Operation
525af245d11STodd Fiala     {
526af245d11STodd Fiala     public:
527af245d11STodd Fiala         ReadRegOperation(lldb::tid_t tid, uint32_t offset, const char *reg_name,
52897ccc294SChaoren Lin                 RegisterValue &value)
52997ccc294SChaoren Lin             : m_tid(tid),
53097ccc294SChaoren Lin               m_offset(static_cast<uintptr_t> (offset)),
53197ccc294SChaoren Lin               m_reg_name(reg_name),
53297ccc294SChaoren Lin               m_value(value)
533af245d11STodd Fiala             { }
534af245d11STodd Fiala 
535d542efdeSTamas Berghammer         void Execute(NativeProcessLinux *monitor) override;
536af245d11STodd Fiala 
537af245d11STodd Fiala     private:
538af245d11STodd Fiala         lldb::tid_t m_tid;
539af245d11STodd Fiala         uintptr_t m_offset;
540af245d11STodd Fiala         const char *m_reg_name;
541af245d11STodd Fiala         RegisterValue &m_value;
542af245d11STodd Fiala     };
543af245d11STodd Fiala 
544af245d11STodd Fiala     void
545af245d11STodd Fiala     ReadRegOperation::Execute(NativeProcessLinux *monitor)
546af245d11STodd Fiala     {
5470fceef80STodd Fiala #if defined (__arm64__) || defined (__aarch64__)
5480fceef80STodd Fiala         if (m_offset > sizeof(struct user_pt_regs))
5490fceef80STodd Fiala         {
5500fceef80STodd Fiala             uintptr_t offset = m_offset - sizeof(struct user_pt_regs);
5510fceef80STodd Fiala             if (offset > sizeof(struct user_fpsimd_state))
5520fceef80STodd Fiala             {
55397ccc294SChaoren Lin                 m_error.SetErrorString("invalid offset value");
55497ccc294SChaoren Lin                 return;
5550fceef80STodd Fiala             }
5560fceef80STodd Fiala             elf_fpregset_t regs;
5570fceef80STodd Fiala             int regset = NT_FPREGSET;
5580fceef80STodd Fiala             struct iovec ioVec;
5590fceef80STodd Fiala 
5600fceef80STodd Fiala             ioVec.iov_base = &regs;
5610fceef80STodd Fiala             ioVec.iov_len = sizeof regs;
56297ccc294SChaoren Lin             PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
56397ccc294SChaoren Lin             if (m_error.Success())
5640fceef80STodd Fiala             {
565db264a6dSTamas Berghammer                 ArchSpec arch;
5660fceef80STodd Fiala                 if (monitor->GetArchitecture(arch))
5670fceef80STodd Fiala                     m_value.SetBytes((void *)(((unsigned char *)(&regs)) + offset), 16, arch.GetByteOrder());
5680fceef80STodd Fiala                 else
56997ccc294SChaoren Lin                     m_error.SetErrorString("failed to get architecture");
5700fceef80STodd Fiala             }
5710fceef80STodd Fiala         }
5720fceef80STodd Fiala         else
5730fceef80STodd Fiala         {
5740fceef80STodd Fiala             elf_gregset_t regs;
5750fceef80STodd Fiala             int regset = NT_PRSTATUS;
5760fceef80STodd Fiala             struct iovec ioVec;
5770fceef80STodd Fiala 
5780fceef80STodd Fiala             ioVec.iov_base = &regs;
5790fceef80STodd Fiala             ioVec.iov_len = sizeof regs;
58097ccc294SChaoren Lin             PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
58197ccc294SChaoren Lin             if (m_error.Success())
5820fceef80STodd Fiala             {
583db264a6dSTamas Berghammer                 ArchSpec arch;
5840fceef80STodd Fiala                 if (monitor->GetArchitecture(arch))
5850fceef80STodd Fiala                     m_value.SetBytes((void *)(((unsigned char *)(regs)) + m_offset), 8, arch.GetByteOrder());
58697ccc294SChaoren Lin                 else
58797ccc294SChaoren Lin                     m_error.SetErrorString("failed to get architecture");
5880fceef80STodd Fiala             }
5890fceef80STodd Fiala         }
59009ba1a32SMohit K. Bhakkad #elif defined (__mips__)
59109ba1a32SMohit K. Bhakkad         elf_gregset_t regs;
59209ba1a32SMohit K. Bhakkad         PTRACE(PTRACE_GETREGS, m_tid, NULL, &regs, sizeof regs, m_error);
59309ba1a32SMohit K. Bhakkad         if (m_error.Success())
59409ba1a32SMohit K. Bhakkad         {
59509ba1a32SMohit K. Bhakkad             lldb_private::ArchSpec arch;
59609ba1a32SMohit K. Bhakkad             if (monitor->GetArchitecture(arch))
59709ba1a32SMohit K. Bhakkad                 m_value.SetBytes((void *)(((unsigned char *)(regs)) + m_offset), 8, arch.GetByteOrder());
59809ba1a32SMohit K. Bhakkad             else
59909ba1a32SMohit K. Bhakkad                 m_error.SetErrorString("failed to get architecture");
60009ba1a32SMohit K. Bhakkad         }
6010fceef80STodd Fiala #else
602af245d11STodd Fiala         Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
603af245d11STodd Fiala 
604adf8adbdSTamas Berghammer         lldb::addr_t data = static_cast<unsigned long>(PTRACE(PTRACE_PEEKUSER, m_tid, (void*)m_offset, nullptr, 0, m_error));
60597ccc294SChaoren Lin         if (m_error.Success())
606af245d11STodd Fiala             m_value = data;
60797ccc294SChaoren Lin 
608af245d11STodd Fiala         if (log)
609af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() reg %s: 0x%" PRIx64, __FUNCTION__,
610af245d11STodd Fiala                     m_reg_name, data);
6110fceef80STodd Fiala #endif
612af245d11STodd Fiala     }
613af245d11STodd Fiala 
614af245d11STodd Fiala     //------------------------------------------------------------------------------
615af245d11STodd Fiala     /// @class WriteRegOperation
616af245d11STodd Fiala     /// @brief Implements NativeProcessLinux::WriteRegisterValue.
617af245d11STodd Fiala     class WriteRegOperation : public Operation
618af245d11STodd Fiala     {
619af245d11STodd Fiala     public:
620af245d11STodd Fiala         WriteRegOperation(lldb::tid_t tid, unsigned offset, const char *reg_name,
62197ccc294SChaoren Lin                 const RegisterValue &value)
62297ccc294SChaoren Lin             : m_tid(tid),
62397ccc294SChaoren Lin               m_offset(offset),
62497ccc294SChaoren Lin               m_reg_name(reg_name),
62597ccc294SChaoren Lin               m_value(value)
626af245d11STodd Fiala             { }
627af245d11STodd Fiala 
628d542efdeSTamas Berghammer         void Execute(NativeProcessLinux *monitor) override;
629af245d11STodd Fiala 
630af245d11STodd Fiala     private:
631af245d11STodd Fiala         lldb::tid_t m_tid;
632af245d11STodd Fiala         uintptr_t m_offset;
633af245d11STodd Fiala         const char *m_reg_name;
634af245d11STodd Fiala         const RegisterValue &m_value;
635af245d11STodd Fiala     };
636af245d11STodd Fiala 
637af245d11STodd Fiala     void
638af245d11STodd Fiala     WriteRegOperation::Execute(NativeProcessLinux *monitor)
639af245d11STodd Fiala     {
6400fceef80STodd Fiala #if defined (__arm64__) || defined (__aarch64__)
6410fceef80STodd Fiala         if (m_offset > sizeof(struct user_pt_regs))
6420fceef80STodd Fiala         {
6430fceef80STodd Fiala             uintptr_t offset = m_offset - sizeof(struct user_pt_regs);
6440fceef80STodd Fiala             if (offset > sizeof(struct user_fpsimd_state))
6450fceef80STodd Fiala             {
64697ccc294SChaoren Lin                 m_error.SetErrorString("invalid offset value");
64797ccc294SChaoren Lin                 return;
6480fceef80STodd Fiala             }
6490fceef80STodd Fiala             elf_fpregset_t regs;
6500fceef80STodd Fiala             int regset = NT_FPREGSET;
6510fceef80STodd Fiala             struct iovec ioVec;
6520fceef80STodd Fiala 
6530fceef80STodd Fiala             ioVec.iov_base = &regs;
6540fceef80STodd Fiala             ioVec.iov_len = sizeof regs;
65597ccc294SChaoren Lin             PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
6569425b329SBhushan D. Attarde             if (m_error.Success())
6570fceef80STodd Fiala             {
6580fceef80STodd Fiala                 ::memcpy((void *)(((unsigned char *)(&regs)) + offset), m_value.GetBytes(), 16);
65997ccc294SChaoren Lin                 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
6600fceef80STodd Fiala             }
6610fceef80STodd Fiala         }
6620fceef80STodd Fiala         else
6630fceef80STodd Fiala         {
6640fceef80STodd Fiala             elf_gregset_t regs;
6650fceef80STodd Fiala             int regset = NT_PRSTATUS;
6660fceef80STodd Fiala             struct iovec ioVec;
6670fceef80STodd Fiala 
6680fceef80STodd Fiala             ioVec.iov_base = &regs;
6690fceef80STodd Fiala             ioVec.iov_len = sizeof regs;
67097ccc294SChaoren Lin             PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
6719425b329SBhushan D. Attarde             if (m_error.Success())
6720fceef80STodd Fiala             {
6730fceef80STodd Fiala                 ::memcpy((void *)(((unsigned char *)(&regs)) + m_offset), m_value.GetBytes(), 8);
67497ccc294SChaoren Lin                 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
6750fceef80STodd Fiala             }
6760fceef80STodd Fiala         }
67709ba1a32SMohit K. Bhakkad #elif defined (__mips__)
67809ba1a32SMohit K. Bhakkad         elf_gregset_t regs;
67909ba1a32SMohit K. Bhakkad         PTRACE(PTRACE_GETREGS, m_tid, NULL, &regs, sizeof regs, m_error);
68009ba1a32SMohit K. Bhakkad         if (m_error.Success())
68109ba1a32SMohit K. Bhakkad         {
68209ba1a32SMohit K. Bhakkad             ::memcpy((void *)(((unsigned char *)(&regs)) + m_offset), m_value.GetBytes(), 8);
68309ba1a32SMohit K. Bhakkad             PTRACE(PTRACE_SETREGS, m_tid, NULL, &regs, sizeof regs, m_error);
68409ba1a32SMohit K. Bhakkad         }
6850fceef80STodd Fiala #else
686af245d11STodd Fiala         void* buf;
687af245d11STodd Fiala         Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
688af245d11STodd Fiala 
689af245d11STodd Fiala         buf = (void*) m_value.GetAsUInt64();
690af245d11STodd Fiala 
691af245d11STodd Fiala         if (log)
692af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() reg %s: %p", __FUNCTION__, m_reg_name, buf);
69397ccc294SChaoren Lin         PTRACE(PTRACE_POKEUSER, m_tid, (void*)m_offset, buf, 0, m_error);
6940fceef80STodd Fiala #endif
695af245d11STodd Fiala     }
696af245d11STodd Fiala 
697af245d11STodd Fiala     //------------------------------------------------------------------------------
698af245d11STodd Fiala     /// @class ReadGPROperation
699af245d11STodd Fiala     /// @brief Implements NativeProcessLinux::ReadGPR.
700af245d11STodd Fiala     class ReadGPROperation : public Operation
701af245d11STodd Fiala     {
702af245d11STodd Fiala     public:
70397ccc294SChaoren Lin         ReadGPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
70497ccc294SChaoren Lin             : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
705af245d11STodd Fiala             { }
706af245d11STodd Fiala 
707d542efdeSTamas Berghammer         void Execute(NativeProcessLinux *monitor) override;
708af245d11STodd Fiala 
709af245d11STodd Fiala     private:
710af245d11STodd Fiala         lldb::tid_t m_tid;
711af245d11STodd Fiala         void *m_buf;
712af245d11STodd Fiala         size_t m_buf_size;
713af245d11STodd Fiala     };
714af245d11STodd Fiala 
715af245d11STodd Fiala     void
716af245d11STodd Fiala     ReadGPROperation::Execute(NativeProcessLinux *monitor)
717af245d11STodd Fiala     {
7186ac1be4bSTodd Fiala #if defined (__arm64__) || defined (__aarch64__)
7196ac1be4bSTodd Fiala         int regset = NT_PRSTATUS;
7206ac1be4bSTodd Fiala         struct iovec ioVec;
7216ac1be4bSTodd Fiala 
7226ac1be4bSTodd Fiala         ioVec.iov_base = m_buf;
7236ac1be4bSTodd Fiala         ioVec.iov_len = m_buf_size;
72497ccc294SChaoren Lin         PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
7256ac1be4bSTodd Fiala #else
72697ccc294SChaoren Lin         PTRACE(PTRACE_GETREGS, m_tid, nullptr, m_buf, m_buf_size, m_error);
7276ac1be4bSTodd Fiala #endif
728af245d11STodd Fiala     }
729af245d11STodd Fiala 
730af245d11STodd Fiala     //------------------------------------------------------------------------------
731af245d11STodd Fiala     /// @class ReadFPROperation
732af245d11STodd Fiala     /// @brief Implements NativeProcessLinux::ReadFPR.
733af245d11STodd Fiala     class ReadFPROperation : public Operation
734af245d11STodd Fiala     {
735af245d11STodd Fiala     public:
73697ccc294SChaoren Lin         ReadFPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
73797ccc294SChaoren Lin             : m_tid(tid),
73897ccc294SChaoren Lin               m_buf(buf),
73997ccc294SChaoren Lin               m_buf_size(buf_size)
740af245d11STodd Fiala             { }
741af245d11STodd Fiala 
742d542efdeSTamas Berghammer         void Execute(NativeProcessLinux *monitor) override;
743af245d11STodd Fiala 
744af245d11STodd Fiala     private:
745af245d11STodd Fiala         lldb::tid_t m_tid;
746af245d11STodd Fiala         void *m_buf;
747af245d11STodd Fiala         size_t m_buf_size;
748af245d11STodd Fiala     };
749af245d11STodd Fiala 
750af245d11STodd Fiala     void
751af245d11STodd Fiala     ReadFPROperation::Execute(NativeProcessLinux *monitor)
752af245d11STodd Fiala     {
7536ac1be4bSTodd Fiala #if defined (__arm64__) || defined (__aarch64__)
7546ac1be4bSTodd Fiala         int regset = NT_FPREGSET;
7556ac1be4bSTodd Fiala         struct iovec ioVec;
7566ac1be4bSTodd Fiala 
7576ac1be4bSTodd Fiala         ioVec.iov_base = m_buf;
7586ac1be4bSTodd Fiala         ioVec.iov_len = m_buf_size;
7591e209fccSTamas Berghammer         PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
7606ac1be4bSTodd Fiala #else
76197ccc294SChaoren Lin         PTRACE(PTRACE_GETFPREGS, m_tid, nullptr, m_buf, m_buf_size, m_error);
7626ac1be4bSTodd Fiala #endif
763af245d11STodd Fiala     }
764af245d11STodd Fiala 
765af245d11STodd Fiala     //------------------------------------------------------------------------------
766af245d11STodd Fiala     /// @class ReadRegisterSetOperation
767af245d11STodd Fiala     /// @brief Implements NativeProcessLinux::ReadRegisterSet.
768af245d11STodd Fiala     class ReadRegisterSetOperation : public Operation
769af245d11STodd Fiala     {
770af245d11STodd Fiala     public:
77197ccc294SChaoren Lin         ReadRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
77297ccc294SChaoren Lin             : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset)
773af245d11STodd Fiala             { }
774af245d11STodd Fiala 
775d542efdeSTamas Berghammer         void Execute(NativeProcessLinux *monitor) override;
776af245d11STodd Fiala 
777af245d11STodd Fiala     private:
778af245d11STodd Fiala         lldb::tid_t m_tid;
779af245d11STodd Fiala         void *m_buf;
780af245d11STodd Fiala         size_t m_buf_size;
781af245d11STodd Fiala         const unsigned int m_regset;
782af245d11STodd Fiala     };
783af245d11STodd Fiala 
784af245d11STodd Fiala     void
785af245d11STodd Fiala     ReadRegisterSetOperation::Execute(NativeProcessLinux *monitor)
786af245d11STodd Fiala     {
78797ccc294SChaoren Lin         PTRACE(PTRACE_GETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size, m_error);
788af245d11STodd Fiala     }
789af245d11STodd Fiala 
790af245d11STodd Fiala     //------------------------------------------------------------------------------
791af245d11STodd Fiala     /// @class WriteGPROperation
792af245d11STodd Fiala     /// @brief Implements NativeProcessLinux::WriteGPR.
793af245d11STodd Fiala     class WriteGPROperation : public Operation
794af245d11STodd Fiala     {
795af245d11STodd Fiala     public:
79697ccc294SChaoren Lin         WriteGPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
79797ccc294SChaoren Lin             : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
798af245d11STodd Fiala             { }
799af245d11STodd Fiala 
800d542efdeSTamas Berghammer         void Execute(NativeProcessLinux *monitor) override;
801af245d11STodd Fiala 
802af245d11STodd Fiala     private:
803af245d11STodd Fiala         lldb::tid_t m_tid;
804af245d11STodd Fiala         void *m_buf;
805af245d11STodd Fiala         size_t m_buf_size;
806af245d11STodd Fiala     };
807af245d11STodd Fiala 
808af245d11STodd Fiala     void
809af245d11STodd Fiala     WriteGPROperation::Execute(NativeProcessLinux *monitor)
810af245d11STodd Fiala     {
8116ac1be4bSTodd Fiala #if defined (__arm64__) || defined (__aarch64__)
8126ac1be4bSTodd Fiala         int regset = NT_PRSTATUS;
8136ac1be4bSTodd Fiala         struct iovec ioVec;
8146ac1be4bSTodd Fiala 
8156ac1be4bSTodd Fiala         ioVec.iov_base = m_buf;
8166ac1be4bSTodd Fiala         ioVec.iov_len = m_buf_size;
81797ccc294SChaoren Lin         PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
8186ac1be4bSTodd Fiala #else
81997ccc294SChaoren Lin         PTRACE(PTRACE_SETREGS, m_tid, NULL, m_buf, m_buf_size, m_error);
8206ac1be4bSTodd Fiala #endif
821af245d11STodd Fiala     }
822af245d11STodd Fiala 
823af245d11STodd Fiala     //------------------------------------------------------------------------------
824af245d11STodd Fiala     /// @class WriteFPROperation
825af245d11STodd Fiala     /// @brief Implements NativeProcessLinux::WriteFPR.
826af245d11STodd Fiala     class WriteFPROperation : public Operation
827af245d11STodd Fiala     {
828af245d11STodd Fiala     public:
82997ccc294SChaoren Lin         WriteFPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
83097ccc294SChaoren Lin             : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
831af245d11STodd Fiala             { }
832af245d11STodd Fiala 
833d542efdeSTamas Berghammer         void Execute(NativeProcessLinux *monitor) override;
834af245d11STodd Fiala 
835af245d11STodd Fiala     private:
836af245d11STodd Fiala         lldb::tid_t m_tid;
837af245d11STodd Fiala         void *m_buf;
838af245d11STodd Fiala         size_t m_buf_size;
839af245d11STodd Fiala     };
840af245d11STodd Fiala 
841af245d11STodd Fiala     void
842af245d11STodd Fiala     WriteFPROperation::Execute(NativeProcessLinux *monitor)
843af245d11STodd Fiala     {
8446ac1be4bSTodd Fiala #if defined (__arm64__) || defined (__aarch64__)
8456ac1be4bSTodd Fiala         int regset = NT_FPREGSET;
8466ac1be4bSTodd Fiala         struct iovec ioVec;
8476ac1be4bSTodd Fiala 
8486ac1be4bSTodd Fiala         ioVec.iov_base = m_buf;
8496ac1be4bSTodd Fiala         ioVec.iov_len = m_buf_size;
85097ccc294SChaoren Lin         PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
8516ac1be4bSTodd Fiala #else
85297ccc294SChaoren Lin         PTRACE(PTRACE_SETFPREGS, m_tid, NULL, m_buf, m_buf_size, m_error);
8536ac1be4bSTodd Fiala #endif
854af245d11STodd Fiala     }
855af245d11STodd Fiala 
856af245d11STodd Fiala     //------------------------------------------------------------------------------
857af245d11STodd Fiala     /// @class WriteRegisterSetOperation
858af245d11STodd Fiala     /// @brief Implements NativeProcessLinux::WriteRegisterSet.
859af245d11STodd Fiala     class WriteRegisterSetOperation : public Operation
860af245d11STodd Fiala     {
861af245d11STodd Fiala     public:
86297ccc294SChaoren Lin         WriteRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
86397ccc294SChaoren Lin             : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset)
864af245d11STodd Fiala             { }
865af245d11STodd Fiala 
866d542efdeSTamas Berghammer         void Execute(NativeProcessLinux *monitor) override;
867af245d11STodd Fiala 
868af245d11STodd Fiala     private:
869af245d11STodd Fiala         lldb::tid_t m_tid;
870af245d11STodd Fiala         void *m_buf;
871af245d11STodd Fiala         size_t m_buf_size;
872af245d11STodd Fiala         const unsigned int m_regset;
873af245d11STodd Fiala     };
874af245d11STodd Fiala 
875af245d11STodd Fiala     void
876af245d11STodd Fiala     WriteRegisterSetOperation::Execute(NativeProcessLinux *monitor)
877af245d11STodd Fiala     {
87897ccc294SChaoren Lin         PTRACE(PTRACE_SETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size, m_error);
879af245d11STodd Fiala     }
880af245d11STodd Fiala 
881af245d11STodd Fiala     //------------------------------------------------------------------------------
882af245d11STodd Fiala     /// @class ResumeOperation
883af245d11STodd Fiala     /// @brief Implements NativeProcessLinux::Resume.
884af245d11STodd Fiala     class ResumeOperation : public Operation
885af245d11STodd Fiala     {
886af245d11STodd Fiala     public:
88797ccc294SChaoren Lin         ResumeOperation(lldb::tid_t tid, uint32_t signo) :
88897ccc294SChaoren Lin             m_tid(tid), m_signo(signo) { }
889af245d11STodd Fiala 
890d542efdeSTamas Berghammer         void Execute(NativeProcessLinux *monitor) override;
891af245d11STodd Fiala 
892af245d11STodd Fiala     private:
893af245d11STodd Fiala         lldb::tid_t m_tid;
894af245d11STodd Fiala         uint32_t m_signo;
895af245d11STodd Fiala     };
896af245d11STodd Fiala 
897af245d11STodd Fiala     void
898af245d11STodd Fiala     ResumeOperation::Execute(NativeProcessLinux *monitor)
899af245d11STodd Fiala     {
900af245d11STodd Fiala         intptr_t data = 0;
901af245d11STodd Fiala 
902af245d11STodd Fiala         if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
903af245d11STodd Fiala             data = m_signo;
904af245d11STodd Fiala 
90597ccc294SChaoren Lin         PTRACE(PTRACE_CONT, m_tid, nullptr, (void*)data, 0, m_error);
90697ccc294SChaoren Lin         if (m_error.Fail())
907af245d11STodd Fiala         {
908af245d11STodd Fiala             Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
909af245d11STodd Fiala 
910af245d11STodd Fiala             if (log)
91197ccc294SChaoren Lin                 log->Printf ("ResumeOperation (%"  PRIu64 ") failed: %s", m_tid, m_error.AsCString());
912af245d11STodd Fiala         }
913af245d11STodd Fiala     }
914af245d11STodd Fiala 
915af245d11STodd Fiala     //------------------------------------------------------------------------------
916af245d11STodd Fiala     /// @class SingleStepOperation
917af245d11STodd Fiala     /// @brief Implements NativeProcessLinux::SingleStep.
918af245d11STodd Fiala     class SingleStepOperation : public Operation
919af245d11STodd Fiala     {
920af245d11STodd Fiala     public:
92197ccc294SChaoren Lin         SingleStepOperation(lldb::tid_t tid, uint32_t signo)
92297ccc294SChaoren Lin             : m_tid(tid), m_signo(signo) { }
923af245d11STodd Fiala 
924d542efdeSTamas Berghammer         void Execute(NativeProcessLinux *monitor) override;
925af245d11STodd Fiala 
926af245d11STodd Fiala     private:
927af245d11STodd Fiala         lldb::tid_t m_tid;
928af245d11STodd Fiala         uint32_t m_signo;
929af245d11STodd Fiala     };
930af245d11STodd Fiala 
931af245d11STodd Fiala     void
932af245d11STodd Fiala     SingleStepOperation::Execute(NativeProcessLinux *monitor)
933af245d11STodd Fiala     {
934af245d11STodd Fiala         intptr_t data = 0;
935af245d11STodd Fiala 
936af245d11STodd Fiala         if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
937af245d11STodd Fiala             data = m_signo;
938af245d11STodd Fiala 
93997ccc294SChaoren Lin         PTRACE(PTRACE_SINGLESTEP, m_tid, nullptr, (void*)data, 0, m_error);
940af245d11STodd Fiala     }
941af245d11STodd Fiala 
942af245d11STodd Fiala     //------------------------------------------------------------------------------
943af245d11STodd Fiala     /// @class SiginfoOperation
944af245d11STodd Fiala     /// @brief Implements NativeProcessLinux::GetSignalInfo.
945af245d11STodd Fiala     class SiginfoOperation : public Operation
946af245d11STodd Fiala     {
947af245d11STodd Fiala     public:
94897ccc294SChaoren Lin         SiginfoOperation(lldb::tid_t tid, void *info)
94997ccc294SChaoren Lin             : m_tid(tid), m_info(info) { }
950af245d11STodd Fiala 
951d542efdeSTamas Berghammer         void Execute(NativeProcessLinux *monitor) override;
952af245d11STodd Fiala 
953af245d11STodd Fiala     private:
954af245d11STodd Fiala         lldb::tid_t m_tid;
955af245d11STodd Fiala         void *m_info;
956af245d11STodd Fiala     };
957af245d11STodd Fiala 
958af245d11STodd Fiala     void
959af245d11STodd Fiala     SiginfoOperation::Execute(NativeProcessLinux *monitor)
960af245d11STodd Fiala     {
96197ccc294SChaoren Lin         PTRACE(PTRACE_GETSIGINFO, m_tid, nullptr, m_info, 0, m_error);
962af245d11STodd Fiala     }
963af245d11STodd Fiala 
964af245d11STodd Fiala     //------------------------------------------------------------------------------
965af245d11STodd Fiala     /// @class EventMessageOperation
966af245d11STodd Fiala     /// @brief Implements NativeProcessLinux::GetEventMessage.
967af245d11STodd Fiala     class EventMessageOperation : public Operation
968af245d11STodd Fiala     {
969af245d11STodd Fiala     public:
97097ccc294SChaoren Lin         EventMessageOperation(lldb::tid_t tid, unsigned long *message)
97197ccc294SChaoren Lin             : m_tid(tid), m_message(message) { }
972af245d11STodd Fiala 
973d542efdeSTamas Berghammer         void Execute(NativeProcessLinux *monitor) override;
974af245d11STodd Fiala 
975af245d11STodd Fiala     private:
976af245d11STodd Fiala         lldb::tid_t m_tid;
977af245d11STodd Fiala         unsigned long *m_message;
978af245d11STodd Fiala     };
979af245d11STodd Fiala 
980af245d11STodd Fiala     void
981af245d11STodd Fiala     EventMessageOperation::Execute(NativeProcessLinux *monitor)
982af245d11STodd Fiala     {
98397ccc294SChaoren Lin         PTRACE(PTRACE_GETEVENTMSG, m_tid, nullptr, m_message, 0, m_error);
984af245d11STodd Fiala     }
985af245d11STodd Fiala 
986af245d11STodd Fiala     class DetachOperation : public Operation
987af245d11STodd Fiala     {
988af245d11STodd Fiala     public:
98997ccc294SChaoren Lin         DetachOperation(lldb::tid_t tid) : m_tid(tid) { }
990af245d11STodd Fiala 
991d542efdeSTamas Berghammer         void Execute(NativeProcessLinux *monitor) override;
992af245d11STodd Fiala 
993af245d11STodd Fiala     private:
994af245d11STodd Fiala         lldb::tid_t m_tid;
995af245d11STodd Fiala     };
996af245d11STodd Fiala 
997af245d11STodd Fiala     void
998af245d11STodd Fiala     DetachOperation::Execute(NativeProcessLinux *monitor)
999af245d11STodd Fiala     {
100097ccc294SChaoren Lin         PTRACE(PTRACE_DETACH, m_tid, nullptr, 0, 0, m_error);
1001af245d11STodd Fiala     }
10021107b5a5SPavel Labath } // end of anonymous namespace
10031107b5a5SPavel Labath 
1004bd7cbc5aSPavel Labath // Simple helper function to ensure flags are enabled on the given file
1005bd7cbc5aSPavel Labath // descriptor.
1006bd7cbc5aSPavel Labath static Error
1007bd7cbc5aSPavel Labath EnsureFDFlags(int fd, int flags)
1008bd7cbc5aSPavel Labath {
1009bd7cbc5aSPavel Labath     Error error;
1010bd7cbc5aSPavel Labath 
1011bd7cbc5aSPavel Labath     int status = fcntl(fd, F_GETFL);
1012bd7cbc5aSPavel Labath     if (status == -1)
1013bd7cbc5aSPavel Labath     {
1014bd7cbc5aSPavel Labath         error.SetErrorToErrno();
1015bd7cbc5aSPavel Labath         return error;
1016bd7cbc5aSPavel Labath     }
1017bd7cbc5aSPavel Labath 
1018bd7cbc5aSPavel Labath     if (fcntl(fd, F_SETFL, status | flags) == -1)
1019bd7cbc5aSPavel Labath     {
1020bd7cbc5aSPavel Labath         error.SetErrorToErrno();
1021bd7cbc5aSPavel Labath         return error;
1022bd7cbc5aSPavel Labath     }
1023bd7cbc5aSPavel Labath 
1024bd7cbc5aSPavel Labath     return error;
1025bd7cbc5aSPavel Labath }
1026bd7cbc5aSPavel Labath 
1027bd7cbc5aSPavel Labath // This class encapsulates the privileged thread which performs all ptrace and wait operations on
1028bd7cbc5aSPavel Labath // the inferior. The thread consists of a main loop which waits for events and processes them
1029bd7cbc5aSPavel Labath //   - SIGCHLD (delivered over a signalfd file descriptor): These signals notify us of events in
1030bd7cbc5aSPavel Labath //     the inferior process. Upon receiving this signal we do a waitpid to get more information
1031bd7cbc5aSPavel Labath //     and dispatch to NativeProcessLinux::MonitorCallback.
1032bd7cbc5aSPavel Labath //   - requests for ptrace operations: These initiated via the DoOperation method, which funnels
1033bd7cbc5aSPavel Labath //     them to the Monitor thread via m_operation member. The Monitor thread is signaled over a
1034bd7cbc5aSPavel Labath //     pipe, and the completion of the operation is signalled over the semaphore.
1035bd7cbc5aSPavel Labath //   - thread exit event: this is signaled from the Monitor destructor by closing the write end
1036bd7cbc5aSPavel Labath //     of the command pipe.
103745f5cb31SPavel Labath class NativeProcessLinux::Monitor
103845f5cb31SPavel Labath {
10391107b5a5SPavel Labath private:
1040bd7cbc5aSPavel Labath     // The initial monitor operation (launch or attach). It returns a inferior process id.
1041bd7cbc5aSPavel Labath     std::unique_ptr<InitialOperation> m_initial_operation_up;
1042bd7cbc5aSPavel Labath 
1043bd7cbc5aSPavel Labath     ::pid_t                           m_child_pid = -1;
10441107b5a5SPavel Labath     NativeProcessLinux              * m_native_process;
10451107b5a5SPavel Labath 
10461107b5a5SPavel Labath     enum { READ, WRITE };
10471107b5a5SPavel Labath     int        m_pipefd[2] = {-1, -1};
10481107b5a5SPavel Labath     int        m_signal_fd = -1;
10491107b5a5SPavel Labath     HostThread m_thread;
10501107b5a5SPavel Labath 
1051bd7cbc5aSPavel Labath     // current operation which must be executed on the priviliged thread
1052bd7cbc5aSPavel Labath     Mutex      m_operation_mutex;
1053bd7cbc5aSPavel Labath     Operation *m_operation = nullptr;
1054bd7cbc5aSPavel Labath     sem_t      m_operation_sem;
1055bd7cbc5aSPavel Labath     Error      m_operation_error;
1056bd7cbc5aSPavel Labath 
105745f5cb31SPavel Labath     unsigned   m_operation_nesting_level = 0;
105845f5cb31SPavel Labath 
1059bd7cbc5aSPavel Labath     static constexpr char operation_command   = 'o';
106045f5cb31SPavel Labath     static constexpr char begin_block_command = '{';
106145f5cb31SPavel Labath     static constexpr char end_block_command   = '}';
1062bd7cbc5aSPavel Labath 
10631107b5a5SPavel Labath     void
10641107b5a5SPavel Labath     HandleSignals();
10651107b5a5SPavel Labath 
10661107b5a5SPavel Labath     void
10671107b5a5SPavel Labath     HandleWait();
10681107b5a5SPavel Labath 
10691107b5a5SPavel Labath     // Returns true if the thread should exit.
10701107b5a5SPavel Labath     bool
10711107b5a5SPavel Labath     HandleCommands();
10721107b5a5SPavel Labath 
10731107b5a5SPavel Labath     void
10741107b5a5SPavel Labath     MainLoop();
10751107b5a5SPavel Labath 
10761107b5a5SPavel Labath     static void *
10771107b5a5SPavel Labath     RunMonitor(void *arg);
10781107b5a5SPavel Labath 
1079bd7cbc5aSPavel Labath     Error
108045f5cb31SPavel Labath     WaitForAck();
108145f5cb31SPavel Labath 
108245f5cb31SPavel Labath     void
108345f5cb31SPavel Labath     BeginOperationBlock()
108445f5cb31SPavel Labath     {
108545f5cb31SPavel Labath         write(m_pipefd[WRITE], &begin_block_command, sizeof operation_command);
108645f5cb31SPavel Labath         WaitForAck();
108745f5cb31SPavel Labath     }
108845f5cb31SPavel Labath 
108945f5cb31SPavel Labath     void
109045f5cb31SPavel Labath     EndOperationBlock()
109145f5cb31SPavel Labath     {
109245f5cb31SPavel Labath         write(m_pipefd[WRITE], &end_block_command, sizeof operation_command);
109345f5cb31SPavel Labath         WaitForAck();
109445f5cb31SPavel Labath     }
109545f5cb31SPavel Labath 
10961107b5a5SPavel Labath public:
1097bd7cbc5aSPavel Labath     Monitor(const InitialOperation &initial_operation,
1098bd7cbc5aSPavel Labath             NativeProcessLinux *native_process)
1099bd7cbc5aSPavel Labath         : m_initial_operation_up(new InitialOperation(initial_operation)),
1100bd7cbc5aSPavel Labath           m_native_process(native_process)
1101bd7cbc5aSPavel Labath     {
1102bd7cbc5aSPavel Labath         sem_init(&m_operation_sem, 0, 0);
1103bd7cbc5aSPavel Labath     }
11041107b5a5SPavel Labath 
11051107b5a5SPavel Labath     ~Monitor();
11061107b5a5SPavel Labath 
11071107b5a5SPavel Labath     Error
11081107b5a5SPavel Labath     Initialize();
1109bd7cbc5aSPavel Labath 
1110bd7cbc5aSPavel Labath     void
111145f5cb31SPavel Labath     Terminate();
111245f5cb31SPavel Labath 
111345f5cb31SPavel Labath     void
1114bd7cbc5aSPavel Labath     DoOperation(Operation *op);
111545f5cb31SPavel Labath 
111645f5cb31SPavel Labath     class ScopedOperationLock {
111745f5cb31SPavel Labath         Monitor &m_monitor;
111845f5cb31SPavel Labath 
111945f5cb31SPavel Labath     public:
112045f5cb31SPavel Labath         ScopedOperationLock(Monitor &monitor)
112145f5cb31SPavel Labath             : m_monitor(monitor)
112245f5cb31SPavel Labath         { m_monitor.BeginOperationBlock(); }
112345f5cb31SPavel Labath 
112445f5cb31SPavel Labath         ~ScopedOperationLock()
112545f5cb31SPavel Labath         { m_monitor.EndOperationBlock(); }
112645f5cb31SPavel Labath     };
11271107b5a5SPavel Labath };
1128bd7cbc5aSPavel Labath constexpr char NativeProcessLinux::Monitor::operation_command;
112945f5cb31SPavel Labath constexpr char NativeProcessLinux::Monitor::begin_block_command;
113045f5cb31SPavel Labath constexpr char NativeProcessLinux::Monitor::end_block_command;
11311107b5a5SPavel Labath 
11321107b5a5SPavel Labath Error
11331107b5a5SPavel Labath NativeProcessLinux::Monitor::Initialize()
11341107b5a5SPavel Labath {
11351107b5a5SPavel Labath     Error error;
11361107b5a5SPavel Labath 
11371107b5a5SPavel Labath     // We get a SIGCHLD every time something interesting happens with the inferior. We shall be
11381107b5a5SPavel Labath     // listening for these signals over a signalfd file descriptors. This allows us to wait for
11391107b5a5SPavel Labath     // multiple kinds of events with select.
11401107b5a5SPavel Labath     sigset_t signals;
11411107b5a5SPavel Labath     sigemptyset(&signals);
11421107b5a5SPavel Labath     sigaddset(&signals, SIGCHLD);
11431107b5a5SPavel Labath     m_signal_fd = signalfd(-1, &signals, SFD_NONBLOCK | SFD_CLOEXEC);
11441107b5a5SPavel Labath     if (m_signal_fd < 0)
11451107b5a5SPavel Labath     {
11461107b5a5SPavel Labath         return Error("NativeProcessLinux::Monitor::%s failed due to signalfd failure. Monitoring the inferior will be impossible: %s",
11471107b5a5SPavel Labath                     __FUNCTION__, strerror(errno));
11481107b5a5SPavel Labath 
1149af245d11STodd Fiala     }
1150af245d11STodd Fiala 
11511107b5a5SPavel Labath     if (pipe2(m_pipefd, O_CLOEXEC) == -1)
11521107b5a5SPavel Labath     {
11531107b5a5SPavel Labath         error.SetErrorToErrno();
11541107b5a5SPavel Labath         return error;
11551107b5a5SPavel Labath     }
11561107b5a5SPavel Labath 
1157bd7cbc5aSPavel Labath     if ((error = EnsureFDFlags(m_pipefd[READ], O_NONBLOCK)).Fail()) {
1158bd7cbc5aSPavel Labath         return error;
1159bd7cbc5aSPavel Labath     }
1160bd7cbc5aSPavel Labath 
1161bd7cbc5aSPavel Labath     static const char g_thread_name[] = "lldb.process.nativelinux.monitor";
1162bd7cbc5aSPavel Labath     m_thread = ThreadLauncher::LaunchThread(g_thread_name, Monitor::RunMonitor, this, nullptr);
11631107b5a5SPavel Labath     if (!m_thread.IsJoinable())
11641107b5a5SPavel Labath         return Error("Failed to create monitor thread for NativeProcessLinux.");
11651107b5a5SPavel Labath 
1166bd7cbc5aSPavel Labath     // Wait for initial operation to complete.
116745f5cb31SPavel Labath     return WaitForAck();
1168bd7cbc5aSPavel Labath }
1169bd7cbc5aSPavel Labath 
1170bd7cbc5aSPavel Labath void
1171bd7cbc5aSPavel Labath NativeProcessLinux::Monitor::DoOperation(Operation *op)
1172bd7cbc5aSPavel Labath {
1173bd7cbc5aSPavel Labath     if (m_thread.EqualsThread(pthread_self())) {
1174bd7cbc5aSPavel Labath         // If we're on the Monitor thread, we can simply execute the operation.
1175bd7cbc5aSPavel Labath         op->Execute(m_native_process);
1176bd7cbc5aSPavel Labath         return;
1177bd7cbc5aSPavel Labath     }
1178bd7cbc5aSPavel Labath 
1179bd7cbc5aSPavel Labath     // Otherwise we need to pass the operation to the Monitor thread so it can handle it.
1180bd7cbc5aSPavel Labath     Mutex::Locker lock(m_operation_mutex);
1181bd7cbc5aSPavel Labath 
1182bd7cbc5aSPavel Labath     m_operation = op;
1183bd7cbc5aSPavel Labath 
1184bd7cbc5aSPavel Labath     // notify the thread that an operation is ready to be processed
1185bd7cbc5aSPavel Labath     write(m_pipefd[WRITE], &operation_command, sizeof operation_command);
1186bd7cbc5aSPavel Labath 
118745f5cb31SPavel Labath     WaitForAck();
118845f5cb31SPavel Labath }
118945f5cb31SPavel Labath 
119045f5cb31SPavel Labath void
119145f5cb31SPavel Labath NativeProcessLinux::Monitor::Terminate()
119245f5cb31SPavel Labath {
119345f5cb31SPavel Labath     if (m_pipefd[WRITE] >= 0)
119445f5cb31SPavel Labath     {
119545f5cb31SPavel Labath         close(m_pipefd[WRITE]);
119645f5cb31SPavel Labath         m_pipefd[WRITE] = -1;
119745f5cb31SPavel Labath     }
119845f5cb31SPavel Labath     if (m_thread.IsJoinable())
119945f5cb31SPavel Labath         m_thread.Join(nullptr);
12001107b5a5SPavel Labath }
12011107b5a5SPavel Labath 
12021107b5a5SPavel Labath NativeProcessLinux::Monitor::~Monitor()
12031107b5a5SPavel Labath {
120445f5cb31SPavel Labath     Terminate();
12051107b5a5SPavel Labath     if (m_pipefd[READ] >= 0)
12061107b5a5SPavel Labath         close(m_pipefd[READ]);
12071107b5a5SPavel Labath     if (m_signal_fd >= 0)
12081107b5a5SPavel Labath         close(m_signal_fd);
1209bd7cbc5aSPavel Labath     sem_destroy(&m_operation_sem);
12101107b5a5SPavel Labath }
12111107b5a5SPavel Labath 
12121107b5a5SPavel Labath void
12131107b5a5SPavel Labath NativeProcessLinux::Monitor::HandleSignals()
12141107b5a5SPavel Labath {
12151107b5a5SPavel Labath     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
12161107b5a5SPavel Labath 
12171107b5a5SPavel Labath     // We don't really care about the content of the SIGCHLD siginfo structure, as we will get
12181107b5a5SPavel Labath     // all the information from waitpid(). We just need to read all the signals so that we can
12191107b5a5SPavel Labath     // sleep next time we reach select().
12201107b5a5SPavel Labath     while (true)
12211107b5a5SPavel Labath     {
12221107b5a5SPavel Labath         signalfd_siginfo info;
12231107b5a5SPavel Labath         ssize_t size = read(m_signal_fd, &info, sizeof info);
12241107b5a5SPavel Labath         if (size == -1)
12251107b5a5SPavel Labath         {
12261107b5a5SPavel Labath             if (errno == EAGAIN || errno == EWOULDBLOCK)
12271107b5a5SPavel Labath                 break; // We are done.
12281107b5a5SPavel Labath             if (errno == EINTR)
12291107b5a5SPavel Labath                 continue;
12301107b5a5SPavel Labath             if (log)
12311107b5a5SPavel Labath                 log->Printf("NativeProcessLinux::Monitor::%s reading from signalfd file descriptor failed: %s",
12321107b5a5SPavel Labath                         __FUNCTION__, strerror(errno));
12331107b5a5SPavel Labath             break;
12341107b5a5SPavel Labath         }
12351107b5a5SPavel Labath         if (size != sizeof info)
12361107b5a5SPavel Labath         {
12371107b5a5SPavel Labath             // We got incomplete information structure. This should not happen, let's just log
12381107b5a5SPavel Labath             // that.
12391107b5a5SPavel Labath             if (log)
12401107b5a5SPavel Labath                 log->Printf("NativeProcessLinux::Monitor::%s reading from signalfd file descriptor returned incomplete data: "
12411107b5a5SPavel Labath                         "structure size is %zd, read returned %zd bytes",
12421107b5a5SPavel Labath                         __FUNCTION__, sizeof info, size);
12431107b5a5SPavel Labath             break;
12441107b5a5SPavel Labath         }
12451107b5a5SPavel Labath         if (log)
12461107b5a5SPavel Labath             log->Printf("NativeProcessLinux::Monitor::%s received signal %s(%d).", __FUNCTION__,
12471107b5a5SPavel Labath                 Host::GetSignalAsCString(info.ssi_signo), info.ssi_signo);
12481107b5a5SPavel Labath     }
12491107b5a5SPavel Labath }
12501107b5a5SPavel Labath 
12511107b5a5SPavel Labath void
12521107b5a5SPavel Labath NativeProcessLinux::Monitor::HandleWait()
12531107b5a5SPavel Labath {
12541107b5a5SPavel Labath     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
12551107b5a5SPavel Labath     // Process all pending waitpid notifications.
12561107b5a5SPavel Labath     while (true)
12571107b5a5SPavel Labath     {
12581107b5a5SPavel Labath         int status = -1;
12591107b5a5SPavel Labath         ::pid_t wait_pid = waitpid(m_child_pid, &status, __WALL | WNOHANG);
12601107b5a5SPavel Labath 
12611107b5a5SPavel Labath         if (wait_pid == 0)
12621107b5a5SPavel Labath             break; // We are done.
12631107b5a5SPavel Labath 
12641107b5a5SPavel Labath         if (wait_pid == -1)
12651107b5a5SPavel Labath         {
12661107b5a5SPavel Labath             if (errno == EINTR)
12671107b5a5SPavel Labath                 continue;
12681107b5a5SPavel Labath 
12691107b5a5SPavel Labath             if (log)
12701107b5a5SPavel Labath               log->Printf("NativeProcessLinux::Monitor::%s waitpid (pid = %" PRIi32 ", &status, __WALL | WNOHANG) failed: %s",
12711107b5a5SPavel Labath                       __FUNCTION__, m_child_pid, strerror(errno));
12721107b5a5SPavel Labath             break;
12731107b5a5SPavel Labath         }
12741107b5a5SPavel Labath 
12751107b5a5SPavel Labath         bool exited = false;
12761107b5a5SPavel Labath         int signal = 0;
12771107b5a5SPavel Labath         int exit_status = 0;
12781107b5a5SPavel Labath         const char *status_cstr = NULL;
12791107b5a5SPavel Labath         if (WIFSTOPPED(status))
12801107b5a5SPavel Labath         {
12811107b5a5SPavel Labath             signal = WSTOPSIG(status);
12821107b5a5SPavel Labath             status_cstr = "STOPPED";
12831107b5a5SPavel Labath         }
12841107b5a5SPavel Labath         else if (WIFEXITED(status))
12851107b5a5SPavel Labath         {
12861107b5a5SPavel Labath             exit_status = WEXITSTATUS(status);
12871107b5a5SPavel Labath             status_cstr = "EXITED";
12881107b5a5SPavel Labath             exited = true;
12891107b5a5SPavel Labath         }
12901107b5a5SPavel Labath         else if (WIFSIGNALED(status))
12911107b5a5SPavel Labath         {
12921107b5a5SPavel Labath             signal = WTERMSIG(status);
12931107b5a5SPavel Labath             status_cstr = "SIGNALED";
12941107b5a5SPavel Labath             if (wait_pid == abs(m_child_pid)) {
12951107b5a5SPavel Labath                 exited = true;
12961107b5a5SPavel Labath                 exit_status = -1;
12971107b5a5SPavel Labath             }
12981107b5a5SPavel Labath         }
12991107b5a5SPavel Labath         else
13001107b5a5SPavel Labath             status_cstr = "(\?\?\?)";
13011107b5a5SPavel Labath 
13021107b5a5SPavel Labath         if (log)
13031107b5a5SPavel Labath             log->Printf("NativeProcessLinux::Monitor::%s: waitpid (pid = %" PRIi32 ", &status, __WALL | WNOHANG)"
13041107b5a5SPavel Labath                 "=> pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
13051107b5a5SPavel Labath                 __FUNCTION__, m_child_pid, wait_pid, status, status_cstr, signal, exit_status);
13061107b5a5SPavel Labath 
13071107b5a5SPavel Labath         m_native_process->MonitorCallback (wait_pid, exited, signal, exit_status);
13081107b5a5SPavel Labath     }
13091107b5a5SPavel Labath }
13101107b5a5SPavel Labath 
13111107b5a5SPavel Labath bool
13121107b5a5SPavel Labath NativeProcessLinux::Monitor::HandleCommands()
13131107b5a5SPavel Labath {
13141107b5a5SPavel Labath     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
13151107b5a5SPavel Labath 
13161107b5a5SPavel Labath     while (true)
13171107b5a5SPavel Labath     {
13181107b5a5SPavel Labath         char command = 0;
13191107b5a5SPavel Labath         ssize_t size = read(m_pipefd[READ], &command, sizeof command);
13201107b5a5SPavel Labath         if (size == -1)
13211107b5a5SPavel Labath         {
13221107b5a5SPavel Labath             if (errno == EAGAIN || errno == EWOULDBLOCK)
13231107b5a5SPavel Labath                 return false;
13241107b5a5SPavel Labath             if (errno == EINTR)
13251107b5a5SPavel Labath                 continue;
13261107b5a5SPavel Labath             if (log)
13271107b5a5SPavel Labath                 log->Printf("NativeProcessLinux::Monitor::%s exiting because read from command file descriptor failed: %s", __FUNCTION__, strerror(errno));
13281107b5a5SPavel Labath             return true;
13291107b5a5SPavel Labath         }
13301107b5a5SPavel Labath         if (size == 0) // end of file - write end closed
13311107b5a5SPavel Labath         {
13321107b5a5SPavel Labath             if (log)
13331107b5a5SPavel Labath                 log->Printf("NativeProcessLinux::Monitor::%s exit command received, exiting...", __FUNCTION__);
133445f5cb31SPavel Labath             assert(m_operation_nesting_level == 0 && "Unbalanced begin/end block commands detected");
13351107b5a5SPavel Labath             return true; // We are done.
13361107b5a5SPavel Labath         }
1337bd7cbc5aSPavel Labath 
1338bd7cbc5aSPavel Labath         switch (command)
1339bd7cbc5aSPavel Labath         {
1340bd7cbc5aSPavel Labath         case operation_command:
1341bd7cbc5aSPavel Labath             m_operation->Execute(m_native_process);
134245f5cb31SPavel Labath             break;
134345f5cb31SPavel Labath         case begin_block_command:
134445f5cb31SPavel Labath             ++m_operation_nesting_level;
134545f5cb31SPavel Labath             break;
134645f5cb31SPavel Labath         case end_block_command:
134745f5cb31SPavel Labath             assert(m_operation_nesting_level > 0);
134845f5cb31SPavel Labath             --m_operation_nesting_level;
1349bd7cbc5aSPavel Labath             break;
1350bd7cbc5aSPavel Labath         default:
13511107b5a5SPavel Labath             if (log)
13521107b5a5SPavel Labath                 log->Printf("NativeProcessLinux::Monitor::%s received unknown command '%c'",
13531107b5a5SPavel Labath                         __FUNCTION__, command);
13541107b5a5SPavel Labath         }
135545f5cb31SPavel Labath 
135645f5cb31SPavel Labath         // notify calling thread that the command has been processed
135745f5cb31SPavel Labath         sem_post(&m_operation_sem);
13581107b5a5SPavel Labath     }
1359bd7cbc5aSPavel Labath }
13601107b5a5SPavel Labath 
13611107b5a5SPavel Labath void
13621107b5a5SPavel Labath NativeProcessLinux::Monitor::MainLoop()
13631107b5a5SPavel Labath {
1364bd7cbc5aSPavel Labath     ::pid_t child_pid = (*m_initial_operation_up)(m_operation_error);
1365bd7cbc5aSPavel Labath     m_initial_operation_up.reset();
1366bd7cbc5aSPavel Labath     m_child_pid = -getpgid(child_pid),
1367bd7cbc5aSPavel Labath     sem_post(&m_operation_sem);
1368bd7cbc5aSPavel Labath 
13691107b5a5SPavel Labath     while (true)
13701107b5a5SPavel Labath     {
13711107b5a5SPavel Labath         fd_set fds;
13721107b5a5SPavel Labath         FD_ZERO(&fds);
137345f5cb31SPavel Labath         // Only process waitpid events if we are outside of an operation block. Any pending
137445f5cb31SPavel Labath         // events will be processed after we leave the block.
137545f5cb31SPavel Labath         if (m_operation_nesting_level == 0)
13761107b5a5SPavel Labath             FD_SET(m_signal_fd, &fds);
13771107b5a5SPavel Labath         FD_SET(m_pipefd[READ], &fds);
13781107b5a5SPavel Labath 
13791107b5a5SPavel Labath         int max_fd = std::max(m_signal_fd, m_pipefd[READ]) + 1;
13801107b5a5SPavel Labath         int r = select(max_fd, &fds, nullptr, nullptr, nullptr);
13811107b5a5SPavel Labath         if (r < 0)
13821107b5a5SPavel Labath         {
13831107b5a5SPavel Labath             Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
13841107b5a5SPavel Labath             if (log)
13851107b5a5SPavel Labath                 log->Printf("NativeProcessLinux::Monitor::%s exiting because select failed: %s",
13861107b5a5SPavel Labath                         __FUNCTION__, strerror(errno));
13871107b5a5SPavel Labath             return;
13881107b5a5SPavel Labath         }
13891107b5a5SPavel Labath 
13901107b5a5SPavel Labath         if (FD_ISSET(m_pipefd[READ], &fds))
13911107b5a5SPavel Labath         {
13921107b5a5SPavel Labath             if (HandleCommands())
13931107b5a5SPavel Labath                 return;
13941107b5a5SPavel Labath         }
13951107b5a5SPavel Labath 
13961107b5a5SPavel Labath         if (FD_ISSET(m_signal_fd, &fds))
13971107b5a5SPavel Labath         {
13981107b5a5SPavel Labath             HandleSignals();
13991107b5a5SPavel Labath             HandleWait();
14001107b5a5SPavel Labath         }
14011107b5a5SPavel Labath     }
14021107b5a5SPavel Labath }
14031107b5a5SPavel Labath 
1404bd7cbc5aSPavel Labath Error
140545f5cb31SPavel Labath NativeProcessLinux::Monitor::WaitForAck()
1406bd7cbc5aSPavel Labath {
1407bd7cbc5aSPavel Labath     Error error;
1408bd7cbc5aSPavel Labath     while (sem_wait(&m_operation_sem) != 0)
1409bd7cbc5aSPavel Labath     {
1410bd7cbc5aSPavel Labath         if (errno == EINTR)
1411bd7cbc5aSPavel Labath             continue;
1412bd7cbc5aSPavel Labath 
1413bd7cbc5aSPavel Labath         error.SetErrorToErrno();
1414bd7cbc5aSPavel Labath         return error;
1415bd7cbc5aSPavel Labath     }
1416bd7cbc5aSPavel Labath 
1417bd7cbc5aSPavel Labath     return m_operation_error;
1418bd7cbc5aSPavel Labath }
1419bd7cbc5aSPavel Labath 
14201107b5a5SPavel Labath void *
14211107b5a5SPavel Labath NativeProcessLinux::Monitor::RunMonitor(void *arg)
14221107b5a5SPavel Labath {
14231107b5a5SPavel Labath     static_cast<Monitor *>(arg)->MainLoop();
14241107b5a5SPavel Labath     return nullptr;
14251107b5a5SPavel Labath }
14261107b5a5SPavel Labath 
14271107b5a5SPavel Labath 
1428bd7cbc5aSPavel Labath NativeProcessLinux::LaunchArgs::LaunchArgs(Module *module,
1429af245d11STodd Fiala                                        char const **argv,
1430af245d11STodd Fiala                                        char const **envp,
143175f47c3aSTodd Fiala                                        const std::string &stdin_path,
143275f47c3aSTodd Fiala                                        const std::string &stdout_path,
143375f47c3aSTodd Fiala                                        const std::string &stderr_path,
14340bce1b67STodd Fiala                                        const char *working_dir,
1435db264a6dSTamas Berghammer                                        const ProcessLaunchInfo &launch_info)
1436bd7cbc5aSPavel Labath     : m_module(module),
1437af245d11STodd Fiala       m_argv(argv),
1438af245d11STodd Fiala       m_envp(envp),
1439af245d11STodd Fiala       m_stdin_path(stdin_path),
1440af245d11STodd Fiala       m_stdout_path(stdout_path),
1441af245d11STodd Fiala       m_stderr_path(stderr_path),
14420bce1b67STodd Fiala       m_working_dir(working_dir),
14430bce1b67STodd Fiala       m_launch_info(launch_info)
14440bce1b67STodd Fiala {
14450bce1b67STodd Fiala }
1446af245d11STodd Fiala 
1447af245d11STodd Fiala NativeProcessLinux::LaunchArgs::~LaunchArgs()
1448af245d11STodd Fiala { }
1449af245d11STodd Fiala 
1450af245d11STodd Fiala // -----------------------------------------------------------------------------
1451af245d11STodd Fiala // Public Static Methods
1452af245d11STodd Fiala // -----------------------------------------------------------------------------
1453af245d11STodd Fiala 
1454db264a6dSTamas Berghammer Error
1455af245d11STodd Fiala NativeProcessLinux::LaunchProcess (
1456db264a6dSTamas Berghammer     Module *exe_module,
1457db264a6dSTamas Berghammer     ProcessLaunchInfo &launch_info,
1458db264a6dSTamas Berghammer     NativeProcessProtocol::NativeDelegate &native_delegate,
1459af245d11STodd Fiala     NativeProcessProtocolSP &native_process_sp)
1460af245d11STodd Fiala {
1461af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1462af245d11STodd Fiala 
1463af245d11STodd Fiala     Error error;
1464af245d11STodd Fiala 
1465af245d11STodd Fiala     // Verify the working directory is valid if one was specified.
1466af245d11STodd Fiala     const char* working_dir = launch_info.GetWorkingDirectory ();
1467af245d11STodd Fiala     if (working_dir)
1468af245d11STodd Fiala     {
1469af245d11STodd Fiala       FileSpec working_dir_fs (working_dir, true);
1470af245d11STodd Fiala       if (!working_dir_fs || working_dir_fs.GetFileType () != FileSpec::eFileTypeDirectory)
1471af245d11STodd Fiala       {
1472af245d11STodd Fiala           error.SetErrorStringWithFormat ("No such file or directory: %s", working_dir);
1473af245d11STodd Fiala           return error;
1474af245d11STodd Fiala       }
1475af245d11STodd Fiala     }
1476af245d11STodd Fiala 
1477db264a6dSTamas Berghammer     const FileAction *file_action;
1478af245d11STodd Fiala 
1479af245d11STodd Fiala     // Default of NULL will mean to use existing open file descriptors.
148075f47c3aSTodd Fiala     std::string stdin_path;
148175f47c3aSTodd Fiala     std::string stdout_path;
148275f47c3aSTodd Fiala     std::string stderr_path;
1483af245d11STodd Fiala 
1484af245d11STodd Fiala     file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
148575f47c3aSTodd Fiala     if (file_action)
148675f47c3aSTodd Fiala         stdin_path = file_action->GetPath ();
1487af245d11STodd Fiala 
1488af245d11STodd Fiala     file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
148975f47c3aSTodd Fiala     if (file_action)
149075f47c3aSTodd Fiala         stdout_path = file_action->GetPath ();
1491af245d11STodd Fiala 
1492af245d11STodd Fiala     file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
149375f47c3aSTodd Fiala     if (file_action)
149475f47c3aSTodd Fiala         stderr_path = file_action->GetPath ();
149575f47c3aSTodd Fiala 
149675f47c3aSTodd Fiala     if (log)
149775f47c3aSTodd Fiala     {
149875f47c3aSTodd Fiala         if (!stdin_path.empty ())
149975f47c3aSTodd Fiala             log->Printf ("NativeProcessLinux::%s setting STDIN to '%s'", __FUNCTION__, stdin_path.c_str ());
150075f47c3aSTodd Fiala         else
150175f47c3aSTodd Fiala             log->Printf ("NativeProcessLinux::%s leaving STDIN as is", __FUNCTION__);
150275f47c3aSTodd Fiala 
150375f47c3aSTodd Fiala         if (!stdout_path.empty ())
150475f47c3aSTodd Fiala             log->Printf ("NativeProcessLinux::%s setting STDOUT to '%s'", __FUNCTION__, stdout_path.c_str ());
150575f47c3aSTodd Fiala         else
150675f47c3aSTodd Fiala             log->Printf ("NativeProcessLinux::%s leaving STDOUT as is", __FUNCTION__);
150775f47c3aSTodd Fiala 
150875f47c3aSTodd Fiala         if (!stderr_path.empty ())
150975f47c3aSTodd Fiala             log->Printf ("NativeProcessLinux::%s setting STDERR to '%s'", __FUNCTION__, stderr_path.c_str ());
151075f47c3aSTodd Fiala         else
151175f47c3aSTodd Fiala             log->Printf ("NativeProcessLinux::%s leaving STDERR as is", __FUNCTION__);
151275f47c3aSTodd Fiala     }
1513af245d11STodd Fiala 
1514af245d11STodd Fiala     // Create the NativeProcessLinux in launch mode.
1515af245d11STodd Fiala     native_process_sp.reset (new NativeProcessLinux ());
1516af245d11STodd Fiala 
1517af245d11STodd Fiala     if (log)
1518af245d11STodd Fiala     {
1519af245d11STodd Fiala         int i = 0;
1520af245d11STodd Fiala         for (const char **args = launch_info.GetArguments ().GetConstArgumentVector (); *args; ++args, ++i)
1521af245d11STodd Fiala         {
1522af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s arg %d: \"%s\"", __FUNCTION__, i, *args ? *args : "nullptr");
1523af245d11STodd Fiala             ++i;
1524af245d11STodd Fiala         }
1525af245d11STodd Fiala     }
1526af245d11STodd Fiala 
1527af245d11STodd Fiala     if (!native_process_sp->RegisterNativeDelegate (native_delegate))
1528af245d11STodd Fiala     {
1529af245d11STodd Fiala         native_process_sp.reset ();
1530af245d11STodd Fiala         error.SetErrorStringWithFormat ("failed to register the native delegate");
1531af245d11STodd Fiala         return error;
1532af245d11STodd Fiala     }
1533af245d11STodd Fiala 
1534cb84eebbSTamas Berghammer     std::static_pointer_cast<NativeProcessLinux> (native_process_sp)->LaunchInferior (
1535af245d11STodd Fiala             exe_module,
1536af245d11STodd Fiala             launch_info.GetArguments ().GetConstArgumentVector (),
1537af245d11STodd Fiala             launch_info.GetEnvironmentEntries ().GetConstArgumentVector (),
1538af245d11STodd Fiala             stdin_path,
1539af245d11STodd Fiala             stdout_path,
1540af245d11STodd Fiala             stderr_path,
1541af245d11STodd Fiala             working_dir,
15420bce1b67STodd Fiala             launch_info,
1543af245d11STodd Fiala             error);
1544af245d11STodd Fiala 
1545af245d11STodd Fiala     if (error.Fail ())
1546af245d11STodd Fiala     {
1547af245d11STodd Fiala         native_process_sp.reset ();
1548af245d11STodd Fiala         if (log)
1549af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s failed to launch process: %s", __FUNCTION__, error.AsCString ());
1550af245d11STodd Fiala         return error;
1551af245d11STodd Fiala     }
1552af245d11STodd Fiala 
1553af245d11STodd Fiala     launch_info.SetProcessID (native_process_sp->GetID ());
1554af245d11STodd Fiala 
1555af245d11STodd Fiala     return error;
1556af245d11STodd Fiala }
1557af245d11STodd Fiala 
1558db264a6dSTamas Berghammer Error
1559af245d11STodd Fiala NativeProcessLinux::AttachToProcess (
1560af245d11STodd Fiala     lldb::pid_t pid,
1561db264a6dSTamas Berghammer     NativeProcessProtocol::NativeDelegate &native_delegate,
1562af245d11STodd Fiala     NativeProcessProtocolSP &native_process_sp)
1563af245d11STodd Fiala {
1564af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1565af245d11STodd Fiala     if (log && log->GetMask ().Test (POSIX_LOG_VERBOSE))
1566af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
1567af245d11STodd Fiala 
1568af245d11STodd Fiala     // Grab the current platform architecture.  This should be Linux,
1569af245d11STodd Fiala     // since this code is only intended to run on a Linux host.
1570615eb7e6SGreg Clayton     PlatformSP platform_sp (Platform::GetHostPlatform ());
1571af245d11STodd Fiala     if (!platform_sp)
1572af245d11STodd Fiala         return Error("failed to get a valid default platform");
1573af245d11STodd Fiala 
1574af245d11STodd Fiala     // Retrieve the architecture for the running process.
1575af245d11STodd Fiala     ArchSpec process_arch;
1576af245d11STodd Fiala     Error error = ResolveProcessArchitecture (pid, *platform_sp.get (), process_arch);
1577af245d11STodd Fiala     if (!error.Success ())
1578af245d11STodd Fiala         return error;
1579af245d11STodd Fiala 
15801339b5e8SOleksiy Vyalov     std::shared_ptr<NativeProcessLinux> native_process_linux_sp (new NativeProcessLinux ());
1581af245d11STodd Fiala 
15821339b5e8SOleksiy Vyalov     if (!native_process_linux_sp->RegisterNativeDelegate (native_delegate))
1583af245d11STodd Fiala     {
1584af245d11STodd Fiala         error.SetErrorStringWithFormat ("failed to register the native delegate");
1585af245d11STodd Fiala         return error;
1586af245d11STodd Fiala     }
1587af245d11STodd Fiala 
15881339b5e8SOleksiy Vyalov     native_process_linux_sp->AttachToInferior (pid, error);
1589af245d11STodd Fiala     if (!error.Success ())
1590af245d11STodd Fiala         return error;
1591af245d11STodd Fiala 
15921339b5e8SOleksiy Vyalov     native_process_sp = native_process_linux_sp;
1593af245d11STodd Fiala     return error;
1594af245d11STodd Fiala }
1595af245d11STodd Fiala 
1596af245d11STodd Fiala // -----------------------------------------------------------------------------
1597af245d11STodd Fiala // Public Instance Methods
1598af245d11STodd Fiala // -----------------------------------------------------------------------------
1599af245d11STodd Fiala 
1600af245d11STodd Fiala NativeProcessLinux::NativeProcessLinux () :
1601af245d11STodd Fiala     NativeProcessProtocol (LLDB_INVALID_PROCESS_ID),
1602af245d11STodd Fiala     m_arch (),
1603af245d11STodd Fiala     m_supports_mem_region (eLazyBoolCalculate),
1604af245d11STodd Fiala     m_mem_region_cache (),
16058c8ff7afSPavel Labath     m_mem_region_cache_mutex ()
1606af245d11STodd Fiala {
1607af245d11STodd Fiala }
1608af245d11STodd Fiala 
1609af245d11STodd Fiala //------------------------------------------------------------------------------
1610bd7cbc5aSPavel Labath // NativeProcessLinux spawns a new thread which performs all operations on the inferior process.
1611bd7cbc5aSPavel Labath // Refer to Monitor and Operation classes to see why this is necessary.
1612bd7cbc5aSPavel Labath //------------------------------------------------------------------------------
1613af245d11STodd Fiala void
1614af245d11STodd Fiala NativeProcessLinux::LaunchInferior (
1615af245d11STodd Fiala     Module *module,
1616af245d11STodd Fiala     const char *argv[],
1617af245d11STodd Fiala     const char *envp[],
161875f47c3aSTodd Fiala     const std::string &stdin_path,
161975f47c3aSTodd Fiala     const std::string &stdout_path,
162075f47c3aSTodd Fiala     const std::string &stderr_path,
1621af245d11STodd Fiala     const char *working_dir,
1622db264a6dSTamas Berghammer     const ProcessLaunchInfo &launch_info,
1623db264a6dSTamas Berghammer     Error &error)
1624af245d11STodd Fiala {
1625af245d11STodd Fiala     if (module)
1626af245d11STodd Fiala         m_arch = module->GetArchitecture ();
1627af245d11STodd Fiala 
1628af245d11STodd Fiala     SetState (eStateLaunching);
1629af245d11STodd Fiala 
1630af245d11STodd Fiala     std::unique_ptr<LaunchArgs> args(
1631af245d11STodd Fiala         new LaunchArgs(
1632bd7cbc5aSPavel Labath             module, argv, envp,
1633af245d11STodd Fiala             stdin_path, stdout_path, stderr_path,
16340bce1b67STodd Fiala             working_dir, launch_info));
1635af245d11STodd Fiala 
1636bd7cbc5aSPavel Labath     StartMonitorThread ([&] (Error &e) { return Launch(args.get(), e); }, error);
1637af245d11STodd Fiala     if (!error.Success ())
1638af245d11STodd Fiala         return;
1639af245d11STodd Fiala }
1640af245d11STodd Fiala 
1641af245d11STodd Fiala void
1642db264a6dSTamas Berghammer NativeProcessLinux::AttachToInferior (lldb::pid_t pid, Error &error)
1643af245d11STodd Fiala {
1644af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1645af245d11STodd Fiala     if (log)
1646af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
1647af245d11STodd Fiala 
1648af245d11STodd Fiala     // We can use the Host for everything except the ResolveExecutable portion.
1649615eb7e6SGreg Clayton     PlatformSP platform_sp = Platform::GetHostPlatform ();
1650af245d11STodd Fiala     if (!platform_sp)
1651af245d11STodd Fiala     {
1652af245d11STodd Fiala         if (log)
1653af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): no default platform set", __FUNCTION__, pid);
1654af245d11STodd Fiala         error.SetErrorString ("no default platform available");
165550d60be3SShawn Best         return;
1656af245d11STodd Fiala     }
1657af245d11STodd Fiala 
1658af245d11STodd Fiala     // Gather info about the process.
1659af245d11STodd Fiala     ProcessInstanceInfo process_info;
166050d60be3SShawn Best     if (!platform_sp->GetProcessInfo (pid, process_info))
166150d60be3SShawn Best     {
166250d60be3SShawn Best         if (log)
166350d60be3SShawn Best             log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): failed to get process info", __FUNCTION__, pid);
166450d60be3SShawn Best         error.SetErrorString ("failed to get process info");
166550d60be3SShawn Best         return;
166650d60be3SShawn Best     }
1667af245d11STodd Fiala 
1668af245d11STodd Fiala     // Resolve the executable module
1669af245d11STodd Fiala     ModuleSP exe_module_sp;
1670af245d11STodd Fiala     FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
1671e56f6dceSChaoren Lin     ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
16726edef204SOleksiy Vyalov     error = platform_sp->ResolveExecutable(exe_module_spec, exe_module_sp,
1673af245d11STodd Fiala                                            executable_search_paths.GetSize() ? &executable_search_paths : NULL);
1674af245d11STodd Fiala     if (!error.Success())
1675af245d11STodd Fiala         return;
1676af245d11STodd Fiala 
1677af245d11STodd Fiala     // Set the architecture to the exe architecture.
1678af245d11STodd Fiala     m_arch = exe_module_sp->GetArchitecture();
1679af245d11STodd Fiala     if (log)
1680af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
1681af245d11STodd Fiala 
1682af245d11STodd Fiala     m_pid = pid;
1683af245d11STodd Fiala     SetState(eStateAttaching);
1684af245d11STodd Fiala 
1685bd7cbc5aSPavel Labath     StartMonitorThread ([=] (Error &e) { return Attach(pid, e); }, error);
1686af245d11STodd Fiala     if (!error.Success ())
1687af245d11STodd Fiala         return;
1688af245d11STodd Fiala }
1689af245d11STodd Fiala 
16908bc34f4dSOleksiy Vyalov void
16918bc34f4dSOleksiy Vyalov NativeProcessLinux::Terminate ()
1692af245d11STodd Fiala {
169345f5cb31SPavel Labath     m_monitor_up->Terminate();
1694af245d11STodd Fiala }
1695af245d11STodd Fiala 
1696bd7cbc5aSPavel Labath ::pid_t
1697bd7cbc5aSPavel Labath NativeProcessLinux::Launch(LaunchArgs *args, Error &error)
1698af245d11STodd Fiala {
16990bce1b67STodd Fiala     assert (args && "null args");
1700af245d11STodd Fiala 
1701af245d11STodd Fiala     const char **argv = args->m_argv;
1702af245d11STodd Fiala     const char **envp = args->m_envp;
1703af245d11STodd Fiala     const char *working_dir = args->m_working_dir;
1704af245d11STodd Fiala 
1705af245d11STodd Fiala     lldb_utility::PseudoTerminal terminal;
1706af245d11STodd Fiala     const size_t err_len = 1024;
1707af245d11STodd Fiala     char err_str[err_len];
1708af245d11STodd Fiala     lldb::pid_t pid;
1709af245d11STodd Fiala     NativeThreadProtocolSP thread_sp;
1710af245d11STodd Fiala 
1711af245d11STodd Fiala     lldb::ThreadSP inferior;
1712af245d11STodd Fiala 
1713af245d11STodd Fiala     // Propagate the environment if one is not supplied.
1714af245d11STodd Fiala     if (envp == NULL || envp[0] == NULL)
1715af245d11STodd Fiala         envp = const_cast<const char **>(environ);
1716af245d11STodd Fiala 
1717af245d11STodd Fiala     if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
1718af245d11STodd Fiala     {
1719bd7cbc5aSPavel Labath         error.SetErrorToGenericError();
1720bd7cbc5aSPavel Labath         error.SetErrorStringWithFormat("Process fork failed: %s", err_str);
1721bd7cbc5aSPavel Labath         return -1;
1722af245d11STodd Fiala     }
1723af245d11STodd Fiala 
1724af245d11STodd Fiala     // Recognized child exit status codes.
1725af245d11STodd Fiala     enum {
1726af245d11STodd Fiala         ePtraceFailed = 1,
1727af245d11STodd Fiala         eDupStdinFailed,
1728af245d11STodd Fiala         eDupStdoutFailed,
1729af245d11STodd Fiala         eDupStderrFailed,
1730af245d11STodd Fiala         eChdirFailed,
1731af245d11STodd Fiala         eExecFailed,
1732af245d11STodd Fiala         eSetGidFailed
1733af245d11STodd Fiala     };
1734af245d11STodd Fiala 
1735af245d11STodd Fiala     // Child process.
1736af245d11STodd Fiala     if (pid == 0)
1737af245d11STodd Fiala     {
173875f47c3aSTodd Fiala         // FIXME consider opening a pipe between parent/child and have this forked child
173975f47c3aSTodd Fiala         // send log info to parent re: launch status, in place of the log lines removed here.
1740af245d11STodd Fiala 
174175f47c3aSTodd Fiala         // Start tracing this child that is about to exec.
1742bd7cbc5aSPavel Labath         PTRACE(PTRACE_TRACEME, 0, nullptr, nullptr, 0, error);
1743bd7cbc5aSPavel Labath         if (error.Fail())
1744af245d11STodd Fiala             exit(ePtraceFailed);
1745af245d11STodd Fiala 
1746493c3a12SPavel Labath         // terminal has already dupped the tty descriptors to stdin/out/err.
1747493c3a12SPavel Labath         // This closes original fd from which they were copied (and avoids
1748493c3a12SPavel Labath         // leaking descriptors to the debugged process.
1749493c3a12SPavel Labath         terminal.CloseSlaveFileDescriptor();
1750493c3a12SPavel Labath 
1751af245d11STodd Fiala         // Do not inherit setgid powers.
1752af245d11STodd Fiala         if (setgid(getgid()) != 0)
1753af245d11STodd Fiala             exit(eSetGidFailed);
1754af245d11STodd Fiala 
1755af245d11STodd Fiala         // Attempt to have our own process group.
1756af245d11STodd Fiala         if (setpgid(0, 0) != 0)
1757af245d11STodd Fiala         {
175875f47c3aSTodd Fiala             // FIXME log that this failed. This is common.
1759af245d11STodd Fiala             // Don't allow this to prevent an inferior exec.
1760af245d11STodd Fiala         }
1761af245d11STodd Fiala 
1762af245d11STodd Fiala         // Dup file descriptors if needed.
176375f47c3aSTodd Fiala         if (!args->m_stdin_path.empty ())
176475f47c3aSTodd Fiala             if (!DupDescriptor(args->m_stdin_path.c_str (), STDIN_FILENO, O_RDONLY))
1765af245d11STodd Fiala                 exit(eDupStdinFailed);
1766af245d11STodd Fiala 
176775f47c3aSTodd Fiala         if (!args->m_stdout_path.empty ())
176814f4476aSTamas Berghammer             if (!DupDescriptor(args->m_stdout_path.c_str (), STDOUT_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
1769af245d11STodd Fiala                 exit(eDupStdoutFailed);
1770af245d11STodd Fiala 
177175f47c3aSTodd Fiala         if (!args->m_stderr_path.empty ())
177214f4476aSTamas Berghammer             if (!DupDescriptor(args->m_stderr_path.c_str (), STDERR_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
1773af245d11STodd Fiala                 exit(eDupStderrFailed);
1774af245d11STodd Fiala 
17759cf4f2c2SChaoren Lin         // Close everything besides stdin, stdout, and stderr that has no file
17769cf4f2c2SChaoren Lin         // action to avoid leaking
17779cf4f2c2SChaoren Lin         for (int fd = 3; fd < sysconf(_SC_OPEN_MAX); ++fd)
17789cf4f2c2SChaoren Lin             if (!args->m_launch_info.GetFileActionForFD(fd))
17799cf4f2c2SChaoren Lin                 close(fd);
17809cf4f2c2SChaoren Lin 
1781af245d11STodd Fiala         // Change working directory
1782af245d11STodd Fiala         if (working_dir != NULL && working_dir[0])
1783af245d11STodd Fiala           if (0 != ::chdir(working_dir))
1784af245d11STodd Fiala               exit(eChdirFailed);
1785af245d11STodd Fiala 
17860bce1b67STodd Fiala         // Disable ASLR if requested.
17870bce1b67STodd Fiala         if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR))
17880bce1b67STodd Fiala         {
17890bce1b67STodd Fiala             const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
17900bce1b67STodd Fiala             if (old_personality == -1)
17910bce1b67STodd Fiala             {
179275f47c3aSTodd Fiala                 // Can't retrieve Linux personality.  Cannot disable ASLR.
17930bce1b67STodd Fiala             }
17940bce1b67STodd Fiala             else
17950bce1b67STodd Fiala             {
17960bce1b67STodd Fiala                 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality);
17970bce1b67STodd Fiala                 if (new_personality == -1)
17980bce1b67STodd Fiala                 {
179975f47c3aSTodd Fiala                     // Disabling ASLR failed.
18000bce1b67STodd Fiala                 }
18010bce1b67STodd Fiala                 else
18020bce1b67STodd Fiala                 {
180375f47c3aSTodd Fiala                     // Disabling ASLR succeeded.
18040bce1b67STodd Fiala                 }
18050bce1b67STodd Fiala             }
18060bce1b67STodd Fiala         }
18070bce1b67STodd Fiala 
180875f47c3aSTodd Fiala         // Execute.  We should never return...
1809af245d11STodd Fiala         execve(argv[0],
1810af245d11STodd Fiala                const_cast<char *const *>(argv),
1811af245d11STodd Fiala                const_cast<char *const *>(envp));
181275f47c3aSTodd Fiala 
181375f47c3aSTodd Fiala         // ...unless exec fails.  In which case we definitely need to end the child here.
1814af245d11STodd Fiala         exit(eExecFailed);
1815af245d11STodd Fiala     }
1816af245d11STodd Fiala 
181775f47c3aSTodd Fiala     //
181875f47c3aSTodd Fiala     // This is the parent code here.
181975f47c3aSTodd Fiala     //
182075f47c3aSTodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
182175f47c3aSTodd Fiala 
1822af245d11STodd Fiala     // Wait for the child process to trap on its call to execve.
1823af245d11STodd Fiala     ::pid_t wpid;
1824af245d11STodd Fiala     int status;
1825af245d11STodd Fiala     if ((wpid = waitpid(pid, &status, 0)) < 0)
1826af245d11STodd Fiala     {
1827bd7cbc5aSPavel Labath         error.SetErrorToErrno();
1828af245d11STodd Fiala         if (log)
1829bd7cbc5aSPavel Labath             log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s",
1830bd7cbc5aSPavel Labath                     __FUNCTION__, error.AsCString ());
1831af245d11STodd Fiala 
1832af245d11STodd Fiala         // Mark the inferior as invalid.
1833af245d11STodd Fiala         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
1834bd7cbc5aSPavel Labath         SetState (StateType::eStateInvalid);
1835af245d11STodd Fiala 
1836bd7cbc5aSPavel Labath         return -1;
1837af245d11STodd Fiala     }
1838af245d11STodd Fiala     else if (WIFEXITED(status))
1839af245d11STodd Fiala     {
1840af245d11STodd Fiala         // open, dup or execve likely failed for some reason.
1841bd7cbc5aSPavel Labath         error.SetErrorToGenericError();
1842af245d11STodd Fiala         switch (WEXITSTATUS(status))
1843af245d11STodd Fiala         {
1844af245d11STodd Fiala             case ePtraceFailed:
1845bd7cbc5aSPavel Labath                 error.SetErrorString("Child ptrace failed.");
1846af245d11STodd Fiala                 break;
1847af245d11STodd Fiala             case eDupStdinFailed:
1848bd7cbc5aSPavel Labath                 error.SetErrorString("Child open stdin failed.");
1849af245d11STodd Fiala                 break;
1850af245d11STodd Fiala             case eDupStdoutFailed:
1851bd7cbc5aSPavel Labath                 error.SetErrorString("Child open stdout failed.");
1852af245d11STodd Fiala                 break;
1853af245d11STodd Fiala             case eDupStderrFailed:
1854bd7cbc5aSPavel Labath                 error.SetErrorString("Child open stderr failed.");
1855af245d11STodd Fiala                 break;
1856af245d11STodd Fiala             case eChdirFailed:
1857bd7cbc5aSPavel Labath                 error.SetErrorString("Child failed to set working directory.");
1858af245d11STodd Fiala                 break;
1859af245d11STodd Fiala             case eExecFailed:
1860bd7cbc5aSPavel Labath                 error.SetErrorString("Child exec failed.");
1861af245d11STodd Fiala                 break;
1862af245d11STodd Fiala             case eSetGidFailed:
1863bd7cbc5aSPavel Labath                 error.SetErrorString("Child setgid failed.");
1864af245d11STodd Fiala                 break;
1865af245d11STodd Fiala             default:
1866bd7cbc5aSPavel Labath                 error.SetErrorString("Child returned unknown exit status.");
1867af245d11STodd Fiala                 break;
1868af245d11STodd Fiala         }
1869af245d11STodd Fiala 
1870af245d11STodd Fiala         if (log)
1871af245d11STodd Fiala         {
1872af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
1873af245d11STodd Fiala                     __FUNCTION__,
1874af245d11STodd Fiala                     WEXITSTATUS(status));
1875af245d11STodd Fiala         }
1876af245d11STodd Fiala 
1877af245d11STodd Fiala         // Mark the inferior as invalid.
1878af245d11STodd Fiala         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
1879bd7cbc5aSPavel Labath         SetState (StateType::eStateInvalid);
1880af245d11STodd Fiala 
1881bd7cbc5aSPavel Labath         return -1;
1882af245d11STodd Fiala     }
1883af245d11STodd Fiala     assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
1884af245d11STodd Fiala            "Could not sync with inferior process.");
1885af245d11STodd Fiala 
1886af245d11STodd Fiala     if (log)
1887af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
1888af245d11STodd Fiala 
1889bd7cbc5aSPavel Labath     error = SetDefaultPtraceOpts(pid);
1890bd7cbc5aSPavel Labath     if (error.Fail())
1891af245d11STodd Fiala     {
1892af245d11STodd Fiala         if (log)
1893af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
1894bd7cbc5aSPavel Labath                     __FUNCTION__, error.AsCString ());
1895af245d11STodd Fiala 
1896af245d11STodd Fiala         // Mark the inferior as invalid.
1897af245d11STodd Fiala         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
1898bd7cbc5aSPavel Labath         SetState (StateType::eStateInvalid);
1899af245d11STodd Fiala 
1900bd7cbc5aSPavel Labath         return -1;
1901af245d11STodd Fiala     }
1902af245d11STodd Fiala 
1903af245d11STodd Fiala     // Release the master terminal descriptor and pass it off to the
1904af245d11STodd Fiala     // NativeProcessLinux instance.  Similarly stash the inferior pid.
1905bd7cbc5aSPavel Labath     m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1906bd7cbc5aSPavel Labath     m_pid = pid;
1907af245d11STodd Fiala 
1908af245d11STodd Fiala     // Set the terminal fd to be in non blocking mode (it simplifies the
1909af245d11STodd Fiala     // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1910af245d11STodd Fiala     // descriptor to read from).
1911bd7cbc5aSPavel Labath     error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
1912bd7cbc5aSPavel Labath     if (error.Fail())
1913af245d11STodd Fiala     {
1914af245d11STodd Fiala         if (log)
1915af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
1916bd7cbc5aSPavel Labath                     __FUNCTION__, error.AsCString ());
1917af245d11STodd Fiala 
1918af245d11STodd Fiala         // Mark the inferior as invalid.
1919af245d11STodd Fiala         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
1920bd7cbc5aSPavel Labath         SetState (StateType::eStateInvalid);
1921af245d11STodd Fiala 
1922bd7cbc5aSPavel Labath         return -1;
1923af245d11STodd Fiala     }
1924af245d11STodd Fiala 
1925af245d11STodd Fiala     if (log)
1926af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
1927af245d11STodd Fiala 
1928bd7cbc5aSPavel Labath     thread_sp = AddThread (pid);
1929af245d11STodd Fiala     assert (thread_sp && "AddThread() returned a nullptr thread");
1930cb84eebbSTamas Berghammer     std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
19318c8ff7afSPavel Labath     NotifyThreadCreate(pid);
1932af245d11STodd Fiala 
1933af245d11STodd Fiala     // Let our process instance know the thread has stopped.
1934bd7cbc5aSPavel Labath     SetCurrentThreadID (thread_sp->GetID ());
1935bd7cbc5aSPavel Labath     SetState (StateType::eStateStopped);
1936af245d11STodd Fiala 
1937af245d11STodd Fiala     if (log)
1938af245d11STodd Fiala     {
1939bd7cbc5aSPavel Labath         if (error.Success ())
1940af245d11STodd Fiala         {
1941af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
1942af245d11STodd Fiala         }
1943af245d11STodd Fiala         else
1944af245d11STodd Fiala         {
1945af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior launching failed: %s",
1946bd7cbc5aSPavel Labath                 __FUNCTION__, error.AsCString ());
1947bd7cbc5aSPavel Labath             return -1;
1948af245d11STodd Fiala         }
1949af245d11STodd Fiala     }
1950bd7cbc5aSPavel Labath     return pid;
1951af245d11STodd Fiala }
1952af245d11STodd Fiala 
1953bd7cbc5aSPavel Labath ::pid_t
1954bd7cbc5aSPavel Labath NativeProcessLinux::Attach(lldb::pid_t pid, Error &error)
1955af245d11STodd Fiala {
1956af245d11STodd Fiala     lldb::ThreadSP inferior;
1957af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1958af245d11STodd Fiala 
1959af245d11STodd Fiala     // Use a map to keep track of the threads which we have attached/need to attach.
1960af245d11STodd Fiala     Host::TidMap tids_to_attach;
1961af245d11STodd Fiala     if (pid <= 1)
1962af245d11STodd Fiala     {
1963bd7cbc5aSPavel Labath         error.SetErrorToGenericError();
1964bd7cbc5aSPavel Labath         error.SetErrorString("Attaching to process 1 is not allowed.");
1965bd7cbc5aSPavel Labath         return -1;
1966af245d11STodd Fiala     }
1967af245d11STodd Fiala 
1968af245d11STodd Fiala     while (Host::FindProcessThreads(pid, tids_to_attach))
1969af245d11STodd Fiala     {
1970af245d11STodd Fiala         for (Host::TidMap::iterator it = tids_to_attach.begin();
1971af245d11STodd Fiala              it != tids_to_attach.end();)
1972af245d11STodd Fiala         {
1973af245d11STodd Fiala             if (it->second == false)
1974af245d11STodd Fiala             {
1975af245d11STodd Fiala                 lldb::tid_t tid = it->first;
1976af245d11STodd Fiala 
1977af245d11STodd Fiala                 // Attach to the requested process.
1978af245d11STodd Fiala                 // An attach will cause the thread to stop with a SIGSTOP.
1979bd7cbc5aSPavel Labath                 PTRACE(PTRACE_ATTACH, tid, nullptr, nullptr, 0, error);
1980bd7cbc5aSPavel Labath                 if (error.Fail())
1981af245d11STodd Fiala                 {
1982af245d11STodd Fiala                     // No such thread. The thread may have exited.
1983af245d11STodd Fiala                     // More error handling may be needed.
1984bd7cbc5aSPavel Labath                     if (error.GetError() == ESRCH)
1985af245d11STodd Fiala                     {
1986af245d11STodd Fiala                         it = tids_to_attach.erase(it);
1987af245d11STodd Fiala                         continue;
1988af245d11STodd Fiala                     }
1989af245d11STodd Fiala                     else
1990bd7cbc5aSPavel Labath                         return -1;
1991af245d11STodd Fiala                 }
1992af245d11STodd Fiala 
1993af245d11STodd Fiala                 int status;
1994af245d11STodd Fiala                 // Need to use __WALL otherwise we receive an error with errno=ECHLD
1995af245d11STodd Fiala                 // At this point we should have a thread stopped if waitpid succeeds.
1996af245d11STodd Fiala                 if ((status = waitpid(tid, NULL, __WALL)) < 0)
1997af245d11STodd Fiala                 {
1998af245d11STodd Fiala                     // No such thread. The thread may have exited.
1999af245d11STodd Fiala                     // More error handling may be needed.
2000af245d11STodd Fiala                     if (errno == ESRCH)
2001af245d11STodd Fiala                     {
2002af245d11STodd Fiala                         it = tids_to_attach.erase(it);
2003af245d11STodd Fiala                         continue;
2004af245d11STodd Fiala                     }
2005af245d11STodd Fiala                     else
2006af245d11STodd Fiala                     {
2007bd7cbc5aSPavel Labath                         error.SetErrorToErrno();
2008bd7cbc5aSPavel Labath                         return -1;
2009af245d11STodd Fiala                     }
2010af245d11STodd Fiala                 }
2011af245d11STodd Fiala 
2012bd7cbc5aSPavel Labath                 error = SetDefaultPtraceOpts(tid);
2013bd7cbc5aSPavel Labath                 if (error.Fail())
2014bd7cbc5aSPavel Labath                     return -1;
2015af245d11STodd Fiala 
2016af245d11STodd Fiala                 if (log)
2017af245d11STodd Fiala                     log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
2018af245d11STodd Fiala 
2019af245d11STodd Fiala                 it->second = true;
2020af245d11STodd Fiala 
2021af245d11STodd Fiala                 // Create the thread, mark it as stopped.
2022bd7cbc5aSPavel Labath                 NativeThreadProtocolSP thread_sp (AddThread (static_cast<lldb::tid_t> (tid)));
2023af245d11STodd Fiala                 assert (thread_sp && "AddThread() returned a nullptr");
2024fa03ad2eSChaoren Lin 
2025fa03ad2eSChaoren Lin                 // This will notify this is a new thread and tell the system it is stopped.
2026cb84eebbSTamas Berghammer                 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
20278c8ff7afSPavel Labath                 NotifyThreadCreate(tid);
2028bd7cbc5aSPavel Labath                 SetCurrentThreadID (thread_sp->GetID ());
2029af245d11STodd Fiala             }
2030af245d11STodd Fiala 
2031af245d11STodd Fiala             // move the loop forward
2032af245d11STodd Fiala             ++it;
2033af245d11STodd Fiala         }
2034af245d11STodd Fiala     }
2035af245d11STodd Fiala 
2036af245d11STodd Fiala     if (tids_to_attach.size() > 0)
2037af245d11STodd Fiala     {
2038bd7cbc5aSPavel Labath         m_pid = pid;
2039af245d11STodd Fiala         // Let our process instance know the thread has stopped.
2040bd7cbc5aSPavel Labath         SetState (StateType::eStateStopped);
2041af245d11STodd Fiala     }
2042af245d11STodd Fiala     else
2043af245d11STodd Fiala     {
2044bd7cbc5aSPavel Labath         error.SetErrorToGenericError();
2045bd7cbc5aSPavel Labath         error.SetErrorString("No such process.");
2046bd7cbc5aSPavel Labath         return -1;
2047af245d11STodd Fiala     }
2048af245d11STodd Fiala 
2049bd7cbc5aSPavel Labath     return pid;
2050af245d11STodd Fiala }
2051af245d11STodd Fiala 
205297ccc294SChaoren Lin Error
2053af245d11STodd Fiala NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
2054af245d11STodd Fiala {
2055af245d11STodd Fiala     long ptrace_opts = 0;
2056af245d11STodd Fiala 
2057af245d11STodd Fiala     // Have the child raise an event on exit.  This is used to keep the child in
2058af245d11STodd Fiala     // limbo until it is destroyed.
2059af245d11STodd Fiala     ptrace_opts |= PTRACE_O_TRACEEXIT;
2060af245d11STodd Fiala 
2061af245d11STodd Fiala     // Have the tracer trace threads which spawn in the inferior process.
2062af245d11STodd Fiala     // TODO: if we want to support tracing the inferiors' child, add the
2063af245d11STodd Fiala     // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
2064af245d11STodd Fiala     ptrace_opts |= PTRACE_O_TRACECLONE;
2065af245d11STodd Fiala 
2066af245d11STodd Fiala     // Have the tracer notify us before execve returns
2067af245d11STodd Fiala     // (needed to disable legacy SIGTRAP generation)
2068af245d11STodd Fiala     ptrace_opts |= PTRACE_O_TRACEEXEC;
2069af245d11STodd Fiala 
207097ccc294SChaoren Lin     Error error;
207197ccc294SChaoren Lin     PTRACE(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts, 0, error);
207297ccc294SChaoren Lin     return error;
2073af245d11STodd Fiala }
2074af245d11STodd Fiala 
2075af245d11STodd Fiala static ExitType convert_pid_status_to_exit_type (int status)
2076af245d11STodd Fiala {
2077af245d11STodd Fiala     if (WIFEXITED (status))
2078af245d11STodd Fiala         return ExitType::eExitTypeExit;
2079af245d11STodd Fiala     else if (WIFSIGNALED (status))
2080af245d11STodd Fiala         return ExitType::eExitTypeSignal;
2081af245d11STodd Fiala     else if (WIFSTOPPED (status))
2082af245d11STodd Fiala         return ExitType::eExitTypeStop;
2083af245d11STodd Fiala     else
2084af245d11STodd Fiala     {
2085af245d11STodd Fiala         // We don't know what this is.
2086af245d11STodd Fiala         return ExitType::eExitTypeInvalid;
2087af245d11STodd Fiala     }
2088af245d11STodd Fiala }
2089af245d11STodd Fiala 
2090af245d11STodd Fiala static int convert_pid_status_to_return_code (int status)
2091af245d11STodd Fiala {
2092af245d11STodd Fiala     if (WIFEXITED (status))
2093af245d11STodd Fiala         return WEXITSTATUS (status);
2094af245d11STodd Fiala     else if (WIFSIGNALED (status))
2095af245d11STodd Fiala         return WTERMSIG (status);
2096af245d11STodd Fiala     else if (WIFSTOPPED (status))
2097af245d11STodd Fiala         return WSTOPSIG (status);
2098af245d11STodd Fiala     else
2099af245d11STodd Fiala     {
2100af245d11STodd Fiala         // We don't know what this is.
2101af245d11STodd Fiala         return ExitType::eExitTypeInvalid;
2102af245d11STodd Fiala     }
2103af245d11STodd Fiala }
2104af245d11STodd Fiala 
21051107b5a5SPavel Labath // Handles all waitpid events from the inferior process.
21061107b5a5SPavel Labath void
21071107b5a5SPavel Labath NativeProcessLinux::MonitorCallback(lldb::pid_t pid,
2108af245d11STodd Fiala                                     bool exited,
2109af245d11STodd Fiala                                     int signal,
2110af245d11STodd Fiala                                     int status)
2111af245d11STodd Fiala {
2112af245d11STodd Fiala     Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
2113af245d11STodd Fiala 
2114af245d11STodd Fiala     // Certain activities differ based on whether the pid is the tid of the main thread.
21151107b5a5SPavel Labath     const bool is_main_thread = (pid == GetID ());
2116af245d11STodd Fiala 
2117af245d11STodd Fiala     // Handle when the thread exits.
2118af245d11STodd Fiala     if (exited)
2119af245d11STodd Fiala     {
2120af245d11STodd Fiala         if (log)
212186fd8e45SChaoren Lin             log->Printf ("NativeProcessLinux::%s() got exit signal(%d) , tid = %"  PRIu64 " (%s main thread)", __FUNCTION__, signal, pid, is_main_thread ? "is" : "is not");
2122af245d11STodd Fiala 
2123af245d11STodd Fiala         // This is a thread that exited.  Ensure we're not tracking it anymore.
21241107b5a5SPavel Labath         const bool thread_found = StopTrackingThread (pid);
2125af245d11STodd Fiala 
2126fa03ad2eSChaoren Lin         // Make sure the thread state coordinator knows about this.
21271107b5a5SPavel Labath         NotifyThreadDeath (pid);
2128fa03ad2eSChaoren Lin 
2129af245d11STodd Fiala         if (is_main_thread)
2130af245d11STodd Fiala         {
2131af245d11STodd Fiala             // We only set the exit status and notify the delegate if we haven't already set the process
2132af245d11STodd Fiala             // state to an exited state.  We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
2133af245d11STodd Fiala             // for the main thread.
21341107b5a5SPavel Labath             const bool already_notified = (GetState() == StateType::eStateExited) || (GetState () == StateType::eStateCrashed);
2135af245d11STodd Fiala             if (!already_notified)
2136af245d11STodd Fiala             {
2137af245d11STodd Fiala                 if (log)
21381107b5a5SPavel Labath                     log->Printf ("NativeProcessLinux::%s() tid = %"  PRIu64 " handling main thread exit (%s), expected exit state already set but state was %s instead, setting exit state now", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found", StateAsCString (GetState ()));
2139af245d11STodd Fiala                 // The main thread exited.  We're done monitoring.  Report to delegate.
21401107b5a5SPavel Labath                 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
2141af245d11STodd Fiala 
2142af245d11STodd Fiala                 // Notify delegate that our process has exited.
21431107b5a5SPavel Labath                 SetState (StateType::eStateExited, true);
2144af245d11STodd Fiala             }
2145af245d11STodd Fiala             else
2146af245d11STodd Fiala             {
2147af245d11STodd Fiala                 if (log)
2148af245d11STodd Fiala                     log->Printf ("NativeProcessLinux::%s() tid = %"  PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
2149af245d11STodd Fiala             }
2150af245d11STodd Fiala         }
2151af245d11STodd Fiala         else
2152af245d11STodd Fiala         {
2153af245d11STodd Fiala             // Do we want to report to the delegate in this case?  I think not.  If this was an orderly
2154af245d11STodd Fiala             // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
2155af245d11STodd Fiala             // and we would have done an all-stop then.
2156af245d11STodd Fiala             if (log)
2157af245d11STodd Fiala                 log->Printf ("NativeProcessLinux::%s() tid = %"  PRIu64 " handling non-main thread exit (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
2158af245d11STodd Fiala         }
21591107b5a5SPavel Labath         return;
2160af245d11STodd Fiala     }
2161af245d11STodd Fiala 
2162af245d11STodd Fiala     // Get details on the signal raised.
2163af245d11STodd Fiala     siginfo_t info;
21641107b5a5SPavel Labath     const auto err = GetSignalInfo(pid, &info);
216597ccc294SChaoren Lin     if (err.Success())
2166fa03ad2eSChaoren Lin     {
2167fa03ad2eSChaoren Lin         // We have retrieved the signal info.  Dispatch appropriately.
2168fa03ad2eSChaoren Lin         if (info.si_signo == SIGTRAP)
21691107b5a5SPavel Labath             MonitorSIGTRAP(&info, pid);
2170fa03ad2eSChaoren Lin         else
21711107b5a5SPavel Labath             MonitorSignal(&info, pid, exited);
2172fa03ad2eSChaoren Lin     }
2173fa03ad2eSChaoren Lin     else
2174af245d11STodd Fiala     {
217597ccc294SChaoren Lin         if (err.GetError() == EINVAL)
2176af245d11STodd Fiala         {
2177fa03ad2eSChaoren Lin             // This is a group stop reception for this tid.
2178fa03ad2eSChaoren Lin             if (log)
21791107b5a5SPavel Labath                 log->Printf ("NativeThreadLinux::%s received a group stop for pid %" PRIu64 " tid %" PRIu64, __FUNCTION__, GetID (), pid);
21805eb721edSPavel Labath             NotifyThreadStop (pid, false);
2181a9882ceeSTodd Fiala         }
2182a9882ceeSTodd Fiala         else
2183a9882ceeSTodd Fiala         {
2184af245d11STodd Fiala             // ptrace(GETSIGINFO) failed (but not due to group-stop).
2185af245d11STodd Fiala 
2186af245d11STodd Fiala             // A return value of ESRCH means the thread/process is no longer on the system,
2187af245d11STodd Fiala             // so it was killed somehow outside of our control.  Either way, we can't do anything
2188af245d11STodd Fiala             // with it anymore.
2189af245d11STodd Fiala 
2190af245d11STodd Fiala             // Stop tracking the metadata for the thread since it's entirely off the system now.
21911107b5a5SPavel Labath             const bool thread_found = StopTrackingThread (pid);
2192af245d11STodd Fiala 
2193fa03ad2eSChaoren Lin             // Make sure the thread state coordinator knows about this.
21941107b5a5SPavel Labath             NotifyThreadDeath (pid);
2195fa03ad2eSChaoren Lin 
2196af245d11STodd Fiala             if (log)
2197af245d11STodd Fiala                 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
219897ccc294SChaoren Lin                              __FUNCTION__, err.AsCString(), pid, signal, status, err.GetError() == ESRCH ? "thread/process killed" : "unknown reason", is_main_thread ? "is main thread" : "is not main thread", thread_found ? "thread metadata removed" : "thread metadata not found");
2199af245d11STodd Fiala 
2200af245d11STodd Fiala             if (is_main_thread)
2201af245d11STodd Fiala             {
2202af245d11STodd Fiala                 // Notify the delegate - our process is not available but appears to have been killed outside
2203af245d11STodd Fiala                 // our control.  Is eStateExited the right exit state in this case?
22041107b5a5SPavel Labath                 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
22051107b5a5SPavel Labath                 SetState (StateType::eStateExited, true);
2206af245d11STodd Fiala             }
2207af245d11STodd Fiala             else
2208af245d11STodd Fiala             {
2209af245d11STodd Fiala                 // This thread was pulled out from underneath us.  Anything to do here? Do we want to do an all stop?
2210af245d11STodd Fiala                 if (log)
22111107b5a5SPavel Labath                     log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 " non-main thread exit occurred, didn't tell delegate anything since thread disappeared out from underneath us", __FUNCTION__, GetID (), pid);
2212af245d11STodd Fiala             }
2213af245d11STodd Fiala         }
2214af245d11STodd Fiala     }
2215af245d11STodd Fiala }
2216af245d11STodd Fiala 
2217af245d11STodd Fiala void
2218426bdf88SPavel Labath NativeProcessLinux::WaitForNewThread(::pid_t tid)
2219426bdf88SPavel Labath {
2220426bdf88SPavel Labath     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2221426bdf88SPavel Labath 
2222426bdf88SPavel Labath     NativeThreadProtocolSP new_thread_sp = GetThreadByID(tid);
2223426bdf88SPavel Labath 
2224426bdf88SPavel Labath     if (new_thread_sp)
2225426bdf88SPavel Labath     {
2226426bdf88SPavel Labath         // We are already tracking the thread - we got the event on the new thread (see
2227426bdf88SPavel Labath         // MonitorSignal) before this one. We are done.
2228426bdf88SPavel Labath         return;
2229426bdf88SPavel Labath     }
2230426bdf88SPavel Labath 
2231426bdf88SPavel Labath     // The thread is not tracked yet, let's wait for it to appear.
2232426bdf88SPavel Labath     int status = -1;
2233426bdf88SPavel Labath     ::pid_t wait_pid;
2234426bdf88SPavel Labath     do
2235426bdf88SPavel Labath     {
2236426bdf88SPavel Labath         if (log)
2237426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() received thread creation event for tid %" PRIu32 ". tid not tracked yet, waiting for thread to appear...", __FUNCTION__, tid);
2238426bdf88SPavel Labath         wait_pid = waitpid(tid, &status, __WALL);
2239426bdf88SPavel Labath     }
2240426bdf88SPavel Labath     while (wait_pid == -1 && errno == EINTR);
2241426bdf88SPavel Labath     // Since we are waiting on a specific tid, this must be the creation event. But let's do
2242426bdf88SPavel Labath     // some checks just in case.
2243426bdf88SPavel Labath     if (wait_pid != tid) {
2244426bdf88SPavel Labath         if (log)
2245426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime", __FUNCTION__, tid);
2246426bdf88SPavel Labath         // The only way I know of this could happen is if the whole process was
2247426bdf88SPavel Labath         // SIGKILLed in the mean time. In any case, we can't do anything about that now.
2248426bdf88SPavel Labath         return;
2249426bdf88SPavel Labath     }
2250426bdf88SPavel Labath     if (WIFEXITED(status))
2251426bdf88SPavel Labath     {
2252426bdf88SPavel Labath         if (log)
2253426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " returned an 'exited' event. Not tracking the thread.", __FUNCTION__, tid);
2254426bdf88SPavel Labath         // Also a very improbable event.
2255426bdf88SPavel Labath         return;
2256426bdf88SPavel Labath     }
2257426bdf88SPavel Labath 
2258426bdf88SPavel Labath     siginfo_t info;
2259426bdf88SPavel Labath     Error error = GetSignalInfo(tid, &info);
2260426bdf88SPavel Labath     if (error.Fail())
2261426bdf88SPavel Labath     {
2262426bdf88SPavel Labath         if (log)
2263426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime.", __FUNCTION__, tid);
2264426bdf88SPavel Labath         return;
2265426bdf88SPavel Labath     }
2266426bdf88SPavel Labath 
2267426bdf88SPavel Labath     if (((info.si_pid != 0) || (info.si_code != SI_USER)) && log)
2268426bdf88SPavel Labath     {
2269426bdf88SPavel Labath         // We should be getting a thread creation signal here, but we received something
2270426bdf88SPavel Labath         // else. There isn't much we can do about it now, so we will just log that. Since the
2271426bdf88SPavel Labath         // thread is alive and we are receiving events from it, we shall pretend that it was
2272426bdf88SPavel Labath         // created properly.
2273426bdf88SPavel Labath         log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " received unexpected signal with code %d from pid %d.", __FUNCTION__, tid, info.si_code, info.si_pid);
2274426bdf88SPavel Labath     }
2275426bdf88SPavel Labath 
2276426bdf88SPavel Labath     if (log)
2277426bdf88SPavel Labath         log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 ": tracking new thread tid %" PRIu32,
2278426bdf88SPavel Labath                  __FUNCTION__, GetID (), tid);
2279426bdf88SPavel Labath 
2280426bdf88SPavel Labath     new_thread_sp = AddThread(tid);
2281426bdf88SPavel Labath     std::static_pointer_cast<NativeThreadLinux> (new_thread_sp)->SetRunning ();
2282426bdf88SPavel Labath     Resume (tid, LLDB_INVALID_SIGNAL_NUMBER);
22838c8ff7afSPavel Labath     NotifyThreadCreate(tid);
2284426bdf88SPavel Labath }
2285426bdf88SPavel Labath 
2286426bdf88SPavel Labath void
2287af245d11STodd Fiala NativeProcessLinux::MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid)
2288af245d11STodd Fiala {
2289af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2290af245d11STodd Fiala     const bool is_main_thread = (pid == GetID ());
2291af245d11STodd Fiala 
2292af245d11STodd Fiala     assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
2293af245d11STodd Fiala     if (!info)
2294af245d11STodd Fiala         return;
2295af245d11STodd Fiala 
22965830aa75STamas Berghammer     Mutex::Locker locker (m_threads_mutex);
22975830aa75STamas Berghammer 
2298af245d11STodd Fiala     // See if we can find a thread for this signal.
2299af245d11STodd Fiala     NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2300af245d11STodd Fiala     if (!thread_sp)
2301af245d11STodd Fiala     {
2302af245d11STodd Fiala         if (log)
2303af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2304af245d11STodd Fiala     }
2305af245d11STodd Fiala 
2306af245d11STodd Fiala     switch (info->si_code)
2307af245d11STodd Fiala     {
2308af245d11STodd Fiala     // TODO: these two cases are required if we want to support tracing of the inferiors' children.  We'd need this to debug a monitor.
2309af245d11STodd Fiala     // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
2310af245d11STodd Fiala     // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
2311af245d11STodd Fiala 
2312af245d11STodd Fiala     case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
2313af245d11STodd Fiala     {
23145fd24c67SPavel Labath         // This is the notification on the parent thread which informs us of new thread
2315426bdf88SPavel Labath         // creation.
2316426bdf88SPavel Labath         // We don't want to do anything with the parent thread so we just resume it. In case we
2317426bdf88SPavel Labath         // want to implement "break on thread creation" functionality, we would need to stop
2318426bdf88SPavel Labath         // here.
2319af245d11STodd Fiala 
2320af245d11STodd Fiala         unsigned long event_message = 0;
2321426bdf88SPavel Labath         if (GetEventMessage (pid, &event_message).Fail())
2322fa03ad2eSChaoren Lin         {
2323426bdf88SPavel Labath             if (log)
2324fa03ad2eSChaoren Lin                 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " received thread creation event but GetEventMessage failed so we don't know the new tid", __FUNCTION__, pid);
2325426bdf88SPavel Labath         } else
2326426bdf88SPavel Labath             WaitForNewThread(event_message);
2327af245d11STodd Fiala 
23285fd24c67SPavel Labath         Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
2329af245d11STodd Fiala         break;
2330af245d11STodd Fiala     }
2331af245d11STodd Fiala 
2332af245d11STodd Fiala     case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
2333a9882ceeSTodd Fiala     {
2334a9882ceeSTodd Fiala         NativeThreadProtocolSP main_thread_sp;
2335af245d11STodd Fiala         if (log)
2336af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
2337a9882ceeSTodd Fiala 
2338fa03ad2eSChaoren Lin         // The thread state coordinator needs to reset due to the exec.
2339c076559aSPavel Labath         ResetForExec ();
2340fa03ad2eSChaoren Lin 
2341fa03ad2eSChaoren Lin         // Remove all but the main thread here.  Linux fork creates a new process which only copies the main thread.  Mutexes are in undefined state.
2342a9882ceeSTodd Fiala         if (log)
2343a9882ceeSTodd Fiala             log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
2344a9882ceeSTodd Fiala 
2345a9882ceeSTodd Fiala         for (auto thread_sp : m_threads)
2346a9882ceeSTodd Fiala         {
2347a9882ceeSTodd Fiala             const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
2348a9882ceeSTodd Fiala             if (is_main_thread)
2349a9882ceeSTodd Fiala             {
2350a9882ceeSTodd Fiala                 main_thread_sp = thread_sp;
2351a9882ceeSTodd Fiala                 if (log)
2352a9882ceeSTodd Fiala                     log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
2353a9882ceeSTodd Fiala             }
2354a9882ceeSTodd Fiala             else
2355a9882ceeSTodd Fiala             {
2356fa03ad2eSChaoren Lin                 // Tell thread coordinator this thread is dead.
2357a9882ceeSTodd Fiala                 if (log)
2358a9882ceeSTodd Fiala                     log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
2359a9882ceeSTodd Fiala             }
2360a9882ceeSTodd Fiala         }
2361a9882ceeSTodd Fiala 
2362a9882ceeSTodd Fiala         m_threads.clear ();
2363a9882ceeSTodd Fiala 
2364a9882ceeSTodd Fiala         if (main_thread_sp)
2365a9882ceeSTodd Fiala         {
2366a9882ceeSTodd Fiala             m_threads.push_back (main_thread_sp);
2367a9882ceeSTodd Fiala             SetCurrentThreadID (main_thread_sp->GetID ());
2368cb84eebbSTamas Berghammer             std::static_pointer_cast<NativeThreadLinux> (main_thread_sp)->SetStoppedByExec ();
2369a9882ceeSTodd Fiala         }
2370a9882ceeSTodd Fiala         else
2371a9882ceeSTodd Fiala         {
2372a9882ceeSTodd Fiala             SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
2373a9882ceeSTodd Fiala             if (log)
2374a9882ceeSTodd Fiala                 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
2375a9882ceeSTodd Fiala         }
2376a9882ceeSTodd Fiala 
2377fa03ad2eSChaoren Lin         // Tell coordinator about about the "new" (since exec) stopped main thread.
2378fa03ad2eSChaoren Lin         const lldb::tid_t main_thread_tid = GetID ();
23798c8ff7afSPavel Labath         NotifyThreadCreate(main_thread_tid);
2380fa03ad2eSChaoren Lin 
2381fa03ad2eSChaoren Lin         // NOTE: ideally these next statements would execute at the same time as the coordinator thread create was executed.
2382fa03ad2eSChaoren Lin         // Consider a handler that can execute when that happens.
2383a9882ceeSTodd Fiala         // Let our delegate know we have just exec'd.
2384a9882ceeSTodd Fiala         NotifyDidExec ();
2385a9882ceeSTodd Fiala 
2386a9882ceeSTodd Fiala         // If we have a main thread, indicate we are stopped.
2387a9882ceeSTodd Fiala         assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
2388fa03ad2eSChaoren Lin 
2389fa03ad2eSChaoren Lin         // Let the process know we're stopped.
2390ed89c7feSPavel Labath         StopRunningThreads (pid);
2391a9882ceeSTodd Fiala 
2392af245d11STodd Fiala         break;
2393a9882ceeSTodd Fiala     }
2394af245d11STodd Fiala 
2395af245d11STodd Fiala     case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
2396af245d11STodd Fiala     {
2397af245d11STodd Fiala         // The inferior process or one of its threads is about to exit.
23988c8ff7afSPavel Labath         if (! thread_sp)
23998c8ff7afSPavel Labath             break;
2400fa03ad2eSChaoren Lin 
2401fa03ad2eSChaoren Lin         // This thread is currently stopped.  It's not actually dead yet, just about to be.
24025eb721edSPavel Labath         NotifyThreadStop (pid, false);
24038c8ff7afSPavel Labath         // The actual stop reason does not matter much, as we are going to resume the thread a
24048c8ff7afSPavel Labath         // few lines down. If we ever want to report this state to the debugger, then we should
24058c8ff7afSPavel Labath         // invent a new stop reason.
24068c8ff7afSPavel Labath         std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedBySignal(LLDB_INVALID_SIGNAL_NUMBER);
2407fa03ad2eSChaoren Lin 
2408af245d11STodd Fiala         unsigned long data = 0;
240997ccc294SChaoren Lin         if (GetEventMessage(pid, &data).Fail())
2410af245d11STodd Fiala             data = -1;
2411af245d11STodd Fiala 
2412af245d11STodd Fiala         if (log)
2413af245d11STodd Fiala         {
2414af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
2415af245d11STodd Fiala                          __FUNCTION__,
2416af245d11STodd Fiala                          data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
2417af245d11STodd Fiala                          pid,
2418af245d11STodd Fiala                     is_main_thread ? "is main thread" : "not main thread");
2419af245d11STodd Fiala         }
2420af245d11STodd Fiala 
2421af245d11STodd Fiala         if (is_main_thread)
2422af245d11STodd Fiala         {
2423af245d11STodd Fiala             SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
242475f47c3aSTodd Fiala         }
242575f47c3aSTodd Fiala 
24269d617ba6SChaoren Lin         const int signo = static_cast<int> (data);
2427c076559aSPavel Labath         RequestThreadResume (pid,
242886fd8e45SChaoren Lin                 [=](lldb::tid_t tid_to_resume, bool supress_signal)
2429fa03ad2eSChaoren Lin                 {
2430cb84eebbSTamas Berghammer                     std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
243137c768caSChaoren Lin                     return Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo);
24325eb721edSPavel Labath                 });
2433af245d11STodd Fiala 
2434af245d11STodd Fiala         break;
2435af245d11STodd Fiala     }
2436af245d11STodd Fiala 
2437af245d11STodd Fiala     case 0:
2438c16f5dcaSChaoren Lin     case TRAP_TRACE:  // We receive this on single stepping.
2439c16f5dcaSChaoren Lin     case TRAP_HWBKPT: // We receive this on watchpoint hit
244086fd8e45SChaoren Lin         if (thread_sp)
244186fd8e45SChaoren Lin         {
2442c16f5dcaSChaoren Lin             // If a watchpoint was hit, report it
2443c16f5dcaSChaoren Lin             uint32_t wp_index;
2444c16f5dcaSChaoren Lin             Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index);
2445c16f5dcaSChaoren Lin             if (error.Fail() && log)
2446c16f5dcaSChaoren Lin                 log->Printf("NativeProcessLinux::%s() "
2447c16f5dcaSChaoren Lin                             "received error while checking for watchpoint hits, "
2448c16f5dcaSChaoren Lin                             "pid = %" PRIu64 " error = %s",
2449c16f5dcaSChaoren Lin                             __FUNCTION__, pid, error.AsCString());
2450c16f5dcaSChaoren Lin             if (wp_index != LLDB_INVALID_INDEX32)
24515830aa75STamas Berghammer             {
2452c16f5dcaSChaoren Lin                 MonitorWatchpoint(pid, thread_sp, wp_index);
2453c16f5dcaSChaoren Lin                 break;
2454c16f5dcaSChaoren Lin             }
2455c16f5dcaSChaoren Lin         }
2456c16f5dcaSChaoren Lin         // Otherwise, report step over
2457c16f5dcaSChaoren Lin         MonitorTrace(pid, thread_sp);
2458af245d11STodd Fiala         break;
2459af245d11STodd Fiala 
2460af245d11STodd Fiala     case SI_KERNEL:
2461af245d11STodd Fiala     case TRAP_BRKPT:
2462c16f5dcaSChaoren Lin         MonitorBreakpoint(pid, thread_sp);
2463af245d11STodd Fiala         break;
2464af245d11STodd Fiala 
2465af245d11STodd Fiala     case SIGTRAP:
2466af245d11STodd Fiala     case (SIGTRAP | 0x80):
2467af245d11STodd Fiala         if (log)
2468fa03ad2eSChaoren Lin             log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), pid);
2469fa03ad2eSChaoren Lin 
2470fa03ad2eSChaoren Lin         // This thread is currently stopped.
24715eb721edSPavel Labath         NotifyThreadStop (pid, false);
2472fa03ad2eSChaoren Lin         if (thread_sp)
2473cb84eebbSTamas Berghammer             std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGTRAP);
2474fa03ad2eSChaoren Lin 
2475fa03ad2eSChaoren Lin 
2476af245d11STodd Fiala         // Ignore these signals until we know more about them.
2477c076559aSPavel Labath         RequestThreadResume (pid,
247886fd8e45SChaoren Lin                 [=](lldb::tid_t tid_to_resume, bool supress_signal)
2479fa03ad2eSChaoren Lin                 {
2480cb84eebbSTamas Berghammer                     std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
248137c768caSChaoren Lin                     return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
24825eb721edSPavel Labath                 });
2483af245d11STodd Fiala         break;
2484af245d11STodd Fiala 
2485af245d11STodd Fiala     default:
2486af245d11STodd Fiala         assert(false && "Unexpected SIGTRAP code!");
2487af245d11STodd Fiala         if (log)
2488af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 "tid %" PRIu64 " received unhandled SIGTRAP code: 0x%" PRIx64, __FUNCTION__, GetID (), pid, static_cast<uint64_t> (SIGTRAP | (PTRACE_EVENT_CLONE << 8)));
2489af245d11STodd Fiala         break;
2490af245d11STodd Fiala 
2491af245d11STodd Fiala     }
2492af245d11STodd Fiala }
2493af245d11STodd Fiala 
2494af245d11STodd Fiala void
2495c16f5dcaSChaoren Lin NativeProcessLinux::MonitorTrace(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
2496c16f5dcaSChaoren Lin {
2497c16f5dcaSChaoren Lin     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2498c16f5dcaSChaoren Lin     if (log)
2499c16f5dcaSChaoren Lin         log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)",
2500c16f5dcaSChaoren Lin                 __FUNCTION__, pid);
2501c16f5dcaSChaoren Lin 
2502c16f5dcaSChaoren Lin     if (thread_sp)
2503c16f5dcaSChaoren Lin         std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
2504c16f5dcaSChaoren Lin 
2505c16f5dcaSChaoren Lin     // This thread is currently stopped.
25065eb721edSPavel Labath     NotifyThreadStop(pid, false);
2507c16f5dcaSChaoren Lin 
2508c16f5dcaSChaoren Lin     // Here we don't have to request the rest of the threads to stop or request a deferred stop.
2509c16f5dcaSChaoren Lin     // This would have already happened at the time the Resume() with step operation was signaled.
2510c16f5dcaSChaoren Lin     // At this point, we just need to say we stopped, and the deferred notifcation will fire off
2511c16f5dcaSChaoren Lin     // once all running threads have checked in as stopped.
2512c16f5dcaSChaoren Lin     SetCurrentThreadID(pid);
2513c16f5dcaSChaoren Lin     // Tell the process we have a stop (from software breakpoint).
2514ed89c7feSPavel Labath     StopRunningThreads(pid);
2515c16f5dcaSChaoren Lin }
2516c16f5dcaSChaoren Lin 
2517c16f5dcaSChaoren Lin void
2518c16f5dcaSChaoren Lin NativeProcessLinux::MonitorBreakpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
2519c16f5dcaSChaoren Lin {
2520c16f5dcaSChaoren Lin     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
2521c16f5dcaSChaoren Lin     if (log)
2522c16f5dcaSChaoren Lin         log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
2523c16f5dcaSChaoren Lin                 __FUNCTION__, pid);
2524c16f5dcaSChaoren Lin 
2525c16f5dcaSChaoren Lin     // This thread is currently stopped.
25265eb721edSPavel Labath     NotifyThreadStop(pid, false);
2527c16f5dcaSChaoren Lin 
2528c16f5dcaSChaoren Lin     // Mark the thread as stopped at breakpoint.
2529c16f5dcaSChaoren Lin     if (thread_sp)
2530c16f5dcaSChaoren Lin     {
2531c16f5dcaSChaoren Lin         std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByBreakpoint();
2532c16f5dcaSChaoren Lin         Error error = FixupBreakpointPCAsNeeded(thread_sp);
2533c16f5dcaSChaoren Lin         if (error.Fail())
2534c16f5dcaSChaoren Lin             if (log)
2535c16f5dcaSChaoren Lin                 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
2536c16f5dcaSChaoren Lin                         __FUNCTION__, pid, error.AsCString());
2537d8c338d4STamas Berghammer 
2538d8c338d4STamas Berghammer         auto it = m_threads_stepping_with_breakpoint.find(pid);
2539d8c338d4STamas Berghammer         if (it != m_threads_stepping_with_breakpoint.end())
2540d8c338d4STamas Berghammer         {
2541d8c338d4STamas Berghammer             Error error = RemoveBreakpoint (it->second);
2542d8c338d4STamas Berghammer             if (error.Fail())
2543d8c338d4STamas Berghammer                 if (log)
2544d8c338d4STamas Berghammer                     log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " remove stepping breakpoint: %s",
2545d8c338d4STamas Berghammer                             __FUNCTION__, pid, error.AsCString());
2546d8c338d4STamas Berghammer 
2547d8c338d4STamas Berghammer             m_threads_stepping_with_breakpoint.erase(it);
2548d8c338d4STamas Berghammer             std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
2549d8c338d4STamas Berghammer         }
2550c16f5dcaSChaoren Lin     }
2551c16f5dcaSChaoren Lin     else
2552c16f5dcaSChaoren Lin         if (log)
2553c16f5dcaSChaoren Lin             log->Printf("NativeProcessLinux::%s()  pid = %" PRIu64 ": "
2554c16f5dcaSChaoren Lin                     "warning, cannot process software breakpoint since no thread metadata",
2555c16f5dcaSChaoren Lin                     __FUNCTION__, pid);
2556c16f5dcaSChaoren Lin 
2557c16f5dcaSChaoren Lin 
2558c16f5dcaSChaoren Lin     // We need to tell all other running threads before we notify the delegate about this stop.
2559ed89c7feSPavel Labath     StopRunningThreads(pid);
2560c16f5dcaSChaoren Lin }
2561c16f5dcaSChaoren Lin 
2562c16f5dcaSChaoren Lin void
2563c16f5dcaSChaoren Lin NativeProcessLinux::MonitorWatchpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp, uint32_t wp_index)
2564c16f5dcaSChaoren Lin {
2565c16f5dcaSChaoren Lin     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
2566c16f5dcaSChaoren Lin     if (log)
2567c16f5dcaSChaoren Lin         log->Printf("NativeProcessLinux::%s() received watchpoint event, "
2568c16f5dcaSChaoren Lin                     "pid = %" PRIu64 ", wp_index = %" PRIu32,
2569c16f5dcaSChaoren Lin                     __FUNCTION__, pid, wp_index);
2570c16f5dcaSChaoren Lin 
2571c16f5dcaSChaoren Lin     // This thread is currently stopped.
25725eb721edSPavel Labath     NotifyThreadStop(pid, false);
2573c16f5dcaSChaoren Lin 
2574c16f5dcaSChaoren Lin     // Mark the thread as stopped at watchpoint.
2575c16f5dcaSChaoren Lin     // The address is at (lldb::addr_t)info->si_addr if we need it.
2576c16f5dcaSChaoren Lin     lldbassert(thread_sp && "thread_sp cannot be NULL");
2577c16f5dcaSChaoren Lin     std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByWatchpoint(wp_index);
2578c16f5dcaSChaoren Lin 
2579c16f5dcaSChaoren Lin     // We need to tell all other running threads before we notify the delegate about this stop.
2580ed89c7feSPavel Labath     StopRunningThreads(pid);
2581c16f5dcaSChaoren Lin }
2582c16f5dcaSChaoren Lin 
2583c16f5dcaSChaoren Lin void
2584af245d11STodd Fiala NativeProcessLinux::MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited)
2585af245d11STodd Fiala {
2586511e5cdcSTodd Fiala     assert (info && "null info");
2587511e5cdcSTodd Fiala     if (!info)
2588511e5cdcSTodd Fiala         return;
2589511e5cdcSTodd Fiala 
2590511e5cdcSTodd Fiala     const int signo = info->si_signo;
2591511e5cdcSTodd Fiala     const bool is_from_llgs = info->si_pid == getpid ();
2592af245d11STodd Fiala 
2593af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2594af245d11STodd Fiala 
2595af245d11STodd Fiala     // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
2596af245d11STodd Fiala     // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
2597af245d11STodd Fiala     // kill(2) or raise(3).  Similarly for tgkill(2) on Linux.
2598af245d11STodd Fiala     //
2599af245d11STodd Fiala     // IOW, user generated signals never generate what we consider to be a
2600af245d11STodd Fiala     // "crash".
2601af245d11STodd Fiala     //
2602af245d11STodd Fiala     // Similarly, ACK signals generated by this monitor.
2603af245d11STodd Fiala 
26045830aa75STamas Berghammer     Mutex::Locker locker (m_threads_mutex);
26055830aa75STamas Berghammer 
2606af245d11STodd Fiala     // See if we can find a thread for this signal.
2607af245d11STodd Fiala     NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2608af245d11STodd Fiala     if (!thread_sp)
2609af245d11STodd Fiala     {
2610af245d11STodd Fiala         if (log)
2611af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2612af245d11STodd Fiala     }
2613af245d11STodd Fiala 
2614af245d11STodd Fiala     // Handle the signal.
2615af245d11STodd Fiala     if (info->si_code == SI_TKILL || info->si_code == SI_USER)
2616af245d11STodd Fiala     {
2617af245d11STodd Fiala         if (log)
2618af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
2619af245d11STodd Fiala                             __FUNCTION__,
2620af245d11STodd Fiala                             GetUnixSignals ().GetSignalAsCString (signo),
2621af245d11STodd Fiala                             signo,
2622af245d11STodd Fiala                             (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
2623af245d11STodd Fiala                             info->si_pid,
2624511e5cdcSTodd Fiala                             is_from_llgs ? "from llgs" : "not from llgs",
2625af245d11STodd Fiala                             pid);
262658a2f669STodd Fiala     }
2627af245d11STodd Fiala 
262858a2f669STodd Fiala     // Check for new thread notification.
262958a2f669STodd Fiala     if ((info->si_pid == 0) && (info->si_code == SI_USER))
2630af245d11STodd Fiala     {
2631af245d11STodd Fiala         // A new thread creation is being signaled. This is one of two parts that come in
2632426bdf88SPavel Labath         // a non-deterministic order. This code handles the case where the new thread event comes
2633426bdf88SPavel Labath         // before the event on the parent thread. For the opposite case see code in
2634426bdf88SPavel Labath         // MonitorSIGTRAP.
2635af245d11STodd Fiala         if (log)
2636af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": new thread notification",
2637af245d11STodd Fiala                      __FUNCTION__, GetID (), pid);
2638af245d11STodd Fiala 
26395fd24c67SPavel Labath         thread_sp = AddThread(pid);
26405fd24c67SPavel Labath         assert (thread_sp.get() && "failed to create the tracking data for newly created inferior thread");
26415fd24c67SPavel Labath         // We can now resume the newly created thread.
2642cb84eebbSTamas Berghammer         std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
26435fd24c67SPavel Labath         Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
26448c8ff7afSPavel Labath         NotifyThreadCreate(pid);
264558a2f669STodd Fiala         // Done handling.
264658a2f669STodd Fiala         return;
2647af245d11STodd Fiala     }
264858a2f669STodd Fiala 
264958a2f669STodd Fiala     // Check for thread stop notification.
2650511e5cdcSTodd Fiala     if (is_from_llgs && (info->si_code == SI_TKILL) && (signo == SIGSTOP))
2651af245d11STodd Fiala     {
2652af245d11STodd Fiala         // This is a tgkill()-based stop.
2653af245d11STodd Fiala         if (thread_sp)
2654af245d11STodd Fiala         {
2655fa03ad2eSChaoren Lin             if (log)
2656fa03ad2eSChaoren Lin                 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
2657fa03ad2eSChaoren Lin                              __FUNCTION__,
2658fa03ad2eSChaoren Lin                              GetID (),
2659fa03ad2eSChaoren Lin                              pid);
2660fa03ad2eSChaoren Lin 
2661aab58633SChaoren Lin             // Check that we're not already marked with a stop reason.
2662aab58633SChaoren Lin             // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
2663aab58633SChaoren Lin             // the kernel signaled us with the thread stopping which we handled and marked as stopped,
2664aab58633SChaoren Lin             // and that, without an intervening resume, we received another stop.  It is more likely
2665aab58633SChaoren Lin             // that we are missing the marking of a run state somewhere if we find that the thread was
2666aab58633SChaoren Lin             // marked as stopped.
2667cb84eebbSTamas Berghammer             std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
2668cb84eebbSTamas Berghammer             assert (linux_thread_sp && "linux_thread_sp is null!");
2669aab58633SChaoren Lin 
2670cb84eebbSTamas Berghammer             const StateType thread_state = linux_thread_sp->GetState ();
2671aab58633SChaoren Lin             if (!StateIsStoppedState (thread_state, false))
2672aab58633SChaoren Lin             {
2673ed89c7feSPavel Labath                 // An inferior thread has stopped because of a SIGSTOP we have sent it.
2674ed89c7feSPavel Labath                 // Generally, these are not important stops and we don't want to report them as
2675ed89c7feSPavel Labath                 // they are just used to stop other threads when one thread (the one with the
2676ed89c7feSPavel Labath                 // *real* stop reason) hits a breakpoint (watchpoint, etc...). However, in the
2677ed89c7feSPavel Labath                 // case of an asynchronous Interrupt(), this *is* the real stop reason, so we
2678ed89c7feSPavel Labath                 // leave the signal intact if this is the thread that was chosen as the
2679ed89c7feSPavel Labath                 // triggering thread.
2680ed89c7feSPavel Labath                 if (m_pending_notification_up && m_pending_notification_up->triggering_tid == pid)
2681ed89c7feSPavel Labath                     linux_thread_sp->SetStoppedBySignal(SIGSTOP);
2682ed89c7feSPavel Labath                 else
2683cb84eebbSTamas Berghammer                     linux_thread_sp->SetStoppedBySignal(0);
2684ed89c7feSPavel Labath 
2685af245d11STodd Fiala                 SetCurrentThreadID (thread_sp->GetID ());
26865eb721edSPavel Labath                 NotifyThreadStop (thread_sp->GetID (), true);
2687aab58633SChaoren Lin             }
2688aab58633SChaoren Lin             else
2689aab58633SChaoren Lin             {
2690aab58633SChaoren Lin                 if (log)
2691aab58633SChaoren Lin                 {
2692aab58633SChaoren Lin                     // Retrieve the signal name if the thread was stopped by a signal.
2693aab58633SChaoren Lin                     int stop_signo = 0;
2694cb84eebbSTamas Berghammer                     const bool stopped_by_signal = linux_thread_sp->IsStopped (&stop_signo);
2695aab58633SChaoren Lin                     const char *signal_name = stopped_by_signal ? GetUnixSignals ().GetSignalAsCString (stop_signo) : "<not stopped by signal>";
2696aab58633SChaoren Lin                     if (!signal_name)
2697aab58633SChaoren Lin                         signal_name = "<no-signal-name>";
2698aab58633SChaoren Lin 
2699aab58633SChaoren Lin                     log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread was already marked as a stopped state (state=%s, signal=%d (%s)), leaving stop signal as is",
2700aab58633SChaoren Lin                                  __FUNCTION__,
2701aab58633SChaoren Lin                                  GetID (),
2702cb84eebbSTamas Berghammer                                  linux_thread_sp->GetID (),
2703aab58633SChaoren Lin                                  StateAsCString (thread_state),
2704aab58633SChaoren Lin                                  stop_signo,
2705aab58633SChaoren Lin                                  signal_name);
2706aab58633SChaoren Lin                 }
2707fa03ad2eSChaoren Lin                 // Tell the thread state coordinator about the stop.
27085eb721edSPavel Labath                 NotifyThreadStop (thread_sp->GetID (), false);
2709af245d11STodd Fiala             }
271086fd8e45SChaoren Lin         }
2711af245d11STodd Fiala 
271258a2f669STodd Fiala         // Done handling.
2713af245d11STodd Fiala         return;
2714af245d11STodd Fiala     }
2715af245d11STodd Fiala 
2716af245d11STodd Fiala     if (log)
2717af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, GetUnixSignals ().GetSignalAsCString (signo));
2718af245d11STodd Fiala 
271986fd8e45SChaoren Lin     // This thread is stopped.
27205eb721edSPavel Labath     NotifyThreadStop (pid, false);
272186fd8e45SChaoren Lin 
2722af245d11STodd Fiala     switch (signo)
2723af245d11STodd Fiala     {
2724511e5cdcSTodd Fiala     case SIGSTOP:
2725511e5cdcSTodd Fiala         {
27268c8ff7afSPavel Labath             std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (signo);
272758a2f669STodd Fiala             if (log)
2728511e5cdcSTodd Fiala             {
2729511e5cdcSTodd Fiala                 if (is_from_llgs)
2730511e5cdcSTodd Fiala                     log->Printf ("NativeProcessLinux::%s pid = %" PRIu64 " tid %" PRIu64 " received SIGSTOP from llgs, most likely an interrupt", __FUNCTION__, GetID (), pid);
2731511e5cdcSTodd Fiala                 else
2732511e5cdcSTodd Fiala                     log->Printf ("NativeProcessLinux::%s pid = %" PRIu64 " tid %" PRIu64 " received SIGSTOP from outside of debugger", __FUNCTION__, GetID (), pid);
2733511e5cdcSTodd Fiala             }
2734511e5cdcSTodd Fiala 
2735fa03ad2eSChaoren Lin             // Resume this thread to get the group-stop mechanism to fire off the true group stops.
2736fa03ad2eSChaoren Lin             // This thread will get stopped again as part of the group-stop completion.
2737c076559aSPavel Labath             RequestThreadResume (pid,
273886fd8e45SChaoren Lin                     [=](lldb::tid_t tid_to_resume, bool supress_signal)
2739fa03ad2eSChaoren Lin                     {
2740cb84eebbSTamas Berghammer                         std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2741fa03ad2eSChaoren Lin                         // Pass this signal number on to the inferior to handle.
274237c768caSChaoren Lin                         return Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo);
27435eb721edSPavel Labath                     });
274486fd8e45SChaoren Lin         }
274586fd8e45SChaoren Lin         break;
274686fd8e45SChaoren Lin     case SIGSEGV:
274786fd8e45SChaoren Lin     case SIGILL:
274886fd8e45SChaoren Lin     case SIGFPE:
274986fd8e45SChaoren Lin     case SIGBUS:
275086fd8e45SChaoren Lin         if (thread_sp)
2751cb84eebbSTamas Berghammer             std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetCrashedWithException (*info);
275286fd8e45SChaoren Lin         break;
275386fd8e45SChaoren Lin     default:
275486fd8e45SChaoren Lin         // This is just a pre-signal-delivery notification of the incoming signal.
275586fd8e45SChaoren Lin         if (thread_sp)
2756cb84eebbSTamas Berghammer             std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (signo);
2757fa03ad2eSChaoren Lin 
275886fd8e45SChaoren Lin         break;
275986fd8e45SChaoren Lin     }
276086fd8e45SChaoren Lin 
276186fd8e45SChaoren Lin     // Send a stop to the debugger after we get all other threads to stop.
2762ed89c7feSPavel Labath     StopRunningThreads (pid);
2763511e5cdcSTodd Fiala }
2764af245d11STodd Fiala 
2765e7708688STamas Berghammer namespace {
2766e7708688STamas Berghammer 
2767e7708688STamas Berghammer struct EmulatorBaton
2768e7708688STamas Berghammer {
2769e7708688STamas Berghammer     NativeProcessLinux* m_process;
2770e7708688STamas Berghammer     NativeRegisterContext* m_reg_context;
27716648fcc3SPavel Labath 
27726648fcc3SPavel Labath     // eRegisterKindDWARF -> RegsiterValue
27736648fcc3SPavel Labath     std::unordered_map<uint32_t, RegisterValue> m_register_values;
2774e7708688STamas Berghammer 
2775e7708688STamas Berghammer     EmulatorBaton(NativeProcessLinux* process, NativeRegisterContext* reg_context) :
2776e7708688STamas Berghammer             m_process(process), m_reg_context(reg_context) {}
2777e7708688STamas Berghammer };
2778e7708688STamas Berghammer 
2779e7708688STamas Berghammer } // anonymous namespace
2780e7708688STamas Berghammer 
2781e7708688STamas Berghammer static size_t
2782e7708688STamas Berghammer ReadMemoryCallback (EmulateInstruction *instruction,
2783e7708688STamas Berghammer                     void *baton,
2784e7708688STamas Berghammer                     const EmulateInstruction::Context &context,
2785e7708688STamas Berghammer                     lldb::addr_t addr,
2786e7708688STamas Berghammer                     void *dst,
2787e7708688STamas Berghammer                     size_t length)
2788e7708688STamas Berghammer {
2789e7708688STamas Berghammer     EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
2790e7708688STamas Berghammer 
27913eb4b458SChaoren Lin     size_t bytes_read;
2792e7708688STamas Berghammer     emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
2793e7708688STamas Berghammer     return bytes_read;
2794e7708688STamas Berghammer }
2795e7708688STamas Berghammer 
2796e7708688STamas Berghammer static bool
2797e7708688STamas Berghammer ReadRegisterCallback (EmulateInstruction *instruction,
2798e7708688STamas Berghammer                       void *baton,
2799e7708688STamas Berghammer                       const RegisterInfo *reg_info,
2800e7708688STamas Berghammer                       RegisterValue &reg_value)
2801e7708688STamas Berghammer {
2802e7708688STamas Berghammer     EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
2803e7708688STamas Berghammer 
28046648fcc3SPavel Labath     auto it = emulator_baton->m_register_values.find(reg_info->kinds[eRegisterKindDWARF]);
28056648fcc3SPavel Labath     if (it != emulator_baton->m_register_values.end())
28066648fcc3SPavel Labath     {
28076648fcc3SPavel Labath         reg_value = it->second;
28086648fcc3SPavel Labath         return true;
28096648fcc3SPavel Labath     }
28106648fcc3SPavel Labath 
2811e7708688STamas Berghammer     // The emulator only fill in the dwarf regsiter numbers (and in some case
2812e7708688STamas Berghammer     // the generic register numbers). Get the full register info from the
2813e7708688STamas Berghammer     // register context based on the dwarf register numbers.
2814e7708688STamas Berghammer     const RegisterInfo* full_reg_info = emulator_baton->m_reg_context->GetRegisterInfo(
2815e7708688STamas Berghammer             eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
2816e7708688STamas Berghammer 
2817e7708688STamas Berghammer     Error error = emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
28186648fcc3SPavel Labath     if (error.Success())
28196648fcc3SPavel Labath         return true;
2820cdc22a88SMohit K. Bhakkad 
28216648fcc3SPavel Labath     return false;
2822e7708688STamas Berghammer }
2823e7708688STamas Berghammer 
2824e7708688STamas Berghammer static bool
2825e7708688STamas Berghammer WriteRegisterCallback (EmulateInstruction *instruction,
2826e7708688STamas Berghammer                        void *baton,
2827e7708688STamas Berghammer                        const EmulateInstruction::Context &context,
2828e7708688STamas Berghammer                        const RegisterInfo *reg_info,
2829e7708688STamas Berghammer                        const RegisterValue &reg_value)
2830e7708688STamas Berghammer {
2831e7708688STamas Berghammer     EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
28326648fcc3SPavel Labath     emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = reg_value;
2833e7708688STamas Berghammer     return true;
2834e7708688STamas Berghammer }
2835e7708688STamas Berghammer 
2836e7708688STamas Berghammer static size_t
2837e7708688STamas Berghammer WriteMemoryCallback (EmulateInstruction *instruction,
2838e7708688STamas Berghammer                      void *baton,
2839e7708688STamas Berghammer                      const EmulateInstruction::Context &context,
2840e7708688STamas Berghammer                      lldb::addr_t addr,
2841e7708688STamas Berghammer                      const void *dst,
2842e7708688STamas Berghammer                      size_t length)
2843e7708688STamas Berghammer {
2844e7708688STamas Berghammer     return length;
2845e7708688STamas Berghammer }
2846e7708688STamas Berghammer 
2847e7708688STamas Berghammer static lldb::addr_t
2848e7708688STamas Berghammer ReadFlags (NativeRegisterContext* regsiter_context)
2849e7708688STamas Berghammer {
2850e7708688STamas Berghammer     const RegisterInfo* flags_info = regsiter_context->GetRegisterInfo(
2851e7708688STamas Berghammer             eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
2852e7708688STamas Berghammer     return regsiter_context->ReadRegisterAsUnsigned(flags_info, LLDB_INVALID_ADDRESS);
2853e7708688STamas Berghammer }
2854e7708688STamas Berghammer 
2855e7708688STamas Berghammer Error
2856e7708688STamas Berghammer NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadProtocolSP thread_sp)
2857e7708688STamas Berghammer {
2858e7708688STamas Berghammer     Error error;
2859e7708688STamas Berghammer     NativeRegisterContextSP register_context_sp = thread_sp->GetRegisterContext();
2860e7708688STamas Berghammer 
2861e7708688STamas Berghammer     std::unique_ptr<EmulateInstruction> emulator_ap(
2862e7708688STamas Berghammer         EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, nullptr));
2863e7708688STamas Berghammer 
2864e7708688STamas Berghammer     if (emulator_ap == nullptr)
2865e7708688STamas Berghammer         return Error("Instruction emulator not found!");
2866e7708688STamas Berghammer 
2867e7708688STamas Berghammer     EmulatorBaton baton(this, register_context_sp.get());
2868e7708688STamas Berghammer     emulator_ap->SetBaton(&baton);
2869e7708688STamas Berghammer     emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
2870e7708688STamas Berghammer     emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
2871e7708688STamas Berghammer     emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
2872e7708688STamas Berghammer     emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
2873e7708688STamas Berghammer 
2874e7708688STamas Berghammer     if (!emulator_ap->ReadInstruction())
2875e7708688STamas Berghammer         return Error("Read instruction failed!");
2876e7708688STamas Berghammer 
28776648fcc3SPavel Labath     bool emulation_result = emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
28786648fcc3SPavel Labath 
28796648fcc3SPavel Labath     const RegisterInfo* reg_info_pc = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
28806648fcc3SPavel Labath     const RegisterInfo* reg_info_flags = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
28816648fcc3SPavel Labath 
28826648fcc3SPavel Labath     auto pc_it = baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
28836648fcc3SPavel Labath     auto flags_it = baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
28846648fcc3SPavel Labath 
2885e7708688STamas Berghammer     lldb::addr_t next_pc;
2886e7708688STamas Berghammer     lldb::addr_t next_flags;
28876648fcc3SPavel Labath     if (emulation_result)
2888e7708688STamas Berghammer     {
28896648fcc3SPavel Labath         assert(pc_it != baton.m_register_values.end() && "Emulation was successfull but PC wasn't updated");
28906648fcc3SPavel Labath         next_pc = pc_it->second.GetAsUInt64();
28916648fcc3SPavel Labath 
28926648fcc3SPavel Labath         if (flags_it != baton.m_register_values.end())
28936648fcc3SPavel Labath             next_flags = flags_it->second.GetAsUInt64();
2894e7708688STamas Berghammer         else
2895e7708688STamas Berghammer             next_flags = ReadFlags (register_context_sp.get());
2896e7708688STamas Berghammer     }
28976648fcc3SPavel Labath     else if (pc_it == baton.m_register_values.end())
2898e7708688STamas Berghammer     {
2899e7708688STamas Berghammer         // Emulate instruction failed and it haven't changed PC. Advance PC
2900e7708688STamas Berghammer         // with the size of the current opcode because the emulation of all
2901e7708688STamas Berghammer         // PC modifying instruction should be successful. The failure most
2902e7708688STamas Berghammer         // likely caused by a not supported instruction which don't modify PC.
2903e7708688STamas Berghammer         next_pc = register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
2904e7708688STamas Berghammer         next_flags = ReadFlags (register_context_sp.get());
2905e7708688STamas Berghammer     }
2906e7708688STamas Berghammer     else
2907e7708688STamas Berghammer     {
2908e7708688STamas Berghammer         // The instruction emulation failed after it modified the PC. It is an
2909e7708688STamas Berghammer         // unknown error where we can't continue because the next instruction is
2910e7708688STamas Berghammer         // modifying the PC but we don't  know how.
2911e7708688STamas Berghammer         return Error ("Instruction emulation failed unexpectedly.");
2912e7708688STamas Berghammer     }
2913e7708688STamas Berghammer 
2914e7708688STamas Berghammer     if (m_arch.GetMachine() == llvm::Triple::arm)
2915e7708688STamas Berghammer     {
2916e7708688STamas Berghammer         if (next_flags & 0x20)
2917e7708688STamas Berghammer         {
2918e7708688STamas Berghammer             // Thumb mode
2919e7708688STamas Berghammer             error = SetSoftwareBreakpoint(next_pc, 2);
2920e7708688STamas Berghammer         }
2921e7708688STamas Berghammer         else
2922e7708688STamas Berghammer         {
2923e7708688STamas Berghammer             // Arm mode
2924e7708688STamas Berghammer             error = SetSoftwareBreakpoint(next_pc, 4);
2925e7708688STamas Berghammer         }
2926e7708688STamas Berghammer     }
2927cdc22a88SMohit K. Bhakkad     else if (m_arch.GetMachine() == llvm::Triple::mips64
2928cdc22a88SMohit K. Bhakkad             || m_arch.GetMachine() == llvm::Triple::mips64el)
2929cdc22a88SMohit K. Bhakkad         error = SetSoftwareBreakpoint(next_pc, 4);
2930e7708688STamas Berghammer     else
2931e7708688STamas Berghammer     {
2932e7708688STamas Berghammer         // No size hint is given for the next breakpoint
2933e7708688STamas Berghammer         error = SetSoftwareBreakpoint(next_pc, 0);
2934e7708688STamas Berghammer     }
2935e7708688STamas Berghammer 
2936e7708688STamas Berghammer     if (error.Fail())
2937e7708688STamas Berghammer         return error;
2938e7708688STamas Berghammer 
2939e7708688STamas Berghammer     m_threads_stepping_with_breakpoint.insert({thread_sp->GetID(), next_pc});
2940e7708688STamas Berghammer 
2941e7708688STamas Berghammer     return Error();
2942e7708688STamas Berghammer }
2943e7708688STamas Berghammer 
2944e7708688STamas Berghammer bool
2945e7708688STamas Berghammer NativeProcessLinux::SupportHardwareSingleStepping() const
2946e7708688STamas Berghammer {
2947cdc22a88SMohit K. Bhakkad     if (m_arch.GetMachine() == llvm::Triple::arm
2948cdc22a88SMohit K. Bhakkad         || m_arch.GetMachine() == llvm::Triple::mips64 || m_arch.GetMachine() == llvm::Triple::mips64el)
2949cdc22a88SMohit K. Bhakkad         return false;
2950cdc22a88SMohit K. Bhakkad     return true;
2951e7708688STamas Berghammer }
2952e7708688STamas Berghammer 
2953af245d11STodd Fiala Error
2954af245d11STodd Fiala NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
2955af245d11STodd Fiala {
2956af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2957af245d11STodd Fiala     if (log)
2958af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
2959af245d11STodd Fiala 
296003f12d6bSChaoren Lin     lldb::tid_t deferred_signal_tid = LLDB_INVALID_THREAD_ID;
296103f12d6bSChaoren Lin     lldb::tid_t deferred_signal_skip_tid = LLDB_INVALID_THREAD_ID;
2962ae29d395SChaoren Lin     int deferred_signo = 0;
2963ae29d395SChaoren Lin     NativeThreadProtocolSP deferred_signal_thread_sp;
296486fd8e45SChaoren Lin     bool stepping = false;
2965e7708688STamas Berghammer     bool software_single_step = !SupportHardwareSingleStepping();
2966af245d11STodd Fiala 
296745f5cb31SPavel Labath     Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
2968af245d11STodd Fiala     Mutex::Locker locker (m_threads_mutex);
29695830aa75STamas Berghammer 
2970e7708688STamas Berghammer     if (software_single_step)
2971e7708688STamas Berghammer     {
2972e7708688STamas Berghammer         for (auto thread_sp : m_threads)
2973e7708688STamas Berghammer         {
2974e7708688STamas Berghammer             assert (thread_sp && "thread list should not contain NULL threads");
2975e7708688STamas Berghammer 
2976e7708688STamas Berghammer             const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
2977e7708688STamas Berghammer             if (action == nullptr)
2978e7708688STamas Berghammer                 continue;
2979e7708688STamas Berghammer 
2980e7708688STamas Berghammer             if (action->state == eStateStepping)
2981e7708688STamas Berghammer             {
2982e7708688STamas Berghammer                 Error error = SetupSoftwareSingleStepping(thread_sp);
2983e7708688STamas Berghammer                 if (error.Fail())
2984e7708688STamas Berghammer                     return error;
2985e7708688STamas Berghammer             }
2986e7708688STamas Berghammer         }
2987e7708688STamas Berghammer     }
2988e7708688STamas Berghammer 
2989af245d11STodd Fiala     for (auto thread_sp : m_threads)
2990af245d11STodd Fiala     {
2991af245d11STodd Fiala         assert (thread_sp && "thread list should not contain NULL threads");
2992af245d11STodd Fiala 
2993af245d11STodd Fiala         const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
29946a196ce6SChaoren Lin 
29956a196ce6SChaoren Lin         if (action == nullptr)
29966a196ce6SChaoren Lin         {
29976a196ce6SChaoren Lin             if (log)
29986a196ce6SChaoren Lin                 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
29996a196ce6SChaoren Lin                     __FUNCTION__, GetID (), thread_sp->GetID ());
30006a196ce6SChaoren Lin             continue;
30016a196ce6SChaoren Lin         }
3002af245d11STodd Fiala 
3003af245d11STodd Fiala         if (log)
3004af245d11STodd Fiala         {
3005af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
3006af245d11STodd Fiala                     __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
3007af245d11STodd Fiala         }
3008af245d11STodd Fiala 
3009af245d11STodd Fiala         switch (action->state)
3010af245d11STodd Fiala         {
3011af245d11STodd Fiala         case eStateRunning:
3012fa03ad2eSChaoren Lin         {
3013af245d11STodd Fiala             // Run the thread, possibly feeding it the signal.
3014fa03ad2eSChaoren Lin             const int signo = action->signal;
3015c076559aSPavel Labath             RequestThreadResumeAsNeeded (thread_sp->GetID (),
301686fd8e45SChaoren Lin                     [=](lldb::tid_t tid_to_resume, bool supress_signal)
3017af245d11STodd Fiala                     {
3018cb84eebbSTamas Berghammer                         std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
3019fa03ad2eSChaoren Lin                         // Pass this signal number on to the inferior to handle.
30205830aa75STamas Berghammer                         const auto resume_result = Resume (tid_to_resume, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
30215830aa75STamas Berghammer                         if (resume_result.Success())
30225830aa75STamas Berghammer                             SetState(eStateRunning, true);
30235830aa75STamas Berghammer                         return resume_result;
30245eb721edSPavel Labath                     });
3025af245d11STodd Fiala             break;
3026fa03ad2eSChaoren Lin         }
3027af245d11STodd Fiala 
3028af245d11STodd Fiala         case eStateStepping:
3029af245d11STodd Fiala         {
3030ae29d395SChaoren Lin             // Request the step.
3031ae29d395SChaoren Lin             const int signo = action->signal;
3032c076559aSPavel Labath             RequestThreadResume (thread_sp->GetID (),
303386fd8e45SChaoren Lin                     [=](lldb::tid_t tid_to_step, bool supress_signal)
3034af245d11STodd Fiala                     {
3035cb84eebbSTamas Berghammer                         std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStepping ();
3036e7708688STamas Berghammer 
3037e7708688STamas Berghammer                         Error step_result;
3038e7708688STamas Berghammer                         if (software_single_step)
3039e7708688STamas Berghammer                             step_result = Resume (tid_to_step, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
3040e7708688STamas Berghammer                         else
3041e7708688STamas Berghammer                             step_result = SingleStep (tid_to_step,(signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
3042e7708688STamas Berghammer 
304337c768caSChaoren Lin                         assert (step_result.Success() && "SingleStep() failed");
30445830aa75STamas Berghammer                         if (step_result.Success())
30455830aa75STamas Berghammer                             SetState(eStateStepping, true);
304637c768caSChaoren Lin                         return step_result;
30475eb721edSPavel Labath                     });
304886fd8e45SChaoren Lin             stepping = true;
3049af245d11STodd Fiala             break;
3050ae29d395SChaoren Lin         }
3051af245d11STodd Fiala 
3052af245d11STodd Fiala         case eStateSuspended:
3053af245d11STodd Fiala         case eStateStopped:
3054ae29d395SChaoren Lin             // if we haven't chosen a deferred signal tid yet, use this one.
3055ae29d395SChaoren Lin             if (deferred_signal_tid == LLDB_INVALID_THREAD_ID)
3056ae29d395SChaoren Lin             {
3057ae29d395SChaoren Lin                 deferred_signal_tid = thread_sp->GetID ();
3058ae29d395SChaoren Lin                 deferred_signal_thread_sp = thread_sp;
3059ae29d395SChaoren Lin                 deferred_signo = SIGSTOP;
3060ae29d395SChaoren Lin             }
3061af245d11STodd Fiala             break;
3062af245d11STodd Fiala 
3063af245d11STodd Fiala         default:
3064af245d11STodd Fiala             return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
3065af245d11STodd Fiala                     __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
3066af245d11STodd Fiala         }
3067af245d11STodd Fiala     }
3068af245d11STodd Fiala 
3069fa03ad2eSChaoren Lin     // If we had any thread stopping, then do a deferred notification of the chosen stop thread id and signal
3070fa03ad2eSChaoren Lin     // after all other running threads have stopped.
307186fd8e45SChaoren Lin     // If there is a stepping thread involved we'll be eventually stopped by SIGTRAP trace signal.
307286fd8e45SChaoren Lin     if (deferred_signal_tid != LLDB_INVALID_THREAD_ID && !stepping)
3073ed89c7feSPavel Labath         StopRunningThreadsWithSkipTID(deferred_signal_tid, deferred_signal_skip_tid);
3074af245d11STodd Fiala 
30755830aa75STamas Berghammer     return Error();
3076af245d11STodd Fiala }
3077af245d11STodd Fiala 
3078af245d11STodd Fiala Error
3079af245d11STodd Fiala NativeProcessLinux::Halt ()
3080af245d11STodd Fiala {
3081af245d11STodd Fiala     Error error;
3082af245d11STodd Fiala 
3083af245d11STodd Fiala     if (kill (GetID (), SIGSTOP) != 0)
3084af245d11STodd Fiala         error.SetErrorToErrno ();
3085af245d11STodd Fiala 
3086af245d11STodd Fiala     return error;
3087af245d11STodd Fiala }
3088af245d11STodd Fiala 
3089af245d11STodd Fiala Error
3090af245d11STodd Fiala NativeProcessLinux::Detach ()
3091af245d11STodd Fiala {
3092af245d11STodd Fiala     Error error;
3093af245d11STodd Fiala 
3094af245d11STodd Fiala     // Tell ptrace to detach from the process.
3095af245d11STodd Fiala     if (GetID () != LLDB_INVALID_PROCESS_ID)
3096af245d11STodd Fiala         error = Detach (GetID ());
3097af245d11STodd Fiala 
3098af245d11STodd Fiala     // Stop monitoring the inferior.
309945f5cb31SPavel Labath     m_monitor_up->Terminate();
3100af245d11STodd Fiala 
3101af245d11STodd Fiala     // No error.
3102af245d11STodd Fiala     return error;
3103af245d11STodd Fiala }
3104af245d11STodd Fiala 
3105af245d11STodd Fiala Error
3106af245d11STodd Fiala NativeProcessLinux::Signal (int signo)
3107af245d11STodd Fiala {
3108af245d11STodd Fiala     Error error;
3109af245d11STodd Fiala 
3110af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3111af245d11STodd Fiala     if (log)
3112af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
3113af245d11STodd Fiala                 __FUNCTION__, signo,  GetUnixSignals ().GetSignalAsCString (signo), GetID ());
3114af245d11STodd Fiala 
3115af245d11STodd Fiala     if (kill(GetID(), signo))
3116af245d11STodd Fiala         error.SetErrorToErrno();
3117af245d11STodd Fiala 
3118af245d11STodd Fiala     return error;
3119af245d11STodd Fiala }
3120af245d11STodd Fiala 
3121af245d11STodd Fiala Error
3122e9547b80SChaoren Lin NativeProcessLinux::Interrupt ()
3123e9547b80SChaoren Lin {
3124e9547b80SChaoren Lin     // Pick a running thread (or if none, a not-dead stopped thread) as
3125e9547b80SChaoren Lin     // the chosen thread that will be the stop-reason thread.
3126e9547b80SChaoren Lin     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3127e9547b80SChaoren Lin 
3128e9547b80SChaoren Lin     NativeThreadProtocolSP running_thread_sp;
3129e9547b80SChaoren Lin     NativeThreadProtocolSP stopped_thread_sp;
3130e9547b80SChaoren Lin 
3131e9547b80SChaoren Lin     if (log)
3132e9547b80SChaoren Lin         log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
3133e9547b80SChaoren Lin 
313445f5cb31SPavel Labath     Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
31355830aa75STamas Berghammer     Mutex::Locker locker (m_threads_mutex);
31365830aa75STamas Berghammer 
3137e9547b80SChaoren Lin     for (auto thread_sp : m_threads)
3138e9547b80SChaoren Lin     {
3139e9547b80SChaoren Lin         // The thread shouldn't be null but lets just cover that here.
3140e9547b80SChaoren Lin         if (!thread_sp)
3141e9547b80SChaoren Lin             continue;
3142e9547b80SChaoren Lin 
3143e9547b80SChaoren Lin         // If we have a running or stepping thread, we'll call that the
3144e9547b80SChaoren Lin         // target of the interrupt.
3145e9547b80SChaoren Lin         const auto thread_state = thread_sp->GetState ();
3146e9547b80SChaoren Lin         if (thread_state == eStateRunning ||
3147e9547b80SChaoren Lin             thread_state == eStateStepping)
3148e9547b80SChaoren Lin         {
3149e9547b80SChaoren Lin             running_thread_sp = thread_sp;
3150e9547b80SChaoren Lin             break;
3151e9547b80SChaoren Lin         }
3152e9547b80SChaoren Lin         else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
3153e9547b80SChaoren Lin         {
3154e9547b80SChaoren Lin             // Remember the first non-dead stopped thread.  We'll use that as a backup if there are no running threads.
3155e9547b80SChaoren Lin             stopped_thread_sp = thread_sp;
3156e9547b80SChaoren Lin         }
3157e9547b80SChaoren Lin     }
3158e9547b80SChaoren Lin 
3159e9547b80SChaoren Lin     if (!running_thread_sp && !stopped_thread_sp)
3160e9547b80SChaoren Lin     {
31615830aa75STamas Berghammer         Error error("found no running/stepping or live stopped threads as target for interrupt");
3162e9547b80SChaoren Lin         if (log)
3163e9547b80SChaoren Lin             log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
31645830aa75STamas Berghammer 
3165e9547b80SChaoren Lin         return error;
3166e9547b80SChaoren Lin     }
3167e9547b80SChaoren Lin 
3168e9547b80SChaoren Lin     NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
3169e9547b80SChaoren Lin 
3170e9547b80SChaoren Lin     if (log)
3171e9547b80SChaoren Lin         log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
3172e9547b80SChaoren Lin                      __FUNCTION__,
3173e9547b80SChaoren Lin                      GetID (),
3174e9547b80SChaoren Lin                      running_thread_sp ? "running" : "stopped",
3175e9547b80SChaoren Lin                      deferred_signal_thread_sp->GetID ());
3176e9547b80SChaoren Lin 
3177ed89c7feSPavel Labath     StopRunningThreads(deferred_signal_thread_sp->GetID());
317845f5cb31SPavel Labath 
31795830aa75STamas Berghammer     return Error();
3180e9547b80SChaoren Lin }
3181e9547b80SChaoren Lin 
3182e9547b80SChaoren Lin Error
3183af245d11STodd Fiala NativeProcessLinux::Kill ()
3184af245d11STodd Fiala {
3185af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3186af245d11STodd Fiala     if (log)
3187af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
3188af245d11STodd Fiala 
3189af245d11STodd Fiala     Error error;
3190af245d11STodd Fiala 
3191af245d11STodd Fiala     switch (m_state)
3192af245d11STodd Fiala     {
3193af245d11STodd Fiala         case StateType::eStateInvalid:
3194af245d11STodd Fiala         case StateType::eStateExited:
3195af245d11STodd Fiala         case StateType::eStateCrashed:
3196af245d11STodd Fiala         case StateType::eStateDetached:
3197af245d11STodd Fiala         case StateType::eStateUnloaded:
3198af245d11STodd Fiala             // Nothing to do - the process is already dead.
3199af245d11STodd Fiala             if (log)
3200af245d11STodd Fiala                 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
3201af245d11STodd Fiala             return error;
3202af245d11STodd Fiala 
3203af245d11STodd Fiala         case StateType::eStateConnected:
3204af245d11STodd Fiala         case StateType::eStateAttaching:
3205af245d11STodd Fiala         case StateType::eStateLaunching:
3206af245d11STodd Fiala         case StateType::eStateStopped:
3207af245d11STodd Fiala         case StateType::eStateRunning:
3208af245d11STodd Fiala         case StateType::eStateStepping:
3209af245d11STodd Fiala         case StateType::eStateSuspended:
3210af245d11STodd Fiala             // We can try to kill a process in these states.
3211af245d11STodd Fiala             break;
3212af245d11STodd Fiala     }
3213af245d11STodd Fiala 
3214af245d11STodd Fiala     if (kill (GetID (), SIGKILL) != 0)
3215af245d11STodd Fiala     {
3216af245d11STodd Fiala         error.SetErrorToErrno ();
3217af245d11STodd Fiala         return error;
3218af245d11STodd Fiala     }
3219af245d11STodd Fiala 
3220af245d11STodd Fiala     return error;
3221af245d11STodd Fiala }
3222af245d11STodd Fiala 
3223af245d11STodd Fiala static Error
3224af245d11STodd Fiala ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
3225af245d11STodd Fiala {
3226af245d11STodd Fiala     memory_region_info.Clear();
3227af245d11STodd Fiala 
3228af245d11STodd Fiala     StringExtractor line_extractor (maps_line.c_str ());
3229af245d11STodd Fiala 
3230af245d11STodd Fiala     // Format: {address_start_hex}-{address_end_hex} perms offset  dev   inode   pathname
3231af245d11STodd Fiala     // perms: rwxp   (letter is present if set, '-' if not, final character is p=private, s=shared).
3232af245d11STodd Fiala 
3233af245d11STodd Fiala     // Parse out the starting address
3234af245d11STodd Fiala     lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
3235af245d11STodd Fiala 
3236af245d11STodd Fiala     // Parse out hyphen separating start and end address from range.
3237af245d11STodd Fiala     if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
3238af245d11STodd Fiala         return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
3239af245d11STodd Fiala 
3240af245d11STodd Fiala     // Parse out the ending address
3241af245d11STodd Fiala     lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
3242af245d11STodd Fiala 
3243af245d11STodd Fiala     // Parse out the space after the address.
3244af245d11STodd Fiala     if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
3245af245d11STodd Fiala         return Error ("malformed /proc/{pid}/maps entry, missing space after range");
3246af245d11STodd Fiala 
3247af245d11STodd Fiala     // Save the range.
3248af245d11STodd Fiala     memory_region_info.GetRange ().SetRangeBase (start_address);
3249af245d11STodd Fiala     memory_region_info.GetRange ().SetRangeEnd (end_address);
3250af245d11STodd Fiala 
3251af245d11STodd Fiala     // Parse out each permission entry.
3252af245d11STodd Fiala     if (line_extractor.GetBytesLeft () < 4)
3253af245d11STodd Fiala         return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
3254af245d11STodd Fiala 
3255af245d11STodd Fiala     // Handle read permission.
3256af245d11STodd Fiala     const char read_perm_char = line_extractor.GetChar ();
3257af245d11STodd Fiala     if (read_perm_char == 'r')
3258af245d11STodd Fiala         memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
3259af245d11STodd Fiala     else
3260af245d11STodd Fiala     {
3261af245d11STodd Fiala         assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
3262af245d11STodd Fiala         memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
3263af245d11STodd Fiala     }
3264af245d11STodd Fiala 
3265af245d11STodd Fiala     // Handle write permission.
3266af245d11STodd Fiala     const char write_perm_char = line_extractor.GetChar ();
3267af245d11STodd Fiala     if (write_perm_char == 'w')
3268af245d11STodd Fiala         memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
3269af245d11STodd Fiala     else
3270af245d11STodd Fiala     {
3271af245d11STodd Fiala         assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
3272af245d11STodd Fiala         memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
3273af245d11STodd Fiala     }
3274af245d11STodd Fiala 
3275af245d11STodd Fiala     // Handle execute permission.
3276af245d11STodd Fiala     const char exec_perm_char = line_extractor.GetChar ();
3277af245d11STodd Fiala     if (exec_perm_char == 'x')
3278af245d11STodd Fiala         memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
3279af245d11STodd Fiala     else
3280af245d11STodd Fiala     {
3281af245d11STodd Fiala         assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
3282af245d11STodd Fiala         memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
3283af245d11STodd Fiala     }
3284af245d11STodd Fiala 
3285af245d11STodd Fiala     return Error ();
3286af245d11STodd Fiala }
3287af245d11STodd Fiala 
3288af245d11STodd Fiala Error
3289af245d11STodd Fiala NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
3290af245d11STodd Fiala {
3291af245d11STodd Fiala     // FIXME review that the final memory region returned extends to the end of the virtual address space,
3292af245d11STodd Fiala     // with no perms if it is not mapped.
3293af245d11STodd Fiala 
3294af245d11STodd Fiala     // Use an approach that reads memory regions from /proc/{pid}/maps.
3295af245d11STodd Fiala     // Assume proc maps entries are in ascending order.
3296af245d11STodd Fiala     // FIXME assert if we find differently.
3297af245d11STodd Fiala     Mutex::Locker locker (m_mem_region_cache_mutex);
3298af245d11STodd Fiala 
3299af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3300af245d11STodd Fiala     Error error;
3301af245d11STodd Fiala 
3302af245d11STodd Fiala     if (m_supports_mem_region == LazyBool::eLazyBoolNo)
3303af245d11STodd Fiala     {
3304af245d11STodd Fiala         // We're done.
3305af245d11STodd Fiala         error.SetErrorString ("unsupported");
3306af245d11STodd Fiala         return error;
3307af245d11STodd Fiala     }
3308af245d11STodd Fiala 
3309af245d11STodd Fiala     // If our cache is empty, pull the latest.  There should always be at least one memory region
3310af245d11STodd Fiala     // if memory region handling is supported.
3311af245d11STodd Fiala     if (m_mem_region_cache.empty ())
3312af245d11STodd Fiala     {
3313af245d11STodd Fiala         error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
3314af245d11STodd Fiala              [&] (const std::string &line) -> bool
3315af245d11STodd Fiala              {
3316af245d11STodd Fiala                  MemoryRegionInfo info;
3317af245d11STodd Fiala                  const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
3318af245d11STodd Fiala                  if (parse_error.Success ())
3319af245d11STodd Fiala                  {
3320af245d11STodd Fiala                      m_mem_region_cache.push_back (info);
3321af245d11STodd Fiala                      return true;
3322af245d11STodd Fiala                  }
3323af245d11STodd Fiala                  else
3324af245d11STodd Fiala                  {
3325af245d11STodd Fiala                      if (log)
3326af245d11STodd Fiala                          log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
3327af245d11STodd Fiala                      return false;
3328af245d11STodd Fiala                  }
3329af245d11STodd Fiala              });
3330af245d11STodd Fiala 
3331af245d11STodd Fiala         // If we had an error, we'll mark unsupported.
3332af245d11STodd Fiala         if (error.Fail ())
3333af245d11STodd Fiala         {
3334af245d11STodd Fiala             m_supports_mem_region = LazyBool::eLazyBoolNo;
3335af245d11STodd Fiala             return error;
3336af245d11STodd Fiala         }
3337af245d11STodd Fiala         else if (m_mem_region_cache.empty ())
3338af245d11STodd Fiala         {
3339af245d11STodd Fiala             // No entries after attempting to read them.  This shouldn't happen if /proc/{pid}/maps
3340af245d11STodd Fiala             // is supported.  Assume we don't support map entries via procfs.
3341af245d11STodd Fiala             if (log)
3342af245d11STodd Fiala                 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
3343af245d11STodd Fiala             m_supports_mem_region = LazyBool::eLazyBoolNo;
3344af245d11STodd Fiala             error.SetErrorString ("not supported");
3345af245d11STodd Fiala             return error;
3346af245d11STodd Fiala         }
3347af245d11STodd Fiala 
3348af245d11STodd Fiala         if (log)
3349af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ());
3350af245d11STodd Fiala 
3351af245d11STodd Fiala         // We support memory retrieval, remember that.
3352af245d11STodd Fiala         m_supports_mem_region = LazyBool::eLazyBoolYes;
3353af245d11STodd Fiala     }
3354af245d11STodd Fiala     else
3355af245d11STodd Fiala     {
3356af245d11STodd Fiala         if (log)
3357af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
3358af245d11STodd Fiala     }
3359af245d11STodd Fiala 
3360af245d11STodd Fiala     lldb::addr_t prev_base_address = 0;
3361af245d11STodd Fiala 
3362af245d11STodd Fiala     // FIXME start by finding the last region that is <= target address using binary search.  Data is sorted.
3363af245d11STodd Fiala     // There can be a ton of regions on pthreads apps with lots of threads.
3364af245d11STodd Fiala     for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
3365af245d11STodd Fiala     {
3366af245d11STodd Fiala         MemoryRegionInfo &proc_entry_info = *it;
3367af245d11STodd Fiala 
3368af245d11STodd Fiala         // Sanity check assumption that /proc/{pid}/maps entries are ascending.
3369af245d11STodd Fiala         assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
3370af245d11STodd Fiala         prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
3371af245d11STodd Fiala 
3372af245d11STodd Fiala         // If the target address comes before this entry, indicate distance to next region.
3373af245d11STodd Fiala         if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
3374af245d11STodd Fiala         {
3375af245d11STodd Fiala             range_info.GetRange ().SetRangeBase (load_addr);
3376af245d11STodd Fiala             range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
3377af245d11STodd Fiala             range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
3378af245d11STodd Fiala             range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
3379af245d11STodd Fiala             range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
3380af245d11STodd Fiala 
3381af245d11STodd Fiala             return error;
3382af245d11STodd Fiala         }
3383af245d11STodd Fiala         else if (proc_entry_info.GetRange ().Contains (load_addr))
3384af245d11STodd Fiala         {
3385af245d11STodd Fiala             // The target address is within the memory region we're processing here.
3386af245d11STodd Fiala             range_info = proc_entry_info;
3387af245d11STodd Fiala             return error;
3388af245d11STodd Fiala         }
3389af245d11STodd Fiala 
3390af245d11STodd Fiala         // The target memory address comes somewhere after the region we just parsed.
3391af245d11STodd Fiala     }
3392af245d11STodd Fiala 
3393af245d11STodd Fiala     // If we made it here, we didn't find an entry that contained the given address.
3394af245d11STodd Fiala     error.SetErrorString ("address comes after final region");
3395af245d11STodd Fiala 
3396af245d11STodd Fiala     if (log)
3397af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s failed to find map entry for address 0x%" PRIx64 ": %s", __FUNCTION__, load_addr, error.AsCString ());
3398af245d11STodd Fiala 
3399af245d11STodd Fiala     return error;
3400af245d11STodd Fiala }
3401af245d11STodd Fiala 
3402af245d11STodd Fiala void
3403af245d11STodd Fiala NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
3404af245d11STodd Fiala {
3405af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3406af245d11STodd Fiala     if (log)
3407af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
3408af245d11STodd Fiala 
3409af245d11STodd Fiala     {
3410af245d11STodd Fiala         Mutex::Locker locker (m_mem_region_cache_mutex);
3411af245d11STodd Fiala         if (log)
3412af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
3413af245d11STodd Fiala         m_mem_region_cache.clear ();
3414af245d11STodd Fiala     }
3415af245d11STodd Fiala }
3416af245d11STodd Fiala 
3417af245d11STodd Fiala Error
34183eb4b458SChaoren Lin NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr)
3419af245d11STodd Fiala {
3420af245d11STodd Fiala     // FIXME implementing this requires the equivalent of
3421af245d11STodd Fiala     // InferiorCallPOSIX::InferiorCallMmap, which depends on
3422af245d11STodd Fiala     // functional ThreadPlans working with Native*Protocol.
3423af245d11STodd Fiala #if 1
3424af245d11STodd Fiala     return Error ("not implemented yet");
3425af245d11STodd Fiala #else
3426af245d11STodd Fiala     addr = LLDB_INVALID_ADDRESS;
3427af245d11STodd Fiala 
3428af245d11STodd Fiala     unsigned prot = 0;
3429af245d11STodd Fiala     if (permissions & lldb::ePermissionsReadable)
3430af245d11STodd Fiala         prot |= eMmapProtRead;
3431af245d11STodd Fiala     if (permissions & lldb::ePermissionsWritable)
3432af245d11STodd Fiala         prot |= eMmapProtWrite;
3433af245d11STodd Fiala     if (permissions & lldb::ePermissionsExecutable)
3434af245d11STodd Fiala         prot |= eMmapProtExec;
3435af245d11STodd Fiala 
3436af245d11STodd Fiala     // TODO implement this directly in NativeProcessLinux
3437af245d11STodd Fiala     // (and lift to NativeProcessPOSIX if/when that class is
3438af245d11STodd Fiala     // refactored out).
3439af245d11STodd Fiala     if (InferiorCallMmap(this, addr, 0, size, prot,
3440af245d11STodd Fiala                          eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
3441af245d11STodd Fiala         m_addr_to_mmap_size[addr] = size;
3442af245d11STodd Fiala         return Error ();
3443af245d11STodd Fiala     } else {
3444af245d11STodd Fiala         addr = LLDB_INVALID_ADDRESS;
3445af245d11STodd Fiala         return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
3446af245d11STodd Fiala     }
3447af245d11STodd Fiala #endif
3448af245d11STodd Fiala }
3449af245d11STodd Fiala 
3450af245d11STodd Fiala Error
3451af245d11STodd Fiala NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
3452af245d11STodd Fiala {
3453af245d11STodd Fiala     // FIXME see comments in AllocateMemory - required lower-level
3454af245d11STodd Fiala     // bits not in place yet (ThreadPlans)
3455af245d11STodd Fiala     return Error ("not implemented");
3456af245d11STodd Fiala }
3457af245d11STodd Fiala 
3458af245d11STodd Fiala lldb::addr_t
3459af245d11STodd Fiala NativeProcessLinux::GetSharedLibraryInfoAddress ()
3460af245d11STodd Fiala {
3461af245d11STodd Fiala #if 1
3462af245d11STodd Fiala     // punt on this for now
3463af245d11STodd Fiala     return LLDB_INVALID_ADDRESS;
3464af245d11STodd Fiala #else
3465af245d11STodd Fiala     // Return the image info address for the exe module
3466af245d11STodd Fiala #if 1
3467af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3468af245d11STodd Fiala 
3469af245d11STodd Fiala     ModuleSP module_sp;
3470af245d11STodd Fiala     Error error = GetExeModuleSP (module_sp);
3471af245d11STodd Fiala     if (error.Fail ())
3472af245d11STodd Fiala     {
3473af245d11STodd Fiala          if (log)
3474af245d11STodd Fiala             log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ());
3475af245d11STodd Fiala         return LLDB_INVALID_ADDRESS;
3476af245d11STodd Fiala     }
3477af245d11STodd Fiala 
3478af245d11STodd Fiala     if (module_sp == nullptr)
3479af245d11STodd Fiala     {
3480af245d11STodd Fiala          if (log)
3481af245d11STodd Fiala             log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__);
3482af245d11STodd Fiala          return LLDB_INVALID_ADDRESS;
3483af245d11STodd Fiala     }
3484af245d11STodd Fiala 
3485af245d11STodd Fiala     ObjectFileSP object_file_sp = module_sp->GetObjectFile ();
3486af245d11STodd Fiala     if (object_file_sp == nullptr)
3487af245d11STodd Fiala     {
3488af245d11STodd Fiala          if (log)
3489af245d11STodd Fiala             log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__);
3490af245d11STodd Fiala          return LLDB_INVALID_ADDRESS;
3491af245d11STodd Fiala     }
3492af245d11STodd Fiala 
3493af245d11STodd Fiala     return obj_file_sp->GetImageInfoAddress();
3494af245d11STodd Fiala #else
3495af245d11STodd Fiala     Target *target = &GetTarget();
3496af245d11STodd Fiala     ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
3497af245d11STodd Fiala     Address addr = obj_file->GetImageInfoAddress(target);
3498af245d11STodd Fiala 
3499af245d11STodd Fiala     if (addr.IsValid())
3500af245d11STodd Fiala         return addr.GetLoadAddress(target);
3501af245d11STodd Fiala     return LLDB_INVALID_ADDRESS;
3502af245d11STodd Fiala #endif
3503af245d11STodd Fiala #endif // punt on this for now
3504af245d11STodd Fiala }
3505af245d11STodd Fiala 
3506af245d11STodd Fiala size_t
3507af245d11STodd Fiala NativeProcessLinux::UpdateThreads ()
3508af245d11STodd Fiala {
3509af245d11STodd Fiala     // The NativeProcessLinux monitoring threads are always up to date
3510af245d11STodd Fiala     // with respect to thread state and they keep the thread list
3511af245d11STodd Fiala     // populated properly. All this method needs to do is return the
3512af245d11STodd Fiala     // thread count.
3513af245d11STodd Fiala     Mutex::Locker locker (m_threads_mutex);
3514af245d11STodd Fiala     return m_threads.size ();
3515af245d11STodd Fiala }
3516af245d11STodd Fiala 
3517af245d11STodd Fiala bool
3518af245d11STodd Fiala NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
3519af245d11STodd Fiala {
3520af245d11STodd Fiala     arch = m_arch;
3521af245d11STodd Fiala     return true;
3522af245d11STodd Fiala }
3523af245d11STodd Fiala 
3524af245d11STodd Fiala Error
352563c8be95STamas Berghammer NativeProcessLinux::GetSoftwareBreakpointPCOffset (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size)
3526af245d11STodd Fiala {
3527af245d11STodd Fiala     // FIXME put this behind a breakpoint protocol class that can be
3528af245d11STodd Fiala     // set per architecture.  Need ARM, MIPS support here.
35292afc5966STodd Fiala     static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
3530af245d11STodd Fiala     static const uint8_t g_i386_opcode [] = { 0xCC };
3531e8659b5dSMohit K. Bhakkad     static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
3532af245d11STodd Fiala 
3533af245d11STodd Fiala     switch (m_arch.GetMachine ())
3534af245d11STodd Fiala     {
35352afc5966STodd Fiala         case llvm::Triple::aarch64:
35362afc5966STodd Fiala             actual_opcode_size = static_cast<uint32_t> (sizeof(g_aarch64_opcode));
35372afc5966STodd Fiala             return Error ();
35382afc5966STodd Fiala 
353963c8be95STamas Berghammer         case llvm::Triple::arm:
354063c8be95STamas Berghammer             actual_opcode_size = 0; // On arm the PC don't get updated for breakpoint hits
354163c8be95STamas Berghammer             return Error ();
354263c8be95STamas Berghammer 
3543af245d11STodd Fiala         case llvm::Triple::x86:
3544af245d11STodd Fiala         case llvm::Triple::x86_64:
3545af245d11STodd Fiala             actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
3546af245d11STodd Fiala             return Error ();
3547af245d11STodd Fiala 
3548e8659b5dSMohit K. Bhakkad         case llvm::Triple::mips64:
3549e8659b5dSMohit K. Bhakkad         case llvm::Triple::mips64el:
3550e8659b5dSMohit K. Bhakkad             actual_opcode_size = static_cast<uint32_t> (sizeof(g_mips64_opcode));
3551e8659b5dSMohit K. Bhakkad             return Error ();
3552e8659b5dSMohit K. Bhakkad 
3553af245d11STodd Fiala         default:
3554af245d11STodd Fiala             assert(false && "CPU type not supported!");
3555af245d11STodd Fiala             return Error ("CPU type not supported");
3556af245d11STodd Fiala     }
3557af245d11STodd Fiala }
3558af245d11STodd Fiala 
3559af245d11STodd Fiala Error
3560af245d11STodd Fiala NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
3561af245d11STodd Fiala {
3562af245d11STodd Fiala     if (hardware)
3563af245d11STodd Fiala         return Error ("NativeProcessLinux does not support hardware breakpoints");
3564af245d11STodd Fiala     else
3565af245d11STodd Fiala         return SetSoftwareBreakpoint (addr, size);
3566af245d11STodd Fiala }
3567af245d11STodd Fiala 
3568af245d11STodd Fiala Error
356963c8be95STamas Berghammer NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint,
357063c8be95STamas Berghammer                                                      size_t &actual_opcode_size,
357163c8be95STamas Berghammer                                                      const uint8_t *&trap_opcode_bytes)
3572af245d11STodd Fiala {
357363c8be95STamas Berghammer     // FIXME put this behind a breakpoint protocol class that can be set per
357463c8be95STamas Berghammer     // architecture.  Need MIPS support here.
35752afc5966STodd Fiala     static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
357663c8be95STamas Berghammer     // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
357763c8be95STamas Berghammer     // linux kernel does otherwise.
357863c8be95STamas Berghammer     static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 };
3579af245d11STodd Fiala     static const uint8_t g_i386_opcode [] = { 0xCC };
35803df471c3SMohit K. Bhakkad     static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
35812c2acf96SMohit K. Bhakkad     static const uint8_t g_mips64el_opcode[] = { 0x0d, 0x00, 0x00, 0x00 };
358263c8be95STamas Berghammer     static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde };
3583af245d11STodd Fiala 
3584af245d11STodd Fiala     switch (m_arch.GetMachine ())
3585af245d11STodd Fiala     {
35862afc5966STodd Fiala     case llvm::Triple::aarch64:
35872afc5966STodd Fiala         trap_opcode_bytes = g_aarch64_opcode;
35882afc5966STodd Fiala         actual_opcode_size = sizeof(g_aarch64_opcode);
35892afc5966STodd Fiala         return Error ();
35902afc5966STodd Fiala 
359163c8be95STamas Berghammer     case llvm::Triple::arm:
359263c8be95STamas Berghammer         switch (trap_opcode_size_hint)
359363c8be95STamas Berghammer         {
359463c8be95STamas Berghammer         case 2:
359563c8be95STamas Berghammer             trap_opcode_bytes = g_thumb_breakpoint_opcode;
359663c8be95STamas Berghammer             actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
359763c8be95STamas Berghammer             return Error ();
359863c8be95STamas Berghammer         case 4:
359963c8be95STamas Berghammer             trap_opcode_bytes = g_arm_breakpoint_opcode;
360063c8be95STamas Berghammer             actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
360163c8be95STamas Berghammer             return Error ();
360263c8be95STamas Berghammer         default:
360363c8be95STamas Berghammer             assert(false && "Unrecognised trap opcode size hint!");
360463c8be95STamas Berghammer             return Error ("Unrecognised trap opcode size hint!");
360563c8be95STamas Berghammer         }
360663c8be95STamas Berghammer 
3607af245d11STodd Fiala     case llvm::Triple::x86:
3608af245d11STodd Fiala     case llvm::Triple::x86_64:
3609af245d11STodd Fiala         trap_opcode_bytes = g_i386_opcode;
3610af245d11STodd Fiala         actual_opcode_size = sizeof(g_i386_opcode);
3611af245d11STodd Fiala         return Error ();
3612af245d11STodd Fiala 
36133df471c3SMohit K. Bhakkad     case llvm::Triple::mips64:
36143df471c3SMohit K. Bhakkad         trap_opcode_bytes = g_mips64_opcode;
36153df471c3SMohit K. Bhakkad         actual_opcode_size = sizeof(g_mips64_opcode);
36163df471c3SMohit K. Bhakkad         return Error ();
36173df471c3SMohit K. Bhakkad 
36182c2acf96SMohit K. Bhakkad     case llvm::Triple::mips64el:
36192c2acf96SMohit K. Bhakkad         trap_opcode_bytes = g_mips64el_opcode;
36202c2acf96SMohit K. Bhakkad         actual_opcode_size = sizeof(g_mips64el_opcode);
36212c2acf96SMohit K. Bhakkad         return Error ();
36222c2acf96SMohit K. Bhakkad 
3623af245d11STodd Fiala     default:
3624af245d11STodd Fiala         assert(false && "CPU type not supported!");
3625af245d11STodd Fiala         return Error ("CPU type not supported");
3626af245d11STodd Fiala     }
3627af245d11STodd Fiala }
3628af245d11STodd Fiala 
3629af245d11STodd Fiala #if 0
3630af245d11STodd Fiala ProcessMessage::CrashReason
3631af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
3632af245d11STodd Fiala {
3633af245d11STodd Fiala     ProcessMessage::CrashReason reason;
3634af245d11STodd Fiala     assert(info->si_signo == SIGSEGV);
3635af245d11STodd Fiala 
3636af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
3637af245d11STodd Fiala 
3638af245d11STodd Fiala     switch (info->si_code)
3639af245d11STodd Fiala     {
3640af245d11STodd Fiala     default:
3641af245d11STodd Fiala         assert(false && "unexpected si_code for SIGSEGV");
3642af245d11STodd Fiala         break;
3643af245d11STodd Fiala     case SI_KERNEL:
3644af245d11STodd Fiala         // Linux will occasionally send spurious SI_KERNEL codes.
3645af245d11STodd Fiala         // (this is poorly documented in sigaction)
3646af245d11STodd Fiala         // One way to get this is via unaligned SIMD loads.
3647af245d11STodd Fiala         reason = ProcessMessage::eInvalidAddress; // for lack of anything better
3648af245d11STodd Fiala         break;
3649af245d11STodd Fiala     case SEGV_MAPERR:
3650af245d11STodd Fiala         reason = ProcessMessage::eInvalidAddress;
3651af245d11STodd Fiala         break;
3652af245d11STodd Fiala     case SEGV_ACCERR:
3653af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedAddress;
3654af245d11STodd Fiala         break;
3655af245d11STodd Fiala     }
3656af245d11STodd Fiala 
3657af245d11STodd Fiala     return reason;
3658af245d11STodd Fiala }
3659af245d11STodd Fiala #endif
3660af245d11STodd Fiala 
3661af245d11STodd Fiala 
3662af245d11STodd Fiala #if 0
3663af245d11STodd Fiala ProcessMessage::CrashReason
3664af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
3665af245d11STodd Fiala {
3666af245d11STodd Fiala     ProcessMessage::CrashReason reason;
3667af245d11STodd Fiala     assert(info->si_signo == SIGILL);
3668af245d11STodd Fiala 
3669af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
3670af245d11STodd Fiala 
3671af245d11STodd Fiala     switch (info->si_code)
3672af245d11STodd Fiala     {
3673af245d11STodd Fiala     default:
3674af245d11STodd Fiala         assert(false && "unexpected si_code for SIGILL");
3675af245d11STodd Fiala         break;
3676af245d11STodd Fiala     case ILL_ILLOPC:
3677af245d11STodd Fiala         reason = ProcessMessage::eIllegalOpcode;
3678af245d11STodd Fiala         break;
3679af245d11STodd Fiala     case ILL_ILLOPN:
3680af245d11STodd Fiala         reason = ProcessMessage::eIllegalOperand;
3681af245d11STodd Fiala         break;
3682af245d11STodd Fiala     case ILL_ILLADR:
3683af245d11STodd Fiala         reason = ProcessMessage::eIllegalAddressingMode;
3684af245d11STodd Fiala         break;
3685af245d11STodd Fiala     case ILL_ILLTRP:
3686af245d11STodd Fiala         reason = ProcessMessage::eIllegalTrap;
3687af245d11STodd Fiala         break;
3688af245d11STodd Fiala     case ILL_PRVOPC:
3689af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedOpcode;
3690af245d11STodd Fiala         break;
3691af245d11STodd Fiala     case ILL_PRVREG:
3692af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedRegister;
3693af245d11STodd Fiala         break;
3694af245d11STodd Fiala     case ILL_COPROC:
3695af245d11STodd Fiala         reason = ProcessMessage::eCoprocessorError;
3696af245d11STodd Fiala         break;
3697af245d11STodd Fiala     case ILL_BADSTK:
3698af245d11STodd Fiala         reason = ProcessMessage::eInternalStackError;
3699af245d11STodd Fiala         break;
3700af245d11STodd Fiala     }
3701af245d11STodd Fiala 
3702af245d11STodd Fiala     return reason;
3703af245d11STodd Fiala }
3704af245d11STodd Fiala #endif
3705af245d11STodd Fiala 
3706af245d11STodd Fiala #if 0
3707af245d11STodd Fiala ProcessMessage::CrashReason
3708af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
3709af245d11STodd Fiala {
3710af245d11STodd Fiala     ProcessMessage::CrashReason reason;
3711af245d11STodd Fiala     assert(info->si_signo == SIGFPE);
3712af245d11STodd Fiala 
3713af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
3714af245d11STodd Fiala 
3715af245d11STodd Fiala     switch (info->si_code)
3716af245d11STodd Fiala     {
3717af245d11STodd Fiala     default:
3718af245d11STodd Fiala         assert(false && "unexpected si_code for SIGFPE");
3719af245d11STodd Fiala         break;
3720af245d11STodd Fiala     case FPE_INTDIV:
3721af245d11STodd Fiala         reason = ProcessMessage::eIntegerDivideByZero;
3722af245d11STodd Fiala         break;
3723af245d11STodd Fiala     case FPE_INTOVF:
3724af245d11STodd Fiala         reason = ProcessMessage::eIntegerOverflow;
3725af245d11STodd Fiala         break;
3726af245d11STodd Fiala     case FPE_FLTDIV:
3727af245d11STodd Fiala         reason = ProcessMessage::eFloatDivideByZero;
3728af245d11STodd Fiala         break;
3729af245d11STodd Fiala     case FPE_FLTOVF:
3730af245d11STodd Fiala         reason = ProcessMessage::eFloatOverflow;
3731af245d11STodd Fiala         break;
3732af245d11STodd Fiala     case FPE_FLTUND:
3733af245d11STodd Fiala         reason = ProcessMessage::eFloatUnderflow;
3734af245d11STodd Fiala         break;
3735af245d11STodd Fiala     case FPE_FLTRES:
3736af245d11STodd Fiala         reason = ProcessMessage::eFloatInexactResult;
3737af245d11STodd Fiala         break;
3738af245d11STodd Fiala     case FPE_FLTINV:
3739af245d11STodd Fiala         reason = ProcessMessage::eFloatInvalidOperation;
3740af245d11STodd Fiala         break;
3741af245d11STodd Fiala     case FPE_FLTSUB:
3742af245d11STodd Fiala         reason = ProcessMessage::eFloatSubscriptRange;
3743af245d11STodd Fiala         break;
3744af245d11STodd Fiala     }
3745af245d11STodd Fiala 
3746af245d11STodd Fiala     return reason;
3747af245d11STodd Fiala }
3748af245d11STodd Fiala #endif
3749af245d11STodd Fiala 
3750af245d11STodd Fiala #if 0
3751af245d11STodd Fiala ProcessMessage::CrashReason
3752af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
3753af245d11STodd Fiala {
3754af245d11STodd Fiala     ProcessMessage::CrashReason reason;
3755af245d11STodd Fiala     assert(info->si_signo == SIGBUS);
3756af245d11STodd Fiala 
3757af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
3758af245d11STodd Fiala 
3759af245d11STodd Fiala     switch (info->si_code)
3760af245d11STodd Fiala     {
3761af245d11STodd Fiala     default:
3762af245d11STodd Fiala         assert(false && "unexpected si_code for SIGBUS");
3763af245d11STodd Fiala         break;
3764af245d11STodd Fiala     case BUS_ADRALN:
3765af245d11STodd Fiala         reason = ProcessMessage::eIllegalAlignment;
3766af245d11STodd Fiala         break;
3767af245d11STodd Fiala     case BUS_ADRERR:
3768af245d11STodd Fiala         reason = ProcessMessage::eIllegalAddress;
3769af245d11STodd Fiala         break;
3770af245d11STodd Fiala     case BUS_OBJERR:
3771af245d11STodd Fiala         reason = ProcessMessage::eHardwareError;
3772af245d11STodd Fiala         break;
3773af245d11STodd Fiala     }
3774af245d11STodd Fiala 
3775af245d11STodd Fiala     return reason;
3776af245d11STodd Fiala }
3777af245d11STodd Fiala #endif
3778af245d11STodd Fiala 
3779af245d11STodd Fiala Error
378045f5cb31SPavel Labath NativeProcessLinux::SetWatchpoint (lldb::addr_t addr, size_t size, uint32_t watch_flags, bool hardware)
378145f5cb31SPavel Labath {
378245f5cb31SPavel Labath     // The base SetWatchpoint will end up executing monitor operations. Let's lock the monitor
378345f5cb31SPavel Labath     // for it.
378445f5cb31SPavel Labath     Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
378545f5cb31SPavel Labath     return NativeProcessProtocol::SetWatchpoint(addr, size, watch_flags, hardware);
378645f5cb31SPavel Labath }
378745f5cb31SPavel Labath 
378845f5cb31SPavel Labath Error
378945f5cb31SPavel Labath NativeProcessLinux::RemoveWatchpoint (lldb::addr_t addr)
379045f5cb31SPavel Labath {
379145f5cb31SPavel Labath     // The base RemoveWatchpoint will end up executing monitor operations. Let's lock the monitor
379245f5cb31SPavel Labath     // for it.
379345f5cb31SPavel Labath     Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
379445f5cb31SPavel Labath     return NativeProcessProtocol::RemoveWatchpoint(addr);
379545f5cb31SPavel Labath }
379645f5cb31SPavel Labath 
379745f5cb31SPavel Labath Error
379826438d26SChaoren Lin NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
3799af245d11STodd Fiala {
3800af245d11STodd Fiala     ReadOperation op(addr, buf, size, bytes_read);
3801bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
3802af245d11STodd Fiala     return op.GetError ();
3803af245d11STodd Fiala }
3804af245d11STodd Fiala 
3805af245d11STodd Fiala Error
38063eb4b458SChaoren Lin NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
38073eb4b458SChaoren Lin {
38083eb4b458SChaoren Lin     Error error = ReadMemory(addr, buf, size, bytes_read);
38093eb4b458SChaoren Lin     if (error.Fail()) return error;
38103eb4b458SChaoren Lin     return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
38113eb4b458SChaoren Lin }
38123eb4b458SChaoren Lin 
38133eb4b458SChaoren Lin Error
38143eb4b458SChaoren Lin NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written)
3815af245d11STodd Fiala {
3816af245d11STodd Fiala     WriteOperation op(addr, buf, size, bytes_written);
3817bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
3818af245d11STodd Fiala     return op.GetError ();
3819af245d11STodd Fiala }
3820af245d11STodd Fiala 
382197ccc294SChaoren Lin Error
3822af245d11STodd Fiala NativeProcessLinux::ReadRegisterValue(lldb::tid_t tid, uint32_t offset, const char* reg_name,
3823af245d11STodd Fiala                                       uint32_t size, RegisterValue &value)
3824af245d11STodd Fiala {
382597ccc294SChaoren Lin     ReadRegOperation op(tid, offset, reg_name, value);
3826bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
382797ccc294SChaoren Lin     return op.GetError();
3828af245d11STodd Fiala }
3829af245d11STodd Fiala 
383097ccc294SChaoren Lin Error
3831af245d11STodd Fiala NativeProcessLinux::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
3832af245d11STodd Fiala                                    const char* reg_name, const RegisterValue &value)
3833af245d11STodd Fiala {
383497ccc294SChaoren Lin     WriteRegOperation op(tid, offset, reg_name, value);
3835bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
383697ccc294SChaoren Lin     return op.GetError();
3837af245d11STodd Fiala }
3838af245d11STodd Fiala 
383997ccc294SChaoren Lin Error
3840af245d11STodd Fiala NativeProcessLinux::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3841af245d11STodd Fiala {
384297ccc294SChaoren Lin     ReadGPROperation op(tid, buf, buf_size);
3843bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
384497ccc294SChaoren Lin     return op.GetError();
3845af245d11STodd Fiala }
3846af245d11STodd Fiala 
384797ccc294SChaoren Lin Error
3848af245d11STodd Fiala NativeProcessLinux::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3849af245d11STodd Fiala {
385097ccc294SChaoren Lin     ReadFPROperation op(tid, buf, buf_size);
3851bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
385297ccc294SChaoren Lin     return op.GetError();
3853af245d11STodd Fiala }
3854af245d11STodd Fiala 
385597ccc294SChaoren Lin Error
3856af245d11STodd Fiala NativeProcessLinux::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3857af245d11STodd Fiala {
385897ccc294SChaoren Lin     ReadRegisterSetOperation op(tid, buf, buf_size, regset);
3859bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
386097ccc294SChaoren Lin     return op.GetError();
3861af245d11STodd Fiala }
3862af245d11STodd Fiala 
386397ccc294SChaoren Lin Error
3864af245d11STodd Fiala NativeProcessLinux::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3865af245d11STodd Fiala {
386697ccc294SChaoren Lin     WriteGPROperation op(tid, buf, buf_size);
3867bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
386897ccc294SChaoren Lin     return op.GetError();
3869af245d11STodd Fiala }
3870af245d11STodd Fiala 
387197ccc294SChaoren Lin Error
3872af245d11STodd Fiala NativeProcessLinux::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3873af245d11STodd Fiala {
387497ccc294SChaoren Lin     WriteFPROperation op(tid, buf, buf_size);
3875bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
387697ccc294SChaoren Lin     return op.GetError();
3877af245d11STodd Fiala }
3878af245d11STodd Fiala 
387997ccc294SChaoren Lin Error
3880af245d11STodd Fiala NativeProcessLinux::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3881af245d11STodd Fiala {
388297ccc294SChaoren Lin     WriteRegisterSetOperation op(tid, buf, buf_size, regset);
3883bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
388497ccc294SChaoren Lin     return op.GetError();
3885af245d11STodd Fiala }
3886af245d11STodd Fiala 
388797ccc294SChaoren Lin Error
3888af245d11STodd Fiala NativeProcessLinux::Resume (lldb::tid_t tid, uint32_t signo)
3889af245d11STodd Fiala {
3890af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3891af245d11STodd Fiala 
3892af245d11STodd Fiala     if (log)
3893af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s() resuming thread = %"  PRIu64 " with signal %s", __FUNCTION__, tid,
3894af245d11STodd Fiala                                  GetUnixSignals().GetSignalAsCString (signo));
389597ccc294SChaoren Lin     ResumeOperation op (tid, signo);
3896bd7cbc5aSPavel Labath     m_monitor_up->DoOperation (&op);
3897af245d11STodd Fiala     if (log)
389897ccc294SChaoren Lin         log->Printf ("NativeProcessLinux::%s() resuming thread = %"  PRIu64 " result = %s", __FUNCTION__, tid, op.GetError().Success() ? "true" : "false");
389997ccc294SChaoren Lin     return op.GetError();
3900af245d11STodd Fiala }
3901af245d11STodd Fiala 
390297ccc294SChaoren Lin Error
3903af245d11STodd Fiala NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo)
3904af245d11STodd Fiala {
390597ccc294SChaoren Lin     SingleStepOperation op(tid, signo);
3906bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
390797ccc294SChaoren Lin     return op.GetError();
3908af245d11STodd Fiala }
3909af245d11STodd Fiala 
391097ccc294SChaoren Lin Error
391197ccc294SChaoren Lin NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
3912af245d11STodd Fiala {
391397ccc294SChaoren Lin     SiginfoOperation op(tid, siginfo);
3914bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
391597ccc294SChaoren Lin     return op.GetError();
3916af245d11STodd Fiala }
3917af245d11STodd Fiala 
391897ccc294SChaoren Lin Error
3919af245d11STodd Fiala NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
3920af245d11STodd Fiala {
392197ccc294SChaoren Lin     EventMessageOperation op(tid, message);
3922bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
392397ccc294SChaoren Lin     return op.GetError();
3924af245d11STodd Fiala }
3925af245d11STodd Fiala 
3926db264a6dSTamas Berghammer Error
3927af245d11STodd Fiala NativeProcessLinux::Detach(lldb::tid_t tid)
3928af245d11STodd Fiala {
392997ccc294SChaoren Lin     if (tid == LLDB_INVALID_THREAD_ID)
393097ccc294SChaoren Lin         return Error();
393197ccc294SChaoren Lin 
393297ccc294SChaoren Lin     DetachOperation op(tid);
3933bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
393497ccc294SChaoren Lin     return op.GetError();
3935af245d11STodd Fiala }
3936af245d11STodd Fiala 
3937af245d11STodd Fiala bool
3938af245d11STodd Fiala NativeProcessLinux::DupDescriptor(const char *path, int fd, int flags)
3939af245d11STodd Fiala {
3940af245d11STodd Fiala     int target_fd = open(path, flags, 0666);
3941af245d11STodd Fiala 
3942af245d11STodd Fiala     if (target_fd == -1)
3943af245d11STodd Fiala         return false;
3944af245d11STodd Fiala 
3945493c3a12SPavel Labath     if (dup2(target_fd, fd) == -1)
3946493c3a12SPavel Labath         return false;
3947493c3a12SPavel Labath 
3948493c3a12SPavel Labath     return (close(target_fd) == -1) ? false : true;
3949af245d11STodd Fiala }
3950af245d11STodd Fiala 
3951af245d11STodd Fiala void
3952bd7cbc5aSPavel Labath NativeProcessLinux::StartMonitorThread(const InitialOperation &initial_operation, Error &error)
3953af245d11STodd Fiala {
3954bd7cbc5aSPavel Labath     m_monitor_up.reset(new Monitor(initial_operation, this));
39551107b5a5SPavel Labath     error = m_monitor_up->Initialize();
39561107b5a5SPavel Labath     if (error.Fail()) {
39571107b5a5SPavel Labath         m_monitor_up.reset();
3958af245d11STodd Fiala     }
3959af245d11STodd Fiala }
3960af245d11STodd Fiala 
3961af245d11STodd Fiala bool
3962af245d11STodd Fiala NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
3963af245d11STodd Fiala {
3964af245d11STodd Fiala     for (auto thread_sp : m_threads)
3965af245d11STodd Fiala     {
3966af245d11STodd Fiala         assert (thread_sp && "thread list should not contain NULL threads");
3967af245d11STodd Fiala         if (thread_sp->GetID () == thread_id)
3968af245d11STodd Fiala         {
3969af245d11STodd Fiala             // We have this thread.
3970af245d11STodd Fiala             return true;
3971af245d11STodd Fiala         }
3972af245d11STodd Fiala     }
3973af245d11STodd Fiala 
3974af245d11STodd Fiala     // We don't have this thread.
3975af245d11STodd Fiala     return false;
3976af245d11STodd Fiala }
3977af245d11STodd Fiala 
3978af245d11STodd Fiala NativeThreadProtocolSP
3979af245d11STodd Fiala NativeProcessLinux::MaybeGetThreadNoLock (lldb::tid_t thread_id)
3980af245d11STodd Fiala {
3981af245d11STodd Fiala     // CONSIDER organize threads by map - we can do better than linear.
3982af245d11STodd Fiala     for (auto thread_sp : m_threads)
3983af245d11STodd Fiala     {
3984af245d11STodd Fiala         if (thread_sp->GetID () == thread_id)
3985af245d11STodd Fiala             return thread_sp;
3986af245d11STodd Fiala     }
3987af245d11STodd Fiala 
3988af245d11STodd Fiala     // We don't have this thread.
3989af245d11STodd Fiala     return NativeThreadProtocolSP ();
3990af245d11STodd Fiala }
3991af245d11STodd Fiala 
3992af245d11STodd Fiala bool
3993af245d11STodd Fiala NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
3994af245d11STodd Fiala {
3995af245d11STodd Fiala     Mutex::Locker locker (m_threads_mutex);
3996af245d11STodd Fiala     for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
3997af245d11STodd Fiala     {
3998af245d11STodd Fiala         if (*it && ((*it)->GetID () == thread_id))
3999af245d11STodd Fiala         {
4000af245d11STodd Fiala             m_threads.erase (it);
4001af245d11STodd Fiala             return true;
4002af245d11STodd Fiala         }
4003af245d11STodd Fiala     }
4004af245d11STodd Fiala 
4005af245d11STodd Fiala     // Didn't find it.
4006af245d11STodd Fiala     return false;
4007af245d11STodd Fiala }
4008af245d11STodd Fiala 
4009af245d11STodd Fiala NativeThreadProtocolSP
4010af245d11STodd Fiala NativeProcessLinux::AddThread (lldb::tid_t thread_id)
4011af245d11STodd Fiala {
4012af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
4013af245d11STodd Fiala 
4014af245d11STodd Fiala     Mutex::Locker locker (m_threads_mutex);
4015af245d11STodd Fiala 
4016af245d11STodd Fiala     if (log)
4017af245d11STodd Fiala     {
4018af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
4019af245d11STodd Fiala                 __FUNCTION__,
4020af245d11STodd Fiala                 GetID (),
4021af245d11STodd Fiala                 thread_id);
4022af245d11STodd Fiala     }
4023af245d11STodd Fiala 
4024af245d11STodd Fiala     assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
4025af245d11STodd Fiala 
4026af245d11STodd Fiala     // If this is the first thread, save it as the current thread
4027af245d11STodd Fiala     if (m_threads.empty ())
4028af245d11STodd Fiala         SetCurrentThreadID (thread_id);
4029af245d11STodd Fiala 
4030af245d11STodd Fiala     NativeThreadProtocolSP thread_sp (new NativeThreadLinux (this, thread_id));
4031af245d11STodd Fiala     m_threads.push_back (thread_sp);
4032af245d11STodd Fiala 
4033af245d11STodd Fiala     return thread_sp;
4034af245d11STodd Fiala }
4035af245d11STodd Fiala 
4036af245d11STodd Fiala Error
4037af245d11STodd Fiala NativeProcessLinux::FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp)
4038af245d11STodd Fiala {
403975f47c3aSTodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
4040af245d11STodd Fiala 
4041af245d11STodd Fiala     Error error;
4042af245d11STodd Fiala 
4043af245d11STodd Fiala     // Get a linux thread pointer.
4044af245d11STodd Fiala     if (!thread_sp)
4045af245d11STodd Fiala     {
4046af245d11STodd Fiala         error.SetErrorString ("null thread_sp");
4047af245d11STodd Fiala         if (log)
4048af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
4049af245d11STodd Fiala         return error;
4050af245d11STodd Fiala     }
4051cb84eebbSTamas Berghammer     std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
4052af245d11STodd Fiala 
4053af245d11STodd Fiala     // Find out the size of a breakpoint (might depend on where we are in the code).
4054cb84eebbSTamas Berghammer     NativeRegisterContextSP context_sp = linux_thread_sp->GetRegisterContext ();
4055af245d11STodd Fiala     if (!context_sp)
4056af245d11STodd Fiala     {
4057af245d11STodd Fiala         error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
4058af245d11STodd Fiala         if (log)
4059af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
4060af245d11STodd Fiala         return error;
4061af245d11STodd Fiala     }
4062af245d11STodd Fiala 
4063af245d11STodd Fiala     uint32_t breakpoint_size = 0;
406463c8be95STamas Berghammer     error = GetSoftwareBreakpointPCOffset (context_sp, breakpoint_size);
4065af245d11STodd Fiala     if (error.Fail ())
4066af245d11STodd Fiala     {
4067af245d11STodd Fiala         if (log)
4068af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
4069af245d11STodd Fiala         return error;
4070af245d11STodd Fiala     }
4071af245d11STodd Fiala     else
4072af245d11STodd Fiala     {
4073af245d11STodd Fiala         if (log)
4074af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
4075af245d11STodd Fiala     }
4076af245d11STodd Fiala 
4077af245d11STodd Fiala     // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
4078af245d11STodd Fiala     const lldb::addr_t initial_pc_addr = context_sp->GetPC ();
4079af245d11STodd Fiala     lldb::addr_t breakpoint_addr = initial_pc_addr;
40803eb4b458SChaoren Lin     if (breakpoint_size > 0)
4081af245d11STodd Fiala     {
4082af245d11STodd Fiala         // Do not allow breakpoint probe to wrap around.
40833eb4b458SChaoren Lin         if (breakpoint_addr >= breakpoint_size)
40843eb4b458SChaoren Lin             breakpoint_addr -= breakpoint_size;
4085af245d11STodd Fiala     }
4086af245d11STodd Fiala 
4087af245d11STodd Fiala     // Check if we stopped because of a breakpoint.
4088af245d11STodd Fiala     NativeBreakpointSP breakpoint_sp;
4089af245d11STodd Fiala     error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
4090af245d11STodd Fiala     if (!error.Success () || !breakpoint_sp)
4091af245d11STodd Fiala     {
4092af245d11STodd Fiala         // We didn't find one at a software probe location.  Nothing to do.
4093af245d11STodd Fiala         if (log)
4094af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
4095af245d11STodd Fiala         return Error ();
4096af245d11STodd Fiala     }
4097af245d11STodd Fiala 
4098af245d11STodd Fiala     // If the breakpoint is not a software breakpoint, nothing to do.
4099af245d11STodd Fiala     if (!breakpoint_sp->IsSoftwareBreakpoint ())
4100af245d11STodd Fiala     {
4101af245d11STodd Fiala         if (log)
4102af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
4103af245d11STodd Fiala         return Error ();
4104af245d11STodd Fiala     }
4105af245d11STodd Fiala 
4106af245d11STodd Fiala     //
4107af245d11STodd Fiala     // We have a software breakpoint and need to adjust the PC.
4108af245d11STodd Fiala     //
4109af245d11STodd Fiala 
4110af245d11STodd Fiala     // Sanity check.
4111af245d11STodd Fiala     if (breakpoint_size == 0)
4112af245d11STodd Fiala     {
4113af245d11STodd Fiala         // Nothing to do!  How did we get here?
4114af245d11STodd Fiala         if (log)
4115af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", it is software, but the size is zero, nothing to do (unexpected)", __FUNCTION__, GetID (), breakpoint_addr);
4116af245d11STodd Fiala         return Error ();
4117af245d11STodd Fiala     }
4118af245d11STodd Fiala 
4119af245d11STodd Fiala     // Change the program counter.
4120af245d11STodd Fiala     if (log)
4121cb84eebbSTamas Berghammer         log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": changing PC from 0x%" PRIx64 " to 0x%" PRIx64, __FUNCTION__, GetID (), linux_thread_sp->GetID (), initial_pc_addr, breakpoint_addr);
4122af245d11STodd Fiala 
4123af245d11STodd Fiala     error = context_sp->SetPC (breakpoint_addr);
4124af245d11STodd Fiala     if (error.Fail ())
4125af245d11STodd Fiala     {
4126af245d11STodd Fiala         if (log)
4127cb84eebbSTamas Berghammer             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": failed to set PC: %s", __FUNCTION__, GetID (), linux_thread_sp->GetID (), error.AsCString ());
4128af245d11STodd Fiala         return error;
4129af245d11STodd Fiala     }
4130af245d11STodd Fiala 
4131af245d11STodd Fiala     return error;
4132af245d11STodd Fiala }
4133fa03ad2eSChaoren Lin 
41347cb18bf5STamas Berghammer Error
41357cb18bf5STamas Berghammer NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec)
41367cb18bf5STamas Berghammer {
41377cb18bf5STamas Berghammer     char maps_file_name[32];
41387cb18bf5STamas Berghammer     snprintf(maps_file_name, sizeof(maps_file_name), "/proc/%" PRIu64 "/maps", GetID());
41397cb18bf5STamas Berghammer 
41407cb18bf5STamas Berghammer     FileSpec maps_file_spec(maps_file_name, false);
41417cb18bf5STamas Berghammer     if (!maps_file_spec.Exists()) {
41427cb18bf5STamas Berghammer         file_spec.Clear();
41437cb18bf5STamas Berghammer         return Error("/proc/%" PRIu64 "/maps file doesn't exists!", GetID());
41447cb18bf5STamas Berghammer     }
41457cb18bf5STamas Berghammer 
41467cb18bf5STamas Berghammer     FileSpec module_file_spec(module_path, true);
41477cb18bf5STamas Berghammer 
41487cb18bf5STamas Berghammer     std::ifstream maps_file(maps_file_name);
41497cb18bf5STamas Berghammer     std::string maps_data_str((std::istreambuf_iterator<char>(maps_file)), std::istreambuf_iterator<char>());
41507cb18bf5STamas Berghammer     StringRef maps_data(maps_data_str.c_str());
41517cb18bf5STamas Berghammer 
41527cb18bf5STamas Berghammer     while (!maps_data.empty())
41537cb18bf5STamas Berghammer     {
41547cb18bf5STamas Berghammer         StringRef maps_row;
41557cb18bf5STamas Berghammer         std::tie(maps_row, maps_data) = maps_data.split('\n');
41567cb18bf5STamas Berghammer 
41577cb18bf5STamas Berghammer         SmallVector<StringRef, 16> maps_columns;
41587cb18bf5STamas Berghammer         maps_row.split(maps_columns, StringRef(" "), -1, false);
41597cb18bf5STamas Berghammer 
41607cb18bf5STamas Berghammer         if (maps_columns.size() >= 6)
41617cb18bf5STamas Berghammer         {
41627cb18bf5STamas Berghammer             file_spec.SetFile(maps_columns[5].str().c_str(), false);
41637cb18bf5STamas Berghammer             if (file_spec.GetFilename() == module_file_spec.GetFilename())
41647cb18bf5STamas Berghammer                 return Error();
41657cb18bf5STamas Berghammer         }
41667cb18bf5STamas Berghammer     }
41677cb18bf5STamas Berghammer 
41687cb18bf5STamas Berghammer     file_spec.Clear();
41697cb18bf5STamas Berghammer     return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
41707cb18bf5STamas Berghammer                  module_file_spec.GetFilename().AsCString(), GetID());
41717cb18bf5STamas Berghammer }
4172c076559aSPavel Labath 
41735eb721edSPavel Labath Error
4174c076559aSPavel Labath NativeProcessLinux::DoResume(
4175c076559aSPavel Labath         lldb::tid_t tid,
41768c8ff7afSPavel Labath         NativeThreadLinux::ResumeThreadFunction request_thread_resume_function,
4177c076559aSPavel Labath         bool error_when_already_running)
4178c076559aSPavel Labath {
41795eb721edSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
41805eb721edSPavel Labath 
41818c8ff7afSPavel Labath     auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
41828c8ff7afSPavel Labath     lldbassert(thread_sp != nullptr);
41835eb721edSPavel Labath 
41848c8ff7afSPavel Labath     auto& context = thread_sp->GetThreadContext();
4185c076559aSPavel Labath     // Tell the thread to resume if we don't already think it is running.
41868c8ff7afSPavel Labath     const bool is_stopped = StateIsStoppedState(thread_sp->GetState(), true);
41875eb721edSPavel Labath 
41885eb721edSPavel Labath     lldbassert(!(error_when_already_running && !is_stopped));
41895eb721edSPavel Labath 
4190c076559aSPavel Labath     if (!is_stopped)
4191c076559aSPavel Labath     {
4192c076559aSPavel Labath         // It's not an error, just a log, if the error_when_already_running flag is not set.
4193c076559aSPavel Labath         // This covers cases where, for instance, we're just trying to resume all threads
4194c076559aSPavel Labath         // from the user side.
41955eb721edSPavel Labath         if (log)
41965eb721edSPavel Labath             log->Printf("NativeProcessLinux::%s tid %" PRIu64 " optional resume skipped since it is already running",
4197c076559aSPavel Labath                     __FUNCTION__,
4198c076559aSPavel Labath                     tid);
41995eb721edSPavel Labath         return Error();
4200c076559aSPavel Labath     }
4201c076559aSPavel Labath 
4202c076559aSPavel Labath     // Before we do the resume below, first check if we have a pending
4203c076559aSPavel Labath     // stop notification this is currently or was previously waiting for
4204c076559aSPavel Labath     // this thread to stop.  This is potentially a buggy situation since
4205c076559aSPavel Labath     // we're ostensibly waiting for threads to stop before we send out the
4206c076559aSPavel Labath     // pending notification, and here we are resuming one before we send
4207c076559aSPavel Labath     // out the pending stop notification.
42085eb721edSPavel Labath     if (m_pending_notification_up && log)
4209c076559aSPavel Labath     {
4210c076559aSPavel Labath         if (m_pending_notification_up->wait_for_stop_tids.count (tid) > 0)
4211c076559aSPavel Labath         {
42125eb721edSPavel Labath             log->Printf("NativeProcessLinux::%s about to resume tid %" PRIu64 " per explicit request but we have a pending stop notification (tid %" PRIu64 ") that is actively waiting for this thread to stop. Valid sequence of events?", __FUNCTION__, tid, m_pending_notification_up->triggering_tid);
4213c076559aSPavel Labath         }
4214c076559aSPavel Labath         else if (m_pending_notification_up->original_wait_for_stop_tids.count (tid) > 0)
4215c076559aSPavel Labath         {
42165eb721edSPavel Labath             log->Printf("NativeProcessLinux::%s about to resume tid %" PRIu64 " per explicit request but we have a pending stop notification (tid %" PRIu64 ") that hasn't fired yet and this is one of the threads we had been waiting on (and already marked satisfied for this tid). Valid sequence of events?", __FUNCTION__, tid, m_pending_notification_up->triggering_tid);
4217c076559aSPavel Labath             for (auto tid : m_pending_notification_up->wait_for_stop_tids)
4218c076559aSPavel Labath             {
42195eb721edSPavel Labath                 log->Printf("NativeProcessLinux::%s tid %" PRIu64 " deferred stop notification still waiting on tid  %" PRIu64,
4220c076559aSPavel Labath                                  __FUNCTION__,
4221c076559aSPavel Labath                                  m_pending_notification_up->triggering_tid,
4222c076559aSPavel Labath                                  tid);
4223c076559aSPavel Labath             }
4224c076559aSPavel Labath         }
4225c076559aSPavel Labath     }
4226c076559aSPavel Labath 
4227c076559aSPavel Labath     // Request a resume.  We expect this to be synchronous and the system
4228c076559aSPavel Labath     // to reflect it is running after this completes.
4229c076559aSPavel Labath     const auto error = request_thread_resume_function (tid, false);
4230c076559aSPavel Labath     if (error.Success())
42318c8ff7afSPavel Labath         context.request_resume_function = request_thread_resume_function;
42325eb721edSPavel Labath     else if (log)
4233c076559aSPavel Labath     {
42345eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s failed to resume thread tid  %" PRIu64 ": %s",
4235c076559aSPavel Labath                          __FUNCTION__, tid, error.AsCString ());
4236c076559aSPavel Labath     }
4237c076559aSPavel Labath 
42385eb721edSPavel Labath     return error;
4239c076559aSPavel Labath }
4240c076559aSPavel Labath 
4241c076559aSPavel Labath //===----------------------------------------------------------------------===//
4242c076559aSPavel Labath 
4243c076559aSPavel Labath void
4244ed89c7feSPavel Labath NativeProcessLinux::StopThreads(const lldb::tid_t triggering_tid,
4245337f3eb9SPavel Labath                                           const ThreadIDSet &wait_for_stop_tids)
4246c076559aSPavel Labath {
42475eb721edSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
4248c076559aSPavel Labath     std::lock_guard<std::mutex> lock(m_event_mutex);
4249c076559aSPavel Labath 
42505eb721edSPavel Labath     if (log)
4251c076559aSPavel Labath     {
42525eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ", wait_for_stop_tids.size(): %zd)",
4253c076559aSPavel Labath                 __FUNCTION__, triggering_tid, wait_for_stop_tids.size());
4254c076559aSPavel Labath     }
4255c076559aSPavel Labath 
4256ed89c7feSPavel Labath     DoStopThreads(PendingNotificationUP(new PendingNotification(
4257337f3eb9SPavel Labath                 triggering_tid, wait_for_stop_tids, ThreadIDSet())));
4258c076559aSPavel Labath 
42595eb721edSPavel Labath     if (log)
4260c076559aSPavel Labath     {
42615eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
4262c076559aSPavel Labath     }
4263c076559aSPavel Labath }
4264c076559aSPavel Labath 
4265c076559aSPavel Labath void
4266337f3eb9SPavel Labath NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid)
4267c076559aSPavel Labath {
42685eb721edSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
4269c076559aSPavel Labath     std::lock_guard<std::mutex> lock(m_event_mutex);
4270c076559aSPavel Labath 
42715eb721edSPavel Labath     if (log)
4272c076559aSPavel Labath     {
42735eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ")",
4274c076559aSPavel Labath                 __FUNCTION__, triggering_tid);
4275c076559aSPavel Labath     }
4276c076559aSPavel Labath 
4277337f3eb9SPavel Labath     DoStopThreads(PendingNotificationUP(new PendingNotification(triggering_tid)));
4278c076559aSPavel Labath 
42795eb721edSPavel Labath     if (log)
4280c076559aSPavel Labath     {
42815eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
4282c076559aSPavel Labath     }
4283c076559aSPavel Labath }
4284c076559aSPavel Labath 
4285c076559aSPavel Labath void
4286ed89c7feSPavel Labath NativeProcessLinux::StopRunningThreadsWithSkipTID(lldb::tid_t triggering_tid,
4287337f3eb9SPavel Labath                                                   lldb::tid_t skip_stop_request_tid)
4288c076559aSPavel Labath {
42895eb721edSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
4290c076559aSPavel Labath     std::lock_guard<std::mutex> lock(m_event_mutex);
4291c076559aSPavel Labath 
42925eb721edSPavel Labath     if (log)
4293c076559aSPavel Labath     {
4294337f3eb9SPavel Labath         log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ", skip_stop_request_tid: %" PRIu64 ")",
4295337f3eb9SPavel Labath                 __FUNCTION__, triggering_tid, skip_stop_request_tid);
4296c076559aSPavel Labath     }
4297c076559aSPavel Labath 
4298ed89c7feSPavel Labath     DoStopThreads(PendingNotificationUP(new PendingNotification(
4299c076559aSPavel Labath                 triggering_tid,
4300337f3eb9SPavel Labath                 ThreadIDSet(),
4301337f3eb9SPavel Labath                 skip_stop_request_tid != LLDB_INVALID_THREAD_ID ? NativeProcessLinux::ThreadIDSet {skip_stop_request_tid} : ThreadIDSet ())));
4302c076559aSPavel Labath 
43035eb721edSPavel Labath     if (log)
4304c076559aSPavel Labath     {
43055eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
4306c076559aSPavel Labath     }
4307c076559aSPavel Labath }
4308c076559aSPavel Labath 
4309c076559aSPavel Labath void
4310c076559aSPavel Labath NativeProcessLinux::SignalIfRequirementsSatisfied()
4311c076559aSPavel Labath {
4312c076559aSPavel Labath     if (m_pending_notification_up && m_pending_notification_up->wait_for_stop_tids.empty ())
4313c076559aSPavel Labath     {
4314ed89c7feSPavel Labath         SetCurrentThreadID(m_pending_notification_up->triggering_tid);
4315ed89c7feSPavel Labath         SetState(StateType::eStateStopped, true);
4316c076559aSPavel Labath         m_pending_notification_up.reset();
4317c076559aSPavel Labath     }
4318c076559aSPavel Labath }
4319c076559aSPavel Labath 
4320c076559aSPavel Labath bool
4321c076559aSPavel Labath NativeProcessLinux::RequestStopOnAllSpecifiedThreads()
4322c076559aSPavel Labath {
4323c076559aSPavel Labath     // Request a stop for all the thread stops that need to be stopped
4324c076559aSPavel Labath     // and are not already known to be stopped.  Keep a list of all the
4325c076559aSPavel Labath     // threads from which we still need to hear a stop reply.
4326c076559aSPavel Labath 
4327c076559aSPavel Labath     ThreadIDSet sent_tids;
4328c076559aSPavel Labath     for (auto tid : m_pending_notification_up->wait_for_stop_tids)
4329c076559aSPavel Labath     {
4330c076559aSPavel Labath         // Validate we know about all tids for which we must first receive a stop before
4331c076559aSPavel Labath         // triggering the deferred stop notification.
43328c8ff7afSPavel Labath         auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
43338c8ff7afSPavel Labath         lldbassert(thread_sp != nullptr);
4334c076559aSPavel Labath 
4335c076559aSPavel Labath         // If the pending stop thread is currently running, we need to send it a stop request.
43368c8ff7afSPavel Labath         if (StateIsRunningState(thread_sp->GetState()))
4337c076559aSPavel Labath         {
43388c8ff7afSPavel Labath             thread_sp->RequestStop();
4339c076559aSPavel Labath             sent_tids.insert (tid);
4340c076559aSPavel Labath         }
4341c076559aSPavel Labath     }
4342c076559aSPavel Labath     // We only need to wait for the sent_tids - so swap our wait set
4343c076559aSPavel Labath     // to the sent tids.  The rest are already stopped and we won't
4344c076559aSPavel Labath     // be receiving stop notifications for them.
4345c076559aSPavel Labath     m_pending_notification_up->wait_for_stop_tids.swap (sent_tids);
4346c076559aSPavel Labath 
4347c076559aSPavel Labath     // Succeeded, keep running.
4348c076559aSPavel Labath     return true;
4349c076559aSPavel Labath }
4350c076559aSPavel Labath 
4351c076559aSPavel Labath void
4352c076559aSPavel Labath NativeProcessLinux::RequestStopOnAllRunningThreads()
4353c076559aSPavel Labath {
4354c076559aSPavel Labath     // Request a stop for all the thread stops that need to be stopped
4355c076559aSPavel Labath     // and are not already known to be stopped.  Keep a list of all the
4356c076559aSPavel Labath     // threads from which we still need to hear a stop reply.
4357c076559aSPavel Labath 
4358c076559aSPavel Labath     ThreadIDSet sent_tids;
43598c8ff7afSPavel Labath     for (const auto &thread_sp: m_threads)
4360c076559aSPavel Labath     {
43618c8ff7afSPavel Labath         // We only care about running threads
43628c8ff7afSPavel Labath         if (StateIsStoppedState(thread_sp->GetState(), true))
43638c8ff7afSPavel Labath             continue;
43648c8ff7afSPavel Labath 
43658c8ff7afSPavel Labath         const lldb::tid_t tid = thread_sp->GetID();
4366c076559aSPavel Labath 
4367c076559aSPavel Labath         // Request this thread stop if the tid stop request is not explicitly ignored.
4368c076559aSPavel Labath         const bool skip_stop_request = m_pending_notification_up->skip_stop_request_tids.count (tid) > 0;
4369c076559aSPavel Labath         if (!skip_stop_request)
43708c8ff7afSPavel Labath             static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
4371c076559aSPavel Labath 
4372c076559aSPavel Labath         // Even if we skipped sending the stop request for other reasons (like stepping),
4373c076559aSPavel Labath         // we still need to wait for that stepping thread to notify completion/stop.
4374c076559aSPavel Labath         sent_tids.insert (tid);
4375c076559aSPavel Labath     }
4376c076559aSPavel Labath 
4377c076559aSPavel Labath     // Set the wait list to the set of tids for which we requested stops.
4378c076559aSPavel Labath     m_pending_notification_up->wait_for_stop_tids.swap (sent_tids);
4379c076559aSPavel Labath }
4380c076559aSPavel Labath 
4381c076559aSPavel Labath 
43825eb721edSPavel Labath Error
43835eb721edSPavel Labath NativeProcessLinux::ThreadDidStop (lldb::tid_t tid, bool initiated_by_llgs)
4384c076559aSPavel Labath {
4385c076559aSPavel Labath     // Ensure we know about the thread.
43868c8ff7afSPavel Labath     auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
43878c8ff7afSPavel Labath     lldbassert(thread_sp != nullptr);
4388c076559aSPavel Labath 
4389c076559aSPavel Labath     // Update the global list of known thread states.  This one is definitely stopped.
43908c8ff7afSPavel Labath     auto& context = thread_sp->GetThreadContext();
43918c8ff7afSPavel Labath     const auto stop_was_requested = context.stop_requested;
43928c8ff7afSPavel Labath     context.stop_requested = false;
4393c076559aSPavel Labath 
4394c076559aSPavel Labath     // If we have a pending notification, remove this from the set.
4395c076559aSPavel Labath     if (m_pending_notification_up)
4396c076559aSPavel Labath     {
4397c076559aSPavel Labath         m_pending_notification_up->wait_for_stop_tids.erase(tid);
4398c076559aSPavel Labath         SignalIfRequirementsSatisfied();
4399c076559aSPavel Labath     }
4400c076559aSPavel Labath 
44018c8ff7afSPavel Labath     Error error;
44028c8ff7afSPavel Labath     if (initiated_by_llgs && context.request_resume_function && !stop_was_requested)
4403c076559aSPavel Labath     {
44045eb721edSPavel Labath         Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
4405c076559aSPavel Labath         // We can end up here if stop was initiated by LLGS but by this time a
4406c076559aSPavel Labath         // thread stop has occurred - maybe initiated by another event.
44075eb721edSPavel Labath         if (log)
44085eb721edSPavel Labath             log->Printf("Resuming thread %"  PRIu64 " since stop wasn't requested", tid);
44098c8ff7afSPavel Labath         error = context.request_resume_function (tid, true);
44108c8ff7afSPavel Labath         if (error.Fail() && log)
44115eb721edSPavel Labath         {
44125eb721edSPavel Labath                 log->Printf("NativeProcessLinux::%s failed to resume thread tid  %" PRIu64 ": %s",
4413c076559aSPavel Labath                         __FUNCTION__, tid, error.AsCString ());
4414c076559aSPavel Labath         }
44158c8ff7afSPavel Labath     }
44165eb721edSPavel Labath     return error;
4417c076559aSPavel Labath }
4418c076559aSPavel Labath 
4419c076559aSPavel Labath void
4420ed89c7feSPavel Labath NativeProcessLinux::DoStopThreads(PendingNotificationUP &&notification_up)
4421c076559aSPavel Labath {
44225eb721edSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
44235eb721edSPavel Labath     if (m_pending_notification_up && log)
4424c076559aSPavel Labath     {
4425c076559aSPavel Labath         // Yikes - we've already got a pending signal notification in progress.
4426c076559aSPavel Labath         // Log this info.  We lose the pending notification here.
44275eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s dropping existing pending signal notification for tid %" PRIu64 ", to be replaced with signal for tid %" PRIu64,
4428c076559aSPavel Labath                    __FUNCTION__,
4429c076559aSPavel Labath                    m_pending_notification_up->triggering_tid,
4430c076559aSPavel Labath                    notification_up->triggering_tid);
4431c076559aSPavel Labath     }
4432c076559aSPavel Labath     m_pending_notification_up = std::move(notification_up);
4433c076559aSPavel Labath 
4434c076559aSPavel Labath     if (m_pending_notification_up->request_stop_on_all_unstopped_threads)
4435c076559aSPavel Labath         RequestStopOnAllRunningThreads();
4436c076559aSPavel Labath     else
4437c076559aSPavel Labath     {
4438c076559aSPavel Labath         if (!RequestStopOnAllSpecifiedThreads())
4439c076559aSPavel Labath             return;
4440c076559aSPavel Labath     }
4441c076559aSPavel Labath 
4442ed89c7feSPavel Labath     SignalIfRequirementsSatisfied();
4443c076559aSPavel Labath }
4444c076559aSPavel Labath 
4445c076559aSPavel Labath void
44468c8ff7afSPavel Labath NativeProcessLinux::ThreadWasCreated (lldb::tid_t tid)
4447c076559aSPavel Labath {
44488c8ff7afSPavel Labath     auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
44498c8ff7afSPavel Labath     lldbassert(thread_sp != nullptr);
4450c076559aSPavel Labath 
44518c8ff7afSPavel Labath     if (m_pending_notification_up && StateIsRunningState(thread_sp->GetState()))
4452c076559aSPavel Labath     {
4453c076559aSPavel Labath         // We will need to wait for this new thread to stop as well before firing the
4454c076559aSPavel Labath         // notification.
4455c076559aSPavel Labath         m_pending_notification_up->wait_for_stop_tids.insert(tid);
44568c8ff7afSPavel Labath         thread_sp->RequestStop();
4457c076559aSPavel Labath     }
4458c076559aSPavel Labath }
4459c076559aSPavel Labath 
4460c076559aSPavel Labath void
44615eb721edSPavel Labath NativeProcessLinux::ThreadDidDie (lldb::tid_t tid)
4462c076559aSPavel Labath {
4463c076559aSPavel Labath     // If we have a pending notification, remove this from the set.
4464c076559aSPavel Labath     if (m_pending_notification_up)
4465c076559aSPavel Labath     {
4466c076559aSPavel Labath         m_pending_notification_up->wait_for_stop_tids.erase(tid);
4467c076559aSPavel Labath         SignalIfRequirementsSatisfied();
4468c076559aSPavel Labath     }
4469c076559aSPavel Labath }
4470c076559aSPavel Labath 
44715eb721edSPavel Labath Error
44725eb721edSPavel Labath NativeProcessLinux::NotifyThreadStop (lldb::tid_t tid, bool initiated_by_llgs)
4473c076559aSPavel Labath {
44745eb721edSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
4475c076559aSPavel Labath     std::lock_guard<std::mutex> lock(m_event_mutex);
4476c076559aSPavel Labath 
44775eb721edSPavel Labath     if (log)
4478c076559aSPavel Labath     {
44795eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ", %sinitiated by llgs)",
4480c076559aSPavel Labath                 __FUNCTION__, tid, initiated_by_llgs?"":"not ");
4481c076559aSPavel Labath     }
4482c076559aSPavel Labath 
44835eb721edSPavel Labath     Error error = ThreadDidStop (tid, initiated_by_llgs);
4484c076559aSPavel Labath 
44855eb721edSPavel Labath     if (log)
4486c076559aSPavel Labath     {
44875eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
4488c076559aSPavel Labath     }
4489c076559aSPavel Labath 
44905eb721edSPavel Labath     return error;
44915eb721edSPavel Labath }
44925eb721edSPavel Labath 
44935eb721edSPavel Labath Error
4494c076559aSPavel Labath NativeProcessLinux::RequestThreadResume (lldb::tid_t tid,
44958c8ff7afSPavel Labath                                          const NativeThreadLinux::ResumeThreadFunction &request_thread_resume_function)
4496c076559aSPavel Labath {
44975eb721edSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
4498c076559aSPavel Labath     std::lock_guard<std::mutex> lock(m_event_mutex);
4499c076559aSPavel Labath 
45005eb721edSPavel Labath     if (log)
4501c076559aSPavel Labath     {
45025eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ")",
4503c076559aSPavel Labath                 __FUNCTION__, tid);
4504c076559aSPavel Labath     }
4505c076559aSPavel Labath 
45065eb721edSPavel Labath     Error error = DoResume(tid, request_thread_resume_function, true);
4507c076559aSPavel Labath 
45085eb721edSPavel Labath     if (log)
4509c076559aSPavel Labath     {
45105eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
4511c076559aSPavel Labath     }
4512c076559aSPavel Labath 
45135eb721edSPavel Labath     return error;
45145eb721edSPavel Labath }
45155eb721edSPavel Labath 
45165eb721edSPavel Labath Error
4517c076559aSPavel Labath NativeProcessLinux::RequestThreadResumeAsNeeded (lldb::tid_t tid,
45188c8ff7afSPavel Labath         const NativeThreadLinux::ResumeThreadFunction &request_thread_resume_function)
4519c076559aSPavel Labath {
45205eb721edSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
4521c076559aSPavel Labath     std::lock_guard<std::mutex> lock(m_event_mutex);
4522c076559aSPavel Labath 
45235eb721edSPavel Labath     if (log)
4524c076559aSPavel Labath     {
45255eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ")",
4526c076559aSPavel Labath                 __FUNCTION__, tid);
4527c076559aSPavel Labath     }
4528c076559aSPavel Labath 
45295eb721edSPavel Labath     Error error = DoResume (tid, request_thread_resume_function, false);
4530c076559aSPavel Labath 
45315eb721edSPavel Labath     if (log)
4532c076559aSPavel Labath     {
45335eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
4534c076559aSPavel Labath     }
45355eb721edSPavel Labath 
45365eb721edSPavel Labath     return error;
4537c076559aSPavel Labath }
4538c076559aSPavel Labath 
4539c076559aSPavel Labath void
45408c8ff7afSPavel Labath NativeProcessLinux::NotifyThreadCreate(lldb::tid_t tid)
4541c076559aSPavel Labath {
45425eb721edSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
4543c076559aSPavel Labath     std::lock_guard<std::mutex> lock(m_event_mutex);
4544c076559aSPavel Labath 
45455eb721edSPavel Labath     if (log)
45468c8ff7afSPavel Labath         log->Printf("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ")", __FUNCTION__, tid);
4547c076559aSPavel Labath 
45488c8ff7afSPavel Labath     ThreadWasCreated(tid);
4549c076559aSPavel Labath 
45505eb721edSPavel Labath     if (log)
4551c076559aSPavel Labath     {
45525eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
4553c076559aSPavel Labath     }
4554c076559aSPavel Labath }
4555c076559aSPavel Labath 
4556c076559aSPavel Labath void
45575eb721edSPavel Labath NativeProcessLinux::NotifyThreadDeath (lldb::tid_t tid)
4558c076559aSPavel Labath {
45595eb721edSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
4560c076559aSPavel Labath     std::lock_guard<std::mutex> lock(m_event_mutex);
4561c076559aSPavel Labath 
45625eb721edSPavel Labath     if (log)
4563c076559aSPavel Labath     {
45645eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ")", __FUNCTION__, tid);
4565c076559aSPavel Labath     }
4566c076559aSPavel Labath 
45675eb721edSPavel Labath     ThreadDidDie(tid);
4568c076559aSPavel Labath 
45695eb721edSPavel Labath     if (log)
4570c076559aSPavel Labath     {
45715eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
4572c076559aSPavel Labath     }
4573c076559aSPavel Labath }
4574c076559aSPavel Labath 
4575c076559aSPavel Labath void
4576c076559aSPavel Labath NativeProcessLinux::ResetForExec ()
4577c076559aSPavel Labath {
45785eb721edSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
4579c076559aSPavel Labath     std::lock_guard<std::mutex> lock(m_event_mutex);
4580c076559aSPavel Labath 
45815eb721edSPavel Labath     if (log)
4582c076559aSPavel Labath     {
45835eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s about to process event", __FUNCTION__);
4584c076559aSPavel Labath     }
4585c076559aSPavel Labath 
4586c076559aSPavel Labath     // Clear the pending notification if there was one.
4587c076559aSPavel Labath     m_pending_notification_up.reset ();
4588c076559aSPavel Labath 
45895eb721edSPavel Labath     if (log)
4590c076559aSPavel Labath     {
45915eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
4592c076559aSPavel Labath     }
4593c076559aSPavel Labath }
4594