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