xref: /llvm-project/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp (revision 202ecd26da6abd5d1a90ddef26023fc1048859b7)
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::ProcessLaunchInfo::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 () == ProcessLaunchInfo::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             size_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::ProcessLaunchInfo::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         if ((info->si_pid == 0) && info->si_code == SI_USER)
2159         {
2160             // A new thread creation is being signaled.  This is one of two parts that come in
2161             // a non-deterministic order.  pid is the thread id.
2162             if (log)
2163                 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": new thread notification",
2164                          __FUNCTION__, GetID (), pid);
2165 
2166             // Did we already create the thread?
2167             bool already_tracked = false;
2168             thread_sp = GetOrCreateThread (pid, already_tracked);
2169             assert (thread_sp.get() && "failed to get or create the tracking data for newly created inferior thread");
2170 
2171             // If the thread was already tracked, it means the main thread already received its SIGTRAP for the create.
2172             if (already_tracked)
2173             {
2174                 // We can now resume this thread up since it is fully created.
2175                 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetRunning ();
2176                 Resume (thread_sp->GetID (), LLDB_INVALID_SIGNAL_NUMBER);
2177             }
2178             else
2179             {
2180                 // Mark the thread as currently launching.  Need to wait for SIGTRAP clone on the main thread before
2181                 // this thread is ready to go.
2182                 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetLaunching ();
2183             }
2184         }
2185         else if (info->si_pid == getpid () && (signo == SIGSTOP))
2186         {
2187             // This is a tgkill()-based stop.
2188             if (thread_sp)
2189             {
2190                 // An inferior thread just stopped.  Mark it as such.
2191                 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedBySignal (signo);
2192                 SetCurrentThreadID (thread_sp->GetID ());
2193 
2194                 // Remove this tid from the wait-for-stop set.
2195                 Mutex::Locker locker (m_wait_for_stop_tids_mutex);
2196 
2197                 auto removed_count = m_wait_for_stop_tids.erase (thread_sp->GetID ());
2198                 if (removed_count < 1)
2199                 {
2200                     log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": tgkill()-stopped thread not in m_wait_for_stop_tids",
2201                                  __FUNCTION__, GetID (), thread_sp->GetID ());
2202 
2203                 }
2204 
2205                 // If this is the last thread in the m_wait_for_stop_tids, we need to notify
2206                 // the delegate that a stop has occurred now that every thread that was supposed
2207                 // to stop has stopped.
2208                 if (m_wait_for_stop_tids.empty ())
2209                 {
2210                     if (log)
2211                     {
2212                         log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", setting process state to stopped now that all tids marked for stop have completed",
2213                                      __FUNCTION__,
2214                                      GetID (),
2215                                      pid);
2216                     }
2217                     SetState (StateType::eStateStopped, true);
2218                 }
2219             }
2220         }
2221         else
2222         {
2223             // Hmm, not sure what to do with this.
2224             if (log)
2225                 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " unsure how to handle SI_KILL or SI_USER signal", __FUNCTION__, GetID ());
2226         }
2227 
2228         return;
2229     }
2230 
2231     if (log)
2232         log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, GetUnixSignals ().GetSignalAsCString (signo));
2233 
2234     switch (signo)
2235     {
2236     case SIGSEGV:
2237         {
2238             lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
2239 
2240             // FIXME figure out how to propagate this properly.  Seems like it
2241             // should go in ThreadStopInfo.
2242             // We can get more details on the exact nature of the crash here.
2243             // ProcessMessage::CrashReason reason = GetCrashReasonForSIGSEGV(info);
2244             if (!exited)
2245             {
2246                 // This is just a pre-signal-delivery notification of the incoming signal.
2247                 // Send a stop to the debugger.
2248                 if (thread_sp)
2249                 {
2250                     reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedBySignal (signo);
2251                     SetCurrentThreadID (thread_sp->GetID ());
2252                 }
2253                 SetState (StateType::eStateStopped, true);
2254             }
2255             else
2256             {
2257                 if (thread_sp)
2258                 {
2259                     // FIXME figure out what type this is.
2260                     const uint64_t exception_type = static_cast<uint64_t> (SIGSEGV);
2261                     reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetCrashedWithException (exception_type, fault_addr);
2262                 }
2263                 SetState (StateType::eStateCrashed, true);
2264             }
2265         }
2266         break;
2267 
2268     case SIGILL:
2269         {
2270             // lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
2271             // Can get the reason from here.
2272             // ProcessMessage::CrashReason reason = GetCrashReasonForSIGILL(info);
2273             // FIXME save the crash reason
2274             SetState (StateType::eStateCrashed, true);
2275         }
2276         break;
2277 
2278     case SIGFPE:
2279         {
2280             // lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
2281             // Can get the crash reason from below.
2282             // ProcessMessage::CrashReason reason = GetCrashReasonForSIGFPE(info);
2283             // FIXME save the crash reason
2284             SetState (StateType::eStateCrashed, true);
2285         }
2286         break;
2287 
2288     case SIGBUS:
2289         {
2290             // lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
2291             // Can get the crash reason from below.
2292             // ProcessMessage::CrashReason reason = GetCrashReasonForSIGBUS(info);
2293             // FIXME save the crash reason
2294             SetState (StateType::eStateCrashed);
2295         }
2296         break;
2297 
2298     default:
2299         // FIXME Stop all threads here.
2300         break;
2301     }
2302 }
2303 
2304 Error
2305 NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
2306 {
2307     Error error;
2308 
2309     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
2310     if (log)
2311         log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
2312 
2313     int run_thread_count = 0;
2314     int stop_thread_count = 0;
2315     int step_thread_count = 0;
2316 
2317     std::vector<NativeThreadProtocolSP> new_stop_threads;
2318 
2319     Mutex::Locker locker (m_threads_mutex);
2320     for (auto thread_sp : m_threads)
2321     {
2322         assert (thread_sp && "thread list should not contain NULL threads");
2323         NativeThreadLinux *const linux_thread_p = reinterpret_cast<NativeThreadLinux*> (thread_sp.get ());
2324 
2325         const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
2326         assert (action && "NULL ResumeAction returned for thread during Resume ()");
2327 
2328         if (log)
2329         {
2330             log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
2331                     __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
2332         }
2333 
2334         switch (action->state)
2335         {
2336         case eStateRunning:
2337             // Run the thread, possibly feeding it the signal.
2338             linux_thread_p->SetRunning ();
2339             if (action->signal > 0)
2340             {
2341                 // Resume the thread and deliver the given signal,
2342                 // then mark as delivered.
2343                 Resume (thread_sp->GetID (), action->signal);
2344                 resume_actions.SetSignalHandledForThread (thread_sp->GetID ());
2345             }
2346             else
2347             {
2348                 // Just resume the thread with no signal.
2349                 Resume (thread_sp->GetID (), LLDB_INVALID_SIGNAL_NUMBER);
2350             }
2351             ++run_thread_count;
2352             break;
2353 
2354         case eStateStepping:
2355             // Note: if we have multiple threads, we may need to stop
2356             // the other threads first, then step this one.
2357             linux_thread_p->SetStepping ();
2358             if (SingleStep (thread_sp->GetID (), 0))
2359             {
2360                 if (log)
2361                     log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 " single step succeeded",
2362                                  __FUNCTION__, GetID (), thread_sp->GetID ());
2363             }
2364             else
2365             {
2366                 if (log)
2367                     log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 " single step failed",
2368                                  __FUNCTION__, GetID (), thread_sp->GetID ());
2369             }
2370             ++step_thread_count;
2371             break;
2372 
2373         case eStateSuspended:
2374         case eStateStopped:
2375             if (!StateIsStoppedState (linux_thread_p->GetState (), false))
2376                 new_stop_threads.push_back (thread_sp);
2377             else
2378             {
2379                 if (log)
2380                     log->Printf ("NativeProcessLinux::%s no need to stop pid %" PRIu64 " tid %" PRIu64 ", thread state already %s",
2381                                  __FUNCTION__, GetID (), thread_sp->GetID (), StateAsCString (linux_thread_p->GetState ()));
2382             }
2383 
2384             ++stop_thread_count;
2385             break;
2386 
2387         default:
2388             return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
2389                     __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
2390         }
2391     }
2392 
2393     // If any thread was set to run, notify the process state as running.
2394     if (run_thread_count > 0)
2395         SetState (StateType::eStateRunning, true);
2396 
2397     // Now do a tgkill SIGSTOP on each thread we want to stop.
2398     if (!new_stop_threads.empty ())
2399     {
2400         // Lock the m_wait_for_stop_tids set so we can fill it with every thread we expect to have stopped.
2401         Mutex::Locker stop_thread_id_locker (m_wait_for_stop_tids_mutex);
2402         for (auto thread_sp : new_stop_threads)
2403         {
2404             // Send a stop signal to the thread.
2405             const int result = tgkill (GetID (), thread_sp->GetID (), SIGSTOP);
2406             if (result != 0)
2407             {
2408                 // tgkill failed.
2409                 if (log)
2410                     log->Printf ("NativeProcessLinux::%s error: tgkill SIGSTOP for pid %" PRIu64 " tid %" PRIu64 "failed, retval %d",
2411                                  __FUNCTION__, GetID (), thread_sp->GetID (), result);
2412             }
2413             else
2414             {
2415                 // tgkill succeeded.  Don't mark the thread state, though.  Let the signal
2416                 // handling mark it.
2417                 if (log)
2418                     log->Printf ("NativeProcessLinux::%s tgkill SIGSTOP for pid %" PRIu64 " tid %" PRIu64 " succeeded",
2419                                  __FUNCTION__, GetID (), thread_sp->GetID ());
2420 
2421                 // Add it to the set of threads we expect to signal a stop.
2422                 // We won't tell the delegate about it until this list drains to empty.
2423                 m_wait_for_stop_tids.insert (thread_sp->GetID ());
2424             }
2425         }
2426     }
2427 
2428     return error;
2429 }
2430 
2431 Error
2432 NativeProcessLinux::Halt ()
2433 {
2434     Error error;
2435 
2436     // FIXME check if we're already stopped
2437     const bool is_stopped = false;
2438     if (is_stopped)
2439         return error;
2440 
2441     if (kill (GetID (), SIGSTOP) != 0)
2442         error.SetErrorToErrno ();
2443 
2444     return error;
2445 }
2446 
2447 Error
2448 NativeProcessLinux::Detach ()
2449 {
2450     Error error;
2451 
2452     // Tell ptrace to detach from the process.
2453     if (GetID () != LLDB_INVALID_PROCESS_ID)
2454         error = Detach (GetID ());
2455 
2456     // Stop monitoring the inferior.
2457     StopMonitor ();
2458 
2459     // No error.
2460     return error;
2461 }
2462 
2463 Error
2464 NativeProcessLinux::Signal (int signo)
2465 {
2466     Error error;
2467 
2468     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2469     if (log)
2470         log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
2471                 __FUNCTION__, signo,  GetUnixSignals ().GetSignalAsCString (signo), GetID ());
2472 
2473     if (kill(GetID(), signo))
2474         error.SetErrorToErrno();
2475 
2476     return error;
2477 }
2478 
2479 Error
2480 NativeProcessLinux::Kill ()
2481 {
2482     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2483     if (log)
2484         log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
2485 
2486     Error error;
2487 
2488     switch (m_state)
2489     {
2490         case StateType::eStateInvalid:
2491         case StateType::eStateExited:
2492         case StateType::eStateCrashed:
2493         case StateType::eStateDetached:
2494         case StateType::eStateUnloaded:
2495             // Nothing to do - the process is already dead.
2496             if (log)
2497                 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
2498             return error;
2499 
2500         case StateType::eStateConnected:
2501         case StateType::eStateAttaching:
2502         case StateType::eStateLaunching:
2503         case StateType::eStateStopped:
2504         case StateType::eStateRunning:
2505         case StateType::eStateStepping:
2506         case StateType::eStateSuspended:
2507             // We can try to kill a process in these states.
2508             break;
2509     }
2510 
2511     if (kill (GetID (), SIGKILL) != 0)
2512     {
2513         error.SetErrorToErrno ();
2514         return error;
2515     }
2516 
2517     return error;
2518 }
2519 
2520 static Error
2521 ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
2522 {
2523     memory_region_info.Clear();
2524 
2525     StringExtractor line_extractor (maps_line.c_str ());
2526 
2527     // Format: {address_start_hex}-{address_end_hex} perms offset  dev   inode   pathname
2528     // perms: rwxp   (letter is present if set, '-' if not, final character is p=private, s=shared).
2529 
2530     // Parse out the starting address
2531     lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
2532 
2533     // Parse out hyphen separating start and end address from range.
2534     if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
2535         return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
2536 
2537     // Parse out the ending address
2538     lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
2539 
2540     // Parse out the space after the address.
2541     if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
2542         return Error ("malformed /proc/{pid}/maps entry, missing space after range");
2543 
2544     // Save the range.
2545     memory_region_info.GetRange ().SetRangeBase (start_address);
2546     memory_region_info.GetRange ().SetRangeEnd (end_address);
2547 
2548     // Parse out each permission entry.
2549     if (line_extractor.GetBytesLeft () < 4)
2550         return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
2551 
2552     // Handle read permission.
2553     const char read_perm_char = line_extractor.GetChar ();
2554     if (read_perm_char == 'r')
2555         memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
2556     else
2557     {
2558         assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
2559         memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2560     }
2561 
2562     // Handle write permission.
2563     const char write_perm_char = line_extractor.GetChar ();
2564     if (write_perm_char == 'w')
2565         memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
2566     else
2567     {
2568         assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
2569         memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2570     }
2571 
2572     // Handle execute permission.
2573     const char exec_perm_char = line_extractor.GetChar ();
2574     if (exec_perm_char == 'x')
2575         memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
2576     else
2577     {
2578         assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
2579         memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2580     }
2581 
2582     return Error ();
2583 }
2584 
2585 Error
2586 NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
2587 {
2588     // FIXME review that the final memory region returned extends to the end of the virtual address space,
2589     // with no perms if it is not mapped.
2590 
2591     // Use an approach that reads memory regions from /proc/{pid}/maps.
2592     // Assume proc maps entries are in ascending order.
2593     // FIXME assert if we find differently.
2594     Mutex::Locker locker (m_mem_region_cache_mutex);
2595 
2596     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2597     Error error;
2598 
2599     if (m_supports_mem_region == LazyBool::eLazyBoolNo)
2600     {
2601         // We're done.
2602         error.SetErrorString ("unsupported");
2603         return error;
2604     }
2605 
2606     // If our cache is empty, pull the latest.  There should always be at least one memory region
2607     // if memory region handling is supported.
2608     if (m_mem_region_cache.empty ())
2609     {
2610         error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
2611              [&] (const std::string &line) -> bool
2612              {
2613                  MemoryRegionInfo info;
2614                  const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
2615                  if (parse_error.Success ())
2616                  {
2617                      m_mem_region_cache.push_back (info);
2618                      return true;
2619                  }
2620                  else
2621                  {
2622                      if (log)
2623                          log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
2624                      return false;
2625                  }
2626              });
2627 
2628         // If we had an error, we'll mark unsupported.
2629         if (error.Fail ())
2630         {
2631             m_supports_mem_region = LazyBool::eLazyBoolNo;
2632             return error;
2633         }
2634         else if (m_mem_region_cache.empty ())
2635         {
2636             // No entries after attempting to read them.  This shouldn't happen if /proc/{pid}/maps
2637             // is supported.  Assume we don't support map entries via procfs.
2638             if (log)
2639                 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
2640             m_supports_mem_region = LazyBool::eLazyBoolNo;
2641             error.SetErrorString ("not supported");
2642             return error;
2643         }
2644 
2645         if (log)
2646             log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ());
2647 
2648         // We support memory retrieval, remember that.
2649         m_supports_mem_region = LazyBool::eLazyBoolYes;
2650     }
2651     else
2652     {
2653         if (log)
2654             log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2655     }
2656 
2657     lldb::addr_t prev_base_address = 0;
2658 
2659     // FIXME start by finding the last region that is <= target address using binary search.  Data is sorted.
2660     // There can be a ton of regions on pthreads apps with lots of threads.
2661     for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
2662     {
2663         MemoryRegionInfo &proc_entry_info = *it;
2664 
2665         // Sanity check assumption that /proc/{pid}/maps entries are ascending.
2666         assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
2667         prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
2668 
2669         // If the target address comes before this entry, indicate distance to next region.
2670         if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
2671         {
2672             range_info.GetRange ().SetRangeBase (load_addr);
2673             range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
2674             range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2675             range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2676             range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2677 
2678             return error;
2679         }
2680         else if (proc_entry_info.GetRange ().Contains (load_addr))
2681         {
2682             // The target address is within the memory region we're processing here.
2683             range_info = proc_entry_info;
2684             return error;
2685         }
2686 
2687         // The target memory address comes somewhere after the region we just parsed.
2688     }
2689 
2690     // If we made it here, we didn't find an entry that contained the given address.
2691     error.SetErrorString ("address comes after final region");
2692 
2693     if (log)
2694         log->Printf ("NativeProcessLinux::%s failed to find map entry for address 0x%" PRIx64 ": %s", __FUNCTION__, load_addr, error.AsCString ());
2695 
2696     return error;
2697 }
2698 
2699 void
2700 NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
2701 {
2702     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2703     if (log)
2704         log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
2705 
2706     {
2707         Mutex::Locker locker (m_mem_region_cache_mutex);
2708         if (log)
2709             log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2710         m_mem_region_cache.clear ();
2711     }
2712 }
2713 
2714 Error
2715 NativeProcessLinux::AllocateMemory (
2716     lldb::addr_t size,
2717     uint32_t permissions,
2718     lldb::addr_t &addr)
2719 {
2720     // FIXME implementing this requires the equivalent of
2721     // InferiorCallPOSIX::InferiorCallMmap, which depends on
2722     // functional ThreadPlans working with Native*Protocol.
2723 #if 1
2724     return Error ("not implemented yet");
2725 #else
2726     addr = LLDB_INVALID_ADDRESS;
2727 
2728     unsigned prot = 0;
2729     if (permissions & lldb::ePermissionsReadable)
2730         prot |= eMmapProtRead;
2731     if (permissions & lldb::ePermissionsWritable)
2732         prot |= eMmapProtWrite;
2733     if (permissions & lldb::ePermissionsExecutable)
2734         prot |= eMmapProtExec;
2735 
2736     // TODO implement this directly in NativeProcessLinux
2737     // (and lift to NativeProcessPOSIX if/when that class is
2738     // refactored out).
2739     if (InferiorCallMmap(this, addr, 0, size, prot,
2740                          eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
2741         m_addr_to_mmap_size[addr] = size;
2742         return Error ();
2743     } else {
2744         addr = LLDB_INVALID_ADDRESS;
2745         return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
2746     }
2747 #endif
2748 }
2749 
2750 Error
2751 NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
2752 {
2753     // FIXME see comments in AllocateMemory - required lower-level
2754     // bits not in place yet (ThreadPlans)
2755     return Error ("not implemented");
2756 }
2757 
2758 lldb::addr_t
2759 NativeProcessLinux::GetSharedLibraryInfoAddress ()
2760 {
2761 #if 1
2762     // punt on this for now
2763     return LLDB_INVALID_ADDRESS;
2764 #else
2765     // Return the image info address for the exe module
2766 #if 1
2767     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2768 
2769     ModuleSP module_sp;
2770     Error error = GetExeModuleSP (module_sp);
2771     if (error.Fail ())
2772     {
2773          if (log)
2774             log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ());
2775         return LLDB_INVALID_ADDRESS;
2776     }
2777 
2778     if (module_sp == nullptr)
2779     {
2780          if (log)
2781             log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__);
2782          return LLDB_INVALID_ADDRESS;
2783     }
2784 
2785     ObjectFileSP object_file_sp = module_sp->GetObjectFile ();
2786     if (object_file_sp == nullptr)
2787     {
2788          if (log)
2789             log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__);
2790          return LLDB_INVALID_ADDRESS;
2791     }
2792 
2793     return obj_file_sp->GetImageInfoAddress();
2794 #else
2795     Target *target = &GetTarget();
2796     ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
2797     Address addr = obj_file->GetImageInfoAddress(target);
2798 
2799     if (addr.IsValid())
2800         return addr.GetLoadAddress(target);
2801     return LLDB_INVALID_ADDRESS;
2802 #endif
2803 #endif // punt on this for now
2804 }
2805 
2806 size_t
2807 NativeProcessLinux::UpdateThreads ()
2808 {
2809     // The NativeProcessLinux monitoring threads are always up to date
2810     // with respect to thread state and they keep the thread list
2811     // populated properly. All this method needs to do is return the
2812     // thread count.
2813     Mutex::Locker locker (m_threads_mutex);
2814     return m_threads.size ();
2815 }
2816 
2817 bool
2818 NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
2819 {
2820     arch = m_arch;
2821     return true;
2822 }
2823 
2824 Error
2825 NativeProcessLinux::GetSoftwareBreakpointSize (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size)
2826 {
2827     // FIXME put this behind a breakpoint protocol class that can be
2828     // set per architecture.  Need ARM, MIPS support here.
2829     static const uint8_t g_i386_opcode [] = { 0xCC };
2830 
2831     switch (m_arch.GetMachine ())
2832     {
2833         case llvm::Triple::x86:
2834         case llvm::Triple::x86_64:
2835             actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
2836             return Error ();
2837 
2838         default:
2839             assert(false && "CPU type not supported!");
2840             return Error ("CPU type not supported");
2841     }
2842 }
2843 
2844 Error
2845 NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
2846 {
2847     if (hardware)
2848         return Error ("NativeProcessLinux does not support hardware breakpoints");
2849     else
2850         return SetSoftwareBreakpoint (addr, size);
2851 }
2852 
2853 Error
2854 NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint, size_t &actual_opcode_size, const uint8_t *&trap_opcode_bytes)
2855 {
2856     // FIXME put this behind a breakpoint protocol class that can be
2857     // set per architecture.  Need ARM, MIPS support here.
2858     static const uint8_t g_i386_opcode [] = { 0xCC };
2859 
2860     switch (m_arch.GetMachine ())
2861     {
2862     case llvm::Triple::x86:
2863     case llvm::Triple::x86_64:
2864         trap_opcode_bytes = g_i386_opcode;
2865         actual_opcode_size = sizeof(g_i386_opcode);
2866         return Error ();
2867 
2868     default:
2869         assert(false && "CPU type not supported!");
2870         return Error ("CPU type not supported");
2871     }
2872 }
2873 
2874 #if 0
2875 ProcessMessage::CrashReason
2876 NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
2877 {
2878     ProcessMessage::CrashReason reason;
2879     assert(info->si_signo == SIGSEGV);
2880 
2881     reason = ProcessMessage::eInvalidCrashReason;
2882 
2883     switch (info->si_code)
2884     {
2885     default:
2886         assert(false && "unexpected si_code for SIGSEGV");
2887         break;
2888     case SI_KERNEL:
2889         // Linux will occasionally send spurious SI_KERNEL codes.
2890         // (this is poorly documented in sigaction)
2891         // One way to get this is via unaligned SIMD loads.
2892         reason = ProcessMessage::eInvalidAddress; // for lack of anything better
2893         break;
2894     case SEGV_MAPERR:
2895         reason = ProcessMessage::eInvalidAddress;
2896         break;
2897     case SEGV_ACCERR:
2898         reason = ProcessMessage::ePrivilegedAddress;
2899         break;
2900     }
2901 
2902     return reason;
2903 }
2904 #endif
2905 
2906 
2907 #if 0
2908 ProcessMessage::CrashReason
2909 NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
2910 {
2911     ProcessMessage::CrashReason reason;
2912     assert(info->si_signo == SIGILL);
2913 
2914     reason = ProcessMessage::eInvalidCrashReason;
2915 
2916     switch (info->si_code)
2917     {
2918     default:
2919         assert(false && "unexpected si_code for SIGILL");
2920         break;
2921     case ILL_ILLOPC:
2922         reason = ProcessMessage::eIllegalOpcode;
2923         break;
2924     case ILL_ILLOPN:
2925         reason = ProcessMessage::eIllegalOperand;
2926         break;
2927     case ILL_ILLADR:
2928         reason = ProcessMessage::eIllegalAddressingMode;
2929         break;
2930     case ILL_ILLTRP:
2931         reason = ProcessMessage::eIllegalTrap;
2932         break;
2933     case ILL_PRVOPC:
2934         reason = ProcessMessage::ePrivilegedOpcode;
2935         break;
2936     case ILL_PRVREG:
2937         reason = ProcessMessage::ePrivilegedRegister;
2938         break;
2939     case ILL_COPROC:
2940         reason = ProcessMessage::eCoprocessorError;
2941         break;
2942     case ILL_BADSTK:
2943         reason = ProcessMessage::eInternalStackError;
2944         break;
2945     }
2946 
2947     return reason;
2948 }
2949 #endif
2950 
2951 #if 0
2952 ProcessMessage::CrashReason
2953 NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
2954 {
2955     ProcessMessage::CrashReason reason;
2956     assert(info->si_signo == SIGFPE);
2957 
2958     reason = ProcessMessage::eInvalidCrashReason;
2959 
2960     switch (info->si_code)
2961     {
2962     default:
2963         assert(false && "unexpected si_code for SIGFPE");
2964         break;
2965     case FPE_INTDIV:
2966         reason = ProcessMessage::eIntegerDivideByZero;
2967         break;
2968     case FPE_INTOVF:
2969         reason = ProcessMessage::eIntegerOverflow;
2970         break;
2971     case FPE_FLTDIV:
2972         reason = ProcessMessage::eFloatDivideByZero;
2973         break;
2974     case FPE_FLTOVF:
2975         reason = ProcessMessage::eFloatOverflow;
2976         break;
2977     case FPE_FLTUND:
2978         reason = ProcessMessage::eFloatUnderflow;
2979         break;
2980     case FPE_FLTRES:
2981         reason = ProcessMessage::eFloatInexactResult;
2982         break;
2983     case FPE_FLTINV:
2984         reason = ProcessMessage::eFloatInvalidOperation;
2985         break;
2986     case FPE_FLTSUB:
2987         reason = ProcessMessage::eFloatSubscriptRange;
2988         break;
2989     }
2990 
2991     return reason;
2992 }
2993 #endif
2994 
2995 #if 0
2996 ProcessMessage::CrashReason
2997 NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
2998 {
2999     ProcessMessage::CrashReason reason;
3000     assert(info->si_signo == SIGBUS);
3001 
3002     reason = ProcessMessage::eInvalidCrashReason;
3003 
3004     switch (info->si_code)
3005     {
3006     default:
3007         assert(false && "unexpected si_code for SIGBUS");
3008         break;
3009     case BUS_ADRALN:
3010         reason = ProcessMessage::eIllegalAlignment;
3011         break;
3012     case BUS_ADRERR:
3013         reason = ProcessMessage::eIllegalAddress;
3014         break;
3015     case BUS_OBJERR:
3016         reason = ProcessMessage::eHardwareError;
3017         break;
3018     }
3019 
3020     return reason;
3021 }
3022 #endif
3023 
3024 void
3025 NativeProcessLinux::ServeOperation(OperationArgs *args)
3026 {
3027     NativeProcessLinux *monitor = args->m_monitor;
3028 
3029     // We are finised with the arguments and are ready to go.  Sync with the
3030     // parent thread and start serving operations on the inferior.
3031     sem_post(&args->m_semaphore);
3032 
3033     for(;;)
3034     {
3035         // wait for next pending operation
3036         if (sem_wait(&monitor->m_operation_pending))
3037         {
3038             if (errno == EINTR)
3039                 continue;
3040             assert(false && "Unexpected errno from sem_wait");
3041         }
3042 
3043         reinterpret_cast<Operation*>(monitor->m_operation)->Execute(monitor);
3044 
3045         // notify calling thread that operation is complete
3046         sem_post(&monitor->m_operation_done);
3047     }
3048 }
3049 
3050 void
3051 NativeProcessLinux::DoOperation(void *op)
3052 {
3053     Mutex::Locker lock(m_operation_mutex);
3054 
3055     m_operation = op;
3056 
3057     // notify operation thread that an operation is ready to be processed
3058     sem_post(&m_operation_pending);
3059 
3060     // wait for operation to complete
3061     while (sem_wait(&m_operation_done))
3062     {
3063         if (errno == EINTR)
3064             continue;
3065         assert(false && "Unexpected errno from sem_wait");
3066     }
3067 }
3068 
3069 Error
3070 NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, lldb::addr_t size, lldb::addr_t &bytes_read)
3071 {
3072     ReadOperation op(addr, buf, size, bytes_read);
3073     DoOperation(&op);
3074     return op.GetError ();
3075 }
3076 
3077 Error
3078 NativeProcessLinux::WriteMemory (lldb::addr_t addr, const void *buf, lldb::addr_t size, lldb::addr_t &bytes_written)
3079 {
3080     WriteOperation op(addr, buf, size, bytes_written);
3081     DoOperation(&op);
3082     return op.GetError ();
3083 }
3084 
3085 bool
3086 NativeProcessLinux::ReadRegisterValue(lldb::tid_t tid, uint32_t offset, const char* reg_name,
3087                                   uint32_t size, RegisterValue &value)
3088 {
3089     bool result;
3090     ReadRegOperation op(tid, offset, reg_name, value, result);
3091     DoOperation(&op);
3092     return result;
3093 }
3094 
3095 bool
3096 NativeProcessLinux::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
3097                                    const char* reg_name, const RegisterValue &value)
3098 {
3099     bool result;
3100     WriteRegOperation op(tid, offset, reg_name, value, result);
3101     DoOperation(&op);
3102     return result;
3103 }
3104 
3105 bool
3106 NativeProcessLinux::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3107 {
3108     bool result;
3109     ReadGPROperation op(tid, buf, buf_size, result);
3110     DoOperation(&op);
3111     return result;
3112 }
3113 
3114 bool
3115 NativeProcessLinux::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3116 {
3117     bool result;
3118     ReadFPROperation op(tid, buf, buf_size, result);
3119     DoOperation(&op);
3120     return result;
3121 }
3122 
3123 bool
3124 NativeProcessLinux::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3125 {
3126     bool result;
3127     ReadRegisterSetOperation op(tid, buf, buf_size, regset, result);
3128     DoOperation(&op);
3129     return result;
3130 }
3131 
3132 bool
3133 NativeProcessLinux::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3134 {
3135     bool result;
3136     WriteGPROperation op(tid, buf, buf_size, result);
3137     DoOperation(&op);
3138     return result;
3139 }
3140 
3141 bool
3142 NativeProcessLinux::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3143 {
3144     bool result;
3145     WriteFPROperation op(tid, buf, buf_size, result);
3146     DoOperation(&op);
3147     return result;
3148 }
3149 
3150 bool
3151 NativeProcessLinux::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3152 {
3153     bool result;
3154     WriteRegisterSetOperation op(tid, buf, buf_size, regset, result);
3155     DoOperation(&op);
3156     return result;
3157 }
3158 
3159 bool
3160 NativeProcessLinux::Resume (lldb::tid_t tid, uint32_t signo)
3161 {
3162     bool result;
3163     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3164 
3165     if (log)
3166         log->Printf ("NativeProcessLinux::%s() resuming thread = %"  PRIu64 " with signal %s", __FUNCTION__, tid,
3167                                  GetUnixSignals().GetSignalAsCString (signo));
3168     ResumeOperation op (tid, signo, result);
3169     DoOperation (&op);
3170     if (log)
3171         log->Printf ("NativeProcessLinux::%s() resuming result = %s", __FUNCTION__, result ? "true" : "false");
3172     return result;
3173 }
3174 
3175 bool
3176 NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo)
3177 {
3178     bool result;
3179     SingleStepOperation op(tid, signo, result);
3180     DoOperation(&op);
3181     return result;
3182 }
3183 
3184 bool
3185 NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo, int &ptrace_err)
3186 {
3187     bool result;
3188     SiginfoOperation op(tid, siginfo, result, ptrace_err);
3189     DoOperation(&op);
3190     return result;
3191 }
3192 
3193 bool
3194 NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
3195 {
3196     bool result;
3197     EventMessageOperation op(tid, message, result);
3198     DoOperation(&op);
3199     return result;
3200 }
3201 
3202 lldb_private::Error
3203 NativeProcessLinux::Detach(lldb::tid_t tid)
3204 {
3205     lldb_private::Error error;
3206     if (tid != LLDB_INVALID_THREAD_ID)
3207     {
3208         DetachOperation op(tid, error);
3209         DoOperation(&op);
3210     }
3211     return error;
3212 }
3213 
3214 bool
3215 NativeProcessLinux::DupDescriptor(const char *path, int fd, int flags)
3216 {
3217     int target_fd = open(path, flags, 0666);
3218 
3219     if (target_fd == -1)
3220         return false;
3221 
3222     return (dup2(target_fd, fd) == -1) ? false : true;
3223 }
3224 
3225 void
3226 NativeProcessLinux::StopMonitoringChildProcess()
3227 {
3228     lldb::thread_result_t thread_result;
3229 
3230     if (IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
3231     {
3232         Host::ThreadCancel(m_monitor_thread, NULL);
3233         Host::ThreadJoin(m_monitor_thread, &thread_result, NULL);
3234         m_monitor_thread = LLDB_INVALID_HOST_THREAD;
3235     }
3236 }
3237 
3238 void
3239 NativeProcessLinux::StopMonitor()
3240 {
3241     StopMonitoringChildProcess();
3242     StopOpThread();
3243     sem_destroy(&m_operation_pending);
3244     sem_destroy(&m_operation_done);
3245 
3246     // TODO: validate whether this still holds, fix up comment.
3247     // Note: ProcessPOSIX passes the m_terminal_fd file descriptor to
3248     // Process::SetSTDIOFileDescriptor, which in turn transfers ownership of
3249     // the descriptor to a ConnectionFileDescriptor object.  Consequently
3250     // even though still has the file descriptor, we shouldn't close it here.
3251 }
3252 
3253 void
3254 NativeProcessLinux::StopOpThread()
3255 {
3256     lldb::thread_result_t result;
3257 
3258     if (!IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
3259         return;
3260 
3261     Host::ThreadCancel(m_operation_thread, NULL);
3262     Host::ThreadJoin(m_operation_thread, &result, NULL);
3263     m_operation_thread = LLDB_INVALID_HOST_THREAD;
3264 }
3265 
3266 bool
3267 NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
3268 {
3269     for (auto thread_sp : m_threads)
3270     {
3271         assert (thread_sp && "thread list should not contain NULL threads");
3272         if (thread_sp->GetID () == thread_id)
3273         {
3274             // We have this thread.
3275             return true;
3276         }
3277     }
3278 
3279     // We don't have this thread.
3280     return false;
3281 }
3282 
3283 NativeThreadProtocolSP
3284 NativeProcessLinux::MaybeGetThreadNoLock (lldb::tid_t thread_id)
3285 {
3286     // CONSIDER organize threads by map - we can do better than linear.
3287     for (auto thread_sp : m_threads)
3288     {
3289         if (thread_sp->GetID () == thread_id)
3290             return thread_sp;
3291     }
3292 
3293     // We don't have this thread.
3294     return NativeThreadProtocolSP ();
3295 }
3296 
3297 bool
3298 NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
3299 {
3300     Mutex::Locker locker (m_threads_mutex);
3301     for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
3302     {
3303         if (*it && ((*it)->GetID () == thread_id))
3304         {
3305             m_threads.erase (it);
3306             return true;
3307         }
3308     }
3309 
3310     // Didn't find it.
3311     return false;
3312 }
3313 
3314 NativeThreadProtocolSP
3315 NativeProcessLinux::AddThread (lldb::tid_t thread_id)
3316 {
3317     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3318 
3319     Mutex::Locker locker (m_threads_mutex);
3320 
3321     if (log)
3322     {
3323         log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
3324                 __FUNCTION__,
3325                 GetID (),
3326                 thread_id);
3327     }
3328 
3329     assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
3330 
3331     // If this is the first thread, save it as the current thread
3332     if (m_threads.empty ())
3333         SetCurrentThreadID (thread_id);
3334 
3335     NativeThreadProtocolSP thread_sp (new NativeThreadLinux (this, thread_id));
3336     m_threads.push_back (thread_sp);
3337 
3338     return thread_sp;
3339 }
3340 
3341 NativeThreadProtocolSP
3342 NativeProcessLinux::GetOrCreateThread (lldb::tid_t thread_id, bool &created)
3343 {
3344     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3345 
3346     Mutex::Locker locker (m_threads_mutex);
3347     if (log)
3348     {
3349         log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " get/create thread with tid %" PRIu64,
3350                      __FUNCTION__,
3351                      GetID (),
3352                      thread_id);
3353     }
3354 
3355     // Retrieve the thread if it is already getting tracked.
3356     NativeThreadProtocolSP thread_sp = MaybeGetThreadNoLock (thread_id);
3357     if (thread_sp)
3358     {
3359         if (log)
3360             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": thread already tracked, returning",
3361                          __FUNCTION__,
3362                          GetID (),
3363                          thread_id);
3364         created = false;
3365         return thread_sp;
3366 
3367     }
3368 
3369     // Create the thread metadata since it isn't being tracked.
3370     if (log)
3371         log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": thread didn't exist, tracking now",
3372                      __FUNCTION__,
3373                      GetID (),
3374                      thread_id);
3375 
3376     thread_sp.reset (new NativeThreadLinux (this, thread_id));
3377     m_threads.push_back (thread_sp);
3378     created = true;
3379 
3380     return thread_sp;
3381 }
3382 
3383 Error
3384 NativeProcessLinux::FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp)
3385 {
3386     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
3387 
3388     Error error;
3389 
3390     // Get a linux thread pointer.
3391     if (!thread_sp)
3392     {
3393         error.SetErrorString ("null thread_sp");
3394         if (log)
3395             log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
3396         return error;
3397     }
3398     NativeThreadLinux *const linux_thread_p = reinterpret_cast<NativeThreadLinux*> (thread_sp.get());
3399 
3400     // Find out the size of a breakpoint (might depend on where we are in the code).
3401     NativeRegisterContextSP context_sp = linux_thread_p->GetRegisterContext ();
3402     if (!context_sp)
3403     {
3404         error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
3405         if (log)
3406             log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
3407         return error;
3408     }
3409 
3410     uint32_t breakpoint_size = 0;
3411     error = GetSoftwareBreakpointSize (context_sp, breakpoint_size);
3412     if (error.Fail ())
3413     {
3414         if (log)
3415             log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
3416         return error;
3417     }
3418     else
3419     {
3420         if (log)
3421             log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
3422     }
3423 
3424     // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
3425     const lldb::addr_t initial_pc_addr = context_sp->GetPC ();
3426     lldb::addr_t breakpoint_addr = initial_pc_addr;
3427     if (breakpoint_size > static_cast<lldb::addr_t> (0))
3428     {
3429         // Do not allow breakpoint probe to wrap around.
3430         if (breakpoint_addr >= static_cast<lldb::addr_t> (breakpoint_size))
3431             breakpoint_addr -= static_cast<lldb::addr_t> (breakpoint_size);
3432     }
3433 
3434     // Check if we stopped because of a breakpoint.
3435     NativeBreakpointSP breakpoint_sp;
3436     error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
3437     if (!error.Success () || !breakpoint_sp)
3438     {
3439         // We didn't find one at a software probe location.  Nothing to do.
3440         if (log)
3441             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
3442         return Error ();
3443     }
3444 
3445     // If the breakpoint is not a software breakpoint, nothing to do.
3446     if (!breakpoint_sp->IsSoftwareBreakpoint ())
3447     {
3448         if (log)
3449             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
3450         return Error ();
3451     }
3452 
3453     //
3454     // We have a software breakpoint and need to adjust the PC.
3455     //
3456 
3457     // Sanity check.
3458     if (breakpoint_size == 0)
3459     {
3460         // Nothing to do!  How did we get here?
3461         if (log)
3462             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);
3463         return Error ();
3464     }
3465 
3466     // Change the program counter.
3467     if (log)
3468         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);
3469 
3470     error = context_sp->SetPC (breakpoint_addr);
3471     if (error.Fail ())
3472     {
3473         if (log)
3474             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": failed to set PC: %s", __FUNCTION__, GetID (), linux_thread_p->GetID (), error.AsCString ());
3475         return error;
3476     }
3477 
3478     return error;
3479 }
3480