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>
16*5b981ab9SPavel Labath #include <semaphore.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>
25*5b981ab9SPavel Labath #include <unordered_map>
26af245d11STodd Fiala 
27af245d11STodd Fiala // Other libraries and framework includes
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/State.h"
341e209fccSTamas Berghammer #include "lldb/Host/common/NativeBreakpoint.h"
350cbf0b13STamas Berghammer #include "lldb/Host/common/NativeRegisterContext.h"
36af245d11STodd Fiala #include "lldb/Host/Host.h"
3739de3110SZachary Turner #include "lldb/Host/ThreadLauncher.h"
38*5b981ab9SPavel Labath #include "lldb/Target/Platform.h"
3990aff47cSZachary Turner #include "lldb/Target/Process.h"
40af245d11STodd Fiala #include "lldb/Target/ProcessLaunchInfo.h"
41*5b981ab9SPavel Labath #include "lldb/Target/Target.h"
42c16f5dcaSChaoren Lin #include "lldb/Utility/LLDBAssert.h"
43af245d11STodd Fiala #include "lldb/Utility/PseudoTerminal.h"
44af245d11STodd Fiala 
451e209fccSTamas Berghammer #include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
46af245d11STodd Fiala #include "Plugins/Process/Utility/LinuxSignals.h"
471e209fccSTamas Berghammer #include "Utility/StringExtractor.h"
48af245d11STodd Fiala #include "NativeThreadLinux.h"
49af245d11STodd Fiala #include "ProcFileReader.h"
501e209fccSTamas Berghammer #include "Procfs.h"
51cacde7dfSTodd Fiala 
52d858487eSTamas Berghammer // System includes - They have to be included after framework includes because they define some
53d858487eSTamas Berghammer // macros which collide with variable names in other modules
54d858487eSTamas Berghammer #include <linux/unistd.h>
55d858487eSTamas Berghammer #include <sys/socket.h>
568b335671SVince Harron 
57d858487eSTamas Berghammer #include <sys/types.h>
58d858487eSTamas Berghammer #include <sys/uio.h>
59d858487eSTamas Berghammer #include <sys/user.h>
60d858487eSTamas Berghammer #include <sys/wait.h>
61d858487eSTamas Berghammer 
628b335671SVince Harron #include "lldb/Host/linux/Personality.h"
638b335671SVince Harron #include "lldb/Host/linux/Ptrace.h"
648b335671SVince Harron #include "lldb/Host/linux/Signalfd.h"
658b335671SVince Harron #include "lldb/Host/android/Android.h"
66af245d11STodd Fiala 
670bce1b67STodd Fiala #define LLDB_PERSONALITY_GET_CURRENT_SETTINGS  0xffffffff
68af245d11STodd Fiala 
69af245d11STodd Fiala // Support hardware breakpoints in case it has not been defined
70af245d11STodd Fiala #ifndef TRAP_HWBKPT
71af245d11STodd Fiala   #define TRAP_HWBKPT 4
72af245d11STodd Fiala #endif
73af245d11STodd Fiala 
747cb18bf5STamas Berghammer using namespace lldb;
757cb18bf5STamas Berghammer using namespace lldb_private;
76db264a6dSTamas Berghammer using namespace lldb_private::process_linux;
777cb18bf5STamas Berghammer using namespace llvm;
787cb18bf5STamas Berghammer 
79af245d11STodd Fiala // Private bits we only need internally.
80af245d11STodd Fiala namespace
81af245d11STodd Fiala {
82af245d11STodd Fiala     const UnixSignals&
83af245d11STodd Fiala     GetUnixSignals ()
84af245d11STodd Fiala     {
85af245d11STodd Fiala         static process_linux::LinuxSignals signals;
86af245d11STodd Fiala         return signals;
87af245d11STodd Fiala     }
88af245d11STodd Fiala 
89af245d11STodd Fiala     Error
90af245d11STodd Fiala     ResolveProcessArchitecture (lldb::pid_t pid, Platform &platform, ArchSpec &arch)
91af245d11STodd Fiala     {
92af245d11STodd Fiala         // Grab process info for the running process.
93af245d11STodd Fiala         ProcessInstanceInfo process_info;
94af245d11STodd Fiala         if (!platform.GetProcessInfo (pid, process_info))
95db264a6dSTamas Berghammer             return Error("failed to get process info");
96af245d11STodd Fiala 
97af245d11STodd Fiala         // Resolve the executable module.
98af245d11STodd Fiala         ModuleSP exe_module_sp;
99e56f6dceSChaoren Lin         ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
100af245d11STodd Fiala         FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths ());
101af245d11STodd Fiala         Error error = platform.ResolveExecutable(
10254539338SOleksiy Vyalov             exe_module_spec,
103af245d11STodd Fiala             exe_module_sp,
104af245d11STodd Fiala             executable_search_paths.GetSize () ? &executable_search_paths : NULL);
105af245d11STodd Fiala 
106af245d11STodd Fiala         if (!error.Success ())
107af245d11STodd Fiala             return error;
108af245d11STodd Fiala 
109af245d11STodd Fiala         // Check if we've got our architecture from the exe_module.
110af245d11STodd Fiala         arch = exe_module_sp->GetArchitecture ();
111af245d11STodd Fiala         if (arch.IsValid ())
112af245d11STodd Fiala             return Error();
113af245d11STodd Fiala         else
114af245d11STodd Fiala             return Error("failed to retrieve a valid architecture from the exe module");
115af245d11STodd Fiala     }
116af245d11STodd Fiala 
117af245d11STodd Fiala     void
118db264a6dSTamas Berghammer     DisplayBytes (StreamString &s, void *bytes, uint32_t count)
119af245d11STodd Fiala     {
120af245d11STodd Fiala         uint8_t *ptr = (uint8_t *)bytes;
121af245d11STodd Fiala         const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
122af245d11STodd Fiala         for(uint32_t i=0; i<loop_count; i++)
123af245d11STodd Fiala         {
124af245d11STodd Fiala             s.Printf ("[%x]", *ptr);
125af245d11STodd Fiala             ptr++;
126af245d11STodd Fiala         }
127af245d11STodd Fiala     }
128af245d11STodd Fiala 
129af245d11STodd Fiala     void
130af245d11STodd Fiala     PtraceDisplayBytes(int &req, void *data, size_t data_size)
131af245d11STodd Fiala     {
132af245d11STodd Fiala         StreamString buf;
133af245d11STodd Fiala         Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
134af245d11STodd Fiala                     POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
135af245d11STodd Fiala 
136af245d11STodd Fiala         if (verbose_log)
137af245d11STodd Fiala         {
138af245d11STodd Fiala             switch(req)
139af245d11STodd Fiala             {
140af245d11STodd Fiala             case PTRACE_POKETEXT:
141af245d11STodd Fiala             {
142af245d11STodd Fiala                 DisplayBytes(buf, &data, 8);
143af245d11STodd Fiala                 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
144af245d11STodd Fiala                 break;
145af245d11STodd Fiala             }
146af245d11STodd Fiala             case PTRACE_POKEDATA:
147af245d11STodd Fiala             {
148af245d11STodd Fiala                 DisplayBytes(buf, &data, 8);
149af245d11STodd Fiala                 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
150af245d11STodd Fiala                 break;
151af245d11STodd Fiala             }
152af245d11STodd Fiala             case PTRACE_POKEUSER:
153af245d11STodd Fiala             {
154af245d11STodd Fiala                 DisplayBytes(buf, &data, 8);
155af245d11STodd Fiala                 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
156af245d11STodd Fiala                 break;
157af245d11STodd Fiala             }
158af245d11STodd Fiala             case PTRACE_SETREGS:
159af245d11STodd Fiala             {
160af245d11STodd Fiala                 DisplayBytes(buf, data, data_size);
161af245d11STodd Fiala                 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
162af245d11STodd Fiala                 break;
163af245d11STodd Fiala             }
164af245d11STodd Fiala             case PTRACE_SETFPREGS:
165af245d11STodd Fiala             {
166af245d11STodd Fiala                 DisplayBytes(buf, data, data_size);
167af245d11STodd Fiala                 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
168af245d11STodd Fiala                 break;
169af245d11STodd Fiala             }
170af245d11STodd Fiala             case PTRACE_SETSIGINFO:
171af245d11STodd Fiala             {
172af245d11STodd Fiala                 DisplayBytes(buf, data, sizeof(siginfo_t));
173af245d11STodd Fiala                 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
174af245d11STodd Fiala                 break;
175af245d11STodd Fiala             }
176af245d11STodd Fiala             case PTRACE_SETREGSET:
177af245d11STodd Fiala             {
178af245d11STodd Fiala                 // Extract iov_base from data, which is a pointer to the struct IOVEC
179af245d11STodd Fiala                 DisplayBytes(buf, *(void **)data, data_size);
180af245d11STodd Fiala                 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
181af245d11STodd Fiala                 break;
182af245d11STodd Fiala             }
183af245d11STodd Fiala             default:
184af245d11STodd Fiala             {
185af245d11STodd Fiala             }
186af245d11STodd Fiala             }
187af245d11STodd Fiala         }
188af245d11STodd Fiala     }
189af245d11STodd Fiala 
190af245d11STodd Fiala     //------------------------------------------------------------------------------
191af245d11STodd Fiala     // Static implementations of NativeProcessLinux::ReadMemory and
192af245d11STodd Fiala     // NativeProcessLinux::WriteMemory.  This enables mutual recursion between these
193af245d11STodd Fiala     // functions without needed to go thru the thread funnel.
194af245d11STodd Fiala 
1953eb4b458SChaoren Lin     size_t
196af245d11STodd Fiala     DoReadMemory(
197af245d11STodd Fiala         lldb::pid_t pid,
198af245d11STodd Fiala         lldb::addr_t vm_addr,
199af245d11STodd Fiala         void *buf,
2003eb4b458SChaoren Lin         size_t size,
201af245d11STodd Fiala         Error &error)
202af245d11STodd Fiala     {
203af245d11STodd Fiala         // ptrace word size is determined by the host, not the child
204af245d11STodd Fiala         static const unsigned word_size = sizeof(void*);
205af245d11STodd Fiala         unsigned char *dst = static_cast<unsigned char*>(buf);
2063eb4b458SChaoren Lin         size_t bytes_read;
2073eb4b458SChaoren Lin         size_t remainder;
208af245d11STodd Fiala         long data;
209af245d11STodd Fiala 
210af245d11STodd Fiala         Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
211af245d11STodd Fiala         if (log)
212af245d11STodd Fiala             ProcessPOSIXLog::IncNestLevel();
213af245d11STodd Fiala         if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
214af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
215af245d11STodd Fiala                     pid, word_size, (void*)vm_addr, buf, size);
216af245d11STodd Fiala 
217af245d11STodd Fiala         assert(sizeof(data) >= word_size);
218af245d11STodd Fiala         for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
219af245d11STodd Fiala         {
220068f8a7eSTamas Berghammer             data = NativeProcessLinux::PtraceWrapper(PTRACE_PEEKDATA, pid, (void*)vm_addr, nullptr, 0, error);
22197ccc294SChaoren Lin             if (error.Fail())
222af245d11STodd Fiala             {
223af245d11STodd Fiala                 if (log)
224af245d11STodd Fiala                     ProcessPOSIXLog::DecNestLevel();
225af245d11STodd Fiala                 return bytes_read;
226af245d11STodd Fiala             }
227af245d11STodd Fiala 
228af245d11STodd Fiala             remainder = size - bytes_read;
229af245d11STodd Fiala             remainder = remainder > word_size ? word_size : remainder;
230af245d11STodd Fiala 
231af245d11STodd Fiala             // Copy the data into our buffer
232af245d11STodd Fiala             for (unsigned i = 0; i < remainder; ++i)
233af245d11STodd Fiala                 dst[i] = ((data >> i*8) & 0xFF);
234af245d11STodd Fiala 
235af245d11STodd Fiala             if (log && ProcessPOSIXLog::AtTopNestLevel() &&
236af245d11STodd Fiala                     (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
237af245d11STodd Fiala                             (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
238af245d11STodd Fiala                                     size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
239af245d11STodd Fiala             {
240af245d11STodd Fiala                 uintptr_t print_dst = 0;
241af245d11STodd Fiala                 // Format bytes from data by moving into print_dst for log output
242af245d11STodd Fiala                 for (unsigned i = 0; i < remainder; ++i)
243af245d11STodd Fiala                     print_dst |= (((data >> i*8) & 0xFF) << i*8);
244af245d11STodd Fiala                 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
245af245d11STodd Fiala                         (void*)vm_addr, print_dst, (unsigned long)data);
246af245d11STodd Fiala             }
247af245d11STodd Fiala 
248af245d11STodd Fiala             vm_addr += word_size;
249af245d11STodd Fiala             dst += word_size;
250af245d11STodd Fiala         }
251af245d11STodd Fiala 
252af245d11STodd Fiala         if (log)
253af245d11STodd Fiala             ProcessPOSIXLog::DecNestLevel();
254af245d11STodd Fiala         return bytes_read;
255af245d11STodd Fiala     }
256af245d11STodd Fiala 
2573eb4b458SChaoren Lin     size_t
258af245d11STodd Fiala     DoWriteMemory(
259af245d11STodd Fiala         lldb::pid_t pid,
260af245d11STodd Fiala         lldb::addr_t vm_addr,
261af245d11STodd Fiala         const void *buf,
2623eb4b458SChaoren Lin         size_t size,
263af245d11STodd Fiala         Error &error)
264af245d11STodd Fiala     {
265af245d11STodd Fiala         // ptrace word size is determined by the host, not the child
266af245d11STodd Fiala         static const unsigned word_size = sizeof(void*);
267af245d11STodd Fiala         const unsigned char *src = static_cast<const unsigned char*>(buf);
2683eb4b458SChaoren Lin         size_t bytes_written = 0;
2693eb4b458SChaoren Lin         size_t remainder;
270af245d11STodd Fiala 
271af245d11STodd Fiala         Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
272af245d11STodd Fiala         if (log)
273af245d11STodd Fiala             ProcessPOSIXLog::IncNestLevel();
274af245d11STodd Fiala         if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
275af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %u, %p, %p, %" PRIu64 ")", __FUNCTION__,
276af245d11STodd Fiala                     pid, word_size, (void*)vm_addr, buf, size);
277af245d11STodd Fiala 
278af245d11STodd Fiala         for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
279af245d11STodd Fiala         {
280af245d11STodd Fiala             remainder = size - bytes_written;
281af245d11STodd Fiala             remainder = remainder > word_size ? word_size : remainder;
282af245d11STodd Fiala 
283af245d11STodd Fiala             if (remainder == word_size)
284af245d11STodd Fiala             {
285af245d11STodd Fiala                 unsigned long data = 0;
286af245d11STodd Fiala                 assert(sizeof(data) >= word_size);
287af245d11STodd Fiala                 for (unsigned i = 0; i < word_size; ++i)
288af245d11STodd Fiala                     data |= (unsigned long)src[i] << i*8;
289af245d11STodd Fiala 
290af245d11STodd Fiala                 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
291af245d11STodd Fiala                         (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
292af245d11STodd Fiala                                 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
293af245d11STodd Fiala                                         size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
294af245d11STodd Fiala                     log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
2951e209fccSTamas Berghammer                             (void*)vm_addr, *(const unsigned long*)src, data);
296af245d11STodd Fiala 
297068f8a7eSTamas Berghammer                 if (NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, pid, (void*)vm_addr, (void*)data, 0, error))
298af245d11STodd Fiala                 {
299af245d11STodd Fiala                     if (log)
300af245d11STodd Fiala                         ProcessPOSIXLog::DecNestLevel();
301af245d11STodd Fiala                     return bytes_written;
302af245d11STodd Fiala                 }
303af245d11STodd Fiala             }
304af245d11STodd Fiala             else
305af245d11STodd Fiala             {
306af245d11STodd Fiala                 unsigned char buff[8];
307af245d11STodd Fiala                 if (DoReadMemory(pid, vm_addr,
308af245d11STodd Fiala                                 buff, word_size, error) != word_size)
309af245d11STodd Fiala                 {
310af245d11STodd Fiala                     if (log)
311af245d11STodd Fiala                         ProcessPOSIXLog::DecNestLevel();
312af245d11STodd Fiala                     return bytes_written;
313af245d11STodd Fiala                 }
314af245d11STodd Fiala 
315af245d11STodd Fiala                 memcpy(buff, src, remainder);
316af245d11STodd Fiala 
317af245d11STodd Fiala                 if (DoWriteMemory(pid, vm_addr,
318af245d11STodd Fiala                                 buff, word_size, error) != word_size)
319af245d11STodd Fiala                 {
320af245d11STodd Fiala                     if (log)
321af245d11STodd Fiala                         ProcessPOSIXLog::DecNestLevel();
322af245d11STodd Fiala                     return bytes_written;
323af245d11STodd Fiala                 }
324af245d11STodd Fiala 
325af245d11STodd Fiala                 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
326af245d11STodd Fiala                         (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
327af245d11STodd Fiala                                 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
328af245d11STodd Fiala                                         size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
329af245d11STodd Fiala                     log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
3301e209fccSTamas Berghammer                             (void*)vm_addr, *(const unsigned long*)src, *(unsigned long*)buff);
331af245d11STodd Fiala             }
332af245d11STodd Fiala 
333af245d11STodd Fiala             vm_addr += word_size;
334af245d11STodd Fiala             src += word_size;
335af245d11STodd Fiala         }
336af245d11STodd Fiala         if (log)
337af245d11STodd Fiala             ProcessPOSIXLog::DecNestLevel();
338af245d11STodd Fiala         return bytes_written;
339af245d11STodd Fiala     }
340af245d11STodd Fiala 
341af245d11STodd Fiala     //------------------------------------------------------------------------------
342af245d11STodd Fiala     /// @class ReadOperation
343af245d11STodd Fiala     /// @brief Implements NativeProcessLinux::ReadMemory.
344068f8a7eSTamas Berghammer     class ReadOperation : public NativeProcessLinux::Operation
345af245d11STodd Fiala     {
346af245d11STodd Fiala     public:
347af245d11STodd Fiala         ReadOperation(
348af245d11STodd Fiala             lldb::addr_t addr,
349af245d11STodd Fiala             void *buff,
3503eb4b458SChaoren Lin             size_t size,
3513eb4b458SChaoren Lin             size_t &result) :
352af245d11STodd Fiala             Operation (),
353af245d11STodd Fiala             m_addr (addr),
354af245d11STodd Fiala             m_buff (buff),
355af245d11STodd Fiala             m_size (size),
356af245d11STodd Fiala             m_result (result)
357af245d11STodd Fiala             {
358af245d11STodd Fiala             }
359af245d11STodd Fiala 
360af245d11STodd Fiala         void Execute (NativeProcessLinux *process) override;
361af245d11STodd Fiala 
362af245d11STodd Fiala     private:
363af245d11STodd Fiala         lldb::addr_t m_addr;
364af245d11STodd Fiala         void *m_buff;
3653eb4b458SChaoren Lin         size_t m_size;
3663eb4b458SChaoren Lin         size_t &m_result;
367af245d11STodd Fiala     };
368af245d11STodd Fiala 
369af245d11STodd Fiala     void
370af245d11STodd Fiala     ReadOperation::Execute (NativeProcessLinux *process)
371af245d11STodd Fiala     {
372af245d11STodd Fiala         m_result = DoReadMemory (process->GetID (), m_addr, m_buff, m_size, m_error);
373af245d11STodd Fiala     }
374af245d11STodd Fiala 
375af245d11STodd Fiala     //------------------------------------------------------------------------------
376af245d11STodd Fiala     /// @class WriteOperation
377af245d11STodd Fiala     /// @brief Implements NativeProcessLinux::WriteMemory.
378068f8a7eSTamas Berghammer     class WriteOperation : public NativeProcessLinux::Operation
379af245d11STodd Fiala     {
380af245d11STodd Fiala     public:
381af245d11STodd Fiala         WriteOperation(
382af245d11STodd Fiala             lldb::addr_t addr,
383af245d11STodd Fiala             const void *buff,
3843eb4b458SChaoren Lin             size_t size,
3853eb4b458SChaoren Lin             size_t &result) :
386af245d11STodd Fiala             Operation (),
387af245d11STodd Fiala             m_addr (addr),
388af245d11STodd Fiala             m_buff (buff),
389af245d11STodd Fiala             m_size (size),
390af245d11STodd Fiala             m_result (result)
391af245d11STodd Fiala             {
392af245d11STodd Fiala             }
393af245d11STodd Fiala 
394af245d11STodd Fiala         void Execute (NativeProcessLinux *process) override;
395af245d11STodd Fiala 
396af245d11STodd Fiala     private:
397af245d11STodd Fiala         lldb::addr_t m_addr;
398af245d11STodd Fiala         const void *m_buff;
3993eb4b458SChaoren Lin         size_t m_size;
4003eb4b458SChaoren Lin         size_t &m_result;
401af245d11STodd Fiala     };
402af245d11STodd Fiala 
403af245d11STodd Fiala     void
404af245d11STodd Fiala     WriteOperation::Execute(NativeProcessLinux *process)
405af245d11STodd Fiala     {
406af245d11STodd Fiala         m_result = DoWriteMemory (process->GetID (), m_addr, m_buff, m_size, m_error);
407af245d11STodd Fiala     }
408af245d11STodd Fiala 
409af245d11STodd Fiala     //------------------------------------------------------------------------------
410af245d11STodd Fiala     /// @class ResumeOperation
411af245d11STodd Fiala     /// @brief Implements NativeProcessLinux::Resume.
412068f8a7eSTamas Berghammer     class ResumeOperation : public NativeProcessLinux::Operation
413af245d11STodd Fiala     {
414af245d11STodd Fiala     public:
41597ccc294SChaoren Lin         ResumeOperation(lldb::tid_t tid, uint32_t signo) :
41697ccc294SChaoren Lin             m_tid(tid), m_signo(signo) { }
417af245d11STodd Fiala 
418d542efdeSTamas Berghammer         void Execute(NativeProcessLinux *monitor) override;
419af245d11STodd Fiala 
420af245d11STodd Fiala     private:
421af245d11STodd Fiala         lldb::tid_t m_tid;
422af245d11STodd Fiala         uint32_t m_signo;
423af245d11STodd Fiala     };
424af245d11STodd Fiala 
425af245d11STodd Fiala     void
426af245d11STodd Fiala     ResumeOperation::Execute(NativeProcessLinux *monitor)
427af245d11STodd Fiala     {
428af245d11STodd Fiala         intptr_t data = 0;
429af245d11STodd Fiala 
430af245d11STodd Fiala         if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
431af245d11STodd Fiala             data = m_signo;
432af245d11STodd Fiala 
433068f8a7eSTamas Berghammer         NativeProcessLinux::PtraceWrapper(PTRACE_CONT, m_tid, nullptr, (void*)data, 0, m_error);
43497ccc294SChaoren Lin         if (m_error.Fail())
435af245d11STodd Fiala         {
436af245d11STodd Fiala             Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
437af245d11STodd Fiala 
438af245d11STodd Fiala             if (log)
43997ccc294SChaoren Lin                 log->Printf ("ResumeOperation (%"  PRIu64 ") failed: %s", m_tid, m_error.AsCString());
440af245d11STodd Fiala         }
441af245d11STodd Fiala     }
442af245d11STodd Fiala 
443af245d11STodd Fiala     //------------------------------------------------------------------------------
444af245d11STodd Fiala     /// @class SingleStepOperation
445af245d11STodd Fiala     /// @brief Implements NativeProcessLinux::SingleStep.
446068f8a7eSTamas Berghammer     class SingleStepOperation : public NativeProcessLinux::Operation
447af245d11STodd Fiala     {
448af245d11STodd Fiala     public:
44997ccc294SChaoren Lin         SingleStepOperation(lldb::tid_t tid, uint32_t signo)
45097ccc294SChaoren Lin             : m_tid(tid), m_signo(signo) { }
451af245d11STodd Fiala 
452d542efdeSTamas Berghammer         void Execute(NativeProcessLinux *monitor) override;
453af245d11STodd Fiala 
454af245d11STodd Fiala     private:
455af245d11STodd Fiala         lldb::tid_t m_tid;
456af245d11STodd Fiala         uint32_t m_signo;
457af245d11STodd Fiala     };
458af245d11STodd Fiala 
459af245d11STodd Fiala     void
460af245d11STodd Fiala     SingleStepOperation::Execute(NativeProcessLinux *monitor)
461af245d11STodd Fiala     {
462af245d11STodd Fiala         intptr_t data = 0;
463af245d11STodd Fiala 
464af245d11STodd Fiala         if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
465af245d11STodd Fiala             data = m_signo;
466af245d11STodd Fiala 
467068f8a7eSTamas Berghammer         NativeProcessLinux::PtraceWrapper(PTRACE_SINGLESTEP, m_tid, nullptr, (void*)data, 0, m_error);
468af245d11STodd Fiala     }
469af245d11STodd Fiala 
470af245d11STodd Fiala     //------------------------------------------------------------------------------
471af245d11STodd Fiala     /// @class SiginfoOperation
472af245d11STodd Fiala     /// @brief Implements NativeProcessLinux::GetSignalInfo.
473068f8a7eSTamas Berghammer     class SiginfoOperation : public NativeProcessLinux::Operation
474af245d11STodd Fiala     {
475af245d11STodd Fiala     public:
47697ccc294SChaoren Lin         SiginfoOperation(lldb::tid_t tid, void *info)
47797ccc294SChaoren Lin             : m_tid(tid), m_info(info) { }
478af245d11STodd Fiala 
479d542efdeSTamas Berghammer         void Execute(NativeProcessLinux *monitor) override;
480af245d11STodd Fiala 
481af245d11STodd Fiala     private:
482af245d11STodd Fiala         lldb::tid_t m_tid;
483af245d11STodd Fiala         void *m_info;
484af245d11STodd Fiala     };
485af245d11STodd Fiala 
486af245d11STodd Fiala     void
487af245d11STodd Fiala     SiginfoOperation::Execute(NativeProcessLinux *monitor)
488af245d11STodd Fiala     {
489068f8a7eSTamas Berghammer         NativeProcessLinux::PtraceWrapper(PTRACE_GETSIGINFO, m_tid, nullptr, m_info, 0, m_error);
490af245d11STodd Fiala     }
491af245d11STodd Fiala 
492af245d11STodd Fiala     //------------------------------------------------------------------------------
493af245d11STodd Fiala     /// @class EventMessageOperation
494af245d11STodd Fiala     /// @brief Implements NativeProcessLinux::GetEventMessage.
495068f8a7eSTamas Berghammer     class EventMessageOperation : public NativeProcessLinux::Operation
496af245d11STodd Fiala     {
497af245d11STodd Fiala     public:
49897ccc294SChaoren Lin         EventMessageOperation(lldb::tid_t tid, unsigned long *message)
49997ccc294SChaoren Lin             : m_tid(tid), m_message(message) { }
500af245d11STodd Fiala 
501d542efdeSTamas Berghammer         void Execute(NativeProcessLinux *monitor) override;
502af245d11STodd Fiala 
503af245d11STodd Fiala     private:
504af245d11STodd Fiala         lldb::tid_t m_tid;
505af245d11STodd Fiala         unsigned long *m_message;
506af245d11STodd Fiala     };
507af245d11STodd Fiala 
508af245d11STodd Fiala     void
509af245d11STodd Fiala     EventMessageOperation::Execute(NativeProcessLinux *monitor)
510af245d11STodd Fiala     {
511068f8a7eSTamas Berghammer         NativeProcessLinux::PtraceWrapper(PTRACE_GETEVENTMSG, m_tid, nullptr, m_message, 0, m_error);
512af245d11STodd Fiala     }
513af245d11STodd Fiala 
514068f8a7eSTamas Berghammer     class DetachOperation : public NativeProcessLinux::Operation
515af245d11STodd Fiala     {
516af245d11STodd Fiala     public:
51797ccc294SChaoren Lin         DetachOperation(lldb::tid_t tid) : m_tid(tid) { }
518af245d11STodd Fiala 
519d542efdeSTamas Berghammer         void Execute(NativeProcessLinux *monitor) override;
520af245d11STodd Fiala 
521af245d11STodd Fiala     private:
522af245d11STodd Fiala         lldb::tid_t m_tid;
523af245d11STodd Fiala     };
524af245d11STodd Fiala 
525af245d11STodd Fiala     void
526af245d11STodd Fiala     DetachOperation::Execute(NativeProcessLinux *monitor)
527af245d11STodd Fiala     {
528068f8a7eSTamas Berghammer         NativeProcessLinux::PtraceWrapper(PTRACE_DETACH, m_tid, nullptr, 0, 0, m_error);
529af245d11STodd Fiala     }
5301107b5a5SPavel Labath } // end of anonymous namespace
5311107b5a5SPavel Labath 
532bd7cbc5aSPavel Labath // Simple helper function to ensure flags are enabled on the given file
533bd7cbc5aSPavel Labath // descriptor.
534bd7cbc5aSPavel Labath static Error
535bd7cbc5aSPavel Labath EnsureFDFlags(int fd, int flags)
536bd7cbc5aSPavel Labath {
537bd7cbc5aSPavel Labath     Error error;
538bd7cbc5aSPavel Labath 
539bd7cbc5aSPavel Labath     int status = fcntl(fd, F_GETFL);
540bd7cbc5aSPavel Labath     if (status == -1)
541bd7cbc5aSPavel Labath     {
542bd7cbc5aSPavel Labath         error.SetErrorToErrno();
543bd7cbc5aSPavel Labath         return error;
544bd7cbc5aSPavel Labath     }
545bd7cbc5aSPavel Labath 
546bd7cbc5aSPavel Labath     if (fcntl(fd, F_SETFL, status | flags) == -1)
547bd7cbc5aSPavel Labath     {
548bd7cbc5aSPavel Labath         error.SetErrorToErrno();
549bd7cbc5aSPavel Labath         return error;
550bd7cbc5aSPavel Labath     }
551bd7cbc5aSPavel Labath 
552bd7cbc5aSPavel Labath     return error;
553bd7cbc5aSPavel Labath }
554bd7cbc5aSPavel Labath 
555bd7cbc5aSPavel Labath // This class encapsulates the privileged thread which performs all ptrace and wait operations on
556bd7cbc5aSPavel Labath // the inferior. The thread consists of a main loop which waits for events and processes them
557bd7cbc5aSPavel Labath //   - SIGCHLD (delivered over a signalfd file descriptor): These signals notify us of events in
558bd7cbc5aSPavel Labath //     the inferior process. Upon receiving this signal we do a waitpid to get more information
559bd7cbc5aSPavel Labath //     and dispatch to NativeProcessLinux::MonitorCallback.
560bd7cbc5aSPavel Labath //   - requests for ptrace operations: These initiated via the DoOperation method, which funnels
561bd7cbc5aSPavel Labath //     them to the Monitor thread via m_operation member. The Monitor thread is signaled over a
562bd7cbc5aSPavel Labath //     pipe, and the completion of the operation is signalled over the semaphore.
563bd7cbc5aSPavel Labath //   - thread exit event: this is signaled from the Monitor destructor by closing the write end
564bd7cbc5aSPavel Labath //     of the command pipe.
56545f5cb31SPavel Labath class NativeProcessLinux::Monitor
56645f5cb31SPavel Labath {
5671107b5a5SPavel Labath private:
568bd7cbc5aSPavel Labath     // The initial monitor operation (launch or attach). It returns a inferior process id.
569bd7cbc5aSPavel Labath     std::unique_ptr<InitialOperation> m_initial_operation_up;
570bd7cbc5aSPavel Labath 
571bd7cbc5aSPavel Labath     ::pid_t                           m_child_pid = -1;
5721107b5a5SPavel Labath     NativeProcessLinux              * m_native_process;
5731107b5a5SPavel Labath 
5741107b5a5SPavel Labath     enum { READ, WRITE };
5751107b5a5SPavel Labath     int        m_pipefd[2] = {-1, -1};
5761107b5a5SPavel Labath     int        m_signal_fd = -1;
5771107b5a5SPavel Labath     HostThread m_thread;
5781107b5a5SPavel Labath 
579bd7cbc5aSPavel Labath     // current operation which must be executed on the priviliged thread
580bd7cbc5aSPavel Labath     Mutex      m_operation_mutex;
581bd7cbc5aSPavel Labath     Operation *m_operation = nullptr;
582bd7cbc5aSPavel Labath     sem_t      m_operation_sem;
583bd7cbc5aSPavel Labath     Error      m_operation_error;
584bd7cbc5aSPavel Labath 
58545f5cb31SPavel Labath     unsigned   m_operation_nesting_level = 0;
58645f5cb31SPavel Labath 
587bd7cbc5aSPavel Labath     static constexpr char operation_command   = 'o';
58845f5cb31SPavel Labath     static constexpr char begin_block_command = '{';
58945f5cb31SPavel Labath     static constexpr char end_block_command   = '}';
590bd7cbc5aSPavel Labath 
5911107b5a5SPavel Labath     void
5921107b5a5SPavel Labath     HandleSignals();
5931107b5a5SPavel Labath 
5941107b5a5SPavel Labath     void
5951107b5a5SPavel Labath     HandleWait();
5961107b5a5SPavel Labath 
5971107b5a5SPavel Labath     // Returns true if the thread should exit.
5981107b5a5SPavel Labath     bool
5991107b5a5SPavel Labath     HandleCommands();
6001107b5a5SPavel Labath 
6011107b5a5SPavel Labath     void
6021107b5a5SPavel Labath     MainLoop();
6031107b5a5SPavel Labath 
6041107b5a5SPavel Labath     static void *
6051107b5a5SPavel Labath     RunMonitor(void *arg);
6061107b5a5SPavel Labath 
607bd7cbc5aSPavel Labath     Error
60845f5cb31SPavel Labath     WaitForAck();
60945f5cb31SPavel Labath 
61045f5cb31SPavel Labath     void
61145f5cb31SPavel Labath     BeginOperationBlock()
61245f5cb31SPavel Labath     {
61345f5cb31SPavel Labath         write(m_pipefd[WRITE], &begin_block_command, sizeof operation_command);
61445f5cb31SPavel Labath         WaitForAck();
61545f5cb31SPavel Labath     }
61645f5cb31SPavel Labath 
61745f5cb31SPavel Labath     void
61845f5cb31SPavel Labath     EndOperationBlock()
61945f5cb31SPavel Labath     {
62045f5cb31SPavel Labath         write(m_pipefd[WRITE], &end_block_command, sizeof operation_command);
62145f5cb31SPavel Labath         WaitForAck();
62245f5cb31SPavel Labath     }
62345f5cb31SPavel Labath 
6241107b5a5SPavel Labath public:
625bd7cbc5aSPavel Labath     Monitor(const InitialOperation &initial_operation,
626bd7cbc5aSPavel Labath             NativeProcessLinux *native_process)
627bd7cbc5aSPavel Labath         : m_initial_operation_up(new InitialOperation(initial_operation)),
628bd7cbc5aSPavel Labath           m_native_process(native_process)
629bd7cbc5aSPavel Labath     {
630bd7cbc5aSPavel Labath         sem_init(&m_operation_sem, 0, 0);
631bd7cbc5aSPavel Labath     }
6321107b5a5SPavel Labath 
6331107b5a5SPavel Labath     ~Monitor();
6341107b5a5SPavel Labath 
6351107b5a5SPavel Labath     Error
6361107b5a5SPavel Labath     Initialize();
637bd7cbc5aSPavel Labath 
638bd7cbc5aSPavel Labath     void
63945f5cb31SPavel Labath     Terminate();
64045f5cb31SPavel Labath 
64145f5cb31SPavel Labath     void
642bd7cbc5aSPavel Labath     DoOperation(Operation *op);
64345f5cb31SPavel Labath 
64445f5cb31SPavel Labath     class ScopedOperationLock {
64545f5cb31SPavel Labath         Monitor &m_monitor;
64645f5cb31SPavel Labath 
64745f5cb31SPavel Labath     public:
64845f5cb31SPavel Labath         ScopedOperationLock(Monitor &monitor)
64945f5cb31SPavel Labath             : m_monitor(monitor)
65045f5cb31SPavel Labath         { m_monitor.BeginOperationBlock(); }
65145f5cb31SPavel Labath 
65245f5cb31SPavel Labath         ~ScopedOperationLock()
65345f5cb31SPavel Labath         { m_monitor.EndOperationBlock(); }
65445f5cb31SPavel Labath     };
6551107b5a5SPavel Labath };
656bd7cbc5aSPavel Labath constexpr char NativeProcessLinux::Monitor::operation_command;
65745f5cb31SPavel Labath constexpr char NativeProcessLinux::Monitor::begin_block_command;
65845f5cb31SPavel Labath constexpr char NativeProcessLinux::Monitor::end_block_command;
6591107b5a5SPavel Labath 
6601107b5a5SPavel Labath Error
6611107b5a5SPavel Labath NativeProcessLinux::Monitor::Initialize()
6621107b5a5SPavel Labath {
6631107b5a5SPavel Labath     Error error;
6641107b5a5SPavel Labath 
6651107b5a5SPavel Labath     // We get a SIGCHLD every time something interesting happens with the inferior. We shall be
6661107b5a5SPavel Labath     // listening for these signals over a signalfd file descriptors. This allows us to wait for
6671107b5a5SPavel Labath     // multiple kinds of events with select.
6681107b5a5SPavel Labath     sigset_t signals;
6691107b5a5SPavel Labath     sigemptyset(&signals);
6701107b5a5SPavel Labath     sigaddset(&signals, SIGCHLD);
6711107b5a5SPavel Labath     m_signal_fd = signalfd(-1, &signals, SFD_NONBLOCK | SFD_CLOEXEC);
6721107b5a5SPavel Labath     if (m_signal_fd < 0)
6731107b5a5SPavel Labath     {
6741107b5a5SPavel Labath         return Error("NativeProcessLinux::Monitor::%s failed due to signalfd failure. Monitoring the inferior will be impossible: %s",
6751107b5a5SPavel Labath                     __FUNCTION__, strerror(errno));
6761107b5a5SPavel Labath 
677af245d11STodd Fiala     }
678af245d11STodd Fiala 
6791107b5a5SPavel Labath     if (pipe2(m_pipefd, O_CLOEXEC) == -1)
6801107b5a5SPavel Labath     {
6811107b5a5SPavel Labath         error.SetErrorToErrno();
6821107b5a5SPavel Labath         return error;
6831107b5a5SPavel Labath     }
6841107b5a5SPavel Labath 
685bd7cbc5aSPavel Labath     if ((error = EnsureFDFlags(m_pipefd[READ], O_NONBLOCK)).Fail()) {
686bd7cbc5aSPavel Labath         return error;
687bd7cbc5aSPavel Labath     }
688bd7cbc5aSPavel Labath 
689bd7cbc5aSPavel Labath     static const char g_thread_name[] = "lldb.process.nativelinux.monitor";
690bd7cbc5aSPavel Labath     m_thread = ThreadLauncher::LaunchThread(g_thread_name, Monitor::RunMonitor, this, nullptr);
6911107b5a5SPavel Labath     if (!m_thread.IsJoinable())
6921107b5a5SPavel Labath         return Error("Failed to create monitor thread for NativeProcessLinux.");
6931107b5a5SPavel Labath 
694bd7cbc5aSPavel Labath     // Wait for initial operation to complete.
69545f5cb31SPavel Labath     return WaitForAck();
696bd7cbc5aSPavel Labath }
697bd7cbc5aSPavel Labath 
698bd7cbc5aSPavel Labath void
699bd7cbc5aSPavel Labath NativeProcessLinux::Monitor::DoOperation(Operation *op)
700bd7cbc5aSPavel Labath {
701bd7cbc5aSPavel Labath     if (m_thread.EqualsThread(pthread_self())) {
702bd7cbc5aSPavel Labath         // If we're on the Monitor thread, we can simply execute the operation.
703bd7cbc5aSPavel Labath         op->Execute(m_native_process);
704bd7cbc5aSPavel Labath         return;
705bd7cbc5aSPavel Labath     }
706bd7cbc5aSPavel Labath 
707bd7cbc5aSPavel Labath     // Otherwise we need to pass the operation to the Monitor thread so it can handle it.
708bd7cbc5aSPavel Labath     Mutex::Locker lock(m_operation_mutex);
709bd7cbc5aSPavel Labath 
710bd7cbc5aSPavel Labath     m_operation = op;
711bd7cbc5aSPavel Labath 
712bd7cbc5aSPavel Labath     // notify the thread that an operation is ready to be processed
713bd7cbc5aSPavel Labath     write(m_pipefd[WRITE], &operation_command, sizeof operation_command);
714bd7cbc5aSPavel Labath 
71545f5cb31SPavel Labath     WaitForAck();
71645f5cb31SPavel Labath }
71745f5cb31SPavel Labath 
71845f5cb31SPavel Labath void
71945f5cb31SPavel Labath NativeProcessLinux::Monitor::Terminate()
72045f5cb31SPavel Labath {
72145f5cb31SPavel Labath     if (m_pipefd[WRITE] >= 0)
72245f5cb31SPavel Labath     {
72345f5cb31SPavel Labath         close(m_pipefd[WRITE]);
72445f5cb31SPavel Labath         m_pipefd[WRITE] = -1;
72545f5cb31SPavel Labath     }
72645f5cb31SPavel Labath     if (m_thread.IsJoinable())
72745f5cb31SPavel Labath         m_thread.Join(nullptr);
7281107b5a5SPavel Labath }
7291107b5a5SPavel Labath 
7301107b5a5SPavel Labath NativeProcessLinux::Monitor::~Monitor()
7311107b5a5SPavel Labath {
73245f5cb31SPavel Labath     Terminate();
7331107b5a5SPavel Labath     if (m_pipefd[READ] >= 0)
7341107b5a5SPavel Labath         close(m_pipefd[READ]);
7351107b5a5SPavel Labath     if (m_signal_fd >= 0)
7361107b5a5SPavel Labath         close(m_signal_fd);
737bd7cbc5aSPavel Labath     sem_destroy(&m_operation_sem);
7381107b5a5SPavel Labath }
7391107b5a5SPavel Labath 
7401107b5a5SPavel Labath void
7411107b5a5SPavel Labath NativeProcessLinux::Monitor::HandleSignals()
7421107b5a5SPavel Labath {
7431107b5a5SPavel Labath     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
7441107b5a5SPavel Labath 
7451107b5a5SPavel Labath     // We don't really care about the content of the SIGCHLD siginfo structure, as we will get
7461107b5a5SPavel Labath     // all the information from waitpid(). We just need to read all the signals so that we can
7471107b5a5SPavel Labath     // sleep next time we reach select().
7481107b5a5SPavel Labath     while (true)
7491107b5a5SPavel Labath     {
7501107b5a5SPavel Labath         signalfd_siginfo info;
7511107b5a5SPavel Labath         ssize_t size = read(m_signal_fd, &info, sizeof info);
7521107b5a5SPavel Labath         if (size == -1)
7531107b5a5SPavel Labath         {
7541107b5a5SPavel Labath             if (errno == EAGAIN || errno == EWOULDBLOCK)
7551107b5a5SPavel Labath                 break; // We are done.
7561107b5a5SPavel Labath             if (errno == EINTR)
7571107b5a5SPavel Labath                 continue;
7581107b5a5SPavel Labath             if (log)
7591107b5a5SPavel Labath                 log->Printf("NativeProcessLinux::Monitor::%s reading from signalfd file descriptor failed: %s",
7601107b5a5SPavel Labath                         __FUNCTION__, strerror(errno));
7611107b5a5SPavel Labath             break;
7621107b5a5SPavel Labath         }
7631107b5a5SPavel Labath         if (size != sizeof info)
7641107b5a5SPavel Labath         {
7651107b5a5SPavel Labath             // We got incomplete information structure. This should not happen, let's just log
7661107b5a5SPavel Labath             // that.
7671107b5a5SPavel Labath             if (log)
7681107b5a5SPavel Labath                 log->Printf("NativeProcessLinux::Monitor::%s reading from signalfd file descriptor returned incomplete data: "
7691107b5a5SPavel Labath                         "structure size is %zd, read returned %zd bytes",
7701107b5a5SPavel Labath                         __FUNCTION__, sizeof info, size);
7711107b5a5SPavel Labath             break;
7721107b5a5SPavel Labath         }
7731107b5a5SPavel Labath         if (log)
7741107b5a5SPavel Labath             log->Printf("NativeProcessLinux::Monitor::%s received signal %s(%d).", __FUNCTION__,
7751107b5a5SPavel Labath                 Host::GetSignalAsCString(info.ssi_signo), info.ssi_signo);
7761107b5a5SPavel Labath     }
7771107b5a5SPavel Labath }
7781107b5a5SPavel Labath 
7791107b5a5SPavel Labath void
7801107b5a5SPavel Labath NativeProcessLinux::Monitor::HandleWait()
7811107b5a5SPavel Labath {
7821107b5a5SPavel Labath     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
7831107b5a5SPavel Labath     // Process all pending waitpid notifications.
7841107b5a5SPavel Labath     while (true)
7851107b5a5SPavel Labath     {
7861107b5a5SPavel Labath         int status = -1;
78705a1f2acSPavel Labath         ::pid_t wait_pid = waitpid(-1, &status, __WALL | __WNOTHREAD | WNOHANG);
7881107b5a5SPavel Labath 
7891107b5a5SPavel Labath         if (wait_pid == 0)
7901107b5a5SPavel Labath             break; // We are done.
7911107b5a5SPavel Labath 
7921107b5a5SPavel Labath         if (wait_pid == -1)
7931107b5a5SPavel Labath         {
7941107b5a5SPavel Labath             if (errno == EINTR)
7951107b5a5SPavel Labath                 continue;
7961107b5a5SPavel Labath 
7971107b5a5SPavel Labath             if (log)
79805a1f2acSPavel Labath               log->Printf("NativeProcessLinux::Monitor::%s waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG) failed: %s",
79905a1f2acSPavel Labath                       __FUNCTION__, strerror(errno));
8001107b5a5SPavel Labath             break;
8011107b5a5SPavel Labath         }
8021107b5a5SPavel Labath 
8031107b5a5SPavel Labath         bool exited = false;
8041107b5a5SPavel Labath         int signal = 0;
8051107b5a5SPavel Labath         int exit_status = 0;
8061107b5a5SPavel Labath         const char *status_cstr = NULL;
8071107b5a5SPavel Labath         if (WIFSTOPPED(status))
8081107b5a5SPavel Labath         {
8091107b5a5SPavel Labath             signal = WSTOPSIG(status);
8101107b5a5SPavel Labath             status_cstr = "STOPPED";
8111107b5a5SPavel Labath         }
8121107b5a5SPavel Labath         else if (WIFEXITED(status))
8131107b5a5SPavel Labath         {
8141107b5a5SPavel Labath             exit_status = WEXITSTATUS(status);
8151107b5a5SPavel Labath             status_cstr = "EXITED";
8161107b5a5SPavel Labath             exited = true;
8171107b5a5SPavel Labath         }
8181107b5a5SPavel Labath         else if (WIFSIGNALED(status))
8191107b5a5SPavel Labath         {
8201107b5a5SPavel Labath             signal = WTERMSIG(status);
8211107b5a5SPavel Labath             status_cstr = "SIGNALED";
82205a1f2acSPavel Labath             if (wait_pid == m_child_pid) {
8231107b5a5SPavel Labath                 exited = true;
8241107b5a5SPavel Labath                 exit_status = -1;
8251107b5a5SPavel Labath             }
8261107b5a5SPavel Labath         }
8271107b5a5SPavel Labath         else
8281107b5a5SPavel Labath             status_cstr = "(\?\?\?)";
8291107b5a5SPavel Labath 
8301107b5a5SPavel Labath         if (log)
83105a1f2acSPavel Labath             log->Printf("NativeProcessLinux::Monitor::%s: waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG)"
8321107b5a5SPavel Labath                 "=> pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
83305a1f2acSPavel Labath                 __FUNCTION__, wait_pid, status, status_cstr, signal, exit_status);
8341107b5a5SPavel Labath 
8351107b5a5SPavel Labath         m_native_process->MonitorCallback (wait_pid, exited, signal, exit_status);
8361107b5a5SPavel Labath     }
8371107b5a5SPavel Labath }
8381107b5a5SPavel Labath 
8391107b5a5SPavel Labath bool
8401107b5a5SPavel Labath NativeProcessLinux::Monitor::HandleCommands()
8411107b5a5SPavel Labath {
8421107b5a5SPavel Labath     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
8431107b5a5SPavel Labath 
8441107b5a5SPavel Labath     while (true)
8451107b5a5SPavel Labath     {
8461107b5a5SPavel Labath         char command = 0;
8471107b5a5SPavel Labath         ssize_t size = read(m_pipefd[READ], &command, sizeof command);
8481107b5a5SPavel Labath         if (size == -1)
8491107b5a5SPavel Labath         {
8501107b5a5SPavel Labath             if (errno == EAGAIN || errno == EWOULDBLOCK)
8511107b5a5SPavel Labath                 return false;
8521107b5a5SPavel Labath             if (errno == EINTR)
8531107b5a5SPavel Labath                 continue;
8541107b5a5SPavel Labath             if (log)
8551107b5a5SPavel Labath                 log->Printf("NativeProcessLinux::Monitor::%s exiting because read from command file descriptor failed: %s", __FUNCTION__, strerror(errno));
8561107b5a5SPavel Labath             return true;
8571107b5a5SPavel Labath         }
8581107b5a5SPavel Labath         if (size == 0) // end of file - write end closed
8591107b5a5SPavel Labath         {
8601107b5a5SPavel Labath             if (log)
8611107b5a5SPavel Labath                 log->Printf("NativeProcessLinux::Monitor::%s exit command received, exiting...", __FUNCTION__);
86245f5cb31SPavel Labath             assert(m_operation_nesting_level == 0 && "Unbalanced begin/end block commands detected");
8631107b5a5SPavel Labath             return true; // We are done.
8641107b5a5SPavel Labath         }
865bd7cbc5aSPavel Labath 
866bd7cbc5aSPavel Labath         switch (command)
867bd7cbc5aSPavel Labath         {
868bd7cbc5aSPavel Labath         case operation_command:
869bd7cbc5aSPavel Labath             m_operation->Execute(m_native_process);
87045f5cb31SPavel Labath             break;
87145f5cb31SPavel Labath         case begin_block_command:
87245f5cb31SPavel Labath             ++m_operation_nesting_level;
87345f5cb31SPavel Labath             break;
87445f5cb31SPavel Labath         case end_block_command:
87545f5cb31SPavel Labath             assert(m_operation_nesting_level > 0);
87645f5cb31SPavel Labath             --m_operation_nesting_level;
877bd7cbc5aSPavel Labath             break;
878bd7cbc5aSPavel Labath         default:
8791107b5a5SPavel Labath             if (log)
8801107b5a5SPavel Labath                 log->Printf("NativeProcessLinux::Monitor::%s received unknown command '%c'",
8811107b5a5SPavel Labath                         __FUNCTION__, command);
8821107b5a5SPavel Labath         }
88345f5cb31SPavel Labath 
88445f5cb31SPavel Labath         // notify calling thread that the command has been processed
88545f5cb31SPavel Labath         sem_post(&m_operation_sem);
8861107b5a5SPavel Labath     }
887bd7cbc5aSPavel Labath }
8881107b5a5SPavel Labath 
8891107b5a5SPavel Labath void
8901107b5a5SPavel Labath NativeProcessLinux::Monitor::MainLoop()
8911107b5a5SPavel Labath {
892bd7cbc5aSPavel Labath     ::pid_t child_pid = (*m_initial_operation_up)(m_operation_error);
893bd7cbc5aSPavel Labath     m_initial_operation_up.reset();
89405a1f2acSPavel Labath     m_child_pid = child_pid;
895bd7cbc5aSPavel Labath     sem_post(&m_operation_sem);
896bd7cbc5aSPavel Labath 
8971107b5a5SPavel Labath     while (true)
8981107b5a5SPavel Labath     {
8991107b5a5SPavel Labath         fd_set fds;
9001107b5a5SPavel Labath         FD_ZERO(&fds);
90145f5cb31SPavel Labath         // Only process waitpid events if we are outside of an operation block. Any pending
90245f5cb31SPavel Labath         // events will be processed after we leave the block.
90345f5cb31SPavel Labath         if (m_operation_nesting_level == 0)
9041107b5a5SPavel Labath             FD_SET(m_signal_fd, &fds);
9051107b5a5SPavel Labath         FD_SET(m_pipefd[READ], &fds);
9061107b5a5SPavel Labath 
9071107b5a5SPavel Labath         int max_fd = std::max(m_signal_fd, m_pipefd[READ]) + 1;
9081107b5a5SPavel Labath         int r = select(max_fd, &fds, nullptr, nullptr, nullptr);
9091107b5a5SPavel Labath         if (r < 0)
9101107b5a5SPavel Labath         {
9111107b5a5SPavel Labath             Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
9121107b5a5SPavel Labath             if (log)
9131107b5a5SPavel Labath                 log->Printf("NativeProcessLinux::Monitor::%s exiting because select failed: %s",
9141107b5a5SPavel Labath                         __FUNCTION__, strerror(errno));
9151107b5a5SPavel Labath             return;
9161107b5a5SPavel Labath         }
9171107b5a5SPavel Labath 
9181107b5a5SPavel Labath         if (FD_ISSET(m_pipefd[READ], &fds))
9191107b5a5SPavel Labath         {
9201107b5a5SPavel Labath             if (HandleCommands())
9211107b5a5SPavel Labath                 return;
9221107b5a5SPavel Labath         }
9231107b5a5SPavel Labath 
9241107b5a5SPavel Labath         if (FD_ISSET(m_signal_fd, &fds))
9251107b5a5SPavel Labath         {
9261107b5a5SPavel Labath             HandleSignals();
9271107b5a5SPavel Labath             HandleWait();
9281107b5a5SPavel Labath         }
9291107b5a5SPavel Labath     }
9301107b5a5SPavel Labath }
9311107b5a5SPavel Labath 
932bd7cbc5aSPavel Labath Error
93345f5cb31SPavel Labath NativeProcessLinux::Monitor::WaitForAck()
934bd7cbc5aSPavel Labath {
935bd7cbc5aSPavel Labath     Error error;
936bd7cbc5aSPavel Labath     while (sem_wait(&m_operation_sem) != 0)
937bd7cbc5aSPavel Labath     {
938bd7cbc5aSPavel Labath         if (errno == EINTR)
939bd7cbc5aSPavel Labath             continue;
940bd7cbc5aSPavel Labath 
941bd7cbc5aSPavel Labath         error.SetErrorToErrno();
942bd7cbc5aSPavel Labath         return error;
943bd7cbc5aSPavel Labath     }
944bd7cbc5aSPavel Labath 
945bd7cbc5aSPavel Labath     return m_operation_error;
946bd7cbc5aSPavel Labath }
947bd7cbc5aSPavel Labath 
9481107b5a5SPavel Labath void *
9491107b5a5SPavel Labath NativeProcessLinux::Monitor::RunMonitor(void *arg)
9501107b5a5SPavel Labath {
9511107b5a5SPavel Labath     static_cast<Monitor *>(arg)->MainLoop();
9521107b5a5SPavel Labath     return nullptr;
9531107b5a5SPavel Labath }
9541107b5a5SPavel Labath 
9551107b5a5SPavel Labath 
956bd7cbc5aSPavel Labath NativeProcessLinux::LaunchArgs::LaunchArgs(Module *module,
957af245d11STodd Fiala                                        char const **argv,
958af245d11STodd Fiala                                        char const **envp,
95975f47c3aSTodd Fiala                                        const std::string &stdin_path,
96075f47c3aSTodd Fiala                                        const std::string &stdout_path,
96175f47c3aSTodd Fiala                                        const std::string &stderr_path,
9620bce1b67STodd Fiala                                        const char *working_dir,
963db264a6dSTamas Berghammer                                        const ProcessLaunchInfo &launch_info)
964bd7cbc5aSPavel Labath     : m_module(module),
965af245d11STodd Fiala       m_argv(argv),
966af245d11STodd Fiala       m_envp(envp),
967af245d11STodd Fiala       m_stdin_path(stdin_path),
968af245d11STodd Fiala       m_stdout_path(stdout_path),
969af245d11STodd Fiala       m_stderr_path(stderr_path),
9700bce1b67STodd Fiala       m_working_dir(working_dir),
9710bce1b67STodd Fiala       m_launch_info(launch_info)
9720bce1b67STodd Fiala {
9730bce1b67STodd Fiala }
974af245d11STodd Fiala 
975af245d11STodd Fiala NativeProcessLinux::LaunchArgs::~LaunchArgs()
976af245d11STodd Fiala { }
977af245d11STodd Fiala 
978af245d11STodd Fiala // -----------------------------------------------------------------------------
979af245d11STodd Fiala // Public Static Methods
980af245d11STodd Fiala // -----------------------------------------------------------------------------
981af245d11STodd Fiala 
982db264a6dSTamas Berghammer Error
983af245d11STodd Fiala NativeProcessLinux::LaunchProcess (
984db264a6dSTamas Berghammer     Module *exe_module,
985db264a6dSTamas Berghammer     ProcessLaunchInfo &launch_info,
986db264a6dSTamas Berghammer     NativeProcessProtocol::NativeDelegate &native_delegate,
987af245d11STodd Fiala     NativeProcessProtocolSP &native_process_sp)
988af245d11STodd Fiala {
989af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
990af245d11STodd Fiala 
991af245d11STodd Fiala     Error error;
992af245d11STodd Fiala 
993af245d11STodd Fiala     // Verify the working directory is valid if one was specified.
994af245d11STodd Fiala     const char* working_dir = launch_info.GetWorkingDirectory ();
995af245d11STodd Fiala     if (working_dir)
996af245d11STodd Fiala     {
997af245d11STodd Fiala       FileSpec working_dir_fs (working_dir, true);
998af245d11STodd Fiala       if (!working_dir_fs || working_dir_fs.GetFileType () != FileSpec::eFileTypeDirectory)
999af245d11STodd Fiala       {
1000af245d11STodd Fiala           error.SetErrorStringWithFormat ("No such file or directory: %s", working_dir);
1001af245d11STodd Fiala           return error;
1002af245d11STodd Fiala       }
1003af245d11STodd Fiala     }
1004af245d11STodd Fiala 
1005db264a6dSTamas Berghammer     const FileAction *file_action;
1006af245d11STodd Fiala 
1007af245d11STodd Fiala     // Default of NULL will mean to use existing open file descriptors.
100875f47c3aSTodd Fiala     std::string stdin_path;
100975f47c3aSTodd Fiala     std::string stdout_path;
101075f47c3aSTodd Fiala     std::string stderr_path;
1011af245d11STodd Fiala 
1012af245d11STodd Fiala     file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
101375f47c3aSTodd Fiala     if (file_action)
101475f47c3aSTodd Fiala         stdin_path = file_action->GetPath ();
1015af245d11STodd Fiala 
1016af245d11STodd Fiala     file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
101775f47c3aSTodd Fiala     if (file_action)
101875f47c3aSTodd Fiala         stdout_path = file_action->GetPath ();
1019af245d11STodd Fiala 
1020af245d11STodd Fiala     file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
102175f47c3aSTodd Fiala     if (file_action)
102275f47c3aSTodd Fiala         stderr_path = file_action->GetPath ();
102375f47c3aSTodd Fiala 
102475f47c3aSTodd Fiala     if (log)
102575f47c3aSTodd Fiala     {
102675f47c3aSTodd Fiala         if (!stdin_path.empty ())
102775f47c3aSTodd Fiala             log->Printf ("NativeProcessLinux::%s setting STDIN to '%s'", __FUNCTION__, stdin_path.c_str ());
102875f47c3aSTodd Fiala         else
102975f47c3aSTodd Fiala             log->Printf ("NativeProcessLinux::%s leaving STDIN as is", __FUNCTION__);
103075f47c3aSTodd Fiala 
103175f47c3aSTodd Fiala         if (!stdout_path.empty ())
103275f47c3aSTodd Fiala             log->Printf ("NativeProcessLinux::%s setting STDOUT to '%s'", __FUNCTION__, stdout_path.c_str ());
103375f47c3aSTodd Fiala         else
103475f47c3aSTodd Fiala             log->Printf ("NativeProcessLinux::%s leaving STDOUT as is", __FUNCTION__);
103575f47c3aSTodd Fiala 
103675f47c3aSTodd Fiala         if (!stderr_path.empty ())
103775f47c3aSTodd Fiala             log->Printf ("NativeProcessLinux::%s setting STDERR to '%s'", __FUNCTION__, stderr_path.c_str ());
103875f47c3aSTodd Fiala         else
103975f47c3aSTodd Fiala             log->Printf ("NativeProcessLinux::%s leaving STDERR as is", __FUNCTION__);
104075f47c3aSTodd Fiala     }
1041af245d11STodd Fiala 
1042af245d11STodd Fiala     // Create the NativeProcessLinux in launch mode.
1043af245d11STodd Fiala     native_process_sp.reset (new NativeProcessLinux ());
1044af245d11STodd Fiala 
1045af245d11STodd Fiala     if (log)
1046af245d11STodd Fiala     {
1047af245d11STodd Fiala         int i = 0;
1048af245d11STodd Fiala         for (const char **args = launch_info.GetArguments ().GetConstArgumentVector (); *args; ++args, ++i)
1049af245d11STodd Fiala         {
1050af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s arg %d: \"%s\"", __FUNCTION__, i, *args ? *args : "nullptr");
1051af245d11STodd Fiala             ++i;
1052af245d11STodd Fiala         }
1053af245d11STodd Fiala     }
1054af245d11STodd Fiala 
1055af245d11STodd Fiala     if (!native_process_sp->RegisterNativeDelegate (native_delegate))
1056af245d11STodd Fiala     {
1057af245d11STodd Fiala         native_process_sp.reset ();
1058af245d11STodd Fiala         error.SetErrorStringWithFormat ("failed to register the native delegate");
1059af245d11STodd Fiala         return error;
1060af245d11STodd Fiala     }
1061af245d11STodd Fiala 
1062cb84eebbSTamas Berghammer     std::static_pointer_cast<NativeProcessLinux> (native_process_sp)->LaunchInferior (
1063af245d11STodd Fiala             exe_module,
1064af245d11STodd Fiala             launch_info.GetArguments ().GetConstArgumentVector (),
1065af245d11STodd Fiala             launch_info.GetEnvironmentEntries ().GetConstArgumentVector (),
1066af245d11STodd Fiala             stdin_path,
1067af245d11STodd Fiala             stdout_path,
1068af245d11STodd Fiala             stderr_path,
1069af245d11STodd Fiala             working_dir,
10700bce1b67STodd Fiala             launch_info,
1071af245d11STodd Fiala             error);
1072af245d11STodd Fiala 
1073af245d11STodd Fiala     if (error.Fail ())
1074af245d11STodd Fiala     {
1075af245d11STodd Fiala         native_process_sp.reset ();
1076af245d11STodd Fiala         if (log)
1077af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s failed to launch process: %s", __FUNCTION__, error.AsCString ());
1078af245d11STodd Fiala         return error;
1079af245d11STodd Fiala     }
1080af245d11STodd Fiala 
1081af245d11STodd Fiala     launch_info.SetProcessID (native_process_sp->GetID ());
1082af245d11STodd Fiala 
1083af245d11STodd Fiala     return error;
1084af245d11STodd Fiala }
1085af245d11STodd Fiala 
1086db264a6dSTamas Berghammer Error
1087af245d11STodd Fiala NativeProcessLinux::AttachToProcess (
1088af245d11STodd Fiala     lldb::pid_t pid,
1089db264a6dSTamas Berghammer     NativeProcessProtocol::NativeDelegate &native_delegate,
1090af245d11STodd Fiala     NativeProcessProtocolSP &native_process_sp)
1091af245d11STodd Fiala {
1092af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1093af245d11STodd Fiala     if (log && log->GetMask ().Test (POSIX_LOG_VERBOSE))
1094af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
1095af245d11STodd Fiala 
1096af245d11STodd Fiala     // Grab the current platform architecture.  This should be Linux,
1097af245d11STodd Fiala     // since this code is only intended to run on a Linux host.
1098615eb7e6SGreg Clayton     PlatformSP platform_sp (Platform::GetHostPlatform ());
1099af245d11STodd Fiala     if (!platform_sp)
1100af245d11STodd Fiala         return Error("failed to get a valid default platform");
1101af245d11STodd Fiala 
1102af245d11STodd Fiala     // Retrieve the architecture for the running process.
1103af245d11STodd Fiala     ArchSpec process_arch;
1104af245d11STodd Fiala     Error error = ResolveProcessArchitecture (pid, *platform_sp.get (), process_arch);
1105af245d11STodd Fiala     if (!error.Success ())
1106af245d11STodd Fiala         return error;
1107af245d11STodd Fiala 
11081339b5e8SOleksiy Vyalov     std::shared_ptr<NativeProcessLinux> native_process_linux_sp (new NativeProcessLinux ());
1109af245d11STodd Fiala 
11101339b5e8SOleksiy Vyalov     if (!native_process_linux_sp->RegisterNativeDelegate (native_delegate))
1111af245d11STodd Fiala     {
1112af245d11STodd Fiala         error.SetErrorStringWithFormat ("failed to register the native delegate");
1113af245d11STodd Fiala         return error;
1114af245d11STodd Fiala     }
1115af245d11STodd Fiala 
11161339b5e8SOleksiy Vyalov     native_process_linux_sp->AttachToInferior (pid, error);
1117af245d11STodd Fiala     if (!error.Success ())
1118af245d11STodd Fiala         return error;
1119af245d11STodd Fiala 
11201339b5e8SOleksiy Vyalov     native_process_sp = native_process_linux_sp;
1121af245d11STodd Fiala     return error;
1122af245d11STodd Fiala }
1123af245d11STodd Fiala 
1124af245d11STodd Fiala // -----------------------------------------------------------------------------
1125af245d11STodd Fiala // Public Instance Methods
1126af245d11STodd Fiala // -----------------------------------------------------------------------------
1127af245d11STodd Fiala 
1128af245d11STodd Fiala NativeProcessLinux::NativeProcessLinux () :
1129af245d11STodd Fiala     NativeProcessProtocol (LLDB_INVALID_PROCESS_ID),
1130af245d11STodd Fiala     m_arch (),
1131af245d11STodd Fiala     m_supports_mem_region (eLazyBoolCalculate),
1132af245d11STodd Fiala     m_mem_region_cache (),
11338c8ff7afSPavel Labath     m_mem_region_cache_mutex ()
1134af245d11STodd Fiala {
1135af245d11STodd Fiala }
1136af245d11STodd Fiala 
1137af245d11STodd Fiala //------------------------------------------------------------------------------
1138bd7cbc5aSPavel Labath // NativeProcessLinux spawns a new thread which performs all operations on the inferior process.
1139bd7cbc5aSPavel Labath // Refer to Monitor and Operation classes to see why this is necessary.
1140bd7cbc5aSPavel Labath //------------------------------------------------------------------------------
1141af245d11STodd Fiala void
1142af245d11STodd Fiala NativeProcessLinux::LaunchInferior (
1143af245d11STodd Fiala     Module *module,
1144af245d11STodd Fiala     const char *argv[],
1145af245d11STodd Fiala     const char *envp[],
114675f47c3aSTodd Fiala     const std::string &stdin_path,
114775f47c3aSTodd Fiala     const std::string &stdout_path,
114875f47c3aSTodd Fiala     const std::string &stderr_path,
1149af245d11STodd Fiala     const char *working_dir,
1150db264a6dSTamas Berghammer     const ProcessLaunchInfo &launch_info,
1151db264a6dSTamas Berghammer     Error &error)
1152af245d11STodd Fiala {
1153af245d11STodd Fiala     if (module)
1154af245d11STodd Fiala         m_arch = module->GetArchitecture ();
1155af245d11STodd Fiala 
1156af245d11STodd Fiala     SetState (eStateLaunching);
1157af245d11STodd Fiala 
1158af245d11STodd Fiala     std::unique_ptr<LaunchArgs> args(
1159af245d11STodd Fiala         new LaunchArgs(
1160bd7cbc5aSPavel Labath             module, argv, envp,
1161af245d11STodd Fiala             stdin_path, stdout_path, stderr_path,
11620bce1b67STodd Fiala             working_dir, launch_info));
1163af245d11STodd Fiala 
1164bd7cbc5aSPavel Labath     StartMonitorThread ([&] (Error &e) { return Launch(args.get(), e); }, error);
1165af245d11STodd Fiala     if (!error.Success ())
1166af245d11STodd Fiala         return;
1167af245d11STodd Fiala }
1168af245d11STodd Fiala 
1169af245d11STodd Fiala void
1170db264a6dSTamas Berghammer NativeProcessLinux::AttachToInferior (lldb::pid_t pid, Error &error)
1171af245d11STodd Fiala {
1172af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1173af245d11STodd Fiala     if (log)
1174af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
1175af245d11STodd Fiala 
1176af245d11STodd Fiala     // We can use the Host for everything except the ResolveExecutable portion.
1177615eb7e6SGreg Clayton     PlatformSP platform_sp = Platform::GetHostPlatform ();
1178af245d11STodd Fiala     if (!platform_sp)
1179af245d11STodd Fiala     {
1180af245d11STodd Fiala         if (log)
1181af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): no default platform set", __FUNCTION__, pid);
1182af245d11STodd Fiala         error.SetErrorString ("no default platform available");
118350d60be3SShawn Best         return;
1184af245d11STodd Fiala     }
1185af245d11STodd Fiala 
1186af245d11STodd Fiala     // Gather info about the process.
1187af245d11STodd Fiala     ProcessInstanceInfo process_info;
118850d60be3SShawn Best     if (!platform_sp->GetProcessInfo (pid, process_info))
118950d60be3SShawn Best     {
119050d60be3SShawn Best         if (log)
119150d60be3SShawn Best             log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): failed to get process info", __FUNCTION__, pid);
119250d60be3SShawn Best         error.SetErrorString ("failed to get process info");
119350d60be3SShawn Best         return;
119450d60be3SShawn Best     }
1195af245d11STodd Fiala 
1196af245d11STodd Fiala     // Resolve the executable module
1197af245d11STodd Fiala     ModuleSP exe_module_sp;
1198af245d11STodd Fiala     FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
1199e56f6dceSChaoren Lin     ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
12006edef204SOleksiy Vyalov     error = platform_sp->ResolveExecutable(exe_module_spec, exe_module_sp,
1201af245d11STodd Fiala                                            executable_search_paths.GetSize() ? &executable_search_paths : NULL);
1202af245d11STodd Fiala     if (!error.Success())
1203af245d11STodd Fiala         return;
1204af245d11STodd Fiala 
1205af245d11STodd Fiala     // Set the architecture to the exe architecture.
1206af245d11STodd Fiala     m_arch = exe_module_sp->GetArchitecture();
1207af245d11STodd Fiala     if (log)
1208af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
1209af245d11STodd Fiala 
1210af245d11STodd Fiala     m_pid = pid;
1211af245d11STodd Fiala     SetState(eStateAttaching);
1212af245d11STodd Fiala 
1213bd7cbc5aSPavel Labath     StartMonitorThread ([=] (Error &e) { return Attach(pid, e); }, error);
1214af245d11STodd Fiala     if (!error.Success ())
1215af245d11STodd Fiala         return;
1216af245d11STodd Fiala }
1217af245d11STodd Fiala 
12188bc34f4dSOleksiy Vyalov void
12198bc34f4dSOleksiy Vyalov NativeProcessLinux::Terminate ()
1220af245d11STodd Fiala {
122145f5cb31SPavel Labath     m_monitor_up->Terminate();
1222af245d11STodd Fiala }
1223af245d11STodd Fiala 
1224bd7cbc5aSPavel Labath ::pid_t
1225bd7cbc5aSPavel Labath NativeProcessLinux::Launch(LaunchArgs *args, Error &error)
1226af245d11STodd Fiala {
12270bce1b67STodd Fiala     assert (args && "null args");
1228af245d11STodd Fiala 
1229af245d11STodd Fiala     const char **argv = args->m_argv;
1230af245d11STodd Fiala     const char **envp = args->m_envp;
1231af245d11STodd Fiala     const char *working_dir = args->m_working_dir;
1232af245d11STodd Fiala 
1233af245d11STodd Fiala     lldb_utility::PseudoTerminal terminal;
1234af245d11STodd Fiala     const size_t err_len = 1024;
1235af245d11STodd Fiala     char err_str[err_len];
1236af245d11STodd Fiala     lldb::pid_t pid;
1237af245d11STodd Fiala     NativeThreadProtocolSP thread_sp;
1238af245d11STodd Fiala 
1239af245d11STodd Fiala     lldb::ThreadSP inferior;
1240af245d11STodd Fiala 
1241af245d11STodd Fiala     // Propagate the environment if one is not supplied.
1242af245d11STodd Fiala     if (envp == NULL || envp[0] == NULL)
1243af245d11STodd Fiala         envp = const_cast<const char **>(environ);
1244af245d11STodd Fiala 
1245af245d11STodd Fiala     if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
1246af245d11STodd Fiala     {
1247bd7cbc5aSPavel Labath         error.SetErrorToGenericError();
1248bd7cbc5aSPavel Labath         error.SetErrorStringWithFormat("Process fork failed: %s", err_str);
1249bd7cbc5aSPavel Labath         return -1;
1250af245d11STodd Fiala     }
1251af245d11STodd Fiala 
1252af245d11STodd Fiala     // Recognized child exit status codes.
1253af245d11STodd Fiala     enum {
1254af245d11STodd Fiala         ePtraceFailed = 1,
1255af245d11STodd Fiala         eDupStdinFailed,
1256af245d11STodd Fiala         eDupStdoutFailed,
1257af245d11STodd Fiala         eDupStderrFailed,
1258af245d11STodd Fiala         eChdirFailed,
1259af245d11STodd Fiala         eExecFailed,
1260af245d11STodd Fiala         eSetGidFailed
1261af245d11STodd Fiala     };
1262af245d11STodd Fiala 
1263af245d11STodd Fiala     // Child process.
1264af245d11STodd Fiala     if (pid == 0)
1265af245d11STodd Fiala     {
126675f47c3aSTodd Fiala         // FIXME consider opening a pipe between parent/child and have this forked child
126775f47c3aSTodd Fiala         // send log info to parent re: launch status, in place of the log lines removed here.
1268af245d11STodd Fiala 
126975f47c3aSTodd Fiala         // Start tracing this child that is about to exec.
1270068f8a7eSTamas Berghammer         NativeProcessLinux::PtraceWrapper(PTRACE_TRACEME, 0, nullptr, nullptr, 0, error);
1271bd7cbc5aSPavel Labath         if (error.Fail())
1272af245d11STodd Fiala             exit(ePtraceFailed);
1273af245d11STodd Fiala 
1274493c3a12SPavel Labath         // terminal has already dupped the tty descriptors to stdin/out/err.
1275493c3a12SPavel Labath         // This closes original fd from which they were copied (and avoids
1276493c3a12SPavel Labath         // leaking descriptors to the debugged process.
1277493c3a12SPavel Labath         terminal.CloseSlaveFileDescriptor();
1278493c3a12SPavel Labath 
1279af245d11STodd Fiala         // Do not inherit setgid powers.
1280af245d11STodd Fiala         if (setgid(getgid()) != 0)
1281af245d11STodd Fiala             exit(eSetGidFailed);
1282af245d11STodd Fiala 
1283af245d11STodd Fiala         // Attempt to have our own process group.
1284af245d11STodd Fiala         if (setpgid(0, 0) != 0)
1285af245d11STodd Fiala         {
128675f47c3aSTodd Fiala             // FIXME log that this failed. This is common.
1287af245d11STodd Fiala             // Don't allow this to prevent an inferior exec.
1288af245d11STodd Fiala         }
1289af245d11STodd Fiala 
1290af245d11STodd Fiala         // Dup file descriptors if needed.
129175f47c3aSTodd Fiala         if (!args->m_stdin_path.empty ())
129275f47c3aSTodd Fiala             if (!DupDescriptor(args->m_stdin_path.c_str (), STDIN_FILENO, O_RDONLY))
1293af245d11STodd Fiala                 exit(eDupStdinFailed);
1294af245d11STodd Fiala 
129575f47c3aSTodd Fiala         if (!args->m_stdout_path.empty ())
129614f4476aSTamas Berghammer             if (!DupDescriptor(args->m_stdout_path.c_str (), STDOUT_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
1297af245d11STodd Fiala                 exit(eDupStdoutFailed);
1298af245d11STodd Fiala 
129975f47c3aSTodd Fiala         if (!args->m_stderr_path.empty ())
130014f4476aSTamas Berghammer             if (!DupDescriptor(args->m_stderr_path.c_str (), STDERR_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
1301af245d11STodd Fiala                 exit(eDupStderrFailed);
1302af245d11STodd Fiala 
13039cf4f2c2SChaoren Lin         // Close everything besides stdin, stdout, and stderr that has no file
13049cf4f2c2SChaoren Lin         // action to avoid leaking
13059cf4f2c2SChaoren Lin         for (int fd = 3; fd < sysconf(_SC_OPEN_MAX); ++fd)
13069cf4f2c2SChaoren Lin             if (!args->m_launch_info.GetFileActionForFD(fd))
13079cf4f2c2SChaoren Lin                 close(fd);
13089cf4f2c2SChaoren Lin 
1309af245d11STodd Fiala         // Change working directory
1310af245d11STodd Fiala         if (working_dir != NULL && working_dir[0])
1311af245d11STodd Fiala           if (0 != ::chdir(working_dir))
1312af245d11STodd Fiala               exit(eChdirFailed);
1313af245d11STodd Fiala 
13140bce1b67STodd Fiala         // Disable ASLR if requested.
13150bce1b67STodd Fiala         if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR))
13160bce1b67STodd Fiala         {
13170bce1b67STodd Fiala             const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
13180bce1b67STodd Fiala             if (old_personality == -1)
13190bce1b67STodd Fiala             {
132075f47c3aSTodd Fiala                 // Can't retrieve Linux personality.  Cannot disable ASLR.
13210bce1b67STodd Fiala             }
13220bce1b67STodd Fiala             else
13230bce1b67STodd Fiala             {
13240bce1b67STodd Fiala                 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality);
13250bce1b67STodd Fiala                 if (new_personality == -1)
13260bce1b67STodd Fiala                 {
132775f47c3aSTodd Fiala                     // Disabling ASLR failed.
13280bce1b67STodd Fiala                 }
13290bce1b67STodd Fiala                 else
13300bce1b67STodd Fiala                 {
133175f47c3aSTodd Fiala                     // Disabling ASLR succeeded.
13320bce1b67STodd Fiala                 }
13330bce1b67STodd Fiala             }
13340bce1b67STodd Fiala         }
13350bce1b67STodd Fiala 
133675f47c3aSTodd Fiala         // Execute.  We should never return...
1337af245d11STodd Fiala         execve(argv[0],
1338af245d11STodd Fiala                const_cast<char *const *>(argv),
1339af245d11STodd Fiala                const_cast<char *const *>(envp));
134075f47c3aSTodd Fiala 
134175f47c3aSTodd Fiala         // ...unless exec fails.  In which case we definitely need to end the child here.
1342af245d11STodd Fiala         exit(eExecFailed);
1343af245d11STodd Fiala     }
1344af245d11STodd Fiala 
134575f47c3aSTodd Fiala     //
134675f47c3aSTodd Fiala     // This is the parent code here.
134775f47c3aSTodd Fiala     //
134875f47c3aSTodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
134975f47c3aSTodd Fiala 
1350af245d11STodd Fiala     // Wait for the child process to trap on its call to execve.
1351af245d11STodd Fiala     ::pid_t wpid;
1352af245d11STodd Fiala     int status;
1353af245d11STodd Fiala     if ((wpid = waitpid(pid, &status, 0)) < 0)
1354af245d11STodd Fiala     {
1355bd7cbc5aSPavel Labath         error.SetErrorToErrno();
1356af245d11STodd Fiala         if (log)
1357bd7cbc5aSPavel Labath             log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s",
1358bd7cbc5aSPavel Labath                     __FUNCTION__, error.AsCString ());
1359af245d11STodd Fiala 
1360af245d11STodd Fiala         // Mark the inferior as invalid.
1361af245d11STodd Fiala         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
1362bd7cbc5aSPavel Labath         SetState (StateType::eStateInvalid);
1363af245d11STodd Fiala 
1364bd7cbc5aSPavel Labath         return -1;
1365af245d11STodd Fiala     }
1366af245d11STodd Fiala     else if (WIFEXITED(status))
1367af245d11STodd Fiala     {
1368af245d11STodd Fiala         // open, dup or execve likely failed for some reason.
1369bd7cbc5aSPavel Labath         error.SetErrorToGenericError();
1370af245d11STodd Fiala         switch (WEXITSTATUS(status))
1371af245d11STodd Fiala         {
1372af245d11STodd Fiala             case ePtraceFailed:
1373bd7cbc5aSPavel Labath                 error.SetErrorString("Child ptrace failed.");
1374af245d11STodd Fiala                 break;
1375af245d11STodd Fiala             case eDupStdinFailed:
1376bd7cbc5aSPavel Labath                 error.SetErrorString("Child open stdin failed.");
1377af245d11STodd Fiala                 break;
1378af245d11STodd Fiala             case eDupStdoutFailed:
1379bd7cbc5aSPavel Labath                 error.SetErrorString("Child open stdout failed.");
1380af245d11STodd Fiala                 break;
1381af245d11STodd Fiala             case eDupStderrFailed:
1382bd7cbc5aSPavel Labath                 error.SetErrorString("Child open stderr failed.");
1383af245d11STodd Fiala                 break;
1384af245d11STodd Fiala             case eChdirFailed:
1385bd7cbc5aSPavel Labath                 error.SetErrorString("Child failed to set working directory.");
1386af245d11STodd Fiala                 break;
1387af245d11STodd Fiala             case eExecFailed:
1388bd7cbc5aSPavel Labath                 error.SetErrorString("Child exec failed.");
1389af245d11STodd Fiala                 break;
1390af245d11STodd Fiala             case eSetGidFailed:
1391bd7cbc5aSPavel Labath                 error.SetErrorString("Child setgid failed.");
1392af245d11STodd Fiala                 break;
1393af245d11STodd Fiala             default:
1394bd7cbc5aSPavel Labath                 error.SetErrorString("Child returned unknown exit status.");
1395af245d11STodd Fiala                 break;
1396af245d11STodd Fiala         }
1397af245d11STodd Fiala 
1398af245d11STodd Fiala         if (log)
1399af245d11STodd Fiala         {
1400af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
1401af245d11STodd Fiala                     __FUNCTION__,
1402af245d11STodd Fiala                     WEXITSTATUS(status));
1403af245d11STodd Fiala         }
1404af245d11STodd Fiala 
1405af245d11STodd Fiala         // Mark the inferior as invalid.
1406af245d11STodd Fiala         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
1407bd7cbc5aSPavel Labath         SetState (StateType::eStateInvalid);
1408af245d11STodd Fiala 
1409bd7cbc5aSPavel Labath         return -1;
1410af245d11STodd Fiala     }
1411af245d11STodd Fiala     assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
1412af245d11STodd Fiala            "Could not sync with inferior process.");
1413af245d11STodd Fiala 
1414af245d11STodd Fiala     if (log)
1415af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
1416af245d11STodd Fiala 
1417bd7cbc5aSPavel Labath     error = SetDefaultPtraceOpts(pid);
1418bd7cbc5aSPavel Labath     if (error.Fail())
1419af245d11STodd Fiala     {
1420af245d11STodd Fiala         if (log)
1421af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
1422bd7cbc5aSPavel Labath                     __FUNCTION__, error.AsCString ());
1423af245d11STodd Fiala 
1424af245d11STodd Fiala         // Mark the inferior as invalid.
1425af245d11STodd Fiala         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
1426bd7cbc5aSPavel Labath         SetState (StateType::eStateInvalid);
1427af245d11STodd Fiala 
1428bd7cbc5aSPavel Labath         return -1;
1429af245d11STodd Fiala     }
1430af245d11STodd Fiala 
1431af245d11STodd Fiala     // Release the master terminal descriptor and pass it off to the
1432af245d11STodd Fiala     // NativeProcessLinux instance.  Similarly stash the inferior pid.
1433bd7cbc5aSPavel Labath     m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1434bd7cbc5aSPavel Labath     m_pid = pid;
1435af245d11STodd Fiala 
1436af245d11STodd Fiala     // Set the terminal fd to be in non blocking mode (it simplifies the
1437af245d11STodd Fiala     // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1438af245d11STodd Fiala     // descriptor to read from).
1439bd7cbc5aSPavel Labath     error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
1440bd7cbc5aSPavel Labath     if (error.Fail())
1441af245d11STodd Fiala     {
1442af245d11STodd Fiala         if (log)
1443af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
1444bd7cbc5aSPavel Labath                     __FUNCTION__, error.AsCString ());
1445af245d11STodd Fiala 
1446af245d11STodd Fiala         // Mark the inferior as invalid.
1447af245d11STodd Fiala         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
1448bd7cbc5aSPavel Labath         SetState (StateType::eStateInvalid);
1449af245d11STodd Fiala 
1450bd7cbc5aSPavel Labath         return -1;
1451af245d11STodd Fiala     }
1452af245d11STodd Fiala 
1453af245d11STodd Fiala     if (log)
1454af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
1455af245d11STodd Fiala 
1456bd7cbc5aSPavel Labath     thread_sp = AddThread (pid);
1457af245d11STodd Fiala     assert (thread_sp && "AddThread() returned a nullptr thread");
1458cb84eebbSTamas Berghammer     std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
14591dbc6c9cSPavel Labath     ThreadWasCreated(pid);
1460af245d11STodd Fiala 
1461af245d11STodd Fiala     // Let our process instance know the thread has stopped.
1462bd7cbc5aSPavel Labath     SetCurrentThreadID (thread_sp->GetID ());
1463bd7cbc5aSPavel Labath     SetState (StateType::eStateStopped);
1464af245d11STodd Fiala 
1465af245d11STodd Fiala     if (log)
1466af245d11STodd Fiala     {
1467bd7cbc5aSPavel Labath         if (error.Success ())
1468af245d11STodd Fiala         {
1469af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
1470af245d11STodd Fiala         }
1471af245d11STodd Fiala         else
1472af245d11STodd Fiala         {
1473af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior launching failed: %s",
1474bd7cbc5aSPavel Labath                 __FUNCTION__, error.AsCString ());
1475bd7cbc5aSPavel Labath             return -1;
1476af245d11STodd Fiala         }
1477af245d11STodd Fiala     }
1478bd7cbc5aSPavel Labath     return pid;
1479af245d11STodd Fiala }
1480af245d11STodd Fiala 
1481bd7cbc5aSPavel Labath ::pid_t
1482bd7cbc5aSPavel Labath NativeProcessLinux::Attach(lldb::pid_t pid, Error &error)
1483af245d11STodd Fiala {
1484af245d11STodd Fiala     lldb::ThreadSP inferior;
1485af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1486af245d11STodd Fiala 
1487af245d11STodd Fiala     // Use a map to keep track of the threads which we have attached/need to attach.
1488af245d11STodd Fiala     Host::TidMap tids_to_attach;
1489af245d11STodd Fiala     if (pid <= 1)
1490af245d11STodd Fiala     {
1491bd7cbc5aSPavel Labath         error.SetErrorToGenericError();
1492bd7cbc5aSPavel Labath         error.SetErrorString("Attaching to process 1 is not allowed.");
1493bd7cbc5aSPavel Labath         return -1;
1494af245d11STodd Fiala     }
1495af245d11STodd Fiala 
1496af245d11STodd Fiala     while (Host::FindProcessThreads(pid, tids_to_attach))
1497af245d11STodd Fiala     {
1498af245d11STodd Fiala         for (Host::TidMap::iterator it = tids_to_attach.begin();
1499af245d11STodd Fiala              it != tids_to_attach.end();)
1500af245d11STodd Fiala         {
1501af245d11STodd Fiala             if (it->second == false)
1502af245d11STodd Fiala             {
1503af245d11STodd Fiala                 lldb::tid_t tid = it->first;
1504af245d11STodd Fiala 
1505af245d11STodd Fiala                 // Attach to the requested process.
1506af245d11STodd Fiala                 // An attach will cause the thread to stop with a SIGSTOP.
1507068f8a7eSTamas Berghammer                 NativeProcessLinux::PtraceWrapper(PTRACE_ATTACH, tid, nullptr, nullptr, 0, error);
1508bd7cbc5aSPavel Labath                 if (error.Fail())
1509af245d11STodd Fiala                 {
1510af245d11STodd Fiala                     // No such thread. The thread may have exited.
1511af245d11STodd Fiala                     // More error handling may be needed.
1512bd7cbc5aSPavel Labath                     if (error.GetError() == ESRCH)
1513af245d11STodd Fiala                     {
1514af245d11STodd Fiala                         it = tids_to_attach.erase(it);
1515af245d11STodd Fiala                         continue;
1516af245d11STodd Fiala                     }
1517af245d11STodd Fiala                     else
1518bd7cbc5aSPavel Labath                         return -1;
1519af245d11STodd Fiala                 }
1520af245d11STodd Fiala 
1521af245d11STodd Fiala                 int status;
1522af245d11STodd Fiala                 // Need to use __WALL otherwise we receive an error with errno=ECHLD
1523af245d11STodd Fiala                 // At this point we should have a thread stopped if waitpid succeeds.
1524af245d11STodd Fiala                 if ((status = waitpid(tid, NULL, __WALL)) < 0)
1525af245d11STodd Fiala                 {
1526af245d11STodd Fiala                     // No such thread. The thread may have exited.
1527af245d11STodd Fiala                     // More error handling may be needed.
1528af245d11STodd Fiala                     if (errno == ESRCH)
1529af245d11STodd Fiala                     {
1530af245d11STodd Fiala                         it = tids_to_attach.erase(it);
1531af245d11STodd Fiala                         continue;
1532af245d11STodd Fiala                     }
1533af245d11STodd Fiala                     else
1534af245d11STodd Fiala                     {
1535bd7cbc5aSPavel Labath                         error.SetErrorToErrno();
1536bd7cbc5aSPavel Labath                         return -1;
1537af245d11STodd Fiala                     }
1538af245d11STodd Fiala                 }
1539af245d11STodd Fiala 
1540bd7cbc5aSPavel Labath                 error = SetDefaultPtraceOpts(tid);
1541bd7cbc5aSPavel Labath                 if (error.Fail())
1542bd7cbc5aSPavel Labath                     return -1;
1543af245d11STodd Fiala 
1544af245d11STodd Fiala                 if (log)
1545af245d11STodd Fiala                     log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
1546af245d11STodd Fiala 
1547af245d11STodd Fiala                 it->second = true;
1548af245d11STodd Fiala 
1549af245d11STodd Fiala                 // Create the thread, mark it as stopped.
1550bd7cbc5aSPavel Labath                 NativeThreadProtocolSP thread_sp (AddThread (static_cast<lldb::tid_t> (tid)));
1551af245d11STodd Fiala                 assert (thread_sp && "AddThread() returned a nullptr");
1552fa03ad2eSChaoren Lin 
1553fa03ad2eSChaoren Lin                 // This will notify this is a new thread and tell the system it is stopped.
1554cb84eebbSTamas Berghammer                 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
15551dbc6c9cSPavel Labath                 ThreadWasCreated(tid);
1556bd7cbc5aSPavel Labath                 SetCurrentThreadID (thread_sp->GetID ());
1557af245d11STodd Fiala             }
1558af245d11STodd Fiala 
1559af245d11STodd Fiala             // move the loop forward
1560af245d11STodd Fiala             ++it;
1561af245d11STodd Fiala         }
1562af245d11STodd Fiala     }
1563af245d11STodd Fiala 
1564af245d11STodd Fiala     if (tids_to_attach.size() > 0)
1565af245d11STodd Fiala     {
1566bd7cbc5aSPavel Labath         m_pid = pid;
1567af245d11STodd Fiala         // Let our process instance know the thread has stopped.
1568bd7cbc5aSPavel Labath         SetState (StateType::eStateStopped);
1569af245d11STodd Fiala     }
1570af245d11STodd Fiala     else
1571af245d11STodd Fiala     {
1572bd7cbc5aSPavel Labath         error.SetErrorToGenericError();
1573bd7cbc5aSPavel Labath         error.SetErrorString("No such process.");
1574bd7cbc5aSPavel Labath         return -1;
1575af245d11STodd Fiala     }
1576af245d11STodd Fiala 
1577bd7cbc5aSPavel Labath     return pid;
1578af245d11STodd Fiala }
1579af245d11STodd Fiala 
158097ccc294SChaoren Lin Error
1581af245d11STodd Fiala NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
1582af245d11STodd Fiala {
1583af245d11STodd Fiala     long ptrace_opts = 0;
1584af245d11STodd Fiala 
1585af245d11STodd Fiala     // Have the child raise an event on exit.  This is used to keep the child in
1586af245d11STodd Fiala     // limbo until it is destroyed.
1587af245d11STodd Fiala     ptrace_opts |= PTRACE_O_TRACEEXIT;
1588af245d11STodd Fiala 
1589af245d11STodd Fiala     // Have the tracer trace threads which spawn in the inferior process.
1590af245d11STodd Fiala     // TODO: if we want to support tracing the inferiors' child, add the
1591af245d11STodd Fiala     // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
1592af245d11STodd Fiala     ptrace_opts |= PTRACE_O_TRACECLONE;
1593af245d11STodd Fiala 
1594af245d11STodd Fiala     // Have the tracer notify us before execve returns
1595af245d11STodd Fiala     // (needed to disable legacy SIGTRAP generation)
1596af245d11STodd Fiala     ptrace_opts |= PTRACE_O_TRACEEXEC;
1597af245d11STodd Fiala 
159897ccc294SChaoren Lin     Error error;
1599068f8a7eSTamas Berghammer     NativeProcessLinux::PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts, 0, error);
160097ccc294SChaoren Lin     return error;
1601af245d11STodd Fiala }
1602af245d11STodd Fiala 
1603af245d11STodd Fiala static ExitType convert_pid_status_to_exit_type (int status)
1604af245d11STodd Fiala {
1605af245d11STodd Fiala     if (WIFEXITED (status))
1606af245d11STodd Fiala         return ExitType::eExitTypeExit;
1607af245d11STodd Fiala     else if (WIFSIGNALED (status))
1608af245d11STodd Fiala         return ExitType::eExitTypeSignal;
1609af245d11STodd Fiala     else if (WIFSTOPPED (status))
1610af245d11STodd Fiala         return ExitType::eExitTypeStop;
1611af245d11STodd Fiala     else
1612af245d11STodd Fiala     {
1613af245d11STodd Fiala         // We don't know what this is.
1614af245d11STodd Fiala         return ExitType::eExitTypeInvalid;
1615af245d11STodd Fiala     }
1616af245d11STodd Fiala }
1617af245d11STodd Fiala 
1618af245d11STodd Fiala static int convert_pid_status_to_return_code (int status)
1619af245d11STodd Fiala {
1620af245d11STodd Fiala     if (WIFEXITED (status))
1621af245d11STodd Fiala         return WEXITSTATUS (status);
1622af245d11STodd Fiala     else if (WIFSIGNALED (status))
1623af245d11STodd Fiala         return WTERMSIG (status);
1624af245d11STodd Fiala     else if (WIFSTOPPED (status))
1625af245d11STodd Fiala         return WSTOPSIG (status);
1626af245d11STodd Fiala     else
1627af245d11STodd Fiala     {
1628af245d11STodd Fiala         // We don't know what this is.
1629af245d11STodd Fiala         return ExitType::eExitTypeInvalid;
1630af245d11STodd Fiala     }
1631af245d11STodd Fiala }
1632af245d11STodd Fiala 
16331107b5a5SPavel Labath // Handles all waitpid events from the inferior process.
16341107b5a5SPavel Labath void
16351107b5a5SPavel Labath NativeProcessLinux::MonitorCallback(lldb::pid_t pid,
1636af245d11STodd Fiala                                     bool exited,
1637af245d11STodd Fiala                                     int signal,
1638af245d11STodd Fiala                                     int status)
1639af245d11STodd Fiala {
1640af245d11STodd Fiala     Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1641af245d11STodd Fiala 
1642af245d11STodd Fiala     // Certain activities differ based on whether the pid is the tid of the main thread.
16431107b5a5SPavel Labath     const bool is_main_thread = (pid == GetID ());
1644af245d11STodd Fiala 
1645af245d11STodd Fiala     // Handle when the thread exits.
1646af245d11STodd Fiala     if (exited)
1647af245d11STodd Fiala     {
1648af245d11STodd Fiala         if (log)
164986fd8e45SChaoren Lin             log->Printf ("NativeProcessLinux::%s() got exit signal(%d) , tid = %"  PRIu64 " (%s main thread)", __FUNCTION__, signal, pid, is_main_thread ? "is" : "is not");
1650af245d11STodd Fiala 
1651af245d11STodd Fiala         // This is a thread that exited.  Ensure we're not tracking it anymore.
16521107b5a5SPavel Labath         const bool thread_found = StopTrackingThread (pid);
1653af245d11STodd Fiala 
1654af245d11STodd Fiala         if (is_main_thread)
1655af245d11STodd Fiala         {
1656af245d11STodd Fiala             // We only set the exit status and notify the delegate if we haven't already set the process
1657af245d11STodd Fiala             // state to an exited state.  We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
1658af245d11STodd Fiala             // for the main thread.
16591107b5a5SPavel Labath             const bool already_notified = (GetState() == StateType::eStateExited) || (GetState () == StateType::eStateCrashed);
1660af245d11STodd Fiala             if (!already_notified)
1661af245d11STodd Fiala             {
1662af245d11STodd Fiala                 if (log)
16631107b5a5SPavel 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 ()));
1664af245d11STodd Fiala                 // The main thread exited.  We're done monitoring.  Report to delegate.
16651107b5a5SPavel Labath                 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
1666af245d11STodd Fiala 
1667af245d11STodd Fiala                 // Notify delegate that our process has exited.
16681107b5a5SPavel Labath                 SetState (StateType::eStateExited, true);
1669af245d11STodd Fiala             }
1670af245d11STodd Fiala             else
1671af245d11STodd Fiala             {
1672af245d11STodd Fiala                 if (log)
1673af245d11STodd Fiala                     log->Printf ("NativeProcessLinux::%s() tid = %"  PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
1674af245d11STodd Fiala             }
1675af245d11STodd Fiala         }
1676af245d11STodd Fiala         else
1677af245d11STodd Fiala         {
1678af245d11STodd Fiala             // Do we want to report to the delegate in this case?  I think not.  If this was an orderly
1679af245d11STodd Fiala             // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
1680af245d11STodd Fiala             // and we would have done an all-stop then.
1681af245d11STodd Fiala             if (log)
1682af245d11STodd 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");
1683af245d11STodd Fiala         }
16841107b5a5SPavel Labath         return;
1685af245d11STodd Fiala     }
1686af245d11STodd Fiala 
1687af245d11STodd Fiala     // Get details on the signal raised.
1688af245d11STodd Fiala     siginfo_t info;
16891107b5a5SPavel Labath     const auto err = GetSignalInfo(pid, &info);
169097ccc294SChaoren Lin     if (err.Success())
1691fa03ad2eSChaoren Lin     {
1692fa03ad2eSChaoren Lin         // We have retrieved the signal info.  Dispatch appropriately.
1693fa03ad2eSChaoren Lin         if (info.si_signo == SIGTRAP)
16941107b5a5SPavel Labath             MonitorSIGTRAP(&info, pid);
1695fa03ad2eSChaoren Lin         else
16961107b5a5SPavel Labath             MonitorSignal(&info, pid, exited);
1697fa03ad2eSChaoren Lin     }
1698fa03ad2eSChaoren Lin     else
1699af245d11STodd Fiala     {
170097ccc294SChaoren Lin         if (err.GetError() == EINVAL)
1701af245d11STodd Fiala         {
1702fa03ad2eSChaoren Lin             // This is a group stop reception for this tid.
170339036ac3SPavel Labath             // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the
170439036ac3SPavel Labath             // tracee, triggering the group-stop mechanism. Normally receiving these would stop
170539036ac3SPavel Labath             // the process, pending a SIGCONT. Simulating this state in a debugger is hard and is
170639036ac3SPavel Labath             // generally not needed (one use case is debugging background task being managed by a
170739036ac3SPavel Labath             // shell). For general use, it is sufficient to stop the process in a signal-delivery
170839036ac3SPavel Labath             // stop which happens before the group stop. This done by MonitorSignal and works
170939036ac3SPavel Labath             // correctly for all signals.
1710fa03ad2eSChaoren Lin             if (log)
171139036ac3SPavel 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);
171239036ac3SPavel Labath             Resume(pid, signal);
1713a9882ceeSTodd Fiala         }
1714a9882ceeSTodd Fiala         else
1715a9882ceeSTodd Fiala         {
1716af245d11STodd Fiala             // ptrace(GETSIGINFO) failed (but not due to group-stop).
1717af245d11STodd Fiala 
1718af245d11STodd Fiala             // A return value of ESRCH means the thread/process is no longer on the system,
1719af245d11STodd Fiala             // so it was killed somehow outside of our control.  Either way, we can't do anything
1720af245d11STodd Fiala             // with it anymore.
1721af245d11STodd Fiala 
1722af245d11STodd Fiala             // Stop tracking the metadata for the thread since it's entirely off the system now.
17231107b5a5SPavel Labath             const bool thread_found = StopTrackingThread (pid);
1724af245d11STodd Fiala 
1725af245d11STodd Fiala             if (log)
1726af245d11STodd Fiala                 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
172797ccc294SChaoren 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");
1728af245d11STodd Fiala 
1729af245d11STodd Fiala             if (is_main_thread)
1730af245d11STodd Fiala             {
1731af245d11STodd Fiala                 // Notify the delegate - our process is not available but appears to have been killed outside
1732af245d11STodd Fiala                 // our control.  Is eStateExited the right exit state in this case?
17331107b5a5SPavel Labath                 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
17341107b5a5SPavel Labath                 SetState (StateType::eStateExited, true);
1735af245d11STodd Fiala             }
1736af245d11STodd Fiala             else
1737af245d11STodd Fiala             {
1738af245d11STodd Fiala                 // This thread was pulled out from underneath us.  Anything to do here? Do we want to do an all stop?
1739af245d11STodd Fiala                 if (log)
17401107b5a5SPavel 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);
1741af245d11STodd Fiala             }
1742af245d11STodd Fiala         }
1743af245d11STodd Fiala     }
1744af245d11STodd Fiala }
1745af245d11STodd Fiala 
1746af245d11STodd Fiala void
1747426bdf88SPavel Labath NativeProcessLinux::WaitForNewThread(::pid_t tid)
1748426bdf88SPavel Labath {
1749426bdf88SPavel Labath     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1750426bdf88SPavel Labath 
1751426bdf88SPavel Labath     NativeThreadProtocolSP new_thread_sp = GetThreadByID(tid);
1752426bdf88SPavel Labath 
1753426bdf88SPavel Labath     if (new_thread_sp)
1754426bdf88SPavel Labath     {
1755426bdf88SPavel Labath         // We are already tracking the thread - we got the event on the new thread (see
1756426bdf88SPavel Labath         // MonitorSignal) before this one. We are done.
1757426bdf88SPavel Labath         return;
1758426bdf88SPavel Labath     }
1759426bdf88SPavel Labath 
1760426bdf88SPavel Labath     // The thread is not tracked yet, let's wait for it to appear.
1761426bdf88SPavel Labath     int status = -1;
1762426bdf88SPavel Labath     ::pid_t wait_pid;
1763426bdf88SPavel Labath     do
1764426bdf88SPavel Labath     {
1765426bdf88SPavel Labath         if (log)
1766426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() received thread creation event for tid %" PRIu32 ". tid not tracked yet, waiting for thread to appear...", __FUNCTION__, tid);
1767426bdf88SPavel Labath         wait_pid = waitpid(tid, &status, __WALL);
1768426bdf88SPavel Labath     }
1769426bdf88SPavel Labath     while (wait_pid == -1 && errno == EINTR);
1770426bdf88SPavel Labath     // Since we are waiting on a specific tid, this must be the creation event. But let's do
1771426bdf88SPavel Labath     // some checks just in case.
1772426bdf88SPavel Labath     if (wait_pid != tid) {
1773426bdf88SPavel Labath         if (log)
1774426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime", __FUNCTION__, tid);
1775426bdf88SPavel Labath         // The only way I know of this could happen is if the whole process was
1776426bdf88SPavel Labath         // SIGKILLed in the mean time. In any case, we can't do anything about that now.
1777426bdf88SPavel Labath         return;
1778426bdf88SPavel Labath     }
1779426bdf88SPavel Labath     if (WIFEXITED(status))
1780426bdf88SPavel Labath     {
1781426bdf88SPavel Labath         if (log)
1782426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " returned an 'exited' event. Not tracking the thread.", __FUNCTION__, tid);
1783426bdf88SPavel Labath         // Also a very improbable event.
1784426bdf88SPavel Labath         return;
1785426bdf88SPavel Labath     }
1786426bdf88SPavel Labath 
1787426bdf88SPavel Labath     siginfo_t info;
1788426bdf88SPavel Labath     Error error = GetSignalInfo(tid, &info);
1789426bdf88SPavel Labath     if (error.Fail())
1790426bdf88SPavel Labath     {
1791426bdf88SPavel Labath         if (log)
1792426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime.", __FUNCTION__, tid);
1793426bdf88SPavel Labath         return;
1794426bdf88SPavel Labath     }
1795426bdf88SPavel Labath 
1796426bdf88SPavel Labath     if (((info.si_pid != 0) || (info.si_code != SI_USER)) && log)
1797426bdf88SPavel Labath     {
1798426bdf88SPavel Labath         // We should be getting a thread creation signal here, but we received something
1799426bdf88SPavel Labath         // else. There isn't much we can do about it now, so we will just log that. Since the
1800426bdf88SPavel Labath         // thread is alive and we are receiving events from it, we shall pretend that it was
1801426bdf88SPavel Labath         // created properly.
1802426bdf88SPavel 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);
1803426bdf88SPavel Labath     }
1804426bdf88SPavel Labath 
1805426bdf88SPavel Labath     if (log)
1806426bdf88SPavel Labath         log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 ": tracking new thread tid %" PRIu32,
1807426bdf88SPavel Labath                  __FUNCTION__, GetID (), tid);
1808426bdf88SPavel Labath 
1809426bdf88SPavel Labath     new_thread_sp = AddThread(tid);
1810426bdf88SPavel Labath     std::static_pointer_cast<NativeThreadLinux> (new_thread_sp)->SetRunning ();
1811426bdf88SPavel Labath     Resume (tid, LLDB_INVALID_SIGNAL_NUMBER);
18121dbc6c9cSPavel Labath     ThreadWasCreated(tid);
1813426bdf88SPavel Labath }
1814426bdf88SPavel Labath 
1815426bdf88SPavel Labath void
1816af245d11STodd Fiala NativeProcessLinux::MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid)
1817af245d11STodd Fiala {
1818af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1819af245d11STodd Fiala     const bool is_main_thread = (pid == GetID ());
1820af245d11STodd Fiala 
1821af245d11STodd Fiala     assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
1822af245d11STodd Fiala     if (!info)
1823af245d11STodd Fiala         return;
1824af245d11STodd Fiala 
18255830aa75STamas Berghammer     Mutex::Locker locker (m_threads_mutex);
18265830aa75STamas Berghammer 
1827af245d11STodd Fiala     // See if we can find a thread for this signal.
1828af245d11STodd Fiala     NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
1829af245d11STodd Fiala     if (!thread_sp)
1830af245d11STodd Fiala     {
1831af245d11STodd Fiala         if (log)
1832af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
1833af245d11STodd Fiala     }
1834af245d11STodd Fiala 
1835af245d11STodd Fiala     switch (info->si_code)
1836af245d11STodd Fiala     {
1837af245d11STodd 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.
1838af245d11STodd Fiala     // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
1839af245d11STodd Fiala     // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
1840af245d11STodd Fiala 
1841af245d11STodd Fiala     case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
1842af245d11STodd Fiala     {
18435fd24c67SPavel Labath         // This is the notification on the parent thread which informs us of new thread
1844426bdf88SPavel Labath         // creation.
1845426bdf88SPavel Labath         // We don't want to do anything with the parent thread so we just resume it. In case we
1846426bdf88SPavel Labath         // want to implement "break on thread creation" functionality, we would need to stop
1847426bdf88SPavel Labath         // here.
1848af245d11STodd Fiala 
1849af245d11STodd Fiala         unsigned long event_message = 0;
1850426bdf88SPavel Labath         if (GetEventMessage (pid, &event_message).Fail())
1851fa03ad2eSChaoren Lin         {
1852426bdf88SPavel Labath             if (log)
1853fa03ad2eSChaoren Lin                 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " received thread creation event but GetEventMessage failed so we don't know the new tid", __FUNCTION__, pid);
1854426bdf88SPavel Labath         } else
1855426bdf88SPavel Labath             WaitForNewThread(event_message);
1856af245d11STodd Fiala 
18575fd24c67SPavel Labath         Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
1858af245d11STodd Fiala         break;
1859af245d11STodd Fiala     }
1860af245d11STodd Fiala 
1861af245d11STodd Fiala     case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
1862a9882ceeSTodd Fiala     {
1863a9882ceeSTodd Fiala         NativeThreadProtocolSP main_thread_sp;
1864af245d11STodd Fiala         if (log)
1865af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
1866a9882ceeSTodd Fiala 
18671dbc6c9cSPavel Labath         // Exec clears any pending notifications.
18681dbc6c9cSPavel Labath         m_pending_notification_up.reset ();
1869fa03ad2eSChaoren Lin 
1870fa03ad2eSChaoren 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.
1871a9882ceeSTodd Fiala         if (log)
1872a9882ceeSTodd Fiala             log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
1873a9882ceeSTodd Fiala 
1874a9882ceeSTodd Fiala         for (auto thread_sp : m_threads)
1875a9882ceeSTodd Fiala         {
1876a9882ceeSTodd Fiala             const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
1877a9882ceeSTodd Fiala             if (is_main_thread)
1878a9882ceeSTodd Fiala             {
1879a9882ceeSTodd Fiala                 main_thread_sp = thread_sp;
1880a9882ceeSTodd Fiala                 if (log)
1881a9882ceeSTodd Fiala                     log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
1882a9882ceeSTodd Fiala             }
1883a9882ceeSTodd Fiala             else
1884a9882ceeSTodd Fiala             {
1885fa03ad2eSChaoren Lin                 // Tell thread coordinator this thread is dead.
1886a9882ceeSTodd Fiala                 if (log)
1887a9882ceeSTodd Fiala                     log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
1888a9882ceeSTodd Fiala             }
1889a9882ceeSTodd Fiala         }
1890a9882ceeSTodd Fiala 
1891a9882ceeSTodd Fiala         m_threads.clear ();
1892a9882ceeSTodd Fiala 
1893a9882ceeSTodd Fiala         if (main_thread_sp)
1894a9882ceeSTodd Fiala         {
1895a9882ceeSTodd Fiala             m_threads.push_back (main_thread_sp);
1896a9882ceeSTodd Fiala             SetCurrentThreadID (main_thread_sp->GetID ());
1897cb84eebbSTamas Berghammer             std::static_pointer_cast<NativeThreadLinux> (main_thread_sp)->SetStoppedByExec ();
1898a9882ceeSTodd Fiala         }
1899a9882ceeSTodd Fiala         else
1900a9882ceeSTodd Fiala         {
1901a9882ceeSTodd Fiala             SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
1902a9882ceeSTodd Fiala             if (log)
1903a9882ceeSTodd Fiala                 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
1904a9882ceeSTodd Fiala         }
1905a9882ceeSTodd Fiala 
1906fa03ad2eSChaoren Lin         // Tell coordinator about about the "new" (since exec) stopped main thread.
1907fa03ad2eSChaoren Lin         const lldb::tid_t main_thread_tid = GetID ();
19081dbc6c9cSPavel Labath         ThreadWasCreated(main_thread_tid);
1909fa03ad2eSChaoren Lin 
1910fa03ad2eSChaoren Lin         // NOTE: ideally these next statements would execute at the same time as the coordinator thread create was executed.
1911fa03ad2eSChaoren Lin         // Consider a handler that can execute when that happens.
1912a9882ceeSTodd Fiala         // Let our delegate know we have just exec'd.
1913a9882ceeSTodd Fiala         NotifyDidExec ();
1914a9882ceeSTodd Fiala 
1915a9882ceeSTodd Fiala         // If we have a main thread, indicate we are stopped.
1916a9882ceeSTodd Fiala         assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
1917fa03ad2eSChaoren Lin 
1918fa03ad2eSChaoren Lin         // Let the process know we're stopped.
1919ed89c7feSPavel Labath         StopRunningThreads (pid);
1920a9882ceeSTodd Fiala 
1921af245d11STodd Fiala         break;
1922a9882ceeSTodd Fiala     }
1923af245d11STodd Fiala 
1924af245d11STodd Fiala     case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
1925af245d11STodd Fiala     {
1926af245d11STodd Fiala         // The inferior process or one of its threads is about to exit.
19276e35163cSPavel Labath         // We don't want to do anything with the thread so we just resume it. In case we
19286e35163cSPavel Labath         // want to implement "break on thread exit" functionality, we would need to stop
19296e35163cSPavel Labath         // here.
1930fa03ad2eSChaoren Lin 
1931af245d11STodd Fiala         unsigned long data = 0;
193297ccc294SChaoren Lin         if (GetEventMessage(pid, &data).Fail())
1933af245d11STodd Fiala             data = -1;
1934af245d11STodd Fiala 
1935af245d11STodd Fiala         if (log)
1936af245d11STodd Fiala         {
1937af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
1938af245d11STodd Fiala                          __FUNCTION__,
1939af245d11STodd Fiala                          data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
1940af245d11STodd Fiala                          pid,
1941af245d11STodd Fiala                     is_main_thread ? "is main thread" : "not main thread");
1942af245d11STodd Fiala         }
1943af245d11STodd Fiala 
1944af245d11STodd Fiala         if (is_main_thread)
1945af245d11STodd Fiala         {
1946af245d11STodd Fiala             SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
194775f47c3aSTodd Fiala         }
194875f47c3aSTodd Fiala 
19496e35163cSPavel Labath         Resume(pid, LLDB_INVALID_SIGNAL_NUMBER);
1950af245d11STodd Fiala 
1951af245d11STodd Fiala         break;
1952af245d11STodd Fiala     }
1953af245d11STodd Fiala 
1954af245d11STodd Fiala     case 0:
1955c16f5dcaSChaoren Lin     case TRAP_TRACE:  // We receive this on single stepping.
1956c16f5dcaSChaoren Lin     case TRAP_HWBKPT: // We receive this on watchpoint hit
195786fd8e45SChaoren Lin         if (thread_sp)
195886fd8e45SChaoren Lin         {
1959c16f5dcaSChaoren Lin             // If a watchpoint was hit, report it
1960c16f5dcaSChaoren Lin             uint32_t wp_index;
1961ea8c25a8SOmair Javaid             Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index, (lldb::addr_t)info->si_addr);
1962c16f5dcaSChaoren Lin             if (error.Fail() && log)
1963c16f5dcaSChaoren Lin                 log->Printf("NativeProcessLinux::%s() "
1964c16f5dcaSChaoren Lin                             "received error while checking for watchpoint hits, "
1965c16f5dcaSChaoren Lin                             "pid = %" PRIu64 " error = %s",
1966c16f5dcaSChaoren Lin                             __FUNCTION__, pid, error.AsCString());
1967c16f5dcaSChaoren Lin             if (wp_index != LLDB_INVALID_INDEX32)
19685830aa75STamas Berghammer             {
1969c16f5dcaSChaoren Lin                 MonitorWatchpoint(pid, thread_sp, wp_index);
1970c16f5dcaSChaoren Lin                 break;
1971c16f5dcaSChaoren Lin             }
1972c16f5dcaSChaoren Lin         }
1973c16f5dcaSChaoren Lin         // Otherwise, report step over
1974c16f5dcaSChaoren Lin         MonitorTrace(pid, thread_sp);
1975af245d11STodd Fiala         break;
1976af245d11STodd Fiala 
1977af245d11STodd Fiala     case SI_KERNEL:
1978af245d11STodd Fiala     case TRAP_BRKPT:
1979c16f5dcaSChaoren Lin         MonitorBreakpoint(pid, thread_sp);
1980af245d11STodd Fiala         break;
1981af245d11STodd Fiala 
1982af245d11STodd Fiala     case SIGTRAP:
1983af245d11STodd Fiala     case (SIGTRAP | 0x80):
1984af245d11STodd Fiala         if (log)
1985fa03ad2eSChaoren Lin             log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), pid);
1986fa03ad2eSChaoren Lin 
1987af245d11STodd Fiala         // Ignore these signals until we know more about them.
19886e35163cSPavel Labath         Resume(pid, LLDB_INVALID_SIGNAL_NUMBER);
1989af245d11STodd Fiala         break;
1990af245d11STodd Fiala 
1991af245d11STodd Fiala     default:
1992af245d11STodd Fiala         assert(false && "Unexpected SIGTRAP code!");
1993af245d11STodd Fiala         if (log)
19946e35163cSPavel Labath             log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 "tid %" PRIu64 " received unhandled SIGTRAP code: 0x%d",
19956e35163cSPavel Labath                     __FUNCTION__, GetID (), pid, info->si_code);
1996af245d11STodd Fiala         break;
1997af245d11STodd Fiala 
1998af245d11STodd Fiala     }
1999af245d11STodd Fiala }
2000af245d11STodd Fiala 
2001af245d11STodd Fiala void
2002c16f5dcaSChaoren Lin NativeProcessLinux::MonitorTrace(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
2003c16f5dcaSChaoren Lin {
2004c16f5dcaSChaoren Lin     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2005c16f5dcaSChaoren Lin     if (log)
2006c16f5dcaSChaoren Lin         log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)",
2007c16f5dcaSChaoren Lin                 __FUNCTION__, pid);
2008c16f5dcaSChaoren Lin 
2009c16f5dcaSChaoren Lin     if (thread_sp)
2010c16f5dcaSChaoren Lin         std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
2011c16f5dcaSChaoren Lin 
2012c16f5dcaSChaoren Lin     // This thread is currently stopped.
20131dbc6c9cSPavel Labath     ThreadDidStop(pid, false);
2014c16f5dcaSChaoren Lin 
2015c16f5dcaSChaoren Lin     // Here we don't have to request the rest of the threads to stop or request a deferred stop.
2016c16f5dcaSChaoren Lin     // This would have already happened at the time the Resume() with step operation was signaled.
2017c16f5dcaSChaoren Lin     // At this point, we just need to say we stopped, and the deferred notifcation will fire off
2018c16f5dcaSChaoren Lin     // once all running threads have checked in as stopped.
2019c16f5dcaSChaoren Lin     SetCurrentThreadID(pid);
2020c16f5dcaSChaoren Lin     // Tell the process we have a stop (from software breakpoint).
2021ed89c7feSPavel Labath     StopRunningThreads(pid);
2022c16f5dcaSChaoren Lin }
2023c16f5dcaSChaoren Lin 
2024c16f5dcaSChaoren Lin void
2025c16f5dcaSChaoren Lin NativeProcessLinux::MonitorBreakpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
2026c16f5dcaSChaoren Lin {
2027c16f5dcaSChaoren Lin     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
2028c16f5dcaSChaoren Lin     if (log)
2029c16f5dcaSChaoren Lin         log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
2030c16f5dcaSChaoren Lin                 __FUNCTION__, pid);
2031c16f5dcaSChaoren Lin 
2032c16f5dcaSChaoren Lin     // This thread is currently stopped.
20331dbc6c9cSPavel Labath     ThreadDidStop(pid, false);
2034c16f5dcaSChaoren Lin 
2035c16f5dcaSChaoren Lin     // Mark the thread as stopped at breakpoint.
2036c16f5dcaSChaoren Lin     if (thread_sp)
2037c16f5dcaSChaoren Lin     {
2038c16f5dcaSChaoren Lin         std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByBreakpoint();
2039c16f5dcaSChaoren Lin         Error error = FixupBreakpointPCAsNeeded(thread_sp);
2040c16f5dcaSChaoren Lin         if (error.Fail())
2041c16f5dcaSChaoren Lin             if (log)
2042c16f5dcaSChaoren Lin                 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
2043c16f5dcaSChaoren Lin                         __FUNCTION__, pid, error.AsCString());
2044d8c338d4STamas Berghammer 
20459eb1ecb9SPavel Labath         if (m_threads_stepping_with_breakpoint.find(pid) != m_threads_stepping_with_breakpoint.end())
2046d8c338d4STamas Berghammer             std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
2047d8c338d4STamas Berghammer     }
2048c16f5dcaSChaoren Lin     else
2049c16f5dcaSChaoren Lin         if (log)
2050c16f5dcaSChaoren Lin             log->Printf("NativeProcessLinux::%s()  pid = %" PRIu64 ": "
2051c16f5dcaSChaoren Lin                     "warning, cannot process software breakpoint since no thread metadata",
2052c16f5dcaSChaoren Lin                     __FUNCTION__, pid);
2053c16f5dcaSChaoren Lin 
2054c16f5dcaSChaoren Lin 
2055c16f5dcaSChaoren Lin     // We need to tell all other running threads before we notify the delegate about this stop.
2056ed89c7feSPavel Labath     StopRunningThreads(pid);
2057c16f5dcaSChaoren Lin }
2058c16f5dcaSChaoren Lin 
2059c16f5dcaSChaoren Lin void
2060c16f5dcaSChaoren Lin NativeProcessLinux::MonitorWatchpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp, uint32_t wp_index)
2061c16f5dcaSChaoren Lin {
2062c16f5dcaSChaoren Lin     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
2063c16f5dcaSChaoren Lin     if (log)
2064c16f5dcaSChaoren Lin         log->Printf("NativeProcessLinux::%s() received watchpoint event, "
2065c16f5dcaSChaoren Lin                     "pid = %" PRIu64 ", wp_index = %" PRIu32,
2066c16f5dcaSChaoren Lin                     __FUNCTION__, pid, wp_index);
2067c16f5dcaSChaoren Lin 
2068c16f5dcaSChaoren Lin     // This thread is currently stopped.
20691dbc6c9cSPavel Labath     ThreadDidStop(pid, false);
2070c16f5dcaSChaoren Lin 
2071c16f5dcaSChaoren Lin     // Mark the thread as stopped at watchpoint.
2072c16f5dcaSChaoren Lin     // The address is at (lldb::addr_t)info->si_addr if we need it.
2073c16f5dcaSChaoren Lin     lldbassert(thread_sp && "thread_sp cannot be NULL");
2074c16f5dcaSChaoren Lin     std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByWatchpoint(wp_index);
2075c16f5dcaSChaoren Lin 
2076c16f5dcaSChaoren Lin     // We need to tell all other running threads before we notify the delegate about this stop.
2077ed89c7feSPavel Labath     StopRunningThreads(pid);
2078c16f5dcaSChaoren Lin }
2079c16f5dcaSChaoren Lin 
2080c16f5dcaSChaoren Lin void
2081af245d11STodd Fiala NativeProcessLinux::MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited)
2082af245d11STodd Fiala {
2083511e5cdcSTodd Fiala     assert (info && "null info");
2084511e5cdcSTodd Fiala     if (!info)
2085511e5cdcSTodd Fiala         return;
2086511e5cdcSTodd Fiala 
2087511e5cdcSTodd Fiala     const int signo = info->si_signo;
2088511e5cdcSTodd Fiala     const bool is_from_llgs = info->si_pid == getpid ();
2089af245d11STodd Fiala 
2090af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2091af245d11STodd Fiala 
2092af245d11STodd Fiala     // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
2093af245d11STodd Fiala     // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
2094af245d11STodd Fiala     // kill(2) or raise(3).  Similarly for tgkill(2) on Linux.
2095af245d11STodd Fiala     //
2096af245d11STodd Fiala     // IOW, user generated signals never generate what we consider to be a
2097af245d11STodd Fiala     // "crash".
2098af245d11STodd Fiala     //
2099af245d11STodd Fiala     // Similarly, ACK signals generated by this monitor.
2100af245d11STodd Fiala 
21015830aa75STamas Berghammer     Mutex::Locker locker (m_threads_mutex);
21025830aa75STamas Berghammer 
2103af245d11STodd Fiala     // See if we can find a thread for this signal.
2104af245d11STodd Fiala     NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2105af245d11STodd Fiala     if (!thread_sp)
2106af245d11STodd Fiala     {
2107af245d11STodd Fiala         if (log)
2108af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2109af245d11STodd Fiala     }
2110af245d11STodd Fiala 
2111af245d11STodd Fiala     // Handle the signal.
2112af245d11STodd Fiala     if (info->si_code == SI_TKILL || info->si_code == SI_USER)
2113af245d11STodd Fiala     {
2114af245d11STodd Fiala         if (log)
2115af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
2116af245d11STodd Fiala                             __FUNCTION__,
2117af245d11STodd Fiala                             GetUnixSignals ().GetSignalAsCString (signo),
2118af245d11STodd Fiala                             signo,
2119af245d11STodd Fiala                             (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
2120af245d11STodd Fiala                             info->si_pid,
2121511e5cdcSTodd Fiala                             is_from_llgs ? "from llgs" : "not from llgs",
2122af245d11STodd Fiala                             pid);
212358a2f669STodd Fiala     }
2124af245d11STodd Fiala 
212558a2f669STodd Fiala     // Check for new thread notification.
212658a2f669STodd Fiala     if ((info->si_pid == 0) && (info->si_code == SI_USER))
2127af245d11STodd Fiala     {
2128af245d11STodd Fiala         // A new thread creation is being signaled. This is one of two parts that come in
2129426bdf88SPavel Labath         // a non-deterministic order. This code handles the case where the new thread event comes
2130426bdf88SPavel Labath         // before the event on the parent thread. For the opposite case see code in
2131426bdf88SPavel Labath         // MonitorSIGTRAP.
2132af245d11STodd Fiala         if (log)
2133af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": new thread notification",
2134af245d11STodd Fiala                      __FUNCTION__, GetID (), pid);
2135af245d11STodd Fiala 
21365fd24c67SPavel Labath         thread_sp = AddThread(pid);
21375fd24c67SPavel Labath         assert (thread_sp.get() && "failed to create the tracking data for newly created inferior thread");
21385fd24c67SPavel Labath         // We can now resume the newly created thread.
2139cb84eebbSTamas Berghammer         std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
21405fd24c67SPavel Labath         Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
21411dbc6c9cSPavel Labath         ThreadWasCreated(pid);
214258a2f669STodd Fiala         // Done handling.
214358a2f669STodd Fiala         return;
2144af245d11STodd Fiala     }
214558a2f669STodd Fiala 
214658a2f669STodd Fiala     // Check for thread stop notification.
2147511e5cdcSTodd Fiala     if (is_from_llgs && (info->si_code == SI_TKILL) && (signo == SIGSTOP))
2148af245d11STodd Fiala     {
2149af245d11STodd Fiala         // This is a tgkill()-based stop.
2150af245d11STodd Fiala         if (thread_sp)
2151af245d11STodd Fiala         {
2152fa03ad2eSChaoren Lin             if (log)
2153fa03ad2eSChaoren Lin                 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
2154fa03ad2eSChaoren Lin                              __FUNCTION__,
2155fa03ad2eSChaoren Lin                              GetID (),
2156fa03ad2eSChaoren Lin                              pid);
2157fa03ad2eSChaoren Lin 
2158aab58633SChaoren Lin             // Check that we're not already marked with a stop reason.
2159aab58633SChaoren Lin             // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
2160aab58633SChaoren Lin             // the kernel signaled us with the thread stopping which we handled and marked as stopped,
2161aab58633SChaoren Lin             // and that, without an intervening resume, we received another stop.  It is more likely
2162aab58633SChaoren Lin             // that we are missing the marking of a run state somewhere if we find that the thread was
2163aab58633SChaoren Lin             // marked as stopped.
2164cb84eebbSTamas Berghammer             std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
2165cb84eebbSTamas Berghammer             assert (linux_thread_sp && "linux_thread_sp is null!");
2166aab58633SChaoren Lin 
2167cb84eebbSTamas Berghammer             const StateType thread_state = linux_thread_sp->GetState ();
2168aab58633SChaoren Lin             if (!StateIsStoppedState (thread_state, false))
2169aab58633SChaoren Lin             {
2170ed89c7feSPavel Labath                 // An inferior thread has stopped because of a SIGSTOP we have sent it.
2171ed89c7feSPavel Labath                 // Generally, these are not important stops and we don't want to report them as
2172ed89c7feSPavel Labath                 // they are just used to stop other threads when one thread (the one with the
2173ed89c7feSPavel Labath                 // *real* stop reason) hits a breakpoint (watchpoint, etc...). However, in the
2174ed89c7feSPavel Labath                 // case of an asynchronous Interrupt(), this *is* the real stop reason, so we
2175ed89c7feSPavel Labath                 // leave the signal intact if this is the thread that was chosen as the
2176ed89c7feSPavel Labath                 // triggering thread.
2177ed89c7feSPavel Labath                 if (m_pending_notification_up && m_pending_notification_up->triggering_tid == pid)
2178c4e25c96SPavel Labath                     linux_thread_sp->SetStoppedBySignal(SIGSTOP, info);
2179ed89c7feSPavel Labath                 else
2180cb84eebbSTamas Berghammer                     linux_thread_sp->SetStoppedBySignal(0);
2181ed89c7feSPavel Labath 
2182af245d11STodd Fiala                 SetCurrentThreadID (thread_sp->GetID ());
21831dbc6c9cSPavel Labath                 ThreadDidStop (thread_sp->GetID (), true);
2184aab58633SChaoren Lin             }
2185aab58633SChaoren Lin             else
2186aab58633SChaoren Lin             {
2187aab58633SChaoren Lin                 if (log)
2188aab58633SChaoren Lin                 {
2189aab58633SChaoren Lin                     // Retrieve the signal name if the thread was stopped by a signal.
2190aab58633SChaoren Lin                     int stop_signo = 0;
2191cb84eebbSTamas Berghammer                     const bool stopped_by_signal = linux_thread_sp->IsStopped (&stop_signo);
2192aab58633SChaoren Lin                     const char *signal_name = stopped_by_signal ? GetUnixSignals ().GetSignalAsCString (stop_signo) : "<not stopped by signal>";
2193aab58633SChaoren Lin                     if (!signal_name)
2194aab58633SChaoren Lin                         signal_name = "<no-signal-name>";
2195aab58633SChaoren Lin 
2196aab58633SChaoren 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",
2197aab58633SChaoren Lin                                  __FUNCTION__,
2198aab58633SChaoren Lin                                  GetID (),
2199cb84eebbSTamas Berghammer                                  linux_thread_sp->GetID (),
2200aab58633SChaoren Lin                                  StateAsCString (thread_state),
2201aab58633SChaoren Lin                                  stop_signo,
2202aab58633SChaoren Lin                                  signal_name);
2203aab58633SChaoren Lin                 }
22041dbc6c9cSPavel Labath                 ThreadDidStop (thread_sp->GetID (), false);
2205af245d11STodd Fiala             }
220686fd8e45SChaoren Lin         }
2207af245d11STodd Fiala 
220858a2f669STodd Fiala         // Done handling.
2209af245d11STodd Fiala         return;
2210af245d11STodd Fiala     }
2211af245d11STodd Fiala 
2212af245d11STodd Fiala     if (log)
2213af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, GetUnixSignals ().GetSignalAsCString (signo));
2214af245d11STodd Fiala 
221586fd8e45SChaoren Lin     // This thread is stopped.
22161dbc6c9cSPavel Labath     ThreadDidStop (pid, false);
221786fd8e45SChaoren Lin 
221886fd8e45SChaoren Lin     if (thread_sp)
2219c4e25c96SPavel Labath         std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal(signo, info);
222086fd8e45SChaoren Lin 
222186fd8e45SChaoren Lin     // Send a stop to the debugger after we get all other threads to stop.
2222ed89c7feSPavel Labath     StopRunningThreads (pid);
2223511e5cdcSTodd Fiala }
2224af245d11STodd Fiala 
2225e7708688STamas Berghammer namespace {
2226e7708688STamas Berghammer 
2227e7708688STamas Berghammer struct EmulatorBaton
2228e7708688STamas Berghammer {
2229e7708688STamas Berghammer     NativeProcessLinux* m_process;
2230e7708688STamas Berghammer     NativeRegisterContext* m_reg_context;
22316648fcc3SPavel Labath 
22326648fcc3SPavel Labath     // eRegisterKindDWARF -> RegsiterValue
22336648fcc3SPavel Labath     std::unordered_map<uint32_t, RegisterValue> m_register_values;
2234e7708688STamas Berghammer 
2235e7708688STamas Berghammer     EmulatorBaton(NativeProcessLinux* process, NativeRegisterContext* reg_context) :
2236e7708688STamas Berghammer             m_process(process), m_reg_context(reg_context) {}
2237e7708688STamas Berghammer };
2238e7708688STamas Berghammer 
2239e7708688STamas Berghammer } // anonymous namespace
2240e7708688STamas Berghammer 
2241e7708688STamas Berghammer static size_t
2242e7708688STamas Berghammer ReadMemoryCallback (EmulateInstruction *instruction,
2243e7708688STamas Berghammer                     void *baton,
2244e7708688STamas Berghammer                     const EmulateInstruction::Context &context,
2245e7708688STamas Berghammer                     lldb::addr_t addr,
2246e7708688STamas Berghammer                     void *dst,
2247e7708688STamas Berghammer                     size_t length)
2248e7708688STamas Berghammer {
2249e7708688STamas Berghammer     EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
2250e7708688STamas Berghammer 
22513eb4b458SChaoren Lin     size_t bytes_read;
2252e7708688STamas Berghammer     emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
2253e7708688STamas Berghammer     return bytes_read;
2254e7708688STamas Berghammer }
2255e7708688STamas Berghammer 
2256e7708688STamas Berghammer static bool
2257e7708688STamas Berghammer ReadRegisterCallback (EmulateInstruction *instruction,
2258e7708688STamas Berghammer                       void *baton,
2259e7708688STamas Berghammer                       const RegisterInfo *reg_info,
2260e7708688STamas Berghammer                       RegisterValue &reg_value)
2261e7708688STamas Berghammer {
2262e7708688STamas Berghammer     EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
2263e7708688STamas Berghammer 
22646648fcc3SPavel Labath     auto it = emulator_baton->m_register_values.find(reg_info->kinds[eRegisterKindDWARF]);
22656648fcc3SPavel Labath     if (it != emulator_baton->m_register_values.end())
22666648fcc3SPavel Labath     {
22676648fcc3SPavel Labath         reg_value = it->second;
22686648fcc3SPavel Labath         return true;
22696648fcc3SPavel Labath     }
22706648fcc3SPavel Labath 
2271e7708688STamas Berghammer     // The emulator only fill in the dwarf regsiter numbers (and in some case
2272e7708688STamas Berghammer     // the generic register numbers). Get the full register info from the
2273e7708688STamas Berghammer     // register context based on the dwarf register numbers.
2274e7708688STamas Berghammer     const RegisterInfo* full_reg_info = emulator_baton->m_reg_context->GetRegisterInfo(
2275e7708688STamas Berghammer             eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
2276e7708688STamas Berghammer 
2277e7708688STamas Berghammer     Error error = emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
22786648fcc3SPavel Labath     if (error.Success())
22796648fcc3SPavel Labath         return true;
2280cdc22a88SMohit K. Bhakkad 
22816648fcc3SPavel Labath     return false;
2282e7708688STamas Berghammer }
2283e7708688STamas Berghammer 
2284e7708688STamas Berghammer static bool
2285e7708688STamas Berghammer WriteRegisterCallback (EmulateInstruction *instruction,
2286e7708688STamas Berghammer                        void *baton,
2287e7708688STamas Berghammer                        const EmulateInstruction::Context &context,
2288e7708688STamas Berghammer                        const RegisterInfo *reg_info,
2289e7708688STamas Berghammer                        const RegisterValue &reg_value)
2290e7708688STamas Berghammer {
2291e7708688STamas Berghammer     EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
22926648fcc3SPavel Labath     emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = reg_value;
2293e7708688STamas Berghammer     return true;
2294e7708688STamas Berghammer }
2295e7708688STamas Berghammer 
2296e7708688STamas Berghammer static size_t
2297e7708688STamas Berghammer WriteMemoryCallback (EmulateInstruction *instruction,
2298e7708688STamas Berghammer                      void *baton,
2299e7708688STamas Berghammer                      const EmulateInstruction::Context &context,
2300e7708688STamas Berghammer                      lldb::addr_t addr,
2301e7708688STamas Berghammer                      const void *dst,
2302e7708688STamas Berghammer                      size_t length)
2303e7708688STamas Berghammer {
2304e7708688STamas Berghammer     return length;
2305e7708688STamas Berghammer }
2306e7708688STamas Berghammer 
2307e7708688STamas Berghammer static lldb::addr_t
2308e7708688STamas Berghammer ReadFlags (NativeRegisterContext* regsiter_context)
2309e7708688STamas Berghammer {
2310e7708688STamas Berghammer     const RegisterInfo* flags_info = regsiter_context->GetRegisterInfo(
2311e7708688STamas Berghammer             eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
2312e7708688STamas Berghammer     return regsiter_context->ReadRegisterAsUnsigned(flags_info, LLDB_INVALID_ADDRESS);
2313e7708688STamas Berghammer }
2314e7708688STamas Berghammer 
2315e7708688STamas Berghammer Error
2316e7708688STamas Berghammer NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadProtocolSP thread_sp)
2317e7708688STamas Berghammer {
2318e7708688STamas Berghammer     Error error;
2319e7708688STamas Berghammer     NativeRegisterContextSP register_context_sp = thread_sp->GetRegisterContext();
2320e7708688STamas Berghammer 
2321e7708688STamas Berghammer     std::unique_ptr<EmulateInstruction> emulator_ap(
2322e7708688STamas Berghammer         EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, nullptr));
2323e7708688STamas Berghammer 
2324e7708688STamas Berghammer     if (emulator_ap == nullptr)
2325e7708688STamas Berghammer         return Error("Instruction emulator not found!");
2326e7708688STamas Berghammer 
2327e7708688STamas Berghammer     EmulatorBaton baton(this, register_context_sp.get());
2328e7708688STamas Berghammer     emulator_ap->SetBaton(&baton);
2329e7708688STamas Berghammer     emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
2330e7708688STamas Berghammer     emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
2331e7708688STamas Berghammer     emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
2332e7708688STamas Berghammer     emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
2333e7708688STamas Berghammer 
2334e7708688STamas Berghammer     if (!emulator_ap->ReadInstruction())
2335e7708688STamas Berghammer         return Error("Read instruction failed!");
2336e7708688STamas Berghammer 
23376648fcc3SPavel Labath     bool emulation_result = emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
23386648fcc3SPavel Labath 
23396648fcc3SPavel Labath     const RegisterInfo* reg_info_pc = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
23406648fcc3SPavel Labath     const RegisterInfo* reg_info_flags = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
23416648fcc3SPavel Labath 
23426648fcc3SPavel Labath     auto pc_it = baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
23436648fcc3SPavel Labath     auto flags_it = baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
23446648fcc3SPavel Labath 
2345e7708688STamas Berghammer     lldb::addr_t next_pc;
2346e7708688STamas Berghammer     lldb::addr_t next_flags;
23476648fcc3SPavel Labath     if (emulation_result)
2348e7708688STamas Berghammer     {
23496648fcc3SPavel Labath         assert(pc_it != baton.m_register_values.end() && "Emulation was successfull but PC wasn't updated");
23506648fcc3SPavel Labath         next_pc = pc_it->second.GetAsUInt64();
23516648fcc3SPavel Labath 
23526648fcc3SPavel Labath         if (flags_it != baton.m_register_values.end())
23536648fcc3SPavel Labath             next_flags = flags_it->second.GetAsUInt64();
2354e7708688STamas Berghammer         else
2355e7708688STamas Berghammer             next_flags = ReadFlags (register_context_sp.get());
2356e7708688STamas Berghammer     }
23576648fcc3SPavel Labath     else if (pc_it == baton.m_register_values.end())
2358e7708688STamas Berghammer     {
2359e7708688STamas Berghammer         // Emulate instruction failed and it haven't changed PC. Advance PC
2360e7708688STamas Berghammer         // with the size of the current opcode because the emulation of all
2361e7708688STamas Berghammer         // PC modifying instruction should be successful. The failure most
2362e7708688STamas Berghammer         // likely caused by a not supported instruction which don't modify PC.
2363e7708688STamas Berghammer         next_pc = register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
2364e7708688STamas Berghammer         next_flags = ReadFlags (register_context_sp.get());
2365e7708688STamas Berghammer     }
2366e7708688STamas Berghammer     else
2367e7708688STamas Berghammer     {
2368e7708688STamas Berghammer         // The instruction emulation failed after it modified the PC. It is an
2369e7708688STamas Berghammer         // unknown error where we can't continue because the next instruction is
2370e7708688STamas Berghammer         // modifying the PC but we don't  know how.
2371e7708688STamas Berghammer         return Error ("Instruction emulation failed unexpectedly.");
2372e7708688STamas Berghammer     }
2373e7708688STamas Berghammer 
2374e7708688STamas Berghammer     if (m_arch.GetMachine() == llvm::Triple::arm)
2375e7708688STamas Berghammer     {
2376e7708688STamas Berghammer         if (next_flags & 0x20)
2377e7708688STamas Berghammer         {
2378e7708688STamas Berghammer             // Thumb mode
2379e7708688STamas Berghammer             error = SetSoftwareBreakpoint(next_pc, 2);
2380e7708688STamas Berghammer         }
2381e7708688STamas Berghammer         else
2382e7708688STamas Berghammer         {
2383e7708688STamas Berghammer             // Arm mode
2384e7708688STamas Berghammer             error = SetSoftwareBreakpoint(next_pc, 4);
2385e7708688STamas Berghammer         }
2386e7708688STamas Berghammer     }
2387cdc22a88SMohit K. Bhakkad     else if (m_arch.GetMachine() == llvm::Triple::mips64
2388cdc22a88SMohit K. Bhakkad             || m_arch.GetMachine() == llvm::Triple::mips64el)
2389cdc22a88SMohit K. Bhakkad         error = SetSoftwareBreakpoint(next_pc, 4);
2390e7708688STamas Berghammer     else
2391e7708688STamas Berghammer     {
2392e7708688STamas Berghammer         // No size hint is given for the next breakpoint
2393e7708688STamas Berghammer         error = SetSoftwareBreakpoint(next_pc, 0);
2394e7708688STamas Berghammer     }
2395e7708688STamas Berghammer 
2396e7708688STamas Berghammer     if (error.Fail())
2397e7708688STamas Berghammer         return error;
2398e7708688STamas Berghammer 
2399e7708688STamas Berghammer     m_threads_stepping_with_breakpoint.insert({thread_sp->GetID(), next_pc});
2400e7708688STamas Berghammer 
2401e7708688STamas Berghammer     return Error();
2402e7708688STamas Berghammer }
2403e7708688STamas Berghammer 
2404e7708688STamas Berghammer bool
2405e7708688STamas Berghammer NativeProcessLinux::SupportHardwareSingleStepping() const
2406e7708688STamas Berghammer {
2407cdc22a88SMohit K. Bhakkad     if (m_arch.GetMachine() == llvm::Triple::arm
2408cdc22a88SMohit K. Bhakkad         || m_arch.GetMachine() == llvm::Triple::mips64 || m_arch.GetMachine() == llvm::Triple::mips64el)
2409cdc22a88SMohit K. Bhakkad         return false;
2410cdc22a88SMohit K. Bhakkad     return true;
2411e7708688STamas Berghammer }
2412e7708688STamas Berghammer 
2413af245d11STodd Fiala Error
2414af245d11STodd Fiala NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
2415af245d11STodd Fiala {
2416af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2417af245d11STodd Fiala     if (log)
2418af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
2419af245d11STodd Fiala 
2420e7708688STamas Berghammer     bool software_single_step = !SupportHardwareSingleStepping();
2421af245d11STodd Fiala 
242245f5cb31SPavel Labath     Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
2423af245d11STodd Fiala     Mutex::Locker locker (m_threads_mutex);
24245830aa75STamas Berghammer 
2425e7708688STamas Berghammer     if (software_single_step)
2426e7708688STamas Berghammer     {
2427e7708688STamas Berghammer         for (auto thread_sp : m_threads)
2428e7708688STamas Berghammer         {
2429e7708688STamas Berghammer             assert (thread_sp && "thread list should not contain NULL threads");
2430e7708688STamas Berghammer 
2431e7708688STamas Berghammer             const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
2432e7708688STamas Berghammer             if (action == nullptr)
2433e7708688STamas Berghammer                 continue;
2434e7708688STamas Berghammer 
2435e7708688STamas Berghammer             if (action->state == eStateStepping)
2436e7708688STamas Berghammer             {
2437e7708688STamas Berghammer                 Error error = SetupSoftwareSingleStepping(thread_sp);
2438e7708688STamas Berghammer                 if (error.Fail())
2439e7708688STamas Berghammer                     return error;
2440e7708688STamas Berghammer             }
2441e7708688STamas Berghammer         }
2442e7708688STamas Berghammer     }
2443e7708688STamas Berghammer 
2444af245d11STodd Fiala     for (auto thread_sp : m_threads)
2445af245d11STodd Fiala     {
2446af245d11STodd Fiala         assert (thread_sp && "thread list should not contain NULL threads");
2447af245d11STodd Fiala 
2448af245d11STodd Fiala         const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
24496a196ce6SChaoren Lin 
24506a196ce6SChaoren Lin         if (action == nullptr)
24516a196ce6SChaoren Lin         {
24526a196ce6SChaoren Lin             if (log)
24536a196ce6SChaoren Lin                 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
24546a196ce6SChaoren Lin                     __FUNCTION__, GetID (), thread_sp->GetID ());
24556a196ce6SChaoren Lin             continue;
24566a196ce6SChaoren Lin         }
2457af245d11STodd Fiala 
2458af245d11STodd Fiala         if (log)
2459af245d11STodd Fiala         {
2460af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
2461af245d11STodd Fiala                     __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
2462af245d11STodd Fiala         }
2463af245d11STodd Fiala 
2464af245d11STodd Fiala         switch (action->state)
2465af245d11STodd Fiala         {
2466af245d11STodd Fiala         case eStateRunning:
2467fa03ad2eSChaoren Lin         {
2468af245d11STodd Fiala             // Run the thread, possibly feeding it the signal.
2469fa03ad2eSChaoren Lin             const int signo = action->signal;
24701dbc6c9cSPavel Labath             ResumeThread(thread_sp->GetID (),
247186fd8e45SChaoren Lin                     [=](lldb::tid_t tid_to_resume, bool supress_signal)
2472af245d11STodd Fiala                     {
2473cb84eebbSTamas Berghammer                         std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2474fa03ad2eSChaoren Lin                         // Pass this signal number on to the inferior to handle.
24755830aa75STamas Berghammer                         const auto resume_result = Resume (tid_to_resume, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
24765830aa75STamas Berghammer                         if (resume_result.Success())
24775830aa75STamas Berghammer                             SetState(eStateRunning, true);
24785830aa75STamas Berghammer                         return resume_result;
24791dbc6c9cSPavel Labath                     },
24801dbc6c9cSPavel Labath                     false);
2481af245d11STodd Fiala             break;
2482fa03ad2eSChaoren Lin         }
2483af245d11STodd Fiala 
2484af245d11STodd Fiala         case eStateStepping:
2485af245d11STodd Fiala         {
2486ae29d395SChaoren Lin             // Request the step.
2487ae29d395SChaoren Lin             const int signo = action->signal;
24881dbc6c9cSPavel Labath             ResumeThread(thread_sp->GetID (),
248986fd8e45SChaoren Lin                     [=](lldb::tid_t tid_to_step, bool supress_signal)
2490af245d11STodd Fiala                     {
2491cb84eebbSTamas Berghammer                         std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStepping ();
2492e7708688STamas Berghammer 
2493e7708688STamas Berghammer                         Error step_result;
2494e7708688STamas Berghammer                         if (software_single_step)
2495e7708688STamas Berghammer                             step_result = Resume (tid_to_step, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
2496e7708688STamas Berghammer                         else
2497e7708688STamas Berghammer                             step_result = SingleStep (tid_to_step,(signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
2498e7708688STamas Berghammer 
249937c768caSChaoren Lin                         assert (step_result.Success() && "SingleStep() failed");
25005830aa75STamas Berghammer                         if (step_result.Success())
25015830aa75STamas Berghammer                             SetState(eStateStepping, true);
250237c768caSChaoren Lin                         return step_result;
25031dbc6c9cSPavel Labath                     },
25041dbc6c9cSPavel Labath                     false);
2505af245d11STodd Fiala             break;
2506ae29d395SChaoren Lin         }
2507af245d11STodd Fiala 
2508af245d11STodd Fiala         case eStateSuspended:
2509af245d11STodd Fiala         case eStateStopped:
2510108c325dSPavel Labath             lldbassert(0 && "Unexpected state");
2511af245d11STodd Fiala 
2512af245d11STodd Fiala         default:
2513af245d11STodd Fiala             return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
2514af245d11STodd Fiala                     __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
2515af245d11STodd Fiala         }
2516af245d11STodd Fiala     }
2517af245d11STodd Fiala 
25185830aa75STamas Berghammer     return Error();
2519af245d11STodd Fiala }
2520af245d11STodd Fiala 
2521af245d11STodd Fiala Error
2522af245d11STodd Fiala NativeProcessLinux::Halt ()
2523af245d11STodd Fiala {
2524af245d11STodd Fiala     Error error;
2525af245d11STodd Fiala 
2526af245d11STodd Fiala     if (kill (GetID (), SIGSTOP) != 0)
2527af245d11STodd Fiala         error.SetErrorToErrno ();
2528af245d11STodd Fiala 
2529af245d11STodd Fiala     return error;
2530af245d11STodd Fiala }
2531af245d11STodd Fiala 
2532af245d11STodd Fiala Error
2533af245d11STodd Fiala NativeProcessLinux::Detach ()
2534af245d11STodd Fiala {
2535af245d11STodd Fiala     Error error;
2536af245d11STodd Fiala 
2537af245d11STodd Fiala     // Tell ptrace to detach from the process.
2538af245d11STodd Fiala     if (GetID () != LLDB_INVALID_PROCESS_ID)
2539af245d11STodd Fiala         error = Detach (GetID ());
2540af245d11STodd Fiala 
2541af245d11STodd Fiala     // Stop monitoring the inferior.
254245f5cb31SPavel Labath     m_monitor_up->Terminate();
2543af245d11STodd Fiala 
2544af245d11STodd Fiala     // No error.
2545af245d11STodd Fiala     return error;
2546af245d11STodd Fiala }
2547af245d11STodd Fiala 
2548af245d11STodd Fiala Error
2549af245d11STodd Fiala NativeProcessLinux::Signal (int signo)
2550af245d11STodd Fiala {
2551af245d11STodd Fiala     Error error;
2552af245d11STodd Fiala 
2553af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2554af245d11STodd Fiala     if (log)
2555af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
2556af245d11STodd Fiala                 __FUNCTION__, signo,  GetUnixSignals ().GetSignalAsCString (signo), GetID ());
2557af245d11STodd Fiala 
2558af245d11STodd Fiala     if (kill(GetID(), signo))
2559af245d11STodd Fiala         error.SetErrorToErrno();
2560af245d11STodd Fiala 
2561af245d11STodd Fiala     return error;
2562af245d11STodd Fiala }
2563af245d11STodd Fiala 
2564af245d11STodd Fiala Error
2565e9547b80SChaoren Lin NativeProcessLinux::Interrupt ()
2566e9547b80SChaoren Lin {
2567e9547b80SChaoren Lin     // Pick a running thread (or if none, a not-dead stopped thread) as
2568e9547b80SChaoren Lin     // the chosen thread that will be the stop-reason thread.
2569e9547b80SChaoren Lin     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2570e9547b80SChaoren Lin 
2571e9547b80SChaoren Lin     NativeThreadProtocolSP running_thread_sp;
2572e9547b80SChaoren Lin     NativeThreadProtocolSP stopped_thread_sp;
2573e9547b80SChaoren Lin 
2574e9547b80SChaoren Lin     if (log)
2575e9547b80SChaoren Lin         log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
2576e9547b80SChaoren Lin 
257745f5cb31SPavel Labath     Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
25785830aa75STamas Berghammer     Mutex::Locker locker (m_threads_mutex);
25795830aa75STamas Berghammer 
2580e9547b80SChaoren Lin     for (auto thread_sp : m_threads)
2581e9547b80SChaoren Lin     {
2582e9547b80SChaoren Lin         // The thread shouldn't be null but lets just cover that here.
2583e9547b80SChaoren Lin         if (!thread_sp)
2584e9547b80SChaoren Lin             continue;
2585e9547b80SChaoren Lin 
2586e9547b80SChaoren Lin         // If we have a running or stepping thread, we'll call that the
2587e9547b80SChaoren Lin         // target of the interrupt.
2588e9547b80SChaoren Lin         const auto thread_state = thread_sp->GetState ();
2589e9547b80SChaoren Lin         if (thread_state == eStateRunning ||
2590e9547b80SChaoren Lin             thread_state == eStateStepping)
2591e9547b80SChaoren Lin         {
2592e9547b80SChaoren Lin             running_thread_sp = thread_sp;
2593e9547b80SChaoren Lin             break;
2594e9547b80SChaoren Lin         }
2595e9547b80SChaoren Lin         else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
2596e9547b80SChaoren Lin         {
2597e9547b80SChaoren Lin             // Remember the first non-dead stopped thread.  We'll use that as a backup if there are no running threads.
2598e9547b80SChaoren Lin             stopped_thread_sp = thread_sp;
2599e9547b80SChaoren Lin         }
2600e9547b80SChaoren Lin     }
2601e9547b80SChaoren Lin 
2602e9547b80SChaoren Lin     if (!running_thread_sp && !stopped_thread_sp)
2603e9547b80SChaoren Lin     {
26045830aa75STamas Berghammer         Error error("found no running/stepping or live stopped threads as target for interrupt");
2605e9547b80SChaoren Lin         if (log)
2606e9547b80SChaoren Lin             log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
26075830aa75STamas Berghammer 
2608e9547b80SChaoren Lin         return error;
2609e9547b80SChaoren Lin     }
2610e9547b80SChaoren Lin 
2611e9547b80SChaoren Lin     NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
2612e9547b80SChaoren Lin 
2613e9547b80SChaoren Lin     if (log)
2614e9547b80SChaoren Lin         log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
2615e9547b80SChaoren Lin                      __FUNCTION__,
2616e9547b80SChaoren Lin                      GetID (),
2617e9547b80SChaoren Lin                      running_thread_sp ? "running" : "stopped",
2618e9547b80SChaoren Lin                      deferred_signal_thread_sp->GetID ());
2619e9547b80SChaoren Lin 
2620ed89c7feSPavel Labath     StopRunningThreads(deferred_signal_thread_sp->GetID());
262145f5cb31SPavel Labath 
26225830aa75STamas Berghammer     return Error();
2623e9547b80SChaoren Lin }
2624e9547b80SChaoren Lin 
2625e9547b80SChaoren Lin Error
2626af245d11STodd Fiala NativeProcessLinux::Kill ()
2627af245d11STodd Fiala {
2628af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2629af245d11STodd Fiala     if (log)
2630af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
2631af245d11STodd Fiala 
2632af245d11STodd Fiala     Error error;
2633af245d11STodd Fiala 
2634af245d11STodd Fiala     switch (m_state)
2635af245d11STodd Fiala     {
2636af245d11STodd Fiala         case StateType::eStateInvalid:
2637af245d11STodd Fiala         case StateType::eStateExited:
2638af245d11STodd Fiala         case StateType::eStateCrashed:
2639af245d11STodd Fiala         case StateType::eStateDetached:
2640af245d11STodd Fiala         case StateType::eStateUnloaded:
2641af245d11STodd Fiala             // Nothing to do - the process is already dead.
2642af245d11STodd Fiala             if (log)
2643af245d11STodd Fiala                 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
2644af245d11STodd Fiala             return error;
2645af245d11STodd Fiala 
2646af245d11STodd Fiala         case StateType::eStateConnected:
2647af245d11STodd Fiala         case StateType::eStateAttaching:
2648af245d11STodd Fiala         case StateType::eStateLaunching:
2649af245d11STodd Fiala         case StateType::eStateStopped:
2650af245d11STodd Fiala         case StateType::eStateRunning:
2651af245d11STodd Fiala         case StateType::eStateStepping:
2652af245d11STodd Fiala         case StateType::eStateSuspended:
2653af245d11STodd Fiala             // We can try to kill a process in these states.
2654af245d11STodd Fiala             break;
2655af245d11STodd Fiala     }
2656af245d11STodd Fiala 
2657af245d11STodd Fiala     if (kill (GetID (), SIGKILL) != 0)
2658af245d11STodd Fiala     {
2659af245d11STodd Fiala         error.SetErrorToErrno ();
2660af245d11STodd Fiala         return error;
2661af245d11STodd Fiala     }
2662af245d11STodd Fiala 
2663af245d11STodd Fiala     return error;
2664af245d11STodd Fiala }
2665af245d11STodd Fiala 
2666af245d11STodd Fiala static Error
2667af245d11STodd Fiala ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
2668af245d11STodd Fiala {
2669af245d11STodd Fiala     memory_region_info.Clear();
2670af245d11STodd Fiala 
2671af245d11STodd Fiala     StringExtractor line_extractor (maps_line.c_str ());
2672af245d11STodd Fiala 
2673af245d11STodd Fiala     // Format: {address_start_hex}-{address_end_hex} perms offset  dev   inode   pathname
2674af245d11STodd Fiala     // perms: rwxp   (letter is present if set, '-' if not, final character is p=private, s=shared).
2675af245d11STodd Fiala 
2676af245d11STodd Fiala     // Parse out the starting address
2677af245d11STodd Fiala     lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
2678af245d11STodd Fiala 
2679af245d11STodd Fiala     // Parse out hyphen separating start and end address from range.
2680af245d11STodd Fiala     if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
2681af245d11STodd Fiala         return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
2682af245d11STodd Fiala 
2683af245d11STodd Fiala     // Parse out the ending address
2684af245d11STodd Fiala     lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
2685af245d11STodd Fiala 
2686af245d11STodd Fiala     // Parse out the space after the address.
2687af245d11STodd Fiala     if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
2688af245d11STodd Fiala         return Error ("malformed /proc/{pid}/maps entry, missing space after range");
2689af245d11STodd Fiala 
2690af245d11STodd Fiala     // Save the range.
2691af245d11STodd Fiala     memory_region_info.GetRange ().SetRangeBase (start_address);
2692af245d11STodd Fiala     memory_region_info.GetRange ().SetRangeEnd (end_address);
2693af245d11STodd Fiala 
2694af245d11STodd Fiala     // Parse out each permission entry.
2695af245d11STodd Fiala     if (line_extractor.GetBytesLeft () < 4)
2696af245d11STodd Fiala         return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
2697af245d11STodd Fiala 
2698af245d11STodd Fiala     // Handle read permission.
2699af245d11STodd Fiala     const char read_perm_char = line_extractor.GetChar ();
2700af245d11STodd Fiala     if (read_perm_char == 'r')
2701af245d11STodd Fiala         memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
2702af245d11STodd Fiala     else
2703af245d11STodd Fiala     {
2704af245d11STodd Fiala         assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
2705af245d11STodd Fiala         memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2706af245d11STodd Fiala     }
2707af245d11STodd Fiala 
2708af245d11STodd Fiala     // Handle write permission.
2709af245d11STodd Fiala     const char write_perm_char = line_extractor.GetChar ();
2710af245d11STodd Fiala     if (write_perm_char == 'w')
2711af245d11STodd Fiala         memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
2712af245d11STodd Fiala     else
2713af245d11STodd Fiala     {
2714af245d11STodd Fiala         assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
2715af245d11STodd Fiala         memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2716af245d11STodd Fiala     }
2717af245d11STodd Fiala 
2718af245d11STodd Fiala     // Handle execute permission.
2719af245d11STodd Fiala     const char exec_perm_char = line_extractor.GetChar ();
2720af245d11STodd Fiala     if (exec_perm_char == 'x')
2721af245d11STodd Fiala         memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
2722af245d11STodd Fiala     else
2723af245d11STodd Fiala     {
2724af245d11STodd Fiala         assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
2725af245d11STodd Fiala         memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2726af245d11STodd Fiala     }
2727af245d11STodd Fiala 
2728af245d11STodd Fiala     return Error ();
2729af245d11STodd Fiala }
2730af245d11STodd Fiala 
2731af245d11STodd Fiala Error
2732af245d11STodd Fiala NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
2733af245d11STodd Fiala {
2734af245d11STodd Fiala     // FIXME review that the final memory region returned extends to the end of the virtual address space,
2735af245d11STodd Fiala     // with no perms if it is not mapped.
2736af245d11STodd Fiala 
2737af245d11STodd Fiala     // Use an approach that reads memory regions from /proc/{pid}/maps.
2738af245d11STodd Fiala     // Assume proc maps entries are in ascending order.
2739af245d11STodd Fiala     // FIXME assert if we find differently.
2740af245d11STodd Fiala     Mutex::Locker locker (m_mem_region_cache_mutex);
2741af245d11STodd Fiala 
2742af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2743af245d11STodd Fiala     Error error;
2744af245d11STodd Fiala 
2745af245d11STodd Fiala     if (m_supports_mem_region == LazyBool::eLazyBoolNo)
2746af245d11STodd Fiala     {
2747af245d11STodd Fiala         // We're done.
2748af245d11STodd Fiala         error.SetErrorString ("unsupported");
2749af245d11STodd Fiala         return error;
2750af245d11STodd Fiala     }
2751af245d11STodd Fiala 
2752af245d11STodd Fiala     // If our cache is empty, pull the latest.  There should always be at least one memory region
2753af245d11STodd Fiala     // if memory region handling is supported.
2754af245d11STodd Fiala     if (m_mem_region_cache.empty ())
2755af245d11STodd Fiala     {
2756af245d11STodd Fiala         error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
2757af245d11STodd Fiala              [&] (const std::string &line) -> bool
2758af245d11STodd Fiala              {
2759af245d11STodd Fiala                  MemoryRegionInfo info;
2760af245d11STodd Fiala                  const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
2761af245d11STodd Fiala                  if (parse_error.Success ())
2762af245d11STodd Fiala                  {
2763af245d11STodd Fiala                      m_mem_region_cache.push_back (info);
2764af245d11STodd Fiala                      return true;
2765af245d11STodd Fiala                  }
2766af245d11STodd Fiala                  else
2767af245d11STodd Fiala                  {
2768af245d11STodd Fiala                      if (log)
2769af245d11STodd Fiala                          log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
2770af245d11STodd Fiala                      return false;
2771af245d11STodd Fiala                  }
2772af245d11STodd Fiala              });
2773af245d11STodd Fiala 
2774af245d11STodd Fiala         // If we had an error, we'll mark unsupported.
2775af245d11STodd Fiala         if (error.Fail ())
2776af245d11STodd Fiala         {
2777af245d11STodd Fiala             m_supports_mem_region = LazyBool::eLazyBoolNo;
2778af245d11STodd Fiala             return error;
2779af245d11STodd Fiala         }
2780af245d11STodd Fiala         else if (m_mem_region_cache.empty ())
2781af245d11STodd Fiala         {
2782af245d11STodd Fiala             // No entries after attempting to read them.  This shouldn't happen if /proc/{pid}/maps
2783af245d11STodd Fiala             // is supported.  Assume we don't support map entries via procfs.
2784af245d11STodd Fiala             if (log)
2785af245d11STodd Fiala                 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
2786af245d11STodd Fiala             m_supports_mem_region = LazyBool::eLazyBoolNo;
2787af245d11STodd Fiala             error.SetErrorString ("not supported");
2788af245d11STodd Fiala             return error;
2789af245d11STodd Fiala         }
2790af245d11STodd Fiala 
2791af245d11STodd Fiala         if (log)
2792af245d11STodd 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 ());
2793af245d11STodd Fiala 
2794af245d11STodd Fiala         // We support memory retrieval, remember that.
2795af245d11STodd Fiala         m_supports_mem_region = LazyBool::eLazyBoolYes;
2796af245d11STodd Fiala     }
2797af245d11STodd Fiala     else
2798af245d11STodd Fiala     {
2799af245d11STodd Fiala         if (log)
2800af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2801af245d11STodd Fiala     }
2802af245d11STodd Fiala 
2803af245d11STodd Fiala     lldb::addr_t prev_base_address = 0;
2804af245d11STodd Fiala 
2805af245d11STodd Fiala     // FIXME start by finding the last region that is <= target address using binary search.  Data is sorted.
2806af245d11STodd Fiala     // There can be a ton of regions on pthreads apps with lots of threads.
2807af245d11STodd Fiala     for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
2808af245d11STodd Fiala     {
2809af245d11STodd Fiala         MemoryRegionInfo &proc_entry_info = *it;
2810af245d11STodd Fiala 
2811af245d11STodd Fiala         // Sanity check assumption that /proc/{pid}/maps entries are ascending.
2812af245d11STodd Fiala         assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
2813af245d11STodd Fiala         prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
2814af245d11STodd Fiala 
2815af245d11STodd Fiala         // If the target address comes before this entry, indicate distance to next region.
2816af245d11STodd Fiala         if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
2817af245d11STodd Fiala         {
2818af245d11STodd Fiala             range_info.GetRange ().SetRangeBase (load_addr);
2819af245d11STodd Fiala             range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
2820af245d11STodd Fiala             range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2821af245d11STodd Fiala             range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2822af245d11STodd Fiala             range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2823af245d11STodd Fiala 
2824af245d11STodd Fiala             return error;
2825af245d11STodd Fiala         }
2826af245d11STodd Fiala         else if (proc_entry_info.GetRange ().Contains (load_addr))
2827af245d11STodd Fiala         {
2828af245d11STodd Fiala             // The target address is within the memory region we're processing here.
2829af245d11STodd Fiala             range_info = proc_entry_info;
2830af245d11STodd Fiala             return error;
2831af245d11STodd Fiala         }
2832af245d11STodd Fiala 
2833af245d11STodd Fiala         // The target memory address comes somewhere after the region we just parsed.
2834af245d11STodd Fiala     }
2835af245d11STodd Fiala 
2836af245d11STodd Fiala     // If we made it here, we didn't find an entry that contained the given address.
2837af245d11STodd Fiala     error.SetErrorString ("address comes after final region");
2838af245d11STodd Fiala 
2839af245d11STodd Fiala     if (log)
2840af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s failed to find map entry for address 0x%" PRIx64 ": %s", __FUNCTION__, load_addr, error.AsCString ());
2841af245d11STodd Fiala 
2842af245d11STodd Fiala     return error;
2843af245d11STodd Fiala }
2844af245d11STodd Fiala 
2845af245d11STodd Fiala void
2846af245d11STodd Fiala NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
2847af245d11STodd Fiala {
2848af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2849af245d11STodd Fiala     if (log)
2850af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
2851af245d11STodd Fiala 
2852af245d11STodd Fiala     {
2853af245d11STodd Fiala         Mutex::Locker locker (m_mem_region_cache_mutex);
2854af245d11STodd Fiala         if (log)
2855af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2856af245d11STodd Fiala         m_mem_region_cache.clear ();
2857af245d11STodd Fiala     }
2858af245d11STodd Fiala }
2859af245d11STodd Fiala 
2860af245d11STodd Fiala Error
28613eb4b458SChaoren Lin NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr)
2862af245d11STodd Fiala {
2863af245d11STodd Fiala     // FIXME implementing this requires the equivalent of
2864af245d11STodd Fiala     // InferiorCallPOSIX::InferiorCallMmap, which depends on
2865af245d11STodd Fiala     // functional ThreadPlans working with Native*Protocol.
2866af245d11STodd Fiala #if 1
2867af245d11STodd Fiala     return Error ("not implemented yet");
2868af245d11STodd Fiala #else
2869af245d11STodd Fiala     addr = LLDB_INVALID_ADDRESS;
2870af245d11STodd Fiala 
2871af245d11STodd Fiala     unsigned prot = 0;
2872af245d11STodd Fiala     if (permissions & lldb::ePermissionsReadable)
2873af245d11STodd Fiala         prot |= eMmapProtRead;
2874af245d11STodd Fiala     if (permissions & lldb::ePermissionsWritable)
2875af245d11STodd Fiala         prot |= eMmapProtWrite;
2876af245d11STodd Fiala     if (permissions & lldb::ePermissionsExecutable)
2877af245d11STodd Fiala         prot |= eMmapProtExec;
2878af245d11STodd Fiala 
2879af245d11STodd Fiala     // TODO implement this directly in NativeProcessLinux
2880af245d11STodd Fiala     // (and lift to NativeProcessPOSIX if/when that class is
2881af245d11STodd Fiala     // refactored out).
2882af245d11STodd Fiala     if (InferiorCallMmap(this, addr, 0, size, prot,
2883af245d11STodd Fiala                          eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
2884af245d11STodd Fiala         m_addr_to_mmap_size[addr] = size;
2885af245d11STodd Fiala         return Error ();
2886af245d11STodd Fiala     } else {
2887af245d11STodd Fiala         addr = LLDB_INVALID_ADDRESS;
2888af245d11STodd Fiala         return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
2889af245d11STodd Fiala     }
2890af245d11STodd Fiala #endif
2891af245d11STodd Fiala }
2892af245d11STodd Fiala 
2893af245d11STodd Fiala Error
2894af245d11STodd Fiala NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
2895af245d11STodd Fiala {
2896af245d11STodd Fiala     // FIXME see comments in AllocateMemory - required lower-level
2897af245d11STodd Fiala     // bits not in place yet (ThreadPlans)
2898af245d11STodd Fiala     return Error ("not implemented");
2899af245d11STodd Fiala }
2900af245d11STodd Fiala 
2901af245d11STodd Fiala lldb::addr_t
2902af245d11STodd Fiala NativeProcessLinux::GetSharedLibraryInfoAddress ()
2903af245d11STodd Fiala {
2904af245d11STodd Fiala #if 1
2905af245d11STodd Fiala     // punt on this for now
2906af245d11STodd Fiala     return LLDB_INVALID_ADDRESS;
2907af245d11STodd Fiala #else
2908af245d11STodd Fiala     // Return the image info address for the exe module
2909af245d11STodd Fiala #if 1
2910af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2911af245d11STodd Fiala 
2912af245d11STodd Fiala     ModuleSP module_sp;
2913af245d11STodd Fiala     Error error = GetExeModuleSP (module_sp);
2914af245d11STodd Fiala     if (error.Fail ())
2915af245d11STodd Fiala     {
2916af245d11STodd Fiala          if (log)
2917af245d11STodd Fiala             log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ());
2918af245d11STodd Fiala         return LLDB_INVALID_ADDRESS;
2919af245d11STodd Fiala     }
2920af245d11STodd Fiala 
2921af245d11STodd Fiala     if (module_sp == nullptr)
2922af245d11STodd Fiala     {
2923af245d11STodd Fiala          if (log)
2924af245d11STodd Fiala             log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__);
2925af245d11STodd Fiala          return LLDB_INVALID_ADDRESS;
2926af245d11STodd Fiala     }
2927af245d11STodd Fiala 
2928af245d11STodd Fiala     ObjectFileSP object_file_sp = module_sp->GetObjectFile ();
2929af245d11STodd Fiala     if (object_file_sp == nullptr)
2930af245d11STodd Fiala     {
2931af245d11STodd Fiala          if (log)
2932af245d11STodd Fiala             log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__);
2933af245d11STodd Fiala          return LLDB_INVALID_ADDRESS;
2934af245d11STodd Fiala     }
2935af245d11STodd Fiala 
2936af245d11STodd Fiala     return obj_file_sp->GetImageInfoAddress();
2937af245d11STodd Fiala #else
2938af245d11STodd Fiala     Target *target = &GetTarget();
2939af245d11STodd Fiala     ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
2940af245d11STodd Fiala     Address addr = obj_file->GetImageInfoAddress(target);
2941af245d11STodd Fiala 
2942af245d11STodd Fiala     if (addr.IsValid())
2943af245d11STodd Fiala         return addr.GetLoadAddress(target);
2944af245d11STodd Fiala     return LLDB_INVALID_ADDRESS;
2945af245d11STodd Fiala #endif
2946af245d11STodd Fiala #endif // punt on this for now
2947af245d11STodd Fiala }
2948af245d11STodd Fiala 
2949af245d11STodd Fiala size_t
2950af245d11STodd Fiala NativeProcessLinux::UpdateThreads ()
2951af245d11STodd Fiala {
2952af245d11STodd Fiala     // The NativeProcessLinux monitoring threads are always up to date
2953af245d11STodd Fiala     // with respect to thread state and they keep the thread list
2954af245d11STodd Fiala     // populated properly. All this method needs to do is return the
2955af245d11STodd Fiala     // thread count.
2956af245d11STodd Fiala     Mutex::Locker locker (m_threads_mutex);
2957af245d11STodd Fiala     return m_threads.size ();
2958af245d11STodd Fiala }
2959af245d11STodd Fiala 
2960af245d11STodd Fiala bool
2961af245d11STodd Fiala NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
2962af245d11STodd Fiala {
2963af245d11STodd Fiala     arch = m_arch;
2964af245d11STodd Fiala     return true;
2965af245d11STodd Fiala }
2966af245d11STodd Fiala 
2967af245d11STodd Fiala Error
296863c8be95STamas Berghammer NativeProcessLinux::GetSoftwareBreakpointPCOffset (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size)
2969af245d11STodd Fiala {
2970af245d11STodd Fiala     // FIXME put this behind a breakpoint protocol class that can be
2971af245d11STodd Fiala     // set per architecture.  Need ARM, MIPS support here.
29722afc5966STodd Fiala     static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
2973af245d11STodd Fiala     static const uint8_t g_i386_opcode [] = { 0xCC };
2974e8659b5dSMohit K. Bhakkad     static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
2975af245d11STodd Fiala 
2976af245d11STodd Fiala     switch (m_arch.GetMachine ())
2977af245d11STodd Fiala     {
29782afc5966STodd Fiala         case llvm::Triple::aarch64:
29792afc5966STodd Fiala             actual_opcode_size = static_cast<uint32_t> (sizeof(g_aarch64_opcode));
29802afc5966STodd Fiala             return Error ();
29812afc5966STodd Fiala 
298263c8be95STamas Berghammer         case llvm::Triple::arm:
298363c8be95STamas Berghammer             actual_opcode_size = 0; // On arm the PC don't get updated for breakpoint hits
298463c8be95STamas Berghammer             return Error ();
298563c8be95STamas Berghammer 
2986af245d11STodd Fiala         case llvm::Triple::x86:
2987af245d11STodd Fiala         case llvm::Triple::x86_64:
2988af245d11STodd Fiala             actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
2989af245d11STodd Fiala             return Error ();
2990af245d11STodd Fiala 
2991e8659b5dSMohit K. Bhakkad         case llvm::Triple::mips64:
2992e8659b5dSMohit K. Bhakkad         case llvm::Triple::mips64el:
2993e8659b5dSMohit K. Bhakkad             actual_opcode_size = static_cast<uint32_t> (sizeof(g_mips64_opcode));
2994e8659b5dSMohit K. Bhakkad             return Error ();
2995e8659b5dSMohit K. Bhakkad 
2996af245d11STodd Fiala         default:
2997af245d11STodd Fiala             assert(false && "CPU type not supported!");
2998af245d11STodd Fiala             return Error ("CPU type not supported");
2999af245d11STodd Fiala     }
3000af245d11STodd Fiala }
3001af245d11STodd Fiala 
3002af245d11STodd Fiala Error
3003af245d11STodd Fiala NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
3004af245d11STodd Fiala {
3005af245d11STodd Fiala     if (hardware)
3006af245d11STodd Fiala         return Error ("NativeProcessLinux does not support hardware breakpoints");
3007af245d11STodd Fiala     else
3008af245d11STodd Fiala         return SetSoftwareBreakpoint (addr, size);
3009af245d11STodd Fiala }
3010af245d11STodd Fiala 
3011af245d11STodd Fiala Error
301263c8be95STamas Berghammer NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint,
301363c8be95STamas Berghammer                                                      size_t &actual_opcode_size,
301463c8be95STamas Berghammer                                                      const uint8_t *&trap_opcode_bytes)
3015af245d11STodd Fiala {
301663c8be95STamas Berghammer     // FIXME put this behind a breakpoint protocol class that can be set per
301763c8be95STamas Berghammer     // architecture.  Need MIPS support here.
30182afc5966STodd Fiala     static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
301963c8be95STamas Berghammer     // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
302063c8be95STamas Berghammer     // linux kernel does otherwise.
302163c8be95STamas Berghammer     static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 };
3022af245d11STodd Fiala     static const uint8_t g_i386_opcode [] = { 0xCC };
30233df471c3SMohit K. Bhakkad     static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
30242c2acf96SMohit K. Bhakkad     static const uint8_t g_mips64el_opcode[] = { 0x0d, 0x00, 0x00, 0x00 };
302563c8be95STamas Berghammer     static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde };
3026af245d11STodd Fiala 
3027af245d11STodd Fiala     switch (m_arch.GetMachine ())
3028af245d11STodd Fiala     {
30292afc5966STodd Fiala     case llvm::Triple::aarch64:
30302afc5966STodd Fiala         trap_opcode_bytes = g_aarch64_opcode;
30312afc5966STodd Fiala         actual_opcode_size = sizeof(g_aarch64_opcode);
30322afc5966STodd Fiala         return Error ();
30332afc5966STodd Fiala 
303463c8be95STamas Berghammer     case llvm::Triple::arm:
303563c8be95STamas Berghammer         switch (trap_opcode_size_hint)
303663c8be95STamas Berghammer         {
303763c8be95STamas Berghammer         case 2:
303863c8be95STamas Berghammer             trap_opcode_bytes = g_thumb_breakpoint_opcode;
303963c8be95STamas Berghammer             actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
304063c8be95STamas Berghammer             return Error ();
304163c8be95STamas Berghammer         case 4:
304263c8be95STamas Berghammer             trap_opcode_bytes = g_arm_breakpoint_opcode;
304363c8be95STamas Berghammer             actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
304463c8be95STamas Berghammer             return Error ();
304563c8be95STamas Berghammer         default:
304663c8be95STamas Berghammer             assert(false && "Unrecognised trap opcode size hint!");
304763c8be95STamas Berghammer             return Error ("Unrecognised trap opcode size hint!");
304863c8be95STamas Berghammer         }
304963c8be95STamas Berghammer 
3050af245d11STodd Fiala     case llvm::Triple::x86:
3051af245d11STodd Fiala     case llvm::Triple::x86_64:
3052af245d11STodd Fiala         trap_opcode_bytes = g_i386_opcode;
3053af245d11STodd Fiala         actual_opcode_size = sizeof(g_i386_opcode);
3054af245d11STodd Fiala         return Error ();
3055af245d11STodd Fiala 
30563df471c3SMohit K. Bhakkad     case llvm::Triple::mips64:
30573df471c3SMohit K. Bhakkad         trap_opcode_bytes = g_mips64_opcode;
30583df471c3SMohit K. Bhakkad         actual_opcode_size = sizeof(g_mips64_opcode);
30593df471c3SMohit K. Bhakkad         return Error ();
30603df471c3SMohit K. Bhakkad 
30612c2acf96SMohit K. Bhakkad     case llvm::Triple::mips64el:
30622c2acf96SMohit K. Bhakkad         trap_opcode_bytes = g_mips64el_opcode;
30632c2acf96SMohit K. Bhakkad         actual_opcode_size = sizeof(g_mips64el_opcode);
30642c2acf96SMohit K. Bhakkad         return Error ();
30652c2acf96SMohit K. Bhakkad 
3066af245d11STodd Fiala     default:
3067af245d11STodd Fiala         assert(false && "CPU type not supported!");
3068af245d11STodd Fiala         return Error ("CPU type not supported");
3069af245d11STodd Fiala     }
3070af245d11STodd Fiala }
3071af245d11STodd Fiala 
3072af245d11STodd Fiala #if 0
3073af245d11STodd Fiala ProcessMessage::CrashReason
3074af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
3075af245d11STodd Fiala {
3076af245d11STodd Fiala     ProcessMessage::CrashReason reason;
3077af245d11STodd Fiala     assert(info->si_signo == SIGSEGV);
3078af245d11STodd Fiala 
3079af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
3080af245d11STodd Fiala 
3081af245d11STodd Fiala     switch (info->si_code)
3082af245d11STodd Fiala     {
3083af245d11STodd Fiala     default:
3084af245d11STodd Fiala         assert(false && "unexpected si_code for SIGSEGV");
3085af245d11STodd Fiala         break;
3086af245d11STodd Fiala     case SI_KERNEL:
3087af245d11STodd Fiala         // Linux will occasionally send spurious SI_KERNEL codes.
3088af245d11STodd Fiala         // (this is poorly documented in sigaction)
3089af245d11STodd Fiala         // One way to get this is via unaligned SIMD loads.
3090af245d11STodd Fiala         reason = ProcessMessage::eInvalidAddress; // for lack of anything better
3091af245d11STodd Fiala         break;
3092af245d11STodd Fiala     case SEGV_MAPERR:
3093af245d11STodd Fiala         reason = ProcessMessage::eInvalidAddress;
3094af245d11STodd Fiala         break;
3095af245d11STodd Fiala     case SEGV_ACCERR:
3096af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedAddress;
3097af245d11STodd Fiala         break;
3098af245d11STodd Fiala     }
3099af245d11STodd Fiala 
3100af245d11STodd Fiala     return reason;
3101af245d11STodd Fiala }
3102af245d11STodd Fiala #endif
3103af245d11STodd Fiala 
3104af245d11STodd Fiala 
3105af245d11STodd Fiala #if 0
3106af245d11STodd Fiala ProcessMessage::CrashReason
3107af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
3108af245d11STodd Fiala {
3109af245d11STodd Fiala     ProcessMessage::CrashReason reason;
3110af245d11STodd Fiala     assert(info->si_signo == SIGILL);
3111af245d11STodd Fiala 
3112af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
3113af245d11STodd Fiala 
3114af245d11STodd Fiala     switch (info->si_code)
3115af245d11STodd Fiala     {
3116af245d11STodd Fiala     default:
3117af245d11STodd Fiala         assert(false && "unexpected si_code for SIGILL");
3118af245d11STodd Fiala         break;
3119af245d11STodd Fiala     case ILL_ILLOPC:
3120af245d11STodd Fiala         reason = ProcessMessage::eIllegalOpcode;
3121af245d11STodd Fiala         break;
3122af245d11STodd Fiala     case ILL_ILLOPN:
3123af245d11STodd Fiala         reason = ProcessMessage::eIllegalOperand;
3124af245d11STodd Fiala         break;
3125af245d11STodd Fiala     case ILL_ILLADR:
3126af245d11STodd Fiala         reason = ProcessMessage::eIllegalAddressingMode;
3127af245d11STodd Fiala         break;
3128af245d11STodd Fiala     case ILL_ILLTRP:
3129af245d11STodd Fiala         reason = ProcessMessage::eIllegalTrap;
3130af245d11STodd Fiala         break;
3131af245d11STodd Fiala     case ILL_PRVOPC:
3132af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedOpcode;
3133af245d11STodd Fiala         break;
3134af245d11STodd Fiala     case ILL_PRVREG:
3135af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedRegister;
3136af245d11STodd Fiala         break;
3137af245d11STodd Fiala     case ILL_COPROC:
3138af245d11STodd Fiala         reason = ProcessMessage::eCoprocessorError;
3139af245d11STodd Fiala         break;
3140af245d11STodd Fiala     case ILL_BADSTK:
3141af245d11STodd Fiala         reason = ProcessMessage::eInternalStackError;
3142af245d11STodd Fiala         break;
3143af245d11STodd Fiala     }
3144af245d11STodd Fiala 
3145af245d11STodd Fiala     return reason;
3146af245d11STodd Fiala }
3147af245d11STodd Fiala #endif
3148af245d11STodd Fiala 
3149af245d11STodd Fiala #if 0
3150af245d11STodd Fiala ProcessMessage::CrashReason
3151af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
3152af245d11STodd Fiala {
3153af245d11STodd Fiala     ProcessMessage::CrashReason reason;
3154af245d11STodd Fiala     assert(info->si_signo == SIGFPE);
3155af245d11STodd Fiala 
3156af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
3157af245d11STodd Fiala 
3158af245d11STodd Fiala     switch (info->si_code)
3159af245d11STodd Fiala     {
3160af245d11STodd Fiala     default:
3161af245d11STodd Fiala         assert(false && "unexpected si_code for SIGFPE");
3162af245d11STodd Fiala         break;
3163af245d11STodd Fiala     case FPE_INTDIV:
3164af245d11STodd Fiala         reason = ProcessMessage::eIntegerDivideByZero;
3165af245d11STodd Fiala         break;
3166af245d11STodd Fiala     case FPE_INTOVF:
3167af245d11STodd Fiala         reason = ProcessMessage::eIntegerOverflow;
3168af245d11STodd Fiala         break;
3169af245d11STodd Fiala     case FPE_FLTDIV:
3170af245d11STodd Fiala         reason = ProcessMessage::eFloatDivideByZero;
3171af245d11STodd Fiala         break;
3172af245d11STodd Fiala     case FPE_FLTOVF:
3173af245d11STodd Fiala         reason = ProcessMessage::eFloatOverflow;
3174af245d11STodd Fiala         break;
3175af245d11STodd Fiala     case FPE_FLTUND:
3176af245d11STodd Fiala         reason = ProcessMessage::eFloatUnderflow;
3177af245d11STodd Fiala         break;
3178af245d11STodd Fiala     case FPE_FLTRES:
3179af245d11STodd Fiala         reason = ProcessMessage::eFloatInexactResult;
3180af245d11STodd Fiala         break;
3181af245d11STodd Fiala     case FPE_FLTINV:
3182af245d11STodd Fiala         reason = ProcessMessage::eFloatInvalidOperation;
3183af245d11STodd Fiala         break;
3184af245d11STodd Fiala     case FPE_FLTSUB:
3185af245d11STodd Fiala         reason = ProcessMessage::eFloatSubscriptRange;
3186af245d11STodd Fiala         break;
3187af245d11STodd Fiala     }
3188af245d11STodd Fiala 
3189af245d11STodd Fiala     return reason;
3190af245d11STodd Fiala }
3191af245d11STodd Fiala #endif
3192af245d11STodd Fiala 
3193af245d11STodd Fiala #if 0
3194af245d11STodd Fiala ProcessMessage::CrashReason
3195af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
3196af245d11STodd Fiala {
3197af245d11STodd Fiala     ProcessMessage::CrashReason reason;
3198af245d11STodd Fiala     assert(info->si_signo == SIGBUS);
3199af245d11STodd Fiala 
3200af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
3201af245d11STodd Fiala 
3202af245d11STodd Fiala     switch (info->si_code)
3203af245d11STodd Fiala     {
3204af245d11STodd Fiala     default:
3205af245d11STodd Fiala         assert(false && "unexpected si_code for SIGBUS");
3206af245d11STodd Fiala         break;
3207af245d11STodd Fiala     case BUS_ADRALN:
3208af245d11STodd Fiala         reason = ProcessMessage::eIllegalAlignment;
3209af245d11STodd Fiala         break;
3210af245d11STodd Fiala     case BUS_ADRERR:
3211af245d11STodd Fiala         reason = ProcessMessage::eIllegalAddress;
3212af245d11STodd Fiala         break;
3213af245d11STodd Fiala     case BUS_OBJERR:
3214af245d11STodd Fiala         reason = ProcessMessage::eHardwareError;
3215af245d11STodd Fiala         break;
3216af245d11STodd Fiala     }
3217af245d11STodd Fiala 
3218af245d11STodd Fiala     return reason;
3219af245d11STodd Fiala }
3220af245d11STodd Fiala #endif
3221af245d11STodd Fiala 
3222af245d11STodd Fiala Error
322345f5cb31SPavel Labath NativeProcessLinux::SetWatchpoint (lldb::addr_t addr, size_t size, uint32_t watch_flags, bool hardware)
322445f5cb31SPavel Labath {
322545f5cb31SPavel Labath     // The base SetWatchpoint will end up executing monitor operations. Let's lock the monitor
322645f5cb31SPavel Labath     // for it.
322745f5cb31SPavel Labath     Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
322845f5cb31SPavel Labath     return NativeProcessProtocol::SetWatchpoint(addr, size, watch_flags, hardware);
322945f5cb31SPavel Labath }
323045f5cb31SPavel Labath 
323145f5cb31SPavel Labath Error
323245f5cb31SPavel Labath NativeProcessLinux::RemoveWatchpoint (lldb::addr_t addr)
323345f5cb31SPavel Labath {
323445f5cb31SPavel Labath     // The base RemoveWatchpoint will end up executing monitor operations. Let's lock the monitor
323545f5cb31SPavel Labath     // for it.
323645f5cb31SPavel Labath     Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
323745f5cb31SPavel Labath     return NativeProcessProtocol::RemoveWatchpoint(addr);
323845f5cb31SPavel Labath }
323945f5cb31SPavel Labath 
324045f5cb31SPavel Labath Error
324126438d26SChaoren Lin NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
3242af245d11STodd Fiala {
3243af245d11STodd Fiala     ReadOperation op(addr, buf, size, bytes_read);
3244bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
3245af245d11STodd Fiala     return op.GetError ();
3246af245d11STodd Fiala }
3247af245d11STodd Fiala 
3248af245d11STodd Fiala Error
32493eb4b458SChaoren Lin NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
32503eb4b458SChaoren Lin {
32513eb4b458SChaoren Lin     Error error = ReadMemory(addr, buf, size, bytes_read);
32523eb4b458SChaoren Lin     if (error.Fail()) return error;
32533eb4b458SChaoren Lin     return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
32543eb4b458SChaoren Lin }
32553eb4b458SChaoren Lin 
32563eb4b458SChaoren Lin Error
32573eb4b458SChaoren Lin NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written)
3258af245d11STodd Fiala {
3259af245d11STodd Fiala     WriteOperation op(addr, buf, size, bytes_written);
3260bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
3261af245d11STodd Fiala     return op.GetError ();
3262af245d11STodd Fiala }
3263af245d11STodd Fiala 
326497ccc294SChaoren Lin Error
3265af245d11STodd Fiala NativeProcessLinux::Resume (lldb::tid_t tid, uint32_t signo)
3266af245d11STodd Fiala {
3267af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3268af245d11STodd Fiala 
3269af245d11STodd Fiala     if (log)
3270af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s() resuming thread = %"  PRIu64 " with signal %s", __FUNCTION__, tid,
3271af245d11STodd Fiala                                  GetUnixSignals().GetSignalAsCString (signo));
327297ccc294SChaoren Lin     ResumeOperation op (tid, signo);
3273bd7cbc5aSPavel Labath     m_monitor_up->DoOperation (&op);
3274af245d11STodd Fiala     if (log)
327597ccc294SChaoren Lin         log->Printf ("NativeProcessLinux::%s() resuming thread = %"  PRIu64 " result = %s", __FUNCTION__, tid, op.GetError().Success() ? "true" : "false");
327697ccc294SChaoren Lin     return op.GetError();
3277af245d11STodd Fiala }
3278af245d11STodd Fiala 
327997ccc294SChaoren Lin Error
3280af245d11STodd Fiala NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo)
3281af245d11STodd Fiala {
328297ccc294SChaoren Lin     SingleStepOperation op(tid, signo);
3283bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
328497ccc294SChaoren Lin     return op.GetError();
3285af245d11STodd Fiala }
3286af245d11STodd Fiala 
328797ccc294SChaoren Lin Error
328897ccc294SChaoren Lin NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
3289af245d11STodd Fiala {
329097ccc294SChaoren Lin     SiginfoOperation op(tid, siginfo);
3291bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
329297ccc294SChaoren Lin     return op.GetError();
3293af245d11STodd Fiala }
3294af245d11STodd Fiala 
329597ccc294SChaoren Lin Error
3296af245d11STodd Fiala NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
3297af245d11STodd Fiala {
329897ccc294SChaoren Lin     EventMessageOperation op(tid, message);
3299bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
330097ccc294SChaoren Lin     return op.GetError();
3301af245d11STodd Fiala }
3302af245d11STodd Fiala 
3303db264a6dSTamas Berghammer Error
3304af245d11STodd Fiala NativeProcessLinux::Detach(lldb::tid_t tid)
3305af245d11STodd Fiala {
330697ccc294SChaoren Lin     if (tid == LLDB_INVALID_THREAD_ID)
330797ccc294SChaoren Lin         return Error();
330897ccc294SChaoren Lin 
330997ccc294SChaoren Lin     DetachOperation op(tid);
3310bd7cbc5aSPavel Labath     m_monitor_up->DoOperation(&op);
331197ccc294SChaoren Lin     return op.GetError();
3312af245d11STodd Fiala }
3313af245d11STodd Fiala 
3314af245d11STodd Fiala bool
3315af245d11STodd Fiala NativeProcessLinux::DupDescriptor(const char *path, int fd, int flags)
3316af245d11STodd Fiala {
3317af245d11STodd Fiala     int target_fd = open(path, flags, 0666);
3318af245d11STodd Fiala 
3319af245d11STodd Fiala     if (target_fd == -1)
3320af245d11STodd Fiala         return false;
3321af245d11STodd Fiala 
3322493c3a12SPavel Labath     if (dup2(target_fd, fd) == -1)
3323493c3a12SPavel Labath         return false;
3324493c3a12SPavel Labath 
3325493c3a12SPavel Labath     return (close(target_fd) == -1) ? false : true;
3326af245d11STodd Fiala }
3327af245d11STodd Fiala 
3328af245d11STodd Fiala void
3329bd7cbc5aSPavel Labath NativeProcessLinux::StartMonitorThread(const InitialOperation &initial_operation, Error &error)
3330af245d11STodd Fiala {
3331bd7cbc5aSPavel Labath     m_monitor_up.reset(new Monitor(initial_operation, this));
33321107b5a5SPavel Labath     error = m_monitor_up->Initialize();
33331107b5a5SPavel Labath     if (error.Fail()) {
33341107b5a5SPavel Labath         m_monitor_up.reset();
3335af245d11STodd Fiala     }
3336af245d11STodd Fiala }
3337af245d11STodd Fiala 
3338af245d11STodd Fiala bool
3339af245d11STodd Fiala NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
3340af245d11STodd Fiala {
3341af245d11STodd Fiala     for (auto thread_sp : m_threads)
3342af245d11STodd Fiala     {
3343af245d11STodd Fiala         assert (thread_sp && "thread list should not contain NULL threads");
3344af245d11STodd Fiala         if (thread_sp->GetID () == thread_id)
3345af245d11STodd Fiala         {
3346af245d11STodd Fiala             // We have this thread.
3347af245d11STodd Fiala             return true;
3348af245d11STodd Fiala         }
3349af245d11STodd Fiala     }
3350af245d11STodd Fiala 
3351af245d11STodd Fiala     // We don't have this thread.
3352af245d11STodd Fiala     return false;
3353af245d11STodd Fiala }
3354af245d11STodd Fiala 
3355af245d11STodd Fiala NativeThreadProtocolSP
3356af245d11STodd Fiala NativeProcessLinux::MaybeGetThreadNoLock (lldb::tid_t thread_id)
3357af245d11STodd Fiala {
3358af245d11STodd Fiala     // CONSIDER organize threads by map - we can do better than linear.
3359af245d11STodd Fiala     for (auto thread_sp : m_threads)
3360af245d11STodd Fiala     {
3361af245d11STodd Fiala         if (thread_sp->GetID () == thread_id)
3362af245d11STodd Fiala             return thread_sp;
3363af245d11STodd Fiala     }
3364af245d11STodd Fiala 
3365af245d11STodd Fiala     // We don't have this thread.
3366af245d11STodd Fiala     return NativeThreadProtocolSP ();
3367af245d11STodd Fiala }
3368af245d11STodd Fiala 
3369af245d11STodd Fiala bool
3370af245d11STodd Fiala NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
3371af245d11STodd Fiala {
33721dbc6c9cSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
33731dbc6c9cSPavel Labath 
33741dbc6c9cSPavel Labath     if (log)
33751dbc6c9cSPavel Labath         log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, thread_id);
33761dbc6c9cSPavel Labath 
33771dbc6c9cSPavel Labath     bool found = false;
33781dbc6c9cSPavel Labath 
3379af245d11STodd Fiala     Mutex::Locker locker (m_threads_mutex);
3380af245d11STodd Fiala     for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
3381af245d11STodd Fiala     {
3382af245d11STodd Fiala         if (*it && ((*it)->GetID () == thread_id))
3383af245d11STodd Fiala         {
3384af245d11STodd Fiala             m_threads.erase (it);
33851dbc6c9cSPavel Labath             found = true;
33861dbc6c9cSPavel Labath             break;
3387af245d11STodd Fiala         }
3388af245d11STodd Fiala     }
3389af245d11STodd Fiala 
33901dbc6c9cSPavel Labath     // If we have a pending notification, remove this from the set.
33911dbc6c9cSPavel Labath     if (m_pending_notification_up)
33921dbc6c9cSPavel Labath     {
33931dbc6c9cSPavel Labath         m_pending_notification_up->wait_for_stop_tids.erase(thread_id);
33949eb1ecb9SPavel Labath         SignalIfAllThreadsStopped();
33951dbc6c9cSPavel Labath     }
33961dbc6c9cSPavel Labath 
33971dbc6c9cSPavel Labath     return found;
3398af245d11STodd Fiala }
3399af245d11STodd Fiala 
3400af245d11STodd Fiala NativeThreadProtocolSP
3401af245d11STodd Fiala NativeProcessLinux::AddThread (lldb::tid_t thread_id)
3402af245d11STodd Fiala {
3403af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3404af245d11STodd Fiala 
3405af245d11STodd Fiala     Mutex::Locker locker (m_threads_mutex);
3406af245d11STodd Fiala 
3407af245d11STodd Fiala     if (log)
3408af245d11STodd Fiala     {
3409af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
3410af245d11STodd Fiala                 __FUNCTION__,
3411af245d11STodd Fiala                 GetID (),
3412af245d11STodd Fiala                 thread_id);
3413af245d11STodd Fiala     }
3414af245d11STodd Fiala 
3415af245d11STodd Fiala     assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
3416af245d11STodd Fiala 
3417af245d11STodd Fiala     // If this is the first thread, save it as the current thread
3418af245d11STodd Fiala     if (m_threads.empty ())
3419af245d11STodd Fiala         SetCurrentThreadID (thread_id);
3420af245d11STodd Fiala 
3421af245d11STodd Fiala     NativeThreadProtocolSP thread_sp (new NativeThreadLinux (this, thread_id));
3422af245d11STodd Fiala     m_threads.push_back (thread_sp);
3423af245d11STodd Fiala 
3424af245d11STodd Fiala     return thread_sp;
3425af245d11STodd Fiala }
3426af245d11STodd Fiala 
3427af245d11STodd Fiala Error
3428af245d11STodd Fiala NativeProcessLinux::FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp)
3429af245d11STodd Fiala {
343075f47c3aSTodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
3431af245d11STodd Fiala 
3432af245d11STodd Fiala     Error error;
3433af245d11STodd Fiala 
3434af245d11STodd Fiala     // Get a linux thread pointer.
3435af245d11STodd Fiala     if (!thread_sp)
3436af245d11STodd Fiala     {
3437af245d11STodd Fiala         error.SetErrorString ("null thread_sp");
3438af245d11STodd Fiala         if (log)
3439af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
3440af245d11STodd Fiala         return error;
3441af245d11STodd Fiala     }
3442cb84eebbSTamas Berghammer     std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
3443af245d11STodd Fiala 
3444af245d11STodd Fiala     // Find out the size of a breakpoint (might depend on where we are in the code).
3445cb84eebbSTamas Berghammer     NativeRegisterContextSP context_sp = linux_thread_sp->GetRegisterContext ();
3446af245d11STodd Fiala     if (!context_sp)
3447af245d11STodd Fiala     {
3448af245d11STodd Fiala         error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
3449af245d11STodd Fiala         if (log)
3450af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
3451af245d11STodd Fiala         return error;
3452af245d11STodd Fiala     }
3453af245d11STodd Fiala 
3454af245d11STodd Fiala     uint32_t breakpoint_size = 0;
345563c8be95STamas Berghammer     error = GetSoftwareBreakpointPCOffset (context_sp, breakpoint_size);
3456af245d11STodd Fiala     if (error.Fail ())
3457af245d11STodd Fiala     {
3458af245d11STodd Fiala         if (log)
3459af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
3460af245d11STodd Fiala         return error;
3461af245d11STodd Fiala     }
3462af245d11STodd Fiala     else
3463af245d11STodd Fiala     {
3464af245d11STodd Fiala         if (log)
3465af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
3466af245d11STodd Fiala     }
3467af245d11STodd Fiala 
3468af245d11STodd Fiala     // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
3469af245d11STodd Fiala     const lldb::addr_t initial_pc_addr = context_sp->GetPC ();
3470af245d11STodd Fiala     lldb::addr_t breakpoint_addr = initial_pc_addr;
34713eb4b458SChaoren Lin     if (breakpoint_size > 0)
3472af245d11STodd Fiala     {
3473af245d11STodd Fiala         // Do not allow breakpoint probe to wrap around.
34743eb4b458SChaoren Lin         if (breakpoint_addr >= breakpoint_size)
34753eb4b458SChaoren Lin             breakpoint_addr -= breakpoint_size;
3476af245d11STodd Fiala     }
3477af245d11STodd Fiala 
3478af245d11STodd Fiala     // Check if we stopped because of a breakpoint.
3479af245d11STodd Fiala     NativeBreakpointSP breakpoint_sp;
3480af245d11STodd Fiala     error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
3481af245d11STodd Fiala     if (!error.Success () || !breakpoint_sp)
3482af245d11STodd Fiala     {
3483af245d11STodd Fiala         // We didn't find one at a software probe location.  Nothing to do.
3484af245d11STodd Fiala         if (log)
3485af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
3486af245d11STodd Fiala         return Error ();
3487af245d11STodd Fiala     }
3488af245d11STodd Fiala 
3489af245d11STodd Fiala     // If the breakpoint is not a software breakpoint, nothing to do.
3490af245d11STodd Fiala     if (!breakpoint_sp->IsSoftwareBreakpoint ())
3491af245d11STodd Fiala     {
3492af245d11STodd Fiala         if (log)
3493af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
3494af245d11STodd Fiala         return Error ();
3495af245d11STodd Fiala     }
3496af245d11STodd Fiala 
3497af245d11STodd Fiala     //
3498af245d11STodd Fiala     // We have a software breakpoint and need to adjust the PC.
3499af245d11STodd Fiala     //
3500af245d11STodd Fiala 
3501af245d11STodd Fiala     // Sanity check.
3502af245d11STodd Fiala     if (breakpoint_size == 0)
3503af245d11STodd Fiala     {
3504af245d11STodd Fiala         // Nothing to do!  How did we get here?
3505af245d11STodd Fiala         if (log)
3506af245d11STodd 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);
3507af245d11STodd Fiala         return Error ();
3508af245d11STodd Fiala     }
3509af245d11STodd Fiala 
3510af245d11STodd Fiala     // Change the program counter.
3511af245d11STodd Fiala     if (log)
3512cb84eebbSTamas 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);
3513af245d11STodd Fiala 
3514af245d11STodd Fiala     error = context_sp->SetPC (breakpoint_addr);
3515af245d11STodd Fiala     if (error.Fail ())
3516af245d11STodd Fiala     {
3517af245d11STodd Fiala         if (log)
3518cb84eebbSTamas Berghammer             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": failed to set PC: %s", __FUNCTION__, GetID (), linux_thread_sp->GetID (), error.AsCString ());
3519af245d11STodd Fiala         return error;
3520af245d11STodd Fiala     }
3521af245d11STodd Fiala 
3522af245d11STodd Fiala     return error;
3523af245d11STodd Fiala }
3524fa03ad2eSChaoren Lin 
35257cb18bf5STamas Berghammer Error
35267cb18bf5STamas Berghammer NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec)
35277cb18bf5STamas Berghammer {
35287cb18bf5STamas Berghammer     char maps_file_name[32];
35297cb18bf5STamas Berghammer     snprintf(maps_file_name, sizeof(maps_file_name), "/proc/%" PRIu64 "/maps", GetID());
35307cb18bf5STamas Berghammer 
35317cb18bf5STamas Berghammer     FileSpec maps_file_spec(maps_file_name, false);
35327cb18bf5STamas Berghammer     if (!maps_file_spec.Exists()) {
35337cb18bf5STamas Berghammer         file_spec.Clear();
35347cb18bf5STamas Berghammer         return Error("/proc/%" PRIu64 "/maps file doesn't exists!", GetID());
35357cb18bf5STamas Berghammer     }
35367cb18bf5STamas Berghammer 
35377cb18bf5STamas Berghammer     FileSpec module_file_spec(module_path, true);
35387cb18bf5STamas Berghammer 
35397cb18bf5STamas Berghammer     std::ifstream maps_file(maps_file_name);
35407cb18bf5STamas Berghammer     std::string maps_data_str((std::istreambuf_iterator<char>(maps_file)), std::istreambuf_iterator<char>());
35417cb18bf5STamas Berghammer     StringRef maps_data(maps_data_str.c_str());
35427cb18bf5STamas Berghammer 
35437cb18bf5STamas Berghammer     while (!maps_data.empty())
35447cb18bf5STamas Berghammer     {
35457cb18bf5STamas Berghammer         StringRef maps_row;
35467cb18bf5STamas Berghammer         std::tie(maps_row, maps_data) = maps_data.split('\n');
35477cb18bf5STamas Berghammer 
35487cb18bf5STamas Berghammer         SmallVector<StringRef, 16> maps_columns;
35497cb18bf5STamas Berghammer         maps_row.split(maps_columns, StringRef(" "), -1, false);
35507cb18bf5STamas Berghammer 
35517cb18bf5STamas Berghammer         if (maps_columns.size() >= 6)
35527cb18bf5STamas Berghammer         {
35537cb18bf5STamas Berghammer             file_spec.SetFile(maps_columns[5].str().c_str(), false);
35547cb18bf5STamas Berghammer             if (file_spec.GetFilename() == module_file_spec.GetFilename())
35557cb18bf5STamas Berghammer                 return Error();
35567cb18bf5STamas Berghammer         }
35577cb18bf5STamas Berghammer     }
35587cb18bf5STamas Berghammer 
35597cb18bf5STamas Berghammer     file_spec.Clear();
35607cb18bf5STamas Berghammer     return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
35617cb18bf5STamas Berghammer                  module_file_spec.GetFilename().AsCString(), GetID());
35627cb18bf5STamas Berghammer }
3563c076559aSPavel Labath 
35645eb721edSPavel Labath Error
35651dbc6c9cSPavel Labath NativeProcessLinux::ResumeThread(
3566c076559aSPavel Labath         lldb::tid_t tid,
35678c8ff7afSPavel Labath         NativeThreadLinux::ResumeThreadFunction request_thread_resume_function,
3568c076559aSPavel Labath         bool error_when_already_running)
3569c076559aSPavel Labath {
35705eb721edSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
35715eb721edSPavel Labath 
35721dbc6c9cSPavel Labath     if (log)
35731dbc6c9cSPavel Labath         log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ", error_when_already_running: %s)",
35741dbc6c9cSPavel Labath                 __FUNCTION__, tid, error_when_already_running?"true":"false");
35751dbc6c9cSPavel Labath 
35768c8ff7afSPavel Labath     auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
35778c8ff7afSPavel Labath     lldbassert(thread_sp != nullptr);
35785eb721edSPavel Labath 
35798c8ff7afSPavel Labath     auto& context = thread_sp->GetThreadContext();
3580c076559aSPavel Labath     // Tell the thread to resume if we don't already think it is running.
35818c8ff7afSPavel Labath     const bool is_stopped = StateIsStoppedState(thread_sp->GetState(), true);
35825eb721edSPavel Labath 
35835eb721edSPavel Labath     lldbassert(!(error_when_already_running && !is_stopped));
35845eb721edSPavel Labath 
3585c076559aSPavel Labath     if (!is_stopped)
3586c076559aSPavel Labath     {
3587c076559aSPavel Labath         // It's not an error, just a log, if the error_when_already_running flag is not set.
3588c076559aSPavel Labath         // This covers cases where, for instance, we're just trying to resume all threads
3589c076559aSPavel Labath         // from the user side.
35905eb721edSPavel Labath         if (log)
35915eb721edSPavel Labath             log->Printf("NativeProcessLinux::%s tid %" PRIu64 " optional resume skipped since it is already running",
3592c076559aSPavel Labath                     __FUNCTION__,
3593c076559aSPavel Labath                     tid);
35945eb721edSPavel Labath         return Error();
3595c076559aSPavel Labath     }
3596c076559aSPavel Labath 
3597c076559aSPavel Labath     // Before we do the resume below, first check if we have a pending
3598108c325dSPavel Labath     // stop notification that is currently waiting for
3599c076559aSPavel Labath     // this thread to stop.  This is potentially a buggy situation since
3600c076559aSPavel Labath     // we're ostensibly waiting for threads to stop before we send out the
3601c076559aSPavel Labath     // pending notification, and here we are resuming one before we send
3602c076559aSPavel Labath     // out the pending stop notification.
3603108c325dSPavel Labath     if (m_pending_notification_up && log && m_pending_notification_up->wait_for_stop_tids.count (tid) > 0)
3604c076559aSPavel Labath     {
36055eb721edSPavel 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);
3606c076559aSPavel Labath     }
3607c076559aSPavel Labath 
3608c076559aSPavel Labath     // Request a resume.  We expect this to be synchronous and the system
3609c076559aSPavel Labath     // to reflect it is running after this completes.
3610c076559aSPavel Labath     const auto error = request_thread_resume_function (tid, false);
3611c076559aSPavel Labath     if (error.Success())
36128c8ff7afSPavel Labath         context.request_resume_function = request_thread_resume_function;
36135eb721edSPavel Labath     else if (log)
3614c076559aSPavel Labath     {
36155eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s failed to resume thread tid  %" PRIu64 ": %s",
3616c076559aSPavel Labath                          __FUNCTION__, tid, error.AsCString ());
3617c076559aSPavel Labath     }
3618c076559aSPavel Labath 
36195eb721edSPavel Labath     return error;
3620c076559aSPavel Labath }
3621c076559aSPavel Labath 
3622c076559aSPavel Labath //===----------------------------------------------------------------------===//
3623c076559aSPavel Labath 
3624c076559aSPavel Labath void
3625337f3eb9SPavel Labath NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid)
3626c076559aSPavel Labath {
36275eb721edSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3628c076559aSPavel Labath 
36295eb721edSPavel Labath     if (log)
3630c076559aSPavel Labath     {
36315eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ")",
3632c076559aSPavel Labath                 __FUNCTION__, triggering_tid);
3633c076559aSPavel Labath     }
3634c076559aSPavel Labath 
3635337f3eb9SPavel Labath     DoStopThreads(PendingNotificationUP(new PendingNotification(triggering_tid)));
3636c076559aSPavel Labath 
36375eb721edSPavel Labath     if (log)
3638c076559aSPavel Labath     {
36395eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
3640c076559aSPavel Labath     }
3641c076559aSPavel Labath }
3642c076559aSPavel Labath 
3643c076559aSPavel Labath void
36449eb1ecb9SPavel Labath NativeProcessLinux::SignalIfAllThreadsStopped()
3645c076559aSPavel Labath {
3646c076559aSPavel Labath     if (m_pending_notification_up && m_pending_notification_up->wait_for_stop_tids.empty ())
3647c076559aSPavel Labath     {
36489eb1ecb9SPavel Labath         Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
36499eb1ecb9SPavel Labath 
36509eb1ecb9SPavel Labath         // Clear any temporary breakpoints we used to implement software single stepping.
36519eb1ecb9SPavel Labath         for (const auto &thread_info: m_threads_stepping_with_breakpoint)
36529eb1ecb9SPavel Labath         {
36539eb1ecb9SPavel Labath             Error error = RemoveBreakpoint (thread_info.second);
36549eb1ecb9SPavel Labath             if (error.Fail())
36559eb1ecb9SPavel Labath                 if (log)
36569eb1ecb9SPavel Labath                     log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " remove stepping breakpoint: %s",
36579eb1ecb9SPavel Labath                             __FUNCTION__, thread_info.first, error.AsCString());
36589eb1ecb9SPavel Labath         }
36599eb1ecb9SPavel Labath         m_threads_stepping_with_breakpoint.clear();
36609eb1ecb9SPavel Labath 
36619eb1ecb9SPavel Labath         // Notify the delegate about the stop
3662ed89c7feSPavel Labath         SetCurrentThreadID(m_pending_notification_up->triggering_tid);
3663ed89c7feSPavel Labath         SetState(StateType::eStateStopped, true);
3664c076559aSPavel Labath         m_pending_notification_up.reset();
3665c076559aSPavel Labath     }
3666c076559aSPavel Labath }
3667c076559aSPavel Labath 
3668c076559aSPavel Labath void
3669c076559aSPavel Labath NativeProcessLinux::RequestStopOnAllRunningThreads()
3670c076559aSPavel Labath {
3671c076559aSPavel Labath     // Request a stop for all the thread stops that need to be stopped
3672c076559aSPavel Labath     // and are not already known to be stopped.  Keep a list of all the
3673c076559aSPavel Labath     // threads from which we still need to hear a stop reply.
3674c076559aSPavel Labath 
3675c076559aSPavel Labath     ThreadIDSet sent_tids;
36768c8ff7afSPavel Labath     for (const auto &thread_sp: m_threads)
3677c076559aSPavel Labath     {
36788c8ff7afSPavel Labath         // We only care about running threads
36798c8ff7afSPavel Labath         if (StateIsStoppedState(thread_sp->GetState(), true))
36808c8ff7afSPavel Labath             continue;
36818c8ff7afSPavel Labath 
36828c8ff7afSPavel Labath         static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
3683108c325dSPavel Labath         sent_tids.insert (thread_sp->GetID());
3684c076559aSPavel Labath     }
3685c076559aSPavel Labath 
3686c076559aSPavel Labath     // Set the wait list to the set of tids for which we requested stops.
3687c076559aSPavel Labath     m_pending_notification_up->wait_for_stop_tids.swap (sent_tids);
3688c076559aSPavel Labath }
3689c076559aSPavel Labath 
3690c076559aSPavel Labath 
36915eb721edSPavel Labath Error
36925eb721edSPavel Labath NativeProcessLinux::ThreadDidStop (lldb::tid_t tid, bool initiated_by_llgs)
3693c076559aSPavel Labath {
36941dbc6c9cSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
36951dbc6c9cSPavel Labath 
36961dbc6c9cSPavel Labath     if (log)
36971dbc6c9cSPavel Labath         log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ", %sinitiated by llgs)",
36981dbc6c9cSPavel Labath                 __FUNCTION__, tid, initiated_by_llgs?"":"not ");
36991dbc6c9cSPavel Labath 
3700c076559aSPavel Labath     // Ensure we know about the thread.
37018c8ff7afSPavel Labath     auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
37028c8ff7afSPavel Labath     lldbassert(thread_sp != nullptr);
3703c076559aSPavel Labath 
3704c076559aSPavel Labath     // Update the global list of known thread states.  This one is definitely stopped.
37058c8ff7afSPavel Labath     auto& context = thread_sp->GetThreadContext();
37068c8ff7afSPavel Labath     const auto stop_was_requested = context.stop_requested;
37078c8ff7afSPavel Labath     context.stop_requested = false;
3708c076559aSPavel Labath 
3709c076559aSPavel Labath     // If we have a pending notification, remove this from the set.
3710c076559aSPavel Labath     if (m_pending_notification_up)
3711c076559aSPavel Labath     {
3712c076559aSPavel Labath         m_pending_notification_up->wait_for_stop_tids.erase(tid);
37139eb1ecb9SPavel Labath         SignalIfAllThreadsStopped();
3714c076559aSPavel Labath     }
3715c076559aSPavel Labath 
37168c8ff7afSPavel Labath     Error error;
37178c8ff7afSPavel Labath     if (initiated_by_llgs && context.request_resume_function && !stop_was_requested)
3718c076559aSPavel Labath     {
3719c076559aSPavel Labath         // We can end up here if stop was initiated by LLGS but by this time a
3720c076559aSPavel Labath         // thread stop has occurred - maybe initiated by another event.
37215eb721edSPavel Labath         if (log)
37225eb721edSPavel Labath             log->Printf("Resuming thread %"  PRIu64 " since stop wasn't requested", tid);
37238c8ff7afSPavel Labath         error = context.request_resume_function (tid, true);
37248c8ff7afSPavel Labath         if (error.Fail() && log)
37255eb721edSPavel Labath         {
37265eb721edSPavel Labath                 log->Printf("NativeProcessLinux::%s failed to resume thread tid  %" PRIu64 ": %s",
3727c076559aSPavel Labath                         __FUNCTION__, tid, error.AsCString ());
3728c076559aSPavel Labath         }
37298c8ff7afSPavel Labath     }
37305eb721edSPavel Labath     return error;
3731c076559aSPavel Labath }
3732c076559aSPavel Labath 
3733c076559aSPavel Labath void
3734ed89c7feSPavel Labath NativeProcessLinux::DoStopThreads(PendingNotificationUP &&notification_up)
3735c076559aSPavel Labath {
37365eb721edSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
37375eb721edSPavel Labath     if (m_pending_notification_up && log)
3738c076559aSPavel Labath     {
3739c076559aSPavel Labath         // Yikes - we've already got a pending signal notification in progress.
3740c076559aSPavel Labath         // Log this info.  We lose the pending notification here.
37415eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s dropping existing pending signal notification for tid %" PRIu64 ", to be replaced with signal for tid %" PRIu64,
3742c076559aSPavel Labath                    __FUNCTION__,
3743c076559aSPavel Labath                    m_pending_notification_up->triggering_tid,
3744c076559aSPavel Labath                    notification_up->triggering_tid);
3745c076559aSPavel Labath     }
3746c076559aSPavel Labath     m_pending_notification_up = std::move(notification_up);
3747c076559aSPavel Labath 
3748c076559aSPavel Labath     RequestStopOnAllRunningThreads();
3749c076559aSPavel Labath 
37509eb1ecb9SPavel Labath     SignalIfAllThreadsStopped();
3751c076559aSPavel Labath }
3752c076559aSPavel Labath 
3753c076559aSPavel Labath void
37548c8ff7afSPavel Labath NativeProcessLinux::ThreadWasCreated (lldb::tid_t tid)
3755c076559aSPavel Labath {
37561dbc6c9cSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
37571dbc6c9cSPavel Labath 
37581dbc6c9cSPavel Labath     if (log)
37591dbc6c9cSPavel Labath         log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, tid);
37601dbc6c9cSPavel Labath 
37618c8ff7afSPavel Labath     auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
37628c8ff7afSPavel Labath     lldbassert(thread_sp != nullptr);
3763c076559aSPavel Labath 
37648c8ff7afSPavel Labath     if (m_pending_notification_up && StateIsRunningState(thread_sp->GetState()))
3765c076559aSPavel Labath     {
3766c076559aSPavel Labath         // We will need to wait for this new thread to stop as well before firing the
3767c076559aSPavel Labath         // notification.
3768c076559aSPavel Labath         m_pending_notification_up->wait_for_stop_tids.insert(tid);
37698c8ff7afSPavel Labath         thread_sp->RequestStop();
3770c076559aSPavel Labath     }
3771c076559aSPavel Labath }
3772068f8a7eSTamas Berghammer 
3773068f8a7eSTamas Berghammer Error
3774068f8a7eSTamas Berghammer NativeProcessLinux::DoOperation(Operation* op)
3775068f8a7eSTamas Berghammer {
3776068f8a7eSTamas Berghammer     m_monitor_up->DoOperation(op);
3777068f8a7eSTamas Berghammer     return op->GetError();
3778068f8a7eSTamas Berghammer }
3779068f8a7eSTamas Berghammer 
3780068f8a7eSTamas Berghammer // Wrapper for ptrace to catch errors and log calls.
3781068f8a7eSTamas Berghammer // Note that ptrace sets errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
3782068f8a7eSTamas Berghammer long
3783068f8a7eSTamas Berghammer NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, Error& error)
3784068f8a7eSTamas Berghammer {
3785068f8a7eSTamas Berghammer     long int result;
3786068f8a7eSTamas Berghammer 
3787068f8a7eSTamas Berghammer     Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
3788068f8a7eSTamas Berghammer 
3789068f8a7eSTamas Berghammer     PtraceDisplayBytes(req, data, data_size);
3790068f8a7eSTamas Berghammer 
3791068f8a7eSTamas Berghammer     error.Clear();
3792068f8a7eSTamas Berghammer     errno = 0;
3793068f8a7eSTamas Berghammer     if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
3794068f8a7eSTamas Berghammer         result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
3795068f8a7eSTamas Berghammer     else
3796068f8a7eSTamas Berghammer         result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
3797068f8a7eSTamas Berghammer 
3798068f8a7eSTamas Berghammer     if (result == -1)
3799068f8a7eSTamas Berghammer         error.SetErrorToErrno();
3800068f8a7eSTamas Berghammer 
3801068f8a7eSTamas Berghammer     if (log)
3802068f8a7eSTamas Berghammer         log->Printf("ptrace(%d, %" PRIu64 ", %p, %p, %zu)=%lX", req, pid, addr, data, data_size, result);
3803068f8a7eSTamas Berghammer 
3804068f8a7eSTamas Berghammer     PtraceDisplayBytes(req, data, data_size);
3805068f8a7eSTamas Berghammer 
3806068f8a7eSTamas Berghammer     if (log && error.GetError() != 0)
3807068f8a7eSTamas Berghammer     {
3808068f8a7eSTamas Berghammer         const char* str;
3809068f8a7eSTamas Berghammer         switch (error.GetError())
3810068f8a7eSTamas Berghammer         {
3811068f8a7eSTamas Berghammer         case ESRCH:  str = "ESRCH"; break;
3812068f8a7eSTamas Berghammer         case EINVAL: str = "EINVAL"; break;
3813068f8a7eSTamas Berghammer         case EBUSY:  str = "EBUSY"; break;
3814068f8a7eSTamas Berghammer         case EPERM:  str = "EPERM"; break;
3815068f8a7eSTamas Berghammer         default:     str = error.AsCString();
3816068f8a7eSTamas Berghammer         }
3817068f8a7eSTamas Berghammer         log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
3818068f8a7eSTamas Berghammer     }
3819068f8a7eSTamas Berghammer 
3820068f8a7eSTamas Berghammer     return result;
3821068f8a7eSTamas Berghammer }
3822