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