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