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