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