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