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