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