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