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