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