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 
765ea8c25a8SOmair Javaid     //------------------------------------------------------------------------------
766ea8c25a8SOmair Javaid     /// @class ReadDBGROperation
767*cdad63b3SOmair Javaid     /// @brief Implements NativeProcessLinux::ReadHardwareDebugInfo.
768ea8c25a8SOmair Javaid     class ReadDBGROperation : public Operation
769ea8c25a8SOmair Javaid     {
770ea8c25a8SOmair Javaid     public:
771ea8c25a8SOmair Javaid         ReadDBGROperation(lldb::tid_t tid, unsigned int &count_wp, unsigned int &count_bp)
772ea8c25a8SOmair Javaid             : m_tid(tid),
773ea8c25a8SOmair Javaid               m_count_wp(count_wp),
774ea8c25a8SOmair Javaid               m_count_bp(count_bp)
775ea8c25a8SOmair Javaid             { }
776ea8c25a8SOmair Javaid 
777ea8c25a8SOmair Javaid         void Execute(NativeProcessLinux *monitor) override;
778ea8c25a8SOmair Javaid 
779ea8c25a8SOmair Javaid     private:
780ea8c25a8SOmair Javaid         lldb::tid_t m_tid;
781ea8c25a8SOmair Javaid         unsigned int &m_count_wp;
782ea8c25a8SOmair Javaid         unsigned int &m_count_bp;
783ea8c25a8SOmair Javaid     };
784ea8c25a8SOmair Javaid 
785ea8c25a8SOmair Javaid     void
786ea8c25a8SOmair Javaid     ReadDBGROperation::Execute(NativeProcessLinux *monitor)
787ea8c25a8SOmair Javaid     {
788*cdad63b3SOmair Javaid #if defined (__arm64__) || defined (__aarch64__)
789ea8c25a8SOmair Javaid        int regset = NT_ARM_HW_WATCH;
790ea8c25a8SOmair Javaid        struct iovec ioVec;
791ea8c25a8SOmair Javaid        struct user_hwdebug_state dreg_state;
792ea8c25a8SOmair Javaid 
793ea8c25a8SOmair Javaid        ioVec.iov_base = &dreg_state;
794ea8c25a8SOmair Javaid        ioVec.iov_len = sizeof (dreg_state);
795ea8c25a8SOmair Javaid 
796ea8c25a8SOmair Javaid        PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, ioVec.iov_len, m_error);
797ea8c25a8SOmair Javaid 
798ea8c25a8SOmair Javaid        m_count_wp = dreg_state.dbg_info & 0xff;
799ea8c25a8SOmair Javaid        regset = NT_ARM_HW_BREAK;
800ea8c25a8SOmair Javaid 
801ea8c25a8SOmair Javaid        PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, ioVec.iov_len, m_error);
802ea8c25a8SOmair Javaid        m_count_bp = dreg_state.dbg_info & 0xff;
803ea8c25a8SOmair Javaid #endif
804*cdad63b3SOmair Javaid     }
805*cdad63b3SOmair Javaid 
806ea8c25a8SOmair Javaid 
807af245d11STodd Fiala     //------------------------------------------------------------------------------
808af245d11STodd Fiala     /// @class ReadRegisterSetOperation
809af245d11STodd Fiala     /// @brief Implements NativeProcessLinux::ReadRegisterSet.
810af245d11STodd Fiala     class ReadRegisterSetOperation : public Operation
811af245d11STodd Fiala     {
812af245d11STodd Fiala     public:
81397ccc294SChaoren Lin         ReadRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
81497ccc294SChaoren Lin             : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset)
815af245d11STodd Fiala             { }
816af245d11STodd Fiala 
817d542efdeSTamas Berghammer         void Execute(NativeProcessLinux *monitor) override;
818af245d11STodd Fiala 
819af245d11STodd Fiala     private:
820af245d11STodd Fiala         lldb::tid_t m_tid;
821af245d11STodd Fiala         void *m_buf;
822af245d11STodd Fiala         size_t m_buf_size;
823af245d11STodd Fiala         const unsigned int m_regset;
824af245d11STodd Fiala     };
825af245d11STodd Fiala 
826af245d11STodd Fiala     void
827af245d11STodd Fiala     ReadRegisterSetOperation::Execute(NativeProcessLinux *monitor)
828af245d11STodd Fiala     {
82997ccc294SChaoren Lin         PTRACE(PTRACE_GETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size, m_error);
830af245d11STodd Fiala     }
831af245d11STodd Fiala 
832af245d11STodd Fiala     //------------------------------------------------------------------------------
833af245d11STodd Fiala     /// @class WriteGPROperation
834af245d11STodd Fiala     /// @brief Implements NativeProcessLinux::WriteGPR.
835af245d11STodd Fiala     class WriteGPROperation : public Operation
836af245d11STodd Fiala     {
837af245d11STodd Fiala     public:
83897ccc294SChaoren Lin         WriteGPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
83997ccc294SChaoren Lin             : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
840af245d11STodd Fiala             { }
841af245d11STodd Fiala 
842d542efdeSTamas Berghammer         void Execute(NativeProcessLinux *monitor) override;
843af245d11STodd Fiala 
844af245d11STodd Fiala     private:
845af245d11STodd Fiala         lldb::tid_t m_tid;
846af245d11STodd Fiala         void *m_buf;
847af245d11STodd Fiala         size_t m_buf_size;
848af245d11STodd Fiala     };
849af245d11STodd Fiala 
850af245d11STodd Fiala     void
851af245d11STodd Fiala     WriteGPROperation::Execute(NativeProcessLinux *monitor)
852af245d11STodd Fiala     {
8536ac1be4bSTodd Fiala #if defined (__arm64__) || defined (__aarch64__)
8546ac1be4bSTodd Fiala         int regset = NT_PRSTATUS;
8556ac1be4bSTodd Fiala         struct iovec ioVec;
8566ac1be4bSTodd Fiala 
8576ac1be4bSTodd Fiala         ioVec.iov_base = m_buf;
8586ac1be4bSTodd Fiala         ioVec.iov_len = m_buf_size;
85997ccc294SChaoren Lin         PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
8606ac1be4bSTodd Fiala #else
86197ccc294SChaoren Lin         PTRACE(PTRACE_SETREGS, m_tid, NULL, m_buf, m_buf_size, m_error);
8626ac1be4bSTodd Fiala #endif
863af245d11STodd Fiala     }
864af245d11STodd Fiala 
865af245d11STodd Fiala     //------------------------------------------------------------------------------
866af245d11STodd Fiala     /// @class WriteFPROperation
867af245d11STodd Fiala     /// @brief Implements NativeProcessLinux::WriteFPR.
868af245d11STodd Fiala     class WriteFPROperation : public Operation
869af245d11STodd Fiala     {
870af245d11STodd Fiala     public:
87197ccc294SChaoren Lin         WriteFPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
87297ccc294SChaoren Lin             : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
873af245d11STodd Fiala             { }
874af245d11STodd Fiala 
875d542efdeSTamas Berghammer         void Execute(NativeProcessLinux *monitor) override;
876af245d11STodd Fiala 
877af245d11STodd Fiala     private:
878af245d11STodd Fiala         lldb::tid_t m_tid;
879af245d11STodd Fiala         void *m_buf;
880af245d11STodd Fiala         size_t m_buf_size;
881af245d11STodd Fiala     };
882af245d11STodd Fiala 
883af245d11STodd Fiala     void
884af245d11STodd Fiala     WriteFPROperation::Execute(NativeProcessLinux *monitor)
885af245d11STodd Fiala     {
8866ac1be4bSTodd Fiala #if defined (__arm64__) || defined (__aarch64__)
8876ac1be4bSTodd Fiala         int regset = NT_FPREGSET;
8886ac1be4bSTodd Fiala         struct iovec ioVec;
8896ac1be4bSTodd Fiala 
8906ac1be4bSTodd Fiala         ioVec.iov_base = m_buf;
8916ac1be4bSTodd Fiala         ioVec.iov_len = m_buf_size;
89297ccc294SChaoren Lin         PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
8936ac1be4bSTodd Fiala #else
89497ccc294SChaoren Lin         PTRACE(PTRACE_SETFPREGS, m_tid, NULL, m_buf, m_buf_size, m_error);
8956ac1be4bSTodd Fiala #endif
896af245d11STodd Fiala     }
897af245d11STodd Fiala 
898ea8c25a8SOmair Javaid     //------------------------------------------------------------------------------
899ea8c25a8SOmair Javaid     /// @class WriteDBGROperation
900*cdad63b3SOmair Javaid     /// @brief Implements NativeProcessLinux::WriteHardwareDebugRegs.
901ea8c25a8SOmair Javaid     class WriteDBGROperation : public Operation
902ea8c25a8SOmair Javaid     {
903ea8c25a8SOmair Javaid     public:
904ea8c25a8SOmair Javaid         WriteDBGROperation(lldb::tid_t tid, lldb::addr_t *addr_buf,
905ea8c25a8SOmair Javaid                            uint32_t *cntrl_buf, int type, int count)
906ea8c25a8SOmair Javaid             : m_tid(tid),
907ea8c25a8SOmair Javaid               m_address(addr_buf),
908ea8c25a8SOmair Javaid               m_control(cntrl_buf),
909ea8c25a8SOmair Javaid               m_type(type),
910ea8c25a8SOmair Javaid               m_count(count)
911ea8c25a8SOmair Javaid             { }
912ea8c25a8SOmair Javaid 
913ea8c25a8SOmair Javaid         void Execute(NativeProcessLinux *monitor) override;
914ea8c25a8SOmair Javaid 
915ea8c25a8SOmair Javaid     private:
916ea8c25a8SOmair Javaid         lldb::tid_t m_tid;
917ea8c25a8SOmair Javaid         lldb::addr_t * m_address;
918ea8c25a8SOmair Javaid         uint32_t * m_control;
919ea8c25a8SOmair Javaid         int m_type;
920ea8c25a8SOmair Javaid         int m_count;
921ea8c25a8SOmair Javaid     };
922ea8c25a8SOmair Javaid 
923ea8c25a8SOmair Javaid     void
924ea8c25a8SOmair Javaid     WriteDBGROperation::Execute(NativeProcessLinux *monitor)
925ea8c25a8SOmair Javaid     {
926*cdad63b3SOmair Javaid #if defined (__arm64__) || defined (__aarch64__)
927ea8c25a8SOmair Javaid         struct iovec ioVec;
928ea8c25a8SOmair Javaid         struct user_hwdebug_state dreg_state;
929ea8c25a8SOmair Javaid 
930ea8c25a8SOmair Javaid         memset (&dreg_state, 0, sizeof (dreg_state));
931ea8c25a8SOmair Javaid         ioVec.iov_len = (__builtin_offsetof (struct user_hwdebug_state, dbg_regs[m_count - 1])
932ea8c25a8SOmair Javaid                       + sizeof (dreg_state.dbg_regs [m_count - 1]));
933ea8c25a8SOmair Javaid 
934ea8c25a8SOmair Javaid         if (m_type == 0)
935ea8c25a8SOmair Javaid             m_type = NT_ARM_HW_WATCH;
936ea8c25a8SOmair Javaid         else
937ea8c25a8SOmair Javaid             m_type = NT_ARM_HW_BREAK;
938ea8c25a8SOmair Javaid 
939ea8c25a8SOmair Javaid         for (int i = 0; i < m_count; i++)
940ea8c25a8SOmair Javaid         {
941ea8c25a8SOmair Javaid             dreg_state.dbg_regs[i].addr = m_address[i];
942ea8c25a8SOmair Javaid             dreg_state.dbg_regs[i].ctrl = m_control[i];
943ea8c25a8SOmair Javaid         }
944ea8c25a8SOmair Javaid 
945ea8c25a8SOmair Javaid         PTRACE(PTRACE_SETREGSET, m_tid, &m_type, &ioVec, ioVec.iov_len, m_error);
946ea8c25a8SOmair Javaid #endif
947*cdad63b3SOmair Javaid     }
948*cdad63b3SOmair Javaid 
949ea8c25a8SOmair Javaid 
950af245d11STodd Fiala     //------------------------------------------------------------------------------
951af245d11STodd Fiala     /// @class WriteRegisterSetOperation
952af245d11STodd Fiala     /// @brief Implements NativeProcessLinux::WriteRegisterSet.
953af245d11STodd Fiala     class WriteRegisterSetOperation : public Operation
954af245d11STodd Fiala     {
955af245d11STodd Fiala     public:
95697ccc294SChaoren Lin         WriteRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
95797ccc294SChaoren Lin             : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset)
958af245d11STodd Fiala             { }
959af245d11STodd Fiala 
960d542efdeSTamas Berghammer         void Execute(NativeProcessLinux *monitor) override;
961af245d11STodd Fiala 
962af245d11STodd Fiala     private:
963af245d11STodd Fiala         lldb::tid_t m_tid;
964af245d11STodd Fiala         void *m_buf;
965af245d11STodd Fiala         size_t m_buf_size;
966af245d11STodd Fiala         const unsigned int m_regset;
967af245d11STodd Fiala     };
968af245d11STodd Fiala 
969af245d11STodd Fiala     void
970af245d11STodd Fiala     WriteRegisterSetOperation::Execute(NativeProcessLinux *monitor)
971af245d11STodd Fiala     {
97297ccc294SChaoren Lin         PTRACE(PTRACE_SETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size, m_error);
973af245d11STodd Fiala     }
974af245d11STodd Fiala 
975af245d11STodd Fiala     //------------------------------------------------------------------------------
976af245d11STodd Fiala     /// @class ResumeOperation
977af245d11STodd Fiala     /// @brief Implements NativeProcessLinux::Resume.
978af245d11STodd Fiala     class ResumeOperation : public Operation
979af245d11STodd Fiala     {
980af245d11STodd Fiala     public:
98197ccc294SChaoren Lin         ResumeOperation(lldb::tid_t tid, uint32_t signo) :
98297ccc294SChaoren Lin             m_tid(tid), m_signo(signo) { }
983af245d11STodd Fiala 
984d542efdeSTamas Berghammer         void Execute(NativeProcessLinux *monitor) override;
985af245d11STodd Fiala 
986af245d11STodd Fiala     private:
987af245d11STodd Fiala         lldb::tid_t m_tid;
988af245d11STodd Fiala         uint32_t m_signo;
989af245d11STodd Fiala     };
990af245d11STodd Fiala 
991af245d11STodd Fiala     void
992af245d11STodd Fiala     ResumeOperation::Execute(NativeProcessLinux *monitor)
993af245d11STodd Fiala     {
994af245d11STodd Fiala         intptr_t data = 0;
995af245d11STodd Fiala 
996af245d11STodd Fiala         if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
997af245d11STodd Fiala             data = m_signo;
998af245d11STodd Fiala 
99997ccc294SChaoren Lin         PTRACE(PTRACE_CONT, m_tid, nullptr, (void*)data, 0, m_error);
100097ccc294SChaoren Lin         if (m_error.Fail())
1001af245d11STodd Fiala         {
1002af245d11STodd Fiala             Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1003af245d11STodd Fiala 
1004af245d11STodd Fiala             if (log)
100597ccc294SChaoren Lin                 log->Printf ("ResumeOperation (%"  PRIu64 ") failed: %s", m_tid, m_error.AsCString());
1006af245d11STodd Fiala         }
1007af245d11STodd Fiala     }
1008af245d11STodd Fiala 
1009af245d11STodd Fiala     //------------------------------------------------------------------------------
1010af245d11STodd Fiala     /// @class SingleStepOperation
1011af245d11STodd Fiala     /// @brief Implements NativeProcessLinux::SingleStep.
1012af245d11STodd Fiala     class SingleStepOperation : public Operation
1013af245d11STodd Fiala     {
1014af245d11STodd Fiala     public:
101597ccc294SChaoren Lin         SingleStepOperation(lldb::tid_t tid, uint32_t signo)
101697ccc294SChaoren Lin             : m_tid(tid), m_signo(signo) { }
1017af245d11STodd Fiala 
1018d542efdeSTamas Berghammer         void Execute(NativeProcessLinux *monitor) override;
1019af245d11STodd Fiala 
1020af245d11STodd Fiala     private:
1021af245d11STodd Fiala         lldb::tid_t m_tid;
1022af245d11STodd Fiala         uint32_t m_signo;
1023af245d11STodd Fiala     };
1024af245d11STodd Fiala 
1025af245d11STodd Fiala     void
1026af245d11STodd Fiala     SingleStepOperation::Execute(NativeProcessLinux *monitor)
1027af245d11STodd Fiala     {
1028af245d11STodd Fiala         intptr_t data = 0;
1029af245d11STodd Fiala 
1030af245d11STodd Fiala         if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
1031af245d11STodd Fiala             data = m_signo;
1032af245d11STodd Fiala 
103397ccc294SChaoren Lin         PTRACE(PTRACE_SINGLESTEP, m_tid, nullptr, (void*)data, 0, m_error);
1034af245d11STodd Fiala     }
1035af245d11STodd Fiala 
1036af245d11STodd Fiala     //------------------------------------------------------------------------------
1037af245d11STodd Fiala     /// @class SiginfoOperation
1038af245d11STodd Fiala     /// @brief Implements NativeProcessLinux::GetSignalInfo.
1039af245d11STodd Fiala     class SiginfoOperation : public Operation
1040af245d11STodd Fiala     {
1041af245d11STodd Fiala     public:
104297ccc294SChaoren Lin         SiginfoOperation(lldb::tid_t tid, void *info)
104397ccc294SChaoren Lin             : m_tid(tid), m_info(info) { }
1044af245d11STodd Fiala 
1045d542efdeSTamas Berghammer         void Execute(NativeProcessLinux *monitor) override;
1046af245d11STodd Fiala 
1047af245d11STodd Fiala     private:
1048af245d11STodd Fiala         lldb::tid_t m_tid;
1049af245d11STodd Fiala         void *m_info;
1050af245d11STodd Fiala     };
1051af245d11STodd Fiala 
1052af245d11STodd Fiala     void
1053af245d11STodd Fiala     SiginfoOperation::Execute(NativeProcessLinux *monitor)
1054af245d11STodd Fiala     {
105597ccc294SChaoren Lin         PTRACE(PTRACE_GETSIGINFO, m_tid, nullptr, m_info, 0, m_error);
1056af245d11STodd Fiala     }
1057af245d11STodd Fiala 
1058af245d11STodd Fiala     //------------------------------------------------------------------------------
1059af245d11STodd Fiala     /// @class EventMessageOperation
1060af245d11STodd Fiala     /// @brief Implements NativeProcessLinux::GetEventMessage.
1061af245d11STodd Fiala     class EventMessageOperation : public Operation
1062af245d11STodd Fiala     {
1063af245d11STodd Fiala     public:
106497ccc294SChaoren Lin         EventMessageOperation(lldb::tid_t tid, unsigned long *message)
106597ccc294SChaoren Lin             : m_tid(tid), m_message(message) { }
1066af245d11STodd Fiala 
1067d542efdeSTamas Berghammer         void Execute(NativeProcessLinux *monitor) override;
1068af245d11STodd Fiala 
1069af245d11STodd Fiala     private:
1070af245d11STodd Fiala         lldb::tid_t m_tid;
1071af245d11STodd Fiala         unsigned long *m_message;
1072af245d11STodd Fiala     };
1073af245d11STodd Fiala 
1074af245d11STodd Fiala     void
1075af245d11STodd Fiala     EventMessageOperation::Execute(NativeProcessLinux *monitor)
1076af245d11STodd Fiala     {
107797ccc294SChaoren Lin         PTRACE(PTRACE_GETEVENTMSG, m_tid, nullptr, m_message, 0, m_error);
1078af245d11STodd Fiala     }
1079af245d11STodd Fiala 
1080af245d11STodd Fiala     class DetachOperation : public Operation
1081af245d11STodd Fiala     {
1082af245d11STodd Fiala     public:
108397ccc294SChaoren Lin         DetachOperation(lldb::tid_t tid) : m_tid(tid) { }
1084af245d11STodd Fiala 
1085d542efdeSTamas Berghammer         void Execute(NativeProcessLinux *monitor) override;
1086af245d11STodd Fiala 
1087af245d11STodd Fiala     private:
1088af245d11STodd Fiala         lldb::tid_t m_tid;
1089af245d11STodd Fiala     };
1090af245d11STodd Fiala 
1091af245d11STodd Fiala     void
1092af245d11STodd Fiala     DetachOperation::Execute(NativeProcessLinux *monitor)
1093af245d11STodd Fiala     {
109497ccc294SChaoren Lin         PTRACE(PTRACE_DETACH, m_tid, nullptr, 0, 0, m_error);
1095af245d11STodd Fiala     }
10961107b5a5SPavel Labath } // end of anonymous namespace
10971107b5a5SPavel Labath 
1098bd7cbc5aSPavel Labath // Simple helper function to ensure flags are enabled on the given file
1099bd7cbc5aSPavel Labath // descriptor.
1100bd7cbc5aSPavel Labath static Error
1101bd7cbc5aSPavel Labath EnsureFDFlags(int fd, int flags)
1102bd7cbc5aSPavel Labath {
1103bd7cbc5aSPavel Labath     Error error;
1104bd7cbc5aSPavel Labath 
1105bd7cbc5aSPavel Labath     int status = fcntl(fd, F_GETFL);
1106bd7cbc5aSPavel Labath     if (status == -1)
1107bd7cbc5aSPavel Labath     {
1108bd7cbc5aSPavel Labath         error.SetErrorToErrno();
1109bd7cbc5aSPavel Labath         return error;
1110bd7cbc5aSPavel Labath     }
1111bd7cbc5aSPavel Labath 
1112bd7cbc5aSPavel Labath     if (fcntl(fd, F_SETFL, status | flags) == -1)
1113bd7cbc5aSPavel Labath     {
1114bd7cbc5aSPavel Labath         error.SetErrorToErrno();
1115bd7cbc5aSPavel Labath         return error;
1116bd7cbc5aSPavel Labath     }
1117bd7cbc5aSPavel Labath 
1118bd7cbc5aSPavel Labath     return error;
1119bd7cbc5aSPavel Labath }
1120bd7cbc5aSPavel Labath 
1121bd7cbc5aSPavel Labath // This class encapsulates the privileged thread which performs all ptrace and wait operations on
1122bd7cbc5aSPavel Labath // the inferior. The thread consists of a main loop which waits for events and processes them
1123bd7cbc5aSPavel Labath //   - SIGCHLD (delivered over a signalfd file descriptor): These signals notify us of events in
1124bd7cbc5aSPavel Labath //     the inferior process. Upon receiving this signal we do a waitpid to get more information
1125bd7cbc5aSPavel Labath //     and dispatch to NativeProcessLinux::MonitorCallback.
1126bd7cbc5aSPavel Labath //   - requests for ptrace operations: These initiated via the DoOperation method, which funnels
1127bd7cbc5aSPavel Labath //     them to the Monitor thread via m_operation member. The Monitor thread is signaled over a
1128bd7cbc5aSPavel Labath //     pipe, and the completion of the operation is signalled over the semaphore.
1129bd7cbc5aSPavel Labath //   - thread exit event: this is signaled from the Monitor destructor by closing the write end
1130bd7cbc5aSPavel Labath //     of the command pipe.
113145f5cb31SPavel Labath class NativeProcessLinux::Monitor
113245f5cb31SPavel Labath {
11331107b5a5SPavel Labath private:
1134bd7cbc5aSPavel Labath     // The initial monitor operation (launch or attach). It returns a inferior process id.
1135bd7cbc5aSPavel Labath     std::unique_ptr<InitialOperation> m_initial_operation_up;
1136bd7cbc5aSPavel Labath 
1137bd7cbc5aSPavel Labath     ::pid_t                           m_child_pid = -1;
11381107b5a5SPavel Labath     NativeProcessLinux              * m_native_process;
11391107b5a5SPavel Labath 
11401107b5a5SPavel Labath     enum { READ, WRITE };
11411107b5a5SPavel Labath     int        m_pipefd[2] = {-1, -1};
11421107b5a5SPavel Labath     int        m_signal_fd = -1;
11431107b5a5SPavel Labath     HostThread m_thread;
11441107b5a5SPavel Labath 
1145bd7cbc5aSPavel Labath     // current operation which must be executed on the priviliged thread
1146bd7cbc5aSPavel Labath     Mutex      m_operation_mutex;
1147bd7cbc5aSPavel Labath     Operation *m_operation = nullptr;
1148bd7cbc5aSPavel Labath     sem_t      m_operation_sem;
1149bd7cbc5aSPavel Labath     Error      m_operation_error;
1150bd7cbc5aSPavel Labath 
115145f5cb31SPavel Labath     unsigned   m_operation_nesting_level = 0;
115245f5cb31SPavel Labath 
1153bd7cbc5aSPavel Labath     static constexpr char operation_command   = 'o';
115445f5cb31SPavel Labath     static constexpr char begin_block_command = '{';
115545f5cb31SPavel Labath     static constexpr char end_block_command   = '}';
1156bd7cbc5aSPavel Labath 
11571107b5a5SPavel Labath     void
11581107b5a5SPavel Labath     HandleSignals();
11591107b5a5SPavel Labath 
11601107b5a5SPavel Labath     void
11611107b5a5SPavel Labath     HandleWait();
11621107b5a5SPavel Labath 
11631107b5a5SPavel Labath     // Returns true if the thread should exit.
11641107b5a5SPavel Labath     bool
11651107b5a5SPavel Labath     HandleCommands();
11661107b5a5SPavel Labath 
11671107b5a5SPavel Labath     void
11681107b5a5SPavel Labath     MainLoop();
11691107b5a5SPavel Labath 
11701107b5a5SPavel Labath     static void *
11711107b5a5SPavel Labath     RunMonitor(void *arg);
11721107b5a5SPavel Labath 
1173bd7cbc5aSPavel Labath     Error
117445f5cb31SPavel Labath     WaitForAck();
117545f5cb31SPavel Labath 
117645f5cb31SPavel Labath     void
117745f5cb31SPavel Labath     BeginOperationBlock()
117845f5cb31SPavel Labath     {
117945f5cb31SPavel Labath         write(m_pipefd[WRITE], &begin_block_command, sizeof operation_command);
118045f5cb31SPavel Labath         WaitForAck();
118145f5cb31SPavel Labath     }
118245f5cb31SPavel Labath 
118345f5cb31SPavel Labath     void
118445f5cb31SPavel Labath     EndOperationBlock()
118545f5cb31SPavel Labath     {
118645f5cb31SPavel Labath         write(m_pipefd[WRITE], &end_block_command, sizeof operation_command);
118745f5cb31SPavel Labath         WaitForAck();
118845f5cb31SPavel Labath     }
118945f5cb31SPavel Labath 
11901107b5a5SPavel Labath public:
1191bd7cbc5aSPavel Labath     Monitor(const InitialOperation &initial_operation,
1192bd7cbc5aSPavel Labath             NativeProcessLinux *native_process)
1193bd7cbc5aSPavel Labath         : m_initial_operation_up(new InitialOperation(initial_operation)),
1194bd7cbc5aSPavel Labath           m_native_process(native_process)
1195bd7cbc5aSPavel Labath     {
1196bd7cbc5aSPavel Labath         sem_init(&m_operation_sem, 0, 0);
1197bd7cbc5aSPavel Labath     }
11981107b5a5SPavel Labath 
11991107b5a5SPavel Labath     ~Monitor();
12001107b5a5SPavel Labath 
12011107b5a5SPavel Labath     Error
12021107b5a5SPavel Labath     Initialize();
1203bd7cbc5aSPavel Labath 
1204bd7cbc5aSPavel Labath     void
120545f5cb31SPavel Labath     Terminate();
120645f5cb31SPavel Labath 
120745f5cb31SPavel Labath     void
1208bd7cbc5aSPavel Labath     DoOperation(Operation *op);
120945f5cb31SPavel Labath 
121045f5cb31SPavel Labath     class ScopedOperationLock {
121145f5cb31SPavel Labath         Monitor &m_monitor;
121245f5cb31SPavel Labath 
121345f5cb31SPavel Labath     public:
121445f5cb31SPavel Labath         ScopedOperationLock(Monitor &monitor)
121545f5cb31SPavel Labath             : m_monitor(monitor)
121645f5cb31SPavel Labath         { m_monitor.BeginOperationBlock(); }
121745f5cb31SPavel Labath 
121845f5cb31SPavel Labath         ~ScopedOperationLock()
121945f5cb31SPavel Labath         { m_monitor.EndOperationBlock(); }
122045f5cb31SPavel Labath     };
12211107b5a5SPavel Labath };
1222bd7cbc5aSPavel Labath constexpr char NativeProcessLinux::Monitor::operation_command;
122345f5cb31SPavel Labath constexpr char NativeProcessLinux::Monitor::begin_block_command;
122445f5cb31SPavel Labath constexpr char NativeProcessLinux::Monitor::end_block_command;
12251107b5a5SPavel Labath 
12261107b5a5SPavel Labath Error
12271107b5a5SPavel Labath NativeProcessLinux::Monitor::Initialize()
12281107b5a5SPavel Labath {
12291107b5a5SPavel Labath     Error error;
12301107b5a5SPavel Labath 
12311107b5a5SPavel Labath     // We get a SIGCHLD every time something interesting happens with the inferior. We shall be
12321107b5a5SPavel Labath     // listening for these signals over a signalfd file descriptors. This allows us to wait for
12331107b5a5SPavel Labath     // multiple kinds of events with select.
12341107b5a5SPavel Labath     sigset_t signals;
12351107b5a5SPavel Labath     sigemptyset(&signals);
12361107b5a5SPavel Labath     sigaddset(&signals, SIGCHLD);
12371107b5a5SPavel Labath     m_signal_fd = signalfd(-1, &signals, SFD_NONBLOCK | SFD_CLOEXEC);
12381107b5a5SPavel Labath     if (m_signal_fd < 0)
12391107b5a5SPavel Labath     {
12401107b5a5SPavel Labath         return Error("NativeProcessLinux::Monitor::%s failed due to signalfd failure. Monitoring the inferior will be impossible: %s",
12411107b5a5SPavel Labath                     __FUNCTION__, strerror(errno));
12421107b5a5SPavel Labath 
1243af245d11STodd Fiala     }
1244af245d11STodd Fiala 
12451107b5a5SPavel Labath     if (pipe2(m_pipefd, O_CLOEXEC) == -1)
12461107b5a5SPavel Labath     {
12471107b5a5SPavel Labath         error.SetErrorToErrno();
12481107b5a5SPavel Labath         return error;
12491107b5a5SPavel Labath     }
12501107b5a5SPavel Labath 
1251bd7cbc5aSPavel Labath     if ((error = EnsureFDFlags(m_pipefd[READ], O_NONBLOCK)).Fail()) {
1252bd7cbc5aSPavel Labath         return error;
1253bd7cbc5aSPavel Labath     }
1254bd7cbc5aSPavel Labath 
1255bd7cbc5aSPavel Labath     static const char g_thread_name[] = "lldb.process.nativelinux.monitor";
1256bd7cbc5aSPavel Labath     m_thread = ThreadLauncher::LaunchThread(g_thread_name, Monitor::RunMonitor, this, nullptr);
12571107b5a5SPavel Labath     if (!m_thread.IsJoinable())
12581107b5a5SPavel Labath         return Error("Failed to create monitor thread for NativeProcessLinux.");
12591107b5a5SPavel Labath 
1260bd7cbc5aSPavel Labath     // Wait for initial operation to complete.
126145f5cb31SPavel Labath     return WaitForAck();
1262bd7cbc5aSPavel Labath }
1263bd7cbc5aSPavel Labath 
1264bd7cbc5aSPavel Labath void
1265bd7cbc5aSPavel Labath NativeProcessLinux::Monitor::DoOperation(Operation *op)
1266bd7cbc5aSPavel Labath {
1267bd7cbc5aSPavel Labath     if (m_thread.EqualsThread(pthread_self())) {
1268bd7cbc5aSPavel Labath         // If we're on the Monitor thread, we can simply execute the operation.
1269bd7cbc5aSPavel Labath         op->Execute(m_native_process);
1270bd7cbc5aSPavel Labath         return;
1271bd7cbc5aSPavel Labath     }
1272bd7cbc5aSPavel Labath 
1273bd7cbc5aSPavel Labath     // Otherwise we need to pass the operation to the Monitor thread so it can handle it.
1274bd7cbc5aSPavel Labath     Mutex::Locker lock(m_operation_mutex);
1275bd7cbc5aSPavel Labath 
1276bd7cbc5aSPavel Labath     m_operation = op;
1277bd7cbc5aSPavel Labath 
1278bd7cbc5aSPavel Labath     // notify the thread that an operation is ready to be processed
1279bd7cbc5aSPavel Labath     write(m_pipefd[WRITE], &operation_command, sizeof operation_command);
1280bd7cbc5aSPavel Labath 
128145f5cb31SPavel Labath     WaitForAck();
128245f5cb31SPavel Labath }
128345f5cb31SPavel Labath 
128445f5cb31SPavel Labath void
128545f5cb31SPavel Labath NativeProcessLinux::Monitor::Terminate()
128645f5cb31SPavel Labath {
128745f5cb31SPavel Labath     if (m_pipefd[WRITE] >= 0)
128845f5cb31SPavel Labath     {
128945f5cb31SPavel Labath         close(m_pipefd[WRITE]);
129045f5cb31SPavel Labath         m_pipefd[WRITE] = -1;
129145f5cb31SPavel Labath     }
129245f5cb31SPavel Labath     if (m_thread.IsJoinable())
129345f5cb31SPavel Labath         m_thread.Join(nullptr);
12941107b5a5SPavel Labath }
12951107b5a5SPavel Labath 
12961107b5a5SPavel Labath NativeProcessLinux::Monitor::~Monitor()
12971107b5a5SPavel Labath {
129845f5cb31SPavel Labath     Terminate();
12991107b5a5SPavel Labath     if (m_pipefd[READ] >= 0)
13001107b5a5SPavel Labath         close(m_pipefd[READ]);
13011107b5a5SPavel Labath     if (m_signal_fd >= 0)
13021107b5a5SPavel Labath         close(m_signal_fd);
1303bd7cbc5aSPavel Labath     sem_destroy(&m_operation_sem);
13041107b5a5SPavel Labath }
13051107b5a5SPavel Labath 
13061107b5a5SPavel Labath void
13071107b5a5SPavel Labath NativeProcessLinux::Monitor::HandleSignals()
13081107b5a5SPavel Labath {
13091107b5a5SPavel Labath     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
13101107b5a5SPavel Labath 
13111107b5a5SPavel Labath     // We don't really care about the content of the SIGCHLD siginfo structure, as we will get
13121107b5a5SPavel Labath     // all the information from waitpid(). We just need to read all the signals so that we can
13131107b5a5SPavel Labath     // sleep next time we reach select().
13141107b5a5SPavel Labath     while (true)
13151107b5a5SPavel Labath     {
13161107b5a5SPavel Labath         signalfd_siginfo info;
13171107b5a5SPavel Labath         ssize_t size = read(m_signal_fd, &info, sizeof info);
13181107b5a5SPavel Labath         if (size == -1)
13191107b5a5SPavel Labath         {
13201107b5a5SPavel Labath             if (errno == EAGAIN || errno == EWOULDBLOCK)
13211107b5a5SPavel Labath                 break; // We are done.
13221107b5a5SPavel Labath             if (errno == EINTR)
13231107b5a5SPavel Labath                 continue;
13241107b5a5SPavel Labath             if (log)
13251107b5a5SPavel Labath                 log->Printf("NativeProcessLinux::Monitor::%s reading from signalfd file descriptor failed: %s",
13261107b5a5SPavel Labath                         __FUNCTION__, strerror(errno));
13271107b5a5SPavel Labath             break;
13281107b5a5SPavel Labath         }
13291107b5a5SPavel Labath         if (size != sizeof info)
13301107b5a5SPavel Labath         {
13311107b5a5SPavel Labath             // We got incomplete information structure. This should not happen, let's just log
13321107b5a5SPavel Labath             // that.
13331107b5a5SPavel Labath             if (log)
13341107b5a5SPavel Labath                 log->Printf("NativeProcessLinux::Monitor::%s reading from signalfd file descriptor returned incomplete data: "
13351107b5a5SPavel Labath                         "structure size is %zd, read returned %zd bytes",
13361107b5a5SPavel Labath                         __FUNCTION__, sizeof info, size);
13371107b5a5SPavel Labath             break;
13381107b5a5SPavel Labath         }
13391107b5a5SPavel Labath         if (log)
13401107b5a5SPavel Labath             log->Printf("NativeProcessLinux::Monitor::%s received signal %s(%d).", __FUNCTION__,
13411107b5a5SPavel Labath                 Host::GetSignalAsCString(info.ssi_signo), info.ssi_signo);
13421107b5a5SPavel Labath     }
13431107b5a5SPavel Labath }
13441107b5a5SPavel Labath 
13451107b5a5SPavel Labath void
13461107b5a5SPavel Labath NativeProcessLinux::Monitor::HandleWait()
13471107b5a5SPavel Labath {
13481107b5a5SPavel Labath     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
13491107b5a5SPavel Labath     // Process all pending waitpid notifications.
13501107b5a5SPavel Labath     while (true)
13511107b5a5SPavel Labath     {
13521107b5a5SPavel Labath         int status = -1;
13531107b5a5SPavel Labath         ::pid_t wait_pid = waitpid(m_child_pid, &status, __WALL | WNOHANG);
13541107b5a5SPavel Labath 
13551107b5a5SPavel Labath         if (wait_pid == 0)
13561107b5a5SPavel Labath             break; // We are done.
13571107b5a5SPavel Labath 
13581107b5a5SPavel Labath         if (wait_pid == -1)
13591107b5a5SPavel Labath         {
13601107b5a5SPavel Labath             if (errno == EINTR)
13611107b5a5SPavel Labath                 continue;
13621107b5a5SPavel Labath 
13631107b5a5SPavel Labath             if (log)
13641107b5a5SPavel Labath               log->Printf("NativeProcessLinux::Monitor::%s waitpid (pid = %" PRIi32 ", &status, __WALL | WNOHANG) failed: %s",
13651107b5a5SPavel Labath                       __FUNCTION__, m_child_pid, strerror(errno));
13661107b5a5SPavel Labath             break;
13671107b5a5SPavel Labath         }
13681107b5a5SPavel Labath 
13691107b5a5SPavel Labath         bool exited = false;
13701107b5a5SPavel Labath         int signal = 0;
13711107b5a5SPavel Labath         int exit_status = 0;
13721107b5a5SPavel Labath         const char *status_cstr = NULL;
13731107b5a5SPavel Labath         if (WIFSTOPPED(status))
13741107b5a5SPavel Labath         {
13751107b5a5SPavel Labath             signal = WSTOPSIG(status);
13761107b5a5SPavel Labath             status_cstr = "STOPPED";
13771107b5a5SPavel Labath         }
13781107b5a5SPavel Labath         else if (WIFEXITED(status))
13791107b5a5SPavel Labath         {
13801107b5a5SPavel Labath             exit_status = WEXITSTATUS(status);
13811107b5a5SPavel Labath             status_cstr = "EXITED";
13821107b5a5SPavel Labath             exited = true;
13831107b5a5SPavel Labath         }
13841107b5a5SPavel Labath         else if (WIFSIGNALED(status))
13851107b5a5SPavel Labath         {
13861107b5a5SPavel Labath             signal = WTERMSIG(status);
13871107b5a5SPavel Labath             status_cstr = "SIGNALED";
13881107b5a5SPavel Labath             if (wait_pid == abs(m_child_pid)) {
13891107b5a5SPavel Labath                 exited = true;
13901107b5a5SPavel Labath                 exit_status = -1;
13911107b5a5SPavel Labath             }
13921107b5a5SPavel Labath         }
13931107b5a5SPavel Labath         else
13941107b5a5SPavel Labath             status_cstr = "(\?\?\?)";
13951107b5a5SPavel Labath 
13961107b5a5SPavel Labath         if (log)
13971107b5a5SPavel Labath             log->Printf("NativeProcessLinux::Monitor::%s: waitpid (pid = %" PRIi32 ", &status, __WALL | WNOHANG)"
13981107b5a5SPavel Labath                 "=> pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
13991107b5a5SPavel Labath                 __FUNCTION__, m_child_pid, wait_pid, status, status_cstr, signal, exit_status);
14001107b5a5SPavel Labath 
14011107b5a5SPavel Labath         m_native_process->MonitorCallback (wait_pid, exited, signal, exit_status);
14021107b5a5SPavel Labath     }
14031107b5a5SPavel Labath }
14041107b5a5SPavel Labath 
14051107b5a5SPavel Labath bool
14061107b5a5SPavel Labath NativeProcessLinux::Monitor::HandleCommands()
14071107b5a5SPavel Labath {
14081107b5a5SPavel Labath     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
14091107b5a5SPavel Labath 
14101107b5a5SPavel Labath     while (true)
14111107b5a5SPavel Labath     {
14121107b5a5SPavel Labath         char command = 0;
14131107b5a5SPavel Labath         ssize_t size = read(m_pipefd[READ], &command, sizeof command);
14141107b5a5SPavel Labath         if (size == -1)
14151107b5a5SPavel Labath         {
14161107b5a5SPavel Labath             if (errno == EAGAIN || errno == EWOULDBLOCK)
14171107b5a5SPavel Labath                 return false;
14181107b5a5SPavel Labath             if (errno == EINTR)
14191107b5a5SPavel Labath                 continue;
14201107b5a5SPavel Labath             if (log)
14211107b5a5SPavel Labath                 log->Printf("NativeProcessLinux::Monitor::%s exiting because read from command file descriptor failed: %s", __FUNCTION__, strerror(errno));
14221107b5a5SPavel Labath             return true;
14231107b5a5SPavel Labath         }
14241107b5a5SPavel Labath         if (size == 0) // end of file - write end closed
14251107b5a5SPavel Labath         {
14261107b5a5SPavel Labath             if (log)
14271107b5a5SPavel Labath                 log->Printf("NativeProcessLinux::Monitor::%s exit command received, exiting...", __FUNCTION__);
142845f5cb31SPavel Labath             assert(m_operation_nesting_level == 0 && "Unbalanced begin/end block commands detected");
14291107b5a5SPavel Labath             return true; // We are done.
14301107b5a5SPavel Labath         }
1431bd7cbc5aSPavel Labath 
1432bd7cbc5aSPavel Labath         switch (command)
1433bd7cbc5aSPavel Labath         {
1434bd7cbc5aSPavel Labath         case operation_command:
1435bd7cbc5aSPavel Labath             m_operation->Execute(m_native_process);
143645f5cb31SPavel Labath             break;
143745f5cb31SPavel Labath         case begin_block_command:
143845f5cb31SPavel Labath             ++m_operation_nesting_level;
143945f5cb31SPavel Labath             break;
144045f5cb31SPavel Labath         case end_block_command:
144145f5cb31SPavel Labath             assert(m_operation_nesting_level > 0);
144245f5cb31SPavel Labath             --m_operation_nesting_level;
1443bd7cbc5aSPavel Labath             break;
1444bd7cbc5aSPavel Labath         default:
14451107b5a5SPavel Labath             if (log)
14461107b5a5SPavel Labath                 log->Printf("NativeProcessLinux::Monitor::%s received unknown command '%c'",
14471107b5a5SPavel Labath                         __FUNCTION__, command);
14481107b5a5SPavel Labath         }
144945f5cb31SPavel Labath 
145045f5cb31SPavel Labath         // notify calling thread that the command has been processed
145145f5cb31SPavel Labath         sem_post(&m_operation_sem);
14521107b5a5SPavel Labath     }
1453bd7cbc5aSPavel Labath }
14541107b5a5SPavel Labath 
14551107b5a5SPavel Labath void
14561107b5a5SPavel Labath NativeProcessLinux::Monitor::MainLoop()
14571107b5a5SPavel Labath {
1458bd7cbc5aSPavel Labath     ::pid_t child_pid = (*m_initial_operation_up)(m_operation_error);
1459bd7cbc5aSPavel Labath     m_initial_operation_up.reset();
1460bd7cbc5aSPavel Labath     m_child_pid = -getpgid(child_pid),
1461bd7cbc5aSPavel Labath     sem_post(&m_operation_sem);
1462bd7cbc5aSPavel Labath 
14631107b5a5SPavel Labath     while (true)
14641107b5a5SPavel Labath     {
14651107b5a5SPavel Labath         fd_set fds;
14661107b5a5SPavel Labath         FD_ZERO(&fds);
146745f5cb31SPavel Labath         // Only process waitpid events if we are outside of an operation block. Any pending
146845f5cb31SPavel Labath         // events will be processed after we leave the block.
146945f5cb31SPavel Labath         if (m_operation_nesting_level == 0)
14701107b5a5SPavel Labath             FD_SET(m_signal_fd, &fds);
14711107b5a5SPavel Labath         FD_SET(m_pipefd[READ], &fds);
14721107b5a5SPavel Labath 
14731107b5a5SPavel Labath         int max_fd = std::max(m_signal_fd, m_pipefd[READ]) + 1;
14741107b5a5SPavel Labath         int r = select(max_fd, &fds, nullptr, nullptr, nullptr);
14751107b5a5SPavel Labath         if (r < 0)
14761107b5a5SPavel Labath         {
14771107b5a5SPavel Labath             Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
14781107b5a5SPavel Labath             if (log)
14791107b5a5SPavel Labath                 log->Printf("NativeProcessLinux::Monitor::%s exiting because select failed: %s",
14801107b5a5SPavel Labath                         __FUNCTION__, strerror(errno));
14811107b5a5SPavel Labath             return;
14821107b5a5SPavel Labath         }
14831107b5a5SPavel Labath 
14841107b5a5SPavel Labath         if (FD_ISSET(m_pipefd[READ], &fds))
14851107b5a5SPavel Labath         {
14861107b5a5SPavel Labath             if (HandleCommands())
14871107b5a5SPavel Labath                 return;
14881107b5a5SPavel Labath         }
14891107b5a5SPavel Labath 
14901107b5a5SPavel Labath         if (FD_ISSET(m_signal_fd, &fds))
14911107b5a5SPavel Labath         {
14921107b5a5SPavel Labath             HandleSignals();
14931107b5a5SPavel Labath             HandleWait();
14941107b5a5SPavel Labath         }
14951107b5a5SPavel Labath     }
14961107b5a5SPavel Labath }
14971107b5a5SPavel Labath 
1498bd7cbc5aSPavel Labath Error
149945f5cb31SPavel Labath NativeProcessLinux::Monitor::WaitForAck()
1500bd7cbc5aSPavel Labath {
1501bd7cbc5aSPavel Labath     Error error;
1502bd7cbc5aSPavel Labath     while (sem_wait(&m_operation_sem) != 0)
1503bd7cbc5aSPavel Labath     {
1504bd7cbc5aSPavel Labath         if (errno == EINTR)
1505bd7cbc5aSPavel Labath             continue;
1506bd7cbc5aSPavel Labath 
1507bd7cbc5aSPavel Labath         error.SetErrorToErrno();
1508bd7cbc5aSPavel Labath         return error;
1509bd7cbc5aSPavel Labath     }
1510bd7cbc5aSPavel Labath 
1511bd7cbc5aSPavel Labath     return m_operation_error;
1512bd7cbc5aSPavel Labath }
1513bd7cbc5aSPavel Labath 
15141107b5a5SPavel Labath void *
15151107b5a5SPavel Labath NativeProcessLinux::Monitor::RunMonitor(void *arg)
15161107b5a5SPavel Labath {
15171107b5a5SPavel Labath     static_cast<Monitor *>(arg)->MainLoop();
15181107b5a5SPavel Labath     return nullptr;
15191107b5a5SPavel Labath }
15201107b5a5SPavel Labath 
15211107b5a5SPavel Labath 
1522bd7cbc5aSPavel Labath NativeProcessLinux::LaunchArgs::LaunchArgs(Module *module,
1523af245d11STodd Fiala                                        char const **argv,
1524af245d11STodd Fiala                                        char const **envp,
152575f47c3aSTodd Fiala                                        const std::string &stdin_path,
152675f47c3aSTodd Fiala                                        const std::string &stdout_path,
152775f47c3aSTodd Fiala                                        const std::string &stderr_path,
15280bce1b67STodd Fiala                                        const char *working_dir,
1529db264a6dSTamas Berghammer                                        const ProcessLaunchInfo &launch_info)
1530bd7cbc5aSPavel Labath     : m_module(module),
1531af245d11STodd Fiala       m_argv(argv),
1532af245d11STodd Fiala       m_envp(envp),
1533af245d11STodd Fiala       m_stdin_path(stdin_path),
1534af245d11STodd Fiala       m_stdout_path(stdout_path),
1535af245d11STodd Fiala       m_stderr_path(stderr_path),
15360bce1b67STodd Fiala       m_working_dir(working_dir),
15370bce1b67STodd Fiala       m_launch_info(launch_info)
15380bce1b67STodd Fiala {
15390bce1b67STodd Fiala }
1540af245d11STodd Fiala 
1541af245d11STodd Fiala NativeProcessLinux::LaunchArgs::~LaunchArgs()
1542af245d11STodd Fiala { }
1543af245d11STodd Fiala 
1544af245d11STodd Fiala // -----------------------------------------------------------------------------
1545af245d11STodd Fiala // Public Static Methods
1546af245d11STodd Fiala // -----------------------------------------------------------------------------
1547af245d11STodd Fiala 
1548db264a6dSTamas Berghammer Error
1549af245d11STodd Fiala NativeProcessLinux::LaunchProcess (
1550db264a6dSTamas Berghammer     Module *exe_module,
1551db264a6dSTamas Berghammer     ProcessLaunchInfo &launch_info,
1552db264a6dSTamas Berghammer     NativeProcessProtocol::NativeDelegate &native_delegate,
1553af245d11STodd Fiala     NativeProcessProtocolSP &native_process_sp)
1554af245d11STodd Fiala {
1555af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1556af245d11STodd Fiala 
1557af245d11STodd Fiala     Error error;
1558af245d11STodd Fiala 
1559af245d11STodd Fiala     // Verify the working directory is valid if one was specified.
1560af245d11STodd Fiala     const char* working_dir = launch_info.GetWorkingDirectory ();
1561af245d11STodd Fiala     if (working_dir)
1562af245d11STodd Fiala     {
1563af245d11STodd Fiala       FileSpec working_dir_fs (working_dir, true);
1564af245d11STodd Fiala       if (!working_dir_fs || working_dir_fs.GetFileType () != FileSpec::eFileTypeDirectory)
1565af245d11STodd Fiala       {
1566af245d11STodd Fiala           error.SetErrorStringWithFormat ("No such file or directory: %s", working_dir);
1567af245d11STodd Fiala           return error;
1568af245d11STodd Fiala       }
1569af245d11STodd Fiala     }
1570af245d11STodd Fiala 
1571db264a6dSTamas Berghammer     const FileAction *file_action;
1572af245d11STodd Fiala 
1573af245d11STodd Fiala     // Default of NULL will mean to use existing open file descriptors.
157475f47c3aSTodd Fiala     std::string stdin_path;
157575f47c3aSTodd Fiala     std::string stdout_path;
157675f47c3aSTodd Fiala     std::string stderr_path;
1577af245d11STodd Fiala 
1578af245d11STodd Fiala     file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
157975f47c3aSTodd Fiala     if (file_action)
158075f47c3aSTodd Fiala         stdin_path = file_action->GetPath ();
1581af245d11STodd Fiala 
1582af245d11STodd Fiala     file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
158375f47c3aSTodd Fiala     if (file_action)
158475f47c3aSTodd Fiala         stdout_path = file_action->GetPath ();
1585af245d11STodd Fiala 
1586af245d11STodd Fiala     file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
158775f47c3aSTodd Fiala     if (file_action)
158875f47c3aSTodd Fiala         stderr_path = file_action->GetPath ();
158975f47c3aSTodd Fiala 
159075f47c3aSTodd Fiala     if (log)
159175f47c3aSTodd Fiala     {
159275f47c3aSTodd Fiala         if (!stdin_path.empty ())
159375f47c3aSTodd Fiala             log->Printf ("NativeProcessLinux::%s setting STDIN to '%s'", __FUNCTION__, stdin_path.c_str ());
159475f47c3aSTodd Fiala         else
159575f47c3aSTodd Fiala             log->Printf ("NativeProcessLinux::%s leaving STDIN as is", __FUNCTION__);
159675f47c3aSTodd Fiala 
159775f47c3aSTodd Fiala         if (!stdout_path.empty ())
159875f47c3aSTodd Fiala             log->Printf ("NativeProcessLinux::%s setting STDOUT to '%s'", __FUNCTION__, stdout_path.c_str ());
159975f47c3aSTodd Fiala         else
160075f47c3aSTodd Fiala             log->Printf ("NativeProcessLinux::%s leaving STDOUT as is", __FUNCTION__);
160175f47c3aSTodd Fiala 
160275f47c3aSTodd Fiala         if (!stderr_path.empty ())
160375f47c3aSTodd Fiala             log->Printf ("NativeProcessLinux::%s setting STDERR to '%s'", __FUNCTION__, stderr_path.c_str ());
160475f47c3aSTodd Fiala         else
160575f47c3aSTodd Fiala             log->Printf ("NativeProcessLinux::%s leaving STDERR as is", __FUNCTION__);
160675f47c3aSTodd Fiala     }
1607af245d11STodd Fiala 
1608af245d11STodd Fiala     // Create the NativeProcessLinux in launch mode.
1609af245d11STodd Fiala     native_process_sp.reset (new NativeProcessLinux ());
1610af245d11STodd Fiala 
1611af245d11STodd Fiala     if (log)
1612af245d11STodd Fiala     {
1613af245d11STodd Fiala         int i = 0;
1614af245d11STodd Fiala         for (const char **args = launch_info.GetArguments ().GetConstArgumentVector (); *args; ++args, ++i)
1615af245d11STodd Fiala         {
1616af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s arg %d: \"%s\"", __FUNCTION__, i, *args ? *args : "nullptr");
1617af245d11STodd Fiala             ++i;
1618af245d11STodd Fiala         }
1619af245d11STodd Fiala     }
1620af245d11STodd Fiala 
1621af245d11STodd Fiala     if (!native_process_sp->RegisterNativeDelegate (native_delegate))
1622af245d11STodd Fiala     {
1623af245d11STodd Fiala         native_process_sp.reset ();
1624af245d11STodd Fiala         error.SetErrorStringWithFormat ("failed to register the native delegate");
1625af245d11STodd Fiala         return error;
1626af245d11STodd Fiala     }
1627af245d11STodd Fiala 
1628cb84eebbSTamas Berghammer     std::static_pointer_cast<NativeProcessLinux> (native_process_sp)->LaunchInferior (
1629af245d11STodd Fiala             exe_module,
1630af245d11STodd Fiala             launch_info.GetArguments ().GetConstArgumentVector (),
1631af245d11STodd Fiala             launch_info.GetEnvironmentEntries ().GetConstArgumentVector (),
1632af245d11STodd Fiala             stdin_path,
1633af245d11STodd Fiala             stdout_path,
1634af245d11STodd Fiala             stderr_path,
1635af245d11STodd Fiala             working_dir,
16360bce1b67STodd Fiala             launch_info,
1637af245d11STodd Fiala             error);
1638af245d11STodd Fiala 
1639af245d11STodd Fiala     if (error.Fail ())
1640af245d11STodd Fiala     {
1641af245d11STodd Fiala         native_process_sp.reset ();
1642af245d11STodd Fiala         if (log)
1643af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s failed to launch process: %s", __FUNCTION__, error.AsCString ());
1644af245d11STodd Fiala         return error;
1645af245d11STodd Fiala     }
1646af245d11STodd Fiala 
1647af245d11STodd Fiala     launch_info.SetProcessID (native_process_sp->GetID ());
1648af245d11STodd Fiala 
1649af245d11STodd Fiala     return error;
1650af245d11STodd Fiala }
1651af245d11STodd Fiala 
1652db264a6dSTamas Berghammer Error
1653af245d11STodd Fiala NativeProcessLinux::AttachToProcess (
1654af245d11STodd Fiala     lldb::pid_t pid,
1655db264a6dSTamas Berghammer     NativeProcessProtocol::NativeDelegate &native_delegate,
1656af245d11STodd Fiala     NativeProcessProtocolSP &native_process_sp)
1657af245d11STodd Fiala {
1658af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1659af245d11STodd Fiala     if (log && log->GetMask ().Test (POSIX_LOG_VERBOSE))
1660af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
1661af245d11STodd Fiala 
1662af245d11STodd Fiala     // Grab the current platform architecture.  This should be Linux,
1663af245d11STodd Fiala     // since this code is only intended to run on a Linux host.
1664615eb7e6SGreg Clayton     PlatformSP platform_sp (Platform::GetHostPlatform ());
1665af245d11STodd Fiala     if (!platform_sp)
1666af245d11STodd Fiala         return Error("failed to get a valid default platform");
1667af245d11STodd Fiala 
1668af245d11STodd Fiala     // Retrieve the architecture for the running process.
1669af245d11STodd Fiala     ArchSpec process_arch;
1670af245d11STodd Fiala     Error error = ResolveProcessArchitecture (pid, *platform_sp.get (), process_arch);
1671af245d11STodd Fiala     if (!error.Success ())
1672af245d11STodd Fiala         return error;
1673af245d11STodd Fiala 
16741339b5e8SOleksiy Vyalov     std::shared_ptr<NativeProcessLinux> native_process_linux_sp (new NativeProcessLinux ());
1675af245d11STodd Fiala 
16761339b5e8SOleksiy Vyalov     if (!native_process_linux_sp->RegisterNativeDelegate (native_delegate))
1677af245d11STodd Fiala     {
1678af245d11STodd Fiala         error.SetErrorStringWithFormat ("failed to register the native delegate");
1679af245d11STodd Fiala         return error;
1680af245d11STodd Fiala     }
1681af245d11STodd Fiala 
16821339b5e8SOleksiy Vyalov     native_process_linux_sp->AttachToInferior (pid, error);
1683af245d11STodd Fiala     if (!error.Success ())
1684af245d11STodd Fiala         return error;
1685af245d11STodd Fiala 
16861339b5e8SOleksiy Vyalov     native_process_sp = native_process_linux_sp;
1687af245d11STodd Fiala     return error;
1688af245d11STodd Fiala }
1689af245d11STodd Fiala 
1690af245d11STodd Fiala // -----------------------------------------------------------------------------
1691af245d11STodd Fiala // Public Instance Methods
1692af245d11STodd Fiala // -----------------------------------------------------------------------------
1693af245d11STodd Fiala 
1694af245d11STodd Fiala NativeProcessLinux::NativeProcessLinux () :
1695af245d11STodd Fiala     NativeProcessProtocol (LLDB_INVALID_PROCESS_ID),
1696af245d11STodd Fiala     m_arch (),
1697af245d11STodd Fiala     m_supports_mem_region (eLazyBoolCalculate),
1698af245d11STodd Fiala     m_mem_region_cache (),
16998c8ff7afSPavel Labath     m_mem_region_cache_mutex ()
1700af245d11STodd Fiala {
1701af245d11STodd Fiala }
1702af245d11STodd Fiala 
1703af245d11STodd Fiala //------------------------------------------------------------------------------
1704bd7cbc5aSPavel Labath // NativeProcessLinux spawns a new thread which performs all operations on the inferior process.
1705bd7cbc5aSPavel Labath // Refer to Monitor and Operation classes to see why this is necessary.
1706bd7cbc5aSPavel Labath //------------------------------------------------------------------------------
1707af245d11STodd Fiala void
1708af245d11STodd Fiala NativeProcessLinux::LaunchInferior (
1709af245d11STodd Fiala     Module *module,
1710af245d11STodd Fiala     const char *argv[],
1711af245d11STodd Fiala     const char *envp[],
171275f47c3aSTodd Fiala     const std::string &stdin_path,
171375f47c3aSTodd Fiala     const std::string &stdout_path,
171475f47c3aSTodd Fiala     const std::string &stderr_path,
1715af245d11STodd Fiala     const char *working_dir,
1716db264a6dSTamas Berghammer     const ProcessLaunchInfo &launch_info,
1717db264a6dSTamas Berghammer     Error &error)
1718af245d11STodd Fiala {
1719af245d11STodd Fiala     if (module)
1720af245d11STodd Fiala         m_arch = module->GetArchitecture ();
1721af245d11STodd Fiala 
1722af245d11STodd Fiala     SetState (eStateLaunching);
1723af245d11STodd Fiala 
1724af245d11STodd Fiala     std::unique_ptr<LaunchArgs> args(
1725af245d11STodd Fiala         new LaunchArgs(
1726bd7cbc5aSPavel Labath             module, argv, envp,
1727af245d11STodd Fiala             stdin_path, stdout_path, stderr_path,
17280bce1b67STodd Fiala             working_dir, launch_info));
1729af245d11STodd Fiala 
1730bd7cbc5aSPavel Labath     StartMonitorThread ([&] (Error &e) { return Launch(args.get(), e); }, error);
1731af245d11STodd Fiala     if (!error.Success ())
1732af245d11STodd Fiala         return;
1733af245d11STodd Fiala }
1734af245d11STodd Fiala 
1735af245d11STodd Fiala void
1736db264a6dSTamas Berghammer NativeProcessLinux::AttachToInferior (lldb::pid_t pid, Error &error)
1737af245d11STodd Fiala {
1738af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1739af245d11STodd Fiala     if (log)
1740af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
1741af245d11STodd Fiala 
1742af245d11STodd Fiala     // We can use the Host for everything except the ResolveExecutable portion.
1743615eb7e6SGreg Clayton     PlatformSP platform_sp = Platform::GetHostPlatform ();
1744af245d11STodd Fiala     if (!platform_sp)
1745af245d11STodd Fiala     {
1746af245d11STodd Fiala         if (log)
1747af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): no default platform set", __FUNCTION__, pid);
1748af245d11STodd Fiala         error.SetErrorString ("no default platform available");
174950d60be3SShawn Best         return;
1750af245d11STodd Fiala     }
1751af245d11STodd Fiala 
1752af245d11STodd Fiala     // Gather info about the process.
1753af245d11STodd Fiala     ProcessInstanceInfo process_info;
175450d60be3SShawn Best     if (!platform_sp->GetProcessInfo (pid, process_info))
175550d60be3SShawn Best     {
175650d60be3SShawn Best         if (log)
175750d60be3SShawn Best             log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): failed to get process info", __FUNCTION__, pid);
175850d60be3SShawn Best         error.SetErrorString ("failed to get process info");
175950d60be3SShawn Best         return;
176050d60be3SShawn Best     }
1761af245d11STodd Fiala 
1762af245d11STodd Fiala     // Resolve the executable module
1763af245d11STodd Fiala     ModuleSP exe_module_sp;
1764af245d11STodd Fiala     FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
1765e56f6dceSChaoren Lin     ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
17666edef204SOleksiy Vyalov     error = platform_sp->ResolveExecutable(exe_module_spec, exe_module_sp,
1767af245d11STodd Fiala                                            executable_search_paths.GetSize() ? &executable_search_paths : NULL);
1768af245d11STodd Fiala     if (!error.Success())
1769af245d11STodd Fiala         return;
1770af245d11STodd Fiala 
1771af245d11STodd Fiala     // Set the architecture to the exe architecture.
1772af245d11STodd Fiala     m_arch = exe_module_sp->GetArchitecture();
1773af245d11STodd Fiala     if (log)
1774af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
1775af245d11STodd Fiala 
1776af245d11STodd Fiala     m_pid = pid;
1777af245d11STodd Fiala     SetState(eStateAttaching);
1778af245d11STodd Fiala 
1779bd7cbc5aSPavel Labath     StartMonitorThread ([=] (Error &e) { return Attach(pid, e); }, error);
1780af245d11STodd Fiala     if (!error.Success ())
1781af245d11STodd Fiala         return;
1782af245d11STodd Fiala }
1783af245d11STodd Fiala 
17848bc34f4dSOleksiy Vyalov void
17858bc34f4dSOleksiy Vyalov NativeProcessLinux::Terminate ()
1786af245d11STodd Fiala {
178745f5cb31SPavel Labath     m_monitor_up->Terminate();
1788af245d11STodd Fiala }
1789af245d11STodd Fiala 
1790bd7cbc5aSPavel Labath ::pid_t
1791bd7cbc5aSPavel Labath NativeProcessLinux::Launch(LaunchArgs *args, Error &error)
1792af245d11STodd Fiala {
17930bce1b67STodd Fiala     assert (args && "null args");
1794af245d11STodd Fiala 
1795af245d11STodd Fiala     const char **argv = args->m_argv;
1796af245d11STodd Fiala     const char **envp = args->m_envp;
1797af245d11STodd Fiala     const char *working_dir = args->m_working_dir;
1798af245d11STodd Fiala 
1799af245d11STodd Fiala     lldb_utility::PseudoTerminal terminal;
1800af245d11STodd Fiala     const size_t err_len = 1024;
1801af245d11STodd Fiala     char err_str[err_len];
1802af245d11STodd Fiala     lldb::pid_t pid;
1803af245d11STodd Fiala     NativeThreadProtocolSP thread_sp;
1804af245d11STodd Fiala 
1805af245d11STodd Fiala     lldb::ThreadSP inferior;
1806af245d11STodd Fiala 
1807af245d11STodd Fiala     // Propagate the environment if one is not supplied.
1808af245d11STodd Fiala     if (envp == NULL || envp[0] == NULL)
1809af245d11STodd Fiala         envp = const_cast<const char **>(environ);
1810af245d11STodd Fiala 
1811af245d11STodd Fiala     if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
1812af245d11STodd Fiala     {
1813bd7cbc5aSPavel Labath         error.SetErrorToGenericError();
1814bd7cbc5aSPavel Labath         error.SetErrorStringWithFormat("Process fork failed: %s", err_str);
1815bd7cbc5aSPavel Labath         return -1;
1816af245d11STodd Fiala     }
1817af245d11STodd Fiala 
1818af245d11STodd Fiala     // Recognized child exit status codes.
1819af245d11STodd Fiala     enum {
1820af245d11STodd Fiala         ePtraceFailed = 1,
1821af245d11STodd Fiala         eDupStdinFailed,
1822af245d11STodd Fiala         eDupStdoutFailed,
1823af245d11STodd Fiala         eDupStderrFailed,
1824af245d11STodd Fiala         eChdirFailed,
1825af245d11STodd Fiala         eExecFailed,
1826af245d11STodd Fiala         eSetGidFailed
1827af245d11STodd Fiala     };
1828af245d11STodd Fiala 
1829af245d11STodd Fiala     // Child process.
1830af245d11STodd Fiala     if (pid == 0)
1831af245d11STodd Fiala     {
183275f47c3aSTodd Fiala         // FIXME consider opening a pipe between parent/child and have this forked child
183375f47c3aSTodd Fiala         // send log info to parent re: launch status, in place of the log lines removed here.
1834af245d11STodd Fiala 
183575f47c3aSTodd Fiala         // Start tracing this child that is about to exec.
1836bd7cbc5aSPavel Labath         PTRACE(PTRACE_TRACEME, 0, nullptr, nullptr, 0, error);
1837bd7cbc5aSPavel Labath         if (error.Fail())
1838af245d11STodd Fiala             exit(ePtraceFailed);
1839af245d11STodd Fiala 
1840493c3a12SPavel Labath         // terminal has already dupped the tty descriptors to stdin/out/err.
1841493c3a12SPavel Labath         // This closes original fd from which they were copied (and avoids
1842493c3a12SPavel Labath         // leaking descriptors to the debugged process.
1843493c3a12SPavel Labath         terminal.CloseSlaveFileDescriptor();
1844493c3a12SPavel Labath 
1845af245d11STodd Fiala         // Do not inherit setgid powers.
1846af245d11STodd Fiala         if (setgid(getgid()) != 0)
1847af245d11STodd Fiala             exit(eSetGidFailed);
1848af245d11STodd Fiala 
1849af245d11STodd Fiala         // Attempt to have our own process group.
1850af245d11STodd Fiala         if (setpgid(0, 0) != 0)
1851af245d11STodd Fiala         {
185275f47c3aSTodd Fiala             // FIXME log that this failed. This is common.
1853af245d11STodd Fiala             // Don't allow this to prevent an inferior exec.
1854af245d11STodd Fiala         }
1855af245d11STodd Fiala 
1856af245d11STodd Fiala         // Dup file descriptors if needed.
185775f47c3aSTodd Fiala         if (!args->m_stdin_path.empty ())
185875f47c3aSTodd Fiala             if (!DupDescriptor(args->m_stdin_path.c_str (), STDIN_FILENO, O_RDONLY))
1859af245d11STodd Fiala                 exit(eDupStdinFailed);
1860af245d11STodd Fiala 
186175f47c3aSTodd Fiala         if (!args->m_stdout_path.empty ())
186214f4476aSTamas Berghammer             if (!DupDescriptor(args->m_stdout_path.c_str (), STDOUT_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
1863af245d11STodd Fiala                 exit(eDupStdoutFailed);
1864af245d11STodd Fiala 
186575f47c3aSTodd Fiala         if (!args->m_stderr_path.empty ())
186614f4476aSTamas Berghammer             if (!DupDescriptor(args->m_stderr_path.c_str (), STDERR_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
1867af245d11STodd Fiala                 exit(eDupStderrFailed);
1868af245d11STodd Fiala 
18699cf4f2c2SChaoren Lin         // Close everything besides stdin, stdout, and stderr that has no file
18709cf4f2c2SChaoren Lin         // action to avoid leaking
18719cf4f2c2SChaoren Lin         for (int fd = 3; fd < sysconf(_SC_OPEN_MAX); ++fd)
18729cf4f2c2SChaoren Lin             if (!args->m_launch_info.GetFileActionForFD(fd))
18739cf4f2c2SChaoren Lin                 close(fd);
18749cf4f2c2SChaoren Lin 
1875af245d11STodd Fiala         // Change working directory
1876af245d11STodd Fiala         if (working_dir != NULL && working_dir[0])
1877af245d11STodd Fiala           if (0 != ::chdir(working_dir))
1878af245d11STodd Fiala               exit(eChdirFailed);
1879af245d11STodd Fiala 
18800bce1b67STodd Fiala         // Disable ASLR if requested.
18810bce1b67STodd Fiala         if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR))
18820bce1b67STodd Fiala         {
18830bce1b67STodd Fiala             const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
18840bce1b67STodd Fiala             if (old_personality == -1)
18850bce1b67STodd Fiala             {
188675f47c3aSTodd Fiala                 // Can't retrieve Linux personality.  Cannot disable ASLR.
18870bce1b67STodd Fiala             }
18880bce1b67STodd Fiala             else
18890bce1b67STodd Fiala             {
18900bce1b67STodd Fiala                 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality);
18910bce1b67STodd Fiala                 if (new_personality == -1)
18920bce1b67STodd Fiala                 {
189375f47c3aSTodd Fiala                     // Disabling ASLR failed.
18940bce1b67STodd Fiala                 }
18950bce1b67STodd Fiala                 else
18960bce1b67STodd Fiala                 {
189775f47c3aSTodd Fiala                     // Disabling ASLR succeeded.
18980bce1b67STodd Fiala                 }
18990bce1b67STodd Fiala             }
19000bce1b67STodd Fiala         }
19010bce1b67STodd Fiala 
190275f47c3aSTodd Fiala         // Execute.  We should never return...
1903af245d11STodd Fiala         execve(argv[0],
1904af245d11STodd Fiala                const_cast<char *const *>(argv),
1905af245d11STodd Fiala                const_cast<char *const *>(envp));
190675f47c3aSTodd Fiala 
190775f47c3aSTodd Fiala         // ...unless exec fails.  In which case we definitely need to end the child here.
1908af245d11STodd Fiala         exit(eExecFailed);
1909af245d11STodd Fiala     }
1910af245d11STodd Fiala 
191175f47c3aSTodd Fiala     //
191275f47c3aSTodd Fiala     // This is the parent code here.
191375f47c3aSTodd Fiala     //
191475f47c3aSTodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
191575f47c3aSTodd Fiala 
1916af245d11STodd Fiala     // Wait for the child process to trap on its call to execve.
1917af245d11STodd Fiala     ::pid_t wpid;
1918af245d11STodd Fiala     int status;
1919af245d11STodd Fiala     if ((wpid = waitpid(pid, &status, 0)) < 0)
1920af245d11STodd Fiala     {
1921bd7cbc5aSPavel Labath         error.SetErrorToErrno();
1922af245d11STodd Fiala         if (log)
1923bd7cbc5aSPavel Labath             log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s",
1924bd7cbc5aSPavel Labath                     __FUNCTION__, error.AsCString ());
1925af245d11STodd Fiala 
1926af245d11STodd Fiala         // Mark the inferior as invalid.
1927af245d11STodd Fiala         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
1928bd7cbc5aSPavel Labath         SetState (StateType::eStateInvalid);
1929af245d11STodd Fiala 
1930bd7cbc5aSPavel Labath         return -1;
1931af245d11STodd Fiala     }
1932af245d11STodd Fiala     else if (WIFEXITED(status))
1933af245d11STodd Fiala     {
1934af245d11STodd Fiala         // open, dup or execve likely failed for some reason.
1935bd7cbc5aSPavel Labath         error.SetErrorToGenericError();
1936af245d11STodd Fiala         switch (WEXITSTATUS(status))
1937af245d11STodd Fiala         {
1938af245d11STodd Fiala             case ePtraceFailed:
1939bd7cbc5aSPavel Labath                 error.SetErrorString("Child ptrace failed.");
1940af245d11STodd Fiala                 break;
1941af245d11STodd Fiala             case eDupStdinFailed:
1942bd7cbc5aSPavel Labath                 error.SetErrorString("Child open stdin failed.");
1943af245d11STodd Fiala                 break;
1944af245d11STodd Fiala             case eDupStdoutFailed:
1945bd7cbc5aSPavel Labath                 error.SetErrorString("Child open stdout failed.");
1946af245d11STodd Fiala                 break;
1947af245d11STodd Fiala             case eDupStderrFailed:
1948bd7cbc5aSPavel Labath                 error.SetErrorString("Child open stderr failed.");
1949af245d11STodd Fiala                 break;
1950af245d11STodd Fiala             case eChdirFailed:
1951bd7cbc5aSPavel Labath                 error.SetErrorString("Child failed to set working directory.");
1952af245d11STodd Fiala                 break;
1953af245d11STodd Fiala             case eExecFailed:
1954bd7cbc5aSPavel Labath                 error.SetErrorString("Child exec failed.");
1955af245d11STodd Fiala                 break;
1956af245d11STodd Fiala             case eSetGidFailed:
1957bd7cbc5aSPavel Labath                 error.SetErrorString("Child setgid failed.");
1958af245d11STodd Fiala                 break;
1959af245d11STodd Fiala             default:
1960bd7cbc5aSPavel Labath                 error.SetErrorString("Child returned unknown exit status.");
1961af245d11STodd Fiala                 break;
1962af245d11STodd Fiala         }
1963af245d11STodd Fiala 
1964af245d11STodd Fiala         if (log)
1965af245d11STodd Fiala         {
1966af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
1967af245d11STodd Fiala                     __FUNCTION__,
1968af245d11STodd Fiala                     WEXITSTATUS(status));
1969af245d11STodd Fiala         }
1970af245d11STodd Fiala 
1971af245d11STodd Fiala         // Mark the inferior as invalid.
1972af245d11STodd Fiala         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
1973bd7cbc5aSPavel Labath         SetState (StateType::eStateInvalid);
1974af245d11STodd Fiala 
1975bd7cbc5aSPavel Labath         return -1;
1976af245d11STodd Fiala     }
1977af245d11STodd Fiala     assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
1978af245d11STodd Fiala            "Could not sync with inferior process.");
1979af245d11STodd Fiala 
1980af245d11STodd Fiala     if (log)
1981af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
1982af245d11STodd Fiala 
1983bd7cbc5aSPavel Labath     error = SetDefaultPtraceOpts(pid);
1984bd7cbc5aSPavel Labath     if (error.Fail())
1985af245d11STodd Fiala     {
1986af245d11STodd Fiala         if (log)
1987af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
1988bd7cbc5aSPavel Labath                     __FUNCTION__, error.AsCString ());
1989af245d11STodd Fiala 
1990af245d11STodd Fiala         // Mark the inferior as invalid.
1991af245d11STodd Fiala         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
1992bd7cbc5aSPavel Labath         SetState (StateType::eStateInvalid);
1993af245d11STodd Fiala 
1994bd7cbc5aSPavel Labath         return -1;
1995af245d11STodd Fiala     }
1996af245d11STodd Fiala 
1997af245d11STodd Fiala     // Release the master terminal descriptor and pass it off to the
1998af245d11STodd Fiala     // NativeProcessLinux instance.  Similarly stash the inferior pid.
1999bd7cbc5aSPavel Labath     m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
2000bd7cbc5aSPavel Labath     m_pid = pid;
2001af245d11STodd Fiala 
2002af245d11STodd Fiala     // Set the terminal fd to be in non blocking mode (it simplifies the
2003af245d11STodd Fiala     // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
2004af245d11STodd Fiala     // descriptor to read from).
2005bd7cbc5aSPavel Labath     error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
2006bd7cbc5aSPavel Labath     if (error.Fail())
2007af245d11STodd Fiala     {
2008af245d11STodd Fiala         if (log)
2009af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
2010bd7cbc5aSPavel Labath                     __FUNCTION__, error.AsCString ());
2011af245d11STodd Fiala 
2012af245d11STodd Fiala         // Mark the inferior as invalid.
2013af245d11STodd Fiala         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
2014bd7cbc5aSPavel Labath         SetState (StateType::eStateInvalid);
2015af245d11STodd Fiala 
2016bd7cbc5aSPavel Labath         return -1;
2017af245d11STodd Fiala     }
2018af245d11STodd Fiala 
2019af245d11STodd Fiala     if (log)
2020af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
2021af245d11STodd Fiala 
2022bd7cbc5aSPavel Labath     thread_sp = AddThread (pid);
2023af245d11STodd Fiala     assert (thread_sp && "AddThread() returned a nullptr thread");
2024cb84eebbSTamas Berghammer     std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
20251dbc6c9cSPavel Labath     ThreadWasCreated(pid);
2026af245d11STodd Fiala 
2027af245d11STodd Fiala     // Let our process instance know the thread has stopped.
2028bd7cbc5aSPavel Labath     SetCurrentThreadID (thread_sp->GetID ());
2029bd7cbc5aSPavel Labath     SetState (StateType::eStateStopped);
2030af245d11STodd Fiala 
2031af245d11STodd Fiala     if (log)
2032af245d11STodd Fiala     {
2033bd7cbc5aSPavel Labath         if (error.Success ())
2034af245d11STodd Fiala         {
2035af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
2036af245d11STodd Fiala         }
2037af245d11STodd Fiala         else
2038af245d11STodd Fiala         {
2039af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior launching failed: %s",
2040bd7cbc5aSPavel Labath                 __FUNCTION__, error.AsCString ());
2041bd7cbc5aSPavel Labath             return -1;
2042af245d11STodd Fiala         }
2043af245d11STodd Fiala     }
2044bd7cbc5aSPavel Labath     return pid;
2045af245d11STodd Fiala }
2046af245d11STodd Fiala 
2047bd7cbc5aSPavel Labath ::pid_t
2048bd7cbc5aSPavel Labath NativeProcessLinux::Attach(lldb::pid_t pid, Error &error)
2049af245d11STodd Fiala {
2050af245d11STodd Fiala     lldb::ThreadSP inferior;
2051af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2052af245d11STodd Fiala 
2053af245d11STodd Fiala     // Use a map to keep track of the threads which we have attached/need to attach.
2054af245d11STodd Fiala     Host::TidMap tids_to_attach;
2055af245d11STodd Fiala     if (pid <= 1)
2056af245d11STodd Fiala     {
2057bd7cbc5aSPavel Labath         error.SetErrorToGenericError();
2058bd7cbc5aSPavel Labath         error.SetErrorString("Attaching to process 1 is not allowed.");
2059bd7cbc5aSPavel Labath         return -1;
2060af245d11STodd Fiala     }
2061af245d11STodd Fiala 
2062af245d11STodd Fiala     while (Host::FindProcessThreads(pid, tids_to_attach))
2063af245d11STodd Fiala     {
2064af245d11STodd Fiala         for (Host::TidMap::iterator it = tids_to_attach.begin();
2065af245d11STodd Fiala              it != tids_to_attach.end();)
2066af245d11STodd Fiala         {
2067af245d11STodd Fiala             if (it->second == false)
2068af245d11STodd Fiala             {
2069af245d11STodd Fiala                 lldb::tid_t tid = it->first;
2070af245d11STodd Fiala 
2071af245d11STodd Fiala                 // Attach to the requested process.
2072af245d11STodd Fiala                 // An attach will cause the thread to stop with a SIGSTOP.
2073bd7cbc5aSPavel Labath                 PTRACE(PTRACE_ATTACH, tid, nullptr, nullptr, 0, error);
2074bd7cbc5aSPavel Labath                 if (error.Fail())
2075af245d11STodd Fiala                 {
2076af245d11STodd Fiala                     // No such thread. The thread may have exited.
2077af245d11STodd Fiala                     // More error handling may be needed.
2078bd7cbc5aSPavel Labath                     if (error.GetError() == ESRCH)
2079af245d11STodd Fiala                     {
2080af245d11STodd Fiala                         it = tids_to_attach.erase(it);
2081af245d11STodd Fiala                         continue;
2082af245d11STodd Fiala                     }
2083af245d11STodd Fiala                     else
2084bd7cbc5aSPavel Labath                         return -1;
2085af245d11STodd Fiala                 }
2086af245d11STodd Fiala 
2087af245d11STodd Fiala                 int status;
2088af245d11STodd Fiala                 // Need to use __WALL otherwise we receive an error with errno=ECHLD
2089af245d11STodd Fiala                 // At this point we should have a thread stopped if waitpid succeeds.
2090af245d11STodd Fiala                 if ((status = waitpid(tid, NULL, __WALL)) < 0)
2091af245d11STodd Fiala                 {
2092af245d11STodd Fiala                     // No such thread. The thread may have exited.
2093af245d11STodd Fiala                     // More error handling may be needed.
2094af245d11STodd Fiala                     if (errno == ESRCH)
2095af245d11STodd Fiala                     {
2096af245d11STodd Fiala                         it = tids_to_attach.erase(it);
2097af245d11STodd Fiala                         continue;
2098af245d11STodd Fiala                     }
2099af245d11STodd Fiala                     else
2100af245d11STodd Fiala                     {
2101bd7cbc5aSPavel Labath                         error.SetErrorToErrno();
2102bd7cbc5aSPavel Labath                         return -1;
2103af245d11STodd Fiala                     }
2104af245d11STodd Fiala                 }
2105af245d11STodd Fiala 
2106bd7cbc5aSPavel Labath                 error = SetDefaultPtraceOpts(tid);
2107bd7cbc5aSPavel Labath                 if (error.Fail())
2108bd7cbc5aSPavel Labath                     return -1;
2109af245d11STodd Fiala 
2110af245d11STodd Fiala                 if (log)
2111af245d11STodd Fiala                     log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
2112af245d11STodd Fiala 
2113af245d11STodd Fiala                 it->second = true;
2114af245d11STodd Fiala 
2115af245d11STodd Fiala                 // Create the thread, mark it as stopped.
2116bd7cbc5aSPavel Labath                 NativeThreadProtocolSP thread_sp (AddThread (static_cast<lldb::tid_t> (tid)));
2117af245d11STodd Fiala                 assert (thread_sp && "AddThread() returned a nullptr");
2118fa03ad2eSChaoren Lin 
2119fa03ad2eSChaoren Lin                 // This will notify this is a new thread and tell the system it is stopped.
2120cb84eebbSTamas Berghammer                 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
21211dbc6c9cSPavel Labath                 ThreadWasCreated(tid);
2122bd7cbc5aSPavel Labath                 SetCurrentThreadID (thread_sp->GetID ());
2123af245d11STodd Fiala             }
2124af245d11STodd Fiala 
2125af245d11STodd Fiala             // move the loop forward
2126af245d11STodd Fiala             ++it;
2127af245d11STodd Fiala         }
2128af245d11STodd Fiala     }
2129af245d11STodd Fiala 
2130af245d11STodd Fiala     if (tids_to_attach.size() > 0)
2131af245d11STodd Fiala     {
2132bd7cbc5aSPavel Labath         m_pid = pid;
2133af245d11STodd Fiala         // Let our process instance know the thread has stopped.
2134bd7cbc5aSPavel Labath         SetState (StateType::eStateStopped);
2135af245d11STodd Fiala     }
2136af245d11STodd Fiala     else
2137af245d11STodd Fiala     {
2138bd7cbc5aSPavel Labath         error.SetErrorToGenericError();
2139bd7cbc5aSPavel Labath         error.SetErrorString("No such process.");
2140bd7cbc5aSPavel Labath         return -1;
2141af245d11STodd Fiala     }
2142af245d11STodd Fiala 
2143bd7cbc5aSPavel Labath     return pid;
2144af245d11STodd Fiala }
2145af245d11STodd Fiala 
214697ccc294SChaoren Lin Error
2147af245d11STodd Fiala NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
2148af245d11STodd Fiala {
2149af245d11STodd Fiala     long ptrace_opts = 0;
2150af245d11STodd Fiala 
2151af245d11STodd Fiala     // Have the child raise an event on exit.  This is used to keep the child in
2152af245d11STodd Fiala     // limbo until it is destroyed.
2153af245d11STodd Fiala     ptrace_opts |= PTRACE_O_TRACEEXIT;
2154af245d11STodd Fiala 
2155af245d11STodd Fiala     // Have the tracer trace threads which spawn in the inferior process.
2156af245d11STodd Fiala     // TODO: if we want to support tracing the inferiors' child, add the
2157af245d11STodd Fiala     // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
2158af245d11STodd Fiala     ptrace_opts |= PTRACE_O_TRACECLONE;
2159af245d11STodd Fiala 
2160af245d11STodd Fiala     // Have the tracer notify us before execve returns
2161af245d11STodd Fiala     // (needed to disable legacy SIGTRAP generation)
2162af245d11STodd Fiala     ptrace_opts |= PTRACE_O_TRACEEXEC;
2163af245d11STodd Fiala 
216497ccc294SChaoren Lin     Error error;
216597ccc294SChaoren Lin     PTRACE(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts, 0, error);
216697ccc294SChaoren Lin     return error;
2167af245d11STodd Fiala }
2168af245d11STodd Fiala 
2169af245d11STodd Fiala static ExitType convert_pid_status_to_exit_type (int status)
2170af245d11STodd Fiala {
2171af245d11STodd Fiala     if (WIFEXITED (status))
2172af245d11STodd Fiala         return ExitType::eExitTypeExit;
2173af245d11STodd Fiala     else if (WIFSIGNALED (status))
2174af245d11STodd Fiala         return ExitType::eExitTypeSignal;
2175af245d11STodd Fiala     else if (WIFSTOPPED (status))
2176af245d11STodd Fiala         return ExitType::eExitTypeStop;
2177af245d11STodd Fiala     else
2178af245d11STodd Fiala     {
2179af245d11STodd Fiala         // We don't know what this is.
2180af245d11STodd Fiala         return ExitType::eExitTypeInvalid;
2181af245d11STodd Fiala     }
2182af245d11STodd Fiala }
2183af245d11STodd Fiala 
2184af245d11STodd Fiala static int convert_pid_status_to_return_code (int status)
2185af245d11STodd Fiala {
2186af245d11STodd Fiala     if (WIFEXITED (status))
2187af245d11STodd Fiala         return WEXITSTATUS (status);
2188af245d11STodd Fiala     else if (WIFSIGNALED (status))
2189af245d11STodd Fiala         return WTERMSIG (status);
2190af245d11STodd Fiala     else if (WIFSTOPPED (status))
2191af245d11STodd Fiala         return WSTOPSIG (status);
2192af245d11STodd Fiala     else
2193af245d11STodd Fiala     {
2194af245d11STodd Fiala         // We don't know what this is.
2195af245d11STodd Fiala         return ExitType::eExitTypeInvalid;
2196af245d11STodd Fiala     }
2197af245d11STodd Fiala }
2198af245d11STodd Fiala 
21991107b5a5SPavel Labath // Handles all waitpid events from the inferior process.
22001107b5a5SPavel Labath void
22011107b5a5SPavel Labath NativeProcessLinux::MonitorCallback(lldb::pid_t pid,
2202af245d11STodd Fiala                                     bool exited,
2203af245d11STodd Fiala                                     int signal,
2204af245d11STodd Fiala                                     int status)
2205af245d11STodd Fiala {
2206af245d11STodd Fiala     Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
2207af245d11STodd Fiala 
2208af245d11STodd Fiala     // Certain activities differ based on whether the pid is the tid of the main thread.
22091107b5a5SPavel Labath     const bool is_main_thread = (pid == GetID ());
2210af245d11STodd Fiala 
2211af245d11STodd Fiala     // Handle when the thread exits.
2212af245d11STodd Fiala     if (exited)
2213af245d11STodd Fiala     {
2214af245d11STodd Fiala         if (log)
221586fd8e45SChaoren Lin             log->Printf ("NativeProcessLinux::%s() got exit signal(%d) , tid = %"  PRIu64 " (%s main thread)", __FUNCTION__, signal, pid, is_main_thread ? "is" : "is not");
2216af245d11STodd Fiala 
2217af245d11STodd Fiala         // This is a thread that exited.  Ensure we're not tracking it anymore.
22181107b5a5SPavel Labath         const bool thread_found = StopTrackingThread (pid);
2219af245d11STodd Fiala 
2220af245d11STodd Fiala         if (is_main_thread)
2221af245d11STodd Fiala         {
2222af245d11STodd Fiala             // We only set the exit status and notify the delegate if we haven't already set the process
2223af245d11STodd Fiala             // state to an exited state.  We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
2224af245d11STodd Fiala             // for the main thread.
22251107b5a5SPavel Labath             const bool already_notified = (GetState() == StateType::eStateExited) || (GetState () == StateType::eStateCrashed);
2226af245d11STodd Fiala             if (!already_notified)
2227af245d11STodd Fiala             {
2228af245d11STodd Fiala                 if (log)
22291107b5a5SPavel 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 ()));
2230af245d11STodd Fiala                 // The main thread exited.  We're done monitoring.  Report to delegate.
22311107b5a5SPavel Labath                 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
2232af245d11STodd Fiala 
2233af245d11STodd Fiala                 // Notify delegate that our process has exited.
22341107b5a5SPavel Labath                 SetState (StateType::eStateExited, true);
2235af245d11STodd Fiala             }
2236af245d11STodd Fiala             else
2237af245d11STodd Fiala             {
2238af245d11STodd Fiala                 if (log)
2239af245d11STodd Fiala                     log->Printf ("NativeProcessLinux::%s() tid = %"  PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
2240af245d11STodd Fiala             }
2241af245d11STodd Fiala         }
2242af245d11STodd Fiala         else
2243af245d11STodd Fiala         {
2244af245d11STodd Fiala             // Do we want to report to the delegate in this case?  I think not.  If this was an orderly
2245af245d11STodd Fiala             // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
2246af245d11STodd Fiala             // and we would have done an all-stop then.
2247af245d11STodd Fiala             if (log)
2248af245d11STodd 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");
2249af245d11STodd Fiala         }
22501107b5a5SPavel Labath         return;
2251af245d11STodd Fiala     }
2252af245d11STodd Fiala 
2253af245d11STodd Fiala     // Get details on the signal raised.
2254af245d11STodd Fiala     siginfo_t info;
22551107b5a5SPavel Labath     const auto err = GetSignalInfo(pid, &info);
225697ccc294SChaoren Lin     if (err.Success())
2257fa03ad2eSChaoren Lin     {
2258fa03ad2eSChaoren Lin         // We have retrieved the signal info.  Dispatch appropriately.
2259fa03ad2eSChaoren Lin         if (info.si_signo == SIGTRAP)
22601107b5a5SPavel Labath             MonitorSIGTRAP(&info, pid);
2261fa03ad2eSChaoren Lin         else
22621107b5a5SPavel Labath             MonitorSignal(&info, pid, exited);
2263fa03ad2eSChaoren Lin     }
2264fa03ad2eSChaoren Lin     else
2265af245d11STodd Fiala     {
226697ccc294SChaoren Lin         if (err.GetError() == EINVAL)
2267af245d11STodd Fiala         {
2268fa03ad2eSChaoren Lin             // This is a group stop reception for this tid.
2269fa03ad2eSChaoren Lin             if (log)
22701dbc6c9cSPavel Labath                 log->Printf ("NativeProcessLinux::%s received a group stop for pid %" PRIu64 " tid %" PRIu64, __FUNCTION__, GetID (), pid);
22711dbc6c9cSPavel Labath             ThreadDidStop(pid, false);
2272a9882ceeSTodd Fiala         }
2273a9882ceeSTodd Fiala         else
2274a9882ceeSTodd Fiala         {
2275af245d11STodd Fiala             // ptrace(GETSIGINFO) failed (but not due to group-stop).
2276af245d11STodd Fiala 
2277af245d11STodd Fiala             // A return value of ESRCH means the thread/process is no longer on the system,
2278af245d11STodd Fiala             // so it was killed somehow outside of our control.  Either way, we can't do anything
2279af245d11STodd Fiala             // with it anymore.
2280af245d11STodd Fiala 
2281af245d11STodd Fiala             // Stop tracking the metadata for the thread since it's entirely off the system now.
22821107b5a5SPavel Labath             const bool thread_found = StopTrackingThread (pid);
2283af245d11STodd Fiala 
2284af245d11STodd Fiala             if (log)
2285af245d11STodd Fiala                 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
228697ccc294SChaoren 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");
2287af245d11STodd Fiala 
2288af245d11STodd Fiala             if (is_main_thread)
2289af245d11STodd Fiala             {
2290af245d11STodd Fiala                 // Notify the delegate - our process is not available but appears to have been killed outside
2291af245d11STodd Fiala                 // our control.  Is eStateExited the right exit state in this case?
22921107b5a5SPavel Labath                 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
22931107b5a5SPavel Labath                 SetState (StateType::eStateExited, true);
2294af245d11STodd Fiala             }
2295af245d11STodd Fiala             else
2296af245d11STodd Fiala             {
2297af245d11STodd Fiala                 // This thread was pulled out from underneath us.  Anything to do here? Do we want to do an all stop?
2298af245d11STodd Fiala                 if (log)
22991107b5a5SPavel 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);
2300af245d11STodd Fiala             }
2301af245d11STodd Fiala         }
2302af245d11STodd Fiala     }
2303af245d11STodd Fiala }
2304af245d11STodd Fiala 
2305af245d11STodd Fiala void
2306426bdf88SPavel Labath NativeProcessLinux::WaitForNewThread(::pid_t tid)
2307426bdf88SPavel Labath {
2308426bdf88SPavel Labath     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2309426bdf88SPavel Labath 
2310426bdf88SPavel Labath     NativeThreadProtocolSP new_thread_sp = GetThreadByID(tid);
2311426bdf88SPavel Labath 
2312426bdf88SPavel Labath     if (new_thread_sp)
2313426bdf88SPavel Labath     {
2314426bdf88SPavel Labath         // We are already tracking the thread - we got the event on the new thread (see
2315426bdf88SPavel Labath         // MonitorSignal) before this one. We are done.
2316426bdf88SPavel Labath         return;
2317426bdf88SPavel Labath     }
2318426bdf88SPavel Labath 
2319426bdf88SPavel Labath     // The thread is not tracked yet, let's wait for it to appear.
2320426bdf88SPavel Labath     int status = -1;
2321426bdf88SPavel Labath     ::pid_t wait_pid;
2322426bdf88SPavel Labath     do
2323426bdf88SPavel Labath     {
2324426bdf88SPavel Labath         if (log)
2325426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() received thread creation event for tid %" PRIu32 ". tid not tracked yet, waiting for thread to appear...", __FUNCTION__, tid);
2326426bdf88SPavel Labath         wait_pid = waitpid(tid, &status, __WALL);
2327426bdf88SPavel Labath     }
2328426bdf88SPavel Labath     while (wait_pid == -1 && errno == EINTR);
2329426bdf88SPavel Labath     // Since we are waiting on a specific tid, this must be the creation event. But let's do
2330426bdf88SPavel Labath     // some checks just in case.
2331426bdf88SPavel Labath     if (wait_pid != tid) {
2332426bdf88SPavel Labath         if (log)
2333426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime", __FUNCTION__, tid);
2334426bdf88SPavel Labath         // The only way I know of this could happen is if the whole process was
2335426bdf88SPavel Labath         // SIGKILLed in the mean time. In any case, we can't do anything about that now.
2336426bdf88SPavel Labath         return;
2337426bdf88SPavel Labath     }
2338426bdf88SPavel Labath     if (WIFEXITED(status))
2339426bdf88SPavel Labath     {
2340426bdf88SPavel Labath         if (log)
2341426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " returned an 'exited' event. Not tracking the thread.", __FUNCTION__, tid);
2342426bdf88SPavel Labath         // Also a very improbable event.
2343426bdf88SPavel Labath         return;
2344426bdf88SPavel Labath     }
2345426bdf88SPavel Labath 
2346426bdf88SPavel Labath     siginfo_t info;
2347426bdf88SPavel Labath     Error error = GetSignalInfo(tid, &info);
2348426bdf88SPavel Labath     if (error.Fail())
2349426bdf88SPavel Labath     {
2350426bdf88SPavel Labath         if (log)
2351426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime.", __FUNCTION__, tid);
2352426bdf88SPavel Labath         return;
2353426bdf88SPavel Labath     }
2354426bdf88SPavel Labath 
2355426bdf88SPavel Labath     if (((info.si_pid != 0) || (info.si_code != SI_USER)) && log)
2356426bdf88SPavel Labath     {
2357426bdf88SPavel Labath         // We should be getting a thread creation signal here, but we received something
2358426bdf88SPavel Labath         // else. There isn't much we can do about it now, so we will just log that. Since the
2359426bdf88SPavel Labath         // thread is alive and we are receiving events from it, we shall pretend that it was
2360426bdf88SPavel Labath         // created properly.
2361426bdf88SPavel 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);
2362426bdf88SPavel Labath     }
2363426bdf88SPavel Labath 
2364426bdf88SPavel Labath     if (log)
2365426bdf88SPavel Labath         log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 ": tracking new thread tid %" PRIu32,
2366426bdf88SPavel Labath                  __FUNCTION__, GetID (), tid);
2367426bdf88SPavel Labath 
2368426bdf88SPavel Labath     new_thread_sp = AddThread(tid);
2369426bdf88SPavel Labath     std::static_pointer_cast<NativeThreadLinux> (new_thread_sp)->SetRunning ();
2370426bdf88SPavel Labath     Resume (tid, LLDB_INVALID_SIGNAL_NUMBER);
23711dbc6c9cSPavel Labath     ThreadWasCreated(tid);
2372426bdf88SPavel Labath }
2373426bdf88SPavel Labath 
2374426bdf88SPavel Labath void
2375af245d11STodd Fiala NativeProcessLinux::MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid)
2376af245d11STodd Fiala {
2377af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2378af245d11STodd Fiala     const bool is_main_thread = (pid == GetID ());
2379af245d11STodd Fiala 
2380af245d11STodd Fiala     assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
2381af245d11STodd Fiala     if (!info)
2382af245d11STodd Fiala         return;
2383af245d11STodd Fiala 
23845830aa75STamas Berghammer     Mutex::Locker locker (m_threads_mutex);
23855830aa75STamas Berghammer 
2386af245d11STodd Fiala     // See if we can find a thread for this signal.
2387af245d11STodd Fiala     NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2388af245d11STodd Fiala     if (!thread_sp)
2389af245d11STodd Fiala     {
2390af245d11STodd Fiala         if (log)
2391af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2392af245d11STodd Fiala     }
2393af245d11STodd Fiala 
2394af245d11STodd Fiala     switch (info->si_code)
2395af245d11STodd Fiala     {
2396af245d11STodd 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.
2397af245d11STodd Fiala     // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
2398af245d11STodd Fiala     // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
2399af245d11STodd Fiala 
2400af245d11STodd Fiala     case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
2401af245d11STodd Fiala     {
24025fd24c67SPavel Labath         // This is the notification on the parent thread which informs us of new thread
2403426bdf88SPavel Labath         // creation.
2404426bdf88SPavel Labath         // We don't want to do anything with the parent thread so we just resume it. In case we
2405426bdf88SPavel Labath         // want to implement "break on thread creation" functionality, we would need to stop
2406426bdf88SPavel Labath         // here.
2407af245d11STodd Fiala 
2408af245d11STodd Fiala         unsigned long event_message = 0;
2409426bdf88SPavel Labath         if (GetEventMessage (pid, &event_message).Fail())
2410fa03ad2eSChaoren Lin         {
2411426bdf88SPavel Labath             if (log)
2412fa03ad2eSChaoren Lin                 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " received thread creation event but GetEventMessage failed so we don't know the new tid", __FUNCTION__, pid);
2413426bdf88SPavel Labath         } else
2414426bdf88SPavel Labath             WaitForNewThread(event_message);
2415af245d11STodd Fiala 
24165fd24c67SPavel Labath         Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
2417af245d11STodd Fiala         break;
2418af245d11STodd Fiala     }
2419af245d11STodd Fiala 
2420af245d11STodd Fiala     case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
2421a9882ceeSTodd Fiala     {
2422a9882ceeSTodd Fiala         NativeThreadProtocolSP main_thread_sp;
2423af245d11STodd Fiala         if (log)
2424af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
2425a9882ceeSTodd Fiala 
24261dbc6c9cSPavel Labath         // Exec clears any pending notifications.
24271dbc6c9cSPavel Labath         m_pending_notification_up.reset ();
2428fa03ad2eSChaoren Lin 
2429fa03ad2eSChaoren 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.
2430a9882ceeSTodd Fiala         if (log)
2431a9882ceeSTodd Fiala             log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
2432a9882ceeSTodd Fiala 
2433a9882ceeSTodd Fiala         for (auto thread_sp : m_threads)
2434a9882ceeSTodd Fiala         {
2435a9882ceeSTodd Fiala             const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
2436a9882ceeSTodd Fiala             if (is_main_thread)
2437a9882ceeSTodd Fiala             {
2438a9882ceeSTodd Fiala                 main_thread_sp = thread_sp;
2439a9882ceeSTodd Fiala                 if (log)
2440a9882ceeSTodd Fiala                     log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
2441a9882ceeSTodd Fiala             }
2442a9882ceeSTodd Fiala             else
2443a9882ceeSTodd Fiala             {
2444fa03ad2eSChaoren Lin                 // Tell thread coordinator this thread is dead.
2445a9882ceeSTodd Fiala                 if (log)
2446a9882ceeSTodd Fiala                     log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
2447a9882ceeSTodd Fiala             }
2448a9882ceeSTodd Fiala         }
2449a9882ceeSTodd Fiala 
2450a9882ceeSTodd Fiala         m_threads.clear ();
2451a9882ceeSTodd Fiala 
2452a9882ceeSTodd Fiala         if (main_thread_sp)
2453a9882ceeSTodd Fiala         {
2454a9882ceeSTodd Fiala             m_threads.push_back (main_thread_sp);
2455a9882ceeSTodd Fiala             SetCurrentThreadID (main_thread_sp->GetID ());
2456cb84eebbSTamas Berghammer             std::static_pointer_cast<NativeThreadLinux> (main_thread_sp)->SetStoppedByExec ();
2457a9882ceeSTodd Fiala         }
2458a9882ceeSTodd Fiala         else
2459a9882ceeSTodd Fiala         {
2460a9882ceeSTodd Fiala             SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
2461a9882ceeSTodd Fiala             if (log)
2462a9882ceeSTodd Fiala                 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
2463a9882ceeSTodd Fiala         }
2464a9882ceeSTodd Fiala 
2465fa03ad2eSChaoren Lin         // Tell coordinator about about the "new" (since exec) stopped main thread.
2466fa03ad2eSChaoren Lin         const lldb::tid_t main_thread_tid = GetID ();
24671dbc6c9cSPavel Labath         ThreadWasCreated(main_thread_tid);
2468fa03ad2eSChaoren Lin 
2469fa03ad2eSChaoren Lin         // NOTE: ideally these next statements would execute at the same time as the coordinator thread create was executed.
2470fa03ad2eSChaoren Lin         // Consider a handler that can execute when that happens.
2471a9882ceeSTodd Fiala         // Let our delegate know we have just exec'd.
2472a9882ceeSTodd Fiala         NotifyDidExec ();
2473a9882ceeSTodd Fiala 
2474a9882ceeSTodd Fiala         // If we have a main thread, indicate we are stopped.
2475a9882ceeSTodd Fiala         assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
2476fa03ad2eSChaoren Lin 
2477fa03ad2eSChaoren Lin         // Let the process know we're stopped.
2478ed89c7feSPavel Labath         StopRunningThreads (pid);
2479a9882ceeSTodd Fiala 
2480af245d11STodd Fiala         break;
2481a9882ceeSTodd Fiala     }
2482af245d11STodd Fiala 
2483af245d11STodd Fiala     case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
2484af245d11STodd Fiala     {
2485af245d11STodd Fiala         // The inferior process or one of its threads is about to exit.
24868c8ff7afSPavel Labath         if (! thread_sp)
24878c8ff7afSPavel Labath             break;
2488fa03ad2eSChaoren Lin 
2489fa03ad2eSChaoren Lin         // This thread is currently stopped.  It's not actually dead yet, just about to be.
24901dbc6c9cSPavel Labath         ThreadDidStop (pid, false);
24918c8ff7afSPavel Labath         // The actual stop reason does not matter much, as we are going to resume the thread a
24928c8ff7afSPavel Labath         // few lines down. If we ever want to report this state to the debugger, then we should
24938c8ff7afSPavel Labath         // invent a new stop reason.
24948c8ff7afSPavel Labath         std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedBySignal(LLDB_INVALID_SIGNAL_NUMBER);
2495fa03ad2eSChaoren Lin 
2496af245d11STodd Fiala         unsigned long data = 0;
249797ccc294SChaoren Lin         if (GetEventMessage(pid, &data).Fail())
2498af245d11STodd Fiala             data = -1;
2499af245d11STodd Fiala 
2500af245d11STodd Fiala         if (log)
2501af245d11STodd Fiala         {
2502af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
2503af245d11STodd Fiala                          __FUNCTION__,
2504af245d11STodd Fiala                          data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
2505af245d11STodd Fiala                          pid,
2506af245d11STodd Fiala                     is_main_thread ? "is main thread" : "not main thread");
2507af245d11STodd Fiala         }
2508af245d11STodd Fiala 
2509af245d11STodd Fiala         if (is_main_thread)
2510af245d11STodd Fiala         {
2511af245d11STodd Fiala             SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
251275f47c3aSTodd Fiala         }
251375f47c3aSTodd Fiala 
25149d617ba6SChaoren Lin         const int signo = static_cast<int> (data);
25151dbc6c9cSPavel Labath         ResumeThread(pid,
251686fd8e45SChaoren Lin                 [=](lldb::tid_t tid_to_resume, bool supress_signal)
2517fa03ad2eSChaoren Lin                 {
2518cb84eebbSTamas Berghammer                     std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
251937c768caSChaoren Lin                     return Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo);
25201dbc6c9cSPavel Labath                 },
25211dbc6c9cSPavel Labath                 true);
2522af245d11STodd Fiala 
2523af245d11STodd Fiala         break;
2524af245d11STodd Fiala     }
2525af245d11STodd Fiala 
2526af245d11STodd Fiala     case 0:
2527c16f5dcaSChaoren Lin     case TRAP_TRACE:  // We receive this on single stepping.
2528c16f5dcaSChaoren Lin     case TRAP_HWBKPT: // We receive this on watchpoint hit
252986fd8e45SChaoren Lin         if (thread_sp)
253086fd8e45SChaoren Lin         {
2531c16f5dcaSChaoren Lin             // If a watchpoint was hit, report it
2532c16f5dcaSChaoren Lin             uint32_t wp_index;
2533ea8c25a8SOmair Javaid             Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index, (lldb::addr_t)info->si_addr);
2534c16f5dcaSChaoren Lin             if (error.Fail() && log)
2535c16f5dcaSChaoren Lin                 log->Printf("NativeProcessLinux::%s() "
2536c16f5dcaSChaoren Lin                             "received error while checking for watchpoint hits, "
2537c16f5dcaSChaoren Lin                             "pid = %" PRIu64 " error = %s",
2538c16f5dcaSChaoren Lin                             __FUNCTION__, pid, error.AsCString());
2539c16f5dcaSChaoren Lin             if (wp_index != LLDB_INVALID_INDEX32)
25405830aa75STamas Berghammer             {
2541c16f5dcaSChaoren Lin                 MonitorWatchpoint(pid, thread_sp, wp_index);
2542c16f5dcaSChaoren Lin                 break;
2543c16f5dcaSChaoren Lin             }
2544c16f5dcaSChaoren Lin         }
2545c16f5dcaSChaoren Lin         // Otherwise, report step over
2546c16f5dcaSChaoren Lin         MonitorTrace(pid, thread_sp);
2547af245d11STodd Fiala         break;
2548af245d11STodd Fiala 
2549af245d11STodd Fiala     case SI_KERNEL:
2550af245d11STodd Fiala     case TRAP_BRKPT:
2551c16f5dcaSChaoren Lin         MonitorBreakpoint(pid, thread_sp);
2552af245d11STodd Fiala         break;
2553af245d11STodd Fiala 
2554af245d11STodd Fiala     case SIGTRAP:
2555af245d11STodd Fiala     case (SIGTRAP | 0x80):
2556af245d11STodd Fiala         if (log)
2557fa03ad2eSChaoren Lin             log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), pid);
2558fa03ad2eSChaoren Lin 
2559fa03ad2eSChaoren Lin         // This thread is currently stopped.
25601dbc6c9cSPavel Labath         ThreadDidStop (pid, false);
2561fa03ad2eSChaoren Lin         if (thread_sp)
2562cb84eebbSTamas Berghammer             std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGTRAP);
2563fa03ad2eSChaoren Lin 
2564fa03ad2eSChaoren Lin 
2565af245d11STodd Fiala         // Ignore these signals until we know more about them.
25661dbc6c9cSPavel Labath         ResumeThread(pid,
256786fd8e45SChaoren Lin                 [=](lldb::tid_t tid_to_resume, bool supress_signal)
2568fa03ad2eSChaoren Lin                 {
2569cb84eebbSTamas Berghammer                     std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
257037c768caSChaoren Lin                     return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
25711dbc6c9cSPavel Labath                 },
25721dbc6c9cSPavel Labath                 true);
2573af245d11STodd Fiala         break;
2574af245d11STodd Fiala 
2575af245d11STodd Fiala     default:
2576af245d11STodd Fiala         assert(false && "Unexpected SIGTRAP code!");
2577af245d11STodd Fiala         if (log)
2578af245d11STodd 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)));
2579af245d11STodd Fiala         break;
2580af245d11STodd Fiala 
2581af245d11STodd Fiala     }
2582af245d11STodd Fiala }
2583af245d11STodd Fiala 
2584af245d11STodd Fiala void
2585c16f5dcaSChaoren Lin NativeProcessLinux::MonitorTrace(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
2586c16f5dcaSChaoren Lin {
2587c16f5dcaSChaoren Lin     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2588c16f5dcaSChaoren Lin     if (log)
2589c16f5dcaSChaoren Lin         log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)",
2590c16f5dcaSChaoren Lin                 __FUNCTION__, pid);
2591c16f5dcaSChaoren Lin 
2592c16f5dcaSChaoren Lin     if (thread_sp)
2593c16f5dcaSChaoren Lin         std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
2594c16f5dcaSChaoren Lin 
2595c16f5dcaSChaoren Lin     // This thread is currently stopped.
25961dbc6c9cSPavel Labath     ThreadDidStop(pid, false);
2597c16f5dcaSChaoren Lin 
2598c16f5dcaSChaoren Lin     // Here we don't have to request the rest of the threads to stop or request a deferred stop.
2599c16f5dcaSChaoren Lin     // This would have already happened at the time the Resume() with step operation was signaled.
2600c16f5dcaSChaoren Lin     // At this point, we just need to say we stopped, and the deferred notifcation will fire off
2601c16f5dcaSChaoren Lin     // once all running threads have checked in as stopped.
2602c16f5dcaSChaoren Lin     SetCurrentThreadID(pid);
2603c16f5dcaSChaoren Lin     // Tell the process we have a stop (from software breakpoint).
2604ed89c7feSPavel Labath     StopRunningThreads(pid);
2605c16f5dcaSChaoren Lin }
2606c16f5dcaSChaoren Lin 
2607c16f5dcaSChaoren Lin void
2608c16f5dcaSChaoren Lin NativeProcessLinux::MonitorBreakpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
2609c16f5dcaSChaoren Lin {
2610c16f5dcaSChaoren Lin     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
2611c16f5dcaSChaoren Lin     if (log)
2612c16f5dcaSChaoren Lin         log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
2613c16f5dcaSChaoren Lin                 __FUNCTION__, pid);
2614c16f5dcaSChaoren Lin 
2615c16f5dcaSChaoren Lin     // This thread is currently stopped.
26161dbc6c9cSPavel Labath     ThreadDidStop(pid, false);
2617c16f5dcaSChaoren Lin 
2618c16f5dcaSChaoren Lin     // Mark the thread as stopped at breakpoint.
2619c16f5dcaSChaoren Lin     if (thread_sp)
2620c16f5dcaSChaoren Lin     {
2621c16f5dcaSChaoren Lin         std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByBreakpoint();
2622c16f5dcaSChaoren Lin         Error error = FixupBreakpointPCAsNeeded(thread_sp);
2623c16f5dcaSChaoren Lin         if (error.Fail())
2624c16f5dcaSChaoren Lin             if (log)
2625c16f5dcaSChaoren Lin                 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
2626c16f5dcaSChaoren Lin                         __FUNCTION__, pid, error.AsCString());
2627d8c338d4STamas Berghammer 
2628d8c338d4STamas Berghammer         auto it = m_threads_stepping_with_breakpoint.find(pid);
2629d8c338d4STamas Berghammer         if (it != m_threads_stepping_with_breakpoint.end())
2630d8c338d4STamas Berghammer         {
2631d8c338d4STamas Berghammer             Error error = RemoveBreakpoint (it->second);
2632d8c338d4STamas Berghammer             if (error.Fail())
2633d8c338d4STamas Berghammer                 if (log)
2634d8c338d4STamas Berghammer                     log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " remove stepping breakpoint: %s",
2635d8c338d4STamas Berghammer                             __FUNCTION__, pid, error.AsCString());
2636d8c338d4STamas Berghammer 
2637d8c338d4STamas Berghammer             m_threads_stepping_with_breakpoint.erase(it);
2638d8c338d4STamas Berghammer             std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
2639d8c338d4STamas Berghammer         }
2640c16f5dcaSChaoren Lin     }
2641c16f5dcaSChaoren Lin     else
2642c16f5dcaSChaoren Lin         if (log)
2643c16f5dcaSChaoren Lin             log->Printf("NativeProcessLinux::%s()  pid = %" PRIu64 ": "
2644c16f5dcaSChaoren Lin                     "warning, cannot process software breakpoint since no thread metadata",
2645c16f5dcaSChaoren Lin                     __FUNCTION__, pid);
2646c16f5dcaSChaoren Lin 
2647c16f5dcaSChaoren Lin 
2648c16f5dcaSChaoren Lin     // We need to tell all other running threads before we notify the delegate about this stop.
2649ed89c7feSPavel Labath     StopRunningThreads(pid);
2650c16f5dcaSChaoren Lin }
2651c16f5dcaSChaoren Lin 
2652c16f5dcaSChaoren Lin void
2653c16f5dcaSChaoren Lin NativeProcessLinux::MonitorWatchpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp, uint32_t wp_index)
2654c16f5dcaSChaoren Lin {
2655c16f5dcaSChaoren Lin     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
2656c16f5dcaSChaoren Lin     if (log)
2657c16f5dcaSChaoren Lin         log->Printf("NativeProcessLinux::%s() received watchpoint event, "
2658c16f5dcaSChaoren Lin                     "pid = %" PRIu64 ", wp_index = %" PRIu32,
2659c16f5dcaSChaoren Lin                     __FUNCTION__, pid, wp_index);
2660c16f5dcaSChaoren Lin 
2661c16f5dcaSChaoren Lin     // This thread is currently stopped.
26621dbc6c9cSPavel Labath     ThreadDidStop(pid, false);
2663c16f5dcaSChaoren Lin 
2664c16f5dcaSChaoren Lin     // Mark the thread as stopped at watchpoint.
2665c16f5dcaSChaoren Lin     // The address is at (lldb::addr_t)info->si_addr if we need it.
2666c16f5dcaSChaoren Lin     lldbassert(thread_sp && "thread_sp cannot be NULL");
2667c16f5dcaSChaoren Lin     std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByWatchpoint(wp_index);
2668c16f5dcaSChaoren Lin 
2669c16f5dcaSChaoren Lin     // We need to tell all other running threads before we notify the delegate about this stop.
2670ed89c7feSPavel Labath     StopRunningThreads(pid);
2671c16f5dcaSChaoren Lin }
2672c16f5dcaSChaoren Lin 
2673c16f5dcaSChaoren Lin void
2674af245d11STodd Fiala NativeProcessLinux::MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited)
2675af245d11STodd Fiala {
2676511e5cdcSTodd Fiala     assert (info && "null info");
2677511e5cdcSTodd Fiala     if (!info)
2678511e5cdcSTodd Fiala         return;
2679511e5cdcSTodd Fiala 
2680511e5cdcSTodd Fiala     const int signo = info->si_signo;
2681511e5cdcSTodd Fiala     const bool is_from_llgs = info->si_pid == getpid ();
2682af245d11STodd Fiala 
2683af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2684af245d11STodd Fiala 
2685af245d11STodd Fiala     // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
2686af245d11STodd Fiala     // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
2687af245d11STodd Fiala     // kill(2) or raise(3).  Similarly for tgkill(2) on Linux.
2688af245d11STodd Fiala     //
2689af245d11STodd Fiala     // IOW, user generated signals never generate what we consider to be a
2690af245d11STodd Fiala     // "crash".
2691af245d11STodd Fiala     //
2692af245d11STodd Fiala     // Similarly, ACK signals generated by this monitor.
2693af245d11STodd Fiala 
26945830aa75STamas Berghammer     Mutex::Locker locker (m_threads_mutex);
26955830aa75STamas Berghammer 
2696af245d11STodd Fiala     // See if we can find a thread for this signal.
2697af245d11STodd Fiala     NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2698af245d11STodd Fiala     if (!thread_sp)
2699af245d11STodd Fiala     {
2700af245d11STodd Fiala         if (log)
2701af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2702af245d11STodd Fiala     }
2703af245d11STodd Fiala 
2704af245d11STodd Fiala     // Handle the signal.
2705af245d11STodd Fiala     if (info->si_code == SI_TKILL || info->si_code == SI_USER)
2706af245d11STodd Fiala     {
2707af245d11STodd Fiala         if (log)
2708af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
2709af245d11STodd Fiala                             __FUNCTION__,
2710af245d11STodd Fiala                             GetUnixSignals ().GetSignalAsCString (signo),
2711af245d11STodd Fiala                             signo,
2712af245d11STodd Fiala                             (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
2713af245d11STodd Fiala                             info->si_pid,
2714511e5cdcSTodd Fiala                             is_from_llgs ? "from llgs" : "not from llgs",
2715af245d11STodd Fiala                             pid);
271658a2f669STodd Fiala     }
2717af245d11STodd Fiala 
271858a2f669STodd Fiala     // Check for new thread notification.
271958a2f669STodd Fiala     if ((info->si_pid == 0) && (info->si_code == SI_USER))
2720af245d11STodd Fiala     {
2721af245d11STodd Fiala         // A new thread creation is being signaled. This is one of two parts that come in
2722426bdf88SPavel Labath         // a non-deterministic order. This code handles the case where the new thread event comes
2723426bdf88SPavel Labath         // before the event on the parent thread. For the opposite case see code in
2724426bdf88SPavel Labath         // MonitorSIGTRAP.
2725af245d11STodd Fiala         if (log)
2726af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": new thread notification",
2727af245d11STodd Fiala                      __FUNCTION__, GetID (), pid);
2728af245d11STodd Fiala 
27295fd24c67SPavel Labath         thread_sp = AddThread(pid);
27305fd24c67SPavel Labath         assert (thread_sp.get() && "failed to create the tracking data for newly created inferior thread");
27315fd24c67SPavel Labath         // We can now resume the newly created thread.
2732cb84eebbSTamas Berghammer         std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
27335fd24c67SPavel Labath         Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
27341dbc6c9cSPavel Labath         ThreadWasCreated(pid);
273558a2f669STodd Fiala         // Done handling.
273658a2f669STodd Fiala         return;
2737af245d11STodd Fiala     }
273858a2f669STodd Fiala 
273958a2f669STodd Fiala     // Check for thread stop notification.
2740511e5cdcSTodd Fiala     if (is_from_llgs && (info->si_code == SI_TKILL) && (signo == SIGSTOP))
2741af245d11STodd Fiala     {
2742af245d11STodd Fiala         // This is a tgkill()-based stop.
2743af245d11STodd Fiala         if (thread_sp)
2744af245d11STodd Fiala         {
2745fa03ad2eSChaoren Lin             if (log)
2746fa03ad2eSChaoren Lin                 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
2747fa03ad2eSChaoren Lin                              __FUNCTION__,
2748fa03ad2eSChaoren Lin                              GetID (),
2749fa03ad2eSChaoren Lin                              pid);
2750fa03ad2eSChaoren Lin 
2751aab58633SChaoren Lin             // Check that we're not already marked with a stop reason.
2752aab58633SChaoren Lin             // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
2753aab58633SChaoren Lin             // the kernel signaled us with the thread stopping which we handled and marked as stopped,
2754aab58633SChaoren Lin             // and that, without an intervening resume, we received another stop.  It is more likely
2755aab58633SChaoren Lin             // that we are missing the marking of a run state somewhere if we find that the thread was
2756aab58633SChaoren Lin             // marked as stopped.
2757cb84eebbSTamas Berghammer             std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
2758cb84eebbSTamas Berghammer             assert (linux_thread_sp && "linux_thread_sp is null!");
2759aab58633SChaoren Lin 
2760cb84eebbSTamas Berghammer             const StateType thread_state = linux_thread_sp->GetState ();
2761aab58633SChaoren Lin             if (!StateIsStoppedState (thread_state, false))
2762aab58633SChaoren Lin             {
2763ed89c7feSPavel Labath                 // An inferior thread has stopped because of a SIGSTOP we have sent it.
2764ed89c7feSPavel Labath                 // Generally, these are not important stops and we don't want to report them as
2765ed89c7feSPavel Labath                 // they are just used to stop other threads when one thread (the one with the
2766ed89c7feSPavel Labath                 // *real* stop reason) hits a breakpoint (watchpoint, etc...). However, in the
2767ed89c7feSPavel Labath                 // case of an asynchronous Interrupt(), this *is* the real stop reason, so we
2768ed89c7feSPavel Labath                 // leave the signal intact if this is the thread that was chosen as the
2769ed89c7feSPavel Labath                 // triggering thread.
2770ed89c7feSPavel Labath                 if (m_pending_notification_up && m_pending_notification_up->triggering_tid == pid)
2771ed89c7feSPavel Labath                     linux_thread_sp->SetStoppedBySignal(SIGSTOP);
2772ed89c7feSPavel Labath                 else
2773cb84eebbSTamas Berghammer                     linux_thread_sp->SetStoppedBySignal(0);
2774ed89c7feSPavel Labath 
2775af245d11STodd Fiala                 SetCurrentThreadID (thread_sp->GetID ());
27761dbc6c9cSPavel Labath                 ThreadDidStop (thread_sp->GetID (), true);
2777aab58633SChaoren Lin             }
2778aab58633SChaoren Lin             else
2779aab58633SChaoren Lin             {
2780aab58633SChaoren Lin                 if (log)
2781aab58633SChaoren Lin                 {
2782aab58633SChaoren Lin                     // Retrieve the signal name if the thread was stopped by a signal.
2783aab58633SChaoren Lin                     int stop_signo = 0;
2784cb84eebbSTamas Berghammer                     const bool stopped_by_signal = linux_thread_sp->IsStopped (&stop_signo);
2785aab58633SChaoren Lin                     const char *signal_name = stopped_by_signal ? GetUnixSignals ().GetSignalAsCString (stop_signo) : "<not stopped by signal>";
2786aab58633SChaoren Lin                     if (!signal_name)
2787aab58633SChaoren Lin                         signal_name = "<no-signal-name>";
2788aab58633SChaoren Lin 
2789aab58633SChaoren 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",
2790aab58633SChaoren Lin                                  __FUNCTION__,
2791aab58633SChaoren Lin                                  GetID (),
2792cb84eebbSTamas Berghammer                                  linux_thread_sp->GetID (),
2793aab58633SChaoren Lin                                  StateAsCString (thread_state),
2794aab58633SChaoren Lin                                  stop_signo,
2795aab58633SChaoren Lin                                  signal_name);
2796aab58633SChaoren Lin                 }
27971dbc6c9cSPavel Labath                 ThreadDidStop (thread_sp->GetID (), false);
2798af245d11STodd Fiala             }
279986fd8e45SChaoren Lin         }
2800af245d11STodd Fiala 
280158a2f669STodd Fiala         // Done handling.
2802af245d11STodd Fiala         return;
2803af245d11STodd Fiala     }
2804af245d11STodd Fiala 
2805af245d11STodd Fiala     if (log)
2806af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, GetUnixSignals ().GetSignalAsCString (signo));
2807af245d11STodd Fiala 
280886fd8e45SChaoren Lin     // This thread is stopped.
28091dbc6c9cSPavel Labath     ThreadDidStop (pid, false);
281086fd8e45SChaoren Lin 
2811af245d11STodd Fiala     switch (signo)
2812af245d11STodd Fiala     {
2813511e5cdcSTodd Fiala     case SIGSTOP:
2814511e5cdcSTodd Fiala         {
28158c8ff7afSPavel Labath             std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (signo);
281658a2f669STodd Fiala             if (log)
2817511e5cdcSTodd Fiala             {
2818511e5cdcSTodd Fiala                 if (is_from_llgs)
2819511e5cdcSTodd Fiala                     log->Printf ("NativeProcessLinux::%s pid = %" PRIu64 " tid %" PRIu64 " received SIGSTOP from llgs, most likely an interrupt", __FUNCTION__, GetID (), pid);
2820511e5cdcSTodd Fiala                 else
2821511e5cdcSTodd Fiala                     log->Printf ("NativeProcessLinux::%s pid = %" PRIu64 " tid %" PRIu64 " received SIGSTOP from outside of debugger", __FUNCTION__, GetID (), pid);
2822511e5cdcSTodd Fiala             }
2823511e5cdcSTodd Fiala 
2824fa03ad2eSChaoren Lin             // Resume this thread to get the group-stop mechanism to fire off the true group stops.
2825fa03ad2eSChaoren Lin             // This thread will get stopped again as part of the group-stop completion.
28261dbc6c9cSPavel Labath             ResumeThread(pid,
282786fd8e45SChaoren Lin                     [=](lldb::tid_t tid_to_resume, bool supress_signal)
2828fa03ad2eSChaoren Lin                     {
2829cb84eebbSTamas Berghammer                         std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2830fa03ad2eSChaoren Lin                         // Pass this signal number on to the inferior to handle.
283137c768caSChaoren Lin                         return Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo);
28321dbc6c9cSPavel Labath                     },
28331dbc6c9cSPavel Labath                     true);
283486fd8e45SChaoren Lin         }
283586fd8e45SChaoren Lin         break;
283686fd8e45SChaoren Lin     case SIGSEGV:
283786fd8e45SChaoren Lin     case SIGILL:
283886fd8e45SChaoren Lin     case SIGFPE:
283986fd8e45SChaoren Lin     case SIGBUS:
284086fd8e45SChaoren Lin         if (thread_sp)
2841cb84eebbSTamas Berghammer             std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetCrashedWithException (*info);
284286fd8e45SChaoren Lin         break;
284386fd8e45SChaoren Lin     default:
284486fd8e45SChaoren Lin         // This is just a pre-signal-delivery notification of the incoming signal.
284586fd8e45SChaoren Lin         if (thread_sp)
2846cb84eebbSTamas Berghammer             std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (signo);
2847fa03ad2eSChaoren Lin 
284886fd8e45SChaoren Lin         break;
284986fd8e45SChaoren Lin     }
285086fd8e45SChaoren Lin 
285186fd8e45SChaoren Lin     // Send a stop to the debugger after we get all other threads to stop.
2852ed89c7feSPavel Labath     StopRunningThreads (pid);
2853511e5cdcSTodd Fiala }
2854af245d11STodd Fiala 
2855e7708688STamas Berghammer namespace {
2856e7708688STamas Berghammer 
2857e7708688STamas Berghammer struct EmulatorBaton
2858e7708688STamas Berghammer {
2859e7708688STamas Berghammer     NativeProcessLinux* m_process;
2860e7708688STamas Berghammer     NativeRegisterContext* m_reg_context;
28616648fcc3SPavel Labath 
28626648fcc3SPavel Labath     // eRegisterKindDWARF -> RegsiterValue
28636648fcc3SPavel Labath     std::unordered_map<uint32_t, RegisterValue> m_register_values;
2864e7708688STamas Berghammer 
2865e7708688STamas Berghammer     EmulatorBaton(NativeProcessLinux* process, NativeRegisterContext* reg_context) :
2866e7708688STamas Berghammer             m_process(process), m_reg_context(reg_context) {}
2867e7708688STamas Berghammer };
2868e7708688STamas Berghammer 
2869e7708688STamas Berghammer } // anonymous namespace
2870e7708688STamas Berghammer 
2871e7708688STamas Berghammer static size_t
2872e7708688STamas Berghammer ReadMemoryCallback (EmulateInstruction *instruction,
2873e7708688STamas Berghammer                     void *baton,
2874e7708688STamas Berghammer                     const EmulateInstruction::Context &context,
2875e7708688STamas Berghammer                     lldb::addr_t addr,
2876e7708688STamas Berghammer                     void *dst,
2877e7708688STamas Berghammer                     size_t length)
2878e7708688STamas Berghammer {
2879e7708688STamas Berghammer     EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
2880e7708688STamas Berghammer 
28813eb4b458SChaoren Lin     size_t bytes_read;
2882e7708688STamas Berghammer     emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
2883e7708688STamas Berghammer     return bytes_read;
2884e7708688STamas Berghammer }
2885e7708688STamas Berghammer 
2886e7708688STamas Berghammer static bool
2887e7708688STamas Berghammer ReadRegisterCallback (EmulateInstruction *instruction,
2888e7708688STamas Berghammer                       void *baton,
2889e7708688STamas Berghammer                       const RegisterInfo *reg_info,
2890e7708688STamas Berghammer                       RegisterValue &reg_value)
2891e7708688STamas Berghammer {
2892e7708688STamas Berghammer     EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
2893e7708688STamas Berghammer 
28946648fcc3SPavel Labath     auto it = emulator_baton->m_register_values.find(reg_info->kinds[eRegisterKindDWARF]);
28956648fcc3SPavel Labath     if (it != emulator_baton->m_register_values.end())
28966648fcc3SPavel Labath     {
28976648fcc3SPavel Labath         reg_value = it->second;
28986648fcc3SPavel Labath         return true;
28996648fcc3SPavel Labath     }
29006648fcc3SPavel Labath 
2901e7708688STamas Berghammer     // The emulator only fill in the dwarf regsiter numbers (and in some case
2902e7708688STamas Berghammer     // the generic register numbers). Get the full register info from the
2903e7708688STamas Berghammer     // register context based on the dwarf register numbers.
2904e7708688STamas Berghammer     const RegisterInfo* full_reg_info = emulator_baton->m_reg_context->GetRegisterInfo(
2905e7708688STamas Berghammer             eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
2906e7708688STamas Berghammer 
2907e7708688STamas Berghammer     Error error = emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
29086648fcc3SPavel Labath     if (error.Success())
29096648fcc3SPavel Labath         return true;
2910cdc22a88SMohit K. Bhakkad 
29116648fcc3SPavel Labath     return false;
2912e7708688STamas Berghammer }
2913e7708688STamas Berghammer 
2914e7708688STamas Berghammer static bool
2915e7708688STamas Berghammer WriteRegisterCallback (EmulateInstruction *instruction,
2916e7708688STamas Berghammer                        void *baton,
2917e7708688STamas Berghammer                        const EmulateInstruction::Context &context,
2918e7708688STamas Berghammer                        const RegisterInfo *reg_info,
2919e7708688STamas Berghammer                        const RegisterValue &reg_value)
2920e7708688STamas Berghammer {
2921e7708688STamas Berghammer     EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
29226648fcc3SPavel Labath     emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = reg_value;
2923e7708688STamas Berghammer     return true;
2924e7708688STamas Berghammer }
2925e7708688STamas Berghammer 
2926e7708688STamas Berghammer static size_t
2927e7708688STamas Berghammer WriteMemoryCallback (EmulateInstruction *instruction,
2928e7708688STamas Berghammer                      void *baton,
2929e7708688STamas Berghammer                      const EmulateInstruction::Context &context,
2930e7708688STamas Berghammer                      lldb::addr_t addr,
2931e7708688STamas Berghammer                      const void *dst,
2932e7708688STamas Berghammer                      size_t length)
2933e7708688STamas Berghammer {
2934e7708688STamas Berghammer     return length;
2935e7708688STamas Berghammer }
2936e7708688STamas Berghammer 
2937e7708688STamas Berghammer static lldb::addr_t
2938e7708688STamas Berghammer ReadFlags (NativeRegisterContext* regsiter_context)
2939e7708688STamas Berghammer {
2940e7708688STamas Berghammer     const RegisterInfo* flags_info = regsiter_context->GetRegisterInfo(
2941e7708688STamas Berghammer             eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
2942e7708688STamas Berghammer     return regsiter_context->ReadRegisterAsUnsigned(flags_info, LLDB_INVALID_ADDRESS);
2943e7708688STamas Berghammer }
2944e7708688STamas Berghammer 
2945e7708688STamas Berghammer Error
2946e7708688STamas Berghammer NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadProtocolSP thread_sp)
2947e7708688STamas Berghammer {
2948e7708688STamas Berghammer     Error error;
2949e7708688STamas Berghammer     NativeRegisterContextSP register_context_sp = thread_sp->GetRegisterContext();
2950e7708688STamas Berghammer 
2951e7708688STamas Berghammer     std::unique_ptr<EmulateInstruction> emulator_ap(
2952e7708688STamas Berghammer         EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, nullptr));
2953e7708688STamas Berghammer 
2954e7708688STamas Berghammer     if (emulator_ap == nullptr)
2955e7708688STamas Berghammer         return Error("Instruction emulator not found!");
2956e7708688STamas Berghammer 
2957e7708688STamas Berghammer     EmulatorBaton baton(this, register_context_sp.get());
2958e7708688STamas Berghammer     emulator_ap->SetBaton(&baton);
2959e7708688STamas Berghammer     emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
2960e7708688STamas Berghammer     emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
2961e7708688STamas Berghammer     emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
2962e7708688STamas Berghammer     emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
2963e7708688STamas Berghammer 
2964e7708688STamas Berghammer     if (!emulator_ap->ReadInstruction())
2965e7708688STamas Berghammer         return Error("Read instruction failed!");
2966e7708688STamas Berghammer 
29676648fcc3SPavel Labath     bool emulation_result = emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
29686648fcc3SPavel Labath 
29696648fcc3SPavel Labath     const RegisterInfo* reg_info_pc = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
29706648fcc3SPavel Labath     const RegisterInfo* reg_info_flags = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
29716648fcc3SPavel Labath 
29726648fcc3SPavel Labath     auto pc_it = baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
29736648fcc3SPavel Labath     auto flags_it = baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
29746648fcc3SPavel Labath 
2975e7708688STamas Berghammer     lldb::addr_t next_pc;
2976e7708688STamas Berghammer     lldb::addr_t next_flags;
29776648fcc3SPavel Labath     if (emulation_result)
2978e7708688STamas Berghammer     {
29796648fcc3SPavel Labath         assert(pc_it != baton.m_register_values.end() && "Emulation was successfull but PC wasn't updated");
29806648fcc3SPavel Labath         next_pc = pc_it->second.GetAsUInt64();
29816648fcc3SPavel Labath 
29826648fcc3SPavel Labath         if (flags_it != baton.m_register_values.end())
29836648fcc3SPavel Labath             next_flags = flags_it->second.GetAsUInt64();
2984e7708688STamas Berghammer         else
2985e7708688STamas Berghammer             next_flags = ReadFlags (register_context_sp.get());
2986e7708688STamas Berghammer     }
29876648fcc3SPavel Labath     else if (pc_it == baton.m_register_values.end())
2988e7708688STamas Berghammer     {
2989e7708688STamas Berghammer         // Emulate instruction failed and it haven't changed PC. Advance PC
2990e7708688STamas Berghammer         // with the size of the current opcode because the emulation of all
2991e7708688STamas Berghammer         // PC modifying instruction should be successful. The failure most
2992e7708688STamas Berghammer         // likely caused by a not supported instruction which don't modify PC.
2993e7708688STamas Berghammer         next_pc = register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
2994e7708688STamas Berghammer         next_flags = ReadFlags (register_context_sp.get());
2995e7708688STamas Berghammer     }
2996e7708688STamas Berghammer     else
2997e7708688STamas Berghammer     {
2998e7708688STamas Berghammer         // The instruction emulation failed after it modified the PC. It is an
2999e7708688STamas Berghammer         // unknown error where we can't continue because the next instruction is
3000e7708688STamas Berghammer         // modifying the PC but we don't  know how.
3001e7708688STamas Berghammer         return Error ("Instruction emulation failed unexpectedly.");
3002e7708688STamas Berghammer     }
3003e7708688STamas Berghammer 
3004e7708688STamas Berghammer     if (m_arch.GetMachine() == llvm::Triple::arm)
3005e7708688STamas Berghammer     {
3006e7708688STamas Berghammer         if (next_flags & 0x20)
3007e7708688STamas Berghammer         {
3008e7708688STamas Berghammer             // Thumb mode
3009e7708688STamas Berghammer             error = SetSoftwareBreakpoint(next_pc, 2);
3010e7708688STamas Berghammer         }
3011e7708688STamas Berghammer         else
3012e7708688STamas Berghammer         {
3013e7708688STamas Berghammer             // Arm mode
3014e7708688STamas Berghammer             error = SetSoftwareBreakpoint(next_pc, 4);
3015e7708688STamas Berghammer         }
3016e7708688STamas Berghammer     }
3017cdc22a88SMohit K. Bhakkad     else if (m_arch.GetMachine() == llvm::Triple::mips64
3018cdc22a88SMohit K. Bhakkad             || m_arch.GetMachine() == llvm::Triple::mips64el)
3019cdc22a88SMohit K. Bhakkad         error = SetSoftwareBreakpoint(next_pc, 4);
3020e7708688STamas Berghammer     else
3021e7708688STamas Berghammer     {
3022e7708688STamas Berghammer         // No size hint is given for the next breakpoint
3023e7708688STamas Berghammer         error = SetSoftwareBreakpoint(next_pc, 0);
3024e7708688STamas Berghammer     }
3025e7708688STamas Berghammer 
3026e7708688STamas Berghammer     if (error.Fail())
3027e7708688STamas Berghammer         return error;
3028e7708688STamas Berghammer 
3029e7708688STamas Berghammer     m_threads_stepping_with_breakpoint.insert({thread_sp->GetID(), next_pc});
3030e7708688STamas Berghammer 
3031e7708688STamas Berghammer     return Error();
3032e7708688STamas Berghammer }
3033e7708688STamas Berghammer 
3034e7708688STamas Berghammer bool
3035e7708688STamas Berghammer NativeProcessLinux::SupportHardwareSingleStepping() const
3036e7708688STamas Berghammer {
3037cdc22a88SMohit K. Bhakkad     if (m_arch.GetMachine() == llvm::Triple::arm
3038cdc22a88SMohit K. Bhakkad         || m_arch.GetMachine() == llvm::Triple::mips64 || m_arch.GetMachine() == llvm::Triple::mips64el)
3039cdc22a88SMohit K. Bhakkad         return false;
3040cdc22a88SMohit K. Bhakkad     return true;
3041e7708688STamas Berghammer }
3042e7708688STamas Berghammer 
3043af245d11STodd Fiala Error
3044af245d11STodd Fiala NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
3045af245d11STodd Fiala {
3046af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
3047af245d11STodd Fiala     if (log)
3048af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
3049af245d11STodd Fiala 
305086fd8e45SChaoren Lin     bool stepping = false;
3051e7708688STamas Berghammer     bool software_single_step = !SupportHardwareSingleStepping();
3052af245d11STodd Fiala 
305345f5cb31SPavel Labath     Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
3054af245d11STodd Fiala     Mutex::Locker locker (m_threads_mutex);
30555830aa75STamas Berghammer 
3056e7708688STamas Berghammer     if (software_single_step)
3057e7708688STamas Berghammer     {
3058e7708688STamas Berghammer         for (auto thread_sp : m_threads)
3059e7708688STamas Berghammer         {
3060e7708688STamas Berghammer             assert (thread_sp && "thread list should not contain NULL threads");
3061e7708688STamas Berghammer 
3062e7708688STamas Berghammer             const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
3063e7708688STamas Berghammer             if (action == nullptr)
3064e7708688STamas Berghammer                 continue;
3065e7708688STamas Berghammer 
3066e7708688STamas Berghammer             if (action->state == eStateStepping)
3067e7708688STamas Berghammer             {
3068e7708688STamas Berghammer                 Error error = SetupSoftwareSingleStepping(thread_sp);
3069e7708688STamas Berghammer                 if (error.Fail())
3070e7708688STamas Berghammer                     return error;
3071e7708688STamas Berghammer             }
3072e7708688STamas Berghammer         }
3073e7708688STamas Berghammer     }
3074e7708688STamas Berghammer 
3075af245d11STodd Fiala     for (auto thread_sp : m_threads)
3076af245d11STodd Fiala     {
3077af245d11STodd Fiala         assert (thread_sp && "thread list should not contain NULL threads");
3078af245d11STodd Fiala 
3079af245d11STodd Fiala         const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
30806a196ce6SChaoren Lin 
30816a196ce6SChaoren Lin         if (action == nullptr)
30826a196ce6SChaoren Lin         {
30836a196ce6SChaoren Lin             if (log)
30846a196ce6SChaoren Lin                 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
30856a196ce6SChaoren Lin                     __FUNCTION__, GetID (), thread_sp->GetID ());
30866a196ce6SChaoren Lin             continue;
30876a196ce6SChaoren Lin         }
3088af245d11STodd Fiala 
3089af245d11STodd Fiala         if (log)
3090af245d11STodd Fiala         {
3091af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
3092af245d11STodd Fiala                     __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
3093af245d11STodd Fiala         }
3094af245d11STodd Fiala 
3095af245d11STodd Fiala         switch (action->state)
3096af245d11STodd Fiala         {
3097af245d11STodd Fiala         case eStateRunning:
3098fa03ad2eSChaoren Lin         {
3099af245d11STodd Fiala             // Run the thread, possibly feeding it the signal.
3100fa03ad2eSChaoren Lin             const int signo = action->signal;
31011dbc6c9cSPavel Labath             ResumeThread(thread_sp->GetID (),
310286fd8e45SChaoren Lin                     [=](lldb::tid_t tid_to_resume, bool supress_signal)
3103af245d11STodd Fiala                     {
3104cb84eebbSTamas Berghammer                         std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
3105fa03ad2eSChaoren Lin                         // Pass this signal number on to the inferior to handle.
31065830aa75STamas Berghammer                         const auto resume_result = Resume (tid_to_resume, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
31075830aa75STamas Berghammer                         if (resume_result.Success())
31085830aa75STamas Berghammer                             SetState(eStateRunning, true);
31095830aa75STamas Berghammer                         return resume_result;
31101dbc6c9cSPavel Labath                     },
31111dbc6c9cSPavel Labath                     false);
3112af245d11STodd Fiala             break;
3113fa03ad2eSChaoren Lin         }
3114af245d11STodd Fiala 
3115af245d11STodd Fiala         case eStateStepping:
3116af245d11STodd Fiala         {
3117ae29d395SChaoren Lin             // Request the step.
3118ae29d395SChaoren Lin             const int signo = action->signal;
31191dbc6c9cSPavel Labath             ResumeThread(thread_sp->GetID (),
312086fd8e45SChaoren Lin                     [=](lldb::tid_t tid_to_step, bool supress_signal)
3121af245d11STodd Fiala                     {
3122cb84eebbSTamas Berghammer                         std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStepping ();
3123e7708688STamas Berghammer 
3124e7708688STamas Berghammer                         Error step_result;
3125e7708688STamas Berghammer                         if (software_single_step)
3126e7708688STamas Berghammer                             step_result = Resume (tid_to_step, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
3127e7708688STamas Berghammer                         else
3128e7708688STamas Berghammer                             step_result = SingleStep (tid_to_step,(signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
3129e7708688STamas Berghammer 
313037c768caSChaoren Lin                         assert (step_result.Success() && "SingleStep() failed");
31315830aa75STamas Berghammer                         if (step_result.Success())
31325830aa75STamas Berghammer                             SetState(eStateStepping, true);
313337c768caSChaoren Lin                         return step_result;
31341dbc6c9cSPavel Labath                     },
31351dbc6c9cSPavel Labath                     false);
313686fd8e45SChaoren Lin             stepping = true;
3137af245d11STodd Fiala             break;
3138ae29d395SChaoren Lin         }
3139af245d11STodd Fiala 
3140af245d11STodd Fiala         case eStateSuspended:
3141af245d11STodd Fiala         case eStateStopped:
3142108c325dSPavel Labath             lldbassert(0 && "Unexpected state");
3143af245d11STodd Fiala 
3144af245d11STodd Fiala         default:
3145af245d11STodd Fiala             return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
3146af245d11STodd Fiala                     __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
3147af245d11STodd Fiala         }
3148af245d11STodd Fiala     }
3149af245d11STodd Fiala 
31505830aa75STamas Berghammer     return Error();
3151af245d11STodd Fiala }
3152af245d11STodd Fiala 
3153af245d11STodd Fiala Error
3154af245d11STodd Fiala NativeProcessLinux::Halt ()
3155af245d11STodd Fiala {
3156af245d11STodd Fiala     Error error;
3157af245d11STodd Fiala 
3158af245d11STodd Fiala     if (kill (GetID (), SIGSTOP) != 0)
3159af245d11STodd Fiala         error.SetErrorToErrno ();
3160af245d11STodd Fiala 
3161af245d11STodd Fiala     return error;
3162af245d11STodd Fiala }
3163af245d11STodd Fiala 
3164af245d11STodd Fiala Error
3165af245d11STodd Fiala NativeProcessLinux::Detach ()
3166af245d11STodd Fiala {
3167af245d11STodd Fiala     Error error;
3168af245d11STodd Fiala 
3169af245d11STodd Fiala     // Tell ptrace to detach from the process.
3170af245d11STodd Fiala     if (GetID () != LLDB_INVALID_PROCESS_ID)
3171af245d11STodd Fiala         error = Detach (GetID ());
3172af245d11STodd Fiala 
3173af245d11STodd Fiala     // Stop monitoring the inferior.
317445f5cb31SPavel Labath     m_monitor_up->Terminate();
3175af245d11STodd Fiala 
3176af245d11STodd Fiala     // No error.
3177af245d11STodd Fiala     return error;
3178af245d11STodd Fiala }
3179af245d11STodd Fiala 
3180af245d11STodd Fiala Error
3181af245d11STodd Fiala NativeProcessLinux::Signal (int signo)
3182af245d11STodd Fiala {
3183af245d11STodd Fiala     Error error;
3184af245d11STodd Fiala 
3185af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3186af245d11STodd Fiala     if (log)
3187af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
3188af245d11STodd Fiala                 __FUNCTION__, signo,  GetUnixSignals ().GetSignalAsCString (signo), GetID ());
3189af245d11STodd Fiala 
3190af245d11STodd Fiala     if (kill(GetID(), signo))
3191af245d11STodd Fiala         error.SetErrorToErrno();
3192af245d11STodd Fiala 
3193af245d11STodd Fiala     return error;
3194af245d11STodd Fiala }
3195af245d11STodd Fiala 
3196af245d11STodd Fiala Error
3197e9547b80SChaoren Lin NativeProcessLinux::Interrupt ()
3198e9547b80SChaoren Lin {
3199e9547b80SChaoren Lin     // Pick a running thread (or if none, a not-dead stopped thread) as
3200e9547b80SChaoren Lin     // the chosen thread that will be the stop-reason thread.
3201e9547b80SChaoren Lin     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3202e9547b80SChaoren Lin 
3203e9547b80SChaoren Lin     NativeThreadProtocolSP running_thread_sp;
3204e9547b80SChaoren Lin     NativeThreadProtocolSP stopped_thread_sp;
3205e9547b80SChaoren Lin 
3206e9547b80SChaoren Lin     if (log)
3207e9547b80SChaoren Lin         log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
3208e9547b80SChaoren Lin 
320945f5cb31SPavel Labath     Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
32105830aa75STamas Berghammer     Mutex::Locker locker (m_threads_mutex);
32115830aa75STamas Berghammer 
3212e9547b80SChaoren Lin     for (auto thread_sp : m_threads)
3213e9547b80SChaoren Lin     {
3214e9547b80SChaoren Lin         // The thread shouldn't be null but lets just cover that here.
3215e9547b80SChaoren Lin         if (!thread_sp)
3216e9547b80SChaoren Lin             continue;
3217e9547b80SChaoren Lin 
3218e9547b80SChaoren Lin         // If we have a running or stepping thread, we'll call that the
3219e9547b80SChaoren Lin         // target of the interrupt.
3220e9547b80SChaoren Lin         const auto thread_state = thread_sp->GetState ();
3221e9547b80SChaoren Lin         if (thread_state == eStateRunning ||
3222e9547b80SChaoren Lin             thread_state == eStateStepping)
3223e9547b80SChaoren Lin         {
3224e9547b80SChaoren Lin             running_thread_sp = thread_sp;
3225e9547b80SChaoren Lin             break;
3226e9547b80SChaoren Lin         }
3227e9547b80SChaoren Lin         else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
3228e9547b80SChaoren Lin         {
3229e9547b80SChaoren Lin             // Remember the first non-dead stopped thread.  We'll use that as a backup if there are no running threads.
3230e9547b80SChaoren Lin             stopped_thread_sp = thread_sp;
3231e9547b80SChaoren Lin         }
3232e9547b80SChaoren Lin     }
3233e9547b80SChaoren Lin 
3234e9547b80SChaoren Lin     if (!running_thread_sp && !stopped_thread_sp)
3235e9547b80SChaoren Lin     {
32365830aa75STamas Berghammer         Error error("found no running/stepping or live stopped threads as target for interrupt");
3237e9547b80SChaoren Lin         if (log)
3238e9547b80SChaoren Lin             log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
32395830aa75STamas Berghammer 
3240e9547b80SChaoren Lin         return error;
3241e9547b80SChaoren Lin     }
3242e9547b80SChaoren Lin 
3243e9547b80SChaoren Lin     NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
3244e9547b80SChaoren Lin 
3245e9547b80SChaoren Lin     if (log)
3246e9547b80SChaoren Lin         log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
3247e9547b80SChaoren Lin                      __FUNCTION__,
3248e9547b80SChaoren Lin                      GetID (),
3249e9547b80SChaoren Lin                      running_thread_sp ? "running" : "stopped",
3250e9547b80SChaoren Lin                      deferred_signal_thread_sp->GetID ());
3251e9547b80SChaoren Lin 
3252ed89c7feSPavel Labath     StopRunningThreads(deferred_signal_thread_sp->GetID());
325345f5cb31SPavel Labath 
32545830aa75STamas Berghammer     return Error();
3255e9547b80SChaoren Lin }
3256e9547b80SChaoren Lin 
3257e9547b80SChaoren Lin Error
3258af245d11STodd Fiala NativeProcessLinux::Kill ()
3259af245d11STodd Fiala {
3260af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3261af245d11STodd Fiala     if (log)
3262af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
3263af245d11STodd Fiala 
3264af245d11STodd Fiala     Error error;
3265af245d11STodd Fiala 
3266af245d11STodd Fiala     switch (m_state)
3267af245d11STodd Fiala     {
3268af245d11STodd Fiala         case StateType::eStateInvalid:
3269af245d11STodd Fiala         case StateType::eStateExited:
3270af245d11STodd Fiala         case StateType::eStateCrashed:
3271af245d11STodd Fiala         case StateType::eStateDetached:
3272af245d11STodd Fiala         case StateType::eStateUnloaded:
3273af245d11STodd Fiala             // Nothing to do - the process is already dead.
3274af245d11STodd Fiala             if (log)
3275af245d11STodd Fiala                 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
3276af245d11STodd Fiala             return error;
3277af245d11STodd Fiala 
3278af245d11STodd Fiala         case StateType::eStateConnected:
3279af245d11STodd Fiala         case StateType::eStateAttaching:
3280af245d11STodd Fiala         case StateType::eStateLaunching:
3281af245d11STodd Fiala         case StateType::eStateStopped:
3282af245d11STodd Fiala         case StateType::eStateRunning:
3283af245d11STodd Fiala         case StateType::eStateStepping:
3284af245d11STodd Fiala         case StateType::eStateSuspended:
3285af245d11STodd Fiala             // We can try to kill a process in these states.
3286af245d11STodd Fiala             break;
3287af245d11STodd Fiala     }
3288af245d11STodd Fiala 
3289af245d11STodd Fiala     if (kill (GetID (), SIGKILL) != 0)
3290af245d11STodd Fiala     {
3291af245d11STodd Fiala         error.SetErrorToErrno ();
3292af245d11STodd Fiala         return error;
3293af245d11STodd Fiala     }
3294af245d11STodd Fiala 
3295af245d11STodd Fiala     return error;
3296af245d11STodd Fiala }
3297af245d11STodd Fiala 
3298af245d11STodd Fiala static Error
3299af245d11STodd Fiala ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
3300af245d11STodd Fiala {
3301af245d11STodd Fiala     memory_region_info.Clear();
3302af245d11STodd Fiala 
3303af245d11STodd Fiala     StringExtractor line_extractor (maps_line.c_str ());
3304af245d11STodd Fiala 
3305af245d11STodd Fiala     // Format: {address_start_hex}-{address_end_hex} perms offset  dev   inode   pathname
3306af245d11STodd Fiala     // perms: rwxp   (letter is present if set, '-' if not, final character is p=private, s=shared).
3307af245d11STodd Fiala 
3308af245d11STodd Fiala     // Parse out the starting address
3309af245d11STodd Fiala     lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
3310af245d11STodd Fiala 
3311af245d11STodd Fiala     // Parse out hyphen separating start and end address from range.
3312af245d11STodd Fiala     if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
3313af245d11STodd Fiala         return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
3314af245d11STodd Fiala 
3315af245d11STodd Fiala     // Parse out the ending address
3316af245d11STodd Fiala     lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
3317af245d11STodd Fiala 
3318af245d11STodd Fiala     // Parse out the space after the address.
3319af245d11STodd Fiala     if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
3320af245d11STodd Fiala         return Error ("malformed /proc/{pid}/maps entry, missing space after range");
3321af245d11STodd Fiala 
3322af245d11STodd Fiala     // Save the range.
3323af245d11STodd Fiala     memory_region_info.GetRange ().SetRangeBase (start_address);
3324af245d11STodd Fiala     memory_region_info.GetRange ().SetRangeEnd (end_address);
3325af245d11STodd Fiala 
3326af245d11STodd Fiala     // Parse out each permission entry.
3327af245d11STodd Fiala     if (line_extractor.GetBytesLeft () < 4)
3328af245d11STodd Fiala         return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
3329af245d11STodd Fiala 
3330af245d11STodd Fiala     // Handle read permission.
3331af245d11STodd Fiala     const char read_perm_char = line_extractor.GetChar ();
3332af245d11STodd Fiala     if (read_perm_char == 'r')
3333af245d11STodd Fiala         memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
3334af245d11STodd Fiala     else
3335af245d11STodd Fiala     {
3336af245d11STodd Fiala         assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
3337af245d11STodd Fiala         memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
3338af245d11STodd Fiala     }
3339af245d11STodd Fiala 
3340af245d11STodd Fiala     // Handle write permission.
3341af245d11STodd Fiala     const char write_perm_char = line_extractor.GetChar ();
3342af245d11STodd Fiala     if (write_perm_char == 'w')
3343af245d11STodd Fiala         memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
3344af245d11STodd Fiala     else
3345af245d11STodd Fiala     {
3346af245d11STodd Fiala         assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
3347af245d11STodd Fiala         memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
3348af245d11STodd Fiala     }
3349af245d11STodd Fiala 
3350af245d11STodd Fiala     // Handle execute permission.
3351af245d11STodd Fiala     const char exec_perm_char = line_extractor.GetChar ();
3352af245d11STodd Fiala     if (exec_perm_char == 'x')
3353af245d11STodd Fiala         memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
3354af245d11STodd Fiala     else
3355af245d11STodd Fiala     {
3356af245d11STodd Fiala         assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
3357af245d11STodd Fiala         memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
3358af245d11STodd Fiala     }
3359af245d11STodd Fiala 
3360af245d11STodd Fiala     return Error ();
3361af245d11STodd Fiala }
3362af245d11STodd Fiala 
3363af245d11STodd Fiala Error
3364af245d11STodd Fiala NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
3365af245d11STodd Fiala {
3366af245d11STodd Fiala     // FIXME review that the final memory region returned extends to the end of the virtual address space,
3367af245d11STodd Fiala     // with no perms if it is not mapped.
3368af245d11STodd Fiala 
3369af245d11STodd Fiala     // Use an approach that reads memory regions from /proc/{pid}/maps.
3370af245d11STodd Fiala     // Assume proc maps entries are in ascending order.
3371af245d11STodd Fiala     // FIXME assert if we find differently.
3372af245d11STodd Fiala     Mutex::Locker locker (m_mem_region_cache_mutex);
3373af245d11STodd Fiala 
3374af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3375af245d11STodd Fiala     Error error;
3376af245d11STodd Fiala 
3377af245d11STodd Fiala     if (m_supports_mem_region == LazyBool::eLazyBoolNo)
3378af245d11STodd Fiala     {
3379af245d11STodd Fiala         // We're done.
3380af245d11STodd Fiala         error.SetErrorString ("unsupported");
3381af245d11STodd Fiala         return error;
3382af245d11STodd Fiala     }
3383af245d11STodd Fiala 
3384af245d11STodd Fiala     // If our cache is empty, pull the latest.  There should always be at least one memory region
3385af245d11STodd Fiala     // if memory region handling is supported.
3386af245d11STodd Fiala     if (m_mem_region_cache.empty ())
3387af245d11STodd Fiala     {
3388af245d11STodd Fiala         error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
3389af245d11STodd Fiala              [&] (const std::string &line) -> bool
3390af245d11STodd Fiala              {
3391af245d11STodd Fiala                  MemoryRegionInfo info;
3392af245d11STodd Fiala                  const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
3393af245d11STodd Fiala                  if (parse_error.Success ())
3394af245d11STodd Fiala                  {
3395af245d11STodd Fiala                      m_mem_region_cache.push_back (info);
3396af245d11STodd Fiala                      return true;
3397af245d11STodd Fiala                  }
3398af245d11STodd Fiala                  else
3399af245d11STodd Fiala                  {
3400af245d11STodd Fiala                      if (log)
3401af245d11STodd Fiala                          log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
3402af245d11STodd Fiala                      return false;
3403af245d11STodd Fiala                  }
3404af245d11STodd Fiala              });
3405af245d11STodd Fiala 
3406af245d11STodd Fiala         // If we had an error, we'll mark unsupported.
3407af245d11STodd Fiala         if (error.Fail ())
3408af245d11STodd Fiala         {
3409af245d11STodd Fiala             m_supports_mem_region = LazyBool::eLazyBoolNo;
3410af245d11STodd Fiala             return error;
3411af245d11STodd Fiala         }
3412af245d11STodd Fiala         else if (m_mem_region_cache.empty ())
3413af245d11STodd Fiala         {
3414af245d11STodd Fiala             // No entries after attempting to read them.  This shouldn't happen if /proc/{pid}/maps
3415af245d11STodd Fiala             // is supported.  Assume we don't support map entries via procfs.
3416af245d11STodd Fiala             if (log)
3417af245d11STodd Fiala                 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
3418af245d11STodd Fiala             m_supports_mem_region = LazyBool::eLazyBoolNo;
3419af245d11STodd Fiala             error.SetErrorString ("not supported");
3420af245d11STodd Fiala             return error;
3421af245d11STodd Fiala         }
3422af245d11STodd Fiala 
3423af245d11STodd Fiala         if (log)
3424af245d11STodd 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 ());
3425af245d11STodd Fiala 
3426af245d11STodd Fiala         // We support memory retrieval, remember that.
3427af245d11STodd Fiala         m_supports_mem_region = LazyBool::eLazyBoolYes;
3428af245d11STodd Fiala     }
3429af245d11STodd Fiala     else
3430af245d11STodd Fiala     {
3431af245d11STodd Fiala         if (log)
3432af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
3433af245d11STodd Fiala     }
3434af245d11STodd Fiala 
3435af245d11STodd Fiala     lldb::addr_t prev_base_address = 0;
3436af245d11STodd Fiala 
3437af245d11STodd Fiala     // FIXME start by finding the last region that is <= target address using binary search.  Data is sorted.
3438af245d11STodd Fiala     // There can be a ton of regions on pthreads apps with lots of threads.
3439af245d11STodd Fiala     for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
3440af245d11STodd Fiala     {
3441af245d11STodd Fiala         MemoryRegionInfo &proc_entry_info = *it;
3442af245d11STodd Fiala 
3443af245d11STodd Fiala         // Sanity check assumption that /proc/{pid}/maps entries are ascending.
3444af245d11STodd Fiala         assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
3445af245d11STodd Fiala         prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
3446af245d11STodd Fiala 
3447af245d11STodd Fiala         // If the target address comes before this entry, indicate distance to next region.
3448af245d11STodd Fiala         if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
3449af245d11STodd Fiala         {
3450af245d11STodd Fiala             range_info.GetRange ().SetRangeBase (load_addr);
3451af245d11STodd Fiala             range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
3452af245d11STodd Fiala             range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
3453af245d11STodd Fiala             range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
3454af245d11STodd Fiala             range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
3455af245d11STodd Fiala 
3456af245d11STodd Fiala             return error;
3457af245d11STodd Fiala         }
3458af245d11STodd Fiala         else if (proc_entry_info.GetRange ().Contains (load_addr))
3459af245d11STodd Fiala         {
3460af245d11STodd Fiala             // The target address is within the memory region we're processing here.
3461af245d11STodd Fiala             range_info = proc_entry_info;
3462af245d11STodd Fiala             return error;
3463af245d11STodd Fiala         }
3464af245d11STodd Fiala 
3465af245d11STodd Fiala         // The target memory address comes somewhere after the region we just parsed.
3466af245d11STodd Fiala     }
3467af245d11STodd Fiala 
3468af245d11STodd Fiala     // If we made it here, we didn't find an entry that contained the given address.
3469af245d11STodd Fiala     error.SetErrorString ("address comes after final region");
3470af245d11STodd Fiala 
3471af245d11STodd Fiala     if (log)
3472af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s failed to find map entry for address 0x%" PRIx64 ": %s", __FUNCTION__, load_addr, error.AsCString ());
3473af245d11STodd Fiala 
3474af245d11STodd Fiala     return error;
3475af245d11STodd Fiala }
3476af245d11STodd Fiala 
3477af245d11STodd Fiala void
3478af245d11STodd Fiala NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
3479af245d11STodd Fiala {
3480af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3481af245d11STodd Fiala     if (log)
3482af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
3483af245d11STodd Fiala 
3484af245d11STodd Fiala     {
3485af245d11STodd Fiala         Mutex::Locker locker (m_mem_region_cache_mutex);
3486af245d11STodd Fiala         if (log)
3487af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
3488af245d11STodd Fiala         m_mem_region_cache.clear ();
3489af245d11STodd Fiala     }
3490af245d11STodd Fiala }
3491af245d11STodd Fiala 
3492af245d11STodd Fiala Error
34933eb4b458SChaoren Lin NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr)
3494af245d11STodd Fiala {
3495af245d11STodd Fiala     // FIXME implementing this requires the equivalent of
3496af245d11STodd Fiala     // InferiorCallPOSIX::InferiorCallMmap, which depends on
3497af245d11STodd Fiala     // functional ThreadPlans working with Native*Protocol.
3498af245d11STodd Fiala #if 1
3499af245d11STodd Fiala     return Error ("not implemented yet");
3500af245d11STodd Fiala #else
3501af245d11STodd Fiala     addr = LLDB_INVALID_ADDRESS;
3502af245d11STodd Fiala 
3503af245d11STodd Fiala     unsigned prot = 0;
3504af245d11STodd Fiala     if (permissions & lldb::ePermissionsReadable)
3505af245d11STodd Fiala         prot |= eMmapProtRead;
3506af245d11STodd Fiala     if (permissions & lldb::ePermissionsWritable)
3507af245d11STodd Fiala         prot |= eMmapProtWrite;
3508af245d11STodd Fiala     if (permissions & lldb::ePermissionsExecutable)
3509af245d11STodd Fiala         prot |= eMmapProtExec;
3510af245d11STodd Fiala 
3511af245d11STodd Fiala     // TODO implement this directly in NativeProcessLinux
3512af245d11STodd Fiala     // (and lift to NativeProcessPOSIX if/when that class is
3513af245d11STodd Fiala     // refactored out).
3514af245d11STodd Fiala     if (InferiorCallMmap(this, addr, 0, size, prot,
3515af245d11STodd Fiala                          eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
3516af245d11STodd Fiala         m_addr_to_mmap_size[addr] = size;
3517af245d11STodd Fiala         return Error ();
3518af245d11STodd Fiala     } else {
3519af245d11STodd Fiala         addr = LLDB_INVALID_ADDRESS;
3520af245d11STodd Fiala         return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
3521af245d11STodd Fiala     }
3522af245d11STodd Fiala #endif
3523af245d11STodd Fiala }
3524af245d11STodd Fiala 
3525af245d11STodd Fiala Error
3526af245d11STodd Fiala NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
3527af245d11STodd Fiala {
3528af245d11STodd Fiala     // FIXME see comments in AllocateMemory - required lower-level
3529af245d11STodd Fiala     // bits not in place yet (ThreadPlans)
3530af245d11STodd Fiala     return Error ("not implemented");
3531af245d11STodd Fiala }
3532af245d11STodd Fiala 
3533af245d11STodd Fiala lldb::addr_t
3534af245d11STodd Fiala NativeProcessLinux::GetSharedLibraryInfoAddress ()
3535af245d11STodd Fiala {
3536af245d11STodd Fiala #if 1
3537af245d11STodd Fiala     // punt on this for now
3538af245d11STodd Fiala     return LLDB_INVALID_ADDRESS;
3539af245d11STodd Fiala #else
3540af245d11STodd Fiala     // Return the image info address for the exe module
3541af245d11STodd Fiala #if 1
3542af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3543af245d11STodd Fiala 
3544af245d11STodd Fiala     ModuleSP module_sp;
3545af245d11STodd Fiala     Error error = GetExeModuleSP (module_sp);
3546af245d11STodd Fiala     if (error.Fail ())
3547af245d11STodd Fiala     {
3548af245d11STodd Fiala          if (log)
3549af245d11STodd Fiala             log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ());
3550af245d11STodd Fiala         return LLDB_INVALID_ADDRESS;
3551af245d11STodd Fiala     }
3552af245d11STodd Fiala 
3553af245d11STodd Fiala     if (module_sp == nullptr)
3554af245d11STodd Fiala     {
3555af245d11STodd Fiala          if (log)
3556af245d11STodd Fiala             log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__);
3557af245d11STodd Fiala          return LLDB_INVALID_ADDRESS;
3558af245d11STodd Fiala     }
3559af245d11STodd Fiala 
3560af245d11STodd Fiala     ObjectFileSP object_file_sp = module_sp->GetObjectFile ();
3561af245d11STodd Fiala     if (object_file_sp == nullptr)
3562af245d11STodd Fiala     {
3563af245d11STodd Fiala          if (log)
3564af245d11STodd Fiala             log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__);
3565af245d11STodd Fiala          return LLDB_INVALID_ADDRESS;
3566af245d11STodd Fiala     }
3567af245d11STodd Fiala 
3568af245d11STodd Fiala     return obj_file_sp->GetImageInfoAddress();
3569af245d11STodd Fiala #else
3570af245d11STodd Fiala     Target *target = &GetTarget();
3571af245d11STodd Fiala     ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
3572af245d11STodd Fiala     Address addr = obj_file->GetImageInfoAddress(target);
3573af245d11STodd Fiala 
3574af245d11STodd Fiala     if (addr.IsValid())
3575af245d11STodd Fiala         return addr.GetLoadAddress(target);
3576af245d11STodd Fiala     return LLDB_INVALID_ADDRESS;
3577af245d11STodd Fiala #endif
3578af245d11STodd Fiala #endif // punt on this for now
3579af245d11STodd Fiala }
3580af245d11STodd Fiala 
3581af245d11STodd Fiala size_t
3582af245d11STodd Fiala NativeProcessLinux::UpdateThreads ()
3583af245d11STodd Fiala {
3584af245d11STodd Fiala     // The NativeProcessLinux monitoring threads are always up to date
3585af245d11STodd Fiala     // with respect to thread state and they keep the thread list
3586af245d11STodd Fiala     // populated properly. All this method needs to do is return the
3587af245d11STodd Fiala     // thread count.
3588af245d11STodd Fiala     Mutex::Locker locker (m_threads_mutex);
3589af245d11STodd Fiala     return m_threads.size ();
3590af245d11STodd Fiala }
3591af245d11STodd Fiala 
3592af245d11STodd Fiala bool
3593af245d11STodd Fiala NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
3594af245d11STodd Fiala {
3595af245d11STodd Fiala     arch = m_arch;
3596af245d11STodd Fiala     return true;
3597af245d11STodd Fiala }
3598af245d11STodd Fiala 
3599af245d11STodd Fiala Error
360063c8be95STamas Berghammer NativeProcessLinux::GetSoftwareBreakpointPCOffset (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size)
3601af245d11STodd Fiala {
3602af245d11STodd Fiala     // FIXME put this behind a breakpoint protocol class that can be
3603af245d11STodd Fiala     // set per architecture.  Need ARM, MIPS support here.
36042afc5966STodd Fiala     static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
3605af245d11STodd Fiala     static const uint8_t g_i386_opcode [] = { 0xCC };
3606e8659b5dSMohit K. Bhakkad     static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
3607af245d11STodd Fiala 
3608af245d11STodd Fiala     switch (m_arch.GetMachine ())
3609af245d11STodd Fiala     {
36102afc5966STodd Fiala         case llvm::Triple::aarch64:
36112afc5966STodd Fiala             actual_opcode_size = static_cast<uint32_t> (sizeof(g_aarch64_opcode));
36122afc5966STodd Fiala             return Error ();
36132afc5966STodd Fiala 
361463c8be95STamas Berghammer         case llvm::Triple::arm:
361563c8be95STamas Berghammer             actual_opcode_size = 0; // On arm the PC don't get updated for breakpoint hits
361663c8be95STamas Berghammer             return Error ();
361763c8be95STamas Berghammer 
3618af245d11STodd Fiala         case llvm::Triple::x86:
3619af245d11STodd Fiala         case llvm::Triple::x86_64:
3620af245d11STodd Fiala             actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
3621af245d11STodd Fiala             return Error ();
3622af245d11STodd Fiala 
3623e8659b5dSMohit K. Bhakkad         case llvm::Triple::mips64:
3624e8659b5dSMohit K. Bhakkad         case llvm::Triple::mips64el:
3625e8659b5dSMohit K. Bhakkad             actual_opcode_size = static_cast<uint32_t> (sizeof(g_mips64_opcode));
3626e8659b5dSMohit K. Bhakkad             return Error ();
3627e8659b5dSMohit K. Bhakkad 
3628af245d11STodd Fiala         default:
3629af245d11STodd Fiala             assert(false && "CPU type not supported!");
3630af245d11STodd Fiala             return Error ("CPU type not supported");
3631af245d11STodd Fiala     }
3632af245d11STodd Fiala }
3633af245d11STodd Fiala 
3634af245d11STodd Fiala Error
3635af245d11STodd Fiala NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
3636af245d11STodd Fiala {
3637af245d11STodd Fiala     if (hardware)
3638af245d11STodd Fiala         return Error ("NativeProcessLinux does not support hardware breakpoints");
3639af245d11STodd Fiala     else
3640af245d11STodd Fiala         return SetSoftwareBreakpoint (addr, size);
3641af245d11STodd Fiala }
3642af245d11STodd Fiala 
3643af245d11STodd Fiala Error
364463c8be95STamas Berghammer NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint,
364563c8be95STamas Berghammer                                                      size_t &actual_opcode_size,
364663c8be95STamas Berghammer                                                      const uint8_t *&trap_opcode_bytes)
3647af245d11STodd Fiala {
364863c8be95STamas Berghammer     // FIXME put this behind a breakpoint protocol class that can be set per
364963c8be95STamas Berghammer     // architecture.  Need MIPS support here.
36502afc5966STodd Fiala     static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
365163c8be95STamas Berghammer     // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
365263c8be95STamas Berghammer     // linux kernel does otherwise.
365363c8be95STamas Berghammer     static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 };
3654af245d11STodd Fiala     static const uint8_t g_i386_opcode [] = { 0xCC };
36553df471c3SMohit K. Bhakkad     static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
36562c2acf96SMohit K. Bhakkad     static const uint8_t g_mips64el_opcode[] = { 0x0d, 0x00, 0x00, 0x00 };
365763c8be95STamas Berghammer     static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde };
3658af245d11STodd Fiala 
3659af245d11STodd Fiala     switch (m_arch.GetMachine ())
3660af245d11STodd Fiala     {
36612afc5966STodd Fiala     case llvm::Triple::aarch64:
36622afc5966STodd Fiala         trap_opcode_bytes = g_aarch64_opcode;
36632afc5966STodd Fiala         actual_opcode_size = sizeof(g_aarch64_opcode);
36642afc5966STodd Fiala         return Error ();
36652afc5966STodd Fiala 
366663c8be95STamas Berghammer     case llvm::Triple::arm:
366763c8be95STamas Berghammer         switch (trap_opcode_size_hint)
366863c8be95STamas Berghammer         {
366963c8be95STamas Berghammer         case 2:
367063c8be95STamas Berghammer             trap_opcode_bytes = g_thumb_breakpoint_opcode;
367163c8be95STamas Berghammer             actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
367263c8be95STamas Berghammer             return Error ();
367363c8be95STamas Berghammer         case 4:
367463c8be95STamas Berghammer             trap_opcode_bytes = g_arm_breakpoint_opcode;
367563c8be95STamas Berghammer             actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
367663c8be95STamas Berghammer             return Error ();
367763c8be95STamas Berghammer         default:
367863c8be95STamas Berghammer             assert(false && "Unrecognised trap opcode size hint!");
367963c8be95STamas Berghammer             return Error ("Unrecognised trap opcode size hint!");
368063c8be95STamas Berghammer         }
368163c8be95STamas Berghammer 
3682af245d11STodd Fiala     case llvm::Triple::x86:
3683af245d11STodd Fiala     case llvm::Triple::x86_64:
3684af245d11STodd Fiala         trap_opcode_bytes = g_i386_opcode;
3685af245d11STodd Fiala         actual_opcode_size = sizeof(g_i386_opcode);
3686af245d11STodd Fiala         return Error ();
3687af245d11STodd Fiala 
36883df471c3SMohit K. Bhakkad     case llvm::Triple::mips64:
36893df471c3SMohit K. Bhakkad         trap_opcode_bytes = g_mips64_opcode;
36903df471c3SMohit K. Bhakkad         actual_opcode_size = sizeof(g_mips64_opcode);
36913df471c3SMohit K. Bhakkad         return Error ();
36923df471c3SMohit K. Bhakkad 
36932c2acf96SMohit K. Bhakkad     case llvm::Triple::mips64el:
36942c2acf96SMohit K. Bhakkad         trap_opcode_bytes = g_mips64el_opcode;
36952c2acf96SMohit K. Bhakkad         actual_opcode_size = sizeof(g_mips64el_opcode);
36962c2acf96SMohit K. Bhakkad         return Error ();
36972c2acf96SMohit K. Bhakkad 
3698af245d11STodd Fiala     default:
3699af245d11STodd Fiala         assert(false && "CPU type not supported!");
3700af245d11STodd Fiala         return Error ("CPU type not supported");
3701af245d11STodd Fiala     }
3702af245d11STodd Fiala }
3703af245d11STodd Fiala 
3704af245d11STodd Fiala #if 0
3705af245d11STodd Fiala ProcessMessage::CrashReason
3706af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
3707af245d11STodd Fiala {
3708af245d11STodd Fiala     ProcessMessage::CrashReason reason;
3709af245d11STodd Fiala     assert(info->si_signo == SIGSEGV);
3710af245d11STodd Fiala 
3711af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
3712af245d11STodd Fiala 
3713af245d11STodd Fiala     switch (info->si_code)
3714af245d11STodd Fiala     {
3715af245d11STodd Fiala     default:
3716af245d11STodd Fiala         assert(false && "unexpected si_code for SIGSEGV");
3717af245d11STodd Fiala         break;
3718af245d11STodd Fiala     case SI_KERNEL:
3719af245d11STodd Fiala         // Linux will occasionally send spurious SI_KERNEL codes.
3720af245d11STodd Fiala         // (this is poorly documented in sigaction)
3721af245d11STodd Fiala         // One way to get this is via unaligned SIMD loads.
3722af245d11STodd Fiala         reason = ProcessMessage::eInvalidAddress; // for lack of anything better
3723af245d11STodd Fiala         break;
3724af245d11STodd Fiala     case SEGV_MAPERR:
3725af245d11STodd Fiala         reason = ProcessMessage::eInvalidAddress;
3726af245d11STodd Fiala         break;
3727af245d11STodd Fiala     case SEGV_ACCERR:
3728af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedAddress;
3729af245d11STodd Fiala         break;
3730af245d11STodd Fiala     }
3731af245d11STodd Fiala 
3732af245d11STodd Fiala     return reason;
3733af245d11STodd Fiala }
3734af245d11STodd Fiala #endif
3735af245d11STodd Fiala 
3736af245d11STodd Fiala 
3737af245d11STodd Fiala #if 0
3738af245d11STodd Fiala ProcessMessage::CrashReason
3739af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
3740af245d11STodd Fiala {
3741af245d11STodd Fiala     ProcessMessage::CrashReason reason;
3742af245d11STodd Fiala     assert(info->si_signo == SIGILL);
3743af245d11STodd Fiala 
3744af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
3745af245d11STodd Fiala 
3746af245d11STodd Fiala     switch (info->si_code)
3747af245d11STodd Fiala     {
3748af245d11STodd Fiala     default:
3749af245d11STodd Fiala         assert(false && "unexpected si_code for SIGILL");
3750af245d11STodd Fiala         break;
3751af245d11STodd Fiala     case ILL_ILLOPC:
3752af245d11STodd Fiala         reason = ProcessMessage::eIllegalOpcode;
3753af245d11STodd Fiala         break;
3754af245d11STodd Fiala     case ILL_ILLOPN:
3755af245d11STodd Fiala         reason = ProcessMessage::eIllegalOperand;
3756af245d11STodd Fiala         break;
3757af245d11STodd Fiala     case ILL_ILLADR:
3758af245d11STodd Fiala         reason = ProcessMessage::eIllegalAddressingMode;
3759af245d11STodd Fiala         break;
3760af245d11STodd Fiala     case ILL_ILLTRP:
3761af245d11STodd Fiala         reason = ProcessMessage::eIllegalTrap;
3762af245d11STodd Fiala         break;
3763af245d11STodd Fiala     case ILL_PRVOPC:
3764af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedOpcode;
3765af245d11STodd Fiala         break;
3766af245d11STodd Fiala     case ILL_PRVREG:
3767af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedRegister;
3768af245d11STodd Fiala         break;
3769af245d11STodd Fiala     case ILL_COPROC:
3770af245d11STodd Fiala         reason = ProcessMessage::eCoprocessorError;
3771af245d11STodd Fiala         break;
3772af245d11STodd Fiala     case ILL_BADSTK:
3773af245d11STodd Fiala         reason = ProcessMessage::eInternalStackError;
3774af245d11STodd Fiala         break;
3775af245d11STodd Fiala     }
3776af245d11STodd Fiala 
3777af245d11STodd Fiala     return reason;
3778af245d11STodd Fiala }
3779af245d11STodd Fiala #endif
3780af245d11STodd Fiala 
3781af245d11STodd Fiala #if 0
3782af245d11STodd Fiala ProcessMessage::CrashReason
3783af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
3784af245d11STodd Fiala {
3785af245d11STodd Fiala     ProcessMessage::CrashReason reason;
3786af245d11STodd Fiala     assert(info->si_signo == SIGFPE);
3787af245d11STodd Fiala 
3788af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
3789af245d11STodd Fiala 
3790af245d11STodd Fiala     switch (info->si_code)
3791af245d11STodd Fiala     {
3792af245d11STodd Fiala     default:
3793af245d11STodd Fiala         assert(false && "unexpected si_code for SIGFPE");
3794af245d11STodd Fiala         break;
3795af245d11STodd Fiala     case FPE_INTDIV:
3796af245d11STodd Fiala         reason = ProcessMessage::eIntegerDivideByZero;
3797af245d11STodd Fiala         break;
3798af245d11STodd Fiala     case FPE_INTOVF:
3799af245d11STodd Fiala         reason = ProcessMessage::eIntegerOverflow;
3800af245d11STodd Fiala         break;
3801af245d11STodd Fiala     case FPE_FLTDIV:
3802af245d11STodd Fiala         reason = ProcessMessage::eFloatDivideByZero;
3803af245d11STodd Fiala         break;
3804af245d11STodd Fiala     case FPE_FLTOVF:
3805af245d11STodd Fiala         reason = ProcessMessage::eFloatOverflow;
3806af245d11STodd Fiala         break;
3807af245d11STodd Fiala     case FPE_FLTUND:
3808af245d11STodd Fiala         reason = ProcessMessage::eFloatUnderflow;
3809af245d11STodd Fiala         break;
3810af245d11STodd Fiala     case FPE_FLTRES:
3811af245d11STodd Fiala         reason = ProcessMessage::eFloatInexactResult;
3812af245d11STodd Fiala         break;
3813af245d11STodd Fiala     case FPE_FLTINV:
3814af245d11STodd Fiala         reason = ProcessMessage::eFloatInvalidOperation;
3815af245d11STodd Fiala         break;
3816af245d11STodd Fiala     case FPE_FLTSUB:
3817af245d11STodd Fiala         reason = ProcessMessage::eFloatSubscriptRange;
3818af245d11STodd Fiala         break;
3819af245d11STodd Fiala     }
3820af245d11STodd Fiala 
3821af245d11STodd Fiala     return reason;
3822af245d11STodd Fiala }
3823af245d11STodd Fiala #endif
3824af245d11STodd Fiala 
3825af245d11STodd Fiala #if 0
3826af245d11STodd Fiala ProcessMessage::CrashReason
3827af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
3828af245d11STodd Fiala {
3829af245d11STodd Fiala     ProcessMessage::CrashReason reason;
3830af245d11STodd Fiala     assert(info->si_signo == SIGBUS);
3831af245d11STodd Fiala 
3832af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
3833af245d11STodd Fiala 
3834af245d11STodd Fiala     switch (info->si_code)
3835af245d11STodd Fiala     {
3836af245d11STodd Fiala     default:
3837af245d11STodd Fiala         assert(false && "unexpected si_code for SIGBUS");
3838af245d11STodd Fiala         break;
3839af245d11STodd Fiala     case BUS_ADRALN:
3840af245d11STodd Fiala         reason = ProcessMessage::eIllegalAlignment;
3841af245d11STodd Fiala         break;
3842af245d11STodd Fiala     case BUS_ADRERR:
3843af245d11STodd Fiala         reason = ProcessMessage::eIllegalAddress;
3844af245d11STodd Fiala         break;
3845af245d11STodd Fiala     case BUS_OBJERR:
3846af245d11STodd Fiala         reason = ProcessMessage::eHardwareError;
3847af245d11STodd Fiala         break;
3848af245d11STodd Fiala     }
3849af245d11STodd Fiala 
3850af245d11STodd Fiala     return reason;
3851af245d11STodd Fiala }
3852af245d11STodd Fiala #endif
3853af245d11STodd Fiala 
3854af245d11STodd Fiala Error
385545f5cb31SPavel Labath NativeProcessLinux::SetWatchpoint (lldb::addr_t addr, size_t size, uint32_t watch_flags, bool hardware)
385645f5cb31SPavel Labath {
385745f5cb31SPavel Labath     // The base SetWatchpoint will end up executing monitor operations. Let's lock the monitor
385845f5cb31SPavel Labath     // for it.
385945f5cb31SPavel Labath     Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
386045f5cb31SPavel Labath     return NativeProcessProtocol::SetWatchpoint(addr, size, watch_flags, hardware);
386145f5cb31SPavel Labath }
386245f5cb31SPavel Labath 
386345f5cb31SPavel Labath Error
386445f5cb31SPavel Labath NativeProcessLinux::RemoveWatchpoint (lldb::addr_t addr)
386545f5cb31SPavel Labath {
386645f5cb31SPavel Labath     // The base RemoveWatchpoint will end up executing monitor operations. Let's lock the monitor
386745f5cb31SPavel Labath     // for it.
386845f5cb31SPavel Labath     Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
386945f5cb31SPavel Labath     return NativeProcessProtocol::RemoveWatchpoint(addr);
387045f5cb31SPavel Labath }
387145f5cb31SPavel Labath 
387245f5cb31SPavel Labath Error
387326438d26SChaoren Lin NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
3874af245d11STodd Fiala {
3875af245d11STodd Fiala     ReadOperation op(addr, buf, size, bytes_read);
3876bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
3877af245d11STodd Fiala     return op.GetError ();
3878af245d11STodd Fiala }
3879af245d11STodd Fiala 
3880af245d11STodd Fiala Error
38813eb4b458SChaoren Lin NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
38823eb4b458SChaoren Lin {
38833eb4b458SChaoren Lin     Error error = ReadMemory(addr, buf, size, bytes_read);
38843eb4b458SChaoren Lin     if (error.Fail()) return error;
38853eb4b458SChaoren Lin     return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
38863eb4b458SChaoren Lin }
38873eb4b458SChaoren Lin 
38883eb4b458SChaoren Lin Error
38893eb4b458SChaoren Lin NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written)
3890af245d11STodd Fiala {
3891af245d11STodd Fiala     WriteOperation op(addr, buf, size, bytes_written);
3892bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
3893af245d11STodd Fiala     return op.GetError ();
3894af245d11STodd Fiala }
3895af245d11STodd Fiala 
389697ccc294SChaoren Lin Error
3897af245d11STodd Fiala NativeProcessLinux::ReadRegisterValue(lldb::tid_t tid, uint32_t offset, const char* reg_name,
3898af245d11STodd Fiala                                       uint32_t size, RegisterValue &value)
3899af245d11STodd Fiala {
390097ccc294SChaoren Lin     ReadRegOperation op(tid, offset, reg_name, value);
3901bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
390297ccc294SChaoren Lin     return op.GetError();
3903af245d11STodd Fiala }
3904af245d11STodd Fiala 
390597ccc294SChaoren Lin Error
3906af245d11STodd Fiala NativeProcessLinux::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
3907af245d11STodd Fiala                                    const char* reg_name, const RegisterValue &value)
3908af245d11STodd Fiala {
390997ccc294SChaoren Lin     WriteRegOperation op(tid, offset, reg_name, value);
3910bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
391197ccc294SChaoren Lin     return op.GetError();
3912af245d11STodd Fiala }
3913af245d11STodd Fiala 
391497ccc294SChaoren Lin Error
3915af245d11STodd Fiala NativeProcessLinux::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3916af245d11STodd Fiala {
391797ccc294SChaoren Lin     ReadGPROperation op(tid, buf, buf_size);
3918bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
391997ccc294SChaoren Lin     return op.GetError();
3920af245d11STodd Fiala }
3921af245d11STodd Fiala 
392297ccc294SChaoren Lin Error
3923af245d11STodd Fiala NativeProcessLinux::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3924af245d11STodd Fiala {
392597ccc294SChaoren Lin     ReadFPROperation op(tid, buf, buf_size);
3926bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
392797ccc294SChaoren Lin     return op.GetError();
3928af245d11STodd Fiala }
3929af245d11STodd Fiala 
393097ccc294SChaoren Lin Error
3931af245d11STodd Fiala NativeProcessLinux::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3932af245d11STodd Fiala {
393397ccc294SChaoren Lin     ReadRegisterSetOperation op(tid, buf, buf_size, regset);
3934bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
393597ccc294SChaoren Lin     return op.GetError();
3936af245d11STodd Fiala }
3937af245d11STodd Fiala 
3938ea8c25a8SOmair Javaid Error
3939ea8c25a8SOmair Javaid NativeProcessLinux::ReadHardwareDebugInfo (lldb::tid_t tid, unsigned int &watch_count , unsigned int &break_count)
3940ea8c25a8SOmair Javaid {
3941ea8c25a8SOmair Javaid     ReadDBGROperation op(tid, watch_count, break_count);
3942ea8c25a8SOmair Javaid     m_monitor_up->DoOperation(&op);
3943ea8c25a8SOmair Javaid     return op.GetError();
3944ea8c25a8SOmair Javaid }
3945ea8c25a8SOmair Javaid 
3946ea8c25a8SOmair Javaid Error
3947ea8c25a8SOmair Javaid NativeProcessLinux::WriteHardwareDebugRegs (lldb::tid_t tid, lldb::addr_t *addr_buf, uint32_t *cntrl_buf, int type, int count)
3948ea8c25a8SOmair Javaid {
3949ea8c25a8SOmair Javaid     WriteDBGROperation op(tid, addr_buf, cntrl_buf, type, count);
3950ea8c25a8SOmair Javaid     m_monitor_up->DoOperation(&op);
3951ea8c25a8SOmair Javaid     return op.GetError();
3952ea8c25a8SOmair Javaid }
3953ea8c25a8SOmair Javaid 
395497ccc294SChaoren Lin Error
3955af245d11STodd Fiala NativeProcessLinux::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3956af245d11STodd Fiala {
395797ccc294SChaoren Lin     WriteGPROperation op(tid, buf, buf_size);
3958bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
395997ccc294SChaoren Lin     return op.GetError();
3960af245d11STodd Fiala }
3961af245d11STodd Fiala 
396297ccc294SChaoren Lin Error
3963af245d11STodd Fiala NativeProcessLinux::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3964af245d11STodd Fiala {
396597ccc294SChaoren Lin     WriteFPROperation op(tid, buf, buf_size);
3966bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
396797ccc294SChaoren Lin     return op.GetError();
3968af245d11STodd Fiala }
3969af245d11STodd Fiala 
397097ccc294SChaoren Lin Error
3971af245d11STodd Fiala NativeProcessLinux::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3972af245d11STodd Fiala {
397397ccc294SChaoren Lin     WriteRegisterSetOperation op(tid, buf, buf_size, regset);
3974bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
397597ccc294SChaoren Lin     return op.GetError();
3976af245d11STodd Fiala }
3977af245d11STodd Fiala 
397897ccc294SChaoren Lin Error
3979af245d11STodd Fiala NativeProcessLinux::Resume (lldb::tid_t tid, uint32_t signo)
3980af245d11STodd Fiala {
3981af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3982af245d11STodd Fiala 
3983af245d11STodd Fiala     if (log)
3984af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s() resuming thread = %"  PRIu64 " with signal %s", __FUNCTION__, tid,
3985af245d11STodd Fiala                                  GetUnixSignals().GetSignalAsCString (signo));
398697ccc294SChaoren Lin     ResumeOperation op (tid, signo);
3987bd7cbc5aSPavel Labath     m_monitor_up->DoOperation (&op);
3988af245d11STodd Fiala     if (log)
398997ccc294SChaoren Lin         log->Printf ("NativeProcessLinux::%s() resuming thread = %"  PRIu64 " result = %s", __FUNCTION__, tid, op.GetError().Success() ? "true" : "false");
399097ccc294SChaoren Lin     return op.GetError();
3991af245d11STodd Fiala }
3992af245d11STodd Fiala 
399397ccc294SChaoren Lin Error
3994af245d11STodd Fiala NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo)
3995af245d11STodd Fiala {
399697ccc294SChaoren Lin     SingleStepOperation op(tid, signo);
3997bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
399897ccc294SChaoren Lin     return op.GetError();
3999af245d11STodd Fiala }
4000af245d11STodd Fiala 
400197ccc294SChaoren Lin Error
400297ccc294SChaoren Lin NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
4003af245d11STodd Fiala {
400497ccc294SChaoren Lin     SiginfoOperation op(tid, siginfo);
4005bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
400697ccc294SChaoren Lin     return op.GetError();
4007af245d11STodd Fiala }
4008af245d11STodd Fiala 
400997ccc294SChaoren Lin Error
4010af245d11STodd Fiala NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
4011af245d11STodd Fiala {
401297ccc294SChaoren Lin     EventMessageOperation op(tid, message);
4013bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
401497ccc294SChaoren Lin     return op.GetError();
4015af245d11STodd Fiala }
4016af245d11STodd Fiala 
4017db264a6dSTamas Berghammer Error
4018af245d11STodd Fiala NativeProcessLinux::Detach(lldb::tid_t tid)
4019af245d11STodd Fiala {
402097ccc294SChaoren Lin     if (tid == LLDB_INVALID_THREAD_ID)
402197ccc294SChaoren Lin         return Error();
402297ccc294SChaoren Lin 
402397ccc294SChaoren Lin     DetachOperation op(tid);
4024bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
402597ccc294SChaoren Lin     return op.GetError();
4026af245d11STodd Fiala }
4027af245d11STodd Fiala 
4028af245d11STodd Fiala bool
4029af245d11STodd Fiala NativeProcessLinux::DupDescriptor(const char *path, int fd, int flags)
4030af245d11STodd Fiala {
4031af245d11STodd Fiala     int target_fd = open(path, flags, 0666);
4032af245d11STodd Fiala 
4033af245d11STodd Fiala     if (target_fd == -1)
4034af245d11STodd Fiala         return false;
4035af245d11STodd Fiala 
4036493c3a12SPavel Labath     if (dup2(target_fd, fd) == -1)
4037493c3a12SPavel Labath         return false;
4038493c3a12SPavel Labath 
4039493c3a12SPavel Labath     return (close(target_fd) == -1) ? false : true;
4040af245d11STodd Fiala }
4041af245d11STodd Fiala 
4042af245d11STodd Fiala void
4043bd7cbc5aSPavel Labath NativeProcessLinux::StartMonitorThread(const InitialOperation &initial_operation, Error &error)
4044af245d11STodd Fiala {
4045bd7cbc5aSPavel Labath     m_monitor_up.reset(new Monitor(initial_operation, this));
40461107b5a5SPavel Labath     error = m_monitor_up->Initialize();
40471107b5a5SPavel Labath     if (error.Fail()) {
40481107b5a5SPavel Labath         m_monitor_up.reset();
4049af245d11STodd Fiala     }
4050af245d11STodd Fiala }
4051af245d11STodd Fiala 
4052af245d11STodd Fiala bool
4053af245d11STodd Fiala NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
4054af245d11STodd Fiala {
4055af245d11STodd Fiala     for (auto thread_sp : m_threads)
4056af245d11STodd Fiala     {
4057af245d11STodd Fiala         assert (thread_sp && "thread list should not contain NULL threads");
4058af245d11STodd Fiala         if (thread_sp->GetID () == thread_id)
4059af245d11STodd Fiala         {
4060af245d11STodd Fiala             // We have this thread.
4061af245d11STodd Fiala             return true;
4062af245d11STodd Fiala         }
4063af245d11STodd Fiala     }
4064af245d11STodd Fiala 
4065af245d11STodd Fiala     // We don't have this thread.
4066af245d11STodd Fiala     return false;
4067af245d11STodd Fiala }
4068af245d11STodd Fiala 
4069af245d11STodd Fiala NativeThreadProtocolSP
4070af245d11STodd Fiala NativeProcessLinux::MaybeGetThreadNoLock (lldb::tid_t thread_id)
4071af245d11STodd Fiala {
4072af245d11STodd Fiala     // CONSIDER organize threads by map - we can do better than linear.
4073af245d11STodd Fiala     for (auto thread_sp : m_threads)
4074af245d11STodd Fiala     {
4075af245d11STodd Fiala         if (thread_sp->GetID () == thread_id)
4076af245d11STodd Fiala             return thread_sp;
4077af245d11STodd Fiala     }
4078af245d11STodd Fiala 
4079af245d11STodd Fiala     // We don't have this thread.
4080af245d11STodd Fiala     return NativeThreadProtocolSP ();
4081af245d11STodd Fiala }
4082af245d11STodd Fiala 
4083af245d11STodd Fiala bool
4084af245d11STodd Fiala NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
4085af245d11STodd Fiala {
40861dbc6c9cSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
40871dbc6c9cSPavel Labath 
40881dbc6c9cSPavel Labath     if (log)
40891dbc6c9cSPavel Labath         log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, thread_id);
40901dbc6c9cSPavel Labath 
40911dbc6c9cSPavel Labath     bool found = false;
40921dbc6c9cSPavel Labath 
4093af245d11STodd Fiala     Mutex::Locker locker (m_threads_mutex);
4094af245d11STodd Fiala     for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
4095af245d11STodd Fiala     {
4096af245d11STodd Fiala         if (*it && ((*it)->GetID () == thread_id))
4097af245d11STodd Fiala         {
4098af245d11STodd Fiala             m_threads.erase (it);
40991dbc6c9cSPavel Labath             found = true;
41001dbc6c9cSPavel Labath             break;
4101af245d11STodd Fiala         }
4102af245d11STodd Fiala     }
4103af245d11STodd Fiala 
41041dbc6c9cSPavel Labath     // If we have a pending notification, remove this from the set.
41051dbc6c9cSPavel Labath     if (m_pending_notification_up)
41061dbc6c9cSPavel Labath     {
41071dbc6c9cSPavel Labath         m_pending_notification_up->wait_for_stop_tids.erase(thread_id);
41081dbc6c9cSPavel Labath         SignalIfRequirementsSatisfied();
41091dbc6c9cSPavel Labath     }
41101dbc6c9cSPavel Labath 
41111dbc6c9cSPavel Labath     return found;
4112af245d11STodd Fiala }
4113af245d11STodd Fiala 
4114af245d11STodd Fiala NativeThreadProtocolSP
4115af245d11STodd Fiala NativeProcessLinux::AddThread (lldb::tid_t thread_id)
4116af245d11STodd Fiala {
4117af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
4118af245d11STodd Fiala 
4119af245d11STodd Fiala     Mutex::Locker locker (m_threads_mutex);
4120af245d11STodd Fiala 
4121af245d11STodd Fiala     if (log)
4122af245d11STodd Fiala     {
4123af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
4124af245d11STodd Fiala                 __FUNCTION__,
4125af245d11STodd Fiala                 GetID (),
4126af245d11STodd Fiala                 thread_id);
4127af245d11STodd Fiala     }
4128af245d11STodd Fiala 
4129af245d11STodd Fiala     assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
4130af245d11STodd Fiala 
4131af245d11STodd Fiala     // If this is the first thread, save it as the current thread
4132af245d11STodd Fiala     if (m_threads.empty ())
4133af245d11STodd Fiala         SetCurrentThreadID (thread_id);
4134af245d11STodd Fiala 
4135af245d11STodd Fiala     NativeThreadProtocolSP thread_sp (new NativeThreadLinux (this, thread_id));
4136af245d11STodd Fiala     m_threads.push_back (thread_sp);
4137af245d11STodd Fiala 
4138af245d11STodd Fiala     return thread_sp;
4139af245d11STodd Fiala }
4140af245d11STodd Fiala 
4141af245d11STodd Fiala Error
4142af245d11STodd Fiala NativeProcessLinux::FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp)
4143af245d11STodd Fiala {
414475f47c3aSTodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
4145af245d11STodd Fiala 
4146af245d11STodd Fiala     Error error;
4147af245d11STodd Fiala 
4148af245d11STodd Fiala     // Get a linux thread pointer.
4149af245d11STodd Fiala     if (!thread_sp)
4150af245d11STodd Fiala     {
4151af245d11STodd Fiala         error.SetErrorString ("null thread_sp");
4152af245d11STodd Fiala         if (log)
4153af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
4154af245d11STodd Fiala         return error;
4155af245d11STodd Fiala     }
4156cb84eebbSTamas Berghammer     std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
4157af245d11STodd Fiala 
4158af245d11STodd Fiala     // Find out the size of a breakpoint (might depend on where we are in the code).
4159cb84eebbSTamas Berghammer     NativeRegisterContextSP context_sp = linux_thread_sp->GetRegisterContext ();
4160af245d11STodd Fiala     if (!context_sp)
4161af245d11STodd Fiala     {
4162af245d11STodd Fiala         error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
4163af245d11STodd Fiala         if (log)
4164af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
4165af245d11STodd Fiala         return error;
4166af245d11STodd Fiala     }
4167af245d11STodd Fiala 
4168af245d11STodd Fiala     uint32_t breakpoint_size = 0;
416963c8be95STamas Berghammer     error = GetSoftwareBreakpointPCOffset (context_sp, breakpoint_size);
4170af245d11STodd Fiala     if (error.Fail ())
4171af245d11STodd Fiala     {
4172af245d11STodd Fiala         if (log)
4173af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
4174af245d11STodd Fiala         return error;
4175af245d11STodd Fiala     }
4176af245d11STodd Fiala     else
4177af245d11STodd Fiala     {
4178af245d11STodd Fiala         if (log)
4179af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
4180af245d11STodd Fiala     }
4181af245d11STodd Fiala 
4182af245d11STodd Fiala     // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
4183af245d11STodd Fiala     const lldb::addr_t initial_pc_addr = context_sp->GetPC ();
4184af245d11STodd Fiala     lldb::addr_t breakpoint_addr = initial_pc_addr;
41853eb4b458SChaoren Lin     if (breakpoint_size > 0)
4186af245d11STodd Fiala     {
4187af245d11STodd Fiala         // Do not allow breakpoint probe to wrap around.
41883eb4b458SChaoren Lin         if (breakpoint_addr >= breakpoint_size)
41893eb4b458SChaoren Lin             breakpoint_addr -= breakpoint_size;
4190af245d11STodd Fiala     }
4191af245d11STodd Fiala 
4192af245d11STodd Fiala     // Check if we stopped because of a breakpoint.
4193af245d11STodd Fiala     NativeBreakpointSP breakpoint_sp;
4194af245d11STodd Fiala     error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
4195af245d11STodd Fiala     if (!error.Success () || !breakpoint_sp)
4196af245d11STodd Fiala     {
4197af245d11STodd Fiala         // We didn't find one at a software probe location.  Nothing to do.
4198af245d11STodd Fiala         if (log)
4199af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
4200af245d11STodd Fiala         return Error ();
4201af245d11STodd Fiala     }
4202af245d11STodd Fiala 
4203af245d11STodd Fiala     // If the breakpoint is not a software breakpoint, nothing to do.
4204af245d11STodd Fiala     if (!breakpoint_sp->IsSoftwareBreakpoint ())
4205af245d11STodd Fiala     {
4206af245d11STodd Fiala         if (log)
4207af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
4208af245d11STodd Fiala         return Error ();
4209af245d11STodd Fiala     }
4210af245d11STodd Fiala 
4211af245d11STodd Fiala     //
4212af245d11STodd Fiala     // We have a software breakpoint and need to adjust the PC.
4213af245d11STodd Fiala     //
4214af245d11STodd Fiala 
4215af245d11STodd Fiala     // Sanity check.
4216af245d11STodd Fiala     if (breakpoint_size == 0)
4217af245d11STodd Fiala     {
4218af245d11STodd Fiala         // Nothing to do!  How did we get here?
4219af245d11STodd Fiala         if (log)
4220af245d11STodd 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);
4221af245d11STodd Fiala         return Error ();
4222af245d11STodd Fiala     }
4223af245d11STodd Fiala 
4224af245d11STodd Fiala     // Change the program counter.
4225af245d11STodd Fiala     if (log)
4226cb84eebbSTamas 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);
4227af245d11STodd Fiala 
4228af245d11STodd Fiala     error = context_sp->SetPC (breakpoint_addr);
4229af245d11STodd Fiala     if (error.Fail ())
4230af245d11STodd Fiala     {
4231af245d11STodd Fiala         if (log)
4232cb84eebbSTamas Berghammer             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": failed to set PC: %s", __FUNCTION__, GetID (), linux_thread_sp->GetID (), error.AsCString ());
4233af245d11STodd Fiala         return error;
4234af245d11STodd Fiala     }
4235af245d11STodd Fiala 
4236af245d11STodd Fiala     return error;
4237af245d11STodd Fiala }
4238fa03ad2eSChaoren Lin 
42397cb18bf5STamas Berghammer Error
42407cb18bf5STamas Berghammer NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec)
42417cb18bf5STamas Berghammer {
42427cb18bf5STamas Berghammer     char maps_file_name[32];
42437cb18bf5STamas Berghammer     snprintf(maps_file_name, sizeof(maps_file_name), "/proc/%" PRIu64 "/maps", GetID());
42447cb18bf5STamas Berghammer 
42457cb18bf5STamas Berghammer     FileSpec maps_file_spec(maps_file_name, false);
42467cb18bf5STamas Berghammer     if (!maps_file_spec.Exists()) {
42477cb18bf5STamas Berghammer         file_spec.Clear();
42487cb18bf5STamas Berghammer         return Error("/proc/%" PRIu64 "/maps file doesn't exists!", GetID());
42497cb18bf5STamas Berghammer     }
42507cb18bf5STamas Berghammer 
42517cb18bf5STamas Berghammer     FileSpec module_file_spec(module_path, true);
42527cb18bf5STamas Berghammer 
42537cb18bf5STamas Berghammer     std::ifstream maps_file(maps_file_name);
42547cb18bf5STamas Berghammer     std::string maps_data_str((std::istreambuf_iterator<char>(maps_file)), std::istreambuf_iterator<char>());
42557cb18bf5STamas Berghammer     StringRef maps_data(maps_data_str.c_str());
42567cb18bf5STamas Berghammer 
42577cb18bf5STamas Berghammer     while (!maps_data.empty())
42587cb18bf5STamas Berghammer     {
42597cb18bf5STamas Berghammer         StringRef maps_row;
42607cb18bf5STamas Berghammer         std::tie(maps_row, maps_data) = maps_data.split('\n');
42617cb18bf5STamas Berghammer 
42627cb18bf5STamas Berghammer         SmallVector<StringRef, 16> maps_columns;
42637cb18bf5STamas Berghammer         maps_row.split(maps_columns, StringRef(" "), -1, false);
42647cb18bf5STamas Berghammer 
42657cb18bf5STamas Berghammer         if (maps_columns.size() >= 6)
42667cb18bf5STamas Berghammer         {
42677cb18bf5STamas Berghammer             file_spec.SetFile(maps_columns[5].str().c_str(), false);
42687cb18bf5STamas Berghammer             if (file_spec.GetFilename() == module_file_spec.GetFilename())
42697cb18bf5STamas Berghammer                 return Error();
42707cb18bf5STamas Berghammer         }
42717cb18bf5STamas Berghammer     }
42727cb18bf5STamas Berghammer 
42737cb18bf5STamas Berghammer     file_spec.Clear();
42747cb18bf5STamas Berghammer     return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
42757cb18bf5STamas Berghammer                  module_file_spec.GetFilename().AsCString(), GetID());
42767cb18bf5STamas Berghammer }
4277c076559aSPavel Labath 
42785eb721edSPavel Labath Error
42791dbc6c9cSPavel Labath NativeProcessLinux::ResumeThread(
4280c076559aSPavel Labath         lldb::tid_t tid,
42818c8ff7afSPavel Labath         NativeThreadLinux::ResumeThreadFunction request_thread_resume_function,
4282c076559aSPavel Labath         bool error_when_already_running)
4283c076559aSPavel Labath {
42845eb721edSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
42855eb721edSPavel Labath 
42861dbc6c9cSPavel Labath     if (log)
42871dbc6c9cSPavel Labath         log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ", error_when_already_running: %s)",
42881dbc6c9cSPavel Labath                 __FUNCTION__, tid, error_when_already_running?"true":"false");
42891dbc6c9cSPavel Labath 
42908c8ff7afSPavel Labath     auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
42918c8ff7afSPavel Labath     lldbassert(thread_sp != nullptr);
42925eb721edSPavel Labath 
42938c8ff7afSPavel Labath     auto& context = thread_sp->GetThreadContext();
4294c076559aSPavel Labath     // Tell the thread to resume if we don't already think it is running.
42958c8ff7afSPavel Labath     const bool is_stopped = StateIsStoppedState(thread_sp->GetState(), true);
42965eb721edSPavel Labath 
42975eb721edSPavel Labath     lldbassert(!(error_when_already_running && !is_stopped));
42985eb721edSPavel Labath 
4299c076559aSPavel Labath     if (!is_stopped)
4300c076559aSPavel Labath     {
4301c076559aSPavel Labath         // It's not an error, just a log, if the error_when_already_running flag is not set.
4302c076559aSPavel Labath         // This covers cases where, for instance, we're just trying to resume all threads
4303c076559aSPavel Labath         // from the user side.
43045eb721edSPavel Labath         if (log)
43055eb721edSPavel Labath             log->Printf("NativeProcessLinux::%s tid %" PRIu64 " optional resume skipped since it is already running",
4306c076559aSPavel Labath                     __FUNCTION__,
4307c076559aSPavel Labath                     tid);
43085eb721edSPavel Labath         return Error();
4309c076559aSPavel Labath     }
4310c076559aSPavel Labath 
4311c076559aSPavel Labath     // Before we do the resume below, first check if we have a pending
4312108c325dSPavel Labath     // stop notification that is currently waiting for
4313c076559aSPavel Labath     // this thread to stop.  This is potentially a buggy situation since
4314c076559aSPavel Labath     // we're ostensibly waiting for threads to stop before we send out the
4315c076559aSPavel Labath     // pending notification, and here we are resuming one before we send
4316c076559aSPavel Labath     // out the pending stop notification.
4317108c325dSPavel Labath     if (m_pending_notification_up && log && m_pending_notification_up->wait_for_stop_tids.count (tid) > 0)
4318c076559aSPavel Labath     {
43195eb721edSPavel 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);
4320c076559aSPavel Labath     }
4321c076559aSPavel Labath 
4322c076559aSPavel Labath     // Request a resume.  We expect this to be synchronous and the system
4323c076559aSPavel Labath     // to reflect it is running after this completes.
4324c076559aSPavel Labath     const auto error = request_thread_resume_function (tid, false);
4325c076559aSPavel Labath     if (error.Success())
43268c8ff7afSPavel Labath         context.request_resume_function = request_thread_resume_function;
43275eb721edSPavel Labath     else if (log)
4328c076559aSPavel Labath     {
43295eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s failed to resume thread tid  %" PRIu64 ": %s",
4330c076559aSPavel Labath                          __FUNCTION__, tid, error.AsCString ());
4331c076559aSPavel Labath     }
4332c076559aSPavel Labath 
43335eb721edSPavel Labath     return error;
4334c076559aSPavel Labath }
4335c076559aSPavel Labath 
4336c076559aSPavel Labath //===----------------------------------------------------------------------===//
4337c076559aSPavel Labath 
4338c076559aSPavel Labath void
4339337f3eb9SPavel Labath NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid)
4340c076559aSPavel Labath {
43415eb721edSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
4342c076559aSPavel Labath 
43435eb721edSPavel Labath     if (log)
4344c076559aSPavel Labath     {
43455eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ")",
4346c076559aSPavel Labath                 __FUNCTION__, triggering_tid);
4347c076559aSPavel Labath     }
4348c076559aSPavel Labath 
4349337f3eb9SPavel Labath     DoStopThreads(PendingNotificationUP(new PendingNotification(triggering_tid)));
4350c076559aSPavel Labath 
43515eb721edSPavel Labath     if (log)
4352c076559aSPavel Labath     {
43535eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
4354c076559aSPavel Labath     }
4355c076559aSPavel Labath }
4356c076559aSPavel Labath 
4357c076559aSPavel Labath void
4358c076559aSPavel Labath NativeProcessLinux::SignalIfRequirementsSatisfied()
4359c076559aSPavel Labath {
4360c076559aSPavel Labath     if (m_pending_notification_up && m_pending_notification_up->wait_for_stop_tids.empty ())
4361c076559aSPavel Labath     {
4362ed89c7feSPavel Labath         SetCurrentThreadID(m_pending_notification_up->triggering_tid);
4363ed89c7feSPavel Labath         SetState(StateType::eStateStopped, true);
4364c076559aSPavel Labath         m_pending_notification_up.reset();
4365c076559aSPavel Labath     }
4366c076559aSPavel Labath }
4367c076559aSPavel Labath 
4368c076559aSPavel Labath void
4369c076559aSPavel Labath NativeProcessLinux::RequestStopOnAllRunningThreads()
4370c076559aSPavel Labath {
4371c076559aSPavel Labath     // Request a stop for all the thread stops that need to be stopped
4372c076559aSPavel Labath     // and are not already known to be stopped.  Keep a list of all the
4373c076559aSPavel Labath     // threads from which we still need to hear a stop reply.
4374c076559aSPavel Labath 
4375c076559aSPavel Labath     ThreadIDSet sent_tids;
43768c8ff7afSPavel Labath     for (const auto &thread_sp: m_threads)
4377c076559aSPavel Labath     {
43788c8ff7afSPavel Labath         // We only care about running threads
43798c8ff7afSPavel Labath         if (StateIsStoppedState(thread_sp->GetState(), true))
43808c8ff7afSPavel Labath             continue;
43818c8ff7afSPavel Labath 
43828c8ff7afSPavel Labath         static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
4383108c325dSPavel Labath         sent_tids.insert (thread_sp->GetID());
4384c076559aSPavel Labath     }
4385c076559aSPavel Labath 
4386c076559aSPavel Labath     // Set the wait list to the set of tids for which we requested stops.
4387c076559aSPavel Labath     m_pending_notification_up->wait_for_stop_tids.swap (sent_tids);
4388c076559aSPavel Labath }
4389c076559aSPavel Labath 
4390c076559aSPavel Labath 
43915eb721edSPavel Labath Error
43925eb721edSPavel Labath NativeProcessLinux::ThreadDidStop (lldb::tid_t tid, bool initiated_by_llgs)
4393c076559aSPavel Labath {
43941dbc6c9cSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
43951dbc6c9cSPavel Labath 
43961dbc6c9cSPavel Labath     if (log)
43971dbc6c9cSPavel Labath         log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ", %sinitiated by llgs)",
43981dbc6c9cSPavel Labath                 __FUNCTION__, tid, initiated_by_llgs?"":"not ");
43991dbc6c9cSPavel Labath 
4400c076559aSPavel Labath     // Ensure we know about the thread.
44018c8ff7afSPavel Labath     auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
44028c8ff7afSPavel Labath     lldbassert(thread_sp != nullptr);
4403c076559aSPavel Labath 
4404c076559aSPavel Labath     // Update the global list of known thread states.  This one is definitely stopped.
44058c8ff7afSPavel Labath     auto& context = thread_sp->GetThreadContext();
44068c8ff7afSPavel Labath     const auto stop_was_requested = context.stop_requested;
44078c8ff7afSPavel Labath     context.stop_requested = false;
4408c076559aSPavel Labath 
4409c076559aSPavel Labath     // If we have a pending notification, remove this from the set.
4410c076559aSPavel Labath     if (m_pending_notification_up)
4411c076559aSPavel Labath     {
4412c076559aSPavel Labath         m_pending_notification_up->wait_for_stop_tids.erase(tid);
4413c076559aSPavel Labath         SignalIfRequirementsSatisfied();
4414c076559aSPavel Labath     }
4415c076559aSPavel Labath 
44168c8ff7afSPavel Labath     Error error;
44178c8ff7afSPavel Labath     if (initiated_by_llgs && context.request_resume_function && !stop_was_requested)
4418c076559aSPavel Labath     {
4419c076559aSPavel Labath         // We can end up here if stop was initiated by LLGS but by this time a
4420c076559aSPavel Labath         // thread stop has occurred - maybe initiated by another event.
44215eb721edSPavel Labath         if (log)
44225eb721edSPavel Labath             log->Printf("Resuming thread %"  PRIu64 " since stop wasn't requested", tid);
44238c8ff7afSPavel Labath         error = context.request_resume_function (tid, true);
44248c8ff7afSPavel Labath         if (error.Fail() && log)
44255eb721edSPavel Labath         {
44265eb721edSPavel Labath                 log->Printf("NativeProcessLinux::%s failed to resume thread tid  %" PRIu64 ": %s",
4427c076559aSPavel Labath                         __FUNCTION__, tid, error.AsCString ());
4428c076559aSPavel Labath         }
44298c8ff7afSPavel Labath     }
44305eb721edSPavel Labath     return error;
4431c076559aSPavel Labath }
4432c076559aSPavel Labath 
4433c076559aSPavel Labath void
4434ed89c7feSPavel Labath NativeProcessLinux::DoStopThreads(PendingNotificationUP &&notification_up)
4435c076559aSPavel Labath {
44365eb721edSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
44375eb721edSPavel Labath     if (m_pending_notification_up && log)
4438c076559aSPavel Labath     {
4439c076559aSPavel Labath         // Yikes - we've already got a pending signal notification in progress.
4440c076559aSPavel Labath         // Log this info.  We lose the pending notification here.
44415eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s dropping existing pending signal notification for tid %" PRIu64 ", to be replaced with signal for tid %" PRIu64,
4442c076559aSPavel Labath                    __FUNCTION__,
4443c076559aSPavel Labath                    m_pending_notification_up->triggering_tid,
4444c076559aSPavel Labath                    notification_up->triggering_tid);
4445c076559aSPavel Labath     }
4446c076559aSPavel Labath     m_pending_notification_up = std::move(notification_up);
4447c076559aSPavel Labath 
4448c076559aSPavel Labath     RequestStopOnAllRunningThreads();
4449c076559aSPavel Labath 
4450ed89c7feSPavel Labath     SignalIfRequirementsSatisfied();
4451c076559aSPavel Labath }
4452c076559aSPavel Labath 
4453c076559aSPavel Labath void
44548c8ff7afSPavel Labath NativeProcessLinux::ThreadWasCreated (lldb::tid_t tid)
4455c076559aSPavel Labath {
44561dbc6c9cSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
44571dbc6c9cSPavel Labath 
44581dbc6c9cSPavel Labath     if (log)
44591dbc6c9cSPavel Labath         log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, tid);
44601dbc6c9cSPavel Labath 
44618c8ff7afSPavel Labath     auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
44628c8ff7afSPavel Labath     lldbassert(thread_sp != nullptr);
4463c076559aSPavel Labath 
44648c8ff7afSPavel Labath     if (m_pending_notification_up && StateIsRunningState(thread_sp->GetState()))
4465c076559aSPavel Labath     {
4466c076559aSPavel Labath         // We will need to wait for this new thread to stop as well before firing the
4467c076559aSPavel Labath         // notification.
4468c076559aSPavel Labath         m_pending_notification_up->wait_for_stop_tids.insert(tid);
44698c8ff7afSPavel Labath         thread_sp->RequestStop();
4470c076559aSPavel Labath     }
4471c076559aSPavel Labath }
4472