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