blob: 4f36fba5fc97a16c88ab7872b3a7579aa7365db4 [file] [log] [blame]
Todd Fialaaf245d12014-06-30 21:05:18 +00001//===-- NativeProcessLinux.cpp -------------------------------- -*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Todd Fialaaf245d12014-06-30 21:05:18 +000010#include "NativeProcessLinux.h"
11
12// C Includes
13#include <errno.h>
Todd Fialaaf245d12014-06-30 21:05:18 +000014#include <stdint.h>
Kate Stoneb9c1b512016-09-06 20:57:50 +000015#include <string.h>
Todd Fialaaf245d12014-06-30 21:05:18 +000016#include <unistd.h>
Todd Fialaaf245d12014-06-30 21:05:18 +000017
18// C++ Includes
19#include <fstream>
Pavel Labathdf7c6992015-06-17 18:38:49 +000020#include <mutex>
Pavel Labathc0765592015-05-06 10:46:34 +000021#include <sstream>
Todd Fialaaf245d12014-06-30 21:05:18 +000022#include <string>
Pavel Labath5b981ab2015-05-29 12:53:54 +000023#include <unordered_map>
Todd Fialaaf245d12014-06-30 21:05:18 +000024
25// Other libraries and framework includes
Tamas Berghammerd8c338d2015-04-15 09:47:02 +000026#include "lldb/Core/EmulateInstruction.h"
Oleksiy Vyalov6edef202014-11-17 22:16:42 +000027#include "lldb/Core/ModuleSpec.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000028#include "lldb/Host/Host.h"
Pavel Labath5ad891f2016-07-21 14:54:03 +000029#include "lldb/Host/HostProcess.h"
Zachary Turner24ae6292017-02-16 19:38:21 +000030#include "lldb/Host/PseudoTerminal.h"
Zachary Turner39de3112014-09-09 20:54:56 +000031#include "lldb/Host/ThreadLauncher.h"
Pavel Labath2a86b552016-06-14 17:30:52 +000032#include "lldb/Host/common/NativeBreakpoint.h"
33#include "lldb/Host/common/NativeRegisterContext.h"
Pavel Labath4ee1c952017-02-06 18:36:58 +000034#include "lldb/Host/linux/Ptrace.h"
35#include "lldb/Host/linux/Uio.h"
Kamil Rytarowski816ae4b2017-02-01 14:30:40 +000036#include "lldb/Host/posix/ProcessLauncherPosixFork.h"
Pavel Labath2a86b552016-06-14 17:30:52 +000037#include "lldb/Symbol/ObjectFile.h"
Zachary Turner90aff472015-03-03 23:36:51 +000038#include "lldb/Target/Process.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000039#include "lldb/Target/ProcessLaunchInfo.h"
Pavel Labath5b981ab2015-05-29 12:53:54 +000040#include "lldb/Target/Target.h"
Chaoren Linc16f5dc2015-03-19 23:28:10 +000041#include "lldb/Utility/LLDBAssert.h"
Pavel Labathd821c992018-08-07 11:07:21 +000042#include "lldb/Utility/RegisterValue.h"
43#include "lldb/Utility/State.h"
Zachary Turner97206d52017-05-12 04:51:55 +000044#include "lldb/Utility/Status.h"
Pavel Labathf805e192015-07-07 10:08:41 +000045#include "lldb/Utility/StringExtractor.h"
Pavel Labath10c41f32017-06-06 14:06:17 +000046#include "llvm/Support/Errno.h"
47#include "llvm/Support/FileSystem.h"
48#include "llvm/Support/Threading.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000049
Todd Fialaaf245d12014-06-30 21:05:18 +000050#include "NativeThreadLinux.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000051#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000052#include "Procfs.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000053
Tamas Berghammerd8584872015-02-06 10:57:40 +000054#include <linux/unistd.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000055#include <sys/socket.h>
Pavel Labathdf7c6992015-06-17 18:38:49 +000056#include <sys/syscall.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000057#include <sys/types.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000058#include <sys/user.h>
59#include <sys/wait.h>
60
Todd Fialaaf245d12014-06-30 21:05:18 +000061// Support hardware breakpoints in case it has not been defined
62#ifndef TRAP_HWBKPT
Kate Stoneb9c1b512016-09-06 20:57:50 +000063#define TRAP_HWBKPT 4
Todd Fialaaf245d12014-06-30 21:05:18 +000064#endif
65
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000066using namespace lldb;
67using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000068using namespace lldb_private::process_linux;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000069using namespace llvm;
70
Todd Fialaaf245d12014-06-30 21:05:18 +000071// Private bits we only need internally.
Pavel Labathdf7c6992015-06-17 18:38:49 +000072
Kate Stoneb9c1b512016-09-06 20:57:50 +000073static bool ProcessVmReadvSupported() {
74 static bool is_supported;
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000075 static llvm::once_flag flag;
Pavel Labathdf7c6992015-06-17 18:38:49 +000076
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000077 llvm::call_once(flag, [] {
Pavel Labatha6321a82017-01-19 15:26:04 +000078 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Pavel Labath4abe5d62016-07-15 10:18:15 +000079
Kate Stoneb9c1b512016-09-06 20:57:50 +000080 uint32_t source = 0x47424742;
81 uint32_t dest = 0;
Pavel Labath4abe5d62016-07-15 10:18:15 +000082
Kate Stoneb9c1b512016-09-06 20:57:50 +000083 struct iovec local, remote;
84 remote.iov_base = &source;
85 local.iov_base = &dest;
86 remote.iov_len = local.iov_len = sizeof source;
Pavel Labath4abe5d62016-07-15 10:18:15 +000087
Kate Stoneb9c1b512016-09-06 20:57:50 +000088 // We shall try if cross-process-memory reads work by attempting to read a
89 // value from our own process.
90 ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
91 is_supported = (res == sizeof(source) && source == dest);
Pavel Labatha6321a82017-01-19 15:26:04 +000092 if (is_supported)
93 LLDB_LOG(log,
94 "Detected kernel support for process_vm_readv syscall. "
95 "Fast memory reads enabled.");
96 else
97 LLDB_LOG(log,
98 "syscall process_vm_readv failed (error: {0}). Fast memory "
99 "reads disabled.",
Pavel Labath10c41f32017-06-06 14:06:17 +0000100 llvm::sys::StrError());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000101 });
Pavel Labath4abe5d62016-07-15 10:18:15 +0000102
Kate Stoneb9c1b512016-09-06 20:57:50 +0000103 return is_supported;
Pavel Labath4abe5d62016-07-15 10:18:15 +0000104}
105
Kate Stoneb9c1b512016-09-06 20:57:50 +0000106namespace {
107void MaybeLogLaunchInfo(const ProcessLaunchInfo &info) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000108 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000109 if (!log)
110 return;
111
112 if (const FileAction *action = info.GetFileActionForFD(STDIN_FILENO))
Pavel Labatha6321a82017-01-19 15:26:04 +0000113 LLDB_LOG(log, "setting STDIN to '{0}'", action->GetFileSpec());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000114 else
Pavel Labatha6321a82017-01-19 15:26:04 +0000115 LLDB_LOG(log, "leaving STDIN as is");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000116
117 if (const FileAction *action = info.GetFileActionForFD(STDOUT_FILENO))
Pavel Labatha6321a82017-01-19 15:26:04 +0000118 LLDB_LOG(log, "setting STDOUT to '{0}'", action->GetFileSpec());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000119 else
Pavel Labatha6321a82017-01-19 15:26:04 +0000120 LLDB_LOG(log, "leaving STDOUT as is");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000121
122 if (const FileAction *action = info.GetFileActionForFD(STDERR_FILENO))
Pavel Labatha6321a82017-01-19 15:26:04 +0000123 LLDB_LOG(log, "setting STDERR to '{0}'", action->GetFileSpec());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000124 else
Pavel Labatha6321a82017-01-19 15:26:04 +0000125 LLDB_LOG(log, "leaving STDERR as is");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000126
127 int i = 0;
128 for (const char **args = info.GetArguments().GetConstArgumentVector(); *args;
129 ++args, ++i)
Pavel Labatha6321a82017-01-19 15:26:04 +0000130 LLDB_LOG(log, "arg {0}: '{1}'", i, *args);
Pavel Labath4abe5d62016-07-15 10:18:15 +0000131}
Todd Fialaaf245d12014-06-30 21:05:18 +0000132
Kate Stoneb9c1b512016-09-06 20:57:50 +0000133void DisplayBytes(StreamString &s, void *bytes, uint32_t count) {
134 uint8_t *ptr = (uint8_t *)bytes;
135 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
136 for (uint32_t i = 0; i < loop_count; i++) {
137 s.Printf("[%x]", *ptr);
138 ptr++;
139 }
140}
Todd Fialaaf245d12014-06-30 21:05:18 +0000141
Kate Stoneb9c1b512016-09-06 20:57:50 +0000142void PtraceDisplayBytes(int &req, void *data, size_t data_size) {
Pavel Labathaafe0532017-02-06 19:31:05 +0000143 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
Pavel Labatha6321a82017-01-19 15:26:04 +0000144 if (!log)
145 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000146 StreamString buf;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000147
Pavel Labatha6321a82017-01-19 15:26:04 +0000148 switch (req) {
149 case PTRACE_POKETEXT: {
150 DisplayBytes(buf, &data, 8);
Pavel Labathaafe0532017-02-06 19:31:05 +0000151 LLDB_LOGV(log, "PTRACE_POKETEXT {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000152 break;
153 }
154 case PTRACE_POKEDATA: {
155 DisplayBytes(buf, &data, 8);
Pavel Labathaafe0532017-02-06 19:31:05 +0000156 LLDB_LOGV(log, "PTRACE_POKEDATA {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000157 break;
158 }
159 case PTRACE_POKEUSER: {
160 DisplayBytes(buf, &data, 8);
Pavel Labathaafe0532017-02-06 19:31:05 +0000161 LLDB_LOGV(log, "PTRACE_POKEUSER {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000162 break;
163 }
164 case PTRACE_SETREGS: {
165 DisplayBytes(buf, data, data_size);
Pavel Labathaafe0532017-02-06 19:31:05 +0000166 LLDB_LOGV(log, "PTRACE_SETREGS {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000167 break;
168 }
169 case PTRACE_SETFPREGS: {
170 DisplayBytes(buf, data, data_size);
Pavel Labathaafe0532017-02-06 19:31:05 +0000171 LLDB_LOGV(log, "PTRACE_SETFPREGS {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000172 break;
173 }
174 case PTRACE_SETSIGINFO: {
175 DisplayBytes(buf, data, sizeof(siginfo_t));
Pavel Labathaafe0532017-02-06 19:31:05 +0000176 LLDB_LOGV(log, "PTRACE_SETSIGINFO {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000177 break;
178 }
179 case PTRACE_SETREGSET: {
Pavel Labath11edb4e2017-12-01 12:05:00 +0000180 // Extract iov_base from data, which is a pointer to the struct iovec
Pavel Labatha6321a82017-01-19 15:26:04 +0000181 DisplayBytes(buf, *(void **)data, data_size);
Pavel Labathaafe0532017-02-06 19:31:05 +0000182 LLDB_LOGV(log, "PTRACE_SETREGSET {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000183 break;
184 }
185 default: {}
Kate Stoneb9c1b512016-09-06 20:57:50 +0000186 }
187}
Todd Fialaaf245d12014-06-30 21:05:18 +0000188
Kate Stoneb9c1b512016-09-06 20:57:50 +0000189static constexpr unsigned k_ptrace_word_size = sizeof(void *);
190static_assert(sizeof(long) >= k_ptrace_word_size,
191 "Size of long must be larger than ptrace word size");
Pavel Labath1107b5a2015-04-17 14:07:49 +0000192} // end of anonymous namespace
193
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000194// Simple helper function to ensure flags are enabled on the given file
195// descriptor.
Zachary Turner97206d52017-05-12 04:51:55 +0000196static Status EnsureFDFlags(int fd, int flags) {
197 Status error;
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000198
Kate Stoneb9c1b512016-09-06 20:57:50 +0000199 int status = fcntl(fd, F_GETFL);
200 if (status == -1) {
201 error.SetErrorToErrno();
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000202 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000203 }
204
205 if (fcntl(fd, F_SETFL, status | flags) == -1) {
206 error.SetErrorToErrno();
207 return error;
208 }
209
210 return error;
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000211}
212
Todd Fialaaf245d12014-06-30 21:05:18 +0000213// -----------------------------------------------------------------------------
214// Public Static Methods
215// -----------------------------------------------------------------------------
216
Pavel Labath82abefa2017-07-18 09:24:48 +0000217llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
Pavel Labath96e600f2017-07-07 11:02:19 +0000218NativeProcessLinux::Factory::Launch(ProcessLaunchInfo &launch_info,
219 NativeDelegate &native_delegate,
220 MainLoop &mainloop) const {
Pavel Labatha6321a82017-01-19 15:26:04 +0000221 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Todd Fialaaf245d12014-06-30 21:05:18 +0000222
Pavel Labath96e600f2017-07-07 11:02:19 +0000223 MaybeLogLaunchInfo(launch_info);
Todd Fialaaf245d12014-06-30 21:05:18 +0000224
Pavel Labath96e600f2017-07-07 11:02:19 +0000225 Status status;
226 ::pid_t pid = ProcessLauncherPosixFork()
227 .LaunchProcess(launch_info, status)
228 .GetProcessId();
229 LLDB_LOG(log, "pid = {0:x}", pid);
230 if (status.Fail()) {
231 LLDB_LOG(log, "failed to launch process: {0}", status);
232 return status.ToError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000233 }
234
Pavel Labath96e600f2017-07-07 11:02:19 +0000235 // Wait for the child process to trap on its call to execve.
236 int wstatus;
237 ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0);
238 assert(wpid == pid);
239 (void)wpid;
240 if (!WIFSTOPPED(wstatus)) {
241 LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}",
242 WaitStatus::Decode(wstatus));
243 return llvm::make_error<StringError>("Could not sync with inferior process",
244 llvm::inconvertibleErrorCode());
245 }
246 LLDB_LOG(log, "inferior started, now in stopped state");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000247
Pavel Labath36e82202018-01-29 10:46:00 +0000248 ProcessInstanceInfo Info;
249 if (!Host::GetProcessInfo(pid, Info)) {
250 return llvm::make_error<StringError>("Cannot get process architecture",
251 llvm::inconvertibleErrorCode());
252 }
Pavel Labath96e600f2017-07-07 11:02:19 +0000253
254 // Set the architecture to the exe architecture.
255 LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid,
Pavel Labath36e82202018-01-29 10:46:00 +0000256 Info.GetArchitecture().GetArchitectureName());
Pavel Labath96e600f2017-07-07 11:02:19 +0000257
258 status = SetDefaultPtraceOpts(pid);
259 if (status.Fail()) {
260 LLDB_LOG(log, "failed to set default ptrace options: {0}", status);
261 return status.ToError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000262 }
263
Pavel Labath82abefa2017-07-18 09:24:48 +0000264 return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
Pavel Labath96e600f2017-07-07 11:02:19 +0000265 pid, launch_info.GetPTY().ReleaseMasterFileDescriptor(), native_delegate,
Pavel Labath36e82202018-01-29 10:46:00 +0000266 Info.GetArchitecture(), mainloop, {pid}));
Todd Fialaaf245d12014-06-30 21:05:18 +0000267}
268
Pavel Labath82abefa2017-07-18 09:24:48 +0000269llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
270NativeProcessLinux::Factory::Attach(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000271 lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
Pavel Labath96e600f2017-07-07 11:02:19 +0000272 MainLoop &mainloop) const {
Pavel Labatha6321a82017-01-19 15:26:04 +0000273 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
274 LLDB_LOG(log, "pid = {0:x}", pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000275
Kate Stoneb9c1b512016-09-06 20:57:50 +0000276 // Retrieve the architecture for the running process.
Pavel Labath36e82202018-01-29 10:46:00 +0000277 ProcessInstanceInfo Info;
278 if (!Host::GetProcessInfo(pid, Info)) {
279 return llvm::make_error<StringError>("Cannot get process architecture",
280 llvm::inconvertibleErrorCode());
281 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000282
Pavel Labath96e600f2017-07-07 11:02:19 +0000283 auto tids_or = NativeProcessLinux::Attach(pid);
284 if (!tids_or)
285 return tids_or.takeError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000286
Pavel Labath82abefa2017-07-18 09:24:48 +0000287 return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
Pavel Labath36e82202018-01-29 10:46:00 +0000288 pid, -1, native_delegate, Info.GetArchitecture(), mainloop, *tids_or));
Todd Fialaaf245d12014-06-30 21:05:18 +0000289}
290
291// -----------------------------------------------------------------------------
292// Public Instance Methods
293// -----------------------------------------------------------------------------
294
Pavel Labath96e600f2017-07-07 11:02:19 +0000295NativeProcessLinux::NativeProcessLinux(::pid_t pid, int terminal_fd,
296 NativeDelegate &delegate,
Pavel Labath82abefa2017-07-18 09:24:48 +0000297 const ArchSpec &arch, MainLoop &mainloop,
298 llvm::ArrayRef<::pid_t> tids)
Pavel Labath96e600f2017-07-07 11:02:19 +0000299 : NativeProcessProtocol(pid, terminal_fd, delegate), m_arch(arch) {
300 if (m_terminal_fd != -1) {
301 Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
302 assert(status.Success());
303 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000304
Pavel Labath96e600f2017-07-07 11:02:19 +0000305 Status status;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000306 m_sigchld_handle = mainloop.RegisterSignal(
Pavel Labath96e600f2017-07-07 11:02:19 +0000307 SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status);
308 assert(m_sigchld_handle && status.Success());
Todd Fialaaf245d12014-06-30 21:05:18 +0000309
Pavel Labath96e600f2017-07-07 11:02:19 +0000310 for (const auto &tid : tids) {
Pavel Labatha5be48b2017-10-17 15:52:16 +0000311 NativeThreadLinux &thread = AddThread(tid);
312 thread.SetStoppedBySignal(SIGSTOP);
313 ThreadWasCreated(thread);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000314 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000315
Kate Stoneb9c1b512016-09-06 20:57:50 +0000316 // Let our process instance know the thread has stopped.
Pavel Labath96e600f2017-07-07 11:02:19 +0000317 SetCurrentThreadID(tids[0]);
318 SetState(StateType::eStateStopped, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000319
Pavel Labath96e600f2017-07-07 11:02:19 +0000320 // Proccess any signals we received before installing our handler
321 SigchldHandler();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000322}
323
Pavel Labath96e600f2017-07-07 11:02:19 +0000324llvm::Expected<std::vector<::pid_t>> NativeProcessLinux::Attach(::pid_t pid) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000325 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000326
Pavel Labath96e600f2017-07-07 11:02:19 +0000327 Status status;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000328 // Use a map to keep track of the threads which we have attached/need to
329 // attach.
330 Host::TidMap tids_to_attach;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000331 while (Host::FindProcessThreads(pid, tids_to_attach)) {
332 for (Host::TidMap::iterator it = tids_to_attach.begin();
333 it != tids_to_attach.end();) {
334 if (it->second == false) {
335 lldb::tid_t tid = it->first;
336
337 // Attach to the requested process.
338 // An attach will cause the thread to stop with a SIGSTOP.
Pavel Labath96e600f2017-07-07 11:02:19 +0000339 if ((status = PtraceWrapper(PTRACE_ATTACH, tid)).Fail()) {
Adrian Prantl05097242018-04-30 16:49:04 +0000340 // No such thread. The thread may have exited. More error handling
341 // may be needed.
Pavel Labath96e600f2017-07-07 11:02:19 +0000342 if (status.GetError() == ESRCH) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000343 it = tids_to_attach.erase(it);
344 continue;
Pavel Labath96e600f2017-07-07 11:02:19 +0000345 }
346 return status.ToError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000347 }
348
Pavel Labath96e600f2017-07-07 11:02:19 +0000349 int wpid =
350 llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, nullptr, __WALL);
Adrian Prantl05097242018-04-30 16:49:04 +0000351 // Need to use __WALL otherwise we receive an error with errno=ECHLD At
352 // this point we should have a thread stopped if waitpid succeeds.
Pavel Labath96e600f2017-07-07 11:02:19 +0000353 if (wpid < 0) {
Adrian Prantl05097242018-04-30 16:49:04 +0000354 // No such thread. The thread may have exited. More error handling
355 // may be needed.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000356 if (errno == ESRCH) {
357 it = tids_to_attach.erase(it);
358 continue;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000359 }
Pavel Labath96e600f2017-07-07 11:02:19 +0000360 return llvm::errorCodeToError(
361 std::error_code(errno, std::generic_category()));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000362 }
363
Pavel Labath96e600f2017-07-07 11:02:19 +0000364 if ((status = SetDefaultPtraceOpts(tid)).Fail())
365 return status.ToError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000366
Pavel Labatha6321a82017-01-19 15:26:04 +0000367 LLDB_LOG(log, "adding tid = {0}", tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000368 it->second = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000369 }
370
371 // move the loop forward
372 ++it;
373 }
374 }
375
Pavel Labath96e600f2017-07-07 11:02:19 +0000376 size_t tid_count = tids_to_attach.size();
377 if (tid_count == 0)
378 return llvm::make_error<StringError>("No such process",
379 llvm::inconvertibleErrorCode());
Todd Fialaaf245d12014-06-30 21:05:18 +0000380
Pavel Labath96e600f2017-07-07 11:02:19 +0000381 std::vector<::pid_t> tids;
382 tids.reserve(tid_count);
383 for (const auto &p : tids_to_attach)
384 tids.push_back(p.first);
385 return std::move(tids);
Todd Fialaaf245d12014-06-30 21:05:18 +0000386}
387
Zachary Turner97206d52017-05-12 04:51:55 +0000388Status NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000389 long ptrace_opts = 0;
Todd Fialaaf245d12014-06-30 21:05:18 +0000390
Kate Stoneb9c1b512016-09-06 20:57:50 +0000391 // Have the child raise an event on exit. This is used to keep the child in
392 // limbo until it is destroyed.
393 ptrace_opts |= PTRACE_O_TRACEEXIT;
Todd Fialaaf245d12014-06-30 21:05:18 +0000394
Kate Stoneb9c1b512016-09-06 20:57:50 +0000395 // Have the tracer trace threads which spawn in the inferior process.
396 // TODO: if we want to support tracing the inferiors' child, add the
397 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
398 ptrace_opts |= PTRACE_O_TRACECLONE;
Todd Fialaaf245d12014-06-30 21:05:18 +0000399
Adrian Prantl05097242018-04-30 16:49:04 +0000400 // Have the tracer notify us before execve returns (needed to disable legacy
401 // SIGTRAP generation)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000402 ptrace_opts |= PTRACE_O_TRACEEXEC;
Todd Fialaaf245d12014-06-30 21:05:18 +0000403
Kate Stoneb9c1b512016-09-06 20:57:50 +0000404 return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void *)ptrace_opts);
Todd Fialaaf245d12014-06-30 21:05:18 +0000405}
406
Pavel Labath1107b5a2015-04-17 14:07:49 +0000407// Handles all waitpid events from the inferior process.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000408void NativeProcessLinux::MonitorCallback(lldb::pid_t pid, bool exited,
Pavel Labath3508fc82017-06-19 12:47:50 +0000409 WaitStatus status) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000410 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Todd Fialaaf245d12014-06-30 21:05:18 +0000411
Kate Stoneb9c1b512016-09-06 20:57:50 +0000412 // Certain activities differ based on whether the pid is the tid of the main
413 // thread.
414 const bool is_main_thread = (pid == GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000415
Kate Stoneb9c1b512016-09-06 20:57:50 +0000416 // Handle when the thread exits.
417 if (exited) {
Pavel Labathd8b3c1a2017-12-18 09:44:29 +0000418 LLDB_LOG(log,
419 "got exit signal({0}) , tid = {1} ({2} main thread), process "
420 "state = {3}",
421 signal, pid, is_main_thread ? "is" : "is not", GetState());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000422
423 // This is a thread that exited. Ensure we're not tracking it anymore.
Pavel Labathd8b3c1a2017-12-18 09:44:29 +0000424 StopTrackingThread(pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000425
426 if (is_main_thread) {
Pavel Labathd8b3c1a2017-12-18 09:44:29 +0000427 // The main thread exited. We're done monitoring. Report to delegate.
428 SetExitStatus(status, true);
Todd Fialaaf245d12014-06-30 21:05:18 +0000429
Pavel Labathd8b3c1a2017-12-18 09:44:29 +0000430 // Notify delegate that our process has exited.
431 SetState(StateType::eStateExited, true);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000432 }
433 return;
434 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000435
Kate Stoneb9c1b512016-09-06 20:57:50 +0000436 siginfo_t info;
437 const auto info_err = GetSignalInfo(pid, &info);
438 auto thread_sp = GetThreadByID(pid);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000439
Kate Stoneb9c1b512016-09-06 20:57:50 +0000440 if (!thread_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +0000441 // Normally, the only situation when we cannot find the thread is if we
442 // have just received a new thread notification. This is indicated by
Pavel Labatha6321a82017-01-19 15:26:04 +0000443 // GetSignalInfo() returning si_code == SI_USER and si_pid == 0
444 LLDB_LOG(log, "received notification about an unknown tid {0}.", pid);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000445
Kate Stoneb9c1b512016-09-06 20:57:50 +0000446 if (info_err.Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000447 LLDB_LOG(log,
448 "(tid {0}) GetSignalInfo failed ({1}). "
449 "Ingoring this notification.",
450 pid, info_err);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000451 return;
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000452 }
453
Pavel Labatha6321a82017-01-19 15:26:04 +0000454 LLDB_LOG(log, "tid {0}, si_code: {1}, si_pid: {2}", pid, info.si_code,
455 info.si_pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000456
Pavel Labatha5be48b2017-10-17 15:52:16 +0000457 NativeThreadLinux &thread = AddThread(pid);
Ravitheja Addepally99e37692017-06-28 07:58:31 +0000458
Kate Stoneb9c1b512016-09-06 20:57:50 +0000459 // Resume the newly created thread.
Pavel Labatha5be48b2017-10-17 15:52:16 +0000460 ResumeThread(thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
461 ThreadWasCreated(thread);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000462 return;
463 }
464
465 // Get details on the signal raised.
466 if (info_err.Success()) {
467 // We have retrieved the signal info. Dispatch appropriately.
468 if (info.si_signo == SIGTRAP)
469 MonitorSIGTRAP(info, *thread_sp);
Chaoren Linfa03ad22015-02-03 01:50:42 +0000470 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000471 MonitorSignal(info, *thread_sp, exited);
472 } else {
473 if (info_err.GetError() == EINVAL) {
Adrian Prantl05097242018-04-30 16:49:04 +0000474 // This is a group stop reception for this tid. We can reach here if we
475 // reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the tracee,
476 // triggering the group-stop mechanism. Normally receiving these would
477 // stop the process, pending a SIGCONT. Simulating this state in a
478 // debugger is hard and is generally not needed (one use case is
479 // debugging background task being managed by a shell). For general use,
480 // it is sufficient to stop the process in a signal-delivery stop which
481 // happens before the group stop. This done by MonitorSignal and works
482 // correctly for all signals.
Pavel Labatha6321a82017-01-19 15:26:04 +0000483 LLDB_LOG(log,
484 "received a group stop for pid {0} tid {1}. Transparent "
485 "handling of group stops not supported, resuming the "
486 "thread.",
487 GetID(), pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000488 ResumeThread(*thread_sp, thread_sp->GetState(),
489 LLDB_INVALID_SIGNAL_NUMBER);
490 } else {
491 // ptrace(GETSIGINFO) failed (but not due to group-stop).
Todd Fialaaf245d12014-06-30 21:05:18 +0000492
Kate Stoneb9c1b512016-09-06 20:57:50 +0000493 // A return value of ESRCH means the thread/process is no longer on the
Pavel Labatha6321a82017-01-19 15:26:04 +0000494 // system, so it was killed somehow outside of our control. Either way,
495 // we can't do anything with it anymore.
Todd Fialaaf245d12014-06-30 21:05:18 +0000496
Kate Stoneb9c1b512016-09-06 20:57:50 +0000497 // Stop tracking the metadata for the thread since it's entirely off the
498 // system now.
499 const bool thread_found = StopTrackingThread(pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000500
Pavel Labatha6321a82017-01-19 15:26:04 +0000501 LLDB_LOG(log,
502 "GetSignalInfo failed: {0}, tid = {1}, signal = {2}, "
503 "status = {3}, main_thread = {4}, thread_found: {5}",
504 info_err, pid, signal, status, is_main_thread, thread_found);
Todd Fialaaf245d12014-06-30 21:05:18 +0000505
Kate Stoneb9c1b512016-09-06 20:57:50 +0000506 if (is_main_thread) {
507 // Notify the delegate - our process is not available but appears to
Adrian Prantl05097242018-04-30 16:49:04 +0000508 // have been killed outside our control. Is eStateExited the right
509 // exit state in this case?
Pavel Labath3508fc82017-06-19 12:47:50 +0000510 SetExitStatus(status, true);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000511 SetState(StateType::eStateExited, true);
512 } else {
513 // This thread was pulled out from underneath us. Anything to do here?
514 // Do we want to do an all stop?
Pavel Labatha6321a82017-01-19 15:26:04 +0000515 LLDB_LOG(log,
516 "pid {0} tid {1} non-main thread exit occurred, didn't "
517 "tell delegate anything since thread disappeared out "
518 "from underneath us",
519 GetID(), pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000520 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000521 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000522 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000523}
524
Kate Stoneb9c1b512016-09-06 20:57:50 +0000525void NativeProcessLinux::WaitForNewThread(::pid_t tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000526 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Pavel Labath426bdf82015-04-28 07:51:52 +0000527
Pavel Labatha5be48b2017-10-17 15:52:16 +0000528 if (GetThreadByID(tid)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000529 // We are already tracking the thread - we got the event on the new thread
Pavel Labatha5be48b2017-10-17 15:52:16 +0000530 // (see MonitorSignal) before this one. We are done.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000531 return;
532 }
Pavel Labath426bdf82015-04-28 07:51:52 +0000533
Kate Stoneb9c1b512016-09-06 20:57:50 +0000534 // The thread is not tracked yet, let's wait for it to appear.
535 int status = -1;
Pavel Labathc1a6b122017-07-03 09:25:55 +0000536 LLDB_LOG(log,
537 "received thread creation event for tid {0}. tid not tracked "
538 "yet, waiting for thread to appear...",
539 tid);
540 ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, &status, __WALL);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000541 // Since we are waiting on a specific tid, this must be the creation event.
Pavel Labatha6321a82017-01-19 15:26:04 +0000542 // But let's do some checks just in case.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000543 if (wait_pid != tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000544 LLDB_LOG(log,
545 "waiting for tid {0} failed. Assuming the thread has "
546 "disappeared in the meantime",
547 tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000548 // The only way I know of this could happen is if the whole process was
549 // SIGKILLed in the mean time. In any case, we can't do anything about that
550 // now.
551 return;
552 }
553 if (WIFEXITED(status)) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000554 LLDB_LOG(log,
555 "waiting for tid {0} returned an 'exited' event. Not "
556 "tracking the thread.",
557 tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000558 // Also a very improbable event.
559 return;
560 }
Pavel Labath426bdf82015-04-28 07:51:52 +0000561
Pavel Labatha6321a82017-01-19 15:26:04 +0000562 LLDB_LOG(log, "pid = {0}: tracking new thread tid {1}", GetID(), tid);
Pavel Labatha5be48b2017-10-17 15:52:16 +0000563 NativeThreadLinux &new_thread = AddThread(tid);
Ravitheja Addepally99e37692017-06-28 07:58:31 +0000564
Pavel Labatha5be48b2017-10-17 15:52:16 +0000565 ResumeThread(new_thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
566 ThreadWasCreated(new_thread);
Pavel Labath426bdf82015-04-28 07:51:52 +0000567}
568
Kate Stoneb9c1b512016-09-06 20:57:50 +0000569void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info,
570 NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000571 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000572 const bool is_main_thread = (thread.GetID() == GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000573
Kate Stoneb9c1b512016-09-06 20:57:50 +0000574 assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
Todd Fialaaf245d12014-06-30 21:05:18 +0000575
Kate Stoneb9c1b512016-09-06 20:57:50 +0000576 switch (info.si_code) {
577 // TODO: these two cases are required if we want to support tracing of the
Adrian Prantl05097242018-04-30 16:49:04 +0000578 // inferiors' children. We'd need this to debug a monitor. case (SIGTRAP |
579 // (PTRACE_EVENT_FORK << 8)): case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
Todd Fialaaf245d12014-06-30 21:05:18 +0000580
Kate Stoneb9c1b512016-09-06 20:57:50 +0000581 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): {
582 // This is the notification on the parent thread which informs us of new
Adrian Prantl05097242018-04-30 16:49:04 +0000583 // thread creation. We don't want to do anything with the parent thread so
584 // we just resume it. In case we want to implement "break on thread
585 // creation" functionality, we would need to stop here.
Todd Fialaaf245d12014-06-30 21:05:18 +0000586
Kate Stoneb9c1b512016-09-06 20:57:50 +0000587 unsigned long event_message = 0;
588 if (GetEventMessage(thread.GetID(), &event_message).Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000589 LLDB_LOG(log,
590 "pid {0} received thread creation event but "
591 "GetEventMessage failed so we don't know the new tid",
592 thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000593 } else
594 WaitForNewThread(event_message);
Todd Fialaaf245d12014-06-30 21:05:18 +0000595
Kate Stoneb9c1b512016-09-06 20:57:50 +0000596 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
597 break;
598 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000599
Kate Stoneb9c1b512016-09-06 20:57:50 +0000600 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): {
Pavel Labatha6321a82017-01-19 15:26:04 +0000601 LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000602
603 // Exec clears any pending notifications.
604 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
605
606 // Remove all but the main thread here. Linux fork creates a new process
607 // which only copies the main thread.
Pavel Labatha6321a82017-01-19 15:26:04 +0000608 LLDB_LOG(log, "exec received, stop tracking all but main thread");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000609
Pavel Labatha5be48b2017-10-17 15:52:16 +0000610 for (auto i = m_threads.begin(); i != m_threads.end();) {
611 if ((*i)->GetID() == GetID())
612 i = m_threads.erase(i);
613 else
614 ++i;
Todd Fialaa9882ce2014-08-28 15:46:54 +0000615 }
Pavel Labatha5be48b2017-10-17 15:52:16 +0000616 assert(m_threads.size() == 1);
617 auto *main_thread = static_cast<NativeThreadLinux *>(m_threads[0].get());
Todd Fialaaf245d12014-06-30 21:05:18 +0000618
Pavel Labatha5be48b2017-10-17 15:52:16 +0000619 SetCurrentThreadID(main_thread->GetID());
620 main_thread->SetStoppedByExec();
Todd Fialaaf245d12014-06-30 21:05:18 +0000621
Kate Stoneb9c1b512016-09-06 20:57:50 +0000622 // Tell coordinator about about the "new" (since exec) stopped main thread.
Pavel Labatha5be48b2017-10-17 15:52:16 +0000623 ThreadWasCreated(*main_thread);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000624
Kate Stoneb9c1b512016-09-06 20:57:50 +0000625 // Let our delegate know we have just exec'd.
626 NotifyDidExec();
627
Kate Stoneb9c1b512016-09-06 20:57:50 +0000628 // Let the process know we're stopped.
Pavel Labatha5be48b2017-10-17 15:52:16 +0000629 StopRunningThreads(main_thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000630
631 break;
632 }
633
634 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): {
Adrian Prantl05097242018-04-30 16:49:04 +0000635 // The inferior process or one of its threads is about to exit. We don't
636 // want to do anything with the thread so we just resume it. In case we
637 // want to implement "break on thread exit" functionality, we would need to
638 // stop here.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000639
640 unsigned long data = 0;
641 if (GetEventMessage(thread.GetID(), &data).Fail())
642 data = -1;
643
Pavel Labatha6321a82017-01-19 15:26:04 +0000644 LLDB_LOG(log,
645 "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
646 "WIFSIGNALED={2}, pid = {3}, main_thread = {4}",
647 data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(),
648 is_main_thread);
Todd Fialaaf245d12014-06-30 21:05:18 +0000649
Kate Stoneb9c1b512016-09-06 20:57:50 +0000650
651 StateType state = thread.GetState();
652 if (!StateIsRunningState(state)) {
653 // Due to a kernel bug, we may sometimes get this stop after the inferior
Pavel Labathd8b3c1a2017-12-18 09:44:29 +0000654 // gets a SIGKILL. This confuses our state tracking logic in
655 // ResumeThread(), since normally, we should not be receiving any ptrace
Adrian Prantl05097242018-04-30 16:49:04 +0000656 // events while the inferior is stopped. This makes sure that the
657 // inferior is resumed and exits normally.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000658 state = eStateRunning;
659 }
660 ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
661
662 break;
663 }
664
665 case 0:
666 case TRAP_TRACE: // We receive this on single stepping.
667 case TRAP_HWBKPT: // We receive this on watchpoint hit
668 {
669 // If a watchpoint was hit, report it
670 uint32_t wp_index;
Pavel Labathd37349f2017-11-10 11:05:49 +0000671 Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000672 wp_index, (uintptr_t)info.si_addr);
Pavel Labatha6321a82017-01-19 15:26:04 +0000673 if (error.Fail())
674 LLDB_LOG(log,
675 "received error while checking for watchpoint hits, pid = "
676 "{0}, error = {1}",
677 thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000678 if (wp_index != LLDB_INVALID_INDEX32) {
679 MonitorWatchpoint(thread, wp_index);
680 break;
681 }
682
Omair Javaidd5ffbad2017-02-24 13:27:31 +0000683 // If a breakpoint was hit, report it
684 uint32_t bp_index;
Pavel Labathd37349f2017-11-10 11:05:49 +0000685 error = thread.GetRegisterContext().GetHardwareBreakHitIndex(
Omair Javaidd5ffbad2017-02-24 13:27:31 +0000686 bp_index, (uintptr_t)info.si_addr);
687 if (error.Fail())
688 LLDB_LOG(log, "received error while checking for hardware "
689 "breakpoint hits, pid = {0}, error = {1}",
690 thread.GetID(), error);
691 if (bp_index != LLDB_INVALID_INDEX32) {
692 MonitorBreakpoint(thread);
693 break;
694 }
695
Kate Stoneb9c1b512016-09-06 20:57:50 +0000696 // Otherwise, report step over
697 MonitorTrace(thread);
698 break;
699 }
700
701 case SI_KERNEL:
Mohit K. Bhakkad35799962015-06-18 04:53:18 +0000702#if defined __mips__
Adrian Prantl05097242018-04-30 16:49:04 +0000703 // For mips there is no special signal for watchpoint So we check for
704 // watchpoint in kernel trap
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000705 {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000706 // If a watchpoint was hit, report it
707 uint32_t wp_index;
Pavel Labathd37349f2017-11-10 11:05:49 +0000708 Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000709 wp_index, LLDB_INVALID_ADDRESS);
Pavel Labatha6321a82017-01-19 15:26:04 +0000710 if (error.Fail())
711 LLDB_LOG(log,
712 "received error while checking for watchpoint hits, pid = "
713 "{0}, error = {1}",
714 thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000715 if (wp_index != LLDB_INVALID_INDEX32) {
716 MonitorWatchpoint(thread, wp_index);
717 break;
718 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000719 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000720// NO BREAK
Mohit K. Bhakkad35799962015-06-18 04:53:18 +0000721#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000722 case TRAP_BRKPT:
723 MonitorBreakpoint(thread);
724 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000725
Kate Stoneb9c1b512016-09-06 20:57:50 +0000726 case SIGTRAP:
727 case (SIGTRAP | 0x80):
Pavel Labatha6321a82017-01-19 15:26:04 +0000728 LLDB_LOG(
729 log,
730 "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",
731 info.si_code, GetID(), thread.GetID());
Chaoren Linfa03ad22015-02-03 01:50:42 +0000732
Kate Stoneb9c1b512016-09-06 20:57:50 +0000733 // Ignore these signals until we know more about them.
734 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
735 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000736
Kate Stoneb9c1b512016-09-06 20:57:50 +0000737 default:
Pavel Labath21a365b2017-07-11 10:38:40 +0000738 LLDB_LOG(log, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}",
739 info.si_code, GetID(), thread.GetID());
740 MonitorSignal(info, thread, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000741 break;
742 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000743}
744
Kate Stoneb9c1b512016-09-06 20:57:50 +0000745void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000746 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
747 LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000748
Kate Stoneb9c1b512016-09-06 20:57:50 +0000749 // This thread is currently stopped.
750 thread.SetStoppedByTrace();
751
752 StopRunningThreads(thread.GetID());
753}
754
755void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) {
756 Log *log(
757 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
Pavel Labatha6321a82017-01-19 15:26:04 +0000758 LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000759
760 // Mark the thread as stopped at breakpoint.
761 thread.SetStoppedByBreakpoint();
Pavel Labathaef79082018-10-03 12:29:33 +0000762 FixupBreakpointPCAsNeeded(thread);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000763
764 if (m_threads_stepping_with_breakpoint.find(thread.GetID()) !=
765 m_threads_stepping_with_breakpoint.end())
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000766 thread.SetStoppedByTrace();
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000767
Kate Stoneb9c1b512016-09-06 20:57:50 +0000768 StopRunningThreads(thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000769}
770
Kate Stoneb9c1b512016-09-06 20:57:50 +0000771void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread,
772 uint32_t wp_index) {
773 Log *log(
774 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
Pavel Labatha6321a82017-01-19 15:26:04 +0000775 LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}",
776 thread.GetID(), wp_index);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000777
Adrian Prantl05097242018-04-30 16:49:04 +0000778 // Mark the thread as stopped at watchpoint. The address is at
779 // (lldb::addr_t)info->si_addr if we need it.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000780 thread.SetStoppedByWatchpoint(wp_index);
781
782 // We need to tell all other running threads before we notify the delegate
783 // about this stop.
784 StopRunningThreads(thread.GetID());
785}
786
787void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
788 NativeThreadLinux &thread, bool exited) {
789 const int signo = info.si_signo;
790 const bool is_from_llgs = info.si_pid == getpid();
791
Pavel Labatha6321a82017-01-19 15:26:04 +0000792 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000793
794 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
Adrian Prantl05097242018-04-30 16:49:04 +0000795 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a kill(2)
796 // or raise(3). Similarly for tgkill(2) on Linux.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000797 //
798 // IOW, user generated signals never generate what we consider to be a
799 // "crash".
800 //
801 // Similarly, ACK signals generated by this monitor.
802
803 // Handle the signal.
Pavel Labatha6321a82017-01-19 15:26:04 +0000804 LLDB_LOG(log,
805 "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
806 "waitpid pid = {4})",
807 Host::GetSignalAsCString(signo), signo, info.si_code,
808 thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000809
Kate Stoneb9c1b512016-09-06 20:57:50 +0000810 // Check for thread stop notification.
811 if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) {
812 // This is a tgkill()-based stop.
Pavel Labatha6321a82017-01-19 15:26:04 +0000813 LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000814
Adrian Prantl05097242018-04-30 16:49:04 +0000815 // Check that we're not already marked with a stop reason. Note this thread
816 // really shouldn't already be marked as stopped - if we were, that would
817 // imply that the kernel signaled us with the thread stopping which we
818 // handled and marked as stopped, and that, without an intervening resume,
819 // we received another stop. It is more likely that we are missing the
820 // marking of a run state somewhere if we find that the thread was marked
821 // as stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000822 const StateType thread_state = thread.GetState();
823 if (!StateIsStoppedState(thread_state, false)) {
824 // An inferior thread has stopped because of a SIGSTOP we have sent it.
825 // Generally, these are not important stops and we don't want to report
Pavel Labatha6321a82017-01-19 15:26:04 +0000826 // them as they are just used to stop other threads when one thread (the
827 // one with the *real* stop reason) hits a breakpoint (watchpoint,
Adrian Prantl05097242018-04-30 16:49:04 +0000828 // etc...). However, in the case of an asynchronous Interrupt(), this
829 // *is* the real stop reason, so we leave the signal intact if this is
830 // the thread that was chosen as the triggering thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000831 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
832 if (m_pending_notification_tid == thread.GetID())
833 thread.SetStoppedBySignal(SIGSTOP, &info);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000834 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000835 thread.SetStoppedWithNoReason();
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000836
Kate Stoneb9c1b512016-09-06 20:57:50 +0000837 SetCurrentThreadID(thread.GetID());
838 SignalIfAllThreadsStopped();
839 } else {
840 // We can end up here if stop was initiated by LLGS but by this time a
841 // thread stop has occurred - maybe initiated by another event.
Zachary Turner97206d52017-05-12 04:51:55 +0000842 Status error = ResumeThread(thread, thread.GetState(), 0);
Pavel Labatha6321a82017-01-19 15:26:04 +0000843 if (error.Fail())
844 LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(),
845 error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000846 }
847 } else {
Pavel Labatha6321a82017-01-19 15:26:04 +0000848 LLDB_LOG(log,
849 "pid {0} tid {1}, thread was already marked as a stopped "
850 "state (state={2}), leaving stop signal as is",
Pavel Labath8198db32017-01-24 11:48:25 +0000851 GetID(), thread.GetID(), thread_state);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000852 SignalIfAllThreadsStopped();
Todd Fialaaf245d12014-06-30 21:05:18 +0000853 }
854
Kate Stoneb9c1b512016-09-06 20:57:50 +0000855 // Done handling.
856 return;
857 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000858
Adrian Prantl05097242018-04-30 16:49:04 +0000859 // Check if debugger should stop at this signal or just ignore it and resume
860 // the inferior.
Pavel Labath4a705e72017-02-24 09:29:14 +0000861 if (m_signals_to_ignore.find(signo) != m_signals_to_ignore.end()) {
862 ResumeThread(thread, thread.GetState(), signo);
863 return;
864 }
865
Kate Stoneb9c1b512016-09-06 20:57:50 +0000866 // This thread is stopped.
Pavel Labatha6321a82017-01-19 15:26:04 +0000867 LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000868 thread.SetStoppedBySignal(signo, &info);
869
870 // Send a stop to the debugger after we get all other threads to stop.
871 StopRunningThreads(thread.GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000872}
873
Tamas Berghammere7708682015-04-22 10:00:23 +0000874namespace {
875
Kate Stoneb9c1b512016-09-06 20:57:50 +0000876struct EmulatorBaton {
Pavel Labathd37349f2017-11-10 11:05:49 +0000877 NativeProcessLinux &m_process;
878 NativeRegisterContext &m_reg_context;
Tamas Berghammere7708682015-04-22 10:00:23 +0000879
Kate Stoneb9c1b512016-09-06 20:57:50 +0000880 // eRegisterKindDWARF -> RegsiterValue
881 std::unordered_map<uint32_t, RegisterValue> m_register_values;
Pavel Labath6648fcc2015-04-27 09:21:14 +0000882
Pavel Labathd37349f2017-11-10 11:05:49 +0000883 EmulatorBaton(NativeProcessLinux &process, NativeRegisterContext &reg_context)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000884 : m_process(process), m_reg_context(reg_context) {}
Tamas Berghammere7708682015-04-22 10:00:23 +0000885};
886
887} // anonymous namespace
888
Kate Stoneb9c1b512016-09-06 20:57:50 +0000889static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
890 const EmulateInstruction::Context &context,
891 lldb::addr_t addr, void *dst, size_t length) {
892 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
Tamas Berghammere7708682015-04-22 10:00:23 +0000893
Kate Stoneb9c1b512016-09-06 20:57:50 +0000894 size_t bytes_read;
Pavel Labathd37349f2017-11-10 11:05:49 +0000895 emulator_baton->m_process.ReadMemory(addr, dst, length, bytes_read);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000896 return bytes_read;
Tamas Berghammere7708682015-04-22 10:00:23 +0000897}
898
Kate Stoneb9c1b512016-09-06 20:57:50 +0000899static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
900 const RegisterInfo *reg_info,
901 RegisterValue &reg_value) {
902 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
Tamas Berghammere7708682015-04-22 10:00:23 +0000903
Kate Stoneb9c1b512016-09-06 20:57:50 +0000904 auto it = emulator_baton->m_register_values.find(
905 reg_info->kinds[eRegisterKindDWARF]);
906 if (it != emulator_baton->m_register_values.end()) {
907 reg_value = it->second;
908 return true;
909 }
910
Adrian Prantl05097242018-04-30 16:49:04 +0000911 // The emulator only fill in the dwarf regsiter numbers (and in some case the
912 // generic register numbers). Get the full register info from the register
913 // context based on the dwarf register numbers.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000914 const RegisterInfo *full_reg_info =
Pavel Labathd37349f2017-11-10 11:05:49 +0000915 emulator_baton->m_reg_context.GetRegisterInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000916 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
917
Zachary Turner97206d52017-05-12 04:51:55 +0000918 Status error =
Pavel Labathd37349f2017-11-10 11:05:49 +0000919 emulator_baton->m_reg_context.ReadRegister(full_reg_info, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000920 if (error.Success())
921 return true;
922
923 return false;
924}
925
926static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
927 const EmulateInstruction::Context &context,
928 const RegisterInfo *reg_info,
929 const RegisterValue &reg_value) {
930 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
931 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
932 reg_value;
933 return true;
934}
935
936static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
937 const EmulateInstruction::Context &context,
938 lldb::addr_t addr, const void *dst,
939 size_t length) {
940 return length;
941}
942
Pavel Labathd37349f2017-11-10 11:05:49 +0000943static lldb::addr_t ReadFlags(NativeRegisterContext &regsiter_context) {
944 const RegisterInfo *flags_info = regsiter_context.GetRegisterInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000945 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
Pavel Labathd37349f2017-11-10 11:05:49 +0000946 return regsiter_context.ReadRegisterAsUnsigned(flags_info,
947 LLDB_INVALID_ADDRESS);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000948}
949
Zachary Turner97206d52017-05-12 04:51:55 +0000950Status
951NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadLinux &thread) {
952 Status error;
Pavel Labathd37349f2017-11-10 11:05:49 +0000953 NativeRegisterContext& register_context = thread.GetRegisterContext();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000954
955 std::unique_ptr<EmulateInstruction> emulator_ap(
956 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying,
957 nullptr));
958
959 if (emulator_ap == nullptr)
Zachary Turner97206d52017-05-12 04:51:55 +0000960 return Status("Instruction emulator not found!");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000961
Pavel Labathd37349f2017-11-10 11:05:49 +0000962 EmulatorBaton baton(*this, register_context);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000963 emulator_ap->SetBaton(&baton);
964 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
965 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
966 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
967 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
968
969 if (!emulator_ap->ReadInstruction())
Zachary Turner97206d52017-05-12 04:51:55 +0000970 return Status("Read instruction failed!");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000971
972 bool emulation_result =
973 emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
974
Pavel Labathd37349f2017-11-10 11:05:49 +0000975 const RegisterInfo *reg_info_pc = register_context.GetRegisterInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000976 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
Pavel Labathd37349f2017-11-10 11:05:49 +0000977 const RegisterInfo *reg_info_flags = register_context.GetRegisterInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000978 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
979
980 auto pc_it =
981 baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
982 auto flags_it =
983 baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
984
985 lldb::addr_t next_pc;
986 lldb::addr_t next_flags;
987 if (emulation_result) {
988 assert(pc_it != baton.m_register_values.end() &&
989 "Emulation was successfull but PC wasn't updated");
990 next_pc = pc_it->second.GetAsUInt64();
991
992 if (flags_it != baton.m_register_values.end())
993 next_flags = flags_it->second.GetAsUInt64();
994 else
Pavel Labathd37349f2017-11-10 11:05:49 +0000995 next_flags = ReadFlags(register_context);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000996 } else if (pc_it == baton.m_register_values.end()) {
Adrian Prantl05097242018-04-30 16:49:04 +0000997 // Emulate instruction failed and it haven't changed PC. Advance PC with
998 // the size of the current opcode because the emulation of all
Kate Stoneb9c1b512016-09-06 20:57:50 +0000999 // PC modifying instruction should be successful. The failure most
1000 // likely caused by a not supported instruction which don't modify PC.
Pavel Labathd37349f2017-11-10 11:05:49 +00001001 next_pc = register_context.GetPC() + emulator_ap->GetOpcode().GetByteSize();
1002 next_flags = ReadFlags(register_context);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001003 } else {
1004 // The instruction emulation failed after it modified the PC. It is an
1005 // unknown error where we can't continue because the next instruction is
1006 // modifying the PC but we don't know how.
Zachary Turner97206d52017-05-12 04:51:55 +00001007 return Status("Instruction emulation failed unexpectedly.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001008 }
1009
1010 if (m_arch.GetMachine() == llvm::Triple::arm) {
1011 if (next_flags & 0x20) {
1012 // Thumb mode
1013 error = SetSoftwareBreakpoint(next_pc, 2);
1014 } else {
1015 // Arm mode
1016 error = SetSoftwareBreakpoint(next_pc, 4);
Pavel Labath6648fcc2015-04-27 09:21:14 +00001017 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001018 } else if (m_arch.GetMachine() == llvm::Triple::mips64 ||
1019 m_arch.GetMachine() == llvm::Triple::mips64el ||
1020 m_arch.GetMachine() == llvm::Triple::mips ||
Eugene Zemtsovaae0a752017-10-05 19:44:05 +00001021 m_arch.GetMachine() == llvm::Triple::mipsel ||
1022 m_arch.GetMachine() == llvm::Triple::ppc64le)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001023 error = SetSoftwareBreakpoint(next_pc, 4);
1024 else {
1025 // No size hint is given for the next breakpoint
1026 error = SetSoftwareBreakpoint(next_pc, 0);
1027 }
Pavel Labath6648fcc2015-04-27 09:21:14 +00001028
Adrian Prantl05097242018-04-30 16:49:04 +00001029 // If setting the breakpoint fails because next_pc is out of the address
1030 // space, ignore it and let the debugee segfault.
Pavel Labath42eb6902016-10-26 11:13:56 +00001031 if (error.GetError() == EIO || error.GetError() == EFAULT) {
Zachary Turner97206d52017-05-12 04:51:55 +00001032 return Status();
Pavel Labath42eb6902016-10-26 11:13:56 +00001033 } else if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001034 return error;
Tamas Berghammere7708682015-04-22 10:00:23 +00001035
Kate Stoneb9c1b512016-09-06 20:57:50 +00001036 m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001037
Zachary Turner97206d52017-05-12 04:51:55 +00001038 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001039}
1040
1041bool NativeProcessLinux::SupportHardwareSingleStepping() const {
1042 if (m_arch.GetMachine() == llvm::Triple::arm ||
1043 m_arch.GetMachine() == llvm::Triple::mips64 ||
1044 m_arch.GetMachine() == llvm::Triple::mips64el ||
1045 m_arch.GetMachine() == llvm::Triple::mips ||
1046 m_arch.GetMachine() == llvm::Triple::mipsel)
Pavel Labath6648fcc2015-04-27 09:21:14 +00001047 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001048 return true;
Tamas Berghammere7708682015-04-22 10:00:23 +00001049}
1050
Zachary Turner97206d52017-05-12 04:51:55 +00001051Status NativeProcessLinux::Resume(const ResumeActionList &resume_actions) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001052 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1053 LLDB_LOG(log, "pid {0}", GetID());
Tamas Berghammere7708682015-04-22 10:00:23 +00001054
Kate Stoneb9c1b512016-09-06 20:57:50 +00001055 bool software_single_step = !SupportHardwareSingleStepping();
Tamas Berghammere7708682015-04-22 10:00:23 +00001056
Kate Stoneb9c1b512016-09-06 20:57:50 +00001057 if (software_single_step) {
Pavel Labatha5be48b2017-10-17 15:52:16 +00001058 for (const auto &thread : m_threads) {
1059 assert(thread && "thread list should not contain NULL threads");
Tamas Berghammere7708682015-04-22 10:00:23 +00001060
Kate Stoneb9c1b512016-09-06 20:57:50 +00001061 const ResumeAction *const action =
Pavel Labatha5be48b2017-10-17 15:52:16 +00001062 resume_actions.GetActionForThread(thread->GetID(), true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001063 if (action == nullptr)
1064 continue;
Tamas Berghammere7708682015-04-22 10:00:23 +00001065
Kate Stoneb9c1b512016-09-06 20:57:50 +00001066 if (action->state == eStateStepping) {
Zachary Turner97206d52017-05-12 04:51:55 +00001067 Status error = SetupSoftwareSingleStepping(
Pavel Labatha5be48b2017-10-17 15:52:16 +00001068 static_cast<NativeThreadLinux &>(*thread));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001069 if (error.Fail())
1070 return error;
1071 }
Tamas Berghammere7708682015-04-22 10:00:23 +00001072 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001073 }
1074
Pavel Labatha5be48b2017-10-17 15:52:16 +00001075 for (const auto &thread : m_threads) {
1076 assert(thread && "thread list should not contain NULL threads");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001077
1078 const ResumeAction *const action =
Pavel Labatha5be48b2017-10-17 15:52:16 +00001079 resume_actions.GetActionForThread(thread->GetID(), true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001080
1081 if (action == nullptr) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001082 LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
Pavel Labatha5be48b2017-10-17 15:52:16 +00001083 thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001084 continue;
Tamas Berghammere7708682015-04-22 10:00:23 +00001085 }
1086
Pavel Labatha6321a82017-01-19 15:26:04 +00001087 LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}",
Pavel Labatha5be48b2017-10-17 15:52:16 +00001088 action->state, GetID(), thread->GetID());
Tamas Berghammere7708682015-04-22 10:00:23 +00001089
Kate Stoneb9c1b512016-09-06 20:57:50 +00001090 switch (action->state) {
1091 case eStateRunning:
1092 case eStateStepping: {
1093 // Run the thread, possibly feeding it the signal.
1094 const int signo = action->signal;
Pavel Labatha5be48b2017-10-17 15:52:16 +00001095 ResumeThread(static_cast<NativeThreadLinux &>(*thread), action->state,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001096 signo);
1097 break;
1098 }
Tamas Berghammere7708682015-04-22 10:00:23 +00001099
Kate Stoneb9c1b512016-09-06 20:57:50 +00001100 case eStateSuspended:
1101 case eStateStopped:
Pavel Labatha6321a82017-01-19 15:26:04 +00001102 llvm_unreachable("Unexpected state");
Tamas Berghammere7708682015-04-22 10:00:23 +00001103
Kate Stoneb9c1b512016-09-06 20:57:50 +00001104 default:
Zachary Turner97206d52017-05-12 04:51:55 +00001105 return Status("NativeProcessLinux::%s (): unexpected state %s specified "
1106 "for pid %" PRIu64 ", tid %" PRIu64,
1107 __FUNCTION__, StateAsCString(action->state), GetID(),
Pavel Labatha5be48b2017-10-17 15:52:16 +00001108 thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001109 }
1110 }
1111
Zachary Turner97206d52017-05-12 04:51:55 +00001112 return Status();
Tamas Berghammere7708682015-04-22 10:00:23 +00001113}
1114
Zachary Turner97206d52017-05-12 04:51:55 +00001115Status NativeProcessLinux::Halt() {
1116 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001117
1118 if (kill(GetID(), SIGSTOP) != 0)
1119 error.SetErrorToErrno();
1120
1121 return error;
Tamas Berghammere7708682015-04-22 10:00:23 +00001122}
1123
Zachary Turner97206d52017-05-12 04:51:55 +00001124Status NativeProcessLinux::Detach() {
1125 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001126
1127 // Stop monitoring the inferior.
1128 m_sigchld_handle.reset();
1129
1130 // Tell ptrace to detach from the process.
1131 if (GetID() == LLDB_INVALID_PROCESS_ID)
1132 return error;
1133
Pavel Labatha5be48b2017-10-17 15:52:16 +00001134 for (const auto &thread : m_threads) {
1135 Status e = Detach(thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001136 if (e.Fail())
1137 error =
1138 e; // Save the error, but still attempt to detach from other threads.
1139 }
1140
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001141 m_processor_trace_monitor.clear();
1142 m_pt_proces_trace_id = LLDB_INVALID_UID;
1143
Kate Stoneb9c1b512016-09-06 20:57:50 +00001144 return error;
1145}
1146
Zachary Turner97206d52017-05-12 04:51:55 +00001147Status NativeProcessLinux::Signal(int signo) {
1148 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001149
Pavel Labatha6321a82017-01-19 15:26:04 +00001150 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1151 LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo,
1152 Host::GetSignalAsCString(signo), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001153
1154 if (kill(GetID(), signo))
1155 error.SetErrorToErrno();
1156
1157 return error;
1158}
1159
Zachary Turner97206d52017-05-12 04:51:55 +00001160Status NativeProcessLinux::Interrupt() {
Adrian Prantl05097242018-04-30 16:49:04 +00001161 // Pick a running thread (or if none, a not-dead stopped thread) as the
1162 // chosen thread that will be the stop-reason thread.
Pavel Labatha6321a82017-01-19 15:26:04 +00001163 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001164
Pavel Labatha5be48b2017-10-17 15:52:16 +00001165 NativeThreadProtocol *running_thread = nullptr;
1166 NativeThreadProtocol *stopped_thread = nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001167
Pavel Labatha6321a82017-01-19 15:26:04 +00001168 LLDB_LOG(log, "selecting running thread for interrupt target");
Pavel Labatha5be48b2017-10-17 15:52:16 +00001169 for (const auto &thread : m_threads) {
Adrian Prantl05097242018-04-30 16:49:04 +00001170 // If we have a running or stepping thread, we'll call that the target of
1171 // the interrupt.
Pavel Labatha5be48b2017-10-17 15:52:16 +00001172 const auto thread_state = thread->GetState();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001173 if (thread_state == eStateRunning || thread_state == eStateStepping) {
Pavel Labatha5be48b2017-10-17 15:52:16 +00001174 running_thread = thread.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001175 break;
Pavel Labatha5be48b2017-10-17 15:52:16 +00001176 } else if (!stopped_thread && StateIsStoppedState(thread_state, true)) {
Adrian Prantl05097242018-04-30 16:49:04 +00001177 // Remember the first non-dead stopped thread. We'll use that as a
1178 // backup if there are no running threads.
Pavel Labatha5be48b2017-10-17 15:52:16 +00001179 stopped_thread = thread.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001180 }
1181 }
1182
Pavel Labatha5be48b2017-10-17 15:52:16 +00001183 if (!running_thread && !stopped_thread) {
Zachary Turner97206d52017-05-12 04:51:55 +00001184 Status error("found no running/stepping or live stopped threads as target "
1185 "for interrupt");
Pavel Labatha6321a82017-01-19 15:26:04 +00001186 LLDB_LOG(log, "skipping due to error: {0}", error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001187
1188 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001189 }
1190
Pavel Labatha5be48b2017-10-17 15:52:16 +00001191 NativeThreadProtocol *deferred_signal_thread =
1192 running_thread ? running_thread : stopped_thread;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001193
Pavel Labatha6321a82017-01-19 15:26:04 +00001194 LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(),
Pavel Labatha5be48b2017-10-17 15:52:16 +00001195 running_thread ? "running" : "stopped",
1196 deferred_signal_thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001197
Pavel Labatha5be48b2017-10-17 15:52:16 +00001198 StopRunningThreads(deferred_signal_thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001199
Zachary Turner97206d52017-05-12 04:51:55 +00001200 return Status();
Todd Fialaaf245d12014-06-30 21:05:18 +00001201}
1202
Zachary Turner97206d52017-05-12 04:51:55 +00001203Status NativeProcessLinux::Kill() {
Pavel Labatha6321a82017-01-19 15:26:04 +00001204 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1205 LLDB_LOG(log, "pid {0}", GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +00001206
Zachary Turner97206d52017-05-12 04:51:55 +00001207 Status error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001208
Kate Stoneb9c1b512016-09-06 20:57:50 +00001209 switch (m_state) {
1210 case StateType::eStateInvalid:
1211 case StateType::eStateExited:
1212 case StateType::eStateCrashed:
1213 case StateType::eStateDetached:
1214 case StateType::eStateUnloaded:
1215 // Nothing to do - the process is already dead.
Pavel Labatha6321a82017-01-19 15:26:04 +00001216 LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
Pavel Labath8198db32017-01-24 11:48:25 +00001217 m_state);
Todd Fialaaf245d12014-06-30 21:05:18 +00001218 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001219
Kate Stoneb9c1b512016-09-06 20:57:50 +00001220 case StateType::eStateConnected:
1221 case StateType::eStateAttaching:
1222 case StateType::eStateLaunching:
1223 case StateType::eStateStopped:
1224 case StateType::eStateRunning:
1225 case StateType::eStateStepping:
1226 case StateType::eStateSuspended:
1227 // We can try to kill a process in these states.
1228 break;
1229 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001230
Kate Stoneb9c1b512016-09-06 20:57:50 +00001231 if (kill(GetID(), SIGKILL) != 0) {
1232 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +00001233 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001234 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001235
Kate Stoneb9c1b512016-09-06 20:57:50 +00001236 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001237}
1238
Zachary Turner97206d52017-05-12 04:51:55 +00001239static Status
Pavel Labath15930862017-03-21 13:49:45 +00001240ParseMemoryRegionInfoFromProcMapsLine(llvm::StringRef &maps_line,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001241 MemoryRegionInfo &memory_region_info) {
1242 memory_region_info.Clear();
Todd Fialaaf245d12014-06-30 21:05:18 +00001243
Pavel Labath15930862017-03-21 13:49:45 +00001244 StringExtractor line_extractor(maps_line);
Todd Fialaaf245d12014-06-30 21:05:18 +00001245
Kate Stoneb9c1b512016-09-06 20:57:50 +00001246 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode
Adrian Prantl05097242018-04-30 16:49:04 +00001247 // pathname perms: rwxp (letter is present if set, '-' if not, final
1248 // character is p=private, s=shared).
Todd Fialaaf245d12014-06-30 21:05:18 +00001249
Kate Stoneb9c1b512016-09-06 20:57:50 +00001250 // Parse out the starting address
1251 lldb::addr_t start_address = line_extractor.GetHexMaxU64(false, 0);
Todd Fialaaf245d12014-06-30 21:05:18 +00001252
Kate Stoneb9c1b512016-09-06 20:57:50 +00001253 // Parse out hyphen separating start and end address from range.
1254 if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != '-'))
Zachary Turner97206d52017-05-12 04:51:55 +00001255 return Status(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001256 "malformed /proc/{pid}/maps entry, missing dash between address range");
Todd Fialaaf245d12014-06-30 21:05:18 +00001257
Kate Stoneb9c1b512016-09-06 20:57:50 +00001258 // Parse out the ending address
1259 lldb::addr_t end_address = line_extractor.GetHexMaxU64(false, start_address);
Todd Fialaaf245d12014-06-30 21:05:18 +00001260
Kate Stoneb9c1b512016-09-06 20:57:50 +00001261 // Parse out the space after the address.
1262 if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != ' '))
Zachary Turner97206d52017-05-12 04:51:55 +00001263 return Status(
1264 "malformed /proc/{pid}/maps entry, missing space after range");
Todd Fialaaf245d12014-06-30 21:05:18 +00001265
Kate Stoneb9c1b512016-09-06 20:57:50 +00001266 // Save the range.
1267 memory_region_info.GetRange().SetRangeBase(start_address);
1268 memory_region_info.GetRange().SetRangeEnd(end_address);
Todd Fialaaf245d12014-06-30 21:05:18 +00001269
Kate Stoneb9c1b512016-09-06 20:57:50 +00001270 // Any memory region in /proc/{pid}/maps is by definition mapped into the
1271 // process.
1272 memory_region_info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
Howard Hellyerad007562016-07-07 08:21:28 +00001273
Kate Stoneb9c1b512016-09-06 20:57:50 +00001274 // Parse out each permission entry.
1275 if (line_extractor.GetBytesLeft() < 4)
Zachary Turner97206d52017-05-12 04:51:55 +00001276 return Status("malformed /proc/{pid}/maps entry, missing some portion of "
1277 "permissions");
Todd Fialaaf245d12014-06-30 21:05:18 +00001278
Kate Stoneb9c1b512016-09-06 20:57:50 +00001279 // Handle read permission.
1280 const char read_perm_char = line_extractor.GetChar();
1281 if (read_perm_char == 'r')
1282 memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eYes);
1283 else if (read_perm_char == '-')
1284 memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1285 else
Zachary Turner97206d52017-05-12 04:51:55 +00001286 return Status("unexpected /proc/{pid}/maps read permission char");
Todd Fialaaf245d12014-06-30 21:05:18 +00001287
Kate Stoneb9c1b512016-09-06 20:57:50 +00001288 // Handle write permission.
1289 const char write_perm_char = line_extractor.GetChar();
1290 if (write_perm_char == 'w')
1291 memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eYes);
1292 else if (write_perm_char == '-')
1293 memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1294 else
Zachary Turner97206d52017-05-12 04:51:55 +00001295 return Status("unexpected /proc/{pid}/maps write permission char");
Todd Fialaaf245d12014-06-30 21:05:18 +00001296
Kate Stoneb9c1b512016-09-06 20:57:50 +00001297 // Handle execute permission.
1298 const char exec_perm_char = line_extractor.GetChar();
1299 if (exec_perm_char == 'x')
1300 memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes);
1301 else if (exec_perm_char == '-')
1302 memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1303 else
Zachary Turner97206d52017-05-12 04:51:55 +00001304 return Status("unexpected /proc/{pid}/maps exec permission char");
Todd Fialaaf245d12014-06-30 21:05:18 +00001305
Kate Stoneb9c1b512016-09-06 20:57:50 +00001306 line_extractor.GetChar(); // Read the private bit
1307 line_extractor.SkipSpaces(); // Skip the separator
1308 line_extractor.GetHexMaxU64(false, 0); // Read the offset
1309 line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1310 line_extractor.GetChar(); // Read the device id separator
1311 line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1312 line_extractor.SkipSpaces(); // Skip the separator
1313 line_extractor.GetU64(0, 10); // Read the inode number
Tamas Berghammerd7d69f82016-07-22 12:55:35 +00001314
Kate Stoneb9c1b512016-09-06 20:57:50 +00001315 line_extractor.SkipSpaces();
1316 const char *name = line_extractor.Peek();
1317 if (name)
1318 memory_region_info.SetName(name);
Tamas Berghammerd7d69f82016-07-22 12:55:35 +00001319
Zachary Turner97206d52017-05-12 04:51:55 +00001320 return Status();
Todd Fialaaf245d12014-06-30 21:05:18 +00001321}
1322
Zachary Turner97206d52017-05-12 04:51:55 +00001323Status NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr,
1324 MemoryRegionInfo &range_info) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001325 // FIXME review that the final memory region returned extends to the end of
1326 // the virtual address space,
1327 // with no perms if it is not mapped.
Todd Fialaaf245d12014-06-30 21:05:18 +00001328
Adrian Prantl05097242018-04-30 16:49:04 +00001329 // Use an approach that reads memory regions from /proc/{pid}/maps. Assume
1330 // proc maps entries are in ascending order.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001331 // FIXME assert if we find differently.
Todd Fialaaf245d12014-06-30 21:05:18 +00001332
Kate Stoneb9c1b512016-09-06 20:57:50 +00001333 if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
1334 // We're done.
Zachary Turner97206d52017-05-12 04:51:55 +00001335 return Status("unsupported");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001336 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001337
Zachary Turner97206d52017-05-12 04:51:55 +00001338 Status error = PopulateMemoryRegionCache();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001339 if (error.Fail()) {
1340 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001341 }
1342
1343 lldb::addr_t prev_base_address = 0;
1344
1345 // FIXME start by finding the last region that is <= target address using
1346 // binary search. Data is sorted.
1347 // There can be a ton of regions on pthreads apps with lots of threads.
1348 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1349 ++it) {
Tamas Berghammera6f57952017-01-03 16:29:43 +00001350 MemoryRegionInfo &proc_entry_info = it->first;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001351
1352 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1353 assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
1354 "descending /proc/pid/maps entries detected, unexpected");
1355 prev_base_address = proc_entry_info.GetRange().GetRangeBase();
Hafiz Abid Qadeerb1554312017-01-20 10:24:03 +00001356 UNUSED_IF_ASSERT_DISABLED(prev_base_address);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001357
1358 // If the target address comes before this entry, indicate distance to next
1359 // region.
1360 if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1361 range_info.GetRange().SetRangeBase(load_addr);
1362 range_info.GetRange().SetByteSize(
1363 proc_entry_info.GetRange().GetRangeBase() - load_addr);
1364 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1365 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1366 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1367 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1368
1369 return error;
1370 } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1371 // The target address is within the memory region we're processing here.
1372 range_info = proc_entry_info;
1373 return error;
1374 }
1375
1376 // The target memory address comes somewhere after the region we just
1377 // parsed.
1378 }
1379
1380 // If we made it here, we didn't find an entry that contained the given
Adrian Prantl05097242018-04-30 16:49:04 +00001381 // address. Return the load_addr as start and the amount of bytes betwwen
1382 // load address and the end of the memory as size.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001383 range_info.GetRange().SetRangeBase(load_addr);
1384 range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
1385 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1386 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1387 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1388 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1389 return error;
1390}
1391
Zachary Turner97206d52017-05-12 04:51:55 +00001392Status NativeProcessLinux::PopulateMemoryRegionCache() {
Pavel Labatha6321a82017-01-19 15:26:04 +00001393 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Tamas Berghammera6f57952017-01-03 16:29:43 +00001394
1395 // If our cache is empty, pull the latest. There should always be at least
1396 // one memory region if memory region handling is supported.
1397 if (!m_mem_region_cache.empty()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001398 LLDB_LOG(log, "reusing {0} cached memory region entries",
1399 m_mem_region_cache.size());
Zachary Turner97206d52017-05-12 04:51:55 +00001400 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001401 }
1402
Pavel Labath15930862017-03-21 13:49:45 +00001403 auto BufferOrError = getProcFile(GetID(), "maps");
1404 if (!BufferOrError) {
Tamas Berghammera6f57952017-01-03 16:29:43 +00001405 m_supports_mem_region = LazyBool::eLazyBoolNo;
Pavel Labath15930862017-03-21 13:49:45 +00001406 return BufferOrError.getError();
1407 }
1408 StringRef Rest = BufferOrError.get()->getBuffer();
1409 while (! Rest.empty()) {
1410 StringRef Line;
1411 std::tie(Line, Rest) = Rest.split('\n');
1412 MemoryRegionInfo info;
Zachary Turner97206d52017-05-12 04:51:55 +00001413 const Status parse_error =
1414 ParseMemoryRegionInfoFromProcMapsLine(Line, info);
Pavel Labath15930862017-03-21 13:49:45 +00001415 if (parse_error.Fail()) {
1416 LLDB_LOG(log, "failed to parse proc maps line '{0}': {1}", Line,
1417 parse_error);
1418 m_supports_mem_region = LazyBool::eLazyBoolNo;
1419 return parse_error;
1420 }
1421 m_mem_region_cache.emplace_back(
1422 info, FileSpec(info.GetName().GetCString(), true));
1423 }
1424
1425 if (m_mem_region_cache.empty()) {
Tamas Berghammera6f57952017-01-03 16:29:43 +00001426 // No entries after attempting to read them. This shouldn't happen if
Adrian Prantl05097242018-04-30 16:49:04 +00001427 // /proc/{pid}/maps is supported. Assume we don't support map entries via
1428 // procfs.
Pavel Labath15930862017-03-21 13:49:45 +00001429 m_supports_mem_region = LazyBool::eLazyBoolNo;
Pavel Labatha6321a82017-01-19 15:26:04 +00001430 LLDB_LOG(log,
1431 "failed to find any procfs maps entries, assuming no support "
1432 "for memory region metadata retrieval");
Zachary Turner97206d52017-05-12 04:51:55 +00001433 return Status("not supported");
Tamas Berghammera6f57952017-01-03 16:29:43 +00001434 }
1435
Pavel Labatha6321a82017-01-19 15:26:04 +00001436 LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps",
1437 m_mem_region_cache.size(), GetID());
Tamas Berghammera6f57952017-01-03 16:29:43 +00001438
1439 // We support memory retrieval, remember that.
1440 m_supports_mem_region = LazyBool::eLazyBoolYes;
Zachary Turner97206d52017-05-12 04:51:55 +00001441 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001442}
1443
Kate Stoneb9c1b512016-09-06 20:57:50 +00001444void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001445 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1446 LLDB_LOG(log, "newBumpId={0}", newBumpId);
1447 LLDB_LOG(log, "clearing {0} entries from memory region cache",
1448 m_mem_region_cache.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001449 m_mem_region_cache.clear();
1450}
1451
Zachary Turner97206d52017-05-12 04:51:55 +00001452Status NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions,
1453 lldb::addr_t &addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001454// FIXME implementing this requires the equivalent of
Adrian Prantl05097242018-04-30 16:49:04 +00001455// InferiorCallPOSIX::InferiorCallMmap, which depends on functional ThreadPlans
1456// working with Native*Protocol.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001457#if 1
Zachary Turner97206d52017-05-12 04:51:55 +00001458 return Status("not implemented yet");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001459#else
1460 addr = LLDB_INVALID_ADDRESS;
1461
1462 unsigned prot = 0;
1463 if (permissions & lldb::ePermissionsReadable)
1464 prot |= eMmapProtRead;
1465 if (permissions & lldb::ePermissionsWritable)
1466 prot |= eMmapProtWrite;
1467 if (permissions & lldb::ePermissionsExecutable)
1468 prot |= eMmapProtExec;
1469
1470 // TODO implement this directly in NativeProcessLinux
Adrian Prantl05097242018-04-30 16:49:04 +00001471 // (and lift to NativeProcessPOSIX if/when that class is refactored out).
Kate Stoneb9c1b512016-09-06 20:57:50 +00001472 if (InferiorCallMmap(this, addr, 0, size, prot,
1473 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
1474 m_addr_to_mmap_size[addr] = size;
Zachary Turner97206d52017-05-12 04:51:55 +00001475 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001476 } else {
1477 addr = LLDB_INVALID_ADDRESS;
Zachary Turner97206d52017-05-12 04:51:55 +00001478 return Status("unable to allocate %" PRIu64
1479 " bytes of memory with permissions %s",
1480 size, GetPermissionsAsCString(permissions));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001481 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001482#endif
1483}
1484
Zachary Turner97206d52017-05-12 04:51:55 +00001485Status NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001486 // FIXME see comments in AllocateMemory - required lower-level
1487 // bits not in place yet (ThreadPlans)
Zachary Turner97206d52017-05-12 04:51:55 +00001488 return Status("not implemented");
Todd Fialaaf245d12014-06-30 21:05:18 +00001489}
1490
Kate Stoneb9c1b512016-09-06 20:57:50 +00001491lldb::addr_t NativeProcessLinux::GetSharedLibraryInfoAddress() {
1492 // punt on this for now
1493 return LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00001494}
1495
Kate Stoneb9c1b512016-09-06 20:57:50 +00001496size_t NativeProcessLinux::UpdateThreads() {
Adrian Prantl05097242018-04-30 16:49:04 +00001497 // The NativeProcessLinux monitoring threads are always up to date with
1498 // respect to thread state and they keep the thread list populated properly.
1499 // All this method needs to do is return the thread count.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001500 return m_threads.size();
Todd Fialaaf245d12014-06-30 21:05:18 +00001501}
1502
Zachary Turner97206d52017-05-12 04:51:55 +00001503Status NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,
1504 bool hardware) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001505 if (hardware)
Omair Javaidd5ffbad2017-02-24 13:27:31 +00001506 return SetHardwareBreakpoint(addr, size);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001507 else
1508 return SetSoftwareBreakpoint(addr, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00001509}
1510
Zachary Turner97206d52017-05-12 04:51:55 +00001511Status NativeProcessLinux::RemoveBreakpoint(lldb::addr_t addr, bool hardware) {
Omair Javaidd5ffbad2017-02-24 13:27:31 +00001512 if (hardware)
1513 return RemoveHardwareBreakpoint(addr);
1514 else
1515 return NativeProcessProtocol::RemoveBreakpoint(addr);
1516}
1517
Pavel Labathf8b825f2018-09-09 06:01:12 +00001518llvm::Expected<llvm::ArrayRef<uint8_t>>
1519NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(size_t size_hint) {
Pavel Labath12286a22018-09-08 10:33:14 +00001520 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1521 // linux kernel does otherwise.
Pavel Labathf8b825f2018-09-09 06:01:12 +00001522 static const uint8_t g_arm_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1523 static const uint8_t g_thumb_opcode[] = {0x01, 0xde};
Todd Fialaaf245d12014-06-30 21:05:18 +00001524
Pavel Labathf8b825f2018-09-09 06:01:12 +00001525 switch (GetArchitecture().GetMachine()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001526 case llvm::Triple::arm:
Pavel Labathf8b825f2018-09-09 06:01:12 +00001527 switch (size_hint) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001528 case 2:
Pavel Labath4f545072018-09-09 08:42:00 +00001529 return llvm::makeArrayRef(g_thumb_opcode);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001530 case 4:
Pavel Labath4f545072018-09-09 08:42:00 +00001531 return llvm::makeArrayRef(g_arm_opcode);
Todd Fialaaf245d12014-06-30 21:05:18 +00001532 default:
Pavel Labathf8b825f2018-09-09 06:01:12 +00001533 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1534 "Unrecognised trap opcode size hint!");
Todd Fialaaf245d12014-06-30 21:05:18 +00001535 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001536 default:
Pavel Labathf8b825f2018-09-09 06:01:12 +00001537 return NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_hint);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001538 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001539}
1540
Zachary Turner97206d52017-05-12 04:51:55 +00001541Status NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
1542 size_t &bytes_read) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001543 if (ProcessVmReadvSupported()) {
1544 // The process_vm_readv path is about 50 times faster than ptrace api. We
Adrian Prantl05097242018-04-30 16:49:04 +00001545 // want to use this syscall if it is supported.
Pavel Labathdf7c6992015-06-17 18:38:49 +00001546
Kate Stoneb9c1b512016-09-06 20:57:50 +00001547 const ::pid_t pid = GetID();
Pavel Labathdf7c6992015-06-17 18:38:49 +00001548
Kate Stoneb9c1b512016-09-06 20:57:50 +00001549 struct iovec local_iov, remote_iov;
1550 local_iov.iov_base = buf;
1551 local_iov.iov_len = size;
1552 remote_iov.iov_base = reinterpret_cast<void *>(addr);
1553 remote_iov.iov_len = size;
Pavel Labathdf7c6992015-06-17 18:38:49 +00001554
Kate Stoneb9c1b512016-09-06 20:57:50 +00001555 bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
1556 const bool success = bytes_read == size;
Pavel Labathdf7c6992015-06-17 18:38:49 +00001557
Pavel Labatha6321a82017-01-19 15:26:04 +00001558 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1559 LLDB_LOG(log,
1560 "using process_vm_readv to read {0} bytes from inferior "
1561 "address {1:x}: {2}",
Pavel Labath10c41f32017-06-06 14:06:17 +00001562 size, addr, success ? "Success" : llvm::sys::StrError(errno));
Pavel Labath19cbe962015-07-21 13:20:32 +00001563
Kate Stoneb9c1b512016-09-06 20:57:50 +00001564 if (success)
Zachary Turner97206d52017-05-12 04:51:55 +00001565 return Status();
Pavel Labatha6321a82017-01-19 15:26:04 +00001566 // else the call failed for some reason, let's retry the read using ptrace
1567 // api.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001568 }
Pavel Labath19cbe962015-07-21 13:20:32 +00001569
Kate Stoneb9c1b512016-09-06 20:57:50 +00001570 unsigned char *dst = static_cast<unsigned char *>(buf);
1571 size_t remainder;
1572 long data;
Pavel Labath19cbe962015-07-21 13:20:32 +00001573
Pavel Labatha6321a82017-01-19 15:26:04 +00001574 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1575 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
Pavel Labath19cbe962015-07-21 13:20:32 +00001576
Kate Stoneb9c1b512016-09-06 20:57:50 +00001577 for (bytes_read = 0; bytes_read < size; bytes_read += remainder) {
Zachary Turner97206d52017-05-12 04:51:55 +00001578 Status error = NativeProcessLinux::PtraceWrapper(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001579 PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data);
Pavel Labatha6321a82017-01-19 15:26:04 +00001580 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001581 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001582
1583 remainder = size - bytes_read;
1584 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
1585
1586 // Copy the data into our buffer
1587 memcpy(dst, &data, remainder);
1588
Pavel Labatha6321a82017-01-19 15:26:04 +00001589 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001590 addr += k_ptrace_word_size;
1591 dst += k_ptrace_word_size;
1592 }
Zachary Turner97206d52017-05-12 04:51:55 +00001593 return Status();
Todd Fialaaf245d12014-06-30 21:05:18 +00001594}
1595
Zachary Turner97206d52017-05-12 04:51:55 +00001596Status NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,
1597 size_t size, size_t &bytes_written) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001598 const unsigned char *src = static_cast<const unsigned char *>(buf);
1599 size_t remainder;
Zachary Turner97206d52017-05-12 04:51:55 +00001600 Status error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001601
Pavel Labatha6321a82017-01-19 15:26:04 +00001602 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1603 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00001604
Kate Stoneb9c1b512016-09-06 20:57:50 +00001605 for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
1606 remainder = size - bytes_written;
1607 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
Chaoren Lin97ccc292015-02-03 01:51:12 +00001608
Kate Stoneb9c1b512016-09-06 20:57:50 +00001609 if (remainder == k_ptrace_word_size) {
1610 unsigned long data = 0;
1611 memcpy(&data, src, k_ptrace_word_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00001612
Pavel Labatha6321a82017-01-19 15:26:04 +00001613 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001614 error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(),
1615 (void *)addr, (void *)data);
Pavel Labatha6321a82017-01-19 15:26:04 +00001616 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001617 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001618 } else {
1619 unsigned char buff[8];
1620 size_t bytes_read;
1621 error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
Pavel Labatha6321a82017-01-19 15:26:04 +00001622 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001623 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001624
1625 memcpy(buff, src, remainder);
1626
1627 size_t bytes_written_rec;
1628 error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
Pavel Labatha6321a82017-01-19 15:26:04 +00001629 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001630 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001631
Pavel Labatha6321a82017-01-19 15:26:04 +00001632 LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src,
1633 *(unsigned long *)buff);
Todd Fialaaf245d12014-06-30 21:05:18 +00001634 }
1635
Kate Stoneb9c1b512016-09-06 20:57:50 +00001636 addr += k_ptrace_word_size;
1637 src += k_ptrace_word_size;
1638 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001639 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001640}
1641
Zachary Turner97206d52017-05-12 04:51:55 +00001642Status NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001643 return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
1644}
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001645
Zachary Turner97206d52017-05-12 04:51:55 +00001646Status NativeProcessLinux::GetEventMessage(lldb::tid_t tid,
1647 unsigned long *message) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001648 return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
1649}
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001650
Zachary Turner97206d52017-05-12 04:51:55 +00001651Status NativeProcessLinux::Detach(lldb::tid_t tid) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001652 if (tid == LLDB_INVALID_THREAD_ID)
Zachary Turner97206d52017-05-12 04:51:55 +00001653 return Status();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001654
Kate Stoneb9c1b512016-09-06 20:57:50 +00001655 return PtraceWrapper(PTRACE_DETACH, tid);
1656}
1657
1658bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {
Pavel Labatha5be48b2017-10-17 15:52:16 +00001659 for (const auto &thread : m_threads) {
1660 assert(thread && "thread list should not contain NULL threads");
1661 if (thread->GetID() == thread_id) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001662 // We have this thread.
1663 return true;
Todd Fialaaf245d12014-06-30 21:05:18 +00001664 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001665 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001666
Kate Stoneb9c1b512016-09-06 20:57:50 +00001667 // We don't have this thread.
1668 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001669}
1670
Kate Stoneb9c1b512016-09-06 20:57:50 +00001671bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001672 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1673 LLDB_LOG(log, "tid: {0})", thread_id);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001674
1675 bool found = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001676 for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
1677 if (*it && ((*it)->GetID() == thread_id)) {
1678 m_threads.erase(it);
1679 found = true;
1680 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00001681 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001682 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001683
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001684 if (found)
1685 StopTracingForThread(thread_id);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001686 SignalIfAllThreadsStopped();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001687 return found;
Todd Fialaaf245d12014-06-30 21:05:18 +00001688}
1689
Pavel Labatha5be48b2017-10-17 15:52:16 +00001690NativeThreadLinux &NativeProcessLinux::AddThread(lldb::tid_t thread_id) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001691 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
1692 LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
Todd Fialaaf245d12014-06-30 21:05:18 +00001693
Kate Stoneb9c1b512016-09-06 20:57:50 +00001694 assert(!HasThreadNoLock(thread_id) &&
1695 "attempted to add a thread by id that already exists");
Todd Fialaaf245d12014-06-30 21:05:18 +00001696
Kate Stoneb9c1b512016-09-06 20:57:50 +00001697 // If this is the first thread, save it as the current thread
1698 if (m_threads.empty())
1699 SetCurrentThreadID(thread_id);
Todd Fialaaf245d12014-06-30 21:05:18 +00001700
Pavel Labatha5be48b2017-10-17 15:52:16 +00001701 m_threads.push_back(llvm::make_unique<NativeThreadLinux>(*this, thread_id));
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001702
1703 if (m_pt_proces_trace_id != LLDB_INVALID_UID) {
1704 auto traceMonitor = ProcessorTraceMonitor::Create(
1705 GetID(), thread_id, m_pt_process_trace_config, true);
1706 if (traceMonitor) {
1707 m_pt_traced_thread_group.insert(thread_id);
1708 m_processor_trace_monitor.insert(
1709 std::make_pair(thread_id, std::move(*traceMonitor)));
1710 } else {
1711 LLDB_LOG(log, "failed to start trace on thread {0}", thread_id);
1712 Status error(traceMonitor.takeError());
1713 LLDB_LOG(log, "error {0}", error);
1714 }
1715 }
1716
Pavel Labatha5be48b2017-10-17 15:52:16 +00001717 return static_cast<NativeThreadLinux &>(*m_threads.back());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001718}
Todd Fialaaf245d12014-06-30 21:05:18 +00001719
Zachary Turner97206d52017-05-12 04:51:55 +00001720Status NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,
1721 FileSpec &file_spec) {
1722 Status error = PopulateMemoryRegionCache();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001723 if (error.Fail())
1724 return error;
1725
Kate Stoneb9c1b512016-09-06 20:57:50 +00001726 FileSpec module_file_spec(module_path, true);
1727
Kate Stoneb9c1b512016-09-06 20:57:50 +00001728 file_spec.Clear();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001729 for (const auto &it : m_mem_region_cache) {
1730 if (it.second.GetFilename() == module_file_spec.GetFilename()) {
1731 file_spec = it.second;
Zachary Turner97206d52017-05-12 04:51:55 +00001732 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001733 }
1734 }
Zachary Turner97206d52017-05-12 04:51:55 +00001735 return Status("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
1736 module_file_spec.GetFilename().AsCString(), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001737}
1738
Zachary Turner97206d52017-05-12 04:51:55 +00001739Status NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
1740 lldb::addr_t &load_addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001741 load_addr = LLDB_INVALID_ADDRESS;
Zachary Turner97206d52017-05-12 04:51:55 +00001742 Status error = PopulateMemoryRegionCache();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001743 if (error.Fail())
1744 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001745
Tamas Berghammera6f57952017-01-03 16:29:43 +00001746 FileSpec file(file_name, false);
1747 for (const auto &it : m_mem_region_cache) {
1748 if (it.second == file) {
1749 load_addr = it.first.GetRange().GetRangeBase();
Zachary Turner97206d52017-05-12 04:51:55 +00001750 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001751 }
1752 }
Zachary Turner97206d52017-05-12 04:51:55 +00001753 return Status("No load address found for specified file.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001754}
1755
Pavel Labatha5be48b2017-10-17 15:52:16 +00001756NativeThreadLinux *NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {
1757 return static_cast<NativeThreadLinux *>(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001758 NativeProcessProtocol::GetThreadByID(tid));
1759}
1760
Zachary Turner97206d52017-05-12 04:51:55 +00001761Status NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,
1762 lldb::StateType state, int signo) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001763 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1764 LLDB_LOG(log, "tid: {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001765
Adrian Prantl05097242018-04-30 16:49:04 +00001766 // 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.
Pavel Labatha6321a82017-01-19 15:26:04 +00001771 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);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001777 }
1778
Adrian Prantl05097242018-04-30 16:49:04 +00001779 // Request a resume. We expect this to be synchronous and the system to
1780 // reflect it is running after this completes.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001781 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:
Pavel Labath8198db32017-01-24 11:48:25 +00001795 LLDB_LOG(log, "Unhandled state {0}.", state);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001796 llvm_unreachable("Unhandled state for resume");
1797 }
Pavel Labathc0765592015-05-06 10:46:34 +00001798}
1799
1800//===----------------------------------------------------------------------===//
1801
Kate Stoneb9c1b512016-09-06 20:57:50 +00001802void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001803 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1804 LLDB_LOG(log, "about to process event: (triggering_tid: {0})",
1805 triggering_tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001806
1807 m_pending_notification_tid = triggering_tid;
1808
Adrian Prantl05097242018-04-30 16:49:04 +00001809 // Request a stop for all the thread stops that need to be stopped and are
1810 // not already known to be stopped.
Pavel Labatha5be48b2017-10-17 15:52:16 +00001811 for (const auto &thread : m_threads) {
1812 if (StateIsRunningState(thread->GetState()))
1813 static_cast<NativeThreadLinux *>(thread.get())->RequestStop();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001814 }
1815
1816 SignalIfAllThreadsStopped();
Pavel Labatha6321a82017-01-19 15:26:04 +00001817 LLDB_LOG(log, "event processing done");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001818}
1819
1820void 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) {
Zachary Turner97206d52017-05-12 04:51:55 +00001836 Status error = RemoveBreakpoint(thread_info.second);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001837 if (error.Fail())
Pavel Labatha6321a82017-01-19 15:26:04 +00001838 LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}",
1839 thread_info.first, error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001840 }
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
1849void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001850 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1851 LLDB_LOG(log, "tid: {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001852
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
Adrian Prantl05097242018-04-30 16:49:04 +00001856 // the notification.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001857 thread.RequestStop();
1858 }
1859}
1860
1861void NativeProcessLinux::SigchldHandler() {
Pavel Labatha6321a82017-01-19 15:26:04 +00001862 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001863 // Process all pending waitpid notifications.
1864 while (true) {
1865 int status = -1;
Pavel Labathc1a6b122017-07-03 09:25:55 +00001866 ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, -1, &status,
1867 __WALL | __WNOTHREAD | WNOHANG);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001868
1869 if (wait_pid == 0)
1870 break; // We are done.
1871
1872 if (wait_pid == -1) {
Zachary Turner97206d52017-05-12 04:51:55 +00001873 Status error(errno, eErrorTypePOSIX);
Pavel Labatha6321a82017-01-19 15:26:04 +00001874 LLDB_LOG(log, "waitpid (-1, &status, _) failed: {0}", error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001875 break;
Pavel Labathc0765592015-05-06 10:46:34 +00001876 }
1877
Pavel Labath3508fc82017-06-19 12:47:50 +00001878 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()));
Pavel Labathc0765592015-05-06 10:46:34 +00001882
Pavel Labath3508fc82017-06-19 12:47:50 +00001883 LLDB_LOG(
1884 log,
1885 "waitpid (-1, &status, _) => pid = {0}, status = {1}, exited = {2}",
1886 wait_pid, wait_status, exited);
Pavel Labathc0765592015-05-06 10:46:34 +00001887
Pavel Labath3508fc82017-06-19 12:47:50 +00001888 MonitorCallback(wait_pid, exited, wait_status);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001889 }
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001890}
1891
Adrian Prantl05097242018-04-30 16:49:04 +00001892// 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*)
Zachary Turner97206d52017-05-12 04:51:55 +00001894Status NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
1895 void *data, size_t data_size,
1896 long *result) {
1897 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001898 long int ret;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001899
Kate Stoneb9c1b512016-09-06 20:57:50 +00001900 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001901
Kate Stoneb9c1b512016-09-06 20:57:50 +00001902 PtraceDisplayBytes(req, data, data_size);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001903
Kate Stoneb9c1b512016-09-06 20:57:50 +00001904 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);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001911
Kate Stoneb9c1b512016-09-06 20:57:50 +00001912 if (ret == -1)
1913 error.SetErrorToErrno();
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001914
Kate Stoneb9c1b512016-09-06 20:57:50 +00001915 if (result)
1916 *result = ret;
Pavel Labath4a9babb2015-06-30 17:04:49 +00001917
Pavel Labath28096202017-02-17 16:09:10 +00001918 LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data,
1919 data_size, ret);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001920
Kate Stoneb9c1b512016-09-06 20:57:50 +00001921 PtraceDisplayBytes(req, data, data_size);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001922
Pavel Labatha6321a82017-01-19 15:26:04 +00001923 if (error.Fail())
1924 LLDB_LOG(log, "ptrace() failed: {0}", error);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001925
Kate Stoneb9c1b512016-09-06 20:57:50 +00001926 return error;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001927}
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001928
1929llvm::Expected<ProcessorTraceMonitor &>
1930NativeProcessLinux::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
1948Status 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
1968Status 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
1986Status 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
2008lldb::user_id_t
2009NativeProcessLinux::StartTraceGroup(const TraceOptions &config,
2010 Status &error) {
2011
2012 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2013 if (config.getType() != TraceType::eTraceTypeProcessorTrace)
2014 return LLDB_INVALID_UID;
2015
2016 if (m_pt_proces_trace_id != LLDB_INVALID_UID) {
2017 error.SetErrorString("tracing already active on this process");
2018 return m_pt_proces_trace_id;
2019 }
2020
2021 for (const auto &thread_sp : m_threads) {
2022 if (auto traceInstance = ProcessorTraceMonitor::Create(
2023 GetID(), thread_sp->GetID(), config, true)) {
2024 m_pt_traced_thread_group.insert(thread_sp->GetID());
2025 m_processor_trace_monitor.insert(
2026 std::make_pair(thread_sp->GetID(), std::move(*traceInstance)));
2027 }
2028 }
2029
2030 m_pt_process_trace_config = config;
2031 error = ProcessorTraceMonitor::GetCPUType(m_pt_process_trace_config);
2032
2033 // Trace on Complete process will have traceid of 0
2034 m_pt_proces_trace_id = 0;
2035
2036 LLDB_LOG(log, "Process Trace ID {0}", m_pt_proces_trace_id);
2037 return m_pt_proces_trace_id;
2038}
2039
2040lldb::user_id_t NativeProcessLinux::StartTrace(const TraceOptions &config,
2041 Status &error) {
2042 if (config.getType() != TraceType::eTraceTypeProcessorTrace)
2043 return NativeProcessProtocol::StartTrace(config, error);
2044
2045 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2046
2047 lldb::tid_t threadid = config.getThreadID();
2048
2049 if (threadid == LLDB_INVALID_THREAD_ID)
2050 return StartTraceGroup(config, error);
2051
2052 auto thread_sp = GetThreadByID(threadid);
2053 if (!thread_sp) {
2054 // Thread not tracked by lldb so don't trace.
2055 error.SetErrorString("invalid thread id");
2056 return LLDB_INVALID_UID;
2057 }
2058
2059 const auto &iter = m_processor_trace_monitor.find(threadid);
2060 if (iter != m_processor_trace_monitor.end()) {
2061 LLDB_LOG(log, "Thread already being traced");
2062 error.SetErrorString("tracing already active on this thread");
2063 return LLDB_INVALID_UID;
2064 }
2065
2066 auto traceMonitor =
2067 ProcessorTraceMonitor::Create(GetID(), threadid, config, false);
2068 if (!traceMonitor) {
2069 error = traceMonitor.takeError();
2070 LLDB_LOG(log, "error {0}", error);
2071 return LLDB_INVALID_UID;
2072 }
2073 lldb::user_id_t ret_trace_id = (*traceMonitor)->GetTraceID();
2074 m_processor_trace_monitor.insert(
2075 std::make_pair(threadid, std::move(*traceMonitor)));
2076 return ret_trace_id;
2077}
2078
2079Status NativeProcessLinux::StopTracingForThread(lldb::tid_t thread) {
2080 Status error;
2081 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2082 LLDB_LOG(log, "Thread {0}", thread);
2083
2084 const auto& iter = m_processor_trace_monitor.find(thread);
2085 if (iter == m_processor_trace_monitor.end()) {
2086 error.SetErrorString("tracing not active for this thread");
2087 return error;
2088 }
2089
2090 if (iter->second->GetTraceID() == m_pt_proces_trace_id) {
Adrian Prantl05097242018-04-30 16:49:04 +00002091 // traceid maps to the whole process so we have to erase it from the thread
2092 // group.
Ravitheja Addepally99e37692017-06-28 07:58:31 +00002093 LLDB_LOG(log, "traceid maps to process");
2094 m_pt_traced_thread_group.erase(thread);
2095 }
2096 m_processor_trace_monitor.erase(iter);
2097
2098 return error;
2099}
2100
2101Status NativeProcessLinux::StopTrace(lldb::user_id_t traceid,
2102 lldb::tid_t thread) {
2103 Status error;
2104
2105 TraceOptions trace_options;
2106 trace_options.setThreadID(thread);
2107 error = NativeProcessLinux::GetTraceConfig(traceid, trace_options);
2108
2109 if (error.Fail())
2110 return error;
2111
2112 switch (trace_options.getType()) {
2113 case lldb::TraceType::eTraceTypeProcessorTrace:
2114 if (traceid == m_pt_proces_trace_id &&
2115 thread == LLDB_INVALID_THREAD_ID)
2116 StopProcessorTracingOnProcess();
2117 else
2118 error = StopProcessorTracingOnThread(traceid, thread);
2119 break;
2120 default:
2121 error.SetErrorString("trace not supported");
2122 break;
2123 }
2124
2125 return error;
2126}
2127
2128void NativeProcessLinux::StopProcessorTracingOnProcess() {
2129 for (auto thread_id_iter : m_pt_traced_thread_group)
2130 m_processor_trace_monitor.erase(thread_id_iter);
2131 m_pt_traced_thread_group.clear();
2132 m_pt_proces_trace_id = LLDB_INVALID_UID;
2133}
2134
2135Status NativeProcessLinux::StopProcessorTracingOnThread(lldb::user_id_t traceid,
2136 lldb::tid_t thread) {
2137 Status error;
2138 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2139
2140 if (thread == LLDB_INVALID_THREAD_ID) {
2141 for (auto& iter : m_processor_trace_monitor) {
2142 if (iter.second->GetTraceID() == traceid) {
Adrian Prantl05097242018-04-30 16:49:04 +00002143 // Stopping a trace instance for an individual thread hence there will
2144 // only be one traceid that can match.
Ravitheja Addepally99e37692017-06-28 07:58:31 +00002145 m_processor_trace_monitor.erase(iter.first);
2146 return error;
2147 }
2148 LLDB_LOG(log, "Trace ID {0}", iter.second->GetTraceID());
2149 }
2150
2151 LLDB_LOG(log, "Invalid TraceID");
2152 error.SetErrorString("invalid trace id");
2153 return error;
2154 }
2155
2156 // thread is specified so we can use find function on the map.
2157 const auto& iter = m_processor_trace_monitor.find(thread);
2158 if (iter == m_processor_trace_monitor.end()) {
2159 // thread not found in our map.
2160 LLDB_LOG(log, "thread not being traced");
2161 error.SetErrorString("tracing not active for this thread");
2162 return error;
2163 }
2164 if (iter->second->GetTraceID() != traceid) {
2165 // traceid did not match so it has to be invalid.
2166 LLDB_LOG(log, "Invalid TraceID");
2167 error.SetErrorString("invalid trace id");
2168 return error;
2169 }
2170
2171 LLDB_LOG(log, "UID - {0} , Thread -{1}", traceid, thread);
2172
2173 if (traceid == m_pt_proces_trace_id) {
Adrian Prantl05097242018-04-30 16:49:04 +00002174 // traceid maps to the whole process so we have to erase it from the thread
2175 // group.
Ravitheja Addepally99e37692017-06-28 07:58:31 +00002176 LLDB_LOG(log, "traceid maps to process");
2177 m_pt_traced_thread_group.erase(thread);
2178 }
2179 m_processor_trace_monitor.erase(iter);
2180
2181 return error;
2182}