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