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