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