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