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 "NativeProcessLinux.h"
11af245d11STodd Fiala 
12af245d11STodd Fiala // C Includes
13af245d11STodd Fiala #include <errno.h>
145b981ab9SPavel Labath #include <semaphore.h>
15af245d11STodd Fiala #include <string.h>
16af245d11STodd Fiala #include <stdint.h>
17af245d11STodd Fiala #include <unistd.h>
18af245d11STodd Fiala 
19af245d11STodd Fiala // C++ Includes
20af245d11STodd Fiala #include <fstream>
21df7c6995SPavel Labath #include <mutex>
22c076559aSPavel Labath #include <sstream>
23af245d11STodd Fiala #include <string>
245b981ab9SPavel Labath #include <unordered_map>
25af245d11STodd Fiala 
26af245d11STodd Fiala // Other libraries and framework includes
27d8c338d4STamas Berghammer #include "lldb/Core/EmulateInstruction.h"
28af245d11STodd Fiala #include "lldb/Core/Error.h"
29af245d11STodd Fiala #include "lldb/Core/Module.h"
306edef204SOleksiy Vyalov #include "lldb/Core/ModuleSpec.h"
31af245d11STodd Fiala #include "lldb/Core/RegisterValue.h"
32af245d11STodd Fiala #include "lldb/Core/State.h"
331e209fccSTamas Berghammer #include "lldb/Host/common/NativeBreakpoint.h"
340cbf0b13STamas Berghammer #include "lldb/Host/common/NativeRegisterContext.h"
35af245d11STodd Fiala #include "lldb/Host/Host.h"
3639de3110SZachary Turner #include "lldb/Host/ThreadLauncher.h"
375b981ab9SPavel Labath #include "lldb/Target/Platform.h"
3890aff47cSZachary Turner #include "lldb/Target/Process.h"
39af245d11STodd Fiala #include "lldb/Target/ProcessLaunchInfo.h"
405b981ab9SPavel Labath #include "lldb/Target/Target.h"
41c16f5dcaSChaoren Lin #include "lldb/Utility/LLDBAssert.h"
42af245d11STodd Fiala #include "lldb/Utility/PseudoTerminal.h"
43f805e190SPavel Labath #include "lldb/Utility/StringExtractor.h"
44af245d11STodd Fiala 
451e209fccSTamas Berghammer #include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
46af245d11STodd Fiala #include "NativeThreadLinux.h"
47af245d11STodd Fiala #include "ProcFileReader.h"
481e209fccSTamas Berghammer #include "Procfs.h"
49cacde7dfSTodd Fiala 
50d858487eSTamas Berghammer // System includes - They have to be included after framework includes because they define some
51d858487eSTamas Berghammer // macros which collide with variable names in other modules
52d858487eSTamas Berghammer #include <linux/unistd.h>
53d858487eSTamas Berghammer #include <sys/socket.h>
548b335671SVince Harron 
55df7c6995SPavel Labath #include <sys/syscall.h>
56d858487eSTamas Berghammer #include <sys/types.h>
57d858487eSTamas Berghammer #include <sys/user.h>
58d858487eSTamas Berghammer #include <sys/wait.h>
59d858487eSTamas Berghammer 
608b335671SVince Harron #include "lldb/Host/linux/Personality.h"
618b335671SVince Harron #include "lldb/Host/linux/Ptrace.h"
628b335671SVince Harron #include "lldb/Host/linux/Signalfd.h"
63df7c6995SPavel Labath #include "lldb/Host/linux/Uio.h"
648b335671SVince Harron #include "lldb/Host/android/Android.h"
65af245d11STodd Fiala 
660bce1b67STodd Fiala #define LLDB_PERSONALITY_GET_CURRENT_SETTINGS  0xffffffff
67af245d11STodd Fiala 
68af245d11STodd Fiala // Support hardware breakpoints in case it has not been defined
69af245d11STodd Fiala #ifndef TRAP_HWBKPT
70af245d11STodd Fiala   #define TRAP_HWBKPT 4
71af245d11STodd Fiala #endif
72af245d11STodd Fiala 
737cb18bf5STamas Berghammer using namespace lldb;
747cb18bf5STamas Berghammer using namespace lldb_private;
75db264a6dSTamas Berghammer using namespace lldb_private::process_linux;
767cb18bf5STamas Berghammer using namespace llvm;
777cb18bf5STamas Berghammer 
78af245d11STodd Fiala // Private bits we only need internally.
79df7c6995SPavel Labath 
80df7c6995SPavel Labath static bool ProcessVmReadvSupported()
81df7c6995SPavel Labath {
82df7c6995SPavel Labath     static bool is_supported;
83df7c6995SPavel Labath     static std::once_flag flag;
84df7c6995SPavel Labath 
85df7c6995SPavel Labath     std::call_once(flag, [] {
86df7c6995SPavel Labath         Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
87df7c6995SPavel Labath 
88df7c6995SPavel Labath         uint32_t source = 0x47424742;
89df7c6995SPavel Labath         uint32_t dest = 0;
90df7c6995SPavel Labath 
91df7c6995SPavel Labath         struct iovec local, remote;
92df7c6995SPavel Labath         remote.iov_base = &source;
93df7c6995SPavel Labath         local.iov_base = &dest;
94df7c6995SPavel Labath         remote.iov_len = local.iov_len = sizeof source;
95df7c6995SPavel Labath 
96df7c6995SPavel Labath         // We shall try if cross-process-memory reads work by attempting to read a value from our own process.
97df7c6995SPavel Labath         ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
98df7c6995SPavel Labath         is_supported = (res == sizeof(source) && source == dest);
99df7c6995SPavel Labath         if (log)
100df7c6995SPavel Labath         {
101df7c6995SPavel Labath             if (is_supported)
102df7c6995SPavel Labath                 log->Printf("%s: Detected kernel support for process_vm_readv syscall. Fast memory reads enabled.",
103df7c6995SPavel Labath                         __FUNCTION__);
104df7c6995SPavel Labath             else
105df7c6995SPavel Labath                 log->Printf("%s: syscall process_vm_readv failed (error: %s). Fast memory reads disabled.",
106df7c6995SPavel Labath                         __FUNCTION__, strerror(errno));
107df7c6995SPavel Labath         }
108df7c6995SPavel Labath     });
109df7c6995SPavel Labath 
110df7c6995SPavel Labath     return is_supported;
111df7c6995SPavel Labath }
112df7c6995SPavel Labath 
113af245d11STodd Fiala namespace
114af245d11STodd Fiala {
115af245d11STodd Fiala     Error
116af245d11STodd Fiala     ResolveProcessArchitecture (lldb::pid_t pid, Platform &platform, ArchSpec &arch)
117af245d11STodd Fiala     {
118af245d11STodd Fiala         // Grab process info for the running process.
119af245d11STodd Fiala         ProcessInstanceInfo process_info;
120af245d11STodd Fiala         if (!platform.GetProcessInfo (pid, process_info))
121db264a6dSTamas Berghammer             return Error("failed to get process info");
122af245d11STodd Fiala 
123af245d11STodd Fiala         // Resolve the executable module.
124af245d11STodd Fiala         ModuleSP exe_module_sp;
125e56f6dceSChaoren Lin         ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
126af245d11STodd Fiala         FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths ());
127af245d11STodd Fiala         Error error = platform.ResolveExecutable(
12854539338SOleksiy Vyalov             exe_module_spec,
129af245d11STodd Fiala             exe_module_sp,
130af245d11STodd Fiala             executable_search_paths.GetSize () ? &executable_search_paths : NULL);
131af245d11STodd Fiala 
132af245d11STodd Fiala         if (!error.Success ())
133af245d11STodd Fiala             return error;
134af245d11STodd Fiala 
135af245d11STodd Fiala         // Check if we've got our architecture from the exe_module.
136af245d11STodd Fiala         arch = exe_module_sp->GetArchitecture ();
137af245d11STodd Fiala         if (arch.IsValid ())
138af245d11STodd Fiala             return Error();
139af245d11STodd Fiala         else
140af245d11STodd Fiala             return Error("failed to retrieve a valid architecture from the exe module");
141af245d11STodd Fiala     }
142af245d11STodd Fiala 
143af245d11STodd Fiala     void
144db264a6dSTamas Berghammer     DisplayBytes (StreamString &s, void *bytes, uint32_t count)
145af245d11STodd Fiala     {
146af245d11STodd Fiala         uint8_t *ptr = (uint8_t *)bytes;
147af245d11STodd Fiala         const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
148af245d11STodd Fiala         for(uint32_t i=0; i<loop_count; i++)
149af245d11STodd Fiala         {
150af245d11STodd Fiala             s.Printf ("[%x]", *ptr);
151af245d11STodd Fiala             ptr++;
152af245d11STodd Fiala         }
153af245d11STodd Fiala     }
154af245d11STodd Fiala 
155af245d11STodd Fiala     void
156af245d11STodd Fiala     PtraceDisplayBytes(int &req, void *data, size_t data_size)
157af245d11STodd Fiala     {
158af245d11STodd Fiala         StreamString buf;
159af245d11STodd Fiala         Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
160af245d11STodd Fiala                     POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
161af245d11STodd Fiala 
162af245d11STodd Fiala         if (verbose_log)
163af245d11STodd Fiala         {
164af245d11STodd Fiala             switch(req)
165af245d11STodd Fiala             {
166af245d11STodd Fiala             case PTRACE_POKETEXT:
167af245d11STodd Fiala             {
168af245d11STodd Fiala                 DisplayBytes(buf, &data, 8);
169af245d11STodd Fiala                 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
170af245d11STodd Fiala                 break;
171af245d11STodd Fiala             }
172af245d11STodd Fiala             case PTRACE_POKEDATA:
173af245d11STodd Fiala             {
174af245d11STodd Fiala                 DisplayBytes(buf, &data, 8);
175af245d11STodd Fiala                 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
176af245d11STodd Fiala                 break;
177af245d11STodd Fiala             }
178af245d11STodd Fiala             case PTRACE_POKEUSER:
179af245d11STodd Fiala             {
180af245d11STodd Fiala                 DisplayBytes(buf, &data, 8);
181af245d11STodd Fiala                 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
182af245d11STodd Fiala                 break;
183af245d11STodd Fiala             }
184af245d11STodd Fiala             case PTRACE_SETREGS:
185af245d11STodd Fiala             {
186af245d11STodd Fiala                 DisplayBytes(buf, data, data_size);
187af245d11STodd Fiala                 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
188af245d11STodd Fiala                 break;
189af245d11STodd Fiala             }
190af245d11STodd Fiala             case PTRACE_SETFPREGS:
191af245d11STodd Fiala             {
192af245d11STodd Fiala                 DisplayBytes(buf, data, data_size);
193af245d11STodd Fiala                 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
194af245d11STodd Fiala                 break;
195af245d11STodd Fiala             }
196af245d11STodd Fiala             case PTRACE_SETSIGINFO:
197af245d11STodd Fiala             {
198af245d11STodd Fiala                 DisplayBytes(buf, data, sizeof(siginfo_t));
199af245d11STodd Fiala                 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
200af245d11STodd Fiala                 break;
201af245d11STodd Fiala             }
202af245d11STodd Fiala             case PTRACE_SETREGSET:
203af245d11STodd Fiala             {
204af245d11STodd Fiala                 // Extract iov_base from data, which is a pointer to the struct IOVEC
205af245d11STodd Fiala                 DisplayBytes(buf, *(void **)data, data_size);
206af245d11STodd Fiala                 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
207af245d11STodd Fiala                 break;
208af245d11STodd Fiala             }
209af245d11STodd Fiala             default:
210af245d11STodd Fiala             {
211af245d11STodd Fiala             }
212af245d11STodd Fiala             }
213af245d11STodd Fiala         }
214af245d11STodd Fiala     }
215af245d11STodd Fiala 
216af245d11STodd Fiala     //------------------------------------------------------------------------------
217af245d11STodd Fiala     // Static implementations of NativeProcessLinux::ReadMemory and
218af245d11STodd Fiala     // NativeProcessLinux::WriteMemory.  This enables mutual recursion between these
219af245d11STodd Fiala     // functions without needed to go thru the thread funnel.
220af245d11STodd Fiala 
221c7512fdcSPavel Labath     Error
222af245d11STodd Fiala     DoReadMemory(
223af245d11STodd Fiala         lldb::pid_t pid,
224af245d11STodd Fiala         lldb::addr_t vm_addr,
225af245d11STodd Fiala         void *buf,
2263eb4b458SChaoren Lin         size_t size,
227c7512fdcSPavel Labath         size_t &bytes_read)
228af245d11STodd Fiala     {
229af245d11STodd Fiala         // ptrace word size is determined by the host, not the child
230af245d11STodd Fiala         static const unsigned word_size = sizeof(void*);
231af245d11STodd Fiala         unsigned char *dst = static_cast<unsigned char*>(buf);
2323eb4b458SChaoren Lin         size_t remainder;
233af245d11STodd Fiala         long data;
234af245d11STodd Fiala 
235af245d11STodd Fiala         Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
236af245d11STodd Fiala         if (log)
237af245d11STodd Fiala             ProcessPOSIXLog::IncNestLevel();
238af245d11STodd Fiala         if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
239af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
240af245d11STodd Fiala                     pid, word_size, (void*)vm_addr, buf, size);
241af245d11STodd Fiala 
242af245d11STodd Fiala         assert(sizeof(data) >= word_size);
243af245d11STodd Fiala         for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
244af245d11STodd Fiala         {
2454a9babb2SPavel Labath             Error error = NativeProcessLinux::PtraceWrapper(PTRACE_PEEKDATA, pid, (void*)vm_addr, nullptr, 0, &data);
24697ccc294SChaoren Lin             if (error.Fail())
247af245d11STodd Fiala             {
248af245d11STodd Fiala                 if (log)
249af245d11STodd Fiala                     ProcessPOSIXLog::DecNestLevel();
250c7512fdcSPavel Labath                 return error;
251af245d11STodd Fiala             }
252af245d11STodd Fiala 
253af245d11STodd Fiala             remainder = size - bytes_read;
254af245d11STodd Fiala             remainder = remainder > word_size ? word_size : remainder;
255af245d11STodd Fiala 
256af245d11STodd Fiala             // Copy the data into our buffer
257af245d11STodd Fiala             for (unsigned i = 0; i < remainder; ++i)
258af245d11STodd Fiala                 dst[i] = ((data >> i*8) & 0xFF);
259af245d11STodd Fiala 
260af245d11STodd Fiala             if (log && ProcessPOSIXLog::AtTopNestLevel() &&
261af245d11STodd Fiala                     (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
262af245d11STodd Fiala                             (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
263af245d11STodd Fiala                                     size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
264af245d11STodd Fiala             {
265af245d11STodd Fiala                 uintptr_t print_dst = 0;
266af245d11STodd Fiala                 // Format bytes from data by moving into print_dst for log output
267af245d11STodd Fiala                 for (unsigned i = 0; i < remainder; ++i)
268af245d11STodd Fiala                     print_dst |= (((data >> i*8) & 0xFF) << i*8);
269af245d11STodd Fiala                 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
270af245d11STodd Fiala                         (void*)vm_addr, print_dst, (unsigned long)data);
271af245d11STodd Fiala             }
272af245d11STodd Fiala             vm_addr += word_size;
273af245d11STodd Fiala             dst += word_size;
274af245d11STodd Fiala         }
275af245d11STodd Fiala 
276af245d11STodd Fiala         if (log)
277af245d11STodd Fiala             ProcessPOSIXLog::DecNestLevel();
278c7512fdcSPavel Labath         return Error();
279af245d11STodd Fiala     }
280af245d11STodd Fiala 
281c7512fdcSPavel Labath     Error
282af245d11STodd Fiala     DoWriteMemory(
283af245d11STodd Fiala         lldb::pid_t pid,
284af245d11STodd Fiala         lldb::addr_t vm_addr,
285af245d11STodd Fiala         const void *buf,
2863eb4b458SChaoren Lin         size_t size,
287c7512fdcSPavel Labath         size_t &bytes_written)
288af245d11STodd Fiala     {
289af245d11STodd Fiala         // ptrace word size is determined by the host, not the child
290af245d11STodd Fiala         static const unsigned word_size = sizeof(void*);
291af245d11STodd Fiala         const unsigned char *src = static_cast<const unsigned char*>(buf);
2923eb4b458SChaoren Lin         size_t remainder;
293c7512fdcSPavel Labath         Error error;
294af245d11STodd Fiala 
295af245d11STodd Fiala         Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
296af245d11STodd Fiala         if (log)
297af245d11STodd Fiala             ProcessPOSIXLog::IncNestLevel();
298af245d11STodd Fiala         if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
299af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %u, %p, %p, %" PRIu64 ")", __FUNCTION__,
300af245d11STodd Fiala                     pid, word_size, (void*)vm_addr, buf, size);
301af245d11STodd Fiala 
302af245d11STodd Fiala         for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
303af245d11STodd Fiala         {
304af245d11STodd Fiala             remainder = size - bytes_written;
305af245d11STodd Fiala             remainder = remainder > word_size ? word_size : remainder;
306af245d11STodd Fiala 
307af245d11STodd Fiala             if (remainder == word_size)
308af245d11STodd Fiala             {
309af245d11STodd Fiala                 unsigned long data = 0;
310af245d11STodd Fiala                 assert(sizeof(data) >= word_size);
311af245d11STodd Fiala                 for (unsigned i = 0; i < word_size; ++i)
312af245d11STodd Fiala                     data |= (unsigned long)src[i] << i*8;
313af245d11STodd Fiala 
314af245d11STodd Fiala                 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
315af245d11STodd Fiala                         (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
316af245d11STodd Fiala                                 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
317af245d11STodd Fiala                                         size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
318af245d11STodd Fiala                     log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
3191e209fccSTamas Berghammer                             (void*)vm_addr, *(const unsigned long*)src, data);
320af245d11STodd Fiala 
3214a9babb2SPavel Labath                 error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, pid, (void*)vm_addr, (void*)data);
3224a9babb2SPavel Labath                 if (error.Fail())
323af245d11STodd Fiala                 {
324af245d11STodd Fiala                     if (log)
325af245d11STodd Fiala                         ProcessPOSIXLog::DecNestLevel();
326c7512fdcSPavel Labath                     return error;
327af245d11STodd Fiala                 }
328af245d11STodd Fiala             }
329af245d11STodd Fiala             else
330af245d11STodd Fiala             {
331af245d11STodd Fiala                 unsigned char buff[8];
332c7512fdcSPavel Labath                 size_t bytes_read;
333c7512fdcSPavel Labath                 error = DoReadMemory(pid, vm_addr, buff, word_size, bytes_read);
334c7512fdcSPavel Labath                 if (error.Fail())
335af245d11STodd Fiala                 {
336af245d11STodd Fiala                     if (log)
337af245d11STodd Fiala                         ProcessPOSIXLog::DecNestLevel();
338c7512fdcSPavel Labath                     return error;
339af245d11STodd Fiala                 }
340af245d11STodd Fiala 
341af245d11STodd Fiala                 memcpy(buff, src, remainder);
342af245d11STodd Fiala 
343c7512fdcSPavel Labath                 size_t bytes_written_rec;
344c7512fdcSPavel Labath                 error = DoWriteMemory(pid, vm_addr, buff, word_size, bytes_written_rec);
345c7512fdcSPavel Labath                 if (error.Fail())
346af245d11STodd Fiala                 {
347af245d11STodd Fiala                     if (log)
348af245d11STodd Fiala                         ProcessPOSIXLog::DecNestLevel();
349c7512fdcSPavel Labath                     return error;
350af245d11STodd Fiala                 }
351af245d11STodd Fiala 
352af245d11STodd Fiala                 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
353af245d11STodd Fiala                         (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
354af245d11STodd Fiala                                 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
355af245d11STodd Fiala                                         size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
356af245d11STodd Fiala                     log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
3571e209fccSTamas Berghammer                             (void*)vm_addr, *(const unsigned long*)src, *(unsigned long*)buff);
358af245d11STodd Fiala             }
359af245d11STodd Fiala 
360af245d11STodd Fiala             vm_addr += word_size;
361af245d11STodd Fiala             src += word_size;
362af245d11STodd Fiala         }
363af245d11STodd Fiala         if (log)
364af245d11STodd Fiala             ProcessPOSIXLog::DecNestLevel();
365c7512fdcSPavel Labath         return error;
366af245d11STodd Fiala     }
3671107b5a5SPavel Labath } // end of anonymous namespace
3681107b5a5SPavel Labath 
369bd7cbc5aSPavel Labath // Simple helper function to ensure flags are enabled on the given file
370bd7cbc5aSPavel Labath // descriptor.
371bd7cbc5aSPavel Labath static Error
372bd7cbc5aSPavel Labath EnsureFDFlags(int fd, int flags)
373bd7cbc5aSPavel Labath {
374bd7cbc5aSPavel Labath     Error error;
375bd7cbc5aSPavel Labath 
376bd7cbc5aSPavel Labath     int status = fcntl(fd, F_GETFL);
377bd7cbc5aSPavel Labath     if (status == -1)
378bd7cbc5aSPavel Labath     {
379bd7cbc5aSPavel Labath         error.SetErrorToErrno();
380bd7cbc5aSPavel Labath         return error;
381bd7cbc5aSPavel Labath     }
382bd7cbc5aSPavel Labath 
383bd7cbc5aSPavel Labath     if (fcntl(fd, F_SETFL, status | flags) == -1)
384bd7cbc5aSPavel Labath     {
385bd7cbc5aSPavel Labath         error.SetErrorToErrno();
386bd7cbc5aSPavel Labath         return error;
387bd7cbc5aSPavel Labath     }
388bd7cbc5aSPavel Labath 
389bd7cbc5aSPavel Labath     return error;
390bd7cbc5aSPavel Labath }
391bd7cbc5aSPavel Labath 
392bd7cbc5aSPavel Labath // This class encapsulates the privileged thread which performs all ptrace and wait operations on
393bd7cbc5aSPavel Labath // the inferior. The thread consists of a main loop which waits for events and processes them
394bd7cbc5aSPavel Labath //   - SIGCHLD (delivered over a signalfd file descriptor): These signals notify us of events in
395bd7cbc5aSPavel Labath //     the inferior process. Upon receiving this signal we do a waitpid to get more information
396bd7cbc5aSPavel Labath //     and dispatch to NativeProcessLinux::MonitorCallback.
397bd7cbc5aSPavel Labath //   - requests for ptrace operations: These initiated via the DoOperation method, which funnels
398bd7cbc5aSPavel Labath //     them to the Monitor thread via m_operation member. The Monitor thread is signaled over a
399bd7cbc5aSPavel Labath //     pipe, and the completion of the operation is signalled over the semaphore.
400bd7cbc5aSPavel Labath //   - thread exit event: this is signaled from the Monitor destructor by closing the write end
401bd7cbc5aSPavel Labath //     of the command pipe.
40245f5cb31SPavel Labath class NativeProcessLinux::Monitor
40345f5cb31SPavel Labath {
4041107b5a5SPavel Labath private:
405bd7cbc5aSPavel Labath     // The initial monitor operation (launch or attach). It returns a inferior process id.
406bd7cbc5aSPavel Labath     std::unique_ptr<InitialOperation> m_initial_operation_up;
407bd7cbc5aSPavel Labath 
408bd7cbc5aSPavel Labath     ::pid_t                           m_child_pid = -1;
4091107b5a5SPavel Labath     NativeProcessLinux              * m_native_process;
4101107b5a5SPavel Labath 
4111107b5a5SPavel Labath     enum { READ, WRITE };
4121107b5a5SPavel Labath     int        m_pipefd[2] = {-1, -1};
4131107b5a5SPavel Labath     int        m_signal_fd = -1;
4141107b5a5SPavel Labath     HostThread m_thread;
4151107b5a5SPavel Labath 
416bd7cbc5aSPavel Labath     // current operation which must be executed on the priviliged thread
417bd7cbc5aSPavel Labath     Mutex            m_operation_mutex;
418c7512fdcSPavel Labath     const Operation *m_operation = nullptr;
419bd7cbc5aSPavel Labath     sem_t            m_operation_sem;
420bd7cbc5aSPavel Labath     Error            m_operation_error;
421bd7cbc5aSPavel Labath 
42245f5cb31SPavel Labath     unsigned   m_operation_nesting_level = 0;
42345f5cb31SPavel Labath 
424bd7cbc5aSPavel Labath     static constexpr char operation_command   = 'o';
42545f5cb31SPavel Labath     static constexpr char begin_block_command = '{';
42645f5cb31SPavel Labath     static constexpr char end_block_command   = '}';
427bd7cbc5aSPavel Labath 
4281107b5a5SPavel Labath     void
4291107b5a5SPavel Labath     HandleSignals();
4301107b5a5SPavel Labath 
4311107b5a5SPavel Labath     void
4321107b5a5SPavel Labath     HandleWait();
4331107b5a5SPavel Labath 
4341107b5a5SPavel Labath     // Returns true if the thread should exit.
4351107b5a5SPavel Labath     bool
4361107b5a5SPavel Labath     HandleCommands();
4371107b5a5SPavel Labath 
4381107b5a5SPavel Labath     void
4391107b5a5SPavel Labath     MainLoop();
4401107b5a5SPavel Labath 
4411107b5a5SPavel Labath     static void *
4421107b5a5SPavel Labath     RunMonitor(void *arg);
4431107b5a5SPavel Labath 
444bd7cbc5aSPavel Labath     Error
44545f5cb31SPavel Labath     WaitForAck();
44645f5cb31SPavel Labath 
44745f5cb31SPavel Labath     void
44845f5cb31SPavel Labath     BeginOperationBlock()
44945f5cb31SPavel Labath     {
45045f5cb31SPavel Labath         write(m_pipefd[WRITE], &begin_block_command, sizeof operation_command);
45145f5cb31SPavel Labath         WaitForAck();
45245f5cb31SPavel Labath     }
45345f5cb31SPavel Labath 
45445f5cb31SPavel Labath     void
45545f5cb31SPavel Labath     EndOperationBlock()
45645f5cb31SPavel Labath     {
45745f5cb31SPavel Labath         write(m_pipefd[WRITE], &end_block_command, sizeof operation_command);
45845f5cb31SPavel Labath         WaitForAck();
45945f5cb31SPavel Labath     }
46045f5cb31SPavel Labath 
4611107b5a5SPavel Labath public:
462bd7cbc5aSPavel Labath     Monitor(const InitialOperation &initial_operation,
463bd7cbc5aSPavel Labath             NativeProcessLinux *native_process)
464bd7cbc5aSPavel Labath         : m_initial_operation_up(new InitialOperation(initial_operation)),
465bd7cbc5aSPavel Labath           m_native_process(native_process)
466bd7cbc5aSPavel Labath     {
467bd7cbc5aSPavel Labath         sem_init(&m_operation_sem, 0, 0);
468bd7cbc5aSPavel Labath     }
4691107b5a5SPavel Labath 
4701107b5a5SPavel Labath     ~Monitor();
4711107b5a5SPavel Labath 
4721107b5a5SPavel Labath     Error
4731107b5a5SPavel Labath     Initialize();
474bd7cbc5aSPavel Labath 
475bd7cbc5aSPavel Labath     void
47645f5cb31SPavel Labath     Terminate();
47745f5cb31SPavel Labath 
478c7512fdcSPavel Labath     Error
479c7512fdcSPavel Labath     DoOperation(const Operation &op);
48045f5cb31SPavel Labath 
48145f5cb31SPavel Labath     class ScopedOperationLock {
48245f5cb31SPavel Labath         Monitor &m_monitor;
48345f5cb31SPavel Labath 
48445f5cb31SPavel Labath     public:
48545f5cb31SPavel Labath         ScopedOperationLock(Monitor &monitor)
48645f5cb31SPavel Labath             : m_monitor(monitor)
48745f5cb31SPavel Labath         { m_monitor.BeginOperationBlock(); }
48845f5cb31SPavel Labath 
48945f5cb31SPavel Labath         ~ScopedOperationLock()
49045f5cb31SPavel Labath         { m_monitor.EndOperationBlock(); }
49145f5cb31SPavel Labath     };
4921107b5a5SPavel Labath };
493bd7cbc5aSPavel Labath constexpr char NativeProcessLinux::Monitor::operation_command;
49445f5cb31SPavel Labath constexpr char NativeProcessLinux::Monitor::begin_block_command;
49545f5cb31SPavel Labath constexpr char NativeProcessLinux::Monitor::end_block_command;
4961107b5a5SPavel Labath 
4971107b5a5SPavel Labath Error
4981107b5a5SPavel Labath NativeProcessLinux::Monitor::Initialize()
4991107b5a5SPavel Labath {
5001107b5a5SPavel Labath     Error error;
5011107b5a5SPavel Labath 
5021107b5a5SPavel Labath     // We get a SIGCHLD every time something interesting happens with the inferior. We shall be
5031107b5a5SPavel Labath     // listening for these signals over a signalfd file descriptors. This allows us to wait for
5041107b5a5SPavel Labath     // multiple kinds of events with select.
5051107b5a5SPavel Labath     sigset_t signals;
5061107b5a5SPavel Labath     sigemptyset(&signals);
5071107b5a5SPavel Labath     sigaddset(&signals, SIGCHLD);
5081107b5a5SPavel Labath     m_signal_fd = signalfd(-1, &signals, SFD_NONBLOCK | SFD_CLOEXEC);
5091107b5a5SPavel Labath     if (m_signal_fd < 0)
5101107b5a5SPavel Labath     {
5111107b5a5SPavel Labath         return Error("NativeProcessLinux::Monitor::%s failed due to signalfd failure. Monitoring the inferior will be impossible: %s",
5121107b5a5SPavel Labath                     __FUNCTION__, strerror(errno));
5131107b5a5SPavel Labath 
514af245d11STodd Fiala     }
515af245d11STodd Fiala 
5161107b5a5SPavel Labath     if (pipe2(m_pipefd, O_CLOEXEC) == -1)
5171107b5a5SPavel Labath     {
5181107b5a5SPavel Labath         error.SetErrorToErrno();
5191107b5a5SPavel Labath         return error;
5201107b5a5SPavel Labath     }
5211107b5a5SPavel Labath 
522bd7cbc5aSPavel Labath     if ((error = EnsureFDFlags(m_pipefd[READ], O_NONBLOCK)).Fail()) {
523bd7cbc5aSPavel Labath         return error;
524bd7cbc5aSPavel Labath     }
525bd7cbc5aSPavel Labath 
526bd7cbc5aSPavel Labath     static const char g_thread_name[] = "lldb.process.nativelinux.monitor";
527bd7cbc5aSPavel Labath     m_thread = ThreadLauncher::LaunchThread(g_thread_name, Monitor::RunMonitor, this, nullptr);
5281107b5a5SPavel Labath     if (!m_thread.IsJoinable())
5291107b5a5SPavel Labath         return Error("Failed to create monitor thread for NativeProcessLinux.");
5301107b5a5SPavel Labath 
531bd7cbc5aSPavel Labath     // Wait for initial operation to complete.
53245f5cb31SPavel Labath     return WaitForAck();
533bd7cbc5aSPavel Labath }
534bd7cbc5aSPavel Labath 
535c7512fdcSPavel Labath Error
536c7512fdcSPavel Labath NativeProcessLinux::Monitor::DoOperation(const Operation &op)
537bd7cbc5aSPavel Labath {
538bd7cbc5aSPavel Labath     if (m_thread.EqualsThread(pthread_self())) {
539bd7cbc5aSPavel Labath         // If we're on the Monitor thread, we can simply execute the operation.
540c7512fdcSPavel Labath         return op();
541bd7cbc5aSPavel Labath     }
542bd7cbc5aSPavel Labath 
543bd7cbc5aSPavel Labath     // Otherwise we need to pass the operation to the Monitor thread so it can handle it.
544bd7cbc5aSPavel Labath     Mutex::Locker lock(m_operation_mutex);
545bd7cbc5aSPavel Labath 
546c7512fdcSPavel Labath     m_operation = &op;
547bd7cbc5aSPavel Labath 
548bd7cbc5aSPavel Labath     // notify the thread that an operation is ready to be processed
549bd7cbc5aSPavel Labath     write(m_pipefd[WRITE], &operation_command, sizeof operation_command);
550bd7cbc5aSPavel Labath 
551c7512fdcSPavel Labath     return WaitForAck();
55245f5cb31SPavel Labath }
55345f5cb31SPavel Labath 
55445f5cb31SPavel Labath void
55545f5cb31SPavel Labath NativeProcessLinux::Monitor::Terminate()
55645f5cb31SPavel Labath {
55745f5cb31SPavel Labath     if (m_pipefd[WRITE] >= 0)
55845f5cb31SPavel Labath     {
55945f5cb31SPavel Labath         close(m_pipefd[WRITE]);
56045f5cb31SPavel Labath         m_pipefd[WRITE] = -1;
56145f5cb31SPavel Labath     }
56245f5cb31SPavel Labath     if (m_thread.IsJoinable())
56345f5cb31SPavel Labath         m_thread.Join(nullptr);
5641107b5a5SPavel Labath }
5651107b5a5SPavel Labath 
5661107b5a5SPavel Labath NativeProcessLinux::Monitor::~Monitor()
5671107b5a5SPavel Labath {
56845f5cb31SPavel Labath     Terminate();
5691107b5a5SPavel Labath     if (m_pipefd[READ] >= 0)
5701107b5a5SPavel Labath         close(m_pipefd[READ]);
5711107b5a5SPavel Labath     if (m_signal_fd >= 0)
5721107b5a5SPavel Labath         close(m_signal_fd);
573bd7cbc5aSPavel Labath     sem_destroy(&m_operation_sem);
5741107b5a5SPavel Labath }
5751107b5a5SPavel Labath 
5761107b5a5SPavel Labath void
5771107b5a5SPavel Labath NativeProcessLinux::Monitor::HandleSignals()
5781107b5a5SPavel Labath {
5791107b5a5SPavel Labath     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
5801107b5a5SPavel Labath 
5811107b5a5SPavel Labath     // We don't really care about the content of the SIGCHLD siginfo structure, as we will get
5821107b5a5SPavel Labath     // all the information from waitpid(). We just need to read all the signals so that we can
5831107b5a5SPavel Labath     // sleep next time we reach select().
5841107b5a5SPavel Labath     while (true)
5851107b5a5SPavel Labath     {
5861107b5a5SPavel Labath         signalfd_siginfo info;
5871107b5a5SPavel Labath         ssize_t size = read(m_signal_fd, &info, sizeof info);
5881107b5a5SPavel Labath         if (size == -1)
5891107b5a5SPavel Labath         {
5901107b5a5SPavel Labath             if (errno == EAGAIN || errno == EWOULDBLOCK)
5911107b5a5SPavel Labath                 break; // We are done.
5921107b5a5SPavel Labath             if (errno == EINTR)
5931107b5a5SPavel Labath                 continue;
5941107b5a5SPavel Labath             if (log)
5951107b5a5SPavel Labath                 log->Printf("NativeProcessLinux::Monitor::%s reading from signalfd file descriptor failed: %s",
5961107b5a5SPavel Labath                         __FUNCTION__, strerror(errno));
5971107b5a5SPavel Labath             break;
5981107b5a5SPavel Labath         }
5991107b5a5SPavel Labath         if (size != sizeof info)
6001107b5a5SPavel Labath         {
6011107b5a5SPavel Labath             // We got incomplete information structure. This should not happen, let's just log
6021107b5a5SPavel Labath             // that.
6031107b5a5SPavel Labath             if (log)
6041107b5a5SPavel Labath                 log->Printf("NativeProcessLinux::Monitor::%s reading from signalfd file descriptor returned incomplete data: "
6051107b5a5SPavel Labath                         "structure size is %zd, read returned %zd bytes",
6061107b5a5SPavel Labath                         __FUNCTION__, sizeof info, size);
6071107b5a5SPavel Labath             break;
6081107b5a5SPavel Labath         }
6091107b5a5SPavel Labath         if (log)
6101107b5a5SPavel Labath             log->Printf("NativeProcessLinux::Monitor::%s received signal %s(%d).", __FUNCTION__,
6111107b5a5SPavel Labath                 Host::GetSignalAsCString(info.ssi_signo), info.ssi_signo);
6121107b5a5SPavel Labath     }
6131107b5a5SPavel Labath }
6141107b5a5SPavel Labath 
6151107b5a5SPavel Labath void
6161107b5a5SPavel Labath NativeProcessLinux::Monitor::HandleWait()
6171107b5a5SPavel Labath {
6181107b5a5SPavel Labath     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
6191107b5a5SPavel Labath     // Process all pending waitpid notifications.
6201107b5a5SPavel Labath     while (true)
6211107b5a5SPavel Labath     {
6221107b5a5SPavel Labath         int status = -1;
62305a1f2acSPavel Labath         ::pid_t wait_pid = waitpid(-1, &status, __WALL | __WNOTHREAD | WNOHANG);
6241107b5a5SPavel Labath 
6251107b5a5SPavel Labath         if (wait_pid == 0)
6261107b5a5SPavel Labath             break; // We are done.
6271107b5a5SPavel Labath 
6281107b5a5SPavel Labath         if (wait_pid == -1)
6291107b5a5SPavel Labath         {
6301107b5a5SPavel Labath             if (errno == EINTR)
6311107b5a5SPavel Labath                 continue;
6321107b5a5SPavel Labath 
6331107b5a5SPavel Labath             if (log)
63405a1f2acSPavel Labath               log->Printf("NativeProcessLinux::Monitor::%s waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG) failed: %s",
63505a1f2acSPavel Labath                       __FUNCTION__, strerror(errno));
6361107b5a5SPavel Labath             break;
6371107b5a5SPavel Labath         }
6381107b5a5SPavel Labath 
6391107b5a5SPavel Labath         bool exited = false;
6401107b5a5SPavel Labath         int signal = 0;
6411107b5a5SPavel Labath         int exit_status = 0;
6421107b5a5SPavel Labath         const char *status_cstr = NULL;
6431107b5a5SPavel Labath         if (WIFSTOPPED(status))
6441107b5a5SPavel Labath         {
6451107b5a5SPavel Labath             signal = WSTOPSIG(status);
6461107b5a5SPavel Labath             status_cstr = "STOPPED";
6471107b5a5SPavel Labath         }
6481107b5a5SPavel Labath         else if (WIFEXITED(status))
6491107b5a5SPavel Labath         {
6501107b5a5SPavel Labath             exit_status = WEXITSTATUS(status);
6511107b5a5SPavel Labath             status_cstr = "EXITED";
6521107b5a5SPavel Labath             exited = true;
6531107b5a5SPavel Labath         }
6541107b5a5SPavel Labath         else if (WIFSIGNALED(status))
6551107b5a5SPavel Labath         {
6561107b5a5SPavel Labath             signal = WTERMSIG(status);
6571107b5a5SPavel Labath             status_cstr = "SIGNALED";
65805a1f2acSPavel Labath             if (wait_pid == m_child_pid) {
6591107b5a5SPavel Labath                 exited = true;
6601107b5a5SPavel Labath                 exit_status = -1;
6611107b5a5SPavel Labath             }
6621107b5a5SPavel Labath         }
6631107b5a5SPavel Labath         else
6641107b5a5SPavel Labath             status_cstr = "(\?\?\?)";
6651107b5a5SPavel Labath 
6661107b5a5SPavel Labath         if (log)
66705a1f2acSPavel Labath             log->Printf("NativeProcessLinux::Monitor::%s: waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG)"
6681107b5a5SPavel Labath                 "=> pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
66905a1f2acSPavel Labath                 __FUNCTION__, wait_pid, status, status_cstr, signal, exit_status);
6701107b5a5SPavel Labath 
6711107b5a5SPavel Labath         m_native_process->MonitorCallback (wait_pid, exited, signal, exit_status);
6721107b5a5SPavel Labath     }
6731107b5a5SPavel Labath }
6741107b5a5SPavel Labath 
6751107b5a5SPavel Labath bool
6761107b5a5SPavel Labath NativeProcessLinux::Monitor::HandleCommands()
6771107b5a5SPavel Labath {
6781107b5a5SPavel Labath     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
6791107b5a5SPavel Labath 
6801107b5a5SPavel Labath     while (true)
6811107b5a5SPavel Labath     {
6821107b5a5SPavel Labath         char command = 0;
6831107b5a5SPavel Labath         ssize_t size = read(m_pipefd[READ], &command, sizeof command);
6841107b5a5SPavel Labath         if (size == -1)
6851107b5a5SPavel Labath         {
6861107b5a5SPavel Labath             if (errno == EAGAIN || errno == EWOULDBLOCK)
6871107b5a5SPavel Labath                 return false;
6881107b5a5SPavel Labath             if (errno == EINTR)
6891107b5a5SPavel Labath                 continue;
6901107b5a5SPavel Labath             if (log)
6911107b5a5SPavel Labath                 log->Printf("NativeProcessLinux::Monitor::%s exiting because read from command file descriptor failed: %s", __FUNCTION__, strerror(errno));
6921107b5a5SPavel Labath             return true;
6931107b5a5SPavel Labath         }
6941107b5a5SPavel Labath         if (size == 0) // end of file - write end closed
6951107b5a5SPavel Labath         {
6961107b5a5SPavel Labath             if (log)
6971107b5a5SPavel Labath                 log->Printf("NativeProcessLinux::Monitor::%s exit command received, exiting...", __FUNCTION__);
69845f5cb31SPavel Labath             assert(m_operation_nesting_level == 0 && "Unbalanced begin/end block commands detected");
6991107b5a5SPavel Labath             return true; // We are done.
7001107b5a5SPavel Labath         }
701bd7cbc5aSPavel Labath 
702bd7cbc5aSPavel Labath         switch (command)
703bd7cbc5aSPavel Labath         {
704bd7cbc5aSPavel Labath         case operation_command:
705c7512fdcSPavel Labath             m_operation_error = (*m_operation)();
70645f5cb31SPavel Labath             break;
70745f5cb31SPavel Labath         case begin_block_command:
70845f5cb31SPavel Labath             ++m_operation_nesting_level;
70945f5cb31SPavel Labath             break;
71045f5cb31SPavel Labath         case end_block_command:
71145f5cb31SPavel Labath             assert(m_operation_nesting_level > 0);
71245f5cb31SPavel Labath             --m_operation_nesting_level;
713bd7cbc5aSPavel Labath             break;
714bd7cbc5aSPavel Labath         default:
7151107b5a5SPavel Labath             if (log)
7161107b5a5SPavel Labath                 log->Printf("NativeProcessLinux::Monitor::%s received unknown command '%c'",
7171107b5a5SPavel Labath                         __FUNCTION__, command);
7181107b5a5SPavel Labath         }
71945f5cb31SPavel Labath 
72045f5cb31SPavel Labath         // notify calling thread that the command has been processed
72145f5cb31SPavel Labath         sem_post(&m_operation_sem);
7221107b5a5SPavel Labath     }
723bd7cbc5aSPavel Labath }
7241107b5a5SPavel Labath 
7251107b5a5SPavel Labath void
7261107b5a5SPavel Labath NativeProcessLinux::Monitor::MainLoop()
7271107b5a5SPavel Labath {
728bd7cbc5aSPavel Labath     ::pid_t child_pid = (*m_initial_operation_up)(m_operation_error);
729bd7cbc5aSPavel Labath     m_initial_operation_up.reset();
73005a1f2acSPavel Labath     m_child_pid = child_pid;
731bd7cbc5aSPavel Labath     sem_post(&m_operation_sem);
732bd7cbc5aSPavel Labath 
7331107b5a5SPavel Labath     while (true)
7341107b5a5SPavel Labath     {
7351107b5a5SPavel Labath         fd_set fds;
7361107b5a5SPavel Labath         FD_ZERO(&fds);
73745f5cb31SPavel Labath         // Only process waitpid events if we are outside of an operation block. Any pending
73845f5cb31SPavel Labath         // events will be processed after we leave the block.
73945f5cb31SPavel Labath         if (m_operation_nesting_level == 0)
7401107b5a5SPavel Labath             FD_SET(m_signal_fd, &fds);
7411107b5a5SPavel Labath         FD_SET(m_pipefd[READ], &fds);
7421107b5a5SPavel Labath 
7431107b5a5SPavel Labath         int max_fd = std::max(m_signal_fd, m_pipefd[READ]) + 1;
7441107b5a5SPavel Labath         int r = select(max_fd, &fds, nullptr, nullptr, nullptr);
7451107b5a5SPavel Labath         if (r < 0)
7461107b5a5SPavel Labath         {
7471107b5a5SPavel Labath             Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
7481107b5a5SPavel Labath             if (log)
7491107b5a5SPavel Labath                 log->Printf("NativeProcessLinux::Monitor::%s exiting because select failed: %s",
7501107b5a5SPavel Labath                         __FUNCTION__, strerror(errno));
7511107b5a5SPavel Labath             return;
7521107b5a5SPavel Labath         }
7531107b5a5SPavel Labath 
7541107b5a5SPavel Labath         if (FD_ISSET(m_pipefd[READ], &fds))
7551107b5a5SPavel Labath         {
7561107b5a5SPavel Labath             if (HandleCommands())
7571107b5a5SPavel Labath                 return;
7581107b5a5SPavel Labath         }
7591107b5a5SPavel Labath 
7601107b5a5SPavel Labath         if (FD_ISSET(m_signal_fd, &fds))
7611107b5a5SPavel Labath         {
7621107b5a5SPavel Labath             HandleSignals();
7631107b5a5SPavel Labath             HandleWait();
7641107b5a5SPavel Labath         }
7651107b5a5SPavel Labath     }
7661107b5a5SPavel Labath }
7671107b5a5SPavel Labath 
768bd7cbc5aSPavel Labath Error
76945f5cb31SPavel Labath NativeProcessLinux::Monitor::WaitForAck()
770bd7cbc5aSPavel Labath {
771bd7cbc5aSPavel Labath     Error error;
772bd7cbc5aSPavel Labath     while (sem_wait(&m_operation_sem) != 0)
773bd7cbc5aSPavel Labath     {
774bd7cbc5aSPavel Labath         if (errno == EINTR)
775bd7cbc5aSPavel Labath             continue;
776bd7cbc5aSPavel Labath 
777bd7cbc5aSPavel Labath         error.SetErrorToErrno();
778bd7cbc5aSPavel Labath         return error;
779bd7cbc5aSPavel Labath     }
780bd7cbc5aSPavel Labath 
781bd7cbc5aSPavel Labath     return m_operation_error;
782bd7cbc5aSPavel Labath }
783bd7cbc5aSPavel Labath 
7841107b5a5SPavel Labath void *
7851107b5a5SPavel Labath NativeProcessLinux::Monitor::RunMonitor(void *arg)
7861107b5a5SPavel Labath {
7871107b5a5SPavel Labath     static_cast<Monitor *>(arg)->MainLoop();
7881107b5a5SPavel Labath     return nullptr;
7891107b5a5SPavel Labath }
7901107b5a5SPavel Labath 
7911107b5a5SPavel Labath 
792bd7cbc5aSPavel Labath NativeProcessLinux::LaunchArgs::LaunchArgs(Module *module,
793af245d11STodd Fiala                                        char const **argv,
794af245d11STodd Fiala                                        char const **envp,
795d3173f34SChaoren Lin                                        const FileSpec &stdin_file_spec,
796d3173f34SChaoren Lin                                        const FileSpec &stdout_file_spec,
797d3173f34SChaoren Lin                                        const FileSpec &stderr_file_spec,
798d3173f34SChaoren Lin                                        const FileSpec &working_dir,
799db264a6dSTamas Berghammer                                        const ProcessLaunchInfo &launch_info)
800bd7cbc5aSPavel Labath     : m_module(module),
801af245d11STodd Fiala       m_argv(argv),
802af245d11STodd Fiala       m_envp(envp),
803d3173f34SChaoren Lin       m_stdin_file_spec(stdin_file_spec),
804d3173f34SChaoren Lin       m_stdout_file_spec(stdout_file_spec),
805d3173f34SChaoren Lin       m_stderr_file_spec(stderr_file_spec),
8060bce1b67STodd Fiala       m_working_dir(working_dir),
8070bce1b67STodd Fiala       m_launch_info(launch_info)
8080bce1b67STodd Fiala {
8090bce1b67STodd Fiala }
810af245d11STodd Fiala 
811af245d11STodd Fiala NativeProcessLinux::LaunchArgs::~LaunchArgs()
812af245d11STodd Fiala { }
813af245d11STodd Fiala 
814af245d11STodd Fiala // -----------------------------------------------------------------------------
815af245d11STodd Fiala // Public Static Methods
816af245d11STodd Fiala // -----------------------------------------------------------------------------
817af245d11STodd Fiala 
818db264a6dSTamas Berghammer Error
819d5b310f2SPavel Labath NativeProcessProtocol::Launch (
820db264a6dSTamas Berghammer     ProcessLaunchInfo &launch_info,
821db264a6dSTamas Berghammer     NativeProcessProtocol::NativeDelegate &native_delegate,
822af245d11STodd Fiala     NativeProcessProtocolSP &native_process_sp)
823af245d11STodd Fiala {
824af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
825af245d11STodd Fiala 
826d5b310f2SPavel Labath     lldb::ModuleSP exe_module_sp;
827d5b310f2SPavel Labath     PlatformSP platform_sp (Platform::GetHostPlatform ());
828d5b310f2SPavel Labath     Error error = platform_sp->ResolveExecutable(
829d5b310f2SPavel Labath             ModuleSpec(launch_info.GetExecutableFile(), launch_info.GetArchitecture()),
830d5b310f2SPavel Labath             exe_module_sp,
831d5b310f2SPavel Labath             nullptr);
832d5b310f2SPavel Labath 
833d5b310f2SPavel Labath     if (! error.Success())
834d5b310f2SPavel Labath         return error;
835af245d11STodd Fiala 
836af245d11STodd Fiala     // Verify the working directory is valid if one was specified.
837d3173f34SChaoren Lin     FileSpec working_dir{launch_info.GetWorkingDirectory()};
838d3173f34SChaoren Lin     if (working_dir &&
839d3173f34SChaoren Lin             (!working_dir.ResolvePath() ||
840d3173f34SChaoren Lin              working_dir.GetFileType() != FileSpec::eFileTypeDirectory))
841af245d11STodd Fiala     {
842d3173f34SChaoren Lin         error.SetErrorStringWithFormat ("No such file or directory: %s",
843d3173f34SChaoren Lin                 working_dir.GetCString());
844af245d11STodd Fiala         return error;
845af245d11STodd Fiala     }
846af245d11STodd Fiala 
847db264a6dSTamas Berghammer     const FileAction *file_action;
848af245d11STodd Fiala 
849d3173f34SChaoren Lin     // Default of empty will mean to use existing open file descriptors.
850d3173f34SChaoren Lin     FileSpec stdin_file_spec{};
851d3173f34SChaoren Lin     FileSpec stdout_file_spec{};
852d3173f34SChaoren Lin     FileSpec stderr_file_spec{};
853af245d11STodd Fiala 
854af245d11STodd Fiala     file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
85575f47c3aSTodd Fiala     if (file_action)
856d3173f34SChaoren Lin         stdin_file_spec = file_action->GetFileSpec();
857af245d11STodd Fiala 
858af245d11STodd Fiala     file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
85975f47c3aSTodd Fiala     if (file_action)
860d3173f34SChaoren Lin         stdout_file_spec = file_action->GetFileSpec();
861af245d11STodd Fiala 
862af245d11STodd Fiala     file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
86375f47c3aSTodd Fiala     if (file_action)
864d3173f34SChaoren Lin         stderr_file_spec = file_action->GetFileSpec();
86575f47c3aSTodd Fiala 
86675f47c3aSTodd Fiala     if (log)
86775f47c3aSTodd Fiala     {
868d3173f34SChaoren Lin         if (stdin_file_spec)
869d3173f34SChaoren Lin             log->Printf ("NativeProcessLinux::%s setting STDIN to '%s'",
870d3173f34SChaoren Lin                     __FUNCTION__, stdin_file_spec.GetCString());
87175f47c3aSTodd Fiala         else
87275f47c3aSTodd Fiala             log->Printf ("NativeProcessLinux::%s leaving STDIN as is", __FUNCTION__);
87375f47c3aSTodd Fiala 
874d3173f34SChaoren Lin         if (stdout_file_spec)
875d3173f34SChaoren Lin             log->Printf ("NativeProcessLinux::%s setting STDOUT to '%s'",
876d3173f34SChaoren Lin                     __FUNCTION__, stdout_file_spec.GetCString());
87775f47c3aSTodd Fiala         else
87875f47c3aSTodd Fiala             log->Printf ("NativeProcessLinux::%s leaving STDOUT as is", __FUNCTION__);
87975f47c3aSTodd Fiala 
880d3173f34SChaoren Lin         if (stderr_file_spec)
881d3173f34SChaoren Lin             log->Printf ("NativeProcessLinux::%s setting STDERR to '%s'",
882d3173f34SChaoren Lin                     __FUNCTION__, stderr_file_spec.GetCString());
88375f47c3aSTodd Fiala         else
88475f47c3aSTodd Fiala             log->Printf ("NativeProcessLinux::%s leaving STDERR as is", __FUNCTION__);
88575f47c3aSTodd Fiala     }
886af245d11STodd Fiala 
887af245d11STodd Fiala     // Create the NativeProcessLinux in launch mode.
888af245d11STodd Fiala     native_process_sp.reset (new NativeProcessLinux ());
889af245d11STodd Fiala 
890af245d11STodd Fiala     if (log)
891af245d11STodd Fiala     {
892af245d11STodd Fiala         int i = 0;
893af245d11STodd Fiala         for (const char **args = launch_info.GetArguments ().GetConstArgumentVector (); *args; ++args, ++i)
894af245d11STodd Fiala         {
895af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s arg %d: \"%s\"", __FUNCTION__, i, *args ? *args : "nullptr");
896af245d11STodd Fiala             ++i;
897af245d11STodd Fiala         }
898af245d11STodd Fiala     }
899af245d11STodd Fiala 
900af245d11STodd Fiala     if (!native_process_sp->RegisterNativeDelegate (native_delegate))
901af245d11STodd Fiala     {
902af245d11STodd Fiala         native_process_sp.reset ();
903af245d11STodd Fiala         error.SetErrorStringWithFormat ("failed to register the native delegate");
904af245d11STodd Fiala         return error;
905af245d11STodd Fiala     }
906af245d11STodd Fiala 
907cb84eebbSTamas Berghammer     std::static_pointer_cast<NativeProcessLinux> (native_process_sp)->LaunchInferior (
908d5b310f2SPavel Labath             exe_module_sp.get(),
909af245d11STodd Fiala             launch_info.GetArguments ().GetConstArgumentVector (),
910af245d11STodd Fiala             launch_info.GetEnvironmentEntries ().GetConstArgumentVector (),
911d3173f34SChaoren Lin             stdin_file_spec,
912d3173f34SChaoren Lin             stdout_file_spec,
913d3173f34SChaoren Lin             stderr_file_spec,
914af245d11STodd Fiala             working_dir,
9150bce1b67STodd Fiala             launch_info,
916af245d11STodd Fiala             error);
917af245d11STodd Fiala 
918af245d11STodd Fiala     if (error.Fail ())
919af245d11STodd Fiala     {
920af245d11STodd Fiala         native_process_sp.reset ();
921af245d11STodd Fiala         if (log)
922af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s failed to launch process: %s", __FUNCTION__, error.AsCString ());
923af245d11STodd Fiala         return error;
924af245d11STodd Fiala     }
925af245d11STodd Fiala 
926af245d11STodd Fiala     launch_info.SetProcessID (native_process_sp->GetID ());
927af245d11STodd Fiala 
928af245d11STodd Fiala     return error;
929af245d11STodd Fiala }
930af245d11STodd Fiala 
931db264a6dSTamas Berghammer Error
932d5b310f2SPavel Labath NativeProcessProtocol::Attach (
933af245d11STodd Fiala     lldb::pid_t pid,
934db264a6dSTamas Berghammer     NativeProcessProtocol::NativeDelegate &native_delegate,
935af245d11STodd Fiala     NativeProcessProtocolSP &native_process_sp)
936af245d11STodd Fiala {
937af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
938af245d11STodd Fiala     if (log && log->GetMask ().Test (POSIX_LOG_VERBOSE))
939af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
940af245d11STodd Fiala 
941af245d11STodd Fiala     // Grab the current platform architecture.  This should be Linux,
942af245d11STodd Fiala     // since this code is only intended to run on a Linux host.
943615eb7e6SGreg Clayton     PlatformSP platform_sp (Platform::GetHostPlatform ());
944af245d11STodd Fiala     if (!platform_sp)
945af245d11STodd Fiala         return Error("failed to get a valid default platform");
946af245d11STodd Fiala 
947af245d11STodd Fiala     // Retrieve the architecture for the running process.
948af245d11STodd Fiala     ArchSpec process_arch;
949af245d11STodd Fiala     Error error = ResolveProcessArchitecture (pid, *platform_sp.get (), process_arch);
950af245d11STodd Fiala     if (!error.Success ())
951af245d11STodd Fiala         return error;
952af245d11STodd Fiala 
9531339b5e8SOleksiy Vyalov     std::shared_ptr<NativeProcessLinux> native_process_linux_sp (new NativeProcessLinux ());
954af245d11STodd Fiala 
9551339b5e8SOleksiy Vyalov     if (!native_process_linux_sp->RegisterNativeDelegate (native_delegate))
956af245d11STodd Fiala     {
957af245d11STodd Fiala         error.SetErrorStringWithFormat ("failed to register the native delegate");
958af245d11STodd Fiala         return error;
959af245d11STodd Fiala     }
960af245d11STodd Fiala 
9611339b5e8SOleksiy Vyalov     native_process_linux_sp->AttachToInferior (pid, error);
962af245d11STodd Fiala     if (!error.Success ())
963af245d11STodd Fiala         return error;
964af245d11STodd Fiala 
9651339b5e8SOleksiy Vyalov     native_process_sp = native_process_linux_sp;
966af245d11STodd Fiala     return error;
967af245d11STodd Fiala }
968af245d11STodd Fiala 
969af245d11STodd Fiala // -----------------------------------------------------------------------------
970af245d11STodd Fiala // Public Instance Methods
971af245d11STodd Fiala // -----------------------------------------------------------------------------
972af245d11STodd Fiala 
973af245d11STodd Fiala NativeProcessLinux::NativeProcessLinux () :
974af245d11STodd Fiala     NativeProcessProtocol (LLDB_INVALID_PROCESS_ID),
975af245d11STodd Fiala     m_arch (),
976af245d11STodd Fiala     m_supports_mem_region (eLazyBoolCalculate),
977af245d11STodd Fiala     m_mem_region_cache (),
9788c8ff7afSPavel Labath     m_mem_region_cache_mutex ()
979af245d11STodd Fiala {
980af245d11STodd Fiala }
981af245d11STodd Fiala 
982af245d11STodd Fiala //------------------------------------------------------------------------------
983bd7cbc5aSPavel Labath // NativeProcessLinux spawns a new thread which performs all operations on the inferior process.
984bd7cbc5aSPavel Labath // Refer to Monitor and Operation classes to see why this is necessary.
985bd7cbc5aSPavel Labath //------------------------------------------------------------------------------
986af245d11STodd Fiala void
987af245d11STodd Fiala NativeProcessLinux::LaunchInferior (
988af245d11STodd Fiala     Module *module,
989af245d11STodd Fiala     const char *argv[],
990af245d11STodd Fiala     const char *envp[],
991d3173f34SChaoren Lin     const FileSpec &stdin_file_spec,
992d3173f34SChaoren Lin     const FileSpec &stdout_file_spec,
993d3173f34SChaoren Lin     const FileSpec &stderr_file_spec,
994d3173f34SChaoren Lin     const FileSpec &working_dir,
995db264a6dSTamas Berghammer     const ProcessLaunchInfo &launch_info,
996db264a6dSTamas Berghammer     Error &error)
997af245d11STodd Fiala {
998af245d11STodd Fiala     if (module)
999af245d11STodd Fiala         m_arch = module->GetArchitecture ();
1000af245d11STodd Fiala 
1001af245d11STodd Fiala     SetState (eStateLaunching);
1002af245d11STodd Fiala 
1003af245d11STodd Fiala     std::unique_ptr<LaunchArgs> args(
1004d3173f34SChaoren Lin         new LaunchArgs(module, argv, envp,
1005d3173f34SChaoren Lin                        stdin_file_spec,
1006d3173f34SChaoren Lin                        stdout_file_spec,
1007d3173f34SChaoren Lin                        stderr_file_spec,
1008d3173f34SChaoren Lin                        working_dir,
1009d3173f34SChaoren Lin                        launch_info));
1010af245d11STodd Fiala 
1011bd7cbc5aSPavel Labath     StartMonitorThread ([&] (Error &e) { return Launch(args.get(), e); }, error);
1012af245d11STodd Fiala     if (!error.Success ())
1013af245d11STodd Fiala         return;
1014af245d11STodd Fiala }
1015af245d11STodd Fiala 
1016af245d11STodd Fiala void
1017db264a6dSTamas Berghammer NativeProcessLinux::AttachToInferior (lldb::pid_t pid, Error &error)
1018af245d11STodd Fiala {
1019af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1020af245d11STodd Fiala     if (log)
1021af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
1022af245d11STodd Fiala 
1023af245d11STodd Fiala     // We can use the Host for everything except the ResolveExecutable portion.
1024615eb7e6SGreg Clayton     PlatformSP platform_sp = Platform::GetHostPlatform ();
1025af245d11STodd Fiala     if (!platform_sp)
1026af245d11STodd Fiala     {
1027af245d11STodd Fiala         if (log)
1028af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): no default platform set", __FUNCTION__, pid);
1029af245d11STodd Fiala         error.SetErrorString ("no default platform available");
103050d60be3SShawn Best         return;
1031af245d11STodd Fiala     }
1032af245d11STodd Fiala 
1033af245d11STodd Fiala     // Gather info about the process.
1034af245d11STodd Fiala     ProcessInstanceInfo process_info;
103550d60be3SShawn Best     if (!platform_sp->GetProcessInfo (pid, process_info))
103650d60be3SShawn Best     {
103750d60be3SShawn Best         if (log)
103850d60be3SShawn Best             log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): failed to get process info", __FUNCTION__, pid);
103950d60be3SShawn Best         error.SetErrorString ("failed to get process info");
104050d60be3SShawn Best         return;
104150d60be3SShawn Best     }
1042af245d11STodd Fiala 
1043af245d11STodd Fiala     // Resolve the executable module
1044af245d11STodd Fiala     ModuleSP exe_module_sp;
1045af245d11STodd Fiala     FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
1046e56f6dceSChaoren Lin     ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
10476edef204SOleksiy Vyalov     error = platform_sp->ResolveExecutable(exe_module_spec, exe_module_sp,
1048af245d11STodd Fiala                                            executable_search_paths.GetSize() ? &executable_search_paths : NULL);
1049af245d11STodd Fiala     if (!error.Success())
1050af245d11STodd Fiala         return;
1051af245d11STodd Fiala 
1052af245d11STodd Fiala     // Set the architecture to the exe architecture.
1053af245d11STodd Fiala     m_arch = exe_module_sp->GetArchitecture();
1054af245d11STodd Fiala     if (log)
1055af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
1056af245d11STodd Fiala 
1057af245d11STodd Fiala     m_pid = pid;
1058af245d11STodd Fiala     SetState(eStateAttaching);
1059af245d11STodd Fiala 
1060bd7cbc5aSPavel Labath     StartMonitorThread ([=] (Error &e) { return Attach(pid, e); }, error);
1061af245d11STodd Fiala     if (!error.Success ())
1062af245d11STodd Fiala         return;
1063af245d11STodd Fiala }
1064af245d11STodd Fiala 
10658bc34f4dSOleksiy Vyalov void
10668bc34f4dSOleksiy Vyalov NativeProcessLinux::Terminate ()
1067af245d11STodd Fiala {
106845f5cb31SPavel Labath     m_monitor_up->Terminate();
1069af245d11STodd Fiala }
1070af245d11STodd Fiala 
1071bd7cbc5aSPavel Labath ::pid_t
1072bd7cbc5aSPavel Labath NativeProcessLinux::Launch(LaunchArgs *args, Error &error)
1073af245d11STodd Fiala {
10740bce1b67STodd Fiala     assert (args && "null args");
1075af245d11STodd Fiala 
1076af245d11STodd Fiala     const char **argv = args->m_argv;
1077af245d11STodd Fiala     const char **envp = args->m_envp;
1078d3173f34SChaoren Lin     const FileSpec working_dir = args->m_working_dir;
1079af245d11STodd Fiala 
1080af245d11STodd Fiala     lldb_utility::PseudoTerminal terminal;
1081af245d11STodd Fiala     const size_t err_len = 1024;
1082af245d11STodd Fiala     char err_str[err_len];
1083af245d11STodd Fiala     lldb::pid_t pid;
1084af245d11STodd Fiala     NativeThreadProtocolSP thread_sp;
1085af245d11STodd Fiala 
1086af245d11STodd Fiala     lldb::ThreadSP inferior;
1087af245d11STodd Fiala 
1088af245d11STodd Fiala     // Propagate the environment if one is not supplied.
1089af245d11STodd Fiala     if (envp == NULL || envp[0] == NULL)
1090af245d11STodd Fiala         envp = const_cast<const char **>(environ);
1091af245d11STodd Fiala 
1092af245d11STodd Fiala     if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
1093af245d11STodd Fiala     {
1094bd7cbc5aSPavel Labath         error.SetErrorToGenericError();
1095bd7cbc5aSPavel Labath         error.SetErrorStringWithFormat("Process fork failed: %s", err_str);
1096bd7cbc5aSPavel Labath         return -1;
1097af245d11STodd Fiala     }
1098af245d11STodd Fiala 
1099af245d11STodd Fiala     // Recognized child exit status codes.
1100af245d11STodd Fiala     enum {
1101af245d11STodd Fiala         ePtraceFailed = 1,
1102af245d11STodd Fiala         eDupStdinFailed,
1103af245d11STodd Fiala         eDupStdoutFailed,
1104af245d11STodd Fiala         eDupStderrFailed,
1105af245d11STodd Fiala         eChdirFailed,
1106af245d11STodd Fiala         eExecFailed,
1107af245d11STodd Fiala         eSetGidFailed
1108af245d11STodd Fiala     };
1109af245d11STodd Fiala 
1110af245d11STodd Fiala     // Child process.
1111af245d11STodd Fiala     if (pid == 0)
1112af245d11STodd Fiala     {
111375f47c3aSTodd Fiala         // FIXME consider opening a pipe between parent/child and have this forked child
111475f47c3aSTodd Fiala         // send log info to parent re: launch status, in place of the log lines removed here.
1115af245d11STodd Fiala 
111675f47c3aSTodd Fiala         // Start tracing this child that is about to exec.
11174a9babb2SPavel Labath         error = PtraceWrapper(PTRACE_TRACEME, 0);
1118bd7cbc5aSPavel Labath         if (error.Fail())
1119af245d11STodd Fiala             exit(ePtraceFailed);
1120af245d11STodd Fiala 
1121493c3a12SPavel Labath         // terminal has already dupped the tty descriptors to stdin/out/err.
1122493c3a12SPavel Labath         // This closes original fd from which they were copied (and avoids
1123493c3a12SPavel Labath         // leaking descriptors to the debugged process.
1124493c3a12SPavel Labath         terminal.CloseSlaveFileDescriptor();
1125493c3a12SPavel Labath 
1126af245d11STodd Fiala         // Do not inherit setgid powers.
1127af245d11STodd Fiala         if (setgid(getgid()) != 0)
1128af245d11STodd Fiala             exit(eSetGidFailed);
1129af245d11STodd Fiala 
1130af245d11STodd Fiala         // Attempt to have our own process group.
1131af245d11STodd Fiala         if (setpgid(0, 0) != 0)
1132af245d11STodd Fiala         {
113375f47c3aSTodd Fiala             // FIXME log that this failed. This is common.
1134af245d11STodd Fiala             // Don't allow this to prevent an inferior exec.
1135af245d11STodd Fiala         }
1136af245d11STodd Fiala 
1137af245d11STodd Fiala         // Dup file descriptors if needed.
1138d3173f34SChaoren Lin         if (args->m_stdin_file_spec)
1139d3173f34SChaoren Lin             if (!DupDescriptor(args->m_stdin_file_spec, STDIN_FILENO, O_RDONLY))
1140af245d11STodd Fiala                 exit(eDupStdinFailed);
1141af245d11STodd Fiala 
1142d3173f34SChaoren Lin         if (args->m_stdout_file_spec)
1143d3173f34SChaoren Lin             if (!DupDescriptor(args->m_stdout_file_spec, STDOUT_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
1144af245d11STodd Fiala                 exit(eDupStdoutFailed);
1145af245d11STodd Fiala 
1146d3173f34SChaoren Lin         if (args->m_stderr_file_spec)
1147d3173f34SChaoren Lin             if (!DupDescriptor(args->m_stderr_file_spec, STDERR_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
1148af245d11STodd Fiala                 exit(eDupStderrFailed);
1149af245d11STodd Fiala 
11509cf4f2c2SChaoren Lin         // Close everything besides stdin, stdout, and stderr that has no file
11519cf4f2c2SChaoren Lin         // action to avoid leaking
11529cf4f2c2SChaoren Lin         for (int fd = 3; fd < sysconf(_SC_OPEN_MAX); ++fd)
11539cf4f2c2SChaoren Lin             if (!args->m_launch_info.GetFileActionForFD(fd))
11549cf4f2c2SChaoren Lin                 close(fd);
11559cf4f2c2SChaoren Lin 
1156af245d11STodd Fiala         // Change working directory
1157d3173f34SChaoren Lin         if (working_dir && 0 != ::chdir(working_dir.GetCString()))
1158af245d11STodd Fiala               exit(eChdirFailed);
1159af245d11STodd Fiala 
11600bce1b67STodd Fiala         // Disable ASLR if requested.
11610bce1b67STodd Fiala         if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR))
11620bce1b67STodd Fiala         {
11630bce1b67STodd Fiala             const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
11640bce1b67STodd Fiala             if (old_personality == -1)
11650bce1b67STodd Fiala             {
116675f47c3aSTodd Fiala                 // Can't retrieve Linux personality.  Cannot disable ASLR.
11670bce1b67STodd Fiala             }
11680bce1b67STodd Fiala             else
11690bce1b67STodd Fiala             {
11700bce1b67STodd Fiala                 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality);
11710bce1b67STodd Fiala                 if (new_personality == -1)
11720bce1b67STodd Fiala                 {
117375f47c3aSTodd Fiala                     // Disabling ASLR failed.
11740bce1b67STodd Fiala                 }
11750bce1b67STodd Fiala                 else
11760bce1b67STodd Fiala                 {
117775f47c3aSTodd Fiala                     // Disabling ASLR succeeded.
11780bce1b67STodd Fiala                 }
11790bce1b67STodd Fiala             }
11800bce1b67STodd Fiala         }
11810bce1b67STodd Fiala 
118275f47c3aSTodd Fiala         // Execute.  We should never return...
1183af245d11STodd Fiala         execve(argv[0],
1184af245d11STodd Fiala                const_cast<char *const *>(argv),
1185af245d11STodd Fiala                const_cast<char *const *>(envp));
118675f47c3aSTodd Fiala 
118775f47c3aSTodd Fiala         // ...unless exec fails.  In which case we definitely need to end the child here.
1188af245d11STodd Fiala         exit(eExecFailed);
1189af245d11STodd Fiala     }
1190af245d11STodd Fiala 
119175f47c3aSTodd Fiala     //
119275f47c3aSTodd Fiala     // This is the parent code here.
119375f47c3aSTodd Fiala     //
119475f47c3aSTodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
119575f47c3aSTodd Fiala 
1196af245d11STodd Fiala     // Wait for the child process to trap on its call to execve.
1197af245d11STodd Fiala     ::pid_t wpid;
1198af245d11STodd Fiala     int status;
1199af245d11STodd Fiala     if ((wpid = waitpid(pid, &status, 0)) < 0)
1200af245d11STodd Fiala     {
1201bd7cbc5aSPavel Labath         error.SetErrorToErrno();
1202af245d11STodd Fiala         if (log)
1203bd7cbc5aSPavel Labath             log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s",
1204bd7cbc5aSPavel Labath                     __FUNCTION__, error.AsCString ());
1205af245d11STodd Fiala 
1206af245d11STodd Fiala         // Mark the inferior as invalid.
1207af245d11STodd Fiala         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
1208bd7cbc5aSPavel Labath         SetState (StateType::eStateInvalid);
1209af245d11STodd Fiala 
1210bd7cbc5aSPavel Labath         return -1;
1211af245d11STodd Fiala     }
1212af245d11STodd Fiala     else if (WIFEXITED(status))
1213af245d11STodd Fiala     {
1214af245d11STodd Fiala         // open, dup or execve likely failed for some reason.
1215bd7cbc5aSPavel Labath         error.SetErrorToGenericError();
1216af245d11STodd Fiala         switch (WEXITSTATUS(status))
1217af245d11STodd Fiala         {
1218af245d11STodd Fiala             case ePtraceFailed:
1219bd7cbc5aSPavel Labath                 error.SetErrorString("Child ptrace failed.");
1220af245d11STodd Fiala                 break;
1221af245d11STodd Fiala             case eDupStdinFailed:
1222bd7cbc5aSPavel Labath                 error.SetErrorString("Child open stdin failed.");
1223af245d11STodd Fiala                 break;
1224af245d11STodd Fiala             case eDupStdoutFailed:
1225bd7cbc5aSPavel Labath                 error.SetErrorString("Child open stdout failed.");
1226af245d11STodd Fiala                 break;
1227af245d11STodd Fiala             case eDupStderrFailed:
1228bd7cbc5aSPavel Labath                 error.SetErrorString("Child open stderr failed.");
1229af245d11STodd Fiala                 break;
1230af245d11STodd Fiala             case eChdirFailed:
1231bd7cbc5aSPavel Labath                 error.SetErrorString("Child failed to set working directory.");
1232af245d11STodd Fiala                 break;
1233af245d11STodd Fiala             case eExecFailed:
1234bd7cbc5aSPavel Labath                 error.SetErrorString("Child exec failed.");
1235af245d11STodd Fiala                 break;
1236af245d11STodd Fiala             case eSetGidFailed:
1237bd7cbc5aSPavel Labath                 error.SetErrorString("Child setgid failed.");
1238af245d11STodd Fiala                 break;
1239af245d11STodd Fiala             default:
1240bd7cbc5aSPavel Labath                 error.SetErrorString("Child returned unknown exit status.");
1241af245d11STodd Fiala                 break;
1242af245d11STodd Fiala         }
1243af245d11STodd Fiala 
1244af245d11STodd Fiala         if (log)
1245af245d11STodd Fiala         {
1246af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
1247af245d11STodd Fiala                     __FUNCTION__,
1248af245d11STodd Fiala                     WEXITSTATUS(status));
1249af245d11STodd Fiala         }
1250af245d11STodd Fiala 
1251af245d11STodd Fiala         // Mark the inferior as invalid.
1252af245d11STodd Fiala         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
1253bd7cbc5aSPavel Labath         SetState (StateType::eStateInvalid);
1254af245d11STodd Fiala 
1255bd7cbc5aSPavel Labath         return -1;
1256af245d11STodd Fiala     }
1257af245d11STodd Fiala     assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
1258af245d11STodd Fiala            "Could not sync with inferior process.");
1259af245d11STodd Fiala 
1260af245d11STodd Fiala     if (log)
1261af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
1262af245d11STodd Fiala 
1263bd7cbc5aSPavel Labath     error = SetDefaultPtraceOpts(pid);
1264bd7cbc5aSPavel Labath     if (error.Fail())
1265af245d11STodd Fiala     {
1266af245d11STodd Fiala         if (log)
1267af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
1268bd7cbc5aSPavel Labath                     __FUNCTION__, error.AsCString ());
1269af245d11STodd Fiala 
1270af245d11STodd Fiala         // Mark the inferior as invalid.
1271af245d11STodd Fiala         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
1272bd7cbc5aSPavel Labath         SetState (StateType::eStateInvalid);
1273af245d11STodd Fiala 
1274bd7cbc5aSPavel Labath         return -1;
1275af245d11STodd Fiala     }
1276af245d11STodd Fiala 
1277af245d11STodd Fiala     // Release the master terminal descriptor and pass it off to the
1278af245d11STodd Fiala     // NativeProcessLinux instance.  Similarly stash the inferior pid.
1279bd7cbc5aSPavel Labath     m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1280bd7cbc5aSPavel Labath     m_pid = pid;
1281af245d11STodd Fiala 
1282af245d11STodd Fiala     // Set the terminal fd to be in non blocking mode (it simplifies the
1283af245d11STodd Fiala     // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1284af245d11STodd Fiala     // descriptor to read from).
1285bd7cbc5aSPavel Labath     error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
1286bd7cbc5aSPavel Labath     if (error.Fail())
1287af245d11STodd Fiala     {
1288af245d11STodd Fiala         if (log)
1289af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
1290bd7cbc5aSPavel Labath                     __FUNCTION__, error.AsCString ());
1291af245d11STodd Fiala 
1292af245d11STodd Fiala         // Mark the inferior as invalid.
1293af245d11STodd Fiala         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
1294bd7cbc5aSPavel Labath         SetState (StateType::eStateInvalid);
1295af245d11STodd Fiala 
1296bd7cbc5aSPavel Labath         return -1;
1297af245d11STodd Fiala     }
1298af245d11STodd Fiala 
1299af245d11STodd Fiala     if (log)
1300af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
1301af245d11STodd Fiala 
1302bd7cbc5aSPavel Labath     thread_sp = AddThread (pid);
1303af245d11STodd Fiala     assert (thread_sp && "AddThread() returned a nullptr thread");
1304cb84eebbSTamas Berghammer     std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
13051dbc6c9cSPavel Labath     ThreadWasCreated(pid);
1306af245d11STodd Fiala 
1307af245d11STodd Fiala     // Let our process instance know the thread has stopped.
1308bd7cbc5aSPavel Labath     SetCurrentThreadID (thread_sp->GetID ());
1309bd7cbc5aSPavel Labath     SetState (StateType::eStateStopped);
1310af245d11STodd Fiala 
1311af245d11STodd Fiala     if (log)
1312af245d11STodd Fiala     {
1313bd7cbc5aSPavel Labath         if (error.Success ())
1314af245d11STodd Fiala         {
1315af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
1316af245d11STodd Fiala         }
1317af245d11STodd Fiala         else
1318af245d11STodd Fiala         {
1319af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s inferior launching failed: %s",
1320bd7cbc5aSPavel Labath                 __FUNCTION__, error.AsCString ());
1321bd7cbc5aSPavel Labath             return -1;
1322af245d11STodd Fiala         }
1323af245d11STodd Fiala     }
1324bd7cbc5aSPavel Labath     return pid;
1325af245d11STodd Fiala }
1326af245d11STodd Fiala 
1327bd7cbc5aSPavel Labath ::pid_t
1328bd7cbc5aSPavel Labath NativeProcessLinux::Attach(lldb::pid_t pid, Error &error)
1329af245d11STodd Fiala {
1330af245d11STodd Fiala     lldb::ThreadSP inferior;
1331af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1332af245d11STodd Fiala 
1333af245d11STodd Fiala     // Use a map to keep track of the threads which we have attached/need to attach.
1334af245d11STodd Fiala     Host::TidMap tids_to_attach;
1335af245d11STodd Fiala     if (pid <= 1)
1336af245d11STodd Fiala     {
1337bd7cbc5aSPavel Labath         error.SetErrorToGenericError();
1338bd7cbc5aSPavel Labath         error.SetErrorString("Attaching to process 1 is not allowed.");
1339bd7cbc5aSPavel Labath         return -1;
1340af245d11STodd Fiala     }
1341af245d11STodd Fiala 
1342af245d11STodd Fiala     while (Host::FindProcessThreads(pid, tids_to_attach))
1343af245d11STodd Fiala     {
1344af245d11STodd Fiala         for (Host::TidMap::iterator it = tids_to_attach.begin();
1345af245d11STodd Fiala              it != tids_to_attach.end();)
1346af245d11STodd Fiala         {
1347af245d11STodd Fiala             if (it->second == false)
1348af245d11STodd Fiala             {
1349af245d11STodd Fiala                 lldb::tid_t tid = it->first;
1350af245d11STodd Fiala 
1351af245d11STodd Fiala                 // Attach to the requested process.
1352af245d11STodd Fiala                 // An attach will cause the thread to stop with a SIGSTOP.
13534a9babb2SPavel Labath                 error = PtraceWrapper(PTRACE_ATTACH, tid);
1354bd7cbc5aSPavel Labath                 if (error.Fail())
1355af245d11STodd Fiala                 {
1356af245d11STodd Fiala                     // No such thread. The thread may have exited.
1357af245d11STodd Fiala                     // More error handling may be needed.
1358bd7cbc5aSPavel Labath                     if (error.GetError() == ESRCH)
1359af245d11STodd Fiala                     {
1360af245d11STodd Fiala                         it = tids_to_attach.erase(it);
1361af245d11STodd Fiala                         continue;
1362af245d11STodd Fiala                     }
1363af245d11STodd Fiala                     else
1364bd7cbc5aSPavel Labath                         return -1;
1365af245d11STodd Fiala                 }
1366af245d11STodd Fiala 
1367af245d11STodd Fiala                 int status;
1368af245d11STodd Fiala                 // Need to use __WALL otherwise we receive an error with errno=ECHLD
1369af245d11STodd Fiala                 // At this point we should have a thread stopped if waitpid succeeds.
1370af245d11STodd Fiala                 if ((status = waitpid(tid, NULL, __WALL)) < 0)
1371af245d11STodd Fiala                 {
1372af245d11STodd Fiala                     // No such thread. The thread may have exited.
1373af245d11STodd Fiala                     // More error handling may be needed.
1374af245d11STodd Fiala                     if (errno == ESRCH)
1375af245d11STodd Fiala                     {
1376af245d11STodd Fiala                         it = tids_to_attach.erase(it);
1377af245d11STodd Fiala                         continue;
1378af245d11STodd Fiala                     }
1379af245d11STodd Fiala                     else
1380af245d11STodd Fiala                     {
1381bd7cbc5aSPavel Labath                         error.SetErrorToErrno();
1382bd7cbc5aSPavel Labath                         return -1;
1383af245d11STodd Fiala                     }
1384af245d11STodd Fiala                 }
1385af245d11STodd Fiala 
1386bd7cbc5aSPavel Labath                 error = SetDefaultPtraceOpts(tid);
1387bd7cbc5aSPavel Labath                 if (error.Fail())
1388bd7cbc5aSPavel Labath                     return -1;
1389af245d11STodd Fiala 
1390af245d11STodd Fiala                 if (log)
1391af245d11STodd Fiala                     log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
1392af245d11STodd Fiala 
1393af245d11STodd Fiala                 it->second = true;
1394af245d11STodd Fiala 
1395af245d11STodd Fiala                 // Create the thread, mark it as stopped.
1396bd7cbc5aSPavel Labath                 NativeThreadProtocolSP thread_sp (AddThread (static_cast<lldb::tid_t> (tid)));
1397af245d11STodd Fiala                 assert (thread_sp && "AddThread() returned a nullptr");
1398fa03ad2eSChaoren Lin 
1399fa03ad2eSChaoren Lin                 // This will notify this is a new thread and tell the system it is stopped.
1400cb84eebbSTamas Berghammer                 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
14011dbc6c9cSPavel Labath                 ThreadWasCreated(tid);
1402bd7cbc5aSPavel Labath                 SetCurrentThreadID (thread_sp->GetID ());
1403af245d11STodd Fiala             }
1404af245d11STodd Fiala 
1405af245d11STodd Fiala             // move the loop forward
1406af245d11STodd Fiala             ++it;
1407af245d11STodd Fiala         }
1408af245d11STodd Fiala     }
1409af245d11STodd Fiala 
1410af245d11STodd Fiala     if (tids_to_attach.size() > 0)
1411af245d11STodd Fiala     {
1412bd7cbc5aSPavel Labath         m_pid = pid;
1413af245d11STodd Fiala         // Let our process instance know the thread has stopped.
1414bd7cbc5aSPavel Labath         SetState (StateType::eStateStopped);
1415af245d11STodd Fiala     }
1416af245d11STodd Fiala     else
1417af245d11STodd Fiala     {
1418bd7cbc5aSPavel Labath         error.SetErrorToGenericError();
1419bd7cbc5aSPavel Labath         error.SetErrorString("No such process.");
1420bd7cbc5aSPavel Labath         return -1;
1421af245d11STodd Fiala     }
1422af245d11STodd Fiala 
1423bd7cbc5aSPavel Labath     return pid;
1424af245d11STodd Fiala }
1425af245d11STodd Fiala 
142697ccc294SChaoren Lin Error
1427af245d11STodd Fiala NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
1428af245d11STodd Fiala {
1429af245d11STodd Fiala     long ptrace_opts = 0;
1430af245d11STodd Fiala 
1431af245d11STodd Fiala     // Have the child raise an event on exit.  This is used to keep the child in
1432af245d11STodd Fiala     // limbo until it is destroyed.
1433af245d11STodd Fiala     ptrace_opts |= PTRACE_O_TRACEEXIT;
1434af245d11STodd Fiala 
1435af245d11STodd Fiala     // Have the tracer trace threads which spawn in the inferior process.
1436af245d11STodd Fiala     // TODO: if we want to support tracing the inferiors' child, add the
1437af245d11STodd Fiala     // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
1438af245d11STodd Fiala     ptrace_opts |= PTRACE_O_TRACECLONE;
1439af245d11STodd Fiala 
1440af245d11STodd Fiala     // Have the tracer notify us before execve returns
1441af245d11STodd Fiala     // (needed to disable legacy SIGTRAP generation)
1442af245d11STodd Fiala     ptrace_opts |= PTRACE_O_TRACEEXEC;
1443af245d11STodd Fiala 
14444a9babb2SPavel Labath     return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts);
1445af245d11STodd Fiala }
1446af245d11STodd Fiala 
1447af245d11STodd Fiala static ExitType convert_pid_status_to_exit_type (int status)
1448af245d11STodd Fiala {
1449af245d11STodd Fiala     if (WIFEXITED (status))
1450af245d11STodd Fiala         return ExitType::eExitTypeExit;
1451af245d11STodd Fiala     else if (WIFSIGNALED (status))
1452af245d11STodd Fiala         return ExitType::eExitTypeSignal;
1453af245d11STodd Fiala     else if (WIFSTOPPED (status))
1454af245d11STodd Fiala         return ExitType::eExitTypeStop;
1455af245d11STodd Fiala     else
1456af245d11STodd Fiala     {
1457af245d11STodd Fiala         // We don't know what this is.
1458af245d11STodd Fiala         return ExitType::eExitTypeInvalid;
1459af245d11STodd Fiala     }
1460af245d11STodd Fiala }
1461af245d11STodd Fiala 
1462af245d11STodd Fiala static int convert_pid_status_to_return_code (int status)
1463af245d11STodd Fiala {
1464af245d11STodd Fiala     if (WIFEXITED (status))
1465af245d11STodd Fiala         return WEXITSTATUS (status);
1466af245d11STodd Fiala     else if (WIFSIGNALED (status))
1467af245d11STodd Fiala         return WTERMSIG (status);
1468af245d11STodd Fiala     else if (WIFSTOPPED (status))
1469af245d11STodd Fiala         return WSTOPSIG (status);
1470af245d11STodd Fiala     else
1471af245d11STodd Fiala     {
1472af245d11STodd Fiala         // We don't know what this is.
1473af245d11STodd Fiala         return ExitType::eExitTypeInvalid;
1474af245d11STodd Fiala     }
1475af245d11STodd Fiala }
1476af245d11STodd Fiala 
14771107b5a5SPavel Labath // Handles all waitpid events from the inferior process.
14781107b5a5SPavel Labath void
14791107b5a5SPavel Labath NativeProcessLinux::MonitorCallback(lldb::pid_t pid,
1480af245d11STodd Fiala                                     bool exited,
1481af245d11STodd Fiala                                     int signal,
1482af245d11STodd Fiala                                     int status)
1483af245d11STodd Fiala {
1484af245d11STodd Fiala     Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1485af245d11STodd Fiala 
1486af245d11STodd Fiala     // Certain activities differ based on whether the pid is the tid of the main thread.
14871107b5a5SPavel Labath     const bool is_main_thread = (pid == GetID ());
1488af245d11STodd Fiala 
1489af245d11STodd Fiala     // Handle when the thread exits.
1490af245d11STodd Fiala     if (exited)
1491af245d11STodd Fiala     {
1492af245d11STodd Fiala         if (log)
149386fd8e45SChaoren Lin             log->Printf ("NativeProcessLinux::%s() got exit signal(%d) , tid = %"  PRIu64 " (%s main thread)", __FUNCTION__, signal, pid, is_main_thread ? "is" : "is not");
1494af245d11STodd Fiala 
1495af245d11STodd Fiala         // This is a thread that exited.  Ensure we're not tracking it anymore.
14961107b5a5SPavel Labath         const bool thread_found = StopTrackingThread (pid);
1497af245d11STodd Fiala 
1498af245d11STodd Fiala         if (is_main_thread)
1499af245d11STodd Fiala         {
1500af245d11STodd Fiala             // We only set the exit status and notify the delegate if we haven't already set the process
1501af245d11STodd Fiala             // state to an exited state.  We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
1502af245d11STodd Fiala             // for the main thread.
15031107b5a5SPavel Labath             const bool already_notified = (GetState() == StateType::eStateExited) || (GetState () == StateType::eStateCrashed);
1504af245d11STodd Fiala             if (!already_notified)
1505af245d11STodd Fiala             {
1506af245d11STodd Fiala                 if (log)
15071107b5a5SPavel 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 ()));
1508af245d11STodd Fiala                 // The main thread exited.  We're done monitoring.  Report to delegate.
15091107b5a5SPavel Labath                 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
1510af245d11STodd Fiala 
1511af245d11STodd Fiala                 // Notify delegate that our process has exited.
15121107b5a5SPavel Labath                 SetState (StateType::eStateExited, true);
1513af245d11STodd Fiala             }
1514af245d11STodd Fiala             else
1515af245d11STodd Fiala             {
1516af245d11STodd Fiala                 if (log)
1517af245d11STodd Fiala                     log->Printf ("NativeProcessLinux::%s() tid = %"  PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
1518af245d11STodd Fiala             }
1519af245d11STodd Fiala         }
1520af245d11STodd Fiala         else
1521af245d11STodd Fiala         {
1522af245d11STodd Fiala             // Do we want to report to the delegate in this case?  I think not.  If this was an orderly
1523af245d11STodd Fiala             // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
1524af245d11STodd Fiala             // and we would have done an all-stop then.
1525af245d11STodd Fiala             if (log)
1526af245d11STodd 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");
1527af245d11STodd Fiala         }
15281107b5a5SPavel Labath         return;
1529af245d11STodd Fiala     }
1530af245d11STodd Fiala 
1531af245d11STodd Fiala     // Get details on the signal raised.
1532af245d11STodd Fiala     siginfo_t info;
15331107b5a5SPavel Labath     const auto err = GetSignalInfo(pid, &info);
153497ccc294SChaoren Lin     if (err.Success())
1535fa03ad2eSChaoren Lin     {
1536fa03ad2eSChaoren Lin         // We have retrieved the signal info.  Dispatch appropriately.
1537fa03ad2eSChaoren Lin         if (info.si_signo == SIGTRAP)
15381107b5a5SPavel Labath             MonitorSIGTRAP(&info, pid);
1539fa03ad2eSChaoren Lin         else
15401107b5a5SPavel Labath             MonitorSignal(&info, pid, exited);
1541fa03ad2eSChaoren Lin     }
1542fa03ad2eSChaoren Lin     else
1543af245d11STodd Fiala     {
154497ccc294SChaoren Lin         if (err.GetError() == EINVAL)
1545af245d11STodd Fiala         {
1546fa03ad2eSChaoren Lin             // This is a group stop reception for this tid.
154739036ac3SPavel Labath             // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the
154839036ac3SPavel Labath             // tracee, triggering the group-stop mechanism. Normally receiving these would stop
154939036ac3SPavel Labath             // the process, pending a SIGCONT. Simulating this state in a debugger is hard and is
155039036ac3SPavel Labath             // generally not needed (one use case is debugging background task being managed by a
155139036ac3SPavel Labath             // shell). For general use, it is sufficient to stop the process in a signal-delivery
155239036ac3SPavel Labath             // stop which happens before the group stop. This done by MonitorSignal and works
155339036ac3SPavel Labath             // correctly for all signals.
1554fa03ad2eSChaoren Lin             if (log)
155539036ac3SPavel 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);
155639036ac3SPavel Labath             Resume(pid, signal);
1557a9882ceeSTodd Fiala         }
1558a9882ceeSTodd Fiala         else
1559a9882ceeSTodd Fiala         {
1560af245d11STodd Fiala             // ptrace(GETSIGINFO) failed (but not due to group-stop).
1561af245d11STodd Fiala 
1562af245d11STodd Fiala             // A return value of ESRCH means the thread/process is no longer on the system,
1563af245d11STodd Fiala             // so it was killed somehow outside of our control.  Either way, we can't do anything
1564af245d11STodd Fiala             // with it anymore.
1565af245d11STodd Fiala 
1566af245d11STodd Fiala             // Stop tracking the metadata for the thread since it's entirely off the system now.
15671107b5a5SPavel Labath             const bool thread_found = StopTrackingThread (pid);
1568af245d11STodd Fiala 
1569af245d11STodd Fiala             if (log)
1570af245d11STodd Fiala                 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
157197ccc294SChaoren 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");
1572af245d11STodd Fiala 
1573af245d11STodd Fiala             if (is_main_thread)
1574af245d11STodd Fiala             {
1575af245d11STodd Fiala                 // Notify the delegate - our process is not available but appears to have been killed outside
1576af245d11STodd Fiala                 // our control.  Is eStateExited the right exit state in this case?
15771107b5a5SPavel Labath                 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
15781107b5a5SPavel Labath                 SetState (StateType::eStateExited, true);
1579af245d11STodd Fiala             }
1580af245d11STodd Fiala             else
1581af245d11STodd Fiala             {
1582af245d11STodd Fiala                 // This thread was pulled out from underneath us.  Anything to do here? Do we want to do an all stop?
1583af245d11STodd Fiala                 if (log)
15841107b5a5SPavel 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);
1585af245d11STodd Fiala             }
1586af245d11STodd Fiala         }
1587af245d11STodd Fiala     }
1588af245d11STodd Fiala }
1589af245d11STodd Fiala 
1590af245d11STodd Fiala void
1591426bdf88SPavel Labath NativeProcessLinux::WaitForNewThread(::pid_t tid)
1592426bdf88SPavel Labath {
1593426bdf88SPavel Labath     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1594426bdf88SPavel Labath 
1595426bdf88SPavel Labath     NativeThreadProtocolSP new_thread_sp = GetThreadByID(tid);
1596426bdf88SPavel Labath 
1597426bdf88SPavel Labath     if (new_thread_sp)
1598426bdf88SPavel Labath     {
1599426bdf88SPavel Labath         // We are already tracking the thread - we got the event on the new thread (see
1600426bdf88SPavel Labath         // MonitorSignal) before this one. We are done.
1601426bdf88SPavel Labath         return;
1602426bdf88SPavel Labath     }
1603426bdf88SPavel Labath 
1604426bdf88SPavel Labath     // The thread is not tracked yet, let's wait for it to appear.
1605426bdf88SPavel Labath     int status = -1;
1606426bdf88SPavel Labath     ::pid_t wait_pid;
1607426bdf88SPavel Labath     do
1608426bdf88SPavel Labath     {
1609426bdf88SPavel Labath         if (log)
1610426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() received thread creation event for tid %" PRIu32 ". tid not tracked yet, waiting for thread to appear...", __FUNCTION__, tid);
1611426bdf88SPavel Labath         wait_pid = waitpid(tid, &status, __WALL);
1612426bdf88SPavel Labath     }
1613426bdf88SPavel Labath     while (wait_pid == -1 && errno == EINTR);
1614426bdf88SPavel Labath     // Since we are waiting on a specific tid, this must be the creation event. But let's do
1615426bdf88SPavel Labath     // some checks just in case.
1616426bdf88SPavel Labath     if (wait_pid != tid) {
1617426bdf88SPavel Labath         if (log)
1618426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime", __FUNCTION__, tid);
1619426bdf88SPavel Labath         // The only way I know of this could happen is if the whole process was
1620426bdf88SPavel Labath         // SIGKILLed in the mean time. In any case, we can't do anything about that now.
1621426bdf88SPavel Labath         return;
1622426bdf88SPavel Labath     }
1623426bdf88SPavel Labath     if (WIFEXITED(status))
1624426bdf88SPavel Labath     {
1625426bdf88SPavel Labath         if (log)
1626426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " returned an 'exited' event. Not tracking the thread.", __FUNCTION__, tid);
1627426bdf88SPavel Labath         // Also a very improbable event.
1628426bdf88SPavel Labath         return;
1629426bdf88SPavel Labath     }
1630426bdf88SPavel Labath 
1631426bdf88SPavel Labath     siginfo_t info;
1632426bdf88SPavel Labath     Error error = GetSignalInfo(tid, &info);
1633426bdf88SPavel Labath     if (error.Fail())
1634426bdf88SPavel Labath     {
1635426bdf88SPavel Labath         if (log)
1636426bdf88SPavel Labath             log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime.", __FUNCTION__, tid);
1637426bdf88SPavel Labath         return;
1638426bdf88SPavel Labath     }
1639426bdf88SPavel Labath 
1640426bdf88SPavel Labath     if (((info.si_pid != 0) || (info.si_code != SI_USER)) && log)
1641426bdf88SPavel Labath     {
1642426bdf88SPavel Labath         // We should be getting a thread creation signal here, but we received something
1643426bdf88SPavel Labath         // else. There isn't much we can do about it now, so we will just log that. Since the
1644426bdf88SPavel Labath         // thread is alive and we are receiving events from it, we shall pretend that it was
1645426bdf88SPavel Labath         // created properly.
1646426bdf88SPavel 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);
1647426bdf88SPavel Labath     }
1648426bdf88SPavel Labath 
1649426bdf88SPavel Labath     if (log)
1650426bdf88SPavel Labath         log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 ": tracking new thread tid %" PRIu32,
1651426bdf88SPavel Labath                  __FUNCTION__, GetID (), tid);
1652426bdf88SPavel Labath 
1653426bdf88SPavel Labath     new_thread_sp = AddThread(tid);
1654426bdf88SPavel Labath     std::static_pointer_cast<NativeThreadLinux> (new_thread_sp)->SetRunning ();
1655426bdf88SPavel Labath     Resume (tid, LLDB_INVALID_SIGNAL_NUMBER);
16561dbc6c9cSPavel Labath     ThreadWasCreated(tid);
1657426bdf88SPavel Labath }
1658426bdf88SPavel Labath 
1659426bdf88SPavel Labath void
1660af245d11STodd Fiala NativeProcessLinux::MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid)
1661af245d11STodd Fiala {
1662af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1663af245d11STodd Fiala     const bool is_main_thread = (pid == GetID ());
1664af245d11STodd Fiala 
1665af245d11STodd Fiala     assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
1666af245d11STodd Fiala     if (!info)
1667af245d11STodd Fiala         return;
1668af245d11STodd Fiala 
16695830aa75STamas Berghammer     Mutex::Locker locker (m_threads_mutex);
16705830aa75STamas Berghammer 
1671af245d11STodd Fiala     // See if we can find a thread for this signal.
1672af245d11STodd Fiala     NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
1673af245d11STodd Fiala     if (!thread_sp)
1674af245d11STodd Fiala     {
1675af245d11STodd Fiala         if (log)
1676af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
1677af245d11STodd Fiala     }
1678af245d11STodd Fiala 
1679af245d11STodd Fiala     switch (info->si_code)
1680af245d11STodd Fiala     {
1681af245d11STodd 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.
1682af245d11STodd Fiala     // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
1683af245d11STodd Fiala     // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
1684af245d11STodd Fiala 
1685af245d11STodd Fiala     case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
1686af245d11STodd Fiala     {
16875fd24c67SPavel Labath         // This is the notification on the parent thread which informs us of new thread
1688426bdf88SPavel Labath         // creation.
1689426bdf88SPavel Labath         // We don't want to do anything with the parent thread so we just resume it. In case we
1690426bdf88SPavel Labath         // want to implement "break on thread creation" functionality, we would need to stop
1691426bdf88SPavel Labath         // here.
1692af245d11STodd Fiala 
1693af245d11STodd Fiala         unsigned long event_message = 0;
1694426bdf88SPavel Labath         if (GetEventMessage (pid, &event_message).Fail())
1695fa03ad2eSChaoren Lin         {
1696426bdf88SPavel Labath             if (log)
1697fa03ad2eSChaoren Lin                 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " received thread creation event but GetEventMessage failed so we don't know the new tid", __FUNCTION__, pid);
1698426bdf88SPavel Labath         } else
1699426bdf88SPavel Labath             WaitForNewThread(event_message);
1700af245d11STodd Fiala 
17015fd24c67SPavel Labath         Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
1702af245d11STodd Fiala         break;
1703af245d11STodd Fiala     }
1704af245d11STodd Fiala 
1705af245d11STodd Fiala     case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
1706a9882ceeSTodd Fiala     {
1707a9882ceeSTodd Fiala         NativeThreadProtocolSP main_thread_sp;
1708af245d11STodd Fiala         if (log)
1709af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
1710a9882ceeSTodd Fiala 
17111dbc6c9cSPavel Labath         // Exec clears any pending notifications.
17121dbc6c9cSPavel Labath         m_pending_notification_up.reset ();
1713fa03ad2eSChaoren Lin 
1714fa03ad2eSChaoren 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.
1715a9882ceeSTodd Fiala         if (log)
1716a9882ceeSTodd Fiala             log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
1717a9882ceeSTodd Fiala 
1718a9882ceeSTodd Fiala         for (auto thread_sp : m_threads)
1719a9882ceeSTodd Fiala         {
1720a9882ceeSTodd Fiala             const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
1721a9882ceeSTodd Fiala             if (is_main_thread)
1722a9882ceeSTodd Fiala             {
1723a9882ceeSTodd Fiala                 main_thread_sp = thread_sp;
1724a9882ceeSTodd Fiala                 if (log)
1725a9882ceeSTodd Fiala                     log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
1726a9882ceeSTodd Fiala             }
1727a9882ceeSTodd Fiala             else
1728a9882ceeSTodd Fiala             {
1729fa03ad2eSChaoren Lin                 // Tell thread coordinator this thread is dead.
1730a9882ceeSTodd Fiala                 if (log)
1731a9882ceeSTodd Fiala                     log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
1732a9882ceeSTodd Fiala             }
1733a9882ceeSTodd Fiala         }
1734a9882ceeSTodd Fiala 
1735a9882ceeSTodd Fiala         m_threads.clear ();
1736a9882ceeSTodd Fiala 
1737a9882ceeSTodd Fiala         if (main_thread_sp)
1738a9882ceeSTodd Fiala         {
1739a9882ceeSTodd Fiala             m_threads.push_back (main_thread_sp);
1740a9882ceeSTodd Fiala             SetCurrentThreadID (main_thread_sp->GetID ());
1741cb84eebbSTamas Berghammer             std::static_pointer_cast<NativeThreadLinux> (main_thread_sp)->SetStoppedByExec ();
1742a9882ceeSTodd Fiala         }
1743a9882ceeSTodd Fiala         else
1744a9882ceeSTodd Fiala         {
1745a9882ceeSTodd Fiala             SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
1746a9882ceeSTodd Fiala             if (log)
1747a9882ceeSTodd Fiala                 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
1748a9882ceeSTodd Fiala         }
1749a9882ceeSTodd Fiala 
1750fa03ad2eSChaoren Lin         // Tell coordinator about about the "new" (since exec) stopped main thread.
1751fa03ad2eSChaoren Lin         const lldb::tid_t main_thread_tid = GetID ();
17521dbc6c9cSPavel Labath         ThreadWasCreated(main_thread_tid);
1753fa03ad2eSChaoren Lin 
1754fa03ad2eSChaoren Lin         // NOTE: ideally these next statements would execute at the same time as the coordinator thread create was executed.
1755fa03ad2eSChaoren Lin         // Consider a handler that can execute when that happens.
1756a9882ceeSTodd Fiala         // Let our delegate know we have just exec'd.
1757a9882ceeSTodd Fiala         NotifyDidExec ();
1758a9882ceeSTodd Fiala 
1759a9882ceeSTodd Fiala         // If we have a main thread, indicate we are stopped.
1760a9882ceeSTodd Fiala         assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
1761fa03ad2eSChaoren Lin 
1762fa03ad2eSChaoren Lin         // Let the process know we're stopped.
1763ed89c7feSPavel Labath         StopRunningThreads (pid);
1764a9882ceeSTodd Fiala 
1765af245d11STodd Fiala         break;
1766a9882ceeSTodd Fiala     }
1767af245d11STodd Fiala 
1768af245d11STodd Fiala     case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
1769af245d11STodd Fiala     {
1770af245d11STodd Fiala         // The inferior process or one of its threads is about to exit.
17716e35163cSPavel Labath         // We don't want to do anything with the thread so we just resume it. In case we
17726e35163cSPavel Labath         // want to implement "break on thread exit" functionality, we would need to stop
17736e35163cSPavel Labath         // here.
1774fa03ad2eSChaoren Lin 
1775af245d11STodd Fiala         unsigned long data = 0;
177697ccc294SChaoren Lin         if (GetEventMessage(pid, &data).Fail())
1777af245d11STodd Fiala             data = -1;
1778af245d11STodd Fiala 
1779af245d11STodd Fiala         if (log)
1780af245d11STodd Fiala         {
1781af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
1782af245d11STodd Fiala                          __FUNCTION__,
1783af245d11STodd Fiala                          data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
1784af245d11STodd Fiala                          pid,
1785af245d11STodd Fiala                     is_main_thread ? "is main thread" : "not main thread");
1786af245d11STodd Fiala         }
1787af245d11STodd Fiala 
1788af245d11STodd Fiala         if (is_main_thread)
1789af245d11STodd Fiala         {
1790af245d11STodd Fiala             SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
179175f47c3aSTodd Fiala         }
179275f47c3aSTodd Fiala 
17936e35163cSPavel Labath         Resume(pid, LLDB_INVALID_SIGNAL_NUMBER);
1794af245d11STodd Fiala 
1795af245d11STodd Fiala         break;
1796af245d11STodd Fiala     }
1797af245d11STodd Fiala 
1798af245d11STodd Fiala     case 0:
1799c16f5dcaSChaoren Lin     case TRAP_TRACE:  // We receive this on single stepping.
1800c16f5dcaSChaoren Lin     case TRAP_HWBKPT: // We receive this on watchpoint hit
180186fd8e45SChaoren Lin         if (thread_sp)
180286fd8e45SChaoren Lin         {
1803c16f5dcaSChaoren Lin             // If a watchpoint was hit, report it
1804c16f5dcaSChaoren Lin             uint32_t wp_index;
1805ea8c25a8SOmair Javaid             Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index, (lldb::addr_t)info->si_addr);
1806c16f5dcaSChaoren Lin             if (error.Fail() && log)
1807c16f5dcaSChaoren Lin                 log->Printf("NativeProcessLinux::%s() "
1808c16f5dcaSChaoren Lin                             "received error while checking for watchpoint hits, "
1809c16f5dcaSChaoren Lin                             "pid = %" PRIu64 " error = %s",
1810c16f5dcaSChaoren Lin                             __FUNCTION__, pid, error.AsCString());
1811c16f5dcaSChaoren Lin             if (wp_index != LLDB_INVALID_INDEX32)
18125830aa75STamas Berghammer             {
1813c16f5dcaSChaoren Lin                 MonitorWatchpoint(pid, thread_sp, wp_index);
1814c16f5dcaSChaoren Lin                 break;
1815c16f5dcaSChaoren Lin             }
1816c16f5dcaSChaoren Lin         }
1817c16f5dcaSChaoren Lin         // Otherwise, report step over
1818c16f5dcaSChaoren Lin         MonitorTrace(pid, thread_sp);
1819af245d11STodd Fiala         break;
1820af245d11STodd Fiala 
1821af245d11STodd Fiala     case SI_KERNEL:
182235799963SMohit K. Bhakkad #if defined __mips__
182335799963SMohit K. Bhakkad         // For mips there is no special signal for watchpoint
182435799963SMohit K. Bhakkad         // So we check for watchpoint in kernel trap
182535799963SMohit K. Bhakkad         if (thread_sp)
182635799963SMohit K. Bhakkad         {
182735799963SMohit K. Bhakkad             // If a watchpoint was hit, report it
182835799963SMohit K. Bhakkad             uint32_t wp_index;
1829c60c9452SJaydeep Patil             Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index, LLDB_INVALID_ADDRESS);
183035799963SMohit K. Bhakkad             if (error.Fail() && log)
183135799963SMohit K. Bhakkad                 log->Printf("NativeProcessLinux::%s() "
183235799963SMohit K. Bhakkad                             "received error while checking for watchpoint hits, "
183335799963SMohit K. Bhakkad                             "pid = %" PRIu64 " error = %s",
183435799963SMohit K. Bhakkad                             __FUNCTION__, pid, error.AsCString());
183535799963SMohit K. Bhakkad             if (wp_index != LLDB_INVALID_INDEX32)
183635799963SMohit K. Bhakkad             {
183735799963SMohit K. Bhakkad                 MonitorWatchpoint(pid, thread_sp, wp_index);
183835799963SMohit K. Bhakkad                 break;
183935799963SMohit K. Bhakkad             }
184035799963SMohit K. Bhakkad         }
184135799963SMohit K. Bhakkad         // NO BREAK
184235799963SMohit K. Bhakkad #endif
1843af245d11STodd Fiala     case TRAP_BRKPT:
1844c16f5dcaSChaoren Lin         MonitorBreakpoint(pid, thread_sp);
1845af245d11STodd Fiala         break;
1846af245d11STodd Fiala 
1847af245d11STodd Fiala     case SIGTRAP:
1848af245d11STodd Fiala     case (SIGTRAP | 0x80):
1849af245d11STodd Fiala         if (log)
1850fa03ad2eSChaoren Lin             log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), pid);
1851fa03ad2eSChaoren Lin 
1852af245d11STodd Fiala         // Ignore these signals until we know more about them.
18536e35163cSPavel Labath         Resume(pid, LLDB_INVALID_SIGNAL_NUMBER);
1854af245d11STodd Fiala         break;
1855af245d11STodd Fiala 
1856af245d11STodd Fiala     default:
1857af245d11STodd Fiala         assert(false && "Unexpected SIGTRAP code!");
1858af245d11STodd Fiala         if (log)
18596e35163cSPavel Labath             log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 "tid %" PRIu64 " received unhandled SIGTRAP code: 0x%d",
18606e35163cSPavel Labath                     __FUNCTION__, GetID (), pid, info->si_code);
1861af245d11STodd Fiala         break;
1862af245d11STodd Fiala 
1863af245d11STodd Fiala     }
1864af245d11STodd Fiala }
1865af245d11STodd Fiala 
1866af245d11STodd Fiala void
1867c16f5dcaSChaoren Lin NativeProcessLinux::MonitorTrace(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
1868c16f5dcaSChaoren Lin {
1869c16f5dcaSChaoren Lin     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1870c16f5dcaSChaoren Lin     if (log)
1871c16f5dcaSChaoren Lin         log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)",
1872c16f5dcaSChaoren Lin                 __FUNCTION__, pid);
1873c16f5dcaSChaoren Lin 
1874c16f5dcaSChaoren Lin     if (thread_sp)
1875c16f5dcaSChaoren Lin         std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
1876c16f5dcaSChaoren Lin 
1877c16f5dcaSChaoren Lin     // This thread is currently stopped.
18781dbc6c9cSPavel Labath     ThreadDidStop(pid, false);
1879c16f5dcaSChaoren Lin 
1880c16f5dcaSChaoren Lin     // Here we don't have to request the rest of the threads to stop or request a deferred stop.
1881c16f5dcaSChaoren Lin     // This would have already happened at the time the Resume() with step operation was signaled.
1882c16f5dcaSChaoren Lin     // At this point, we just need to say we stopped, and the deferred notifcation will fire off
1883c16f5dcaSChaoren Lin     // once all running threads have checked in as stopped.
1884c16f5dcaSChaoren Lin     SetCurrentThreadID(pid);
1885c16f5dcaSChaoren Lin     // Tell the process we have a stop (from software breakpoint).
1886ed89c7feSPavel Labath     StopRunningThreads(pid);
1887c16f5dcaSChaoren Lin }
1888c16f5dcaSChaoren Lin 
1889c16f5dcaSChaoren Lin void
1890c16f5dcaSChaoren Lin NativeProcessLinux::MonitorBreakpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
1891c16f5dcaSChaoren Lin {
1892c16f5dcaSChaoren Lin     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
1893c16f5dcaSChaoren Lin     if (log)
1894c16f5dcaSChaoren Lin         log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
1895c16f5dcaSChaoren Lin                 __FUNCTION__, pid);
1896c16f5dcaSChaoren Lin 
1897c16f5dcaSChaoren Lin     // This thread is currently stopped.
18981dbc6c9cSPavel Labath     ThreadDidStop(pid, false);
1899c16f5dcaSChaoren Lin 
1900c16f5dcaSChaoren Lin     // Mark the thread as stopped at breakpoint.
1901c16f5dcaSChaoren Lin     if (thread_sp)
1902c16f5dcaSChaoren Lin     {
1903c16f5dcaSChaoren Lin         std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByBreakpoint();
1904c16f5dcaSChaoren Lin         Error error = FixupBreakpointPCAsNeeded(thread_sp);
1905c16f5dcaSChaoren Lin         if (error.Fail())
1906c16f5dcaSChaoren Lin             if (log)
1907c16f5dcaSChaoren Lin                 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
1908c16f5dcaSChaoren Lin                         __FUNCTION__, pid, error.AsCString());
1909d8c338d4STamas Berghammer 
19109eb1ecb9SPavel Labath         if (m_threads_stepping_with_breakpoint.find(pid) != m_threads_stepping_with_breakpoint.end())
1911d8c338d4STamas Berghammer             std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
1912d8c338d4STamas Berghammer     }
1913c16f5dcaSChaoren Lin     else
1914c16f5dcaSChaoren Lin         if (log)
1915c16f5dcaSChaoren Lin             log->Printf("NativeProcessLinux::%s()  pid = %" PRIu64 ": "
1916c16f5dcaSChaoren Lin                     "warning, cannot process software breakpoint since no thread metadata",
1917c16f5dcaSChaoren Lin                     __FUNCTION__, pid);
1918c16f5dcaSChaoren Lin 
1919c16f5dcaSChaoren Lin 
1920c16f5dcaSChaoren Lin     // We need to tell all other running threads before we notify the delegate about this stop.
1921ed89c7feSPavel Labath     StopRunningThreads(pid);
1922c16f5dcaSChaoren Lin }
1923c16f5dcaSChaoren Lin 
1924c16f5dcaSChaoren Lin void
1925c16f5dcaSChaoren Lin NativeProcessLinux::MonitorWatchpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp, uint32_t wp_index)
1926c16f5dcaSChaoren Lin {
1927c16f5dcaSChaoren Lin     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
1928c16f5dcaSChaoren Lin     if (log)
1929c16f5dcaSChaoren Lin         log->Printf("NativeProcessLinux::%s() received watchpoint event, "
1930c16f5dcaSChaoren Lin                     "pid = %" PRIu64 ", wp_index = %" PRIu32,
1931c16f5dcaSChaoren Lin                     __FUNCTION__, pid, wp_index);
1932c16f5dcaSChaoren Lin 
1933c16f5dcaSChaoren Lin     // This thread is currently stopped.
19341dbc6c9cSPavel Labath     ThreadDidStop(pid, false);
1935c16f5dcaSChaoren Lin 
1936c16f5dcaSChaoren Lin     // Mark the thread as stopped at watchpoint.
1937c16f5dcaSChaoren Lin     // The address is at (lldb::addr_t)info->si_addr if we need it.
1938c16f5dcaSChaoren Lin     lldbassert(thread_sp && "thread_sp cannot be NULL");
1939c16f5dcaSChaoren Lin     std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByWatchpoint(wp_index);
1940c16f5dcaSChaoren Lin 
1941c16f5dcaSChaoren Lin     // We need to tell all other running threads before we notify the delegate about this stop.
1942ed89c7feSPavel Labath     StopRunningThreads(pid);
1943c16f5dcaSChaoren Lin }
1944c16f5dcaSChaoren Lin 
1945c16f5dcaSChaoren Lin void
1946af245d11STodd Fiala NativeProcessLinux::MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited)
1947af245d11STodd Fiala {
1948511e5cdcSTodd Fiala     assert (info && "null info");
1949511e5cdcSTodd Fiala     if (!info)
1950511e5cdcSTodd Fiala         return;
1951511e5cdcSTodd Fiala 
1952511e5cdcSTodd Fiala     const int signo = info->si_signo;
1953511e5cdcSTodd Fiala     const bool is_from_llgs = info->si_pid == getpid ();
1954af245d11STodd Fiala 
1955af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1956af245d11STodd Fiala 
1957af245d11STodd Fiala     // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1958af245d11STodd Fiala     // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1959af245d11STodd Fiala     // kill(2) or raise(3).  Similarly for tgkill(2) on Linux.
1960af245d11STodd Fiala     //
1961af245d11STodd Fiala     // IOW, user generated signals never generate what we consider to be a
1962af245d11STodd Fiala     // "crash".
1963af245d11STodd Fiala     //
1964af245d11STodd Fiala     // Similarly, ACK signals generated by this monitor.
1965af245d11STodd Fiala 
19665830aa75STamas Berghammer     Mutex::Locker locker (m_threads_mutex);
19675830aa75STamas Berghammer 
1968af245d11STodd Fiala     // See if we can find a thread for this signal.
1969af245d11STodd Fiala     NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
1970af245d11STodd Fiala     if (!thread_sp)
1971af245d11STodd Fiala     {
1972af245d11STodd Fiala         if (log)
1973af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
1974af245d11STodd Fiala     }
1975af245d11STodd Fiala 
1976af245d11STodd Fiala     // Handle the signal.
1977af245d11STodd Fiala     if (info->si_code == SI_TKILL || info->si_code == SI_USER)
1978af245d11STodd Fiala     {
1979af245d11STodd Fiala         if (log)
1980af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
1981af245d11STodd Fiala                             __FUNCTION__,
1982*98d0a4b3SChaoren Lin                             Host::GetSignalAsCString(signo),
1983af245d11STodd Fiala                             signo,
1984af245d11STodd Fiala                             (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
1985af245d11STodd Fiala                             info->si_pid,
1986511e5cdcSTodd Fiala                             is_from_llgs ? "from llgs" : "not from llgs",
1987af245d11STodd Fiala                             pid);
198858a2f669STodd Fiala     }
1989af245d11STodd Fiala 
199058a2f669STodd Fiala     // Check for new thread notification.
199158a2f669STodd Fiala     if ((info->si_pid == 0) && (info->si_code == SI_USER))
1992af245d11STodd Fiala     {
1993af245d11STodd Fiala         // A new thread creation is being signaled. This is one of two parts that come in
1994426bdf88SPavel Labath         // a non-deterministic order. This code handles the case where the new thread event comes
1995426bdf88SPavel Labath         // before the event on the parent thread. For the opposite case see code in
1996426bdf88SPavel Labath         // MonitorSIGTRAP.
1997af245d11STodd Fiala         if (log)
1998af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": new thread notification",
1999af245d11STodd Fiala                      __FUNCTION__, GetID (), pid);
2000af245d11STodd Fiala 
20015fd24c67SPavel Labath         thread_sp = AddThread(pid);
20025fd24c67SPavel Labath         assert (thread_sp.get() && "failed to create the tracking data for newly created inferior thread");
20035fd24c67SPavel Labath         // We can now resume the newly created thread.
2004cb84eebbSTamas Berghammer         std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
20055fd24c67SPavel Labath         Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
20061dbc6c9cSPavel Labath         ThreadWasCreated(pid);
200758a2f669STodd Fiala         // Done handling.
200858a2f669STodd Fiala         return;
2009af245d11STodd Fiala     }
201058a2f669STodd Fiala 
201158a2f669STodd Fiala     // Check for thread stop notification.
2012511e5cdcSTodd Fiala     if (is_from_llgs && (info->si_code == SI_TKILL) && (signo == SIGSTOP))
2013af245d11STodd Fiala     {
2014af245d11STodd Fiala         // This is a tgkill()-based stop.
2015af245d11STodd Fiala         if (thread_sp)
2016af245d11STodd Fiala         {
2017fa03ad2eSChaoren Lin             if (log)
2018fa03ad2eSChaoren Lin                 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
2019fa03ad2eSChaoren Lin                              __FUNCTION__,
2020fa03ad2eSChaoren Lin                              GetID (),
2021fa03ad2eSChaoren Lin                              pid);
2022fa03ad2eSChaoren Lin 
2023aab58633SChaoren Lin             // Check that we're not already marked with a stop reason.
2024aab58633SChaoren Lin             // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
2025aab58633SChaoren Lin             // the kernel signaled us with the thread stopping which we handled and marked as stopped,
2026aab58633SChaoren Lin             // and that, without an intervening resume, we received another stop.  It is more likely
2027aab58633SChaoren Lin             // that we are missing the marking of a run state somewhere if we find that the thread was
2028aab58633SChaoren Lin             // marked as stopped.
2029cb84eebbSTamas Berghammer             std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
2030cb84eebbSTamas Berghammer             assert (linux_thread_sp && "linux_thread_sp is null!");
2031aab58633SChaoren Lin 
2032cb84eebbSTamas Berghammer             const StateType thread_state = linux_thread_sp->GetState ();
2033aab58633SChaoren Lin             if (!StateIsStoppedState (thread_state, false))
2034aab58633SChaoren Lin             {
2035ed89c7feSPavel Labath                 // An inferior thread has stopped because of a SIGSTOP we have sent it.
2036ed89c7feSPavel Labath                 // Generally, these are not important stops and we don't want to report them as
2037ed89c7feSPavel Labath                 // they are just used to stop other threads when one thread (the one with the
2038ed89c7feSPavel Labath                 // *real* stop reason) hits a breakpoint (watchpoint, etc...). However, in the
2039ed89c7feSPavel Labath                 // case of an asynchronous Interrupt(), this *is* the real stop reason, so we
2040ed89c7feSPavel Labath                 // leave the signal intact if this is the thread that was chosen as the
2041ed89c7feSPavel Labath                 // triggering thread.
2042ed89c7feSPavel Labath                 if (m_pending_notification_up && m_pending_notification_up->triggering_tid == pid)
2043c4e25c96SPavel Labath                     linux_thread_sp->SetStoppedBySignal(SIGSTOP, info);
2044ed89c7feSPavel Labath                 else
2045cb84eebbSTamas Berghammer                     linux_thread_sp->SetStoppedBySignal(0);
2046ed89c7feSPavel Labath 
2047af245d11STodd Fiala                 SetCurrentThreadID (thread_sp->GetID ());
20481dbc6c9cSPavel Labath                 ThreadDidStop (thread_sp->GetID (), true);
2049aab58633SChaoren Lin             }
2050aab58633SChaoren Lin             else
2051aab58633SChaoren Lin             {
2052aab58633SChaoren Lin                 if (log)
2053aab58633SChaoren Lin                 {
2054aab58633SChaoren Lin                     // Retrieve the signal name if the thread was stopped by a signal.
2055aab58633SChaoren Lin                     int stop_signo = 0;
2056cb84eebbSTamas Berghammer                     const bool stopped_by_signal = linux_thread_sp->IsStopped (&stop_signo);
2057*98d0a4b3SChaoren Lin                     const char *signal_name = stopped_by_signal ? Host::GetSignalAsCString(stop_signo) : "<not stopped by signal>";
2058aab58633SChaoren Lin                     if (!signal_name)
2059aab58633SChaoren Lin                         signal_name = "<no-signal-name>";
2060aab58633SChaoren Lin 
2061aab58633SChaoren 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",
2062aab58633SChaoren Lin                                  __FUNCTION__,
2063aab58633SChaoren Lin                                  GetID (),
2064cb84eebbSTamas Berghammer                                  linux_thread_sp->GetID (),
2065aab58633SChaoren Lin                                  StateAsCString (thread_state),
2066aab58633SChaoren Lin                                  stop_signo,
2067aab58633SChaoren Lin                                  signal_name);
2068aab58633SChaoren Lin                 }
20691dbc6c9cSPavel Labath                 ThreadDidStop (thread_sp->GetID (), false);
2070af245d11STodd Fiala             }
207186fd8e45SChaoren Lin         }
2072af245d11STodd Fiala 
207358a2f669STodd Fiala         // Done handling.
2074af245d11STodd Fiala         return;
2075af245d11STodd Fiala     }
2076af245d11STodd Fiala 
2077af245d11STodd Fiala     if (log)
2078*98d0a4b3SChaoren Lin         log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, Host::GetSignalAsCString(signo));
2079af245d11STodd Fiala 
208086fd8e45SChaoren Lin     // This thread is stopped.
20811dbc6c9cSPavel Labath     ThreadDidStop (pid, false);
208286fd8e45SChaoren Lin 
208386fd8e45SChaoren Lin     if (thread_sp)
2084c4e25c96SPavel Labath         std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal(signo, info);
208586fd8e45SChaoren Lin 
208686fd8e45SChaoren Lin     // Send a stop to the debugger after we get all other threads to stop.
2087ed89c7feSPavel Labath     StopRunningThreads (pid);
2088511e5cdcSTodd Fiala }
2089af245d11STodd Fiala 
2090e7708688STamas Berghammer namespace {
2091e7708688STamas Berghammer 
2092e7708688STamas Berghammer struct EmulatorBaton
2093e7708688STamas Berghammer {
2094e7708688STamas Berghammer     NativeProcessLinux* m_process;
2095e7708688STamas Berghammer     NativeRegisterContext* m_reg_context;
20966648fcc3SPavel Labath 
20976648fcc3SPavel Labath     // eRegisterKindDWARF -> RegsiterValue
20986648fcc3SPavel Labath     std::unordered_map<uint32_t, RegisterValue> m_register_values;
2099e7708688STamas Berghammer 
2100e7708688STamas Berghammer     EmulatorBaton(NativeProcessLinux* process, NativeRegisterContext* reg_context) :
2101e7708688STamas Berghammer             m_process(process), m_reg_context(reg_context) {}
2102e7708688STamas Berghammer };
2103e7708688STamas Berghammer 
2104e7708688STamas Berghammer } // anonymous namespace
2105e7708688STamas Berghammer 
2106e7708688STamas Berghammer static size_t
2107e7708688STamas Berghammer ReadMemoryCallback (EmulateInstruction *instruction,
2108e7708688STamas Berghammer                     void *baton,
2109e7708688STamas Berghammer                     const EmulateInstruction::Context &context,
2110e7708688STamas Berghammer                     lldb::addr_t addr,
2111e7708688STamas Berghammer                     void *dst,
2112e7708688STamas Berghammer                     size_t length)
2113e7708688STamas Berghammer {
2114e7708688STamas Berghammer     EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
2115e7708688STamas Berghammer 
21163eb4b458SChaoren Lin     size_t bytes_read;
2117e7708688STamas Berghammer     emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
2118e7708688STamas Berghammer     return bytes_read;
2119e7708688STamas Berghammer }
2120e7708688STamas Berghammer 
2121e7708688STamas Berghammer static bool
2122e7708688STamas Berghammer ReadRegisterCallback (EmulateInstruction *instruction,
2123e7708688STamas Berghammer                       void *baton,
2124e7708688STamas Berghammer                       const RegisterInfo *reg_info,
2125e7708688STamas Berghammer                       RegisterValue &reg_value)
2126e7708688STamas Berghammer {
2127e7708688STamas Berghammer     EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
2128e7708688STamas Berghammer 
21296648fcc3SPavel Labath     auto it = emulator_baton->m_register_values.find(reg_info->kinds[eRegisterKindDWARF]);
21306648fcc3SPavel Labath     if (it != emulator_baton->m_register_values.end())
21316648fcc3SPavel Labath     {
21326648fcc3SPavel Labath         reg_value = it->second;
21336648fcc3SPavel Labath         return true;
21346648fcc3SPavel Labath     }
21356648fcc3SPavel Labath 
2136e7708688STamas Berghammer     // The emulator only fill in the dwarf regsiter numbers (and in some case
2137e7708688STamas Berghammer     // the generic register numbers). Get the full register info from the
2138e7708688STamas Berghammer     // register context based on the dwarf register numbers.
2139e7708688STamas Berghammer     const RegisterInfo* full_reg_info = emulator_baton->m_reg_context->GetRegisterInfo(
2140e7708688STamas Berghammer             eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
2141e7708688STamas Berghammer 
2142e7708688STamas Berghammer     Error error = emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
21436648fcc3SPavel Labath     if (error.Success())
21446648fcc3SPavel Labath         return true;
2145cdc22a88SMohit K. Bhakkad 
21466648fcc3SPavel Labath     return false;
2147e7708688STamas Berghammer }
2148e7708688STamas Berghammer 
2149e7708688STamas Berghammer static bool
2150e7708688STamas Berghammer WriteRegisterCallback (EmulateInstruction *instruction,
2151e7708688STamas Berghammer                        void *baton,
2152e7708688STamas Berghammer                        const EmulateInstruction::Context &context,
2153e7708688STamas Berghammer                        const RegisterInfo *reg_info,
2154e7708688STamas Berghammer                        const RegisterValue &reg_value)
2155e7708688STamas Berghammer {
2156e7708688STamas Berghammer     EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
21576648fcc3SPavel Labath     emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = reg_value;
2158e7708688STamas Berghammer     return true;
2159e7708688STamas Berghammer }
2160e7708688STamas Berghammer 
2161e7708688STamas Berghammer static size_t
2162e7708688STamas Berghammer WriteMemoryCallback (EmulateInstruction *instruction,
2163e7708688STamas Berghammer                      void *baton,
2164e7708688STamas Berghammer                      const EmulateInstruction::Context &context,
2165e7708688STamas Berghammer                      lldb::addr_t addr,
2166e7708688STamas Berghammer                      const void *dst,
2167e7708688STamas Berghammer                      size_t length)
2168e7708688STamas Berghammer {
2169e7708688STamas Berghammer     return length;
2170e7708688STamas Berghammer }
2171e7708688STamas Berghammer 
2172e7708688STamas Berghammer static lldb::addr_t
2173e7708688STamas Berghammer ReadFlags (NativeRegisterContext* regsiter_context)
2174e7708688STamas Berghammer {
2175e7708688STamas Berghammer     const RegisterInfo* flags_info = regsiter_context->GetRegisterInfo(
2176e7708688STamas Berghammer             eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
2177e7708688STamas Berghammer     return regsiter_context->ReadRegisterAsUnsigned(flags_info, LLDB_INVALID_ADDRESS);
2178e7708688STamas Berghammer }
2179e7708688STamas Berghammer 
2180e7708688STamas Berghammer Error
2181e7708688STamas Berghammer NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadProtocolSP thread_sp)
2182e7708688STamas Berghammer {
2183e7708688STamas Berghammer     Error error;
2184e7708688STamas Berghammer     NativeRegisterContextSP register_context_sp = thread_sp->GetRegisterContext();
2185e7708688STamas Berghammer 
2186e7708688STamas Berghammer     std::unique_ptr<EmulateInstruction> emulator_ap(
2187e7708688STamas Berghammer         EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, nullptr));
2188e7708688STamas Berghammer 
2189e7708688STamas Berghammer     if (emulator_ap == nullptr)
2190e7708688STamas Berghammer         return Error("Instruction emulator not found!");
2191e7708688STamas Berghammer 
2192e7708688STamas Berghammer     EmulatorBaton baton(this, register_context_sp.get());
2193e7708688STamas Berghammer     emulator_ap->SetBaton(&baton);
2194e7708688STamas Berghammer     emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
2195e7708688STamas Berghammer     emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
2196e7708688STamas Berghammer     emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
2197e7708688STamas Berghammer     emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
2198e7708688STamas Berghammer 
2199e7708688STamas Berghammer     if (!emulator_ap->ReadInstruction())
2200e7708688STamas Berghammer         return Error("Read instruction failed!");
2201e7708688STamas Berghammer 
22026648fcc3SPavel Labath     bool emulation_result = emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
22036648fcc3SPavel Labath 
22046648fcc3SPavel Labath     const RegisterInfo* reg_info_pc = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
22056648fcc3SPavel Labath     const RegisterInfo* reg_info_flags = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
22066648fcc3SPavel Labath 
22076648fcc3SPavel Labath     auto pc_it = baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
22086648fcc3SPavel Labath     auto flags_it = baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
22096648fcc3SPavel Labath 
2210e7708688STamas Berghammer     lldb::addr_t next_pc;
2211e7708688STamas Berghammer     lldb::addr_t next_flags;
22126648fcc3SPavel Labath     if (emulation_result)
2213e7708688STamas Berghammer     {
22146648fcc3SPavel Labath         assert(pc_it != baton.m_register_values.end() && "Emulation was successfull but PC wasn't updated");
22156648fcc3SPavel Labath         next_pc = pc_it->second.GetAsUInt64();
22166648fcc3SPavel Labath 
22176648fcc3SPavel Labath         if (flags_it != baton.m_register_values.end())
22186648fcc3SPavel Labath             next_flags = flags_it->second.GetAsUInt64();
2219e7708688STamas Berghammer         else
2220e7708688STamas Berghammer             next_flags = ReadFlags (register_context_sp.get());
2221e7708688STamas Berghammer     }
22226648fcc3SPavel Labath     else if (pc_it == baton.m_register_values.end())
2223e7708688STamas Berghammer     {
2224e7708688STamas Berghammer         // Emulate instruction failed and it haven't changed PC. Advance PC
2225e7708688STamas Berghammer         // with the size of the current opcode because the emulation of all
2226e7708688STamas Berghammer         // PC modifying instruction should be successful. The failure most
2227e7708688STamas Berghammer         // likely caused by a not supported instruction which don't modify PC.
2228e7708688STamas Berghammer         next_pc = register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
2229e7708688STamas Berghammer         next_flags = ReadFlags (register_context_sp.get());
2230e7708688STamas Berghammer     }
2231e7708688STamas Berghammer     else
2232e7708688STamas Berghammer     {
2233e7708688STamas Berghammer         // The instruction emulation failed after it modified the PC. It is an
2234e7708688STamas Berghammer         // unknown error where we can't continue because the next instruction is
2235e7708688STamas Berghammer         // modifying the PC but we don't  know how.
2236e7708688STamas Berghammer         return Error ("Instruction emulation failed unexpectedly.");
2237e7708688STamas Berghammer     }
2238e7708688STamas Berghammer 
2239e7708688STamas Berghammer     if (m_arch.GetMachine() == llvm::Triple::arm)
2240e7708688STamas Berghammer     {
2241e7708688STamas Berghammer         if (next_flags & 0x20)
2242e7708688STamas Berghammer         {
2243e7708688STamas Berghammer             // Thumb mode
2244e7708688STamas Berghammer             error = SetSoftwareBreakpoint(next_pc, 2);
2245e7708688STamas Berghammer         }
2246e7708688STamas Berghammer         else
2247e7708688STamas Berghammer         {
2248e7708688STamas Berghammer             // Arm mode
2249e7708688STamas Berghammer             error = SetSoftwareBreakpoint(next_pc, 4);
2250e7708688STamas Berghammer         }
2251e7708688STamas Berghammer     }
2252cdc22a88SMohit K. Bhakkad     else if (m_arch.GetMachine() == llvm::Triple::mips64
2253c60c9452SJaydeep Patil             || m_arch.GetMachine() == llvm::Triple::mips64el
2254c60c9452SJaydeep Patil             || m_arch.GetMachine() == llvm::Triple::mips
2255c60c9452SJaydeep Patil             || m_arch.GetMachine() == llvm::Triple::mipsel)
2256cdc22a88SMohit K. Bhakkad         error = SetSoftwareBreakpoint(next_pc, 4);
2257e7708688STamas Berghammer     else
2258e7708688STamas Berghammer     {
2259e7708688STamas Berghammer         // No size hint is given for the next breakpoint
2260e7708688STamas Berghammer         error = SetSoftwareBreakpoint(next_pc, 0);
2261e7708688STamas Berghammer     }
2262e7708688STamas Berghammer 
2263e7708688STamas Berghammer     if (error.Fail())
2264e7708688STamas Berghammer         return error;
2265e7708688STamas Berghammer 
2266e7708688STamas Berghammer     m_threads_stepping_with_breakpoint.insert({thread_sp->GetID(), next_pc});
2267e7708688STamas Berghammer 
2268e7708688STamas Berghammer     return Error();
2269e7708688STamas Berghammer }
2270e7708688STamas Berghammer 
2271e7708688STamas Berghammer bool
2272e7708688STamas Berghammer NativeProcessLinux::SupportHardwareSingleStepping() const
2273e7708688STamas Berghammer {
2274cdc22a88SMohit K. Bhakkad     if (m_arch.GetMachine() == llvm::Triple::arm
2275c60c9452SJaydeep Patil         || m_arch.GetMachine() == llvm::Triple::mips64 || m_arch.GetMachine() == llvm::Triple::mips64el
2276c60c9452SJaydeep Patil         || m_arch.GetMachine() == llvm::Triple::mips || m_arch.GetMachine() == llvm::Triple::mipsel)
2277cdc22a88SMohit K. Bhakkad         return false;
2278cdc22a88SMohit K. Bhakkad     return true;
2279e7708688STamas Berghammer }
2280e7708688STamas Berghammer 
2281af245d11STodd Fiala Error
2282af245d11STodd Fiala NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
2283af245d11STodd Fiala {
2284af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2285af245d11STodd Fiala     if (log)
2286af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
2287af245d11STodd Fiala 
2288e7708688STamas Berghammer     bool software_single_step = !SupportHardwareSingleStepping();
2289af245d11STodd Fiala 
229045f5cb31SPavel Labath     Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
2291af245d11STodd Fiala     Mutex::Locker locker (m_threads_mutex);
22925830aa75STamas Berghammer 
2293e7708688STamas Berghammer     if (software_single_step)
2294e7708688STamas Berghammer     {
2295e7708688STamas Berghammer         for (auto thread_sp : m_threads)
2296e7708688STamas Berghammer         {
2297e7708688STamas Berghammer             assert (thread_sp && "thread list should not contain NULL threads");
2298e7708688STamas Berghammer 
2299e7708688STamas Berghammer             const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
2300e7708688STamas Berghammer             if (action == nullptr)
2301e7708688STamas Berghammer                 continue;
2302e7708688STamas Berghammer 
2303e7708688STamas Berghammer             if (action->state == eStateStepping)
2304e7708688STamas Berghammer             {
2305e7708688STamas Berghammer                 Error error = SetupSoftwareSingleStepping(thread_sp);
2306e7708688STamas Berghammer                 if (error.Fail())
2307e7708688STamas Berghammer                     return error;
2308e7708688STamas Berghammer             }
2309e7708688STamas Berghammer         }
2310e7708688STamas Berghammer     }
2311e7708688STamas Berghammer 
2312af245d11STodd Fiala     for (auto thread_sp : m_threads)
2313af245d11STodd Fiala     {
2314af245d11STodd Fiala         assert (thread_sp && "thread list should not contain NULL threads");
2315af245d11STodd Fiala 
2316af245d11STodd Fiala         const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
23176a196ce6SChaoren Lin 
23186a196ce6SChaoren Lin         if (action == nullptr)
23196a196ce6SChaoren Lin         {
23206a196ce6SChaoren Lin             if (log)
23216a196ce6SChaoren Lin                 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
23226a196ce6SChaoren Lin                     __FUNCTION__, GetID (), thread_sp->GetID ());
23236a196ce6SChaoren Lin             continue;
23246a196ce6SChaoren Lin         }
2325af245d11STodd Fiala 
2326af245d11STodd Fiala         if (log)
2327af245d11STodd Fiala         {
2328af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
2329af245d11STodd Fiala                     __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
2330af245d11STodd Fiala         }
2331af245d11STodd Fiala 
2332af245d11STodd Fiala         switch (action->state)
2333af245d11STodd Fiala         {
2334af245d11STodd Fiala         case eStateRunning:
2335fa03ad2eSChaoren Lin         {
2336af245d11STodd Fiala             // Run the thread, possibly feeding it the signal.
2337fa03ad2eSChaoren Lin             const int signo = action->signal;
23381dbc6c9cSPavel Labath             ResumeThread(thread_sp->GetID (),
233986fd8e45SChaoren Lin                     [=](lldb::tid_t tid_to_resume, bool supress_signal)
2340af245d11STodd Fiala                     {
2341cb84eebbSTamas Berghammer                         std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2342fa03ad2eSChaoren Lin                         // Pass this signal number on to the inferior to handle.
23435830aa75STamas Berghammer                         const auto resume_result = Resume (tid_to_resume, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
23445830aa75STamas Berghammer                         if (resume_result.Success())
23455830aa75STamas Berghammer                             SetState(eStateRunning, true);
23465830aa75STamas Berghammer                         return resume_result;
23471dbc6c9cSPavel Labath                     },
23481dbc6c9cSPavel Labath                     false);
2349af245d11STodd Fiala             break;
2350fa03ad2eSChaoren Lin         }
2351af245d11STodd Fiala 
2352af245d11STodd Fiala         case eStateStepping:
2353af245d11STodd Fiala         {
2354ae29d395SChaoren Lin             // Request the step.
2355ae29d395SChaoren Lin             const int signo = action->signal;
23561dbc6c9cSPavel Labath             ResumeThread(thread_sp->GetID (),
235786fd8e45SChaoren Lin                     [=](lldb::tid_t tid_to_step, bool supress_signal)
2358af245d11STodd Fiala                     {
2359cb84eebbSTamas Berghammer                         std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStepping ();
2360e7708688STamas Berghammer 
2361e7708688STamas Berghammer                         Error step_result;
2362e7708688STamas Berghammer                         if (software_single_step)
2363e7708688STamas Berghammer                             step_result = Resume (tid_to_step, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
2364e7708688STamas Berghammer                         else
2365e7708688STamas Berghammer                             step_result = SingleStep (tid_to_step,(signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
2366e7708688STamas Berghammer 
236737c768caSChaoren Lin                         assert (step_result.Success() && "SingleStep() failed");
23685830aa75STamas Berghammer                         if (step_result.Success())
23695830aa75STamas Berghammer                             SetState(eStateStepping, true);
237037c768caSChaoren Lin                         return step_result;
23711dbc6c9cSPavel Labath                     },
23721dbc6c9cSPavel Labath                     false);
2373af245d11STodd Fiala             break;
2374ae29d395SChaoren Lin         }
2375af245d11STodd Fiala 
2376af245d11STodd Fiala         case eStateSuspended:
2377af245d11STodd Fiala         case eStateStopped:
2378108c325dSPavel Labath             lldbassert(0 && "Unexpected state");
2379af245d11STodd Fiala 
2380af245d11STodd Fiala         default:
2381af245d11STodd Fiala             return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
2382af245d11STodd Fiala                     __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
2383af245d11STodd Fiala         }
2384af245d11STodd Fiala     }
2385af245d11STodd Fiala 
23865830aa75STamas Berghammer     return Error();
2387af245d11STodd Fiala }
2388af245d11STodd Fiala 
2389af245d11STodd Fiala Error
2390af245d11STodd Fiala NativeProcessLinux::Halt ()
2391af245d11STodd Fiala {
2392af245d11STodd Fiala     Error error;
2393af245d11STodd Fiala 
2394af245d11STodd Fiala     if (kill (GetID (), SIGSTOP) != 0)
2395af245d11STodd Fiala         error.SetErrorToErrno ();
2396af245d11STodd Fiala 
2397af245d11STodd Fiala     return error;
2398af245d11STodd Fiala }
2399af245d11STodd Fiala 
2400af245d11STodd Fiala Error
2401af245d11STodd Fiala NativeProcessLinux::Detach ()
2402af245d11STodd Fiala {
2403af245d11STodd Fiala     Error error;
2404af245d11STodd Fiala 
2405af245d11STodd Fiala     // Tell ptrace to detach from the process.
2406af245d11STodd Fiala     if (GetID () != LLDB_INVALID_PROCESS_ID)
2407af245d11STodd Fiala         error = Detach (GetID ());
2408af245d11STodd Fiala 
2409af245d11STodd Fiala     // Stop monitoring the inferior.
241045f5cb31SPavel Labath     m_monitor_up->Terminate();
2411af245d11STodd Fiala 
2412af245d11STodd Fiala     // No error.
2413af245d11STodd Fiala     return error;
2414af245d11STodd Fiala }
2415af245d11STodd Fiala 
2416af245d11STodd Fiala Error
2417af245d11STodd Fiala NativeProcessLinux::Signal (int signo)
2418af245d11STodd Fiala {
2419af245d11STodd Fiala     Error error;
2420af245d11STodd Fiala 
2421af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2422af245d11STodd Fiala     if (log)
2423af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
2424*98d0a4b3SChaoren Lin                 __FUNCTION__, signo, Host::GetSignalAsCString(signo), GetID());
2425af245d11STodd Fiala 
2426af245d11STodd Fiala     if (kill(GetID(), signo))
2427af245d11STodd Fiala         error.SetErrorToErrno();
2428af245d11STodd Fiala 
2429af245d11STodd Fiala     return error;
2430af245d11STodd Fiala }
2431af245d11STodd Fiala 
2432af245d11STodd Fiala Error
2433e9547b80SChaoren Lin NativeProcessLinux::Interrupt ()
2434e9547b80SChaoren Lin {
2435e9547b80SChaoren Lin     // Pick a running thread (or if none, a not-dead stopped thread) as
2436e9547b80SChaoren Lin     // the chosen thread that will be the stop-reason thread.
2437e9547b80SChaoren Lin     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2438e9547b80SChaoren Lin 
2439e9547b80SChaoren Lin     NativeThreadProtocolSP running_thread_sp;
2440e9547b80SChaoren Lin     NativeThreadProtocolSP stopped_thread_sp;
2441e9547b80SChaoren Lin 
2442e9547b80SChaoren Lin     if (log)
2443e9547b80SChaoren Lin         log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
2444e9547b80SChaoren Lin 
244545f5cb31SPavel Labath     Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
24465830aa75STamas Berghammer     Mutex::Locker locker (m_threads_mutex);
24475830aa75STamas Berghammer 
2448e9547b80SChaoren Lin     for (auto thread_sp : m_threads)
2449e9547b80SChaoren Lin     {
2450e9547b80SChaoren Lin         // The thread shouldn't be null but lets just cover that here.
2451e9547b80SChaoren Lin         if (!thread_sp)
2452e9547b80SChaoren Lin             continue;
2453e9547b80SChaoren Lin 
2454e9547b80SChaoren Lin         // If we have a running or stepping thread, we'll call that the
2455e9547b80SChaoren Lin         // target of the interrupt.
2456e9547b80SChaoren Lin         const auto thread_state = thread_sp->GetState ();
2457e9547b80SChaoren Lin         if (thread_state == eStateRunning ||
2458e9547b80SChaoren Lin             thread_state == eStateStepping)
2459e9547b80SChaoren Lin         {
2460e9547b80SChaoren Lin             running_thread_sp = thread_sp;
2461e9547b80SChaoren Lin             break;
2462e9547b80SChaoren Lin         }
2463e9547b80SChaoren Lin         else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
2464e9547b80SChaoren Lin         {
2465e9547b80SChaoren Lin             // Remember the first non-dead stopped thread.  We'll use that as a backup if there are no running threads.
2466e9547b80SChaoren Lin             stopped_thread_sp = thread_sp;
2467e9547b80SChaoren Lin         }
2468e9547b80SChaoren Lin     }
2469e9547b80SChaoren Lin 
2470e9547b80SChaoren Lin     if (!running_thread_sp && !stopped_thread_sp)
2471e9547b80SChaoren Lin     {
24725830aa75STamas Berghammer         Error error("found no running/stepping or live stopped threads as target for interrupt");
2473e9547b80SChaoren Lin         if (log)
2474e9547b80SChaoren Lin             log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
24755830aa75STamas Berghammer 
2476e9547b80SChaoren Lin         return error;
2477e9547b80SChaoren Lin     }
2478e9547b80SChaoren Lin 
2479e9547b80SChaoren Lin     NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
2480e9547b80SChaoren Lin 
2481e9547b80SChaoren Lin     if (log)
2482e9547b80SChaoren Lin         log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
2483e9547b80SChaoren Lin                      __FUNCTION__,
2484e9547b80SChaoren Lin                      GetID (),
2485e9547b80SChaoren Lin                      running_thread_sp ? "running" : "stopped",
2486e9547b80SChaoren Lin                      deferred_signal_thread_sp->GetID ());
2487e9547b80SChaoren Lin 
2488ed89c7feSPavel Labath     StopRunningThreads(deferred_signal_thread_sp->GetID());
248945f5cb31SPavel Labath 
24905830aa75STamas Berghammer     return Error();
2491e9547b80SChaoren Lin }
2492e9547b80SChaoren Lin 
2493e9547b80SChaoren Lin Error
2494af245d11STodd Fiala NativeProcessLinux::Kill ()
2495af245d11STodd Fiala {
2496af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2497af245d11STodd Fiala     if (log)
2498af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
2499af245d11STodd Fiala 
2500af245d11STodd Fiala     Error error;
2501af245d11STodd Fiala 
2502af245d11STodd Fiala     switch (m_state)
2503af245d11STodd Fiala     {
2504af245d11STodd Fiala         case StateType::eStateInvalid:
2505af245d11STodd Fiala         case StateType::eStateExited:
2506af245d11STodd Fiala         case StateType::eStateCrashed:
2507af245d11STodd Fiala         case StateType::eStateDetached:
2508af245d11STodd Fiala         case StateType::eStateUnloaded:
2509af245d11STodd Fiala             // Nothing to do - the process is already dead.
2510af245d11STodd Fiala             if (log)
2511af245d11STodd Fiala                 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
2512af245d11STodd Fiala             return error;
2513af245d11STodd Fiala 
2514af245d11STodd Fiala         case StateType::eStateConnected:
2515af245d11STodd Fiala         case StateType::eStateAttaching:
2516af245d11STodd Fiala         case StateType::eStateLaunching:
2517af245d11STodd Fiala         case StateType::eStateStopped:
2518af245d11STodd Fiala         case StateType::eStateRunning:
2519af245d11STodd Fiala         case StateType::eStateStepping:
2520af245d11STodd Fiala         case StateType::eStateSuspended:
2521af245d11STodd Fiala             // We can try to kill a process in these states.
2522af245d11STodd Fiala             break;
2523af245d11STodd Fiala     }
2524af245d11STodd Fiala 
2525af245d11STodd Fiala     if (kill (GetID (), SIGKILL) != 0)
2526af245d11STodd Fiala     {
2527af245d11STodd Fiala         error.SetErrorToErrno ();
2528af245d11STodd Fiala         return error;
2529af245d11STodd Fiala     }
2530af245d11STodd Fiala 
2531af245d11STodd Fiala     return error;
2532af245d11STodd Fiala }
2533af245d11STodd Fiala 
2534af245d11STodd Fiala static Error
2535af245d11STodd Fiala ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
2536af245d11STodd Fiala {
2537af245d11STodd Fiala     memory_region_info.Clear();
2538af245d11STodd Fiala 
2539af245d11STodd Fiala     StringExtractor line_extractor (maps_line.c_str ());
2540af245d11STodd Fiala 
2541af245d11STodd Fiala     // Format: {address_start_hex}-{address_end_hex} perms offset  dev   inode   pathname
2542af245d11STodd Fiala     // perms: rwxp   (letter is present if set, '-' if not, final character is p=private, s=shared).
2543af245d11STodd Fiala 
2544af245d11STodd Fiala     // Parse out the starting address
2545af245d11STodd Fiala     lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
2546af245d11STodd Fiala 
2547af245d11STodd Fiala     // Parse out hyphen separating start and end address from range.
2548af245d11STodd Fiala     if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
2549af245d11STodd Fiala         return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
2550af245d11STodd Fiala 
2551af245d11STodd Fiala     // Parse out the ending address
2552af245d11STodd Fiala     lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
2553af245d11STodd Fiala 
2554af245d11STodd Fiala     // Parse out the space after the address.
2555af245d11STodd Fiala     if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
2556af245d11STodd Fiala         return Error ("malformed /proc/{pid}/maps entry, missing space after range");
2557af245d11STodd Fiala 
2558af245d11STodd Fiala     // Save the range.
2559af245d11STodd Fiala     memory_region_info.GetRange ().SetRangeBase (start_address);
2560af245d11STodd Fiala     memory_region_info.GetRange ().SetRangeEnd (end_address);
2561af245d11STodd Fiala 
2562af245d11STodd Fiala     // Parse out each permission entry.
2563af245d11STodd Fiala     if (line_extractor.GetBytesLeft () < 4)
2564af245d11STodd Fiala         return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
2565af245d11STodd Fiala 
2566af245d11STodd Fiala     // Handle read permission.
2567af245d11STodd Fiala     const char read_perm_char = line_extractor.GetChar ();
2568af245d11STodd Fiala     if (read_perm_char == 'r')
2569af245d11STodd Fiala         memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
2570af245d11STodd Fiala     else
2571af245d11STodd Fiala     {
2572af245d11STodd Fiala         assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
2573af245d11STodd Fiala         memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2574af245d11STodd Fiala     }
2575af245d11STodd Fiala 
2576af245d11STodd Fiala     // Handle write permission.
2577af245d11STodd Fiala     const char write_perm_char = line_extractor.GetChar ();
2578af245d11STodd Fiala     if (write_perm_char == 'w')
2579af245d11STodd Fiala         memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
2580af245d11STodd Fiala     else
2581af245d11STodd Fiala     {
2582af245d11STodd Fiala         assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
2583af245d11STodd Fiala         memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2584af245d11STodd Fiala     }
2585af245d11STodd Fiala 
2586af245d11STodd Fiala     // Handle execute permission.
2587af245d11STodd Fiala     const char exec_perm_char = line_extractor.GetChar ();
2588af245d11STodd Fiala     if (exec_perm_char == 'x')
2589af245d11STodd Fiala         memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
2590af245d11STodd Fiala     else
2591af245d11STodd Fiala     {
2592af245d11STodd Fiala         assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
2593af245d11STodd Fiala         memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2594af245d11STodd Fiala     }
2595af245d11STodd Fiala 
2596af245d11STodd Fiala     return Error ();
2597af245d11STodd Fiala }
2598af245d11STodd Fiala 
2599af245d11STodd Fiala Error
2600af245d11STodd Fiala NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
2601af245d11STodd Fiala {
2602af245d11STodd Fiala     // FIXME review that the final memory region returned extends to the end of the virtual address space,
2603af245d11STodd Fiala     // with no perms if it is not mapped.
2604af245d11STodd Fiala 
2605af245d11STodd Fiala     // Use an approach that reads memory regions from /proc/{pid}/maps.
2606af245d11STodd Fiala     // Assume proc maps entries are in ascending order.
2607af245d11STodd Fiala     // FIXME assert if we find differently.
2608af245d11STodd Fiala     Mutex::Locker locker (m_mem_region_cache_mutex);
2609af245d11STodd Fiala 
2610af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2611af245d11STodd Fiala     Error error;
2612af245d11STodd Fiala 
2613af245d11STodd Fiala     if (m_supports_mem_region == LazyBool::eLazyBoolNo)
2614af245d11STodd Fiala     {
2615af245d11STodd Fiala         // We're done.
2616af245d11STodd Fiala         error.SetErrorString ("unsupported");
2617af245d11STodd Fiala         return error;
2618af245d11STodd Fiala     }
2619af245d11STodd Fiala 
2620af245d11STodd Fiala     // If our cache is empty, pull the latest.  There should always be at least one memory region
2621af245d11STodd Fiala     // if memory region handling is supported.
2622af245d11STodd Fiala     if (m_mem_region_cache.empty ())
2623af245d11STodd Fiala     {
2624af245d11STodd Fiala         error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
2625af245d11STodd Fiala              [&] (const std::string &line) -> bool
2626af245d11STodd Fiala              {
2627af245d11STodd Fiala                  MemoryRegionInfo info;
2628af245d11STodd Fiala                  const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
2629af245d11STodd Fiala                  if (parse_error.Success ())
2630af245d11STodd Fiala                  {
2631af245d11STodd Fiala                      m_mem_region_cache.push_back (info);
2632af245d11STodd Fiala                      return true;
2633af245d11STodd Fiala                  }
2634af245d11STodd Fiala                  else
2635af245d11STodd Fiala                  {
2636af245d11STodd Fiala                      if (log)
2637af245d11STodd Fiala                          log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
2638af245d11STodd Fiala                      return false;
2639af245d11STodd Fiala                  }
2640af245d11STodd Fiala              });
2641af245d11STodd Fiala 
2642af245d11STodd Fiala         // If we had an error, we'll mark unsupported.
2643af245d11STodd Fiala         if (error.Fail ())
2644af245d11STodd Fiala         {
2645af245d11STodd Fiala             m_supports_mem_region = LazyBool::eLazyBoolNo;
2646af245d11STodd Fiala             return error;
2647af245d11STodd Fiala         }
2648af245d11STodd Fiala         else if (m_mem_region_cache.empty ())
2649af245d11STodd Fiala         {
2650af245d11STodd Fiala             // No entries after attempting to read them.  This shouldn't happen if /proc/{pid}/maps
2651af245d11STodd Fiala             // is supported.  Assume we don't support map entries via procfs.
2652af245d11STodd Fiala             if (log)
2653af245d11STodd Fiala                 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
2654af245d11STodd Fiala             m_supports_mem_region = LazyBool::eLazyBoolNo;
2655af245d11STodd Fiala             error.SetErrorString ("not supported");
2656af245d11STodd Fiala             return error;
2657af245d11STodd Fiala         }
2658af245d11STodd Fiala 
2659af245d11STodd Fiala         if (log)
2660af245d11STodd 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 ());
2661af245d11STodd Fiala 
2662af245d11STodd Fiala         // We support memory retrieval, remember that.
2663af245d11STodd Fiala         m_supports_mem_region = LazyBool::eLazyBoolYes;
2664af245d11STodd Fiala     }
2665af245d11STodd Fiala     else
2666af245d11STodd Fiala     {
2667af245d11STodd Fiala         if (log)
2668af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2669af245d11STodd Fiala     }
2670af245d11STodd Fiala 
2671af245d11STodd Fiala     lldb::addr_t prev_base_address = 0;
2672af245d11STodd Fiala 
2673af245d11STodd Fiala     // FIXME start by finding the last region that is <= target address using binary search.  Data is sorted.
2674af245d11STodd Fiala     // There can be a ton of regions on pthreads apps with lots of threads.
2675af245d11STodd Fiala     for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
2676af245d11STodd Fiala     {
2677af245d11STodd Fiala         MemoryRegionInfo &proc_entry_info = *it;
2678af245d11STodd Fiala 
2679af245d11STodd Fiala         // Sanity check assumption that /proc/{pid}/maps entries are ascending.
2680af245d11STodd Fiala         assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
2681af245d11STodd Fiala         prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
2682af245d11STodd Fiala 
2683af245d11STodd Fiala         // If the target address comes before this entry, indicate distance to next region.
2684af245d11STodd Fiala         if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
2685af245d11STodd Fiala         {
2686af245d11STodd Fiala             range_info.GetRange ().SetRangeBase (load_addr);
2687af245d11STodd Fiala             range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
2688af245d11STodd Fiala             range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2689af245d11STodd Fiala             range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2690af245d11STodd Fiala             range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2691af245d11STodd Fiala 
2692af245d11STodd Fiala             return error;
2693af245d11STodd Fiala         }
2694af245d11STodd Fiala         else if (proc_entry_info.GetRange ().Contains (load_addr))
2695af245d11STodd Fiala         {
2696af245d11STodd Fiala             // The target address is within the memory region we're processing here.
2697af245d11STodd Fiala             range_info = proc_entry_info;
2698af245d11STodd Fiala             return error;
2699af245d11STodd Fiala         }
2700af245d11STodd Fiala 
2701af245d11STodd Fiala         // The target memory address comes somewhere after the region we just parsed.
2702af245d11STodd Fiala     }
2703af245d11STodd Fiala 
270409839c33STamas Berghammer     // If we made it here, we didn't find an entry that contained the given address. Return the
270509839c33STamas Berghammer     // load_addr as start and the amount of bytes betwwen load address and the end of the memory as
270609839c33STamas Berghammer     // size.
270709839c33STamas Berghammer     range_info.GetRange ().SetRangeBase (load_addr);
270809839c33STamas Berghammer     switch (m_arch.GetAddressByteSize())
270909839c33STamas Berghammer     {
271009839c33STamas Berghammer         case 4:
271109839c33STamas Berghammer             range_info.GetRange ().SetByteSize (0x100000000ull - load_addr);
271209839c33STamas Berghammer             break;
271309839c33STamas Berghammer         case 8:
271409839c33STamas Berghammer             range_info.GetRange ().SetByteSize (0ull - load_addr);
271509839c33STamas Berghammer             break;
271609839c33STamas Berghammer         default:
271709839c33STamas Berghammer             assert(false && "Unrecognized data byte size");
271809839c33STamas Berghammer             break;
271909839c33STamas Berghammer     }
272009839c33STamas Berghammer     range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
272109839c33STamas Berghammer     range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
272209839c33STamas Berghammer     range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2723af245d11STodd Fiala     return error;
2724af245d11STodd Fiala }
2725af245d11STodd Fiala 
2726af245d11STodd Fiala void
2727af245d11STodd Fiala NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
2728af245d11STodd Fiala {
2729af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2730af245d11STodd Fiala     if (log)
2731af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
2732af245d11STodd Fiala 
2733af245d11STodd Fiala     {
2734af245d11STodd Fiala         Mutex::Locker locker (m_mem_region_cache_mutex);
2735af245d11STodd Fiala         if (log)
2736af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2737af245d11STodd Fiala         m_mem_region_cache.clear ();
2738af245d11STodd Fiala     }
2739af245d11STodd Fiala }
2740af245d11STodd Fiala 
2741af245d11STodd Fiala Error
27423eb4b458SChaoren Lin NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr)
2743af245d11STodd Fiala {
2744af245d11STodd Fiala     // FIXME implementing this requires the equivalent of
2745af245d11STodd Fiala     // InferiorCallPOSIX::InferiorCallMmap, which depends on
2746af245d11STodd Fiala     // functional ThreadPlans working with Native*Protocol.
2747af245d11STodd Fiala #if 1
2748af245d11STodd Fiala     return Error ("not implemented yet");
2749af245d11STodd Fiala #else
2750af245d11STodd Fiala     addr = LLDB_INVALID_ADDRESS;
2751af245d11STodd Fiala 
2752af245d11STodd Fiala     unsigned prot = 0;
2753af245d11STodd Fiala     if (permissions & lldb::ePermissionsReadable)
2754af245d11STodd Fiala         prot |= eMmapProtRead;
2755af245d11STodd Fiala     if (permissions & lldb::ePermissionsWritable)
2756af245d11STodd Fiala         prot |= eMmapProtWrite;
2757af245d11STodd Fiala     if (permissions & lldb::ePermissionsExecutable)
2758af245d11STodd Fiala         prot |= eMmapProtExec;
2759af245d11STodd Fiala 
2760af245d11STodd Fiala     // TODO implement this directly in NativeProcessLinux
2761af245d11STodd Fiala     // (and lift to NativeProcessPOSIX if/when that class is
2762af245d11STodd Fiala     // refactored out).
2763af245d11STodd Fiala     if (InferiorCallMmap(this, addr, 0, size, prot,
2764af245d11STodd Fiala                          eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
2765af245d11STodd Fiala         m_addr_to_mmap_size[addr] = size;
2766af245d11STodd Fiala         return Error ();
2767af245d11STodd Fiala     } else {
2768af245d11STodd Fiala         addr = LLDB_INVALID_ADDRESS;
2769af245d11STodd Fiala         return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
2770af245d11STodd Fiala     }
2771af245d11STodd Fiala #endif
2772af245d11STodd Fiala }
2773af245d11STodd Fiala 
2774af245d11STodd Fiala Error
2775af245d11STodd Fiala NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
2776af245d11STodd Fiala {
2777af245d11STodd Fiala     // FIXME see comments in AllocateMemory - required lower-level
2778af245d11STodd Fiala     // bits not in place yet (ThreadPlans)
2779af245d11STodd Fiala     return Error ("not implemented");
2780af245d11STodd Fiala }
2781af245d11STodd Fiala 
2782af245d11STodd Fiala lldb::addr_t
2783af245d11STodd Fiala NativeProcessLinux::GetSharedLibraryInfoAddress ()
2784af245d11STodd Fiala {
2785af245d11STodd Fiala #if 1
2786af245d11STodd Fiala     // punt on this for now
2787af245d11STodd Fiala     return LLDB_INVALID_ADDRESS;
2788af245d11STodd Fiala #else
2789af245d11STodd Fiala     // Return the image info address for the exe module
2790af245d11STodd Fiala #if 1
2791af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2792af245d11STodd Fiala 
2793af245d11STodd Fiala     ModuleSP module_sp;
2794af245d11STodd Fiala     Error error = GetExeModuleSP (module_sp);
2795af245d11STodd Fiala     if (error.Fail ())
2796af245d11STodd Fiala     {
2797af245d11STodd Fiala          if (log)
2798af245d11STodd Fiala             log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ());
2799af245d11STodd Fiala         return LLDB_INVALID_ADDRESS;
2800af245d11STodd Fiala     }
2801af245d11STodd Fiala 
2802af245d11STodd Fiala     if (module_sp == nullptr)
2803af245d11STodd Fiala     {
2804af245d11STodd Fiala          if (log)
2805af245d11STodd Fiala             log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__);
2806af245d11STodd Fiala          return LLDB_INVALID_ADDRESS;
2807af245d11STodd Fiala     }
2808af245d11STodd Fiala 
2809af245d11STodd Fiala     ObjectFileSP object_file_sp = module_sp->GetObjectFile ();
2810af245d11STodd Fiala     if (object_file_sp == nullptr)
2811af245d11STodd Fiala     {
2812af245d11STodd Fiala          if (log)
2813af245d11STodd Fiala             log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__);
2814af245d11STodd Fiala          return LLDB_INVALID_ADDRESS;
2815af245d11STodd Fiala     }
2816af245d11STodd Fiala 
2817af245d11STodd Fiala     return obj_file_sp->GetImageInfoAddress();
2818af245d11STodd Fiala #else
2819af245d11STodd Fiala     Target *target = &GetTarget();
2820af245d11STodd Fiala     ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
2821af245d11STodd Fiala     Address addr = obj_file->GetImageInfoAddress(target);
2822af245d11STodd Fiala 
2823af245d11STodd Fiala     if (addr.IsValid())
2824af245d11STodd Fiala         return addr.GetLoadAddress(target);
2825af245d11STodd Fiala     return LLDB_INVALID_ADDRESS;
2826af245d11STodd Fiala #endif
2827af245d11STodd Fiala #endif // punt on this for now
2828af245d11STodd Fiala }
2829af245d11STodd Fiala 
2830af245d11STodd Fiala size_t
2831af245d11STodd Fiala NativeProcessLinux::UpdateThreads ()
2832af245d11STodd Fiala {
2833af245d11STodd Fiala     // The NativeProcessLinux monitoring threads are always up to date
2834af245d11STodd Fiala     // with respect to thread state and they keep the thread list
2835af245d11STodd Fiala     // populated properly. All this method needs to do is return the
2836af245d11STodd Fiala     // thread count.
2837af245d11STodd Fiala     Mutex::Locker locker (m_threads_mutex);
2838af245d11STodd Fiala     return m_threads.size ();
2839af245d11STodd Fiala }
2840af245d11STodd Fiala 
2841af245d11STodd Fiala bool
2842af245d11STodd Fiala NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
2843af245d11STodd Fiala {
2844af245d11STodd Fiala     arch = m_arch;
2845af245d11STodd Fiala     return true;
2846af245d11STodd Fiala }
2847af245d11STodd Fiala 
2848af245d11STodd Fiala Error
284963c8be95STamas Berghammer NativeProcessLinux::GetSoftwareBreakpointPCOffset (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size)
2850af245d11STodd Fiala {
2851af245d11STodd Fiala     // FIXME put this behind a breakpoint protocol class that can be
2852af245d11STodd Fiala     // set per architecture.  Need ARM, MIPS support here.
2853af245d11STodd Fiala     static const uint8_t g_i386_opcode [] = { 0xCC };
2854af245d11STodd Fiala 
2855af245d11STodd Fiala     switch (m_arch.GetMachine ())
2856af245d11STodd Fiala     {
2857af245d11STodd Fiala         case llvm::Triple::x86:
2858af245d11STodd Fiala         case llvm::Triple::x86_64:
2859af245d11STodd Fiala             actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
2860af245d11STodd Fiala             return Error ();
2861af245d11STodd Fiala 
2862ff7fd900STamas Berghammer         case llvm::Triple::arm:
2863ff7fd900STamas Berghammer         case llvm::Triple::aarch64:
2864e8659b5dSMohit K. Bhakkad         case llvm::Triple::mips64:
2865e8659b5dSMohit K. Bhakkad         case llvm::Triple::mips64el:
2866ce815e45SSagar Thakur         case llvm::Triple::mips:
2867ce815e45SSagar Thakur         case llvm::Triple::mipsel:
2868ff7fd900STamas Berghammer             // On these architectures the PC don't get updated for breakpoint hits
2869c60c9452SJaydeep Patil             actual_opcode_size = 0;
2870e8659b5dSMohit K. Bhakkad             return Error ();
2871e8659b5dSMohit K. Bhakkad 
2872af245d11STodd Fiala         default:
2873af245d11STodd Fiala             assert(false && "CPU type not supported!");
2874af245d11STodd Fiala             return Error ("CPU type not supported");
2875af245d11STodd Fiala     }
2876af245d11STodd Fiala }
2877af245d11STodd Fiala 
2878af245d11STodd Fiala Error
2879af245d11STodd Fiala NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
2880af245d11STodd Fiala {
2881af245d11STodd Fiala     if (hardware)
2882af245d11STodd Fiala         return Error ("NativeProcessLinux does not support hardware breakpoints");
2883af245d11STodd Fiala     else
2884af245d11STodd Fiala         return SetSoftwareBreakpoint (addr, size);
2885af245d11STodd Fiala }
2886af245d11STodd Fiala 
2887af245d11STodd Fiala Error
288863c8be95STamas Berghammer NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint,
288963c8be95STamas Berghammer                                                      size_t &actual_opcode_size,
289063c8be95STamas Berghammer                                                      const uint8_t *&trap_opcode_bytes)
2891af245d11STodd Fiala {
289263c8be95STamas Berghammer     // FIXME put this behind a breakpoint protocol class that can be set per
289363c8be95STamas Berghammer     // architecture.  Need MIPS support here.
28942afc5966STodd Fiala     static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
289563c8be95STamas Berghammer     // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
289663c8be95STamas Berghammer     // linux kernel does otherwise.
289763c8be95STamas Berghammer     static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 };
2898af245d11STodd Fiala     static const uint8_t g_i386_opcode [] = { 0xCC };
28993df471c3SMohit K. Bhakkad     static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
29002c2acf96SMohit K. Bhakkad     static const uint8_t g_mips64el_opcode[] = { 0x0d, 0x00, 0x00, 0x00 };
290163c8be95STamas Berghammer     static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde };
2902af245d11STodd Fiala 
2903af245d11STodd Fiala     switch (m_arch.GetMachine ())
2904af245d11STodd Fiala     {
29052afc5966STodd Fiala     case llvm::Triple::aarch64:
29062afc5966STodd Fiala         trap_opcode_bytes = g_aarch64_opcode;
29072afc5966STodd Fiala         actual_opcode_size = sizeof(g_aarch64_opcode);
29082afc5966STodd Fiala         return Error ();
29092afc5966STodd Fiala 
291063c8be95STamas Berghammer     case llvm::Triple::arm:
291163c8be95STamas Berghammer         switch (trap_opcode_size_hint)
291263c8be95STamas Berghammer         {
291363c8be95STamas Berghammer         case 2:
291463c8be95STamas Berghammer             trap_opcode_bytes = g_thumb_breakpoint_opcode;
291563c8be95STamas Berghammer             actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
291663c8be95STamas Berghammer             return Error ();
291763c8be95STamas Berghammer         case 4:
291863c8be95STamas Berghammer             trap_opcode_bytes = g_arm_breakpoint_opcode;
291963c8be95STamas Berghammer             actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
292063c8be95STamas Berghammer             return Error ();
292163c8be95STamas Berghammer         default:
292263c8be95STamas Berghammer             assert(false && "Unrecognised trap opcode size hint!");
292363c8be95STamas Berghammer             return Error ("Unrecognised trap opcode size hint!");
292463c8be95STamas Berghammer         }
292563c8be95STamas Berghammer 
2926af245d11STodd Fiala     case llvm::Triple::x86:
2927af245d11STodd Fiala     case llvm::Triple::x86_64:
2928af245d11STodd Fiala         trap_opcode_bytes = g_i386_opcode;
2929af245d11STodd Fiala         actual_opcode_size = sizeof(g_i386_opcode);
2930af245d11STodd Fiala         return Error ();
2931af245d11STodd Fiala 
2932ce815e45SSagar Thakur     case llvm::Triple::mips:
29333df471c3SMohit K. Bhakkad     case llvm::Triple::mips64:
29343df471c3SMohit K. Bhakkad         trap_opcode_bytes = g_mips64_opcode;
29353df471c3SMohit K. Bhakkad         actual_opcode_size = sizeof(g_mips64_opcode);
29363df471c3SMohit K. Bhakkad         return Error ();
29373df471c3SMohit K. Bhakkad 
2938ce815e45SSagar Thakur     case llvm::Triple::mipsel:
29392c2acf96SMohit K. Bhakkad     case llvm::Triple::mips64el:
29402c2acf96SMohit K. Bhakkad         trap_opcode_bytes = g_mips64el_opcode;
29412c2acf96SMohit K. Bhakkad         actual_opcode_size = sizeof(g_mips64el_opcode);
29422c2acf96SMohit K. Bhakkad         return Error ();
29432c2acf96SMohit K. Bhakkad 
2944af245d11STodd Fiala     default:
2945af245d11STodd Fiala         assert(false && "CPU type not supported!");
2946af245d11STodd Fiala         return Error ("CPU type not supported");
2947af245d11STodd Fiala     }
2948af245d11STodd Fiala }
2949af245d11STodd Fiala 
2950af245d11STodd Fiala #if 0
2951af245d11STodd Fiala ProcessMessage::CrashReason
2952af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
2953af245d11STodd Fiala {
2954af245d11STodd Fiala     ProcessMessage::CrashReason reason;
2955af245d11STodd Fiala     assert(info->si_signo == SIGSEGV);
2956af245d11STodd Fiala 
2957af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
2958af245d11STodd Fiala 
2959af245d11STodd Fiala     switch (info->si_code)
2960af245d11STodd Fiala     {
2961af245d11STodd Fiala     default:
2962af245d11STodd Fiala         assert(false && "unexpected si_code for SIGSEGV");
2963af245d11STodd Fiala         break;
2964af245d11STodd Fiala     case SI_KERNEL:
2965af245d11STodd Fiala         // Linux will occasionally send spurious SI_KERNEL codes.
2966af245d11STodd Fiala         // (this is poorly documented in sigaction)
2967af245d11STodd Fiala         // One way to get this is via unaligned SIMD loads.
2968af245d11STodd Fiala         reason = ProcessMessage::eInvalidAddress; // for lack of anything better
2969af245d11STodd Fiala         break;
2970af245d11STodd Fiala     case SEGV_MAPERR:
2971af245d11STodd Fiala         reason = ProcessMessage::eInvalidAddress;
2972af245d11STodd Fiala         break;
2973af245d11STodd Fiala     case SEGV_ACCERR:
2974af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedAddress;
2975af245d11STodd Fiala         break;
2976af245d11STodd Fiala     }
2977af245d11STodd Fiala 
2978af245d11STodd Fiala     return reason;
2979af245d11STodd Fiala }
2980af245d11STodd Fiala #endif
2981af245d11STodd Fiala 
2982af245d11STodd Fiala 
2983af245d11STodd Fiala #if 0
2984af245d11STodd Fiala ProcessMessage::CrashReason
2985af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
2986af245d11STodd Fiala {
2987af245d11STodd Fiala     ProcessMessage::CrashReason reason;
2988af245d11STodd Fiala     assert(info->si_signo == SIGILL);
2989af245d11STodd Fiala 
2990af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
2991af245d11STodd Fiala 
2992af245d11STodd Fiala     switch (info->si_code)
2993af245d11STodd Fiala     {
2994af245d11STodd Fiala     default:
2995af245d11STodd Fiala         assert(false && "unexpected si_code for SIGILL");
2996af245d11STodd Fiala         break;
2997af245d11STodd Fiala     case ILL_ILLOPC:
2998af245d11STodd Fiala         reason = ProcessMessage::eIllegalOpcode;
2999af245d11STodd Fiala         break;
3000af245d11STodd Fiala     case ILL_ILLOPN:
3001af245d11STodd Fiala         reason = ProcessMessage::eIllegalOperand;
3002af245d11STodd Fiala         break;
3003af245d11STodd Fiala     case ILL_ILLADR:
3004af245d11STodd Fiala         reason = ProcessMessage::eIllegalAddressingMode;
3005af245d11STodd Fiala         break;
3006af245d11STodd Fiala     case ILL_ILLTRP:
3007af245d11STodd Fiala         reason = ProcessMessage::eIllegalTrap;
3008af245d11STodd Fiala         break;
3009af245d11STodd Fiala     case ILL_PRVOPC:
3010af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedOpcode;
3011af245d11STodd Fiala         break;
3012af245d11STodd Fiala     case ILL_PRVREG:
3013af245d11STodd Fiala         reason = ProcessMessage::ePrivilegedRegister;
3014af245d11STodd Fiala         break;
3015af245d11STodd Fiala     case ILL_COPROC:
3016af245d11STodd Fiala         reason = ProcessMessage::eCoprocessorError;
3017af245d11STodd Fiala         break;
3018af245d11STodd Fiala     case ILL_BADSTK:
3019af245d11STodd Fiala         reason = ProcessMessage::eInternalStackError;
3020af245d11STodd Fiala         break;
3021af245d11STodd Fiala     }
3022af245d11STodd Fiala 
3023af245d11STodd Fiala     return reason;
3024af245d11STodd Fiala }
3025af245d11STodd Fiala #endif
3026af245d11STodd Fiala 
3027af245d11STodd Fiala #if 0
3028af245d11STodd Fiala ProcessMessage::CrashReason
3029af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
3030af245d11STodd Fiala {
3031af245d11STodd Fiala     ProcessMessage::CrashReason reason;
3032af245d11STodd Fiala     assert(info->si_signo == SIGFPE);
3033af245d11STodd Fiala 
3034af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
3035af245d11STodd Fiala 
3036af245d11STodd Fiala     switch (info->si_code)
3037af245d11STodd Fiala     {
3038af245d11STodd Fiala     default:
3039af245d11STodd Fiala         assert(false && "unexpected si_code for SIGFPE");
3040af245d11STodd Fiala         break;
3041af245d11STodd Fiala     case FPE_INTDIV:
3042af245d11STodd Fiala         reason = ProcessMessage::eIntegerDivideByZero;
3043af245d11STodd Fiala         break;
3044af245d11STodd Fiala     case FPE_INTOVF:
3045af245d11STodd Fiala         reason = ProcessMessage::eIntegerOverflow;
3046af245d11STodd Fiala         break;
3047af245d11STodd Fiala     case FPE_FLTDIV:
3048af245d11STodd Fiala         reason = ProcessMessage::eFloatDivideByZero;
3049af245d11STodd Fiala         break;
3050af245d11STodd Fiala     case FPE_FLTOVF:
3051af245d11STodd Fiala         reason = ProcessMessage::eFloatOverflow;
3052af245d11STodd Fiala         break;
3053af245d11STodd Fiala     case FPE_FLTUND:
3054af245d11STodd Fiala         reason = ProcessMessage::eFloatUnderflow;
3055af245d11STodd Fiala         break;
3056af245d11STodd Fiala     case FPE_FLTRES:
3057af245d11STodd Fiala         reason = ProcessMessage::eFloatInexactResult;
3058af245d11STodd Fiala         break;
3059af245d11STodd Fiala     case FPE_FLTINV:
3060af245d11STodd Fiala         reason = ProcessMessage::eFloatInvalidOperation;
3061af245d11STodd Fiala         break;
3062af245d11STodd Fiala     case FPE_FLTSUB:
3063af245d11STodd Fiala         reason = ProcessMessage::eFloatSubscriptRange;
3064af245d11STodd Fiala         break;
3065af245d11STodd Fiala     }
3066af245d11STodd Fiala 
3067af245d11STodd Fiala     return reason;
3068af245d11STodd Fiala }
3069af245d11STodd Fiala #endif
3070af245d11STodd Fiala 
3071af245d11STodd Fiala #if 0
3072af245d11STodd Fiala ProcessMessage::CrashReason
3073af245d11STodd Fiala NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
3074af245d11STodd Fiala {
3075af245d11STodd Fiala     ProcessMessage::CrashReason reason;
3076af245d11STodd Fiala     assert(info->si_signo == SIGBUS);
3077af245d11STodd Fiala 
3078af245d11STodd Fiala     reason = ProcessMessage::eInvalidCrashReason;
3079af245d11STodd Fiala 
3080af245d11STodd Fiala     switch (info->si_code)
3081af245d11STodd Fiala     {
3082af245d11STodd Fiala     default:
3083af245d11STodd Fiala         assert(false && "unexpected si_code for SIGBUS");
3084af245d11STodd Fiala         break;
3085af245d11STodd Fiala     case BUS_ADRALN:
3086af245d11STodd Fiala         reason = ProcessMessage::eIllegalAlignment;
3087af245d11STodd Fiala         break;
3088af245d11STodd Fiala     case BUS_ADRERR:
3089af245d11STodd Fiala         reason = ProcessMessage::eIllegalAddress;
3090af245d11STodd Fiala         break;
3091af245d11STodd Fiala     case BUS_OBJERR:
3092af245d11STodd Fiala         reason = ProcessMessage::eHardwareError;
3093af245d11STodd Fiala         break;
3094af245d11STodd Fiala     }
3095af245d11STodd Fiala 
3096af245d11STodd Fiala     return reason;
3097af245d11STodd Fiala }
3098af245d11STodd Fiala #endif
3099af245d11STodd Fiala 
3100af245d11STodd Fiala Error
310145f5cb31SPavel Labath NativeProcessLinux::SetWatchpoint (lldb::addr_t addr, size_t size, uint32_t watch_flags, bool hardware)
310245f5cb31SPavel Labath {
310345f5cb31SPavel Labath     // The base SetWatchpoint will end up executing monitor operations. Let's lock the monitor
310445f5cb31SPavel Labath     // for it.
310545f5cb31SPavel Labath     Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
310645f5cb31SPavel Labath     return NativeProcessProtocol::SetWatchpoint(addr, size, watch_flags, hardware);
310745f5cb31SPavel Labath }
310845f5cb31SPavel Labath 
310945f5cb31SPavel Labath Error
311045f5cb31SPavel Labath NativeProcessLinux::RemoveWatchpoint (lldb::addr_t addr)
311145f5cb31SPavel Labath {
311245f5cb31SPavel Labath     // The base RemoveWatchpoint will end up executing monitor operations. Let's lock the monitor
311345f5cb31SPavel Labath     // for it.
311445f5cb31SPavel Labath     Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
311545f5cb31SPavel Labath     return NativeProcessProtocol::RemoveWatchpoint(addr);
311645f5cb31SPavel Labath }
311745f5cb31SPavel Labath 
311845f5cb31SPavel Labath Error
311926438d26SChaoren Lin NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
3120af245d11STodd Fiala {
3121df7c6995SPavel Labath     if (ProcessVmReadvSupported()) {
3122df7c6995SPavel Labath         // The process_vm_readv path is about 50 times faster than ptrace api. We want to use
3123df7c6995SPavel Labath         // this syscall if it is supported.
3124df7c6995SPavel Labath 
3125df7c6995SPavel Labath         const ::pid_t pid = GetID();
3126df7c6995SPavel Labath 
3127df7c6995SPavel Labath         struct iovec local_iov, remote_iov;
3128df7c6995SPavel Labath         local_iov.iov_base = buf;
3129df7c6995SPavel Labath         local_iov.iov_len = size;
3130df7c6995SPavel Labath         remote_iov.iov_base = reinterpret_cast<void *>(addr);
3131df7c6995SPavel Labath         remote_iov.iov_len = size;
3132df7c6995SPavel Labath 
3133df7c6995SPavel Labath         bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
3134df7c6995SPavel Labath         const bool success = bytes_read == size;
3135df7c6995SPavel Labath 
3136df7c6995SPavel Labath         Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3137df7c6995SPavel Labath         if (log)
3138df7c6995SPavel Labath             log->Printf ("NativeProcessLinux::%s using process_vm_readv to read %zd bytes from inferior address 0x%" PRIx64": %s",
3139df7c6995SPavel Labath                     __FUNCTION__, size, addr, success ? "Success" : strerror(errno));
3140df7c6995SPavel Labath 
3141df7c6995SPavel Labath         if (success)
3142df7c6995SPavel Labath             return Error();
3143df7c6995SPavel Labath         // else
3144df7c6995SPavel Labath         //     the call failed for some reason, let's retry the read using ptrace api.
3145df7c6995SPavel Labath     }
3146df7c6995SPavel Labath 
3147c7512fdcSPavel Labath     return DoOperation([&] { return DoReadMemory(GetID(), addr, buf, size, bytes_read); });
3148af245d11STodd Fiala }
3149af245d11STodd Fiala 
3150af245d11STodd Fiala Error
31513eb4b458SChaoren Lin NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
31523eb4b458SChaoren Lin {
31533eb4b458SChaoren Lin     Error error = ReadMemory(addr, buf, size, bytes_read);
31543eb4b458SChaoren Lin     if (error.Fail()) return error;
31553eb4b458SChaoren Lin     return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
31563eb4b458SChaoren Lin }
31573eb4b458SChaoren Lin 
31583eb4b458SChaoren Lin Error
31593eb4b458SChaoren Lin NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written)
3160af245d11STodd Fiala {
3161c7512fdcSPavel Labath     return DoOperation([&] { return DoWriteMemory(GetID(), addr, buf, size, bytes_written); });
3162af245d11STodd Fiala }
3163af245d11STodd Fiala 
316497ccc294SChaoren Lin Error
3165af245d11STodd Fiala NativeProcessLinux::Resume (lldb::tid_t tid, uint32_t signo)
3166af245d11STodd Fiala {
3167af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3168af245d11STodd Fiala 
3169af245d11STodd Fiala     if (log)
3170af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s() resuming thread = %"  PRIu64 " with signal %s", __FUNCTION__, tid,
3171*98d0a4b3SChaoren Lin                                  Host::GetSignalAsCString(signo));
3172c7512fdcSPavel Labath 
3173c7512fdcSPavel Labath 
3174c7512fdcSPavel Labath 
3175c7512fdcSPavel Labath     intptr_t data = 0;
3176c7512fdcSPavel Labath 
3177c7512fdcSPavel Labath     if (signo != LLDB_INVALID_SIGNAL_NUMBER)
3178c7512fdcSPavel Labath         data = signo;
3179c7512fdcSPavel Labath 
31804a9babb2SPavel Labath     Error error = DoOperation([&] { return PtraceWrapper(PTRACE_CONT, tid, nullptr, (void*)data); });
3181c7512fdcSPavel Labath 
3182af245d11STodd Fiala     if (log)
3183c7512fdcSPavel Labath         log->Printf ("NativeProcessLinux::%s() resuming thread = %"  PRIu64 " result = %s", __FUNCTION__, tid, error.Success() ? "true" : "false");
3184c7512fdcSPavel Labath     return error;
3185af245d11STodd Fiala }
3186af245d11STodd Fiala 
318797ccc294SChaoren Lin Error
3188af245d11STodd Fiala NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo)
3189af245d11STodd Fiala {
3190c7512fdcSPavel Labath     intptr_t data = 0;
3191c7512fdcSPavel Labath 
3192c7512fdcSPavel Labath     if (signo != LLDB_INVALID_SIGNAL_NUMBER)
3193c7512fdcSPavel Labath         data = signo;
3194c7512fdcSPavel Labath 
31954a9babb2SPavel Labath     return DoOperation([&] { return PtraceWrapper(PTRACE_SINGLESTEP, tid, nullptr, (void*)data); });
3196af245d11STodd Fiala }
3197af245d11STodd Fiala 
319897ccc294SChaoren Lin Error
319997ccc294SChaoren Lin NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
3200af245d11STodd Fiala {
32014a9babb2SPavel Labath     return DoOperation([&] { return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo); });
3202af245d11STodd Fiala }
3203af245d11STodd Fiala 
320497ccc294SChaoren Lin Error
3205af245d11STodd Fiala NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
3206af245d11STodd Fiala {
32074a9babb2SPavel Labath     return DoOperation([&] { return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message); });
3208af245d11STodd Fiala }
3209af245d11STodd Fiala 
3210db264a6dSTamas Berghammer Error
3211af245d11STodd Fiala NativeProcessLinux::Detach(lldb::tid_t tid)
3212af245d11STodd Fiala {
321397ccc294SChaoren Lin     if (tid == LLDB_INVALID_THREAD_ID)
321497ccc294SChaoren Lin         return Error();
321597ccc294SChaoren Lin 
32164a9babb2SPavel Labath     return DoOperation([&] { return PtraceWrapper(PTRACE_DETACH, tid); });
3217af245d11STodd Fiala }
3218af245d11STodd Fiala 
3219af245d11STodd Fiala bool
3220d3173f34SChaoren Lin NativeProcessLinux::DupDescriptor(const FileSpec &file_spec, int fd, int flags)
3221af245d11STodd Fiala {
3222d3173f34SChaoren Lin     int target_fd = open(file_spec.GetCString(), flags, 0666);
3223af245d11STodd Fiala 
3224af245d11STodd Fiala     if (target_fd == -1)
3225af245d11STodd Fiala         return false;
3226af245d11STodd Fiala 
3227493c3a12SPavel Labath     if (dup2(target_fd, fd) == -1)
3228493c3a12SPavel Labath         return false;
3229493c3a12SPavel Labath 
3230493c3a12SPavel Labath     return (close(target_fd) == -1) ? false : true;
3231af245d11STodd Fiala }
3232af245d11STodd Fiala 
3233af245d11STodd Fiala void
3234bd7cbc5aSPavel Labath NativeProcessLinux::StartMonitorThread(const InitialOperation &initial_operation, Error &error)
3235af245d11STodd Fiala {
3236bd7cbc5aSPavel Labath     m_monitor_up.reset(new Monitor(initial_operation, this));
32371107b5a5SPavel Labath     error = m_monitor_up->Initialize();
32381107b5a5SPavel Labath     if (error.Fail()) {
32391107b5a5SPavel Labath         m_monitor_up.reset();
3240af245d11STodd Fiala     }
3241af245d11STodd Fiala }
3242af245d11STodd Fiala 
3243af245d11STodd Fiala bool
3244af245d11STodd Fiala NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
3245af245d11STodd Fiala {
3246af245d11STodd Fiala     for (auto thread_sp : m_threads)
3247af245d11STodd Fiala     {
3248af245d11STodd Fiala         assert (thread_sp && "thread list should not contain NULL threads");
3249af245d11STodd Fiala         if (thread_sp->GetID () == thread_id)
3250af245d11STodd Fiala         {
3251af245d11STodd Fiala             // We have this thread.
3252af245d11STodd Fiala             return true;
3253af245d11STodd Fiala         }
3254af245d11STodd Fiala     }
3255af245d11STodd Fiala 
3256af245d11STodd Fiala     // We don't have this thread.
3257af245d11STodd Fiala     return false;
3258af245d11STodd Fiala }
3259af245d11STodd Fiala 
3260af245d11STodd Fiala NativeThreadProtocolSP
3261af245d11STodd Fiala NativeProcessLinux::MaybeGetThreadNoLock (lldb::tid_t thread_id)
3262af245d11STodd Fiala {
3263af245d11STodd Fiala     // CONSIDER organize threads by map - we can do better than linear.
3264af245d11STodd Fiala     for (auto thread_sp : m_threads)
3265af245d11STodd Fiala     {
3266af245d11STodd Fiala         if (thread_sp->GetID () == thread_id)
3267af245d11STodd Fiala             return thread_sp;
3268af245d11STodd Fiala     }
3269af245d11STodd Fiala 
3270af245d11STodd Fiala     // We don't have this thread.
3271af245d11STodd Fiala     return NativeThreadProtocolSP ();
3272af245d11STodd Fiala }
3273af245d11STodd Fiala 
3274af245d11STodd Fiala bool
3275af245d11STodd Fiala NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
3276af245d11STodd Fiala {
32771dbc6c9cSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
32781dbc6c9cSPavel Labath 
32791dbc6c9cSPavel Labath     if (log)
32801dbc6c9cSPavel Labath         log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, thread_id);
32811dbc6c9cSPavel Labath 
32821dbc6c9cSPavel Labath     bool found = false;
32831dbc6c9cSPavel Labath 
3284af245d11STodd Fiala     Mutex::Locker locker (m_threads_mutex);
3285af245d11STodd Fiala     for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
3286af245d11STodd Fiala     {
3287af245d11STodd Fiala         if (*it && ((*it)->GetID () == thread_id))
3288af245d11STodd Fiala         {
3289af245d11STodd Fiala             m_threads.erase (it);
32901dbc6c9cSPavel Labath             found = true;
32911dbc6c9cSPavel Labath             break;
3292af245d11STodd Fiala         }
3293af245d11STodd Fiala     }
3294af245d11STodd Fiala 
32951dbc6c9cSPavel Labath     // If we have a pending notification, remove this from the set.
32961dbc6c9cSPavel Labath     if (m_pending_notification_up)
32971dbc6c9cSPavel Labath     {
32981dbc6c9cSPavel Labath         m_pending_notification_up->wait_for_stop_tids.erase(thread_id);
32999eb1ecb9SPavel Labath         SignalIfAllThreadsStopped();
33001dbc6c9cSPavel Labath     }
33011dbc6c9cSPavel Labath 
33021dbc6c9cSPavel Labath     return found;
3303af245d11STodd Fiala }
3304af245d11STodd Fiala 
3305af245d11STodd Fiala NativeThreadProtocolSP
3306af245d11STodd Fiala NativeProcessLinux::AddThread (lldb::tid_t thread_id)
3307af245d11STodd Fiala {
3308af245d11STodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3309af245d11STodd Fiala 
3310af245d11STodd Fiala     Mutex::Locker locker (m_threads_mutex);
3311af245d11STodd Fiala 
3312af245d11STodd Fiala     if (log)
3313af245d11STodd Fiala     {
3314af245d11STodd Fiala         log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
3315af245d11STodd Fiala                 __FUNCTION__,
3316af245d11STodd Fiala                 GetID (),
3317af245d11STodd Fiala                 thread_id);
3318af245d11STodd Fiala     }
3319af245d11STodd Fiala 
3320af245d11STodd Fiala     assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
3321af245d11STodd Fiala 
3322af245d11STodd Fiala     // If this is the first thread, save it as the current thread
3323af245d11STodd Fiala     if (m_threads.empty ())
3324af245d11STodd Fiala         SetCurrentThreadID (thread_id);
3325af245d11STodd Fiala 
3326af245d11STodd Fiala     NativeThreadProtocolSP thread_sp (new NativeThreadLinux (this, thread_id));
3327af245d11STodd Fiala     m_threads.push_back (thread_sp);
3328af245d11STodd Fiala 
3329af245d11STodd Fiala     return thread_sp;
3330af245d11STodd Fiala }
3331af245d11STodd Fiala 
3332af245d11STodd Fiala Error
3333af245d11STodd Fiala NativeProcessLinux::FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp)
3334af245d11STodd Fiala {
333575f47c3aSTodd Fiala     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
3336af245d11STodd Fiala 
3337af245d11STodd Fiala     Error error;
3338af245d11STodd Fiala 
3339af245d11STodd Fiala     // Get a linux thread pointer.
3340af245d11STodd Fiala     if (!thread_sp)
3341af245d11STodd Fiala     {
3342af245d11STodd Fiala         error.SetErrorString ("null thread_sp");
3343af245d11STodd Fiala         if (log)
3344af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
3345af245d11STodd Fiala         return error;
3346af245d11STodd Fiala     }
3347cb84eebbSTamas Berghammer     std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
3348af245d11STodd Fiala 
3349af245d11STodd Fiala     // Find out the size of a breakpoint (might depend on where we are in the code).
3350cb84eebbSTamas Berghammer     NativeRegisterContextSP context_sp = linux_thread_sp->GetRegisterContext ();
3351af245d11STodd Fiala     if (!context_sp)
3352af245d11STodd Fiala     {
3353af245d11STodd Fiala         error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
3354af245d11STodd Fiala         if (log)
3355af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
3356af245d11STodd Fiala         return error;
3357af245d11STodd Fiala     }
3358af245d11STodd Fiala 
3359af245d11STodd Fiala     uint32_t breakpoint_size = 0;
336063c8be95STamas Berghammer     error = GetSoftwareBreakpointPCOffset (context_sp, breakpoint_size);
3361af245d11STodd Fiala     if (error.Fail ())
3362af245d11STodd Fiala     {
3363af245d11STodd Fiala         if (log)
3364af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
3365af245d11STodd Fiala         return error;
3366af245d11STodd Fiala     }
3367af245d11STodd Fiala     else
3368af245d11STodd Fiala     {
3369af245d11STodd Fiala         if (log)
3370af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
3371af245d11STodd Fiala     }
3372af245d11STodd Fiala 
3373af245d11STodd Fiala     // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
3374c60c9452SJaydeep Patil     const lldb::addr_t initial_pc_addr = context_sp->GetPCfromBreakpointLocation ();
3375af245d11STodd Fiala     lldb::addr_t breakpoint_addr = initial_pc_addr;
33763eb4b458SChaoren Lin     if (breakpoint_size > 0)
3377af245d11STodd Fiala     {
3378af245d11STodd Fiala         // Do not allow breakpoint probe to wrap around.
33793eb4b458SChaoren Lin         if (breakpoint_addr >= breakpoint_size)
33803eb4b458SChaoren Lin             breakpoint_addr -= breakpoint_size;
3381af245d11STodd Fiala     }
3382af245d11STodd Fiala 
3383af245d11STodd Fiala     // Check if we stopped because of a breakpoint.
3384af245d11STodd Fiala     NativeBreakpointSP breakpoint_sp;
3385af245d11STodd Fiala     error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
3386af245d11STodd Fiala     if (!error.Success () || !breakpoint_sp)
3387af245d11STodd Fiala     {
3388af245d11STodd Fiala         // We didn't find one at a software probe location.  Nothing to do.
3389af245d11STodd Fiala         if (log)
3390af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
3391af245d11STodd Fiala         return Error ();
3392af245d11STodd Fiala     }
3393af245d11STodd Fiala 
3394af245d11STodd Fiala     // If the breakpoint is not a software breakpoint, nothing to do.
3395af245d11STodd Fiala     if (!breakpoint_sp->IsSoftwareBreakpoint ())
3396af245d11STodd Fiala     {
3397af245d11STodd Fiala         if (log)
3398af245d11STodd Fiala             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
3399af245d11STodd Fiala         return Error ();
3400af245d11STodd Fiala     }
3401af245d11STodd Fiala 
3402af245d11STodd Fiala     //
3403af245d11STodd Fiala     // We have a software breakpoint and need to adjust the PC.
3404af245d11STodd Fiala     //
3405af245d11STodd Fiala 
3406af245d11STodd Fiala     // Sanity check.
3407af245d11STodd Fiala     if (breakpoint_size == 0)
3408af245d11STodd Fiala     {
3409af245d11STodd Fiala         // Nothing to do!  How did we get here?
3410af245d11STodd Fiala         if (log)
3411af245d11STodd 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);
3412af245d11STodd Fiala         return Error ();
3413af245d11STodd Fiala     }
3414af245d11STodd Fiala 
3415af245d11STodd Fiala     // Change the program counter.
3416af245d11STodd Fiala     if (log)
3417cb84eebbSTamas 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);
3418af245d11STodd Fiala 
3419af245d11STodd Fiala     error = context_sp->SetPC (breakpoint_addr);
3420af245d11STodd Fiala     if (error.Fail ())
3421af245d11STodd Fiala     {
3422af245d11STodd Fiala         if (log)
3423cb84eebbSTamas Berghammer             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": failed to set PC: %s", __FUNCTION__, GetID (), linux_thread_sp->GetID (), error.AsCString ());
3424af245d11STodd Fiala         return error;
3425af245d11STodd Fiala     }
3426af245d11STodd Fiala 
3427af245d11STodd Fiala     return error;
3428af245d11STodd Fiala }
3429fa03ad2eSChaoren Lin 
34307cb18bf5STamas Berghammer Error
34317cb18bf5STamas Berghammer NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec)
34327cb18bf5STamas Berghammer {
34337cb18bf5STamas Berghammer     char maps_file_name[32];
34347cb18bf5STamas Berghammer     snprintf(maps_file_name, sizeof(maps_file_name), "/proc/%" PRIu64 "/maps", GetID());
34357cb18bf5STamas Berghammer 
34367cb18bf5STamas Berghammer     FileSpec maps_file_spec(maps_file_name, false);
34377cb18bf5STamas Berghammer     if (!maps_file_spec.Exists()) {
34387cb18bf5STamas Berghammer         file_spec.Clear();
34397cb18bf5STamas Berghammer         return Error("/proc/%" PRIu64 "/maps file doesn't exists!", GetID());
34407cb18bf5STamas Berghammer     }
34417cb18bf5STamas Berghammer 
34427cb18bf5STamas Berghammer     FileSpec module_file_spec(module_path, true);
34437cb18bf5STamas Berghammer 
34447cb18bf5STamas Berghammer     std::ifstream maps_file(maps_file_name);
34457cb18bf5STamas Berghammer     std::string maps_data_str((std::istreambuf_iterator<char>(maps_file)), std::istreambuf_iterator<char>());
34467cb18bf5STamas Berghammer     StringRef maps_data(maps_data_str.c_str());
34477cb18bf5STamas Berghammer 
34487cb18bf5STamas Berghammer     while (!maps_data.empty())
34497cb18bf5STamas Berghammer     {
34507cb18bf5STamas Berghammer         StringRef maps_row;
34517cb18bf5STamas Berghammer         std::tie(maps_row, maps_data) = maps_data.split('\n');
34527cb18bf5STamas Berghammer 
34537cb18bf5STamas Berghammer         SmallVector<StringRef, 16> maps_columns;
34547cb18bf5STamas Berghammer         maps_row.split(maps_columns, StringRef(" "), -1, false);
34557cb18bf5STamas Berghammer 
34567cb18bf5STamas Berghammer         if (maps_columns.size() >= 6)
34577cb18bf5STamas Berghammer         {
34587cb18bf5STamas Berghammer             file_spec.SetFile(maps_columns[5].str().c_str(), false);
34597cb18bf5STamas Berghammer             if (file_spec.GetFilename() == module_file_spec.GetFilename())
34607cb18bf5STamas Berghammer                 return Error();
34617cb18bf5STamas Berghammer         }
34627cb18bf5STamas Berghammer     }
34637cb18bf5STamas Berghammer 
34647cb18bf5STamas Berghammer     file_spec.Clear();
34657cb18bf5STamas Berghammer     return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
34667cb18bf5STamas Berghammer                  module_file_spec.GetFilename().AsCString(), GetID());
34677cb18bf5STamas Berghammer }
3468c076559aSPavel Labath 
34695eb721edSPavel Labath Error
3470783bfc8cSTamas Berghammer NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef& file_name, lldb::addr_t& load_addr)
3471783bfc8cSTamas Berghammer {
3472783bfc8cSTamas Berghammer     load_addr = LLDB_INVALID_ADDRESS;
3473783bfc8cSTamas Berghammer     Error error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
3474783bfc8cSTamas Berghammer         [&] (const std::string &line) -> bool
3475783bfc8cSTamas Berghammer         {
3476783bfc8cSTamas Berghammer             StringRef maps_row(line);
3477783bfc8cSTamas Berghammer 
3478783bfc8cSTamas Berghammer             SmallVector<StringRef, 16> maps_columns;
3479783bfc8cSTamas Berghammer             maps_row.split(maps_columns, StringRef(" "), -1, false);
3480783bfc8cSTamas Berghammer 
3481783bfc8cSTamas Berghammer             if (maps_columns.size() < 6)
3482783bfc8cSTamas Berghammer             {
3483783bfc8cSTamas Berghammer                 // Return true to continue reading the proc file
3484783bfc8cSTamas Berghammer                 return true;
3485783bfc8cSTamas Berghammer             }
3486783bfc8cSTamas Berghammer 
3487783bfc8cSTamas Berghammer             if (maps_columns[5] == file_name)
3488783bfc8cSTamas Berghammer             {
3489783bfc8cSTamas Berghammer                 StringExtractor addr_extractor(maps_columns[0].str().c_str());
3490783bfc8cSTamas Berghammer                 load_addr = addr_extractor.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
3491783bfc8cSTamas Berghammer 
3492783bfc8cSTamas Berghammer                 // Return false to stop reading the proc file further
3493783bfc8cSTamas Berghammer                 return false;
3494783bfc8cSTamas Berghammer             }
3495783bfc8cSTamas Berghammer 
3496783bfc8cSTamas Berghammer             // Return true to continue reading the proc file
3497783bfc8cSTamas Berghammer             return true;
3498783bfc8cSTamas Berghammer         });
3499783bfc8cSTamas Berghammer     return error;
3500783bfc8cSTamas Berghammer }
3501783bfc8cSTamas Berghammer 
3502783bfc8cSTamas Berghammer Error
35031dbc6c9cSPavel Labath NativeProcessLinux::ResumeThread(
3504c076559aSPavel Labath         lldb::tid_t tid,
35058c8ff7afSPavel Labath         NativeThreadLinux::ResumeThreadFunction request_thread_resume_function,
3506c076559aSPavel Labath         bool error_when_already_running)
3507c076559aSPavel Labath {
35085eb721edSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
35095eb721edSPavel Labath 
35101dbc6c9cSPavel Labath     if (log)
35111dbc6c9cSPavel Labath         log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ", error_when_already_running: %s)",
35121dbc6c9cSPavel Labath                 __FUNCTION__, tid, error_when_already_running?"true":"false");
35131dbc6c9cSPavel Labath 
35148c8ff7afSPavel Labath     auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
35158c8ff7afSPavel Labath     lldbassert(thread_sp != nullptr);
35165eb721edSPavel Labath 
35178c8ff7afSPavel Labath     auto& context = thread_sp->GetThreadContext();
3518c076559aSPavel Labath     // Tell the thread to resume if we don't already think it is running.
35198c8ff7afSPavel Labath     const bool is_stopped = StateIsStoppedState(thread_sp->GetState(), true);
35205eb721edSPavel Labath 
35215eb721edSPavel Labath     lldbassert(!(error_when_already_running && !is_stopped));
35225eb721edSPavel Labath 
3523c076559aSPavel Labath     if (!is_stopped)
3524c076559aSPavel Labath     {
3525c076559aSPavel Labath         // It's not an error, just a log, if the error_when_already_running flag is not set.
3526c076559aSPavel Labath         // This covers cases where, for instance, we're just trying to resume all threads
3527c076559aSPavel Labath         // from the user side.
35285eb721edSPavel Labath         if (log)
35295eb721edSPavel Labath             log->Printf("NativeProcessLinux::%s tid %" PRIu64 " optional resume skipped since it is already running",
3530c076559aSPavel Labath                     __FUNCTION__,
3531c076559aSPavel Labath                     tid);
35325eb721edSPavel Labath         return Error();
3533c076559aSPavel Labath     }
3534c076559aSPavel Labath 
3535c076559aSPavel Labath     // Before we do the resume below, first check if we have a pending
3536108c325dSPavel Labath     // stop notification that is currently waiting for
3537c076559aSPavel Labath     // this thread to stop.  This is potentially a buggy situation since
3538c076559aSPavel Labath     // we're ostensibly waiting for threads to stop before we send out the
3539c076559aSPavel Labath     // pending notification, and here we are resuming one before we send
3540c076559aSPavel Labath     // out the pending stop notification.
3541108c325dSPavel Labath     if (m_pending_notification_up && log && m_pending_notification_up->wait_for_stop_tids.count (tid) > 0)
3542c076559aSPavel Labath     {
35435eb721edSPavel 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);
3544c076559aSPavel Labath     }
3545c076559aSPavel Labath 
3546c076559aSPavel Labath     // Request a resume.  We expect this to be synchronous and the system
3547c076559aSPavel Labath     // to reflect it is running after this completes.
3548c076559aSPavel Labath     const auto error = request_thread_resume_function (tid, false);
3549c076559aSPavel Labath     if (error.Success())
35508c8ff7afSPavel Labath         context.request_resume_function = request_thread_resume_function;
35515eb721edSPavel Labath     else if (log)
3552c076559aSPavel Labath     {
35535eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s failed to resume thread tid  %" PRIu64 ": %s",
3554c076559aSPavel Labath                          __FUNCTION__, tid, error.AsCString ());
3555c076559aSPavel Labath     }
3556c076559aSPavel Labath 
35575eb721edSPavel Labath     return error;
3558c076559aSPavel Labath }
3559c076559aSPavel Labath 
3560c076559aSPavel Labath //===----------------------------------------------------------------------===//
3561c076559aSPavel Labath 
3562c076559aSPavel Labath void
3563337f3eb9SPavel Labath NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid)
3564c076559aSPavel Labath {
35655eb721edSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3566c076559aSPavel Labath 
35675eb721edSPavel Labath     if (log)
3568c076559aSPavel Labath     {
35695eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ")",
3570c076559aSPavel Labath                 __FUNCTION__, triggering_tid);
3571c076559aSPavel Labath     }
3572c076559aSPavel Labath 
3573337f3eb9SPavel Labath     DoStopThreads(PendingNotificationUP(new PendingNotification(triggering_tid)));
3574c076559aSPavel Labath 
35755eb721edSPavel Labath     if (log)
3576c076559aSPavel Labath     {
35775eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
3578c076559aSPavel Labath     }
3579c076559aSPavel Labath }
3580c076559aSPavel Labath 
3581c076559aSPavel Labath void
35829eb1ecb9SPavel Labath NativeProcessLinux::SignalIfAllThreadsStopped()
3583c076559aSPavel Labath {
3584c076559aSPavel Labath     if (m_pending_notification_up && m_pending_notification_up->wait_for_stop_tids.empty ())
3585c076559aSPavel Labath     {
35869eb1ecb9SPavel Labath         Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
35879eb1ecb9SPavel Labath 
35889eb1ecb9SPavel Labath         // Clear any temporary breakpoints we used to implement software single stepping.
35899eb1ecb9SPavel Labath         for (const auto &thread_info: m_threads_stepping_with_breakpoint)
35909eb1ecb9SPavel Labath         {
35919eb1ecb9SPavel Labath             Error error = RemoveBreakpoint (thread_info.second);
35929eb1ecb9SPavel Labath             if (error.Fail())
35939eb1ecb9SPavel Labath                 if (log)
35949eb1ecb9SPavel Labath                     log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " remove stepping breakpoint: %s",
35959eb1ecb9SPavel Labath                             __FUNCTION__, thread_info.first, error.AsCString());
35969eb1ecb9SPavel Labath         }
35979eb1ecb9SPavel Labath         m_threads_stepping_with_breakpoint.clear();
35989eb1ecb9SPavel Labath 
35999eb1ecb9SPavel Labath         // Notify the delegate about the stop
3600ed89c7feSPavel Labath         SetCurrentThreadID(m_pending_notification_up->triggering_tid);
3601ed89c7feSPavel Labath         SetState(StateType::eStateStopped, true);
3602c076559aSPavel Labath         m_pending_notification_up.reset();
3603c076559aSPavel Labath     }
3604c076559aSPavel Labath }
3605c076559aSPavel Labath 
3606c076559aSPavel Labath void
3607c076559aSPavel Labath NativeProcessLinux::RequestStopOnAllRunningThreads()
3608c076559aSPavel Labath {
3609c076559aSPavel Labath     // Request a stop for all the thread stops that need to be stopped
3610c076559aSPavel Labath     // and are not already known to be stopped.  Keep a list of all the
3611c076559aSPavel Labath     // threads from which we still need to hear a stop reply.
3612c076559aSPavel Labath 
3613c076559aSPavel Labath     ThreadIDSet sent_tids;
36148c8ff7afSPavel Labath     for (const auto &thread_sp: m_threads)
3615c076559aSPavel Labath     {
36168c8ff7afSPavel Labath         // We only care about running threads
36178c8ff7afSPavel Labath         if (StateIsStoppedState(thread_sp->GetState(), true))
36188c8ff7afSPavel Labath             continue;
36198c8ff7afSPavel Labath 
36208c8ff7afSPavel Labath         static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
3621108c325dSPavel Labath         sent_tids.insert (thread_sp->GetID());
3622c076559aSPavel Labath     }
3623c076559aSPavel Labath 
3624c076559aSPavel Labath     // Set the wait list to the set of tids for which we requested stops.
3625c076559aSPavel Labath     m_pending_notification_up->wait_for_stop_tids.swap (sent_tids);
3626c076559aSPavel Labath }
3627c076559aSPavel Labath 
3628c076559aSPavel Labath 
36295eb721edSPavel Labath Error
36305eb721edSPavel Labath NativeProcessLinux::ThreadDidStop (lldb::tid_t tid, bool initiated_by_llgs)
3631c076559aSPavel Labath {
36321dbc6c9cSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
36331dbc6c9cSPavel Labath 
36341dbc6c9cSPavel Labath     if (log)
36351dbc6c9cSPavel Labath         log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ", %sinitiated by llgs)",
36361dbc6c9cSPavel Labath                 __FUNCTION__, tid, initiated_by_llgs?"":"not ");
36371dbc6c9cSPavel Labath 
3638c076559aSPavel Labath     // Ensure we know about the thread.
36398c8ff7afSPavel Labath     auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
36408c8ff7afSPavel Labath     lldbassert(thread_sp != nullptr);
3641c076559aSPavel Labath 
3642c076559aSPavel Labath     // Update the global list of known thread states.  This one is definitely stopped.
36438c8ff7afSPavel Labath     auto& context = thread_sp->GetThreadContext();
36448c8ff7afSPavel Labath     const auto stop_was_requested = context.stop_requested;
36458c8ff7afSPavel Labath     context.stop_requested = false;
3646c076559aSPavel Labath 
3647c076559aSPavel Labath     // If we have a pending notification, remove this from the set.
3648c076559aSPavel Labath     if (m_pending_notification_up)
3649c076559aSPavel Labath     {
3650c076559aSPavel Labath         m_pending_notification_up->wait_for_stop_tids.erase(tid);
36519eb1ecb9SPavel Labath         SignalIfAllThreadsStopped();
3652c076559aSPavel Labath     }
3653c076559aSPavel Labath 
36548c8ff7afSPavel Labath     Error error;
36558c8ff7afSPavel Labath     if (initiated_by_llgs && context.request_resume_function && !stop_was_requested)
3656c076559aSPavel Labath     {
3657c076559aSPavel Labath         // We can end up here if stop was initiated by LLGS but by this time a
3658c076559aSPavel Labath         // thread stop has occurred - maybe initiated by another event.
36595eb721edSPavel Labath         if (log)
36605eb721edSPavel Labath             log->Printf("Resuming thread %"  PRIu64 " since stop wasn't requested", tid);
36618c8ff7afSPavel Labath         error = context.request_resume_function (tid, true);
36628c8ff7afSPavel Labath         if (error.Fail() && log)
36635eb721edSPavel Labath         {
36645eb721edSPavel Labath                 log->Printf("NativeProcessLinux::%s failed to resume thread tid  %" PRIu64 ": %s",
3665c076559aSPavel Labath                         __FUNCTION__, tid, error.AsCString ());
3666c076559aSPavel Labath         }
36678c8ff7afSPavel Labath     }
36685eb721edSPavel Labath     return error;
3669c076559aSPavel Labath }
3670c076559aSPavel Labath 
3671c076559aSPavel Labath void
3672ed89c7feSPavel Labath NativeProcessLinux::DoStopThreads(PendingNotificationUP &&notification_up)
3673c076559aSPavel Labath {
36745eb721edSPavel Labath     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
36755eb721edSPavel Labath     if (m_pending_notification_up && log)
3676c076559aSPavel Labath     {
3677c076559aSPavel Labath         // Yikes - we've already got a pending signal notification in progress.
3678c076559aSPavel Labath         // Log this info.  We lose the pending notification here.
36795eb721edSPavel Labath         log->Printf("NativeProcessLinux::%s dropping existing pending signal notification for tid %" PRIu64 ", to be replaced with signal for tid %" PRIu64,
3680c076559aSPavel Labath                    __FUNCTION__,
3681c076559aSPavel Labath                    m_pending_notification_up->triggering_tid,
3682c076559aSPavel Labath                    notification_up->triggering_tid);
3683c076559aSPavel Labath     }
3684c076559aSPavel Labath     m_pending_notification_up = std::move(notification_up);
3685c076559aSPavel Labath 
3686c076559aSPavel Labath     RequestStopOnAllRunningThreads();
3687c076559aSPavel Labath 
36889eb1ecb9SPavel Labath     SignalIfAllThreadsStopped();
3689c076559aSPavel Labath }
3690c076559aSPavel Labath 
3691c076559aSPavel Labath void
36928c8ff7afSPavel Labath NativeProcessLinux::ThreadWasCreated (lldb::tid_t tid)
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 ")", __FUNCTION__, tid);
36981dbc6c9cSPavel Labath 
36998c8ff7afSPavel Labath     auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
37008c8ff7afSPavel Labath     lldbassert(thread_sp != nullptr);
3701c076559aSPavel Labath 
37028c8ff7afSPavel Labath     if (m_pending_notification_up && StateIsRunningState(thread_sp->GetState()))
3703c076559aSPavel Labath     {
3704c076559aSPavel Labath         // We will need to wait for this new thread to stop as well before firing the
3705c076559aSPavel Labath         // notification.
3706c076559aSPavel Labath         m_pending_notification_up->wait_for_stop_tids.insert(tid);
37078c8ff7afSPavel Labath         thread_sp->RequestStop();
3708c076559aSPavel Labath     }
3709c076559aSPavel Labath }
3710068f8a7eSTamas Berghammer 
3711068f8a7eSTamas Berghammer Error
3712c7512fdcSPavel Labath NativeProcessLinux::DoOperation(const Operation &op)
3713068f8a7eSTamas Berghammer {
3714c7512fdcSPavel Labath     return m_monitor_up->DoOperation(op);
3715068f8a7eSTamas Berghammer }
3716068f8a7eSTamas Berghammer 
3717068f8a7eSTamas Berghammer // Wrapper for ptrace to catch errors and log calls.
3718068f8a7eSTamas Berghammer // Note that ptrace sets errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
37194a9babb2SPavel Labath Error
37204a9babb2SPavel Labath NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, long *result)
3721068f8a7eSTamas Berghammer {
37224a9babb2SPavel Labath     Error error;
37234a9babb2SPavel Labath     long int ret;
3724068f8a7eSTamas Berghammer 
3725068f8a7eSTamas Berghammer     Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
3726068f8a7eSTamas Berghammer 
3727068f8a7eSTamas Berghammer     PtraceDisplayBytes(req, data, data_size);
3728068f8a7eSTamas Berghammer 
3729068f8a7eSTamas Berghammer     errno = 0;
3730068f8a7eSTamas Berghammer     if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
37314a9babb2SPavel Labath         ret = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
3732068f8a7eSTamas Berghammer     else
37334a9babb2SPavel Labath         ret = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
3734068f8a7eSTamas Berghammer 
37354a9babb2SPavel Labath     if (ret == -1)
3736068f8a7eSTamas Berghammer         error.SetErrorToErrno();
3737068f8a7eSTamas Berghammer 
37384a9babb2SPavel Labath     if (result)
37394a9babb2SPavel Labath         *result = ret;
37404a9babb2SPavel Labath 
3741068f8a7eSTamas Berghammer     if (log)
37424a9babb2SPavel Labath         log->Printf("ptrace(%d, %" PRIu64 ", %p, %p, %zu)=%lX", req, pid, addr, data, data_size, ret);
3743068f8a7eSTamas Berghammer 
3744068f8a7eSTamas Berghammer     PtraceDisplayBytes(req, data, data_size);
3745068f8a7eSTamas Berghammer 
3746068f8a7eSTamas Berghammer     if (log && error.GetError() != 0)
3747068f8a7eSTamas Berghammer     {
3748068f8a7eSTamas Berghammer         const char* str;
3749068f8a7eSTamas Berghammer         switch (error.GetError())
3750068f8a7eSTamas Berghammer         {
3751068f8a7eSTamas Berghammer         case ESRCH:  str = "ESRCH"; break;
3752068f8a7eSTamas Berghammer         case EINVAL: str = "EINVAL"; break;
3753068f8a7eSTamas Berghammer         case EBUSY:  str = "EBUSY"; break;
3754068f8a7eSTamas Berghammer         case EPERM:  str = "EPERM"; break;
3755068f8a7eSTamas Berghammer         default:     str = error.AsCString();
3756068f8a7eSTamas Berghammer         }
3757068f8a7eSTamas Berghammer         log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
3758068f8a7eSTamas Berghammer     }
3759068f8a7eSTamas Berghammer 
37604a9babb2SPavel Labath     return error;
3761068f8a7eSTamas Berghammer }
3762