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
767cdad63b3SOmair 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     {
788cdad63b3SOmair 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
804cdad63b3SOmair Javaid     }
805cdad63b3SOmair 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
900cdad63b3SOmair 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     {
926cdad63b3SOmair 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));
931341eda4cSVince Harron         ioVec.iov_base = &dreg_state;
932341eda4cSVince Harron         ioVec.iov_len = sizeof (dreg_state);
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
947cdad63b3SOmair Javaid     }
948cdad63b3SOmair 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.
2269*39036ac3SPavel Labath             // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the
2270*39036ac3SPavel Labath             // tracee, triggering the group-stop mechanism. Normally receiving these would stop
2271*39036ac3SPavel Labath             // the process, pending a SIGCONT. Simulating this state in a debugger is hard and is
2272*39036ac3SPavel Labath             // generally not needed (one use case is debugging background task being managed by a
2273*39036ac3SPavel Labath             // shell). For general use, it is sufficient to stop the process in a signal-delivery
2274*39036ac3SPavel Labath             // stop which happens before the group stop. This done by MonitorSignal and works
2275*39036ac3SPavel Labath             // correctly for all signals.
2276fa03ad2eSChaoren Lin             if (log)
2277*39036ac3SPavel Labath                 log->Printf("NativeProcessLinux::%s received a group stop for pid %" PRIu64 " tid %" PRIu64 ". Transparent handling of group stops not supported, resuming the thread.", __FUNCTION__, GetID (), pid);
2278*39036ac3SPavel Labath             Resume(pid, signal);
2279a9882ceeSTodd Fiala         }
2280a9882ceeSTodd Fiala         else
2281a9882ceeSTodd Fiala         {
2282af245d11STodd Fiala             // ptrace(GETSIGINFO) failed (but not due to group-stop).
2283af245d11STodd Fiala 
2284af245d11STodd Fiala             // A return value of ESRCH means the thread/process is no longer on the system,
2285af245d11STodd Fiala             // so it was killed somehow outside of our control.  Either way, we can't do anything
2286af245d11STodd Fiala             // with it anymore.
2287af245d11STodd Fiala 
2288af245d11STodd Fiala             // Stop tracking the metadata for the thread since it's entirely off the system now.
22891107b5a5SPavel Labath             const bool thread_found = StopTrackingThread (pid);
2290af245d11STodd Fiala 
2291af245d11STodd Fiala             if (log)
2292af245d11STodd Fiala                 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
229397ccc294SChaoren 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");
2294af245d11STodd Fiala 
2295af245d11STodd Fiala             if (is_main_thread)
2296af245d11STodd Fiala             {
2297af245d11STodd Fiala                 // Notify the delegate - our process is not available but appears to have been killed outside
2298af245d11STodd Fiala                 // our control.  Is eStateExited the right exit state in this case?
22991107b5a5SPavel Labath                 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
23001107b5a5SPavel Labath                 SetState (StateType::eStateExited, true);
2301af245d11STodd Fiala             }
2302af245d11STodd Fiala             else
2303af245d11STodd Fiala             {
2304af245d11STodd Fiala                 // This thread was pulled out from underneath us.  Anything to do here? Do we want to do an all stop?
2305af245d11STodd Fiala                 if (log)
23061107b5a5SPavel 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);
2307af245d11STodd Fiala             }
2308af245d11STodd Fiala         }
2309af245d11STodd Fiala     }
2310af245d11STodd Fiala }
2311af245d11STodd Fiala 
2312af245d11STodd Fiala void
2313426bdf88SPavel Labath NativeProcessLinux::WaitForNewThread(::pid_t tid)
2314426bdf88SPavel Labath {
2315426bdf88SPavel Labath     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2316426bdf88SPavel Labath 
2317426bdf88SPavel Labath     NativeThreadProtocolSP new_thread_sp = GetThreadByID(tid);
2318426bdf88SPavel Labath 
2319426bdf88SPavel Labath     if (new_thread_sp)
2320426bdf88SPavel Labath     {
2321426bdf88SPavel Labath         // We are already tracking the thread - we got the event on the new thread (see
2322426bdf88SPavel Labath         // MonitorSignal) before this one. We are done.
2323426bdf88SPavel Labath         return;
2324426bdf88SPavel Labath     }
2325426bdf88SPavel Labath 
2326426bdf88SPavel Labath     // The thread is not tracked yet, let's wait for it to appear.
2327426bdf88SPavel Labath     int status = -1;
2328426bdf88SPavel Labath     ::pid_t wait_pid;
2329426bdf88SPavel Labath     do
2330426bdf88SPavel Labath     {
2331426bdf88SPavel Labath         if (log)
2332426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() received thread creation event for tid %" PRIu32 ". tid not tracked yet, waiting for thread to appear...", __FUNCTION__, tid);
2333426bdf88SPavel Labath         wait_pid = waitpid(tid, &status, __WALL);
2334426bdf88SPavel Labath     }
2335426bdf88SPavel Labath     while (wait_pid == -1 && errno == EINTR);
2336426bdf88SPavel Labath     // Since we are waiting on a specific tid, this must be the creation event. But let's do
2337426bdf88SPavel Labath     // some checks just in case.
2338426bdf88SPavel Labath     if (wait_pid != tid) {
2339426bdf88SPavel Labath         if (log)
2340426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime", __FUNCTION__, tid);
2341426bdf88SPavel Labath         // The only way I know of this could happen is if the whole process was
2342426bdf88SPavel Labath         // SIGKILLed in the mean time. In any case, we can't do anything about that now.
2343426bdf88SPavel Labath         return;
2344426bdf88SPavel Labath     }
2345426bdf88SPavel Labath     if (WIFEXITED(status))
2346426bdf88SPavel Labath     {
2347426bdf88SPavel Labath         if (log)
2348426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " returned an 'exited' event. Not tracking the thread.", __FUNCTION__, tid);
2349426bdf88SPavel Labath         // Also a very improbable event.
2350426bdf88SPavel Labath         return;
2351426bdf88SPavel Labath     }
2352426bdf88SPavel Labath 
2353426bdf88SPavel Labath     siginfo_t info;
2354426bdf88SPavel Labath     Error error = GetSignalInfo(tid, &info);
2355426bdf88SPavel Labath     if (error.Fail())
2356426bdf88SPavel Labath     {
2357426bdf88SPavel Labath         if (log)
2358426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime.", __FUNCTION__, tid);
2359426bdf88SPavel Labath         return;
2360426bdf88SPavel Labath     }
2361426bdf88SPavel Labath 
2362426bdf88SPavel Labath     if (((info.si_pid != 0) || (info.si_code != SI_USER)) && log)
2363426bdf88SPavel Labath     {
2364426bdf88SPavel Labath         // We should be getting a thread creation signal here, but we received something
2365426bdf88SPavel Labath         // else. There isn't much we can do about it now, so we will just log that. Since the
2366426bdf88SPavel Labath         // thread is alive and we are receiving events from it, we shall pretend that it was
2367426bdf88SPavel Labath         // created properly.
2368426bdf88SPavel 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);
2369426bdf88SPavel Labath     }
2370426bdf88SPavel Labath 
2371426bdf88SPavel Labath     if (log)
2372426bdf88SPavel Labath         log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 ": tracking new thread tid %" PRIu32,
2373426bdf88SPavel Labath                  __FUNCTION__, GetID (), tid);
2374426bdf88SPavel Labath 
2375426bdf88SPavel Labath     new_thread_sp = AddThread(tid);
2376426bdf88SPavel Labath     std::static_pointer_cast<NativeThreadLinux> (new_thread_sp)->SetRunning ();
2377426bdf88SPavel Labath     Resume (tid, LLDB_INVALID_SIGNAL_NUMBER);
23781dbc6c9cSPavel Labath     ThreadWasCreated(tid);
2379426bdf88SPavel Labath }
2380426bdf88SPavel Labath 
2381426bdf88SPavel Labath void
2382af245d11STodd Fiala NativeProcessLinux::MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid)
2383af245d11STodd Fiala {
2384af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2385af245d11STodd Fiala     const bool is_main_thread = (pid == GetID ());
2386af245d11STodd Fiala 
2387af245d11STodd Fiala     assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
2388af245d11STodd Fiala     if (!info)
2389af245d11STodd Fiala         return;
2390af245d11STodd Fiala 
23915830aa75STamas Berghammer     Mutex::Locker locker (m_threads_mutex);
23925830aa75STamas Berghammer 
2393af245d11STodd Fiala     // See if we can find a thread for this signal.
2394af245d11STodd Fiala     NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2395af245d11STodd Fiala     if (!thread_sp)
2396af245d11STodd Fiala     {
2397af245d11STodd Fiala         if (log)
2398af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2399af245d11STodd Fiala     }
2400af245d11STodd Fiala 
2401af245d11STodd Fiala     switch (info->si_code)
2402af245d11STodd Fiala     {
2403af245d11STodd 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.
2404af245d11STodd Fiala     // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
2405af245d11STodd Fiala     // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
2406af245d11STodd Fiala 
2407af245d11STodd Fiala     case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
2408af245d11STodd Fiala     {
24095fd24c67SPavel Labath         // This is the notification on the parent thread which informs us of new thread
2410426bdf88SPavel Labath         // creation.
2411426bdf88SPavel Labath         // We don't want to do anything with the parent thread so we just resume it. In case we
2412426bdf88SPavel Labath         // want to implement "break on thread creation" functionality, we would need to stop
2413426bdf88SPavel Labath         // here.
2414af245d11STodd Fiala 
2415af245d11STodd Fiala         unsigned long event_message = 0;
2416426bdf88SPavel Labath         if (GetEventMessage (pid, &event_message).Fail())
2417fa03ad2eSChaoren Lin         {
2418426bdf88SPavel Labath             if (log)
2419fa03ad2eSChaoren Lin                 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " received thread creation event but GetEventMessage failed so we don't know the new tid", __FUNCTION__, pid);
2420426bdf88SPavel Labath         } else
2421426bdf88SPavel Labath             WaitForNewThread(event_message);
2422af245d11STodd Fiala 
24235fd24c67SPavel Labath         Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
2424af245d11STodd Fiala         break;
2425af245d11STodd Fiala     }
2426af245d11STodd Fiala 
2427af245d11STodd Fiala     case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
2428a9882ceeSTodd Fiala     {
2429a9882ceeSTodd Fiala         NativeThreadProtocolSP main_thread_sp;
2430af245d11STodd Fiala         if (log)
2431af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
2432a9882ceeSTodd Fiala 
24331dbc6c9cSPavel Labath         // Exec clears any pending notifications.
24341dbc6c9cSPavel Labath         m_pending_notification_up.reset ();
2435fa03ad2eSChaoren Lin 
2436fa03ad2eSChaoren 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.
2437a9882ceeSTodd Fiala         if (log)
2438a9882ceeSTodd Fiala             log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
2439a9882ceeSTodd Fiala 
2440a9882ceeSTodd Fiala         for (auto thread_sp : m_threads)
2441a9882ceeSTodd Fiala         {
2442a9882ceeSTodd Fiala             const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
2443a9882ceeSTodd Fiala             if (is_main_thread)
2444a9882ceeSTodd Fiala             {
2445a9882ceeSTodd Fiala                 main_thread_sp = thread_sp;
2446a9882ceeSTodd Fiala                 if (log)
2447a9882ceeSTodd Fiala                     log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
2448a9882ceeSTodd Fiala             }
2449a9882ceeSTodd Fiala             else
2450a9882ceeSTodd Fiala             {
2451fa03ad2eSChaoren Lin                 // Tell thread coordinator this thread is dead.
2452a9882ceeSTodd Fiala                 if (log)
2453a9882ceeSTodd Fiala                     log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
2454a9882ceeSTodd Fiala             }
2455a9882ceeSTodd Fiala         }
2456a9882ceeSTodd Fiala 
2457a9882ceeSTodd Fiala         m_threads.clear ();
2458a9882ceeSTodd Fiala 
2459a9882ceeSTodd Fiala         if (main_thread_sp)
2460a9882ceeSTodd Fiala         {
2461a9882ceeSTodd Fiala             m_threads.push_back (main_thread_sp);
2462a9882ceeSTodd Fiala             SetCurrentThreadID (main_thread_sp->GetID ());
2463cb84eebbSTamas Berghammer             std::static_pointer_cast<NativeThreadLinux> (main_thread_sp)->SetStoppedByExec ();
2464a9882ceeSTodd Fiala         }
2465a9882ceeSTodd Fiala         else
2466a9882ceeSTodd Fiala         {
2467a9882ceeSTodd Fiala             SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
2468a9882ceeSTodd Fiala             if (log)
2469a9882ceeSTodd Fiala                 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
2470a9882ceeSTodd Fiala         }
2471a9882ceeSTodd Fiala 
2472fa03ad2eSChaoren Lin         // Tell coordinator about about the "new" (since exec) stopped main thread.
2473fa03ad2eSChaoren Lin         const lldb::tid_t main_thread_tid = GetID ();
24741dbc6c9cSPavel Labath         ThreadWasCreated(main_thread_tid);
2475fa03ad2eSChaoren Lin 
2476fa03ad2eSChaoren Lin         // NOTE: ideally these next statements would execute at the same time as the coordinator thread create was executed.
2477fa03ad2eSChaoren Lin         // Consider a handler that can execute when that happens.
2478a9882ceeSTodd Fiala         // Let our delegate know we have just exec'd.
2479a9882ceeSTodd Fiala         NotifyDidExec ();
2480a9882ceeSTodd Fiala 
2481a9882ceeSTodd Fiala         // If we have a main thread, indicate we are stopped.
2482a9882ceeSTodd Fiala         assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
2483fa03ad2eSChaoren Lin 
2484fa03ad2eSChaoren Lin         // Let the process know we're stopped.
2485ed89c7feSPavel Labath         StopRunningThreads (pid);
2486a9882ceeSTodd Fiala 
2487af245d11STodd Fiala         break;
2488a9882ceeSTodd Fiala     }
2489af245d11STodd Fiala 
2490af245d11STodd Fiala     case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
2491af245d11STodd Fiala     {
2492af245d11STodd Fiala         // The inferior process or one of its threads is about to exit.
24936e35163cSPavel Labath         // We don't want to do anything with the thread so we just resume it. In case we
24946e35163cSPavel Labath         // want to implement "break on thread exit" functionality, we would need to stop
24956e35163cSPavel Labath         // here.
2496fa03ad2eSChaoren Lin 
2497af245d11STodd Fiala         unsigned long data = 0;
249897ccc294SChaoren Lin         if (GetEventMessage(pid, &data).Fail())
2499af245d11STodd Fiala             data = -1;
2500af245d11STodd Fiala 
2501af245d11STodd Fiala         if (log)
2502af245d11STodd Fiala         {
2503af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
2504af245d11STodd Fiala                          __FUNCTION__,
2505af245d11STodd Fiala                          data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
2506af245d11STodd Fiala                          pid,
2507af245d11STodd Fiala                     is_main_thread ? "is main thread" : "not main thread");
2508af245d11STodd Fiala         }
2509af245d11STodd Fiala 
2510af245d11STodd Fiala         if (is_main_thread)
2511af245d11STodd Fiala         {
2512af245d11STodd Fiala             SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
251375f47c3aSTodd Fiala         }
251475f47c3aSTodd Fiala 
25156e35163cSPavel Labath         Resume(pid, LLDB_INVALID_SIGNAL_NUMBER);
2516af245d11STodd Fiala 
2517af245d11STodd Fiala         break;
2518af245d11STodd Fiala     }
2519af245d11STodd Fiala 
2520af245d11STodd Fiala     case 0:
2521c16f5dcaSChaoren Lin     case TRAP_TRACE:  // We receive this on single stepping.
2522c16f5dcaSChaoren Lin     case TRAP_HWBKPT: // We receive this on watchpoint hit
252386fd8e45SChaoren Lin         if (thread_sp)
252486fd8e45SChaoren Lin         {
2525c16f5dcaSChaoren Lin             // If a watchpoint was hit, report it
2526c16f5dcaSChaoren Lin             uint32_t wp_index;
2527ea8c25a8SOmair Javaid             Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index, (lldb::addr_t)info->si_addr);
2528c16f5dcaSChaoren Lin             if (error.Fail() && log)
2529c16f5dcaSChaoren Lin                 log->Printf("NativeProcessLinux::%s() "
2530c16f5dcaSChaoren Lin                             "received error while checking for watchpoint hits, "
2531c16f5dcaSChaoren Lin                             "pid = %" PRIu64 " error = %s",
2532c16f5dcaSChaoren Lin                             __FUNCTION__, pid, error.AsCString());
2533c16f5dcaSChaoren Lin             if (wp_index != LLDB_INVALID_INDEX32)
25345830aa75STamas Berghammer             {
2535c16f5dcaSChaoren Lin                 MonitorWatchpoint(pid, thread_sp, wp_index);
2536c16f5dcaSChaoren Lin                 break;
2537c16f5dcaSChaoren Lin             }
2538c16f5dcaSChaoren Lin         }
2539c16f5dcaSChaoren Lin         // Otherwise, report step over
2540c16f5dcaSChaoren Lin         MonitorTrace(pid, thread_sp);
2541af245d11STodd Fiala         break;
2542af245d11STodd Fiala 
2543af245d11STodd Fiala     case SI_KERNEL:
2544af245d11STodd Fiala     case TRAP_BRKPT:
2545c16f5dcaSChaoren Lin         MonitorBreakpoint(pid, thread_sp);
2546af245d11STodd Fiala         break;
2547af245d11STodd Fiala 
2548af245d11STodd Fiala     case SIGTRAP:
2549af245d11STodd Fiala     case (SIGTRAP | 0x80):
2550af245d11STodd Fiala         if (log)
2551fa03ad2eSChaoren Lin             log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), pid);
2552fa03ad2eSChaoren Lin 
2553af245d11STodd Fiala         // Ignore these signals until we know more about them.
25546e35163cSPavel Labath         Resume(pid, LLDB_INVALID_SIGNAL_NUMBER);
2555af245d11STodd Fiala         break;
2556af245d11STodd Fiala 
2557af245d11STodd Fiala     default:
2558af245d11STodd Fiala         assert(false && "Unexpected SIGTRAP code!");
2559af245d11STodd Fiala         if (log)
25606e35163cSPavel Labath             log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 "tid %" PRIu64 " received unhandled SIGTRAP code: 0x%d",
25616e35163cSPavel Labath                     __FUNCTION__, GetID (), pid, info->si_code);
2562af245d11STodd Fiala         break;
2563af245d11STodd Fiala 
2564af245d11STodd Fiala     }
2565af245d11STodd Fiala }
2566af245d11STodd Fiala 
2567af245d11STodd Fiala void
2568c16f5dcaSChaoren Lin NativeProcessLinux::MonitorTrace(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
2569c16f5dcaSChaoren Lin {
2570c16f5dcaSChaoren Lin     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2571c16f5dcaSChaoren Lin     if (log)
2572c16f5dcaSChaoren Lin         log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)",
2573c16f5dcaSChaoren Lin                 __FUNCTION__, pid);
2574c16f5dcaSChaoren Lin 
2575c16f5dcaSChaoren Lin     if (thread_sp)
2576c16f5dcaSChaoren Lin         std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
2577c16f5dcaSChaoren Lin 
2578c16f5dcaSChaoren Lin     // This thread is currently stopped.
25791dbc6c9cSPavel Labath     ThreadDidStop(pid, false);
2580c16f5dcaSChaoren Lin 
2581c16f5dcaSChaoren Lin     // Here we don't have to request the rest of the threads to stop or request a deferred stop.
2582c16f5dcaSChaoren Lin     // This would have already happened at the time the Resume() with step operation was signaled.
2583c16f5dcaSChaoren Lin     // At this point, we just need to say we stopped, and the deferred notifcation will fire off
2584c16f5dcaSChaoren Lin     // once all running threads have checked in as stopped.
2585c16f5dcaSChaoren Lin     SetCurrentThreadID(pid);
2586c16f5dcaSChaoren Lin     // Tell the process we have a stop (from software breakpoint).
2587ed89c7feSPavel Labath     StopRunningThreads(pid);
2588c16f5dcaSChaoren Lin }
2589c16f5dcaSChaoren Lin 
2590c16f5dcaSChaoren Lin void
2591c16f5dcaSChaoren Lin NativeProcessLinux::MonitorBreakpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
2592c16f5dcaSChaoren Lin {
2593c16f5dcaSChaoren Lin     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
2594c16f5dcaSChaoren Lin     if (log)
2595c16f5dcaSChaoren Lin         log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
2596c16f5dcaSChaoren Lin                 __FUNCTION__, pid);
2597c16f5dcaSChaoren Lin 
2598c16f5dcaSChaoren Lin     // This thread is currently stopped.
25991dbc6c9cSPavel Labath     ThreadDidStop(pid, false);
2600c16f5dcaSChaoren Lin 
2601c16f5dcaSChaoren Lin     // Mark the thread as stopped at breakpoint.
2602c16f5dcaSChaoren Lin     if (thread_sp)
2603c16f5dcaSChaoren Lin     {
2604c16f5dcaSChaoren Lin         std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByBreakpoint();
2605c16f5dcaSChaoren Lin         Error error = FixupBreakpointPCAsNeeded(thread_sp);
2606c16f5dcaSChaoren Lin         if (error.Fail())
2607c16f5dcaSChaoren Lin             if (log)
2608c16f5dcaSChaoren Lin                 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
2609c16f5dcaSChaoren Lin                         __FUNCTION__, pid, error.AsCString());
2610d8c338d4STamas Berghammer 
26119eb1ecb9SPavel Labath         if (m_threads_stepping_with_breakpoint.find(pid) != m_threads_stepping_with_breakpoint.end())
2612d8c338d4STamas Berghammer             std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
2613d8c338d4STamas Berghammer     }
2614c16f5dcaSChaoren Lin     else
2615c16f5dcaSChaoren Lin         if (log)
2616c16f5dcaSChaoren Lin             log->Printf("NativeProcessLinux::%s()  pid = %" PRIu64 ": "
2617c16f5dcaSChaoren Lin                     "warning, cannot process software breakpoint since no thread metadata",
2618c16f5dcaSChaoren Lin                     __FUNCTION__, pid);
2619c16f5dcaSChaoren Lin 
2620c16f5dcaSChaoren Lin 
2621c16f5dcaSChaoren Lin     // We need to tell all other running threads before we notify the delegate about this stop.
2622ed89c7feSPavel Labath     StopRunningThreads(pid);
2623c16f5dcaSChaoren Lin }
2624c16f5dcaSChaoren Lin 
2625c16f5dcaSChaoren Lin void
2626c16f5dcaSChaoren Lin NativeProcessLinux::MonitorWatchpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp, uint32_t wp_index)
2627c16f5dcaSChaoren Lin {
2628c16f5dcaSChaoren Lin     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
2629c16f5dcaSChaoren Lin     if (log)
2630c16f5dcaSChaoren Lin         log->Printf("NativeProcessLinux::%s() received watchpoint event, "
2631c16f5dcaSChaoren Lin                     "pid = %" PRIu64 ", wp_index = %" PRIu32,
2632c16f5dcaSChaoren Lin                     __FUNCTION__, pid, wp_index);
2633c16f5dcaSChaoren Lin 
2634c16f5dcaSChaoren Lin     // This thread is currently stopped.
26351dbc6c9cSPavel Labath     ThreadDidStop(pid, false);
2636c16f5dcaSChaoren Lin 
2637c16f5dcaSChaoren Lin     // Mark the thread as stopped at watchpoint.
2638c16f5dcaSChaoren Lin     // The address is at (lldb::addr_t)info->si_addr if we need it.
2639c16f5dcaSChaoren Lin     lldbassert(thread_sp && "thread_sp cannot be NULL");
2640c16f5dcaSChaoren Lin     std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByWatchpoint(wp_index);
2641c16f5dcaSChaoren Lin 
2642c16f5dcaSChaoren Lin     // We need to tell all other running threads before we notify the delegate about this stop.
2643ed89c7feSPavel Labath     StopRunningThreads(pid);
2644c16f5dcaSChaoren Lin }
2645c16f5dcaSChaoren Lin 
2646c16f5dcaSChaoren Lin void
2647af245d11STodd Fiala NativeProcessLinux::MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited)
2648af245d11STodd Fiala {
2649511e5cdcSTodd Fiala     assert (info && "null info");
2650511e5cdcSTodd Fiala     if (!info)
2651511e5cdcSTodd Fiala         return;
2652511e5cdcSTodd Fiala 
2653511e5cdcSTodd Fiala     const int signo = info->si_signo;
2654511e5cdcSTodd Fiala     const bool is_from_llgs = info->si_pid == getpid ();
2655af245d11STodd Fiala 
2656af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2657af245d11STodd Fiala 
2658af245d11STodd Fiala     // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
2659af245d11STodd Fiala     // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
2660af245d11STodd Fiala     // kill(2) or raise(3).  Similarly for tgkill(2) on Linux.
2661af245d11STodd Fiala     //
2662af245d11STodd Fiala     // IOW, user generated signals never generate what we consider to be a
2663af245d11STodd Fiala     // "crash".
2664af245d11STodd Fiala     //
2665af245d11STodd Fiala     // Similarly, ACK signals generated by this monitor.
2666af245d11STodd Fiala 
26675830aa75STamas Berghammer     Mutex::Locker locker (m_threads_mutex);
26685830aa75STamas Berghammer 
2669af245d11STodd Fiala     // See if we can find a thread for this signal.
2670af245d11STodd Fiala     NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2671af245d11STodd Fiala     if (!thread_sp)
2672af245d11STodd Fiala     {
2673af245d11STodd Fiala         if (log)
2674af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2675af245d11STodd Fiala     }
2676af245d11STodd Fiala 
2677af245d11STodd Fiala     // Handle the signal.
2678af245d11STodd Fiala     if (info->si_code == SI_TKILL || info->si_code == SI_USER)
2679af245d11STodd Fiala     {
2680af245d11STodd Fiala         if (log)
2681af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
2682af245d11STodd Fiala                             __FUNCTION__,
2683af245d11STodd Fiala                             GetUnixSignals ().GetSignalAsCString (signo),
2684af245d11STodd Fiala                             signo,
2685af245d11STodd Fiala                             (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
2686af245d11STodd Fiala                             info->si_pid,
2687511e5cdcSTodd Fiala                             is_from_llgs ? "from llgs" : "not from llgs",
2688af245d11STodd Fiala                             pid);
268958a2f669STodd Fiala     }
2690af245d11STodd Fiala 
269158a2f669STodd Fiala     // Check for new thread notification.
269258a2f669STodd Fiala     if ((info->si_pid == 0) && (info->si_code == SI_USER))
2693af245d11STodd Fiala     {
2694af245d11STodd Fiala         // A new thread creation is being signaled. This is one of two parts that come in
2695426bdf88SPavel Labath         // a non-deterministic order. This code handles the case where the new thread event comes
2696426bdf88SPavel Labath         // before the event on the parent thread. For the opposite case see code in
2697426bdf88SPavel Labath         // MonitorSIGTRAP.
2698af245d11STodd Fiala         if (log)
2699af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": new thread notification",
2700af245d11STodd Fiala                      __FUNCTION__, GetID (), pid);
2701af245d11STodd Fiala 
27025fd24c67SPavel Labath         thread_sp = AddThread(pid);
27035fd24c67SPavel Labath         assert (thread_sp.get() && "failed to create the tracking data for newly created inferior thread");
27045fd24c67SPavel Labath         // We can now resume the newly created thread.
2705cb84eebbSTamas Berghammer         std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
27065fd24c67SPavel Labath         Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
27071dbc6c9cSPavel Labath         ThreadWasCreated(pid);
270858a2f669STodd Fiala         // Done handling.
270958a2f669STodd Fiala         return;
2710af245d11STodd Fiala     }
271158a2f669STodd Fiala 
271258a2f669STodd Fiala     // Check for thread stop notification.
2713511e5cdcSTodd Fiala     if (is_from_llgs && (info->si_code == SI_TKILL) && (signo == SIGSTOP))
2714af245d11STodd Fiala     {
2715af245d11STodd Fiala         // This is a tgkill()-based stop.
2716af245d11STodd Fiala         if (thread_sp)
2717af245d11STodd Fiala         {
2718fa03ad2eSChaoren Lin             if (log)
2719fa03ad2eSChaoren Lin                 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
2720fa03ad2eSChaoren Lin                              __FUNCTION__,
2721fa03ad2eSChaoren Lin                              GetID (),
2722fa03ad2eSChaoren Lin                              pid);
2723fa03ad2eSChaoren Lin 
2724aab58633SChaoren Lin             // Check that we're not already marked with a stop reason.
2725aab58633SChaoren Lin             // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
2726aab58633SChaoren Lin             // the kernel signaled us with the thread stopping which we handled and marked as stopped,
2727aab58633SChaoren Lin             // and that, without an intervening resume, we received another stop.  It is more likely
2728aab58633SChaoren Lin             // that we are missing the marking of a run state somewhere if we find that the thread was
2729aab58633SChaoren Lin             // marked as stopped.
2730cb84eebbSTamas Berghammer             std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
2731cb84eebbSTamas Berghammer             assert (linux_thread_sp && "linux_thread_sp is null!");
2732aab58633SChaoren Lin 
2733cb84eebbSTamas Berghammer             const StateType thread_state = linux_thread_sp->GetState ();
2734aab58633SChaoren Lin             if (!StateIsStoppedState (thread_state, false))
2735aab58633SChaoren Lin             {
2736ed89c7feSPavel Labath                 // An inferior thread has stopped because of a SIGSTOP we have sent it.
2737ed89c7feSPavel Labath                 // Generally, these are not important stops and we don't want to report them as
2738ed89c7feSPavel Labath                 // they are just used to stop other threads when one thread (the one with the
2739ed89c7feSPavel Labath                 // *real* stop reason) hits a breakpoint (watchpoint, etc...). However, in the
2740ed89c7feSPavel Labath                 // case of an asynchronous Interrupt(), this *is* the real stop reason, so we
2741ed89c7feSPavel Labath                 // leave the signal intact if this is the thread that was chosen as the
2742ed89c7feSPavel Labath                 // triggering thread.
2743ed89c7feSPavel Labath                 if (m_pending_notification_up && m_pending_notification_up->triggering_tid == pid)
2744ed89c7feSPavel Labath                     linux_thread_sp->SetStoppedBySignal(SIGSTOP);
2745ed89c7feSPavel Labath                 else
2746cb84eebbSTamas Berghammer                     linux_thread_sp->SetStoppedBySignal(0);
2747ed89c7feSPavel Labath 
2748af245d11STodd Fiala                 SetCurrentThreadID (thread_sp->GetID ());
27491dbc6c9cSPavel Labath                 ThreadDidStop (thread_sp->GetID (), true);
2750aab58633SChaoren Lin             }
2751aab58633SChaoren Lin             else
2752aab58633SChaoren Lin             {
2753aab58633SChaoren Lin                 if (log)
2754aab58633SChaoren Lin                 {
2755aab58633SChaoren Lin                     // Retrieve the signal name if the thread was stopped by a signal.
2756aab58633SChaoren Lin                     int stop_signo = 0;
2757cb84eebbSTamas Berghammer                     const bool stopped_by_signal = linux_thread_sp->IsStopped (&stop_signo);
2758aab58633SChaoren Lin                     const char *signal_name = stopped_by_signal ? GetUnixSignals ().GetSignalAsCString (stop_signo) : "<not stopped by signal>";
2759aab58633SChaoren Lin                     if (!signal_name)
2760aab58633SChaoren Lin                         signal_name = "<no-signal-name>";
2761aab58633SChaoren Lin 
2762aab58633SChaoren 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",
2763aab58633SChaoren Lin                                  __FUNCTION__,
2764aab58633SChaoren Lin                                  GetID (),
2765cb84eebbSTamas Berghammer                                  linux_thread_sp->GetID (),
2766aab58633SChaoren Lin                                  StateAsCString (thread_state),
2767aab58633SChaoren Lin                                  stop_signo,
2768aab58633SChaoren Lin                                  signal_name);
2769aab58633SChaoren Lin                 }
27701dbc6c9cSPavel Labath                 ThreadDidStop (thread_sp->GetID (), false);
2771af245d11STodd Fiala             }
277286fd8e45SChaoren Lin         }
2773af245d11STodd Fiala 
277458a2f669STodd Fiala         // Done handling.
2775af245d11STodd Fiala         return;
2776af245d11STodd Fiala     }
2777af245d11STodd Fiala 
2778af245d11STodd Fiala     if (log)
2779af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, GetUnixSignals ().GetSignalAsCString (signo));
2780af245d11STodd Fiala 
278186fd8e45SChaoren Lin     // This thread is stopped.
27821dbc6c9cSPavel Labath     ThreadDidStop (pid, false);
278386fd8e45SChaoren Lin 
2784af245d11STodd Fiala     switch (signo)
2785af245d11STodd Fiala     {
278686fd8e45SChaoren Lin     case SIGSEGV:
278786fd8e45SChaoren Lin     case SIGILL:
278886fd8e45SChaoren Lin     case SIGFPE:
278986fd8e45SChaoren Lin     case SIGBUS:
279086fd8e45SChaoren Lin         if (thread_sp)
2791cb84eebbSTamas Berghammer             std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetCrashedWithException (*info);
279286fd8e45SChaoren Lin         break;
279386fd8e45SChaoren Lin     default:
279486fd8e45SChaoren Lin         // This is just a pre-signal-delivery notification of the incoming signal.
279586fd8e45SChaoren Lin         if (thread_sp)
2796cb84eebbSTamas Berghammer             std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (signo);
2797fa03ad2eSChaoren Lin 
279886fd8e45SChaoren Lin         break;
279986fd8e45SChaoren Lin     }
280086fd8e45SChaoren Lin 
280186fd8e45SChaoren Lin     // Send a stop to the debugger after we get all other threads to stop.
2802ed89c7feSPavel Labath     StopRunningThreads (pid);
2803511e5cdcSTodd Fiala }
2804af245d11STodd Fiala 
2805e7708688STamas Berghammer namespace {
2806e7708688STamas Berghammer 
2807e7708688STamas Berghammer struct EmulatorBaton
2808e7708688STamas Berghammer {
2809e7708688STamas Berghammer     NativeProcessLinux* m_process;
2810e7708688STamas Berghammer     NativeRegisterContext* m_reg_context;
28116648fcc3SPavel Labath 
28126648fcc3SPavel Labath     // eRegisterKindDWARF -> RegsiterValue
28136648fcc3SPavel Labath     std::unordered_map<uint32_t, RegisterValue> m_register_values;
2814e7708688STamas Berghammer 
2815e7708688STamas Berghammer     EmulatorBaton(NativeProcessLinux* process, NativeRegisterContext* reg_context) :
2816e7708688STamas Berghammer             m_process(process), m_reg_context(reg_context) {}
2817e7708688STamas Berghammer };
2818e7708688STamas Berghammer 
2819e7708688STamas Berghammer } // anonymous namespace
2820e7708688STamas Berghammer 
2821e7708688STamas Berghammer static size_t
2822e7708688STamas Berghammer ReadMemoryCallback (EmulateInstruction *instruction,
2823e7708688STamas Berghammer                     void *baton,
2824e7708688STamas Berghammer                     const EmulateInstruction::Context &context,
2825e7708688STamas Berghammer                     lldb::addr_t addr,
2826e7708688STamas Berghammer                     void *dst,
2827e7708688STamas Berghammer                     size_t length)
2828e7708688STamas Berghammer {
2829e7708688STamas Berghammer     EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
2830e7708688STamas Berghammer 
28313eb4b458SChaoren Lin     size_t bytes_read;
2832e7708688STamas Berghammer     emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
2833e7708688STamas Berghammer     return bytes_read;
2834e7708688STamas Berghammer }
2835e7708688STamas Berghammer 
2836e7708688STamas Berghammer static bool
2837e7708688STamas Berghammer ReadRegisterCallback (EmulateInstruction *instruction,
2838e7708688STamas Berghammer                       void *baton,
2839e7708688STamas Berghammer                       const RegisterInfo *reg_info,
2840e7708688STamas Berghammer                       RegisterValue &reg_value)
2841e7708688STamas Berghammer {
2842e7708688STamas Berghammer     EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
2843e7708688STamas Berghammer 
28446648fcc3SPavel Labath     auto it = emulator_baton->m_register_values.find(reg_info->kinds[eRegisterKindDWARF]);
28456648fcc3SPavel Labath     if (it != emulator_baton->m_register_values.end())
28466648fcc3SPavel Labath     {
28476648fcc3SPavel Labath         reg_value = it->second;
28486648fcc3SPavel Labath         return true;
28496648fcc3SPavel Labath     }
28506648fcc3SPavel Labath 
2851e7708688STamas Berghammer     // The emulator only fill in the dwarf regsiter numbers (and in some case
2852e7708688STamas Berghammer     // the generic register numbers). Get the full register info from the
2853e7708688STamas Berghammer     // register context based on the dwarf register numbers.
2854e7708688STamas Berghammer     const RegisterInfo* full_reg_info = emulator_baton->m_reg_context->GetRegisterInfo(
2855e7708688STamas Berghammer             eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
2856e7708688STamas Berghammer 
2857e7708688STamas Berghammer     Error error = emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
28586648fcc3SPavel Labath     if (error.Success())
28596648fcc3SPavel Labath         return true;
2860cdc22a88SMohit K. Bhakkad 
28616648fcc3SPavel Labath     return false;
2862e7708688STamas Berghammer }
2863e7708688STamas Berghammer 
2864e7708688STamas Berghammer static bool
2865e7708688STamas Berghammer WriteRegisterCallback (EmulateInstruction *instruction,
2866e7708688STamas Berghammer                        void *baton,
2867e7708688STamas Berghammer                        const EmulateInstruction::Context &context,
2868e7708688STamas Berghammer                        const RegisterInfo *reg_info,
2869e7708688STamas Berghammer                        const RegisterValue &reg_value)
2870e7708688STamas Berghammer {
2871e7708688STamas Berghammer     EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
28726648fcc3SPavel Labath     emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = reg_value;
2873e7708688STamas Berghammer     return true;
2874e7708688STamas Berghammer }
2875e7708688STamas Berghammer 
2876e7708688STamas Berghammer static size_t
2877e7708688STamas Berghammer WriteMemoryCallback (EmulateInstruction *instruction,
2878e7708688STamas Berghammer                      void *baton,
2879e7708688STamas Berghammer                      const EmulateInstruction::Context &context,
2880e7708688STamas Berghammer                      lldb::addr_t addr,
2881e7708688STamas Berghammer                      const void *dst,
2882e7708688STamas Berghammer                      size_t length)
2883e7708688STamas Berghammer {
2884e7708688STamas Berghammer     return length;
2885e7708688STamas Berghammer }
2886e7708688STamas Berghammer 
2887e7708688STamas Berghammer static lldb::addr_t
2888e7708688STamas Berghammer ReadFlags (NativeRegisterContext* regsiter_context)
2889e7708688STamas Berghammer {
2890e7708688STamas Berghammer     const RegisterInfo* flags_info = regsiter_context->GetRegisterInfo(
2891e7708688STamas Berghammer             eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
2892e7708688STamas Berghammer     return regsiter_context->ReadRegisterAsUnsigned(flags_info, LLDB_INVALID_ADDRESS);
2893e7708688STamas Berghammer }
2894e7708688STamas Berghammer 
2895e7708688STamas Berghammer Error
2896e7708688STamas Berghammer NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadProtocolSP thread_sp)
2897e7708688STamas Berghammer {
2898e7708688STamas Berghammer     Error error;
2899e7708688STamas Berghammer     NativeRegisterContextSP register_context_sp = thread_sp->GetRegisterContext();
2900e7708688STamas Berghammer 
2901e7708688STamas Berghammer     std::unique_ptr<EmulateInstruction> emulator_ap(
2902e7708688STamas Berghammer         EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, nullptr));
2903e7708688STamas Berghammer 
2904e7708688STamas Berghammer     if (emulator_ap == nullptr)
2905e7708688STamas Berghammer         return Error("Instruction emulator not found!");
2906e7708688STamas Berghammer 
2907e7708688STamas Berghammer     EmulatorBaton baton(this, register_context_sp.get());
2908e7708688STamas Berghammer     emulator_ap->SetBaton(&baton);
2909e7708688STamas Berghammer     emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
2910e7708688STamas Berghammer     emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
2911e7708688STamas Berghammer     emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
2912e7708688STamas Berghammer     emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
2913e7708688STamas Berghammer 
2914e7708688STamas Berghammer     if (!emulator_ap->ReadInstruction())
2915e7708688STamas Berghammer         return Error("Read instruction failed!");
2916e7708688STamas Berghammer 
29176648fcc3SPavel Labath     bool emulation_result = emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
29186648fcc3SPavel Labath 
29196648fcc3SPavel Labath     const RegisterInfo* reg_info_pc = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
29206648fcc3SPavel Labath     const RegisterInfo* reg_info_flags = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
29216648fcc3SPavel Labath 
29226648fcc3SPavel Labath     auto pc_it = baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
29236648fcc3SPavel Labath     auto flags_it = baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
29246648fcc3SPavel Labath 
2925e7708688STamas Berghammer     lldb::addr_t next_pc;
2926e7708688STamas Berghammer     lldb::addr_t next_flags;
29276648fcc3SPavel Labath     if (emulation_result)
2928e7708688STamas Berghammer     {
29296648fcc3SPavel Labath         assert(pc_it != baton.m_register_values.end() && "Emulation was successfull but PC wasn't updated");
29306648fcc3SPavel Labath         next_pc = pc_it->second.GetAsUInt64();
29316648fcc3SPavel Labath 
29326648fcc3SPavel Labath         if (flags_it != baton.m_register_values.end())
29336648fcc3SPavel Labath             next_flags = flags_it->second.GetAsUInt64();
2934e7708688STamas Berghammer         else
2935e7708688STamas Berghammer             next_flags = ReadFlags (register_context_sp.get());
2936e7708688STamas Berghammer     }
29376648fcc3SPavel Labath     else if (pc_it == baton.m_register_values.end())
2938e7708688STamas Berghammer     {
2939e7708688STamas Berghammer         // Emulate instruction failed and it haven't changed PC. Advance PC
2940e7708688STamas Berghammer         // with the size of the current opcode because the emulation of all
2941e7708688STamas Berghammer         // PC modifying instruction should be successful. The failure most
2942e7708688STamas Berghammer         // likely caused by a not supported instruction which don't modify PC.
2943e7708688STamas Berghammer         next_pc = register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
2944e7708688STamas Berghammer         next_flags = ReadFlags (register_context_sp.get());
2945e7708688STamas Berghammer     }
2946e7708688STamas Berghammer     else
2947e7708688STamas Berghammer     {
2948e7708688STamas Berghammer         // The instruction emulation failed after it modified the PC. It is an
2949e7708688STamas Berghammer         // unknown error where we can't continue because the next instruction is
2950e7708688STamas Berghammer         // modifying the PC but we don't  know how.
2951e7708688STamas Berghammer         return Error ("Instruction emulation failed unexpectedly.");
2952e7708688STamas Berghammer     }
2953e7708688STamas Berghammer 
2954e7708688STamas Berghammer     if (m_arch.GetMachine() == llvm::Triple::arm)
2955e7708688STamas Berghammer     {
2956e7708688STamas Berghammer         if (next_flags & 0x20)
2957e7708688STamas Berghammer         {
2958e7708688STamas Berghammer             // Thumb mode
2959e7708688STamas Berghammer             error = SetSoftwareBreakpoint(next_pc, 2);
2960e7708688STamas Berghammer         }
2961e7708688STamas Berghammer         else
2962e7708688STamas Berghammer         {
2963e7708688STamas Berghammer             // Arm mode
2964e7708688STamas Berghammer             error = SetSoftwareBreakpoint(next_pc, 4);
2965e7708688STamas Berghammer         }
2966e7708688STamas Berghammer     }
2967cdc22a88SMohit K. Bhakkad     else if (m_arch.GetMachine() == llvm::Triple::mips64
2968cdc22a88SMohit K. Bhakkad             || m_arch.GetMachine() == llvm::Triple::mips64el)
2969cdc22a88SMohit K. Bhakkad         error = SetSoftwareBreakpoint(next_pc, 4);
2970e7708688STamas Berghammer     else
2971e7708688STamas Berghammer     {
2972e7708688STamas Berghammer         // No size hint is given for the next breakpoint
2973e7708688STamas Berghammer         error = SetSoftwareBreakpoint(next_pc, 0);
2974e7708688STamas Berghammer     }
2975e7708688STamas Berghammer 
2976e7708688STamas Berghammer     if (error.Fail())
2977e7708688STamas Berghammer         return error;
2978e7708688STamas Berghammer 
2979e7708688STamas Berghammer     m_threads_stepping_with_breakpoint.insert({thread_sp->GetID(), next_pc});
2980e7708688STamas Berghammer 
2981e7708688STamas Berghammer     return Error();
2982e7708688STamas Berghammer }
2983e7708688STamas Berghammer 
2984e7708688STamas Berghammer bool
2985e7708688STamas Berghammer NativeProcessLinux::SupportHardwareSingleStepping() const
2986e7708688STamas Berghammer {
2987cdc22a88SMohit K. Bhakkad     if (m_arch.GetMachine() == llvm::Triple::arm
2988cdc22a88SMohit K. Bhakkad         || m_arch.GetMachine() == llvm::Triple::mips64 || m_arch.GetMachine() == llvm::Triple::mips64el)
2989cdc22a88SMohit K. Bhakkad         return false;
2990cdc22a88SMohit K. Bhakkad     return true;
2991e7708688STamas Berghammer }
2992e7708688STamas Berghammer 
2993af245d11STodd Fiala Error
2994af245d11STodd Fiala NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
2995af245d11STodd Fiala {
2996af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2997af245d11STodd Fiala     if (log)
2998af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
2999af245d11STodd Fiala 
3000e7708688STamas Berghammer     bool software_single_step = !SupportHardwareSingleStepping();
3001af245d11STodd Fiala 
300245f5cb31SPavel Labath     Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
3003af245d11STodd Fiala     Mutex::Locker locker (m_threads_mutex);
30045830aa75STamas Berghammer 
3005e7708688STamas Berghammer     if (software_single_step)
3006e7708688STamas Berghammer     {
3007e7708688STamas Berghammer         for (auto thread_sp : m_threads)
3008e7708688STamas Berghammer         {
3009e7708688STamas Berghammer             assert (thread_sp && "thread list should not contain NULL threads");
3010e7708688STamas Berghammer 
3011e7708688STamas Berghammer             const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
3012e7708688STamas Berghammer             if (action == nullptr)
3013e7708688STamas Berghammer                 continue;
3014e7708688STamas Berghammer 
3015e7708688STamas Berghammer             if (action->state == eStateStepping)
3016e7708688STamas Berghammer             {
3017e7708688STamas Berghammer                 Error error = SetupSoftwareSingleStepping(thread_sp);
3018e7708688STamas Berghammer                 if (error.Fail())
3019e7708688STamas Berghammer                     return error;
3020e7708688STamas Berghammer             }
3021e7708688STamas Berghammer         }
3022e7708688STamas Berghammer     }
3023e7708688STamas Berghammer 
3024af245d11STodd Fiala     for (auto thread_sp : m_threads)
3025af245d11STodd Fiala     {
3026af245d11STodd Fiala         assert (thread_sp && "thread list should not contain NULL threads");
3027af245d11STodd Fiala 
3028af245d11STodd Fiala         const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
30296a196ce6SChaoren Lin 
30306a196ce6SChaoren Lin         if (action == nullptr)
30316a196ce6SChaoren Lin         {
30326a196ce6SChaoren Lin             if (log)
30336a196ce6SChaoren Lin                 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
30346a196ce6SChaoren Lin                     __FUNCTION__, GetID (), thread_sp->GetID ());
30356a196ce6SChaoren Lin             continue;
30366a196ce6SChaoren Lin         }
3037af245d11STodd Fiala 
3038af245d11STodd Fiala         if (log)
3039af245d11STodd Fiala         {
3040af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
3041af245d11STodd Fiala                     __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
3042af245d11STodd Fiala         }
3043af245d11STodd Fiala 
3044af245d11STodd Fiala         switch (action->state)
3045af245d11STodd Fiala         {
3046af245d11STodd Fiala         case eStateRunning:
3047fa03ad2eSChaoren Lin         {
3048af245d11STodd Fiala             // Run the thread, possibly feeding it the signal.
3049fa03ad2eSChaoren Lin             const int signo = action->signal;
30501dbc6c9cSPavel Labath             ResumeThread(thread_sp->GetID (),
305186fd8e45SChaoren Lin                     [=](lldb::tid_t tid_to_resume, bool supress_signal)
3052af245d11STodd Fiala                     {
3053cb84eebbSTamas Berghammer                         std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
3054fa03ad2eSChaoren Lin                         // Pass this signal number on to the inferior to handle.
30555830aa75STamas Berghammer                         const auto resume_result = Resume (tid_to_resume, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
30565830aa75STamas Berghammer                         if (resume_result.Success())
30575830aa75STamas Berghammer                             SetState(eStateRunning, true);
30585830aa75STamas Berghammer                         return resume_result;
30591dbc6c9cSPavel Labath                     },
30601dbc6c9cSPavel Labath                     false);
3061af245d11STodd Fiala             break;
3062fa03ad2eSChaoren Lin         }
3063af245d11STodd Fiala 
3064af245d11STodd Fiala         case eStateStepping:
3065af245d11STodd Fiala         {
3066ae29d395SChaoren Lin             // Request the step.
3067ae29d395SChaoren Lin             const int signo = action->signal;
30681dbc6c9cSPavel Labath             ResumeThread(thread_sp->GetID (),
306986fd8e45SChaoren Lin                     [=](lldb::tid_t tid_to_step, bool supress_signal)
3070af245d11STodd Fiala                     {
3071cb84eebbSTamas Berghammer                         std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStepping ();
3072e7708688STamas Berghammer 
3073e7708688STamas Berghammer                         Error step_result;
3074e7708688STamas Berghammer                         if (software_single_step)
3075e7708688STamas Berghammer                             step_result = Resume (tid_to_step, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
3076e7708688STamas Berghammer                         else
3077e7708688STamas Berghammer                             step_result = SingleStep (tid_to_step,(signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
3078e7708688STamas Berghammer 
307937c768caSChaoren Lin                         assert (step_result.Success() && "SingleStep() failed");
30805830aa75STamas Berghammer                         if (step_result.Success())
30815830aa75STamas Berghammer                             SetState(eStateStepping, true);
308237c768caSChaoren Lin                         return step_result;
30831dbc6c9cSPavel Labath                     },
30841dbc6c9cSPavel Labath                     false);
3085af245d11STodd Fiala             break;
3086ae29d395SChaoren Lin         }
3087af245d11STodd Fiala 
3088af245d11STodd Fiala         case eStateSuspended:
3089af245d11STodd Fiala         case eStateStopped:
3090108c325dSPavel Labath             lldbassert(0 && "Unexpected state");
3091af245d11STodd Fiala 
3092af245d11STodd Fiala         default:
3093af245d11STodd Fiala             return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
3094af245d11STodd Fiala                     __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
3095af245d11STodd Fiala         }
3096af245d11STodd Fiala     }
3097af245d11STodd Fiala 
30985830aa75STamas Berghammer     return Error();
3099af245d11STodd Fiala }
3100af245d11STodd Fiala 
3101af245d11STodd Fiala Error
3102af245d11STodd Fiala NativeProcessLinux::Halt ()
3103af245d11STodd Fiala {
3104af245d11STodd Fiala     Error error;
3105af245d11STodd Fiala 
3106af245d11STodd Fiala     if (kill (GetID (), SIGSTOP) != 0)
3107af245d11STodd Fiala         error.SetErrorToErrno ();
3108af245d11STodd Fiala 
3109af245d11STodd Fiala     return error;
3110af245d11STodd Fiala }
3111af245d11STodd Fiala 
3112af245d11STodd Fiala Error
3113af245d11STodd Fiala NativeProcessLinux::Detach ()
3114af245d11STodd Fiala {
3115af245d11STodd Fiala     Error error;
3116af245d11STodd Fiala 
3117af245d11STodd Fiala     // Tell ptrace to detach from the process.
3118af245d11STodd Fiala     if (GetID () != LLDB_INVALID_PROCESS_ID)
3119af245d11STodd Fiala         error = Detach (GetID ());
3120af245d11STodd Fiala 
3121af245d11STodd Fiala     // Stop monitoring the inferior.
312245f5cb31SPavel Labath     m_monitor_up->Terminate();
3123af245d11STodd Fiala 
3124af245d11STodd Fiala     // No error.
3125af245d11STodd Fiala     return error;
3126af245d11STodd Fiala }
3127af245d11STodd Fiala 
3128af245d11STodd Fiala Error
3129af245d11STodd Fiala NativeProcessLinux::Signal (int signo)
3130af245d11STodd Fiala {
3131af245d11STodd Fiala     Error error;
3132af245d11STodd Fiala 
3133af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3134af245d11STodd Fiala     if (log)
3135af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
3136af245d11STodd Fiala                 __FUNCTION__, signo,  GetUnixSignals ().GetSignalAsCString (signo), GetID ());
3137af245d11STodd Fiala 
3138af245d11STodd Fiala     if (kill(GetID(), signo))
3139af245d11STodd Fiala         error.SetErrorToErrno();
3140af245d11STodd Fiala 
3141af245d11STodd Fiala     return error;
3142af245d11STodd Fiala }
3143af245d11STodd Fiala 
3144af245d11STodd Fiala Error
3145e9547b80SChaoren Lin NativeProcessLinux::Interrupt ()
3146e9547b80SChaoren Lin {
3147e9547b80SChaoren Lin     // Pick a running thread (or if none, a not-dead stopped thread) as
3148e9547b80SChaoren Lin     // the chosen thread that will be the stop-reason thread.
3149e9547b80SChaoren Lin     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3150e9547b80SChaoren Lin 
3151e9547b80SChaoren Lin     NativeThreadProtocolSP running_thread_sp;
3152e9547b80SChaoren Lin     NativeThreadProtocolSP stopped_thread_sp;
3153e9547b80SChaoren Lin 
3154e9547b80SChaoren Lin     if (log)
3155e9547b80SChaoren Lin         log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
3156e9547b80SChaoren Lin 
315745f5cb31SPavel Labath     Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
31585830aa75STamas Berghammer     Mutex::Locker locker (m_threads_mutex);
31595830aa75STamas Berghammer 
3160e9547b80SChaoren Lin     for (auto thread_sp : m_threads)
3161e9547b80SChaoren Lin     {
3162e9547b80SChaoren Lin         // The thread shouldn't be null but lets just cover that here.
3163e9547b80SChaoren Lin         if (!thread_sp)
3164e9547b80SChaoren Lin             continue;
3165e9547b80SChaoren Lin 
3166e9547b80SChaoren Lin         // If we have a running or stepping thread, we'll call that the
3167e9547b80SChaoren Lin         // target of the interrupt.
3168e9547b80SChaoren Lin         const auto thread_state = thread_sp->GetState ();
3169e9547b80SChaoren Lin         if (thread_state == eStateRunning ||
3170e9547b80SChaoren Lin             thread_state == eStateStepping)
3171e9547b80SChaoren Lin         {
3172e9547b80SChaoren Lin             running_thread_sp = thread_sp;
3173e9547b80SChaoren Lin             break;
3174e9547b80SChaoren Lin         }
3175e9547b80SChaoren Lin         else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
3176e9547b80SChaoren Lin         {
3177e9547b80SChaoren Lin             // Remember the first non-dead stopped thread.  We'll use that as a backup if there are no running threads.
3178e9547b80SChaoren Lin             stopped_thread_sp = thread_sp;
3179e9547b80SChaoren Lin         }
3180e9547b80SChaoren Lin     }
3181e9547b80SChaoren Lin 
3182e9547b80SChaoren Lin     if (!running_thread_sp && !stopped_thread_sp)
3183e9547b80SChaoren Lin     {
31845830aa75STamas Berghammer         Error error("found no running/stepping or live stopped threads as target for interrupt");
3185e9547b80SChaoren Lin         if (log)
3186e9547b80SChaoren Lin             log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
31875830aa75STamas Berghammer 
3188e9547b80SChaoren Lin         return error;
3189e9547b80SChaoren Lin     }
3190e9547b80SChaoren Lin 
3191e9547b80SChaoren Lin     NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
3192e9547b80SChaoren Lin 
3193e9547b80SChaoren Lin     if (log)
3194e9547b80SChaoren Lin         log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
3195e9547b80SChaoren Lin                      __FUNCTION__,
3196e9547b80SChaoren Lin                      GetID (),
3197e9547b80SChaoren Lin                      running_thread_sp ? "running" : "stopped",
3198e9547b80SChaoren Lin                      deferred_signal_thread_sp->GetID ());
3199e9547b80SChaoren Lin 
3200ed89c7feSPavel Labath     StopRunningThreads(deferred_signal_thread_sp->GetID());
320145f5cb31SPavel Labath 
32025830aa75STamas Berghammer     return Error();
3203e9547b80SChaoren Lin }
3204e9547b80SChaoren Lin 
3205e9547b80SChaoren Lin Error
3206af245d11STodd Fiala NativeProcessLinux::Kill ()
3207af245d11STodd Fiala {
3208af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3209af245d11STodd Fiala     if (log)
3210af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
3211af245d11STodd Fiala 
3212af245d11STodd Fiala     Error error;
3213af245d11STodd Fiala 
3214af245d11STodd Fiala     switch (m_state)
3215af245d11STodd Fiala     {
3216af245d11STodd Fiala         case StateType::eStateInvalid:
3217af245d11STodd Fiala         case StateType::eStateExited:
3218af245d11STodd Fiala         case StateType::eStateCrashed:
3219af245d11STodd Fiala         case StateType::eStateDetached:
3220af245d11STodd Fiala         case StateType::eStateUnloaded:
3221af245d11STodd Fiala             // Nothing to do - the process is already dead.
3222af245d11STodd Fiala             if (log)
3223af245d11STodd Fiala                 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
3224af245d11STodd Fiala             return error;
3225af245d11STodd Fiala 
3226af245d11STodd Fiala         case StateType::eStateConnected:
3227af245d11STodd Fiala         case StateType::eStateAttaching:
3228af245d11STodd Fiala         case StateType::eStateLaunching:
3229af245d11STodd Fiala         case StateType::eStateStopped:
3230af245d11STodd Fiala         case StateType::eStateRunning:
3231af245d11STodd Fiala         case StateType::eStateStepping:
3232af245d11STodd Fiala         case StateType::eStateSuspended:
3233af245d11STodd Fiala             // We can try to kill a process in these states.
3234af245d11STodd Fiala             break;
3235af245d11STodd Fiala     }
3236af245d11STodd Fiala 
3237af245d11STodd Fiala     if (kill (GetID (), SIGKILL) != 0)
3238af245d11STodd Fiala     {
3239af245d11STodd Fiala         error.SetErrorToErrno ();
3240af245d11STodd Fiala         return error;
3241af245d11STodd Fiala     }
3242af245d11STodd Fiala 
3243af245d11STodd Fiala     return error;
3244af245d11STodd Fiala }
3245af245d11STodd Fiala 
3246af245d11STodd Fiala static Error
3247af245d11STodd Fiala ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
3248af245d11STodd Fiala {
3249af245d11STodd Fiala     memory_region_info.Clear();
3250af245d11STodd Fiala 
3251af245d11STodd Fiala     StringExtractor line_extractor (maps_line.c_str ());
3252af245d11STodd Fiala 
3253af245d11STodd Fiala     // Format: {address_start_hex}-{address_end_hex} perms offset  dev   inode   pathname
3254af245d11STodd Fiala     // perms: rwxp   (letter is present if set, '-' if not, final character is p=private, s=shared).
3255af245d11STodd Fiala 
3256af245d11STodd Fiala     // Parse out the starting address
3257af245d11STodd Fiala     lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
3258af245d11STodd Fiala 
3259af245d11STodd Fiala     // Parse out hyphen separating start and end address from range.
3260af245d11STodd Fiala     if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
3261af245d11STodd Fiala         return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
3262af245d11STodd Fiala 
3263af245d11STodd Fiala     // Parse out the ending address
3264af245d11STodd Fiala     lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
3265af245d11STodd Fiala 
3266af245d11STodd Fiala     // Parse out the space after the address.
3267af245d11STodd Fiala     if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
3268af245d11STodd Fiala         return Error ("malformed /proc/{pid}/maps entry, missing space after range");
3269af245d11STodd Fiala 
3270af245d11STodd Fiala     // Save the range.
3271af245d11STodd Fiala     memory_region_info.GetRange ().SetRangeBase (start_address);
3272af245d11STodd Fiala     memory_region_info.GetRange ().SetRangeEnd (end_address);
3273af245d11STodd Fiala 
3274af245d11STodd Fiala     // Parse out each permission entry.
3275af245d11STodd Fiala     if (line_extractor.GetBytesLeft () < 4)
3276af245d11STodd Fiala         return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
3277af245d11STodd Fiala 
3278af245d11STodd Fiala     // Handle read permission.
3279af245d11STodd Fiala     const char read_perm_char = line_extractor.GetChar ();
3280af245d11STodd Fiala     if (read_perm_char == 'r')
3281af245d11STodd Fiala         memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
3282af245d11STodd Fiala     else
3283af245d11STodd Fiala     {
3284af245d11STodd Fiala         assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
3285af245d11STodd Fiala         memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
3286af245d11STodd Fiala     }
3287af245d11STodd Fiala 
3288af245d11STodd Fiala     // Handle write permission.
3289af245d11STodd Fiala     const char write_perm_char = line_extractor.GetChar ();
3290af245d11STodd Fiala     if (write_perm_char == 'w')
3291af245d11STodd Fiala         memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
3292af245d11STodd Fiala     else
3293af245d11STodd Fiala     {
3294af245d11STodd Fiala         assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
3295af245d11STodd Fiala         memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
3296af245d11STodd Fiala     }
3297af245d11STodd Fiala 
3298af245d11STodd Fiala     // Handle execute permission.
3299af245d11STodd Fiala     const char exec_perm_char = line_extractor.GetChar ();
3300af245d11STodd Fiala     if (exec_perm_char == 'x')
3301af245d11STodd Fiala         memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
3302af245d11STodd Fiala     else
3303af245d11STodd Fiala     {
3304af245d11STodd Fiala         assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
3305af245d11STodd Fiala         memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
3306af245d11STodd Fiala     }
3307af245d11STodd Fiala 
3308af245d11STodd Fiala     return Error ();
3309af245d11STodd Fiala }
3310af245d11STodd Fiala 
3311af245d11STodd Fiala Error
3312af245d11STodd Fiala NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
3313af245d11STodd Fiala {
3314af245d11STodd Fiala     // FIXME review that the final memory region returned extends to the end of the virtual address space,
3315af245d11STodd Fiala     // with no perms if it is not mapped.
3316af245d11STodd Fiala 
3317af245d11STodd Fiala     // Use an approach that reads memory regions from /proc/{pid}/maps.
3318af245d11STodd Fiala     // Assume proc maps entries are in ascending order.
3319af245d11STodd Fiala     // FIXME assert if we find differently.
3320af245d11STodd Fiala     Mutex::Locker locker (m_mem_region_cache_mutex);
3321af245d11STodd Fiala 
3322af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3323af245d11STodd Fiala     Error error;
3324af245d11STodd Fiala 
3325af245d11STodd Fiala     if (m_supports_mem_region == LazyBool::eLazyBoolNo)
3326af245d11STodd Fiala     {
3327af245d11STodd Fiala         // We're done.
3328af245d11STodd Fiala         error.SetErrorString ("unsupported");
3329af245d11STodd Fiala         return error;
3330af245d11STodd Fiala     }
3331af245d11STodd Fiala 
3332af245d11STodd Fiala     // If our cache is empty, pull the latest.  There should always be at least one memory region
3333af245d11STodd Fiala     // if memory region handling is supported.
3334af245d11STodd Fiala     if (m_mem_region_cache.empty ())
3335af245d11STodd Fiala     {
3336af245d11STodd Fiala         error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
3337af245d11STodd Fiala              [&] (const std::string &line) -> bool
3338af245d11STodd Fiala              {
3339af245d11STodd Fiala                  MemoryRegionInfo info;
3340af245d11STodd Fiala                  const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
3341af245d11STodd Fiala                  if (parse_error.Success ())
3342af245d11STodd Fiala                  {
3343af245d11STodd Fiala                      m_mem_region_cache.push_back (info);
3344af245d11STodd Fiala                      return true;
3345af245d11STodd Fiala                  }
3346af245d11STodd Fiala                  else
3347af245d11STodd Fiala                  {
3348af245d11STodd Fiala                      if (log)
3349af245d11STodd Fiala                          log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
3350af245d11STodd Fiala                      return false;
3351af245d11STodd Fiala                  }
3352af245d11STodd Fiala              });
3353af245d11STodd Fiala 
3354af245d11STodd Fiala         // If we had an error, we'll mark unsupported.
3355af245d11STodd Fiala         if (error.Fail ())
3356af245d11STodd Fiala         {
3357af245d11STodd Fiala             m_supports_mem_region = LazyBool::eLazyBoolNo;
3358af245d11STodd Fiala             return error;
3359af245d11STodd Fiala         }
3360af245d11STodd Fiala         else if (m_mem_region_cache.empty ())
3361af245d11STodd Fiala         {
3362af245d11STodd Fiala             // No entries after attempting to read them.  This shouldn't happen if /proc/{pid}/maps
3363af245d11STodd Fiala             // is supported.  Assume we don't support map entries via procfs.
3364af245d11STodd Fiala             if (log)
3365af245d11STodd Fiala                 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
3366af245d11STodd Fiala             m_supports_mem_region = LazyBool::eLazyBoolNo;
3367af245d11STodd Fiala             error.SetErrorString ("not supported");
3368af245d11STodd Fiala             return error;
3369af245d11STodd Fiala         }
3370af245d11STodd Fiala 
3371af245d11STodd Fiala         if (log)
3372af245d11STodd 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 ());
3373af245d11STodd Fiala 
3374af245d11STodd Fiala         // We support memory retrieval, remember that.
3375af245d11STodd Fiala         m_supports_mem_region = LazyBool::eLazyBoolYes;
3376af245d11STodd Fiala     }
3377af245d11STodd Fiala     else
3378af245d11STodd Fiala     {
3379af245d11STodd Fiala         if (log)
3380af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
3381af245d11STodd Fiala     }
3382af245d11STodd Fiala 
3383af245d11STodd Fiala     lldb::addr_t prev_base_address = 0;
3384af245d11STodd Fiala 
3385af245d11STodd Fiala     // FIXME start by finding the last region that is <= target address using binary search.  Data is sorted.
3386af245d11STodd Fiala     // There can be a ton of regions on pthreads apps with lots of threads.
3387af245d11STodd Fiala     for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
3388af245d11STodd Fiala     {
3389af245d11STodd Fiala         MemoryRegionInfo &proc_entry_info = *it;
3390af245d11STodd Fiala 
3391af245d11STodd Fiala         // Sanity check assumption that /proc/{pid}/maps entries are ascending.
3392af245d11STodd Fiala         assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
3393af245d11STodd Fiala         prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
3394af245d11STodd Fiala 
3395af245d11STodd Fiala         // If the target address comes before this entry, indicate distance to next region.
3396af245d11STodd Fiala         if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
3397af245d11STodd Fiala         {
3398af245d11STodd Fiala             range_info.GetRange ().SetRangeBase (load_addr);
3399af245d11STodd Fiala             range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
3400af245d11STodd Fiala             range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
3401af245d11STodd Fiala             range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
3402af245d11STodd Fiala             range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
3403af245d11STodd Fiala 
3404af245d11STodd Fiala             return error;
3405af245d11STodd Fiala         }
3406af245d11STodd Fiala         else if (proc_entry_info.GetRange ().Contains (load_addr))
3407af245d11STodd Fiala         {
3408af245d11STodd Fiala             // The target address is within the memory region we're processing here.
3409af245d11STodd Fiala             range_info = proc_entry_info;
3410af245d11STodd Fiala             return error;
3411af245d11STodd Fiala         }
3412af245d11STodd Fiala 
3413af245d11STodd Fiala         // The target memory address comes somewhere after the region we just parsed.
3414af245d11STodd Fiala     }
3415af245d11STodd Fiala 
3416af245d11STodd Fiala     // If we made it here, we didn't find an entry that contained the given address.
3417af245d11STodd Fiala     error.SetErrorString ("address comes after final region");
3418af245d11STodd Fiala 
3419af245d11STodd Fiala     if (log)
3420af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s failed to find map entry for address 0x%" PRIx64 ": %s", __FUNCTION__, load_addr, error.AsCString ());
3421af245d11STodd Fiala 
3422af245d11STodd Fiala     return error;
3423af245d11STodd Fiala }
3424af245d11STodd Fiala 
3425af245d11STodd Fiala void
3426af245d11STodd Fiala NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
3427af245d11STodd Fiala {
3428af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3429af245d11STodd Fiala     if (log)
3430af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
3431af245d11STodd Fiala 
3432af245d11STodd Fiala     {
3433af245d11STodd Fiala         Mutex::Locker locker (m_mem_region_cache_mutex);
3434af245d11STodd Fiala         if (log)
3435af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
3436af245d11STodd Fiala         m_mem_region_cache.clear ();
3437af245d11STodd Fiala     }
3438af245d11STodd Fiala }
3439af245d11STodd Fiala 
3440af245d11STodd Fiala Error
34413eb4b458SChaoren Lin NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr)
3442af245d11STodd Fiala {
3443af245d11STodd Fiala     // FIXME implementing this requires the equivalent of
3444af245d11STodd Fiala     // InferiorCallPOSIX::InferiorCallMmap, which depends on
3445af245d11STodd Fiala     // functional ThreadPlans working with Native*Protocol.
3446af245d11STodd Fiala #if 1
3447af245d11STodd Fiala     return Error ("not implemented yet");
3448af245d11STodd Fiala #else
3449af245d11STodd Fiala     addr = LLDB_INVALID_ADDRESS;
3450af245d11STodd Fiala 
3451af245d11STodd Fiala     unsigned prot = 0;
3452af245d11STodd Fiala     if (permissions & lldb::ePermissionsReadable)
3453af245d11STodd Fiala         prot |= eMmapProtRead;
3454af245d11STodd Fiala     if (permissions & lldb::ePermissionsWritable)
3455af245d11STodd Fiala         prot |= eMmapProtWrite;
3456af245d11STodd Fiala     if (permissions & lldb::ePermissionsExecutable)
3457af245d11STodd Fiala         prot |= eMmapProtExec;
3458af245d11STodd Fiala 
3459af245d11STodd Fiala     // TODO implement this directly in NativeProcessLinux
3460af245d11STodd Fiala     // (and lift to NativeProcessPOSIX if/when that class is
3461af245d11STodd Fiala     // refactored out).
3462af245d11STodd Fiala     if (InferiorCallMmap(this, addr, 0, size, prot,
3463af245d11STodd Fiala                          eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
3464af245d11STodd Fiala         m_addr_to_mmap_size[addr] = size;
3465af245d11STodd Fiala         return Error ();
3466af245d11STodd Fiala     } else {
3467af245d11STodd Fiala         addr = LLDB_INVALID_ADDRESS;
3468af245d11STodd Fiala         return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
3469af245d11STodd Fiala     }
3470af245d11STodd Fiala #endif
3471af245d11STodd Fiala }
3472af245d11STodd Fiala 
3473af245d11STodd Fiala Error
3474af245d11STodd Fiala NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
3475af245d11STodd Fiala {
3476af245d11STodd Fiala     // FIXME see comments in AllocateMemory - required lower-level
3477af245d11STodd Fiala     // bits not in place yet (ThreadPlans)
3478af245d11STodd Fiala     return Error ("not implemented");
3479af245d11STodd Fiala }
3480af245d11STodd Fiala 
3481af245d11STodd Fiala lldb::addr_t
3482af245d11STodd Fiala NativeProcessLinux::GetSharedLibraryInfoAddress ()
3483af245d11STodd Fiala {
3484af245d11STodd Fiala #if 1
3485af245d11STodd Fiala     // punt on this for now
3486af245d11STodd Fiala     return LLDB_INVALID_ADDRESS;
3487af245d11STodd Fiala #else
3488af245d11STodd Fiala     // Return the image info address for the exe module
3489af245d11STodd Fiala #if 1
3490af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3491af245d11STodd Fiala 
3492af245d11STodd Fiala     ModuleSP module_sp;
3493af245d11STodd Fiala     Error error = GetExeModuleSP (module_sp);
3494af245d11STodd Fiala     if (error.Fail ())
3495af245d11STodd Fiala     {
3496af245d11STodd Fiala          if (log)
3497af245d11STodd Fiala             log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ());
3498af245d11STodd Fiala         return LLDB_INVALID_ADDRESS;
3499af245d11STodd Fiala     }
3500af245d11STodd Fiala 
3501af245d11STodd Fiala     if (module_sp == nullptr)
3502af245d11STodd Fiala     {
3503af245d11STodd Fiala          if (log)
3504af245d11STodd Fiala             log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__);
3505af245d11STodd Fiala          return LLDB_INVALID_ADDRESS;
3506af245d11STodd Fiala     }
3507af245d11STodd Fiala 
3508af245d11STodd Fiala     ObjectFileSP object_file_sp = module_sp->GetObjectFile ();
3509af245d11STodd Fiala     if (object_file_sp == nullptr)
3510af245d11STodd Fiala     {
3511af245d11STodd Fiala          if (log)
3512af245d11STodd Fiala             log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__);
3513af245d11STodd Fiala          return LLDB_INVALID_ADDRESS;
3514af245d11STodd Fiala     }
3515af245d11STodd Fiala 
3516af245d11STodd Fiala     return obj_file_sp->GetImageInfoAddress();
3517af245d11STodd Fiala #else
3518af245d11STodd Fiala     Target *target = &GetTarget();
3519af245d11STodd Fiala     ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
3520af245d11STodd Fiala     Address addr = obj_file->GetImageInfoAddress(target);
3521af245d11STodd Fiala 
3522af245d11STodd Fiala     if (addr.IsValid())
3523af245d11STodd Fiala         return addr.GetLoadAddress(target);
3524af245d11STodd Fiala     return LLDB_INVALID_ADDRESS;
3525af245d11STodd Fiala #endif
3526af245d11STodd Fiala #endif // punt on this for now
3527af245d11STodd Fiala }
3528af245d11STodd Fiala 
3529af245d11STodd Fiala size_t
3530af245d11STodd Fiala NativeProcessLinux::UpdateThreads ()
3531af245d11STodd Fiala {
3532af245d11STodd Fiala     // The NativeProcessLinux monitoring threads are always up to date
3533af245d11STodd Fiala     // with respect to thread state and they keep the thread list
3534af245d11STodd Fiala     // populated properly. All this method needs to do is return the
3535af245d11STodd Fiala     // thread count.
3536af245d11STodd Fiala     Mutex::Locker locker (m_threads_mutex);
3537af245d11STodd Fiala     return m_threads.size ();
3538af245d11STodd Fiala }
3539af245d11STodd Fiala 
3540af245d11STodd Fiala bool
3541af245d11STodd Fiala NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
3542af245d11STodd Fiala {
3543af245d11STodd Fiala     arch = m_arch;
3544af245d11STodd Fiala     return true;
3545af245d11STodd Fiala }
3546af245d11STodd Fiala 
3547af245d11STodd Fiala Error
354863c8be95STamas Berghammer NativeProcessLinux::GetSoftwareBreakpointPCOffset (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size)
3549af245d11STodd Fiala {
3550af245d11STodd Fiala     // FIXME put this behind a breakpoint protocol class that can be
3551af245d11STodd Fiala     // set per architecture.  Need ARM, MIPS support here.
35522afc5966STodd Fiala     static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
3553af245d11STodd Fiala     static const uint8_t g_i386_opcode [] = { 0xCC };
3554e8659b5dSMohit K. Bhakkad     static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
3555af245d11STodd Fiala 
3556af245d11STodd Fiala     switch (m_arch.GetMachine ())
3557af245d11STodd Fiala     {
35582afc5966STodd Fiala         case llvm::Triple::aarch64:
35592afc5966STodd Fiala             actual_opcode_size = static_cast<uint32_t> (sizeof(g_aarch64_opcode));
35602afc5966STodd Fiala             return Error ();
35612afc5966STodd Fiala 
356263c8be95STamas Berghammer         case llvm::Triple::arm:
356363c8be95STamas Berghammer             actual_opcode_size = 0; // On arm the PC don't get updated for breakpoint hits
356463c8be95STamas Berghammer             return Error ();
356563c8be95STamas Berghammer 
3566af245d11STodd Fiala         case llvm::Triple::x86:
3567af245d11STodd Fiala         case llvm::Triple::x86_64:
3568af245d11STodd Fiala             actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
3569af245d11STodd Fiala             return Error ();
3570af245d11STodd Fiala 
3571e8659b5dSMohit K. Bhakkad         case llvm::Triple::mips64:
3572e8659b5dSMohit K. Bhakkad         case llvm::Triple::mips64el:
3573e8659b5dSMohit K. Bhakkad             actual_opcode_size = static_cast<uint32_t> (sizeof(g_mips64_opcode));
3574e8659b5dSMohit K. Bhakkad             return Error ();
3575e8659b5dSMohit K. Bhakkad 
3576af245d11STodd Fiala         default:
3577af245d11STodd Fiala             assert(false && "CPU type not supported!");
3578af245d11STodd Fiala             return Error ("CPU type not supported");
3579af245d11STodd Fiala     }
3580af245d11STodd Fiala }
3581af245d11STodd Fiala 
3582af245d11STodd Fiala Error
3583af245d11STodd Fiala NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
3584af245d11STodd Fiala {
3585af245d11STodd Fiala     if (hardware)
3586af245d11STodd Fiala         return Error ("NativeProcessLinux does not support hardware breakpoints");
3587af245d11STodd Fiala     else
3588af245d11STodd Fiala         return SetSoftwareBreakpoint (addr, size);
3589af245d11STodd Fiala }
3590af245d11STodd Fiala 
3591af245d11STodd Fiala Error
359263c8be95STamas Berghammer NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint,
359363c8be95STamas Berghammer                                                      size_t &actual_opcode_size,
359463c8be95STamas Berghammer                                                      const uint8_t *&trap_opcode_bytes)
3595af245d11STodd Fiala {
359663c8be95STamas Berghammer     // FIXME put this behind a breakpoint protocol class that can be set per
359763c8be95STamas Berghammer     // architecture.  Need MIPS support here.
35982afc5966STodd Fiala     static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
359963c8be95STamas Berghammer     // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
360063c8be95STamas Berghammer     // linux kernel does otherwise.
360163c8be95STamas Berghammer     static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 };
3602af245d11STodd Fiala     static const uint8_t g_i386_opcode [] = { 0xCC };
36033df471c3SMohit K. Bhakkad     static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
36042c2acf96SMohit K. Bhakkad     static const uint8_t g_mips64el_opcode[] = { 0x0d, 0x00, 0x00, 0x00 };
360563c8be95STamas Berghammer     static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde };
3606af245d11STodd Fiala 
3607af245d11STodd Fiala     switch (m_arch.GetMachine ())
3608af245d11STodd Fiala     {
36092afc5966STodd Fiala     case llvm::Triple::aarch64:
36102afc5966STodd Fiala         trap_opcode_bytes = g_aarch64_opcode;
36112afc5966STodd Fiala         actual_opcode_size = sizeof(g_aarch64_opcode);
36122afc5966STodd Fiala         return Error ();
36132afc5966STodd Fiala 
361463c8be95STamas Berghammer     case llvm::Triple::arm:
361563c8be95STamas Berghammer         switch (trap_opcode_size_hint)
361663c8be95STamas Berghammer         {
361763c8be95STamas Berghammer         case 2:
361863c8be95STamas Berghammer             trap_opcode_bytes = g_thumb_breakpoint_opcode;
361963c8be95STamas Berghammer             actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
362063c8be95STamas Berghammer             return Error ();
362163c8be95STamas Berghammer         case 4:
362263c8be95STamas Berghammer             trap_opcode_bytes = g_arm_breakpoint_opcode;
362363c8be95STamas Berghammer             actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
362463c8be95STamas Berghammer             return Error ();
362563c8be95STamas Berghammer         default:
362663c8be95STamas Berghammer             assert(false && "Unrecognised trap opcode size hint!");
362763c8be95STamas Berghammer             return Error ("Unrecognised trap opcode size hint!");
362863c8be95STamas Berghammer         }
362963c8be95STamas Berghammer 
3630af245d11STodd Fiala     case llvm::Triple::x86:
3631af245d11STodd Fiala     case llvm::Triple::x86_64:
3632af245d11STodd Fiala         trap_opcode_bytes = g_i386_opcode;
3633af245d11STodd Fiala         actual_opcode_size = sizeof(g_i386_opcode);
3634af245d11STodd Fiala         return Error ();
3635af245d11STodd Fiala 
36363df471c3SMohit K. Bhakkad     case llvm::Triple::mips64:
36373df471c3SMohit K. Bhakkad         trap_opcode_bytes = g_mips64_opcode;
36383df471c3SMohit K. Bhakkad         actual_opcode_size = sizeof(g_mips64_opcode);
36393df471c3SMohit K. Bhakkad         return Error ();
36403df471c3SMohit K. Bhakkad 
36412c2acf96SMohit K. Bhakkad     case llvm::Triple::mips64el:
36422c2acf96SMohit K. Bhakkad         trap_opcode_bytes = g_mips64el_opcode;
36432c2acf96SMohit K. Bhakkad         actual_opcode_size = sizeof(g_mips64el_opcode);
36442c2acf96SMohit K. Bhakkad         return Error ();
36452c2acf96SMohit K. Bhakkad 
3646af245d11STodd Fiala     default:
3647af245d11STodd Fiala         assert(false && "CPU type not supported!");
3648af245d11STodd Fiala         return Error ("CPU type not supported");
3649af245d11STodd Fiala     }
3650af245d11STodd Fiala }
3651af245d11STodd Fiala 
3652af245d11STodd Fiala #if 0
3653af245d11STodd Fiala ProcessMessage::CrashReason
3654af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
3655af245d11STodd Fiala {
3656af245d11STodd Fiala     ProcessMessage::CrashReason reason;
3657af245d11STodd Fiala     assert(info->si_signo == SIGSEGV);
3658af245d11STodd Fiala 
3659af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
3660af245d11STodd Fiala 
3661af245d11STodd Fiala     switch (info->si_code)
3662af245d11STodd Fiala     {
3663af245d11STodd Fiala     default:
3664af245d11STodd Fiala         assert(false && "unexpected si_code for SIGSEGV");
3665af245d11STodd Fiala         break;
3666af245d11STodd Fiala     case SI_KERNEL:
3667af245d11STodd Fiala         // Linux will occasionally send spurious SI_KERNEL codes.
3668af245d11STodd Fiala         // (this is poorly documented in sigaction)
3669af245d11STodd Fiala         // One way to get this is via unaligned SIMD loads.
3670af245d11STodd Fiala         reason = ProcessMessage::eInvalidAddress; // for lack of anything better
3671af245d11STodd Fiala         break;
3672af245d11STodd Fiala     case SEGV_MAPERR:
3673af245d11STodd Fiala         reason = ProcessMessage::eInvalidAddress;
3674af245d11STodd Fiala         break;
3675af245d11STodd Fiala     case SEGV_ACCERR:
3676af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedAddress;
3677af245d11STodd Fiala         break;
3678af245d11STodd Fiala     }
3679af245d11STodd Fiala 
3680af245d11STodd Fiala     return reason;
3681af245d11STodd Fiala }
3682af245d11STodd Fiala #endif
3683af245d11STodd Fiala 
3684af245d11STodd Fiala 
3685af245d11STodd Fiala #if 0
3686af245d11STodd Fiala ProcessMessage::CrashReason
3687af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
3688af245d11STodd Fiala {
3689af245d11STodd Fiala     ProcessMessage::CrashReason reason;
3690af245d11STodd Fiala     assert(info->si_signo == SIGILL);
3691af245d11STodd Fiala 
3692af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
3693af245d11STodd Fiala 
3694af245d11STodd Fiala     switch (info->si_code)
3695af245d11STodd Fiala     {
3696af245d11STodd Fiala     default:
3697af245d11STodd Fiala         assert(false && "unexpected si_code for SIGILL");
3698af245d11STodd Fiala         break;
3699af245d11STodd Fiala     case ILL_ILLOPC:
3700af245d11STodd Fiala         reason = ProcessMessage::eIllegalOpcode;
3701af245d11STodd Fiala         break;
3702af245d11STodd Fiala     case ILL_ILLOPN:
3703af245d11STodd Fiala         reason = ProcessMessage::eIllegalOperand;
3704af245d11STodd Fiala         break;
3705af245d11STodd Fiala     case ILL_ILLADR:
3706af245d11STodd Fiala         reason = ProcessMessage::eIllegalAddressingMode;
3707af245d11STodd Fiala         break;
3708af245d11STodd Fiala     case ILL_ILLTRP:
3709af245d11STodd Fiala         reason = ProcessMessage::eIllegalTrap;
3710af245d11STodd Fiala         break;
3711af245d11STodd Fiala     case ILL_PRVOPC:
3712af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedOpcode;
3713af245d11STodd Fiala         break;
3714af245d11STodd Fiala     case ILL_PRVREG:
3715af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedRegister;
3716af245d11STodd Fiala         break;
3717af245d11STodd Fiala     case ILL_COPROC:
3718af245d11STodd Fiala         reason = ProcessMessage::eCoprocessorError;
3719af245d11STodd Fiala         break;
3720af245d11STodd Fiala     case ILL_BADSTK:
3721af245d11STodd Fiala         reason = ProcessMessage::eInternalStackError;
3722af245d11STodd Fiala         break;
3723af245d11STodd Fiala     }
3724af245d11STodd Fiala 
3725af245d11STodd Fiala     return reason;
3726af245d11STodd Fiala }
3727af245d11STodd Fiala #endif
3728af245d11STodd Fiala 
3729af245d11STodd Fiala #if 0
3730af245d11STodd Fiala ProcessMessage::CrashReason
3731af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
3732af245d11STodd Fiala {
3733af245d11STodd Fiala     ProcessMessage::CrashReason reason;
3734af245d11STodd Fiala     assert(info->si_signo == SIGFPE);
3735af245d11STodd Fiala 
3736af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
3737af245d11STodd Fiala 
3738af245d11STodd Fiala     switch (info->si_code)
3739af245d11STodd Fiala     {
3740af245d11STodd Fiala     default:
3741af245d11STodd Fiala         assert(false && "unexpected si_code for SIGFPE");
3742af245d11STodd Fiala         break;
3743af245d11STodd Fiala     case FPE_INTDIV:
3744af245d11STodd Fiala         reason = ProcessMessage::eIntegerDivideByZero;
3745af245d11STodd Fiala         break;
3746af245d11STodd Fiala     case FPE_INTOVF:
3747af245d11STodd Fiala         reason = ProcessMessage::eIntegerOverflow;
3748af245d11STodd Fiala         break;
3749af245d11STodd Fiala     case FPE_FLTDIV:
3750af245d11STodd Fiala         reason = ProcessMessage::eFloatDivideByZero;
3751af245d11STodd Fiala         break;
3752af245d11STodd Fiala     case FPE_FLTOVF:
3753af245d11STodd Fiala         reason = ProcessMessage::eFloatOverflow;
3754af245d11STodd Fiala         break;
3755af245d11STodd Fiala     case FPE_FLTUND:
3756af245d11STodd Fiala         reason = ProcessMessage::eFloatUnderflow;
3757af245d11STodd Fiala         break;
3758af245d11STodd Fiala     case FPE_FLTRES:
3759af245d11STodd Fiala         reason = ProcessMessage::eFloatInexactResult;
3760af245d11STodd Fiala         break;
3761af245d11STodd Fiala     case FPE_FLTINV:
3762af245d11STodd Fiala         reason = ProcessMessage::eFloatInvalidOperation;
3763af245d11STodd Fiala         break;
3764af245d11STodd Fiala     case FPE_FLTSUB:
3765af245d11STodd Fiala         reason = ProcessMessage::eFloatSubscriptRange;
3766af245d11STodd Fiala         break;
3767af245d11STodd Fiala     }
3768af245d11STodd Fiala 
3769af245d11STodd Fiala     return reason;
3770af245d11STodd Fiala }
3771af245d11STodd Fiala #endif
3772af245d11STodd Fiala 
3773af245d11STodd Fiala #if 0
3774af245d11STodd Fiala ProcessMessage::CrashReason
3775af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
3776af245d11STodd Fiala {
3777af245d11STodd Fiala     ProcessMessage::CrashReason reason;
3778af245d11STodd Fiala     assert(info->si_signo == SIGBUS);
3779af245d11STodd Fiala 
3780af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
3781af245d11STodd Fiala 
3782af245d11STodd Fiala     switch (info->si_code)
3783af245d11STodd Fiala     {
3784af245d11STodd Fiala     default:
3785af245d11STodd Fiala         assert(false && "unexpected si_code for SIGBUS");
3786af245d11STodd Fiala         break;
3787af245d11STodd Fiala     case BUS_ADRALN:
3788af245d11STodd Fiala         reason = ProcessMessage::eIllegalAlignment;
3789af245d11STodd Fiala         break;
3790af245d11STodd Fiala     case BUS_ADRERR:
3791af245d11STodd Fiala         reason = ProcessMessage::eIllegalAddress;
3792af245d11STodd Fiala         break;
3793af245d11STodd Fiala     case BUS_OBJERR:
3794af245d11STodd Fiala         reason = ProcessMessage::eHardwareError;
3795af245d11STodd Fiala         break;
3796af245d11STodd Fiala     }
3797af245d11STodd Fiala 
3798af245d11STodd Fiala     return reason;
3799af245d11STodd Fiala }
3800af245d11STodd Fiala #endif
3801af245d11STodd Fiala 
3802af245d11STodd Fiala Error
380345f5cb31SPavel Labath NativeProcessLinux::SetWatchpoint (lldb::addr_t addr, size_t size, uint32_t watch_flags, bool hardware)
380445f5cb31SPavel Labath {
380545f5cb31SPavel Labath     // The base SetWatchpoint will end up executing monitor operations. Let's lock the monitor
380645f5cb31SPavel Labath     // for it.
380745f5cb31SPavel Labath     Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
380845f5cb31SPavel Labath     return NativeProcessProtocol::SetWatchpoint(addr, size, watch_flags, hardware);
380945f5cb31SPavel Labath }
381045f5cb31SPavel Labath 
381145f5cb31SPavel Labath Error
381245f5cb31SPavel Labath NativeProcessLinux::RemoveWatchpoint (lldb::addr_t addr)
381345f5cb31SPavel Labath {
381445f5cb31SPavel Labath     // The base RemoveWatchpoint will end up executing monitor operations. Let's lock the monitor
381545f5cb31SPavel Labath     // for it.
381645f5cb31SPavel Labath     Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
381745f5cb31SPavel Labath     return NativeProcessProtocol::RemoveWatchpoint(addr);
381845f5cb31SPavel Labath }
381945f5cb31SPavel Labath 
382045f5cb31SPavel Labath Error
382126438d26SChaoren Lin NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
3822af245d11STodd Fiala {
3823af245d11STodd Fiala     ReadOperation op(addr, buf, size, bytes_read);
3824bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
3825af245d11STodd Fiala     return op.GetError ();
3826af245d11STodd Fiala }
3827af245d11STodd Fiala 
3828af245d11STodd Fiala Error
38293eb4b458SChaoren Lin NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
38303eb4b458SChaoren Lin {
38313eb4b458SChaoren Lin     Error error = ReadMemory(addr, buf, size, bytes_read);
38323eb4b458SChaoren Lin     if (error.Fail()) return error;
38333eb4b458SChaoren Lin     return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
38343eb4b458SChaoren Lin }
38353eb4b458SChaoren Lin 
38363eb4b458SChaoren Lin Error
38373eb4b458SChaoren Lin NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written)
3838af245d11STodd Fiala {
3839af245d11STodd Fiala     WriteOperation op(addr, buf, size, bytes_written);
3840bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
3841af245d11STodd Fiala     return op.GetError ();
3842af245d11STodd Fiala }
3843af245d11STodd Fiala 
384497ccc294SChaoren Lin Error
3845af245d11STodd Fiala NativeProcessLinux::ReadRegisterValue(lldb::tid_t tid, uint32_t offset, const char* reg_name,
3846af245d11STodd Fiala                                       uint32_t size, RegisterValue &value)
3847af245d11STodd Fiala {
384897ccc294SChaoren Lin     ReadRegOperation op(tid, offset, reg_name, value);
3849bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
385097ccc294SChaoren Lin     return op.GetError();
3851af245d11STodd Fiala }
3852af245d11STodd Fiala 
385397ccc294SChaoren Lin Error
3854af245d11STodd Fiala NativeProcessLinux::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
3855af245d11STodd Fiala                                    const char* reg_name, const RegisterValue &value)
3856af245d11STodd Fiala {
385797ccc294SChaoren Lin     WriteRegOperation op(tid, offset, reg_name, value);
3858bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
385997ccc294SChaoren Lin     return op.GetError();
3860af245d11STodd Fiala }
3861af245d11STodd Fiala 
386297ccc294SChaoren Lin Error
3863af245d11STodd Fiala NativeProcessLinux::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3864af245d11STodd Fiala {
386597ccc294SChaoren Lin     ReadGPROperation op(tid, buf, buf_size);
3866bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
386797ccc294SChaoren Lin     return op.GetError();
3868af245d11STodd Fiala }
3869af245d11STodd Fiala 
387097ccc294SChaoren Lin Error
3871af245d11STodd Fiala NativeProcessLinux::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3872af245d11STodd Fiala {
387397ccc294SChaoren Lin     ReadFPROperation op(tid, buf, buf_size);
3874bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
387597ccc294SChaoren Lin     return op.GetError();
3876af245d11STodd Fiala }
3877af245d11STodd Fiala 
387897ccc294SChaoren Lin Error
3879af245d11STodd Fiala NativeProcessLinux::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3880af245d11STodd Fiala {
388197ccc294SChaoren Lin     ReadRegisterSetOperation op(tid, buf, buf_size, regset);
3882bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
388397ccc294SChaoren Lin     return op.GetError();
3884af245d11STodd Fiala }
3885af245d11STodd Fiala 
3886ea8c25a8SOmair Javaid Error
3887ea8c25a8SOmair Javaid NativeProcessLinux::ReadHardwareDebugInfo (lldb::tid_t tid, unsigned int &watch_count , unsigned int &break_count)
3888ea8c25a8SOmair Javaid {
3889ea8c25a8SOmair Javaid     ReadDBGROperation op(tid, watch_count, break_count);
3890ea8c25a8SOmair Javaid     m_monitor_up->DoOperation(&op);
3891ea8c25a8SOmair Javaid     return op.GetError();
3892ea8c25a8SOmair Javaid }
3893ea8c25a8SOmair Javaid 
3894ea8c25a8SOmair Javaid Error
3895ea8c25a8SOmair Javaid NativeProcessLinux::WriteHardwareDebugRegs (lldb::tid_t tid, lldb::addr_t *addr_buf, uint32_t *cntrl_buf, int type, int count)
3896ea8c25a8SOmair Javaid {
3897ea8c25a8SOmair Javaid     WriteDBGROperation op(tid, addr_buf, cntrl_buf, type, count);
3898ea8c25a8SOmair Javaid     m_monitor_up->DoOperation(&op);
3899ea8c25a8SOmair Javaid     return op.GetError();
3900ea8c25a8SOmair Javaid }
3901ea8c25a8SOmair Javaid 
390297ccc294SChaoren Lin Error
3903af245d11STodd Fiala NativeProcessLinux::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3904af245d11STodd Fiala {
390597ccc294SChaoren Lin     WriteGPROperation op(tid, buf, buf_size);
3906bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
390797ccc294SChaoren Lin     return op.GetError();
3908af245d11STodd Fiala }
3909af245d11STodd Fiala 
391097ccc294SChaoren Lin Error
3911af245d11STodd Fiala NativeProcessLinux::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3912af245d11STodd Fiala {
391397ccc294SChaoren Lin     WriteFPROperation op(tid, buf, buf_size);
3914bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
391597ccc294SChaoren Lin     return op.GetError();
3916af245d11STodd Fiala }
3917af245d11STodd Fiala 
391897ccc294SChaoren Lin Error
3919af245d11STodd Fiala NativeProcessLinux::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3920af245d11STodd Fiala {
392197ccc294SChaoren Lin     WriteRegisterSetOperation op(tid, buf, buf_size, regset);
3922bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
392397ccc294SChaoren Lin     return op.GetError();
3924af245d11STodd Fiala }
3925af245d11STodd Fiala 
392697ccc294SChaoren Lin Error
3927af245d11STodd Fiala NativeProcessLinux::Resume (lldb::tid_t tid, uint32_t signo)
3928af245d11STodd Fiala {
3929af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3930af245d11STodd Fiala 
3931af245d11STodd Fiala     if (log)
3932af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s() resuming thread = %"  PRIu64 " with signal %s", __FUNCTION__, tid,
3933af245d11STodd Fiala                                  GetUnixSignals().GetSignalAsCString (signo));
393497ccc294SChaoren Lin     ResumeOperation op (tid, signo);
3935bd7cbc5aSPavel Labath     m_monitor_up->DoOperation (&op);
3936af245d11STodd Fiala     if (log)
393797ccc294SChaoren Lin         log->Printf ("NativeProcessLinux::%s() resuming thread = %"  PRIu64 " result = %s", __FUNCTION__, tid, op.GetError().Success() ? "true" : "false");
393897ccc294SChaoren Lin     return op.GetError();
3939af245d11STodd Fiala }
3940af245d11STodd Fiala 
394197ccc294SChaoren Lin Error
3942af245d11STodd Fiala NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo)
3943af245d11STodd Fiala {
394497ccc294SChaoren Lin     SingleStepOperation op(tid, signo);
3945bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
394697ccc294SChaoren Lin     return op.GetError();
3947af245d11STodd Fiala }
3948af245d11STodd Fiala 
394997ccc294SChaoren Lin Error
395097ccc294SChaoren Lin NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
3951af245d11STodd Fiala {
395297ccc294SChaoren Lin     SiginfoOperation op(tid, siginfo);
3953bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
395497ccc294SChaoren Lin     return op.GetError();
3955af245d11STodd Fiala }
3956af245d11STodd Fiala 
395797ccc294SChaoren Lin Error
3958af245d11STodd Fiala NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
3959af245d11STodd Fiala {
396097ccc294SChaoren Lin     EventMessageOperation op(tid, message);
3961bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
396297ccc294SChaoren Lin     return op.GetError();
3963af245d11STodd Fiala }
3964af245d11STodd Fiala 
3965db264a6dSTamas Berghammer Error
3966af245d11STodd Fiala NativeProcessLinux::Detach(lldb::tid_t tid)
3967af245d11STodd Fiala {
396897ccc294SChaoren Lin     if (tid == LLDB_INVALID_THREAD_ID)
396997ccc294SChaoren Lin         return Error();
397097ccc294SChaoren Lin 
397197ccc294SChaoren Lin     DetachOperation op(tid);
3972bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
397397ccc294SChaoren Lin     return op.GetError();
3974af245d11STodd Fiala }
3975af245d11STodd Fiala 
3976af245d11STodd Fiala bool
3977af245d11STodd Fiala NativeProcessLinux::DupDescriptor(const char *path, int fd, int flags)
3978af245d11STodd Fiala {
3979af245d11STodd Fiala     int target_fd = open(path, flags, 0666);
3980af245d11STodd Fiala 
3981af245d11STodd Fiala     if (target_fd == -1)
3982af245d11STodd Fiala         return false;
3983af245d11STodd Fiala 
3984493c3a12SPavel Labath     if (dup2(target_fd, fd) == -1)
3985493c3a12SPavel Labath         return false;
3986493c3a12SPavel Labath 
3987493c3a12SPavel Labath     return (close(target_fd) == -1) ? false : true;
3988af245d11STodd Fiala }
3989af245d11STodd Fiala 
3990af245d11STodd Fiala void
3991bd7cbc5aSPavel Labath NativeProcessLinux::StartMonitorThread(const InitialOperation &initial_operation, Error &error)
3992af245d11STodd Fiala {
3993bd7cbc5aSPavel Labath     m_monitor_up.reset(new Monitor(initial_operation, this));
39941107b5a5SPavel Labath     error = m_monitor_up->Initialize();
39951107b5a5SPavel Labath     if (error.Fail()) {
39961107b5a5SPavel Labath         m_monitor_up.reset();
3997af245d11STodd Fiala     }
3998af245d11STodd Fiala }
3999af245d11STodd Fiala 
4000af245d11STodd Fiala bool
4001af245d11STodd Fiala NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
4002af245d11STodd Fiala {
4003af245d11STodd Fiala     for (auto thread_sp : m_threads)
4004af245d11STodd Fiala     {
4005af245d11STodd Fiala         assert (thread_sp && "thread list should not contain NULL threads");
4006af245d11STodd Fiala         if (thread_sp->GetID () == thread_id)
4007af245d11STodd Fiala         {
4008af245d11STodd Fiala             // We have this thread.
4009af245d11STodd Fiala             return true;
4010af245d11STodd Fiala         }
4011af245d11STodd Fiala     }
4012af245d11STodd Fiala 
4013af245d11STodd Fiala     // We don't have this thread.
4014af245d11STodd Fiala     return false;
4015af245d11STodd Fiala }
4016af245d11STodd Fiala 
4017af245d11STodd Fiala NativeThreadProtocolSP
4018af245d11STodd Fiala NativeProcessLinux::MaybeGetThreadNoLock (lldb::tid_t thread_id)
4019af245d11STodd Fiala {
4020af245d11STodd Fiala     // CONSIDER organize threads by map - we can do better than linear.
4021af245d11STodd Fiala     for (auto thread_sp : m_threads)
4022af245d11STodd Fiala     {
4023af245d11STodd Fiala         if (thread_sp->GetID () == thread_id)
4024af245d11STodd Fiala             return thread_sp;
4025af245d11STodd Fiala     }
4026af245d11STodd Fiala 
4027af245d11STodd Fiala     // We don't have this thread.
4028af245d11STodd Fiala     return NativeThreadProtocolSP ();
4029af245d11STodd Fiala }
4030af245d11STodd Fiala 
4031af245d11STodd Fiala bool
4032af245d11STodd Fiala NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
4033af245d11STodd Fiala {
40341dbc6c9cSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
40351dbc6c9cSPavel Labath 
40361dbc6c9cSPavel Labath     if (log)
40371dbc6c9cSPavel Labath         log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, thread_id);
40381dbc6c9cSPavel Labath 
40391dbc6c9cSPavel Labath     bool found = false;
40401dbc6c9cSPavel Labath 
4041af245d11STodd Fiala     Mutex::Locker locker (m_threads_mutex);
4042af245d11STodd Fiala     for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
4043af245d11STodd Fiala     {
4044af245d11STodd Fiala         if (*it && ((*it)->GetID () == thread_id))
4045af245d11STodd Fiala         {
4046af245d11STodd Fiala             m_threads.erase (it);
40471dbc6c9cSPavel Labath             found = true;
40481dbc6c9cSPavel Labath             break;
4049af245d11STodd Fiala         }
4050af245d11STodd Fiala     }
4051af245d11STodd Fiala 
40521dbc6c9cSPavel Labath     // If we have a pending notification, remove this from the set.
40531dbc6c9cSPavel Labath     if (m_pending_notification_up)
40541dbc6c9cSPavel Labath     {
40551dbc6c9cSPavel Labath         m_pending_notification_up->wait_for_stop_tids.erase(thread_id);
40569eb1ecb9SPavel Labath         SignalIfAllThreadsStopped();
40571dbc6c9cSPavel Labath     }
40581dbc6c9cSPavel Labath 
40591dbc6c9cSPavel Labath     return found;
4060af245d11STodd Fiala }
4061af245d11STodd Fiala 
4062af245d11STodd Fiala NativeThreadProtocolSP
4063af245d11STodd Fiala NativeProcessLinux::AddThread (lldb::tid_t thread_id)
4064af245d11STodd Fiala {
4065af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
4066af245d11STodd Fiala 
4067af245d11STodd Fiala     Mutex::Locker locker (m_threads_mutex);
4068af245d11STodd Fiala 
4069af245d11STodd Fiala     if (log)
4070af245d11STodd Fiala     {
4071af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
4072af245d11STodd Fiala                 __FUNCTION__,
4073af245d11STodd Fiala                 GetID (),
4074af245d11STodd Fiala                 thread_id);
4075af245d11STodd Fiala     }
4076af245d11STodd Fiala 
4077af245d11STodd Fiala     assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
4078af245d11STodd Fiala 
4079af245d11STodd Fiala     // If this is the first thread, save it as the current thread
4080af245d11STodd Fiala     if (m_threads.empty ())
4081af245d11STodd Fiala         SetCurrentThreadID (thread_id);
4082af245d11STodd Fiala 
4083af245d11STodd Fiala     NativeThreadProtocolSP thread_sp (new NativeThreadLinux (this, thread_id));
4084af245d11STodd Fiala     m_threads.push_back (thread_sp);
4085af245d11STodd Fiala 
4086af245d11STodd Fiala     return thread_sp;
4087af245d11STodd Fiala }
4088af245d11STodd Fiala 
4089af245d11STodd Fiala Error
4090af245d11STodd Fiala NativeProcessLinux::FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp)
4091af245d11STodd Fiala {
409275f47c3aSTodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
4093af245d11STodd Fiala 
4094af245d11STodd Fiala     Error error;
4095af245d11STodd Fiala 
4096af245d11STodd Fiala     // Get a linux thread pointer.
4097af245d11STodd Fiala     if (!thread_sp)
4098af245d11STodd Fiala     {
4099af245d11STodd Fiala         error.SetErrorString ("null thread_sp");
4100af245d11STodd Fiala         if (log)
4101af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
4102af245d11STodd Fiala         return error;
4103af245d11STodd Fiala     }
4104cb84eebbSTamas Berghammer     std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
4105af245d11STodd Fiala 
4106af245d11STodd Fiala     // Find out the size of a breakpoint (might depend on where we are in the code).
4107cb84eebbSTamas Berghammer     NativeRegisterContextSP context_sp = linux_thread_sp->GetRegisterContext ();
4108af245d11STodd Fiala     if (!context_sp)
4109af245d11STodd Fiala     {
4110af245d11STodd Fiala         error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
4111af245d11STodd Fiala         if (log)
4112af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
4113af245d11STodd Fiala         return error;
4114af245d11STodd Fiala     }
4115af245d11STodd Fiala 
4116af245d11STodd Fiala     uint32_t breakpoint_size = 0;
411763c8be95STamas Berghammer     error = GetSoftwareBreakpointPCOffset (context_sp, breakpoint_size);
4118af245d11STodd Fiala     if (error.Fail ())
4119af245d11STodd Fiala     {
4120af245d11STodd Fiala         if (log)
4121af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
4122af245d11STodd Fiala         return error;
4123af245d11STodd Fiala     }
4124af245d11STodd Fiala     else
4125af245d11STodd Fiala     {
4126af245d11STodd Fiala         if (log)
4127af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
4128af245d11STodd Fiala     }
4129af245d11STodd Fiala 
4130af245d11STodd Fiala     // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
4131af245d11STodd Fiala     const lldb::addr_t initial_pc_addr = context_sp->GetPC ();
4132af245d11STodd Fiala     lldb::addr_t breakpoint_addr = initial_pc_addr;
41333eb4b458SChaoren Lin     if (breakpoint_size > 0)
4134af245d11STodd Fiala     {
4135af245d11STodd Fiala         // Do not allow breakpoint probe to wrap around.
41363eb4b458SChaoren Lin         if (breakpoint_addr >= breakpoint_size)
41373eb4b458SChaoren Lin             breakpoint_addr -= breakpoint_size;
4138af245d11STodd Fiala     }
4139af245d11STodd Fiala 
4140af245d11STodd Fiala     // Check if we stopped because of a breakpoint.
4141af245d11STodd Fiala     NativeBreakpointSP breakpoint_sp;
4142af245d11STodd Fiala     error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
4143af245d11STodd Fiala     if (!error.Success () || !breakpoint_sp)
4144af245d11STodd Fiala     {
4145af245d11STodd Fiala         // We didn't find one at a software probe location.  Nothing to do.
4146af245d11STodd Fiala         if (log)
4147af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
4148af245d11STodd Fiala         return Error ();
4149af245d11STodd Fiala     }
4150af245d11STodd Fiala 
4151af245d11STodd Fiala     // If the breakpoint is not a software breakpoint, nothing to do.
4152af245d11STodd Fiala     if (!breakpoint_sp->IsSoftwareBreakpoint ())
4153af245d11STodd Fiala     {
4154af245d11STodd Fiala         if (log)
4155af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
4156af245d11STodd Fiala         return Error ();
4157af245d11STodd Fiala     }
4158af245d11STodd Fiala 
4159af245d11STodd Fiala     //
4160af245d11STodd Fiala     // We have a software breakpoint and need to adjust the PC.
4161af245d11STodd Fiala     //
4162af245d11STodd Fiala 
4163af245d11STodd Fiala     // Sanity check.
4164af245d11STodd Fiala     if (breakpoint_size == 0)
4165af245d11STodd Fiala     {
4166af245d11STodd Fiala         // Nothing to do!  How did we get here?
4167af245d11STodd Fiala         if (log)
4168af245d11STodd 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);
4169af245d11STodd Fiala         return Error ();
4170af245d11STodd Fiala     }
4171af245d11STodd Fiala 
4172af245d11STodd Fiala     // Change the program counter.
4173af245d11STodd Fiala     if (log)
4174cb84eebbSTamas 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);
4175af245d11STodd Fiala 
4176af245d11STodd Fiala     error = context_sp->SetPC (breakpoint_addr);
4177af245d11STodd Fiala     if (error.Fail ())
4178af245d11STodd Fiala     {
4179af245d11STodd Fiala         if (log)
4180cb84eebbSTamas Berghammer             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": failed to set PC: %s", __FUNCTION__, GetID (), linux_thread_sp->GetID (), error.AsCString ());
4181af245d11STodd Fiala         return error;
4182af245d11STodd Fiala     }
4183af245d11STodd Fiala 
4184af245d11STodd Fiala     return error;
4185af245d11STodd Fiala }
4186fa03ad2eSChaoren Lin 
41877cb18bf5STamas Berghammer Error
41887cb18bf5STamas Berghammer NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec)
41897cb18bf5STamas Berghammer {
41907cb18bf5STamas Berghammer     char maps_file_name[32];
41917cb18bf5STamas Berghammer     snprintf(maps_file_name, sizeof(maps_file_name), "/proc/%" PRIu64 "/maps", GetID());
41927cb18bf5STamas Berghammer 
41937cb18bf5STamas Berghammer     FileSpec maps_file_spec(maps_file_name, false);
41947cb18bf5STamas Berghammer     if (!maps_file_spec.Exists()) {
41957cb18bf5STamas Berghammer         file_spec.Clear();
41967cb18bf5STamas Berghammer         return Error("/proc/%" PRIu64 "/maps file doesn't exists!", GetID());
41977cb18bf5STamas Berghammer     }
41987cb18bf5STamas Berghammer 
41997cb18bf5STamas Berghammer     FileSpec module_file_spec(module_path, true);
42007cb18bf5STamas Berghammer 
42017cb18bf5STamas Berghammer     std::ifstream maps_file(maps_file_name);
42027cb18bf5STamas Berghammer     std::string maps_data_str((std::istreambuf_iterator<char>(maps_file)), std::istreambuf_iterator<char>());
42037cb18bf5STamas Berghammer     StringRef maps_data(maps_data_str.c_str());
42047cb18bf5STamas Berghammer 
42057cb18bf5STamas Berghammer     while (!maps_data.empty())
42067cb18bf5STamas Berghammer     {
42077cb18bf5STamas Berghammer         StringRef maps_row;
42087cb18bf5STamas Berghammer         std::tie(maps_row, maps_data) = maps_data.split('\n');
42097cb18bf5STamas Berghammer 
42107cb18bf5STamas Berghammer         SmallVector<StringRef, 16> maps_columns;
42117cb18bf5STamas Berghammer         maps_row.split(maps_columns, StringRef(" "), -1, false);
42127cb18bf5STamas Berghammer 
42137cb18bf5STamas Berghammer         if (maps_columns.size() >= 6)
42147cb18bf5STamas Berghammer         {
42157cb18bf5STamas Berghammer             file_spec.SetFile(maps_columns[5].str().c_str(), false);
42167cb18bf5STamas Berghammer             if (file_spec.GetFilename() == module_file_spec.GetFilename())
42177cb18bf5STamas Berghammer                 return Error();
42187cb18bf5STamas Berghammer         }
42197cb18bf5STamas Berghammer     }
42207cb18bf5STamas Berghammer 
42217cb18bf5STamas Berghammer     file_spec.Clear();
42227cb18bf5STamas Berghammer     return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
42237cb18bf5STamas Berghammer                  module_file_spec.GetFilename().AsCString(), GetID());
42247cb18bf5STamas Berghammer }
4225c076559aSPavel Labath 
42265eb721edSPavel Labath Error
42271dbc6c9cSPavel Labath NativeProcessLinux::ResumeThread(
4228c076559aSPavel Labath         lldb::tid_t tid,
42298c8ff7afSPavel Labath         NativeThreadLinux::ResumeThreadFunction request_thread_resume_function,
4230c076559aSPavel Labath         bool error_when_already_running)
4231c076559aSPavel Labath {
42325eb721edSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
42335eb721edSPavel Labath 
42341dbc6c9cSPavel Labath     if (log)
42351dbc6c9cSPavel Labath         log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ", error_when_already_running: %s)",
42361dbc6c9cSPavel Labath                 __FUNCTION__, tid, error_when_already_running?"true":"false");
42371dbc6c9cSPavel Labath 
42388c8ff7afSPavel Labath     auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
42398c8ff7afSPavel Labath     lldbassert(thread_sp != nullptr);
42405eb721edSPavel Labath 
42418c8ff7afSPavel Labath     auto& context = thread_sp->GetThreadContext();
4242c076559aSPavel Labath     // Tell the thread to resume if we don't already think it is running.
42438c8ff7afSPavel Labath     const bool is_stopped = StateIsStoppedState(thread_sp->GetState(), true);
42445eb721edSPavel Labath 
42455eb721edSPavel Labath     lldbassert(!(error_when_already_running && !is_stopped));
42465eb721edSPavel Labath 
4247c076559aSPavel Labath     if (!is_stopped)
4248c076559aSPavel Labath     {
4249c076559aSPavel Labath         // It's not an error, just a log, if the error_when_already_running flag is not set.
4250c076559aSPavel Labath         // This covers cases where, for instance, we're just trying to resume all threads
4251c076559aSPavel Labath         // from the user side.
42525eb721edSPavel Labath         if (log)
42535eb721edSPavel Labath             log->Printf("NativeProcessLinux::%s tid %" PRIu64 " optional resume skipped since it is already running",
4254c076559aSPavel Labath                     __FUNCTION__,
4255c076559aSPavel Labath                     tid);
42565eb721edSPavel Labath         return Error();
4257c076559aSPavel Labath     }
4258c076559aSPavel Labath 
4259c076559aSPavel Labath     // Before we do the resume below, first check if we have a pending
4260108c325dSPavel Labath     // stop notification that is currently waiting for
4261c076559aSPavel Labath     // this thread to stop.  This is potentially a buggy situation since
4262c076559aSPavel Labath     // we're ostensibly waiting for threads to stop before we send out the
4263c076559aSPavel Labath     // pending notification, and here we are resuming one before we send
4264c076559aSPavel Labath     // out the pending stop notification.
4265108c325dSPavel Labath     if (m_pending_notification_up && log && m_pending_notification_up->wait_for_stop_tids.count (tid) > 0)
4266c076559aSPavel Labath     {
42675eb721edSPavel 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);
4268c076559aSPavel Labath     }
4269c076559aSPavel Labath 
4270c076559aSPavel Labath     // Request a resume.  We expect this to be synchronous and the system
4271c076559aSPavel Labath     // to reflect it is running after this completes.
4272c076559aSPavel Labath     const auto error = request_thread_resume_function (tid, false);
4273c076559aSPavel Labath     if (error.Success())
42748c8ff7afSPavel Labath         context.request_resume_function = request_thread_resume_function;
42755eb721edSPavel Labath     else if (log)
4276c076559aSPavel Labath     {
42775eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s failed to resume thread tid  %" PRIu64 ": %s",
4278c076559aSPavel Labath                          __FUNCTION__, tid, error.AsCString ());
4279c076559aSPavel Labath     }
4280c076559aSPavel Labath 
42815eb721edSPavel Labath     return error;
4282c076559aSPavel Labath }
4283c076559aSPavel Labath 
4284c076559aSPavel Labath //===----------------------------------------------------------------------===//
4285c076559aSPavel Labath 
4286c076559aSPavel Labath void
4287337f3eb9SPavel Labath NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid)
4288c076559aSPavel Labath {
42895eb721edSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
4290c076559aSPavel Labath 
42915eb721edSPavel Labath     if (log)
4292c076559aSPavel Labath     {
42935eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ")",
4294c076559aSPavel Labath                 __FUNCTION__, triggering_tid);
4295c076559aSPavel Labath     }
4296c076559aSPavel Labath 
4297337f3eb9SPavel Labath     DoStopThreads(PendingNotificationUP(new PendingNotification(triggering_tid)));
4298c076559aSPavel Labath 
42995eb721edSPavel Labath     if (log)
4300c076559aSPavel Labath     {
43015eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
4302c076559aSPavel Labath     }
4303c076559aSPavel Labath }
4304c076559aSPavel Labath 
4305c076559aSPavel Labath void
43069eb1ecb9SPavel Labath NativeProcessLinux::SignalIfAllThreadsStopped()
4307c076559aSPavel Labath {
4308c076559aSPavel Labath     if (m_pending_notification_up && m_pending_notification_up->wait_for_stop_tids.empty ())
4309c076559aSPavel Labath     {
43109eb1ecb9SPavel Labath         Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
43119eb1ecb9SPavel Labath 
43129eb1ecb9SPavel Labath         // Clear any temporary breakpoints we used to implement software single stepping.
43139eb1ecb9SPavel Labath         for (const auto &thread_info: m_threads_stepping_with_breakpoint)
43149eb1ecb9SPavel Labath         {
43159eb1ecb9SPavel Labath             Error error = RemoveBreakpoint (thread_info.second);
43169eb1ecb9SPavel Labath             if (error.Fail())
43179eb1ecb9SPavel Labath                 if (log)
43189eb1ecb9SPavel Labath                     log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " remove stepping breakpoint: %s",
43199eb1ecb9SPavel Labath                             __FUNCTION__, thread_info.first, error.AsCString());
43209eb1ecb9SPavel Labath         }
43219eb1ecb9SPavel Labath         m_threads_stepping_with_breakpoint.clear();
43229eb1ecb9SPavel Labath 
43239eb1ecb9SPavel Labath         // Notify the delegate about the stop
4324ed89c7feSPavel Labath         SetCurrentThreadID(m_pending_notification_up->triggering_tid);
4325ed89c7feSPavel Labath         SetState(StateType::eStateStopped, true);
4326c076559aSPavel Labath         m_pending_notification_up.reset();
4327c076559aSPavel Labath     }
4328c076559aSPavel Labath }
4329c076559aSPavel Labath 
4330c076559aSPavel Labath void
4331c076559aSPavel Labath NativeProcessLinux::RequestStopOnAllRunningThreads()
4332c076559aSPavel Labath {
4333c076559aSPavel Labath     // Request a stop for all the thread stops that need to be stopped
4334c076559aSPavel Labath     // and are not already known to be stopped.  Keep a list of all the
4335c076559aSPavel Labath     // threads from which we still need to hear a stop reply.
4336c076559aSPavel Labath 
4337c076559aSPavel Labath     ThreadIDSet sent_tids;
43388c8ff7afSPavel Labath     for (const auto &thread_sp: m_threads)
4339c076559aSPavel Labath     {
43408c8ff7afSPavel Labath         // We only care about running threads
43418c8ff7afSPavel Labath         if (StateIsStoppedState(thread_sp->GetState(), true))
43428c8ff7afSPavel Labath             continue;
43438c8ff7afSPavel Labath 
43448c8ff7afSPavel Labath         static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
4345108c325dSPavel Labath         sent_tids.insert (thread_sp->GetID());
4346c076559aSPavel Labath     }
4347c076559aSPavel Labath 
4348c076559aSPavel Labath     // Set the wait list to the set of tids for which we requested stops.
4349c076559aSPavel Labath     m_pending_notification_up->wait_for_stop_tids.swap (sent_tids);
4350c076559aSPavel Labath }
4351c076559aSPavel Labath 
4352c076559aSPavel Labath 
43535eb721edSPavel Labath Error
43545eb721edSPavel Labath NativeProcessLinux::ThreadDidStop (lldb::tid_t tid, bool initiated_by_llgs)
4355c076559aSPavel Labath {
43561dbc6c9cSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
43571dbc6c9cSPavel Labath 
43581dbc6c9cSPavel Labath     if (log)
43591dbc6c9cSPavel Labath         log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ", %sinitiated by llgs)",
43601dbc6c9cSPavel Labath                 __FUNCTION__, tid, initiated_by_llgs?"":"not ");
43611dbc6c9cSPavel Labath 
4362c076559aSPavel Labath     // Ensure we know about the thread.
43638c8ff7afSPavel Labath     auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
43648c8ff7afSPavel Labath     lldbassert(thread_sp != nullptr);
4365c076559aSPavel Labath 
4366c076559aSPavel Labath     // Update the global list of known thread states.  This one is definitely stopped.
43678c8ff7afSPavel Labath     auto& context = thread_sp->GetThreadContext();
43688c8ff7afSPavel Labath     const auto stop_was_requested = context.stop_requested;
43698c8ff7afSPavel Labath     context.stop_requested = false;
4370c076559aSPavel Labath 
4371c076559aSPavel Labath     // If we have a pending notification, remove this from the set.
4372c076559aSPavel Labath     if (m_pending_notification_up)
4373c076559aSPavel Labath     {
4374c076559aSPavel Labath         m_pending_notification_up->wait_for_stop_tids.erase(tid);
43759eb1ecb9SPavel Labath         SignalIfAllThreadsStopped();
4376c076559aSPavel Labath     }
4377c076559aSPavel Labath 
43788c8ff7afSPavel Labath     Error error;
43798c8ff7afSPavel Labath     if (initiated_by_llgs && context.request_resume_function && !stop_was_requested)
4380c076559aSPavel Labath     {
4381c076559aSPavel Labath         // We can end up here if stop was initiated by LLGS but by this time a
4382c076559aSPavel Labath         // thread stop has occurred - maybe initiated by another event.
43835eb721edSPavel Labath         if (log)
43845eb721edSPavel Labath             log->Printf("Resuming thread %"  PRIu64 " since stop wasn't requested", tid);
43858c8ff7afSPavel Labath         error = context.request_resume_function (tid, true);
43868c8ff7afSPavel Labath         if (error.Fail() && log)
43875eb721edSPavel Labath         {
43885eb721edSPavel Labath                 log->Printf("NativeProcessLinux::%s failed to resume thread tid  %" PRIu64 ": %s",
4389c076559aSPavel Labath                         __FUNCTION__, tid, error.AsCString ());
4390c076559aSPavel Labath         }
43918c8ff7afSPavel Labath     }
43925eb721edSPavel Labath     return error;
4393c076559aSPavel Labath }
4394c076559aSPavel Labath 
4395c076559aSPavel Labath void
4396ed89c7feSPavel Labath NativeProcessLinux::DoStopThreads(PendingNotificationUP &&notification_up)
4397c076559aSPavel Labath {
43985eb721edSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
43995eb721edSPavel Labath     if (m_pending_notification_up && log)
4400c076559aSPavel Labath     {
4401c076559aSPavel Labath         // Yikes - we've already got a pending signal notification in progress.
4402c076559aSPavel Labath         // Log this info.  We lose the pending notification here.
44035eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s dropping existing pending signal notification for tid %" PRIu64 ", to be replaced with signal for tid %" PRIu64,
4404c076559aSPavel Labath                    __FUNCTION__,
4405c076559aSPavel Labath                    m_pending_notification_up->triggering_tid,
4406c076559aSPavel Labath                    notification_up->triggering_tid);
4407c076559aSPavel Labath     }
4408c076559aSPavel Labath     m_pending_notification_up = std::move(notification_up);
4409c076559aSPavel Labath 
4410c076559aSPavel Labath     RequestStopOnAllRunningThreads();
4411c076559aSPavel Labath 
44129eb1ecb9SPavel Labath     SignalIfAllThreadsStopped();
4413c076559aSPavel Labath }
4414c076559aSPavel Labath 
4415c076559aSPavel Labath void
44168c8ff7afSPavel Labath NativeProcessLinux::ThreadWasCreated (lldb::tid_t tid)
4417c076559aSPavel Labath {
44181dbc6c9cSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
44191dbc6c9cSPavel Labath 
44201dbc6c9cSPavel Labath     if (log)
44211dbc6c9cSPavel Labath         log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, tid);
44221dbc6c9cSPavel Labath 
44238c8ff7afSPavel Labath     auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
44248c8ff7afSPavel Labath     lldbassert(thread_sp != nullptr);
4425c076559aSPavel Labath 
44268c8ff7afSPavel Labath     if (m_pending_notification_up && StateIsRunningState(thread_sp->GetState()))
4427c076559aSPavel Labath     {
4428c076559aSPavel Labath         // We will need to wait for this new thread to stop as well before firing the
4429c076559aSPavel Labath         // notification.
4430c076559aSPavel Labath         m_pending_notification_up->wait_for_stop_tids.insert(tid);
44318c8ff7afSPavel Labath         thread_sp->RequestStop();
4432c076559aSPavel Labath     }
4433c076559aSPavel Labath }
4434