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