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