1 //===-- NativeProcessLinux.cpp -------------------------------- -*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "lldb/lldb-python.h"
11 
12 #include "NativeProcessLinux.h"
13 
14 // C Includes
15 #include <errno.h>
16 #include <poll.h>
17 #include <string.h>
18 #include <stdint.h>
19 #include <unistd.h>
20 
21 // C++ Includes
22 #include <fstream>
23 #include <string>
24 
25 // Other libraries and framework includes
26 #include "lldb/Core/Debugger.h"
27 #include "lldb/Core/EmulateInstruction.h"
28 #include "lldb/Core/Error.h"
29 #include "lldb/Core/Module.h"
30 #include "lldb/Core/ModuleSpec.h"
31 #include "lldb/Core/RegisterValue.h"
32 #include "lldb/Core/Scalar.h"
33 #include "lldb/Core/State.h"
34 #include "lldb/Host/common/NativeBreakpoint.h"
35 #include "lldb/Host/common/NativeRegisterContext.h"
36 #include "lldb/Host/Host.h"
37 #include "lldb/Host/HostInfo.h"
38 #include "lldb/Host/HostNativeThread.h"
39 #include "lldb/Host/ThreadLauncher.h"
40 #include "lldb/Symbol/ObjectFile.h"
41 #include "lldb/Target/Process.h"
42 #include "lldb/Target/ProcessLaunchInfo.h"
43 #include "lldb/Utility/LLDBAssert.h"
44 #include "lldb/Utility/PseudoTerminal.h"
45 
46 #include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
47 #include "Plugins/Process/Utility/LinuxSignals.h"
48 #include "Utility/StringExtractor.h"
49 #include "NativeThreadLinux.h"
50 #include "ProcFileReader.h"
51 #include "Procfs.h"
52 #include "ThreadStateCoordinator.h"
53 
54 // System includes - They have to be included after framework includes because they define some
55 // macros which collide with variable names in other modules
56 #include <linux/unistd.h>
57 #include <sys/personality.h>
58 #include <sys/ptrace.h>
59 #include <sys/socket.h>
60 #include <sys/signalfd.h>
61 #include <sys/syscall.h>
62 #include <sys/types.h>
63 #include <sys/uio.h>
64 #include <sys/user.h>
65 #include <sys/wait.h>
66 
67 #if defined (__arm64__) || defined (__aarch64__)
68 // NT_PRSTATUS and NT_FPREGSET definition
69 #include <elf.h>
70 #endif
71 
72 #ifdef __ANDROID__
73 #define __ptrace_request int
74 #define PT_DETACH PTRACE_DETACH
75 #endif
76 
77 #define DEBUG_PTRACE_MAXBYTES 20
78 
79 // Support ptrace extensions even when compiled without required kernel support
80 #ifndef PT_GETREGS
81 #ifndef PTRACE_GETREGS
82   #define PTRACE_GETREGS 12
83 #endif
84 #endif
85 #ifndef PT_SETREGS
86 #ifndef PTRACE_SETREGS
87   #define PTRACE_SETREGS 13
88 #endif
89 #endif
90 #ifndef PT_GETFPREGS
91 #ifndef PTRACE_GETFPREGS
92   #define PTRACE_GETFPREGS 14
93 #endif
94 #endif
95 #ifndef PT_SETFPREGS
96 #ifndef PTRACE_SETFPREGS
97   #define PTRACE_SETFPREGS 15
98 #endif
99 #endif
100 #ifndef PTRACE_GETREGSET
101   #define PTRACE_GETREGSET 0x4204
102 #endif
103 #ifndef PTRACE_SETREGSET
104   #define PTRACE_SETREGSET 0x4205
105 #endif
106 #ifndef PTRACE_GET_THREAD_AREA
107   #define PTRACE_GET_THREAD_AREA 25
108 #endif
109 #ifndef PTRACE_ARCH_PRCTL
110   #define PTRACE_ARCH_PRCTL      30
111 #endif
112 #ifndef ARCH_GET_FS
113   #define ARCH_SET_GS 0x1001
114   #define ARCH_SET_FS 0x1002
115   #define ARCH_GET_FS 0x1003
116   #define ARCH_GET_GS 0x1004
117 #endif
118 
119 #define LLDB_PERSONALITY_GET_CURRENT_SETTINGS  0xffffffff
120 
121 // Support hardware breakpoints in case it has not been defined
122 #ifndef TRAP_HWBKPT
123   #define TRAP_HWBKPT 4
124 #endif
125 
126 // Try to define a macro to encapsulate the tgkill syscall
127 // fall back on kill() if tgkill isn't available
128 #define tgkill(pid, tid, sig) \
129     syscall(SYS_tgkill, static_cast<::pid_t>(pid), static_cast<::pid_t>(tid), sig)
130 
131 // We disable the tracing of ptrace calls for integration builds to
132 // avoid the additional indirection and checks.
133 #ifndef LLDB_CONFIGURATION_BUILDANDINTEGRATION
134 #define PTRACE(req, pid, addr, data, data_size, error) \
135     PtraceWrapper((req), (pid), (addr), (data), (data_size), (error), #req, __FILE__, __LINE__)
136 #else
137 #define PTRACE(req, pid, addr, data, data_size, error) \
138     PtraceWrapper((req), (pid), (addr), (data), (data_size), (error))
139 #endif
140 
141 using namespace lldb;
142 using namespace lldb_private;
143 using namespace lldb_private::process_linux;
144 using namespace llvm;
145 
146 // Private bits we only need internally.
147 namespace
148 {
149     static void * const EXIT_OPERATION = nullptr;
150 
151     const UnixSignals&
152     GetUnixSignals ()
153     {
154         static process_linux::LinuxSignals signals;
155         return signals;
156     }
157 
158     ThreadStateCoordinator::LogFunction
159     GetThreadLoggerFunction ()
160     {
161         return [](const char *format, va_list args)
162         {
163             Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
164             if (log)
165                 log->VAPrintf (format, args);
166         };
167     }
168 
169     void
170     CoordinatorErrorHandler (const std::string &error_message)
171     {
172         Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
173         if (log)
174             log->Printf ("NativeProcessLinux::%s %s", __FUNCTION__, error_message.c_str ());
175         assert (false && "ThreadStateCoordinator error reported");
176     }
177 
178     Error
179     ResolveProcessArchitecture (lldb::pid_t pid, Platform &platform, ArchSpec &arch)
180     {
181         // Grab process info for the running process.
182         ProcessInstanceInfo process_info;
183         if (!platform.GetProcessInfo (pid, process_info))
184             return Error("failed to get process info");
185 
186         // Resolve the executable module.
187         ModuleSP exe_module_sp;
188         ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
189         FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths ());
190         Error error = platform.ResolveExecutable(
191             exe_module_spec,
192             exe_module_sp,
193             executable_search_paths.GetSize () ? &executable_search_paths : NULL);
194 
195         if (!error.Success ())
196             return error;
197 
198         // Check if we've got our architecture from the exe_module.
199         arch = exe_module_sp->GetArchitecture ();
200         if (arch.IsValid ())
201             return Error();
202         else
203             return Error("failed to retrieve a valid architecture from the exe module");
204     }
205 
206     void
207     DisplayBytes (StreamString &s, void *bytes, uint32_t count)
208     {
209         uint8_t *ptr = (uint8_t *)bytes;
210         const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
211         for(uint32_t i=0; i<loop_count; i++)
212         {
213             s.Printf ("[%x]", *ptr);
214             ptr++;
215         }
216     }
217 
218     void
219     PtraceDisplayBytes(int &req, void *data, size_t data_size)
220     {
221         StreamString buf;
222         Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
223                     POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
224 
225         if (verbose_log)
226         {
227             switch(req)
228             {
229             case PTRACE_POKETEXT:
230             {
231                 DisplayBytes(buf, &data, 8);
232                 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
233                 break;
234             }
235             case PTRACE_POKEDATA:
236             {
237                 DisplayBytes(buf, &data, 8);
238                 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
239                 break;
240             }
241             case PTRACE_POKEUSER:
242             {
243                 DisplayBytes(buf, &data, 8);
244                 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
245                 break;
246             }
247             case PTRACE_SETREGS:
248             {
249                 DisplayBytes(buf, data, data_size);
250                 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
251                 break;
252             }
253             case PTRACE_SETFPREGS:
254             {
255                 DisplayBytes(buf, data, data_size);
256                 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
257                 break;
258             }
259             case PTRACE_SETSIGINFO:
260             {
261                 DisplayBytes(buf, data, sizeof(siginfo_t));
262                 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
263                 break;
264             }
265             case PTRACE_SETREGSET:
266             {
267                 // Extract iov_base from data, which is a pointer to the struct IOVEC
268                 DisplayBytes(buf, *(void **)data, data_size);
269                 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
270                 break;
271             }
272             default:
273             {
274             }
275             }
276         }
277     }
278 
279     // Wrapper for ptrace to catch errors and log calls.
280     // Note that ptrace sets errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
281     long
282     PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, Error& error,
283                   const char* reqName, const char* file, int line)
284     {
285         long int result;
286 
287         Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
288 
289         PtraceDisplayBytes(req, data, data_size);
290 
291         error.Clear();
292         errno = 0;
293         if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
294             result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
295         else
296             result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
297 
298         if (result == -1)
299             error.SetErrorToErrno();
300 
301         if (log)
302             log->Printf("ptrace(%s, %" PRIu64 ", %p, %p, %zu)=%lX called from file %s line %d",
303                     reqName, pid, addr, data, data_size, result, file, line);
304 
305         PtraceDisplayBytes(req, data, data_size);
306 
307         if (log && error.GetError() != 0)
308         {
309             const char* str;
310             switch (error.GetError())
311             {
312             case ESRCH:  str = "ESRCH"; break;
313             case EINVAL: str = "EINVAL"; break;
314             case EBUSY:  str = "EBUSY"; break;
315             case EPERM:  str = "EPERM"; break;
316             default:     str = error.AsCString();
317             }
318             log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
319         }
320 
321         return result;
322     }
323 
324 #ifdef LLDB_CONFIGURATION_BUILDANDINTEGRATION
325     // Wrapper for ptrace when logging is not required.
326     // Sets errno to 0 prior to calling ptrace.
327     long
328     PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, Error& error)
329     {
330         long result = 0;
331 
332         error.Clear();
333         errno = 0;
334         if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
335             result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
336         else
337             result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
338 
339         if (result == -1)
340             error.SetErrorToErrno();
341         return result;
342     }
343 #endif
344 
345     //------------------------------------------------------------------------------
346     // Static implementations of NativeProcessLinux::ReadMemory and
347     // NativeProcessLinux::WriteMemory.  This enables mutual recursion between these
348     // functions without needed to go thru the thread funnel.
349 
350     lldb::addr_t
351     DoReadMemory (
352         lldb::pid_t pid,
353         lldb::addr_t vm_addr,
354         void *buf,
355         lldb::addr_t size,
356         Error &error)
357     {
358         // ptrace word size is determined by the host, not the child
359         static const unsigned word_size = sizeof(void*);
360         unsigned char *dst = static_cast<unsigned char*>(buf);
361         lldb::addr_t bytes_read;
362         lldb::addr_t remainder;
363         long data;
364 
365         Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
366         if (log)
367             ProcessPOSIXLog::IncNestLevel();
368         if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
369             log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
370                     pid, word_size, (void*)vm_addr, buf, size);
371 
372         assert(sizeof(data) >= word_size);
373         for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
374         {
375             data = PTRACE(PTRACE_PEEKDATA, pid, (void*)vm_addr, nullptr, 0, error);
376             if (error.Fail())
377             {
378                 if (log)
379                     ProcessPOSIXLog::DecNestLevel();
380                 return bytes_read;
381             }
382 
383             remainder = size - bytes_read;
384             remainder = remainder > word_size ? word_size : remainder;
385 
386             // Copy the data into our buffer
387             for (unsigned i = 0; i < remainder; ++i)
388                 dst[i] = ((data >> i*8) & 0xFF);
389 
390             if (log && ProcessPOSIXLog::AtTopNestLevel() &&
391                     (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
392                             (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
393                                     size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
394             {
395                 uintptr_t print_dst = 0;
396                 // Format bytes from data by moving into print_dst for log output
397                 for (unsigned i = 0; i < remainder; ++i)
398                     print_dst |= (((data >> i*8) & 0xFF) << i*8);
399                 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
400                         (void*)vm_addr, print_dst, (unsigned long)data);
401             }
402 
403             vm_addr += word_size;
404             dst += word_size;
405         }
406 
407         if (log)
408             ProcessPOSIXLog::DecNestLevel();
409         return bytes_read;
410     }
411 
412     lldb::addr_t
413     DoWriteMemory(
414         lldb::pid_t pid,
415         lldb::addr_t vm_addr,
416         const void *buf,
417         lldb::addr_t size,
418         Error &error)
419     {
420         // ptrace word size is determined by the host, not the child
421         static const unsigned word_size = sizeof(void*);
422         const unsigned char *src = static_cast<const unsigned char*>(buf);
423         lldb::addr_t bytes_written = 0;
424         lldb::addr_t remainder;
425 
426         Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
427         if (log)
428             ProcessPOSIXLog::IncNestLevel();
429         if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
430             log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %u, %p, %p, %" PRIu64 ")", __FUNCTION__,
431                     pid, word_size, (void*)vm_addr, buf, size);
432 
433         for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
434         {
435             remainder = size - bytes_written;
436             remainder = remainder > word_size ? word_size : remainder;
437 
438             if (remainder == word_size)
439             {
440                 unsigned long data = 0;
441                 assert(sizeof(data) >= word_size);
442                 for (unsigned i = 0; i < word_size; ++i)
443                     data |= (unsigned long)src[i] << i*8;
444 
445                 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
446                         (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
447                                 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
448                                         size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
449                     log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
450                             (void*)vm_addr, *(const unsigned long*)src, data);
451 
452                 if (PTRACE(PTRACE_POKEDATA, pid, (void*)vm_addr, (void*)data, 0, error))
453                 {
454                     if (log)
455                         ProcessPOSIXLog::DecNestLevel();
456                     return bytes_written;
457                 }
458             }
459             else
460             {
461                 unsigned char buff[8];
462                 if (DoReadMemory(pid, vm_addr,
463                                 buff, word_size, error) != word_size)
464                 {
465                     if (log)
466                         ProcessPOSIXLog::DecNestLevel();
467                     return bytes_written;
468                 }
469 
470                 memcpy(buff, src, remainder);
471 
472                 if (DoWriteMemory(pid, vm_addr,
473                                 buff, word_size, error) != word_size)
474                 {
475                     if (log)
476                         ProcessPOSIXLog::DecNestLevel();
477                     return bytes_written;
478                 }
479 
480                 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
481                         (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
482                                 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
483                                         size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
484                     log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
485                             (void*)vm_addr, *(const unsigned long*)src, *(unsigned long*)buff);
486             }
487 
488             vm_addr += word_size;
489             src += word_size;
490         }
491         if (log)
492             ProcessPOSIXLog::DecNestLevel();
493         return bytes_written;
494     }
495 
496     //------------------------------------------------------------------------------
497     /// @class Operation
498     /// @brief Represents a NativeProcessLinux operation.
499     ///
500     /// Under Linux, it is not possible to ptrace() from any other thread but the
501     /// one that spawned or attached to the process from the start.  Therefore, when
502     /// a NativeProcessLinux is asked to deliver or change the state of an inferior
503     /// process the operation must be "funneled" to a specific thread to perform the
504     /// task.  The Operation class provides an abstract base for all services the
505     /// NativeProcessLinux must perform via the single virtual function Execute, thus
506     /// encapsulating the code that needs to run in the privileged context.
507     class Operation
508     {
509     public:
510         Operation () : m_error() { }
511 
512         virtual
513         ~Operation() {}
514 
515         virtual void
516         Execute (NativeProcessLinux *process) = 0;
517 
518         const Error &
519         GetError () const { return m_error; }
520 
521     protected:
522         Error m_error;
523     };
524 
525     //------------------------------------------------------------------------------
526     /// @class ReadOperation
527     /// @brief Implements NativeProcessLinux::ReadMemory.
528     class ReadOperation : public Operation
529     {
530     public:
531         ReadOperation (
532             lldb::addr_t addr,
533             void *buff,
534             lldb::addr_t size,
535             lldb::addr_t &result) :
536             Operation (),
537             m_addr (addr),
538             m_buff (buff),
539             m_size (size),
540             m_result (result)
541             {
542             }
543 
544         void Execute (NativeProcessLinux *process) override;
545 
546     private:
547         lldb::addr_t m_addr;
548         void *m_buff;
549         lldb::addr_t m_size;
550         lldb::addr_t &m_result;
551     };
552 
553     void
554     ReadOperation::Execute (NativeProcessLinux *process)
555     {
556         m_result = DoReadMemory (process->GetID (), m_addr, m_buff, m_size, m_error);
557     }
558 
559     //------------------------------------------------------------------------------
560     /// @class WriteOperation
561     /// @brief Implements NativeProcessLinux::WriteMemory.
562     class WriteOperation : public Operation
563     {
564     public:
565         WriteOperation (
566             lldb::addr_t addr,
567             const void *buff,
568             lldb::addr_t size,
569             lldb::addr_t &result) :
570             Operation (),
571             m_addr (addr),
572             m_buff (buff),
573             m_size (size),
574             m_result (result)
575             {
576             }
577 
578         void Execute (NativeProcessLinux *process) override;
579 
580     private:
581         lldb::addr_t m_addr;
582         const void *m_buff;
583         lldb::addr_t m_size;
584         lldb::addr_t &m_result;
585     };
586 
587     void
588     WriteOperation::Execute(NativeProcessLinux *process)
589     {
590         m_result = DoWriteMemory (process->GetID (), m_addr, m_buff, m_size, m_error);
591     }
592 
593     //------------------------------------------------------------------------------
594     /// @class ReadRegOperation
595     /// @brief Implements NativeProcessLinux::ReadRegisterValue.
596     class ReadRegOperation : public Operation
597     {
598     public:
599         ReadRegOperation(lldb::tid_t tid, uint32_t offset, const char *reg_name,
600                 RegisterValue &value)
601             : m_tid(tid),
602               m_offset(static_cast<uintptr_t> (offset)),
603               m_reg_name(reg_name),
604               m_value(value)
605             { }
606 
607         void Execute(NativeProcessLinux *monitor) override;
608 
609     private:
610         lldb::tid_t m_tid;
611         uintptr_t m_offset;
612         const char *m_reg_name;
613         RegisterValue &m_value;
614     };
615 
616     void
617     ReadRegOperation::Execute(NativeProcessLinux *monitor)
618     {
619 #if defined (__arm64__) || defined (__aarch64__)
620         if (m_offset > sizeof(struct user_pt_regs))
621         {
622             uintptr_t offset = m_offset - sizeof(struct user_pt_regs);
623             if (offset > sizeof(struct user_fpsimd_state))
624             {
625                 m_error.SetErrorString("invalid offset value");
626                 return;
627             }
628             elf_fpregset_t regs;
629             int regset = NT_FPREGSET;
630             struct iovec ioVec;
631 
632             ioVec.iov_base = &regs;
633             ioVec.iov_len = sizeof regs;
634             PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
635             if (m_error.Success())
636             {
637                 ArchSpec arch;
638                 if (monitor->GetArchitecture(arch))
639                     m_value.SetBytes((void *)(((unsigned char *)(&regs)) + offset), 16, arch.GetByteOrder());
640                 else
641                     m_error.SetErrorString("failed to get architecture");
642             }
643         }
644         else
645         {
646             elf_gregset_t regs;
647             int regset = NT_PRSTATUS;
648             struct iovec ioVec;
649 
650             ioVec.iov_base = &regs;
651             ioVec.iov_len = sizeof regs;
652             PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
653             if (m_error.Success())
654             {
655                 ArchSpec arch;
656                 if (monitor->GetArchitecture(arch))
657                     m_value.SetBytes((void *)(((unsigned char *)(regs)) + m_offset), 8, arch.GetByteOrder());
658                 else
659                     m_error.SetErrorString("failed to get architecture");
660             }
661         }
662 #elif defined (__mips__)
663         elf_gregset_t regs;
664         PTRACE(PTRACE_GETREGS, m_tid, NULL, &regs, sizeof regs, m_error);
665         if (m_error.Success())
666         {
667             lldb_private::ArchSpec arch;
668             if (monitor->GetArchitecture(arch))
669                 m_value.SetBytes((void *)(((unsigned char *)(regs)) + m_offset), 8, arch.GetByteOrder());
670             else
671                 m_error.SetErrorString("failed to get architecture");
672         }
673 #else
674         Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
675 
676         lldb::addr_t data = static_cast<unsigned long>(PTRACE(PTRACE_PEEKUSER, m_tid, (void*)m_offset, nullptr, 0, m_error));
677         if (m_error.Success())
678             m_value = data;
679 
680         if (log)
681             log->Printf ("NativeProcessLinux::%s() reg %s: 0x%" PRIx64, __FUNCTION__,
682                     m_reg_name, data);
683 #endif
684     }
685 
686     //------------------------------------------------------------------------------
687     /// @class WriteRegOperation
688     /// @brief Implements NativeProcessLinux::WriteRegisterValue.
689     class WriteRegOperation : public Operation
690     {
691     public:
692         WriteRegOperation(lldb::tid_t tid, unsigned offset, const char *reg_name,
693                 const RegisterValue &value)
694             : m_tid(tid),
695               m_offset(offset),
696               m_reg_name(reg_name),
697               m_value(value)
698             { }
699 
700         void Execute(NativeProcessLinux *monitor) override;
701 
702     private:
703         lldb::tid_t m_tid;
704         uintptr_t m_offset;
705         const char *m_reg_name;
706         const RegisterValue &m_value;
707     };
708 
709     void
710     WriteRegOperation::Execute(NativeProcessLinux *monitor)
711     {
712 #if defined (__arm64__) || defined (__aarch64__)
713         if (m_offset > sizeof(struct user_pt_regs))
714         {
715             uintptr_t offset = m_offset - sizeof(struct user_pt_regs);
716             if (offset > sizeof(struct user_fpsimd_state))
717             {
718                 m_error.SetErrorString("invalid offset value");
719                 return;
720             }
721             elf_fpregset_t regs;
722             int regset = NT_FPREGSET;
723             struct iovec ioVec;
724 
725             ioVec.iov_base = &regs;
726             ioVec.iov_len = sizeof regs;
727             PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
728             if (m_error.Success())
729             {
730                 ::memcpy((void *)(((unsigned char *)(&regs)) + offset), m_value.GetBytes(), 16);
731                 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
732             }
733         }
734         else
735         {
736             elf_gregset_t regs;
737             int regset = NT_PRSTATUS;
738             struct iovec ioVec;
739 
740             ioVec.iov_base = &regs;
741             ioVec.iov_len = sizeof regs;
742             PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
743             if (m_error.Success())
744             {
745                 ::memcpy((void *)(((unsigned char *)(&regs)) + m_offset), m_value.GetBytes(), 8);
746                 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
747             }
748         }
749 #elif defined (__mips__)
750         elf_gregset_t regs;
751         PTRACE(PTRACE_GETREGS, m_tid, NULL, &regs, sizeof regs, m_error);
752         if (m_error.Success())
753         {
754             ::memcpy((void *)(((unsigned char *)(&regs)) + m_offset), m_value.GetBytes(), 8);
755             PTRACE(PTRACE_SETREGS, m_tid, NULL, &regs, sizeof regs, m_error);
756         }
757 #else
758         void* buf;
759         Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
760 
761         buf = (void*) m_value.GetAsUInt64();
762 
763         if (log)
764             log->Printf ("NativeProcessLinux::%s() reg %s: %p", __FUNCTION__, m_reg_name, buf);
765         PTRACE(PTRACE_POKEUSER, m_tid, (void*)m_offset, buf, 0, m_error);
766 #endif
767     }
768 
769     //------------------------------------------------------------------------------
770     /// @class ReadGPROperation
771     /// @brief Implements NativeProcessLinux::ReadGPR.
772     class ReadGPROperation : public Operation
773     {
774     public:
775         ReadGPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
776             : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
777             { }
778 
779         void Execute(NativeProcessLinux *monitor) override;
780 
781     private:
782         lldb::tid_t m_tid;
783         void *m_buf;
784         size_t m_buf_size;
785     };
786 
787     void
788     ReadGPROperation::Execute(NativeProcessLinux *monitor)
789     {
790 #if defined (__arm64__) || defined (__aarch64__)
791         int regset = NT_PRSTATUS;
792         struct iovec ioVec;
793 
794         ioVec.iov_base = m_buf;
795         ioVec.iov_len = m_buf_size;
796         PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
797 #else
798         PTRACE(PTRACE_GETREGS, m_tid, nullptr, m_buf, m_buf_size, m_error);
799 #endif
800     }
801 
802     //------------------------------------------------------------------------------
803     /// @class ReadFPROperation
804     /// @brief Implements NativeProcessLinux::ReadFPR.
805     class ReadFPROperation : public Operation
806     {
807     public:
808         ReadFPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
809             : m_tid(tid),
810               m_buf(buf),
811               m_buf_size(buf_size)
812             { }
813 
814         void Execute(NativeProcessLinux *monitor) override;
815 
816     private:
817         lldb::tid_t m_tid;
818         void *m_buf;
819         size_t m_buf_size;
820     };
821 
822     void
823     ReadFPROperation::Execute(NativeProcessLinux *monitor)
824     {
825 #if defined (__arm64__) || defined (__aarch64__)
826         int regset = NT_FPREGSET;
827         struct iovec ioVec;
828 
829         ioVec.iov_base = m_buf;
830         ioVec.iov_len = m_buf_size;
831         PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
832 #else
833         PTRACE(PTRACE_GETFPREGS, m_tid, nullptr, m_buf, m_buf_size, m_error);
834 #endif
835     }
836 
837     //------------------------------------------------------------------------------
838     /// @class ReadRegisterSetOperation
839     /// @brief Implements NativeProcessLinux::ReadRegisterSet.
840     class ReadRegisterSetOperation : public Operation
841     {
842     public:
843         ReadRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
844             : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset)
845             { }
846 
847         void Execute(NativeProcessLinux *monitor) override;
848 
849     private:
850         lldb::tid_t m_tid;
851         void *m_buf;
852         size_t m_buf_size;
853         const unsigned int m_regset;
854     };
855 
856     void
857     ReadRegisterSetOperation::Execute(NativeProcessLinux *monitor)
858     {
859         PTRACE(PTRACE_GETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size, m_error);
860     }
861 
862     //------------------------------------------------------------------------------
863     /// @class WriteGPROperation
864     /// @brief Implements NativeProcessLinux::WriteGPR.
865     class WriteGPROperation : public Operation
866     {
867     public:
868         WriteGPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
869             : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
870             { }
871 
872         void Execute(NativeProcessLinux *monitor) override;
873 
874     private:
875         lldb::tid_t m_tid;
876         void *m_buf;
877         size_t m_buf_size;
878     };
879 
880     void
881     WriteGPROperation::Execute(NativeProcessLinux *monitor)
882     {
883 #if defined (__arm64__) || defined (__aarch64__)
884         int regset = NT_PRSTATUS;
885         struct iovec ioVec;
886 
887         ioVec.iov_base = m_buf;
888         ioVec.iov_len = m_buf_size;
889         PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
890 #else
891         PTRACE(PTRACE_SETREGS, m_tid, NULL, m_buf, m_buf_size, m_error);
892 #endif
893     }
894 
895     //------------------------------------------------------------------------------
896     /// @class WriteFPROperation
897     /// @brief Implements NativeProcessLinux::WriteFPR.
898     class WriteFPROperation : public Operation
899     {
900     public:
901         WriteFPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
902             : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
903             { }
904 
905         void Execute(NativeProcessLinux *monitor) override;
906 
907     private:
908         lldb::tid_t m_tid;
909         void *m_buf;
910         size_t m_buf_size;
911     };
912 
913     void
914     WriteFPROperation::Execute(NativeProcessLinux *monitor)
915     {
916 #if defined (__arm64__) || defined (__aarch64__)
917         int regset = NT_FPREGSET;
918         struct iovec ioVec;
919 
920         ioVec.iov_base = m_buf;
921         ioVec.iov_len = m_buf_size;
922         PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
923 #else
924         PTRACE(PTRACE_SETFPREGS, m_tid, NULL, m_buf, m_buf_size, m_error);
925 #endif
926     }
927 
928     //------------------------------------------------------------------------------
929     /// @class WriteRegisterSetOperation
930     /// @brief Implements NativeProcessLinux::WriteRegisterSet.
931     class WriteRegisterSetOperation : public Operation
932     {
933     public:
934         WriteRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
935             : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset)
936             { }
937 
938         void Execute(NativeProcessLinux *monitor) override;
939 
940     private:
941         lldb::tid_t m_tid;
942         void *m_buf;
943         size_t m_buf_size;
944         const unsigned int m_regset;
945     };
946 
947     void
948     WriteRegisterSetOperation::Execute(NativeProcessLinux *monitor)
949     {
950         PTRACE(PTRACE_SETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size, m_error);
951     }
952 
953     //------------------------------------------------------------------------------
954     /// @class ResumeOperation
955     /// @brief Implements NativeProcessLinux::Resume.
956     class ResumeOperation : public Operation
957     {
958     public:
959         ResumeOperation(lldb::tid_t tid, uint32_t signo) :
960             m_tid(tid), m_signo(signo) { }
961 
962         void Execute(NativeProcessLinux *monitor) override;
963 
964     private:
965         lldb::tid_t m_tid;
966         uint32_t m_signo;
967     };
968 
969     void
970     ResumeOperation::Execute(NativeProcessLinux *monitor)
971     {
972         intptr_t data = 0;
973 
974         if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
975             data = m_signo;
976 
977         PTRACE(PTRACE_CONT, m_tid, nullptr, (void*)data, 0, m_error);
978         if (m_error.Fail())
979         {
980             Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
981 
982             if (log)
983                 log->Printf ("ResumeOperation (%"  PRIu64 ") failed: %s", m_tid, m_error.AsCString());
984         }
985     }
986 
987     //------------------------------------------------------------------------------
988     /// @class SingleStepOperation
989     /// @brief Implements NativeProcessLinux::SingleStep.
990     class SingleStepOperation : public Operation
991     {
992     public:
993         SingleStepOperation(lldb::tid_t tid, uint32_t signo)
994             : m_tid(tid), m_signo(signo) { }
995 
996         void Execute(NativeProcessLinux *monitor) override;
997 
998     private:
999         lldb::tid_t m_tid;
1000         uint32_t m_signo;
1001     };
1002 
1003     void
1004     SingleStepOperation::Execute(NativeProcessLinux *monitor)
1005     {
1006         intptr_t data = 0;
1007 
1008         if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
1009             data = m_signo;
1010 
1011         PTRACE(PTRACE_SINGLESTEP, m_tid, nullptr, (void*)data, 0, m_error);
1012     }
1013 
1014     //------------------------------------------------------------------------------
1015     /// @class SiginfoOperation
1016     /// @brief Implements NativeProcessLinux::GetSignalInfo.
1017     class SiginfoOperation : public Operation
1018     {
1019     public:
1020         SiginfoOperation(lldb::tid_t tid, void *info)
1021             : m_tid(tid), m_info(info) { }
1022 
1023         void Execute(NativeProcessLinux *monitor) override;
1024 
1025     private:
1026         lldb::tid_t m_tid;
1027         void *m_info;
1028     };
1029 
1030     void
1031     SiginfoOperation::Execute(NativeProcessLinux *monitor)
1032     {
1033         PTRACE(PTRACE_GETSIGINFO, m_tid, nullptr, m_info, 0, m_error);
1034     }
1035 
1036     //------------------------------------------------------------------------------
1037     /// @class EventMessageOperation
1038     /// @brief Implements NativeProcessLinux::GetEventMessage.
1039     class EventMessageOperation : public Operation
1040     {
1041     public:
1042         EventMessageOperation(lldb::tid_t tid, unsigned long *message)
1043             : m_tid(tid), m_message(message) { }
1044 
1045         void Execute(NativeProcessLinux *monitor) override;
1046 
1047     private:
1048         lldb::tid_t m_tid;
1049         unsigned long *m_message;
1050     };
1051 
1052     void
1053     EventMessageOperation::Execute(NativeProcessLinux *monitor)
1054     {
1055         PTRACE(PTRACE_GETEVENTMSG, m_tid, nullptr, m_message, 0, m_error);
1056     }
1057 
1058     class DetachOperation : public Operation
1059     {
1060     public:
1061         DetachOperation(lldb::tid_t tid) : m_tid(tid) { }
1062 
1063         void Execute(NativeProcessLinux *monitor) override;
1064 
1065     private:
1066         lldb::tid_t m_tid;
1067     };
1068 
1069     void
1070     DetachOperation::Execute(NativeProcessLinux *monitor)
1071     {
1072         PTRACE(PTRACE_DETACH, m_tid, nullptr, 0, 0, m_error);
1073     }
1074 
1075 } // end of anonymous namespace
1076 
1077 class NativeProcessLinux::Monitor {
1078 private:
1079     ::pid_t             m_child_pid;
1080     NativeProcessLinux *m_native_process;
1081 
1082     enum { READ, WRITE };
1083     int        m_pipefd[2] = {-1, -1};
1084     int        m_signal_fd = -1;
1085     HostThread m_thread;
1086 
1087     void
1088     HandleSignals();
1089 
1090     void
1091     HandleWait();
1092 
1093     // Returns true if the thread should exit.
1094     bool
1095     HandleCommands();
1096 
1097     void
1098     MainLoop();
1099 
1100     static void *
1101     RunMonitor(void *arg);
1102 
1103 public:
1104     // Takes ownership of command_fd.
1105     Monitor(::pid_t child_pid, NativeProcessLinux *native_process)
1106         : m_child_pid(-getpgid(child_pid)), m_native_process(native_process)
1107     {}
1108 
1109     ~Monitor();
1110 
1111     Error
1112     Initialize();
1113 };
1114 
1115 Error
1116 NativeProcessLinux::Monitor::Initialize()
1117 {
1118     Error error;
1119 
1120     // We get a SIGCHLD every time something interesting happens with the inferior. We shall be
1121     // listening for these signals over a signalfd file descriptors. This allows us to wait for
1122     // multiple kinds of events with select.
1123     sigset_t signals;
1124     sigemptyset(&signals);
1125     sigaddset(&signals, SIGCHLD);
1126     m_signal_fd = signalfd(-1, &signals, SFD_NONBLOCK | SFD_CLOEXEC);
1127     if (m_signal_fd < 0)
1128     {
1129         return Error("NativeProcessLinux::Monitor::%s failed due to signalfd failure. Monitoring the inferior will be impossible: %s",
1130                     __FUNCTION__, strerror(errno));
1131 
1132     }
1133 
1134     if (pipe2(m_pipefd, O_CLOEXEC) == -1)
1135     {
1136         error.SetErrorToErrno();
1137         return error;
1138     }
1139 
1140     m_thread = ThreadLauncher::LaunchThread("monitor", Monitor::RunMonitor, this, nullptr);
1141     if (!m_thread.IsJoinable())
1142         return Error("Failed to create monitor thread for NativeProcessLinux.");
1143 
1144     return error;
1145 }
1146 
1147 NativeProcessLinux::Monitor::~Monitor()
1148 {
1149     if (m_pipefd[WRITE] >= 0)
1150         close(m_pipefd[WRITE]);
1151     if (m_thread.IsJoinable())
1152         m_thread.Join(nullptr);
1153     if (m_pipefd[READ] >= 0)
1154         close(m_pipefd[READ]);
1155     if (m_signal_fd >= 0)
1156         close(m_signal_fd);
1157 }
1158 
1159 void
1160 NativeProcessLinux::Monitor::HandleSignals()
1161 {
1162     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1163 
1164     // We don't really care about the content of the SIGCHLD siginfo structure, as we will get
1165     // all the information from waitpid(). We just need to read all the signals so that we can
1166     // sleep next time we reach select().
1167     while (true)
1168     {
1169         signalfd_siginfo info;
1170         ssize_t size = read(m_signal_fd, &info, sizeof info);
1171         if (size == -1)
1172         {
1173             if (errno == EAGAIN || errno == EWOULDBLOCK)
1174                 break; // We are done.
1175             if (errno == EINTR)
1176                 continue;
1177             if (log)
1178                 log->Printf("NativeProcessLinux::Monitor::%s reading from signalfd file descriptor failed: %s",
1179                         __FUNCTION__, strerror(errno));
1180             break;
1181         }
1182         if (size != sizeof info)
1183         {
1184             // We got incomplete information structure. This should not happen, let's just log
1185             // that.
1186             if (log)
1187                 log->Printf("NativeProcessLinux::Monitor::%s reading from signalfd file descriptor returned incomplete data: "
1188                         "structure size is %zd, read returned %zd bytes",
1189                         __FUNCTION__, sizeof info, size);
1190             break;
1191         }
1192         if (log)
1193             log->Printf("NativeProcessLinux::Monitor::%s received signal %s(%d).", __FUNCTION__,
1194                 Host::GetSignalAsCString(info.ssi_signo), info.ssi_signo);
1195     }
1196 }
1197 
1198 void
1199 NativeProcessLinux::Monitor::HandleWait()
1200 {
1201     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1202     // Process all pending waitpid notifications.
1203     while (true)
1204     {
1205         int status = -1;
1206         ::pid_t wait_pid = waitpid(m_child_pid, &status, __WALL | WNOHANG);
1207 
1208         if (wait_pid == 0)
1209             break; // We are done.
1210 
1211         if (wait_pid == -1)
1212         {
1213             if (errno == EINTR)
1214                 continue;
1215 
1216             if (log)
1217               log->Printf("NativeProcessLinux::Monitor::%s waitpid (pid = %" PRIi32 ", &status, __WALL | WNOHANG) failed: %s",
1218                       __FUNCTION__, m_child_pid, strerror(errno));
1219             break;
1220         }
1221 
1222         bool exited = false;
1223         int signal = 0;
1224         int exit_status = 0;
1225         const char *status_cstr = NULL;
1226         if (WIFSTOPPED(status))
1227         {
1228             signal = WSTOPSIG(status);
1229             status_cstr = "STOPPED";
1230         }
1231         else if (WIFEXITED(status))
1232         {
1233             exit_status = WEXITSTATUS(status);
1234             status_cstr = "EXITED";
1235             exited = true;
1236         }
1237         else if (WIFSIGNALED(status))
1238         {
1239             signal = WTERMSIG(status);
1240             status_cstr = "SIGNALED";
1241             if (wait_pid == abs(m_child_pid)) {
1242                 exited = true;
1243                 exit_status = -1;
1244             }
1245         }
1246         else
1247             status_cstr = "(\?\?\?)";
1248 
1249         if (log)
1250             log->Printf("NativeProcessLinux::Monitor::%s: waitpid (pid = %" PRIi32 ", &status, __WALL | WNOHANG)"
1251                 "=> pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
1252                 __FUNCTION__, m_child_pid, wait_pid, status, status_cstr, signal, exit_status);
1253 
1254         m_native_process->MonitorCallback (wait_pid, exited, signal, exit_status);
1255     }
1256 }
1257 
1258 bool
1259 NativeProcessLinux::Monitor::HandleCommands()
1260 {
1261     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1262 
1263     while (true)
1264     {
1265         char command = 0;
1266         ssize_t size = read(m_pipefd[READ], &command, sizeof command);
1267         if (size == -1)
1268         {
1269             if (errno == EAGAIN || errno == EWOULDBLOCK)
1270                 return false;
1271             if (errno == EINTR)
1272                 continue;
1273             if (log)
1274                 log->Printf("NativeProcessLinux::Monitor::%s exiting because read from command file descriptor failed: %s", __FUNCTION__, strerror(errno));
1275             return true;
1276         }
1277         if (size == 0) // end of file - write end closed
1278         {
1279             if (log)
1280                 log->Printf("NativeProcessLinux::Monitor::%s exit command received, exiting...", __FUNCTION__);
1281             return true; // We are done.
1282         }
1283         if (log)
1284             log->Printf("NativeProcessLinux::Monitor::%s received unknown command '%c'",
1285                     __FUNCTION__, command);
1286     }
1287 }
1288 
1289 void
1290 NativeProcessLinux::Monitor::MainLoop()
1291 {
1292     while (true)
1293     {
1294         fd_set fds;
1295         FD_ZERO(&fds);
1296         FD_SET(m_signal_fd, &fds);
1297         FD_SET(m_pipefd[READ], &fds);
1298 
1299         int max_fd = std::max(m_signal_fd, m_pipefd[READ]) + 1;
1300         int r = select(max_fd, &fds, nullptr, nullptr, nullptr);
1301         if (r < 0)
1302         {
1303             Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1304             if (log)
1305                 log->Printf("NativeProcessLinux::Monitor::%s exiting because select failed: %s",
1306                         __FUNCTION__, strerror(errno));
1307             return;
1308         }
1309 
1310         if (FD_ISSET(m_pipefd[READ], &fds))
1311         {
1312             if (HandleCommands())
1313                 return;
1314         }
1315 
1316         if (FD_ISSET(m_signal_fd, &fds))
1317         {
1318             HandleSignals();
1319             HandleWait();
1320         }
1321     }
1322 }
1323 
1324 void *
1325 NativeProcessLinux::Monitor::RunMonitor(void *arg)
1326 {
1327     static_cast<Monitor *>(arg)->MainLoop();
1328     return nullptr;
1329 }
1330 
1331 
1332 // Simple helper function to ensure flags are enabled on the given file
1333 // descriptor.
1334 static bool
1335 EnsureFDFlags(int fd, int flags, Error &error)
1336 {
1337     int status;
1338 
1339     if ((status = fcntl(fd, F_GETFL)) == -1)
1340     {
1341         error.SetErrorToErrno();
1342         return false;
1343     }
1344 
1345     if (fcntl(fd, F_SETFL, status | flags) == -1)
1346     {
1347         error.SetErrorToErrno();
1348         return false;
1349     }
1350 
1351     return true;
1352 }
1353 
1354 NativeProcessLinux::OperationArgs::OperationArgs(NativeProcessLinux *monitor)
1355     : m_monitor(monitor)
1356 {
1357     sem_init(&m_semaphore, 0, 0);
1358 }
1359 
1360 NativeProcessLinux::OperationArgs::~OperationArgs()
1361 {
1362     sem_destroy(&m_semaphore);
1363 }
1364 
1365 NativeProcessLinux::LaunchArgs::LaunchArgs(NativeProcessLinux *monitor,
1366                                        Module *module,
1367                                        char const **argv,
1368                                        char const **envp,
1369                                        const std::string &stdin_path,
1370                                        const std::string &stdout_path,
1371                                        const std::string &stderr_path,
1372                                        const char *working_dir,
1373                                        const ProcessLaunchInfo &launch_info)
1374     : OperationArgs(monitor),
1375       m_module(module),
1376       m_argv(argv),
1377       m_envp(envp),
1378       m_stdin_path(stdin_path),
1379       m_stdout_path(stdout_path),
1380       m_stderr_path(stderr_path),
1381       m_working_dir(working_dir),
1382       m_launch_info(launch_info)
1383 {
1384 }
1385 
1386 NativeProcessLinux::LaunchArgs::~LaunchArgs()
1387 { }
1388 
1389 NativeProcessLinux::AttachArgs::AttachArgs(NativeProcessLinux *monitor,
1390                                        lldb::pid_t pid)
1391     : OperationArgs(monitor), m_pid(pid) { }
1392 
1393 NativeProcessLinux::AttachArgs::~AttachArgs()
1394 { }
1395 
1396 // -----------------------------------------------------------------------------
1397 // Public Static Methods
1398 // -----------------------------------------------------------------------------
1399 
1400 Error
1401 NativeProcessLinux::LaunchProcess (
1402     Module *exe_module,
1403     ProcessLaunchInfo &launch_info,
1404     NativeProcessProtocol::NativeDelegate &native_delegate,
1405     NativeProcessProtocolSP &native_process_sp)
1406 {
1407     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1408 
1409     Error error;
1410 
1411     // Verify the working directory is valid if one was specified.
1412     const char* working_dir = launch_info.GetWorkingDirectory ();
1413     if (working_dir)
1414     {
1415       FileSpec working_dir_fs (working_dir, true);
1416       if (!working_dir_fs || working_dir_fs.GetFileType () != FileSpec::eFileTypeDirectory)
1417       {
1418           error.SetErrorStringWithFormat ("No such file or directory: %s", working_dir);
1419           return error;
1420       }
1421     }
1422 
1423     const FileAction *file_action;
1424 
1425     // Default of NULL will mean to use existing open file descriptors.
1426     std::string stdin_path;
1427     std::string stdout_path;
1428     std::string stderr_path;
1429 
1430     file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
1431     if (file_action)
1432         stdin_path = file_action->GetPath ();
1433 
1434     file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
1435     if (file_action)
1436         stdout_path = file_action->GetPath ();
1437 
1438     file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
1439     if (file_action)
1440         stderr_path = file_action->GetPath ();
1441 
1442     if (log)
1443     {
1444         if (!stdin_path.empty ())
1445             log->Printf ("NativeProcessLinux::%s setting STDIN to '%s'", __FUNCTION__, stdin_path.c_str ());
1446         else
1447             log->Printf ("NativeProcessLinux::%s leaving STDIN as is", __FUNCTION__);
1448 
1449         if (!stdout_path.empty ())
1450             log->Printf ("NativeProcessLinux::%s setting STDOUT to '%s'", __FUNCTION__, stdout_path.c_str ());
1451         else
1452             log->Printf ("NativeProcessLinux::%s leaving STDOUT as is", __FUNCTION__);
1453 
1454         if (!stderr_path.empty ())
1455             log->Printf ("NativeProcessLinux::%s setting STDERR to '%s'", __FUNCTION__, stderr_path.c_str ());
1456         else
1457             log->Printf ("NativeProcessLinux::%s leaving STDERR as is", __FUNCTION__);
1458     }
1459 
1460     // Create the NativeProcessLinux in launch mode.
1461     native_process_sp.reset (new NativeProcessLinux ());
1462 
1463     if (log)
1464     {
1465         int i = 0;
1466         for (const char **args = launch_info.GetArguments ().GetConstArgumentVector (); *args; ++args, ++i)
1467         {
1468             log->Printf ("NativeProcessLinux::%s arg %d: \"%s\"", __FUNCTION__, i, *args ? *args : "nullptr");
1469             ++i;
1470         }
1471     }
1472 
1473     if (!native_process_sp->RegisterNativeDelegate (native_delegate))
1474     {
1475         native_process_sp.reset ();
1476         error.SetErrorStringWithFormat ("failed to register the native delegate");
1477         return error;
1478     }
1479 
1480     std::static_pointer_cast<NativeProcessLinux> (native_process_sp)->LaunchInferior (
1481             exe_module,
1482             launch_info.GetArguments ().GetConstArgumentVector (),
1483             launch_info.GetEnvironmentEntries ().GetConstArgumentVector (),
1484             stdin_path,
1485             stdout_path,
1486             stderr_path,
1487             working_dir,
1488             launch_info,
1489             error);
1490 
1491     if (error.Fail ())
1492     {
1493         native_process_sp.reset ();
1494         if (log)
1495             log->Printf ("NativeProcessLinux::%s failed to launch process: %s", __FUNCTION__, error.AsCString ());
1496         return error;
1497     }
1498 
1499     launch_info.SetProcessID (native_process_sp->GetID ());
1500 
1501     return error;
1502 }
1503 
1504 Error
1505 NativeProcessLinux::AttachToProcess (
1506     lldb::pid_t pid,
1507     NativeProcessProtocol::NativeDelegate &native_delegate,
1508     NativeProcessProtocolSP &native_process_sp)
1509 {
1510     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1511     if (log && log->GetMask ().Test (POSIX_LOG_VERBOSE))
1512         log->Printf ("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
1513 
1514     // Grab the current platform architecture.  This should be Linux,
1515     // since this code is only intended to run on a Linux host.
1516     PlatformSP platform_sp (Platform::GetHostPlatform ());
1517     if (!platform_sp)
1518         return Error("failed to get a valid default platform");
1519 
1520     // Retrieve the architecture for the running process.
1521     ArchSpec process_arch;
1522     Error error = ResolveProcessArchitecture (pid, *platform_sp.get (), process_arch);
1523     if (!error.Success ())
1524         return error;
1525 
1526     std::shared_ptr<NativeProcessLinux> native_process_linux_sp (new NativeProcessLinux ());
1527 
1528     if (!native_process_linux_sp->RegisterNativeDelegate (native_delegate))
1529     {
1530         error.SetErrorStringWithFormat ("failed to register the native delegate");
1531         return error;
1532     }
1533 
1534     native_process_linux_sp->AttachToInferior (pid, error);
1535     if (!error.Success ())
1536         return error;
1537 
1538     native_process_sp = native_process_linux_sp;
1539     return error;
1540 }
1541 
1542 // -----------------------------------------------------------------------------
1543 // Public Instance Methods
1544 // -----------------------------------------------------------------------------
1545 
1546 NativeProcessLinux::NativeProcessLinux () :
1547     NativeProcessProtocol (LLDB_INVALID_PROCESS_ID),
1548     m_arch (),
1549     m_operation_thread (),
1550     m_operation (nullptr),
1551     m_operation_mutex (),
1552     m_operation_pending (),
1553     m_operation_done (),
1554     m_supports_mem_region (eLazyBoolCalculate),
1555     m_mem_region_cache (),
1556     m_mem_region_cache_mutex (),
1557     m_coordinator_up (new ThreadStateCoordinator (GetThreadLoggerFunction ())),
1558     m_coordinator_thread ()
1559 {
1560 }
1561 
1562 //------------------------------------------------------------------------------
1563 /// The basic design of the NativeProcessLinux is built around two threads.
1564 ///
1565 /// One thread (@see SignalThread) simply blocks on a call to waitpid() looking
1566 /// for changes in the debugee state.  When a change is detected a
1567 /// ProcessMessage is sent to the associated ProcessLinux instance.  This thread
1568 /// "drives" state changes in the debugger.
1569 ///
1570 /// The second thread (@see OperationThread) is responsible for two things 1)
1571 /// launching or attaching to the inferior process, and then 2) servicing
1572 /// operations such as register reads/writes, stepping, etc.  See the comments
1573 /// on the Operation class for more info as to why this is needed.
1574 void
1575 NativeProcessLinux::LaunchInferior (
1576     Module *module,
1577     const char *argv[],
1578     const char *envp[],
1579     const std::string &stdin_path,
1580     const std::string &stdout_path,
1581     const std::string &stderr_path,
1582     const char *working_dir,
1583     const ProcessLaunchInfo &launch_info,
1584     Error &error)
1585 {
1586     if (module)
1587         m_arch = module->GetArchitecture ();
1588 
1589     SetState (eStateLaunching);
1590 
1591     std::unique_ptr<LaunchArgs> args(
1592         new LaunchArgs(
1593             this, module, argv, envp,
1594             stdin_path, stdout_path, stderr_path,
1595             working_dir, launch_info));
1596 
1597     sem_init (&m_operation_pending, 0, 0);
1598     sem_init (&m_operation_done, 0, 0);
1599 
1600     StartLaunchOpThread (args.get(), error);
1601     if (!error.Success ())
1602         return;
1603 
1604     error = StartCoordinatorThread ();
1605     if (!error.Success ())
1606         return;
1607 
1608 WAIT_AGAIN:
1609     // Wait for the operation thread to initialize.
1610     if (sem_wait(&args->m_semaphore))
1611     {
1612         if (errno == EINTR)
1613             goto WAIT_AGAIN;
1614         else
1615         {
1616             error.SetErrorToErrno();
1617             return;
1618         }
1619     }
1620 
1621     // Check that the launch was a success.
1622     if (!args->m_error.Success())
1623     {
1624         StopOpThread();
1625         StopCoordinatorThread ();
1626         error = args->m_error;
1627         return;
1628     }
1629 
1630     // Finally, start monitoring the child process for change in state.
1631     StartMonitorThread(error);
1632 }
1633 
1634 void
1635 NativeProcessLinux::AttachToInferior (lldb::pid_t pid, Error &error)
1636 {
1637     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1638     if (log)
1639         log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
1640 
1641     // We can use the Host for everything except the ResolveExecutable portion.
1642     PlatformSP platform_sp = Platform::GetHostPlatform ();
1643     if (!platform_sp)
1644     {
1645         if (log)
1646             log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): no default platform set", __FUNCTION__, pid);
1647         error.SetErrorString ("no default platform available");
1648         return;
1649     }
1650 
1651     // Gather info about the process.
1652     ProcessInstanceInfo process_info;
1653     if (!platform_sp->GetProcessInfo (pid, process_info))
1654     {
1655         if (log)
1656             log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): failed to get process info", __FUNCTION__, pid);
1657         error.SetErrorString ("failed to get process info");
1658         return;
1659     }
1660 
1661     // Resolve the executable module
1662     ModuleSP exe_module_sp;
1663     FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
1664     ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
1665     error = platform_sp->ResolveExecutable(exe_module_spec, exe_module_sp,
1666                                            executable_search_paths.GetSize() ? &executable_search_paths : NULL);
1667     if (!error.Success())
1668         return;
1669 
1670     // Set the architecture to the exe architecture.
1671     m_arch = exe_module_sp->GetArchitecture();
1672     if (log)
1673         log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
1674 
1675     m_pid = pid;
1676     SetState(eStateAttaching);
1677 
1678     sem_init (&m_operation_pending, 0, 0);
1679     sem_init (&m_operation_done, 0, 0);
1680 
1681     std::unique_ptr<AttachArgs> args (new AttachArgs (this, pid));
1682 
1683     StartAttachOpThread(args.get (), error);
1684     if (!error.Success ())
1685         return;
1686 
1687     error = StartCoordinatorThread ();
1688     if (!error.Success ())
1689         return;
1690 
1691 WAIT_AGAIN:
1692     // Wait for the operation thread to initialize.
1693     if (sem_wait (&args->m_semaphore))
1694     {
1695         if (errno == EINTR)
1696             goto WAIT_AGAIN;
1697         else
1698         {
1699             error.SetErrorToErrno ();
1700             return;
1701         }
1702     }
1703 
1704     // Check that the attach was a success.
1705     if (!args->m_error.Success ())
1706     {
1707         StopOpThread ();
1708         StopCoordinatorThread ();
1709         error = args->m_error;
1710         return;
1711     }
1712 
1713     // Finally, start monitoring the child process for change in state.
1714     StartMonitorThread(error);
1715 }
1716 
1717 void
1718 NativeProcessLinux::Terminate ()
1719 {
1720     StopMonitor();
1721 }
1722 
1723 //------------------------------------------------------------------------------
1724 // Thread setup and tear down.
1725 
1726 void
1727 NativeProcessLinux::StartLaunchOpThread(LaunchArgs *args, Error &error)
1728 {
1729     static const char *g_thread_name = "lldb.process.nativelinux.operation";
1730 
1731     if (m_operation_thread.IsJoinable())
1732         return;
1733 
1734     m_operation_thread = ThreadLauncher::LaunchThread(g_thread_name, LaunchOpThread, args, &error);
1735 }
1736 
1737 void *
1738 NativeProcessLinux::LaunchOpThread(void *arg)
1739 {
1740     LaunchArgs *args = static_cast<LaunchArgs*>(arg);
1741 
1742     if (!Launch(args)) {
1743         sem_post(&args->m_semaphore);
1744         return NULL;
1745     }
1746 
1747     ServeOperation(args);
1748     return NULL;
1749 }
1750 
1751 bool
1752 NativeProcessLinux::Launch(LaunchArgs *args)
1753 {
1754     assert (args && "null args");
1755     if (!args)
1756         return false;
1757 
1758     NativeProcessLinux *monitor = args->m_monitor;
1759     assert (monitor && "monitor is NULL");
1760 
1761     const char **argv = args->m_argv;
1762     const char **envp = args->m_envp;
1763     const char *working_dir = args->m_working_dir;
1764 
1765     lldb_utility::PseudoTerminal terminal;
1766     const size_t err_len = 1024;
1767     char err_str[err_len];
1768     lldb::pid_t pid;
1769     NativeThreadProtocolSP thread_sp;
1770 
1771     lldb::ThreadSP inferior;
1772 
1773     // Propagate the environment if one is not supplied.
1774     if (envp == NULL || envp[0] == NULL)
1775         envp = const_cast<const char **>(environ);
1776 
1777     if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
1778     {
1779         args->m_error.SetErrorToGenericError();
1780         args->m_error.SetErrorString("Process fork failed.");
1781         return false;
1782     }
1783 
1784     // Recognized child exit status codes.
1785     enum {
1786         ePtraceFailed = 1,
1787         eDupStdinFailed,
1788         eDupStdoutFailed,
1789         eDupStderrFailed,
1790         eChdirFailed,
1791         eExecFailed,
1792         eSetGidFailed
1793     };
1794 
1795     // Child process.
1796     if (pid == 0)
1797     {
1798         // FIXME consider opening a pipe between parent/child and have this forked child
1799         // send log info to parent re: launch status, in place of the log lines removed here.
1800 
1801         // Start tracing this child that is about to exec.
1802         PTRACE(PTRACE_TRACEME, 0, nullptr, nullptr, 0, args->m_error);
1803         if (args->m_error.Fail())
1804             exit(ePtraceFailed);
1805 
1806         // terminal has already dupped the tty descriptors to stdin/out/err.
1807         // This closes original fd from which they were copied (and avoids
1808         // leaking descriptors to the debugged process.
1809         terminal.CloseSlaveFileDescriptor();
1810 
1811         // Do not inherit setgid powers.
1812         if (setgid(getgid()) != 0)
1813             exit(eSetGidFailed);
1814 
1815         // Attempt to have our own process group.
1816         if (setpgid(0, 0) != 0)
1817         {
1818             // FIXME log that this failed. This is common.
1819             // Don't allow this to prevent an inferior exec.
1820         }
1821 
1822         // Dup file descriptors if needed.
1823         if (!args->m_stdin_path.empty ())
1824             if (!DupDescriptor(args->m_stdin_path.c_str (), STDIN_FILENO, O_RDONLY))
1825                 exit(eDupStdinFailed);
1826 
1827         if (!args->m_stdout_path.empty ())
1828             if (!DupDescriptor(args->m_stdout_path.c_str (), STDOUT_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
1829                 exit(eDupStdoutFailed);
1830 
1831         if (!args->m_stderr_path.empty ())
1832             if (!DupDescriptor(args->m_stderr_path.c_str (), STDERR_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
1833                 exit(eDupStderrFailed);
1834 
1835         // Change working directory
1836         if (working_dir != NULL && working_dir[0])
1837           if (0 != ::chdir(working_dir))
1838               exit(eChdirFailed);
1839 
1840         // Disable ASLR if requested.
1841         if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR))
1842         {
1843             const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
1844             if (old_personality == -1)
1845             {
1846                 // Can't retrieve Linux personality.  Cannot disable ASLR.
1847             }
1848             else
1849             {
1850                 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality);
1851                 if (new_personality == -1)
1852                 {
1853                     // Disabling ASLR failed.
1854                 }
1855                 else
1856                 {
1857                     // Disabling ASLR succeeded.
1858                 }
1859             }
1860         }
1861 
1862         // Execute.  We should never return...
1863         execve(argv[0],
1864                const_cast<char *const *>(argv),
1865                const_cast<char *const *>(envp));
1866 
1867         // ...unless exec fails.  In which case we definitely need to end the child here.
1868         exit(eExecFailed);
1869     }
1870 
1871     //
1872     // This is the parent code here.
1873     //
1874     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1875 
1876     // Wait for the child process to trap on its call to execve.
1877     ::pid_t wpid;
1878     int status;
1879     if ((wpid = waitpid(pid, &status, 0)) < 0)
1880     {
1881         args->m_error.SetErrorToErrno();
1882 
1883         if (log)
1884             log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s", __FUNCTION__, args->m_error.AsCString ());
1885 
1886         // Mark the inferior as invalid.
1887         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
1888         monitor->SetState (StateType::eStateInvalid);
1889 
1890         return false;
1891     }
1892     else if (WIFEXITED(status))
1893     {
1894         // open, dup or execve likely failed for some reason.
1895         args->m_error.SetErrorToGenericError();
1896         switch (WEXITSTATUS(status))
1897         {
1898             case ePtraceFailed:
1899                 args->m_error.SetErrorString("Child ptrace failed.");
1900                 break;
1901             case eDupStdinFailed:
1902                 args->m_error.SetErrorString("Child open stdin failed.");
1903                 break;
1904             case eDupStdoutFailed:
1905                 args->m_error.SetErrorString("Child open stdout failed.");
1906                 break;
1907             case eDupStderrFailed:
1908                 args->m_error.SetErrorString("Child open stderr failed.");
1909                 break;
1910             case eChdirFailed:
1911                 args->m_error.SetErrorString("Child failed to set working directory.");
1912                 break;
1913             case eExecFailed:
1914                 args->m_error.SetErrorString("Child exec failed.");
1915                 break;
1916             case eSetGidFailed:
1917                 args->m_error.SetErrorString("Child setgid failed.");
1918                 break;
1919             default:
1920                 args->m_error.SetErrorString("Child returned unknown exit status.");
1921                 break;
1922         }
1923 
1924         if (log)
1925         {
1926             log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
1927                     __FUNCTION__,
1928                     WEXITSTATUS(status));
1929         }
1930 
1931         // Mark the inferior as invalid.
1932         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
1933         monitor->SetState (StateType::eStateInvalid);
1934 
1935         return false;
1936     }
1937     assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
1938            "Could not sync with inferior process.");
1939 
1940     if (log)
1941         log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
1942 
1943     args->m_error = SetDefaultPtraceOpts(pid);
1944     if (args->m_error.Fail())
1945     {
1946         if (log)
1947             log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
1948                     __FUNCTION__,
1949                     args->m_error.AsCString ());
1950 
1951         // Mark the inferior as invalid.
1952         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
1953         monitor->SetState (StateType::eStateInvalid);
1954 
1955         return false;
1956     }
1957 
1958     // Release the master terminal descriptor and pass it off to the
1959     // NativeProcessLinux instance.  Similarly stash the inferior pid.
1960     monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1961     monitor->m_pid = pid;
1962 
1963     // Set the terminal fd to be in non blocking mode (it simplifies the
1964     // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1965     // descriptor to read from).
1966     if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error))
1967     {
1968         if (log)
1969             log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
1970                     __FUNCTION__,
1971                     args->m_error.AsCString ());
1972 
1973         // Mark the inferior as invalid.
1974         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
1975         monitor->SetState (StateType::eStateInvalid);
1976 
1977         return false;
1978     }
1979 
1980     if (log)
1981         log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
1982 
1983     thread_sp = monitor->AddThread (pid);
1984     assert (thread_sp && "AddThread() returned a nullptr thread");
1985     monitor->NotifyThreadCreateStopped (pid);
1986     std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
1987 
1988     // Let our process instance know the thread has stopped.
1989     monitor->SetCurrentThreadID (thread_sp->GetID ());
1990     monitor->SetState (StateType::eStateStopped);
1991 
1992     if (log)
1993     {
1994         if (args->m_error.Success ())
1995         {
1996             log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
1997         }
1998         else
1999         {
2000             log->Printf ("NativeProcessLinux::%s inferior launching failed: %s",
2001                 __FUNCTION__,
2002                 args->m_error.AsCString ());
2003         }
2004     }
2005     return args->m_error.Success();
2006 }
2007 
2008 void
2009 NativeProcessLinux::StartAttachOpThread(AttachArgs *args, Error &error)
2010 {
2011     static const char *g_thread_name = "lldb.process.linux.operation";
2012 
2013     if (m_operation_thread.IsJoinable())
2014         return;
2015 
2016     m_operation_thread = ThreadLauncher::LaunchThread(g_thread_name, AttachOpThread, args, &error);
2017 }
2018 
2019 void *
2020 NativeProcessLinux::AttachOpThread(void *arg)
2021 {
2022     AttachArgs *args = static_cast<AttachArgs*>(arg);
2023 
2024     if (!Attach(args)) {
2025         sem_post(&args->m_semaphore);
2026         return nullptr;
2027     }
2028 
2029     ServeOperation(args);
2030     return nullptr;
2031 }
2032 
2033 bool
2034 NativeProcessLinux::Attach(AttachArgs *args)
2035 {
2036     lldb::pid_t pid = args->m_pid;
2037 
2038     NativeProcessLinux *monitor = args->m_monitor;
2039     lldb::ThreadSP inferior;
2040     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2041 
2042     // Use a map to keep track of the threads which we have attached/need to attach.
2043     Host::TidMap tids_to_attach;
2044     if (pid <= 1)
2045     {
2046         args->m_error.SetErrorToGenericError();
2047         args->m_error.SetErrorString("Attaching to process 1 is not allowed.");
2048         goto FINISH;
2049     }
2050 
2051     while (Host::FindProcessThreads(pid, tids_to_attach))
2052     {
2053         for (Host::TidMap::iterator it = tids_to_attach.begin();
2054              it != tids_to_attach.end();)
2055         {
2056             if (it->second == false)
2057             {
2058                 lldb::tid_t tid = it->first;
2059 
2060                 // Attach to the requested process.
2061                 // An attach will cause the thread to stop with a SIGSTOP.
2062                 PTRACE(PTRACE_ATTACH, tid, nullptr, nullptr, 0, args->m_error);
2063                 if (args->m_error.Fail())
2064                 {
2065                     // No such thread. The thread may have exited.
2066                     // More error handling may be needed.
2067                     if (args->m_error.GetError() == ESRCH)
2068                     {
2069                         it = tids_to_attach.erase(it);
2070                         continue;
2071                     }
2072                     else
2073                         goto FINISH;
2074                 }
2075 
2076                 int status;
2077                 // Need to use __WALL otherwise we receive an error with errno=ECHLD
2078                 // At this point we should have a thread stopped if waitpid succeeds.
2079                 if ((status = waitpid(tid, NULL, __WALL)) < 0)
2080                 {
2081                     // No such thread. The thread may have exited.
2082                     // More error handling may be needed.
2083                     if (errno == ESRCH)
2084                     {
2085                         it = tids_to_attach.erase(it);
2086                         continue;
2087                     }
2088                     else
2089                     {
2090                         args->m_error.SetErrorToErrno();
2091                         goto FINISH;
2092                     }
2093                 }
2094 
2095                 args->m_error = SetDefaultPtraceOpts(tid);
2096                 if (args->m_error.Fail())
2097                     goto FINISH;
2098 
2099 
2100                 if (log)
2101                     log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
2102 
2103                 it->second = true;
2104 
2105                 // Create the thread, mark it as stopped.
2106                 NativeThreadProtocolSP thread_sp (monitor->AddThread (static_cast<lldb::tid_t> (tid)));
2107                 assert (thread_sp && "AddThread() returned a nullptr");
2108 
2109                 // This will notify this is a new thread and tell the system it is stopped.
2110                 monitor->NotifyThreadCreateStopped (tid);
2111                 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
2112                 monitor->SetCurrentThreadID (thread_sp->GetID ());
2113             }
2114 
2115             // move the loop forward
2116             ++it;
2117         }
2118     }
2119 
2120     if (tids_to_attach.size() > 0)
2121     {
2122         monitor->m_pid = pid;
2123         // Let our process instance know the thread has stopped.
2124         monitor->SetState (StateType::eStateStopped);
2125     }
2126     else
2127     {
2128         args->m_error.SetErrorToGenericError();
2129         args->m_error.SetErrorString("No such process.");
2130     }
2131 
2132  FINISH:
2133     return args->m_error.Success();
2134 }
2135 
2136 Error
2137 NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
2138 {
2139     long ptrace_opts = 0;
2140 
2141     // Have the child raise an event on exit.  This is used to keep the child in
2142     // limbo until it is destroyed.
2143     ptrace_opts |= PTRACE_O_TRACEEXIT;
2144 
2145     // Have the tracer trace threads which spawn in the inferior process.
2146     // TODO: if we want to support tracing the inferiors' child, add the
2147     // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
2148     ptrace_opts |= PTRACE_O_TRACECLONE;
2149 
2150     // Have the tracer notify us before execve returns
2151     // (needed to disable legacy SIGTRAP generation)
2152     ptrace_opts |= PTRACE_O_TRACEEXEC;
2153 
2154     Error error;
2155     PTRACE(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts, 0, error);
2156     return error;
2157 }
2158 
2159 static ExitType convert_pid_status_to_exit_type (int status)
2160 {
2161     if (WIFEXITED (status))
2162         return ExitType::eExitTypeExit;
2163     else if (WIFSIGNALED (status))
2164         return ExitType::eExitTypeSignal;
2165     else if (WIFSTOPPED (status))
2166         return ExitType::eExitTypeStop;
2167     else
2168     {
2169         // We don't know what this is.
2170         return ExitType::eExitTypeInvalid;
2171     }
2172 }
2173 
2174 static int convert_pid_status_to_return_code (int status)
2175 {
2176     if (WIFEXITED (status))
2177         return WEXITSTATUS (status);
2178     else if (WIFSIGNALED (status))
2179         return WTERMSIG (status);
2180     else if (WIFSTOPPED (status))
2181         return WSTOPSIG (status);
2182     else
2183     {
2184         // We don't know what this is.
2185         return ExitType::eExitTypeInvalid;
2186     }
2187 }
2188 
2189 // Handles all waitpid events from the inferior process.
2190 void
2191 NativeProcessLinux::MonitorCallback(lldb::pid_t pid,
2192                                     bool exited,
2193                                     int signal,
2194                                     int status)
2195 {
2196     Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
2197 
2198     // Certain activities differ based on whether the pid is the tid of the main thread.
2199     const bool is_main_thread = (pid == GetID ());
2200 
2201     // Handle when the thread exits.
2202     if (exited)
2203     {
2204         if (log)
2205             log->Printf ("NativeProcessLinux::%s() got exit signal(%d) , tid = %"  PRIu64 " (%s main thread)", __FUNCTION__, signal, pid, is_main_thread ? "is" : "is not");
2206 
2207         // This is a thread that exited.  Ensure we're not tracking it anymore.
2208         const bool thread_found = StopTrackingThread (pid);
2209 
2210         // Make sure the thread state coordinator knows about this.
2211         NotifyThreadDeath (pid);
2212 
2213         if (is_main_thread)
2214         {
2215             // We only set the exit status and notify the delegate if we haven't already set the process
2216             // state to an exited state.  We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
2217             // for the main thread.
2218             const bool already_notified = (GetState() == StateType::eStateExited) || (GetState () == StateType::eStateCrashed);
2219             if (!already_notified)
2220             {
2221                 if (log)
2222                     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 ()));
2223                 // The main thread exited.  We're done monitoring.  Report to delegate.
2224                 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
2225 
2226                 // Notify delegate that our process has exited.
2227                 SetState (StateType::eStateExited, true);
2228             }
2229             else
2230             {
2231                 if (log)
2232                     log->Printf ("NativeProcessLinux::%s() tid = %"  PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
2233             }
2234         }
2235         else
2236         {
2237             // Do we want to report to the delegate in this case?  I think not.  If this was an orderly
2238             // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
2239             // and we would have done an all-stop then.
2240             if (log)
2241                 log->Printf ("NativeProcessLinux::%s() tid = %"  PRIu64 " handling non-main thread exit (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
2242         }
2243         return;
2244     }
2245 
2246     // Get details on the signal raised.
2247     siginfo_t info;
2248     const auto err = GetSignalInfo(pid, &info);
2249     if (err.Success())
2250     {
2251         // We have retrieved the signal info.  Dispatch appropriately.
2252         if (info.si_signo == SIGTRAP)
2253             MonitorSIGTRAP(&info, pid);
2254         else
2255             MonitorSignal(&info, pid, exited);
2256     }
2257     else
2258     {
2259         if (err.GetError() == EINVAL)
2260         {
2261             // This is a group stop reception for this tid.
2262             if (log)
2263                 log->Printf ("NativeThreadLinux::%s received a group stop for pid %" PRIu64 " tid %" PRIu64, __FUNCTION__, GetID (), pid);
2264             NotifyThreadStop (pid);
2265         }
2266         else
2267         {
2268             // ptrace(GETSIGINFO) failed (but not due to group-stop).
2269 
2270             // A return value of ESRCH means the thread/process is no longer on the system,
2271             // so it was killed somehow outside of our control.  Either way, we can't do anything
2272             // with it anymore.
2273 
2274             // Stop tracking the metadata for the thread since it's entirely off the system now.
2275             const bool thread_found = StopTrackingThread (pid);
2276 
2277             // Make sure the thread state coordinator knows about this.
2278             NotifyThreadDeath (pid);
2279 
2280             if (log)
2281                 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
2282                              __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");
2283 
2284             if (is_main_thread)
2285             {
2286                 // Notify the delegate - our process is not available but appears to have been killed outside
2287                 // our control.  Is eStateExited the right exit state in this case?
2288                 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
2289                 SetState (StateType::eStateExited, true);
2290             }
2291             else
2292             {
2293                 // This thread was pulled out from underneath us.  Anything to do here? Do we want to do an all stop?
2294                 if (log)
2295                     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);
2296             }
2297         }
2298     }
2299 }
2300 
2301 void
2302 NativeProcessLinux::MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid)
2303 {
2304     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2305     const bool is_main_thread = (pid == GetID ());
2306 
2307     assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
2308     if (!info)
2309         return;
2310 
2311     Mutex::Locker locker (m_threads_mutex);
2312 
2313     // See if we can find a thread for this signal.
2314     NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2315     if (!thread_sp)
2316     {
2317         if (log)
2318             log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2319     }
2320 
2321     switch (info->si_code)
2322     {
2323     // TODO: these two cases are required if we want to support tracing of the inferiors' children.  We'd need this to debug a monitor.
2324     // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
2325     // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
2326 
2327     case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
2328     {
2329         lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2330 
2331         // The main thread is stopped here.
2332         if (thread_sp)
2333             std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGTRAP);
2334         NotifyThreadStop (pid);
2335 
2336         unsigned long event_message = 0;
2337         if (GetEventMessage (pid, &event_message).Success())
2338         {
2339             tid = static_cast<lldb::tid_t> (event_message);
2340             if (log)
2341                 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " received thread creation event for tid %" PRIu64, __FUNCTION__, pid, tid);
2342 
2343             // If we don't track the thread yet: create it, mark as stopped.
2344             // If we do track it, this is the wait we needed.  Now resume the new thread.
2345             // In all cases, resume the current (i.e. main process) thread.
2346             bool created_now = false;
2347             NativeThreadProtocolSP new_thread_sp = GetOrCreateThread (tid, created_now);
2348             assert (new_thread_sp.get() && "failed to get or create the tracking data for newly created inferior thread");
2349 
2350             // If the thread was already tracked, it means the created thread already received its SI_USER notification of creation.
2351             if (!created_now)
2352             {
2353                 // We can now resume the newly created thread since it is fully created.
2354                 NotifyThreadCreateStopped (tid);
2355                 m_coordinator_up->RequestThreadResume (tid,
2356                                                        [=](lldb::tid_t tid_to_resume, bool supress_signal)
2357                                                        {
2358                                                            std::static_pointer_cast<NativeThreadLinux> (new_thread_sp)->SetRunning ();
2359                                                            return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
2360                                                        },
2361                                                        CoordinatorErrorHandler);
2362             }
2363             else
2364             {
2365                 // Mark the thread as currently launching.  Need to wait for SIGTRAP clone on the main thread before
2366                 // this thread is ready to go.
2367                 std::static_pointer_cast<NativeThreadLinux> (new_thread_sp)->SetLaunching ();
2368             }
2369         }
2370         else
2371         {
2372             if (log)
2373                 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " received thread creation event but GetEventMessage failed so we don't know the new tid", __FUNCTION__, pid);
2374         }
2375 
2376         // In all cases, we can resume the main thread here.
2377         m_coordinator_up->RequestThreadResume (pid,
2378                                                [=](lldb::tid_t tid_to_resume, bool supress_signal)
2379                                                {
2380                                                    std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2381                                                    return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
2382                                                },
2383                                                CoordinatorErrorHandler);
2384 
2385         break;
2386     }
2387 
2388     case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
2389     {
2390         NativeThreadProtocolSP main_thread_sp;
2391         if (log)
2392             log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
2393 
2394         // The thread state coordinator needs to reset due to the exec.
2395         m_coordinator_up->ResetForExec ();
2396 
2397         // Remove all but the main thread here.  Linux fork creates a new process which only copies the main thread.  Mutexes are in undefined state.
2398         if (log)
2399             log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
2400 
2401         for (auto thread_sp : m_threads)
2402         {
2403             const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
2404             if (is_main_thread)
2405             {
2406                 main_thread_sp = thread_sp;
2407                 if (log)
2408                     log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
2409             }
2410             else
2411             {
2412                 // Tell thread coordinator this thread is dead.
2413                 if (log)
2414                     log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
2415             }
2416         }
2417 
2418         m_threads.clear ();
2419 
2420         if (main_thread_sp)
2421         {
2422             m_threads.push_back (main_thread_sp);
2423             SetCurrentThreadID (main_thread_sp->GetID ());
2424             std::static_pointer_cast<NativeThreadLinux> (main_thread_sp)->SetStoppedByExec ();
2425         }
2426         else
2427         {
2428             SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
2429             if (log)
2430                 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
2431         }
2432 
2433         // Tell coordinator about about the "new" (since exec) stopped main thread.
2434         const lldb::tid_t main_thread_tid = GetID ();
2435         NotifyThreadCreateStopped (main_thread_tid);
2436 
2437         // NOTE: ideally these next statements would execute at the same time as the coordinator thread create was executed.
2438         // Consider a handler that can execute when that happens.
2439         // Let our delegate know we have just exec'd.
2440         NotifyDidExec ();
2441 
2442         // If we have a main thread, indicate we are stopped.
2443         assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
2444 
2445         // Let the process know we're stopped.
2446         CallAfterRunningThreadsStop (pid,
2447                                      [=] (lldb::tid_t signaling_tid)
2448                                      {
2449                                          SetState (StateType::eStateStopped, true);
2450                                      });
2451 
2452         break;
2453     }
2454 
2455     case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
2456     {
2457         // The inferior process or one of its threads is about to exit.
2458 
2459         // This thread is currently stopped.  It's not actually dead yet, just about to be.
2460         NotifyThreadStop (pid);
2461 
2462         unsigned long data = 0;
2463         if (GetEventMessage(pid, &data).Fail())
2464             data = -1;
2465 
2466         if (log)
2467         {
2468             log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
2469                          __FUNCTION__,
2470                          data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
2471                          pid,
2472                     is_main_thread ? "is main thread" : "not main thread");
2473         }
2474 
2475         if (is_main_thread)
2476         {
2477             SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
2478         }
2479 
2480         const int signo = static_cast<int> (data);
2481         m_coordinator_up->RequestThreadResume (pid,
2482                                                [=](lldb::tid_t tid_to_resume, bool supress_signal)
2483                                                {
2484                                                    std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2485                                                    return Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo);
2486                                                },
2487                                                CoordinatorErrorHandler);
2488 
2489         break;
2490     }
2491 
2492     case 0:
2493     case TRAP_TRACE:  // We receive this on single stepping.
2494     case TRAP_HWBKPT: // We receive this on watchpoint hit
2495         if (thread_sp)
2496         {
2497             // If a watchpoint was hit, report it
2498             uint32_t wp_index;
2499             Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index);
2500             if (error.Fail() && log)
2501                 log->Printf("NativeProcessLinux::%s() "
2502                             "received error while checking for watchpoint hits, "
2503                             "pid = %" PRIu64 " error = %s",
2504                             __FUNCTION__, pid, error.AsCString());
2505             if (wp_index != LLDB_INVALID_INDEX32)
2506             {
2507                 MonitorWatchpoint(pid, thread_sp, wp_index);
2508                 break;
2509             }
2510         }
2511         // Otherwise, report step over
2512         MonitorTrace(pid, thread_sp);
2513         break;
2514 
2515     case SI_KERNEL:
2516     case TRAP_BRKPT:
2517         MonitorBreakpoint(pid, thread_sp);
2518         break;
2519 
2520     case SIGTRAP:
2521     case (SIGTRAP | 0x80):
2522         if (log)
2523             log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), pid);
2524 
2525         // This thread is currently stopped.
2526         NotifyThreadStop (pid);
2527         if (thread_sp)
2528             std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGTRAP);
2529 
2530 
2531         // Ignore these signals until we know more about them.
2532         m_coordinator_up->RequestThreadResume (pid,
2533                                                [=](lldb::tid_t tid_to_resume, bool supress_signal)
2534                                                {
2535                                                    std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2536                                                    return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
2537                                                },
2538                                                CoordinatorErrorHandler);
2539         break;
2540 
2541     default:
2542         assert(false && "Unexpected SIGTRAP code!");
2543         if (log)
2544             log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 "tid %" PRIu64 " received unhandled SIGTRAP code: 0x%" PRIx64, __FUNCTION__, GetID (), pid, static_cast<uint64_t> (SIGTRAP | (PTRACE_EVENT_CLONE << 8)));
2545         break;
2546 
2547     }
2548 }
2549 
2550 void
2551 NativeProcessLinux::MonitorTrace(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
2552 {
2553     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2554     if (log)
2555         log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)",
2556                 __FUNCTION__, pid);
2557 
2558     if (thread_sp)
2559         std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
2560 
2561     // This thread is currently stopped.
2562     NotifyThreadStop(pid);
2563 
2564     // Here we don't have to request the rest of the threads to stop or request a deferred stop.
2565     // This would have already happened at the time the Resume() with step operation was signaled.
2566     // At this point, we just need to say we stopped, and the deferred notifcation will fire off
2567     // once all running threads have checked in as stopped.
2568     SetCurrentThreadID(pid);
2569     // Tell the process we have a stop (from software breakpoint).
2570     CallAfterRunningThreadsStop(pid,
2571                                 [=](lldb::tid_t signaling_tid)
2572                                 {
2573                                    SetState(StateType::eStateStopped, true);
2574                                 });
2575 }
2576 
2577 void
2578 NativeProcessLinux::MonitorBreakpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
2579 {
2580     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
2581     if (log)
2582         log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
2583                 __FUNCTION__, pid);
2584 
2585     // This thread is currently stopped.
2586     NotifyThreadStop(pid);
2587 
2588     // Mark the thread as stopped at breakpoint.
2589     if (thread_sp)
2590     {
2591         std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByBreakpoint();
2592         Error error = FixupBreakpointPCAsNeeded(thread_sp);
2593         if (error.Fail())
2594             if (log)
2595                 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
2596                         __FUNCTION__, pid, error.AsCString());
2597 
2598         auto it = m_threads_stepping_with_breakpoint.find(pid);
2599         if (it != m_threads_stepping_with_breakpoint.end())
2600         {
2601             Error error = RemoveBreakpoint (it->second);
2602             if (error.Fail())
2603                 if (log)
2604                     log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " remove stepping breakpoint: %s",
2605                             __FUNCTION__, pid, error.AsCString());
2606 
2607             m_threads_stepping_with_breakpoint.erase(it);
2608             std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
2609         }
2610     }
2611     else
2612         if (log)
2613             log->Printf("NativeProcessLinux::%s()  pid = %" PRIu64 ": "
2614                     "warning, cannot process software breakpoint since no thread metadata",
2615                     __FUNCTION__, pid);
2616 
2617 
2618     // We need to tell all other running threads before we notify the delegate about this stop.
2619     CallAfterRunningThreadsStop(pid,
2620                                 [=](lldb::tid_t deferred_notification_tid)
2621                                 {
2622                                     SetCurrentThreadID(deferred_notification_tid);
2623                                     // Tell the process we have a stop (from software breakpoint).
2624                                     SetState(StateType::eStateStopped, true);
2625                                 });
2626 }
2627 
2628 void
2629 NativeProcessLinux::MonitorWatchpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp, uint32_t wp_index)
2630 {
2631     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
2632     if (log)
2633         log->Printf("NativeProcessLinux::%s() received watchpoint event, "
2634                     "pid = %" PRIu64 ", wp_index = %" PRIu32,
2635                     __FUNCTION__, pid, wp_index);
2636 
2637     // This thread is currently stopped.
2638     NotifyThreadStop(pid);
2639 
2640     // Mark the thread as stopped at watchpoint.
2641     // The address is at (lldb::addr_t)info->si_addr if we need it.
2642     lldbassert(thread_sp && "thread_sp cannot be NULL");
2643     std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByWatchpoint(wp_index);
2644 
2645     // We need to tell all other running threads before we notify the delegate about this stop.
2646     CallAfterRunningThreadsStop(pid,
2647                                 [=](lldb::tid_t deferred_notification_tid)
2648                                 {
2649                                     SetCurrentThreadID(deferred_notification_tid);
2650                                     // Tell the process we have a stop (from watchpoint).
2651                                     SetState(StateType::eStateStopped, true);
2652                                 });
2653 }
2654 
2655 void
2656 NativeProcessLinux::MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited)
2657 {
2658     assert (info && "null info");
2659     if (!info)
2660         return;
2661 
2662     const int signo = info->si_signo;
2663     const bool is_from_llgs = info->si_pid == getpid ();
2664 
2665     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2666 
2667     // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
2668     // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
2669     // kill(2) or raise(3).  Similarly for tgkill(2) on Linux.
2670     //
2671     // IOW, user generated signals never generate what we consider to be a
2672     // "crash".
2673     //
2674     // Similarly, ACK signals generated by this monitor.
2675 
2676     Mutex::Locker locker (m_threads_mutex);
2677 
2678     // See if we can find a thread for this signal.
2679     NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2680     if (!thread_sp)
2681     {
2682         if (log)
2683             log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2684     }
2685 
2686     // Handle the signal.
2687     if (info->si_code == SI_TKILL || info->si_code == SI_USER)
2688     {
2689         if (log)
2690             log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
2691                             __FUNCTION__,
2692                             GetUnixSignals ().GetSignalAsCString (signo),
2693                             signo,
2694                             (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
2695                             info->si_pid,
2696                             is_from_llgs ? "from llgs" : "not from llgs",
2697                             pid);
2698     }
2699 
2700     // Check for new thread notification.
2701     if ((info->si_pid == 0) && (info->si_code == SI_USER))
2702     {
2703         // A new thread creation is being signaled.  This is one of two parts that come in
2704         // a non-deterministic order.  pid is the thread id.
2705         if (log)
2706             log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": new thread notification",
2707                      __FUNCTION__, GetID (), pid);
2708 
2709         // Did we already create the thread?
2710         bool created_now = false;
2711         thread_sp = GetOrCreateThread (pid, created_now);
2712         assert (thread_sp.get() && "failed to get or create the tracking data for newly created inferior thread");
2713 
2714         // If the thread was already tracked, it means the main thread already received its SIGTRAP for the create.
2715         if (!created_now)
2716         {
2717             // We can now resume the newly created thread since it is fully created.
2718             NotifyThreadCreateStopped (pid);
2719             m_coordinator_up->RequestThreadResume (pid,
2720                                                    [=](lldb::tid_t tid_to_resume, bool supress_signal)
2721                                                    {
2722                                                        std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2723                                                        return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
2724                                                    },
2725                                                    CoordinatorErrorHandler);
2726         }
2727         else
2728         {
2729             // Mark the thread as currently launching.  Need to wait for SIGTRAP clone on the main thread before
2730             // this thread is ready to go.
2731             std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetLaunching ();
2732         }
2733 
2734         // Done handling.
2735         return;
2736     }
2737 
2738     // Check for thread stop notification.
2739     if (is_from_llgs && (info->si_code == SI_TKILL) && (signo == SIGSTOP))
2740     {
2741         // This is a tgkill()-based stop.
2742         if (thread_sp)
2743         {
2744             if (log)
2745                 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
2746                              __FUNCTION__,
2747                              GetID (),
2748                              pid);
2749 
2750             // Check that we're not already marked with a stop reason.
2751             // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
2752             // the kernel signaled us with the thread stopping which we handled and marked as stopped,
2753             // and that, without an intervening resume, we received another stop.  It is more likely
2754             // that we are missing the marking of a run state somewhere if we find that the thread was
2755             // marked as stopped.
2756             std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
2757             assert (linux_thread_sp && "linux_thread_sp is null!");
2758 
2759             const StateType thread_state = linux_thread_sp->GetState ();
2760             if (!StateIsStoppedState (thread_state, false))
2761             {
2762                 // An inferior thread just stopped, but was not the primary cause of the process stop.
2763                 // Instead, something else (like a breakpoint or step) caused the stop.  Mark the
2764                 // stop signal as 0 to let lldb know this isn't the important stop.
2765                 linux_thread_sp->SetStoppedBySignal (0);
2766                 SetCurrentThreadID (thread_sp->GetID ());
2767                 m_coordinator_up->NotifyThreadStop (thread_sp->GetID (), true, CoordinatorErrorHandler);
2768             }
2769             else
2770             {
2771                 if (log)
2772                 {
2773                     // Retrieve the signal name if the thread was stopped by a signal.
2774                     int stop_signo = 0;
2775                     const bool stopped_by_signal = linux_thread_sp->IsStopped (&stop_signo);
2776                     const char *signal_name = stopped_by_signal ? GetUnixSignals ().GetSignalAsCString (stop_signo) : "<not stopped by signal>";
2777                     if (!signal_name)
2778                         signal_name = "<no-signal-name>";
2779 
2780                     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",
2781                                  __FUNCTION__,
2782                                  GetID (),
2783                                  linux_thread_sp->GetID (),
2784                                  StateAsCString (thread_state),
2785                                  stop_signo,
2786                                  signal_name);
2787                 }
2788                 // Tell the thread state coordinator about the stop.
2789                 NotifyThreadStop (thread_sp->GetID ());
2790             }
2791         }
2792 
2793         // Done handling.
2794         return;
2795     }
2796 
2797     if (log)
2798         log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, GetUnixSignals ().GetSignalAsCString (signo));
2799 
2800     // This thread is stopped.
2801     NotifyThreadStop (pid);
2802 
2803     switch (signo)
2804     {
2805     case SIGSTOP:
2806         {
2807             if (log)
2808             {
2809                 if (is_from_llgs)
2810                     log->Printf ("NativeProcessLinux::%s pid = %" PRIu64 " tid %" PRIu64 " received SIGSTOP from llgs, most likely an interrupt", __FUNCTION__, GetID (), pid);
2811                 else
2812                     log->Printf ("NativeProcessLinux::%s pid = %" PRIu64 " tid %" PRIu64 " received SIGSTOP from outside of debugger", __FUNCTION__, GetID (), pid);
2813             }
2814 
2815             // Resume this thread to get the group-stop mechanism to fire off the true group stops.
2816             // This thread will get stopped again as part of the group-stop completion.
2817             m_coordinator_up->RequestThreadResume (pid,
2818                                                    [=](lldb::tid_t tid_to_resume, bool supress_signal)
2819                                                    {
2820                                                        std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2821                                                        // Pass this signal number on to the inferior to handle.
2822                                                        return Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo);
2823                                                    },
2824                                                    CoordinatorErrorHandler);
2825         }
2826         break;
2827     case SIGSEGV:
2828     case SIGILL:
2829     case SIGFPE:
2830     case SIGBUS:
2831         if (thread_sp)
2832             std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetCrashedWithException (*info);
2833         break;
2834     default:
2835         // This is just a pre-signal-delivery notification of the incoming signal.
2836         if (thread_sp)
2837             std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (signo);
2838 
2839         break;
2840     }
2841 
2842     // Send a stop to the debugger after we get all other threads to stop.
2843     CallAfterRunningThreadsStop (pid,
2844                                  [=] (lldb::tid_t signaling_tid)
2845                                  {
2846                                      SetCurrentThreadID (signaling_tid);
2847                                      SetState (StateType::eStateStopped, true);
2848                                  });
2849 }
2850 
2851 Error
2852 NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
2853 {
2854     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2855     if (log)
2856         log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
2857 
2858     lldb::tid_t deferred_signal_tid = LLDB_INVALID_THREAD_ID;
2859     lldb::tid_t deferred_signal_skip_tid = LLDB_INVALID_THREAD_ID;
2860     int deferred_signo = 0;
2861     NativeThreadProtocolSP deferred_signal_thread_sp;
2862     bool stepping = false;
2863 
2864     Mutex::Locker locker (m_threads_mutex);
2865 
2866     for (auto thread_sp : m_threads)
2867     {
2868         assert (thread_sp && "thread list should not contain NULL threads");
2869 
2870         const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
2871 
2872         if (action == nullptr)
2873         {
2874             if (log)
2875                 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
2876                     __FUNCTION__, GetID (), thread_sp->GetID ());
2877             continue;
2878         }
2879 
2880         if (log)
2881         {
2882             log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
2883                     __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
2884         }
2885 
2886         switch (action->state)
2887         {
2888         case eStateRunning:
2889         {
2890             // Run the thread, possibly feeding it the signal.
2891             const int signo = action->signal;
2892             m_coordinator_up->RequestThreadResumeAsNeeded (thread_sp->GetID (),
2893                                                            [=](lldb::tid_t tid_to_resume, bool supress_signal)
2894                                                            {
2895                                                                std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2896                                                                // Pass this signal number on to the inferior to handle.
2897                                                                const auto resume_result = Resume (tid_to_resume, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
2898                                                                if (resume_result.Success())
2899                                                                    SetState(eStateRunning, true);
2900                                                                return resume_result;
2901                                                            },
2902                                                            CoordinatorErrorHandler);
2903             break;
2904         }
2905 
2906         case eStateStepping:
2907         {
2908             // Request the step.
2909             const int signo = action->signal;
2910             m_coordinator_up->RequestThreadResume (thread_sp->GetID (),
2911                                                    [=](lldb::tid_t tid_to_step, bool supress_signal)
2912                                                    {
2913                                                        std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStepping ();
2914                                                        const auto step_result = SingleStep (tid_to_step,(signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
2915                                                        assert (step_result.Success() && "SingleStep() failed");
2916                                                        if (step_result.Success())
2917                                                            SetState(eStateStepping, true);
2918                                                        return step_result;
2919                                                    },
2920                                                    CoordinatorErrorHandler);
2921             stepping = true;
2922             break;
2923         }
2924 
2925         case eStateSuspended:
2926         case eStateStopped:
2927             // if we haven't chosen a deferred signal tid yet, use this one.
2928             if (deferred_signal_tid == LLDB_INVALID_THREAD_ID)
2929             {
2930                 deferred_signal_tid = thread_sp->GetID ();
2931                 deferred_signal_thread_sp = thread_sp;
2932                 deferred_signo = SIGSTOP;
2933             }
2934             break;
2935 
2936         default:
2937             return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
2938                     __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
2939         }
2940     }
2941 
2942     // If we had any thread stopping, then do a deferred notification of the chosen stop thread id and signal
2943     // after all other running threads have stopped.
2944     // If there is a stepping thread involved we'll be eventually stopped by SIGTRAP trace signal.
2945     if (deferred_signal_tid != LLDB_INVALID_THREAD_ID && !stepping)
2946     {
2947         CallAfterRunningThreadsStopWithSkipTID (deferred_signal_tid,
2948                                                 deferred_signal_skip_tid,
2949                                      [=](lldb::tid_t deferred_notification_tid)
2950                                      {
2951                                          // Set the signal thread to the current thread.
2952                                          SetCurrentThreadID (deferred_notification_tid);
2953 
2954                                          // Set the thread state as stopped by the deferred signo.
2955                                          std::static_pointer_cast<NativeThreadLinux> (deferred_signal_thread_sp)->SetStoppedBySignal (deferred_signo);
2956 
2957                                          // Tell the process delegate that the process is in a stopped state.
2958                                          SetState (StateType::eStateStopped, true);
2959                                      });
2960     }
2961 
2962     return Error();
2963 }
2964 
2965 Error
2966 NativeProcessLinux::Halt ()
2967 {
2968     Error error;
2969 
2970     if (kill (GetID (), SIGSTOP) != 0)
2971         error.SetErrorToErrno ();
2972 
2973     return error;
2974 }
2975 
2976 Error
2977 NativeProcessLinux::Detach ()
2978 {
2979     Error error;
2980 
2981     // Tell ptrace to detach from the process.
2982     if (GetID () != LLDB_INVALID_PROCESS_ID)
2983         error = Detach (GetID ());
2984 
2985     // Stop monitoring the inferior.
2986     StopMonitor ();
2987 
2988     // No error.
2989     return error;
2990 }
2991 
2992 Error
2993 NativeProcessLinux::Signal (int signo)
2994 {
2995     Error error;
2996 
2997     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2998     if (log)
2999         log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
3000                 __FUNCTION__, signo,  GetUnixSignals ().GetSignalAsCString (signo), GetID ());
3001 
3002     if (kill(GetID(), signo))
3003         error.SetErrorToErrno();
3004 
3005     return error;
3006 }
3007 
3008 Error
3009 NativeProcessLinux::Interrupt ()
3010 {
3011     // Pick a running thread (or if none, a not-dead stopped thread) as
3012     // the chosen thread that will be the stop-reason thread.
3013     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3014 
3015     NativeThreadProtocolSP running_thread_sp;
3016     NativeThreadProtocolSP stopped_thread_sp;
3017 
3018     if (log)
3019         log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
3020 
3021     Mutex::Locker locker (m_threads_mutex);
3022 
3023     for (auto thread_sp : m_threads)
3024     {
3025         // The thread shouldn't be null but lets just cover that here.
3026         if (!thread_sp)
3027             continue;
3028 
3029         // If we have a running or stepping thread, we'll call that the
3030         // target of the interrupt.
3031         const auto thread_state = thread_sp->GetState ();
3032         if (thread_state == eStateRunning ||
3033             thread_state == eStateStepping)
3034         {
3035             running_thread_sp = thread_sp;
3036             break;
3037         }
3038         else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
3039         {
3040             // Remember the first non-dead stopped thread.  We'll use that as a backup if there are no running threads.
3041             stopped_thread_sp = thread_sp;
3042         }
3043     }
3044 
3045     if (!running_thread_sp && !stopped_thread_sp)
3046     {
3047         Error error("found no running/stepping or live stopped threads as target for interrupt");
3048         if (log)
3049             log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
3050 
3051         return error;
3052     }
3053 
3054     NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
3055 
3056     if (log)
3057         log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
3058                      __FUNCTION__,
3059                      GetID (),
3060                      running_thread_sp ? "running" : "stopped",
3061                      deferred_signal_thread_sp->GetID ());
3062 
3063     CallAfterRunningThreadsStop (deferred_signal_thread_sp->GetID (),
3064                                  [=](lldb::tid_t deferred_notification_tid)
3065                                  {
3066                                      // Set the signal thread to the current thread.
3067                                      SetCurrentThreadID (deferred_notification_tid);
3068 
3069                                      // Set the thread state as stopped by the deferred signo.
3070                                      std::static_pointer_cast<NativeThreadLinux> (deferred_signal_thread_sp)->SetStoppedBySignal (SIGSTOP);
3071 
3072                                      // Tell the process delegate that the process is in a stopped state.
3073                                      SetState (StateType::eStateStopped, true);
3074                                  });
3075     return Error();
3076 }
3077 
3078 Error
3079 NativeProcessLinux::Kill ()
3080 {
3081     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3082     if (log)
3083         log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
3084 
3085     Error error;
3086 
3087     switch (m_state)
3088     {
3089         case StateType::eStateInvalid:
3090         case StateType::eStateExited:
3091         case StateType::eStateCrashed:
3092         case StateType::eStateDetached:
3093         case StateType::eStateUnloaded:
3094             // Nothing to do - the process is already dead.
3095             if (log)
3096                 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
3097             return error;
3098 
3099         case StateType::eStateConnected:
3100         case StateType::eStateAttaching:
3101         case StateType::eStateLaunching:
3102         case StateType::eStateStopped:
3103         case StateType::eStateRunning:
3104         case StateType::eStateStepping:
3105         case StateType::eStateSuspended:
3106             // We can try to kill a process in these states.
3107             break;
3108     }
3109 
3110     if (kill (GetID (), SIGKILL) != 0)
3111     {
3112         error.SetErrorToErrno ();
3113         return error;
3114     }
3115 
3116     return error;
3117 }
3118 
3119 static Error
3120 ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
3121 {
3122     memory_region_info.Clear();
3123 
3124     StringExtractor line_extractor (maps_line.c_str ());
3125 
3126     // Format: {address_start_hex}-{address_end_hex} perms offset  dev   inode   pathname
3127     // perms: rwxp   (letter is present if set, '-' if not, final character is p=private, s=shared).
3128 
3129     // Parse out the starting address
3130     lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
3131 
3132     // Parse out hyphen separating start and end address from range.
3133     if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
3134         return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
3135 
3136     // Parse out the ending address
3137     lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
3138 
3139     // Parse out the space after the address.
3140     if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
3141         return Error ("malformed /proc/{pid}/maps entry, missing space after range");
3142 
3143     // Save the range.
3144     memory_region_info.GetRange ().SetRangeBase (start_address);
3145     memory_region_info.GetRange ().SetRangeEnd (end_address);
3146 
3147     // Parse out each permission entry.
3148     if (line_extractor.GetBytesLeft () < 4)
3149         return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
3150 
3151     // Handle read permission.
3152     const char read_perm_char = line_extractor.GetChar ();
3153     if (read_perm_char == 'r')
3154         memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
3155     else
3156     {
3157         assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
3158         memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
3159     }
3160 
3161     // Handle write permission.
3162     const char write_perm_char = line_extractor.GetChar ();
3163     if (write_perm_char == 'w')
3164         memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
3165     else
3166     {
3167         assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
3168         memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
3169     }
3170 
3171     // Handle execute permission.
3172     const char exec_perm_char = line_extractor.GetChar ();
3173     if (exec_perm_char == 'x')
3174         memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
3175     else
3176     {
3177         assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
3178         memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
3179     }
3180 
3181     return Error ();
3182 }
3183 
3184 Error
3185 NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
3186 {
3187     // FIXME review that the final memory region returned extends to the end of the virtual address space,
3188     // with no perms if it is not mapped.
3189 
3190     // Use an approach that reads memory regions from /proc/{pid}/maps.
3191     // Assume proc maps entries are in ascending order.
3192     // FIXME assert if we find differently.
3193     Mutex::Locker locker (m_mem_region_cache_mutex);
3194 
3195     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3196     Error error;
3197 
3198     if (m_supports_mem_region == LazyBool::eLazyBoolNo)
3199     {
3200         // We're done.
3201         error.SetErrorString ("unsupported");
3202         return error;
3203     }
3204 
3205     // If our cache is empty, pull the latest.  There should always be at least one memory region
3206     // if memory region handling is supported.
3207     if (m_mem_region_cache.empty ())
3208     {
3209         error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
3210              [&] (const std::string &line) -> bool
3211              {
3212                  MemoryRegionInfo info;
3213                  const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
3214                  if (parse_error.Success ())
3215                  {
3216                      m_mem_region_cache.push_back (info);
3217                      return true;
3218                  }
3219                  else
3220                  {
3221                      if (log)
3222                          log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
3223                      return false;
3224                  }
3225              });
3226 
3227         // If we had an error, we'll mark unsupported.
3228         if (error.Fail ())
3229         {
3230             m_supports_mem_region = LazyBool::eLazyBoolNo;
3231             return error;
3232         }
3233         else if (m_mem_region_cache.empty ())
3234         {
3235             // No entries after attempting to read them.  This shouldn't happen if /proc/{pid}/maps
3236             // is supported.  Assume we don't support map entries via procfs.
3237             if (log)
3238                 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
3239             m_supports_mem_region = LazyBool::eLazyBoolNo;
3240             error.SetErrorString ("not supported");
3241             return error;
3242         }
3243 
3244         if (log)
3245             log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ());
3246 
3247         // We support memory retrieval, remember that.
3248         m_supports_mem_region = LazyBool::eLazyBoolYes;
3249     }
3250     else
3251     {
3252         if (log)
3253             log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
3254     }
3255 
3256     lldb::addr_t prev_base_address = 0;
3257 
3258     // FIXME start by finding the last region that is <= target address using binary search.  Data is sorted.
3259     // There can be a ton of regions on pthreads apps with lots of threads.
3260     for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
3261     {
3262         MemoryRegionInfo &proc_entry_info = *it;
3263 
3264         // Sanity check assumption that /proc/{pid}/maps entries are ascending.
3265         assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
3266         prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
3267 
3268         // If the target address comes before this entry, indicate distance to next region.
3269         if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
3270         {
3271             range_info.GetRange ().SetRangeBase (load_addr);
3272             range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
3273             range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
3274             range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
3275             range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
3276 
3277             return error;
3278         }
3279         else if (proc_entry_info.GetRange ().Contains (load_addr))
3280         {
3281             // The target address is within the memory region we're processing here.
3282             range_info = proc_entry_info;
3283             return error;
3284         }
3285 
3286         // The target memory address comes somewhere after the region we just parsed.
3287     }
3288 
3289     // If we made it here, we didn't find an entry that contained the given address.
3290     error.SetErrorString ("address comes after final region");
3291 
3292     if (log)
3293         log->Printf ("NativeProcessLinux::%s failed to find map entry for address 0x%" PRIx64 ": %s", __FUNCTION__, load_addr, error.AsCString ());
3294 
3295     return error;
3296 }
3297 
3298 void
3299 NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
3300 {
3301     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3302     if (log)
3303         log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
3304 
3305     {
3306         Mutex::Locker locker (m_mem_region_cache_mutex);
3307         if (log)
3308             log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
3309         m_mem_region_cache.clear ();
3310     }
3311 }
3312 
3313 Error
3314 NativeProcessLinux::AllocateMemory (
3315     lldb::addr_t size,
3316     uint32_t permissions,
3317     lldb::addr_t &addr)
3318 {
3319     // FIXME implementing this requires the equivalent of
3320     // InferiorCallPOSIX::InferiorCallMmap, which depends on
3321     // functional ThreadPlans working with Native*Protocol.
3322 #if 1
3323     return Error ("not implemented yet");
3324 #else
3325     addr = LLDB_INVALID_ADDRESS;
3326 
3327     unsigned prot = 0;
3328     if (permissions & lldb::ePermissionsReadable)
3329         prot |= eMmapProtRead;
3330     if (permissions & lldb::ePermissionsWritable)
3331         prot |= eMmapProtWrite;
3332     if (permissions & lldb::ePermissionsExecutable)
3333         prot |= eMmapProtExec;
3334 
3335     // TODO implement this directly in NativeProcessLinux
3336     // (and lift to NativeProcessPOSIX if/when that class is
3337     // refactored out).
3338     if (InferiorCallMmap(this, addr, 0, size, prot,
3339                          eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
3340         m_addr_to_mmap_size[addr] = size;
3341         return Error ();
3342     } else {
3343         addr = LLDB_INVALID_ADDRESS;
3344         return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
3345     }
3346 #endif
3347 }
3348 
3349 Error
3350 NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
3351 {
3352     // FIXME see comments in AllocateMemory - required lower-level
3353     // bits not in place yet (ThreadPlans)
3354     return Error ("not implemented");
3355 }
3356 
3357 lldb::addr_t
3358 NativeProcessLinux::GetSharedLibraryInfoAddress ()
3359 {
3360 #if 1
3361     // punt on this for now
3362     return LLDB_INVALID_ADDRESS;
3363 #else
3364     // Return the image info address for the exe module
3365 #if 1
3366     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3367 
3368     ModuleSP module_sp;
3369     Error error = GetExeModuleSP (module_sp);
3370     if (error.Fail ())
3371     {
3372          if (log)
3373             log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ());
3374         return LLDB_INVALID_ADDRESS;
3375     }
3376 
3377     if (module_sp == nullptr)
3378     {
3379          if (log)
3380             log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__);
3381          return LLDB_INVALID_ADDRESS;
3382     }
3383 
3384     ObjectFileSP object_file_sp = module_sp->GetObjectFile ();
3385     if (object_file_sp == nullptr)
3386     {
3387          if (log)
3388             log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__);
3389          return LLDB_INVALID_ADDRESS;
3390     }
3391 
3392     return obj_file_sp->GetImageInfoAddress();
3393 #else
3394     Target *target = &GetTarget();
3395     ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
3396     Address addr = obj_file->GetImageInfoAddress(target);
3397 
3398     if (addr.IsValid())
3399         return addr.GetLoadAddress(target);
3400     return LLDB_INVALID_ADDRESS;
3401 #endif
3402 #endif // punt on this for now
3403 }
3404 
3405 size_t
3406 NativeProcessLinux::UpdateThreads ()
3407 {
3408     // The NativeProcessLinux monitoring threads are always up to date
3409     // with respect to thread state and they keep the thread list
3410     // populated properly. All this method needs to do is return the
3411     // thread count.
3412     Mutex::Locker locker (m_threads_mutex);
3413     return m_threads.size ();
3414 }
3415 
3416 bool
3417 NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
3418 {
3419     arch = m_arch;
3420     return true;
3421 }
3422 
3423 Error
3424 NativeProcessLinux::GetSoftwareBreakpointPCOffset (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size)
3425 {
3426     // FIXME put this behind a breakpoint protocol class that can be
3427     // set per architecture.  Need ARM, MIPS support here.
3428     static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
3429     static const uint8_t g_i386_opcode [] = { 0xCC };
3430 
3431     switch (m_arch.GetMachine ())
3432     {
3433         case llvm::Triple::aarch64:
3434             actual_opcode_size = static_cast<uint32_t> (sizeof(g_aarch64_opcode));
3435             return Error ();
3436 
3437         case llvm::Triple::arm:
3438             actual_opcode_size = 0; // On arm the PC don't get updated for breakpoint hits
3439             return Error ();
3440 
3441         case llvm::Triple::x86:
3442         case llvm::Triple::x86_64:
3443             actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
3444             return Error ();
3445 
3446         default:
3447             assert(false && "CPU type not supported!");
3448             return Error ("CPU type not supported");
3449     }
3450 }
3451 
3452 Error
3453 NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
3454 {
3455     if (hardware)
3456         return Error ("NativeProcessLinux does not support hardware breakpoints");
3457     else
3458         return SetSoftwareBreakpoint (addr, size);
3459 }
3460 
3461 Error
3462 NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint,
3463                                                      size_t &actual_opcode_size,
3464                                                      const uint8_t *&trap_opcode_bytes)
3465 {
3466     // FIXME put this behind a breakpoint protocol class that can be set per
3467     // architecture.  Need MIPS support here.
3468     static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
3469     // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
3470     // linux kernel does otherwise.
3471     static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 };
3472     static const uint8_t g_i386_opcode [] = { 0xCC };
3473     static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
3474     static const uint8_t g_mips64el_opcode[] = { 0x0d, 0x00, 0x00, 0x00 };
3475     static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde };
3476 
3477     switch (m_arch.GetMachine ())
3478     {
3479     case llvm::Triple::aarch64:
3480         trap_opcode_bytes = g_aarch64_opcode;
3481         actual_opcode_size = sizeof(g_aarch64_opcode);
3482         return Error ();
3483 
3484     case llvm::Triple::arm:
3485         switch (trap_opcode_size_hint)
3486         {
3487         case 2:
3488             trap_opcode_bytes = g_thumb_breakpoint_opcode;
3489             actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
3490             return Error ();
3491         case 4:
3492             trap_opcode_bytes = g_arm_breakpoint_opcode;
3493             actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
3494             return Error ();
3495         default:
3496             assert(false && "Unrecognised trap opcode size hint!");
3497             return Error ("Unrecognised trap opcode size hint!");
3498         }
3499 
3500     case llvm::Triple::x86:
3501     case llvm::Triple::x86_64:
3502         trap_opcode_bytes = g_i386_opcode;
3503         actual_opcode_size = sizeof(g_i386_opcode);
3504         return Error ();
3505 
3506     case llvm::Triple::mips64:
3507         trap_opcode_bytes = g_mips64_opcode;
3508         actual_opcode_size = sizeof(g_mips64_opcode);
3509         return Error ();
3510 
3511     case llvm::Triple::mips64el:
3512         trap_opcode_bytes = g_mips64el_opcode;
3513         actual_opcode_size = sizeof(g_mips64el_opcode);
3514         return Error ();
3515 
3516     default:
3517         assert(false && "CPU type not supported!");
3518         return Error ("CPU type not supported");
3519     }
3520 }
3521 
3522 #if 0
3523 ProcessMessage::CrashReason
3524 NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
3525 {
3526     ProcessMessage::CrashReason reason;
3527     assert(info->si_signo == SIGSEGV);
3528 
3529     reason = ProcessMessage::eInvalidCrashReason;
3530 
3531     switch (info->si_code)
3532     {
3533     default:
3534         assert(false && "unexpected si_code for SIGSEGV");
3535         break;
3536     case SI_KERNEL:
3537         // Linux will occasionally send spurious SI_KERNEL codes.
3538         // (this is poorly documented in sigaction)
3539         // One way to get this is via unaligned SIMD loads.
3540         reason = ProcessMessage::eInvalidAddress; // for lack of anything better
3541         break;
3542     case SEGV_MAPERR:
3543         reason = ProcessMessage::eInvalidAddress;
3544         break;
3545     case SEGV_ACCERR:
3546         reason = ProcessMessage::ePrivilegedAddress;
3547         break;
3548     }
3549 
3550     return reason;
3551 }
3552 #endif
3553 
3554 
3555 #if 0
3556 ProcessMessage::CrashReason
3557 NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
3558 {
3559     ProcessMessage::CrashReason reason;
3560     assert(info->si_signo == SIGILL);
3561 
3562     reason = ProcessMessage::eInvalidCrashReason;
3563 
3564     switch (info->si_code)
3565     {
3566     default:
3567         assert(false && "unexpected si_code for SIGILL");
3568         break;
3569     case ILL_ILLOPC:
3570         reason = ProcessMessage::eIllegalOpcode;
3571         break;
3572     case ILL_ILLOPN:
3573         reason = ProcessMessage::eIllegalOperand;
3574         break;
3575     case ILL_ILLADR:
3576         reason = ProcessMessage::eIllegalAddressingMode;
3577         break;
3578     case ILL_ILLTRP:
3579         reason = ProcessMessage::eIllegalTrap;
3580         break;
3581     case ILL_PRVOPC:
3582         reason = ProcessMessage::ePrivilegedOpcode;
3583         break;
3584     case ILL_PRVREG:
3585         reason = ProcessMessage::ePrivilegedRegister;
3586         break;
3587     case ILL_COPROC:
3588         reason = ProcessMessage::eCoprocessorError;
3589         break;
3590     case ILL_BADSTK:
3591         reason = ProcessMessage::eInternalStackError;
3592         break;
3593     }
3594 
3595     return reason;
3596 }
3597 #endif
3598 
3599 #if 0
3600 ProcessMessage::CrashReason
3601 NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
3602 {
3603     ProcessMessage::CrashReason reason;
3604     assert(info->si_signo == SIGFPE);
3605 
3606     reason = ProcessMessage::eInvalidCrashReason;
3607 
3608     switch (info->si_code)
3609     {
3610     default:
3611         assert(false && "unexpected si_code for SIGFPE");
3612         break;
3613     case FPE_INTDIV:
3614         reason = ProcessMessage::eIntegerDivideByZero;
3615         break;
3616     case FPE_INTOVF:
3617         reason = ProcessMessage::eIntegerOverflow;
3618         break;
3619     case FPE_FLTDIV:
3620         reason = ProcessMessage::eFloatDivideByZero;
3621         break;
3622     case FPE_FLTOVF:
3623         reason = ProcessMessage::eFloatOverflow;
3624         break;
3625     case FPE_FLTUND:
3626         reason = ProcessMessage::eFloatUnderflow;
3627         break;
3628     case FPE_FLTRES:
3629         reason = ProcessMessage::eFloatInexactResult;
3630         break;
3631     case FPE_FLTINV:
3632         reason = ProcessMessage::eFloatInvalidOperation;
3633         break;
3634     case FPE_FLTSUB:
3635         reason = ProcessMessage::eFloatSubscriptRange;
3636         break;
3637     }
3638 
3639     return reason;
3640 }
3641 #endif
3642 
3643 #if 0
3644 ProcessMessage::CrashReason
3645 NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
3646 {
3647     ProcessMessage::CrashReason reason;
3648     assert(info->si_signo == SIGBUS);
3649 
3650     reason = ProcessMessage::eInvalidCrashReason;
3651 
3652     switch (info->si_code)
3653     {
3654     default:
3655         assert(false && "unexpected si_code for SIGBUS");
3656         break;
3657     case BUS_ADRALN:
3658         reason = ProcessMessage::eIllegalAlignment;
3659         break;
3660     case BUS_ADRERR:
3661         reason = ProcessMessage::eIllegalAddress;
3662         break;
3663     case BUS_OBJERR:
3664         reason = ProcessMessage::eHardwareError;
3665         break;
3666     }
3667 
3668     return reason;
3669 }
3670 #endif
3671 
3672 void
3673 NativeProcessLinux::ServeOperation(OperationArgs *args)
3674 {
3675     NativeProcessLinux *monitor = args->m_monitor;
3676 
3677     // We are finised with the arguments and are ready to go.  Sync with the
3678     // parent thread and start serving operations on the inferior.
3679     sem_post(&args->m_semaphore);
3680 
3681     for(;;)
3682     {
3683         // wait for next pending operation
3684         if (sem_wait(&monitor->m_operation_pending))
3685         {
3686             if (errno == EINTR)
3687                 continue;
3688             assert(false && "Unexpected errno from sem_wait");
3689         }
3690 
3691         // EXIT_OPERATION used to stop the operation thread because Cancel() isn't supported on
3692         // android. We don't have to send a post to the m_operation_done semaphore because in this
3693         // case the synchronization is achieved by a Join() call
3694         if (monitor->m_operation == EXIT_OPERATION)
3695             break;
3696 
3697         static_cast<Operation*>(monitor->m_operation)->Execute(monitor);
3698 
3699         // notify calling thread that operation is complete
3700         sem_post(&monitor->m_operation_done);
3701     }
3702 }
3703 
3704 void
3705 NativeProcessLinux::DoOperation(void *op)
3706 {
3707     Mutex::Locker lock(m_operation_mutex);
3708 
3709     m_operation = op;
3710 
3711     // notify operation thread that an operation is ready to be processed
3712     sem_post(&m_operation_pending);
3713 
3714     // Don't wait for the operation to complete in case of an exit operation. The operation thread
3715     // will exit without posting to the semaphore
3716     if (m_operation == EXIT_OPERATION)
3717         return;
3718 
3719     // wait for operation to complete
3720     while (sem_wait(&m_operation_done))
3721     {
3722         if (errno == EINTR)
3723             continue;
3724         assert(false && "Unexpected errno from sem_wait");
3725     }
3726 }
3727 
3728 Error
3729 NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, lldb::addr_t size, lldb::addr_t &bytes_read)
3730 {
3731     ReadOperation op(addr, buf, size, bytes_read);
3732     DoOperation(&op);
3733     return op.GetError ();
3734 }
3735 
3736 Error
3737 NativeProcessLinux::WriteMemory (lldb::addr_t addr, const void *buf, lldb::addr_t size, lldb::addr_t &bytes_written)
3738 {
3739     WriteOperation op(addr, buf, size, bytes_written);
3740     DoOperation(&op);
3741     return op.GetError ();
3742 }
3743 
3744 Error
3745 NativeProcessLinux::ReadRegisterValue(lldb::tid_t tid, uint32_t offset, const char* reg_name,
3746                                       uint32_t size, RegisterValue &value)
3747 {
3748     ReadRegOperation op(tid, offset, reg_name, value);
3749     DoOperation(&op);
3750     return op.GetError();
3751 }
3752 
3753 Error
3754 NativeProcessLinux::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
3755                                    const char* reg_name, const RegisterValue &value)
3756 {
3757     WriteRegOperation op(tid, offset, reg_name, value);
3758     DoOperation(&op);
3759     return op.GetError();
3760 }
3761 
3762 Error
3763 NativeProcessLinux::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3764 {
3765     ReadGPROperation op(tid, buf, buf_size);
3766     DoOperation(&op);
3767     return op.GetError();
3768 }
3769 
3770 Error
3771 NativeProcessLinux::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3772 {
3773     ReadFPROperation op(tid, buf, buf_size);
3774     DoOperation(&op);
3775     return op.GetError();
3776 }
3777 
3778 Error
3779 NativeProcessLinux::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3780 {
3781     ReadRegisterSetOperation op(tid, buf, buf_size, regset);
3782     DoOperation(&op);
3783     return op.GetError();
3784 }
3785 
3786 Error
3787 NativeProcessLinux::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3788 {
3789     WriteGPROperation op(tid, buf, buf_size);
3790     DoOperation(&op);
3791     return op.GetError();
3792 }
3793 
3794 Error
3795 NativeProcessLinux::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3796 {
3797     WriteFPROperation op(tid, buf, buf_size);
3798     DoOperation(&op);
3799     return op.GetError();
3800 }
3801 
3802 Error
3803 NativeProcessLinux::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3804 {
3805     WriteRegisterSetOperation op(tid, buf, buf_size, regset);
3806     DoOperation(&op);
3807     return op.GetError();
3808 }
3809 
3810 Error
3811 NativeProcessLinux::Resume (lldb::tid_t tid, uint32_t signo)
3812 {
3813     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3814 
3815     if (log)
3816         log->Printf ("NativeProcessLinux::%s() resuming thread = %"  PRIu64 " with signal %s", __FUNCTION__, tid,
3817                                  GetUnixSignals().GetSignalAsCString (signo));
3818     ResumeOperation op (tid, signo);
3819     DoOperation (&op);
3820     if (log)
3821         log->Printf ("NativeProcessLinux::%s() resuming thread = %"  PRIu64 " result = %s", __FUNCTION__, tid, op.GetError().Success() ? "true" : "false");
3822     return op.GetError();
3823 }
3824 
3825 #if defined(__arm__)
3826 
3827 namespace {
3828 
3829 struct EmulatorBaton
3830 {
3831     NativeProcessLinux* m_process;
3832     NativeRegisterContext* m_reg_context;
3833     RegisterValue m_pc;
3834     RegisterValue m_cpsr;
3835 
3836     EmulatorBaton(NativeProcessLinux* process, NativeRegisterContext* reg_context) :
3837             m_process(process), m_reg_context(reg_context) {}
3838 };
3839 
3840 } // anonymous namespace
3841 
3842 static size_t
3843 ReadMemoryCallback (EmulateInstruction *instruction,
3844                     void *baton,
3845                     const EmulateInstruction::Context &context,
3846                     lldb::addr_t addr,
3847                     void *dst,
3848                     size_t length)
3849 {
3850     EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
3851 
3852     lldb::addr_t bytes_read;
3853     emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
3854     return bytes_read;
3855 }
3856 
3857 static bool
3858 ReadRegisterCallback (EmulateInstruction *instruction,
3859                       void *baton,
3860                       const RegisterInfo *reg_info,
3861                       RegisterValue &reg_value)
3862 {
3863     EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
3864 
3865     // The emulator only fill in the dwarf regsiter numbers (and in some case
3866     // the generic register numbers). Get the full register info from the
3867     // register context based on the dwarf register numbers.
3868     const RegisterInfo* full_reg_info = emulator_baton->m_reg_context->GetRegisterInfo(
3869             eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
3870 
3871     Error error = emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
3872     return error.Success();
3873 }
3874 
3875 static bool
3876 WriteRegisterCallback (EmulateInstruction *instruction,
3877                        void *baton,
3878                        const EmulateInstruction::Context &context,
3879                        const RegisterInfo *reg_info,
3880                        const RegisterValue &reg_value)
3881 {
3882     EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
3883 
3884     switch (reg_info->kinds[eRegisterKindGeneric])
3885     {
3886     case LLDB_REGNUM_GENERIC_PC:
3887         emulator_baton->m_pc = reg_value;
3888         break;
3889     case LLDB_REGNUM_GENERIC_FLAGS:
3890         emulator_baton->m_cpsr = reg_value;
3891         break;
3892     }
3893 
3894     return true;
3895 }
3896 
3897 static size_t WriteMemoryCallback (EmulateInstruction *instruction,
3898                                    void *baton,
3899                                    const EmulateInstruction::Context &context,
3900                                    lldb::addr_t addr,
3901                                    const void *dst,
3902                                    size_t length)
3903 {
3904     return length;
3905 }
3906 
3907 Error
3908 NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo)
3909 {
3910     Error error;
3911     NativeRegisterContextSP register_context_sp = GetThreadByID(tid)->GetRegisterContext();
3912 
3913     std::unique_ptr<EmulateInstruction> emulator_ap(
3914         EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, nullptr));
3915 
3916     if (emulator_ap == nullptr)
3917         return Error("Instrunction emulator not found!");
3918 
3919     EmulatorBaton baton(this, register_context_sp.get());
3920     emulator_ap->SetBaton(&baton);
3921     emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
3922     emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
3923     emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
3924     emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
3925 
3926     if (!emulator_ap->ReadInstruction())
3927         return Error("Read instruction failed!");
3928 
3929     if (!emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC))
3930         return Error("Evaluate instrcution failed!");
3931 
3932     lldb::addr_t next_pc = baton.m_pc.GetAsUInt32();
3933     lldb::addr_t next_cpsr = 0;
3934     if (baton.m_cpsr.GetType() != RegisterValue::eTypeInvalid)
3935     {
3936         next_cpsr = baton.m_cpsr.GetAsUInt32();
3937     }
3938     else
3939     {
3940         const RegisterInfo* cpsr_info = register_context_sp->GetRegisterInfo(
3941             eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
3942         next_cpsr = register_context_sp->ReadRegisterAsUnsigned(cpsr_info, LLDB_INVALID_ADDRESS);
3943     }
3944 
3945     if (next_cpsr & 0x20)
3946     {
3947         // Thumb mode
3948         error = SetBreakpoint(next_pc, 2, false);
3949     }
3950     else
3951     {
3952         // Arm mode
3953         error = SetBreakpoint(next_pc, 4, false);
3954     }
3955 
3956     if (error.Fail())
3957         return error;
3958 
3959     m_threads_stepping_with_breakpoint.emplace(tid, next_pc);
3960 
3961     error = Resume(tid, signo);
3962     if (error.Fail())
3963         return error;
3964 
3965     return Error();
3966 }
3967 
3968 #else // defined(__arm__)
3969 
3970 Error
3971 NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo)
3972 {
3973     SingleStepOperation op(tid, signo);
3974     DoOperation(&op);
3975     return op.GetError();
3976 }
3977 
3978 #endif // defined(__arm__)
3979 
3980 Error
3981 NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
3982 {
3983     SiginfoOperation op(tid, siginfo);
3984     DoOperation(&op);
3985     return op.GetError();
3986 }
3987 
3988 Error
3989 NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
3990 {
3991     EventMessageOperation op(tid, message);
3992     DoOperation(&op);
3993     return op.GetError();
3994 }
3995 
3996 Error
3997 NativeProcessLinux::Detach(lldb::tid_t tid)
3998 {
3999     if (tid == LLDB_INVALID_THREAD_ID)
4000         return Error();
4001 
4002     DetachOperation op(tid);
4003     DoOperation(&op);
4004     return op.GetError();
4005 }
4006 
4007 bool
4008 NativeProcessLinux::DupDescriptor(const char *path, int fd, int flags)
4009 {
4010     int target_fd = open(path, flags, 0666);
4011 
4012     if (target_fd == -1)
4013         return false;
4014 
4015     if (dup2(target_fd, fd) == -1)
4016         return false;
4017 
4018     return (close(target_fd) == -1) ? false : true;
4019 }
4020 
4021 void
4022 NativeProcessLinux::StartMonitorThread(Error &error)
4023 {
4024     m_monitor_up.reset(new Monitor(GetID(), this));
4025     error = m_monitor_up->Initialize();
4026     if (error.Fail()) {
4027         m_monitor_up.reset();
4028     }
4029 }
4030 
4031 void
4032 NativeProcessLinux::StopMonitor()
4033 {
4034     m_monitor_up.reset();
4035     StopCoordinatorThread ();
4036     StopOpThread();
4037     sem_destroy(&m_operation_pending);
4038     sem_destroy(&m_operation_done);
4039 
4040     // TODO: validate whether this still holds, fix up comment.
4041     // Note: ProcessPOSIX passes the m_terminal_fd file descriptor to
4042     // Process::SetSTDIOFileDescriptor, which in turn transfers ownership of
4043     // the descriptor to a ConnectionFileDescriptor object.  Consequently
4044     // even though still has the file descriptor, we shouldn't close it here.
4045 }
4046 
4047 void
4048 NativeProcessLinux::StopOpThread()
4049 {
4050     if (!m_operation_thread.IsJoinable())
4051         return;
4052 
4053     DoOperation(EXIT_OPERATION);
4054     m_operation_thread.Join(nullptr);
4055 }
4056 
4057 Error
4058 NativeProcessLinux::StartCoordinatorThread ()
4059 {
4060     Error error;
4061     static const char *g_thread_name = "lldb.process.linux.ts_coordinator";
4062     Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
4063 
4064     // Skip if thread is already running
4065     if (m_coordinator_thread.IsJoinable())
4066     {
4067         error.SetErrorString ("ThreadStateCoordinator's run loop is already running");
4068         if (log)
4069             log->Printf ("NativeProcessLinux::%s %s", __FUNCTION__, error.AsCString ());
4070         return error;
4071     }
4072 
4073     // Enable verbose logging if lldb thread logging is enabled.
4074     m_coordinator_up->LogEnableEventProcessing (log != nullptr);
4075 
4076     if (log)
4077         log->Printf ("NativeProcessLinux::%s launching ThreadStateCoordinator thread for pid %" PRIu64, __FUNCTION__, GetID ());
4078     m_coordinator_thread = ThreadLauncher::LaunchThread(g_thread_name, CoordinatorThread, this, &error);
4079     return error;
4080 }
4081 
4082 void *
4083 NativeProcessLinux::CoordinatorThread (void *arg)
4084 {
4085     Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
4086 
4087     NativeProcessLinux *const process = static_cast<NativeProcessLinux*> (arg);
4088     assert (process && "null process passed to CoordinatorThread");
4089     if (!process)
4090     {
4091         if (log)
4092             log->Printf ("NativeProcessLinux::%s null process, exiting ThreadStateCoordinator processing loop", __FUNCTION__);
4093         return nullptr;
4094     }
4095 
4096     // Run the thread state coordinator loop until it is done.  This call uses
4097     // efficient waiting for an event to be ready.
4098     while (process->m_coordinator_up->ProcessNextEvent () == ThreadStateCoordinator::eventLoopResultContinue)
4099     {
4100     }
4101 
4102     if (log)
4103         log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " exiting ThreadStateCoordinator processing loop due to coordinator indicating completion", __FUNCTION__, process->GetID ());
4104 
4105     return nullptr;
4106 }
4107 
4108 void
4109 NativeProcessLinux::StopCoordinatorThread()
4110 {
4111     Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
4112     if (log)
4113         log->Printf ("NativeProcessLinux::%s requesting ThreadStateCoordinator stop for pid %" PRIu64, __FUNCTION__, GetID ());
4114 
4115     // Tell the coordinator we're done.  This will cause the coordinator
4116     // run loop thread to exit when the processing queue hits this message.
4117     m_coordinator_up->StopCoordinator ();
4118     m_coordinator_thread.Join (nullptr);
4119 }
4120 
4121 bool
4122 NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
4123 {
4124     for (auto thread_sp : m_threads)
4125     {
4126         assert (thread_sp && "thread list should not contain NULL threads");
4127         if (thread_sp->GetID () == thread_id)
4128         {
4129             // We have this thread.
4130             return true;
4131         }
4132     }
4133 
4134     // We don't have this thread.
4135     return false;
4136 }
4137 
4138 NativeThreadProtocolSP
4139 NativeProcessLinux::MaybeGetThreadNoLock (lldb::tid_t thread_id)
4140 {
4141     // CONSIDER organize threads by map - we can do better than linear.
4142     for (auto thread_sp : m_threads)
4143     {
4144         if (thread_sp->GetID () == thread_id)
4145             return thread_sp;
4146     }
4147 
4148     // We don't have this thread.
4149     return NativeThreadProtocolSP ();
4150 }
4151 
4152 bool
4153 NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
4154 {
4155     Mutex::Locker locker (m_threads_mutex);
4156     for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
4157     {
4158         if (*it && ((*it)->GetID () == thread_id))
4159         {
4160             m_threads.erase (it);
4161             return true;
4162         }
4163     }
4164 
4165     // Didn't find it.
4166     return false;
4167 }
4168 
4169 NativeThreadProtocolSP
4170 NativeProcessLinux::AddThread (lldb::tid_t thread_id)
4171 {
4172     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
4173 
4174     Mutex::Locker locker (m_threads_mutex);
4175 
4176     if (log)
4177     {
4178         log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
4179                 __FUNCTION__,
4180                 GetID (),
4181                 thread_id);
4182     }
4183 
4184     assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
4185 
4186     // If this is the first thread, save it as the current thread
4187     if (m_threads.empty ())
4188         SetCurrentThreadID (thread_id);
4189 
4190     NativeThreadProtocolSP thread_sp (new NativeThreadLinux (this, thread_id));
4191     m_threads.push_back (thread_sp);
4192 
4193     return thread_sp;
4194 }
4195 
4196 NativeThreadProtocolSP
4197 NativeProcessLinux::GetOrCreateThread (lldb::tid_t thread_id, bool &created)
4198 {
4199     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
4200 
4201     Mutex::Locker locker (m_threads_mutex);
4202     if (log)
4203     {
4204         log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " get/create thread with tid %" PRIu64,
4205                      __FUNCTION__,
4206                      GetID (),
4207                      thread_id);
4208     }
4209 
4210     // Retrieve the thread if it is already getting tracked.
4211     NativeThreadProtocolSP thread_sp = MaybeGetThreadNoLock (thread_id);
4212     if (thread_sp)
4213     {
4214         if (log)
4215             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": thread already tracked, returning",
4216                          __FUNCTION__,
4217                          GetID (),
4218                          thread_id);
4219         created = false;
4220         return thread_sp;
4221 
4222     }
4223 
4224     // Create the thread metadata since it isn't being tracked.
4225     if (log)
4226         log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": thread didn't exist, tracking now",
4227                      __FUNCTION__,
4228                      GetID (),
4229                      thread_id);
4230 
4231     thread_sp.reset (new NativeThreadLinux (this, thread_id));
4232     m_threads.push_back (thread_sp);
4233     created = true;
4234 
4235     return thread_sp;
4236 }
4237 
4238 Error
4239 NativeProcessLinux::FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp)
4240 {
4241     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
4242 
4243     Error error;
4244 
4245     // Get a linux thread pointer.
4246     if (!thread_sp)
4247     {
4248         error.SetErrorString ("null thread_sp");
4249         if (log)
4250             log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
4251         return error;
4252     }
4253     std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
4254 
4255     // Find out the size of a breakpoint (might depend on where we are in the code).
4256     NativeRegisterContextSP context_sp = linux_thread_sp->GetRegisterContext ();
4257     if (!context_sp)
4258     {
4259         error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
4260         if (log)
4261             log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
4262         return error;
4263     }
4264 
4265     uint32_t breakpoint_size = 0;
4266     error = GetSoftwareBreakpointPCOffset (context_sp, breakpoint_size);
4267     if (error.Fail ())
4268     {
4269         if (log)
4270             log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
4271         return error;
4272     }
4273     else
4274     {
4275         if (log)
4276             log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
4277     }
4278 
4279     // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
4280     const lldb::addr_t initial_pc_addr = context_sp->GetPC ();
4281     lldb::addr_t breakpoint_addr = initial_pc_addr;
4282     if (breakpoint_size > static_cast<lldb::addr_t> (0))
4283     {
4284         // Do not allow breakpoint probe to wrap around.
4285         if (breakpoint_addr >= static_cast<lldb::addr_t> (breakpoint_size))
4286             breakpoint_addr -= static_cast<lldb::addr_t> (breakpoint_size);
4287     }
4288 
4289     // Check if we stopped because of a breakpoint.
4290     NativeBreakpointSP breakpoint_sp;
4291     error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
4292     if (!error.Success () || !breakpoint_sp)
4293     {
4294         // We didn't find one at a software probe location.  Nothing to do.
4295         if (log)
4296             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
4297         return Error ();
4298     }
4299 
4300     // If the breakpoint is not a software breakpoint, nothing to do.
4301     if (!breakpoint_sp->IsSoftwareBreakpoint ())
4302     {
4303         if (log)
4304             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
4305         return Error ();
4306     }
4307 
4308     //
4309     // We have a software breakpoint and need to adjust the PC.
4310     //
4311 
4312     // Sanity check.
4313     if (breakpoint_size == 0)
4314     {
4315         // Nothing to do!  How did we get here?
4316         if (log)
4317             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);
4318         return Error ();
4319     }
4320 
4321     // Change the program counter.
4322     if (log)
4323         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);
4324 
4325     error = context_sp->SetPC (breakpoint_addr);
4326     if (error.Fail ())
4327     {
4328         if (log)
4329             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": failed to set PC: %s", __FUNCTION__, GetID (), linux_thread_sp->GetID (), error.AsCString ());
4330         return error;
4331     }
4332 
4333     return error;
4334 }
4335 
4336 void
4337 NativeProcessLinux::NotifyThreadCreateStopped (lldb::tid_t tid)
4338 {
4339     const bool is_stopped = true;
4340     m_coordinator_up->NotifyThreadCreate (tid, is_stopped, CoordinatorErrorHandler);
4341 }
4342 
4343 void
4344 NativeProcessLinux::NotifyThreadDeath (lldb::tid_t tid)
4345 {
4346     m_coordinator_up->NotifyThreadDeath (tid, CoordinatorErrorHandler);
4347 }
4348 
4349 void
4350 NativeProcessLinux::NotifyThreadStop (lldb::tid_t tid)
4351 {
4352     m_coordinator_up->NotifyThreadStop (tid, false, CoordinatorErrorHandler);
4353 }
4354 
4355 void
4356 NativeProcessLinux::CallAfterRunningThreadsStop (lldb::tid_t tid,
4357                                                  const std::function<void (lldb::tid_t tid)> &call_after_function)
4358 {
4359     Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
4360     if (log)
4361         log->Printf("NativeProcessLinux::%s tid %" PRIu64, __FUNCTION__, tid);
4362 
4363     const lldb::pid_t pid = GetID ();
4364     m_coordinator_up->CallAfterRunningThreadsStop (tid,
4365                                                    [=](lldb::tid_t request_stop_tid)
4366                                                    {
4367                                                        return RequestThreadStop(pid, request_stop_tid);
4368                                                    },
4369                                                    call_after_function,
4370                                                    CoordinatorErrorHandler);
4371 }
4372 
4373 void
4374 NativeProcessLinux::CallAfterRunningThreadsStopWithSkipTID (lldb::tid_t deferred_signal_tid,
4375                                                             lldb::tid_t skip_stop_request_tid,
4376                                                             const std::function<void (lldb::tid_t tid)> &call_after_function)
4377 {
4378     Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
4379     if (log)
4380         log->Printf("NativeProcessLinux::%s deferred_signal_tid %" PRIu64 ", skip_stop_request_tid %" PRIu64, __FUNCTION__, deferred_signal_tid, skip_stop_request_tid);
4381 
4382     const lldb::pid_t pid = GetID ();
4383     m_coordinator_up->CallAfterRunningThreadsStopWithSkipTIDs (deferred_signal_tid,
4384                                                                skip_stop_request_tid != LLDB_INVALID_THREAD_ID ? ThreadStateCoordinator::ThreadIDSet {skip_stop_request_tid} : ThreadStateCoordinator::ThreadIDSet (),
4385                                                                [=](lldb::tid_t request_stop_tid)
4386                                                                {
4387                                                                    return RequestThreadStop(pid, request_stop_tid);
4388                                                                },
4389                                                                call_after_function,
4390                                                                CoordinatorErrorHandler);
4391 }
4392 
4393 Error
4394 NativeProcessLinux::RequestThreadStop (const lldb::pid_t pid, const lldb::tid_t tid)
4395 {
4396     Log* log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
4397     if (log)
4398         log->Printf ("NativeProcessLinux::%s requesting thread stop(pid: %" PRIu64 ", tid: %" PRIu64 ")", __FUNCTION__, pid, tid);
4399 
4400     Error err;
4401     errno = 0;
4402     if (::tgkill (pid, tid, SIGSTOP) != 0)
4403     {
4404         err.SetErrorToErrno ();
4405         if (log)
4406             log->Printf ("NativeProcessLinux::%s tgkill(%" PRIu64 ", %" PRIu64 ", SIGSTOP) failed: %s", __FUNCTION__, pid, tid, err.AsCString ());
4407     }
4408 
4409     return err;
4410 }
4411 
4412 Error
4413 NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec)
4414 {
4415     char maps_file_name[32];
4416     snprintf(maps_file_name, sizeof(maps_file_name), "/proc/%" PRIu64 "/maps", GetID());
4417 
4418     FileSpec maps_file_spec(maps_file_name, false);
4419     if (!maps_file_spec.Exists()) {
4420         file_spec.Clear();
4421         return Error("/proc/%" PRIu64 "/maps file doesn't exists!", GetID());
4422     }
4423 
4424     FileSpec module_file_spec(module_path, true);
4425 
4426     std::ifstream maps_file(maps_file_name);
4427     std::string maps_data_str((std::istreambuf_iterator<char>(maps_file)), std::istreambuf_iterator<char>());
4428     StringRef maps_data(maps_data_str.c_str());
4429 
4430     while (!maps_data.empty())
4431     {
4432         StringRef maps_row;
4433         std::tie(maps_row, maps_data) = maps_data.split('\n');
4434 
4435         SmallVector<StringRef, 16> maps_columns;
4436         maps_row.split(maps_columns, StringRef(" "), -1, false);
4437 
4438         if (maps_columns.size() >= 6)
4439         {
4440             file_spec.SetFile(maps_columns[5].str().c_str(), false);
4441             if (file_spec.GetFilename() == module_file_spec.GetFilename())
4442                 return Error();
4443         }
4444     }
4445 
4446     file_spec.Clear();
4447     return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
4448                  module_file_spec.GetFilename().AsCString(), GetID());
4449 }
4450