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