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