blob: 170d3b1000641408ac62160e29b953a944349534 [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/Core/RegisterValue.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000029#include "lldb/Core/State.h"
30#include "lldb/Host/Host.h"
Pavel Labath5ad891f2016-07-21 14:54:03 +000031#include "lldb/Host/HostProcess.h"
Zachary Turner24ae6292017-02-16 19:38:21 +000032#include "lldb/Host/PseudoTerminal.h"
Zachary Turner39de3112014-09-09 20:54:56 +000033#include "lldb/Host/ThreadLauncher.h"
Pavel Labath2a86b552016-06-14 17:30:52 +000034#include "lldb/Host/common/NativeBreakpoint.h"
35#include "lldb/Host/common/NativeRegisterContext.h"
Pavel Labath4ee1c952017-02-06 18:36:58 +000036#include "lldb/Host/linux/Ptrace.h"
37#include "lldb/Host/linux/Uio.h"
Kamil Rytarowski816ae4b2017-02-01 14:30:40 +000038#include "lldb/Host/posix/ProcessLauncherPosixFork.h"
Pavel Labath2a86b552016-06-14 17:30:52 +000039#include "lldb/Symbol/ObjectFile.h"
Zachary Turner90aff472015-03-03 23:36:51 +000040#include "lldb/Target/Process.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000041#include "lldb/Target/ProcessLaunchInfo.h"
Pavel Labath5b981ab2015-05-29 12:53:54 +000042#include "lldb/Target/Target.h"
Chaoren Linc16f5dc2015-03-19 23:28:10 +000043#include "lldb/Utility/LLDBAssert.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: {
180 // Extract iov_base from data, which is a pointer to the struct IOVEC
181 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 Labath96e600f2017-07-07 11:02:19 +0000248 ArchSpec arch;
249 if ((status = ResolveProcessArchitecture(pid, arch)).Fail())
250 return status.ToError();
251
252 // Set the architecture to the exe architecture.
253 LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid,
254 arch.GetArchitectureName());
255
256 status = SetDefaultPtraceOpts(pid);
257 if (status.Fail()) {
258 LLDB_LOG(log, "failed to set default ptrace options: {0}", status);
259 return status.ToError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000260 }
261
Pavel Labath82abefa2017-07-18 09:24:48 +0000262 return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
Pavel Labath96e600f2017-07-07 11:02:19 +0000263 pid, launch_info.GetPTY().ReleaseMasterFileDescriptor(), native_delegate,
Pavel Labath82abefa2017-07-18 09:24:48 +0000264 arch, mainloop, {pid}));
Todd Fialaaf245d12014-06-30 21:05:18 +0000265}
266
Pavel Labath82abefa2017-07-18 09:24:48 +0000267llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
268NativeProcessLinux::Factory::Attach(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000269 lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
Pavel Labath96e600f2017-07-07 11:02:19 +0000270 MainLoop &mainloop) const {
Pavel Labatha6321a82017-01-19 15:26:04 +0000271 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
272 LLDB_LOG(log, "pid = {0:x}", pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000273
Kate Stoneb9c1b512016-09-06 20:57:50 +0000274 // Retrieve the architecture for the running process.
Pavel Labath96e600f2017-07-07 11:02:19 +0000275 ArchSpec arch;
276 Status status = ResolveProcessArchitecture(pid, arch);
277 if (!status.Success())
278 return status.ToError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000279
Pavel Labath96e600f2017-07-07 11:02:19 +0000280 auto tids_or = NativeProcessLinux::Attach(pid);
281 if (!tids_or)
282 return tids_or.takeError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000283
Pavel Labath82abefa2017-07-18 09:24:48 +0000284 return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
285 pid, -1, native_delegate, arch, mainloop, *tids_or));
Todd Fialaaf245d12014-06-30 21:05:18 +0000286}
287
288// -----------------------------------------------------------------------------
289// Public Instance Methods
290// -----------------------------------------------------------------------------
291
Pavel Labath96e600f2017-07-07 11:02:19 +0000292NativeProcessLinux::NativeProcessLinux(::pid_t pid, int terminal_fd,
293 NativeDelegate &delegate,
Pavel Labath82abefa2017-07-18 09:24:48 +0000294 const ArchSpec &arch, MainLoop &mainloop,
295 llvm::ArrayRef<::pid_t> tids)
Pavel Labath96e600f2017-07-07 11:02:19 +0000296 : NativeProcessProtocol(pid, terminal_fd, delegate), m_arch(arch) {
297 if (m_terminal_fd != -1) {
298 Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
299 assert(status.Success());
300 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000301
Pavel Labath96e600f2017-07-07 11:02:19 +0000302 Status status;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000303 m_sigchld_handle = mainloop.RegisterSignal(
Pavel Labath96e600f2017-07-07 11:02:19 +0000304 SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status);
305 assert(m_sigchld_handle && status.Success());
Todd Fialaaf245d12014-06-30 21:05:18 +0000306
Pavel Labath96e600f2017-07-07 11:02:19 +0000307 for (const auto &tid : tids) {
308 NativeThreadLinuxSP thread_sp = AddThread(tid);
309 assert(thread_sp && "AddThread() returned a nullptr thread");
310 thread_sp->SetStoppedBySignal(SIGSTOP);
311 ThreadWasCreated(*thread_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000312 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000313
Kate Stoneb9c1b512016-09-06 20:57:50 +0000314 // Let our process instance know the thread has stopped.
Pavel Labath96e600f2017-07-07 11:02:19 +0000315 SetCurrentThreadID(tids[0]);
316 SetState(StateType::eStateStopped, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000317
Pavel Labath96e600f2017-07-07 11:02:19 +0000318 // Proccess any signals we received before installing our handler
319 SigchldHandler();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000320}
321
Pavel Labath96e600f2017-07-07 11:02:19 +0000322llvm::Expected<std::vector<::pid_t>> NativeProcessLinux::Attach(::pid_t pid) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000323 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000324
Pavel Labath96e600f2017-07-07 11:02:19 +0000325 Status status;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000326 // Use a map to keep track of the threads which we have attached/need to
327 // attach.
328 Host::TidMap tids_to_attach;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000329 while (Host::FindProcessThreads(pid, tids_to_attach)) {
330 for (Host::TidMap::iterator it = tids_to_attach.begin();
331 it != tids_to_attach.end();) {
332 if (it->second == false) {
333 lldb::tid_t tid = it->first;
334
335 // Attach to the requested process.
336 // An attach will cause the thread to stop with a SIGSTOP.
Pavel Labath96e600f2017-07-07 11:02:19 +0000337 if ((status = PtraceWrapper(PTRACE_ATTACH, tid)).Fail()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000338 // No such thread. The thread may have exited.
339 // More error handling may be needed.
Pavel Labath96e600f2017-07-07 11:02:19 +0000340 if (status.GetError() == ESRCH) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000341 it = tids_to_attach.erase(it);
342 continue;
Pavel Labath96e600f2017-07-07 11:02:19 +0000343 }
344 return status.ToError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000345 }
346
Pavel Labath96e600f2017-07-07 11:02:19 +0000347 int wpid =
348 llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, nullptr, __WALL);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000349 // Need to use __WALL otherwise we receive an error with errno=ECHLD
350 // At this point we should have a thread stopped if waitpid succeeds.
Pavel Labath96e600f2017-07-07 11:02:19 +0000351 if (wpid < 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000352 // No such thread. The thread may have exited.
353 // More error handling may be needed.
354 if (errno == ESRCH) {
355 it = tids_to_attach.erase(it);
356 continue;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000357 }
Pavel Labath96e600f2017-07-07 11:02:19 +0000358 return llvm::errorCodeToError(
359 std::error_code(errno, std::generic_category()));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000360 }
361
Pavel Labath96e600f2017-07-07 11:02:19 +0000362 if ((status = SetDefaultPtraceOpts(tid)).Fail())
363 return status.ToError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000364
Pavel Labatha6321a82017-01-19 15:26:04 +0000365 LLDB_LOG(log, "adding tid = {0}", tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000366 it->second = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000367 }
368
369 // move the loop forward
370 ++it;
371 }
372 }
373
Pavel Labath96e600f2017-07-07 11:02:19 +0000374 size_t tid_count = tids_to_attach.size();
375 if (tid_count == 0)
376 return llvm::make_error<StringError>("No such process",
377 llvm::inconvertibleErrorCode());
Todd Fialaaf245d12014-06-30 21:05:18 +0000378
Pavel Labath96e600f2017-07-07 11:02:19 +0000379 std::vector<::pid_t> tids;
380 tids.reserve(tid_count);
381 for (const auto &p : tids_to_attach)
382 tids.push_back(p.first);
383 return std::move(tids);
Todd Fialaaf245d12014-06-30 21:05:18 +0000384}
385
Zachary Turner97206d52017-05-12 04:51:55 +0000386Status NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000387 long ptrace_opts = 0;
Todd Fialaaf245d12014-06-30 21:05:18 +0000388
Kate Stoneb9c1b512016-09-06 20:57:50 +0000389 // Have the child raise an event on exit. This is used to keep the child in
390 // limbo until it is destroyed.
391 ptrace_opts |= PTRACE_O_TRACEEXIT;
Todd Fialaaf245d12014-06-30 21:05:18 +0000392
Kate Stoneb9c1b512016-09-06 20:57:50 +0000393 // Have the tracer trace threads which spawn in the inferior process.
394 // TODO: if we want to support tracing the inferiors' child, add the
395 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
396 ptrace_opts |= PTRACE_O_TRACECLONE;
Todd Fialaaf245d12014-06-30 21:05:18 +0000397
Kate Stoneb9c1b512016-09-06 20:57:50 +0000398 // Have the tracer notify us before execve returns
399 // (needed to disable legacy SIGTRAP generation)
400 ptrace_opts |= PTRACE_O_TRACEEXEC;
Todd Fialaaf245d12014-06-30 21:05:18 +0000401
Kate Stoneb9c1b512016-09-06 20:57:50 +0000402 return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void *)ptrace_opts);
Todd Fialaaf245d12014-06-30 21:05:18 +0000403}
404
Pavel Labath1107b5a2015-04-17 14:07:49 +0000405// Handles all waitpid events from the inferior process.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000406void NativeProcessLinux::MonitorCallback(lldb::pid_t pid, bool exited,
Pavel Labath3508fc82017-06-19 12:47:50 +0000407 WaitStatus status) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000408 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Todd Fialaaf245d12014-06-30 21:05:18 +0000409
Kate Stoneb9c1b512016-09-06 20:57:50 +0000410 // Certain activities differ based on whether the pid is the tid of the main
411 // thread.
412 const bool is_main_thread = (pid == GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000413
Kate Stoneb9c1b512016-09-06 20:57:50 +0000414 // Handle when the thread exits.
415 if (exited) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000416 LLDB_LOG(log, "got exit signal({0}) , tid = {1} ({2} main thread)", signal,
417 pid, is_main_thread ? "is" : "is not");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000418
419 // This is a thread that exited. Ensure we're not tracking it anymore.
420 const bool thread_found = StopTrackingThread(pid);
421
422 if (is_main_thread) {
423 // We only set the exit status and notify the delegate if we haven't
424 // already set the process
425 // state to an exited state. We normally should have received a SIGTRAP |
426 // (PTRACE_EVENT_EXIT << 8)
427 // for the main thread.
428 const bool already_notified = (GetState() == StateType::eStateExited) ||
429 (GetState() == StateType::eStateCrashed);
430 if (!already_notified) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000431 LLDB_LOG(
432 log,
433 "tid = {0} handling main thread exit ({1}), expected exit state "
434 "already set but state was {2} instead, setting exit state now",
435 pid,
436 thread_found ? "stopped tracking thread metadata"
437 : "thread metadata not found",
Pavel Labath8198db32017-01-24 11:48:25 +0000438 GetState());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000439 // The main thread exited. We're done monitoring. Report to delegate.
Pavel Labath3508fc82017-06-19 12:47:50 +0000440 SetExitStatus(status, true);
Todd Fialaaf245d12014-06-30 21:05:18 +0000441
Kate Stoneb9c1b512016-09-06 20:57:50 +0000442 // Notify delegate that our process has exited.
443 SetState(StateType::eStateExited, true);
Pavel Labatha6321a82017-01-19 15:26:04 +0000444 } else
445 LLDB_LOG(log, "tid = {0} main thread now exited (%s)", pid,
446 thread_found ? "stopped tracking thread metadata"
447 : "thread metadata not found");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000448 } else {
449 // Do we want to report to the delegate in this case? I think not. If
Pavel Labatha6321a82017-01-19 15:26:04 +0000450 // this was an orderly thread exit, we would already have received the
451 // SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal, and we would have done an
452 // all-stop then.
453 LLDB_LOG(log, "tid = {0} handling non-main thread exit (%s)", pid,
454 thread_found ? "stopped tracking thread metadata"
455 : "thread metadata not found");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000456 }
457 return;
458 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000459
Kate Stoneb9c1b512016-09-06 20:57:50 +0000460 siginfo_t info;
461 const auto info_err = GetSignalInfo(pid, &info);
462 auto thread_sp = GetThreadByID(pid);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000463
Kate Stoneb9c1b512016-09-06 20:57:50 +0000464 if (!thread_sp) {
465 // Normally, the only situation when we cannot find the thread is if we have
Pavel Labatha6321a82017-01-19 15:26:04 +0000466 // just received a new thread notification. This is indicated by
467 // GetSignalInfo() returning si_code == SI_USER and si_pid == 0
468 LLDB_LOG(log, "received notification about an unknown tid {0}.", pid);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000469
Kate Stoneb9c1b512016-09-06 20:57:50 +0000470 if (info_err.Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000471 LLDB_LOG(log,
472 "(tid {0}) GetSignalInfo failed ({1}). "
473 "Ingoring this notification.",
474 pid, info_err);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000475 return;
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000476 }
477
Pavel Labatha6321a82017-01-19 15:26:04 +0000478 LLDB_LOG(log, "tid {0}, si_code: {1}, si_pid: {2}", pid, info.si_code,
479 info.si_pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000480
481 auto thread_sp = AddThread(pid);
Ravitheja Addepally99e37692017-06-28 07:58:31 +0000482
Kate Stoneb9c1b512016-09-06 20:57:50 +0000483 // Resume the newly created thread.
484 ResumeThread(*thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
485 ThreadWasCreated(*thread_sp);
486 return;
487 }
488
489 // Get details on the signal raised.
490 if (info_err.Success()) {
491 // We have retrieved the signal info. Dispatch appropriately.
492 if (info.si_signo == SIGTRAP)
493 MonitorSIGTRAP(info, *thread_sp);
Chaoren Linfa03ad22015-02-03 01:50:42 +0000494 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000495 MonitorSignal(info, *thread_sp, exited);
496 } else {
497 if (info_err.GetError() == EINVAL) {
498 // This is a group stop reception for this tid.
499 // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU
Pavel Labatha6321a82017-01-19 15:26:04 +0000500 // into the tracee, triggering the group-stop mechanism. Normally
501 // receiving these would stop the process, pending a SIGCONT. Simulating
502 // this state in a debugger is hard and is generally not needed (one use
503 // case is debugging background task being managed by a shell). For
504 // general use, it is sufficient to stop the process in a signal-delivery
Kate Stoneb9c1b512016-09-06 20:57:50 +0000505 // stop which happens before the group stop. This done by MonitorSignal
Pavel Labatha6321a82017-01-19 15:26:04 +0000506 // and works correctly for all signals.
507 LLDB_LOG(log,
508 "received a group stop for pid {0} tid {1}. Transparent "
509 "handling of group stops not supported, resuming the "
510 "thread.",
511 GetID(), pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000512 ResumeThread(*thread_sp, thread_sp->GetState(),
513 LLDB_INVALID_SIGNAL_NUMBER);
514 } else {
515 // ptrace(GETSIGINFO) failed (but not due to group-stop).
Todd Fialaaf245d12014-06-30 21:05:18 +0000516
Kate Stoneb9c1b512016-09-06 20:57:50 +0000517 // A return value of ESRCH means the thread/process is no longer on the
Pavel Labatha6321a82017-01-19 15:26:04 +0000518 // system, so it was killed somehow outside of our control. Either way,
519 // we can't do anything with it anymore.
Todd Fialaaf245d12014-06-30 21:05:18 +0000520
Kate Stoneb9c1b512016-09-06 20:57:50 +0000521 // Stop tracking the metadata for the thread since it's entirely off the
522 // system now.
523 const bool thread_found = StopTrackingThread(pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000524
Pavel Labatha6321a82017-01-19 15:26:04 +0000525 LLDB_LOG(log,
526 "GetSignalInfo failed: {0}, tid = {1}, signal = {2}, "
527 "status = {3}, main_thread = {4}, thread_found: {5}",
528 info_err, pid, signal, status, is_main_thread, thread_found);
Todd Fialaaf245d12014-06-30 21:05:18 +0000529
Kate Stoneb9c1b512016-09-06 20:57:50 +0000530 if (is_main_thread) {
531 // Notify the delegate - our process is not available but appears to
532 // have been killed outside
533 // our control. Is eStateExited the right exit state in this case?
Pavel Labath3508fc82017-06-19 12:47:50 +0000534 SetExitStatus(status, true);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000535 SetState(StateType::eStateExited, true);
536 } else {
537 // This thread was pulled out from underneath us. Anything to do here?
538 // Do we want to do an all stop?
Pavel Labatha6321a82017-01-19 15:26:04 +0000539 LLDB_LOG(log,
540 "pid {0} tid {1} non-main thread exit occurred, didn't "
541 "tell delegate anything since thread disappeared out "
542 "from underneath us",
543 GetID(), pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000544 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000545 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000546 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000547}
548
Kate Stoneb9c1b512016-09-06 20:57:50 +0000549void NativeProcessLinux::WaitForNewThread(::pid_t tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000550 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Pavel Labath426bdf82015-04-28 07:51:52 +0000551
Kate Stoneb9c1b512016-09-06 20:57:50 +0000552 NativeThreadLinuxSP new_thread_sp = GetThreadByID(tid);
Pavel Labath426bdf82015-04-28 07:51:52 +0000553
Kate Stoneb9c1b512016-09-06 20:57:50 +0000554 if (new_thread_sp) {
555 // We are already tracking the thread - we got the event on the new thread
556 // (see
557 // MonitorSignal) before this one. We are done.
558 return;
559 }
Pavel Labath426bdf82015-04-28 07:51:52 +0000560
Kate Stoneb9c1b512016-09-06 20:57:50 +0000561 // The thread is not tracked yet, let's wait for it to appear.
562 int status = -1;
Pavel Labathc1a6b122017-07-03 09:25:55 +0000563 LLDB_LOG(log,
564 "received thread creation event for tid {0}. tid not tracked "
565 "yet, waiting for thread to appear...",
566 tid);
567 ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, &status, __WALL);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000568 // Since we are waiting on a specific tid, this must be the creation event.
Pavel Labatha6321a82017-01-19 15:26:04 +0000569 // But let's do some checks just in case.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000570 if (wait_pid != tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000571 LLDB_LOG(log,
572 "waiting for tid {0} failed. Assuming the thread has "
573 "disappeared in the meantime",
574 tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000575 // The only way I know of this could happen is if the whole process was
576 // SIGKILLed in the mean time. In any case, we can't do anything about that
577 // now.
578 return;
579 }
580 if (WIFEXITED(status)) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000581 LLDB_LOG(log,
582 "waiting for tid {0} returned an 'exited' event. Not "
583 "tracking the thread.",
584 tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000585 // Also a very improbable event.
586 return;
587 }
Pavel Labath426bdf82015-04-28 07:51:52 +0000588
Pavel Labatha6321a82017-01-19 15:26:04 +0000589 LLDB_LOG(log, "pid = {0}: tracking new thread tid {1}", GetID(), tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000590 new_thread_sp = AddThread(tid);
Ravitheja Addepally99e37692017-06-28 07:58:31 +0000591
Kate Stoneb9c1b512016-09-06 20:57:50 +0000592 ResumeThread(*new_thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
593 ThreadWasCreated(*new_thread_sp);
Pavel Labath426bdf82015-04-28 07:51:52 +0000594}
595
Kate Stoneb9c1b512016-09-06 20:57:50 +0000596void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info,
597 NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000598 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000599 const bool is_main_thread = (thread.GetID() == GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000600
Kate Stoneb9c1b512016-09-06 20:57:50 +0000601 assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
Todd Fialaaf245d12014-06-30 21:05:18 +0000602
Kate Stoneb9c1b512016-09-06 20:57:50 +0000603 switch (info.si_code) {
604 // TODO: these two cases are required if we want to support tracing of the
605 // inferiors' children. We'd need this to debug a monitor.
606 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
607 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
Todd Fialaaf245d12014-06-30 21:05:18 +0000608
Kate Stoneb9c1b512016-09-06 20:57:50 +0000609 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): {
610 // This is the notification on the parent thread which informs us of new
611 // thread
612 // creation.
613 // We don't want to do anything with the parent thread so we just resume it.
614 // In case we
615 // want to implement "break on thread creation" functionality, we would need
616 // to stop
617 // here.
Todd Fialaaf245d12014-06-30 21:05:18 +0000618
Kate Stoneb9c1b512016-09-06 20:57:50 +0000619 unsigned long event_message = 0;
620 if (GetEventMessage(thread.GetID(), &event_message).Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000621 LLDB_LOG(log,
622 "pid {0} received thread creation event but "
623 "GetEventMessage failed so we don't know the new tid",
624 thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000625 } else
626 WaitForNewThread(event_message);
Todd Fialaaf245d12014-06-30 21:05:18 +0000627
Kate Stoneb9c1b512016-09-06 20:57:50 +0000628 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
629 break;
630 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000631
Kate Stoneb9c1b512016-09-06 20:57:50 +0000632 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): {
633 NativeThreadLinuxSP main_thread_sp;
Pavel Labatha6321a82017-01-19 15:26:04 +0000634 LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000635
636 // Exec clears any pending notifications.
637 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
638
639 // Remove all but the main thread here. Linux fork creates a new process
640 // which only copies the main thread.
Pavel Labatha6321a82017-01-19 15:26:04 +0000641 LLDB_LOG(log, "exec received, stop tracking all but main thread");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000642
643 for (auto thread_sp : m_threads) {
644 const bool is_main_thread = thread_sp && thread_sp->GetID() == GetID();
645 if (is_main_thread) {
646 main_thread_sp = std::static_pointer_cast<NativeThreadLinux>(thread_sp);
Pavel Labatha6321a82017-01-19 15:26:04 +0000647 LLDB_LOG(log, "found main thread with tid {0}, keeping",
648 main_thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000649 } else {
Pavel Labatha6321a82017-01-19 15:26:04 +0000650 LLDB_LOG(log, "discarding non-main-thread tid {0} due to exec",
651 thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000652 }
Todd Fialaa9882ce2014-08-28 15:46:54 +0000653 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000654
Kate Stoneb9c1b512016-09-06 20:57:50 +0000655 m_threads.clear();
Chaoren Linfa03ad22015-02-03 01:50:42 +0000656
Kate Stoneb9c1b512016-09-06 20:57:50 +0000657 if (main_thread_sp) {
658 m_threads.push_back(main_thread_sp);
659 SetCurrentThreadID(main_thread_sp->GetID());
660 main_thread_sp->SetStoppedByExec();
661 } else {
662 SetCurrentThreadID(LLDB_INVALID_THREAD_ID);
Pavel Labatha6321a82017-01-19 15:26:04 +0000663 LLDB_LOG(log,
664 "pid {0} no main thread found, discarded all threads, "
665 "we're in a no-thread state!",
666 GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000667 }
668
Kate Stoneb9c1b512016-09-06 20:57:50 +0000669 // Tell coordinator about about the "new" (since exec) stopped main thread.
670 ThreadWasCreated(*main_thread_sp);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000671
Kate Stoneb9c1b512016-09-06 20:57:50 +0000672 // Let our delegate know we have just exec'd.
673 NotifyDidExec();
674
675 // If we have a main thread, indicate we are stopped.
676 assert(main_thread_sp && "exec called during ptraced process but no main "
677 "thread metadata tracked");
678
679 // Let the process know we're stopped.
680 StopRunningThreads(main_thread_sp->GetID());
681
682 break;
683 }
684
685 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): {
686 // The inferior process or one of its threads is about to exit.
687 // We don't want to do anything with the thread so we just resume it. In
688 // case we
689 // want to implement "break on thread exit" functionality, we would need to
690 // stop
691 // here.
692
693 unsigned long data = 0;
694 if (GetEventMessage(thread.GetID(), &data).Fail())
695 data = -1;
696
Pavel Labatha6321a82017-01-19 15:26:04 +0000697 LLDB_LOG(log,
698 "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
699 "WIFSIGNALED={2}, pid = {3}, main_thread = {4}",
700 data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(),
701 is_main_thread);
Todd Fialaaf245d12014-06-30 21:05:18 +0000702
Pavel Labath3508fc82017-06-19 12:47:50 +0000703 if (is_main_thread)
704 SetExitStatus(WaitStatus::Decode(data), true);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000705
706 StateType state = thread.GetState();
707 if (!StateIsRunningState(state)) {
708 // Due to a kernel bug, we may sometimes get this stop after the inferior
709 // gets a
710 // SIGKILL. This confuses our state tracking logic in ResumeThread(),
711 // since normally,
712 // we should not be receiving any ptrace events while the inferior is
713 // stopped. This
714 // makes sure that the inferior is resumed and exits normally.
715 state = eStateRunning;
716 }
717 ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
718
719 break;
720 }
721
722 case 0:
723 case TRAP_TRACE: // We receive this on single stepping.
724 case TRAP_HWBKPT: // We receive this on watchpoint hit
725 {
726 // If a watchpoint was hit, report it
727 uint32_t wp_index;
Zachary Turner97206d52017-05-12 04:51:55 +0000728 Status error = thread.GetRegisterContext()->GetWatchpointHitIndex(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000729 wp_index, (uintptr_t)info.si_addr);
Pavel Labatha6321a82017-01-19 15:26:04 +0000730 if (error.Fail())
731 LLDB_LOG(log,
732 "received error while checking for watchpoint hits, pid = "
733 "{0}, error = {1}",
734 thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000735 if (wp_index != LLDB_INVALID_INDEX32) {
736 MonitorWatchpoint(thread, wp_index);
737 break;
738 }
739
Omair Javaidd5ffbad2017-02-24 13:27:31 +0000740 // If a breakpoint was hit, report it
741 uint32_t bp_index;
742 error = thread.GetRegisterContext()->GetHardwareBreakHitIndex(
743 bp_index, (uintptr_t)info.si_addr);
744 if (error.Fail())
745 LLDB_LOG(log, "received error while checking for hardware "
746 "breakpoint hits, pid = {0}, error = {1}",
747 thread.GetID(), error);
748 if (bp_index != LLDB_INVALID_INDEX32) {
749 MonitorBreakpoint(thread);
750 break;
751 }
752
Kate Stoneb9c1b512016-09-06 20:57:50 +0000753 // Otherwise, report step over
754 MonitorTrace(thread);
755 break;
756 }
757
758 case SI_KERNEL:
Mohit K. Bhakkad35799962015-06-18 04:53:18 +0000759#if defined __mips__
Kate Stoneb9c1b512016-09-06 20:57:50 +0000760 // For mips there is no special signal for watchpoint
761 // So we check for watchpoint in kernel trap
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000762 {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000763 // If a watchpoint was hit, report it
764 uint32_t wp_index;
Zachary Turner97206d52017-05-12 04:51:55 +0000765 Status error = thread.GetRegisterContext()->GetWatchpointHitIndex(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000766 wp_index, LLDB_INVALID_ADDRESS);
Pavel Labatha6321a82017-01-19 15:26:04 +0000767 if (error.Fail())
768 LLDB_LOG(log,
769 "received error while checking for watchpoint hits, pid = "
770 "{0}, error = {1}",
771 thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000772 if (wp_index != LLDB_INVALID_INDEX32) {
773 MonitorWatchpoint(thread, wp_index);
774 break;
775 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000776 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000777// NO BREAK
Mohit K. Bhakkad35799962015-06-18 04:53:18 +0000778#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000779 case TRAP_BRKPT:
780 MonitorBreakpoint(thread);
781 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000782
Kate Stoneb9c1b512016-09-06 20:57:50 +0000783 case SIGTRAP:
784 case (SIGTRAP | 0x80):
Pavel Labatha6321a82017-01-19 15:26:04 +0000785 LLDB_LOG(
786 log,
787 "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",
788 info.si_code, GetID(), thread.GetID());
Chaoren Linfa03ad22015-02-03 01:50:42 +0000789
Kate Stoneb9c1b512016-09-06 20:57:50 +0000790 // Ignore these signals until we know more about them.
791 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
792 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000793
Kate Stoneb9c1b512016-09-06 20:57:50 +0000794 default:
Pavel Labath21a365b2017-07-11 10:38:40 +0000795 LLDB_LOG(log, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}",
796 info.si_code, GetID(), thread.GetID());
797 MonitorSignal(info, thread, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000798 break;
799 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000800}
801
Kate Stoneb9c1b512016-09-06 20:57:50 +0000802void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000803 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
804 LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000805
Kate Stoneb9c1b512016-09-06 20:57:50 +0000806 // This thread is currently stopped.
807 thread.SetStoppedByTrace();
808
809 StopRunningThreads(thread.GetID());
810}
811
812void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) {
813 Log *log(
814 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
Pavel Labatha6321a82017-01-19 15:26:04 +0000815 LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000816
817 // Mark the thread as stopped at breakpoint.
818 thread.SetStoppedByBreakpoint();
Zachary Turner97206d52017-05-12 04:51:55 +0000819 Status error = FixupBreakpointPCAsNeeded(thread);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000820 if (error.Fail())
Pavel Labatha6321a82017-01-19 15:26:04 +0000821 LLDB_LOG(log, "pid = {0} fixup: {1}", thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000822
823 if (m_threads_stepping_with_breakpoint.find(thread.GetID()) !=
824 m_threads_stepping_with_breakpoint.end())
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000825 thread.SetStoppedByTrace();
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000826
Kate Stoneb9c1b512016-09-06 20:57:50 +0000827 StopRunningThreads(thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000828}
829
Kate Stoneb9c1b512016-09-06 20:57:50 +0000830void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread,
831 uint32_t wp_index) {
832 Log *log(
833 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
Pavel Labatha6321a82017-01-19 15:26:04 +0000834 LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}",
835 thread.GetID(), wp_index);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000836
837 // Mark the thread as stopped at watchpoint.
838 // The address is at (lldb::addr_t)info->si_addr if we need it.
839 thread.SetStoppedByWatchpoint(wp_index);
840
841 // We need to tell all other running threads before we notify the delegate
842 // about this stop.
843 StopRunningThreads(thread.GetID());
844}
845
846void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
847 NativeThreadLinux &thread, bool exited) {
848 const int signo = info.si_signo;
849 const bool is_from_llgs = info.si_pid == getpid();
850
Pavel Labatha6321a82017-01-19 15:26:04 +0000851 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000852
853 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
854 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
855 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
856 //
857 // IOW, user generated signals never generate what we consider to be a
858 // "crash".
859 //
860 // Similarly, ACK signals generated by this monitor.
861
862 // Handle the signal.
Pavel Labatha6321a82017-01-19 15:26:04 +0000863 LLDB_LOG(log,
864 "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
865 "waitpid pid = {4})",
866 Host::GetSignalAsCString(signo), signo, info.si_code,
867 thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000868
Kate Stoneb9c1b512016-09-06 20:57:50 +0000869 // Check for thread stop notification.
870 if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) {
871 // This is a tgkill()-based stop.
Pavel Labatha6321a82017-01-19 15:26:04 +0000872 LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000873
Kate Stoneb9c1b512016-09-06 20:57:50 +0000874 // Check that we're not already marked with a stop reason.
875 // Note this thread really shouldn't already be marked as stopped - if we
Pavel Labatha6321a82017-01-19 15:26:04 +0000876 // were, that would imply that the kernel signaled us with the thread
877 // stopping which we handled and marked as stopped, and that, without an
878 // intervening resume, we received another stop. It is more likely that we
879 // are missing the marking of a run state somewhere if we find that the
880 // thread was marked as stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000881 const StateType thread_state = thread.GetState();
882 if (!StateIsStoppedState(thread_state, false)) {
883 // An inferior thread has stopped because of a SIGSTOP we have sent it.
884 // Generally, these are not important stops and we don't want to report
Pavel Labatha6321a82017-01-19 15:26:04 +0000885 // them as they are just used to stop other threads when one thread (the
886 // one with the *real* stop reason) hits a breakpoint (watchpoint,
887 // etc...). However, in the case of an asynchronous Interrupt(), this *is*
888 // the real stop reason, so we leave the signal intact if this is the
889 // thread that was chosen as the triggering thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000890 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
891 if (m_pending_notification_tid == thread.GetID())
892 thread.SetStoppedBySignal(SIGSTOP, &info);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000893 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000894 thread.SetStoppedWithNoReason();
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000895
Kate Stoneb9c1b512016-09-06 20:57:50 +0000896 SetCurrentThreadID(thread.GetID());
897 SignalIfAllThreadsStopped();
898 } else {
899 // We can end up here if stop was initiated by LLGS but by this time a
900 // thread stop has occurred - maybe initiated by another event.
Zachary Turner97206d52017-05-12 04:51:55 +0000901 Status error = ResumeThread(thread, thread.GetState(), 0);
Pavel Labatha6321a82017-01-19 15:26:04 +0000902 if (error.Fail())
903 LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(),
904 error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000905 }
906 } else {
Pavel Labatha6321a82017-01-19 15:26:04 +0000907 LLDB_LOG(log,
908 "pid {0} tid {1}, thread was already marked as a stopped "
909 "state (state={2}), leaving stop signal as is",
Pavel Labath8198db32017-01-24 11:48:25 +0000910 GetID(), thread.GetID(), thread_state);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000911 SignalIfAllThreadsStopped();
Todd Fialaaf245d12014-06-30 21:05:18 +0000912 }
913
Kate Stoneb9c1b512016-09-06 20:57:50 +0000914 // Done handling.
915 return;
916 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000917
Pavel Labath4a705e72017-02-24 09:29:14 +0000918 // Check if debugger should stop at this signal or just ignore it
919 // and resume the inferior.
920 if (m_signals_to_ignore.find(signo) != m_signals_to_ignore.end()) {
921 ResumeThread(thread, thread.GetState(), signo);
922 return;
923 }
924
Kate Stoneb9c1b512016-09-06 20:57:50 +0000925 // This thread is stopped.
Pavel Labatha6321a82017-01-19 15:26:04 +0000926 LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000927 thread.SetStoppedBySignal(signo, &info);
928
929 // Send a stop to the debugger after we get all other threads to stop.
930 StopRunningThreads(thread.GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000931}
932
Tamas Berghammere7708682015-04-22 10:00:23 +0000933namespace {
934
Kate Stoneb9c1b512016-09-06 20:57:50 +0000935struct EmulatorBaton {
936 NativeProcessLinux *m_process;
937 NativeRegisterContext *m_reg_context;
Tamas Berghammere7708682015-04-22 10:00:23 +0000938
Kate Stoneb9c1b512016-09-06 20:57:50 +0000939 // eRegisterKindDWARF -> RegsiterValue
940 std::unordered_map<uint32_t, RegisterValue> m_register_values;
Pavel Labath6648fcc2015-04-27 09:21:14 +0000941
Kate Stoneb9c1b512016-09-06 20:57:50 +0000942 EmulatorBaton(NativeProcessLinux *process, NativeRegisterContext *reg_context)
943 : m_process(process), m_reg_context(reg_context) {}
Tamas Berghammere7708682015-04-22 10:00:23 +0000944};
945
946} // anonymous namespace
947
Kate Stoneb9c1b512016-09-06 20:57:50 +0000948static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
949 const EmulateInstruction::Context &context,
950 lldb::addr_t addr, void *dst, size_t length) {
951 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
Tamas Berghammere7708682015-04-22 10:00:23 +0000952
Kate Stoneb9c1b512016-09-06 20:57:50 +0000953 size_t bytes_read;
954 emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
955 return bytes_read;
Tamas Berghammere7708682015-04-22 10:00:23 +0000956}
957
Kate Stoneb9c1b512016-09-06 20:57:50 +0000958static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
959 const RegisterInfo *reg_info,
960 RegisterValue &reg_value) {
961 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
Tamas Berghammere7708682015-04-22 10:00:23 +0000962
Kate Stoneb9c1b512016-09-06 20:57:50 +0000963 auto it = emulator_baton->m_register_values.find(
964 reg_info->kinds[eRegisterKindDWARF]);
965 if (it != emulator_baton->m_register_values.end()) {
966 reg_value = it->second;
967 return true;
968 }
969
970 // The emulator only fill in the dwarf regsiter numbers (and in some case
971 // the generic register numbers). Get the full register info from the
972 // register context based on the dwarf register numbers.
973 const RegisterInfo *full_reg_info =
974 emulator_baton->m_reg_context->GetRegisterInfo(
975 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
976
Zachary Turner97206d52017-05-12 04:51:55 +0000977 Status error =
Kate Stoneb9c1b512016-09-06 20:57:50 +0000978 emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
979 if (error.Success())
980 return true;
981
982 return false;
983}
984
985static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
986 const EmulateInstruction::Context &context,
987 const RegisterInfo *reg_info,
988 const RegisterValue &reg_value) {
989 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
990 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
991 reg_value;
992 return true;
993}
994
995static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
996 const EmulateInstruction::Context &context,
997 lldb::addr_t addr, const void *dst,
998 size_t length) {
999 return length;
1000}
1001
1002static lldb::addr_t ReadFlags(NativeRegisterContext *regsiter_context) {
1003 const RegisterInfo *flags_info = regsiter_context->GetRegisterInfo(
1004 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1005 return regsiter_context->ReadRegisterAsUnsigned(flags_info,
1006 LLDB_INVALID_ADDRESS);
1007}
1008
Zachary Turner97206d52017-05-12 04:51:55 +00001009Status
1010NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadLinux &thread) {
1011 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001012 NativeRegisterContextSP register_context_sp = thread.GetRegisterContext();
1013
1014 std::unique_ptr<EmulateInstruction> emulator_ap(
1015 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying,
1016 nullptr));
1017
1018 if (emulator_ap == nullptr)
Zachary Turner97206d52017-05-12 04:51:55 +00001019 return Status("Instruction emulator not found!");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001020
1021 EmulatorBaton baton(this, register_context_sp.get());
1022 emulator_ap->SetBaton(&baton);
1023 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
1024 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
1025 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
1026 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
1027
1028 if (!emulator_ap->ReadInstruction())
Zachary Turner97206d52017-05-12 04:51:55 +00001029 return Status("Read instruction failed!");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001030
1031 bool emulation_result =
1032 emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
1033
1034 const RegisterInfo *reg_info_pc = register_context_sp->GetRegisterInfo(
1035 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1036 const RegisterInfo *reg_info_flags = register_context_sp->GetRegisterInfo(
1037 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1038
1039 auto pc_it =
1040 baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1041 auto flags_it =
1042 baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
1043
1044 lldb::addr_t next_pc;
1045 lldb::addr_t next_flags;
1046 if (emulation_result) {
1047 assert(pc_it != baton.m_register_values.end() &&
1048 "Emulation was successfull but PC wasn't updated");
1049 next_pc = pc_it->second.GetAsUInt64();
1050
1051 if (flags_it != baton.m_register_values.end())
1052 next_flags = flags_it->second.GetAsUInt64();
1053 else
1054 next_flags = ReadFlags(register_context_sp.get());
1055 } else if (pc_it == baton.m_register_values.end()) {
1056 // Emulate instruction failed and it haven't changed PC. Advance PC
1057 // with the size of the current opcode because the emulation of all
1058 // PC modifying instruction should be successful. The failure most
1059 // likely caused by a not supported instruction which don't modify PC.
1060 next_pc =
1061 register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
1062 next_flags = ReadFlags(register_context_sp.get());
1063 } else {
1064 // The instruction emulation failed after it modified the PC. It is an
1065 // unknown error where we can't continue because the next instruction is
1066 // modifying the PC but we don't know how.
Zachary Turner97206d52017-05-12 04:51:55 +00001067 return Status("Instruction emulation failed unexpectedly.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001068 }
1069
1070 if (m_arch.GetMachine() == llvm::Triple::arm) {
1071 if (next_flags & 0x20) {
1072 // Thumb mode
1073 error = SetSoftwareBreakpoint(next_pc, 2);
1074 } else {
1075 // Arm mode
1076 error = SetSoftwareBreakpoint(next_pc, 4);
Pavel Labath6648fcc2015-04-27 09:21:14 +00001077 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001078 } else if (m_arch.GetMachine() == llvm::Triple::mips64 ||
1079 m_arch.GetMachine() == llvm::Triple::mips64el ||
1080 m_arch.GetMachine() == llvm::Triple::mips ||
1081 m_arch.GetMachine() == llvm::Triple::mipsel)
1082 error = SetSoftwareBreakpoint(next_pc, 4);
1083 else {
1084 // No size hint is given for the next breakpoint
1085 error = SetSoftwareBreakpoint(next_pc, 0);
1086 }
Pavel Labath6648fcc2015-04-27 09:21:14 +00001087
Pavel Labath42eb6902016-10-26 11:13:56 +00001088 // If setting the breakpoint fails because next_pc is out of
1089 // the address space, ignore it and let the debugee segfault.
1090 if (error.GetError() == EIO || error.GetError() == EFAULT) {
Zachary Turner97206d52017-05-12 04:51:55 +00001091 return Status();
Pavel Labath42eb6902016-10-26 11:13:56 +00001092 } else if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001093 return error;
Tamas Berghammere7708682015-04-22 10:00:23 +00001094
Kate Stoneb9c1b512016-09-06 20:57:50 +00001095 m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001096
Zachary Turner97206d52017-05-12 04:51:55 +00001097 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001098}
1099
1100bool NativeProcessLinux::SupportHardwareSingleStepping() const {
1101 if (m_arch.GetMachine() == llvm::Triple::arm ||
1102 m_arch.GetMachine() == llvm::Triple::mips64 ||
1103 m_arch.GetMachine() == llvm::Triple::mips64el ||
1104 m_arch.GetMachine() == llvm::Triple::mips ||
1105 m_arch.GetMachine() == llvm::Triple::mipsel)
Pavel Labath6648fcc2015-04-27 09:21:14 +00001106 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001107 return true;
Tamas Berghammere7708682015-04-22 10:00:23 +00001108}
1109
Zachary Turner97206d52017-05-12 04:51:55 +00001110Status NativeProcessLinux::Resume(const ResumeActionList &resume_actions) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001111 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1112 LLDB_LOG(log, "pid {0}", GetID());
Tamas Berghammere7708682015-04-22 10:00:23 +00001113
Kate Stoneb9c1b512016-09-06 20:57:50 +00001114 bool software_single_step = !SupportHardwareSingleStepping();
Tamas Berghammere7708682015-04-22 10:00:23 +00001115
Kate Stoneb9c1b512016-09-06 20:57:50 +00001116 if (software_single_step) {
1117 for (auto thread_sp : m_threads) {
1118 assert(thread_sp && "thread list should not contain NULL threads");
Tamas Berghammere7708682015-04-22 10:00:23 +00001119
Kate Stoneb9c1b512016-09-06 20:57:50 +00001120 const ResumeAction *const action =
1121 resume_actions.GetActionForThread(thread_sp->GetID(), true);
1122 if (action == nullptr)
1123 continue;
Tamas Berghammere7708682015-04-22 10:00:23 +00001124
Kate Stoneb9c1b512016-09-06 20:57:50 +00001125 if (action->state == eStateStepping) {
Zachary Turner97206d52017-05-12 04:51:55 +00001126 Status error = SetupSoftwareSingleStepping(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001127 static_cast<NativeThreadLinux &>(*thread_sp));
1128 if (error.Fail())
1129 return error;
1130 }
Tamas Berghammere7708682015-04-22 10:00:23 +00001131 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001132 }
1133
1134 for (auto thread_sp : m_threads) {
1135 assert(thread_sp && "thread list should not contain NULL threads");
1136
1137 const ResumeAction *const action =
1138 resume_actions.GetActionForThread(thread_sp->GetID(), true);
1139
1140 if (action == nullptr) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001141 LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
1142 thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001143 continue;
Tamas Berghammere7708682015-04-22 10:00:23 +00001144 }
1145
Pavel Labatha6321a82017-01-19 15:26:04 +00001146 LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}",
Pavel Labath8198db32017-01-24 11:48:25 +00001147 action->state, GetID(), thread_sp->GetID());
Tamas Berghammere7708682015-04-22 10:00:23 +00001148
Kate Stoneb9c1b512016-09-06 20:57:50 +00001149 switch (action->state) {
1150 case eStateRunning:
1151 case eStateStepping: {
1152 // Run the thread, possibly feeding it the signal.
1153 const int signo = action->signal;
1154 ResumeThread(static_cast<NativeThreadLinux &>(*thread_sp), action->state,
1155 signo);
1156 break;
1157 }
Tamas Berghammere7708682015-04-22 10:00:23 +00001158
Kate Stoneb9c1b512016-09-06 20:57:50 +00001159 case eStateSuspended:
1160 case eStateStopped:
Pavel Labatha6321a82017-01-19 15:26:04 +00001161 llvm_unreachable("Unexpected state");
Tamas Berghammere7708682015-04-22 10:00:23 +00001162
Kate Stoneb9c1b512016-09-06 20:57:50 +00001163 default:
Zachary Turner97206d52017-05-12 04:51:55 +00001164 return Status("NativeProcessLinux::%s (): unexpected state %s specified "
1165 "for pid %" PRIu64 ", tid %" PRIu64,
1166 __FUNCTION__, StateAsCString(action->state), GetID(),
1167 thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001168 }
1169 }
1170
Zachary Turner97206d52017-05-12 04:51:55 +00001171 return Status();
Tamas Berghammere7708682015-04-22 10:00:23 +00001172}
1173
Zachary Turner97206d52017-05-12 04:51:55 +00001174Status NativeProcessLinux::Halt() {
1175 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001176
1177 if (kill(GetID(), SIGSTOP) != 0)
1178 error.SetErrorToErrno();
1179
1180 return error;
Tamas Berghammere7708682015-04-22 10:00:23 +00001181}
1182
Zachary Turner97206d52017-05-12 04:51:55 +00001183Status NativeProcessLinux::Detach() {
1184 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001185
1186 // Stop monitoring the inferior.
1187 m_sigchld_handle.reset();
1188
1189 // Tell ptrace to detach from the process.
1190 if (GetID() == LLDB_INVALID_PROCESS_ID)
1191 return error;
1192
1193 for (auto thread_sp : m_threads) {
Zachary Turner97206d52017-05-12 04:51:55 +00001194 Status e = Detach(thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001195 if (e.Fail())
1196 error =
1197 e; // Save the error, but still attempt to detach from other threads.
1198 }
1199
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001200 m_processor_trace_monitor.clear();
1201 m_pt_proces_trace_id = LLDB_INVALID_UID;
1202
Kate Stoneb9c1b512016-09-06 20:57:50 +00001203 return error;
1204}
1205
Zachary Turner97206d52017-05-12 04:51:55 +00001206Status NativeProcessLinux::Signal(int signo) {
1207 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001208
Pavel Labatha6321a82017-01-19 15:26:04 +00001209 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1210 LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo,
1211 Host::GetSignalAsCString(signo), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001212
1213 if (kill(GetID(), signo))
1214 error.SetErrorToErrno();
1215
1216 return error;
1217}
1218
Zachary Turner97206d52017-05-12 04:51:55 +00001219Status NativeProcessLinux::Interrupt() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001220 // Pick a running thread (or if none, a not-dead stopped thread) as
1221 // the chosen thread that will be the stop-reason thread.
Pavel Labatha6321a82017-01-19 15:26:04 +00001222 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001223
1224 NativeThreadProtocolSP running_thread_sp;
1225 NativeThreadProtocolSP stopped_thread_sp;
1226
Pavel Labatha6321a82017-01-19 15:26:04 +00001227 LLDB_LOG(log, "selecting running thread for interrupt target");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001228 for (auto thread_sp : m_threads) {
1229 // The thread shouldn't be null but lets just cover that here.
1230 if (!thread_sp)
1231 continue;
1232
1233 // If we have a running or stepping thread, we'll call that the
1234 // target of the interrupt.
1235 const auto thread_state = thread_sp->GetState();
1236 if (thread_state == eStateRunning || thread_state == eStateStepping) {
1237 running_thread_sp = thread_sp;
1238 break;
1239 } else if (!stopped_thread_sp && StateIsStoppedState(thread_state, true)) {
1240 // Remember the first non-dead stopped thread. We'll use that as a backup
1241 // if there are no running threads.
1242 stopped_thread_sp = thread_sp;
1243 }
1244 }
1245
1246 if (!running_thread_sp && !stopped_thread_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00001247 Status error("found no running/stepping or live stopped threads as target "
1248 "for interrupt");
Pavel Labatha6321a82017-01-19 15:26:04 +00001249 LLDB_LOG(log, "skipping due to error: {0}", error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001250
1251 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001252 }
1253
1254 NativeThreadProtocolSP deferred_signal_thread_sp =
1255 running_thread_sp ? running_thread_sp : stopped_thread_sp;
1256
Pavel Labatha6321a82017-01-19 15:26:04 +00001257 LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(),
1258 running_thread_sp ? "running" : "stopped",
1259 deferred_signal_thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001260
1261 StopRunningThreads(deferred_signal_thread_sp->GetID());
1262
Zachary Turner97206d52017-05-12 04:51:55 +00001263 return Status();
Todd Fialaaf245d12014-06-30 21:05:18 +00001264}
1265
Zachary Turner97206d52017-05-12 04:51:55 +00001266Status NativeProcessLinux::Kill() {
Pavel Labatha6321a82017-01-19 15:26:04 +00001267 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1268 LLDB_LOG(log, "pid {0}", GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +00001269
Zachary Turner97206d52017-05-12 04:51:55 +00001270 Status error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001271
Kate Stoneb9c1b512016-09-06 20:57:50 +00001272 switch (m_state) {
1273 case StateType::eStateInvalid:
1274 case StateType::eStateExited:
1275 case StateType::eStateCrashed:
1276 case StateType::eStateDetached:
1277 case StateType::eStateUnloaded:
1278 // Nothing to do - the process is already dead.
Pavel Labatha6321a82017-01-19 15:26:04 +00001279 LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
Pavel Labath8198db32017-01-24 11:48:25 +00001280 m_state);
Todd Fialaaf245d12014-06-30 21:05:18 +00001281 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001282
Kate Stoneb9c1b512016-09-06 20:57:50 +00001283 case StateType::eStateConnected:
1284 case StateType::eStateAttaching:
1285 case StateType::eStateLaunching:
1286 case StateType::eStateStopped:
1287 case StateType::eStateRunning:
1288 case StateType::eStateStepping:
1289 case StateType::eStateSuspended:
1290 // We can try to kill a process in these states.
1291 break;
1292 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001293
Kate Stoneb9c1b512016-09-06 20:57:50 +00001294 if (kill(GetID(), SIGKILL) != 0) {
1295 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +00001296 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001297 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001298
Kate Stoneb9c1b512016-09-06 20:57:50 +00001299 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001300}
1301
Zachary Turner97206d52017-05-12 04:51:55 +00001302static Status
Pavel Labath15930862017-03-21 13:49:45 +00001303ParseMemoryRegionInfoFromProcMapsLine(llvm::StringRef &maps_line,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001304 MemoryRegionInfo &memory_region_info) {
1305 memory_region_info.Clear();
Todd Fialaaf245d12014-06-30 21:05:18 +00001306
Pavel Labath15930862017-03-21 13:49:45 +00001307 StringExtractor line_extractor(maps_line);
Todd Fialaaf245d12014-06-30 21:05:18 +00001308
Kate Stoneb9c1b512016-09-06 20:57:50 +00001309 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode
1310 // pathname
1311 // perms: rwxp (letter is present if set, '-' if not, final character is
1312 // p=private, s=shared).
Todd Fialaaf245d12014-06-30 21:05:18 +00001313
Kate Stoneb9c1b512016-09-06 20:57:50 +00001314 // Parse out the starting address
1315 lldb::addr_t start_address = line_extractor.GetHexMaxU64(false, 0);
Todd Fialaaf245d12014-06-30 21:05:18 +00001316
Kate Stoneb9c1b512016-09-06 20:57:50 +00001317 // Parse out hyphen separating start and end address from range.
1318 if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != '-'))
Zachary Turner97206d52017-05-12 04:51:55 +00001319 return Status(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001320 "malformed /proc/{pid}/maps entry, missing dash between address range");
Todd Fialaaf245d12014-06-30 21:05:18 +00001321
Kate Stoneb9c1b512016-09-06 20:57:50 +00001322 // Parse out the ending address
1323 lldb::addr_t end_address = line_extractor.GetHexMaxU64(false, start_address);
Todd Fialaaf245d12014-06-30 21:05:18 +00001324
Kate Stoneb9c1b512016-09-06 20:57:50 +00001325 // Parse out the space after the address.
1326 if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != ' '))
Zachary Turner97206d52017-05-12 04:51:55 +00001327 return Status(
1328 "malformed /proc/{pid}/maps entry, missing space after range");
Todd Fialaaf245d12014-06-30 21:05:18 +00001329
Kate Stoneb9c1b512016-09-06 20:57:50 +00001330 // Save the range.
1331 memory_region_info.GetRange().SetRangeBase(start_address);
1332 memory_region_info.GetRange().SetRangeEnd(end_address);
Todd Fialaaf245d12014-06-30 21:05:18 +00001333
Kate Stoneb9c1b512016-09-06 20:57:50 +00001334 // Any memory region in /proc/{pid}/maps is by definition mapped into the
1335 // process.
1336 memory_region_info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
Howard Hellyerad007562016-07-07 08:21:28 +00001337
Kate Stoneb9c1b512016-09-06 20:57:50 +00001338 // Parse out each permission entry.
1339 if (line_extractor.GetBytesLeft() < 4)
Zachary Turner97206d52017-05-12 04:51:55 +00001340 return Status("malformed /proc/{pid}/maps entry, missing some portion of "
1341 "permissions");
Todd Fialaaf245d12014-06-30 21:05:18 +00001342
Kate Stoneb9c1b512016-09-06 20:57:50 +00001343 // Handle read permission.
1344 const char read_perm_char = line_extractor.GetChar();
1345 if (read_perm_char == 'r')
1346 memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eYes);
1347 else if (read_perm_char == '-')
1348 memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1349 else
Zachary Turner97206d52017-05-12 04:51:55 +00001350 return Status("unexpected /proc/{pid}/maps read permission char");
Todd Fialaaf245d12014-06-30 21:05:18 +00001351
Kate Stoneb9c1b512016-09-06 20:57:50 +00001352 // Handle write permission.
1353 const char write_perm_char = line_extractor.GetChar();
1354 if (write_perm_char == 'w')
1355 memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eYes);
1356 else if (write_perm_char == '-')
1357 memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1358 else
Zachary Turner97206d52017-05-12 04:51:55 +00001359 return Status("unexpected /proc/{pid}/maps write permission char");
Todd Fialaaf245d12014-06-30 21:05:18 +00001360
Kate Stoneb9c1b512016-09-06 20:57:50 +00001361 // Handle execute permission.
1362 const char exec_perm_char = line_extractor.GetChar();
1363 if (exec_perm_char == 'x')
1364 memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes);
1365 else if (exec_perm_char == '-')
1366 memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1367 else
Zachary Turner97206d52017-05-12 04:51:55 +00001368 return Status("unexpected /proc/{pid}/maps exec permission char");
Todd Fialaaf245d12014-06-30 21:05:18 +00001369
Kate Stoneb9c1b512016-09-06 20:57:50 +00001370 line_extractor.GetChar(); // Read the private bit
1371 line_extractor.SkipSpaces(); // Skip the separator
1372 line_extractor.GetHexMaxU64(false, 0); // Read the offset
1373 line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1374 line_extractor.GetChar(); // Read the device id separator
1375 line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1376 line_extractor.SkipSpaces(); // Skip the separator
1377 line_extractor.GetU64(0, 10); // Read the inode number
Tamas Berghammerd7d69f82016-07-22 12:55:35 +00001378
Kate Stoneb9c1b512016-09-06 20:57:50 +00001379 line_extractor.SkipSpaces();
1380 const char *name = line_extractor.Peek();
1381 if (name)
1382 memory_region_info.SetName(name);
Tamas Berghammerd7d69f82016-07-22 12:55:35 +00001383
Zachary Turner97206d52017-05-12 04:51:55 +00001384 return Status();
Todd Fialaaf245d12014-06-30 21:05:18 +00001385}
1386
Zachary Turner97206d52017-05-12 04:51:55 +00001387Status NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr,
1388 MemoryRegionInfo &range_info) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001389 // FIXME review that the final memory region returned extends to the end of
1390 // the virtual address space,
1391 // with no perms if it is not mapped.
Todd Fialaaf245d12014-06-30 21:05:18 +00001392
Kate Stoneb9c1b512016-09-06 20:57:50 +00001393 // Use an approach that reads memory regions from /proc/{pid}/maps.
1394 // Assume proc maps entries are in ascending order.
1395 // FIXME assert if we find differently.
Todd Fialaaf245d12014-06-30 21:05:18 +00001396
Kate Stoneb9c1b512016-09-06 20:57:50 +00001397 if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
1398 // We're done.
Zachary Turner97206d52017-05-12 04:51:55 +00001399 return Status("unsupported");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001400 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001401
Zachary Turner97206d52017-05-12 04:51:55 +00001402 Status error = PopulateMemoryRegionCache();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001403 if (error.Fail()) {
1404 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001405 }
1406
1407 lldb::addr_t prev_base_address = 0;
1408
1409 // FIXME start by finding the last region that is <= target address using
1410 // binary search. Data is sorted.
1411 // There can be a ton of regions on pthreads apps with lots of threads.
1412 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1413 ++it) {
Tamas Berghammera6f57952017-01-03 16:29:43 +00001414 MemoryRegionInfo &proc_entry_info = it->first;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001415
1416 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1417 assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
1418 "descending /proc/pid/maps entries detected, unexpected");
1419 prev_base_address = proc_entry_info.GetRange().GetRangeBase();
Hafiz Abid Qadeerb1554312017-01-20 10:24:03 +00001420 UNUSED_IF_ASSERT_DISABLED(prev_base_address);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001421
1422 // If the target address comes before this entry, indicate distance to next
1423 // region.
1424 if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1425 range_info.GetRange().SetRangeBase(load_addr);
1426 range_info.GetRange().SetByteSize(
1427 proc_entry_info.GetRange().GetRangeBase() - load_addr);
1428 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1429 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1430 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1431 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1432
1433 return error;
1434 } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1435 // The target address is within the memory region we're processing here.
1436 range_info = proc_entry_info;
1437 return error;
1438 }
1439
1440 // The target memory address comes somewhere after the region we just
1441 // parsed.
1442 }
1443
1444 // If we made it here, we didn't find an entry that contained the given
1445 // address. Return the
1446 // load_addr as start and the amount of bytes betwwen load address and the end
1447 // of the memory as
1448 // size.
1449 range_info.GetRange().SetRangeBase(load_addr);
1450 range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
1451 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1452 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1453 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1454 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1455 return error;
1456}
1457
Zachary Turner97206d52017-05-12 04:51:55 +00001458Status NativeProcessLinux::PopulateMemoryRegionCache() {
Pavel Labatha6321a82017-01-19 15:26:04 +00001459 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Tamas Berghammera6f57952017-01-03 16:29:43 +00001460
1461 // If our cache is empty, pull the latest. There should always be at least
1462 // one memory region if memory region handling is supported.
1463 if (!m_mem_region_cache.empty()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001464 LLDB_LOG(log, "reusing {0} cached memory region entries",
1465 m_mem_region_cache.size());
Zachary Turner97206d52017-05-12 04:51:55 +00001466 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001467 }
1468
Pavel Labath15930862017-03-21 13:49:45 +00001469 auto BufferOrError = getProcFile(GetID(), "maps");
1470 if (!BufferOrError) {
Tamas Berghammera6f57952017-01-03 16:29:43 +00001471 m_supports_mem_region = LazyBool::eLazyBoolNo;
Pavel Labath15930862017-03-21 13:49:45 +00001472 return BufferOrError.getError();
1473 }
1474 StringRef Rest = BufferOrError.get()->getBuffer();
1475 while (! Rest.empty()) {
1476 StringRef Line;
1477 std::tie(Line, Rest) = Rest.split('\n');
1478 MemoryRegionInfo info;
Zachary Turner97206d52017-05-12 04:51:55 +00001479 const Status parse_error =
1480 ParseMemoryRegionInfoFromProcMapsLine(Line, info);
Pavel Labath15930862017-03-21 13:49:45 +00001481 if (parse_error.Fail()) {
1482 LLDB_LOG(log, "failed to parse proc maps line '{0}': {1}", Line,
1483 parse_error);
1484 m_supports_mem_region = LazyBool::eLazyBoolNo;
1485 return parse_error;
1486 }
1487 m_mem_region_cache.emplace_back(
1488 info, FileSpec(info.GetName().GetCString(), true));
1489 }
1490
1491 if (m_mem_region_cache.empty()) {
Tamas Berghammera6f57952017-01-03 16:29:43 +00001492 // No entries after attempting to read them. This shouldn't happen if
1493 // /proc/{pid}/maps is supported. Assume we don't support map entries
1494 // via procfs.
Pavel Labath15930862017-03-21 13:49:45 +00001495 m_supports_mem_region = LazyBool::eLazyBoolNo;
Pavel Labatha6321a82017-01-19 15:26:04 +00001496 LLDB_LOG(log,
1497 "failed to find any procfs maps entries, assuming no support "
1498 "for memory region metadata retrieval");
Zachary Turner97206d52017-05-12 04:51:55 +00001499 return Status("not supported");
Tamas Berghammera6f57952017-01-03 16:29:43 +00001500 }
1501
Pavel Labatha6321a82017-01-19 15:26:04 +00001502 LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps",
1503 m_mem_region_cache.size(), GetID());
Tamas Berghammera6f57952017-01-03 16:29:43 +00001504
1505 // We support memory retrieval, remember that.
1506 m_supports_mem_region = LazyBool::eLazyBoolYes;
Zachary Turner97206d52017-05-12 04:51:55 +00001507 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001508}
1509
Kate Stoneb9c1b512016-09-06 20:57:50 +00001510void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001511 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1512 LLDB_LOG(log, "newBumpId={0}", newBumpId);
1513 LLDB_LOG(log, "clearing {0} entries from memory region cache",
1514 m_mem_region_cache.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001515 m_mem_region_cache.clear();
1516}
1517
Zachary Turner97206d52017-05-12 04:51:55 +00001518Status NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions,
1519 lldb::addr_t &addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001520// FIXME implementing this requires the equivalent of
1521// InferiorCallPOSIX::InferiorCallMmap, which depends on
1522// functional ThreadPlans working with Native*Protocol.
1523#if 1
Zachary Turner97206d52017-05-12 04:51:55 +00001524 return Status("not implemented yet");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001525#else
1526 addr = LLDB_INVALID_ADDRESS;
1527
1528 unsigned prot = 0;
1529 if (permissions & lldb::ePermissionsReadable)
1530 prot |= eMmapProtRead;
1531 if (permissions & lldb::ePermissionsWritable)
1532 prot |= eMmapProtWrite;
1533 if (permissions & lldb::ePermissionsExecutable)
1534 prot |= eMmapProtExec;
1535
1536 // TODO implement this directly in NativeProcessLinux
1537 // (and lift to NativeProcessPOSIX if/when that class is
1538 // refactored out).
1539 if (InferiorCallMmap(this, addr, 0, size, prot,
1540 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
1541 m_addr_to_mmap_size[addr] = size;
Zachary Turner97206d52017-05-12 04:51:55 +00001542 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001543 } else {
1544 addr = LLDB_INVALID_ADDRESS;
Zachary Turner97206d52017-05-12 04:51:55 +00001545 return Status("unable to allocate %" PRIu64
1546 " bytes of memory with permissions %s",
1547 size, GetPermissionsAsCString(permissions));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001548 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001549#endif
1550}
1551
Zachary Turner97206d52017-05-12 04:51:55 +00001552Status NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001553 // FIXME see comments in AllocateMemory - required lower-level
1554 // bits not in place yet (ThreadPlans)
Zachary Turner97206d52017-05-12 04:51:55 +00001555 return Status("not implemented");
Todd Fialaaf245d12014-06-30 21:05:18 +00001556}
1557
Kate Stoneb9c1b512016-09-06 20:57:50 +00001558lldb::addr_t NativeProcessLinux::GetSharedLibraryInfoAddress() {
1559 // punt on this for now
1560 return LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00001561}
1562
Kate Stoneb9c1b512016-09-06 20:57:50 +00001563size_t NativeProcessLinux::UpdateThreads() {
1564 // The NativeProcessLinux monitoring threads are always up to date
1565 // with respect to thread state and they keep the thread list
1566 // populated properly. All this method needs to do is return the
1567 // thread count.
1568 return m_threads.size();
Todd Fialaaf245d12014-06-30 21:05:18 +00001569}
1570
Kate Stoneb9c1b512016-09-06 20:57:50 +00001571bool NativeProcessLinux::GetArchitecture(ArchSpec &arch) const {
1572 arch = m_arch;
1573 return true;
Todd Fialaaf245d12014-06-30 21:05:18 +00001574}
1575
Zachary Turner97206d52017-05-12 04:51:55 +00001576Status NativeProcessLinux::GetSoftwareBreakpointPCOffset(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001577 uint32_t &actual_opcode_size) {
1578 // FIXME put this behind a breakpoint protocol class that can be
1579 // set per architecture. Need ARM, MIPS support here.
1580 static const uint8_t g_i386_opcode[] = {0xCC};
1581 static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
Todd Fialaaf245d12014-06-30 21:05:18 +00001582
Kate Stoneb9c1b512016-09-06 20:57:50 +00001583 switch (m_arch.GetMachine()) {
1584 case llvm::Triple::x86:
1585 case llvm::Triple::x86_64:
1586 actual_opcode_size = static_cast<uint32_t>(sizeof(g_i386_opcode));
Zachary Turner97206d52017-05-12 04:51:55 +00001587 return Status();
Todd Fialaaf245d12014-06-30 21:05:18 +00001588
Kate Stoneb9c1b512016-09-06 20:57:50 +00001589 case llvm::Triple::systemz:
1590 actual_opcode_size = static_cast<uint32_t>(sizeof(g_s390x_opcode));
Zachary Turner97206d52017-05-12 04:51:55 +00001591 return Status();
Ulrich Weigandbb00d0b2016-04-14 14:28:34 +00001592
Kate Stoneb9c1b512016-09-06 20:57:50 +00001593 case llvm::Triple::arm:
1594 case llvm::Triple::aarch64:
1595 case llvm::Triple::mips64:
1596 case llvm::Triple::mips64el:
1597 case llvm::Triple::mips:
1598 case llvm::Triple::mipsel:
1599 // On these architectures the PC don't get updated for breakpoint hits
1600 actual_opcode_size = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00001601 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001602
1603 default:
1604 assert(false && "CPU type not supported!");
Zachary Turner97206d52017-05-12 04:51:55 +00001605 return Status("CPU type not supported");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001606 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001607}
1608
Zachary Turner97206d52017-05-12 04:51:55 +00001609Status NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,
1610 bool hardware) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001611 if (hardware)
Omair Javaidd5ffbad2017-02-24 13:27:31 +00001612 return SetHardwareBreakpoint(addr, size);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001613 else
1614 return SetSoftwareBreakpoint(addr, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00001615}
1616
Zachary Turner97206d52017-05-12 04:51:55 +00001617Status NativeProcessLinux::RemoveBreakpoint(lldb::addr_t addr, bool hardware) {
Omair Javaidd5ffbad2017-02-24 13:27:31 +00001618 if (hardware)
1619 return RemoveHardwareBreakpoint(addr);
1620 else
1621 return NativeProcessProtocol::RemoveBreakpoint(addr);
1622}
1623
Zachary Turner97206d52017-05-12 04:51:55 +00001624Status NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001625 size_t trap_opcode_size_hint, size_t &actual_opcode_size,
1626 const uint8_t *&trap_opcode_bytes) {
1627 // FIXME put this behind a breakpoint protocol class that can be set per
1628 // architecture. Need MIPS support here.
1629 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};
1630 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1631 // linux kernel does otherwise.
1632 static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1633 static const uint8_t g_i386_opcode[] = {0xCC};
1634 static const uint8_t g_mips64_opcode[] = {0x00, 0x00, 0x00, 0x0d};
1635 static const uint8_t g_mips64el_opcode[] = {0x0d, 0x00, 0x00, 0x00};
1636 static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
1637 static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
Todd Fialaaf245d12014-06-30 21:05:18 +00001638
Kate Stoneb9c1b512016-09-06 20:57:50 +00001639 switch (m_arch.GetMachine()) {
1640 case llvm::Triple::aarch64:
1641 trap_opcode_bytes = g_aarch64_opcode;
1642 actual_opcode_size = sizeof(g_aarch64_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001643 return Status();
Todd Fiala2afc5962014-08-21 16:42:31 +00001644
Kate Stoneb9c1b512016-09-06 20:57:50 +00001645 case llvm::Triple::arm:
1646 switch (trap_opcode_size_hint) {
1647 case 2:
1648 trap_opcode_bytes = g_thumb_breakpoint_opcode;
1649 actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001650 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001651 case 4:
1652 trap_opcode_bytes = g_arm_breakpoint_opcode;
1653 actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001654 return Status();
Todd Fialaaf245d12014-06-30 21:05:18 +00001655 default:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001656 assert(false && "Unrecognised trap opcode size hint!");
Zachary Turner97206d52017-05-12 04:51:55 +00001657 return Status("Unrecognised trap opcode size hint!");
Todd Fialaaf245d12014-06-30 21:05:18 +00001658 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001659
1660 case llvm::Triple::x86:
1661 case llvm::Triple::x86_64:
1662 trap_opcode_bytes = g_i386_opcode;
1663 actual_opcode_size = sizeof(g_i386_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001664 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001665
1666 case llvm::Triple::mips:
1667 case llvm::Triple::mips64:
1668 trap_opcode_bytes = g_mips64_opcode;
1669 actual_opcode_size = sizeof(g_mips64_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001670 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001671
1672 case llvm::Triple::mipsel:
1673 case llvm::Triple::mips64el:
1674 trap_opcode_bytes = g_mips64el_opcode;
1675 actual_opcode_size = sizeof(g_mips64el_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001676 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001677
1678 case llvm::Triple::systemz:
1679 trap_opcode_bytes = g_s390x_opcode;
1680 actual_opcode_size = sizeof(g_s390x_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001681 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001682
1683 default:
1684 assert(false && "CPU type not supported!");
Zachary Turner97206d52017-05-12 04:51:55 +00001685 return Status("CPU type not supported");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001686 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001687}
1688
1689#if 0
1690ProcessMessage::CrashReason
1691NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
1692{
1693 ProcessMessage::CrashReason reason;
1694 assert(info->si_signo == SIGSEGV);
1695
1696 reason = ProcessMessage::eInvalidCrashReason;
1697
1698 switch (info->si_code)
1699 {
1700 default:
1701 assert(false && "unexpected si_code for SIGSEGV");
1702 break;
1703 case SI_KERNEL:
1704 // Linux will occasionally send spurious SI_KERNEL codes.
1705 // (this is poorly documented in sigaction)
1706 // One way to get this is via unaligned SIMD loads.
1707 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
1708 break;
1709 case SEGV_MAPERR:
1710 reason = ProcessMessage::eInvalidAddress;
1711 break;
1712 case SEGV_ACCERR:
1713 reason = ProcessMessage::ePrivilegedAddress;
1714 break;
1715 }
1716
1717 return reason;
1718}
1719#endif
1720
Todd Fialaaf245d12014-06-30 21:05:18 +00001721#if 0
1722ProcessMessage::CrashReason
1723NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
1724{
1725 ProcessMessage::CrashReason reason;
1726 assert(info->si_signo == SIGILL);
1727
1728 reason = ProcessMessage::eInvalidCrashReason;
1729
1730 switch (info->si_code)
1731 {
1732 default:
1733 assert(false && "unexpected si_code for SIGILL");
1734 break;
1735 case ILL_ILLOPC:
1736 reason = ProcessMessage::eIllegalOpcode;
1737 break;
1738 case ILL_ILLOPN:
1739 reason = ProcessMessage::eIllegalOperand;
1740 break;
1741 case ILL_ILLADR:
1742 reason = ProcessMessage::eIllegalAddressingMode;
1743 break;
1744 case ILL_ILLTRP:
1745 reason = ProcessMessage::eIllegalTrap;
1746 break;
1747 case ILL_PRVOPC:
1748 reason = ProcessMessage::ePrivilegedOpcode;
1749 break;
1750 case ILL_PRVREG:
1751 reason = ProcessMessage::ePrivilegedRegister;
1752 break;
1753 case ILL_COPROC:
1754 reason = ProcessMessage::eCoprocessorError;
1755 break;
1756 case ILL_BADSTK:
1757 reason = ProcessMessage::eInternalStackError;
1758 break;
1759 }
1760
1761 return reason;
1762}
1763#endif
1764
1765#if 0
1766ProcessMessage::CrashReason
1767NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
1768{
1769 ProcessMessage::CrashReason reason;
1770 assert(info->si_signo == SIGFPE);
1771
1772 reason = ProcessMessage::eInvalidCrashReason;
1773
1774 switch (info->si_code)
1775 {
1776 default:
1777 assert(false && "unexpected si_code for SIGFPE");
1778 break;
1779 case FPE_INTDIV:
1780 reason = ProcessMessage::eIntegerDivideByZero;
1781 break;
1782 case FPE_INTOVF:
1783 reason = ProcessMessage::eIntegerOverflow;
1784 break;
1785 case FPE_FLTDIV:
1786 reason = ProcessMessage::eFloatDivideByZero;
1787 break;
1788 case FPE_FLTOVF:
1789 reason = ProcessMessage::eFloatOverflow;
1790 break;
1791 case FPE_FLTUND:
1792 reason = ProcessMessage::eFloatUnderflow;
1793 break;
1794 case FPE_FLTRES:
1795 reason = ProcessMessage::eFloatInexactResult;
1796 break;
1797 case FPE_FLTINV:
1798 reason = ProcessMessage::eFloatInvalidOperation;
1799 break;
1800 case FPE_FLTSUB:
1801 reason = ProcessMessage::eFloatSubscriptRange;
1802 break;
1803 }
1804
1805 return reason;
1806}
1807#endif
1808
1809#if 0
1810ProcessMessage::CrashReason
1811NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
1812{
1813 ProcessMessage::CrashReason reason;
1814 assert(info->si_signo == SIGBUS);
1815
1816 reason = ProcessMessage::eInvalidCrashReason;
1817
1818 switch (info->si_code)
1819 {
1820 default:
1821 assert(false && "unexpected si_code for SIGBUS");
1822 break;
1823 case BUS_ADRALN:
1824 reason = ProcessMessage::eIllegalAlignment;
1825 break;
1826 case BUS_ADRERR:
1827 reason = ProcessMessage::eIllegalAddress;
1828 break;
1829 case BUS_OBJERR:
1830 reason = ProcessMessage::eHardwareError;
1831 break;
1832 }
1833
1834 return reason;
1835}
1836#endif
1837
Zachary Turner97206d52017-05-12 04:51:55 +00001838Status NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
1839 size_t &bytes_read) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001840 if (ProcessVmReadvSupported()) {
1841 // The process_vm_readv path is about 50 times faster than ptrace api. We
1842 // want to use
1843 // this syscall if it is supported.
Pavel Labathdf7c6992015-06-17 18:38:49 +00001844
Kate Stoneb9c1b512016-09-06 20:57:50 +00001845 const ::pid_t pid = GetID();
Pavel Labathdf7c6992015-06-17 18:38:49 +00001846
Kate Stoneb9c1b512016-09-06 20:57:50 +00001847 struct iovec local_iov, remote_iov;
1848 local_iov.iov_base = buf;
1849 local_iov.iov_len = size;
1850 remote_iov.iov_base = reinterpret_cast<void *>(addr);
1851 remote_iov.iov_len = size;
Pavel Labathdf7c6992015-06-17 18:38:49 +00001852
Kate Stoneb9c1b512016-09-06 20:57:50 +00001853 bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
1854 const bool success = bytes_read == size;
Pavel Labathdf7c6992015-06-17 18:38:49 +00001855
Pavel Labatha6321a82017-01-19 15:26:04 +00001856 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1857 LLDB_LOG(log,
1858 "using process_vm_readv to read {0} bytes from inferior "
1859 "address {1:x}: {2}",
Pavel Labath10c41f32017-06-06 14:06:17 +00001860 size, addr, success ? "Success" : llvm::sys::StrError(errno));
Pavel Labath19cbe962015-07-21 13:20:32 +00001861
Kate Stoneb9c1b512016-09-06 20:57:50 +00001862 if (success)
Zachary Turner97206d52017-05-12 04:51:55 +00001863 return Status();
Pavel Labatha6321a82017-01-19 15:26:04 +00001864 // else the call failed for some reason, let's retry the read using ptrace
1865 // api.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001866 }
Pavel Labath19cbe962015-07-21 13:20:32 +00001867
Kate Stoneb9c1b512016-09-06 20:57:50 +00001868 unsigned char *dst = static_cast<unsigned char *>(buf);
1869 size_t remainder;
1870 long data;
Pavel Labath19cbe962015-07-21 13:20:32 +00001871
Pavel Labatha6321a82017-01-19 15:26:04 +00001872 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1873 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
Pavel Labath19cbe962015-07-21 13:20:32 +00001874
Kate Stoneb9c1b512016-09-06 20:57:50 +00001875 for (bytes_read = 0; bytes_read < size; bytes_read += remainder) {
Zachary Turner97206d52017-05-12 04:51:55 +00001876 Status error = NativeProcessLinux::PtraceWrapper(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001877 PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data);
Pavel Labatha6321a82017-01-19 15:26:04 +00001878 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001879 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001880
1881 remainder = size - bytes_read;
1882 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
1883
1884 // Copy the data into our buffer
1885 memcpy(dst, &data, remainder);
1886
Pavel Labatha6321a82017-01-19 15:26:04 +00001887 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001888 addr += k_ptrace_word_size;
1889 dst += k_ptrace_word_size;
1890 }
Zachary Turner97206d52017-05-12 04:51:55 +00001891 return Status();
Todd Fialaaf245d12014-06-30 21:05:18 +00001892}
1893
Zachary Turner97206d52017-05-12 04:51:55 +00001894Status NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf,
1895 size_t size,
1896 size_t &bytes_read) {
1897 Status error = ReadMemory(addr, buf, size, bytes_read);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001898 if (error.Fail())
Pavel Labath19cbe962015-07-21 13:20:32 +00001899 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001900 return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00001901}
1902
Zachary Turner97206d52017-05-12 04:51:55 +00001903Status NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,
1904 size_t size, size_t &bytes_written) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001905 const unsigned char *src = static_cast<const unsigned char *>(buf);
1906 size_t remainder;
Zachary Turner97206d52017-05-12 04:51:55 +00001907 Status error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001908
Pavel Labatha6321a82017-01-19 15:26:04 +00001909 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1910 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00001911
Kate Stoneb9c1b512016-09-06 20:57:50 +00001912 for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
1913 remainder = size - bytes_written;
1914 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
Chaoren Lin97ccc292015-02-03 01:51:12 +00001915
Kate Stoneb9c1b512016-09-06 20:57:50 +00001916 if (remainder == k_ptrace_word_size) {
1917 unsigned long data = 0;
1918 memcpy(&data, src, k_ptrace_word_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00001919
Pavel Labatha6321a82017-01-19 15:26:04 +00001920 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001921 error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(),
1922 (void *)addr, (void *)data);
Pavel Labatha6321a82017-01-19 15:26:04 +00001923 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001924 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001925 } else {
1926 unsigned char buff[8];
1927 size_t bytes_read;
1928 error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
Pavel Labatha6321a82017-01-19 15:26:04 +00001929 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001930 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001931
1932 memcpy(buff, src, remainder);
1933
1934 size_t bytes_written_rec;
1935 error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
Pavel Labatha6321a82017-01-19 15:26:04 +00001936 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001937 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001938
Pavel Labatha6321a82017-01-19 15:26:04 +00001939 LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src,
1940 *(unsigned long *)buff);
Todd Fialaaf245d12014-06-30 21:05:18 +00001941 }
1942
Kate Stoneb9c1b512016-09-06 20:57:50 +00001943 addr += k_ptrace_word_size;
1944 src += k_ptrace_word_size;
1945 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001946 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001947}
1948
Zachary Turner97206d52017-05-12 04:51:55 +00001949Status NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001950 return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
1951}
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001952
Zachary Turner97206d52017-05-12 04:51:55 +00001953Status NativeProcessLinux::GetEventMessage(lldb::tid_t tid,
1954 unsigned long *message) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001955 return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
1956}
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001957
Zachary Turner97206d52017-05-12 04:51:55 +00001958Status NativeProcessLinux::Detach(lldb::tid_t tid) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001959 if (tid == LLDB_INVALID_THREAD_ID)
Zachary Turner97206d52017-05-12 04:51:55 +00001960 return Status();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001961
Kate Stoneb9c1b512016-09-06 20:57:50 +00001962 return PtraceWrapper(PTRACE_DETACH, tid);
1963}
1964
1965bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {
1966 for (auto thread_sp : m_threads) {
1967 assert(thread_sp && "thread list should not contain NULL threads");
1968 if (thread_sp->GetID() == thread_id) {
1969 // We have this thread.
1970 return true;
Todd Fialaaf245d12014-06-30 21:05:18 +00001971 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001972 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001973
Kate Stoneb9c1b512016-09-06 20:57:50 +00001974 // We don't have this thread.
1975 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001976}
1977
Kate Stoneb9c1b512016-09-06 20:57:50 +00001978bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001979 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1980 LLDB_LOG(log, "tid: {0})", thread_id);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001981
1982 bool found = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001983 for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
1984 if (*it && ((*it)->GetID() == thread_id)) {
1985 m_threads.erase(it);
1986 found = true;
1987 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00001988 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001989 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001990
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001991 if (found)
1992 StopTracingForThread(thread_id);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001993 SignalIfAllThreadsStopped();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001994 return found;
Todd Fialaaf245d12014-06-30 21:05:18 +00001995}
1996
Kate Stoneb9c1b512016-09-06 20:57:50 +00001997NativeThreadLinuxSP NativeProcessLinux::AddThread(lldb::tid_t thread_id) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001998 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
1999 LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
Todd Fialaaf245d12014-06-30 21:05:18 +00002000
Kate Stoneb9c1b512016-09-06 20:57:50 +00002001 assert(!HasThreadNoLock(thread_id) &&
2002 "attempted to add a thread by id that already exists");
Todd Fialaaf245d12014-06-30 21:05:18 +00002003
Kate Stoneb9c1b512016-09-06 20:57:50 +00002004 // If this is the first thread, save it as the current thread
2005 if (m_threads.empty())
2006 SetCurrentThreadID(thread_id);
Todd Fialaaf245d12014-06-30 21:05:18 +00002007
Pavel Labath82abefa2017-07-18 09:24:48 +00002008 auto thread_sp = std::make_shared<NativeThreadLinux>(*this, thread_id);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002009 m_threads.push_back(thread_sp);
Ravitheja Addepally99e37692017-06-28 07:58:31 +00002010
2011 if (m_pt_proces_trace_id != LLDB_INVALID_UID) {
2012 auto traceMonitor = ProcessorTraceMonitor::Create(
2013 GetID(), thread_id, m_pt_process_trace_config, true);
2014 if (traceMonitor) {
2015 m_pt_traced_thread_group.insert(thread_id);
2016 m_processor_trace_monitor.insert(
2017 std::make_pair(thread_id, std::move(*traceMonitor)));
2018 } else {
2019 LLDB_LOG(log, "failed to start trace on thread {0}", thread_id);
2020 Status error(traceMonitor.takeError());
2021 LLDB_LOG(log, "error {0}", error);
2022 }
2023 }
2024
Kate Stoneb9c1b512016-09-06 20:57:50 +00002025 return thread_sp;
2026}
Todd Fialaaf245d12014-06-30 21:05:18 +00002027
Zachary Turner97206d52017-05-12 04:51:55 +00002028Status
2029NativeProcessLinux::FixupBreakpointPCAsNeeded(NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002030 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_BREAKPOINTS));
Todd Fialaaf245d12014-06-30 21:05:18 +00002031
Zachary Turner97206d52017-05-12 04:51:55 +00002032 Status error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002033
Kate Stoneb9c1b512016-09-06 20:57:50 +00002034 // Find out the size of a breakpoint (might depend on where we are in the
2035 // code).
2036 NativeRegisterContextSP context_sp = thread.GetRegisterContext();
2037 if (!context_sp) {
2038 error.SetErrorString("cannot get a NativeRegisterContext for the thread");
Pavel Labatha6321a82017-01-19 15:26:04 +00002039 LLDB_LOG(log, "failed: {0}", error);
Todd Fialaaf245d12014-06-30 21:05:18 +00002040 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002041 }
Chaoren Linfa03ad22015-02-03 01:50:42 +00002042
Kate Stoneb9c1b512016-09-06 20:57:50 +00002043 uint32_t breakpoint_size = 0;
2044 error = GetSoftwareBreakpointPCOffset(breakpoint_size);
2045 if (error.Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002046 LLDB_LOG(log, "GetBreakpointSize() failed: {0}", error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002047 return error;
Pavel Labatha6321a82017-01-19 15:26:04 +00002048 } else
2049 LLDB_LOG(log, "breakpoint size: {0}", breakpoint_size);
Pavel Labathc0765592015-05-06 10:46:34 +00002050
Kate Stoneb9c1b512016-09-06 20:57:50 +00002051 // First try probing for a breakpoint at a software breakpoint location: PC -
2052 // breakpoint size.
2053 const lldb::addr_t initial_pc_addr =
2054 context_sp->GetPCfromBreakpointLocation();
2055 lldb::addr_t breakpoint_addr = initial_pc_addr;
2056 if (breakpoint_size > 0) {
2057 // Do not allow breakpoint probe to wrap around.
2058 if (breakpoint_addr >= breakpoint_size)
2059 breakpoint_addr -= breakpoint_size;
2060 }
2061
2062 // Check if we stopped because of a breakpoint.
2063 NativeBreakpointSP breakpoint_sp;
2064 error = m_breakpoint_list.GetBreakpoint(breakpoint_addr, breakpoint_sp);
2065 if (!error.Success() || !breakpoint_sp) {
2066 // We didn't find one at a software probe location. Nothing to do.
Pavel Labatha6321a82017-01-19 15:26:04 +00002067 LLDB_LOG(log,
2068 "pid {0} no lldb breakpoint found at current pc with "
2069 "adjustment: {1}",
2070 GetID(), breakpoint_addr);
Zachary Turner97206d52017-05-12 04:51:55 +00002071 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002072 }
2073
2074 // If the breakpoint is not a software breakpoint, nothing to do.
2075 if (!breakpoint_sp->IsSoftwareBreakpoint()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002076 LLDB_LOG(
2077 log,
2078 "pid {0} breakpoint found at {1:x}, not software, nothing to adjust",
2079 GetID(), breakpoint_addr);
Zachary Turner97206d52017-05-12 04:51:55 +00002080 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002081 }
2082
2083 //
2084 // We have a software breakpoint and need to adjust the PC.
2085 //
2086
2087 // Sanity check.
2088 if (breakpoint_size == 0) {
2089 // Nothing to do! How did we get here?
Pavel Labatha6321a82017-01-19 15:26:04 +00002090 LLDB_LOG(log,
2091 "pid {0} breakpoint found at {1:x}, it is software, but the "
2092 "size is zero, nothing to do (unexpected)",
2093 GetID(), breakpoint_addr);
Zachary Turner97206d52017-05-12 04:51:55 +00002094 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002095 }
2096
2097 // Change the program counter.
Pavel Labatha6321a82017-01-19 15:26:04 +00002098 LLDB_LOG(log, "pid {0} tid {1}: changing PC from {2:x} to {3:x}", GetID(),
2099 thread.GetID(), initial_pc_addr, breakpoint_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002100
2101 error = context_sp->SetPC(breakpoint_addr);
2102 if (error.Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002103 LLDB_LOG(log, "pid {0} tid {1}: failed to set PC: {2}", GetID(),
2104 thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002105 return error;
2106 }
2107
2108 return error;
2109}
2110
Zachary Turner97206d52017-05-12 04:51:55 +00002111Status NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,
2112 FileSpec &file_spec) {
2113 Status error = PopulateMemoryRegionCache();
Tamas Berghammera6f57952017-01-03 16:29:43 +00002114 if (error.Fail())
2115 return error;
2116
Kate Stoneb9c1b512016-09-06 20:57:50 +00002117 FileSpec module_file_spec(module_path, true);
2118
Kate Stoneb9c1b512016-09-06 20:57:50 +00002119 file_spec.Clear();
Tamas Berghammera6f57952017-01-03 16:29:43 +00002120 for (const auto &it : m_mem_region_cache) {
2121 if (it.second.GetFilename() == module_file_spec.GetFilename()) {
2122 file_spec = it.second;
Zachary Turner97206d52017-05-12 04:51:55 +00002123 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00002124 }
2125 }
Zachary Turner97206d52017-05-12 04:51:55 +00002126 return Status("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
2127 module_file_spec.GetFilename().AsCString(), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002128}
2129
Zachary Turner97206d52017-05-12 04:51:55 +00002130Status NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
2131 lldb::addr_t &load_addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002132 load_addr = LLDB_INVALID_ADDRESS;
Zachary Turner97206d52017-05-12 04:51:55 +00002133 Status error = PopulateMemoryRegionCache();
Tamas Berghammera6f57952017-01-03 16:29:43 +00002134 if (error.Fail())
2135 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002136
Tamas Berghammera6f57952017-01-03 16:29:43 +00002137 FileSpec file(file_name, false);
2138 for (const auto &it : m_mem_region_cache) {
2139 if (it.second == file) {
2140 load_addr = it.first.GetRange().GetRangeBase();
Zachary Turner97206d52017-05-12 04:51:55 +00002141 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00002142 }
2143 }
Zachary Turner97206d52017-05-12 04:51:55 +00002144 return Status("No load address found for specified file.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002145}
2146
2147NativeThreadLinuxSP NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {
2148 return std::static_pointer_cast<NativeThreadLinux>(
2149 NativeProcessProtocol::GetThreadByID(tid));
2150}
2151
Zachary Turner97206d52017-05-12 04:51:55 +00002152Status NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,
2153 lldb::StateType state, int signo) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002154 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2155 LLDB_LOG(log, "tid: {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002156
2157 // Before we do the resume below, first check if we have a pending
2158 // stop notification that is currently waiting for
2159 // all threads to stop. This is potentially a buggy situation since
2160 // we're ostensibly waiting for threads to stop before we send out the
2161 // pending notification, and here we are resuming one before we send
2162 // out the pending stop notification.
Pavel Labatha6321a82017-01-19 15:26:04 +00002163 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
2164 LLDB_LOG(log,
2165 "about to resume tid {0} per explicit request but we have a "
2166 "pending stop notification (tid {1}) that is actively "
2167 "waiting for this thread to stop. Valid sequence of events?",
2168 thread.GetID(), m_pending_notification_tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002169 }
2170
2171 // Request a resume. We expect this to be synchronous and the system
2172 // to reflect it is running after this completes.
2173 switch (state) {
2174 case eStateRunning: {
2175 const auto resume_result = thread.Resume(signo);
2176 if (resume_result.Success())
2177 SetState(eStateRunning, true);
2178 return resume_result;
2179 }
2180 case eStateStepping: {
2181 const auto step_result = thread.SingleStep(signo);
2182 if (step_result.Success())
2183 SetState(eStateRunning, true);
2184 return step_result;
2185 }
2186 default:
Pavel Labath8198db32017-01-24 11:48:25 +00002187 LLDB_LOG(log, "Unhandled state {0}.", state);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002188 llvm_unreachable("Unhandled state for resume");
2189 }
Pavel Labathc0765592015-05-06 10:46:34 +00002190}
2191
2192//===----------------------------------------------------------------------===//
2193
Kate Stoneb9c1b512016-09-06 20:57:50 +00002194void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002195 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2196 LLDB_LOG(log, "about to process event: (triggering_tid: {0})",
2197 triggering_tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002198
2199 m_pending_notification_tid = triggering_tid;
2200
2201 // Request a stop for all the thread stops that need to be stopped
2202 // and are not already known to be stopped.
2203 for (const auto &thread_sp : m_threads) {
2204 if (StateIsRunningState(thread_sp->GetState()))
2205 static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
2206 }
2207
2208 SignalIfAllThreadsStopped();
Pavel Labatha6321a82017-01-19 15:26:04 +00002209 LLDB_LOG(log, "event processing done");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002210}
2211
2212void NativeProcessLinux::SignalIfAllThreadsStopped() {
2213 if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
2214 return; // No pending notification. Nothing to do.
2215
2216 for (const auto &thread_sp : m_threads) {
2217 if (StateIsRunningState(thread_sp->GetState()))
2218 return; // Some threads are still running. Don't signal yet.
2219 }
2220
2221 // We have a pending notification and all threads have stopped.
2222 Log *log(
2223 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
2224
2225 // Clear any temporary breakpoints we used to implement software single
2226 // stepping.
2227 for (const auto &thread_info : m_threads_stepping_with_breakpoint) {
Zachary Turner97206d52017-05-12 04:51:55 +00002228 Status error = RemoveBreakpoint(thread_info.second);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002229 if (error.Fail())
Pavel Labatha6321a82017-01-19 15:26:04 +00002230 LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}",
2231 thread_info.first, error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002232 }
2233 m_threads_stepping_with_breakpoint.clear();
2234
2235 // Notify the delegate about the stop
2236 SetCurrentThreadID(m_pending_notification_tid);
2237 SetState(StateType::eStateStopped, true);
2238 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
2239}
2240
2241void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002242 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2243 LLDB_LOG(log, "tid: {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002244
2245 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID &&
2246 StateIsRunningState(thread.GetState())) {
2247 // We will need to wait for this new thread to stop as well before firing
2248 // the
2249 // notification.
2250 thread.RequestStop();
2251 }
2252}
2253
2254void NativeProcessLinux::SigchldHandler() {
Pavel Labatha6321a82017-01-19 15:26:04 +00002255 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002256 // Process all pending waitpid notifications.
2257 while (true) {
2258 int status = -1;
Pavel Labathc1a6b122017-07-03 09:25:55 +00002259 ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, -1, &status,
2260 __WALL | __WNOTHREAD | WNOHANG);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002261
2262 if (wait_pid == 0)
2263 break; // We are done.
2264
2265 if (wait_pid == -1) {
Zachary Turner97206d52017-05-12 04:51:55 +00002266 Status error(errno, eErrorTypePOSIX);
Pavel Labatha6321a82017-01-19 15:26:04 +00002267 LLDB_LOG(log, "waitpid (-1, &status, _) failed: {0}", error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002268 break;
Pavel Labathc0765592015-05-06 10:46:34 +00002269 }
2270
Pavel Labath3508fc82017-06-19 12:47:50 +00002271 WaitStatus wait_status = WaitStatus::Decode(status);
2272 bool exited = wait_status.type == WaitStatus::Exit ||
2273 (wait_status.type == WaitStatus::Signal &&
2274 wait_pid == static_cast<::pid_t>(GetID()));
Pavel Labathc0765592015-05-06 10:46:34 +00002275
Pavel Labath3508fc82017-06-19 12:47:50 +00002276 LLDB_LOG(
2277 log,
2278 "waitpid (-1, &status, _) => pid = {0}, status = {1}, exited = {2}",
2279 wait_pid, wait_status, exited);
Pavel Labathc0765592015-05-06 10:46:34 +00002280
Pavel Labath3508fc82017-06-19 12:47:50 +00002281 MonitorCallback(wait_pid, exited, wait_status);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002282 }
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002283}
2284
2285// Wrapper for ptrace to catch errors and log calls.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002286// Note that ptrace sets errno on error because -1 can be a valid result (i.e.
2287// for PTRACE_PEEK*)
Zachary Turner97206d52017-05-12 04:51:55 +00002288Status NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
2289 void *data, size_t data_size,
2290 long *result) {
2291 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002292 long int ret;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002293
Kate Stoneb9c1b512016-09-06 20:57:50 +00002294 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002295
Kate Stoneb9c1b512016-09-06 20:57:50 +00002296 PtraceDisplayBytes(req, data, data_size);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002297
Kate Stoneb9c1b512016-09-06 20:57:50 +00002298 errno = 0;
2299 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
2300 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2301 *(unsigned int *)addr, data);
2302 else
2303 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2304 addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002305
Kate Stoneb9c1b512016-09-06 20:57:50 +00002306 if (ret == -1)
2307 error.SetErrorToErrno();
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002308
Kate Stoneb9c1b512016-09-06 20:57:50 +00002309 if (result)
2310 *result = ret;
Pavel Labath4a9babb2015-06-30 17:04:49 +00002311
Pavel Labath28096202017-02-17 16:09:10 +00002312 LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data,
2313 data_size, ret);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002314
Kate Stoneb9c1b512016-09-06 20:57:50 +00002315 PtraceDisplayBytes(req, data, data_size);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002316
Pavel Labatha6321a82017-01-19 15:26:04 +00002317 if (error.Fail())
2318 LLDB_LOG(log, "ptrace() failed: {0}", error);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002319
Kate Stoneb9c1b512016-09-06 20:57:50 +00002320 return error;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002321}
Ravitheja Addepally99e37692017-06-28 07:58:31 +00002322
2323llvm::Expected<ProcessorTraceMonitor &>
2324NativeProcessLinux::LookupProcessorTraceInstance(lldb::user_id_t traceid,
2325 lldb::tid_t thread) {
2326 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2327 if (thread == LLDB_INVALID_THREAD_ID && traceid == m_pt_proces_trace_id) {
2328 LLDB_LOG(log, "thread not specified: {0}", traceid);
2329 return Status("tracing not active thread not specified").ToError();
2330 }
2331
2332 for (auto& iter : m_processor_trace_monitor) {
2333 if (traceid == iter.second->GetTraceID() &&
2334 (thread == iter.first || thread == LLDB_INVALID_THREAD_ID))
2335 return *(iter.second);
2336 }
2337
2338 LLDB_LOG(log, "traceid not being traced: {0}", traceid);
2339 return Status("tracing not active for this thread").ToError();
2340}
2341
2342Status NativeProcessLinux::GetMetaData(lldb::user_id_t traceid,
2343 lldb::tid_t thread,
2344 llvm::MutableArrayRef<uint8_t> &buffer,
2345 size_t offset) {
2346 TraceOptions trace_options;
2347 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2348 Status error;
2349
2350 LLDB_LOG(log, "traceid {0}", traceid);
2351
2352 auto perf_monitor = LookupProcessorTraceInstance(traceid, thread);
2353 if (!perf_monitor) {
2354 LLDB_LOG(log, "traceid not being traced: {0}", traceid);
2355 buffer = buffer.slice(buffer.size());
2356 error = perf_monitor.takeError();
2357 return error;
2358 }
2359 return (*perf_monitor).ReadPerfTraceData(buffer, offset);
2360}
2361
2362Status NativeProcessLinux::GetData(lldb::user_id_t traceid, lldb::tid_t thread,
2363 llvm::MutableArrayRef<uint8_t> &buffer,
2364 size_t offset) {
2365 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2366 Status error;
2367
2368 LLDB_LOG(log, "traceid {0}", traceid);
2369
2370 auto perf_monitor = LookupProcessorTraceInstance(traceid, thread);
2371 if (!perf_monitor) {
2372 LLDB_LOG(log, "traceid not being traced: {0}", traceid);
2373 buffer = buffer.slice(buffer.size());
2374 error = perf_monitor.takeError();
2375 return error;
2376 }
2377 return (*perf_monitor).ReadPerfTraceAux(buffer, offset);
2378}
2379
2380Status NativeProcessLinux::GetTraceConfig(lldb::user_id_t traceid,
2381 TraceOptions &config) {
2382 Status error;
2383 if (config.getThreadID() == LLDB_INVALID_THREAD_ID &&
2384 m_pt_proces_trace_id == traceid) {
2385 if (m_pt_proces_trace_id == LLDB_INVALID_UID) {
2386 error.SetErrorString("tracing not active for this process");
2387 return error;
2388 }
2389 config = m_pt_process_trace_config;
2390 } else {
2391 auto perf_monitor =
2392 LookupProcessorTraceInstance(traceid, config.getThreadID());
2393 if (!perf_monitor) {
2394 error = perf_monitor.takeError();
2395 return error;
2396 }
2397 error = (*perf_monitor).GetTraceConfig(config);
2398 }
2399 return error;
2400}
2401
2402lldb::user_id_t
2403NativeProcessLinux::StartTraceGroup(const TraceOptions &config,
2404 Status &error) {
2405
2406 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2407 if (config.getType() != TraceType::eTraceTypeProcessorTrace)
2408 return LLDB_INVALID_UID;
2409
2410 if (m_pt_proces_trace_id != LLDB_INVALID_UID) {
2411 error.SetErrorString("tracing already active on this process");
2412 return m_pt_proces_trace_id;
2413 }
2414
2415 for (const auto &thread_sp : m_threads) {
2416 if (auto traceInstance = ProcessorTraceMonitor::Create(
2417 GetID(), thread_sp->GetID(), config, true)) {
2418 m_pt_traced_thread_group.insert(thread_sp->GetID());
2419 m_processor_trace_monitor.insert(
2420 std::make_pair(thread_sp->GetID(), std::move(*traceInstance)));
2421 }
2422 }
2423
2424 m_pt_process_trace_config = config;
2425 error = ProcessorTraceMonitor::GetCPUType(m_pt_process_trace_config);
2426
2427 // Trace on Complete process will have traceid of 0
2428 m_pt_proces_trace_id = 0;
2429
2430 LLDB_LOG(log, "Process Trace ID {0}", m_pt_proces_trace_id);
2431 return m_pt_proces_trace_id;
2432}
2433
2434lldb::user_id_t NativeProcessLinux::StartTrace(const TraceOptions &config,
2435 Status &error) {
2436 if (config.getType() != TraceType::eTraceTypeProcessorTrace)
2437 return NativeProcessProtocol::StartTrace(config, error);
2438
2439 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2440
2441 lldb::tid_t threadid = config.getThreadID();
2442
2443 if (threadid == LLDB_INVALID_THREAD_ID)
2444 return StartTraceGroup(config, error);
2445
2446 auto thread_sp = GetThreadByID(threadid);
2447 if (!thread_sp) {
2448 // Thread not tracked by lldb so don't trace.
2449 error.SetErrorString("invalid thread id");
2450 return LLDB_INVALID_UID;
2451 }
2452
2453 const auto &iter = m_processor_trace_monitor.find(threadid);
2454 if (iter != m_processor_trace_monitor.end()) {
2455 LLDB_LOG(log, "Thread already being traced");
2456 error.SetErrorString("tracing already active on this thread");
2457 return LLDB_INVALID_UID;
2458 }
2459
2460 auto traceMonitor =
2461 ProcessorTraceMonitor::Create(GetID(), threadid, config, false);
2462 if (!traceMonitor) {
2463 error = traceMonitor.takeError();
2464 LLDB_LOG(log, "error {0}", error);
2465 return LLDB_INVALID_UID;
2466 }
2467 lldb::user_id_t ret_trace_id = (*traceMonitor)->GetTraceID();
2468 m_processor_trace_monitor.insert(
2469 std::make_pair(threadid, std::move(*traceMonitor)));
2470 return ret_trace_id;
2471}
2472
2473Status NativeProcessLinux::StopTracingForThread(lldb::tid_t thread) {
2474 Status error;
2475 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2476 LLDB_LOG(log, "Thread {0}", thread);
2477
2478 const auto& iter = m_processor_trace_monitor.find(thread);
2479 if (iter == m_processor_trace_monitor.end()) {
2480 error.SetErrorString("tracing not active for this thread");
2481 return error;
2482 }
2483
2484 if (iter->second->GetTraceID() == m_pt_proces_trace_id) {
2485 // traceid maps to the whole process so we have to erase it from the
2486 // thread group.
2487 LLDB_LOG(log, "traceid maps to process");
2488 m_pt_traced_thread_group.erase(thread);
2489 }
2490 m_processor_trace_monitor.erase(iter);
2491
2492 return error;
2493}
2494
2495Status NativeProcessLinux::StopTrace(lldb::user_id_t traceid,
2496 lldb::tid_t thread) {
2497 Status error;
2498
2499 TraceOptions trace_options;
2500 trace_options.setThreadID(thread);
2501 error = NativeProcessLinux::GetTraceConfig(traceid, trace_options);
2502
2503 if (error.Fail())
2504 return error;
2505
2506 switch (trace_options.getType()) {
2507 case lldb::TraceType::eTraceTypeProcessorTrace:
2508 if (traceid == m_pt_proces_trace_id &&
2509 thread == LLDB_INVALID_THREAD_ID)
2510 StopProcessorTracingOnProcess();
2511 else
2512 error = StopProcessorTracingOnThread(traceid, thread);
2513 break;
2514 default:
2515 error.SetErrorString("trace not supported");
2516 break;
2517 }
2518
2519 return error;
2520}
2521
2522void NativeProcessLinux::StopProcessorTracingOnProcess() {
2523 for (auto thread_id_iter : m_pt_traced_thread_group)
2524 m_processor_trace_monitor.erase(thread_id_iter);
2525 m_pt_traced_thread_group.clear();
2526 m_pt_proces_trace_id = LLDB_INVALID_UID;
2527}
2528
2529Status NativeProcessLinux::StopProcessorTracingOnThread(lldb::user_id_t traceid,
2530 lldb::tid_t thread) {
2531 Status error;
2532 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2533
2534 if (thread == LLDB_INVALID_THREAD_ID) {
2535 for (auto& iter : m_processor_trace_monitor) {
2536 if (iter.second->GetTraceID() == traceid) {
2537 // Stopping a trace instance for an individual thread
2538 // hence there will only be one traceid that can match.
2539 m_processor_trace_monitor.erase(iter.first);
2540 return error;
2541 }
2542 LLDB_LOG(log, "Trace ID {0}", iter.second->GetTraceID());
2543 }
2544
2545 LLDB_LOG(log, "Invalid TraceID");
2546 error.SetErrorString("invalid trace id");
2547 return error;
2548 }
2549
2550 // thread is specified so we can use find function on the map.
2551 const auto& iter = m_processor_trace_monitor.find(thread);
2552 if (iter == m_processor_trace_monitor.end()) {
2553 // thread not found in our map.
2554 LLDB_LOG(log, "thread not being traced");
2555 error.SetErrorString("tracing not active for this thread");
2556 return error;
2557 }
2558 if (iter->second->GetTraceID() != traceid) {
2559 // traceid did not match so it has to be invalid.
2560 LLDB_LOG(log, "Invalid TraceID");
2561 error.SetErrorString("invalid trace id");
2562 return error;
2563 }
2564
2565 LLDB_LOG(log, "UID - {0} , Thread -{1}", traceid, thread);
2566
2567 if (traceid == m_pt_proces_trace_id) {
2568 // traceid maps to the whole process so we have to erase it from the
2569 // thread group.
2570 LLDB_LOG(log, "traceid maps to process");
2571 m_pt_traced_thread_group.erase(thread);
2572 }
2573 m_processor_trace_monitor.erase(iter);
2574
2575 return error;
2576}