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