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