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