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       m_intel_pt_manager(pid) {
291   if (m_terminal_fd != -1) {
292     Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
293     assert(status.Success());
294   }
295 
296   Status status;
297   m_sigchld_handle = mainloop.RegisterSignal(
298       SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status);
299   assert(m_sigchld_handle && status.Success());
300 
301   for (const auto &tid : tids) {
302     NativeThreadLinux &thread = AddThread(tid, /*resume*/ false);
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, /*resume*/ true);
448     ThreadWasCreated(thread);
449     return;
450   }
451 
452   // Get details on the signal raised.
453   if (info_err.Success()) {
454     // We have retrieved the signal info.  Dispatch appropriately.
455     if (info.si_signo == SIGTRAP)
456       MonitorSIGTRAP(info, *thread_sp);
457     else
458       MonitorSignal(info, *thread_sp, exited);
459   } else {
460     if (info_err.GetError() == EINVAL) {
461       // This is a group stop reception for this tid. We can reach here if we
462       // reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the tracee,
463       // triggering the group-stop mechanism. Normally receiving these would
464       // stop the process, pending a SIGCONT. Simulating this state in a
465       // debugger is hard and is generally not needed (one use case is
466       // debugging background task being managed by a shell). For general use,
467       // it is sufficient to stop the process in a signal-delivery stop which
468       // happens before the group stop. This done by MonitorSignal and works
469       // correctly for all signals.
470       LLDB_LOG(log,
471                "received a group stop for pid {0} tid {1}. Transparent "
472                "handling of group stops not supported, resuming the "
473                "thread.",
474                GetID(), pid);
475       ResumeThread(*thread_sp, thread_sp->GetState(),
476                    LLDB_INVALID_SIGNAL_NUMBER);
477     } else {
478       // ptrace(GETSIGINFO) failed (but not due to group-stop).
479 
480       // A return value of ESRCH means the thread/process is no longer on the
481       // system, so it was killed somehow outside of our control.  Either way,
482       // we can't do anything with it anymore.
483 
484       // Stop tracking the metadata for the thread since it's entirely off the
485       // system now.
486       const bool thread_found = StopTrackingThread(pid);
487 
488       LLDB_LOG(log,
489                "GetSignalInfo failed: {0}, tid = {1}, status = {2}, "
490                "status = {3}, main_thread = {4}, thread_found: {5}",
491                info_err, pid, status, status, is_main_thread, thread_found);
492 
493       if (is_main_thread) {
494         // Notify the delegate - our process is not available but appears to
495         // have been killed outside our control.  Is eStateExited the right
496         // exit state in this case?
497         SetExitStatus(status, true);
498         SetState(StateType::eStateExited, true);
499       } else {
500         // This thread was pulled out from underneath us.  Anything to do here?
501         // Do we want to do an all stop?
502         LLDB_LOG(log,
503                  "pid {0} tid {1} non-main thread exit occurred, didn't "
504                  "tell delegate anything since thread disappeared out "
505                  "from underneath us",
506                  GetID(), pid);
507       }
508     }
509   }
510 }
511 
512 void NativeProcessLinux::WaitForNewThread(::pid_t tid) {
513   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
514 
515   if (GetThreadByID(tid)) {
516     // We are already tracking the thread - we got the event on the new thread
517     // (see MonitorSignal) before this one. We are done.
518     return;
519   }
520 
521   // The thread is not tracked yet, let's wait for it to appear.
522   int status = -1;
523   LLDB_LOG(log,
524            "received thread creation event for tid {0}. tid not tracked "
525            "yet, waiting for thread to appear...",
526            tid);
527   ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, &status, __WALL);
528   // Since we are waiting on a specific tid, this must be the creation event.
529   // But let's do some checks just in case.
530   if (wait_pid != tid) {
531     LLDB_LOG(log,
532              "waiting for tid {0} failed. Assuming the thread has "
533              "disappeared in the meantime",
534              tid);
535     // The only way I know of this could happen is if the whole process was
536     // SIGKILLed in the mean time. In any case, we can't do anything about that
537     // now.
538     return;
539   }
540   if (WIFEXITED(status)) {
541     LLDB_LOG(log,
542              "waiting for tid {0} returned an 'exited' event. Not "
543              "tracking the thread.",
544              tid);
545     // Also a very improbable event.
546     return;
547   }
548 
549   LLDB_LOG(log, "pid = {0}: tracking new thread tid {1}", GetID(), tid);
550   NativeThreadLinux &new_thread = AddThread(tid, /*resume*/ true);
551 
552   ThreadWasCreated(new_thread);
553 }
554 
555 void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info,
556                                         NativeThreadLinux &thread) {
557   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
558   const bool is_main_thread = (thread.GetID() == GetID());
559 
560   assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
561 
562   switch (info.si_code) {
563   // TODO: these two cases are required if we want to support tracing of the
564   // inferiors' children.  We'd need this to debug a monitor. case (SIGTRAP |
565   // (PTRACE_EVENT_FORK << 8)): case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
566 
567   case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): {
568     // This is the notification on the parent thread which informs us of new
569     // thread creation. We don't want to do anything with the parent thread so
570     // we just resume it. In case we want to implement "break on thread
571     // creation" functionality, we would need to stop here.
572 
573     unsigned long event_message = 0;
574     if (GetEventMessage(thread.GetID(), &event_message).Fail()) {
575       LLDB_LOG(log,
576                "pid {0} received thread creation event but "
577                "GetEventMessage failed so we don't know the new tid",
578                thread.GetID());
579     } else
580       WaitForNewThread(event_message);
581 
582     ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
583     break;
584   }
585 
586   case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): {
587     LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP);
588 
589     // Exec clears any pending notifications.
590     m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
591 
592     // Remove all but the main thread here.  Linux fork creates a new process
593     // which only copies the main thread.
594     LLDB_LOG(log, "exec received, stop tracking all but main thread");
595 
596     llvm::erase_if(m_threads, [&](std::unique_ptr<NativeThreadProtocol> &t) {
597       return t->GetID() != GetID();
598     });
599     assert(m_threads.size() == 1);
600     auto *main_thread = static_cast<NativeThreadLinux *>(m_threads[0].get());
601 
602     SetCurrentThreadID(main_thread->GetID());
603     main_thread->SetStoppedByExec();
604 
605     // Tell coordinator about about the "new" (since exec) stopped main thread.
606     ThreadWasCreated(*main_thread);
607 
608     // Let our delegate know we have just exec'd.
609     NotifyDidExec();
610 
611     // Let the process know we're stopped.
612     StopRunningThreads(main_thread->GetID());
613 
614     break;
615   }
616 
617   case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): {
618     // The inferior process or one of its threads is about to exit. We don't
619     // want to do anything with the thread so we just resume it. In case we
620     // want to implement "break on thread exit" functionality, we would need to
621     // stop here.
622 
623     unsigned long data = 0;
624     if (GetEventMessage(thread.GetID(), &data).Fail())
625       data = -1;
626 
627     LLDB_LOG(log,
628              "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
629              "WIFSIGNALED={2}, pid = {3}, main_thread = {4}",
630              data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(),
631              is_main_thread);
632 
633 
634     StateType state = thread.GetState();
635     if (!StateIsRunningState(state)) {
636       // Due to a kernel bug, we may sometimes get this stop after the inferior
637       // gets a SIGKILL. This confuses our state tracking logic in
638       // ResumeThread(), since normally, we should not be receiving any ptrace
639       // events while the inferior is stopped. This makes sure that the
640       // inferior is resumed and exits normally.
641       state = eStateRunning;
642     }
643     ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
644 
645     break;
646   }
647 
648   case 0:
649   case TRAP_TRACE:  // We receive this on single stepping.
650   case TRAP_HWBKPT: // We receive this on watchpoint hit
651   {
652     // If a watchpoint was hit, report it
653     uint32_t wp_index;
654     Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
655         wp_index, (uintptr_t)info.si_addr);
656     if (error.Fail())
657       LLDB_LOG(log,
658                "received error while checking for watchpoint hits, pid = "
659                "{0}, error = {1}",
660                thread.GetID(), error);
661     if (wp_index != LLDB_INVALID_INDEX32) {
662       MonitorWatchpoint(thread, wp_index);
663       break;
664     }
665 
666     // If a breakpoint was hit, report it
667     uint32_t bp_index;
668     error = thread.GetRegisterContext().GetHardwareBreakHitIndex(
669         bp_index, (uintptr_t)info.si_addr);
670     if (error.Fail())
671       LLDB_LOG(log, "received error while checking for hardware "
672                     "breakpoint hits, pid = {0}, error = {1}",
673                thread.GetID(), error);
674     if (bp_index != LLDB_INVALID_INDEX32) {
675       MonitorBreakpoint(thread);
676       break;
677     }
678 
679     // Otherwise, report step over
680     MonitorTrace(thread);
681     break;
682   }
683 
684   case SI_KERNEL:
685 #if defined __mips__
686     // For mips there is no special signal for watchpoint So we check for
687     // watchpoint in kernel trap
688     {
689       // If a watchpoint was hit, report it
690       uint32_t wp_index;
691       Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
692           wp_index, LLDB_INVALID_ADDRESS);
693       if (error.Fail())
694         LLDB_LOG(log,
695                  "received error while checking for watchpoint hits, pid = "
696                  "{0}, error = {1}",
697                  thread.GetID(), error);
698       if (wp_index != LLDB_INVALID_INDEX32) {
699         MonitorWatchpoint(thread, wp_index);
700         break;
701       }
702     }
703 // NO BREAK
704 #endif
705   case TRAP_BRKPT:
706     MonitorBreakpoint(thread);
707     break;
708 
709   case SIGTRAP:
710   case (SIGTRAP | 0x80):
711     LLDB_LOG(
712         log,
713         "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",
714         info.si_code, GetID(), thread.GetID());
715 
716     // Ignore these signals until we know more about them.
717     ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
718     break;
719 
720   default:
721     LLDB_LOG(log, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}",
722              info.si_code, GetID(), thread.GetID());
723     MonitorSignal(info, thread, false);
724     break;
725   }
726 }
727 
728 void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) {
729   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
730   LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID());
731 
732   // This thread is currently stopped.
733   thread.SetStoppedByTrace();
734 
735   StopRunningThreads(thread.GetID());
736 }
737 
738 void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) {
739   Log *log(
740       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
741   LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID());
742 
743   // Mark the thread as stopped at breakpoint.
744   thread.SetStoppedByBreakpoint();
745   FixupBreakpointPCAsNeeded(thread);
746 
747   if (m_threads_stepping_with_breakpoint.find(thread.GetID()) !=
748       m_threads_stepping_with_breakpoint.end())
749     thread.SetStoppedByTrace();
750 
751   StopRunningThreads(thread.GetID());
752 }
753 
754 void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread,
755                                            uint32_t wp_index) {
756   Log *log(
757       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
758   LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}",
759            thread.GetID(), wp_index);
760 
761   // Mark the thread as stopped at watchpoint. The address is at
762   // (lldb::addr_t)info->si_addr if we need it.
763   thread.SetStoppedByWatchpoint(wp_index);
764 
765   // We need to tell all other running threads before we notify the delegate
766   // about this stop.
767   StopRunningThreads(thread.GetID());
768 }
769 
770 void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
771                                        NativeThreadLinux &thread, bool exited) {
772   const int signo = info.si_signo;
773   const bool is_from_llgs = info.si_pid == getpid();
774 
775   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
776 
777   // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
778   // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a kill(2)
779   // or raise(3).  Similarly for tgkill(2) on Linux.
780   //
781   // IOW, user generated signals never generate what we consider to be a
782   // "crash".
783   //
784   // Similarly, ACK signals generated by this monitor.
785 
786   // Handle the signal.
787   LLDB_LOG(log,
788            "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
789            "waitpid pid = {4})",
790            Host::GetSignalAsCString(signo), signo, info.si_code,
791            thread.GetID());
792 
793   // Check for thread stop notification.
794   if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) {
795     // This is a tgkill()-based stop.
796     LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID());
797 
798     // Check that we're not already marked with a stop reason. Note this thread
799     // really shouldn't already be marked as stopped - if we were, that would
800     // imply that the kernel signaled us with the thread stopping which we
801     // handled and marked as stopped, and that, without an intervening resume,
802     // we received another stop.  It is more likely that we are missing the
803     // marking of a run state somewhere if we find that the thread was marked
804     // as stopped.
805     const StateType thread_state = thread.GetState();
806     if (!StateIsStoppedState(thread_state, false)) {
807       // An inferior thread has stopped because of a SIGSTOP we have sent it.
808       // Generally, these are not important stops and we don't want to report
809       // them as they are just used to stop other threads when one thread (the
810       // one with the *real* stop reason) hits a breakpoint (watchpoint,
811       // etc...). However, in the case of an asynchronous Interrupt(), this
812       // *is* the real stop reason, so we leave the signal intact if this is
813       // the thread that was chosen as the triggering thread.
814       if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
815         if (m_pending_notification_tid == thread.GetID())
816           thread.SetStoppedBySignal(SIGSTOP, &info);
817         else
818           thread.SetStoppedWithNoReason();
819 
820         SetCurrentThreadID(thread.GetID());
821         SignalIfAllThreadsStopped();
822       } else {
823         // We can end up here if stop was initiated by LLGS but by this time a
824         // thread stop has occurred - maybe initiated by another event.
825         Status error = ResumeThread(thread, thread.GetState(), 0);
826         if (error.Fail())
827           LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(),
828                    error);
829       }
830     } else {
831       LLDB_LOG(log,
832                "pid {0} tid {1}, thread was already marked as a stopped "
833                "state (state={2}), leaving stop signal as is",
834                GetID(), thread.GetID(), thread_state);
835       SignalIfAllThreadsStopped();
836     }
837 
838     // Done handling.
839     return;
840   }
841 
842   // Check if debugger should stop at this signal or just ignore it and resume
843   // the inferior.
844   if (m_signals_to_ignore.find(signo) != m_signals_to_ignore.end()) {
845      ResumeThread(thread, thread.GetState(), signo);
846      return;
847   }
848 
849   // This thread is stopped.
850   LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo));
851   thread.SetStoppedBySignal(signo, &info);
852 
853   // Send a stop to the debugger after we get all other threads to stop.
854   StopRunningThreads(thread.GetID());
855 }
856 
857 bool NativeProcessLinux::SupportHardwareSingleStepping() const {
858   if (m_arch.GetMachine() == llvm::Triple::arm || m_arch.IsMIPS())
859     return false;
860   return true;
861 }
862 
863 Status NativeProcessLinux::Resume(const ResumeActionList &resume_actions) {
864   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
865   LLDB_LOG(log, "pid {0}", GetID());
866 
867   bool software_single_step = !SupportHardwareSingleStepping();
868 
869   if (software_single_step) {
870     for (const auto &thread : m_threads) {
871       assert(thread && "thread list should not contain NULL threads");
872 
873       const ResumeAction *const action =
874           resume_actions.GetActionForThread(thread->GetID(), true);
875       if (action == nullptr)
876         continue;
877 
878       if (action->state == eStateStepping) {
879         Status error = SetupSoftwareSingleStepping(
880             static_cast<NativeThreadLinux &>(*thread));
881         if (error.Fail())
882           return error;
883       }
884     }
885   }
886 
887   for (const auto &thread : m_threads) {
888     assert(thread && "thread list should not contain NULL threads");
889 
890     const ResumeAction *const action =
891         resume_actions.GetActionForThread(thread->GetID(), true);
892 
893     if (action == nullptr) {
894       LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
895                thread->GetID());
896       continue;
897     }
898 
899     LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}",
900              action->state, GetID(), thread->GetID());
901 
902     switch (action->state) {
903     case eStateRunning:
904     case eStateStepping: {
905       // Run the thread, possibly feeding it the signal.
906       const int signo = action->signal;
907       ResumeThread(static_cast<NativeThreadLinux &>(*thread), action->state,
908                    signo);
909       break;
910     }
911 
912     case eStateSuspended:
913     case eStateStopped:
914       llvm_unreachable("Unexpected state");
915 
916     default:
917       return Status("NativeProcessLinux::%s (): unexpected state %s specified "
918                     "for pid %" PRIu64 ", tid %" PRIu64,
919                     __FUNCTION__, StateAsCString(action->state), GetID(),
920                     thread->GetID());
921     }
922   }
923 
924   return Status();
925 }
926 
927 Status NativeProcessLinux::Halt() {
928   Status error;
929 
930   if (kill(GetID(), SIGSTOP) != 0)
931     error.SetErrorToErrno();
932 
933   return error;
934 }
935 
936 Status NativeProcessLinux::Detach() {
937   Status error;
938 
939   // Stop monitoring the inferior.
940   m_sigchld_handle.reset();
941 
942   // Tell ptrace to detach from the process.
943   if (GetID() == LLDB_INVALID_PROCESS_ID)
944     return error;
945 
946   for (const auto &thread : m_threads) {
947     Status e = Detach(thread->GetID());
948     if (e.Fail())
949       error =
950           e; // Save the error, but still attempt to detach from other threads.
951   }
952 
953   m_intel_pt_manager.Clear();
954 
955   return error;
956 }
957 
958 Status NativeProcessLinux::Signal(int signo) {
959   Status error;
960 
961   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
962   LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo,
963            Host::GetSignalAsCString(signo), GetID());
964 
965   if (kill(GetID(), signo))
966     error.SetErrorToErrno();
967 
968   return error;
969 }
970 
971 Status NativeProcessLinux::Interrupt() {
972   // Pick a running thread (or if none, a not-dead stopped thread) as the
973   // chosen thread that will be the stop-reason thread.
974   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
975 
976   NativeThreadProtocol *running_thread = nullptr;
977   NativeThreadProtocol *stopped_thread = nullptr;
978 
979   LLDB_LOG(log, "selecting running thread for interrupt target");
980   for (const auto &thread : m_threads) {
981     // If we have a running or stepping thread, we'll call that the target of
982     // the interrupt.
983     const auto thread_state = thread->GetState();
984     if (thread_state == eStateRunning || thread_state == eStateStepping) {
985       running_thread = thread.get();
986       break;
987     } else if (!stopped_thread && StateIsStoppedState(thread_state, true)) {
988       // Remember the first non-dead stopped thread.  We'll use that as a
989       // backup if there are no running threads.
990       stopped_thread = thread.get();
991     }
992   }
993 
994   if (!running_thread && !stopped_thread) {
995     Status error("found no running/stepping or live stopped threads as target "
996                  "for interrupt");
997     LLDB_LOG(log, "skipping due to error: {0}", error);
998 
999     return error;
1000   }
1001 
1002   NativeThreadProtocol *deferred_signal_thread =
1003       running_thread ? running_thread : stopped_thread;
1004 
1005   LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(),
1006            running_thread ? "running" : "stopped",
1007            deferred_signal_thread->GetID());
1008 
1009   StopRunningThreads(deferred_signal_thread->GetID());
1010 
1011   return Status();
1012 }
1013 
1014 Status NativeProcessLinux::Kill() {
1015   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1016   LLDB_LOG(log, "pid {0}", GetID());
1017 
1018   Status error;
1019 
1020   switch (m_state) {
1021   case StateType::eStateInvalid:
1022   case StateType::eStateExited:
1023   case StateType::eStateCrashed:
1024   case StateType::eStateDetached:
1025   case StateType::eStateUnloaded:
1026     // Nothing to do - the process is already dead.
1027     LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
1028              m_state);
1029     return error;
1030 
1031   case StateType::eStateConnected:
1032   case StateType::eStateAttaching:
1033   case StateType::eStateLaunching:
1034   case StateType::eStateStopped:
1035   case StateType::eStateRunning:
1036   case StateType::eStateStepping:
1037   case StateType::eStateSuspended:
1038     // We can try to kill a process in these states.
1039     break;
1040   }
1041 
1042   if (kill(GetID(), SIGKILL) != 0) {
1043     error.SetErrorToErrno();
1044     return error;
1045   }
1046 
1047   return error;
1048 }
1049 
1050 Status NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr,
1051                                                MemoryRegionInfo &range_info) {
1052   // FIXME review that the final memory region returned extends to the end of
1053   // the virtual address space,
1054   // with no perms if it is not mapped.
1055 
1056   // Use an approach that reads memory regions from /proc/{pid}/maps. Assume
1057   // proc maps entries are in ascending order.
1058   // FIXME assert if we find differently.
1059 
1060   if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
1061     // We're done.
1062     return Status("unsupported");
1063   }
1064 
1065   Status error = PopulateMemoryRegionCache();
1066   if (error.Fail()) {
1067     return error;
1068   }
1069 
1070   lldb::addr_t prev_base_address = 0;
1071 
1072   // FIXME start by finding the last region that is <= target address using
1073   // binary search.  Data is sorted.
1074   // There can be a ton of regions on pthreads apps with lots of threads.
1075   for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1076        ++it) {
1077     MemoryRegionInfo &proc_entry_info = it->first;
1078 
1079     // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1080     assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
1081            "descending /proc/pid/maps entries detected, unexpected");
1082     prev_base_address = proc_entry_info.GetRange().GetRangeBase();
1083     UNUSED_IF_ASSERT_DISABLED(prev_base_address);
1084 
1085     // If the target address comes before this entry, indicate distance to next
1086     // region.
1087     if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1088       range_info.GetRange().SetRangeBase(load_addr);
1089       range_info.GetRange().SetByteSize(
1090           proc_entry_info.GetRange().GetRangeBase() - load_addr);
1091       range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1092       range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1093       range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1094       range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1095 
1096       return error;
1097     } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1098       // The target address is within the memory region we're processing here.
1099       range_info = proc_entry_info;
1100       return error;
1101     }
1102 
1103     // The target memory address comes somewhere after the region we just
1104     // parsed.
1105   }
1106 
1107   // If we made it here, we didn't find an entry that contained the given
1108   // address. Return the load_addr as start and the amount of bytes betwwen
1109   // load address and the end of the memory as size.
1110   range_info.GetRange().SetRangeBase(load_addr);
1111   range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
1112   range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1113   range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1114   range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1115   range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1116   return error;
1117 }
1118 
1119 Status NativeProcessLinux::PopulateMemoryRegionCache() {
1120   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1121 
1122   // If our cache is empty, pull the latest.  There should always be at least
1123   // one memory region if memory region handling is supported.
1124   if (!m_mem_region_cache.empty()) {
1125     LLDB_LOG(log, "reusing {0} cached memory region entries",
1126              m_mem_region_cache.size());
1127     return Status();
1128   }
1129 
1130   Status Result;
1131   LinuxMapCallback callback = [&](llvm::Expected<MemoryRegionInfo> Info) {
1132     if (Info) {
1133       FileSpec file_spec(Info->GetName().GetCString());
1134       FileSystem::Instance().Resolve(file_spec);
1135       m_mem_region_cache.emplace_back(*Info, file_spec);
1136       return true;
1137     }
1138 
1139     Result = Info.takeError();
1140     m_supports_mem_region = LazyBool::eLazyBoolNo;
1141     LLDB_LOG(log, "failed to parse proc maps: {0}", Result);
1142     return false;
1143   };
1144 
1145   // Linux kernel since 2.6.14 has /proc/{pid}/smaps
1146   // if CONFIG_PROC_PAGE_MONITOR is enabled
1147   auto BufferOrError = getProcFile(GetID(), "smaps");
1148   if (BufferOrError)
1149     ParseLinuxSMapRegions(BufferOrError.get()->getBuffer(), callback);
1150   else {
1151     BufferOrError = getProcFile(GetID(), "maps");
1152     if (!BufferOrError) {
1153       m_supports_mem_region = LazyBool::eLazyBoolNo;
1154       return BufferOrError.getError();
1155     }
1156 
1157     ParseLinuxMapRegions(BufferOrError.get()->getBuffer(), callback);
1158   }
1159 
1160   if (Result.Fail())
1161     return Result;
1162 
1163   if (m_mem_region_cache.empty()) {
1164     // No entries after attempting to read them.  This shouldn't happen if
1165     // /proc/{pid}/maps is supported. Assume we don't support map entries via
1166     // procfs.
1167     m_supports_mem_region = LazyBool::eLazyBoolNo;
1168     LLDB_LOG(log,
1169              "failed to find any procfs maps entries, assuming no support "
1170              "for memory region metadata retrieval");
1171     return Status("not supported");
1172   }
1173 
1174   LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps",
1175            m_mem_region_cache.size(), GetID());
1176 
1177   // We support memory retrieval, remember that.
1178   m_supports_mem_region = LazyBool::eLazyBoolYes;
1179   return Status();
1180 }
1181 
1182 void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
1183   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1184   LLDB_LOG(log, "newBumpId={0}", newBumpId);
1185   LLDB_LOG(log, "clearing {0} entries from memory region cache",
1186            m_mem_region_cache.size());
1187   m_mem_region_cache.clear();
1188 }
1189 
1190 llvm::Expected<uint64_t>
1191 NativeProcessLinux::Syscall(llvm::ArrayRef<uint64_t> args) {
1192   PopulateMemoryRegionCache();
1193   auto region_it = llvm::find_if(m_mem_region_cache, [](const auto &pair) {
1194     return pair.first.GetExecutable() == MemoryRegionInfo::eYes;
1195   });
1196   if (region_it == m_mem_region_cache.end())
1197     return llvm::createStringError(llvm::inconvertibleErrorCode(),
1198                                    "No executable memory region found!");
1199 
1200   addr_t exe_addr = region_it->first.GetRange().GetRangeBase();
1201 
1202   NativeThreadLinux &thread = *GetThreadByID(GetID());
1203   assert(thread.GetState() == eStateStopped);
1204   NativeRegisterContextLinux &reg_ctx = thread.GetRegisterContext();
1205 
1206   NativeRegisterContextLinux::SyscallData syscall_data =
1207       *reg_ctx.GetSyscallData();
1208 
1209   DataBufferSP registers_sp;
1210   if (llvm::Error Err = reg_ctx.ReadAllRegisterValues(registers_sp).ToError())
1211     return std::move(Err);
1212   auto restore_regs = llvm::make_scope_exit(
1213       [&] { reg_ctx.WriteAllRegisterValues(registers_sp); });
1214 
1215   llvm::SmallVector<uint8_t, 8> memory(syscall_data.Insn.size());
1216   size_t bytes_read;
1217   if (llvm::Error Err =
1218           ReadMemory(exe_addr, memory.data(), memory.size(), bytes_read)
1219               .ToError()) {
1220     return std::move(Err);
1221   }
1222 
1223   auto restore_mem = llvm::make_scope_exit(
1224       [&] { WriteMemory(exe_addr, memory.data(), memory.size(), bytes_read); });
1225 
1226   if (llvm::Error Err = reg_ctx.SetPC(exe_addr).ToError())
1227     return std::move(Err);
1228 
1229   for (const auto &zip : llvm::zip_first(args, syscall_data.Args)) {
1230     if (llvm::Error Err =
1231             reg_ctx
1232                 .WriteRegisterFromUnsigned(std::get<1>(zip), std::get<0>(zip))
1233                 .ToError()) {
1234       return std::move(Err);
1235     }
1236   }
1237   if (llvm::Error Err = WriteMemory(exe_addr, syscall_data.Insn.data(),
1238                                     syscall_data.Insn.size(), bytes_read)
1239                             .ToError())
1240     return std::move(Err);
1241 
1242   m_mem_region_cache.clear();
1243 
1244   // With software single stepping the syscall insn buffer must also include a
1245   // trap instruction to stop the process.
1246   int req = SupportHardwareSingleStepping() ? PTRACE_SINGLESTEP : PTRACE_CONT;
1247   if (llvm::Error Err =
1248           PtraceWrapper(req, thread.GetID(), nullptr, nullptr).ToError())
1249     return std::move(Err);
1250 
1251   int status;
1252   ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, thread.GetID(),
1253                                                  &status, __WALL);
1254   if (wait_pid == -1) {
1255     return llvm::errorCodeToError(
1256         std::error_code(errno, std::generic_category()));
1257   }
1258   assert((unsigned)wait_pid == thread.GetID());
1259 
1260   uint64_t result = reg_ctx.ReadRegisterAsUnsigned(syscall_data.Result, -ESRCH);
1261 
1262   // Values larger than this are actually negative errno numbers.
1263   uint64_t errno_threshold =
1264       (uint64_t(-1) >> (64 - 8 * m_arch.GetAddressByteSize())) - 0x1000;
1265   if (result > errno_threshold) {
1266     return llvm::errorCodeToError(
1267         std::error_code(-result & 0xfff, std::generic_category()));
1268   }
1269 
1270   return result;
1271 }
1272 
1273 llvm::Expected<addr_t>
1274 NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions) {
1275 
1276   llvm::Optional<NativeRegisterContextLinux::MmapData> mmap_data =
1277       GetCurrentThread()->GetRegisterContext().GetMmapData();
1278   if (!mmap_data)
1279     return llvm::make_error<UnimplementedError>();
1280 
1281   unsigned prot = PROT_NONE;
1282   assert((permissions & (ePermissionsReadable | ePermissionsWritable |
1283                          ePermissionsExecutable)) == permissions &&
1284          "Unknown permission!");
1285   if (permissions & ePermissionsReadable)
1286     prot |= PROT_READ;
1287   if (permissions & ePermissionsWritable)
1288     prot |= PROT_WRITE;
1289   if (permissions & ePermissionsExecutable)
1290     prot |= PROT_EXEC;
1291 
1292   llvm::Expected<uint64_t> Result =
1293       Syscall({mmap_data->SysMmap, 0, size, prot, MAP_ANONYMOUS | MAP_PRIVATE,
1294                uint64_t(-1), 0});
1295   if (Result)
1296     m_allocated_memory.try_emplace(*Result, size);
1297   return Result;
1298 }
1299 
1300 llvm::Error NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {
1301   llvm::Optional<NativeRegisterContextLinux::MmapData> mmap_data =
1302       GetCurrentThread()->GetRegisterContext().GetMmapData();
1303   if (!mmap_data)
1304     return llvm::make_error<UnimplementedError>();
1305 
1306   auto it = m_allocated_memory.find(addr);
1307   if (it == m_allocated_memory.end())
1308     return llvm::createStringError(llvm::errc::invalid_argument,
1309                                    "Memory not allocated by the debugger.");
1310 
1311   llvm::Expected<uint64_t> Result =
1312       Syscall({mmap_data->SysMunmap, addr, it->second});
1313   if (!Result)
1314     return Result.takeError();
1315 
1316   m_allocated_memory.erase(it);
1317   return llvm::Error::success();
1318 }
1319 
1320 size_t NativeProcessLinux::UpdateThreads() {
1321   // The NativeProcessLinux monitoring threads are always up to date with
1322   // respect to thread state and they keep the thread list populated properly.
1323   // All this method needs to do is return the thread count.
1324   return m_threads.size();
1325 }
1326 
1327 Status NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,
1328                                          bool hardware) {
1329   if (hardware)
1330     return SetHardwareBreakpoint(addr, size);
1331   else
1332     return SetSoftwareBreakpoint(addr, size);
1333 }
1334 
1335 Status NativeProcessLinux::RemoveBreakpoint(lldb::addr_t addr, bool hardware) {
1336   if (hardware)
1337     return RemoveHardwareBreakpoint(addr);
1338   else
1339     return NativeProcessProtocol::RemoveBreakpoint(addr);
1340 }
1341 
1342 llvm::Expected<llvm::ArrayRef<uint8_t>>
1343 NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(size_t size_hint) {
1344   // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1345   // linux kernel does otherwise.
1346   static const uint8_t g_arm_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1347   static const uint8_t g_thumb_opcode[] = {0x01, 0xde};
1348 
1349   switch (GetArchitecture().GetMachine()) {
1350   case llvm::Triple::arm:
1351     switch (size_hint) {
1352     case 2:
1353       return llvm::makeArrayRef(g_thumb_opcode);
1354     case 4:
1355       return llvm::makeArrayRef(g_arm_opcode);
1356     default:
1357       return llvm::createStringError(llvm::inconvertibleErrorCode(),
1358                                      "Unrecognised trap opcode size hint!");
1359     }
1360   default:
1361     return NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_hint);
1362   }
1363 }
1364 
1365 Status NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
1366                                       size_t &bytes_read) {
1367   if (ProcessVmReadvSupported()) {
1368     // The process_vm_readv path is about 50 times faster than ptrace api. We
1369     // want to use this syscall if it is supported.
1370 
1371     const ::pid_t pid = GetID();
1372 
1373     struct iovec local_iov, remote_iov;
1374     local_iov.iov_base = buf;
1375     local_iov.iov_len = size;
1376     remote_iov.iov_base = reinterpret_cast<void *>(addr);
1377     remote_iov.iov_len = size;
1378 
1379     bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
1380     const bool success = bytes_read == size;
1381 
1382     Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1383     LLDB_LOG(log,
1384              "using process_vm_readv to read {0} bytes from inferior "
1385              "address {1:x}: {2}",
1386              size, addr, success ? "Success" : llvm::sys::StrError(errno));
1387 
1388     if (success)
1389       return Status();
1390     // else the call failed for some reason, let's retry the read using ptrace
1391     // api.
1392   }
1393 
1394   unsigned char *dst = static_cast<unsigned char *>(buf);
1395   size_t remainder;
1396   long data;
1397 
1398   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1399   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
1400 
1401   for (bytes_read = 0; bytes_read < size; bytes_read += remainder) {
1402     Status error = NativeProcessLinux::PtraceWrapper(
1403         PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data);
1404     if (error.Fail())
1405       return error;
1406 
1407     remainder = size - bytes_read;
1408     remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
1409 
1410     // Copy the data into our buffer
1411     memcpy(dst, &data, remainder);
1412 
1413     LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
1414     addr += k_ptrace_word_size;
1415     dst += k_ptrace_word_size;
1416   }
1417   return Status();
1418 }
1419 
1420 Status NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,
1421                                        size_t size, size_t &bytes_written) {
1422   const unsigned char *src = static_cast<const unsigned char *>(buf);
1423   size_t remainder;
1424   Status error;
1425 
1426   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1427   LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
1428 
1429   for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
1430     remainder = size - bytes_written;
1431     remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
1432 
1433     if (remainder == k_ptrace_word_size) {
1434       unsigned long data = 0;
1435       memcpy(&data, src, k_ptrace_word_size);
1436 
1437       LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
1438       error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(),
1439                                                 (void *)addr, (void *)data);
1440       if (error.Fail())
1441         return error;
1442     } else {
1443       unsigned char buff[8];
1444       size_t bytes_read;
1445       error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
1446       if (error.Fail())
1447         return error;
1448 
1449       memcpy(buff, src, remainder);
1450 
1451       size_t bytes_written_rec;
1452       error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
1453       if (error.Fail())
1454         return error;
1455 
1456       LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src,
1457                *(unsigned long *)buff);
1458     }
1459 
1460     addr += k_ptrace_word_size;
1461     src += k_ptrace_word_size;
1462   }
1463   return error;
1464 }
1465 
1466 Status NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) {
1467   return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
1468 }
1469 
1470 Status NativeProcessLinux::GetEventMessage(lldb::tid_t tid,
1471                                            unsigned long *message) {
1472   return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
1473 }
1474 
1475 Status NativeProcessLinux::Detach(lldb::tid_t tid) {
1476   if (tid == LLDB_INVALID_THREAD_ID)
1477     return Status();
1478 
1479   return PtraceWrapper(PTRACE_DETACH, tid);
1480 }
1481 
1482 bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {
1483   for (const auto &thread : m_threads) {
1484     assert(thread && "thread list should not contain NULL threads");
1485     if (thread->GetID() == thread_id) {
1486       // We have this thread.
1487       return true;
1488     }
1489   }
1490 
1491   // We don't have this thread.
1492   return false;
1493 }
1494 
1495 bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) {
1496   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1497   LLDB_LOG(log, "tid: {0})", thread_id);
1498 
1499   bool found = false;
1500   for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
1501     if (*it && ((*it)->GetID() == thread_id)) {
1502       m_threads.erase(it);
1503       found = true;
1504       break;
1505     }
1506   }
1507 
1508   if (found)
1509     NotifyTracersOfThreadDestroyed(thread_id);
1510 
1511   SignalIfAllThreadsStopped();
1512   return found;
1513 }
1514 
1515 Status NativeProcessLinux::NotifyTracersOfNewThread(lldb::tid_t tid) {
1516   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
1517   Status error(m_intel_pt_manager.OnThreadCreated(tid));
1518   if (error.Fail())
1519     LLDB_LOG(log, "Failed to trace a new thread with intel-pt, tid = {0}. {1}",
1520              tid, error.AsCString());
1521   return error;
1522 }
1523 
1524 Status NativeProcessLinux::NotifyTracersOfThreadDestroyed(lldb::tid_t tid) {
1525   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
1526   Status error(m_intel_pt_manager.OnThreadDestroyed(tid));
1527   if (error.Fail())
1528     LLDB_LOG(log,
1529              "Failed to stop a destroyed thread with intel-pt, tid = {0}. {1}",
1530              tid, error.AsCString());
1531   return error;
1532 }
1533 
1534 NativeThreadLinux &NativeProcessLinux::AddThread(lldb::tid_t thread_id,
1535                                                  bool resume) {
1536   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
1537   LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
1538 
1539   assert(!HasThreadNoLock(thread_id) &&
1540          "attempted to add a thread by id that already exists");
1541 
1542   // If this is the first thread, save it as the current thread
1543   if (m_threads.empty())
1544     SetCurrentThreadID(thread_id);
1545 
1546   m_threads.push_back(std::make_unique<NativeThreadLinux>(*this, thread_id));
1547   NativeThreadLinux &thread =
1548       static_cast<NativeThreadLinux &>(*m_threads.back());
1549 
1550   Status tracing_error = NotifyTracersOfNewThread(thread.GetID());
1551   if (tracing_error.Fail()) {
1552     thread.SetStoppedByProcessorTrace(tracing_error.AsCString());
1553     StopRunningThreads(thread.GetID());
1554   } else if (resume)
1555     ResumeThread(thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
1556   else
1557     thread.SetStoppedBySignal(SIGSTOP);
1558 
1559   return thread;
1560 }
1561 
1562 Status NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,
1563                                                    FileSpec &file_spec) {
1564   Status error = PopulateMemoryRegionCache();
1565   if (error.Fail())
1566     return error;
1567 
1568   FileSpec module_file_spec(module_path);
1569   FileSystem::Instance().Resolve(module_file_spec);
1570 
1571   file_spec.Clear();
1572   for (const auto &it : m_mem_region_cache) {
1573     if (it.second.GetFilename() == module_file_spec.GetFilename()) {
1574       file_spec = it.second;
1575       return Status();
1576     }
1577   }
1578   return Status("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
1579                 module_file_spec.GetFilename().AsCString(), GetID());
1580 }
1581 
1582 Status NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
1583                                               lldb::addr_t &load_addr) {
1584   load_addr = LLDB_INVALID_ADDRESS;
1585   Status error = PopulateMemoryRegionCache();
1586   if (error.Fail())
1587     return error;
1588 
1589   FileSpec file(file_name);
1590   for (const auto &it : m_mem_region_cache) {
1591     if (it.second == file) {
1592       load_addr = it.first.GetRange().GetRangeBase();
1593       return Status();
1594     }
1595   }
1596   return Status("No load address found for specified file.");
1597 }
1598 
1599 NativeThreadLinux *NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {
1600   return static_cast<NativeThreadLinux *>(
1601       NativeProcessProtocol::GetThreadByID(tid));
1602 }
1603 
1604 NativeThreadLinux *NativeProcessLinux::GetCurrentThread() {
1605   return static_cast<NativeThreadLinux *>(
1606       NativeProcessProtocol::GetCurrentThread());
1607 }
1608 
1609 Status NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,
1610                                         lldb::StateType state, int signo) {
1611   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1612   LLDB_LOG(log, "tid: {0}", thread.GetID());
1613 
1614   // Before we do the resume below, first check if we have a pending stop
1615   // notification that is currently waiting for all threads to stop.  This is
1616   // potentially a buggy situation since we're ostensibly waiting for threads
1617   // to stop before we send out the pending notification, and here we are
1618   // resuming one before we send out the pending stop notification.
1619   if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
1620     LLDB_LOG(log,
1621              "about to resume tid {0} per explicit request but we have a "
1622              "pending stop notification (tid {1}) that is actively "
1623              "waiting for this thread to stop. Valid sequence of events?",
1624              thread.GetID(), m_pending_notification_tid);
1625   }
1626 
1627   // Request a resume.  We expect this to be synchronous and the system to
1628   // reflect it is running after this completes.
1629   switch (state) {
1630   case eStateRunning: {
1631     const auto resume_result = thread.Resume(signo);
1632     if (resume_result.Success())
1633       SetState(eStateRunning, true);
1634     return resume_result;
1635   }
1636   case eStateStepping: {
1637     const auto step_result = thread.SingleStep(signo);
1638     if (step_result.Success())
1639       SetState(eStateRunning, true);
1640     return step_result;
1641   }
1642   default:
1643     LLDB_LOG(log, "Unhandled state {0}.", state);
1644     llvm_unreachable("Unhandled state for resume");
1645   }
1646 }
1647 
1648 //===----------------------------------------------------------------------===//
1649 
1650 void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {
1651   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1652   LLDB_LOG(log, "about to process event: (triggering_tid: {0})",
1653            triggering_tid);
1654 
1655   m_pending_notification_tid = triggering_tid;
1656 
1657   // Request a stop for all the thread stops that need to be stopped and are
1658   // not already known to be stopped.
1659   for (const auto &thread : m_threads) {
1660     if (StateIsRunningState(thread->GetState()))
1661       static_cast<NativeThreadLinux *>(thread.get())->RequestStop();
1662   }
1663 
1664   SignalIfAllThreadsStopped();
1665   LLDB_LOG(log, "event processing done");
1666 }
1667 
1668 void NativeProcessLinux::SignalIfAllThreadsStopped() {
1669   if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
1670     return; // No pending notification. Nothing to do.
1671 
1672   for (const auto &thread_sp : m_threads) {
1673     if (StateIsRunningState(thread_sp->GetState()))
1674       return; // Some threads are still running. Don't signal yet.
1675   }
1676 
1677   // We have a pending notification and all threads have stopped.
1678   Log *log(
1679       GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
1680 
1681   // Clear any temporary breakpoints we used to implement software single
1682   // stepping.
1683   for (const auto &thread_info : m_threads_stepping_with_breakpoint) {
1684     Status error = RemoveBreakpoint(thread_info.second);
1685     if (error.Fail())
1686       LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}",
1687                thread_info.first, error);
1688   }
1689   m_threads_stepping_with_breakpoint.clear();
1690 
1691   // Notify the delegate about the stop
1692   SetCurrentThreadID(m_pending_notification_tid);
1693   SetState(StateType::eStateStopped, true);
1694   m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
1695 }
1696 
1697 void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {
1698   Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1699   LLDB_LOG(log, "tid: {0}", thread.GetID());
1700 
1701   if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID &&
1702       StateIsRunningState(thread.GetState())) {
1703     // We will need to wait for this new thread to stop as well before firing
1704     // the notification.
1705     thread.RequestStop();
1706   }
1707 }
1708 
1709 void NativeProcessLinux::SigchldHandler() {
1710   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1711   // Process all pending waitpid notifications.
1712   while (true) {
1713     int status = -1;
1714     ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, -1, &status,
1715                                           __WALL | __WNOTHREAD | WNOHANG);
1716 
1717     if (wait_pid == 0)
1718       break; // We are done.
1719 
1720     if (wait_pid == -1) {
1721       Status error(errno, eErrorTypePOSIX);
1722       LLDB_LOG(log, "waitpid (-1, &status, _) failed: {0}", error);
1723       break;
1724     }
1725 
1726     WaitStatus wait_status = WaitStatus::Decode(status);
1727     bool exited = wait_status.type == WaitStatus::Exit ||
1728                   (wait_status.type == WaitStatus::Signal &&
1729                    wait_pid == static_cast<::pid_t>(GetID()));
1730 
1731     LLDB_LOG(
1732         log,
1733         "waitpid (-1, &status, _) => pid = {0}, status = {1}, exited = {2}",
1734         wait_pid, wait_status, exited);
1735 
1736     MonitorCallback(wait_pid, exited, wait_status);
1737   }
1738 }
1739 
1740 // Wrapper for ptrace to catch errors and log calls. Note that ptrace sets
1741 // errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
1742 Status NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
1743                                          void *data, size_t data_size,
1744                                          long *result) {
1745   Status error;
1746   long int ret;
1747 
1748   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
1749 
1750   PtraceDisplayBytes(req, data, data_size);
1751 
1752   errno = 0;
1753   if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
1754     ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
1755                  *(unsigned int *)addr, data);
1756   else
1757     ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
1758                  addr, data);
1759 
1760   if (ret == -1)
1761     error.SetErrorToErrno();
1762 
1763   if (result)
1764     *result = ret;
1765 
1766   LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data,
1767            data_size, ret);
1768 
1769   PtraceDisplayBytes(req, data, data_size);
1770 
1771   if (error.Fail())
1772     LLDB_LOG(log, "ptrace() failed: {0}", error);
1773 
1774   return error;
1775 }
1776 
1777 llvm::Expected<TraceSupportedResponse> NativeProcessLinux::TraceSupported() {
1778   if (IntelPTManager::IsSupported())
1779     return TraceSupportedResponse{"intel-pt", "Intel Processor Trace"};
1780   return NativeProcessProtocol::TraceSupported();
1781 }
1782 
1783 Error NativeProcessLinux::TraceStart(StringRef json_request, StringRef type) {
1784   if (type == "intel-pt") {
1785     if (Expected<TraceIntelPTStartRequest> request =
1786             json::parse<TraceIntelPTStartRequest>(json_request,
1787                                                   "TraceIntelPTStartRequest")) {
1788       std::vector<lldb::tid_t> process_threads;
1789       for (auto &thread : m_threads)
1790         process_threads.push_back(thread->GetID());
1791       return m_intel_pt_manager.TraceStart(*request, process_threads);
1792     } else
1793       return request.takeError();
1794   }
1795 
1796   return NativeProcessProtocol::TraceStart(json_request, type);
1797 }
1798 
1799 Error NativeProcessLinux::TraceStop(const TraceStopRequest &request) {
1800   if (request.type == "intel-pt")
1801     return m_intel_pt_manager.TraceStop(request);
1802   return NativeProcessProtocol::TraceStop(request);
1803 }
1804 
1805 Expected<json::Value> NativeProcessLinux::TraceGetState(StringRef type) {
1806   if (type == "intel-pt")
1807     return m_intel_pt_manager.GetState();
1808   return NativeProcessProtocol::TraceGetState(type);
1809 }
1810 
1811 Expected<std::vector<uint8_t>> NativeProcessLinux::TraceGetBinaryData(
1812     const TraceGetBinaryDataRequest &request) {
1813   if (request.type == "intel-pt")
1814     return m_intel_pt_manager.GetBinaryData(request);
1815   return NativeProcessProtocol::TraceGetBinaryData(request);
1816 }
1817