blob: 136af361af2968ebc597003491684ea8390b5921 [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: {
Pavel Labath11edb4e2017-12-01 12:05:00 +0000180 // Extract iov_base from data, which is a pointer to the struct iovec
Pavel Labatha6321a82017-01-19 15:26:04 +0000181 DisplayBytes(buf, *(void **)data, data_size);
Pavel Labathaafe0532017-02-06 19:31:05 +0000182 LLDB_LOGV(log, "PTRACE_SETREGSET {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000183 break;
184 }
185 default: {}
Kate Stoneb9c1b512016-09-06 20:57:50 +0000186 }
187}
Todd Fialaaf245d12014-06-30 21:05:18 +0000188
Kate Stoneb9c1b512016-09-06 20:57:50 +0000189static constexpr unsigned k_ptrace_word_size = sizeof(void *);
190static_assert(sizeof(long) >= k_ptrace_word_size,
191 "Size of long must be larger than ptrace word size");
Pavel Labath1107b5a2015-04-17 14:07:49 +0000192} // end of anonymous namespace
193
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000194// Simple helper function to ensure flags are enabled on the given file
195// descriptor.
Zachary Turner97206d52017-05-12 04:51:55 +0000196static Status EnsureFDFlags(int fd, int flags) {
197 Status error;
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000198
Kate Stoneb9c1b512016-09-06 20:57:50 +0000199 int status = fcntl(fd, F_GETFL);
200 if (status == -1) {
201 error.SetErrorToErrno();
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000202 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000203 }
204
205 if (fcntl(fd, F_SETFL, status | flags) == -1) {
206 error.SetErrorToErrno();
207 return error;
208 }
209
210 return error;
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000211}
212
Todd Fialaaf245d12014-06-30 21:05:18 +0000213// -----------------------------------------------------------------------------
214// Public Static Methods
215// -----------------------------------------------------------------------------
216
Pavel Labath82abefa2017-07-18 09:24:48 +0000217llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
Pavel Labath96e600f2017-07-07 11:02:19 +0000218NativeProcessLinux::Factory::Launch(ProcessLaunchInfo &launch_info,
219 NativeDelegate &native_delegate,
220 MainLoop &mainloop) const {
Pavel Labatha6321a82017-01-19 15:26:04 +0000221 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Todd Fialaaf245d12014-06-30 21:05:18 +0000222
Pavel Labath96e600f2017-07-07 11:02:19 +0000223 MaybeLogLaunchInfo(launch_info);
Todd Fialaaf245d12014-06-30 21:05:18 +0000224
Pavel Labath96e600f2017-07-07 11:02:19 +0000225 Status status;
226 ::pid_t pid = ProcessLauncherPosixFork()
227 .LaunchProcess(launch_info, status)
228 .GetProcessId();
229 LLDB_LOG(log, "pid = {0:x}", pid);
230 if (status.Fail()) {
231 LLDB_LOG(log, "failed to launch process: {0}", status);
232 return status.ToError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000233 }
234
Pavel Labath96e600f2017-07-07 11:02:19 +0000235 // Wait for the child process to trap on its call to execve.
236 int wstatus;
237 ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0);
238 assert(wpid == pid);
239 (void)wpid;
240 if (!WIFSTOPPED(wstatus)) {
241 LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}",
242 WaitStatus::Decode(wstatus));
243 return llvm::make_error<StringError>("Could not sync with inferior process",
244 llvm::inconvertibleErrorCode());
245 }
246 LLDB_LOG(log, "inferior started, now in stopped state");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000247
Pavel 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) {
Pavel Labatha5be48b2017-10-17 15:52:16 +0000308 NativeThreadLinux &thread = AddThread(tid);
309 thread.SetStoppedBySignal(SIGSTOP);
310 ThreadWasCreated(thread);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000311 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000312
Kate Stoneb9c1b512016-09-06 20:57:50 +0000313 // Let our process instance know the thread has stopped.
Pavel Labath96e600f2017-07-07 11:02:19 +0000314 SetCurrentThreadID(tids[0]);
315 SetState(StateType::eStateStopped, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000316
Pavel Labath96e600f2017-07-07 11:02:19 +0000317 // Proccess any signals we received before installing our handler
318 SigchldHandler();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000319}
320
Pavel Labath96e600f2017-07-07 11:02:19 +0000321llvm::Expected<std::vector<::pid_t>> NativeProcessLinux::Attach(::pid_t pid) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000322 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000323
Pavel Labath96e600f2017-07-07 11:02:19 +0000324 Status status;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000325 // Use a map to keep track of the threads which we have attached/need to
326 // attach.
327 Host::TidMap tids_to_attach;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000328 while (Host::FindProcessThreads(pid, tids_to_attach)) {
329 for (Host::TidMap::iterator it = tids_to_attach.begin();
330 it != tids_to_attach.end();) {
331 if (it->second == false) {
332 lldb::tid_t tid = it->first;
333
334 // Attach to the requested process.
335 // An attach will cause the thread to stop with a SIGSTOP.
Pavel Labath96e600f2017-07-07 11:02:19 +0000336 if ((status = PtraceWrapper(PTRACE_ATTACH, tid)).Fail()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000337 // No such thread. The thread may have exited.
338 // More error handling may be needed.
Pavel Labath96e600f2017-07-07 11:02:19 +0000339 if (status.GetError() == ESRCH) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000340 it = tids_to_attach.erase(it);
341 continue;
Pavel Labath96e600f2017-07-07 11:02:19 +0000342 }
343 return status.ToError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000344 }
345
Pavel Labath96e600f2017-07-07 11:02:19 +0000346 int wpid =
347 llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, nullptr, __WALL);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000348 // Need to use __WALL otherwise we receive an error with errno=ECHLD
349 // At this point we should have a thread stopped if waitpid succeeds.
Pavel Labath96e600f2017-07-07 11:02:19 +0000350 if (wpid < 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000351 // No such thread. The thread may have exited.
352 // More error handling may be needed.
353 if (errno == ESRCH) {
354 it = tids_to_attach.erase(it);
355 continue;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000356 }
Pavel Labath96e600f2017-07-07 11:02:19 +0000357 return llvm::errorCodeToError(
358 std::error_code(errno, std::generic_category()));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000359 }
360
Pavel Labath96e600f2017-07-07 11:02:19 +0000361 if ((status = SetDefaultPtraceOpts(tid)).Fail())
362 return status.ToError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000363
Pavel Labatha6321a82017-01-19 15:26:04 +0000364 LLDB_LOG(log, "adding tid = {0}", tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000365 it->second = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000366 }
367
368 // move the loop forward
369 ++it;
370 }
371 }
372
Pavel Labath96e600f2017-07-07 11:02:19 +0000373 size_t tid_count = tids_to_attach.size();
374 if (tid_count == 0)
375 return llvm::make_error<StringError>("No such process",
376 llvm::inconvertibleErrorCode());
Todd Fialaaf245d12014-06-30 21:05:18 +0000377
Pavel Labath96e600f2017-07-07 11:02:19 +0000378 std::vector<::pid_t> tids;
379 tids.reserve(tid_count);
380 for (const auto &p : tids_to_attach)
381 tids.push_back(p.first);
382 return std::move(tids);
Todd Fialaaf245d12014-06-30 21:05:18 +0000383}
384
Zachary Turner97206d52017-05-12 04:51:55 +0000385Status NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000386 long ptrace_opts = 0;
Todd Fialaaf245d12014-06-30 21:05:18 +0000387
Kate Stoneb9c1b512016-09-06 20:57:50 +0000388 // Have the child raise an event on exit. This is used to keep the child in
389 // limbo until it is destroyed.
390 ptrace_opts |= PTRACE_O_TRACEEXIT;
Todd Fialaaf245d12014-06-30 21:05:18 +0000391
Kate Stoneb9c1b512016-09-06 20:57:50 +0000392 // Have the tracer trace threads which spawn in the inferior process.
393 // TODO: if we want to support tracing the inferiors' child, add the
394 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
395 ptrace_opts |= PTRACE_O_TRACECLONE;
Todd Fialaaf245d12014-06-30 21:05:18 +0000396
Kate Stoneb9c1b512016-09-06 20:57:50 +0000397 // Have the tracer notify us before execve returns
398 // (needed to disable legacy SIGTRAP generation)
399 ptrace_opts |= PTRACE_O_TRACEEXEC;
Todd Fialaaf245d12014-06-30 21:05:18 +0000400
Kate Stoneb9c1b512016-09-06 20:57:50 +0000401 return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void *)ptrace_opts);
Todd Fialaaf245d12014-06-30 21:05:18 +0000402}
403
Pavel Labath1107b5a2015-04-17 14:07:49 +0000404// Handles all waitpid events from the inferior process.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000405void NativeProcessLinux::MonitorCallback(lldb::pid_t pid, bool exited,
Pavel Labath3508fc82017-06-19 12:47:50 +0000406 WaitStatus status) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000407 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Todd Fialaaf245d12014-06-30 21:05:18 +0000408
Kate Stoneb9c1b512016-09-06 20:57:50 +0000409 // Certain activities differ based on whether the pid is the tid of the main
410 // thread.
411 const bool is_main_thread = (pid == GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000412
Kate Stoneb9c1b512016-09-06 20:57:50 +0000413 // Handle when the thread exits.
414 if (exited) {
Pavel Labathd8b3c1a2017-12-18 09:44:29 +0000415 LLDB_LOG(log,
416 "got exit signal({0}) , tid = {1} ({2} main thread), process "
417 "state = {3}",
418 signal, pid, is_main_thread ? "is" : "is not", GetState());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000419
420 // This is a thread that exited. Ensure we're not tracking it anymore.
Pavel Labathd8b3c1a2017-12-18 09:44:29 +0000421 StopTrackingThread(pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000422
423 if (is_main_thread) {
Pavel Labathd8b3c1a2017-12-18 09:44:29 +0000424 // The main thread exited. We're done monitoring. Report to delegate.
425 SetExitStatus(status, true);
Todd Fialaaf245d12014-06-30 21:05:18 +0000426
Pavel Labathd8b3c1a2017-12-18 09:44:29 +0000427 // Notify delegate that our process has exited.
428 SetState(StateType::eStateExited, true);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000429 }
430 return;
431 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000432
Kate Stoneb9c1b512016-09-06 20:57:50 +0000433 siginfo_t info;
434 const auto info_err = GetSignalInfo(pid, &info);
435 auto thread_sp = GetThreadByID(pid);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000436
Kate Stoneb9c1b512016-09-06 20:57:50 +0000437 if (!thread_sp) {
438 // Normally, the only situation when we cannot find the thread is if we have
Pavel Labatha6321a82017-01-19 15:26:04 +0000439 // just received a new thread notification. This is indicated by
440 // GetSignalInfo() returning si_code == SI_USER and si_pid == 0
441 LLDB_LOG(log, "received notification about an unknown tid {0}.", pid);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000442
Kate Stoneb9c1b512016-09-06 20:57:50 +0000443 if (info_err.Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000444 LLDB_LOG(log,
445 "(tid {0}) GetSignalInfo failed ({1}). "
446 "Ingoring this notification.",
447 pid, info_err);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000448 return;
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000449 }
450
Pavel Labatha6321a82017-01-19 15:26:04 +0000451 LLDB_LOG(log, "tid {0}, si_code: {1}, si_pid: {2}", pid, info.si_code,
452 info.si_pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000453
Pavel Labatha5be48b2017-10-17 15:52:16 +0000454 NativeThreadLinux &thread = AddThread(pid);
Ravitheja Addepally99e37692017-06-28 07:58:31 +0000455
Kate Stoneb9c1b512016-09-06 20:57:50 +0000456 // Resume the newly created thread.
Pavel Labatha5be48b2017-10-17 15:52:16 +0000457 ResumeThread(thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
458 ThreadWasCreated(thread);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000459 return;
460 }
461
462 // Get details on the signal raised.
463 if (info_err.Success()) {
464 // We have retrieved the signal info. Dispatch appropriately.
465 if (info.si_signo == SIGTRAP)
466 MonitorSIGTRAP(info, *thread_sp);
Chaoren Linfa03ad22015-02-03 01:50:42 +0000467 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000468 MonitorSignal(info, *thread_sp, exited);
469 } else {
470 if (info_err.GetError() == EINVAL) {
471 // This is a group stop reception for this tid.
472 // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU
Pavel Labatha6321a82017-01-19 15:26:04 +0000473 // into the tracee, triggering the group-stop mechanism. Normally
474 // receiving these would stop the process, pending a SIGCONT. Simulating
475 // this state in a debugger is hard and is generally not needed (one use
476 // case is debugging background task being managed by a shell). For
477 // general use, it is sufficient to stop the process in a signal-delivery
Kate Stoneb9c1b512016-09-06 20:57:50 +0000478 // stop which happens before the group stop. This done by MonitorSignal
Pavel Labatha6321a82017-01-19 15:26:04 +0000479 // and works correctly for all signals.
480 LLDB_LOG(log,
481 "received a group stop for pid {0} tid {1}. Transparent "
482 "handling of group stops not supported, resuming the "
483 "thread.",
484 GetID(), pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000485 ResumeThread(*thread_sp, thread_sp->GetState(),
486 LLDB_INVALID_SIGNAL_NUMBER);
487 } else {
488 // ptrace(GETSIGINFO) failed (but not due to group-stop).
Todd Fialaaf245d12014-06-30 21:05:18 +0000489
Kate Stoneb9c1b512016-09-06 20:57:50 +0000490 // A return value of ESRCH means the thread/process is no longer on the
Pavel Labatha6321a82017-01-19 15:26:04 +0000491 // system, so it was killed somehow outside of our control. Either way,
492 // we can't do anything with it anymore.
Todd Fialaaf245d12014-06-30 21:05:18 +0000493
Kate Stoneb9c1b512016-09-06 20:57:50 +0000494 // Stop tracking the metadata for the thread since it's entirely off the
495 // system now.
496 const bool thread_found = StopTrackingThread(pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000497
Pavel Labatha6321a82017-01-19 15:26:04 +0000498 LLDB_LOG(log,
499 "GetSignalInfo failed: {0}, tid = {1}, signal = {2}, "
500 "status = {3}, main_thread = {4}, thread_found: {5}",
501 info_err, pid, signal, status, is_main_thread, thread_found);
Todd Fialaaf245d12014-06-30 21:05:18 +0000502
Kate Stoneb9c1b512016-09-06 20:57:50 +0000503 if (is_main_thread) {
504 // Notify the delegate - our process is not available but appears to
505 // have been killed outside
506 // our control. Is eStateExited the right exit state in this case?
Pavel Labath3508fc82017-06-19 12:47:50 +0000507 SetExitStatus(status, true);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000508 SetState(StateType::eStateExited, true);
509 } else {
510 // This thread was pulled out from underneath us. Anything to do here?
511 // Do we want to do an all stop?
Pavel Labatha6321a82017-01-19 15:26:04 +0000512 LLDB_LOG(log,
513 "pid {0} tid {1} non-main thread exit occurred, didn't "
514 "tell delegate anything since thread disappeared out "
515 "from underneath us",
516 GetID(), pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000517 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000518 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000519 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000520}
521
Kate Stoneb9c1b512016-09-06 20:57:50 +0000522void NativeProcessLinux::WaitForNewThread(::pid_t tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000523 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Pavel Labath426bdf82015-04-28 07:51:52 +0000524
Pavel Labatha5be48b2017-10-17 15:52:16 +0000525 if (GetThreadByID(tid)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000526 // We are already tracking the thread - we got the event on the new thread
Pavel Labatha5be48b2017-10-17 15:52:16 +0000527 // (see MonitorSignal) before this one. We are done.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000528 return;
529 }
Pavel Labath426bdf82015-04-28 07:51:52 +0000530
Kate Stoneb9c1b512016-09-06 20:57:50 +0000531 // The thread is not tracked yet, let's wait for it to appear.
532 int status = -1;
Pavel Labathc1a6b122017-07-03 09:25:55 +0000533 LLDB_LOG(log,
534 "received thread creation event for tid {0}. tid not tracked "
535 "yet, waiting for thread to appear...",
536 tid);
537 ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, &status, __WALL);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000538 // Since we are waiting on a specific tid, this must be the creation event.
Pavel Labatha6321a82017-01-19 15:26:04 +0000539 // But let's do some checks just in case.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000540 if (wait_pid != tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000541 LLDB_LOG(log,
542 "waiting for tid {0} failed. Assuming the thread has "
543 "disappeared in the meantime",
544 tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000545 // The only way I know of this could happen is if the whole process was
546 // SIGKILLed in the mean time. In any case, we can't do anything about that
547 // now.
548 return;
549 }
550 if (WIFEXITED(status)) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000551 LLDB_LOG(log,
552 "waiting for tid {0} returned an 'exited' event. Not "
553 "tracking the thread.",
554 tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000555 // Also a very improbable event.
556 return;
557 }
Pavel Labath426bdf82015-04-28 07:51:52 +0000558
Pavel Labatha6321a82017-01-19 15:26:04 +0000559 LLDB_LOG(log, "pid = {0}: tracking new thread tid {1}", GetID(), tid);
Pavel Labatha5be48b2017-10-17 15:52:16 +0000560 NativeThreadLinux &new_thread = AddThread(tid);
Ravitheja Addepally99e37692017-06-28 07:58:31 +0000561
Pavel Labatha5be48b2017-10-17 15:52:16 +0000562 ResumeThread(new_thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
563 ThreadWasCreated(new_thread);
Pavel Labath426bdf82015-04-28 07:51:52 +0000564}
565
Kate Stoneb9c1b512016-09-06 20:57:50 +0000566void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info,
567 NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000568 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000569 const bool is_main_thread = (thread.GetID() == GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000570
Kate Stoneb9c1b512016-09-06 20:57:50 +0000571 assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
Todd Fialaaf245d12014-06-30 21:05:18 +0000572
Kate Stoneb9c1b512016-09-06 20:57:50 +0000573 switch (info.si_code) {
574 // TODO: these two cases are required if we want to support tracing of the
575 // inferiors' children. We'd need this to debug a monitor.
576 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
577 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
Todd Fialaaf245d12014-06-30 21:05:18 +0000578
Kate Stoneb9c1b512016-09-06 20:57:50 +0000579 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): {
580 // This is the notification on the parent thread which informs us of new
581 // thread
582 // creation.
583 // We don't want to do anything with the parent thread so we just resume it.
584 // In case we
585 // want to implement "break on thread creation" functionality, we would need
586 // to stop
587 // here.
Todd Fialaaf245d12014-06-30 21:05:18 +0000588
Kate Stoneb9c1b512016-09-06 20:57:50 +0000589 unsigned long event_message = 0;
590 if (GetEventMessage(thread.GetID(), &event_message).Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000591 LLDB_LOG(log,
592 "pid {0} received thread creation event but "
593 "GetEventMessage failed so we don't know the new tid",
594 thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000595 } else
596 WaitForNewThread(event_message);
Todd Fialaaf245d12014-06-30 21:05:18 +0000597
Kate Stoneb9c1b512016-09-06 20:57:50 +0000598 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
599 break;
600 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000601
Kate Stoneb9c1b512016-09-06 20:57:50 +0000602 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): {
Pavel Labatha6321a82017-01-19 15:26:04 +0000603 LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000604
605 // Exec clears any pending notifications.
606 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
607
608 // Remove all but the main thread here. Linux fork creates a new process
609 // which only copies the main thread.
Pavel Labatha6321a82017-01-19 15:26:04 +0000610 LLDB_LOG(log, "exec received, stop tracking all but main thread");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000611
Pavel Labatha5be48b2017-10-17 15:52:16 +0000612 for (auto i = m_threads.begin(); i != m_threads.end();) {
613 if ((*i)->GetID() == GetID())
614 i = m_threads.erase(i);
615 else
616 ++i;
Todd Fialaa9882ce2014-08-28 15:46:54 +0000617 }
Pavel Labatha5be48b2017-10-17 15:52:16 +0000618 assert(m_threads.size() == 1);
619 auto *main_thread = static_cast<NativeThreadLinux *>(m_threads[0].get());
Todd Fialaaf245d12014-06-30 21:05:18 +0000620
Pavel Labatha5be48b2017-10-17 15:52:16 +0000621 SetCurrentThreadID(main_thread->GetID());
622 main_thread->SetStoppedByExec();
Todd Fialaaf245d12014-06-30 21:05:18 +0000623
Kate Stoneb9c1b512016-09-06 20:57:50 +0000624 // Tell coordinator about about the "new" (since exec) stopped main thread.
Pavel Labatha5be48b2017-10-17 15:52:16 +0000625 ThreadWasCreated(*main_thread);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000626
Kate Stoneb9c1b512016-09-06 20:57:50 +0000627 // Let our delegate know we have just exec'd.
628 NotifyDidExec();
629
Kate Stoneb9c1b512016-09-06 20:57:50 +0000630 // Let the process know we're stopped.
Pavel Labatha5be48b2017-10-17 15:52:16 +0000631 StopRunningThreads(main_thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000632
633 break;
634 }
635
636 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): {
637 // The inferior process or one of its threads is about to exit.
638 // We don't want to do anything with the thread so we just resume it. In
Pavel Labathd8b3c1a2017-12-18 09:44:29 +0000639 // case we want to implement "break on thread exit" functionality, we would
640 // need to stop here.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000641
642 unsigned long data = 0;
643 if (GetEventMessage(thread.GetID(), &data).Fail())
644 data = -1;
645
Pavel Labatha6321a82017-01-19 15:26:04 +0000646 LLDB_LOG(log,
647 "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
648 "WIFSIGNALED={2}, pid = {3}, main_thread = {4}",
649 data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(),
650 is_main_thread);
Todd Fialaaf245d12014-06-30 21:05:18 +0000651
Kate Stoneb9c1b512016-09-06 20:57:50 +0000652
653 StateType state = thread.GetState();
654 if (!StateIsRunningState(state)) {
655 // Due to a kernel bug, we may sometimes get this stop after the inferior
Pavel Labathd8b3c1a2017-12-18 09:44:29 +0000656 // gets a SIGKILL. This confuses our state tracking logic in
657 // ResumeThread(), since normally, we should not be receiving any ptrace
658 // events while the inferior is stopped. This makes sure that the inferior
659 // is resumed and exits normally.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000660 state = eStateRunning;
661 }
662 ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
663
664 break;
665 }
666
667 case 0:
668 case TRAP_TRACE: // We receive this on single stepping.
669 case TRAP_HWBKPT: // We receive this on watchpoint hit
670 {
671 // If a watchpoint was hit, report it
672 uint32_t wp_index;
Pavel Labathd37349f2017-11-10 11:05:49 +0000673 Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000674 wp_index, (uintptr_t)info.si_addr);
Pavel Labatha6321a82017-01-19 15:26:04 +0000675 if (error.Fail())
676 LLDB_LOG(log,
677 "received error while checking for watchpoint hits, pid = "
678 "{0}, error = {1}",
679 thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000680 if (wp_index != LLDB_INVALID_INDEX32) {
681 MonitorWatchpoint(thread, wp_index);
682 break;
683 }
684
Omair Javaidd5ffbad2017-02-24 13:27:31 +0000685 // If a breakpoint was hit, report it
686 uint32_t bp_index;
Pavel Labathd37349f2017-11-10 11:05:49 +0000687 error = thread.GetRegisterContext().GetHardwareBreakHitIndex(
Omair Javaidd5ffbad2017-02-24 13:27:31 +0000688 bp_index, (uintptr_t)info.si_addr);
689 if (error.Fail())
690 LLDB_LOG(log, "received error while checking for hardware "
691 "breakpoint hits, pid = {0}, error = {1}",
692 thread.GetID(), error);
693 if (bp_index != LLDB_INVALID_INDEX32) {
694 MonitorBreakpoint(thread);
695 break;
696 }
697
Kate Stoneb9c1b512016-09-06 20:57:50 +0000698 // Otherwise, report step over
699 MonitorTrace(thread);
700 break;
701 }
702
703 case SI_KERNEL:
Mohit K. Bhakkad35799962015-06-18 04:53:18 +0000704#if defined __mips__
Kate Stoneb9c1b512016-09-06 20:57:50 +0000705 // For mips there is no special signal for watchpoint
706 // So we check for watchpoint in kernel trap
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000707 {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000708 // If a watchpoint was hit, report it
709 uint32_t wp_index;
Pavel Labathd37349f2017-11-10 11:05:49 +0000710 Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000711 wp_index, LLDB_INVALID_ADDRESS);
Pavel Labatha6321a82017-01-19 15:26:04 +0000712 if (error.Fail())
713 LLDB_LOG(log,
714 "received error while checking for watchpoint hits, pid = "
715 "{0}, error = {1}",
716 thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000717 if (wp_index != LLDB_INVALID_INDEX32) {
718 MonitorWatchpoint(thread, wp_index);
719 break;
720 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000721 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000722// NO BREAK
Mohit K. Bhakkad35799962015-06-18 04:53:18 +0000723#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000724 case TRAP_BRKPT:
725 MonitorBreakpoint(thread);
726 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000727
Kate Stoneb9c1b512016-09-06 20:57:50 +0000728 case SIGTRAP:
729 case (SIGTRAP | 0x80):
Pavel Labatha6321a82017-01-19 15:26:04 +0000730 LLDB_LOG(
731 log,
732 "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",
733 info.si_code, GetID(), thread.GetID());
Chaoren Linfa03ad22015-02-03 01:50:42 +0000734
Kate Stoneb9c1b512016-09-06 20:57:50 +0000735 // Ignore these signals until we know more about them.
736 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
737 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000738
Kate Stoneb9c1b512016-09-06 20:57:50 +0000739 default:
Pavel Labath21a365b2017-07-11 10:38:40 +0000740 LLDB_LOG(log, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}",
741 info.si_code, GetID(), thread.GetID());
742 MonitorSignal(info, thread, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000743 break;
744 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000745}
746
Kate Stoneb9c1b512016-09-06 20:57:50 +0000747void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000748 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
749 LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000750
Kate Stoneb9c1b512016-09-06 20:57:50 +0000751 // This thread is currently stopped.
752 thread.SetStoppedByTrace();
753
754 StopRunningThreads(thread.GetID());
755}
756
757void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) {
758 Log *log(
759 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
Pavel Labatha6321a82017-01-19 15:26:04 +0000760 LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000761
762 // Mark the thread as stopped at breakpoint.
763 thread.SetStoppedByBreakpoint();
Zachary Turner97206d52017-05-12 04:51:55 +0000764 Status error = FixupBreakpointPCAsNeeded(thread);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000765 if (error.Fail())
Pavel Labatha6321a82017-01-19 15:26:04 +0000766 LLDB_LOG(log, "pid = {0} fixup: {1}", thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000767
768 if (m_threads_stepping_with_breakpoint.find(thread.GetID()) !=
769 m_threads_stepping_with_breakpoint.end())
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000770 thread.SetStoppedByTrace();
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000771
Kate Stoneb9c1b512016-09-06 20:57:50 +0000772 StopRunningThreads(thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000773}
774
Kate Stoneb9c1b512016-09-06 20:57:50 +0000775void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread,
776 uint32_t wp_index) {
777 Log *log(
778 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
Pavel Labatha6321a82017-01-19 15:26:04 +0000779 LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}",
780 thread.GetID(), wp_index);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000781
782 // Mark the thread as stopped at watchpoint.
783 // The address is at (lldb::addr_t)info->si_addr if we need it.
784 thread.SetStoppedByWatchpoint(wp_index);
785
786 // We need to tell all other running threads before we notify the delegate
787 // about this stop.
788 StopRunningThreads(thread.GetID());
789}
790
791void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
792 NativeThreadLinux &thread, bool exited) {
793 const int signo = info.si_signo;
794 const bool is_from_llgs = info.si_pid == getpid();
795
Pavel Labatha6321a82017-01-19 15:26:04 +0000796 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000797
798 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
799 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
800 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
801 //
802 // IOW, user generated signals never generate what we consider to be a
803 // "crash".
804 //
805 // Similarly, ACK signals generated by this monitor.
806
807 // Handle the signal.
Pavel Labatha6321a82017-01-19 15:26:04 +0000808 LLDB_LOG(log,
809 "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
810 "waitpid pid = {4})",
811 Host::GetSignalAsCString(signo), signo, info.si_code,
812 thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000813
Kate Stoneb9c1b512016-09-06 20:57:50 +0000814 // Check for thread stop notification.
815 if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) {
816 // This is a tgkill()-based stop.
Pavel Labatha6321a82017-01-19 15:26:04 +0000817 LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000818
Kate Stoneb9c1b512016-09-06 20:57:50 +0000819 // Check that we're not already marked with a stop reason.
820 // Note this thread really shouldn't already be marked as stopped - if we
Pavel Labatha6321a82017-01-19 15:26:04 +0000821 // were, that would imply that the kernel signaled us with the thread
822 // stopping which we handled and marked as stopped, and that, without an
823 // intervening resume, we received another stop. It is more likely that we
824 // are missing the marking of a run state somewhere if we find that the
825 // thread was marked as stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000826 const StateType thread_state = thread.GetState();
827 if (!StateIsStoppedState(thread_state, false)) {
828 // An inferior thread has stopped because of a SIGSTOP we have sent it.
829 // Generally, these are not important stops and we don't want to report
Pavel Labatha6321a82017-01-19 15:26:04 +0000830 // them as they are just used to stop other threads when one thread (the
831 // one with the *real* stop reason) hits a breakpoint (watchpoint,
832 // etc...). However, in the case of an asynchronous Interrupt(), this *is*
833 // the real stop reason, so we leave the signal intact if this is the
834 // thread that was chosen as the triggering thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000835 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
836 if (m_pending_notification_tid == thread.GetID())
837 thread.SetStoppedBySignal(SIGSTOP, &info);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000838 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000839 thread.SetStoppedWithNoReason();
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000840
Kate Stoneb9c1b512016-09-06 20:57:50 +0000841 SetCurrentThreadID(thread.GetID());
842 SignalIfAllThreadsStopped();
843 } else {
844 // We can end up here if stop was initiated by LLGS but by this time a
845 // thread stop has occurred - maybe initiated by another event.
Zachary Turner97206d52017-05-12 04:51:55 +0000846 Status error = ResumeThread(thread, thread.GetState(), 0);
Pavel Labatha6321a82017-01-19 15:26:04 +0000847 if (error.Fail())
848 LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(),
849 error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000850 }
851 } else {
Pavel Labatha6321a82017-01-19 15:26:04 +0000852 LLDB_LOG(log,
853 "pid {0} tid {1}, thread was already marked as a stopped "
854 "state (state={2}), leaving stop signal as is",
Pavel Labath8198db32017-01-24 11:48:25 +0000855 GetID(), thread.GetID(), thread_state);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000856 SignalIfAllThreadsStopped();
Todd Fialaaf245d12014-06-30 21:05:18 +0000857 }
858
Kate Stoneb9c1b512016-09-06 20:57:50 +0000859 // Done handling.
860 return;
861 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000862
Pavel Labath4a705e72017-02-24 09:29:14 +0000863 // Check if debugger should stop at this signal or just ignore it
864 // and resume the inferior.
865 if (m_signals_to_ignore.find(signo) != m_signals_to_ignore.end()) {
866 ResumeThread(thread, thread.GetState(), signo);
867 return;
868 }
869
Kate Stoneb9c1b512016-09-06 20:57:50 +0000870 // This thread is stopped.
Pavel Labatha6321a82017-01-19 15:26:04 +0000871 LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000872 thread.SetStoppedBySignal(signo, &info);
873
874 // Send a stop to the debugger after we get all other threads to stop.
875 StopRunningThreads(thread.GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000876}
877
Tamas Berghammere7708682015-04-22 10:00:23 +0000878namespace {
879
Kate Stoneb9c1b512016-09-06 20:57:50 +0000880struct EmulatorBaton {
Pavel Labathd37349f2017-11-10 11:05:49 +0000881 NativeProcessLinux &m_process;
882 NativeRegisterContext &m_reg_context;
Tamas Berghammere7708682015-04-22 10:00:23 +0000883
Kate Stoneb9c1b512016-09-06 20:57:50 +0000884 // eRegisterKindDWARF -> RegsiterValue
885 std::unordered_map<uint32_t, RegisterValue> m_register_values;
Pavel Labath6648fcc2015-04-27 09:21:14 +0000886
Pavel Labathd37349f2017-11-10 11:05:49 +0000887 EmulatorBaton(NativeProcessLinux &process, NativeRegisterContext &reg_context)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000888 : m_process(process), m_reg_context(reg_context) {}
Tamas Berghammere7708682015-04-22 10:00:23 +0000889};
890
891} // anonymous namespace
892
Kate Stoneb9c1b512016-09-06 20:57:50 +0000893static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
894 const EmulateInstruction::Context &context,
895 lldb::addr_t addr, void *dst, size_t length) {
896 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
Tamas Berghammere7708682015-04-22 10:00:23 +0000897
Kate Stoneb9c1b512016-09-06 20:57:50 +0000898 size_t bytes_read;
Pavel Labathd37349f2017-11-10 11:05:49 +0000899 emulator_baton->m_process.ReadMemory(addr, dst, length, bytes_read);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000900 return bytes_read;
Tamas Berghammere7708682015-04-22 10:00:23 +0000901}
902
Kate Stoneb9c1b512016-09-06 20:57:50 +0000903static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
904 const RegisterInfo *reg_info,
905 RegisterValue &reg_value) {
906 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
Tamas Berghammere7708682015-04-22 10:00:23 +0000907
Kate Stoneb9c1b512016-09-06 20:57:50 +0000908 auto it = emulator_baton->m_register_values.find(
909 reg_info->kinds[eRegisterKindDWARF]);
910 if (it != emulator_baton->m_register_values.end()) {
911 reg_value = it->second;
912 return true;
913 }
914
915 // The emulator only fill in the dwarf regsiter numbers (and in some case
916 // the generic register numbers). Get the full register info from the
917 // register context based on the dwarf register numbers.
918 const RegisterInfo *full_reg_info =
Pavel Labathd37349f2017-11-10 11:05:49 +0000919 emulator_baton->m_reg_context.GetRegisterInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000920 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
921
Zachary Turner97206d52017-05-12 04:51:55 +0000922 Status error =
Pavel Labathd37349f2017-11-10 11:05:49 +0000923 emulator_baton->m_reg_context.ReadRegister(full_reg_info, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000924 if (error.Success())
925 return true;
926
927 return false;
928}
929
930static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
931 const EmulateInstruction::Context &context,
932 const RegisterInfo *reg_info,
933 const RegisterValue &reg_value) {
934 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
935 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
936 reg_value;
937 return true;
938}
939
940static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
941 const EmulateInstruction::Context &context,
942 lldb::addr_t addr, const void *dst,
943 size_t length) {
944 return length;
945}
946
Pavel Labathd37349f2017-11-10 11:05:49 +0000947static lldb::addr_t ReadFlags(NativeRegisterContext &regsiter_context) {
948 const RegisterInfo *flags_info = regsiter_context.GetRegisterInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000949 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
Pavel Labathd37349f2017-11-10 11:05:49 +0000950 return regsiter_context.ReadRegisterAsUnsigned(flags_info,
951 LLDB_INVALID_ADDRESS);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000952}
953
Zachary Turner97206d52017-05-12 04:51:55 +0000954Status
955NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadLinux &thread) {
956 Status error;
Pavel Labathd37349f2017-11-10 11:05:49 +0000957 NativeRegisterContext& register_context = thread.GetRegisterContext();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000958
959 std::unique_ptr<EmulateInstruction> emulator_ap(
960 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying,
961 nullptr));
962
963 if (emulator_ap == nullptr)
Zachary Turner97206d52017-05-12 04:51:55 +0000964 return Status("Instruction emulator not found!");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000965
Pavel Labathd37349f2017-11-10 11:05:49 +0000966 EmulatorBaton baton(*this, register_context);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000967 emulator_ap->SetBaton(&baton);
968 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
969 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
970 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
971 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
972
973 if (!emulator_ap->ReadInstruction())
Zachary Turner97206d52017-05-12 04:51:55 +0000974 return Status("Read instruction failed!");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000975
976 bool emulation_result =
977 emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
978
Pavel Labathd37349f2017-11-10 11:05:49 +0000979 const RegisterInfo *reg_info_pc = register_context.GetRegisterInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000980 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
Pavel Labathd37349f2017-11-10 11:05:49 +0000981 const RegisterInfo *reg_info_flags = register_context.GetRegisterInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000982 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
983
984 auto pc_it =
985 baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
986 auto flags_it =
987 baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
988
989 lldb::addr_t next_pc;
990 lldb::addr_t next_flags;
991 if (emulation_result) {
992 assert(pc_it != baton.m_register_values.end() &&
993 "Emulation was successfull but PC wasn't updated");
994 next_pc = pc_it->second.GetAsUInt64();
995
996 if (flags_it != baton.m_register_values.end())
997 next_flags = flags_it->second.GetAsUInt64();
998 else
Pavel Labathd37349f2017-11-10 11:05:49 +0000999 next_flags = ReadFlags(register_context);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001000 } else if (pc_it == baton.m_register_values.end()) {
1001 // Emulate instruction failed and it haven't changed PC. Advance PC
1002 // with the size of the current opcode because the emulation of all
1003 // PC modifying instruction should be successful. The failure most
1004 // likely caused by a not supported instruction which don't modify PC.
Pavel Labathd37349f2017-11-10 11:05:49 +00001005 next_pc = register_context.GetPC() + emulator_ap->GetOpcode().GetByteSize();
1006 next_flags = ReadFlags(register_context);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001007 } else {
1008 // The instruction emulation failed after it modified the PC. It is an
1009 // unknown error where we can't continue because the next instruction is
1010 // modifying the PC but we don't know how.
Zachary Turner97206d52017-05-12 04:51:55 +00001011 return Status("Instruction emulation failed unexpectedly.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001012 }
1013
1014 if (m_arch.GetMachine() == llvm::Triple::arm) {
1015 if (next_flags & 0x20) {
1016 // Thumb mode
1017 error = SetSoftwareBreakpoint(next_pc, 2);
1018 } else {
1019 // Arm mode
1020 error = SetSoftwareBreakpoint(next_pc, 4);
Pavel Labath6648fcc2015-04-27 09:21:14 +00001021 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001022 } else if (m_arch.GetMachine() == llvm::Triple::mips64 ||
1023 m_arch.GetMachine() == llvm::Triple::mips64el ||
1024 m_arch.GetMachine() == llvm::Triple::mips ||
Eugene Zemtsovaae0a752017-10-05 19:44:05 +00001025 m_arch.GetMachine() == llvm::Triple::mipsel ||
1026 m_arch.GetMachine() == llvm::Triple::ppc64le)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001027 error = SetSoftwareBreakpoint(next_pc, 4);
1028 else {
1029 // No size hint is given for the next breakpoint
1030 error = SetSoftwareBreakpoint(next_pc, 0);
1031 }
Pavel Labath6648fcc2015-04-27 09:21:14 +00001032
Pavel Labath42eb6902016-10-26 11:13:56 +00001033 // If setting the breakpoint fails because next_pc is out of
1034 // the address space, ignore it and let the debugee segfault.
1035 if (error.GetError() == EIO || error.GetError() == EFAULT) {
Zachary Turner97206d52017-05-12 04:51:55 +00001036 return Status();
Pavel Labath42eb6902016-10-26 11:13:56 +00001037 } else if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001038 return error;
Tamas Berghammere7708682015-04-22 10:00:23 +00001039
Kate Stoneb9c1b512016-09-06 20:57:50 +00001040 m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001041
Zachary Turner97206d52017-05-12 04:51:55 +00001042 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001043}
1044
1045bool NativeProcessLinux::SupportHardwareSingleStepping() const {
1046 if (m_arch.GetMachine() == llvm::Triple::arm ||
1047 m_arch.GetMachine() == llvm::Triple::mips64 ||
1048 m_arch.GetMachine() == llvm::Triple::mips64el ||
1049 m_arch.GetMachine() == llvm::Triple::mips ||
1050 m_arch.GetMachine() == llvm::Triple::mipsel)
Pavel Labath6648fcc2015-04-27 09:21:14 +00001051 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001052 return true;
Tamas Berghammere7708682015-04-22 10:00:23 +00001053}
1054
Zachary Turner97206d52017-05-12 04:51:55 +00001055Status NativeProcessLinux::Resume(const ResumeActionList &resume_actions) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001056 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1057 LLDB_LOG(log, "pid {0}", GetID());
Tamas Berghammere7708682015-04-22 10:00:23 +00001058
Kate Stoneb9c1b512016-09-06 20:57:50 +00001059 bool software_single_step = !SupportHardwareSingleStepping();
Tamas Berghammere7708682015-04-22 10:00:23 +00001060
Kate Stoneb9c1b512016-09-06 20:57:50 +00001061 if (software_single_step) {
Pavel Labatha5be48b2017-10-17 15:52:16 +00001062 for (const auto &thread : m_threads) {
1063 assert(thread && "thread list should not contain NULL threads");
Tamas Berghammere7708682015-04-22 10:00:23 +00001064
Kate Stoneb9c1b512016-09-06 20:57:50 +00001065 const ResumeAction *const action =
Pavel Labatha5be48b2017-10-17 15:52:16 +00001066 resume_actions.GetActionForThread(thread->GetID(), true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001067 if (action == nullptr)
1068 continue;
Tamas Berghammere7708682015-04-22 10:00:23 +00001069
Kate Stoneb9c1b512016-09-06 20:57:50 +00001070 if (action->state == eStateStepping) {
Zachary Turner97206d52017-05-12 04:51:55 +00001071 Status error = SetupSoftwareSingleStepping(
Pavel Labatha5be48b2017-10-17 15:52:16 +00001072 static_cast<NativeThreadLinux &>(*thread));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001073 if (error.Fail())
1074 return error;
1075 }
Tamas Berghammere7708682015-04-22 10:00:23 +00001076 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001077 }
1078
Pavel Labatha5be48b2017-10-17 15:52:16 +00001079 for (const auto &thread : m_threads) {
1080 assert(thread && "thread list should not contain NULL threads");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001081
1082 const ResumeAction *const action =
Pavel Labatha5be48b2017-10-17 15:52:16 +00001083 resume_actions.GetActionForThread(thread->GetID(), true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001084
1085 if (action == nullptr) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001086 LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
Pavel Labatha5be48b2017-10-17 15:52:16 +00001087 thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001088 continue;
Tamas Berghammere7708682015-04-22 10:00:23 +00001089 }
1090
Pavel Labatha6321a82017-01-19 15:26:04 +00001091 LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}",
Pavel Labatha5be48b2017-10-17 15:52:16 +00001092 action->state, GetID(), thread->GetID());
Tamas Berghammere7708682015-04-22 10:00:23 +00001093
Kate Stoneb9c1b512016-09-06 20:57:50 +00001094 switch (action->state) {
1095 case eStateRunning:
1096 case eStateStepping: {
1097 // Run the thread, possibly feeding it the signal.
1098 const int signo = action->signal;
Pavel Labatha5be48b2017-10-17 15:52:16 +00001099 ResumeThread(static_cast<NativeThreadLinux &>(*thread), action->state,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001100 signo);
1101 break;
1102 }
Tamas Berghammere7708682015-04-22 10:00:23 +00001103
Kate Stoneb9c1b512016-09-06 20:57:50 +00001104 case eStateSuspended:
1105 case eStateStopped:
Pavel Labatha6321a82017-01-19 15:26:04 +00001106 llvm_unreachable("Unexpected state");
Tamas Berghammere7708682015-04-22 10:00:23 +00001107
Kate Stoneb9c1b512016-09-06 20:57:50 +00001108 default:
Zachary Turner97206d52017-05-12 04:51:55 +00001109 return Status("NativeProcessLinux::%s (): unexpected state %s specified "
1110 "for pid %" PRIu64 ", tid %" PRIu64,
1111 __FUNCTION__, StateAsCString(action->state), GetID(),
Pavel Labatha5be48b2017-10-17 15:52:16 +00001112 thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001113 }
1114 }
1115
Zachary Turner97206d52017-05-12 04:51:55 +00001116 return Status();
Tamas Berghammere7708682015-04-22 10:00:23 +00001117}
1118
Zachary Turner97206d52017-05-12 04:51:55 +00001119Status NativeProcessLinux::Halt() {
1120 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001121
1122 if (kill(GetID(), SIGSTOP) != 0)
1123 error.SetErrorToErrno();
1124
1125 return error;
Tamas Berghammere7708682015-04-22 10:00:23 +00001126}
1127
Zachary Turner97206d52017-05-12 04:51:55 +00001128Status NativeProcessLinux::Detach() {
1129 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001130
1131 // Stop monitoring the inferior.
1132 m_sigchld_handle.reset();
1133
1134 // Tell ptrace to detach from the process.
1135 if (GetID() == LLDB_INVALID_PROCESS_ID)
1136 return error;
1137
Pavel Labatha5be48b2017-10-17 15:52:16 +00001138 for (const auto &thread : m_threads) {
1139 Status e = Detach(thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001140 if (e.Fail())
1141 error =
1142 e; // Save the error, but still attempt to detach from other threads.
1143 }
1144
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001145 m_processor_trace_monitor.clear();
1146 m_pt_proces_trace_id = LLDB_INVALID_UID;
1147
Kate Stoneb9c1b512016-09-06 20:57:50 +00001148 return error;
1149}
1150
Zachary Turner97206d52017-05-12 04:51:55 +00001151Status NativeProcessLinux::Signal(int signo) {
1152 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001153
Pavel Labatha6321a82017-01-19 15:26:04 +00001154 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1155 LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo,
1156 Host::GetSignalAsCString(signo), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001157
1158 if (kill(GetID(), signo))
1159 error.SetErrorToErrno();
1160
1161 return error;
1162}
1163
Zachary Turner97206d52017-05-12 04:51:55 +00001164Status NativeProcessLinux::Interrupt() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001165 // Pick a running thread (or if none, a not-dead stopped thread) as
1166 // the chosen thread that will be the stop-reason thread.
Pavel Labatha6321a82017-01-19 15:26:04 +00001167 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001168
Pavel Labatha5be48b2017-10-17 15:52:16 +00001169 NativeThreadProtocol *running_thread = nullptr;
1170 NativeThreadProtocol *stopped_thread = nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001171
Pavel Labatha6321a82017-01-19 15:26:04 +00001172 LLDB_LOG(log, "selecting running thread for interrupt target");
Pavel Labatha5be48b2017-10-17 15:52:16 +00001173 for (const auto &thread : m_threads) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001174 // If we have a running or stepping thread, we'll call that the
1175 // target of the interrupt.
Pavel Labatha5be48b2017-10-17 15:52:16 +00001176 const auto thread_state = thread->GetState();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001177 if (thread_state == eStateRunning || thread_state == eStateStepping) {
Pavel Labatha5be48b2017-10-17 15:52:16 +00001178 running_thread = thread.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001179 break;
Pavel Labatha5be48b2017-10-17 15:52:16 +00001180 } else if (!stopped_thread && StateIsStoppedState(thread_state, true)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001181 // Remember the first non-dead stopped thread. We'll use that as a backup
1182 // if there are no running threads.
Pavel Labatha5be48b2017-10-17 15:52:16 +00001183 stopped_thread = thread.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001184 }
1185 }
1186
Pavel Labatha5be48b2017-10-17 15:52:16 +00001187 if (!running_thread && !stopped_thread) {
Zachary Turner97206d52017-05-12 04:51:55 +00001188 Status error("found no running/stepping or live stopped threads as target "
1189 "for interrupt");
Pavel Labatha6321a82017-01-19 15:26:04 +00001190 LLDB_LOG(log, "skipping due to error: {0}", error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001191
1192 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001193 }
1194
Pavel Labatha5be48b2017-10-17 15:52:16 +00001195 NativeThreadProtocol *deferred_signal_thread =
1196 running_thread ? running_thread : stopped_thread;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001197
Pavel Labatha6321a82017-01-19 15:26:04 +00001198 LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(),
Pavel Labatha5be48b2017-10-17 15:52:16 +00001199 running_thread ? "running" : "stopped",
1200 deferred_signal_thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001201
Pavel Labatha5be48b2017-10-17 15:52:16 +00001202 StopRunningThreads(deferred_signal_thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001203
Zachary Turner97206d52017-05-12 04:51:55 +00001204 return Status();
Todd Fialaaf245d12014-06-30 21:05:18 +00001205}
1206
Zachary Turner97206d52017-05-12 04:51:55 +00001207Status NativeProcessLinux::Kill() {
Pavel Labatha6321a82017-01-19 15:26:04 +00001208 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1209 LLDB_LOG(log, "pid {0}", GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +00001210
Zachary Turner97206d52017-05-12 04:51:55 +00001211 Status error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001212
Kate Stoneb9c1b512016-09-06 20:57:50 +00001213 switch (m_state) {
1214 case StateType::eStateInvalid:
1215 case StateType::eStateExited:
1216 case StateType::eStateCrashed:
1217 case StateType::eStateDetached:
1218 case StateType::eStateUnloaded:
1219 // Nothing to do - the process is already dead.
Pavel Labatha6321a82017-01-19 15:26:04 +00001220 LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
Pavel Labath8198db32017-01-24 11:48:25 +00001221 m_state);
Todd Fialaaf245d12014-06-30 21:05:18 +00001222 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001223
Kate Stoneb9c1b512016-09-06 20:57:50 +00001224 case StateType::eStateConnected:
1225 case StateType::eStateAttaching:
1226 case StateType::eStateLaunching:
1227 case StateType::eStateStopped:
1228 case StateType::eStateRunning:
1229 case StateType::eStateStepping:
1230 case StateType::eStateSuspended:
1231 // We can try to kill a process in these states.
1232 break;
1233 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001234
Kate Stoneb9c1b512016-09-06 20:57:50 +00001235 if (kill(GetID(), SIGKILL) != 0) {
1236 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +00001237 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001238 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001239
Kate Stoneb9c1b512016-09-06 20:57:50 +00001240 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001241}
1242
Zachary Turner97206d52017-05-12 04:51:55 +00001243static Status
Pavel Labath15930862017-03-21 13:49:45 +00001244ParseMemoryRegionInfoFromProcMapsLine(llvm::StringRef &maps_line,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001245 MemoryRegionInfo &memory_region_info) {
1246 memory_region_info.Clear();
Todd Fialaaf245d12014-06-30 21:05:18 +00001247
Pavel Labath15930862017-03-21 13:49:45 +00001248 StringExtractor line_extractor(maps_line);
Todd Fialaaf245d12014-06-30 21:05:18 +00001249
Kate Stoneb9c1b512016-09-06 20:57:50 +00001250 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode
1251 // pathname
1252 // perms: rwxp (letter is present if set, '-' if not, final character is
1253 // p=private, s=shared).
Todd Fialaaf245d12014-06-30 21:05:18 +00001254
Kate Stoneb9c1b512016-09-06 20:57:50 +00001255 // Parse out the starting address
1256 lldb::addr_t start_address = line_extractor.GetHexMaxU64(false, 0);
Todd Fialaaf245d12014-06-30 21:05:18 +00001257
Kate Stoneb9c1b512016-09-06 20:57:50 +00001258 // Parse out hyphen separating start and end address from range.
1259 if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != '-'))
Zachary Turner97206d52017-05-12 04:51:55 +00001260 return Status(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001261 "malformed /proc/{pid}/maps entry, missing dash between address range");
Todd Fialaaf245d12014-06-30 21:05:18 +00001262
Kate Stoneb9c1b512016-09-06 20:57:50 +00001263 // Parse out the ending address
1264 lldb::addr_t end_address = line_extractor.GetHexMaxU64(false, start_address);
Todd Fialaaf245d12014-06-30 21:05:18 +00001265
Kate Stoneb9c1b512016-09-06 20:57:50 +00001266 // Parse out the space after the address.
1267 if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != ' '))
Zachary Turner97206d52017-05-12 04:51:55 +00001268 return Status(
1269 "malformed /proc/{pid}/maps entry, missing space after range");
Todd Fialaaf245d12014-06-30 21:05:18 +00001270
Kate Stoneb9c1b512016-09-06 20:57:50 +00001271 // Save the range.
1272 memory_region_info.GetRange().SetRangeBase(start_address);
1273 memory_region_info.GetRange().SetRangeEnd(end_address);
Todd Fialaaf245d12014-06-30 21:05:18 +00001274
Kate Stoneb9c1b512016-09-06 20:57:50 +00001275 // Any memory region in /proc/{pid}/maps is by definition mapped into the
1276 // process.
1277 memory_region_info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
Howard Hellyerad007562016-07-07 08:21:28 +00001278
Kate Stoneb9c1b512016-09-06 20:57:50 +00001279 // Parse out each permission entry.
1280 if (line_extractor.GetBytesLeft() < 4)
Zachary Turner97206d52017-05-12 04:51:55 +00001281 return Status("malformed /proc/{pid}/maps entry, missing some portion of "
1282 "permissions");
Todd Fialaaf245d12014-06-30 21:05:18 +00001283
Kate Stoneb9c1b512016-09-06 20:57:50 +00001284 // Handle read permission.
1285 const char read_perm_char = line_extractor.GetChar();
1286 if (read_perm_char == 'r')
1287 memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eYes);
1288 else if (read_perm_char == '-')
1289 memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1290 else
Zachary Turner97206d52017-05-12 04:51:55 +00001291 return Status("unexpected /proc/{pid}/maps read permission char");
Todd Fialaaf245d12014-06-30 21:05:18 +00001292
Kate Stoneb9c1b512016-09-06 20:57:50 +00001293 // Handle write permission.
1294 const char write_perm_char = line_extractor.GetChar();
1295 if (write_perm_char == 'w')
1296 memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eYes);
1297 else if (write_perm_char == '-')
1298 memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1299 else
Zachary Turner97206d52017-05-12 04:51:55 +00001300 return Status("unexpected /proc/{pid}/maps write permission char");
Todd Fialaaf245d12014-06-30 21:05:18 +00001301
Kate Stoneb9c1b512016-09-06 20:57:50 +00001302 // Handle execute permission.
1303 const char exec_perm_char = line_extractor.GetChar();
1304 if (exec_perm_char == 'x')
1305 memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes);
1306 else if (exec_perm_char == '-')
1307 memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1308 else
Zachary Turner97206d52017-05-12 04:51:55 +00001309 return Status("unexpected /proc/{pid}/maps exec permission char");
Todd Fialaaf245d12014-06-30 21:05:18 +00001310
Kate Stoneb9c1b512016-09-06 20:57:50 +00001311 line_extractor.GetChar(); // Read the private bit
1312 line_extractor.SkipSpaces(); // Skip the separator
1313 line_extractor.GetHexMaxU64(false, 0); // Read the offset
1314 line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1315 line_extractor.GetChar(); // Read the device id separator
1316 line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1317 line_extractor.SkipSpaces(); // Skip the separator
1318 line_extractor.GetU64(0, 10); // Read the inode number
Tamas Berghammerd7d69f82016-07-22 12:55:35 +00001319
Kate Stoneb9c1b512016-09-06 20:57:50 +00001320 line_extractor.SkipSpaces();
1321 const char *name = line_extractor.Peek();
1322 if (name)
1323 memory_region_info.SetName(name);
Tamas Berghammerd7d69f82016-07-22 12:55:35 +00001324
Zachary Turner97206d52017-05-12 04:51:55 +00001325 return Status();
Todd Fialaaf245d12014-06-30 21:05:18 +00001326}
1327
Zachary Turner97206d52017-05-12 04:51:55 +00001328Status NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr,
1329 MemoryRegionInfo &range_info) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001330 // FIXME review that the final memory region returned extends to the end of
1331 // the virtual address space,
1332 // with no perms if it is not mapped.
Todd Fialaaf245d12014-06-30 21:05:18 +00001333
Kate Stoneb9c1b512016-09-06 20:57:50 +00001334 // Use an approach that reads memory regions from /proc/{pid}/maps.
1335 // Assume proc maps entries are in ascending order.
1336 // FIXME assert if we find differently.
Todd Fialaaf245d12014-06-30 21:05:18 +00001337
Kate Stoneb9c1b512016-09-06 20:57:50 +00001338 if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
1339 // We're done.
Zachary Turner97206d52017-05-12 04:51:55 +00001340 return Status("unsupported");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001341 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001342
Zachary Turner97206d52017-05-12 04:51:55 +00001343 Status error = PopulateMemoryRegionCache();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001344 if (error.Fail()) {
1345 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001346 }
1347
1348 lldb::addr_t prev_base_address = 0;
1349
1350 // FIXME start by finding the last region that is <= target address using
1351 // binary search. Data is sorted.
1352 // There can be a ton of regions on pthreads apps with lots of threads.
1353 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1354 ++it) {
Tamas Berghammera6f57952017-01-03 16:29:43 +00001355 MemoryRegionInfo &proc_entry_info = it->first;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001356
1357 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1358 assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
1359 "descending /proc/pid/maps entries detected, unexpected");
1360 prev_base_address = proc_entry_info.GetRange().GetRangeBase();
Hafiz Abid Qadeerb1554312017-01-20 10:24:03 +00001361 UNUSED_IF_ASSERT_DISABLED(prev_base_address);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001362
1363 // If the target address comes before this entry, indicate distance to next
1364 // region.
1365 if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1366 range_info.GetRange().SetRangeBase(load_addr);
1367 range_info.GetRange().SetByteSize(
1368 proc_entry_info.GetRange().GetRangeBase() - load_addr);
1369 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1370 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1371 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1372 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1373
1374 return error;
1375 } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1376 // The target address is within the memory region we're processing here.
1377 range_info = proc_entry_info;
1378 return error;
1379 }
1380
1381 // The target memory address comes somewhere after the region we just
1382 // parsed.
1383 }
1384
1385 // If we made it here, we didn't find an entry that contained the given
1386 // address. Return the
1387 // load_addr as start and the amount of bytes betwwen load address and the end
1388 // of the memory as
1389 // size.
1390 range_info.GetRange().SetRangeBase(load_addr);
1391 range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
1392 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1393 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1394 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1395 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1396 return error;
1397}
1398
Zachary Turner97206d52017-05-12 04:51:55 +00001399Status NativeProcessLinux::PopulateMemoryRegionCache() {
Pavel Labatha6321a82017-01-19 15:26:04 +00001400 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Tamas Berghammera6f57952017-01-03 16:29:43 +00001401
1402 // If our cache is empty, pull the latest. There should always be at least
1403 // one memory region if memory region handling is supported.
1404 if (!m_mem_region_cache.empty()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001405 LLDB_LOG(log, "reusing {0} cached memory region entries",
1406 m_mem_region_cache.size());
Zachary Turner97206d52017-05-12 04:51:55 +00001407 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001408 }
1409
Pavel Labath15930862017-03-21 13:49:45 +00001410 auto BufferOrError = getProcFile(GetID(), "maps");
1411 if (!BufferOrError) {
Tamas Berghammera6f57952017-01-03 16:29:43 +00001412 m_supports_mem_region = LazyBool::eLazyBoolNo;
Pavel Labath15930862017-03-21 13:49:45 +00001413 return BufferOrError.getError();
1414 }
1415 StringRef Rest = BufferOrError.get()->getBuffer();
1416 while (! Rest.empty()) {
1417 StringRef Line;
1418 std::tie(Line, Rest) = Rest.split('\n');
1419 MemoryRegionInfo info;
Zachary Turner97206d52017-05-12 04:51:55 +00001420 const Status parse_error =
1421 ParseMemoryRegionInfoFromProcMapsLine(Line, info);
Pavel Labath15930862017-03-21 13:49:45 +00001422 if (parse_error.Fail()) {
1423 LLDB_LOG(log, "failed to parse proc maps line '{0}': {1}", Line,
1424 parse_error);
1425 m_supports_mem_region = LazyBool::eLazyBoolNo;
1426 return parse_error;
1427 }
1428 m_mem_region_cache.emplace_back(
1429 info, FileSpec(info.GetName().GetCString(), true));
1430 }
1431
1432 if (m_mem_region_cache.empty()) {
Tamas Berghammera6f57952017-01-03 16:29:43 +00001433 // No entries after attempting to read them. This shouldn't happen if
1434 // /proc/{pid}/maps is supported. Assume we don't support map entries
1435 // via procfs.
Pavel Labath15930862017-03-21 13:49:45 +00001436 m_supports_mem_region = LazyBool::eLazyBoolNo;
Pavel Labatha6321a82017-01-19 15:26:04 +00001437 LLDB_LOG(log,
1438 "failed to find any procfs maps entries, assuming no support "
1439 "for memory region metadata retrieval");
Zachary Turner97206d52017-05-12 04:51:55 +00001440 return Status("not supported");
Tamas Berghammera6f57952017-01-03 16:29:43 +00001441 }
1442
Pavel Labatha6321a82017-01-19 15:26:04 +00001443 LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps",
1444 m_mem_region_cache.size(), GetID());
Tamas Berghammera6f57952017-01-03 16:29:43 +00001445
1446 // We support memory retrieval, remember that.
1447 m_supports_mem_region = LazyBool::eLazyBoolYes;
Zachary Turner97206d52017-05-12 04:51:55 +00001448 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001449}
1450
Kate Stoneb9c1b512016-09-06 20:57:50 +00001451void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001452 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1453 LLDB_LOG(log, "newBumpId={0}", newBumpId);
1454 LLDB_LOG(log, "clearing {0} entries from memory region cache",
1455 m_mem_region_cache.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001456 m_mem_region_cache.clear();
1457}
1458
Zachary Turner97206d52017-05-12 04:51:55 +00001459Status NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions,
1460 lldb::addr_t &addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001461// FIXME implementing this requires the equivalent of
1462// InferiorCallPOSIX::InferiorCallMmap, which depends on
1463// functional ThreadPlans working with Native*Protocol.
1464#if 1
Zachary Turner97206d52017-05-12 04:51:55 +00001465 return Status("not implemented yet");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001466#else
1467 addr = LLDB_INVALID_ADDRESS;
1468
1469 unsigned prot = 0;
1470 if (permissions & lldb::ePermissionsReadable)
1471 prot |= eMmapProtRead;
1472 if (permissions & lldb::ePermissionsWritable)
1473 prot |= eMmapProtWrite;
1474 if (permissions & lldb::ePermissionsExecutable)
1475 prot |= eMmapProtExec;
1476
1477 // TODO implement this directly in NativeProcessLinux
1478 // (and lift to NativeProcessPOSIX if/when that class is
1479 // refactored out).
1480 if (InferiorCallMmap(this, addr, 0, size, prot,
1481 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
1482 m_addr_to_mmap_size[addr] = size;
Zachary Turner97206d52017-05-12 04:51:55 +00001483 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001484 } else {
1485 addr = LLDB_INVALID_ADDRESS;
Zachary Turner97206d52017-05-12 04:51:55 +00001486 return Status("unable to allocate %" PRIu64
1487 " bytes of memory with permissions %s",
1488 size, GetPermissionsAsCString(permissions));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001489 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001490#endif
1491}
1492
Zachary Turner97206d52017-05-12 04:51:55 +00001493Status NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001494 // FIXME see comments in AllocateMemory - required lower-level
1495 // bits not in place yet (ThreadPlans)
Zachary Turner97206d52017-05-12 04:51:55 +00001496 return Status("not implemented");
Todd Fialaaf245d12014-06-30 21:05:18 +00001497}
1498
Kate Stoneb9c1b512016-09-06 20:57:50 +00001499lldb::addr_t NativeProcessLinux::GetSharedLibraryInfoAddress() {
1500 // punt on this for now
1501 return LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00001502}
1503
Kate Stoneb9c1b512016-09-06 20:57:50 +00001504size_t NativeProcessLinux::UpdateThreads() {
1505 // The NativeProcessLinux monitoring threads are always up to date
1506 // with respect to thread state and they keep the thread list
1507 // populated properly. All this method needs to do is return the
1508 // thread count.
1509 return m_threads.size();
Todd Fialaaf245d12014-06-30 21:05:18 +00001510}
1511
Zachary Turner97206d52017-05-12 04:51:55 +00001512Status NativeProcessLinux::GetSoftwareBreakpointPCOffset(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001513 uint32_t &actual_opcode_size) {
1514 // FIXME put this behind a breakpoint protocol class that can be
1515 // set per architecture. Need ARM, MIPS support here.
1516 static const uint8_t g_i386_opcode[] = {0xCC};
1517 static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
Eugene Zemtsovaae0a752017-10-05 19:44:05 +00001518 static const uint8_t g_ppc64le_opcode[] = {0x08, 0x00, 0xe0, 0x7f}; // trap
Todd Fialaaf245d12014-06-30 21:05:18 +00001519
Kate Stoneb9c1b512016-09-06 20:57:50 +00001520 switch (m_arch.GetMachine()) {
1521 case llvm::Triple::x86:
1522 case llvm::Triple::x86_64:
1523 actual_opcode_size = static_cast<uint32_t>(sizeof(g_i386_opcode));
Zachary Turner97206d52017-05-12 04:51:55 +00001524 return Status();
Todd Fialaaf245d12014-06-30 21:05:18 +00001525
Kate Stoneb9c1b512016-09-06 20:57:50 +00001526 case llvm::Triple::systemz:
1527 actual_opcode_size = static_cast<uint32_t>(sizeof(g_s390x_opcode));
Zachary Turner97206d52017-05-12 04:51:55 +00001528 return Status();
Ulrich Weigandbb00d0b2016-04-14 14:28:34 +00001529
Eugene Zemtsovaae0a752017-10-05 19:44:05 +00001530 case llvm::Triple::ppc64le:
1531 actual_opcode_size = static_cast<uint32_t>(sizeof(g_ppc64le_opcode));
1532 return Status();
1533
Kate Stoneb9c1b512016-09-06 20:57:50 +00001534 case llvm::Triple::arm:
1535 case llvm::Triple::aarch64:
1536 case llvm::Triple::mips64:
1537 case llvm::Triple::mips64el:
1538 case llvm::Triple::mips:
1539 case llvm::Triple::mipsel:
1540 // On these architectures the PC don't get updated for breakpoint hits
1541 actual_opcode_size = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00001542 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001543
1544 default:
1545 assert(false && "CPU type not supported!");
Zachary Turner97206d52017-05-12 04:51:55 +00001546 return Status("CPU type not supported");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001547 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001548}
1549
Zachary Turner97206d52017-05-12 04:51:55 +00001550Status NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,
1551 bool hardware) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001552 if (hardware)
Omair Javaidd5ffbad2017-02-24 13:27:31 +00001553 return SetHardwareBreakpoint(addr, size);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001554 else
1555 return SetSoftwareBreakpoint(addr, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00001556}
1557
Zachary Turner97206d52017-05-12 04:51:55 +00001558Status NativeProcessLinux::RemoveBreakpoint(lldb::addr_t addr, bool hardware) {
Omair Javaidd5ffbad2017-02-24 13:27:31 +00001559 if (hardware)
1560 return RemoveHardwareBreakpoint(addr);
1561 else
1562 return NativeProcessProtocol::RemoveBreakpoint(addr);
1563}
1564
Zachary Turner97206d52017-05-12 04:51:55 +00001565Status NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001566 size_t trap_opcode_size_hint, size_t &actual_opcode_size,
1567 const uint8_t *&trap_opcode_bytes) {
1568 // FIXME put this behind a breakpoint protocol class that can be set per
1569 // architecture. Need MIPS support here.
1570 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};
1571 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1572 // linux kernel does otherwise.
1573 static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1574 static const uint8_t g_i386_opcode[] = {0xCC};
1575 static const uint8_t g_mips64_opcode[] = {0x00, 0x00, 0x00, 0x0d};
1576 static const uint8_t g_mips64el_opcode[] = {0x0d, 0x00, 0x00, 0x00};
1577 static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
1578 static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
Eugene Zemtsovaae0a752017-10-05 19:44:05 +00001579 static const uint8_t g_ppc64le_opcode[] = {0x08, 0x00, 0xe0, 0x7f}; // trap
Todd Fialaaf245d12014-06-30 21:05:18 +00001580
Kate Stoneb9c1b512016-09-06 20:57:50 +00001581 switch (m_arch.GetMachine()) {
1582 case llvm::Triple::aarch64:
1583 trap_opcode_bytes = g_aarch64_opcode;
1584 actual_opcode_size = sizeof(g_aarch64_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001585 return Status();
Todd Fiala2afc5962014-08-21 16:42:31 +00001586
Kate Stoneb9c1b512016-09-06 20:57:50 +00001587 case llvm::Triple::arm:
1588 switch (trap_opcode_size_hint) {
1589 case 2:
1590 trap_opcode_bytes = g_thumb_breakpoint_opcode;
1591 actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001592 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001593 case 4:
1594 trap_opcode_bytes = g_arm_breakpoint_opcode;
1595 actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001596 return Status();
Todd Fialaaf245d12014-06-30 21:05:18 +00001597 default:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001598 assert(false && "Unrecognised trap opcode size hint!");
Zachary Turner97206d52017-05-12 04:51:55 +00001599 return Status("Unrecognised trap opcode size hint!");
Todd Fialaaf245d12014-06-30 21:05:18 +00001600 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001601
1602 case llvm::Triple::x86:
1603 case llvm::Triple::x86_64:
1604 trap_opcode_bytes = g_i386_opcode;
1605 actual_opcode_size = sizeof(g_i386_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001606 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001607
1608 case llvm::Triple::mips:
1609 case llvm::Triple::mips64:
1610 trap_opcode_bytes = g_mips64_opcode;
1611 actual_opcode_size = sizeof(g_mips64_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001612 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001613
1614 case llvm::Triple::mipsel:
1615 case llvm::Triple::mips64el:
1616 trap_opcode_bytes = g_mips64el_opcode;
1617 actual_opcode_size = sizeof(g_mips64el_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001618 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001619
1620 case llvm::Triple::systemz:
1621 trap_opcode_bytes = g_s390x_opcode;
1622 actual_opcode_size = sizeof(g_s390x_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001623 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001624
Eugene Zemtsovaae0a752017-10-05 19:44:05 +00001625 case llvm::Triple::ppc64le:
1626 trap_opcode_bytes = g_ppc64le_opcode;
1627 actual_opcode_size = sizeof(g_ppc64le_opcode);
1628 return Status();
1629
Kate Stoneb9c1b512016-09-06 20:57:50 +00001630 default:
1631 assert(false && "CPU type not supported!");
Zachary Turner97206d52017-05-12 04:51:55 +00001632 return Status("CPU type not supported");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001633 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001634}
1635
1636#if 0
1637ProcessMessage::CrashReason
1638NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
1639{
1640 ProcessMessage::CrashReason reason;
1641 assert(info->si_signo == SIGSEGV);
1642
1643 reason = ProcessMessage::eInvalidCrashReason;
1644
1645 switch (info->si_code)
1646 {
1647 default:
1648 assert(false && "unexpected si_code for SIGSEGV");
1649 break;
1650 case SI_KERNEL:
1651 // Linux will occasionally send spurious SI_KERNEL codes.
1652 // (this is poorly documented in sigaction)
1653 // One way to get this is via unaligned SIMD loads.
1654 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
1655 break;
1656 case SEGV_MAPERR:
1657 reason = ProcessMessage::eInvalidAddress;
1658 break;
1659 case SEGV_ACCERR:
1660 reason = ProcessMessage::ePrivilegedAddress;
1661 break;
1662 }
1663
1664 return reason;
1665}
1666#endif
1667
Todd Fialaaf245d12014-06-30 21:05:18 +00001668#if 0
1669ProcessMessage::CrashReason
1670NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
1671{
1672 ProcessMessage::CrashReason reason;
1673 assert(info->si_signo == SIGILL);
1674
1675 reason = ProcessMessage::eInvalidCrashReason;
1676
1677 switch (info->si_code)
1678 {
1679 default:
1680 assert(false && "unexpected si_code for SIGILL");
1681 break;
1682 case ILL_ILLOPC:
1683 reason = ProcessMessage::eIllegalOpcode;
1684 break;
1685 case ILL_ILLOPN:
1686 reason = ProcessMessage::eIllegalOperand;
1687 break;
1688 case ILL_ILLADR:
1689 reason = ProcessMessage::eIllegalAddressingMode;
1690 break;
1691 case ILL_ILLTRP:
1692 reason = ProcessMessage::eIllegalTrap;
1693 break;
1694 case ILL_PRVOPC:
1695 reason = ProcessMessage::ePrivilegedOpcode;
1696 break;
1697 case ILL_PRVREG:
1698 reason = ProcessMessage::ePrivilegedRegister;
1699 break;
1700 case ILL_COPROC:
1701 reason = ProcessMessage::eCoprocessorError;
1702 break;
1703 case ILL_BADSTK:
1704 reason = ProcessMessage::eInternalStackError;
1705 break;
1706 }
1707
1708 return reason;
1709}
1710#endif
1711
1712#if 0
1713ProcessMessage::CrashReason
1714NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
1715{
1716 ProcessMessage::CrashReason reason;
1717 assert(info->si_signo == SIGFPE);
1718
1719 reason = ProcessMessage::eInvalidCrashReason;
1720
1721 switch (info->si_code)
1722 {
1723 default:
1724 assert(false && "unexpected si_code for SIGFPE");
1725 break;
1726 case FPE_INTDIV:
1727 reason = ProcessMessage::eIntegerDivideByZero;
1728 break;
1729 case FPE_INTOVF:
1730 reason = ProcessMessage::eIntegerOverflow;
1731 break;
1732 case FPE_FLTDIV:
1733 reason = ProcessMessage::eFloatDivideByZero;
1734 break;
1735 case FPE_FLTOVF:
1736 reason = ProcessMessage::eFloatOverflow;
1737 break;
1738 case FPE_FLTUND:
1739 reason = ProcessMessage::eFloatUnderflow;
1740 break;
1741 case FPE_FLTRES:
1742 reason = ProcessMessage::eFloatInexactResult;
1743 break;
1744 case FPE_FLTINV:
1745 reason = ProcessMessage::eFloatInvalidOperation;
1746 break;
1747 case FPE_FLTSUB:
1748 reason = ProcessMessage::eFloatSubscriptRange;
1749 break;
1750 }
1751
1752 return reason;
1753}
1754#endif
1755
1756#if 0
1757ProcessMessage::CrashReason
1758NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
1759{
1760 ProcessMessage::CrashReason reason;
1761 assert(info->si_signo == SIGBUS);
1762
1763 reason = ProcessMessage::eInvalidCrashReason;
1764
1765 switch (info->si_code)
1766 {
1767 default:
1768 assert(false && "unexpected si_code for SIGBUS");
1769 break;
1770 case BUS_ADRALN:
1771 reason = ProcessMessage::eIllegalAlignment;
1772 break;
1773 case BUS_ADRERR:
1774 reason = ProcessMessage::eIllegalAddress;
1775 break;
1776 case BUS_OBJERR:
1777 reason = ProcessMessage::eHardwareError;
1778 break;
1779 }
1780
1781 return reason;
1782}
1783#endif
1784
Zachary Turner97206d52017-05-12 04:51:55 +00001785Status NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
1786 size_t &bytes_read) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001787 if (ProcessVmReadvSupported()) {
1788 // The process_vm_readv path is about 50 times faster than ptrace api. We
1789 // want to use
1790 // this syscall if it is supported.
Pavel Labathdf7c6992015-06-17 18:38:49 +00001791
Kate Stoneb9c1b512016-09-06 20:57:50 +00001792 const ::pid_t pid = GetID();
Pavel Labathdf7c6992015-06-17 18:38:49 +00001793
Kate Stoneb9c1b512016-09-06 20:57:50 +00001794 struct iovec local_iov, remote_iov;
1795 local_iov.iov_base = buf;
1796 local_iov.iov_len = size;
1797 remote_iov.iov_base = reinterpret_cast<void *>(addr);
1798 remote_iov.iov_len = size;
Pavel Labathdf7c6992015-06-17 18:38:49 +00001799
Kate Stoneb9c1b512016-09-06 20:57:50 +00001800 bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
1801 const bool success = bytes_read == size;
Pavel Labathdf7c6992015-06-17 18:38:49 +00001802
Pavel Labatha6321a82017-01-19 15:26:04 +00001803 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1804 LLDB_LOG(log,
1805 "using process_vm_readv to read {0} bytes from inferior "
1806 "address {1:x}: {2}",
Pavel Labath10c41f32017-06-06 14:06:17 +00001807 size, addr, success ? "Success" : llvm::sys::StrError(errno));
Pavel Labath19cbe962015-07-21 13:20:32 +00001808
Kate Stoneb9c1b512016-09-06 20:57:50 +00001809 if (success)
Zachary Turner97206d52017-05-12 04:51:55 +00001810 return Status();
Pavel Labatha6321a82017-01-19 15:26:04 +00001811 // else the call failed for some reason, let's retry the read using ptrace
1812 // api.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001813 }
Pavel Labath19cbe962015-07-21 13:20:32 +00001814
Kate Stoneb9c1b512016-09-06 20:57:50 +00001815 unsigned char *dst = static_cast<unsigned char *>(buf);
1816 size_t remainder;
1817 long data;
Pavel Labath19cbe962015-07-21 13:20:32 +00001818
Pavel Labatha6321a82017-01-19 15:26:04 +00001819 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1820 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
Pavel Labath19cbe962015-07-21 13:20:32 +00001821
Kate Stoneb9c1b512016-09-06 20:57:50 +00001822 for (bytes_read = 0; bytes_read < size; bytes_read += remainder) {
Zachary Turner97206d52017-05-12 04:51:55 +00001823 Status error = NativeProcessLinux::PtraceWrapper(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001824 PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data);
Pavel Labatha6321a82017-01-19 15:26:04 +00001825 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001826 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001827
1828 remainder = size - bytes_read;
1829 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
1830
1831 // Copy the data into our buffer
1832 memcpy(dst, &data, remainder);
1833
Pavel Labatha6321a82017-01-19 15:26:04 +00001834 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001835 addr += k_ptrace_word_size;
1836 dst += k_ptrace_word_size;
1837 }
Zachary Turner97206d52017-05-12 04:51:55 +00001838 return Status();
Todd Fialaaf245d12014-06-30 21:05:18 +00001839}
1840
Zachary Turner97206d52017-05-12 04:51:55 +00001841Status NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf,
1842 size_t size,
1843 size_t &bytes_read) {
1844 Status error = ReadMemory(addr, buf, size, bytes_read);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001845 if (error.Fail())
Pavel Labath19cbe962015-07-21 13:20:32 +00001846 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001847 return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00001848}
1849
Zachary Turner97206d52017-05-12 04:51:55 +00001850Status NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,
1851 size_t size, size_t &bytes_written) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001852 const unsigned char *src = static_cast<const unsigned char *>(buf);
1853 size_t remainder;
Zachary Turner97206d52017-05-12 04:51:55 +00001854 Status error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001855
Pavel Labatha6321a82017-01-19 15:26:04 +00001856 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1857 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00001858
Kate Stoneb9c1b512016-09-06 20:57:50 +00001859 for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
1860 remainder = size - bytes_written;
1861 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
Chaoren Lin97ccc292015-02-03 01:51:12 +00001862
Kate Stoneb9c1b512016-09-06 20:57:50 +00001863 if (remainder == k_ptrace_word_size) {
1864 unsigned long data = 0;
1865 memcpy(&data, src, k_ptrace_word_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00001866
Pavel Labatha6321a82017-01-19 15:26:04 +00001867 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001868 error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(),
1869 (void *)addr, (void *)data);
Pavel Labatha6321a82017-01-19 15:26:04 +00001870 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001871 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001872 } else {
1873 unsigned char buff[8];
1874 size_t bytes_read;
1875 error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
Pavel Labatha6321a82017-01-19 15:26:04 +00001876 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001877 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001878
1879 memcpy(buff, src, remainder);
1880
1881 size_t bytes_written_rec;
1882 error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
Pavel Labatha6321a82017-01-19 15:26:04 +00001883 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001884 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001885
Pavel Labatha6321a82017-01-19 15:26:04 +00001886 LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src,
1887 *(unsigned long *)buff);
Todd Fialaaf245d12014-06-30 21:05:18 +00001888 }
1889
Kate Stoneb9c1b512016-09-06 20:57:50 +00001890 addr += k_ptrace_word_size;
1891 src += k_ptrace_word_size;
1892 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001893 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001894}
1895
Zachary Turner97206d52017-05-12 04:51:55 +00001896Status NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001897 return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
1898}
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001899
Zachary Turner97206d52017-05-12 04:51:55 +00001900Status NativeProcessLinux::GetEventMessage(lldb::tid_t tid,
1901 unsigned long *message) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001902 return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
1903}
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001904
Zachary Turner97206d52017-05-12 04:51:55 +00001905Status NativeProcessLinux::Detach(lldb::tid_t tid) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001906 if (tid == LLDB_INVALID_THREAD_ID)
Zachary Turner97206d52017-05-12 04:51:55 +00001907 return Status();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001908
Kate Stoneb9c1b512016-09-06 20:57:50 +00001909 return PtraceWrapper(PTRACE_DETACH, tid);
1910}
1911
1912bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {
Pavel Labatha5be48b2017-10-17 15:52:16 +00001913 for (const auto &thread : m_threads) {
1914 assert(thread && "thread list should not contain NULL threads");
1915 if (thread->GetID() == thread_id) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001916 // We have this thread.
1917 return true;
Todd Fialaaf245d12014-06-30 21:05:18 +00001918 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001919 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001920
Kate Stoneb9c1b512016-09-06 20:57:50 +00001921 // We don't have this thread.
1922 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001923}
1924
Kate Stoneb9c1b512016-09-06 20:57:50 +00001925bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001926 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1927 LLDB_LOG(log, "tid: {0})", thread_id);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001928
1929 bool found = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001930 for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
1931 if (*it && ((*it)->GetID() == thread_id)) {
1932 m_threads.erase(it);
1933 found = true;
1934 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00001935 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001936 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001937
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001938 if (found)
1939 StopTracingForThread(thread_id);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001940 SignalIfAllThreadsStopped();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001941 return found;
Todd Fialaaf245d12014-06-30 21:05:18 +00001942}
1943
Pavel Labatha5be48b2017-10-17 15:52:16 +00001944NativeThreadLinux &NativeProcessLinux::AddThread(lldb::tid_t thread_id) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001945 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
1946 LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
Todd Fialaaf245d12014-06-30 21:05:18 +00001947
Kate Stoneb9c1b512016-09-06 20:57:50 +00001948 assert(!HasThreadNoLock(thread_id) &&
1949 "attempted to add a thread by id that already exists");
Todd Fialaaf245d12014-06-30 21:05:18 +00001950
Kate Stoneb9c1b512016-09-06 20:57:50 +00001951 // If this is the first thread, save it as the current thread
1952 if (m_threads.empty())
1953 SetCurrentThreadID(thread_id);
Todd Fialaaf245d12014-06-30 21:05:18 +00001954
Pavel Labatha5be48b2017-10-17 15:52:16 +00001955 m_threads.push_back(llvm::make_unique<NativeThreadLinux>(*this, thread_id));
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001956
1957 if (m_pt_proces_trace_id != LLDB_INVALID_UID) {
1958 auto traceMonitor = ProcessorTraceMonitor::Create(
1959 GetID(), thread_id, m_pt_process_trace_config, true);
1960 if (traceMonitor) {
1961 m_pt_traced_thread_group.insert(thread_id);
1962 m_processor_trace_monitor.insert(
1963 std::make_pair(thread_id, std::move(*traceMonitor)));
1964 } else {
1965 LLDB_LOG(log, "failed to start trace on thread {0}", thread_id);
1966 Status error(traceMonitor.takeError());
1967 LLDB_LOG(log, "error {0}", error);
1968 }
1969 }
1970
Pavel Labatha5be48b2017-10-17 15:52:16 +00001971 return static_cast<NativeThreadLinux &>(*m_threads.back());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001972}
Todd Fialaaf245d12014-06-30 21:05:18 +00001973
Zachary Turner97206d52017-05-12 04:51:55 +00001974Status
1975NativeProcessLinux::FixupBreakpointPCAsNeeded(NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001976 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_BREAKPOINTS));
Todd Fialaaf245d12014-06-30 21:05:18 +00001977
Zachary Turner97206d52017-05-12 04:51:55 +00001978 Status error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001979
Kate Stoneb9c1b512016-09-06 20:57:50 +00001980 // Find out the size of a breakpoint (might depend on where we are in the
1981 // code).
Pavel Labathd37349f2017-11-10 11:05:49 +00001982 NativeRegisterContext &context = thread.GetRegisterContext();
Chaoren Linfa03ad22015-02-03 01:50:42 +00001983
Kate Stoneb9c1b512016-09-06 20:57:50 +00001984 uint32_t breakpoint_size = 0;
1985 error = GetSoftwareBreakpointPCOffset(breakpoint_size);
1986 if (error.Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001987 LLDB_LOG(log, "GetBreakpointSize() failed: {0}", error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001988 return error;
Pavel Labatha6321a82017-01-19 15:26:04 +00001989 } else
1990 LLDB_LOG(log, "breakpoint size: {0}", breakpoint_size);
Pavel Labathc0765592015-05-06 10:46:34 +00001991
Kate Stoneb9c1b512016-09-06 20:57:50 +00001992 // First try probing for a breakpoint at a software breakpoint location: PC -
1993 // breakpoint size.
Pavel Labathd37349f2017-11-10 11:05:49 +00001994 const lldb::addr_t initial_pc_addr = context.GetPCfromBreakpointLocation();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001995 lldb::addr_t breakpoint_addr = initial_pc_addr;
1996 if (breakpoint_size > 0) {
1997 // Do not allow breakpoint probe to wrap around.
1998 if (breakpoint_addr >= breakpoint_size)
1999 breakpoint_addr -= breakpoint_size;
2000 }
2001
2002 // Check if we stopped because of a breakpoint.
2003 NativeBreakpointSP breakpoint_sp;
2004 error = m_breakpoint_list.GetBreakpoint(breakpoint_addr, breakpoint_sp);
2005 if (!error.Success() || !breakpoint_sp) {
2006 // We didn't find one at a software probe location. Nothing to do.
Pavel Labatha6321a82017-01-19 15:26:04 +00002007 LLDB_LOG(log,
2008 "pid {0} no lldb breakpoint found at current pc with "
2009 "adjustment: {1}",
2010 GetID(), breakpoint_addr);
Zachary Turner97206d52017-05-12 04:51:55 +00002011 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002012 }
2013
2014 // If the breakpoint is not a software breakpoint, nothing to do.
2015 if (!breakpoint_sp->IsSoftwareBreakpoint()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002016 LLDB_LOG(
2017 log,
2018 "pid {0} breakpoint found at {1:x}, not software, nothing to adjust",
2019 GetID(), breakpoint_addr);
Zachary Turner97206d52017-05-12 04:51:55 +00002020 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002021 }
2022
2023 //
2024 // We have a software breakpoint and need to adjust the PC.
2025 //
2026
2027 // Sanity check.
2028 if (breakpoint_size == 0) {
2029 // Nothing to do! How did we get here?
Pavel Labatha6321a82017-01-19 15:26:04 +00002030 LLDB_LOG(log,
2031 "pid {0} breakpoint found at {1:x}, it is software, but the "
2032 "size is zero, nothing to do (unexpected)",
2033 GetID(), breakpoint_addr);
Zachary Turner97206d52017-05-12 04:51:55 +00002034 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002035 }
2036
2037 // Change the program counter.
Pavel Labatha6321a82017-01-19 15:26:04 +00002038 LLDB_LOG(log, "pid {0} tid {1}: changing PC from {2:x} to {3:x}", GetID(),
2039 thread.GetID(), initial_pc_addr, breakpoint_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002040
Pavel Labathd37349f2017-11-10 11:05:49 +00002041 error = context.SetPC(breakpoint_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002042 if (error.Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002043 LLDB_LOG(log, "pid {0} tid {1}: failed to set PC: {2}", GetID(),
2044 thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002045 return error;
2046 }
2047
2048 return error;
2049}
2050
Zachary Turner97206d52017-05-12 04:51:55 +00002051Status NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,
2052 FileSpec &file_spec) {
2053 Status error = PopulateMemoryRegionCache();
Tamas Berghammera6f57952017-01-03 16:29:43 +00002054 if (error.Fail())
2055 return error;
2056
Kate Stoneb9c1b512016-09-06 20:57:50 +00002057 FileSpec module_file_spec(module_path, true);
2058
Kate Stoneb9c1b512016-09-06 20:57:50 +00002059 file_spec.Clear();
Tamas Berghammera6f57952017-01-03 16:29:43 +00002060 for (const auto &it : m_mem_region_cache) {
2061 if (it.second.GetFilename() == module_file_spec.GetFilename()) {
2062 file_spec = it.second;
Zachary Turner97206d52017-05-12 04:51:55 +00002063 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00002064 }
2065 }
Zachary Turner97206d52017-05-12 04:51:55 +00002066 return Status("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
2067 module_file_spec.GetFilename().AsCString(), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002068}
2069
Zachary Turner97206d52017-05-12 04:51:55 +00002070Status NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
2071 lldb::addr_t &load_addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002072 load_addr = LLDB_INVALID_ADDRESS;
Zachary Turner97206d52017-05-12 04:51:55 +00002073 Status error = PopulateMemoryRegionCache();
Tamas Berghammera6f57952017-01-03 16:29:43 +00002074 if (error.Fail())
2075 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002076
Tamas Berghammera6f57952017-01-03 16:29:43 +00002077 FileSpec file(file_name, false);
2078 for (const auto &it : m_mem_region_cache) {
2079 if (it.second == file) {
2080 load_addr = it.first.GetRange().GetRangeBase();
Zachary Turner97206d52017-05-12 04:51:55 +00002081 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00002082 }
2083 }
Zachary Turner97206d52017-05-12 04:51:55 +00002084 return Status("No load address found for specified file.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002085}
2086
Pavel Labatha5be48b2017-10-17 15:52:16 +00002087NativeThreadLinux *NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {
2088 return static_cast<NativeThreadLinux *>(
Kate Stoneb9c1b512016-09-06 20:57:50 +00002089 NativeProcessProtocol::GetThreadByID(tid));
2090}
2091
Zachary Turner97206d52017-05-12 04:51:55 +00002092Status NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,
2093 lldb::StateType state, int signo) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002094 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2095 LLDB_LOG(log, "tid: {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002096
2097 // Before we do the resume below, first check if we have a pending
2098 // stop notification that is currently waiting for
2099 // all threads to stop. This is potentially a buggy situation since
2100 // we're ostensibly waiting for threads to stop before we send out the
2101 // pending notification, and here we are resuming one before we send
2102 // out the pending stop notification.
Pavel Labatha6321a82017-01-19 15:26:04 +00002103 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
2104 LLDB_LOG(log,
2105 "about to resume tid {0} per explicit request but we have a "
2106 "pending stop notification (tid {1}) that is actively "
2107 "waiting for this thread to stop. Valid sequence of events?",
2108 thread.GetID(), m_pending_notification_tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002109 }
2110
2111 // Request a resume. We expect this to be synchronous and the system
2112 // to reflect it is running after this completes.
2113 switch (state) {
2114 case eStateRunning: {
2115 const auto resume_result = thread.Resume(signo);
2116 if (resume_result.Success())
2117 SetState(eStateRunning, true);
2118 return resume_result;
2119 }
2120 case eStateStepping: {
2121 const auto step_result = thread.SingleStep(signo);
2122 if (step_result.Success())
2123 SetState(eStateRunning, true);
2124 return step_result;
2125 }
2126 default:
Pavel Labath8198db32017-01-24 11:48:25 +00002127 LLDB_LOG(log, "Unhandled state {0}.", state);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002128 llvm_unreachable("Unhandled state for resume");
2129 }
Pavel Labathc0765592015-05-06 10:46:34 +00002130}
2131
2132//===----------------------------------------------------------------------===//
2133
Kate Stoneb9c1b512016-09-06 20:57:50 +00002134void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002135 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2136 LLDB_LOG(log, "about to process event: (triggering_tid: {0})",
2137 triggering_tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002138
2139 m_pending_notification_tid = triggering_tid;
2140
2141 // Request a stop for all the thread stops that need to be stopped
2142 // and are not already known to be stopped.
Pavel Labatha5be48b2017-10-17 15:52:16 +00002143 for (const auto &thread : m_threads) {
2144 if (StateIsRunningState(thread->GetState()))
2145 static_cast<NativeThreadLinux *>(thread.get())->RequestStop();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002146 }
2147
2148 SignalIfAllThreadsStopped();
Pavel Labatha6321a82017-01-19 15:26:04 +00002149 LLDB_LOG(log, "event processing done");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002150}
2151
2152void NativeProcessLinux::SignalIfAllThreadsStopped() {
2153 if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
2154 return; // No pending notification. Nothing to do.
2155
2156 for (const auto &thread_sp : m_threads) {
2157 if (StateIsRunningState(thread_sp->GetState()))
2158 return; // Some threads are still running. Don't signal yet.
2159 }
2160
2161 // We have a pending notification and all threads have stopped.
2162 Log *log(
2163 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
2164
2165 // Clear any temporary breakpoints we used to implement software single
2166 // stepping.
2167 for (const auto &thread_info : m_threads_stepping_with_breakpoint) {
Zachary Turner97206d52017-05-12 04:51:55 +00002168 Status error = RemoveBreakpoint(thread_info.second);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002169 if (error.Fail())
Pavel Labatha6321a82017-01-19 15:26:04 +00002170 LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}",
2171 thread_info.first, error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002172 }
2173 m_threads_stepping_with_breakpoint.clear();
2174
2175 // Notify the delegate about the stop
2176 SetCurrentThreadID(m_pending_notification_tid);
2177 SetState(StateType::eStateStopped, true);
2178 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
2179}
2180
2181void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002182 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2183 LLDB_LOG(log, "tid: {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002184
2185 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID &&
2186 StateIsRunningState(thread.GetState())) {
2187 // We will need to wait for this new thread to stop as well before firing
2188 // the
2189 // notification.
2190 thread.RequestStop();
2191 }
2192}
2193
2194void NativeProcessLinux::SigchldHandler() {
Pavel Labatha6321a82017-01-19 15:26:04 +00002195 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002196 // Process all pending waitpid notifications.
2197 while (true) {
2198 int status = -1;
Pavel Labathc1a6b122017-07-03 09:25:55 +00002199 ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, -1, &status,
2200 __WALL | __WNOTHREAD | WNOHANG);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002201
2202 if (wait_pid == 0)
2203 break; // We are done.
2204
2205 if (wait_pid == -1) {
Zachary Turner97206d52017-05-12 04:51:55 +00002206 Status error(errno, eErrorTypePOSIX);
Pavel Labatha6321a82017-01-19 15:26:04 +00002207 LLDB_LOG(log, "waitpid (-1, &status, _) failed: {0}", error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002208 break;
Pavel Labathc0765592015-05-06 10:46:34 +00002209 }
2210
Pavel Labath3508fc82017-06-19 12:47:50 +00002211 WaitStatus wait_status = WaitStatus::Decode(status);
2212 bool exited = wait_status.type == WaitStatus::Exit ||
2213 (wait_status.type == WaitStatus::Signal &&
2214 wait_pid == static_cast<::pid_t>(GetID()));
Pavel Labathc0765592015-05-06 10:46:34 +00002215
Pavel Labath3508fc82017-06-19 12:47:50 +00002216 LLDB_LOG(
2217 log,
2218 "waitpid (-1, &status, _) => pid = {0}, status = {1}, exited = {2}",
2219 wait_pid, wait_status, exited);
Pavel Labathc0765592015-05-06 10:46:34 +00002220
Pavel Labath3508fc82017-06-19 12:47:50 +00002221 MonitorCallback(wait_pid, exited, wait_status);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002222 }
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002223}
2224
2225// Wrapper for ptrace to catch errors and log calls.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002226// Note that ptrace sets errno on error because -1 can be a valid result (i.e.
2227// for PTRACE_PEEK*)
Zachary Turner97206d52017-05-12 04:51:55 +00002228Status NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
2229 void *data, size_t data_size,
2230 long *result) {
2231 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002232 long int ret;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002233
Kate Stoneb9c1b512016-09-06 20:57:50 +00002234 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002235
Kate Stoneb9c1b512016-09-06 20:57:50 +00002236 PtraceDisplayBytes(req, data, data_size);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002237
Kate Stoneb9c1b512016-09-06 20:57:50 +00002238 errno = 0;
2239 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
2240 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2241 *(unsigned int *)addr, data);
2242 else
2243 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2244 addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002245
Kate Stoneb9c1b512016-09-06 20:57:50 +00002246 if (ret == -1)
2247 error.SetErrorToErrno();
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002248
Kate Stoneb9c1b512016-09-06 20:57:50 +00002249 if (result)
2250 *result = ret;
Pavel Labath4a9babb2015-06-30 17:04:49 +00002251
Pavel Labath28096202017-02-17 16:09:10 +00002252 LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data,
2253 data_size, ret);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002254
Kate Stoneb9c1b512016-09-06 20:57:50 +00002255 PtraceDisplayBytes(req, data, data_size);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002256
Pavel Labatha6321a82017-01-19 15:26:04 +00002257 if (error.Fail())
2258 LLDB_LOG(log, "ptrace() failed: {0}", error);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002259
Kate Stoneb9c1b512016-09-06 20:57:50 +00002260 return error;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002261}
Ravitheja Addepally99e37692017-06-28 07:58:31 +00002262
2263llvm::Expected<ProcessorTraceMonitor &>
2264NativeProcessLinux::LookupProcessorTraceInstance(lldb::user_id_t traceid,
2265 lldb::tid_t thread) {
2266 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2267 if (thread == LLDB_INVALID_THREAD_ID && traceid == m_pt_proces_trace_id) {
2268 LLDB_LOG(log, "thread not specified: {0}", traceid);
2269 return Status("tracing not active thread not specified").ToError();
2270 }
2271
2272 for (auto& iter : m_processor_trace_monitor) {
2273 if (traceid == iter.second->GetTraceID() &&
2274 (thread == iter.first || thread == LLDB_INVALID_THREAD_ID))
2275 return *(iter.second);
2276 }
2277
2278 LLDB_LOG(log, "traceid not being traced: {0}", traceid);
2279 return Status("tracing not active for this thread").ToError();
2280}
2281
2282Status NativeProcessLinux::GetMetaData(lldb::user_id_t traceid,
2283 lldb::tid_t thread,
2284 llvm::MutableArrayRef<uint8_t> &buffer,
2285 size_t offset) {
2286 TraceOptions trace_options;
2287 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2288 Status error;
2289
2290 LLDB_LOG(log, "traceid {0}", traceid);
2291
2292 auto perf_monitor = LookupProcessorTraceInstance(traceid, thread);
2293 if (!perf_monitor) {
2294 LLDB_LOG(log, "traceid not being traced: {0}", traceid);
2295 buffer = buffer.slice(buffer.size());
2296 error = perf_monitor.takeError();
2297 return error;
2298 }
2299 return (*perf_monitor).ReadPerfTraceData(buffer, offset);
2300}
2301
2302Status NativeProcessLinux::GetData(lldb::user_id_t traceid, lldb::tid_t thread,
2303 llvm::MutableArrayRef<uint8_t> &buffer,
2304 size_t offset) {
2305 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2306 Status error;
2307
2308 LLDB_LOG(log, "traceid {0}", traceid);
2309
2310 auto perf_monitor = LookupProcessorTraceInstance(traceid, thread);
2311 if (!perf_monitor) {
2312 LLDB_LOG(log, "traceid not being traced: {0}", traceid);
2313 buffer = buffer.slice(buffer.size());
2314 error = perf_monitor.takeError();
2315 return error;
2316 }
2317 return (*perf_monitor).ReadPerfTraceAux(buffer, offset);
2318}
2319
2320Status NativeProcessLinux::GetTraceConfig(lldb::user_id_t traceid,
2321 TraceOptions &config) {
2322 Status error;
2323 if (config.getThreadID() == LLDB_INVALID_THREAD_ID &&
2324 m_pt_proces_trace_id == traceid) {
2325 if (m_pt_proces_trace_id == LLDB_INVALID_UID) {
2326 error.SetErrorString("tracing not active for this process");
2327 return error;
2328 }
2329 config = m_pt_process_trace_config;
2330 } else {
2331 auto perf_monitor =
2332 LookupProcessorTraceInstance(traceid, config.getThreadID());
2333 if (!perf_monitor) {
2334 error = perf_monitor.takeError();
2335 return error;
2336 }
2337 error = (*perf_monitor).GetTraceConfig(config);
2338 }
2339 return error;
2340}
2341
2342lldb::user_id_t
2343NativeProcessLinux::StartTraceGroup(const TraceOptions &config,
2344 Status &error) {
2345
2346 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2347 if (config.getType() != TraceType::eTraceTypeProcessorTrace)
2348 return LLDB_INVALID_UID;
2349
2350 if (m_pt_proces_trace_id != LLDB_INVALID_UID) {
2351 error.SetErrorString("tracing already active on this process");
2352 return m_pt_proces_trace_id;
2353 }
2354
2355 for (const auto &thread_sp : m_threads) {
2356 if (auto traceInstance = ProcessorTraceMonitor::Create(
2357 GetID(), thread_sp->GetID(), config, true)) {
2358 m_pt_traced_thread_group.insert(thread_sp->GetID());
2359 m_processor_trace_monitor.insert(
2360 std::make_pair(thread_sp->GetID(), std::move(*traceInstance)));
2361 }
2362 }
2363
2364 m_pt_process_trace_config = config;
2365 error = ProcessorTraceMonitor::GetCPUType(m_pt_process_trace_config);
2366
2367 // Trace on Complete process will have traceid of 0
2368 m_pt_proces_trace_id = 0;
2369
2370 LLDB_LOG(log, "Process Trace ID {0}", m_pt_proces_trace_id);
2371 return m_pt_proces_trace_id;
2372}
2373
2374lldb::user_id_t NativeProcessLinux::StartTrace(const TraceOptions &config,
2375 Status &error) {
2376 if (config.getType() != TraceType::eTraceTypeProcessorTrace)
2377 return NativeProcessProtocol::StartTrace(config, error);
2378
2379 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2380
2381 lldb::tid_t threadid = config.getThreadID();
2382
2383 if (threadid == LLDB_INVALID_THREAD_ID)
2384 return StartTraceGroup(config, error);
2385
2386 auto thread_sp = GetThreadByID(threadid);
2387 if (!thread_sp) {
2388 // Thread not tracked by lldb so don't trace.
2389 error.SetErrorString("invalid thread id");
2390 return LLDB_INVALID_UID;
2391 }
2392
2393 const auto &iter = m_processor_trace_monitor.find(threadid);
2394 if (iter != m_processor_trace_monitor.end()) {
2395 LLDB_LOG(log, "Thread already being traced");
2396 error.SetErrorString("tracing already active on this thread");
2397 return LLDB_INVALID_UID;
2398 }
2399
2400 auto traceMonitor =
2401 ProcessorTraceMonitor::Create(GetID(), threadid, config, false);
2402 if (!traceMonitor) {
2403 error = traceMonitor.takeError();
2404 LLDB_LOG(log, "error {0}", error);
2405 return LLDB_INVALID_UID;
2406 }
2407 lldb::user_id_t ret_trace_id = (*traceMonitor)->GetTraceID();
2408 m_processor_trace_monitor.insert(
2409 std::make_pair(threadid, std::move(*traceMonitor)));
2410 return ret_trace_id;
2411}
2412
2413Status NativeProcessLinux::StopTracingForThread(lldb::tid_t thread) {
2414 Status error;
2415 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2416 LLDB_LOG(log, "Thread {0}", thread);
2417
2418 const auto& iter = m_processor_trace_monitor.find(thread);
2419 if (iter == m_processor_trace_monitor.end()) {
2420 error.SetErrorString("tracing not active for this thread");
2421 return error;
2422 }
2423
2424 if (iter->second->GetTraceID() == m_pt_proces_trace_id) {
2425 // traceid maps to the whole process so we have to erase it from the
2426 // thread group.
2427 LLDB_LOG(log, "traceid maps to process");
2428 m_pt_traced_thread_group.erase(thread);
2429 }
2430 m_processor_trace_monitor.erase(iter);
2431
2432 return error;
2433}
2434
2435Status NativeProcessLinux::StopTrace(lldb::user_id_t traceid,
2436 lldb::tid_t thread) {
2437 Status error;
2438
2439 TraceOptions trace_options;
2440 trace_options.setThreadID(thread);
2441 error = NativeProcessLinux::GetTraceConfig(traceid, trace_options);
2442
2443 if (error.Fail())
2444 return error;
2445
2446 switch (trace_options.getType()) {
2447 case lldb::TraceType::eTraceTypeProcessorTrace:
2448 if (traceid == m_pt_proces_trace_id &&
2449 thread == LLDB_INVALID_THREAD_ID)
2450 StopProcessorTracingOnProcess();
2451 else
2452 error = StopProcessorTracingOnThread(traceid, thread);
2453 break;
2454 default:
2455 error.SetErrorString("trace not supported");
2456 break;
2457 }
2458
2459 return error;
2460}
2461
2462void NativeProcessLinux::StopProcessorTracingOnProcess() {
2463 for (auto thread_id_iter : m_pt_traced_thread_group)
2464 m_processor_trace_monitor.erase(thread_id_iter);
2465 m_pt_traced_thread_group.clear();
2466 m_pt_proces_trace_id = LLDB_INVALID_UID;
2467}
2468
2469Status NativeProcessLinux::StopProcessorTracingOnThread(lldb::user_id_t traceid,
2470 lldb::tid_t thread) {
2471 Status error;
2472 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2473
2474 if (thread == LLDB_INVALID_THREAD_ID) {
2475 for (auto& iter : m_processor_trace_monitor) {
2476 if (iter.second->GetTraceID() == traceid) {
2477 // Stopping a trace instance for an individual thread
2478 // hence there will only be one traceid that can match.
2479 m_processor_trace_monitor.erase(iter.first);
2480 return error;
2481 }
2482 LLDB_LOG(log, "Trace ID {0}", iter.second->GetTraceID());
2483 }
2484
2485 LLDB_LOG(log, "Invalid TraceID");
2486 error.SetErrorString("invalid trace id");
2487 return error;
2488 }
2489
2490 // thread is specified so we can use find function on the map.
2491 const auto& iter = m_processor_trace_monitor.find(thread);
2492 if (iter == m_processor_trace_monitor.end()) {
2493 // thread not found in our map.
2494 LLDB_LOG(log, "thread not being traced");
2495 error.SetErrorString("tracing not active for this thread");
2496 return error;
2497 }
2498 if (iter->second->GetTraceID() != traceid) {
2499 // traceid did not match so it has to be invalid.
2500 LLDB_LOG(log, "Invalid TraceID");
2501 error.SetErrorString("invalid trace id");
2502 return error;
2503 }
2504
2505 LLDB_LOG(log, "UID - {0} , Thread -{1}", traceid, thread);
2506
2507 if (traceid == m_pt_proces_trace_id) {
2508 // traceid maps to the whole process so we have to erase it from the
2509 // thread group.
2510 LLDB_LOG(log, "traceid maps to process");
2511 m_pt_traced_thread_group.erase(thread);
2512 }
2513 m_processor_trace_monitor.erase(iter);
2514
2515 return error;
2516}