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