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_supports_mem_region (eLazyBoolCalculate),
1220     m_mem_region_cache (),
1221     m_mem_region_cache_mutex ()
1222 {
1223 }
1224 
1225 //------------------------------------------------------------------------------
1226 /// The basic design of the NativeProcessLinux is built around two threads.
1227 ///
1228 /// One thread (@see SignalThread) simply blocks on a call to waitpid() looking
1229 /// for changes in the debugee state.  When a change is detected a
1230 /// ProcessMessage is sent to the associated ProcessLinux instance.  This thread
1231 /// "drives" state changes in the debugger.
1232 ///
1233 /// The second thread (@see OperationThread) is responsible for two things 1)
1234 /// launching or attaching to the inferior process, and then 2) servicing
1235 /// operations such as register reads/writes, stepping, etc.  See the comments
1236 /// on the Operation class for more info as to why this is needed.
1237 void
1238 NativeProcessLinux::LaunchInferior (
1239     Module *module,
1240     const char *argv[],
1241     const char *envp[],
1242     const char *stdin_path,
1243     const char *stdout_path,
1244     const char *stderr_path,
1245     const char *working_dir,
1246     const lldb_private::ProcessLaunchInfo &launch_info,
1247     lldb_private::Error &error)
1248 {
1249     if (module)
1250         m_arch = module->GetArchitecture ();
1251 
1252     SetState(eStateLaunching);
1253 
1254     std::unique_ptr<LaunchArgs> args(
1255         new LaunchArgs(
1256             this, module, argv, envp,
1257             stdin_path, stdout_path, stderr_path,
1258             working_dir, launch_info));
1259 
1260     sem_init(&m_operation_pending, 0, 0);
1261     sem_init(&m_operation_done, 0, 0);
1262 
1263     StartLaunchOpThread(args.get(), error);
1264     if (!error.Success())
1265         return;
1266 
1267 WAIT_AGAIN:
1268     // Wait for the operation thread to initialize.
1269     if (sem_wait(&args->m_semaphore))
1270     {
1271         if (errno == EINTR)
1272             goto WAIT_AGAIN;
1273         else
1274         {
1275             error.SetErrorToErrno();
1276             return;
1277         }
1278     }
1279 
1280     // Check that the launch was a success.
1281     if (!args->m_error.Success())
1282     {
1283         StopOpThread();
1284         error = args->m_error;
1285         return;
1286     }
1287 
1288     // Finally, start monitoring the child process for change in state.
1289     m_monitor_thread = Host::StartMonitoringChildProcess(
1290         NativeProcessLinux::MonitorCallback, this, GetID(), true);
1291     if (m_monitor_thread.GetState() != eThreadStateRunning)
1292     {
1293         error.SetErrorToGenericError();
1294         error.SetErrorString ("Process attach failed to create monitor thread for NativeProcessLinux::MonitorCallback.");
1295         return;
1296     }
1297 }
1298 
1299 void
1300 NativeProcessLinux::AttachToInferior (lldb::pid_t pid, lldb_private::Error &error)
1301 {
1302     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1303     if (log)
1304         log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
1305 
1306     // We can use the Host for everything except the ResolveExecutable portion.
1307     PlatformSP platform_sp = Platform::GetDefaultPlatform ();
1308     if (!platform_sp)
1309     {
1310         if (log)
1311             log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): no default platform set", __FUNCTION__, pid);
1312         error.SetErrorString ("no default platform available");
1313     }
1314 
1315     // Gather info about the process.
1316     ProcessInstanceInfo process_info;
1317     platform_sp->GetProcessInfo (pid, process_info);
1318 
1319     // Resolve the executable module
1320     ModuleSP exe_module_sp;
1321     FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
1322 
1323     error = platform_sp->ResolveExecutable(process_info.GetExecutableFile(), HostInfo::GetArchitecture(), exe_module_sp,
1324                                            executable_search_paths.GetSize() ? &executable_search_paths : NULL);
1325     if (!error.Success())
1326         return;
1327 
1328     // Set the architecture to the exe architecture.
1329     m_arch = exe_module_sp->GetArchitecture();
1330     if (log)
1331         log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
1332 
1333     m_pid = pid;
1334     SetState(eStateAttaching);
1335 
1336     sem_init (&m_operation_pending, 0, 0);
1337     sem_init (&m_operation_done, 0, 0);
1338 
1339     std::unique_ptr<AttachArgs> args (new AttachArgs (this, pid));
1340 
1341     StartAttachOpThread(args.get (), error);
1342     if (!error.Success ())
1343         return;
1344 
1345 WAIT_AGAIN:
1346     // Wait for the operation thread to initialize.
1347     if (sem_wait (&args->m_semaphore))
1348     {
1349         if (errno == EINTR)
1350             goto WAIT_AGAIN;
1351         else
1352         {
1353             error.SetErrorToErrno ();
1354             return;
1355         }
1356     }
1357 
1358     // Check that the attach was a success.
1359     if (!args->m_error.Success ())
1360     {
1361         StopOpThread ();
1362         error = args->m_error;
1363         return;
1364     }
1365 
1366     // Finally, start monitoring the child process for change in state.
1367     m_monitor_thread = Host::StartMonitoringChildProcess (
1368         NativeProcessLinux::MonitorCallback, this, GetID (), true);
1369     if (m_monitor_thread.GetState() != eThreadStateRunning)
1370     {
1371         error.SetErrorToGenericError ();
1372         error.SetErrorString ("Process attach failed to create monitor thread for NativeProcessLinux::MonitorCallback.");
1373         return;
1374     }
1375 }
1376 
1377 NativeProcessLinux::~NativeProcessLinux()
1378 {
1379     StopMonitor();
1380 }
1381 
1382 //------------------------------------------------------------------------------
1383 // Thread setup and tear down.
1384 
1385 void
1386 NativeProcessLinux::StartLaunchOpThread(LaunchArgs *args, Error &error)
1387 {
1388     static const char *g_thread_name = "lldb.process.nativelinux.operation";
1389 
1390     if (m_operation_thread.GetState() == eThreadStateRunning)
1391         return;
1392 
1393     m_operation_thread = ThreadLauncher::LaunchThread(g_thread_name, LaunchOpThread, args, &error);
1394 }
1395 
1396 void *
1397 NativeProcessLinux::LaunchOpThread(void *arg)
1398 {
1399     LaunchArgs *args = static_cast<LaunchArgs*>(arg);
1400 
1401     if (!Launch(args)) {
1402         sem_post(&args->m_semaphore);
1403         return NULL;
1404     }
1405 
1406     ServeOperation(args);
1407     return NULL;
1408 }
1409 
1410 bool
1411 NativeProcessLinux::Launch(LaunchArgs *args)
1412 {
1413     assert (args && "null args");
1414     if (!args)
1415         return false;
1416 
1417     NativeProcessLinux *monitor = args->m_monitor;
1418     assert (monitor && "monitor is NULL");
1419     if (!monitor)
1420         return false;
1421 
1422     const char **argv = args->m_argv;
1423     const char **envp = args->m_envp;
1424     const char *stdin_path = args->m_stdin_path;
1425     const char *stdout_path = args->m_stdout_path;
1426     const char *stderr_path = args->m_stderr_path;
1427     const char *working_dir = args->m_working_dir;
1428 
1429     lldb_utility::PseudoTerminal terminal;
1430     const size_t err_len = 1024;
1431     char err_str[err_len];
1432     lldb::pid_t pid;
1433     NativeThreadProtocolSP thread_sp;
1434 
1435     lldb::ThreadSP inferior;
1436     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1437 
1438     // Propagate the environment if one is not supplied.
1439     if (envp == NULL || envp[0] == NULL)
1440         envp = const_cast<const char **>(environ);
1441 
1442     if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
1443     {
1444         args->m_error.SetErrorToGenericError();
1445         args->m_error.SetErrorString("Process fork failed.");
1446         goto FINISH;
1447     }
1448 
1449     // Recognized child exit status codes.
1450     enum {
1451         ePtraceFailed = 1,
1452         eDupStdinFailed,
1453         eDupStdoutFailed,
1454         eDupStderrFailed,
1455         eChdirFailed,
1456         eExecFailed,
1457         eSetGidFailed
1458     };
1459 
1460     // Child process.
1461     if (pid == 0)
1462     {
1463         if (log)
1464             log->Printf ("NativeProcessLinux::%s inferior process preparing to fork", __FUNCTION__);
1465 
1466         // Trace this process.
1467         if (log)
1468             log->Printf ("NativeProcessLinux::%s inferior process issuing PTRACE_TRACEME", __FUNCTION__);
1469 
1470         if (PTRACE(PTRACE_TRACEME, 0, NULL, NULL, 0) < 0)
1471         {
1472             if (log)
1473                 log->Printf ("NativeProcessLinux::%s inferior process PTRACE_TRACEME failed", __FUNCTION__);
1474             exit(ePtraceFailed);
1475         }
1476 
1477         // Do not inherit setgid powers.
1478         if (log)
1479             log->Printf ("NativeProcessLinux::%s inferior process resetting gid", __FUNCTION__);
1480 
1481         if (setgid(getgid()) != 0)
1482         {
1483             if (log)
1484                 log->Printf ("NativeProcessLinux::%s inferior process setgid() failed", __FUNCTION__);
1485             exit(eSetGidFailed);
1486         }
1487 
1488         // Attempt to have our own process group.
1489         // TODO verify if we really want this.
1490         if (log)
1491             log->Printf ("NativeProcessLinux::%s inferior process resetting process group", __FUNCTION__);
1492 
1493         if (setpgid(0, 0) != 0)
1494         {
1495             if (log)
1496             {
1497                 const int error_code = errno;
1498                 log->Printf ("NativeProcessLinux::%s inferior setpgid() failed, errno=%d (%s), continuing with existing proccess group %" PRIu64,
1499                         __FUNCTION__,
1500                         error_code,
1501                         strerror (error_code),
1502                         static_cast<lldb::pid_t> (getpgid (0)));
1503             }
1504             // Don't allow this to prevent an inferior exec.
1505         }
1506 
1507         // Dup file descriptors if needed.
1508         //
1509         // FIXME: If two or more of the paths are the same we needlessly open
1510         // the same file multiple times.
1511         if (stdin_path != NULL && stdin_path[0])
1512             if (!DupDescriptor(stdin_path, STDIN_FILENO, O_RDONLY))
1513                 exit(eDupStdinFailed);
1514 
1515         if (stdout_path != NULL && stdout_path[0])
1516             if (!DupDescriptor(stdout_path, STDOUT_FILENO, O_WRONLY | O_CREAT))
1517                 exit(eDupStdoutFailed);
1518 
1519         if (stderr_path != NULL && stderr_path[0])
1520             if (!DupDescriptor(stderr_path, STDERR_FILENO, O_WRONLY | O_CREAT))
1521                 exit(eDupStderrFailed);
1522 
1523         // Change working directory
1524         if (working_dir != NULL && working_dir[0])
1525           if (0 != ::chdir(working_dir))
1526               exit(eChdirFailed);
1527 
1528         // Disable ASLR if requested.
1529         if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR))
1530         {
1531             const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
1532             if (old_personality == -1)
1533             {
1534                 if (log)
1535                     log->Printf ("NativeProcessLinux::%s retrieval of Linux personality () failed: %s. Cannot disable ASLR.", __FUNCTION__, strerror (errno));
1536             }
1537             else
1538             {
1539                 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality);
1540                 if (new_personality == -1)
1541                 {
1542                     if (log)
1543                         log->Printf ("NativeProcessLinux::%s setting of Linux personality () to disable ASLR failed, ignoring: %s", __FUNCTION__, strerror (errno));
1544 
1545                 }
1546                 else
1547                 {
1548                     if (log)
1549                         log->Printf ("NativeProcessLinux::%s disbling ASLR: SUCCESS", __FUNCTION__);
1550 
1551                 }
1552             }
1553         }
1554 
1555         // Execute.  We should never return.
1556         execve(argv[0],
1557                const_cast<char *const *>(argv),
1558                const_cast<char *const *>(envp));
1559         exit(eExecFailed);
1560     }
1561 
1562     // Wait for the child process to trap on its call to execve.
1563     ::pid_t wpid;
1564     int status;
1565     if ((wpid = waitpid(pid, &status, 0)) < 0)
1566     {
1567         args->m_error.SetErrorToErrno();
1568 
1569         if (log)
1570             log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s", __FUNCTION__, args->m_error.AsCString ());
1571 
1572         // Mark the inferior as invalid.
1573         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
1574         monitor->SetState (StateType::eStateInvalid);
1575 
1576         goto FINISH;
1577     }
1578     else if (WIFEXITED(status))
1579     {
1580         // open, dup or execve likely failed for some reason.
1581         args->m_error.SetErrorToGenericError();
1582         switch (WEXITSTATUS(status))
1583         {
1584             case ePtraceFailed:
1585                 args->m_error.SetErrorString("Child ptrace failed.");
1586                 break;
1587             case eDupStdinFailed:
1588                 args->m_error.SetErrorString("Child open stdin failed.");
1589                 break;
1590             case eDupStdoutFailed:
1591                 args->m_error.SetErrorString("Child open stdout failed.");
1592                 break;
1593             case eDupStderrFailed:
1594                 args->m_error.SetErrorString("Child open stderr failed.");
1595                 break;
1596             case eChdirFailed:
1597                 args->m_error.SetErrorString("Child failed to set working directory.");
1598                 break;
1599             case eExecFailed:
1600                 args->m_error.SetErrorString("Child exec failed.");
1601                 break;
1602             case eSetGidFailed:
1603                 args->m_error.SetErrorString("Child setgid failed.");
1604                 break;
1605             default:
1606                 args->m_error.SetErrorString("Child returned unknown exit status.");
1607                 break;
1608         }
1609 
1610         if (log)
1611         {
1612             log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
1613                     __FUNCTION__,
1614                     WEXITSTATUS(status));
1615         }
1616 
1617         // Mark the inferior as invalid.
1618         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
1619         monitor->SetState (StateType::eStateInvalid);
1620 
1621         goto FINISH;
1622     }
1623     assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
1624            "Could not sync with inferior process.");
1625 
1626     if (log)
1627         log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
1628 
1629     if (!SetDefaultPtraceOpts(pid))
1630     {
1631         args->m_error.SetErrorToErrno();
1632         if (log)
1633             log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
1634                     __FUNCTION__,
1635                     args->m_error.AsCString ());
1636 
1637         // Mark the inferior as invalid.
1638         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
1639         monitor->SetState (StateType::eStateInvalid);
1640 
1641         goto FINISH;
1642     }
1643 
1644     // Release the master terminal descriptor and pass it off to the
1645     // NativeProcessLinux instance.  Similarly stash the inferior pid.
1646     monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1647     monitor->m_pid = pid;
1648 
1649     // Set the terminal fd to be in non blocking mode (it simplifies the
1650     // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1651     // descriptor to read from).
1652     if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error))
1653     {
1654         if (log)
1655             log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
1656                     __FUNCTION__,
1657                     args->m_error.AsCString ());
1658 
1659         // Mark the inferior as invalid.
1660         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
1661         monitor->SetState (StateType::eStateInvalid);
1662 
1663         goto FINISH;
1664     }
1665 
1666     if (log)
1667         log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
1668 
1669     thread_sp = monitor->AddThread (static_cast<lldb::tid_t> (pid));
1670     assert (thread_sp && "AddThread() returned a nullptr thread");
1671     reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedBySignal (SIGSTOP);
1672     monitor->SetCurrentThreadID (thread_sp->GetID ());
1673 
1674     // Let our process instance know the thread has stopped.
1675     monitor->SetState (StateType::eStateStopped);
1676 
1677 FINISH:
1678     if (log)
1679     {
1680         if (args->m_error.Success ())
1681         {
1682             log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
1683         }
1684         else
1685         {
1686             log->Printf ("NativeProcessLinux::%s inferior launching failed: %s",
1687                 __FUNCTION__,
1688                 args->m_error.AsCString ());
1689         }
1690     }
1691     return args->m_error.Success();
1692 }
1693 
1694 void
1695 NativeProcessLinux::StartAttachOpThread(AttachArgs *args, lldb_private::Error &error)
1696 {
1697     static const char *g_thread_name = "lldb.process.linux.operation";
1698 
1699     if (m_operation_thread.GetState() == eThreadStateRunning)
1700         return;
1701 
1702     m_operation_thread = ThreadLauncher::LaunchThread(g_thread_name, AttachOpThread, args, &error);
1703 }
1704 
1705 void *
1706 NativeProcessLinux::AttachOpThread(void *arg)
1707 {
1708     AttachArgs *args = static_cast<AttachArgs*>(arg);
1709 
1710     if (!Attach(args)) {
1711         sem_post(&args->m_semaphore);
1712         return NULL;
1713     }
1714 
1715     ServeOperation(args);
1716     return NULL;
1717 }
1718 
1719 bool
1720 NativeProcessLinux::Attach(AttachArgs *args)
1721 {
1722     lldb::pid_t pid = args->m_pid;
1723 
1724     NativeProcessLinux *monitor = args->m_monitor;
1725     lldb::ThreadSP inferior;
1726     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1727 
1728     // Use a map to keep track of the threads which we have attached/need to attach.
1729     Host::TidMap tids_to_attach;
1730     if (pid <= 1)
1731     {
1732         args->m_error.SetErrorToGenericError();
1733         args->m_error.SetErrorString("Attaching to process 1 is not allowed.");
1734         goto FINISH;
1735     }
1736 
1737     while (Host::FindProcessThreads(pid, tids_to_attach))
1738     {
1739         for (Host::TidMap::iterator it = tids_to_attach.begin();
1740              it != tids_to_attach.end();)
1741         {
1742             if (it->second == false)
1743             {
1744                 lldb::tid_t tid = it->first;
1745 
1746                 // Attach to the requested process.
1747                 // An attach will cause the thread to stop with a SIGSTOP.
1748                 if (PTRACE(PTRACE_ATTACH, tid, NULL, NULL, 0) < 0)
1749                 {
1750                     // No such thread. The thread may have exited.
1751                     // More error handling may be needed.
1752                     if (errno == ESRCH)
1753                     {
1754                         it = tids_to_attach.erase(it);
1755                         continue;
1756                     }
1757                     else
1758                     {
1759                         args->m_error.SetErrorToErrno();
1760                         goto FINISH;
1761                     }
1762                 }
1763 
1764                 int status;
1765                 // Need to use __WALL otherwise we receive an error with errno=ECHLD
1766                 // At this point we should have a thread stopped if waitpid succeeds.
1767                 if ((status = waitpid(tid, NULL, __WALL)) < 0)
1768                 {
1769                     // No such thread. The thread may have exited.
1770                     // More error handling may be needed.
1771                     if (errno == ESRCH)
1772                     {
1773                         it = tids_to_attach.erase(it);
1774                         continue;
1775                     }
1776                     else
1777                     {
1778                         args->m_error.SetErrorToErrno();
1779                         goto FINISH;
1780                     }
1781                 }
1782 
1783                 if (!SetDefaultPtraceOpts(tid))
1784                 {
1785                     args->m_error.SetErrorToErrno();
1786                     goto FINISH;
1787                 }
1788 
1789 
1790                 if (log)
1791                     log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
1792 
1793                 it->second = true;
1794 
1795                 // Create the thread, mark it as stopped.
1796                 NativeThreadProtocolSP thread_sp (monitor->AddThread (static_cast<lldb::tid_t> (tid)));
1797                 assert (thread_sp && "AddThread() returned a nullptr");
1798                 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedBySignal (SIGSTOP);
1799                 monitor->SetCurrentThreadID (thread_sp->GetID ());
1800             }
1801 
1802             // move the loop forward
1803             ++it;
1804         }
1805     }
1806 
1807     if (tids_to_attach.size() > 0)
1808     {
1809         monitor->m_pid = pid;
1810         // Let our process instance know the thread has stopped.
1811         monitor->SetState (StateType::eStateStopped);
1812     }
1813     else
1814     {
1815         args->m_error.SetErrorToGenericError();
1816         args->m_error.SetErrorString("No such process.");
1817     }
1818 
1819  FINISH:
1820     return args->m_error.Success();
1821 }
1822 
1823 bool
1824 NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
1825 {
1826     long ptrace_opts = 0;
1827 
1828     // Have the child raise an event on exit.  This is used to keep the child in
1829     // limbo until it is destroyed.
1830     ptrace_opts |= PTRACE_O_TRACEEXIT;
1831 
1832     // Have the tracer trace threads which spawn in the inferior process.
1833     // TODO: if we want to support tracing the inferiors' child, add the
1834     // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
1835     ptrace_opts |= PTRACE_O_TRACECLONE;
1836 
1837     // Have the tracer notify us before execve returns
1838     // (needed to disable legacy SIGTRAP generation)
1839     ptrace_opts |= PTRACE_O_TRACEEXEC;
1840 
1841     return PTRACE(PTRACE_SETOPTIONS, pid, NULL, (void*)ptrace_opts, 0) >= 0;
1842 }
1843 
1844 static ExitType convert_pid_status_to_exit_type (int status)
1845 {
1846     if (WIFEXITED (status))
1847         return ExitType::eExitTypeExit;
1848     else if (WIFSIGNALED (status))
1849         return ExitType::eExitTypeSignal;
1850     else if (WIFSTOPPED (status))
1851         return ExitType::eExitTypeStop;
1852     else
1853     {
1854         // We don't know what this is.
1855         return ExitType::eExitTypeInvalid;
1856     }
1857 }
1858 
1859 static int convert_pid_status_to_return_code (int status)
1860 {
1861     if (WIFEXITED (status))
1862         return WEXITSTATUS (status);
1863     else if (WIFSIGNALED (status))
1864         return WTERMSIG (status);
1865     else if (WIFSTOPPED (status))
1866         return WSTOPSIG (status);
1867     else
1868     {
1869         // We don't know what this is.
1870         return ExitType::eExitTypeInvalid;
1871     }
1872 }
1873 
1874 // Main process monitoring waitpid-loop handler.
1875 bool
1876 NativeProcessLinux::MonitorCallback(void *callback_baton,
1877                                 lldb::pid_t pid,
1878                                 bool exited,
1879                                 int signal,
1880                                 int status)
1881 {
1882     Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1883 
1884     NativeProcessLinux *const process = static_cast<NativeProcessLinux*>(callback_baton);
1885     assert (process && "process is null");
1886     if (!process)
1887     {
1888         if (log)
1889             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " callback_baton was null, can't determine process to use", __FUNCTION__, pid);
1890         return true;
1891     }
1892 
1893     // Certain activities differ based on whether the pid is the tid of the main thread.
1894     const bool is_main_thread = (pid == process->GetID ());
1895 
1896     // Assume we keep monitoring by default.
1897     bool stop_monitoring = false;
1898 
1899     // Handle when the thread exits.
1900     if (exited)
1901     {
1902         if (log)
1903             log->Printf ("NativeProcessLinux::%s() got exit signal, tid = %"  PRIu64 " (%s main thread)", __FUNCTION__, pid, is_main_thread ? "is" : "is not");
1904 
1905         // This is a thread that exited.  Ensure we're not tracking it anymore.
1906         const bool thread_found = process->StopTrackingThread (pid);
1907 
1908         if (is_main_thread)
1909         {
1910             // We only set the exit status and notify the delegate if we haven't already set the process
1911             // state to an exited state.  We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
1912             // for the main thread.
1913             const bool already_notified = (process->GetState() == StateType::eStateExited) | (process->GetState () == StateType::eStateCrashed);
1914             if (!already_notified)
1915             {
1916                 if (log)
1917                     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 ()));
1918                 // The main thread exited.  We're done monitoring.  Report to delegate.
1919                 process->SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
1920 
1921                 // Notify delegate that our process has exited.
1922                 process->SetState (StateType::eStateExited, true);
1923             }
1924             else
1925             {
1926                 if (log)
1927                     log->Printf ("NativeProcessLinux::%s() tid = %"  PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
1928             }
1929             return true;
1930         }
1931         else
1932         {
1933             // Do we want to report to the delegate in this case?  I think not.  If this was an orderly
1934             // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
1935             // and we would have done an all-stop then.
1936             if (log)
1937                 log->Printf ("NativeProcessLinux::%s() tid = %"  PRIu64 " handling non-main thread exit (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
1938 
1939             // Not the main thread, we keep going.
1940             return false;
1941         }
1942     }
1943 
1944     // Get details on the signal raised.
1945     siginfo_t info;
1946     int ptrace_err = 0;
1947 
1948     if (!process->GetSignalInfo (pid, &info, ptrace_err))
1949     {
1950         if (ptrace_err == EINVAL)
1951         {
1952             // This is the first part of the Linux ptrace group-stop mechanism.
1953             // (The other thing it can conceivably be is a call on a pid that no
1954             // longer exists for some reason).
1955             // The tracer (i.e. NativeProcessLinux) is expected to inject the signal
1956             // into the tracee (i.e. inferior) at this point.
1957             if (log)
1958                 log->Printf ("NativeProcessLinux::%s resuming from group-stop", __FUNCTION__);
1959 
1960             // The inferior process is in 'group-stop', so deliver the stopping signal.
1961             const bool signal_delivered = process->Resume (pid, info.si_signo);
1962             if (log)
1963                 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " group-stop signal delivery of signal 0x%x (%s) - %s", __FUNCTION__, pid, info.si_signo, GetUnixSignals ().GetSignalAsCString (info.si_signo), signal_delivered ? "success" : "failed");
1964 
1965             if (signal_delivered)
1966             {
1967                 // All is well.
1968                 stop_monitoring = false;
1969             }
1970             else
1971             {
1972                 if (log)
1973                     log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " something looks horribly wrong - like the process we're monitoring died.  Stop monitoring it.", __FUNCTION__, pid);
1974 
1975                 // Stop monitoring now.
1976                 return true;
1977             }
1978         }
1979         else
1980         {
1981             // ptrace(GETSIGINFO) failed (but not due to group-stop).
1982 
1983             // A return value of ESRCH means the thread/process is no longer on the system,
1984             // so it was killed somehow outside of our control.  Either way, we can't do anything
1985             // with it anymore.
1986 
1987             // We stop monitoring if it was the main thread.
1988             stop_monitoring = is_main_thread;
1989 
1990             // Stop tracking the metadata for the thread since it's entirely off the system now.
1991             const bool thread_found = process->StopTrackingThread (pid);
1992 
1993             if (log)
1994                 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
1995                              __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");
1996 
1997             if (is_main_thread)
1998             {
1999                 // Notify the delegate - our process is not available but appears to have been killed outside
2000                 // our control.  Is eStateExited the right exit state in this case?
2001                 process->SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
2002                 process->SetState (StateType::eStateExited, true);
2003             }
2004             else
2005             {
2006                 // This thread was pulled out from underneath us.  Anything to do here? Do we want to do an all stop?
2007                 if (log)
2008                     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);
2009             }
2010         }
2011     }
2012     else
2013     {
2014         // We have retrieved the signal info.  Dispatch appropriately.
2015         if (info.si_signo == SIGTRAP)
2016             process->MonitorSIGTRAP(&info, pid);
2017         else
2018             process->MonitorSignal(&info, pid, exited);
2019 
2020         stop_monitoring = false;
2021     }
2022 
2023     return stop_monitoring;
2024 }
2025 
2026 void
2027 NativeProcessLinux::MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid)
2028 {
2029     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2030     const bool is_main_thread = (pid == GetID ());
2031 
2032     assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
2033     if (!info)
2034         return;
2035 
2036     // See if we can find a thread for this signal.
2037     NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2038     if (!thread_sp)
2039     {
2040         if (log)
2041             log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2042     }
2043 
2044     switch (info->si_code)
2045     {
2046     // TODO: these two cases are required if we want to support tracing of the inferiors' children.  We'd need this to debug a monitor.
2047     // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
2048     // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
2049 
2050     case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
2051     {
2052         lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2053 
2054         unsigned long event_message = 0;
2055         if (GetEventMessage(pid, &event_message))
2056             tid = static_cast<lldb::tid_t> (event_message);
2057 
2058         if (log)
2059             log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " received thread creation event for tid %" PRIu64, __FUNCTION__, pid, tid);
2060 
2061         // If we don't track the thread yet: create it, mark as stopped.
2062         // If we do track it, this is the wait we needed.  Now resume the new thread.
2063         // In all cases, resume the current (i.e. main process) thread.
2064         bool already_tracked = false;
2065         thread_sp = GetOrCreateThread (tid, already_tracked);
2066         assert (thread_sp.get() && "failed to get or create the tracking data for newly created inferior thread");
2067 
2068         // If the thread was already tracked, it means the created thread already received its SI_USER notification of creation.
2069         if (already_tracked)
2070         {
2071             // FIXME loops like we want to stop all theads here.
2072             // StopAllThreads
2073 
2074             // We can now resume the newly created thread since it is fully created.
2075             reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetRunning ();
2076             Resume (tid, LLDB_INVALID_SIGNAL_NUMBER);
2077         }
2078         else
2079         {
2080             // Mark the thread as currently launching.  Need to wait for SIGTRAP clone on the main thread before
2081             // this thread is ready to go.
2082             reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetLaunching ();
2083         }
2084 
2085         // In all cases, we can resume the main thread here.
2086         Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
2087         break;
2088     }
2089 
2090     case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
2091     {
2092         NativeThreadProtocolSP main_thread_sp;
2093 
2094         if (log)
2095             log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
2096 
2097         // Remove all but the main thread here.
2098         // FIXME check if we really need to do this - how does ptrace behave under exec when multiple threads were present
2099         // before the exec?  If we get all the detach signals right, we don't need to do this.  However, it makes it clearer
2100         // what we should really be tracking.
2101         {
2102             Mutex::Locker locker (m_threads_mutex);
2103 
2104             if (log)
2105                 log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
2106 
2107             for (auto thread_sp : m_threads)
2108             {
2109                 const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
2110                 if (is_main_thread)
2111                 {
2112                     main_thread_sp = thread_sp;
2113                     if (log)
2114                         log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
2115                 }
2116                 else
2117                 {
2118                     if (log)
2119                         log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
2120                 }
2121             }
2122 
2123             m_threads.clear ();
2124 
2125             if (main_thread_sp)
2126             {
2127                 m_threads.push_back (main_thread_sp);
2128                 SetCurrentThreadID (main_thread_sp->GetID ());
2129                 reinterpret_cast<NativeThreadLinux*>(main_thread_sp.get())->SetStoppedByExec ();
2130             }
2131             else
2132             {
2133                 SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
2134                 if (log)
2135                     log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
2136             }
2137         }
2138 
2139         // Let our delegate know we have just exec'd.
2140         NotifyDidExec ();
2141 
2142         // If we have a main thread, indicate we are stopped.
2143         assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
2144         SetState (StateType::eStateStopped);
2145 
2146         break;
2147     }
2148 
2149     case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
2150     {
2151         // The inferior process or one of its threads is about to exit.
2152         // Maintain the process or thread in a state of "limbo" until we are
2153         // explicitly commanded to detach, destroy, resume, etc.
2154         unsigned long data = 0;
2155         if (!GetEventMessage(pid, &data))
2156             data = -1;
2157 
2158         if (log)
2159         {
2160             log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
2161                          __FUNCTION__,
2162                          data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
2163                          pid,
2164                     is_main_thread ? "is main thread" : "not main thread");
2165         }
2166 
2167         // Set the thread to exited.
2168         if (thread_sp)
2169             reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetExited ();
2170         else
2171         {
2172             if (log)
2173                 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " failed to retrieve thread for tid %" PRIu64", cannot set thread state", __FUNCTION__, GetID (), pid);
2174         }
2175 
2176         if (is_main_thread)
2177         {
2178             SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
2179             // Resume the thread so it completely exits.
2180             Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
2181         }
2182         else
2183         {
2184             // FIXME figure out the path where we plan to reap the metadata for the thread.
2185         }
2186 
2187         break;
2188     }
2189 
2190     case 0:
2191     case TRAP_TRACE:
2192         // We receive this on single stepping.
2193         if (log)
2194             log->Printf ("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)", __FUNCTION__, pid);
2195 
2196         if (thread_sp)
2197         {
2198             reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedBySignal (SIGTRAP);
2199             SetCurrentThreadID (thread_sp->GetID ());
2200         }
2201         else
2202         {
2203             if (log)
2204                 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 " single stepping received trace but thread not found", __FUNCTION__, GetID (), pid);
2205         }
2206 
2207         // Tell the process we have a stop (from single stepping).
2208         SetState (StateType::eStateStopped, true);
2209         break;
2210 
2211     case SI_KERNEL:
2212     case TRAP_BRKPT:
2213         if (log)
2214             log->Printf ("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64, __FUNCTION__, pid);
2215 
2216         // Mark the thread as stopped at breakpoint.
2217         if (thread_sp)
2218         {
2219             reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedBySignal (SIGTRAP);
2220             Error error = FixupBreakpointPCAsNeeded (thread_sp);
2221             if (error.Fail ())
2222             {
2223                 if (log)
2224                     log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s", __FUNCTION__, pid, error.AsCString ());
2225             }
2226         }
2227         else
2228         {
2229             if (log)
2230                 log->Printf ("NativeProcessLinux::%s()  pid = %" PRIu64 ": warning, cannot process software breakpoint since no thread metadata", __FUNCTION__, pid);
2231         }
2232 
2233 
2234         // Tell the process we have a stop from this thread.
2235         SetCurrentThreadID (pid);
2236         SetState (StateType::eStateStopped, true);
2237         break;
2238 
2239     case TRAP_HWBKPT:
2240         if (log)
2241             log->Printf ("NativeProcessLinux::%s() received watchpoint event, pid = %" PRIu64, __FUNCTION__, pid);
2242 
2243         // Mark the thread as stopped at watchpoint.
2244         // The address is at (lldb::addr_t)info->si_addr if we need it.
2245         if (thread_sp)
2246             reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedBySignal (SIGTRAP);
2247         else
2248         {
2249             if (log)
2250                 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ": warning, cannot process hardware breakpoint since no thread metadata", __FUNCTION__, GetID (), pid);
2251         }
2252 
2253         // Tell the process we have a stop from this thread.
2254         SetCurrentThreadID (pid);
2255         SetState (StateType::eStateStopped, true);
2256         break;
2257 
2258     case SIGTRAP:
2259     case (SIGTRAP | 0x80):
2260         if (log)
2261             log->Printf ("NativeProcessLinux::%s() received system call stop event, pid %" PRIu64 "tid %" PRIu64, __FUNCTION__, GetID (), pid);
2262         // Ignore these signals until we know more about them.
2263         Resume(pid, 0);
2264         break;
2265 
2266     default:
2267         assert(false && "Unexpected SIGTRAP code!");
2268         if (log)
2269             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)));
2270         break;
2271 
2272     }
2273 }
2274 
2275 void
2276 NativeProcessLinux::MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited)
2277 {
2278     int signo = info->si_signo;
2279 
2280     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2281 
2282     // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
2283     // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
2284     // kill(2) or raise(3).  Similarly for tgkill(2) on Linux.
2285     //
2286     // IOW, user generated signals never generate what we consider to be a
2287     // "crash".
2288     //
2289     // Similarly, ACK signals generated by this monitor.
2290 
2291     // See if we can find a thread for this signal.
2292     NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2293     if (!thread_sp)
2294     {
2295         if (log)
2296             log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2297     }
2298 
2299     // Handle the signal.
2300     if (info->si_code == SI_TKILL || info->si_code == SI_USER)
2301     {
2302         if (log)
2303             log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
2304                             __FUNCTION__,
2305                             GetUnixSignals ().GetSignalAsCString (signo),
2306                             signo,
2307                             (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
2308                             info->si_pid,
2309                             (info->si_pid == getpid ()) ? "is monitor" : "is not monitor",
2310                             pid);
2311     }
2312 
2313     // Check for new thread notification.
2314     if ((info->si_pid == 0) && (info->si_code == SI_USER))
2315     {
2316         // A new thread creation is being signaled.  This is one of two parts that come in
2317         // a non-deterministic order.  pid is the thread id.
2318         if (log)
2319             log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": new thread notification",
2320                      __FUNCTION__, GetID (), pid);
2321 
2322         // Did we already create the thread?
2323         bool already_tracked = false;
2324         thread_sp = GetOrCreateThread (pid, already_tracked);
2325         assert (thread_sp.get() && "failed to get or create the tracking data for newly created inferior thread");
2326 
2327         // If the thread was already tracked, it means the main thread already received its SIGTRAP for the create.
2328         if (already_tracked)
2329         {
2330             // We can now resume this thread up since it is fully created.
2331             reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetRunning ();
2332             Resume (thread_sp->GetID (), LLDB_INVALID_SIGNAL_NUMBER);
2333         }
2334         else
2335         {
2336             // Mark the thread as currently launching.  Need to wait for SIGTRAP clone on the main thread before
2337             // this thread is ready to go.
2338             reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetLaunching ();
2339         }
2340 
2341         // Done handling.
2342         return;
2343     }
2344 
2345     // Check for thread stop notification.
2346     if ((info->si_pid == getpid ()) && (info->si_code == SI_TKILL) && (signo == SIGSTOP))
2347     {
2348         // This is a tgkill()-based stop.
2349         if (thread_sp)
2350         {
2351             // An inferior thread just stopped.  Mark it as such.
2352             reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedBySignal (signo);
2353             SetCurrentThreadID (thread_sp->GetID ());
2354 
2355             // Remove this tid from the wait-for-stop set.
2356             Mutex::Locker locker (m_wait_for_stop_tids_mutex);
2357 
2358             auto removed_count = m_wait_for_stop_tids.erase (thread_sp->GetID ());
2359             if (removed_count < 1)
2360             {
2361                 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": tgkill()-stopped thread not in m_wait_for_stop_tids",
2362                              __FUNCTION__, GetID (), thread_sp->GetID ());
2363 
2364             }
2365 
2366             // If this is the last thread in the m_wait_for_stop_tids, we need to notify
2367             // the delegate that a stop has occurred now that every thread that was supposed
2368             // to stop has stopped.
2369             if (m_wait_for_stop_tids.empty ())
2370             {
2371                 if (log)
2372                 {
2373                     log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", setting process state to stopped now that all tids marked for stop have completed",
2374                                  __FUNCTION__,
2375                                  GetID (),
2376                                  pid);
2377                 }
2378                 SetState (StateType::eStateStopped, true);
2379             }
2380         }
2381 
2382         // Done handling.
2383         return;
2384     }
2385 
2386     if (log)
2387         log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, GetUnixSignals ().GetSignalAsCString (signo));
2388 
2389     switch (signo)
2390     {
2391     case SIGSEGV:
2392         {
2393             lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
2394 
2395             // FIXME figure out how to propagate this properly.  Seems like it
2396             // should go in ThreadStopInfo.
2397             // We can get more details on the exact nature of the crash here.
2398             // ProcessMessage::CrashReason reason = GetCrashReasonForSIGSEGV(info);
2399             if (!exited)
2400             {
2401                 // This is just a pre-signal-delivery notification of the incoming signal.
2402                 // Send a stop to the debugger.
2403                 if (thread_sp)
2404                 {
2405                     reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedBySignal (signo);
2406                     SetCurrentThreadID (thread_sp->GetID ());
2407                 }
2408                 SetState (StateType::eStateStopped, true);
2409             }
2410             else
2411             {
2412                 if (thread_sp)
2413                 {
2414                     // FIXME figure out what type this is.
2415                     const uint64_t exception_type = static_cast<uint64_t> (SIGSEGV);
2416                     reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetCrashedWithException (exception_type, fault_addr);
2417                 }
2418                 SetState (StateType::eStateCrashed, true);
2419             }
2420         }
2421         break;
2422 
2423     case SIGABRT:
2424     case SIGILL:
2425     case SIGFPE:
2426     case SIGBUS:
2427         {
2428             // Break these out into separate cases once I have more data for each type of signal.
2429             lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
2430             if (!exited)
2431             {
2432                 // This is just a pre-signal-delivery notification of the incoming signal.
2433                 // Send a stop to the debugger.
2434                 if (thread_sp)
2435                 {
2436                     reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedBySignal (signo);
2437                     SetCurrentThreadID (thread_sp->GetID ());
2438                 }
2439                 SetState (StateType::eStateStopped, true);
2440             }
2441             else
2442             {
2443                 if (thread_sp)
2444                 {
2445                     // FIXME figure out how to report exit by signal correctly.
2446                     const uint64_t exception_type = static_cast<uint64_t> (SIGABRT);
2447                     reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetCrashedWithException (exception_type, fault_addr);
2448                 }
2449                 SetState (StateType::eStateCrashed, true);
2450             }
2451         }
2452         break;
2453 
2454     default:
2455         if (log)
2456             log->Printf ("NativeProcessLinux::%s unhandled signal %s (%d)", __FUNCTION__, GetUnixSignals ().GetSignalAsCString (signo), signo);
2457         break;
2458     }
2459 }
2460 
2461 Error
2462 NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
2463 {
2464     Error error;
2465 
2466     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2467     if (log)
2468         log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
2469 
2470     int run_thread_count = 0;
2471     int stop_thread_count = 0;
2472     int step_thread_count = 0;
2473 
2474     std::vector<NativeThreadProtocolSP> new_stop_threads;
2475 
2476     Mutex::Locker locker (m_threads_mutex);
2477     for (auto thread_sp : m_threads)
2478     {
2479         assert (thread_sp && "thread list should not contain NULL threads");
2480         NativeThreadLinux *const linux_thread_p = reinterpret_cast<NativeThreadLinux*> (thread_sp.get ());
2481 
2482         const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
2483         assert (action && "NULL ResumeAction returned for thread during Resume ()");
2484 
2485         if (log)
2486         {
2487             log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
2488                     __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
2489         }
2490 
2491         switch (action->state)
2492         {
2493         case eStateRunning:
2494             // Run the thread, possibly feeding it the signal.
2495             linux_thread_p->SetRunning ();
2496             if (action->signal > 0)
2497             {
2498                 // Resume the thread and deliver the given signal,
2499                 // then mark as delivered.
2500                 Resume (thread_sp->GetID (), action->signal);
2501                 resume_actions.SetSignalHandledForThread (thread_sp->GetID ());
2502             }
2503             else
2504             {
2505                 // Just resume the thread with no signal.
2506                 Resume (thread_sp->GetID (), LLDB_INVALID_SIGNAL_NUMBER);
2507             }
2508             ++run_thread_count;
2509             break;
2510 
2511         case eStateStepping:
2512             // Note: if we have multiple threads, we may need to stop
2513             // the other threads first, then step this one.
2514             linux_thread_p->SetStepping ();
2515             if (SingleStep (thread_sp->GetID (), 0))
2516             {
2517                 if (log)
2518                     log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 " single step succeeded",
2519                                  __FUNCTION__, GetID (), thread_sp->GetID ());
2520             }
2521             else
2522             {
2523                 if (log)
2524                     log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 " single step failed",
2525                                  __FUNCTION__, GetID (), thread_sp->GetID ());
2526             }
2527             ++step_thread_count;
2528             break;
2529 
2530         case eStateSuspended:
2531         case eStateStopped:
2532             if (!StateIsStoppedState (linux_thread_p->GetState (), false))
2533                 new_stop_threads.push_back (thread_sp);
2534             else
2535             {
2536                 if (log)
2537                     log->Printf ("NativeProcessLinux::%s no need to stop pid %" PRIu64 " tid %" PRIu64 ", thread state already %s",
2538                                  __FUNCTION__, GetID (), thread_sp->GetID (), StateAsCString (linux_thread_p->GetState ()));
2539             }
2540 
2541             ++stop_thread_count;
2542             break;
2543 
2544         default:
2545             return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
2546                     __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
2547         }
2548     }
2549 
2550     // If any thread was set to run, notify the process state as running.
2551     if (run_thread_count > 0)
2552         SetState (StateType::eStateRunning, true);
2553 
2554     // Now do a tgkill SIGSTOP on each thread we want to stop.
2555     if (!new_stop_threads.empty ())
2556     {
2557         // Lock the m_wait_for_stop_tids set so we can fill it with every thread we expect to have stopped.
2558         Mutex::Locker stop_thread_id_locker (m_wait_for_stop_tids_mutex);
2559         for (auto thread_sp : new_stop_threads)
2560         {
2561             // Send a stop signal to the thread.
2562             const int result = tgkill (GetID (), thread_sp->GetID (), SIGSTOP);
2563             if (result != 0)
2564             {
2565                 // tgkill failed.
2566                 if (log)
2567                     log->Printf ("NativeProcessLinux::%s error: tgkill SIGSTOP for pid %" PRIu64 " tid %" PRIu64 "failed, retval %d",
2568                                  __FUNCTION__, GetID (), thread_sp->GetID (), result);
2569             }
2570             else
2571             {
2572                 // tgkill succeeded.  Don't mark the thread state, though.  Let the signal
2573                 // handling mark it.
2574                 if (log)
2575                     log->Printf ("NativeProcessLinux::%s tgkill SIGSTOP for pid %" PRIu64 " tid %" PRIu64 " succeeded",
2576                                  __FUNCTION__, GetID (), thread_sp->GetID ());
2577 
2578                 // Add it to the set of threads we expect to signal a stop.
2579                 // We won't tell the delegate about it until this list drains to empty.
2580                 m_wait_for_stop_tids.insert (thread_sp->GetID ());
2581             }
2582         }
2583     }
2584 
2585     return error;
2586 }
2587 
2588 Error
2589 NativeProcessLinux::Halt ()
2590 {
2591     Error error;
2592 
2593     // FIXME check if we're already stopped
2594     const bool is_stopped = false;
2595     if (is_stopped)
2596         return error;
2597 
2598     if (kill (GetID (), SIGSTOP) != 0)
2599         error.SetErrorToErrno ();
2600 
2601     return error;
2602 }
2603 
2604 Error
2605 NativeProcessLinux::Detach ()
2606 {
2607     Error error;
2608 
2609     // Tell ptrace to detach from the process.
2610     if (GetID () != LLDB_INVALID_PROCESS_ID)
2611         error = Detach (GetID ());
2612 
2613     // Stop monitoring the inferior.
2614     StopMonitor ();
2615 
2616     // No error.
2617     return error;
2618 }
2619 
2620 Error
2621 NativeProcessLinux::Signal (int signo)
2622 {
2623     Error error;
2624 
2625     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2626     if (log)
2627         log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
2628                 __FUNCTION__, signo,  GetUnixSignals ().GetSignalAsCString (signo), GetID ());
2629 
2630     if (kill(GetID(), signo))
2631         error.SetErrorToErrno();
2632 
2633     return error;
2634 }
2635 
2636 Error
2637 NativeProcessLinux::Kill ()
2638 {
2639     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2640     if (log)
2641         log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
2642 
2643     Error error;
2644 
2645     switch (m_state)
2646     {
2647         case StateType::eStateInvalid:
2648         case StateType::eStateExited:
2649         case StateType::eStateCrashed:
2650         case StateType::eStateDetached:
2651         case StateType::eStateUnloaded:
2652             // Nothing to do - the process is already dead.
2653             if (log)
2654                 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
2655             return error;
2656 
2657         case StateType::eStateConnected:
2658         case StateType::eStateAttaching:
2659         case StateType::eStateLaunching:
2660         case StateType::eStateStopped:
2661         case StateType::eStateRunning:
2662         case StateType::eStateStepping:
2663         case StateType::eStateSuspended:
2664             // We can try to kill a process in these states.
2665             break;
2666     }
2667 
2668     if (kill (GetID (), SIGKILL) != 0)
2669     {
2670         error.SetErrorToErrno ();
2671         return error;
2672     }
2673 
2674     return error;
2675 }
2676 
2677 static Error
2678 ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
2679 {
2680     memory_region_info.Clear();
2681 
2682     StringExtractor line_extractor (maps_line.c_str ());
2683 
2684     // Format: {address_start_hex}-{address_end_hex} perms offset  dev   inode   pathname
2685     // perms: rwxp   (letter is present if set, '-' if not, final character is p=private, s=shared).
2686 
2687     // Parse out the starting address
2688     lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
2689 
2690     // Parse out hyphen separating start and end address from range.
2691     if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
2692         return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
2693 
2694     // Parse out the ending address
2695     lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
2696 
2697     // Parse out the space after the address.
2698     if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
2699         return Error ("malformed /proc/{pid}/maps entry, missing space after range");
2700 
2701     // Save the range.
2702     memory_region_info.GetRange ().SetRangeBase (start_address);
2703     memory_region_info.GetRange ().SetRangeEnd (end_address);
2704 
2705     // Parse out each permission entry.
2706     if (line_extractor.GetBytesLeft () < 4)
2707         return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
2708 
2709     // Handle read permission.
2710     const char read_perm_char = line_extractor.GetChar ();
2711     if (read_perm_char == 'r')
2712         memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
2713     else
2714     {
2715         assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
2716         memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2717     }
2718 
2719     // Handle write permission.
2720     const char write_perm_char = line_extractor.GetChar ();
2721     if (write_perm_char == 'w')
2722         memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
2723     else
2724     {
2725         assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
2726         memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2727     }
2728 
2729     // Handle execute permission.
2730     const char exec_perm_char = line_extractor.GetChar ();
2731     if (exec_perm_char == 'x')
2732         memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
2733     else
2734     {
2735         assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
2736         memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2737     }
2738 
2739     return Error ();
2740 }
2741 
2742 Error
2743 NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
2744 {
2745     // FIXME review that the final memory region returned extends to the end of the virtual address space,
2746     // with no perms if it is not mapped.
2747 
2748     // Use an approach that reads memory regions from /proc/{pid}/maps.
2749     // Assume proc maps entries are in ascending order.
2750     // FIXME assert if we find differently.
2751     Mutex::Locker locker (m_mem_region_cache_mutex);
2752 
2753     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2754     Error error;
2755 
2756     if (m_supports_mem_region == LazyBool::eLazyBoolNo)
2757     {
2758         // We're done.
2759         error.SetErrorString ("unsupported");
2760         return error;
2761     }
2762 
2763     // If our cache is empty, pull the latest.  There should always be at least one memory region
2764     // if memory region handling is supported.
2765     if (m_mem_region_cache.empty ())
2766     {
2767         error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
2768              [&] (const std::string &line) -> bool
2769              {
2770                  MemoryRegionInfo info;
2771                  const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
2772                  if (parse_error.Success ())
2773                  {
2774                      m_mem_region_cache.push_back (info);
2775                      return true;
2776                  }
2777                  else
2778                  {
2779                      if (log)
2780                          log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
2781                      return false;
2782                  }
2783              });
2784 
2785         // If we had an error, we'll mark unsupported.
2786         if (error.Fail ())
2787         {
2788             m_supports_mem_region = LazyBool::eLazyBoolNo;
2789             return error;
2790         }
2791         else if (m_mem_region_cache.empty ())
2792         {
2793             // No entries after attempting to read them.  This shouldn't happen if /proc/{pid}/maps
2794             // is supported.  Assume we don't support map entries via procfs.
2795             if (log)
2796                 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
2797             m_supports_mem_region = LazyBool::eLazyBoolNo;
2798             error.SetErrorString ("not supported");
2799             return error;
2800         }
2801 
2802         if (log)
2803             log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ());
2804 
2805         // We support memory retrieval, remember that.
2806         m_supports_mem_region = LazyBool::eLazyBoolYes;
2807     }
2808     else
2809     {
2810         if (log)
2811             log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2812     }
2813 
2814     lldb::addr_t prev_base_address = 0;
2815 
2816     // FIXME start by finding the last region that is <= target address using binary search.  Data is sorted.
2817     // There can be a ton of regions on pthreads apps with lots of threads.
2818     for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
2819     {
2820         MemoryRegionInfo &proc_entry_info = *it;
2821 
2822         // Sanity check assumption that /proc/{pid}/maps entries are ascending.
2823         assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
2824         prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
2825 
2826         // If the target address comes before this entry, indicate distance to next region.
2827         if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
2828         {
2829             range_info.GetRange ().SetRangeBase (load_addr);
2830             range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
2831             range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2832             range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2833             range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2834 
2835             return error;
2836         }
2837         else if (proc_entry_info.GetRange ().Contains (load_addr))
2838         {
2839             // The target address is within the memory region we're processing here.
2840             range_info = proc_entry_info;
2841             return error;
2842         }
2843 
2844         // The target memory address comes somewhere after the region we just parsed.
2845     }
2846 
2847     // If we made it here, we didn't find an entry that contained the given address.
2848     error.SetErrorString ("address comes after final region");
2849 
2850     if (log)
2851         log->Printf ("NativeProcessLinux::%s failed to find map entry for address 0x%" PRIx64 ": %s", __FUNCTION__, load_addr, error.AsCString ());
2852 
2853     return error;
2854 }
2855 
2856 void
2857 NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
2858 {
2859     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2860     if (log)
2861         log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
2862 
2863     {
2864         Mutex::Locker locker (m_mem_region_cache_mutex);
2865         if (log)
2866             log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2867         m_mem_region_cache.clear ();
2868     }
2869 }
2870 
2871 Error
2872 NativeProcessLinux::AllocateMemory (
2873     lldb::addr_t size,
2874     uint32_t permissions,
2875     lldb::addr_t &addr)
2876 {
2877     // FIXME implementing this requires the equivalent of
2878     // InferiorCallPOSIX::InferiorCallMmap, which depends on
2879     // functional ThreadPlans working with Native*Protocol.
2880 #if 1
2881     return Error ("not implemented yet");
2882 #else
2883     addr = LLDB_INVALID_ADDRESS;
2884 
2885     unsigned prot = 0;
2886     if (permissions & lldb::ePermissionsReadable)
2887         prot |= eMmapProtRead;
2888     if (permissions & lldb::ePermissionsWritable)
2889         prot |= eMmapProtWrite;
2890     if (permissions & lldb::ePermissionsExecutable)
2891         prot |= eMmapProtExec;
2892 
2893     // TODO implement this directly in NativeProcessLinux
2894     // (and lift to NativeProcessPOSIX if/when that class is
2895     // refactored out).
2896     if (InferiorCallMmap(this, addr, 0, size, prot,
2897                          eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
2898         m_addr_to_mmap_size[addr] = size;
2899         return Error ();
2900     } else {
2901         addr = LLDB_INVALID_ADDRESS;
2902         return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
2903     }
2904 #endif
2905 }
2906 
2907 Error
2908 NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
2909 {
2910     // FIXME see comments in AllocateMemory - required lower-level
2911     // bits not in place yet (ThreadPlans)
2912     return Error ("not implemented");
2913 }
2914 
2915 lldb::addr_t
2916 NativeProcessLinux::GetSharedLibraryInfoAddress ()
2917 {
2918 #if 1
2919     // punt on this for now
2920     return LLDB_INVALID_ADDRESS;
2921 #else
2922     // Return the image info address for the exe module
2923 #if 1
2924     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2925 
2926     ModuleSP module_sp;
2927     Error error = GetExeModuleSP (module_sp);
2928     if (error.Fail ())
2929     {
2930          if (log)
2931             log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ());
2932         return LLDB_INVALID_ADDRESS;
2933     }
2934 
2935     if (module_sp == nullptr)
2936     {
2937          if (log)
2938             log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__);
2939          return LLDB_INVALID_ADDRESS;
2940     }
2941 
2942     ObjectFileSP object_file_sp = module_sp->GetObjectFile ();
2943     if (object_file_sp == nullptr)
2944     {
2945          if (log)
2946             log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__);
2947          return LLDB_INVALID_ADDRESS;
2948     }
2949 
2950     return obj_file_sp->GetImageInfoAddress();
2951 #else
2952     Target *target = &GetTarget();
2953     ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
2954     Address addr = obj_file->GetImageInfoAddress(target);
2955 
2956     if (addr.IsValid())
2957         return addr.GetLoadAddress(target);
2958     return LLDB_INVALID_ADDRESS;
2959 #endif
2960 #endif // punt on this for now
2961 }
2962 
2963 size_t
2964 NativeProcessLinux::UpdateThreads ()
2965 {
2966     // The NativeProcessLinux monitoring threads are always up to date
2967     // with respect to thread state and they keep the thread list
2968     // populated properly. All this method needs to do is return the
2969     // thread count.
2970     Mutex::Locker locker (m_threads_mutex);
2971     return m_threads.size ();
2972 }
2973 
2974 bool
2975 NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
2976 {
2977     arch = m_arch;
2978     return true;
2979 }
2980 
2981 Error
2982 NativeProcessLinux::GetSoftwareBreakpointSize (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size)
2983 {
2984     // FIXME put this behind a breakpoint protocol class that can be
2985     // set per architecture.  Need ARM, MIPS support here.
2986     static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
2987     static const uint8_t g_i386_opcode [] = { 0xCC };
2988 
2989     switch (m_arch.GetMachine ())
2990     {
2991         case llvm::Triple::aarch64:
2992             actual_opcode_size = static_cast<uint32_t> (sizeof(g_aarch64_opcode));
2993             return Error ();
2994 
2995         case llvm::Triple::x86:
2996         case llvm::Triple::x86_64:
2997             actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
2998             return Error ();
2999 
3000         default:
3001             assert(false && "CPU type not supported!");
3002             return Error ("CPU type not supported");
3003     }
3004 }
3005 
3006 Error
3007 NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
3008 {
3009     if (hardware)
3010         return Error ("NativeProcessLinux does not support hardware breakpoints");
3011     else
3012         return SetSoftwareBreakpoint (addr, size);
3013 }
3014 
3015 Error
3016 NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint, size_t &actual_opcode_size, const uint8_t *&trap_opcode_bytes)
3017 {
3018     // FIXME put this behind a breakpoint protocol class that can be
3019     // set per architecture.  Need ARM, MIPS support here.
3020     static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
3021     static const uint8_t g_i386_opcode [] = { 0xCC };
3022 
3023     switch (m_arch.GetMachine ())
3024     {
3025     case llvm::Triple::aarch64:
3026         trap_opcode_bytes = g_aarch64_opcode;
3027         actual_opcode_size = sizeof(g_aarch64_opcode);
3028         return Error ();
3029 
3030     case llvm::Triple::x86:
3031     case llvm::Triple::x86_64:
3032         trap_opcode_bytes = g_i386_opcode;
3033         actual_opcode_size = sizeof(g_i386_opcode);
3034         return Error ();
3035 
3036     default:
3037         assert(false && "CPU type not supported!");
3038         return Error ("CPU type not supported");
3039     }
3040 }
3041 
3042 #if 0
3043 ProcessMessage::CrashReason
3044 NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
3045 {
3046     ProcessMessage::CrashReason reason;
3047     assert(info->si_signo == SIGSEGV);
3048 
3049     reason = ProcessMessage::eInvalidCrashReason;
3050 
3051     switch (info->si_code)
3052     {
3053     default:
3054         assert(false && "unexpected si_code for SIGSEGV");
3055         break;
3056     case SI_KERNEL:
3057         // Linux will occasionally send spurious SI_KERNEL codes.
3058         // (this is poorly documented in sigaction)
3059         // One way to get this is via unaligned SIMD loads.
3060         reason = ProcessMessage::eInvalidAddress; // for lack of anything better
3061         break;
3062     case SEGV_MAPERR:
3063         reason = ProcessMessage::eInvalidAddress;
3064         break;
3065     case SEGV_ACCERR:
3066         reason = ProcessMessage::ePrivilegedAddress;
3067         break;
3068     }
3069 
3070     return reason;
3071 }
3072 #endif
3073 
3074 
3075 #if 0
3076 ProcessMessage::CrashReason
3077 NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
3078 {
3079     ProcessMessage::CrashReason reason;
3080     assert(info->si_signo == SIGILL);
3081 
3082     reason = ProcessMessage::eInvalidCrashReason;
3083 
3084     switch (info->si_code)
3085     {
3086     default:
3087         assert(false && "unexpected si_code for SIGILL");
3088         break;
3089     case ILL_ILLOPC:
3090         reason = ProcessMessage::eIllegalOpcode;
3091         break;
3092     case ILL_ILLOPN:
3093         reason = ProcessMessage::eIllegalOperand;
3094         break;
3095     case ILL_ILLADR:
3096         reason = ProcessMessage::eIllegalAddressingMode;
3097         break;
3098     case ILL_ILLTRP:
3099         reason = ProcessMessage::eIllegalTrap;
3100         break;
3101     case ILL_PRVOPC:
3102         reason = ProcessMessage::ePrivilegedOpcode;
3103         break;
3104     case ILL_PRVREG:
3105         reason = ProcessMessage::ePrivilegedRegister;
3106         break;
3107     case ILL_COPROC:
3108         reason = ProcessMessage::eCoprocessorError;
3109         break;
3110     case ILL_BADSTK:
3111         reason = ProcessMessage::eInternalStackError;
3112         break;
3113     }
3114 
3115     return reason;
3116 }
3117 #endif
3118 
3119 #if 0
3120 ProcessMessage::CrashReason
3121 NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
3122 {
3123     ProcessMessage::CrashReason reason;
3124     assert(info->si_signo == SIGFPE);
3125 
3126     reason = ProcessMessage::eInvalidCrashReason;
3127 
3128     switch (info->si_code)
3129     {
3130     default:
3131         assert(false && "unexpected si_code for SIGFPE");
3132         break;
3133     case FPE_INTDIV:
3134         reason = ProcessMessage::eIntegerDivideByZero;
3135         break;
3136     case FPE_INTOVF:
3137         reason = ProcessMessage::eIntegerOverflow;
3138         break;
3139     case FPE_FLTDIV:
3140         reason = ProcessMessage::eFloatDivideByZero;
3141         break;
3142     case FPE_FLTOVF:
3143         reason = ProcessMessage::eFloatOverflow;
3144         break;
3145     case FPE_FLTUND:
3146         reason = ProcessMessage::eFloatUnderflow;
3147         break;
3148     case FPE_FLTRES:
3149         reason = ProcessMessage::eFloatInexactResult;
3150         break;
3151     case FPE_FLTINV:
3152         reason = ProcessMessage::eFloatInvalidOperation;
3153         break;
3154     case FPE_FLTSUB:
3155         reason = ProcessMessage::eFloatSubscriptRange;
3156         break;
3157     }
3158 
3159     return reason;
3160 }
3161 #endif
3162 
3163 #if 0
3164 ProcessMessage::CrashReason
3165 NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
3166 {
3167     ProcessMessage::CrashReason reason;
3168     assert(info->si_signo == SIGBUS);
3169 
3170     reason = ProcessMessage::eInvalidCrashReason;
3171 
3172     switch (info->si_code)
3173     {
3174     default:
3175         assert(false && "unexpected si_code for SIGBUS");
3176         break;
3177     case BUS_ADRALN:
3178         reason = ProcessMessage::eIllegalAlignment;
3179         break;
3180     case BUS_ADRERR:
3181         reason = ProcessMessage::eIllegalAddress;
3182         break;
3183     case BUS_OBJERR:
3184         reason = ProcessMessage::eHardwareError;
3185         break;
3186     }
3187 
3188     return reason;
3189 }
3190 #endif
3191 
3192 void
3193 NativeProcessLinux::ServeOperation(OperationArgs *args)
3194 {
3195     NativeProcessLinux *monitor = args->m_monitor;
3196 
3197     // We are finised with the arguments and are ready to go.  Sync with the
3198     // parent thread and start serving operations on the inferior.
3199     sem_post(&args->m_semaphore);
3200 
3201     for(;;)
3202     {
3203         // wait for next pending operation
3204         if (sem_wait(&monitor->m_operation_pending))
3205         {
3206             if (errno == EINTR)
3207                 continue;
3208             assert(false && "Unexpected errno from sem_wait");
3209         }
3210 
3211         reinterpret_cast<Operation*>(monitor->m_operation)->Execute(monitor);
3212 
3213         // notify calling thread that operation is complete
3214         sem_post(&monitor->m_operation_done);
3215     }
3216 }
3217 
3218 void
3219 NativeProcessLinux::DoOperation(void *op)
3220 {
3221     Mutex::Locker lock(m_operation_mutex);
3222 
3223     m_operation = op;
3224 
3225     // notify operation thread that an operation is ready to be processed
3226     sem_post(&m_operation_pending);
3227 
3228     // wait for operation to complete
3229     while (sem_wait(&m_operation_done))
3230     {
3231         if (errno == EINTR)
3232             continue;
3233         assert(false && "Unexpected errno from sem_wait");
3234     }
3235 }
3236 
3237 Error
3238 NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, lldb::addr_t size, lldb::addr_t &bytes_read)
3239 {
3240     ReadOperation op(addr, buf, size, bytes_read);
3241     DoOperation(&op);
3242     return op.GetError ();
3243 }
3244 
3245 Error
3246 NativeProcessLinux::WriteMemory (lldb::addr_t addr, const void *buf, lldb::addr_t size, lldb::addr_t &bytes_written)
3247 {
3248     WriteOperation op(addr, buf, size, bytes_written);
3249     DoOperation(&op);
3250     return op.GetError ();
3251 }
3252 
3253 bool
3254 NativeProcessLinux::ReadRegisterValue(lldb::tid_t tid, uint32_t offset, const char* reg_name,
3255                                   uint32_t size, RegisterValue &value)
3256 {
3257     bool result;
3258     ReadRegOperation op(tid, offset, reg_name, value, result);
3259     DoOperation(&op);
3260     return result;
3261 }
3262 
3263 bool
3264 NativeProcessLinux::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
3265                                    const char* reg_name, const RegisterValue &value)
3266 {
3267     bool result;
3268     WriteRegOperation op(tid, offset, reg_name, value, result);
3269     DoOperation(&op);
3270     return result;
3271 }
3272 
3273 bool
3274 NativeProcessLinux::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3275 {
3276     bool result;
3277     ReadGPROperation op(tid, buf, buf_size, result);
3278     DoOperation(&op);
3279     return result;
3280 }
3281 
3282 bool
3283 NativeProcessLinux::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3284 {
3285     bool result;
3286     ReadFPROperation op(tid, buf, buf_size, result);
3287     DoOperation(&op);
3288     return result;
3289 }
3290 
3291 bool
3292 NativeProcessLinux::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3293 {
3294     bool result;
3295     ReadRegisterSetOperation op(tid, buf, buf_size, regset, result);
3296     DoOperation(&op);
3297     return result;
3298 }
3299 
3300 bool
3301 NativeProcessLinux::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3302 {
3303     bool result;
3304     WriteGPROperation op(tid, buf, buf_size, result);
3305     DoOperation(&op);
3306     return result;
3307 }
3308 
3309 bool
3310 NativeProcessLinux::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3311 {
3312     bool result;
3313     WriteFPROperation op(tid, buf, buf_size, result);
3314     DoOperation(&op);
3315     return result;
3316 }
3317 
3318 bool
3319 NativeProcessLinux::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3320 {
3321     bool result;
3322     WriteRegisterSetOperation op(tid, buf, buf_size, regset, result);
3323     DoOperation(&op);
3324     return result;
3325 }
3326 
3327 bool
3328 NativeProcessLinux::Resume (lldb::tid_t tid, uint32_t signo)
3329 {
3330     bool result;
3331     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3332 
3333     if (log)
3334         log->Printf ("NativeProcessLinux::%s() resuming thread = %"  PRIu64 " with signal %s", __FUNCTION__, tid,
3335                                  GetUnixSignals().GetSignalAsCString (signo));
3336     ResumeOperation op (tid, signo, result);
3337     DoOperation (&op);
3338     if (log)
3339         log->Printf ("NativeProcessLinux::%s() resuming result = %s", __FUNCTION__, result ? "true" : "false");
3340     return result;
3341 }
3342 
3343 bool
3344 NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo)
3345 {
3346     bool result;
3347     SingleStepOperation op(tid, signo, result);
3348     DoOperation(&op);
3349     return result;
3350 }
3351 
3352 bool
3353 NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo, int &ptrace_err)
3354 {
3355     bool result;
3356     SiginfoOperation op(tid, siginfo, result, ptrace_err);
3357     DoOperation(&op);
3358     return result;
3359 }
3360 
3361 bool
3362 NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
3363 {
3364     bool result;
3365     EventMessageOperation op(tid, message, result);
3366     DoOperation(&op);
3367     return result;
3368 }
3369 
3370 lldb_private::Error
3371 NativeProcessLinux::Detach(lldb::tid_t tid)
3372 {
3373     lldb_private::Error error;
3374     if (tid != LLDB_INVALID_THREAD_ID)
3375     {
3376         DetachOperation op(tid, error);
3377         DoOperation(&op);
3378     }
3379     return error;
3380 }
3381 
3382 bool
3383 NativeProcessLinux::DupDescriptor(const char *path, int fd, int flags)
3384 {
3385     int target_fd = open(path, flags, 0666);
3386 
3387     if (target_fd == -1)
3388         return false;
3389 
3390     return (dup2(target_fd, fd) == -1) ? false : true;
3391 }
3392 
3393 void
3394 NativeProcessLinux::StopMonitoringChildProcess()
3395 {
3396     if (m_monitor_thread.GetState() == eThreadStateRunning)
3397     {
3398         m_monitor_thread.Cancel();
3399         m_monitor_thread.Join(nullptr);
3400         m_monitor_thread.Reset();
3401     }
3402 }
3403 
3404 void
3405 NativeProcessLinux::StopMonitor()
3406 {
3407     StopMonitoringChildProcess();
3408     StopOpThread();
3409     sem_destroy(&m_operation_pending);
3410     sem_destroy(&m_operation_done);
3411 
3412     // TODO: validate whether this still holds, fix up comment.
3413     // Note: ProcessPOSIX passes the m_terminal_fd file descriptor to
3414     // Process::SetSTDIOFileDescriptor, which in turn transfers ownership of
3415     // the descriptor to a ConnectionFileDescriptor object.  Consequently
3416     // even though still has the file descriptor, we shouldn't close it here.
3417 }
3418 
3419 void
3420 NativeProcessLinux::StopOpThread()
3421 {
3422     if (m_operation_thread.GetState() != eThreadStateRunning)
3423         return;
3424 
3425     m_operation_thread.Cancel();
3426     m_operation_thread.Join(nullptr);
3427     m_operation_thread.Reset();
3428 }
3429 
3430 bool
3431 NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
3432 {
3433     for (auto thread_sp : m_threads)
3434     {
3435         assert (thread_sp && "thread list should not contain NULL threads");
3436         if (thread_sp->GetID () == thread_id)
3437         {
3438             // We have this thread.
3439             return true;
3440         }
3441     }
3442 
3443     // We don't have this thread.
3444     return false;
3445 }
3446 
3447 NativeThreadProtocolSP
3448 NativeProcessLinux::MaybeGetThreadNoLock (lldb::tid_t thread_id)
3449 {
3450     // CONSIDER organize threads by map - we can do better than linear.
3451     for (auto thread_sp : m_threads)
3452     {
3453         if (thread_sp->GetID () == thread_id)
3454             return thread_sp;
3455     }
3456 
3457     // We don't have this thread.
3458     return NativeThreadProtocolSP ();
3459 }
3460 
3461 bool
3462 NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
3463 {
3464     Mutex::Locker locker (m_threads_mutex);
3465     for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
3466     {
3467         if (*it && ((*it)->GetID () == thread_id))
3468         {
3469             m_threads.erase (it);
3470             return true;
3471         }
3472     }
3473 
3474     // Didn't find it.
3475     return false;
3476 }
3477 
3478 NativeThreadProtocolSP
3479 NativeProcessLinux::AddThread (lldb::tid_t thread_id)
3480 {
3481     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3482 
3483     Mutex::Locker locker (m_threads_mutex);
3484 
3485     if (log)
3486     {
3487         log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
3488                 __FUNCTION__,
3489                 GetID (),
3490                 thread_id);
3491     }
3492 
3493     assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
3494 
3495     // If this is the first thread, save it as the current thread
3496     if (m_threads.empty ())
3497         SetCurrentThreadID (thread_id);
3498 
3499     NativeThreadProtocolSP thread_sp (new NativeThreadLinux (this, thread_id));
3500     m_threads.push_back (thread_sp);
3501 
3502     return thread_sp;
3503 }
3504 
3505 NativeThreadProtocolSP
3506 NativeProcessLinux::GetOrCreateThread (lldb::tid_t thread_id, bool &created)
3507 {
3508     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3509 
3510     Mutex::Locker locker (m_threads_mutex);
3511     if (log)
3512     {
3513         log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " get/create thread with tid %" PRIu64,
3514                      __FUNCTION__,
3515                      GetID (),
3516                      thread_id);
3517     }
3518 
3519     // Retrieve the thread if it is already getting tracked.
3520     NativeThreadProtocolSP thread_sp = MaybeGetThreadNoLock (thread_id);
3521     if (thread_sp)
3522     {
3523         if (log)
3524             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": thread already tracked, returning",
3525                          __FUNCTION__,
3526                          GetID (),
3527                          thread_id);
3528         created = false;
3529         return thread_sp;
3530 
3531     }
3532 
3533     // Create the thread metadata since it isn't being tracked.
3534     if (log)
3535         log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": thread didn't exist, tracking now",
3536                      __FUNCTION__,
3537                      GetID (),
3538                      thread_id);
3539 
3540     thread_sp.reset (new NativeThreadLinux (this, thread_id));
3541     m_threads.push_back (thread_sp);
3542     created = true;
3543 
3544     return thread_sp;
3545 }
3546 
3547 Error
3548 NativeProcessLinux::FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp)
3549 {
3550     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3551 
3552     Error error;
3553 
3554     // Get a linux thread pointer.
3555     if (!thread_sp)
3556     {
3557         error.SetErrorString ("null thread_sp");
3558         if (log)
3559             log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
3560         return error;
3561     }
3562     NativeThreadLinux *const linux_thread_p = reinterpret_cast<NativeThreadLinux*> (thread_sp.get());
3563 
3564     // Find out the size of a breakpoint (might depend on where we are in the code).
3565     NativeRegisterContextSP context_sp = linux_thread_p->GetRegisterContext ();
3566     if (!context_sp)
3567     {
3568         error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
3569         if (log)
3570             log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
3571         return error;
3572     }
3573 
3574     uint32_t breakpoint_size = 0;
3575     error = GetSoftwareBreakpointSize (context_sp, breakpoint_size);
3576     if (error.Fail ())
3577     {
3578         if (log)
3579             log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
3580         return error;
3581     }
3582     else
3583     {
3584         if (log)
3585             log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
3586     }
3587 
3588     // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
3589     const lldb::addr_t initial_pc_addr = context_sp->GetPC ();
3590     lldb::addr_t breakpoint_addr = initial_pc_addr;
3591     if (breakpoint_size > static_cast<lldb::addr_t> (0))
3592     {
3593         // Do not allow breakpoint probe to wrap around.
3594         if (breakpoint_addr >= static_cast<lldb::addr_t> (breakpoint_size))
3595             breakpoint_addr -= static_cast<lldb::addr_t> (breakpoint_size);
3596     }
3597 
3598     // Check if we stopped because of a breakpoint.
3599     NativeBreakpointSP breakpoint_sp;
3600     error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
3601     if (!error.Success () || !breakpoint_sp)
3602     {
3603         // We didn't find one at a software probe location.  Nothing to do.
3604         if (log)
3605             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
3606         return Error ();
3607     }
3608 
3609     // If the breakpoint is not a software breakpoint, nothing to do.
3610     if (!breakpoint_sp->IsSoftwareBreakpoint ())
3611     {
3612         if (log)
3613             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
3614         return Error ();
3615     }
3616 
3617     //
3618     // We have a software breakpoint and need to adjust the PC.
3619     //
3620 
3621     // Sanity check.
3622     if (breakpoint_size == 0)
3623     {
3624         // Nothing to do!  How did we get here?
3625         if (log)
3626             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);
3627         return Error ();
3628     }
3629 
3630     // Change the program counter.
3631     if (log)
3632         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);
3633 
3634     error = context_sp->SetPC (breakpoint_addr);
3635     if (error.Fail ())
3636     {
3637         if (log)
3638             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": failed to set PC: %s", __FUNCTION__, GetID (), linux_thread_p->GetID (), error.AsCString ());
3639         return error;
3640     }
3641 
3642     return error;
3643 }
3644