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>
588b335671SVince 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 
698b335671SVince Harron #include "lldb/Host/linux/Personality.h"
708b335671SVince Harron #include "lldb/Host/linux/Ptrace.h"
718b335671SVince Harron #include "lldb/Host/linux/Signalfd.h"
728b335671SVince 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);
19311dbc6c9cSPavel Labath     ThreadWasCreated(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);
20271dbc6c9cSPavel Labath                 ThreadWasCreated(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 
2126af245d11STodd Fiala         if (is_main_thread)
2127af245d11STodd Fiala         {
2128af245d11STodd Fiala             // We only set the exit status and notify the delegate if we haven't already set the process
2129af245d11STodd Fiala             // state to an exited state.  We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
2130af245d11STodd Fiala             // for the main thread.
21311107b5a5SPavel Labath             const bool already_notified = (GetState() == StateType::eStateExited) || (GetState () == StateType::eStateCrashed);
2132af245d11STodd Fiala             if (!already_notified)
2133af245d11STodd Fiala             {
2134af245d11STodd Fiala                 if (log)
21351107b5a5SPavel 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 ()));
2136af245d11STodd Fiala                 // The main thread exited.  We're done monitoring.  Report to delegate.
21371107b5a5SPavel Labath                 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
2138af245d11STodd Fiala 
2139af245d11STodd Fiala                 // Notify delegate that our process has exited.
21401107b5a5SPavel Labath                 SetState (StateType::eStateExited, true);
2141af245d11STodd Fiala             }
2142af245d11STodd Fiala             else
2143af245d11STodd Fiala             {
2144af245d11STodd Fiala                 if (log)
2145af245d11STodd Fiala                     log->Printf ("NativeProcessLinux::%s() tid = %"  PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
2146af245d11STodd Fiala             }
2147af245d11STodd Fiala         }
2148af245d11STodd Fiala         else
2149af245d11STodd Fiala         {
2150af245d11STodd Fiala             // Do we want to report to the delegate in this case?  I think not.  If this was an orderly
2151af245d11STodd Fiala             // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
2152af245d11STodd Fiala             // and we would have done an all-stop then.
2153af245d11STodd Fiala             if (log)
2154af245d11STodd 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");
2155af245d11STodd Fiala         }
21561107b5a5SPavel Labath         return;
2157af245d11STodd Fiala     }
2158af245d11STodd Fiala 
2159af245d11STodd Fiala     // Get details on the signal raised.
2160af245d11STodd Fiala     siginfo_t info;
21611107b5a5SPavel Labath     const auto err = GetSignalInfo(pid, &info);
216297ccc294SChaoren Lin     if (err.Success())
2163fa03ad2eSChaoren Lin     {
2164fa03ad2eSChaoren Lin         // We have retrieved the signal info.  Dispatch appropriately.
2165fa03ad2eSChaoren Lin         if (info.si_signo == SIGTRAP)
21661107b5a5SPavel Labath             MonitorSIGTRAP(&info, pid);
2167fa03ad2eSChaoren Lin         else
21681107b5a5SPavel Labath             MonitorSignal(&info, pid, exited);
2169fa03ad2eSChaoren Lin     }
2170fa03ad2eSChaoren Lin     else
2171af245d11STodd Fiala     {
217297ccc294SChaoren Lin         if (err.GetError() == EINVAL)
2173af245d11STodd Fiala         {
2174fa03ad2eSChaoren Lin             // This is a group stop reception for this tid.
2175fa03ad2eSChaoren Lin             if (log)
21761dbc6c9cSPavel Labath                 log->Printf ("NativeProcessLinux::%s received a group stop for pid %" PRIu64 " tid %" PRIu64, __FUNCTION__, GetID (), pid);
21771dbc6c9cSPavel Labath             ThreadDidStop(pid, false);
2178a9882ceeSTodd Fiala         }
2179a9882ceeSTodd Fiala         else
2180a9882ceeSTodd Fiala         {
2181af245d11STodd Fiala             // ptrace(GETSIGINFO) failed (but not due to group-stop).
2182af245d11STodd Fiala 
2183af245d11STodd Fiala             // A return value of ESRCH means the thread/process is no longer on the system,
2184af245d11STodd Fiala             // so it was killed somehow outside of our control.  Either way, we can't do anything
2185af245d11STodd Fiala             // with it anymore.
2186af245d11STodd Fiala 
2187af245d11STodd Fiala             // Stop tracking the metadata for the thread since it's entirely off the system now.
21881107b5a5SPavel Labath             const bool thread_found = StopTrackingThread (pid);
2189af245d11STodd Fiala 
2190af245d11STodd Fiala             if (log)
2191af245d11STodd Fiala                 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
219297ccc294SChaoren 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");
2193af245d11STodd Fiala 
2194af245d11STodd Fiala             if (is_main_thread)
2195af245d11STodd Fiala             {
2196af245d11STodd Fiala                 // Notify the delegate - our process is not available but appears to have been killed outside
2197af245d11STodd Fiala                 // our control.  Is eStateExited the right exit state in this case?
21981107b5a5SPavel Labath                 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
21991107b5a5SPavel Labath                 SetState (StateType::eStateExited, true);
2200af245d11STodd Fiala             }
2201af245d11STodd Fiala             else
2202af245d11STodd Fiala             {
2203af245d11STodd Fiala                 // This thread was pulled out from underneath us.  Anything to do here? Do we want to do an all stop?
2204af245d11STodd Fiala                 if (log)
22051107b5a5SPavel 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);
2206af245d11STodd Fiala             }
2207af245d11STodd Fiala         }
2208af245d11STodd Fiala     }
2209af245d11STodd Fiala }
2210af245d11STodd Fiala 
2211af245d11STodd Fiala void
2212426bdf88SPavel Labath NativeProcessLinux::WaitForNewThread(::pid_t tid)
2213426bdf88SPavel Labath {
2214426bdf88SPavel Labath     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2215426bdf88SPavel Labath 
2216426bdf88SPavel Labath     NativeThreadProtocolSP new_thread_sp = GetThreadByID(tid);
2217426bdf88SPavel Labath 
2218426bdf88SPavel Labath     if (new_thread_sp)
2219426bdf88SPavel Labath     {
2220426bdf88SPavel Labath         // We are already tracking the thread - we got the event on the new thread (see
2221426bdf88SPavel Labath         // MonitorSignal) before this one. We are done.
2222426bdf88SPavel Labath         return;
2223426bdf88SPavel Labath     }
2224426bdf88SPavel Labath 
2225426bdf88SPavel Labath     // The thread is not tracked yet, let's wait for it to appear.
2226426bdf88SPavel Labath     int status = -1;
2227426bdf88SPavel Labath     ::pid_t wait_pid;
2228426bdf88SPavel Labath     do
2229426bdf88SPavel Labath     {
2230426bdf88SPavel Labath         if (log)
2231426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() received thread creation event for tid %" PRIu32 ". tid not tracked yet, waiting for thread to appear...", __FUNCTION__, tid);
2232426bdf88SPavel Labath         wait_pid = waitpid(tid, &status, __WALL);
2233426bdf88SPavel Labath     }
2234426bdf88SPavel Labath     while (wait_pid == -1 && errno == EINTR);
2235426bdf88SPavel Labath     // Since we are waiting on a specific tid, this must be the creation event. But let's do
2236426bdf88SPavel Labath     // some checks just in case.
2237426bdf88SPavel Labath     if (wait_pid != tid) {
2238426bdf88SPavel Labath         if (log)
2239426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime", __FUNCTION__, tid);
2240426bdf88SPavel Labath         // The only way I know of this could happen is if the whole process was
2241426bdf88SPavel Labath         // SIGKILLed in the mean time. In any case, we can't do anything about that now.
2242426bdf88SPavel Labath         return;
2243426bdf88SPavel Labath     }
2244426bdf88SPavel Labath     if (WIFEXITED(status))
2245426bdf88SPavel Labath     {
2246426bdf88SPavel Labath         if (log)
2247426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " returned an 'exited' event. Not tracking the thread.", __FUNCTION__, tid);
2248426bdf88SPavel Labath         // Also a very improbable event.
2249426bdf88SPavel Labath         return;
2250426bdf88SPavel Labath     }
2251426bdf88SPavel Labath 
2252426bdf88SPavel Labath     siginfo_t info;
2253426bdf88SPavel Labath     Error error = GetSignalInfo(tid, &info);
2254426bdf88SPavel Labath     if (error.Fail())
2255426bdf88SPavel Labath     {
2256426bdf88SPavel Labath         if (log)
2257426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime.", __FUNCTION__, tid);
2258426bdf88SPavel Labath         return;
2259426bdf88SPavel Labath     }
2260426bdf88SPavel Labath 
2261426bdf88SPavel Labath     if (((info.si_pid != 0) || (info.si_code != SI_USER)) && log)
2262426bdf88SPavel Labath     {
2263426bdf88SPavel Labath         // We should be getting a thread creation signal here, but we received something
2264426bdf88SPavel Labath         // else. There isn't much we can do about it now, so we will just log that. Since the
2265426bdf88SPavel Labath         // thread is alive and we are receiving events from it, we shall pretend that it was
2266426bdf88SPavel Labath         // created properly.
2267426bdf88SPavel 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);
2268426bdf88SPavel Labath     }
2269426bdf88SPavel Labath 
2270426bdf88SPavel Labath     if (log)
2271426bdf88SPavel Labath         log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 ": tracking new thread tid %" PRIu32,
2272426bdf88SPavel Labath                  __FUNCTION__, GetID (), tid);
2273426bdf88SPavel Labath 
2274426bdf88SPavel Labath     new_thread_sp = AddThread(tid);
2275426bdf88SPavel Labath     std::static_pointer_cast<NativeThreadLinux> (new_thread_sp)->SetRunning ();
2276426bdf88SPavel Labath     Resume (tid, LLDB_INVALID_SIGNAL_NUMBER);
22771dbc6c9cSPavel Labath     ThreadWasCreated(tid);
2278426bdf88SPavel Labath }
2279426bdf88SPavel Labath 
2280426bdf88SPavel Labath void
2281af245d11STodd Fiala NativeProcessLinux::MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid)
2282af245d11STodd Fiala {
2283af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2284af245d11STodd Fiala     const bool is_main_thread = (pid == GetID ());
2285af245d11STodd Fiala 
2286af245d11STodd Fiala     assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
2287af245d11STodd Fiala     if (!info)
2288af245d11STodd Fiala         return;
2289af245d11STodd Fiala 
22905830aa75STamas Berghammer     Mutex::Locker locker (m_threads_mutex);
22915830aa75STamas Berghammer 
2292af245d11STodd Fiala     // See if we can find a thread for this signal.
2293af245d11STodd Fiala     NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2294af245d11STodd Fiala     if (!thread_sp)
2295af245d11STodd Fiala     {
2296af245d11STodd Fiala         if (log)
2297af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2298af245d11STodd Fiala     }
2299af245d11STodd Fiala 
2300af245d11STodd Fiala     switch (info->si_code)
2301af245d11STodd Fiala     {
2302af245d11STodd 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.
2303af245d11STodd Fiala     // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
2304af245d11STodd Fiala     // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
2305af245d11STodd Fiala 
2306af245d11STodd Fiala     case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
2307af245d11STodd Fiala     {
23085fd24c67SPavel Labath         // This is the notification on the parent thread which informs us of new thread
2309426bdf88SPavel Labath         // creation.
2310426bdf88SPavel Labath         // We don't want to do anything with the parent thread so we just resume it. In case we
2311426bdf88SPavel Labath         // want to implement "break on thread creation" functionality, we would need to stop
2312426bdf88SPavel Labath         // here.
2313af245d11STodd Fiala 
2314af245d11STodd Fiala         unsigned long event_message = 0;
2315426bdf88SPavel Labath         if (GetEventMessage (pid, &event_message).Fail())
2316fa03ad2eSChaoren Lin         {
2317426bdf88SPavel Labath             if (log)
2318fa03ad2eSChaoren Lin                 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " received thread creation event but GetEventMessage failed so we don't know the new tid", __FUNCTION__, pid);
2319426bdf88SPavel Labath         } else
2320426bdf88SPavel Labath             WaitForNewThread(event_message);
2321af245d11STodd Fiala 
23225fd24c67SPavel Labath         Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
2323af245d11STodd Fiala         break;
2324af245d11STodd Fiala     }
2325af245d11STodd Fiala 
2326af245d11STodd Fiala     case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
2327a9882ceeSTodd Fiala     {
2328a9882ceeSTodd Fiala         NativeThreadProtocolSP main_thread_sp;
2329af245d11STodd Fiala         if (log)
2330af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
2331a9882ceeSTodd Fiala 
23321dbc6c9cSPavel Labath         // Exec clears any pending notifications.
23331dbc6c9cSPavel Labath         m_pending_notification_up.reset ();
2334fa03ad2eSChaoren Lin 
2335fa03ad2eSChaoren 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.
2336a9882ceeSTodd Fiala         if (log)
2337a9882ceeSTodd Fiala             log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
2338a9882ceeSTodd Fiala 
2339a9882ceeSTodd Fiala         for (auto thread_sp : m_threads)
2340a9882ceeSTodd Fiala         {
2341a9882ceeSTodd Fiala             const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
2342a9882ceeSTodd Fiala             if (is_main_thread)
2343a9882ceeSTodd Fiala             {
2344a9882ceeSTodd Fiala                 main_thread_sp = thread_sp;
2345a9882ceeSTodd Fiala                 if (log)
2346a9882ceeSTodd Fiala                     log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
2347a9882ceeSTodd Fiala             }
2348a9882ceeSTodd Fiala             else
2349a9882ceeSTodd Fiala             {
2350fa03ad2eSChaoren Lin                 // Tell thread coordinator this thread is dead.
2351a9882ceeSTodd Fiala                 if (log)
2352a9882ceeSTodd Fiala                     log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
2353a9882ceeSTodd Fiala             }
2354a9882ceeSTodd Fiala         }
2355a9882ceeSTodd Fiala 
2356a9882ceeSTodd Fiala         m_threads.clear ();
2357a9882ceeSTodd Fiala 
2358a9882ceeSTodd Fiala         if (main_thread_sp)
2359a9882ceeSTodd Fiala         {
2360a9882ceeSTodd Fiala             m_threads.push_back (main_thread_sp);
2361a9882ceeSTodd Fiala             SetCurrentThreadID (main_thread_sp->GetID ());
2362cb84eebbSTamas Berghammer             std::static_pointer_cast<NativeThreadLinux> (main_thread_sp)->SetStoppedByExec ();
2363a9882ceeSTodd Fiala         }
2364a9882ceeSTodd Fiala         else
2365a9882ceeSTodd Fiala         {
2366a9882ceeSTodd Fiala             SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
2367a9882ceeSTodd Fiala             if (log)
2368a9882ceeSTodd Fiala                 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
2369a9882ceeSTodd Fiala         }
2370a9882ceeSTodd Fiala 
2371fa03ad2eSChaoren Lin         // Tell coordinator about about the "new" (since exec) stopped main thread.
2372fa03ad2eSChaoren Lin         const lldb::tid_t main_thread_tid = GetID ();
23731dbc6c9cSPavel Labath         ThreadWasCreated(main_thread_tid);
2374fa03ad2eSChaoren Lin 
2375fa03ad2eSChaoren Lin         // NOTE: ideally these next statements would execute at the same time as the coordinator thread create was executed.
2376fa03ad2eSChaoren Lin         // Consider a handler that can execute when that happens.
2377a9882ceeSTodd Fiala         // Let our delegate know we have just exec'd.
2378a9882ceeSTodd Fiala         NotifyDidExec ();
2379a9882ceeSTodd Fiala 
2380a9882ceeSTodd Fiala         // If we have a main thread, indicate we are stopped.
2381a9882ceeSTodd Fiala         assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
2382fa03ad2eSChaoren Lin 
2383fa03ad2eSChaoren Lin         // Let the process know we're stopped.
2384ed89c7feSPavel Labath         StopRunningThreads (pid);
2385a9882ceeSTodd Fiala 
2386af245d11STodd Fiala         break;
2387a9882ceeSTodd Fiala     }
2388af245d11STodd Fiala 
2389af245d11STodd Fiala     case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
2390af245d11STodd Fiala     {
2391af245d11STodd Fiala         // The inferior process or one of its threads is about to exit.
23928c8ff7afSPavel Labath         if (! thread_sp)
23938c8ff7afSPavel Labath             break;
2394fa03ad2eSChaoren Lin 
2395fa03ad2eSChaoren Lin         // This thread is currently stopped.  It's not actually dead yet, just about to be.
23961dbc6c9cSPavel Labath         ThreadDidStop (pid, false);
23978c8ff7afSPavel Labath         // The actual stop reason does not matter much, as we are going to resume the thread a
23988c8ff7afSPavel Labath         // few lines down. If we ever want to report this state to the debugger, then we should
23998c8ff7afSPavel Labath         // invent a new stop reason.
24008c8ff7afSPavel Labath         std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedBySignal(LLDB_INVALID_SIGNAL_NUMBER);
2401fa03ad2eSChaoren Lin 
2402af245d11STodd Fiala         unsigned long data = 0;
240397ccc294SChaoren Lin         if (GetEventMessage(pid, &data).Fail())
2404af245d11STodd Fiala             data = -1;
2405af245d11STodd Fiala 
2406af245d11STodd Fiala         if (log)
2407af245d11STodd Fiala         {
2408af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
2409af245d11STodd Fiala                          __FUNCTION__,
2410af245d11STodd Fiala                          data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
2411af245d11STodd Fiala                          pid,
2412af245d11STodd Fiala                     is_main_thread ? "is main thread" : "not main thread");
2413af245d11STodd Fiala         }
2414af245d11STodd Fiala 
2415af245d11STodd Fiala         if (is_main_thread)
2416af245d11STodd Fiala         {
2417af245d11STodd Fiala             SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
241875f47c3aSTodd Fiala         }
241975f47c3aSTodd Fiala 
24209d617ba6SChaoren Lin         const int signo = static_cast<int> (data);
24211dbc6c9cSPavel Labath         ResumeThread(pid,
242286fd8e45SChaoren Lin                 [=](lldb::tid_t tid_to_resume, bool supress_signal)
2423fa03ad2eSChaoren Lin                 {
2424cb84eebbSTamas Berghammer                     std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
242537c768caSChaoren Lin                     return Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo);
24261dbc6c9cSPavel Labath                 },
24271dbc6c9cSPavel Labath                 true);
2428af245d11STodd Fiala 
2429af245d11STodd Fiala         break;
2430af245d11STodd Fiala     }
2431af245d11STodd Fiala 
2432af245d11STodd Fiala     case 0:
2433c16f5dcaSChaoren Lin     case TRAP_TRACE:  // We receive this on single stepping.
2434c16f5dcaSChaoren Lin     case TRAP_HWBKPT: // We receive this on watchpoint hit
243586fd8e45SChaoren Lin         if (thread_sp)
243686fd8e45SChaoren Lin         {
2437c16f5dcaSChaoren Lin             // If a watchpoint was hit, report it
2438c16f5dcaSChaoren Lin             uint32_t wp_index;
2439c16f5dcaSChaoren Lin             Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index);
2440c16f5dcaSChaoren Lin             if (error.Fail() && log)
2441c16f5dcaSChaoren Lin                 log->Printf("NativeProcessLinux::%s() "
2442c16f5dcaSChaoren Lin                             "received error while checking for watchpoint hits, "
2443c16f5dcaSChaoren Lin                             "pid = %" PRIu64 " error = %s",
2444c16f5dcaSChaoren Lin                             __FUNCTION__, pid, error.AsCString());
2445c16f5dcaSChaoren Lin             if (wp_index != LLDB_INVALID_INDEX32)
24465830aa75STamas Berghammer             {
2447c16f5dcaSChaoren Lin                 MonitorWatchpoint(pid, thread_sp, wp_index);
2448c16f5dcaSChaoren Lin                 break;
2449c16f5dcaSChaoren Lin             }
2450c16f5dcaSChaoren Lin         }
2451c16f5dcaSChaoren Lin         // Otherwise, report step over
2452c16f5dcaSChaoren Lin         MonitorTrace(pid, thread_sp);
2453af245d11STodd Fiala         break;
2454af245d11STodd Fiala 
2455af245d11STodd Fiala     case SI_KERNEL:
2456af245d11STodd Fiala     case TRAP_BRKPT:
2457c16f5dcaSChaoren Lin         MonitorBreakpoint(pid, thread_sp);
2458af245d11STodd Fiala         break;
2459af245d11STodd Fiala 
2460af245d11STodd Fiala     case SIGTRAP:
2461af245d11STodd Fiala     case (SIGTRAP | 0x80):
2462af245d11STodd Fiala         if (log)
2463fa03ad2eSChaoren Lin             log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), pid);
2464fa03ad2eSChaoren Lin 
2465fa03ad2eSChaoren Lin         // This thread is currently stopped.
24661dbc6c9cSPavel Labath         ThreadDidStop (pid, false);
2467fa03ad2eSChaoren Lin         if (thread_sp)
2468cb84eebbSTamas Berghammer             std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGTRAP);
2469fa03ad2eSChaoren Lin 
2470fa03ad2eSChaoren Lin 
2471af245d11STodd Fiala         // Ignore these signals until we know more about them.
24721dbc6c9cSPavel Labath         ResumeThread(pid,
247386fd8e45SChaoren Lin                 [=](lldb::tid_t tid_to_resume, bool supress_signal)
2474fa03ad2eSChaoren Lin                 {
2475cb84eebbSTamas Berghammer                     std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
247637c768caSChaoren Lin                     return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
24771dbc6c9cSPavel Labath                 },
24781dbc6c9cSPavel Labath                 true);
2479af245d11STodd Fiala         break;
2480af245d11STodd Fiala 
2481af245d11STodd Fiala     default:
2482af245d11STodd Fiala         assert(false && "Unexpected SIGTRAP code!");
2483af245d11STodd Fiala         if (log)
2484af245d11STodd 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)));
2485af245d11STodd Fiala         break;
2486af245d11STodd Fiala 
2487af245d11STodd Fiala     }
2488af245d11STodd Fiala }
2489af245d11STodd Fiala 
2490af245d11STodd Fiala void
2491c16f5dcaSChaoren Lin NativeProcessLinux::MonitorTrace(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
2492c16f5dcaSChaoren Lin {
2493c16f5dcaSChaoren Lin     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2494c16f5dcaSChaoren Lin     if (log)
2495c16f5dcaSChaoren Lin         log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)",
2496c16f5dcaSChaoren Lin                 __FUNCTION__, pid);
2497c16f5dcaSChaoren Lin 
2498c16f5dcaSChaoren Lin     if (thread_sp)
2499c16f5dcaSChaoren Lin         std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
2500c16f5dcaSChaoren Lin 
2501c16f5dcaSChaoren Lin     // This thread is currently stopped.
25021dbc6c9cSPavel Labath     ThreadDidStop(pid, false);
2503c16f5dcaSChaoren Lin 
2504c16f5dcaSChaoren Lin     // Here we don't have to request the rest of the threads to stop or request a deferred stop.
2505c16f5dcaSChaoren Lin     // This would have already happened at the time the Resume() with step operation was signaled.
2506c16f5dcaSChaoren Lin     // At this point, we just need to say we stopped, and the deferred notifcation will fire off
2507c16f5dcaSChaoren Lin     // once all running threads have checked in as stopped.
2508c16f5dcaSChaoren Lin     SetCurrentThreadID(pid);
2509c16f5dcaSChaoren Lin     // Tell the process we have a stop (from software breakpoint).
2510ed89c7feSPavel Labath     StopRunningThreads(pid);
2511c16f5dcaSChaoren Lin }
2512c16f5dcaSChaoren Lin 
2513c16f5dcaSChaoren Lin void
2514c16f5dcaSChaoren Lin NativeProcessLinux::MonitorBreakpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
2515c16f5dcaSChaoren Lin {
2516c16f5dcaSChaoren Lin     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
2517c16f5dcaSChaoren Lin     if (log)
2518c16f5dcaSChaoren Lin         log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
2519c16f5dcaSChaoren Lin                 __FUNCTION__, pid);
2520c16f5dcaSChaoren Lin 
2521c16f5dcaSChaoren Lin     // This thread is currently stopped.
25221dbc6c9cSPavel Labath     ThreadDidStop(pid, false);
2523c16f5dcaSChaoren Lin 
2524c16f5dcaSChaoren Lin     // Mark the thread as stopped at breakpoint.
2525c16f5dcaSChaoren Lin     if (thread_sp)
2526c16f5dcaSChaoren Lin     {
2527c16f5dcaSChaoren Lin         std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByBreakpoint();
2528c16f5dcaSChaoren Lin         Error error = FixupBreakpointPCAsNeeded(thread_sp);
2529c16f5dcaSChaoren Lin         if (error.Fail())
2530c16f5dcaSChaoren Lin             if (log)
2531c16f5dcaSChaoren Lin                 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
2532c16f5dcaSChaoren Lin                         __FUNCTION__, pid, error.AsCString());
2533d8c338d4STamas Berghammer 
2534d8c338d4STamas Berghammer         auto it = m_threads_stepping_with_breakpoint.find(pid);
2535d8c338d4STamas Berghammer         if (it != m_threads_stepping_with_breakpoint.end())
2536d8c338d4STamas Berghammer         {
2537d8c338d4STamas Berghammer             Error error = RemoveBreakpoint (it->second);
2538d8c338d4STamas Berghammer             if (error.Fail())
2539d8c338d4STamas Berghammer                 if (log)
2540d8c338d4STamas Berghammer                     log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " remove stepping breakpoint: %s",
2541d8c338d4STamas Berghammer                             __FUNCTION__, pid, error.AsCString());
2542d8c338d4STamas Berghammer 
2543d8c338d4STamas Berghammer             m_threads_stepping_with_breakpoint.erase(it);
2544d8c338d4STamas Berghammer             std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
2545d8c338d4STamas Berghammer         }
2546c16f5dcaSChaoren Lin     }
2547c16f5dcaSChaoren Lin     else
2548c16f5dcaSChaoren Lin         if (log)
2549c16f5dcaSChaoren Lin             log->Printf("NativeProcessLinux::%s()  pid = %" PRIu64 ": "
2550c16f5dcaSChaoren Lin                     "warning, cannot process software breakpoint since no thread metadata",
2551c16f5dcaSChaoren Lin                     __FUNCTION__, pid);
2552c16f5dcaSChaoren Lin 
2553c16f5dcaSChaoren Lin 
2554c16f5dcaSChaoren Lin     // We need to tell all other running threads before we notify the delegate about this stop.
2555ed89c7feSPavel Labath     StopRunningThreads(pid);
2556c16f5dcaSChaoren Lin }
2557c16f5dcaSChaoren Lin 
2558c16f5dcaSChaoren Lin void
2559c16f5dcaSChaoren Lin NativeProcessLinux::MonitorWatchpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp, uint32_t wp_index)
2560c16f5dcaSChaoren Lin {
2561c16f5dcaSChaoren Lin     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
2562c16f5dcaSChaoren Lin     if (log)
2563c16f5dcaSChaoren Lin         log->Printf("NativeProcessLinux::%s() received watchpoint event, "
2564c16f5dcaSChaoren Lin                     "pid = %" PRIu64 ", wp_index = %" PRIu32,
2565c16f5dcaSChaoren Lin                     __FUNCTION__, pid, wp_index);
2566c16f5dcaSChaoren Lin 
2567c16f5dcaSChaoren Lin     // This thread is currently stopped.
25681dbc6c9cSPavel Labath     ThreadDidStop(pid, false);
2569c16f5dcaSChaoren Lin 
2570c16f5dcaSChaoren Lin     // Mark the thread as stopped at watchpoint.
2571c16f5dcaSChaoren Lin     // The address is at (lldb::addr_t)info->si_addr if we need it.
2572c16f5dcaSChaoren Lin     lldbassert(thread_sp && "thread_sp cannot be NULL");
2573c16f5dcaSChaoren Lin     std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByWatchpoint(wp_index);
2574c16f5dcaSChaoren Lin 
2575c16f5dcaSChaoren Lin     // We need to tell all other running threads before we notify the delegate about this stop.
2576ed89c7feSPavel Labath     StopRunningThreads(pid);
2577c16f5dcaSChaoren Lin }
2578c16f5dcaSChaoren Lin 
2579c16f5dcaSChaoren Lin void
2580af245d11STodd Fiala NativeProcessLinux::MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited)
2581af245d11STodd Fiala {
2582511e5cdcSTodd Fiala     assert (info && "null info");
2583511e5cdcSTodd Fiala     if (!info)
2584511e5cdcSTodd Fiala         return;
2585511e5cdcSTodd Fiala 
2586511e5cdcSTodd Fiala     const int signo = info->si_signo;
2587511e5cdcSTodd Fiala     const bool is_from_llgs = info->si_pid == getpid ();
2588af245d11STodd Fiala 
2589af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2590af245d11STodd Fiala 
2591af245d11STodd Fiala     // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
2592af245d11STodd Fiala     // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
2593af245d11STodd Fiala     // kill(2) or raise(3).  Similarly for tgkill(2) on Linux.
2594af245d11STodd Fiala     //
2595af245d11STodd Fiala     // IOW, user generated signals never generate what we consider to be a
2596af245d11STodd Fiala     // "crash".
2597af245d11STodd Fiala     //
2598af245d11STodd Fiala     // Similarly, ACK signals generated by this monitor.
2599af245d11STodd Fiala 
26005830aa75STamas Berghammer     Mutex::Locker locker (m_threads_mutex);
26015830aa75STamas Berghammer 
2602af245d11STodd Fiala     // See if we can find a thread for this signal.
2603af245d11STodd Fiala     NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2604af245d11STodd Fiala     if (!thread_sp)
2605af245d11STodd Fiala     {
2606af245d11STodd Fiala         if (log)
2607af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2608af245d11STodd Fiala     }
2609af245d11STodd Fiala 
2610af245d11STodd Fiala     // Handle the signal.
2611af245d11STodd Fiala     if (info->si_code == SI_TKILL || info->si_code == SI_USER)
2612af245d11STodd Fiala     {
2613af245d11STodd Fiala         if (log)
2614af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
2615af245d11STodd Fiala                             __FUNCTION__,
2616af245d11STodd Fiala                             GetUnixSignals ().GetSignalAsCString (signo),
2617af245d11STodd Fiala                             signo,
2618af245d11STodd Fiala                             (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
2619af245d11STodd Fiala                             info->si_pid,
2620511e5cdcSTodd Fiala                             is_from_llgs ? "from llgs" : "not from llgs",
2621af245d11STodd Fiala                             pid);
262258a2f669STodd Fiala     }
2623af245d11STodd Fiala 
262458a2f669STodd Fiala     // Check for new thread notification.
262558a2f669STodd Fiala     if ((info->si_pid == 0) && (info->si_code == SI_USER))
2626af245d11STodd Fiala     {
2627af245d11STodd Fiala         // A new thread creation is being signaled. This is one of two parts that come in
2628426bdf88SPavel Labath         // a non-deterministic order. This code handles the case where the new thread event comes
2629426bdf88SPavel Labath         // before the event on the parent thread. For the opposite case see code in
2630426bdf88SPavel Labath         // MonitorSIGTRAP.
2631af245d11STodd Fiala         if (log)
2632af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": new thread notification",
2633af245d11STodd Fiala                      __FUNCTION__, GetID (), pid);
2634af245d11STodd Fiala 
26355fd24c67SPavel Labath         thread_sp = AddThread(pid);
26365fd24c67SPavel Labath         assert (thread_sp.get() && "failed to create the tracking data for newly created inferior thread");
26375fd24c67SPavel Labath         // We can now resume the newly created thread.
2638cb84eebbSTamas Berghammer         std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
26395fd24c67SPavel Labath         Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
26401dbc6c9cSPavel Labath         ThreadWasCreated(pid);
264158a2f669STodd Fiala         // Done handling.
264258a2f669STodd Fiala         return;
2643af245d11STodd Fiala     }
264458a2f669STodd Fiala 
264558a2f669STodd Fiala     // Check for thread stop notification.
2646511e5cdcSTodd Fiala     if (is_from_llgs && (info->si_code == SI_TKILL) && (signo == SIGSTOP))
2647af245d11STodd Fiala     {
2648af245d11STodd Fiala         // This is a tgkill()-based stop.
2649af245d11STodd Fiala         if (thread_sp)
2650af245d11STodd Fiala         {
2651fa03ad2eSChaoren Lin             if (log)
2652fa03ad2eSChaoren Lin                 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
2653fa03ad2eSChaoren Lin                              __FUNCTION__,
2654fa03ad2eSChaoren Lin                              GetID (),
2655fa03ad2eSChaoren Lin                              pid);
2656fa03ad2eSChaoren Lin 
2657aab58633SChaoren Lin             // Check that we're not already marked with a stop reason.
2658aab58633SChaoren Lin             // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
2659aab58633SChaoren Lin             // the kernel signaled us with the thread stopping which we handled and marked as stopped,
2660aab58633SChaoren Lin             // and that, without an intervening resume, we received another stop.  It is more likely
2661aab58633SChaoren Lin             // that we are missing the marking of a run state somewhere if we find that the thread was
2662aab58633SChaoren Lin             // marked as stopped.
2663cb84eebbSTamas Berghammer             std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
2664cb84eebbSTamas Berghammer             assert (linux_thread_sp && "linux_thread_sp is null!");
2665aab58633SChaoren Lin 
2666cb84eebbSTamas Berghammer             const StateType thread_state = linux_thread_sp->GetState ();
2667aab58633SChaoren Lin             if (!StateIsStoppedState (thread_state, false))
2668aab58633SChaoren Lin             {
2669ed89c7feSPavel Labath                 // An inferior thread has stopped because of a SIGSTOP we have sent it.
2670ed89c7feSPavel Labath                 // Generally, these are not important stops and we don't want to report them as
2671ed89c7feSPavel Labath                 // they are just used to stop other threads when one thread (the one with the
2672ed89c7feSPavel Labath                 // *real* stop reason) hits a breakpoint (watchpoint, etc...). However, in the
2673ed89c7feSPavel Labath                 // case of an asynchronous Interrupt(), this *is* the real stop reason, so we
2674ed89c7feSPavel Labath                 // leave the signal intact if this is the thread that was chosen as the
2675ed89c7feSPavel Labath                 // triggering thread.
2676ed89c7feSPavel Labath                 if (m_pending_notification_up && m_pending_notification_up->triggering_tid == pid)
2677ed89c7feSPavel Labath                     linux_thread_sp->SetStoppedBySignal(SIGSTOP);
2678ed89c7feSPavel Labath                 else
2679cb84eebbSTamas Berghammer                     linux_thread_sp->SetStoppedBySignal(0);
2680ed89c7feSPavel Labath 
2681af245d11STodd Fiala                 SetCurrentThreadID (thread_sp->GetID ());
26821dbc6c9cSPavel Labath                 ThreadDidStop (thread_sp->GetID (), true);
2683aab58633SChaoren Lin             }
2684aab58633SChaoren Lin             else
2685aab58633SChaoren Lin             {
2686aab58633SChaoren Lin                 if (log)
2687aab58633SChaoren Lin                 {
2688aab58633SChaoren Lin                     // Retrieve the signal name if the thread was stopped by a signal.
2689aab58633SChaoren Lin                     int stop_signo = 0;
2690cb84eebbSTamas Berghammer                     const bool stopped_by_signal = linux_thread_sp->IsStopped (&stop_signo);
2691aab58633SChaoren Lin                     const char *signal_name = stopped_by_signal ? GetUnixSignals ().GetSignalAsCString (stop_signo) : "<not stopped by signal>";
2692aab58633SChaoren Lin                     if (!signal_name)
2693aab58633SChaoren Lin                         signal_name = "<no-signal-name>";
2694aab58633SChaoren Lin 
2695aab58633SChaoren 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",
2696aab58633SChaoren Lin                                  __FUNCTION__,
2697aab58633SChaoren Lin                                  GetID (),
2698cb84eebbSTamas Berghammer                                  linux_thread_sp->GetID (),
2699aab58633SChaoren Lin                                  StateAsCString (thread_state),
2700aab58633SChaoren Lin                                  stop_signo,
2701aab58633SChaoren Lin                                  signal_name);
2702aab58633SChaoren Lin                 }
27031dbc6c9cSPavel Labath                 ThreadDidStop (thread_sp->GetID (), false);
2704af245d11STodd Fiala             }
270586fd8e45SChaoren Lin         }
2706af245d11STodd Fiala 
270758a2f669STodd Fiala         // Done handling.
2708af245d11STodd Fiala         return;
2709af245d11STodd Fiala     }
2710af245d11STodd Fiala 
2711af245d11STodd Fiala     if (log)
2712af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, GetUnixSignals ().GetSignalAsCString (signo));
2713af245d11STodd Fiala 
271486fd8e45SChaoren Lin     // This thread is stopped.
27151dbc6c9cSPavel Labath     ThreadDidStop (pid, false);
271686fd8e45SChaoren Lin 
2717af245d11STodd Fiala     switch (signo)
2718af245d11STodd Fiala     {
2719511e5cdcSTodd Fiala     case SIGSTOP:
2720511e5cdcSTodd Fiala         {
27218c8ff7afSPavel Labath             std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (signo);
272258a2f669STodd Fiala             if (log)
2723511e5cdcSTodd Fiala             {
2724511e5cdcSTodd Fiala                 if (is_from_llgs)
2725511e5cdcSTodd Fiala                     log->Printf ("NativeProcessLinux::%s pid = %" PRIu64 " tid %" PRIu64 " received SIGSTOP from llgs, most likely an interrupt", __FUNCTION__, GetID (), pid);
2726511e5cdcSTodd Fiala                 else
2727511e5cdcSTodd Fiala                     log->Printf ("NativeProcessLinux::%s pid = %" PRIu64 " tid %" PRIu64 " received SIGSTOP from outside of debugger", __FUNCTION__, GetID (), pid);
2728511e5cdcSTodd Fiala             }
2729511e5cdcSTodd Fiala 
2730fa03ad2eSChaoren Lin             // Resume this thread to get the group-stop mechanism to fire off the true group stops.
2731fa03ad2eSChaoren Lin             // This thread will get stopped again as part of the group-stop completion.
27321dbc6c9cSPavel Labath             ResumeThread(pid,
273386fd8e45SChaoren Lin                     [=](lldb::tid_t tid_to_resume, bool supress_signal)
2734fa03ad2eSChaoren Lin                     {
2735cb84eebbSTamas Berghammer                         std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2736fa03ad2eSChaoren Lin                         // Pass this signal number on to the inferior to handle.
273737c768caSChaoren Lin                         return Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo);
27381dbc6c9cSPavel Labath                     },
27391dbc6c9cSPavel Labath                     true);
274086fd8e45SChaoren Lin         }
274186fd8e45SChaoren Lin         break;
274286fd8e45SChaoren Lin     case SIGSEGV:
274386fd8e45SChaoren Lin     case SIGILL:
274486fd8e45SChaoren Lin     case SIGFPE:
274586fd8e45SChaoren Lin     case SIGBUS:
274686fd8e45SChaoren Lin         if (thread_sp)
2747cb84eebbSTamas Berghammer             std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetCrashedWithException (*info);
274886fd8e45SChaoren Lin         break;
274986fd8e45SChaoren Lin     default:
275086fd8e45SChaoren Lin         // This is just a pre-signal-delivery notification of the incoming signal.
275186fd8e45SChaoren Lin         if (thread_sp)
2752cb84eebbSTamas Berghammer             std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (signo);
2753fa03ad2eSChaoren Lin 
275486fd8e45SChaoren Lin         break;
275586fd8e45SChaoren Lin     }
275686fd8e45SChaoren Lin 
275786fd8e45SChaoren Lin     // Send a stop to the debugger after we get all other threads to stop.
2758ed89c7feSPavel Labath     StopRunningThreads (pid);
2759511e5cdcSTodd Fiala }
2760af245d11STodd Fiala 
2761e7708688STamas Berghammer namespace {
2762e7708688STamas Berghammer 
2763e7708688STamas Berghammer struct EmulatorBaton
2764e7708688STamas Berghammer {
2765e7708688STamas Berghammer     NativeProcessLinux* m_process;
2766e7708688STamas Berghammer     NativeRegisterContext* m_reg_context;
27676648fcc3SPavel Labath 
27686648fcc3SPavel Labath     // eRegisterKindDWARF -> RegsiterValue
27696648fcc3SPavel Labath     std::unordered_map<uint32_t, RegisterValue> m_register_values;
2770e7708688STamas Berghammer 
2771e7708688STamas Berghammer     EmulatorBaton(NativeProcessLinux* process, NativeRegisterContext* reg_context) :
2772e7708688STamas Berghammer             m_process(process), m_reg_context(reg_context) {}
2773e7708688STamas Berghammer };
2774e7708688STamas Berghammer 
2775e7708688STamas Berghammer } // anonymous namespace
2776e7708688STamas Berghammer 
2777e7708688STamas Berghammer static size_t
2778e7708688STamas Berghammer ReadMemoryCallback (EmulateInstruction *instruction,
2779e7708688STamas Berghammer                     void *baton,
2780e7708688STamas Berghammer                     const EmulateInstruction::Context &context,
2781e7708688STamas Berghammer                     lldb::addr_t addr,
2782e7708688STamas Berghammer                     void *dst,
2783e7708688STamas Berghammer                     size_t length)
2784e7708688STamas Berghammer {
2785e7708688STamas Berghammer     EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
2786e7708688STamas Berghammer 
27873eb4b458SChaoren Lin     size_t bytes_read;
2788e7708688STamas Berghammer     emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
2789e7708688STamas Berghammer     return bytes_read;
2790e7708688STamas Berghammer }
2791e7708688STamas Berghammer 
2792e7708688STamas Berghammer static bool
2793e7708688STamas Berghammer ReadRegisterCallback (EmulateInstruction *instruction,
2794e7708688STamas Berghammer                       void *baton,
2795e7708688STamas Berghammer                       const RegisterInfo *reg_info,
2796e7708688STamas Berghammer                       RegisterValue &reg_value)
2797e7708688STamas Berghammer {
2798e7708688STamas Berghammer     EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
2799e7708688STamas Berghammer 
28006648fcc3SPavel Labath     auto it = emulator_baton->m_register_values.find(reg_info->kinds[eRegisterKindDWARF]);
28016648fcc3SPavel Labath     if (it != emulator_baton->m_register_values.end())
28026648fcc3SPavel Labath     {
28036648fcc3SPavel Labath         reg_value = it->second;
28046648fcc3SPavel Labath         return true;
28056648fcc3SPavel Labath     }
28066648fcc3SPavel Labath 
2807e7708688STamas Berghammer     // The emulator only fill in the dwarf regsiter numbers (and in some case
2808e7708688STamas Berghammer     // the generic register numbers). Get the full register info from the
2809e7708688STamas Berghammer     // register context based on the dwarf register numbers.
2810e7708688STamas Berghammer     const RegisterInfo* full_reg_info = emulator_baton->m_reg_context->GetRegisterInfo(
2811e7708688STamas Berghammer             eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
2812e7708688STamas Berghammer 
2813e7708688STamas Berghammer     Error error = emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
28146648fcc3SPavel Labath     if (error.Success())
28156648fcc3SPavel Labath         return true;
2816cdc22a88SMohit K. Bhakkad 
28176648fcc3SPavel Labath     return false;
2818e7708688STamas Berghammer }
2819e7708688STamas Berghammer 
2820e7708688STamas Berghammer static bool
2821e7708688STamas Berghammer WriteRegisterCallback (EmulateInstruction *instruction,
2822e7708688STamas Berghammer                        void *baton,
2823e7708688STamas Berghammer                        const EmulateInstruction::Context &context,
2824e7708688STamas Berghammer                        const RegisterInfo *reg_info,
2825e7708688STamas Berghammer                        const RegisterValue &reg_value)
2826e7708688STamas Berghammer {
2827e7708688STamas Berghammer     EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
28286648fcc3SPavel Labath     emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = reg_value;
2829e7708688STamas Berghammer     return true;
2830e7708688STamas Berghammer }
2831e7708688STamas Berghammer 
2832e7708688STamas Berghammer static size_t
2833e7708688STamas Berghammer WriteMemoryCallback (EmulateInstruction *instruction,
2834e7708688STamas Berghammer                      void *baton,
2835e7708688STamas Berghammer                      const EmulateInstruction::Context &context,
2836e7708688STamas Berghammer                      lldb::addr_t addr,
2837e7708688STamas Berghammer                      const void *dst,
2838e7708688STamas Berghammer                      size_t length)
2839e7708688STamas Berghammer {
2840e7708688STamas Berghammer     return length;
2841e7708688STamas Berghammer }
2842e7708688STamas Berghammer 
2843e7708688STamas Berghammer static lldb::addr_t
2844e7708688STamas Berghammer ReadFlags (NativeRegisterContext* regsiter_context)
2845e7708688STamas Berghammer {
2846e7708688STamas Berghammer     const RegisterInfo* flags_info = regsiter_context->GetRegisterInfo(
2847e7708688STamas Berghammer             eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
2848e7708688STamas Berghammer     return regsiter_context->ReadRegisterAsUnsigned(flags_info, LLDB_INVALID_ADDRESS);
2849e7708688STamas Berghammer }
2850e7708688STamas Berghammer 
2851e7708688STamas Berghammer Error
2852e7708688STamas Berghammer NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadProtocolSP thread_sp)
2853e7708688STamas Berghammer {
2854e7708688STamas Berghammer     Error error;
2855e7708688STamas Berghammer     NativeRegisterContextSP register_context_sp = thread_sp->GetRegisterContext();
2856e7708688STamas Berghammer 
2857e7708688STamas Berghammer     std::unique_ptr<EmulateInstruction> emulator_ap(
2858e7708688STamas Berghammer         EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, nullptr));
2859e7708688STamas Berghammer 
2860e7708688STamas Berghammer     if (emulator_ap == nullptr)
2861e7708688STamas Berghammer         return Error("Instruction emulator not found!");
2862e7708688STamas Berghammer 
2863e7708688STamas Berghammer     EmulatorBaton baton(this, register_context_sp.get());
2864e7708688STamas Berghammer     emulator_ap->SetBaton(&baton);
2865e7708688STamas Berghammer     emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
2866e7708688STamas Berghammer     emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
2867e7708688STamas Berghammer     emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
2868e7708688STamas Berghammer     emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
2869e7708688STamas Berghammer 
2870e7708688STamas Berghammer     if (!emulator_ap->ReadInstruction())
2871e7708688STamas Berghammer         return Error("Read instruction failed!");
2872e7708688STamas Berghammer 
28736648fcc3SPavel Labath     bool emulation_result = emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
28746648fcc3SPavel Labath 
28756648fcc3SPavel Labath     const RegisterInfo* reg_info_pc = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
28766648fcc3SPavel Labath     const RegisterInfo* reg_info_flags = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
28776648fcc3SPavel Labath 
28786648fcc3SPavel Labath     auto pc_it = baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
28796648fcc3SPavel Labath     auto flags_it = baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
28806648fcc3SPavel Labath 
2881e7708688STamas Berghammer     lldb::addr_t next_pc;
2882e7708688STamas Berghammer     lldb::addr_t next_flags;
28836648fcc3SPavel Labath     if (emulation_result)
2884e7708688STamas Berghammer     {
28856648fcc3SPavel Labath         assert(pc_it != baton.m_register_values.end() && "Emulation was successfull but PC wasn't updated");
28866648fcc3SPavel Labath         next_pc = pc_it->second.GetAsUInt64();
28876648fcc3SPavel Labath 
28886648fcc3SPavel Labath         if (flags_it != baton.m_register_values.end())
28896648fcc3SPavel Labath             next_flags = flags_it->second.GetAsUInt64();
2890e7708688STamas Berghammer         else
2891e7708688STamas Berghammer             next_flags = ReadFlags (register_context_sp.get());
2892e7708688STamas Berghammer     }
28936648fcc3SPavel Labath     else if (pc_it == baton.m_register_values.end())
2894e7708688STamas Berghammer     {
2895e7708688STamas Berghammer         // Emulate instruction failed and it haven't changed PC. Advance PC
2896e7708688STamas Berghammer         // with the size of the current opcode because the emulation of all
2897e7708688STamas Berghammer         // PC modifying instruction should be successful. The failure most
2898e7708688STamas Berghammer         // likely caused by a not supported instruction which don't modify PC.
2899e7708688STamas Berghammer         next_pc = register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
2900e7708688STamas Berghammer         next_flags = ReadFlags (register_context_sp.get());
2901e7708688STamas Berghammer     }
2902e7708688STamas Berghammer     else
2903e7708688STamas Berghammer     {
2904e7708688STamas Berghammer         // The instruction emulation failed after it modified the PC. It is an
2905e7708688STamas Berghammer         // unknown error where we can't continue because the next instruction is
2906e7708688STamas Berghammer         // modifying the PC but we don't  know how.
2907e7708688STamas Berghammer         return Error ("Instruction emulation failed unexpectedly.");
2908e7708688STamas Berghammer     }
2909e7708688STamas Berghammer 
2910e7708688STamas Berghammer     if (m_arch.GetMachine() == llvm::Triple::arm)
2911e7708688STamas Berghammer     {
2912e7708688STamas Berghammer         if (next_flags & 0x20)
2913e7708688STamas Berghammer         {
2914e7708688STamas Berghammer             // Thumb mode
2915e7708688STamas Berghammer             error = SetSoftwareBreakpoint(next_pc, 2);
2916e7708688STamas Berghammer         }
2917e7708688STamas Berghammer         else
2918e7708688STamas Berghammer         {
2919e7708688STamas Berghammer             // Arm mode
2920e7708688STamas Berghammer             error = SetSoftwareBreakpoint(next_pc, 4);
2921e7708688STamas Berghammer         }
2922e7708688STamas Berghammer     }
2923cdc22a88SMohit K. Bhakkad     else if (m_arch.GetMachine() == llvm::Triple::mips64
2924cdc22a88SMohit K. Bhakkad             || m_arch.GetMachine() == llvm::Triple::mips64el)
2925cdc22a88SMohit K. Bhakkad         error = SetSoftwareBreakpoint(next_pc, 4);
2926e7708688STamas Berghammer     else
2927e7708688STamas Berghammer     {
2928e7708688STamas Berghammer         // No size hint is given for the next breakpoint
2929e7708688STamas Berghammer         error = SetSoftwareBreakpoint(next_pc, 0);
2930e7708688STamas Berghammer     }
2931e7708688STamas Berghammer 
2932e7708688STamas Berghammer     if (error.Fail())
2933e7708688STamas Berghammer         return error;
2934e7708688STamas Berghammer 
2935e7708688STamas Berghammer     m_threads_stepping_with_breakpoint.insert({thread_sp->GetID(), next_pc});
2936e7708688STamas Berghammer 
2937e7708688STamas Berghammer     return Error();
2938e7708688STamas Berghammer }
2939e7708688STamas Berghammer 
2940e7708688STamas Berghammer bool
2941e7708688STamas Berghammer NativeProcessLinux::SupportHardwareSingleStepping() const
2942e7708688STamas Berghammer {
2943cdc22a88SMohit K. Bhakkad     if (m_arch.GetMachine() == llvm::Triple::arm
2944cdc22a88SMohit K. Bhakkad         || m_arch.GetMachine() == llvm::Triple::mips64 || m_arch.GetMachine() == llvm::Triple::mips64el)
2945cdc22a88SMohit K. Bhakkad         return false;
2946cdc22a88SMohit K. Bhakkad     return true;
2947e7708688STamas Berghammer }
2948e7708688STamas Berghammer 
2949af245d11STodd Fiala Error
2950af245d11STodd Fiala NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
2951af245d11STodd Fiala {
2952af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2953af245d11STodd Fiala     if (log)
2954af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
2955af245d11STodd Fiala 
295686fd8e45SChaoren Lin     bool stepping = false;
2957e7708688STamas Berghammer     bool software_single_step = !SupportHardwareSingleStepping();
2958af245d11STodd Fiala 
295945f5cb31SPavel Labath     Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
2960af245d11STodd Fiala     Mutex::Locker locker (m_threads_mutex);
29615830aa75STamas Berghammer 
2962e7708688STamas Berghammer     if (software_single_step)
2963e7708688STamas Berghammer     {
2964e7708688STamas Berghammer         for (auto thread_sp : m_threads)
2965e7708688STamas Berghammer         {
2966e7708688STamas Berghammer             assert (thread_sp && "thread list should not contain NULL threads");
2967e7708688STamas Berghammer 
2968e7708688STamas Berghammer             const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
2969e7708688STamas Berghammer             if (action == nullptr)
2970e7708688STamas Berghammer                 continue;
2971e7708688STamas Berghammer 
2972e7708688STamas Berghammer             if (action->state == eStateStepping)
2973e7708688STamas Berghammer             {
2974e7708688STamas Berghammer                 Error error = SetupSoftwareSingleStepping(thread_sp);
2975e7708688STamas Berghammer                 if (error.Fail())
2976e7708688STamas Berghammer                     return error;
2977e7708688STamas Berghammer             }
2978e7708688STamas Berghammer         }
2979e7708688STamas Berghammer     }
2980e7708688STamas Berghammer 
2981af245d11STodd Fiala     for (auto thread_sp : m_threads)
2982af245d11STodd Fiala     {
2983af245d11STodd Fiala         assert (thread_sp && "thread list should not contain NULL threads");
2984af245d11STodd Fiala 
2985af245d11STodd Fiala         const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
29866a196ce6SChaoren Lin 
29876a196ce6SChaoren Lin         if (action == nullptr)
29886a196ce6SChaoren Lin         {
29896a196ce6SChaoren Lin             if (log)
29906a196ce6SChaoren Lin                 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
29916a196ce6SChaoren Lin                     __FUNCTION__, GetID (), thread_sp->GetID ());
29926a196ce6SChaoren Lin             continue;
29936a196ce6SChaoren Lin         }
2994af245d11STodd Fiala 
2995af245d11STodd Fiala         if (log)
2996af245d11STodd Fiala         {
2997af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
2998af245d11STodd Fiala                     __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
2999af245d11STodd Fiala         }
3000af245d11STodd Fiala 
3001af245d11STodd Fiala         switch (action->state)
3002af245d11STodd Fiala         {
3003af245d11STodd Fiala         case eStateRunning:
3004fa03ad2eSChaoren Lin         {
3005af245d11STodd Fiala             // Run the thread, possibly feeding it the signal.
3006fa03ad2eSChaoren Lin             const int signo = action->signal;
30071dbc6c9cSPavel Labath             ResumeThread(thread_sp->GetID (),
300886fd8e45SChaoren Lin                     [=](lldb::tid_t tid_to_resume, bool supress_signal)
3009af245d11STodd Fiala                     {
3010cb84eebbSTamas Berghammer                         std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
3011fa03ad2eSChaoren Lin                         // Pass this signal number on to the inferior to handle.
30125830aa75STamas Berghammer                         const auto resume_result = Resume (tid_to_resume, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
30135830aa75STamas Berghammer                         if (resume_result.Success())
30145830aa75STamas Berghammer                             SetState(eStateRunning, true);
30155830aa75STamas Berghammer                         return resume_result;
30161dbc6c9cSPavel Labath                     },
30171dbc6c9cSPavel Labath                     false);
3018af245d11STodd Fiala             break;
3019fa03ad2eSChaoren Lin         }
3020af245d11STodd Fiala 
3021af245d11STodd Fiala         case eStateStepping:
3022af245d11STodd Fiala         {
3023ae29d395SChaoren Lin             // Request the step.
3024ae29d395SChaoren Lin             const int signo = action->signal;
30251dbc6c9cSPavel Labath             ResumeThread(thread_sp->GetID (),
302686fd8e45SChaoren Lin                     [=](lldb::tid_t tid_to_step, bool supress_signal)
3027af245d11STodd Fiala                     {
3028cb84eebbSTamas Berghammer                         std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStepping ();
3029e7708688STamas Berghammer 
3030e7708688STamas Berghammer                         Error step_result;
3031e7708688STamas Berghammer                         if (software_single_step)
3032e7708688STamas Berghammer                             step_result = Resume (tid_to_step, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
3033e7708688STamas Berghammer                         else
3034e7708688STamas Berghammer                             step_result = SingleStep (tid_to_step,(signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
3035e7708688STamas Berghammer 
303637c768caSChaoren Lin                         assert (step_result.Success() && "SingleStep() failed");
30375830aa75STamas Berghammer                         if (step_result.Success())
30385830aa75STamas Berghammer                             SetState(eStateStepping, true);
303937c768caSChaoren Lin                         return step_result;
30401dbc6c9cSPavel Labath                     },
30411dbc6c9cSPavel Labath                     false);
304286fd8e45SChaoren Lin             stepping = true;
3043af245d11STodd Fiala             break;
3044ae29d395SChaoren Lin         }
3045af245d11STodd Fiala 
3046af245d11STodd Fiala         case eStateSuspended:
3047af245d11STodd Fiala         case eStateStopped:
3048*108c325dSPavel Labath             lldbassert(0 && "Unexpected state");
3049af245d11STodd Fiala 
3050af245d11STodd Fiala         default:
3051af245d11STodd Fiala             return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
3052af245d11STodd Fiala                     __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
3053af245d11STodd Fiala         }
3054af245d11STodd Fiala     }
3055af245d11STodd Fiala 
30565830aa75STamas Berghammer     return Error();
3057af245d11STodd Fiala }
3058af245d11STodd Fiala 
3059af245d11STodd Fiala Error
3060af245d11STodd Fiala NativeProcessLinux::Halt ()
3061af245d11STodd Fiala {
3062af245d11STodd Fiala     Error error;
3063af245d11STodd Fiala 
3064af245d11STodd Fiala     if (kill (GetID (), SIGSTOP) != 0)
3065af245d11STodd Fiala         error.SetErrorToErrno ();
3066af245d11STodd Fiala 
3067af245d11STodd Fiala     return error;
3068af245d11STodd Fiala }
3069af245d11STodd Fiala 
3070af245d11STodd Fiala Error
3071af245d11STodd Fiala NativeProcessLinux::Detach ()
3072af245d11STodd Fiala {
3073af245d11STodd Fiala     Error error;
3074af245d11STodd Fiala 
3075af245d11STodd Fiala     // Tell ptrace to detach from the process.
3076af245d11STodd Fiala     if (GetID () != LLDB_INVALID_PROCESS_ID)
3077af245d11STodd Fiala         error = Detach (GetID ());
3078af245d11STodd Fiala 
3079af245d11STodd Fiala     // Stop monitoring the inferior.
308045f5cb31SPavel Labath     m_monitor_up->Terminate();
3081af245d11STodd Fiala 
3082af245d11STodd Fiala     // No error.
3083af245d11STodd Fiala     return error;
3084af245d11STodd Fiala }
3085af245d11STodd Fiala 
3086af245d11STodd Fiala Error
3087af245d11STodd Fiala NativeProcessLinux::Signal (int signo)
3088af245d11STodd Fiala {
3089af245d11STodd Fiala     Error error;
3090af245d11STodd Fiala 
3091af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3092af245d11STodd Fiala     if (log)
3093af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
3094af245d11STodd Fiala                 __FUNCTION__, signo,  GetUnixSignals ().GetSignalAsCString (signo), GetID ());
3095af245d11STodd Fiala 
3096af245d11STodd Fiala     if (kill(GetID(), signo))
3097af245d11STodd Fiala         error.SetErrorToErrno();
3098af245d11STodd Fiala 
3099af245d11STodd Fiala     return error;
3100af245d11STodd Fiala }
3101af245d11STodd Fiala 
3102af245d11STodd Fiala Error
3103e9547b80SChaoren Lin NativeProcessLinux::Interrupt ()
3104e9547b80SChaoren Lin {
3105e9547b80SChaoren Lin     // Pick a running thread (or if none, a not-dead stopped thread) as
3106e9547b80SChaoren Lin     // the chosen thread that will be the stop-reason thread.
3107e9547b80SChaoren Lin     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3108e9547b80SChaoren Lin 
3109e9547b80SChaoren Lin     NativeThreadProtocolSP running_thread_sp;
3110e9547b80SChaoren Lin     NativeThreadProtocolSP stopped_thread_sp;
3111e9547b80SChaoren Lin 
3112e9547b80SChaoren Lin     if (log)
3113e9547b80SChaoren Lin         log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
3114e9547b80SChaoren Lin 
311545f5cb31SPavel Labath     Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
31165830aa75STamas Berghammer     Mutex::Locker locker (m_threads_mutex);
31175830aa75STamas Berghammer 
3118e9547b80SChaoren Lin     for (auto thread_sp : m_threads)
3119e9547b80SChaoren Lin     {
3120e9547b80SChaoren Lin         // The thread shouldn't be null but lets just cover that here.
3121e9547b80SChaoren Lin         if (!thread_sp)
3122e9547b80SChaoren Lin             continue;
3123e9547b80SChaoren Lin 
3124e9547b80SChaoren Lin         // If we have a running or stepping thread, we'll call that the
3125e9547b80SChaoren Lin         // target of the interrupt.
3126e9547b80SChaoren Lin         const auto thread_state = thread_sp->GetState ();
3127e9547b80SChaoren Lin         if (thread_state == eStateRunning ||
3128e9547b80SChaoren Lin             thread_state == eStateStepping)
3129e9547b80SChaoren Lin         {
3130e9547b80SChaoren Lin             running_thread_sp = thread_sp;
3131e9547b80SChaoren Lin             break;
3132e9547b80SChaoren Lin         }
3133e9547b80SChaoren Lin         else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
3134e9547b80SChaoren Lin         {
3135e9547b80SChaoren Lin             // Remember the first non-dead stopped thread.  We'll use that as a backup if there are no running threads.
3136e9547b80SChaoren Lin             stopped_thread_sp = thread_sp;
3137e9547b80SChaoren Lin         }
3138e9547b80SChaoren Lin     }
3139e9547b80SChaoren Lin 
3140e9547b80SChaoren Lin     if (!running_thread_sp && !stopped_thread_sp)
3141e9547b80SChaoren Lin     {
31425830aa75STamas Berghammer         Error error("found no running/stepping or live stopped threads as target for interrupt");
3143e9547b80SChaoren Lin         if (log)
3144e9547b80SChaoren Lin             log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
31455830aa75STamas Berghammer 
3146e9547b80SChaoren Lin         return error;
3147e9547b80SChaoren Lin     }
3148e9547b80SChaoren Lin 
3149e9547b80SChaoren Lin     NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
3150e9547b80SChaoren Lin 
3151e9547b80SChaoren Lin     if (log)
3152e9547b80SChaoren Lin         log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
3153e9547b80SChaoren Lin                      __FUNCTION__,
3154e9547b80SChaoren Lin                      GetID (),
3155e9547b80SChaoren Lin                      running_thread_sp ? "running" : "stopped",
3156e9547b80SChaoren Lin                      deferred_signal_thread_sp->GetID ());
3157e9547b80SChaoren Lin 
3158ed89c7feSPavel Labath     StopRunningThreads(deferred_signal_thread_sp->GetID());
315945f5cb31SPavel Labath 
31605830aa75STamas Berghammer     return Error();
3161e9547b80SChaoren Lin }
3162e9547b80SChaoren Lin 
3163e9547b80SChaoren Lin Error
3164af245d11STodd Fiala NativeProcessLinux::Kill ()
3165af245d11STodd Fiala {
3166af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3167af245d11STodd Fiala     if (log)
3168af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
3169af245d11STodd Fiala 
3170af245d11STodd Fiala     Error error;
3171af245d11STodd Fiala 
3172af245d11STodd Fiala     switch (m_state)
3173af245d11STodd Fiala     {
3174af245d11STodd Fiala         case StateType::eStateInvalid:
3175af245d11STodd Fiala         case StateType::eStateExited:
3176af245d11STodd Fiala         case StateType::eStateCrashed:
3177af245d11STodd Fiala         case StateType::eStateDetached:
3178af245d11STodd Fiala         case StateType::eStateUnloaded:
3179af245d11STodd Fiala             // Nothing to do - the process is already dead.
3180af245d11STodd Fiala             if (log)
3181af245d11STodd Fiala                 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
3182af245d11STodd Fiala             return error;
3183af245d11STodd Fiala 
3184af245d11STodd Fiala         case StateType::eStateConnected:
3185af245d11STodd Fiala         case StateType::eStateAttaching:
3186af245d11STodd Fiala         case StateType::eStateLaunching:
3187af245d11STodd Fiala         case StateType::eStateStopped:
3188af245d11STodd Fiala         case StateType::eStateRunning:
3189af245d11STodd Fiala         case StateType::eStateStepping:
3190af245d11STodd Fiala         case StateType::eStateSuspended:
3191af245d11STodd Fiala             // We can try to kill a process in these states.
3192af245d11STodd Fiala             break;
3193af245d11STodd Fiala     }
3194af245d11STodd Fiala 
3195af245d11STodd Fiala     if (kill (GetID (), SIGKILL) != 0)
3196af245d11STodd Fiala     {
3197af245d11STodd Fiala         error.SetErrorToErrno ();
3198af245d11STodd Fiala         return error;
3199af245d11STodd Fiala     }
3200af245d11STodd Fiala 
3201af245d11STodd Fiala     return error;
3202af245d11STodd Fiala }
3203af245d11STodd Fiala 
3204af245d11STodd Fiala static Error
3205af245d11STodd Fiala ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
3206af245d11STodd Fiala {
3207af245d11STodd Fiala     memory_region_info.Clear();
3208af245d11STodd Fiala 
3209af245d11STodd Fiala     StringExtractor line_extractor (maps_line.c_str ());
3210af245d11STodd Fiala 
3211af245d11STodd Fiala     // Format: {address_start_hex}-{address_end_hex} perms offset  dev   inode   pathname
3212af245d11STodd Fiala     // perms: rwxp   (letter is present if set, '-' if not, final character is p=private, s=shared).
3213af245d11STodd Fiala 
3214af245d11STodd Fiala     // Parse out the starting address
3215af245d11STodd Fiala     lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
3216af245d11STodd Fiala 
3217af245d11STodd Fiala     // Parse out hyphen separating start and end address from range.
3218af245d11STodd Fiala     if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
3219af245d11STodd Fiala         return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
3220af245d11STodd Fiala 
3221af245d11STodd Fiala     // Parse out the ending address
3222af245d11STodd Fiala     lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
3223af245d11STodd Fiala 
3224af245d11STodd Fiala     // Parse out the space after the address.
3225af245d11STodd Fiala     if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
3226af245d11STodd Fiala         return Error ("malformed /proc/{pid}/maps entry, missing space after range");
3227af245d11STodd Fiala 
3228af245d11STodd Fiala     // Save the range.
3229af245d11STodd Fiala     memory_region_info.GetRange ().SetRangeBase (start_address);
3230af245d11STodd Fiala     memory_region_info.GetRange ().SetRangeEnd (end_address);
3231af245d11STodd Fiala 
3232af245d11STodd Fiala     // Parse out each permission entry.
3233af245d11STodd Fiala     if (line_extractor.GetBytesLeft () < 4)
3234af245d11STodd Fiala         return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
3235af245d11STodd Fiala 
3236af245d11STodd Fiala     // Handle read permission.
3237af245d11STodd Fiala     const char read_perm_char = line_extractor.GetChar ();
3238af245d11STodd Fiala     if (read_perm_char == 'r')
3239af245d11STodd Fiala         memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
3240af245d11STodd Fiala     else
3241af245d11STodd Fiala     {
3242af245d11STodd Fiala         assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
3243af245d11STodd Fiala         memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
3244af245d11STodd Fiala     }
3245af245d11STodd Fiala 
3246af245d11STodd Fiala     // Handle write permission.
3247af245d11STodd Fiala     const char write_perm_char = line_extractor.GetChar ();
3248af245d11STodd Fiala     if (write_perm_char == 'w')
3249af245d11STodd Fiala         memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
3250af245d11STodd Fiala     else
3251af245d11STodd Fiala     {
3252af245d11STodd Fiala         assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
3253af245d11STodd Fiala         memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
3254af245d11STodd Fiala     }
3255af245d11STodd Fiala 
3256af245d11STodd Fiala     // Handle execute permission.
3257af245d11STodd Fiala     const char exec_perm_char = line_extractor.GetChar ();
3258af245d11STodd Fiala     if (exec_perm_char == 'x')
3259af245d11STodd Fiala         memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
3260af245d11STodd Fiala     else
3261af245d11STodd Fiala     {
3262af245d11STodd Fiala         assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
3263af245d11STodd Fiala         memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
3264af245d11STodd Fiala     }
3265af245d11STodd Fiala 
3266af245d11STodd Fiala     return Error ();
3267af245d11STodd Fiala }
3268af245d11STodd Fiala 
3269af245d11STodd Fiala Error
3270af245d11STodd Fiala NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
3271af245d11STodd Fiala {
3272af245d11STodd Fiala     // FIXME review that the final memory region returned extends to the end of the virtual address space,
3273af245d11STodd Fiala     // with no perms if it is not mapped.
3274af245d11STodd Fiala 
3275af245d11STodd Fiala     // Use an approach that reads memory regions from /proc/{pid}/maps.
3276af245d11STodd Fiala     // Assume proc maps entries are in ascending order.
3277af245d11STodd Fiala     // FIXME assert if we find differently.
3278af245d11STodd Fiala     Mutex::Locker locker (m_mem_region_cache_mutex);
3279af245d11STodd Fiala 
3280af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3281af245d11STodd Fiala     Error error;
3282af245d11STodd Fiala 
3283af245d11STodd Fiala     if (m_supports_mem_region == LazyBool::eLazyBoolNo)
3284af245d11STodd Fiala     {
3285af245d11STodd Fiala         // We're done.
3286af245d11STodd Fiala         error.SetErrorString ("unsupported");
3287af245d11STodd Fiala         return error;
3288af245d11STodd Fiala     }
3289af245d11STodd Fiala 
3290af245d11STodd Fiala     // If our cache is empty, pull the latest.  There should always be at least one memory region
3291af245d11STodd Fiala     // if memory region handling is supported.
3292af245d11STodd Fiala     if (m_mem_region_cache.empty ())
3293af245d11STodd Fiala     {
3294af245d11STodd Fiala         error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
3295af245d11STodd Fiala              [&] (const std::string &line) -> bool
3296af245d11STodd Fiala              {
3297af245d11STodd Fiala                  MemoryRegionInfo info;
3298af245d11STodd Fiala                  const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
3299af245d11STodd Fiala                  if (parse_error.Success ())
3300af245d11STodd Fiala                  {
3301af245d11STodd Fiala                      m_mem_region_cache.push_back (info);
3302af245d11STodd Fiala                      return true;
3303af245d11STodd Fiala                  }
3304af245d11STodd Fiala                  else
3305af245d11STodd Fiala                  {
3306af245d11STodd Fiala                      if (log)
3307af245d11STodd Fiala                          log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
3308af245d11STodd Fiala                      return false;
3309af245d11STodd Fiala                  }
3310af245d11STodd Fiala              });
3311af245d11STodd Fiala 
3312af245d11STodd Fiala         // If we had an error, we'll mark unsupported.
3313af245d11STodd Fiala         if (error.Fail ())
3314af245d11STodd Fiala         {
3315af245d11STodd Fiala             m_supports_mem_region = LazyBool::eLazyBoolNo;
3316af245d11STodd Fiala             return error;
3317af245d11STodd Fiala         }
3318af245d11STodd Fiala         else if (m_mem_region_cache.empty ())
3319af245d11STodd Fiala         {
3320af245d11STodd Fiala             // No entries after attempting to read them.  This shouldn't happen if /proc/{pid}/maps
3321af245d11STodd Fiala             // is supported.  Assume we don't support map entries via procfs.
3322af245d11STodd Fiala             if (log)
3323af245d11STodd Fiala                 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
3324af245d11STodd Fiala             m_supports_mem_region = LazyBool::eLazyBoolNo;
3325af245d11STodd Fiala             error.SetErrorString ("not supported");
3326af245d11STodd Fiala             return error;
3327af245d11STodd Fiala         }
3328af245d11STodd Fiala 
3329af245d11STodd Fiala         if (log)
3330af245d11STodd 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 ());
3331af245d11STodd Fiala 
3332af245d11STodd Fiala         // We support memory retrieval, remember that.
3333af245d11STodd Fiala         m_supports_mem_region = LazyBool::eLazyBoolYes;
3334af245d11STodd Fiala     }
3335af245d11STodd Fiala     else
3336af245d11STodd Fiala     {
3337af245d11STodd Fiala         if (log)
3338af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
3339af245d11STodd Fiala     }
3340af245d11STodd Fiala 
3341af245d11STodd Fiala     lldb::addr_t prev_base_address = 0;
3342af245d11STodd Fiala 
3343af245d11STodd Fiala     // FIXME start by finding the last region that is <= target address using binary search.  Data is sorted.
3344af245d11STodd Fiala     // There can be a ton of regions on pthreads apps with lots of threads.
3345af245d11STodd Fiala     for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
3346af245d11STodd Fiala     {
3347af245d11STodd Fiala         MemoryRegionInfo &proc_entry_info = *it;
3348af245d11STodd Fiala 
3349af245d11STodd Fiala         // Sanity check assumption that /proc/{pid}/maps entries are ascending.
3350af245d11STodd Fiala         assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
3351af245d11STodd Fiala         prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
3352af245d11STodd Fiala 
3353af245d11STodd Fiala         // If the target address comes before this entry, indicate distance to next region.
3354af245d11STodd Fiala         if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
3355af245d11STodd Fiala         {
3356af245d11STodd Fiala             range_info.GetRange ().SetRangeBase (load_addr);
3357af245d11STodd Fiala             range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
3358af245d11STodd Fiala             range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
3359af245d11STodd Fiala             range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
3360af245d11STodd Fiala             range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
3361af245d11STodd Fiala 
3362af245d11STodd Fiala             return error;
3363af245d11STodd Fiala         }
3364af245d11STodd Fiala         else if (proc_entry_info.GetRange ().Contains (load_addr))
3365af245d11STodd Fiala         {
3366af245d11STodd Fiala             // The target address is within the memory region we're processing here.
3367af245d11STodd Fiala             range_info = proc_entry_info;
3368af245d11STodd Fiala             return error;
3369af245d11STodd Fiala         }
3370af245d11STodd Fiala 
3371af245d11STodd Fiala         // The target memory address comes somewhere after the region we just parsed.
3372af245d11STodd Fiala     }
3373af245d11STodd Fiala 
3374af245d11STodd Fiala     // If we made it here, we didn't find an entry that contained the given address.
3375af245d11STodd Fiala     error.SetErrorString ("address comes after final region");
3376af245d11STodd Fiala 
3377af245d11STodd Fiala     if (log)
3378af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s failed to find map entry for address 0x%" PRIx64 ": %s", __FUNCTION__, load_addr, error.AsCString ());
3379af245d11STodd Fiala 
3380af245d11STodd Fiala     return error;
3381af245d11STodd Fiala }
3382af245d11STodd Fiala 
3383af245d11STodd Fiala void
3384af245d11STodd Fiala NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
3385af245d11STodd Fiala {
3386af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3387af245d11STodd Fiala     if (log)
3388af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
3389af245d11STodd Fiala 
3390af245d11STodd Fiala     {
3391af245d11STodd Fiala         Mutex::Locker locker (m_mem_region_cache_mutex);
3392af245d11STodd Fiala         if (log)
3393af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
3394af245d11STodd Fiala         m_mem_region_cache.clear ();
3395af245d11STodd Fiala     }
3396af245d11STodd Fiala }
3397af245d11STodd Fiala 
3398af245d11STodd Fiala Error
33993eb4b458SChaoren Lin NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr)
3400af245d11STodd Fiala {
3401af245d11STodd Fiala     // FIXME implementing this requires the equivalent of
3402af245d11STodd Fiala     // InferiorCallPOSIX::InferiorCallMmap, which depends on
3403af245d11STodd Fiala     // functional ThreadPlans working with Native*Protocol.
3404af245d11STodd Fiala #if 1
3405af245d11STodd Fiala     return Error ("not implemented yet");
3406af245d11STodd Fiala #else
3407af245d11STodd Fiala     addr = LLDB_INVALID_ADDRESS;
3408af245d11STodd Fiala 
3409af245d11STodd Fiala     unsigned prot = 0;
3410af245d11STodd Fiala     if (permissions & lldb::ePermissionsReadable)
3411af245d11STodd Fiala         prot |= eMmapProtRead;
3412af245d11STodd Fiala     if (permissions & lldb::ePermissionsWritable)
3413af245d11STodd Fiala         prot |= eMmapProtWrite;
3414af245d11STodd Fiala     if (permissions & lldb::ePermissionsExecutable)
3415af245d11STodd Fiala         prot |= eMmapProtExec;
3416af245d11STodd Fiala 
3417af245d11STodd Fiala     // TODO implement this directly in NativeProcessLinux
3418af245d11STodd Fiala     // (and lift to NativeProcessPOSIX if/when that class is
3419af245d11STodd Fiala     // refactored out).
3420af245d11STodd Fiala     if (InferiorCallMmap(this, addr, 0, size, prot,
3421af245d11STodd Fiala                          eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
3422af245d11STodd Fiala         m_addr_to_mmap_size[addr] = size;
3423af245d11STodd Fiala         return Error ();
3424af245d11STodd Fiala     } else {
3425af245d11STodd Fiala         addr = LLDB_INVALID_ADDRESS;
3426af245d11STodd Fiala         return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
3427af245d11STodd Fiala     }
3428af245d11STodd Fiala #endif
3429af245d11STodd Fiala }
3430af245d11STodd Fiala 
3431af245d11STodd Fiala Error
3432af245d11STodd Fiala NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
3433af245d11STodd Fiala {
3434af245d11STodd Fiala     // FIXME see comments in AllocateMemory - required lower-level
3435af245d11STodd Fiala     // bits not in place yet (ThreadPlans)
3436af245d11STodd Fiala     return Error ("not implemented");
3437af245d11STodd Fiala }
3438af245d11STodd Fiala 
3439af245d11STodd Fiala lldb::addr_t
3440af245d11STodd Fiala NativeProcessLinux::GetSharedLibraryInfoAddress ()
3441af245d11STodd Fiala {
3442af245d11STodd Fiala #if 1
3443af245d11STodd Fiala     // punt on this for now
3444af245d11STodd Fiala     return LLDB_INVALID_ADDRESS;
3445af245d11STodd Fiala #else
3446af245d11STodd Fiala     // Return the image info address for the exe module
3447af245d11STodd Fiala #if 1
3448af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3449af245d11STodd Fiala 
3450af245d11STodd Fiala     ModuleSP module_sp;
3451af245d11STodd Fiala     Error error = GetExeModuleSP (module_sp);
3452af245d11STodd Fiala     if (error.Fail ())
3453af245d11STodd Fiala     {
3454af245d11STodd Fiala          if (log)
3455af245d11STodd Fiala             log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ());
3456af245d11STodd Fiala         return LLDB_INVALID_ADDRESS;
3457af245d11STodd Fiala     }
3458af245d11STodd Fiala 
3459af245d11STodd Fiala     if (module_sp == nullptr)
3460af245d11STodd Fiala     {
3461af245d11STodd Fiala          if (log)
3462af245d11STodd Fiala             log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__);
3463af245d11STodd Fiala          return LLDB_INVALID_ADDRESS;
3464af245d11STodd Fiala     }
3465af245d11STodd Fiala 
3466af245d11STodd Fiala     ObjectFileSP object_file_sp = module_sp->GetObjectFile ();
3467af245d11STodd Fiala     if (object_file_sp == nullptr)
3468af245d11STodd Fiala     {
3469af245d11STodd Fiala          if (log)
3470af245d11STodd Fiala             log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__);
3471af245d11STodd Fiala          return LLDB_INVALID_ADDRESS;
3472af245d11STodd Fiala     }
3473af245d11STodd Fiala 
3474af245d11STodd Fiala     return obj_file_sp->GetImageInfoAddress();
3475af245d11STodd Fiala #else
3476af245d11STodd Fiala     Target *target = &GetTarget();
3477af245d11STodd Fiala     ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
3478af245d11STodd Fiala     Address addr = obj_file->GetImageInfoAddress(target);
3479af245d11STodd Fiala 
3480af245d11STodd Fiala     if (addr.IsValid())
3481af245d11STodd Fiala         return addr.GetLoadAddress(target);
3482af245d11STodd Fiala     return LLDB_INVALID_ADDRESS;
3483af245d11STodd Fiala #endif
3484af245d11STodd Fiala #endif // punt on this for now
3485af245d11STodd Fiala }
3486af245d11STodd Fiala 
3487af245d11STodd Fiala size_t
3488af245d11STodd Fiala NativeProcessLinux::UpdateThreads ()
3489af245d11STodd Fiala {
3490af245d11STodd Fiala     // The NativeProcessLinux monitoring threads are always up to date
3491af245d11STodd Fiala     // with respect to thread state and they keep the thread list
3492af245d11STodd Fiala     // populated properly. All this method needs to do is return the
3493af245d11STodd Fiala     // thread count.
3494af245d11STodd Fiala     Mutex::Locker locker (m_threads_mutex);
3495af245d11STodd Fiala     return m_threads.size ();
3496af245d11STodd Fiala }
3497af245d11STodd Fiala 
3498af245d11STodd Fiala bool
3499af245d11STodd Fiala NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
3500af245d11STodd Fiala {
3501af245d11STodd Fiala     arch = m_arch;
3502af245d11STodd Fiala     return true;
3503af245d11STodd Fiala }
3504af245d11STodd Fiala 
3505af245d11STodd Fiala Error
350663c8be95STamas Berghammer NativeProcessLinux::GetSoftwareBreakpointPCOffset (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size)
3507af245d11STodd Fiala {
3508af245d11STodd Fiala     // FIXME put this behind a breakpoint protocol class that can be
3509af245d11STodd Fiala     // set per architecture.  Need ARM, MIPS support here.
35102afc5966STodd Fiala     static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
3511af245d11STodd Fiala     static const uint8_t g_i386_opcode [] = { 0xCC };
3512e8659b5dSMohit K. Bhakkad     static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
3513af245d11STodd Fiala 
3514af245d11STodd Fiala     switch (m_arch.GetMachine ())
3515af245d11STodd Fiala     {
35162afc5966STodd Fiala         case llvm::Triple::aarch64:
35172afc5966STodd Fiala             actual_opcode_size = static_cast<uint32_t> (sizeof(g_aarch64_opcode));
35182afc5966STodd Fiala             return Error ();
35192afc5966STodd Fiala 
352063c8be95STamas Berghammer         case llvm::Triple::arm:
352163c8be95STamas Berghammer             actual_opcode_size = 0; // On arm the PC don't get updated for breakpoint hits
352263c8be95STamas Berghammer             return Error ();
352363c8be95STamas Berghammer 
3524af245d11STodd Fiala         case llvm::Triple::x86:
3525af245d11STodd Fiala         case llvm::Triple::x86_64:
3526af245d11STodd Fiala             actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
3527af245d11STodd Fiala             return Error ();
3528af245d11STodd Fiala 
3529e8659b5dSMohit K. Bhakkad         case llvm::Triple::mips64:
3530e8659b5dSMohit K. Bhakkad         case llvm::Triple::mips64el:
3531e8659b5dSMohit K. Bhakkad             actual_opcode_size = static_cast<uint32_t> (sizeof(g_mips64_opcode));
3532e8659b5dSMohit K. Bhakkad             return Error ();
3533e8659b5dSMohit K. Bhakkad 
3534af245d11STodd Fiala         default:
3535af245d11STodd Fiala             assert(false && "CPU type not supported!");
3536af245d11STodd Fiala             return Error ("CPU type not supported");
3537af245d11STodd Fiala     }
3538af245d11STodd Fiala }
3539af245d11STodd Fiala 
3540af245d11STodd Fiala Error
3541af245d11STodd Fiala NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
3542af245d11STodd Fiala {
3543af245d11STodd Fiala     if (hardware)
3544af245d11STodd Fiala         return Error ("NativeProcessLinux does not support hardware breakpoints");
3545af245d11STodd Fiala     else
3546af245d11STodd Fiala         return SetSoftwareBreakpoint (addr, size);
3547af245d11STodd Fiala }
3548af245d11STodd Fiala 
3549af245d11STodd Fiala Error
355063c8be95STamas Berghammer NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint,
355163c8be95STamas Berghammer                                                      size_t &actual_opcode_size,
355263c8be95STamas Berghammer                                                      const uint8_t *&trap_opcode_bytes)
3553af245d11STodd Fiala {
355463c8be95STamas Berghammer     // FIXME put this behind a breakpoint protocol class that can be set per
355563c8be95STamas Berghammer     // architecture.  Need MIPS support here.
35562afc5966STodd Fiala     static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
355763c8be95STamas Berghammer     // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
355863c8be95STamas Berghammer     // linux kernel does otherwise.
355963c8be95STamas Berghammer     static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 };
3560af245d11STodd Fiala     static const uint8_t g_i386_opcode [] = { 0xCC };
35613df471c3SMohit K. Bhakkad     static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
35622c2acf96SMohit K. Bhakkad     static const uint8_t g_mips64el_opcode[] = { 0x0d, 0x00, 0x00, 0x00 };
356363c8be95STamas Berghammer     static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde };
3564af245d11STodd Fiala 
3565af245d11STodd Fiala     switch (m_arch.GetMachine ())
3566af245d11STodd Fiala     {
35672afc5966STodd Fiala     case llvm::Triple::aarch64:
35682afc5966STodd Fiala         trap_opcode_bytes = g_aarch64_opcode;
35692afc5966STodd Fiala         actual_opcode_size = sizeof(g_aarch64_opcode);
35702afc5966STodd Fiala         return Error ();
35712afc5966STodd Fiala 
357263c8be95STamas Berghammer     case llvm::Triple::arm:
357363c8be95STamas Berghammer         switch (trap_opcode_size_hint)
357463c8be95STamas Berghammer         {
357563c8be95STamas Berghammer         case 2:
357663c8be95STamas Berghammer             trap_opcode_bytes = g_thumb_breakpoint_opcode;
357763c8be95STamas Berghammer             actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
357863c8be95STamas Berghammer             return Error ();
357963c8be95STamas Berghammer         case 4:
358063c8be95STamas Berghammer             trap_opcode_bytes = g_arm_breakpoint_opcode;
358163c8be95STamas Berghammer             actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
358263c8be95STamas Berghammer             return Error ();
358363c8be95STamas Berghammer         default:
358463c8be95STamas Berghammer             assert(false && "Unrecognised trap opcode size hint!");
358563c8be95STamas Berghammer             return Error ("Unrecognised trap opcode size hint!");
358663c8be95STamas Berghammer         }
358763c8be95STamas Berghammer 
3588af245d11STodd Fiala     case llvm::Triple::x86:
3589af245d11STodd Fiala     case llvm::Triple::x86_64:
3590af245d11STodd Fiala         trap_opcode_bytes = g_i386_opcode;
3591af245d11STodd Fiala         actual_opcode_size = sizeof(g_i386_opcode);
3592af245d11STodd Fiala         return Error ();
3593af245d11STodd Fiala 
35943df471c3SMohit K. Bhakkad     case llvm::Triple::mips64:
35953df471c3SMohit K. Bhakkad         trap_opcode_bytes = g_mips64_opcode;
35963df471c3SMohit K. Bhakkad         actual_opcode_size = sizeof(g_mips64_opcode);
35973df471c3SMohit K. Bhakkad         return Error ();
35983df471c3SMohit K. Bhakkad 
35992c2acf96SMohit K. Bhakkad     case llvm::Triple::mips64el:
36002c2acf96SMohit K. Bhakkad         trap_opcode_bytes = g_mips64el_opcode;
36012c2acf96SMohit K. Bhakkad         actual_opcode_size = sizeof(g_mips64el_opcode);
36022c2acf96SMohit K. Bhakkad         return Error ();
36032c2acf96SMohit K. Bhakkad 
3604af245d11STodd Fiala     default:
3605af245d11STodd Fiala         assert(false && "CPU type not supported!");
3606af245d11STodd Fiala         return Error ("CPU type not supported");
3607af245d11STodd Fiala     }
3608af245d11STodd Fiala }
3609af245d11STodd Fiala 
3610af245d11STodd Fiala #if 0
3611af245d11STodd Fiala ProcessMessage::CrashReason
3612af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
3613af245d11STodd Fiala {
3614af245d11STodd Fiala     ProcessMessage::CrashReason reason;
3615af245d11STodd Fiala     assert(info->si_signo == SIGSEGV);
3616af245d11STodd Fiala 
3617af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
3618af245d11STodd Fiala 
3619af245d11STodd Fiala     switch (info->si_code)
3620af245d11STodd Fiala     {
3621af245d11STodd Fiala     default:
3622af245d11STodd Fiala         assert(false && "unexpected si_code for SIGSEGV");
3623af245d11STodd Fiala         break;
3624af245d11STodd Fiala     case SI_KERNEL:
3625af245d11STodd Fiala         // Linux will occasionally send spurious SI_KERNEL codes.
3626af245d11STodd Fiala         // (this is poorly documented in sigaction)
3627af245d11STodd Fiala         // One way to get this is via unaligned SIMD loads.
3628af245d11STodd Fiala         reason = ProcessMessage::eInvalidAddress; // for lack of anything better
3629af245d11STodd Fiala         break;
3630af245d11STodd Fiala     case SEGV_MAPERR:
3631af245d11STodd Fiala         reason = ProcessMessage::eInvalidAddress;
3632af245d11STodd Fiala         break;
3633af245d11STodd Fiala     case SEGV_ACCERR:
3634af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedAddress;
3635af245d11STodd Fiala         break;
3636af245d11STodd Fiala     }
3637af245d11STodd Fiala 
3638af245d11STodd Fiala     return reason;
3639af245d11STodd Fiala }
3640af245d11STodd Fiala #endif
3641af245d11STodd Fiala 
3642af245d11STodd Fiala 
3643af245d11STodd Fiala #if 0
3644af245d11STodd Fiala ProcessMessage::CrashReason
3645af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
3646af245d11STodd Fiala {
3647af245d11STodd Fiala     ProcessMessage::CrashReason reason;
3648af245d11STodd Fiala     assert(info->si_signo == SIGILL);
3649af245d11STodd Fiala 
3650af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
3651af245d11STodd Fiala 
3652af245d11STodd Fiala     switch (info->si_code)
3653af245d11STodd Fiala     {
3654af245d11STodd Fiala     default:
3655af245d11STodd Fiala         assert(false && "unexpected si_code for SIGILL");
3656af245d11STodd Fiala         break;
3657af245d11STodd Fiala     case ILL_ILLOPC:
3658af245d11STodd Fiala         reason = ProcessMessage::eIllegalOpcode;
3659af245d11STodd Fiala         break;
3660af245d11STodd Fiala     case ILL_ILLOPN:
3661af245d11STodd Fiala         reason = ProcessMessage::eIllegalOperand;
3662af245d11STodd Fiala         break;
3663af245d11STodd Fiala     case ILL_ILLADR:
3664af245d11STodd Fiala         reason = ProcessMessage::eIllegalAddressingMode;
3665af245d11STodd Fiala         break;
3666af245d11STodd Fiala     case ILL_ILLTRP:
3667af245d11STodd Fiala         reason = ProcessMessage::eIllegalTrap;
3668af245d11STodd Fiala         break;
3669af245d11STodd Fiala     case ILL_PRVOPC:
3670af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedOpcode;
3671af245d11STodd Fiala         break;
3672af245d11STodd Fiala     case ILL_PRVREG:
3673af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedRegister;
3674af245d11STodd Fiala         break;
3675af245d11STodd Fiala     case ILL_COPROC:
3676af245d11STodd Fiala         reason = ProcessMessage::eCoprocessorError;
3677af245d11STodd Fiala         break;
3678af245d11STodd Fiala     case ILL_BADSTK:
3679af245d11STodd Fiala         reason = ProcessMessage::eInternalStackError;
3680af245d11STodd Fiala         break;
3681af245d11STodd Fiala     }
3682af245d11STodd Fiala 
3683af245d11STodd Fiala     return reason;
3684af245d11STodd Fiala }
3685af245d11STodd Fiala #endif
3686af245d11STodd Fiala 
3687af245d11STodd Fiala #if 0
3688af245d11STodd Fiala ProcessMessage::CrashReason
3689af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
3690af245d11STodd Fiala {
3691af245d11STodd Fiala     ProcessMessage::CrashReason reason;
3692af245d11STodd Fiala     assert(info->si_signo == SIGFPE);
3693af245d11STodd Fiala 
3694af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
3695af245d11STodd Fiala 
3696af245d11STodd Fiala     switch (info->si_code)
3697af245d11STodd Fiala     {
3698af245d11STodd Fiala     default:
3699af245d11STodd Fiala         assert(false && "unexpected si_code for SIGFPE");
3700af245d11STodd Fiala         break;
3701af245d11STodd Fiala     case FPE_INTDIV:
3702af245d11STodd Fiala         reason = ProcessMessage::eIntegerDivideByZero;
3703af245d11STodd Fiala         break;
3704af245d11STodd Fiala     case FPE_INTOVF:
3705af245d11STodd Fiala         reason = ProcessMessage::eIntegerOverflow;
3706af245d11STodd Fiala         break;
3707af245d11STodd Fiala     case FPE_FLTDIV:
3708af245d11STodd Fiala         reason = ProcessMessage::eFloatDivideByZero;
3709af245d11STodd Fiala         break;
3710af245d11STodd Fiala     case FPE_FLTOVF:
3711af245d11STodd Fiala         reason = ProcessMessage::eFloatOverflow;
3712af245d11STodd Fiala         break;
3713af245d11STodd Fiala     case FPE_FLTUND:
3714af245d11STodd Fiala         reason = ProcessMessage::eFloatUnderflow;
3715af245d11STodd Fiala         break;
3716af245d11STodd Fiala     case FPE_FLTRES:
3717af245d11STodd Fiala         reason = ProcessMessage::eFloatInexactResult;
3718af245d11STodd Fiala         break;
3719af245d11STodd Fiala     case FPE_FLTINV:
3720af245d11STodd Fiala         reason = ProcessMessage::eFloatInvalidOperation;
3721af245d11STodd Fiala         break;
3722af245d11STodd Fiala     case FPE_FLTSUB:
3723af245d11STodd Fiala         reason = ProcessMessage::eFloatSubscriptRange;
3724af245d11STodd Fiala         break;
3725af245d11STodd Fiala     }
3726af245d11STodd Fiala 
3727af245d11STodd Fiala     return reason;
3728af245d11STodd Fiala }
3729af245d11STodd Fiala #endif
3730af245d11STodd Fiala 
3731af245d11STodd Fiala #if 0
3732af245d11STodd Fiala ProcessMessage::CrashReason
3733af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
3734af245d11STodd Fiala {
3735af245d11STodd Fiala     ProcessMessage::CrashReason reason;
3736af245d11STodd Fiala     assert(info->si_signo == SIGBUS);
3737af245d11STodd Fiala 
3738af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
3739af245d11STodd Fiala 
3740af245d11STodd Fiala     switch (info->si_code)
3741af245d11STodd Fiala     {
3742af245d11STodd Fiala     default:
3743af245d11STodd Fiala         assert(false && "unexpected si_code for SIGBUS");
3744af245d11STodd Fiala         break;
3745af245d11STodd Fiala     case BUS_ADRALN:
3746af245d11STodd Fiala         reason = ProcessMessage::eIllegalAlignment;
3747af245d11STodd Fiala         break;
3748af245d11STodd Fiala     case BUS_ADRERR:
3749af245d11STodd Fiala         reason = ProcessMessage::eIllegalAddress;
3750af245d11STodd Fiala         break;
3751af245d11STodd Fiala     case BUS_OBJERR:
3752af245d11STodd Fiala         reason = ProcessMessage::eHardwareError;
3753af245d11STodd Fiala         break;
3754af245d11STodd Fiala     }
3755af245d11STodd Fiala 
3756af245d11STodd Fiala     return reason;
3757af245d11STodd Fiala }
3758af245d11STodd Fiala #endif
3759af245d11STodd Fiala 
3760af245d11STodd Fiala Error
376145f5cb31SPavel Labath NativeProcessLinux::SetWatchpoint (lldb::addr_t addr, size_t size, uint32_t watch_flags, bool hardware)
376245f5cb31SPavel Labath {
376345f5cb31SPavel Labath     // The base SetWatchpoint will end up executing monitor operations. Let's lock the monitor
376445f5cb31SPavel Labath     // for it.
376545f5cb31SPavel Labath     Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
376645f5cb31SPavel Labath     return NativeProcessProtocol::SetWatchpoint(addr, size, watch_flags, hardware);
376745f5cb31SPavel Labath }
376845f5cb31SPavel Labath 
376945f5cb31SPavel Labath Error
377045f5cb31SPavel Labath NativeProcessLinux::RemoveWatchpoint (lldb::addr_t addr)
377145f5cb31SPavel Labath {
377245f5cb31SPavel Labath     // The base RemoveWatchpoint will end up executing monitor operations. Let's lock the monitor
377345f5cb31SPavel Labath     // for it.
377445f5cb31SPavel Labath     Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
377545f5cb31SPavel Labath     return NativeProcessProtocol::RemoveWatchpoint(addr);
377645f5cb31SPavel Labath }
377745f5cb31SPavel Labath 
377845f5cb31SPavel Labath Error
377926438d26SChaoren Lin NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
3780af245d11STodd Fiala {
3781af245d11STodd Fiala     ReadOperation op(addr, buf, size, bytes_read);
3782bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
3783af245d11STodd Fiala     return op.GetError ();
3784af245d11STodd Fiala }
3785af245d11STodd Fiala 
3786af245d11STodd Fiala Error
37873eb4b458SChaoren Lin NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
37883eb4b458SChaoren Lin {
37893eb4b458SChaoren Lin     Error error = ReadMemory(addr, buf, size, bytes_read);
37903eb4b458SChaoren Lin     if (error.Fail()) return error;
37913eb4b458SChaoren Lin     return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
37923eb4b458SChaoren Lin }
37933eb4b458SChaoren Lin 
37943eb4b458SChaoren Lin Error
37953eb4b458SChaoren Lin NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written)
3796af245d11STodd Fiala {
3797af245d11STodd Fiala     WriteOperation op(addr, buf, size, bytes_written);
3798bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
3799af245d11STodd Fiala     return op.GetError ();
3800af245d11STodd Fiala }
3801af245d11STodd Fiala 
380297ccc294SChaoren Lin Error
3803af245d11STodd Fiala NativeProcessLinux::ReadRegisterValue(lldb::tid_t tid, uint32_t offset, const char* reg_name,
3804af245d11STodd Fiala                                       uint32_t size, RegisterValue &value)
3805af245d11STodd Fiala {
380697ccc294SChaoren Lin     ReadRegOperation op(tid, offset, reg_name, value);
3807bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
380897ccc294SChaoren Lin     return op.GetError();
3809af245d11STodd Fiala }
3810af245d11STodd Fiala 
381197ccc294SChaoren Lin Error
3812af245d11STodd Fiala NativeProcessLinux::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
3813af245d11STodd Fiala                                    const char* reg_name, const RegisterValue &value)
3814af245d11STodd Fiala {
381597ccc294SChaoren Lin     WriteRegOperation op(tid, offset, reg_name, value);
3816bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
381797ccc294SChaoren Lin     return op.GetError();
3818af245d11STodd Fiala }
3819af245d11STodd Fiala 
382097ccc294SChaoren Lin Error
3821af245d11STodd Fiala NativeProcessLinux::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3822af245d11STodd Fiala {
382397ccc294SChaoren Lin     ReadGPROperation op(tid, buf, buf_size);
3824bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
382597ccc294SChaoren Lin     return op.GetError();
3826af245d11STodd Fiala }
3827af245d11STodd Fiala 
382897ccc294SChaoren Lin Error
3829af245d11STodd Fiala NativeProcessLinux::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3830af245d11STodd Fiala {
383197ccc294SChaoren Lin     ReadFPROperation op(tid, buf, buf_size);
3832bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
383397ccc294SChaoren Lin     return op.GetError();
3834af245d11STodd Fiala }
3835af245d11STodd Fiala 
383697ccc294SChaoren Lin Error
3837af245d11STodd Fiala NativeProcessLinux::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3838af245d11STodd Fiala {
383997ccc294SChaoren Lin     ReadRegisterSetOperation op(tid, buf, buf_size, regset);
3840bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
384197ccc294SChaoren Lin     return op.GetError();
3842af245d11STodd Fiala }
3843af245d11STodd Fiala 
384497ccc294SChaoren Lin Error
3845af245d11STodd Fiala NativeProcessLinux::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3846af245d11STodd Fiala {
384797ccc294SChaoren Lin     WriteGPROperation op(tid, buf, buf_size);
3848bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
384997ccc294SChaoren Lin     return op.GetError();
3850af245d11STodd Fiala }
3851af245d11STodd Fiala 
385297ccc294SChaoren Lin Error
3853af245d11STodd Fiala NativeProcessLinux::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3854af245d11STodd Fiala {
385597ccc294SChaoren Lin     WriteFPROperation op(tid, buf, buf_size);
3856bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
385797ccc294SChaoren Lin     return op.GetError();
3858af245d11STodd Fiala }
3859af245d11STodd Fiala 
386097ccc294SChaoren Lin Error
3861af245d11STodd Fiala NativeProcessLinux::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3862af245d11STodd Fiala {
386397ccc294SChaoren Lin     WriteRegisterSetOperation op(tid, buf, buf_size, regset);
3864bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
386597ccc294SChaoren Lin     return op.GetError();
3866af245d11STodd Fiala }
3867af245d11STodd Fiala 
386897ccc294SChaoren Lin Error
3869af245d11STodd Fiala NativeProcessLinux::Resume (lldb::tid_t tid, uint32_t signo)
3870af245d11STodd Fiala {
3871af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3872af245d11STodd Fiala 
3873af245d11STodd Fiala     if (log)
3874af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s() resuming thread = %"  PRIu64 " with signal %s", __FUNCTION__, tid,
3875af245d11STodd Fiala                                  GetUnixSignals().GetSignalAsCString (signo));
387697ccc294SChaoren Lin     ResumeOperation op (tid, signo);
3877bd7cbc5aSPavel Labath     m_monitor_up->DoOperation (&op);
3878af245d11STodd Fiala     if (log)
387997ccc294SChaoren Lin         log->Printf ("NativeProcessLinux::%s() resuming thread = %"  PRIu64 " result = %s", __FUNCTION__, tid, op.GetError().Success() ? "true" : "false");
388097ccc294SChaoren Lin     return op.GetError();
3881af245d11STodd Fiala }
3882af245d11STodd Fiala 
388397ccc294SChaoren Lin Error
3884af245d11STodd Fiala NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo)
3885af245d11STodd Fiala {
388697ccc294SChaoren Lin     SingleStepOperation op(tid, signo);
3887bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
388897ccc294SChaoren Lin     return op.GetError();
3889af245d11STodd Fiala }
3890af245d11STodd Fiala 
389197ccc294SChaoren Lin Error
389297ccc294SChaoren Lin NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
3893af245d11STodd Fiala {
389497ccc294SChaoren Lin     SiginfoOperation op(tid, siginfo);
3895bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
389697ccc294SChaoren Lin     return op.GetError();
3897af245d11STodd Fiala }
3898af245d11STodd Fiala 
389997ccc294SChaoren Lin Error
3900af245d11STodd Fiala NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
3901af245d11STodd Fiala {
390297ccc294SChaoren Lin     EventMessageOperation op(tid, message);
3903bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
390497ccc294SChaoren Lin     return op.GetError();
3905af245d11STodd Fiala }
3906af245d11STodd Fiala 
3907db264a6dSTamas Berghammer Error
3908af245d11STodd Fiala NativeProcessLinux::Detach(lldb::tid_t tid)
3909af245d11STodd Fiala {
391097ccc294SChaoren Lin     if (tid == LLDB_INVALID_THREAD_ID)
391197ccc294SChaoren Lin         return Error();
391297ccc294SChaoren Lin 
391397ccc294SChaoren Lin     DetachOperation op(tid);
3914bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
391597ccc294SChaoren Lin     return op.GetError();
3916af245d11STodd Fiala }
3917af245d11STodd Fiala 
3918af245d11STodd Fiala bool
3919af245d11STodd Fiala NativeProcessLinux::DupDescriptor(const char *path, int fd, int flags)
3920af245d11STodd Fiala {
3921af245d11STodd Fiala     int target_fd = open(path, flags, 0666);
3922af245d11STodd Fiala 
3923af245d11STodd Fiala     if (target_fd == -1)
3924af245d11STodd Fiala         return false;
3925af245d11STodd Fiala 
3926493c3a12SPavel Labath     if (dup2(target_fd, fd) == -1)
3927493c3a12SPavel Labath         return false;
3928493c3a12SPavel Labath 
3929493c3a12SPavel Labath     return (close(target_fd) == -1) ? false : true;
3930af245d11STodd Fiala }
3931af245d11STodd Fiala 
3932af245d11STodd Fiala void
3933bd7cbc5aSPavel Labath NativeProcessLinux::StartMonitorThread(const InitialOperation &initial_operation, Error &error)
3934af245d11STodd Fiala {
3935bd7cbc5aSPavel Labath     m_monitor_up.reset(new Monitor(initial_operation, this));
39361107b5a5SPavel Labath     error = m_monitor_up->Initialize();
39371107b5a5SPavel Labath     if (error.Fail()) {
39381107b5a5SPavel Labath         m_monitor_up.reset();
3939af245d11STodd Fiala     }
3940af245d11STodd Fiala }
3941af245d11STodd Fiala 
3942af245d11STodd Fiala bool
3943af245d11STodd Fiala NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
3944af245d11STodd Fiala {
3945af245d11STodd Fiala     for (auto thread_sp : m_threads)
3946af245d11STodd Fiala     {
3947af245d11STodd Fiala         assert (thread_sp && "thread list should not contain NULL threads");
3948af245d11STodd Fiala         if (thread_sp->GetID () == thread_id)
3949af245d11STodd Fiala         {
3950af245d11STodd Fiala             // We have this thread.
3951af245d11STodd Fiala             return true;
3952af245d11STodd Fiala         }
3953af245d11STodd Fiala     }
3954af245d11STodd Fiala 
3955af245d11STodd Fiala     // We don't have this thread.
3956af245d11STodd Fiala     return false;
3957af245d11STodd Fiala }
3958af245d11STodd Fiala 
3959af245d11STodd Fiala NativeThreadProtocolSP
3960af245d11STodd Fiala NativeProcessLinux::MaybeGetThreadNoLock (lldb::tid_t thread_id)
3961af245d11STodd Fiala {
3962af245d11STodd Fiala     // CONSIDER organize threads by map - we can do better than linear.
3963af245d11STodd Fiala     for (auto thread_sp : m_threads)
3964af245d11STodd Fiala     {
3965af245d11STodd Fiala         if (thread_sp->GetID () == thread_id)
3966af245d11STodd Fiala             return thread_sp;
3967af245d11STodd Fiala     }
3968af245d11STodd Fiala 
3969af245d11STodd Fiala     // We don't have this thread.
3970af245d11STodd Fiala     return NativeThreadProtocolSP ();
3971af245d11STodd Fiala }
3972af245d11STodd Fiala 
3973af245d11STodd Fiala bool
3974af245d11STodd Fiala NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
3975af245d11STodd Fiala {
39761dbc6c9cSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
39771dbc6c9cSPavel Labath 
39781dbc6c9cSPavel Labath     if (log)
39791dbc6c9cSPavel Labath         log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, thread_id);
39801dbc6c9cSPavel Labath 
39811dbc6c9cSPavel Labath     bool found = false;
39821dbc6c9cSPavel Labath 
3983af245d11STodd Fiala     Mutex::Locker locker (m_threads_mutex);
3984af245d11STodd Fiala     for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
3985af245d11STodd Fiala     {
3986af245d11STodd Fiala         if (*it && ((*it)->GetID () == thread_id))
3987af245d11STodd Fiala         {
3988af245d11STodd Fiala             m_threads.erase (it);
39891dbc6c9cSPavel Labath             found = true;
39901dbc6c9cSPavel Labath             break;
3991af245d11STodd Fiala         }
3992af245d11STodd Fiala     }
3993af245d11STodd Fiala 
39941dbc6c9cSPavel Labath     // If we have a pending notification, remove this from the set.
39951dbc6c9cSPavel Labath     if (m_pending_notification_up)
39961dbc6c9cSPavel Labath     {
39971dbc6c9cSPavel Labath         m_pending_notification_up->wait_for_stop_tids.erase(thread_id);
39981dbc6c9cSPavel Labath         SignalIfRequirementsSatisfied();
39991dbc6c9cSPavel Labath     }
40001dbc6c9cSPavel Labath 
40011dbc6c9cSPavel Labath     return found;
4002af245d11STodd Fiala }
4003af245d11STodd Fiala 
4004af245d11STodd Fiala NativeThreadProtocolSP
4005af245d11STodd Fiala NativeProcessLinux::AddThread (lldb::tid_t thread_id)
4006af245d11STodd Fiala {
4007af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
4008af245d11STodd Fiala 
4009af245d11STodd Fiala     Mutex::Locker locker (m_threads_mutex);
4010af245d11STodd Fiala 
4011af245d11STodd Fiala     if (log)
4012af245d11STodd Fiala     {
4013af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
4014af245d11STodd Fiala                 __FUNCTION__,
4015af245d11STodd Fiala                 GetID (),
4016af245d11STodd Fiala                 thread_id);
4017af245d11STodd Fiala     }
4018af245d11STodd Fiala 
4019af245d11STodd Fiala     assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
4020af245d11STodd Fiala 
4021af245d11STodd Fiala     // If this is the first thread, save it as the current thread
4022af245d11STodd Fiala     if (m_threads.empty ())
4023af245d11STodd Fiala         SetCurrentThreadID (thread_id);
4024af245d11STodd Fiala 
4025af245d11STodd Fiala     NativeThreadProtocolSP thread_sp (new NativeThreadLinux (this, thread_id));
4026af245d11STodd Fiala     m_threads.push_back (thread_sp);
4027af245d11STodd Fiala 
4028af245d11STodd Fiala     return thread_sp;
4029af245d11STodd Fiala }
4030af245d11STodd Fiala 
4031af245d11STodd Fiala Error
4032af245d11STodd Fiala NativeProcessLinux::FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp)
4033af245d11STodd Fiala {
403475f47c3aSTodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
4035af245d11STodd Fiala 
4036af245d11STodd Fiala     Error error;
4037af245d11STodd Fiala 
4038af245d11STodd Fiala     // Get a linux thread pointer.
4039af245d11STodd Fiala     if (!thread_sp)
4040af245d11STodd Fiala     {
4041af245d11STodd Fiala         error.SetErrorString ("null thread_sp");
4042af245d11STodd Fiala         if (log)
4043af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
4044af245d11STodd Fiala         return error;
4045af245d11STodd Fiala     }
4046cb84eebbSTamas Berghammer     std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
4047af245d11STodd Fiala 
4048af245d11STodd Fiala     // Find out the size of a breakpoint (might depend on where we are in the code).
4049cb84eebbSTamas Berghammer     NativeRegisterContextSP context_sp = linux_thread_sp->GetRegisterContext ();
4050af245d11STodd Fiala     if (!context_sp)
4051af245d11STodd Fiala     {
4052af245d11STodd Fiala         error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
4053af245d11STodd Fiala         if (log)
4054af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
4055af245d11STodd Fiala         return error;
4056af245d11STodd Fiala     }
4057af245d11STodd Fiala 
4058af245d11STodd Fiala     uint32_t breakpoint_size = 0;
405963c8be95STamas Berghammer     error = GetSoftwareBreakpointPCOffset (context_sp, breakpoint_size);
4060af245d11STodd Fiala     if (error.Fail ())
4061af245d11STodd Fiala     {
4062af245d11STodd Fiala         if (log)
4063af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
4064af245d11STodd Fiala         return error;
4065af245d11STodd Fiala     }
4066af245d11STodd Fiala     else
4067af245d11STodd Fiala     {
4068af245d11STodd Fiala         if (log)
4069af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
4070af245d11STodd Fiala     }
4071af245d11STodd Fiala 
4072af245d11STodd Fiala     // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
4073af245d11STodd Fiala     const lldb::addr_t initial_pc_addr = context_sp->GetPC ();
4074af245d11STodd Fiala     lldb::addr_t breakpoint_addr = initial_pc_addr;
40753eb4b458SChaoren Lin     if (breakpoint_size > 0)
4076af245d11STodd Fiala     {
4077af245d11STodd Fiala         // Do not allow breakpoint probe to wrap around.
40783eb4b458SChaoren Lin         if (breakpoint_addr >= breakpoint_size)
40793eb4b458SChaoren Lin             breakpoint_addr -= breakpoint_size;
4080af245d11STodd Fiala     }
4081af245d11STodd Fiala 
4082af245d11STodd Fiala     // Check if we stopped because of a breakpoint.
4083af245d11STodd Fiala     NativeBreakpointSP breakpoint_sp;
4084af245d11STodd Fiala     error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
4085af245d11STodd Fiala     if (!error.Success () || !breakpoint_sp)
4086af245d11STodd Fiala     {
4087af245d11STodd Fiala         // We didn't find one at a software probe location.  Nothing to do.
4088af245d11STodd Fiala         if (log)
4089af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
4090af245d11STodd Fiala         return Error ();
4091af245d11STodd Fiala     }
4092af245d11STodd Fiala 
4093af245d11STodd Fiala     // If the breakpoint is not a software breakpoint, nothing to do.
4094af245d11STodd Fiala     if (!breakpoint_sp->IsSoftwareBreakpoint ())
4095af245d11STodd Fiala     {
4096af245d11STodd Fiala         if (log)
4097af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
4098af245d11STodd Fiala         return Error ();
4099af245d11STodd Fiala     }
4100af245d11STodd Fiala 
4101af245d11STodd Fiala     //
4102af245d11STodd Fiala     // We have a software breakpoint and need to adjust the PC.
4103af245d11STodd Fiala     //
4104af245d11STodd Fiala 
4105af245d11STodd Fiala     // Sanity check.
4106af245d11STodd Fiala     if (breakpoint_size == 0)
4107af245d11STodd Fiala     {
4108af245d11STodd Fiala         // Nothing to do!  How did we get here?
4109af245d11STodd Fiala         if (log)
4110af245d11STodd 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);
4111af245d11STodd Fiala         return Error ();
4112af245d11STodd Fiala     }
4113af245d11STodd Fiala 
4114af245d11STodd Fiala     // Change the program counter.
4115af245d11STodd Fiala     if (log)
4116cb84eebbSTamas 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);
4117af245d11STodd Fiala 
4118af245d11STodd Fiala     error = context_sp->SetPC (breakpoint_addr);
4119af245d11STodd Fiala     if (error.Fail ())
4120af245d11STodd Fiala     {
4121af245d11STodd Fiala         if (log)
4122cb84eebbSTamas Berghammer             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": failed to set PC: %s", __FUNCTION__, GetID (), linux_thread_sp->GetID (), error.AsCString ());
4123af245d11STodd Fiala         return error;
4124af245d11STodd Fiala     }
4125af245d11STodd Fiala 
4126af245d11STodd Fiala     return error;
4127af245d11STodd Fiala }
4128fa03ad2eSChaoren Lin 
41297cb18bf5STamas Berghammer Error
41307cb18bf5STamas Berghammer NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec)
41317cb18bf5STamas Berghammer {
41327cb18bf5STamas Berghammer     char maps_file_name[32];
41337cb18bf5STamas Berghammer     snprintf(maps_file_name, sizeof(maps_file_name), "/proc/%" PRIu64 "/maps", GetID());
41347cb18bf5STamas Berghammer 
41357cb18bf5STamas Berghammer     FileSpec maps_file_spec(maps_file_name, false);
41367cb18bf5STamas Berghammer     if (!maps_file_spec.Exists()) {
41377cb18bf5STamas Berghammer         file_spec.Clear();
41387cb18bf5STamas Berghammer         return Error("/proc/%" PRIu64 "/maps file doesn't exists!", GetID());
41397cb18bf5STamas Berghammer     }
41407cb18bf5STamas Berghammer 
41417cb18bf5STamas Berghammer     FileSpec module_file_spec(module_path, true);
41427cb18bf5STamas Berghammer 
41437cb18bf5STamas Berghammer     std::ifstream maps_file(maps_file_name);
41447cb18bf5STamas Berghammer     std::string maps_data_str((std::istreambuf_iterator<char>(maps_file)), std::istreambuf_iterator<char>());
41457cb18bf5STamas Berghammer     StringRef maps_data(maps_data_str.c_str());
41467cb18bf5STamas Berghammer 
41477cb18bf5STamas Berghammer     while (!maps_data.empty())
41487cb18bf5STamas Berghammer     {
41497cb18bf5STamas Berghammer         StringRef maps_row;
41507cb18bf5STamas Berghammer         std::tie(maps_row, maps_data) = maps_data.split('\n');
41517cb18bf5STamas Berghammer 
41527cb18bf5STamas Berghammer         SmallVector<StringRef, 16> maps_columns;
41537cb18bf5STamas Berghammer         maps_row.split(maps_columns, StringRef(" "), -1, false);
41547cb18bf5STamas Berghammer 
41557cb18bf5STamas Berghammer         if (maps_columns.size() >= 6)
41567cb18bf5STamas Berghammer         {
41577cb18bf5STamas Berghammer             file_spec.SetFile(maps_columns[5].str().c_str(), false);
41587cb18bf5STamas Berghammer             if (file_spec.GetFilename() == module_file_spec.GetFilename())
41597cb18bf5STamas Berghammer                 return Error();
41607cb18bf5STamas Berghammer         }
41617cb18bf5STamas Berghammer     }
41627cb18bf5STamas Berghammer 
41637cb18bf5STamas Berghammer     file_spec.Clear();
41647cb18bf5STamas Berghammer     return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
41657cb18bf5STamas Berghammer                  module_file_spec.GetFilename().AsCString(), GetID());
41667cb18bf5STamas Berghammer }
4167c076559aSPavel Labath 
41685eb721edSPavel Labath Error
41691dbc6c9cSPavel Labath NativeProcessLinux::ResumeThread(
4170c076559aSPavel Labath         lldb::tid_t tid,
41718c8ff7afSPavel Labath         NativeThreadLinux::ResumeThreadFunction request_thread_resume_function,
4172c076559aSPavel Labath         bool error_when_already_running)
4173c076559aSPavel Labath {
41745eb721edSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
41755eb721edSPavel Labath 
41761dbc6c9cSPavel Labath     if (log)
41771dbc6c9cSPavel Labath         log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ", error_when_already_running: %s)",
41781dbc6c9cSPavel Labath                 __FUNCTION__, tid, error_when_already_running?"true":"false");
41791dbc6c9cSPavel Labath 
41808c8ff7afSPavel Labath     auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
41818c8ff7afSPavel Labath     lldbassert(thread_sp != nullptr);
41825eb721edSPavel Labath 
41838c8ff7afSPavel Labath     auto& context = thread_sp->GetThreadContext();
4184c076559aSPavel Labath     // Tell the thread to resume if we don't already think it is running.
41858c8ff7afSPavel Labath     const bool is_stopped = StateIsStoppedState(thread_sp->GetState(), true);
41865eb721edSPavel Labath 
41875eb721edSPavel Labath     lldbassert(!(error_when_already_running && !is_stopped));
41885eb721edSPavel Labath 
4189c076559aSPavel Labath     if (!is_stopped)
4190c076559aSPavel Labath     {
4191c076559aSPavel Labath         // It's not an error, just a log, if the error_when_already_running flag is not set.
4192c076559aSPavel Labath         // This covers cases where, for instance, we're just trying to resume all threads
4193c076559aSPavel Labath         // from the user side.
41945eb721edSPavel Labath         if (log)
41955eb721edSPavel Labath             log->Printf("NativeProcessLinux::%s tid %" PRIu64 " optional resume skipped since it is already running",
4196c076559aSPavel Labath                     __FUNCTION__,
4197c076559aSPavel Labath                     tid);
41985eb721edSPavel Labath         return Error();
4199c076559aSPavel Labath     }
4200c076559aSPavel Labath 
4201c076559aSPavel Labath     // Before we do the resume below, first check if we have a pending
4202*108c325dSPavel Labath     // stop notification that is currently waiting for
4203c076559aSPavel Labath     // this thread to stop.  This is potentially a buggy situation since
4204c076559aSPavel Labath     // we're ostensibly waiting for threads to stop before we send out the
4205c076559aSPavel Labath     // pending notification, and here we are resuming one before we send
4206c076559aSPavel Labath     // out the pending stop notification.
4207*108c325dSPavel Labath     if (m_pending_notification_up && log && m_pending_notification_up->wait_for_stop_tids.count (tid) > 0)
4208c076559aSPavel Labath     {
42095eb721edSPavel 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);
4210c076559aSPavel Labath     }
4211c076559aSPavel Labath 
4212c076559aSPavel Labath     // Request a resume.  We expect this to be synchronous and the system
4213c076559aSPavel Labath     // to reflect it is running after this completes.
4214c076559aSPavel Labath     const auto error = request_thread_resume_function (tid, false);
4215c076559aSPavel Labath     if (error.Success())
42168c8ff7afSPavel Labath         context.request_resume_function = request_thread_resume_function;
42175eb721edSPavel Labath     else if (log)
4218c076559aSPavel Labath     {
42195eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s failed to resume thread tid  %" PRIu64 ": %s",
4220c076559aSPavel Labath                          __FUNCTION__, tid, error.AsCString ());
4221c076559aSPavel Labath     }
4222c076559aSPavel Labath 
42235eb721edSPavel Labath     return error;
4224c076559aSPavel Labath }
4225c076559aSPavel Labath 
4226c076559aSPavel Labath //===----------------------------------------------------------------------===//
4227c076559aSPavel Labath 
4228c076559aSPavel Labath void
4229337f3eb9SPavel Labath NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid)
4230c076559aSPavel Labath {
42315eb721edSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
4232c076559aSPavel Labath 
42335eb721edSPavel Labath     if (log)
4234c076559aSPavel Labath     {
42355eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ")",
4236c076559aSPavel Labath                 __FUNCTION__, triggering_tid);
4237c076559aSPavel Labath     }
4238c076559aSPavel Labath 
4239337f3eb9SPavel Labath     DoStopThreads(PendingNotificationUP(new PendingNotification(triggering_tid)));
4240c076559aSPavel Labath 
42415eb721edSPavel Labath     if (log)
4242c076559aSPavel Labath     {
42435eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
4244c076559aSPavel Labath     }
4245c076559aSPavel Labath }
4246c076559aSPavel Labath 
4247c076559aSPavel Labath void
4248c076559aSPavel Labath NativeProcessLinux::SignalIfRequirementsSatisfied()
4249c076559aSPavel Labath {
4250c076559aSPavel Labath     if (m_pending_notification_up && m_pending_notification_up->wait_for_stop_tids.empty ())
4251c076559aSPavel Labath     {
4252ed89c7feSPavel Labath         SetCurrentThreadID(m_pending_notification_up->triggering_tid);
4253ed89c7feSPavel Labath         SetState(StateType::eStateStopped, true);
4254c076559aSPavel Labath         m_pending_notification_up.reset();
4255c076559aSPavel Labath     }
4256c076559aSPavel Labath }
4257c076559aSPavel Labath 
4258c076559aSPavel Labath void
4259c076559aSPavel Labath NativeProcessLinux::RequestStopOnAllRunningThreads()
4260c076559aSPavel Labath {
4261c076559aSPavel Labath     // Request a stop for all the thread stops that need to be stopped
4262c076559aSPavel Labath     // and are not already known to be stopped.  Keep a list of all the
4263c076559aSPavel Labath     // threads from which we still need to hear a stop reply.
4264c076559aSPavel Labath 
4265c076559aSPavel Labath     ThreadIDSet sent_tids;
42668c8ff7afSPavel Labath     for (const auto &thread_sp: m_threads)
4267c076559aSPavel Labath     {
42688c8ff7afSPavel Labath         // We only care about running threads
42698c8ff7afSPavel Labath         if (StateIsStoppedState(thread_sp->GetState(), true))
42708c8ff7afSPavel Labath             continue;
42718c8ff7afSPavel Labath 
42728c8ff7afSPavel Labath         static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
4273*108c325dSPavel Labath         sent_tids.insert (thread_sp->GetID());
4274c076559aSPavel Labath     }
4275c076559aSPavel Labath 
4276c076559aSPavel Labath     // Set the wait list to the set of tids for which we requested stops.
4277c076559aSPavel Labath     m_pending_notification_up->wait_for_stop_tids.swap (sent_tids);
4278c076559aSPavel Labath }
4279c076559aSPavel Labath 
4280c076559aSPavel Labath 
42815eb721edSPavel Labath Error
42825eb721edSPavel Labath NativeProcessLinux::ThreadDidStop (lldb::tid_t tid, bool initiated_by_llgs)
4283c076559aSPavel Labath {
42841dbc6c9cSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
42851dbc6c9cSPavel Labath 
42861dbc6c9cSPavel Labath     if (log)
42871dbc6c9cSPavel Labath         log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ", %sinitiated by llgs)",
42881dbc6c9cSPavel Labath                 __FUNCTION__, tid, initiated_by_llgs?"":"not ");
42891dbc6c9cSPavel Labath 
4290c076559aSPavel Labath     // Ensure we know about the thread.
42918c8ff7afSPavel Labath     auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
42928c8ff7afSPavel Labath     lldbassert(thread_sp != nullptr);
4293c076559aSPavel Labath 
4294c076559aSPavel Labath     // Update the global list of known thread states.  This one is definitely stopped.
42958c8ff7afSPavel Labath     auto& context = thread_sp->GetThreadContext();
42968c8ff7afSPavel Labath     const auto stop_was_requested = context.stop_requested;
42978c8ff7afSPavel Labath     context.stop_requested = false;
4298c076559aSPavel Labath 
4299c076559aSPavel Labath     // If we have a pending notification, remove this from the set.
4300c076559aSPavel Labath     if (m_pending_notification_up)
4301c076559aSPavel Labath     {
4302c076559aSPavel Labath         m_pending_notification_up->wait_for_stop_tids.erase(tid);
4303c076559aSPavel Labath         SignalIfRequirementsSatisfied();
4304c076559aSPavel Labath     }
4305c076559aSPavel Labath 
43068c8ff7afSPavel Labath     Error error;
43078c8ff7afSPavel Labath     if (initiated_by_llgs && context.request_resume_function && !stop_was_requested)
4308c076559aSPavel Labath     {
4309c076559aSPavel Labath         // We can end up here if stop was initiated by LLGS but by this time a
4310c076559aSPavel Labath         // thread stop has occurred - maybe initiated by another event.
43115eb721edSPavel Labath         if (log)
43125eb721edSPavel Labath             log->Printf("Resuming thread %"  PRIu64 " since stop wasn't requested", tid);
43138c8ff7afSPavel Labath         error = context.request_resume_function (tid, true);
43148c8ff7afSPavel Labath         if (error.Fail() && log)
43155eb721edSPavel Labath         {
43165eb721edSPavel Labath                 log->Printf("NativeProcessLinux::%s failed to resume thread tid  %" PRIu64 ": %s",
4317c076559aSPavel Labath                         __FUNCTION__, tid, error.AsCString ());
4318c076559aSPavel Labath         }
43198c8ff7afSPavel Labath     }
43205eb721edSPavel Labath     return error;
4321c076559aSPavel Labath }
4322c076559aSPavel Labath 
4323c076559aSPavel Labath void
4324ed89c7feSPavel Labath NativeProcessLinux::DoStopThreads(PendingNotificationUP &&notification_up)
4325c076559aSPavel Labath {
43265eb721edSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
43275eb721edSPavel Labath     if (m_pending_notification_up && log)
4328c076559aSPavel Labath     {
4329c076559aSPavel Labath         // Yikes - we've already got a pending signal notification in progress.
4330c076559aSPavel Labath         // Log this info.  We lose the pending notification here.
43315eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s dropping existing pending signal notification for tid %" PRIu64 ", to be replaced with signal for tid %" PRIu64,
4332c076559aSPavel Labath                    __FUNCTION__,
4333c076559aSPavel Labath                    m_pending_notification_up->triggering_tid,
4334c076559aSPavel Labath                    notification_up->triggering_tid);
4335c076559aSPavel Labath     }
4336c076559aSPavel Labath     m_pending_notification_up = std::move(notification_up);
4337c076559aSPavel Labath 
4338c076559aSPavel Labath     RequestStopOnAllRunningThreads();
4339c076559aSPavel Labath 
4340ed89c7feSPavel Labath     SignalIfRequirementsSatisfied();
4341c076559aSPavel Labath }
4342c076559aSPavel Labath 
4343c076559aSPavel Labath void
43448c8ff7afSPavel Labath NativeProcessLinux::ThreadWasCreated (lldb::tid_t tid)
4345c076559aSPavel Labath {
43461dbc6c9cSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
43471dbc6c9cSPavel Labath 
43481dbc6c9cSPavel Labath     if (log)
43491dbc6c9cSPavel Labath         log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, tid);
43501dbc6c9cSPavel Labath 
43518c8ff7afSPavel Labath     auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
43528c8ff7afSPavel Labath     lldbassert(thread_sp != nullptr);
4353c076559aSPavel Labath 
43548c8ff7afSPavel Labath     if (m_pending_notification_up && StateIsRunningState(thread_sp->GetState()))
4355c076559aSPavel Labath     {
4356c076559aSPavel Labath         // We will need to wait for this new thread to stop as well before firing the
4357c076559aSPavel Labath         // notification.
4358c076559aSPavel Labath         m_pending_notification_up->wait_for_stop_tids.insert(tid);
43598c8ff7afSPavel Labath         thread_sp->RequestStop();
4360c076559aSPavel Labath     }
4361c076559aSPavel Labath }
4362