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