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