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