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