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