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