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