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