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