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