blob: 3f4842a760a9058eab70faee93e0b0bcd1cb9658 [file] [log] [blame]
Todd Fialaaf245d12014-06-30 21:05:18 +00001//===-- NativeProcessLinux.cpp -------------------------------- -*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Todd Fialaaf245d12014-06-30 21:05:18 +000010#include "NativeProcessLinux.h"
11
12// C Includes
13#include <errno.h>
Todd Fialaaf245d12014-06-30 21:05:18 +000014#include <stdint.h>
Kate Stoneb9c1b512016-09-06 20:57:50 +000015#include <string.h>
Todd Fialaaf245d12014-06-30 21:05:18 +000016#include <unistd.h>
Todd Fialaaf245d12014-06-30 21:05:18 +000017
18// C++ Includes
19#include <fstream>
Pavel Labathdf7c6992015-06-17 18:38:49 +000020#include <mutex>
Pavel Labathc0765592015-05-06 10:46:34 +000021#include <sstream>
Todd Fialaaf245d12014-06-30 21:05:18 +000022#include <string>
Pavel Labath5b981ab2015-05-29 12:53:54 +000023#include <unordered_map>
Todd Fialaaf245d12014-06-30 21:05:18 +000024
25// Other libraries and framework includes
Tamas Berghammerd8c338d2015-04-15 09:47:02 +000026#include "lldb/Core/EmulateInstruction.h"
Oleksiy Vyalov6edef202014-11-17 22:16:42 +000027#include "lldb/Core/ModuleSpec.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000028#include "lldb/Core/RegisterValue.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000029#include "lldb/Core/State.h"
30#include "lldb/Host/Host.h"
Pavel Labath5ad891f2016-07-21 14:54:03 +000031#include "lldb/Host/HostProcess.h"
Zachary Turner24ae6292017-02-16 19:38:21 +000032#include "lldb/Host/PseudoTerminal.h"
Zachary Turner39de3112014-09-09 20:54:56 +000033#include "lldb/Host/ThreadLauncher.h"
Pavel Labath2a86b552016-06-14 17:30:52 +000034#include "lldb/Host/common/NativeBreakpoint.h"
35#include "lldb/Host/common/NativeRegisterContext.h"
Pavel Labath4ee1c952017-02-06 18:36:58 +000036#include "lldb/Host/linux/Ptrace.h"
37#include "lldb/Host/linux/Uio.h"
Kamil Rytarowski816ae4b2017-02-01 14:30:40 +000038#include "lldb/Host/posix/ProcessLauncherPosixFork.h"
Pavel Labath2a86b552016-06-14 17:30:52 +000039#include "lldb/Symbol/ObjectFile.h"
Zachary Turner90aff472015-03-03 23:36:51 +000040#include "lldb/Target/Process.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000041#include "lldb/Target/ProcessLaunchInfo.h"
Pavel Labath5b981ab2015-05-29 12:53:54 +000042#include "lldb/Target/Target.h"
Chaoren Linc16f5dc2015-03-19 23:28:10 +000043#include "lldb/Utility/LLDBAssert.h"
Zachary Turner97206d52017-05-12 04:51:55 +000044#include "lldb/Utility/Status.h"
Pavel Labathf805e192015-07-07 10:08:41 +000045#include "lldb/Utility/StringExtractor.h"
Pavel Labath10c41f32017-06-06 14:06:17 +000046#include "llvm/Support/Errno.h"
47#include "llvm/Support/FileSystem.h"
48#include "llvm/Support/Threading.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000049
Todd Fialaaf245d12014-06-30 21:05:18 +000050#include "NativeThreadLinux.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000051#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000052#include "Procfs.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000053
Tamas Berghammerd8584872015-02-06 10:57:40 +000054#include <linux/unistd.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000055#include <sys/socket.h>
Pavel Labathdf7c6992015-06-17 18:38:49 +000056#include <sys/syscall.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000057#include <sys/types.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000058#include <sys/user.h>
59#include <sys/wait.h>
60
Todd Fialaaf245d12014-06-30 21:05:18 +000061// Support hardware breakpoints in case it has not been defined
62#ifndef TRAP_HWBKPT
Kate Stoneb9c1b512016-09-06 20:57:50 +000063#define TRAP_HWBKPT 4
Todd Fialaaf245d12014-06-30 21:05:18 +000064#endif
65
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000066using namespace lldb;
67using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000068using namespace lldb_private::process_linux;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000069using namespace llvm;
70
Todd Fialaaf245d12014-06-30 21:05:18 +000071// Private bits we only need internally.
Pavel Labathdf7c6992015-06-17 18:38:49 +000072
Kate Stoneb9c1b512016-09-06 20:57:50 +000073static bool ProcessVmReadvSupported() {
74 static bool is_supported;
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000075 static llvm::once_flag flag;
Pavel Labathdf7c6992015-06-17 18:38:49 +000076
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000077 llvm::call_once(flag, [] {
Pavel Labatha6321a82017-01-19 15:26:04 +000078 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Pavel Labath4abe5d62016-07-15 10:18:15 +000079
Kate Stoneb9c1b512016-09-06 20:57:50 +000080 uint32_t source = 0x47424742;
81 uint32_t dest = 0;
Pavel Labath4abe5d62016-07-15 10:18:15 +000082
Kate Stoneb9c1b512016-09-06 20:57:50 +000083 struct iovec local, remote;
84 remote.iov_base = &source;
85 local.iov_base = &dest;
86 remote.iov_len = local.iov_len = sizeof source;
Pavel Labath4abe5d62016-07-15 10:18:15 +000087
Kate Stoneb9c1b512016-09-06 20:57:50 +000088 // We shall try if cross-process-memory reads work by attempting to read a
89 // value from our own process.
90 ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
91 is_supported = (res == sizeof(source) && source == dest);
Pavel Labatha6321a82017-01-19 15:26:04 +000092 if (is_supported)
93 LLDB_LOG(log,
94 "Detected kernel support for process_vm_readv syscall. "
95 "Fast memory reads enabled.");
96 else
97 LLDB_LOG(log,
98 "syscall process_vm_readv failed (error: {0}). Fast memory "
99 "reads disabled.",
Pavel Labath10c41f32017-06-06 14:06:17 +0000100 llvm::sys::StrError());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000101 });
Pavel Labath4abe5d62016-07-15 10:18:15 +0000102
Kate Stoneb9c1b512016-09-06 20:57:50 +0000103 return is_supported;
Pavel Labath4abe5d62016-07-15 10:18:15 +0000104}
105
Kate Stoneb9c1b512016-09-06 20:57:50 +0000106namespace {
107void MaybeLogLaunchInfo(const ProcessLaunchInfo &info) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000108 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000109 if (!log)
110 return;
111
112 if (const FileAction *action = info.GetFileActionForFD(STDIN_FILENO))
Pavel Labatha6321a82017-01-19 15:26:04 +0000113 LLDB_LOG(log, "setting STDIN to '{0}'", action->GetFileSpec());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000114 else
Pavel Labatha6321a82017-01-19 15:26:04 +0000115 LLDB_LOG(log, "leaving STDIN as is");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000116
117 if (const FileAction *action = info.GetFileActionForFD(STDOUT_FILENO))
Pavel Labatha6321a82017-01-19 15:26:04 +0000118 LLDB_LOG(log, "setting STDOUT to '{0}'", action->GetFileSpec());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000119 else
Pavel Labatha6321a82017-01-19 15:26:04 +0000120 LLDB_LOG(log, "leaving STDOUT as is");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000121
122 if (const FileAction *action = info.GetFileActionForFD(STDERR_FILENO))
Pavel Labatha6321a82017-01-19 15:26:04 +0000123 LLDB_LOG(log, "setting STDERR to '{0}'", action->GetFileSpec());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000124 else
Pavel Labatha6321a82017-01-19 15:26:04 +0000125 LLDB_LOG(log, "leaving STDERR as is");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000126
127 int i = 0;
128 for (const char **args = info.GetArguments().GetConstArgumentVector(); *args;
129 ++args, ++i)
Pavel Labatha6321a82017-01-19 15:26:04 +0000130 LLDB_LOG(log, "arg {0}: '{1}'", i, *args);
Pavel Labath4abe5d62016-07-15 10:18:15 +0000131}
Todd Fialaaf245d12014-06-30 21:05:18 +0000132
Kate Stoneb9c1b512016-09-06 20:57:50 +0000133void DisplayBytes(StreamString &s, void *bytes, uint32_t count) {
134 uint8_t *ptr = (uint8_t *)bytes;
135 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
136 for (uint32_t i = 0; i < loop_count; i++) {
137 s.Printf("[%x]", *ptr);
138 ptr++;
139 }
140}
Todd Fialaaf245d12014-06-30 21:05:18 +0000141
Kate Stoneb9c1b512016-09-06 20:57:50 +0000142void PtraceDisplayBytes(int &req, void *data, size_t data_size) {
Pavel Labathaafe0532017-02-06 19:31:05 +0000143 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
Pavel Labatha6321a82017-01-19 15:26:04 +0000144 if (!log)
145 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000146 StreamString buf;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000147
Pavel Labatha6321a82017-01-19 15:26:04 +0000148 switch (req) {
149 case PTRACE_POKETEXT: {
150 DisplayBytes(buf, &data, 8);
Pavel Labathaafe0532017-02-06 19:31:05 +0000151 LLDB_LOGV(log, "PTRACE_POKETEXT {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000152 break;
153 }
154 case PTRACE_POKEDATA: {
155 DisplayBytes(buf, &data, 8);
Pavel Labathaafe0532017-02-06 19:31:05 +0000156 LLDB_LOGV(log, "PTRACE_POKEDATA {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000157 break;
158 }
159 case PTRACE_POKEUSER: {
160 DisplayBytes(buf, &data, 8);
Pavel Labathaafe0532017-02-06 19:31:05 +0000161 LLDB_LOGV(log, "PTRACE_POKEUSER {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000162 break;
163 }
164 case PTRACE_SETREGS: {
165 DisplayBytes(buf, data, data_size);
Pavel Labathaafe0532017-02-06 19:31:05 +0000166 LLDB_LOGV(log, "PTRACE_SETREGS {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000167 break;
168 }
169 case PTRACE_SETFPREGS: {
170 DisplayBytes(buf, data, data_size);
Pavel Labathaafe0532017-02-06 19:31:05 +0000171 LLDB_LOGV(log, "PTRACE_SETFPREGS {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000172 break;
173 }
174 case PTRACE_SETSIGINFO: {
175 DisplayBytes(buf, data, sizeof(siginfo_t));
Pavel Labathaafe0532017-02-06 19:31:05 +0000176 LLDB_LOGV(log, "PTRACE_SETSIGINFO {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000177 break;
178 }
179 case PTRACE_SETREGSET: {
180 // Extract iov_base from data, which is a pointer to the struct IOVEC
181 DisplayBytes(buf, *(void **)data, data_size);
Pavel Labathaafe0532017-02-06 19:31:05 +0000182 LLDB_LOGV(log, "PTRACE_SETREGSET {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000183 break;
184 }
185 default: {}
Kate Stoneb9c1b512016-09-06 20:57:50 +0000186 }
187}
Todd Fialaaf245d12014-06-30 21:05:18 +0000188
Kate Stoneb9c1b512016-09-06 20:57:50 +0000189static constexpr unsigned k_ptrace_word_size = sizeof(void *);
190static_assert(sizeof(long) >= k_ptrace_word_size,
191 "Size of long must be larger than ptrace word size");
Pavel Labath1107b5a2015-04-17 14:07:49 +0000192} // end of anonymous namespace
193
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000194// Simple helper function to ensure flags are enabled on the given file
195// descriptor.
Zachary Turner97206d52017-05-12 04:51:55 +0000196static Status EnsureFDFlags(int fd, int flags) {
197 Status error;
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000198
Kate Stoneb9c1b512016-09-06 20:57:50 +0000199 int status = fcntl(fd, F_GETFL);
200 if (status == -1) {
201 error.SetErrorToErrno();
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000202 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000203 }
204
205 if (fcntl(fd, F_SETFL, status | flags) == -1) {
206 error.SetErrorToErrno();
207 return error;
208 }
209
210 return error;
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000211}
212
Todd Fialaaf245d12014-06-30 21:05:18 +0000213// -----------------------------------------------------------------------------
214// Public Static Methods
215// -----------------------------------------------------------------------------
216
Pavel Labath82abefa2017-07-18 09:24:48 +0000217llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
Pavel Labath96e600f2017-07-07 11:02:19 +0000218NativeProcessLinux::Factory::Launch(ProcessLaunchInfo &launch_info,
219 NativeDelegate &native_delegate,
220 MainLoop &mainloop) const {
Pavel Labatha6321a82017-01-19 15:26:04 +0000221 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Todd Fialaaf245d12014-06-30 21:05:18 +0000222
Pavel Labath96e600f2017-07-07 11:02:19 +0000223 MaybeLogLaunchInfo(launch_info);
Todd Fialaaf245d12014-06-30 21:05:18 +0000224
Pavel Labath96e600f2017-07-07 11:02:19 +0000225 Status status;
226 ::pid_t pid = ProcessLauncherPosixFork()
227 .LaunchProcess(launch_info, status)
228 .GetProcessId();
229 LLDB_LOG(log, "pid = {0:x}", pid);
230 if (status.Fail()) {
231 LLDB_LOG(log, "failed to launch process: {0}", status);
232 return status.ToError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000233 }
234
Pavel Labath96e600f2017-07-07 11:02:19 +0000235 // Wait for the child process to trap on its call to execve.
236 int wstatus;
237 ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0);
238 assert(wpid == pid);
239 (void)wpid;
240 if (!WIFSTOPPED(wstatus)) {
241 LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}",
242 WaitStatus::Decode(wstatus));
243 return llvm::make_error<StringError>("Could not sync with inferior process",
244 llvm::inconvertibleErrorCode());
245 }
246 LLDB_LOG(log, "inferior started, now in stopped state");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000247
Pavel Labath96e600f2017-07-07 11:02:19 +0000248 ArchSpec arch;
249 if ((status = ResolveProcessArchitecture(pid, arch)).Fail())
250 return status.ToError();
251
252 // Set the architecture to the exe architecture.
253 LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid,
254 arch.GetArchitectureName());
255
256 status = SetDefaultPtraceOpts(pid);
257 if (status.Fail()) {
258 LLDB_LOG(log, "failed to set default ptrace options: {0}", status);
259 return status.ToError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000260 }
261
Pavel Labath82abefa2017-07-18 09:24:48 +0000262 return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
Pavel Labath96e600f2017-07-07 11:02:19 +0000263 pid, launch_info.GetPTY().ReleaseMasterFileDescriptor(), native_delegate,
Pavel Labath82abefa2017-07-18 09:24:48 +0000264 arch, mainloop, {pid}));
Todd Fialaaf245d12014-06-30 21:05:18 +0000265}
266
Pavel Labath82abefa2017-07-18 09:24:48 +0000267llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
268NativeProcessLinux::Factory::Attach(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000269 lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
Pavel Labath96e600f2017-07-07 11:02:19 +0000270 MainLoop &mainloop) const {
Pavel Labatha6321a82017-01-19 15:26:04 +0000271 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
272 LLDB_LOG(log, "pid = {0:x}", pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000273
Kate Stoneb9c1b512016-09-06 20:57:50 +0000274 // Retrieve the architecture for the running process.
Pavel Labath96e600f2017-07-07 11:02:19 +0000275 ArchSpec arch;
276 Status status = ResolveProcessArchitecture(pid, arch);
277 if (!status.Success())
278 return status.ToError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000279
Pavel Labath96e600f2017-07-07 11:02:19 +0000280 auto tids_or = NativeProcessLinux::Attach(pid);
281 if (!tids_or)
282 return tids_or.takeError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000283
Pavel Labath82abefa2017-07-18 09:24:48 +0000284 return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
285 pid, -1, native_delegate, arch, mainloop, *tids_or));
Todd Fialaaf245d12014-06-30 21:05:18 +0000286}
287
288// -----------------------------------------------------------------------------
289// Public Instance Methods
290// -----------------------------------------------------------------------------
291
Pavel Labath96e600f2017-07-07 11:02:19 +0000292NativeProcessLinux::NativeProcessLinux(::pid_t pid, int terminal_fd,
293 NativeDelegate &delegate,
Pavel Labath82abefa2017-07-18 09:24:48 +0000294 const ArchSpec &arch, MainLoop &mainloop,
295 llvm::ArrayRef<::pid_t> tids)
Pavel Labath96e600f2017-07-07 11:02:19 +0000296 : NativeProcessProtocol(pid, terminal_fd, delegate), m_arch(arch) {
297 if (m_terminal_fd != -1) {
298 Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
299 assert(status.Success());
300 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000301
Pavel Labath96e600f2017-07-07 11:02:19 +0000302 Status status;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000303 m_sigchld_handle = mainloop.RegisterSignal(
Pavel Labath96e600f2017-07-07 11:02:19 +0000304 SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status);
305 assert(m_sigchld_handle && status.Success());
Todd Fialaaf245d12014-06-30 21:05:18 +0000306
Pavel Labath96e600f2017-07-07 11:02:19 +0000307 for (const auto &tid : tids) {
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 Labatha6321a82017-01-19 15:26:04 +0000415 LLDB_LOG(log, "got exit signal({0}) , tid = {1} ({2} main thread)", signal,
416 pid, is_main_thread ? "is" : "is not");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000417
418 // This is a thread that exited. Ensure we're not tracking it anymore.
419 const bool thread_found = StopTrackingThread(pid);
420
421 if (is_main_thread) {
422 // We only set the exit status and notify the delegate if we haven't
423 // already set the process
424 // state to an exited state. We normally should have received a SIGTRAP |
425 // (PTRACE_EVENT_EXIT << 8)
426 // for the main thread.
427 const bool already_notified = (GetState() == StateType::eStateExited) ||
428 (GetState() == StateType::eStateCrashed);
429 if (!already_notified) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000430 LLDB_LOG(
431 log,
432 "tid = {0} handling main thread exit ({1}), expected exit state "
433 "already set but state was {2} instead, setting exit state now",
434 pid,
435 thread_found ? "stopped tracking thread metadata"
436 : "thread metadata not found",
Pavel Labath8198db32017-01-24 11:48:25 +0000437 GetState());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000438 // The main thread exited. We're done monitoring. Report to delegate.
Pavel Labath3508fc82017-06-19 12:47:50 +0000439 SetExitStatus(status, true);
Todd Fialaaf245d12014-06-30 21:05:18 +0000440
Kate Stoneb9c1b512016-09-06 20:57:50 +0000441 // Notify delegate that our process has exited.
442 SetState(StateType::eStateExited, true);
Pavel Labatha6321a82017-01-19 15:26:04 +0000443 } else
444 LLDB_LOG(log, "tid = {0} main thread now exited (%s)", pid,
445 thread_found ? "stopped tracking thread metadata"
446 : "thread metadata not found");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000447 } else {
448 // Do we want to report to the delegate in this case? I think not. If
Pavel Labatha6321a82017-01-19 15:26:04 +0000449 // this was an orderly thread exit, we would already have received the
450 // SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal, and we would have done an
451 // all-stop then.
452 LLDB_LOG(log, "tid = {0} handling non-main thread exit (%s)", pid,
453 thread_found ? "stopped tracking thread metadata"
454 : "thread metadata not found");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000455 }
456 return;
457 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000458
Kate Stoneb9c1b512016-09-06 20:57:50 +0000459 siginfo_t info;
460 const auto info_err = GetSignalInfo(pid, &info);
461 auto thread_sp = GetThreadByID(pid);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000462
Kate Stoneb9c1b512016-09-06 20:57:50 +0000463 if (!thread_sp) {
464 // Normally, the only situation when we cannot find the thread is if we have
Pavel Labatha6321a82017-01-19 15:26:04 +0000465 // just received a new thread notification. This is indicated by
466 // GetSignalInfo() returning si_code == SI_USER and si_pid == 0
467 LLDB_LOG(log, "received notification about an unknown tid {0}.", pid);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000468
Kate Stoneb9c1b512016-09-06 20:57:50 +0000469 if (info_err.Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000470 LLDB_LOG(log,
471 "(tid {0}) GetSignalInfo failed ({1}). "
472 "Ingoring this notification.",
473 pid, info_err);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000474 return;
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000475 }
476
Pavel Labatha6321a82017-01-19 15:26:04 +0000477 LLDB_LOG(log, "tid {0}, si_code: {1}, si_pid: {2}", pid, info.si_code,
478 info.si_pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000479
Pavel Labatha5be48b2017-10-17 15:52:16 +0000480 NativeThreadLinux &thread = AddThread(pid);
Ravitheja Addepally99e37692017-06-28 07:58:31 +0000481
Kate Stoneb9c1b512016-09-06 20:57:50 +0000482 // Resume the newly created thread.
Pavel Labatha5be48b2017-10-17 15:52:16 +0000483 ResumeThread(thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
484 ThreadWasCreated(thread);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000485 return;
486 }
487
488 // Get details on the signal raised.
489 if (info_err.Success()) {
490 // We have retrieved the signal info. Dispatch appropriately.
491 if (info.si_signo == SIGTRAP)
492 MonitorSIGTRAP(info, *thread_sp);
Chaoren Linfa03ad22015-02-03 01:50:42 +0000493 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000494 MonitorSignal(info, *thread_sp, exited);
495 } else {
496 if (info_err.GetError() == EINVAL) {
497 // This is a group stop reception for this tid.
498 // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU
Pavel Labatha6321a82017-01-19 15:26:04 +0000499 // into the tracee, triggering the group-stop mechanism. Normally
500 // receiving these would stop the process, pending a SIGCONT. Simulating
501 // this state in a debugger is hard and is generally not needed (one use
502 // case is debugging background task being managed by a shell). For
503 // general use, it is sufficient to stop the process in a signal-delivery
Kate Stoneb9c1b512016-09-06 20:57:50 +0000504 // stop which happens before the group stop. This done by MonitorSignal
Pavel Labatha6321a82017-01-19 15:26:04 +0000505 // and works correctly for all signals.
506 LLDB_LOG(log,
507 "received a group stop for pid {0} tid {1}. Transparent "
508 "handling of group stops not supported, resuming the "
509 "thread.",
510 GetID(), pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000511 ResumeThread(*thread_sp, thread_sp->GetState(),
512 LLDB_INVALID_SIGNAL_NUMBER);
513 } else {
514 // ptrace(GETSIGINFO) failed (but not due to group-stop).
Todd Fialaaf245d12014-06-30 21:05:18 +0000515
Kate Stoneb9c1b512016-09-06 20:57:50 +0000516 // A return value of ESRCH means the thread/process is no longer on the
Pavel Labatha6321a82017-01-19 15:26:04 +0000517 // system, so it was killed somehow outside of our control. Either way,
518 // we can't do anything with it anymore.
Todd Fialaaf245d12014-06-30 21:05:18 +0000519
Kate Stoneb9c1b512016-09-06 20:57:50 +0000520 // Stop tracking the metadata for the thread since it's entirely off the
521 // system now.
522 const bool thread_found = StopTrackingThread(pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000523
Pavel Labatha6321a82017-01-19 15:26:04 +0000524 LLDB_LOG(log,
525 "GetSignalInfo failed: {0}, tid = {1}, signal = {2}, "
526 "status = {3}, main_thread = {4}, thread_found: {5}",
527 info_err, pid, signal, status, is_main_thread, thread_found);
Todd Fialaaf245d12014-06-30 21:05:18 +0000528
Kate Stoneb9c1b512016-09-06 20:57:50 +0000529 if (is_main_thread) {
530 // Notify the delegate - our process is not available but appears to
531 // have been killed outside
532 // our control. Is eStateExited the right exit state in this case?
Pavel Labath3508fc82017-06-19 12:47:50 +0000533 SetExitStatus(status, true);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000534 SetState(StateType::eStateExited, true);
535 } else {
536 // This thread was pulled out from underneath us. Anything to do here?
537 // Do we want to do an all stop?
Pavel Labatha6321a82017-01-19 15:26:04 +0000538 LLDB_LOG(log,
539 "pid {0} tid {1} non-main thread exit occurred, didn't "
540 "tell delegate anything since thread disappeared out "
541 "from underneath us",
542 GetID(), pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000543 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000544 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000545 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000546}
547
Kate Stoneb9c1b512016-09-06 20:57:50 +0000548void NativeProcessLinux::WaitForNewThread(::pid_t tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000549 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Pavel Labath426bdf82015-04-28 07:51:52 +0000550
Pavel Labatha5be48b2017-10-17 15:52:16 +0000551 if (GetThreadByID(tid)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000552 // We are already tracking the thread - we got the event on the new thread
Pavel Labatha5be48b2017-10-17 15:52:16 +0000553 // (see MonitorSignal) before this one. We are done.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000554 return;
555 }
Pavel Labath426bdf82015-04-28 07:51:52 +0000556
Kate Stoneb9c1b512016-09-06 20:57:50 +0000557 // The thread is not tracked yet, let's wait for it to appear.
558 int status = -1;
Pavel Labathc1a6b122017-07-03 09:25:55 +0000559 LLDB_LOG(log,
560 "received thread creation event for tid {0}. tid not tracked "
561 "yet, waiting for thread to appear...",
562 tid);
563 ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, &status, __WALL);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000564 // Since we are waiting on a specific tid, this must be the creation event.
Pavel Labatha6321a82017-01-19 15:26:04 +0000565 // But let's do some checks just in case.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000566 if (wait_pid != tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000567 LLDB_LOG(log,
568 "waiting for tid {0} failed. Assuming the thread has "
569 "disappeared in the meantime",
570 tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000571 // The only way I know of this could happen is if the whole process was
572 // SIGKILLed in the mean time. In any case, we can't do anything about that
573 // now.
574 return;
575 }
576 if (WIFEXITED(status)) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000577 LLDB_LOG(log,
578 "waiting for tid {0} returned an 'exited' event. Not "
579 "tracking the thread.",
580 tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000581 // Also a very improbable event.
582 return;
583 }
Pavel Labath426bdf82015-04-28 07:51:52 +0000584
Pavel Labatha6321a82017-01-19 15:26:04 +0000585 LLDB_LOG(log, "pid = {0}: tracking new thread tid {1}", GetID(), tid);
Pavel Labatha5be48b2017-10-17 15:52:16 +0000586 NativeThreadLinux &new_thread = AddThread(tid);
Ravitheja Addepally99e37692017-06-28 07:58:31 +0000587
Pavel Labatha5be48b2017-10-17 15:52:16 +0000588 ResumeThread(new_thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
589 ThreadWasCreated(new_thread);
Pavel Labath426bdf82015-04-28 07:51:52 +0000590}
591
Kate Stoneb9c1b512016-09-06 20:57:50 +0000592void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info,
593 NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000594 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000595 const bool is_main_thread = (thread.GetID() == GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000596
Kate Stoneb9c1b512016-09-06 20:57:50 +0000597 assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
Todd Fialaaf245d12014-06-30 21:05:18 +0000598
Kate Stoneb9c1b512016-09-06 20:57:50 +0000599 switch (info.si_code) {
600 // TODO: these two cases are required if we want to support tracing of the
601 // inferiors' children. We'd need this to debug a monitor.
602 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
603 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
Todd Fialaaf245d12014-06-30 21:05:18 +0000604
Kate Stoneb9c1b512016-09-06 20:57:50 +0000605 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): {
606 // This is the notification on the parent thread which informs us of new
607 // thread
608 // creation.
609 // We don't want to do anything with the parent thread so we just resume it.
610 // In case we
611 // want to implement "break on thread creation" functionality, we would need
612 // to stop
613 // here.
Todd Fialaaf245d12014-06-30 21:05:18 +0000614
Kate Stoneb9c1b512016-09-06 20:57:50 +0000615 unsigned long event_message = 0;
616 if (GetEventMessage(thread.GetID(), &event_message).Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000617 LLDB_LOG(log,
618 "pid {0} received thread creation event but "
619 "GetEventMessage failed so we don't know the new tid",
620 thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000621 } else
622 WaitForNewThread(event_message);
Todd Fialaaf245d12014-06-30 21:05:18 +0000623
Kate Stoneb9c1b512016-09-06 20:57:50 +0000624 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
625 break;
626 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000627
Kate Stoneb9c1b512016-09-06 20:57:50 +0000628 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): {
Pavel Labatha6321a82017-01-19 15:26:04 +0000629 LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000630
631 // Exec clears any pending notifications.
632 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
633
634 // Remove all but the main thread here. Linux fork creates a new process
635 // which only copies the main thread.
Pavel Labatha6321a82017-01-19 15:26:04 +0000636 LLDB_LOG(log, "exec received, stop tracking all but main thread");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000637
Pavel Labatha5be48b2017-10-17 15:52:16 +0000638 for (auto i = m_threads.begin(); i != m_threads.end();) {
639 if ((*i)->GetID() == GetID())
640 i = m_threads.erase(i);
641 else
642 ++i;
Todd Fialaa9882ce2014-08-28 15:46:54 +0000643 }
Pavel Labatha5be48b2017-10-17 15:52:16 +0000644 assert(m_threads.size() == 1);
645 auto *main_thread = static_cast<NativeThreadLinux *>(m_threads[0].get());
Todd Fialaaf245d12014-06-30 21:05:18 +0000646
Pavel Labatha5be48b2017-10-17 15:52:16 +0000647 SetCurrentThreadID(main_thread->GetID());
648 main_thread->SetStoppedByExec();
Todd Fialaaf245d12014-06-30 21:05:18 +0000649
Kate Stoneb9c1b512016-09-06 20:57:50 +0000650 // Tell coordinator about about the "new" (since exec) stopped main thread.
Pavel Labatha5be48b2017-10-17 15:52:16 +0000651 ThreadWasCreated(*main_thread);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000652
Kate Stoneb9c1b512016-09-06 20:57:50 +0000653 // Let our delegate know we have just exec'd.
654 NotifyDidExec();
655
Kate Stoneb9c1b512016-09-06 20:57:50 +0000656 // Let the process know we're stopped.
Pavel Labatha5be48b2017-10-17 15:52:16 +0000657 StopRunningThreads(main_thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000658
659 break;
660 }
661
662 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): {
663 // The inferior process or one of its threads is about to exit.
664 // We don't want to do anything with the thread so we just resume it. In
665 // case we
666 // want to implement "break on thread exit" functionality, we would need to
667 // stop
668 // here.
669
670 unsigned long data = 0;
671 if (GetEventMessage(thread.GetID(), &data).Fail())
672 data = -1;
673
Pavel Labatha6321a82017-01-19 15:26:04 +0000674 LLDB_LOG(log,
675 "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
676 "WIFSIGNALED={2}, pid = {3}, main_thread = {4}",
677 data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(),
678 is_main_thread);
Todd Fialaaf245d12014-06-30 21:05:18 +0000679
Pavel Labath3508fc82017-06-19 12:47:50 +0000680 if (is_main_thread)
681 SetExitStatus(WaitStatus::Decode(data), true);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000682
683 StateType state = thread.GetState();
684 if (!StateIsRunningState(state)) {
685 // Due to a kernel bug, we may sometimes get this stop after the inferior
686 // gets a
687 // SIGKILL. This confuses our state tracking logic in ResumeThread(),
688 // since normally,
689 // we should not be receiving any ptrace events while the inferior is
690 // stopped. This
691 // makes sure that the inferior is resumed and exits normally.
692 state = eStateRunning;
693 }
694 ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
695
696 break;
697 }
698
699 case 0:
700 case TRAP_TRACE: // We receive this on single stepping.
701 case TRAP_HWBKPT: // We receive this on watchpoint hit
702 {
703 // If a watchpoint was hit, report it
704 uint32_t wp_index;
Zachary Turner97206d52017-05-12 04:51:55 +0000705 Status error = thread.GetRegisterContext()->GetWatchpointHitIndex(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000706 wp_index, (uintptr_t)info.si_addr);
Pavel Labatha6321a82017-01-19 15:26:04 +0000707 if (error.Fail())
708 LLDB_LOG(log,
709 "received error while checking for watchpoint hits, pid = "
710 "{0}, error = {1}",
711 thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000712 if (wp_index != LLDB_INVALID_INDEX32) {
713 MonitorWatchpoint(thread, wp_index);
714 break;
715 }
716
Omair Javaidd5ffbad2017-02-24 13:27:31 +0000717 // If a breakpoint was hit, report it
718 uint32_t bp_index;
719 error = thread.GetRegisterContext()->GetHardwareBreakHitIndex(
720 bp_index, (uintptr_t)info.si_addr);
721 if (error.Fail())
722 LLDB_LOG(log, "received error while checking for hardware "
723 "breakpoint hits, pid = {0}, error = {1}",
724 thread.GetID(), error);
725 if (bp_index != LLDB_INVALID_INDEX32) {
726 MonitorBreakpoint(thread);
727 break;
728 }
729
Kate Stoneb9c1b512016-09-06 20:57:50 +0000730 // Otherwise, report step over
731 MonitorTrace(thread);
732 break;
733 }
734
735 case SI_KERNEL:
Mohit K. Bhakkad35799962015-06-18 04:53:18 +0000736#if defined __mips__
Kate Stoneb9c1b512016-09-06 20:57:50 +0000737 // For mips there is no special signal for watchpoint
738 // So we check for watchpoint in kernel trap
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000739 {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000740 // If a watchpoint was hit, report it
741 uint32_t wp_index;
Zachary Turner97206d52017-05-12 04:51:55 +0000742 Status error = thread.GetRegisterContext()->GetWatchpointHitIndex(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000743 wp_index, LLDB_INVALID_ADDRESS);
Pavel Labatha6321a82017-01-19 15:26:04 +0000744 if (error.Fail())
745 LLDB_LOG(log,
746 "received error while checking for watchpoint hits, pid = "
747 "{0}, error = {1}",
748 thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000749 if (wp_index != LLDB_INVALID_INDEX32) {
750 MonitorWatchpoint(thread, wp_index);
751 break;
752 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000753 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000754// NO BREAK
Mohit K. Bhakkad35799962015-06-18 04:53:18 +0000755#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000756 case TRAP_BRKPT:
757 MonitorBreakpoint(thread);
758 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000759
Kate Stoneb9c1b512016-09-06 20:57:50 +0000760 case SIGTRAP:
761 case (SIGTRAP | 0x80):
Pavel Labatha6321a82017-01-19 15:26:04 +0000762 LLDB_LOG(
763 log,
764 "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",
765 info.si_code, GetID(), thread.GetID());
Chaoren Linfa03ad22015-02-03 01:50:42 +0000766
Kate Stoneb9c1b512016-09-06 20:57:50 +0000767 // Ignore these signals until we know more about them.
768 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
769 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000770
Kate Stoneb9c1b512016-09-06 20:57:50 +0000771 default:
Pavel Labath21a365b2017-07-11 10:38:40 +0000772 LLDB_LOG(log, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}",
773 info.si_code, GetID(), thread.GetID());
774 MonitorSignal(info, thread, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000775 break;
776 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000777}
778
Kate Stoneb9c1b512016-09-06 20:57:50 +0000779void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000780 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
781 LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000782
Kate Stoneb9c1b512016-09-06 20:57:50 +0000783 // This thread is currently stopped.
784 thread.SetStoppedByTrace();
785
786 StopRunningThreads(thread.GetID());
787}
788
789void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) {
790 Log *log(
791 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
Pavel Labatha6321a82017-01-19 15:26:04 +0000792 LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000793
794 // Mark the thread as stopped at breakpoint.
795 thread.SetStoppedByBreakpoint();
Zachary Turner97206d52017-05-12 04:51:55 +0000796 Status error = FixupBreakpointPCAsNeeded(thread);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000797 if (error.Fail())
Pavel Labatha6321a82017-01-19 15:26:04 +0000798 LLDB_LOG(log, "pid = {0} fixup: {1}", thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000799
800 if (m_threads_stepping_with_breakpoint.find(thread.GetID()) !=
801 m_threads_stepping_with_breakpoint.end())
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000802 thread.SetStoppedByTrace();
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000803
Kate Stoneb9c1b512016-09-06 20:57:50 +0000804 StopRunningThreads(thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000805}
806
Kate Stoneb9c1b512016-09-06 20:57:50 +0000807void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread,
808 uint32_t wp_index) {
809 Log *log(
810 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
Pavel Labatha6321a82017-01-19 15:26:04 +0000811 LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}",
812 thread.GetID(), wp_index);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000813
814 // Mark the thread as stopped at watchpoint.
815 // The address is at (lldb::addr_t)info->si_addr if we need it.
816 thread.SetStoppedByWatchpoint(wp_index);
817
818 // We need to tell all other running threads before we notify the delegate
819 // about this stop.
820 StopRunningThreads(thread.GetID());
821}
822
823void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
824 NativeThreadLinux &thread, bool exited) {
825 const int signo = info.si_signo;
826 const bool is_from_llgs = info.si_pid == getpid();
827
Pavel Labatha6321a82017-01-19 15:26:04 +0000828 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000829
830 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
831 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
832 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
833 //
834 // IOW, user generated signals never generate what we consider to be a
835 // "crash".
836 //
837 // Similarly, ACK signals generated by this monitor.
838
839 // Handle the signal.
Pavel Labatha6321a82017-01-19 15:26:04 +0000840 LLDB_LOG(log,
841 "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
842 "waitpid pid = {4})",
843 Host::GetSignalAsCString(signo), signo, info.si_code,
844 thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000845
Kate Stoneb9c1b512016-09-06 20:57:50 +0000846 // Check for thread stop notification.
847 if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) {
848 // This is a tgkill()-based stop.
Pavel Labatha6321a82017-01-19 15:26:04 +0000849 LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000850
Kate Stoneb9c1b512016-09-06 20:57:50 +0000851 // Check that we're not already marked with a stop reason.
852 // Note this thread really shouldn't already be marked as stopped - if we
Pavel Labatha6321a82017-01-19 15:26:04 +0000853 // were, that would imply that the kernel signaled us with the thread
854 // stopping which we handled and marked as stopped, and that, without an
855 // intervening resume, we received another stop. It is more likely that we
856 // are missing the marking of a run state somewhere if we find that the
857 // thread was marked as stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000858 const StateType thread_state = thread.GetState();
859 if (!StateIsStoppedState(thread_state, false)) {
860 // An inferior thread has stopped because of a SIGSTOP we have sent it.
861 // Generally, these are not important stops and we don't want to report
Pavel Labatha6321a82017-01-19 15:26:04 +0000862 // them as they are just used to stop other threads when one thread (the
863 // one with the *real* stop reason) hits a breakpoint (watchpoint,
864 // etc...). However, in the case of an asynchronous Interrupt(), this *is*
865 // the real stop reason, so we leave the signal intact if this is the
866 // thread that was chosen as the triggering thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000867 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
868 if (m_pending_notification_tid == thread.GetID())
869 thread.SetStoppedBySignal(SIGSTOP, &info);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000870 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000871 thread.SetStoppedWithNoReason();
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000872
Kate Stoneb9c1b512016-09-06 20:57:50 +0000873 SetCurrentThreadID(thread.GetID());
874 SignalIfAllThreadsStopped();
875 } else {
876 // We can end up here if stop was initiated by LLGS but by this time a
877 // thread stop has occurred - maybe initiated by another event.
Zachary Turner97206d52017-05-12 04:51:55 +0000878 Status error = ResumeThread(thread, thread.GetState(), 0);
Pavel Labatha6321a82017-01-19 15:26:04 +0000879 if (error.Fail())
880 LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(),
881 error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000882 }
883 } else {
Pavel Labatha6321a82017-01-19 15:26:04 +0000884 LLDB_LOG(log,
885 "pid {0} tid {1}, thread was already marked as a stopped "
886 "state (state={2}), leaving stop signal as is",
Pavel Labath8198db32017-01-24 11:48:25 +0000887 GetID(), thread.GetID(), thread_state);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000888 SignalIfAllThreadsStopped();
Todd Fialaaf245d12014-06-30 21:05:18 +0000889 }
890
Kate Stoneb9c1b512016-09-06 20:57:50 +0000891 // Done handling.
892 return;
893 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000894
Pavel Labath4a705e72017-02-24 09:29:14 +0000895 // Check if debugger should stop at this signal or just ignore it
896 // and resume the inferior.
897 if (m_signals_to_ignore.find(signo) != m_signals_to_ignore.end()) {
898 ResumeThread(thread, thread.GetState(), signo);
899 return;
900 }
901
Kate Stoneb9c1b512016-09-06 20:57:50 +0000902 // This thread is stopped.
Pavel Labatha6321a82017-01-19 15:26:04 +0000903 LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000904 thread.SetStoppedBySignal(signo, &info);
905
906 // Send a stop to the debugger after we get all other threads to stop.
907 StopRunningThreads(thread.GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000908}
909
Tamas Berghammere7708682015-04-22 10:00:23 +0000910namespace {
911
Kate Stoneb9c1b512016-09-06 20:57:50 +0000912struct EmulatorBaton {
913 NativeProcessLinux *m_process;
914 NativeRegisterContext *m_reg_context;
Tamas Berghammere7708682015-04-22 10:00:23 +0000915
Kate Stoneb9c1b512016-09-06 20:57:50 +0000916 // eRegisterKindDWARF -> RegsiterValue
917 std::unordered_map<uint32_t, RegisterValue> m_register_values;
Pavel Labath6648fcc2015-04-27 09:21:14 +0000918
Kate Stoneb9c1b512016-09-06 20:57:50 +0000919 EmulatorBaton(NativeProcessLinux *process, NativeRegisterContext *reg_context)
920 : m_process(process), m_reg_context(reg_context) {}
Tamas Berghammere7708682015-04-22 10:00:23 +0000921};
922
923} // anonymous namespace
924
Kate Stoneb9c1b512016-09-06 20:57:50 +0000925static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
926 const EmulateInstruction::Context &context,
927 lldb::addr_t addr, void *dst, size_t length) {
928 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
Tamas Berghammere7708682015-04-22 10:00:23 +0000929
Kate Stoneb9c1b512016-09-06 20:57:50 +0000930 size_t bytes_read;
931 emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
932 return bytes_read;
Tamas Berghammere7708682015-04-22 10:00:23 +0000933}
934
Kate Stoneb9c1b512016-09-06 20:57:50 +0000935static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
936 const RegisterInfo *reg_info,
937 RegisterValue &reg_value) {
938 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
Tamas Berghammere7708682015-04-22 10:00:23 +0000939
Kate Stoneb9c1b512016-09-06 20:57:50 +0000940 auto it = emulator_baton->m_register_values.find(
941 reg_info->kinds[eRegisterKindDWARF]);
942 if (it != emulator_baton->m_register_values.end()) {
943 reg_value = it->second;
944 return true;
945 }
946
947 // The emulator only fill in the dwarf regsiter numbers (and in some case
948 // the generic register numbers). Get the full register info from the
949 // register context based on the dwarf register numbers.
950 const RegisterInfo *full_reg_info =
951 emulator_baton->m_reg_context->GetRegisterInfo(
952 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
953
Zachary Turner97206d52017-05-12 04:51:55 +0000954 Status error =
Kate Stoneb9c1b512016-09-06 20:57:50 +0000955 emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
956 if (error.Success())
957 return true;
958
959 return false;
960}
961
962static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
963 const EmulateInstruction::Context &context,
964 const RegisterInfo *reg_info,
965 const RegisterValue &reg_value) {
966 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
967 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
968 reg_value;
969 return true;
970}
971
972static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
973 const EmulateInstruction::Context &context,
974 lldb::addr_t addr, const void *dst,
975 size_t length) {
976 return length;
977}
978
979static lldb::addr_t ReadFlags(NativeRegisterContext *regsiter_context) {
980 const RegisterInfo *flags_info = regsiter_context->GetRegisterInfo(
981 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
982 return regsiter_context->ReadRegisterAsUnsigned(flags_info,
983 LLDB_INVALID_ADDRESS);
984}
985
Zachary Turner97206d52017-05-12 04:51:55 +0000986Status
987NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadLinux &thread) {
988 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000989 NativeRegisterContextSP register_context_sp = thread.GetRegisterContext();
990
991 std::unique_ptr<EmulateInstruction> emulator_ap(
992 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying,
993 nullptr));
994
995 if (emulator_ap == nullptr)
Zachary Turner97206d52017-05-12 04:51:55 +0000996 return Status("Instruction emulator not found!");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000997
998 EmulatorBaton baton(this, register_context_sp.get());
999 emulator_ap->SetBaton(&baton);
1000 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
1001 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
1002 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
1003 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
1004
1005 if (!emulator_ap->ReadInstruction())
Zachary Turner97206d52017-05-12 04:51:55 +00001006 return Status("Read instruction failed!");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001007
1008 bool emulation_result =
1009 emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
1010
1011 const RegisterInfo *reg_info_pc = register_context_sp->GetRegisterInfo(
1012 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1013 const RegisterInfo *reg_info_flags = register_context_sp->GetRegisterInfo(
1014 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1015
1016 auto pc_it =
1017 baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1018 auto flags_it =
1019 baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
1020
1021 lldb::addr_t next_pc;
1022 lldb::addr_t next_flags;
1023 if (emulation_result) {
1024 assert(pc_it != baton.m_register_values.end() &&
1025 "Emulation was successfull but PC wasn't updated");
1026 next_pc = pc_it->second.GetAsUInt64();
1027
1028 if (flags_it != baton.m_register_values.end())
1029 next_flags = flags_it->second.GetAsUInt64();
1030 else
1031 next_flags = ReadFlags(register_context_sp.get());
1032 } else if (pc_it == baton.m_register_values.end()) {
1033 // Emulate instruction failed and it haven't changed PC. Advance PC
1034 // with the size of the current opcode because the emulation of all
1035 // PC modifying instruction should be successful. The failure most
1036 // likely caused by a not supported instruction which don't modify PC.
1037 next_pc =
1038 register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
1039 next_flags = ReadFlags(register_context_sp.get());
1040 } else {
1041 // The instruction emulation failed after it modified the PC. It is an
1042 // unknown error where we can't continue because the next instruction is
1043 // modifying the PC but we don't know how.
Zachary Turner97206d52017-05-12 04:51:55 +00001044 return Status("Instruction emulation failed unexpectedly.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001045 }
1046
1047 if (m_arch.GetMachine() == llvm::Triple::arm) {
1048 if (next_flags & 0x20) {
1049 // Thumb mode
1050 error = SetSoftwareBreakpoint(next_pc, 2);
1051 } else {
1052 // Arm mode
1053 error = SetSoftwareBreakpoint(next_pc, 4);
Pavel Labath6648fcc2015-04-27 09:21:14 +00001054 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001055 } else if (m_arch.GetMachine() == llvm::Triple::mips64 ||
1056 m_arch.GetMachine() == llvm::Triple::mips64el ||
1057 m_arch.GetMachine() == llvm::Triple::mips ||
Eugene Zemtsovaae0a752017-10-05 19:44:05 +00001058 m_arch.GetMachine() == llvm::Triple::mipsel ||
1059 m_arch.GetMachine() == llvm::Triple::ppc64le)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001060 error = SetSoftwareBreakpoint(next_pc, 4);
1061 else {
1062 // No size hint is given for the next breakpoint
1063 error = SetSoftwareBreakpoint(next_pc, 0);
1064 }
Pavel Labath6648fcc2015-04-27 09:21:14 +00001065
Pavel Labath42eb6902016-10-26 11:13:56 +00001066 // If setting the breakpoint fails because next_pc is out of
1067 // the address space, ignore it and let the debugee segfault.
1068 if (error.GetError() == EIO || error.GetError() == EFAULT) {
Zachary Turner97206d52017-05-12 04:51:55 +00001069 return Status();
Pavel Labath42eb6902016-10-26 11:13:56 +00001070 } else if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001071 return error;
Tamas Berghammere7708682015-04-22 10:00:23 +00001072
Kate Stoneb9c1b512016-09-06 20:57:50 +00001073 m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001074
Zachary Turner97206d52017-05-12 04:51:55 +00001075 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001076}
1077
1078bool NativeProcessLinux::SupportHardwareSingleStepping() const {
1079 if (m_arch.GetMachine() == llvm::Triple::arm ||
1080 m_arch.GetMachine() == llvm::Triple::mips64 ||
1081 m_arch.GetMachine() == llvm::Triple::mips64el ||
1082 m_arch.GetMachine() == llvm::Triple::mips ||
1083 m_arch.GetMachine() == llvm::Triple::mipsel)
Pavel Labath6648fcc2015-04-27 09:21:14 +00001084 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001085 return true;
Tamas Berghammere7708682015-04-22 10:00:23 +00001086}
1087
Zachary Turner97206d52017-05-12 04:51:55 +00001088Status NativeProcessLinux::Resume(const ResumeActionList &resume_actions) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001089 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1090 LLDB_LOG(log, "pid {0}", GetID());
Tamas Berghammere7708682015-04-22 10:00:23 +00001091
Kate Stoneb9c1b512016-09-06 20:57:50 +00001092 bool software_single_step = !SupportHardwareSingleStepping();
Tamas Berghammere7708682015-04-22 10:00:23 +00001093
Kate Stoneb9c1b512016-09-06 20:57:50 +00001094 if (software_single_step) {
Pavel Labatha5be48b2017-10-17 15:52:16 +00001095 for (const auto &thread : m_threads) {
1096 assert(thread && "thread list should not contain NULL threads");
Tamas Berghammere7708682015-04-22 10:00:23 +00001097
Kate Stoneb9c1b512016-09-06 20:57:50 +00001098 const ResumeAction *const action =
Pavel Labatha5be48b2017-10-17 15:52:16 +00001099 resume_actions.GetActionForThread(thread->GetID(), true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001100 if (action == nullptr)
1101 continue;
Tamas Berghammere7708682015-04-22 10:00:23 +00001102
Kate Stoneb9c1b512016-09-06 20:57:50 +00001103 if (action->state == eStateStepping) {
Zachary Turner97206d52017-05-12 04:51:55 +00001104 Status error = SetupSoftwareSingleStepping(
Pavel Labatha5be48b2017-10-17 15:52:16 +00001105 static_cast<NativeThreadLinux &>(*thread));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001106 if (error.Fail())
1107 return error;
1108 }
Tamas Berghammere7708682015-04-22 10:00:23 +00001109 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001110 }
1111
Pavel Labatha5be48b2017-10-17 15:52:16 +00001112 for (const auto &thread : m_threads) {
1113 assert(thread && "thread list should not contain NULL threads");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001114
1115 const ResumeAction *const action =
Pavel Labatha5be48b2017-10-17 15:52:16 +00001116 resume_actions.GetActionForThread(thread->GetID(), true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001117
1118 if (action == nullptr) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001119 LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
Pavel Labatha5be48b2017-10-17 15:52:16 +00001120 thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001121 continue;
Tamas Berghammere7708682015-04-22 10:00:23 +00001122 }
1123
Pavel Labatha6321a82017-01-19 15:26:04 +00001124 LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}",
Pavel Labatha5be48b2017-10-17 15:52:16 +00001125 action->state, GetID(), thread->GetID());
Tamas Berghammere7708682015-04-22 10:00:23 +00001126
Kate Stoneb9c1b512016-09-06 20:57:50 +00001127 switch (action->state) {
1128 case eStateRunning:
1129 case eStateStepping: {
1130 // Run the thread, possibly feeding it the signal.
1131 const int signo = action->signal;
Pavel Labatha5be48b2017-10-17 15:52:16 +00001132 ResumeThread(static_cast<NativeThreadLinux &>(*thread), action->state,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001133 signo);
1134 break;
1135 }
Tamas Berghammere7708682015-04-22 10:00:23 +00001136
Kate Stoneb9c1b512016-09-06 20:57:50 +00001137 case eStateSuspended:
1138 case eStateStopped:
Pavel Labatha6321a82017-01-19 15:26:04 +00001139 llvm_unreachable("Unexpected state");
Tamas Berghammere7708682015-04-22 10:00:23 +00001140
Kate Stoneb9c1b512016-09-06 20:57:50 +00001141 default:
Zachary Turner97206d52017-05-12 04:51:55 +00001142 return Status("NativeProcessLinux::%s (): unexpected state %s specified "
1143 "for pid %" PRIu64 ", tid %" PRIu64,
1144 __FUNCTION__, StateAsCString(action->state), GetID(),
Pavel Labatha5be48b2017-10-17 15:52:16 +00001145 thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001146 }
1147 }
1148
Zachary Turner97206d52017-05-12 04:51:55 +00001149 return Status();
Tamas Berghammere7708682015-04-22 10:00:23 +00001150}
1151
Zachary Turner97206d52017-05-12 04:51:55 +00001152Status NativeProcessLinux::Halt() {
1153 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001154
1155 if (kill(GetID(), SIGSTOP) != 0)
1156 error.SetErrorToErrno();
1157
1158 return error;
Tamas Berghammere7708682015-04-22 10:00:23 +00001159}
1160
Zachary Turner97206d52017-05-12 04:51:55 +00001161Status NativeProcessLinux::Detach() {
1162 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001163
1164 // Stop monitoring the inferior.
1165 m_sigchld_handle.reset();
1166
1167 // Tell ptrace to detach from the process.
1168 if (GetID() == LLDB_INVALID_PROCESS_ID)
1169 return error;
1170
Pavel Labatha5be48b2017-10-17 15:52:16 +00001171 for (const auto &thread : m_threads) {
1172 Status e = Detach(thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001173 if (e.Fail())
1174 error =
1175 e; // Save the error, but still attempt to detach from other threads.
1176 }
1177
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001178 m_processor_trace_monitor.clear();
1179 m_pt_proces_trace_id = LLDB_INVALID_UID;
1180
Kate Stoneb9c1b512016-09-06 20:57:50 +00001181 return error;
1182}
1183
Zachary Turner97206d52017-05-12 04:51:55 +00001184Status NativeProcessLinux::Signal(int signo) {
1185 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001186
Pavel Labatha6321a82017-01-19 15:26:04 +00001187 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1188 LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo,
1189 Host::GetSignalAsCString(signo), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001190
1191 if (kill(GetID(), signo))
1192 error.SetErrorToErrno();
1193
1194 return error;
1195}
1196
Zachary Turner97206d52017-05-12 04:51:55 +00001197Status NativeProcessLinux::Interrupt() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001198 // Pick a running thread (or if none, a not-dead stopped thread) as
1199 // the chosen thread that will be the stop-reason thread.
Pavel Labatha6321a82017-01-19 15:26:04 +00001200 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001201
Pavel Labatha5be48b2017-10-17 15:52:16 +00001202 NativeThreadProtocol *running_thread = nullptr;
1203 NativeThreadProtocol *stopped_thread = nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001204
Pavel Labatha6321a82017-01-19 15:26:04 +00001205 LLDB_LOG(log, "selecting running thread for interrupt target");
Pavel Labatha5be48b2017-10-17 15:52:16 +00001206 for (const auto &thread : m_threads) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001207 // If we have a running or stepping thread, we'll call that the
1208 // target of the interrupt.
Pavel Labatha5be48b2017-10-17 15:52:16 +00001209 const auto thread_state = thread->GetState();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001210 if (thread_state == eStateRunning || thread_state == eStateStepping) {
Pavel Labatha5be48b2017-10-17 15:52:16 +00001211 running_thread = thread.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001212 break;
Pavel Labatha5be48b2017-10-17 15:52:16 +00001213 } else if (!stopped_thread && StateIsStoppedState(thread_state, true)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001214 // Remember the first non-dead stopped thread. We'll use that as a backup
1215 // if there are no running threads.
Pavel Labatha5be48b2017-10-17 15:52:16 +00001216 stopped_thread = thread.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001217 }
1218 }
1219
Pavel Labatha5be48b2017-10-17 15:52:16 +00001220 if (!running_thread && !stopped_thread) {
Zachary Turner97206d52017-05-12 04:51:55 +00001221 Status error("found no running/stepping or live stopped threads as target "
1222 "for interrupt");
Pavel Labatha6321a82017-01-19 15:26:04 +00001223 LLDB_LOG(log, "skipping due to error: {0}", error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001224
1225 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001226 }
1227
Pavel Labatha5be48b2017-10-17 15:52:16 +00001228 NativeThreadProtocol *deferred_signal_thread =
1229 running_thread ? running_thread : stopped_thread;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001230
Pavel Labatha6321a82017-01-19 15:26:04 +00001231 LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(),
Pavel Labatha5be48b2017-10-17 15:52:16 +00001232 running_thread ? "running" : "stopped",
1233 deferred_signal_thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001234
Pavel Labatha5be48b2017-10-17 15:52:16 +00001235 StopRunningThreads(deferred_signal_thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001236
Zachary Turner97206d52017-05-12 04:51:55 +00001237 return Status();
Todd Fialaaf245d12014-06-30 21:05:18 +00001238}
1239
Zachary Turner97206d52017-05-12 04:51:55 +00001240Status NativeProcessLinux::Kill() {
Pavel Labatha6321a82017-01-19 15:26:04 +00001241 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1242 LLDB_LOG(log, "pid {0}", GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +00001243
Zachary Turner97206d52017-05-12 04:51:55 +00001244 Status error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001245
Kate Stoneb9c1b512016-09-06 20:57:50 +00001246 switch (m_state) {
1247 case StateType::eStateInvalid:
1248 case StateType::eStateExited:
1249 case StateType::eStateCrashed:
1250 case StateType::eStateDetached:
1251 case StateType::eStateUnloaded:
1252 // Nothing to do - the process is already dead.
Pavel Labatha6321a82017-01-19 15:26:04 +00001253 LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
Pavel Labath8198db32017-01-24 11:48:25 +00001254 m_state);
Todd Fialaaf245d12014-06-30 21:05:18 +00001255 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001256
Kate Stoneb9c1b512016-09-06 20:57:50 +00001257 case StateType::eStateConnected:
1258 case StateType::eStateAttaching:
1259 case StateType::eStateLaunching:
1260 case StateType::eStateStopped:
1261 case StateType::eStateRunning:
1262 case StateType::eStateStepping:
1263 case StateType::eStateSuspended:
1264 // We can try to kill a process in these states.
1265 break;
1266 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001267
Kate Stoneb9c1b512016-09-06 20:57:50 +00001268 if (kill(GetID(), SIGKILL) != 0) {
1269 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +00001270 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001271 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001272
Kate Stoneb9c1b512016-09-06 20:57:50 +00001273 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001274}
1275
Zachary Turner97206d52017-05-12 04:51:55 +00001276static Status
Pavel Labath15930862017-03-21 13:49:45 +00001277ParseMemoryRegionInfoFromProcMapsLine(llvm::StringRef &maps_line,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001278 MemoryRegionInfo &memory_region_info) {
1279 memory_region_info.Clear();
Todd Fialaaf245d12014-06-30 21:05:18 +00001280
Pavel Labath15930862017-03-21 13:49:45 +00001281 StringExtractor line_extractor(maps_line);
Todd Fialaaf245d12014-06-30 21:05:18 +00001282
Kate Stoneb9c1b512016-09-06 20:57:50 +00001283 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode
1284 // pathname
1285 // perms: rwxp (letter is present if set, '-' if not, final character is
1286 // p=private, s=shared).
Todd Fialaaf245d12014-06-30 21:05:18 +00001287
Kate Stoneb9c1b512016-09-06 20:57:50 +00001288 // Parse out the starting address
1289 lldb::addr_t start_address = line_extractor.GetHexMaxU64(false, 0);
Todd Fialaaf245d12014-06-30 21:05:18 +00001290
Kate Stoneb9c1b512016-09-06 20:57:50 +00001291 // Parse out hyphen separating start and end address from range.
1292 if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != '-'))
Zachary Turner97206d52017-05-12 04:51:55 +00001293 return Status(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001294 "malformed /proc/{pid}/maps entry, missing dash between address range");
Todd Fialaaf245d12014-06-30 21:05:18 +00001295
Kate Stoneb9c1b512016-09-06 20:57:50 +00001296 // Parse out the ending address
1297 lldb::addr_t end_address = line_extractor.GetHexMaxU64(false, start_address);
Todd Fialaaf245d12014-06-30 21:05:18 +00001298
Kate Stoneb9c1b512016-09-06 20:57:50 +00001299 // Parse out the space after the address.
1300 if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != ' '))
Zachary Turner97206d52017-05-12 04:51:55 +00001301 return Status(
1302 "malformed /proc/{pid}/maps entry, missing space after range");
Todd Fialaaf245d12014-06-30 21:05:18 +00001303
Kate Stoneb9c1b512016-09-06 20:57:50 +00001304 // Save the range.
1305 memory_region_info.GetRange().SetRangeBase(start_address);
1306 memory_region_info.GetRange().SetRangeEnd(end_address);
Todd Fialaaf245d12014-06-30 21:05:18 +00001307
Kate Stoneb9c1b512016-09-06 20:57:50 +00001308 // Any memory region in /proc/{pid}/maps is by definition mapped into the
1309 // process.
1310 memory_region_info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
Howard Hellyerad007562016-07-07 08:21:28 +00001311
Kate Stoneb9c1b512016-09-06 20:57:50 +00001312 // Parse out each permission entry.
1313 if (line_extractor.GetBytesLeft() < 4)
Zachary Turner97206d52017-05-12 04:51:55 +00001314 return Status("malformed /proc/{pid}/maps entry, missing some portion of "
1315 "permissions");
Todd Fialaaf245d12014-06-30 21:05:18 +00001316
Kate Stoneb9c1b512016-09-06 20:57:50 +00001317 // Handle read permission.
1318 const char read_perm_char = line_extractor.GetChar();
1319 if (read_perm_char == 'r')
1320 memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eYes);
1321 else if (read_perm_char == '-')
1322 memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1323 else
Zachary Turner97206d52017-05-12 04:51:55 +00001324 return Status("unexpected /proc/{pid}/maps read permission char");
Todd Fialaaf245d12014-06-30 21:05:18 +00001325
Kate Stoneb9c1b512016-09-06 20:57:50 +00001326 // Handle write permission.
1327 const char write_perm_char = line_extractor.GetChar();
1328 if (write_perm_char == 'w')
1329 memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eYes);
1330 else if (write_perm_char == '-')
1331 memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1332 else
Zachary Turner97206d52017-05-12 04:51:55 +00001333 return Status("unexpected /proc/{pid}/maps write permission char");
Todd Fialaaf245d12014-06-30 21:05:18 +00001334
Kate Stoneb9c1b512016-09-06 20:57:50 +00001335 // Handle execute permission.
1336 const char exec_perm_char = line_extractor.GetChar();
1337 if (exec_perm_char == 'x')
1338 memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes);
1339 else if (exec_perm_char == '-')
1340 memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1341 else
Zachary Turner97206d52017-05-12 04:51:55 +00001342 return Status("unexpected /proc/{pid}/maps exec permission char");
Todd Fialaaf245d12014-06-30 21:05:18 +00001343
Kate Stoneb9c1b512016-09-06 20:57:50 +00001344 line_extractor.GetChar(); // Read the private bit
1345 line_extractor.SkipSpaces(); // Skip the separator
1346 line_extractor.GetHexMaxU64(false, 0); // Read the offset
1347 line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1348 line_extractor.GetChar(); // Read the device id separator
1349 line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1350 line_extractor.SkipSpaces(); // Skip the separator
1351 line_extractor.GetU64(0, 10); // Read the inode number
Tamas Berghammerd7d69f82016-07-22 12:55:35 +00001352
Kate Stoneb9c1b512016-09-06 20:57:50 +00001353 line_extractor.SkipSpaces();
1354 const char *name = line_extractor.Peek();
1355 if (name)
1356 memory_region_info.SetName(name);
Tamas Berghammerd7d69f82016-07-22 12:55:35 +00001357
Zachary Turner97206d52017-05-12 04:51:55 +00001358 return Status();
Todd Fialaaf245d12014-06-30 21:05:18 +00001359}
1360
Zachary Turner97206d52017-05-12 04:51:55 +00001361Status NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr,
1362 MemoryRegionInfo &range_info) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001363 // FIXME review that the final memory region returned extends to the end of
1364 // the virtual address space,
1365 // with no perms if it is not mapped.
Todd Fialaaf245d12014-06-30 21:05:18 +00001366
Kate Stoneb9c1b512016-09-06 20:57:50 +00001367 // Use an approach that reads memory regions from /proc/{pid}/maps.
1368 // Assume proc maps entries are in ascending order.
1369 // FIXME assert if we find differently.
Todd Fialaaf245d12014-06-30 21:05:18 +00001370
Kate Stoneb9c1b512016-09-06 20:57:50 +00001371 if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
1372 // We're done.
Zachary Turner97206d52017-05-12 04:51:55 +00001373 return Status("unsupported");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001374 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001375
Zachary Turner97206d52017-05-12 04:51:55 +00001376 Status error = PopulateMemoryRegionCache();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001377 if (error.Fail()) {
1378 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001379 }
1380
1381 lldb::addr_t prev_base_address = 0;
1382
1383 // FIXME start by finding the last region that is <= target address using
1384 // binary search. Data is sorted.
1385 // There can be a ton of regions on pthreads apps with lots of threads.
1386 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1387 ++it) {
Tamas Berghammera6f57952017-01-03 16:29:43 +00001388 MemoryRegionInfo &proc_entry_info = it->first;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001389
1390 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1391 assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
1392 "descending /proc/pid/maps entries detected, unexpected");
1393 prev_base_address = proc_entry_info.GetRange().GetRangeBase();
Hafiz Abid Qadeerb1554312017-01-20 10:24:03 +00001394 UNUSED_IF_ASSERT_DISABLED(prev_base_address);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001395
1396 // If the target address comes before this entry, indicate distance to next
1397 // region.
1398 if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1399 range_info.GetRange().SetRangeBase(load_addr);
1400 range_info.GetRange().SetByteSize(
1401 proc_entry_info.GetRange().GetRangeBase() - load_addr);
1402 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1403 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1404 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1405 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1406
1407 return error;
1408 } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1409 // The target address is within the memory region we're processing here.
1410 range_info = proc_entry_info;
1411 return error;
1412 }
1413
1414 // The target memory address comes somewhere after the region we just
1415 // parsed.
1416 }
1417
1418 // If we made it here, we didn't find an entry that contained the given
1419 // address. Return the
1420 // load_addr as start and the amount of bytes betwwen load address and the end
1421 // of the memory as
1422 // size.
1423 range_info.GetRange().SetRangeBase(load_addr);
1424 range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
1425 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1426 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1427 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1428 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1429 return error;
1430}
1431
Zachary Turner97206d52017-05-12 04:51:55 +00001432Status NativeProcessLinux::PopulateMemoryRegionCache() {
Pavel Labatha6321a82017-01-19 15:26:04 +00001433 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Tamas Berghammera6f57952017-01-03 16:29:43 +00001434
1435 // If our cache is empty, pull the latest. There should always be at least
1436 // one memory region if memory region handling is supported.
1437 if (!m_mem_region_cache.empty()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001438 LLDB_LOG(log, "reusing {0} cached memory region entries",
1439 m_mem_region_cache.size());
Zachary Turner97206d52017-05-12 04:51:55 +00001440 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001441 }
1442
Pavel Labath15930862017-03-21 13:49:45 +00001443 auto BufferOrError = getProcFile(GetID(), "maps");
1444 if (!BufferOrError) {
Tamas Berghammera6f57952017-01-03 16:29:43 +00001445 m_supports_mem_region = LazyBool::eLazyBoolNo;
Pavel Labath15930862017-03-21 13:49:45 +00001446 return BufferOrError.getError();
1447 }
1448 StringRef Rest = BufferOrError.get()->getBuffer();
1449 while (! Rest.empty()) {
1450 StringRef Line;
1451 std::tie(Line, Rest) = Rest.split('\n');
1452 MemoryRegionInfo info;
Zachary Turner97206d52017-05-12 04:51:55 +00001453 const Status parse_error =
1454 ParseMemoryRegionInfoFromProcMapsLine(Line, info);
Pavel Labath15930862017-03-21 13:49:45 +00001455 if (parse_error.Fail()) {
1456 LLDB_LOG(log, "failed to parse proc maps line '{0}': {1}", Line,
1457 parse_error);
1458 m_supports_mem_region = LazyBool::eLazyBoolNo;
1459 return parse_error;
1460 }
1461 m_mem_region_cache.emplace_back(
1462 info, FileSpec(info.GetName().GetCString(), true));
1463 }
1464
1465 if (m_mem_region_cache.empty()) {
Tamas Berghammera6f57952017-01-03 16:29:43 +00001466 // No entries after attempting to read them. This shouldn't happen if
1467 // /proc/{pid}/maps is supported. Assume we don't support map entries
1468 // via procfs.
Pavel Labath15930862017-03-21 13:49:45 +00001469 m_supports_mem_region = LazyBool::eLazyBoolNo;
Pavel Labatha6321a82017-01-19 15:26:04 +00001470 LLDB_LOG(log,
1471 "failed to find any procfs maps entries, assuming no support "
1472 "for memory region metadata retrieval");
Zachary Turner97206d52017-05-12 04:51:55 +00001473 return Status("not supported");
Tamas Berghammera6f57952017-01-03 16:29:43 +00001474 }
1475
Pavel Labatha6321a82017-01-19 15:26:04 +00001476 LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps",
1477 m_mem_region_cache.size(), GetID());
Tamas Berghammera6f57952017-01-03 16:29:43 +00001478
1479 // We support memory retrieval, remember that.
1480 m_supports_mem_region = LazyBool::eLazyBoolYes;
Zachary Turner97206d52017-05-12 04:51:55 +00001481 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001482}
1483
Kate Stoneb9c1b512016-09-06 20:57:50 +00001484void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001485 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1486 LLDB_LOG(log, "newBumpId={0}", newBumpId);
1487 LLDB_LOG(log, "clearing {0} entries from memory region cache",
1488 m_mem_region_cache.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001489 m_mem_region_cache.clear();
1490}
1491
Zachary Turner97206d52017-05-12 04:51:55 +00001492Status NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions,
1493 lldb::addr_t &addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001494// FIXME implementing this requires the equivalent of
1495// InferiorCallPOSIX::InferiorCallMmap, which depends on
1496// functional ThreadPlans working with Native*Protocol.
1497#if 1
Zachary Turner97206d52017-05-12 04:51:55 +00001498 return Status("not implemented yet");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001499#else
1500 addr = LLDB_INVALID_ADDRESS;
1501
1502 unsigned prot = 0;
1503 if (permissions & lldb::ePermissionsReadable)
1504 prot |= eMmapProtRead;
1505 if (permissions & lldb::ePermissionsWritable)
1506 prot |= eMmapProtWrite;
1507 if (permissions & lldb::ePermissionsExecutable)
1508 prot |= eMmapProtExec;
1509
1510 // TODO implement this directly in NativeProcessLinux
1511 // (and lift to NativeProcessPOSIX if/when that class is
1512 // refactored out).
1513 if (InferiorCallMmap(this, addr, 0, size, prot,
1514 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
1515 m_addr_to_mmap_size[addr] = size;
Zachary Turner97206d52017-05-12 04:51:55 +00001516 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001517 } else {
1518 addr = LLDB_INVALID_ADDRESS;
Zachary Turner97206d52017-05-12 04:51:55 +00001519 return Status("unable to allocate %" PRIu64
1520 " bytes of memory with permissions %s",
1521 size, GetPermissionsAsCString(permissions));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001522 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001523#endif
1524}
1525
Zachary Turner97206d52017-05-12 04:51:55 +00001526Status NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001527 // FIXME see comments in AllocateMemory - required lower-level
1528 // bits not in place yet (ThreadPlans)
Zachary Turner97206d52017-05-12 04:51:55 +00001529 return Status("not implemented");
Todd Fialaaf245d12014-06-30 21:05:18 +00001530}
1531
Kate Stoneb9c1b512016-09-06 20:57:50 +00001532lldb::addr_t NativeProcessLinux::GetSharedLibraryInfoAddress() {
1533 // punt on this for now
1534 return LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00001535}
1536
Kate Stoneb9c1b512016-09-06 20:57:50 +00001537size_t NativeProcessLinux::UpdateThreads() {
1538 // The NativeProcessLinux monitoring threads are always up to date
1539 // with respect to thread state and they keep the thread list
1540 // populated properly. All this method needs to do is return the
1541 // thread count.
1542 return m_threads.size();
Todd Fialaaf245d12014-06-30 21:05:18 +00001543}
1544
Zachary Turner97206d52017-05-12 04:51:55 +00001545Status NativeProcessLinux::GetSoftwareBreakpointPCOffset(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001546 uint32_t &actual_opcode_size) {
1547 // FIXME put this behind a breakpoint protocol class that can be
1548 // set per architecture. Need ARM, MIPS support here.
1549 static const uint8_t g_i386_opcode[] = {0xCC};
1550 static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
Eugene Zemtsovaae0a752017-10-05 19:44:05 +00001551 static const uint8_t g_ppc64le_opcode[] = {0x08, 0x00, 0xe0, 0x7f}; // trap
Todd Fialaaf245d12014-06-30 21:05:18 +00001552
Kate Stoneb9c1b512016-09-06 20:57:50 +00001553 switch (m_arch.GetMachine()) {
1554 case llvm::Triple::x86:
1555 case llvm::Triple::x86_64:
1556 actual_opcode_size = static_cast<uint32_t>(sizeof(g_i386_opcode));
Zachary Turner97206d52017-05-12 04:51:55 +00001557 return Status();
Todd Fialaaf245d12014-06-30 21:05:18 +00001558
Kate Stoneb9c1b512016-09-06 20:57:50 +00001559 case llvm::Triple::systemz:
1560 actual_opcode_size = static_cast<uint32_t>(sizeof(g_s390x_opcode));
Zachary Turner97206d52017-05-12 04:51:55 +00001561 return Status();
Ulrich Weigandbb00d0b2016-04-14 14:28:34 +00001562
Eugene Zemtsovaae0a752017-10-05 19:44:05 +00001563 case llvm::Triple::ppc64le:
1564 actual_opcode_size = static_cast<uint32_t>(sizeof(g_ppc64le_opcode));
1565 return Status();
1566
Kate Stoneb9c1b512016-09-06 20:57:50 +00001567 case llvm::Triple::arm:
1568 case llvm::Triple::aarch64:
1569 case llvm::Triple::mips64:
1570 case llvm::Triple::mips64el:
1571 case llvm::Triple::mips:
1572 case llvm::Triple::mipsel:
1573 // On these architectures the PC don't get updated for breakpoint hits
1574 actual_opcode_size = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00001575 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001576
1577 default:
1578 assert(false && "CPU type not supported!");
Zachary Turner97206d52017-05-12 04:51:55 +00001579 return Status("CPU type not supported");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001580 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001581}
1582
Zachary Turner97206d52017-05-12 04:51:55 +00001583Status NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,
1584 bool hardware) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001585 if (hardware)
Omair Javaidd5ffbad2017-02-24 13:27:31 +00001586 return SetHardwareBreakpoint(addr, size);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001587 else
1588 return SetSoftwareBreakpoint(addr, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00001589}
1590
Zachary Turner97206d52017-05-12 04:51:55 +00001591Status NativeProcessLinux::RemoveBreakpoint(lldb::addr_t addr, bool hardware) {
Omair Javaidd5ffbad2017-02-24 13:27:31 +00001592 if (hardware)
1593 return RemoveHardwareBreakpoint(addr);
1594 else
1595 return NativeProcessProtocol::RemoveBreakpoint(addr);
1596}
1597
Zachary Turner97206d52017-05-12 04:51:55 +00001598Status NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001599 size_t trap_opcode_size_hint, size_t &actual_opcode_size,
1600 const uint8_t *&trap_opcode_bytes) {
1601 // FIXME put this behind a breakpoint protocol class that can be set per
1602 // architecture. Need MIPS support here.
1603 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};
1604 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1605 // linux kernel does otherwise.
1606 static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1607 static const uint8_t g_i386_opcode[] = {0xCC};
1608 static const uint8_t g_mips64_opcode[] = {0x00, 0x00, 0x00, 0x0d};
1609 static const uint8_t g_mips64el_opcode[] = {0x0d, 0x00, 0x00, 0x00};
1610 static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
1611 static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
Eugene Zemtsovaae0a752017-10-05 19:44:05 +00001612 static const uint8_t g_ppc64le_opcode[] = {0x08, 0x00, 0xe0, 0x7f}; // trap
Todd Fialaaf245d12014-06-30 21:05:18 +00001613
Kate Stoneb9c1b512016-09-06 20:57:50 +00001614 switch (m_arch.GetMachine()) {
1615 case llvm::Triple::aarch64:
1616 trap_opcode_bytes = g_aarch64_opcode;
1617 actual_opcode_size = sizeof(g_aarch64_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001618 return Status();
Todd Fiala2afc5962014-08-21 16:42:31 +00001619
Kate Stoneb9c1b512016-09-06 20:57:50 +00001620 case llvm::Triple::arm:
1621 switch (trap_opcode_size_hint) {
1622 case 2:
1623 trap_opcode_bytes = g_thumb_breakpoint_opcode;
1624 actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001625 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001626 case 4:
1627 trap_opcode_bytes = g_arm_breakpoint_opcode;
1628 actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001629 return Status();
Todd Fialaaf245d12014-06-30 21:05:18 +00001630 default:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001631 assert(false && "Unrecognised trap opcode size hint!");
Zachary Turner97206d52017-05-12 04:51:55 +00001632 return Status("Unrecognised trap opcode size hint!");
Todd Fialaaf245d12014-06-30 21:05:18 +00001633 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001634
1635 case llvm::Triple::x86:
1636 case llvm::Triple::x86_64:
1637 trap_opcode_bytes = g_i386_opcode;
1638 actual_opcode_size = sizeof(g_i386_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001639 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001640
1641 case llvm::Triple::mips:
1642 case llvm::Triple::mips64:
1643 trap_opcode_bytes = g_mips64_opcode;
1644 actual_opcode_size = sizeof(g_mips64_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001645 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001646
1647 case llvm::Triple::mipsel:
1648 case llvm::Triple::mips64el:
1649 trap_opcode_bytes = g_mips64el_opcode;
1650 actual_opcode_size = sizeof(g_mips64el_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001651 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001652
1653 case llvm::Triple::systemz:
1654 trap_opcode_bytes = g_s390x_opcode;
1655 actual_opcode_size = sizeof(g_s390x_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001656 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001657
Eugene Zemtsovaae0a752017-10-05 19:44:05 +00001658 case llvm::Triple::ppc64le:
1659 trap_opcode_bytes = g_ppc64le_opcode;
1660 actual_opcode_size = sizeof(g_ppc64le_opcode);
1661 return Status();
1662
Kate Stoneb9c1b512016-09-06 20:57:50 +00001663 default:
1664 assert(false && "CPU type not supported!");
Zachary Turner97206d52017-05-12 04:51:55 +00001665 return Status("CPU type not supported");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001666 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001667}
1668
1669#if 0
1670ProcessMessage::CrashReason
1671NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
1672{
1673 ProcessMessage::CrashReason reason;
1674 assert(info->si_signo == SIGSEGV);
1675
1676 reason = ProcessMessage::eInvalidCrashReason;
1677
1678 switch (info->si_code)
1679 {
1680 default:
1681 assert(false && "unexpected si_code for SIGSEGV");
1682 break;
1683 case SI_KERNEL:
1684 // Linux will occasionally send spurious SI_KERNEL codes.
1685 // (this is poorly documented in sigaction)
1686 // One way to get this is via unaligned SIMD loads.
1687 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
1688 break;
1689 case SEGV_MAPERR:
1690 reason = ProcessMessage::eInvalidAddress;
1691 break;
1692 case SEGV_ACCERR:
1693 reason = ProcessMessage::ePrivilegedAddress;
1694 break;
1695 }
1696
1697 return reason;
1698}
1699#endif
1700
Todd Fialaaf245d12014-06-30 21:05:18 +00001701#if 0
1702ProcessMessage::CrashReason
1703NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
1704{
1705 ProcessMessage::CrashReason reason;
1706 assert(info->si_signo == SIGILL);
1707
1708 reason = ProcessMessage::eInvalidCrashReason;
1709
1710 switch (info->si_code)
1711 {
1712 default:
1713 assert(false && "unexpected si_code for SIGILL");
1714 break;
1715 case ILL_ILLOPC:
1716 reason = ProcessMessage::eIllegalOpcode;
1717 break;
1718 case ILL_ILLOPN:
1719 reason = ProcessMessage::eIllegalOperand;
1720 break;
1721 case ILL_ILLADR:
1722 reason = ProcessMessage::eIllegalAddressingMode;
1723 break;
1724 case ILL_ILLTRP:
1725 reason = ProcessMessage::eIllegalTrap;
1726 break;
1727 case ILL_PRVOPC:
1728 reason = ProcessMessage::ePrivilegedOpcode;
1729 break;
1730 case ILL_PRVREG:
1731 reason = ProcessMessage::ePrivilegedRegister;
1732 break;
1733 case ILL_COPROC:
1734 reason = ProcessMessage::eCoprocessorError;
1735 break;
1736 case ILL_BADSTK:
1737 reason = ProcessMessage::eInternalStackError;
1738 break;
1739 }
1740
1741 return reason;
1742}
1743#endif
1744
1745#if 0
1746ProcessMessage::CrashReason
1747NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
1748{
1749 ProcessMessage::CrashReason reason;
1750 assert(info->si_signo == SIGFPE);
1751
1752 reason = ProcessMessage::eInvalidCrashReason;
1753
1754 switch (info->si_code)
1755 {
1756 default:
1757 assert(false && "unexpected si_code for SIGFPE");
1758 break;
1759 case FPE_INTDIV:
1760 reason = ProcessMessage::eIntegerDivideByZero;
1761 break;
1762 case FPE_INTOVF:
1763 reason = ProcessMessage::eIntegerOverflow;
1764 break;
1765 case FPE_FLTDIV:
1766 reason = ProcessMessage::eFloatDivideByZero;
1767 break;
1768 case FPE_FLTOVF:
1769 reason = ProcessMessage::eFloatOverflow;
1770 break;
1771 case FPE_FLTUND:
1772 reason = ProcessMessage::eFloatUnderflow;
1773 break;
1774 case FPE_FLTRES:
1775 reason = ProcessMessage::eFloatInexactResult;
1776 break;
1777 case FPE_FLTINV:
1778 reason = ProcessMessage::eFloatInvalidOperation;
1779 break;
1780 case FPE_FLTSUB:
1781 reason = ProcessMessage::eFloatSubscriptRange;
1782 break;
1783 }
1784
1785 return reason;
1786}
1787#endif
1788
1789#if 0
1790ProcessMessage::CrashReason
1791NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
1792{
1793 ProcessMessage::CrashReason reason;
1794 assert(info->si_signo == SIGBUS);
1795
1796 reason = ProcessMessage::eInvalidCrashReason;
1797
1798 switch (info->si_code)
1799 {
1800 default:
1801 assert(false && "unexpected si_code for SIGBUS");
1802 break;
1803 case BUS_ADRALN:
1804 reason = ProcessMessage::eIllegalAlignment;
1805 break;
1806 case BUS_ADRERR:
1807 reason = ProcessMessage::eIllegalAddress;
1808 break;
1809 case BUS_OBJERR:
1810 reason = ProcessMessage::eHardwareError;
1811 break;
1812 }
1813
1814 return reason;
1815}
1816#endif
1817
Zachary Turner97206d52017-05-12 04:51:55 +00001818Status NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
1819 size_t &bytes_read) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001820 if (ProcessVmReadvSupported()) {
1821 // The process_vm_readv path is about 50 times faster than ptrace api. We
1822 // want to use
1823 // this syscall if it is supported.
Pavel Labathdf7c6992015-06-17 18:38:49 +00001824
Kate Stoneb9c1b512016-09-06 20:57:50 +00001825 const ::pid_t pid = GetID();
Pavel Labathdf7c6992015-06-17 18:38:49 +00001826
Kate Stoneb9c1b512016-09-06 20:57:50 +00001827 struct iovec local_iov, remote_iov;
1828 local_iov.iov_base = buf;
1829 local_iov.iov_len = size;
1830 remote_iov.iov_base = reinterpret_cast<void *>(addr);
1831 remote_iov.iov_len = size;
Pavel Labathdf7c6992015-06-17 18:38:49 +00001832
Kate Stoneb9c1b512016-09-06 20:57:50 +00001833 bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
1834 const bool success = bytes_read == size;
Pavel Labathdf7c6992015-06-17 18:38:49 +00001835
Pavel Labatha6321a82017-01-19 15:26:04 +00001836 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1837 LLDB_LOG(log,
1838 "using process_vm_readv to read {0} bytes from inferior "
1839 "address {1:x}: {2}",
Pavel Labath10c41f32017-06-06 14:06:17 +00001840 size, addr, success ? "Success" : llvm::sys::StrError(errno));
Pavel Labath19cbe962015-07-21 13:20:32 +00001841
Kate Stoneb9c1b512016-09-06 20:57:50 +00001842 if (success)
Zachary Turner97206d52017-05-12 04:51:55 +00001843 return Status();
Pavel Labatha6321a82017-01-19 15:26:04 +00001844 // else the call failed for some reason, let's retry the read using ptrace
1845 // api.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001846 }
Pavel Labath19cbe962015-07-21 13:20:32 +00001847
Kate Stoneb9c1b512016-09-06 20:57:50 +00001848 unsigned char *dst = static_cast<unsigned char *>(buf);
1849 size_t remainder;
1850 long data;
Pavel Labath19cbe962015-07-21 13:20:32 +00001851
Pavel Labatha6321a82017-01-19 15:26:04 +00001852 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1853 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
Pavel Labath19cbe962015-07-21 13:20:32 +00001854
Kate Stoneb9c1b512016-09-06 20:57:50 +00001855 for (bytes_read = 0; bytes_read < size; bytes_read += remainder) {
Zachary Turner97206d52017-05-12 04:51:55 +00001856 Status error = NativeProcessLinux::PtraceWrapper(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001857 PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data);
Pavel Labatha6321a82017-01-19 15:26:04 +00001858 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001859 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001860
1861 remainder = size - bytes_read;
1862 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
1863
1864 // Copy the data into our buffer
1865 memcpy(dst, &data, remainder);
1866
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 addr += k_ptrace_word_size;
1869 dst += k_ptrace_word_size;
1870 }
Zachary Turner97206d52017-05-12 04:51:55 +00001871 return Status();
Todd Fialaaf245d12014-06-30 21:05:18 +00001872}
1873
Zachary Turner97206d52017-05-12 04:51:55 +00001874Status NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf,
1875 size_t size,
1876 size_t &bytes_read) {
1877 Status error = ReadMemory(addr, buf, size, bytes_read);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001878 if (error.Fail())
Pavel Labath19cbe962015-07-21 13:20:32 +00001879 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001880 return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00001881}
1882
Zachary Turner97206d52017-05-12 04:51:55 +00001883Status NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,
1884 size_t size, size_t &bytes_written) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001885 const unsigned char *src = static_cast<const unsigned char *>(buf);
1886 size_t remainder;
Zachary Turner97206d52017-05-12 04:51:55 +00001887 Status error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001888
Pavel Labatha6321a82017-01-19 15:26:04 +00001889 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1890 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00001891
Kate Stoneb9c1b512016-09-06 20:57:50 +00001892 for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
1893 remainder = size - bytes_written;
1894 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
Chaoren Lin97ccc292015-02-03 01:51:12 +00001895
Kate Stoneb9c1b512016-09-06 20:57:50 +00001896 if (remainder == k_ptrace_word_size) {
1897 unsigned long data = 0;
1898 memcpy(&data, src, k_ptrace_word_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00001899
Pavel Labatha6321a82017-01-19 15:26:04 +00001900 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001901 error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(),
1902 (void *)addr, (void *)data);
Pavel Labatha6321a82017-01-19 15:26:04 +00001903 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001904 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001905 } else {
1906 unsigned char buff[8];
1907 size_t bytes_read;
1908 error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
Pavel Labatha6321a82017-01-19 15:26:04 +00001909 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001910 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001911
1912 memcpy(buff, src, remainder);
1913
1914 size_t bytes_written_rec;
1915 error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
Pavel Labatha6321a82017-01-19 15:26:04 +00001916 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001917 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001918
Pavel Labatha6321a82017-01-19 15:26:04 +00001919 LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src,
1920 *(unsigned long *)buff);
Todd Fialaaf245d12014-06-30 21:05:18 +00001921 }
1922
Kate Stoneb9c1b512016-09-06 20:57:50 +00001923 addr += k_ptrace_word_size;
1924 src += k_ptrace_word_size;
1925 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001926 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001927}
1928
Zachary Turner97206d52017-05-12 04:51:55 +00001929Status NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001930 return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
1931}
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001932
Zachary Turner97206d52017-05-12 04:51:55 +00001933Status NativeProcessLinux::GetEventMessage(lldb::tid_t tid,
1934 unsigned long *message) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001935 return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
1936}
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001937
Zachary Turner97206d52017-05-12 04:51:55 +00001938Status NativeProcessLinux::Detach(lldb::tid_t tid) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001939 if (tid == LLDB_INVALID_THREAD_ID)
Zachary Turner97206d52017-05-12 04:51:55 +00001940 return Status();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001941
Kate Stoneb9c1b512016-09-06 20:57:50 +00001942 return PtraceWrapper(PTRACE_DETACH, tid);
1943}
1944
1945bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {
Pavel Labatha5be48b2017-10-17 15:52:16 +00001946 for (const auto &thread : m_threads) {
1947 assert(thread && "thread list should not contain NULL threads");
1948 if (thread->GetID() == thread_id) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001949 // We have this thread.
1950 return true;
Todd Fialaaf245d12014-06-30 21:05:18 +00001951 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001952 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001953
Kate Stoneb9c1b512016-09-06 20:57:50 +00001954 // We don't have this thread.
1955 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001956}
1957
Kate Stoneb9c1b512016-09-06 20:57:50 +00001958bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001959 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1960 LLDB_LOG(log, "tid: {0})", thread_id);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001961
1962 bool found = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001963 for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
1964 if (*it && ((*it)->GetID() == thread_id)) {
1965 m_threads.erase(it);
1966 found = true;
1967 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00001968 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001969 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001970
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001971 if (found)
1972 StopTracingForThread(thread_id);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001973 SignalIfAllThreadsStopped();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001974 return found;
Todd Fialaaf245d12014-06-30 21:05:18 +00001975}
1976
Pavel Labatha5be48b2017-10-17 15:52:16 +00001977NativeThreadLinux &NativeProcessLinux::AddThread(lldb::tid_t thread_id) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001978 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
1979 LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
Todd Fialaaf245d12014-06-30 21:05:18 +00001980
Kate Stoneb9c1b512016-09-06 20:57:50 +00001981 assert(!HasThreadNoLock(thread_id) &&
1982 "attempted to add a thread by id that already exists");
Todd Fialaaf245d12014-06-30 21:05:18 +00001983
Kate Stoneb9c1b512016-09-06 20:57:50 +00001984 // If this is the first thread, save it as the current thread
1985 if (m_threads.empty())
1986 SetCurrentThreadID(thread_id);
Todd Fialaaf245d12014-06-30 21:05:18 +00001987
Pavel Labatha5be48b2017-10-17 15:52:16 +00001988 m_threads.push_back(llvm::make_unique<NativeThreadLinux>(*this, thread_id));
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001989
1990 if (m_pt_proces_trace_id != LLDB_INVALID_UID) {
1991 auto traceMonitor = ProcessorTraceMonitor::Create(
1992 GetID(), thread_id, m_pt_process_trace_config, true);
1993 if (traceMonitor) {
1994 m_pt_traced_thread_group.insert(thread_id);
1995 m_processor_trace_monitor.insert(
1996 std::make_pair(thread_id, std::move(*traceMonitor)));
1997 } else {
1998 LLDB_LOG(log, "failed to start trace on thread {0}", thread_id);
1999 Status error(traceMonitor.takeError());
2000 LLDB_LOG(log, "error {0}", error);
2001 }
2002 }
2003
Pavel Labatha5be48b2017-10-17 15:52:16 +00002004 return static_cast<NativeThreadLinux &>(*m_threads.back());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002005}
Todd Fialaaf245d12014-06-30 21:05:18 +00002006
Zachary Turner97206d52017-05-12 04:51:55 +00002007Status
2008NativeProcessLinux::FixupBreakpointPCAsNeeded(NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002009 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_BREAKPOINTS));
Todd Fialaaf245d12014-06-30 21:05:18 +00002010
Zachary Turner97206d52017-05-12 04:51:55 +00002011 Status error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002012
Kate Stoneb9c1b512016-09-06 20:57:50 +00002013 // Find out the size of a breakpoint (might depend on where we are in the
2014 // code).
2015 NativeRegisterContextSP context_sp = thread.GetRegisterContext();
2016 if (!context_sp) {
2017 error.SetErrorString("cannot get a NativeRegisterContext for the thread");
Pavel Labatha6321a82017-01-19 15:26:04 +00002018 LLDB_LOG(log, "failed: {0}", error);
Todd Fialaaf245d12014-06-30 21:05:18 +00002019 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002020 }
Chaoren Linfa03ad22015-02-03 01:50:42 +00002021
Kate Stoneb9c1b512016-09-06 20:57:50 +00002022 uint32_t breakpoint_size = 0;
2023 error = GetSoftwareBreakpointPCOffset(breakpoint_size);
2024 if (error.Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002025 LLDB_LOG(log, "GetBreakpointSize() failed: {0}", error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002026 return error;
Pavel Labatha6321a82017-01-19 15:26:04 +00002027 } else
2028 LLDB_LOG(log, "breakpoint size: {0}", breakpoint_size);
Pavel Labathc0765592015-05-06 10:46:34 +00002029
Kate Stoneb9c1b512016-09-06 20:57:50 +00002030 // First try probing for a breakpoint at a software breakpoint location: PC -
2031 // breakpoint size.
2032 const lldb::addr_t initial_pc_addr =
2033 context_sp->GetPCfromBreakpointLocation();
2034 lldb::addr_t breakpoint_addr = initial_pc_addr;
2035 if (breakpoint_size > 0) {
2036 // Do not allow breakpoint probe to wrap around.
2037 if (breakpoint_addr >= breakpoint_size)
2038 breakpoint_addr -= breakpoint_size;
2039 }
2040
2041 // Check if we stopped because of a breakpoint.
2042 NativeBreakpointSP breakpoint_sp;
2043 error = m_breakpoint_list.GetBreakpoint(breakpoint_addr, breakpoint_sp);
2044 if (!error.Success() || !breakpoint_sp) {
2045 // We didn't find one at a software probe location. Nothing to do.
Pavel Labatha6321a82017-01-19 15:26:04 +00002046 LLDB_LOG(log,
2047 "pid {0} no lldb breakpoint found at current pc with "
2048 "adjustment: {1}",
2049 GetID(), breakpoint_addr);
Zachary Turner97206d52017-05-12 04:51:55 +00002050 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002051 }
2052
2053 // If the breakpoint is not a software breakpoint, nothing to do.
2054 if (!breakpoint_sp->IsSoftwareBreakpoint()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002055 LLDB_LOG(
2056 log,
2057 "pid {0} breakpoint found at {1:x}, not software, nothing to adjust",
2058 GetID(), breakpoint_addr);
Zachary Turner97206d52017-05-12 04:51:55 +00002059 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002060 }
2061
2062 //
2063 // We have a software breakpoint and need to adjust the PC.
2064 //
2065
2066 // Sanity check.
2067 if (breakpoint_size == 0) {
2068 // Nothing to do! How did we get here?
Pavel Labatha6321a82017-01-19 15:26:04 +00002069 LLDB_LOG(log,
2070 "pid {0} breakpoint found at {1:x}, it is software, but the "
2071 "size is zero, nothing to do (unexpected)",
2072 GetID(), breakpoint_addr);
Zachary Turner97206d52017-05-12 04:51:55 +00002073 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002074 }
2075
2076 // Change the program counter.
Pavel Labatha6321a82017-01-19 15:26:04 +00002077 LLDB_LOG(log, "pid {0} tid {1}: changing PC from {2:x} to {3:x}", GetID(),
2078 thread.GetID(), initial_pc_addr, breakpoint_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002079
2080 error = context_sp->SetPC(breakpoint_addr);
2081 if (error.Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002082 LLDB_LOG(log, "pid {0} tid {1}: failed to set PC: {2}", GetID(),
2083 thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002084 return error;
2085 }
2086
2087 return error;
2088}
2089
Zachary Turner97206d52017-05-12 04:51:55 +00002090Status NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,
2091 FileSpec &file_spec) {
2092 Status error = PopulateMemoryRegionCache();
Tamas Berghammera6f57952017-01-03 16:29:43 +00002093 if (error.Fail())
2094 return error;
2095
Kate Stoneb9c1b512016-09-06 20:57:50 +00002096 FileSpec module_file_spec(module_path, true);
2097
Kate Stoneb9c1b512016-09-06 20:57:50 +00002098 file_spec.Clear();
Tamas Berghammera6f57952017-01-03 16:29:43 +00002099 for (const auto &it : m_mem_region_cache) {
2100 if (it.second.GetFilename() == module_file_spec.GetFilename()) {
2101 file_spec = it.second;
Zachary Turner97206d52017-05-12 04:51:55 +00002102 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00002103 }
2104 }
Zachary Turner97206d52017-05-12 04:51:55 +00002105 return Status("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
2106 module_file_spec.GetFilename().AsCString(), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002107}
2108
Zachary Turner97206d52017-05-12 04:51:55 +00002109Status NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
2110 lldb::addr_t &load_addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002111 load_addr = LLDB_INVALID_ADDRESS;
Zachary Turner97206d52017-05-12 04:51:55 +00002112 Status error = PopulateMemoryRegionCache();
Tamas Berghammera6f57952017-01-03 16:29:43 +00002113 if (error.Fail())
2114 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002115
Tamas Berghammera6f57952017-01-03 16:29:43 +00002116 FileSpec file(file_name, false);
2117 for (const auto &it : m_mem_region_cache) {
2118 if (it.second == file) {
2119 load_addr = it.first.GetRange().GetRangeBase();
Zachary Turner97206d52017-05-12 04:51:55 +00002120 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00002121 }
2122 }
Zachary Turner97206d52017-05-12 04:51:55 +00002123 return Status("No load address found for specified file.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002124}
2125
Pavel Labatha5be48b2017-10-17 15:52:16 +00002126NativeThreadLinux *NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {
2127 return static_cast<NativeThreadLinux *>(
Kate Stoneb9c1b512016-09-06 20:57:50 +00002128 NativeProcessProtocol::GetThreadByID(tid));
2129}
2130
Zachary Turner97206d52017-05-12 04:51:55 +00002131Status NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,
2132 lldb::StateType state, int signo) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002133 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2134 LLDB_LOG(log, "tid: {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002135
2136 // Before we do the resume below, first check if we have a pending
2137 // stop notification that is currently waiting for
2138 // all threads to stop. This is potentially a buggy situation since
2139 // we're ostensibly waiting for threads to stop before we send out the
2140 // pending notification, and here we are resuming one before we send
2141 // out the pending stop notification.
Pavel Labatha6321a82017-01-19 15:26:04 +00002142 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
2143 LLDB_LOG(log,
2144 "about to resume tid {0} per explicit request but we have a "
2145 "pending stop notification (tid {1}) that is actively "
2146 "waiting for this thread to stop. Valid sequence of events?",
2147 thread.GetID(), m_pending_notification_tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002148 }
2149
2150 // Request a resume. We expect this to be synchronous and the system
2151 // to reflect it is running after this completes.
2152 switch (state) {
2153 case eStateRunning: {
2154 const auto resume_result = thread.Resume(signo);
2155 if (resume_result.Success())
2156 SetState(eStateRunning, true);
2157 return resume_result;
2158 }
2159 case eStateStepping: {
2160 const auto step_result = thread.SingleStep(signo);
2161 if (step_result.Success())
2162 SetState(eStateRunning, true);
2163 return step_result;
2164 }
2165 default:
Pavel Labath8198db32017-01-24 11:48:25 +00002166 LLDB_LOG(log, "Unhandled state {0}.", state);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002167 llvm_unreachable("Unhandled state for resume");
2168 }
Pavel Labathc0765592015-05-06 10:46:34 +00002169}
2170
2171//===----------------------------------------------------------------------===//
2172
Kate Stoneb9c1b512016-09-06 20:57:50 +00002173void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002174 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2175 LLDB_LOG(log, "about to process event: (triggering_tid: {0})",
2176 triggering_tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002177
2178 m_pending_notification_tid = triggering_tid;
2179
2180 // Request a stop for all the thread stops that need to be stopped
2181 // and are not already known to be stopped.
Pavel Labatha5be48b2017-10-17 15:52:16 +00002182 for (const auto &thread : m_threads) {
2183 if (StateIsRunningState(thread->GetState()))
2184 static_cast<NativeThreadLinux *>(thread.get())->RequestStop();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002185 }
2186
2187 SignalIfAllThreadsStopped();
Pavel Labatha6321a82017-01-19 15:26:04 +00002188 LLDB_LOG(log, "event processing done");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002189}
2190
2191void NativeProcessLinux::SignalIfAllThreadsStopped() {
2192 if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
2193 return; // No pending notification. Nothing to do.
2194
2195 for (const auto &thread_sp : m_threads) {
2196 if (StateIsRunningState(thread_sp->GetState()))
2197 return; // Some threads are still running. Don't signal yet.
2198 }
2199
2200 // We have a pending notification and all threads have stopped.
2201 Log *log(
2202 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
2203
2204 // Clear any temporary breakpoints we used to implement software single
2205 // stepping.
2206 for (const auto &thread_info : m_threads_stepping_with_breakpoint) {
Zachary Turner97206d52017-05-12 04:51:55 +00002207 Status error = RemoveBreakpoint(thread_info.second);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002208 if (error.Fail())
Pavel Labatha6321a82017-01-19 15:26:04 +00002209 LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}",
2210 thread_info.first, error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002211 }
2212 m_threads_stepping_with_breakpoint.clear();
2213
2214 // Notify the delegate about the stop
2215 SetCurrentThreadID(m_pending_notification_tid);
2216 SetState(StateType::eStateStopped, true);
2217 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
2218}
2219
2220void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002221 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2222 LLDB_LOG(log, "tid: {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002223
2224 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID &&
2225 StateIsRunningState(thread.GetState())) {
2226 // We will need to wait for this new thread to stop as well before firing
2227 // the
2228 // notification.
2229 thread.RequestStop();
2230 }
2231}
2232
2233void NativeProcessLinux::SigchldHandler() {
Pavel Labatha6321a82017-01-19 15:26:04 +00002234 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002235 // Process all pending waitpid notifications.
2236 while (true) {
2237 int status = -1;
Pavel Labathc1a6b122017-07-03 09:25:55 +00002238 ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, -1, &status,
2239 __WALL | __WNOTHREAD | WNOHANG);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002240
2241 if (wait_pid == 0)
2242 break; // We are done.
2243
2244 if (wait_pid == -1) {
Zachary Turner97206d52017-05-12 04:51:55 +00002245 Status error(errno, eErrorTypePOSIX);
Pavel Labatha6321a82017-01-19 15:26:04 +00002246 LLDB_LOG(log, "waitpid (-1, &status, _) failed: {0}", error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002247 break;
Pavel Labathc0765592015-05-06 10:46:34 +00002248 }
2249
Pavel Labath3508fc82017-06-19 12:47:50 +00002250 WaitStatus wait_status = WaitStatus::Decode(status);
2251 bool exited = wait_status.type == WaitStatus::Exit ||
2252 (wait_status.type == WaitStatus::Signal &&
2253 wait_pid == static_cast<::pid_t>(GetID()));
Pavel Labathc0765592015-05-06 10:46:34 +00002254
Pavel Labath3508fc82017-06-19 12:47:50 +00002255 LLDB_LOG(
2256 log,
2257 "waitpid (-1, &status, _) => pid = {0}, status = {1}, exited = {2}",
2258 wait_pid, wait_status, exited);
Pavel Labathc0765592015-05-06 10:46:34 +00002259
Pavel Labath3508fc82017-06-19 12:47:50 +00002260 MonitorCallback(wait_pid, exited, wait_status);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002261 }
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002262}
2263
2264// Wrapper for ptrace to catch errors and log calls.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002265// Note that ptrace sets errno on error because -1 can be a valid result (i.e.
2266// for PTRACE_PEEK*)
Zachary Turner97206d52017-05-12 04:51:55 +00002267Status NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
2268 void *data, size_t data_size,
2269 long *result) {
2270 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002271 long int ret;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002272
Kate Stoneb9c1b512016-09-06 20:57:50 +00002273 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002274
Kate Stoneb9c1b512016-09-06 20:57:50 +00002275 PtraceDisplayBytes(req, data, data_size);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002276
Kate Stoneb9c1b512016-09-06 20:57:50 +00002277 errno = 0;
2278 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
2279 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2280 *(unsigned int *)addr, data);
2281 else
2282 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2283 addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002284
Kate Stoneb9c1b512016-09-06 20:57:50 +00002285 if (ret == -1)
2286 error.SetErrorToErrno();
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002287
Kate Stoneb9c1b512016-09-06 20:57:50 +00002288 if (result)
2289 *result = ret;
Pavel Labath4a9babb2015-06-30 17:04:49 +00002290
Pavel Labath28096202017-02-17 16:09:10 +00002291 LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data,
2292 data_size, ret);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002293
Kate Stoneb9c1b512016-09-06 20:57:50 +00002294 PtraceDisplayBytes(req, data, data_size);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002295
Pavel Labatha6321a82017-01-19 15:26:04 +00002296 if (error.Fail())
2297 LLDB_LOG(log, "ptrace() failed: {0}", error);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002298
Kate Stoneb9c1b512016-09-06 20:57:50 +00002299 return error;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002300}
Ravitheja Addepally99e37692017-06-28 07:58:31 +00002301
2302llvm::Expected<ProcessorTraceMonitor &>
2303NativeProcessLinux::LookupProcessorTraceInstance(lldb::user_id_t traceid,
2304 lldb::tid_t thread) {
2305 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2306 if (thread == LLDB_INVALID_THREAD_ID && traceid == m_pt_proces_trace_id) {
2307 LLDB_LOG(log, "thread not specified: {0}", traceid);
2308 return Status("tracing not active thread not specified").ToError();
2309 }
2310
2311 for (auto& iter : m_processor_trace_monitor) {
2312 if (traceid == iter.second->GetTraceID() &&
2313 (thread == iter.first || thread == LLDB_INVALID_THREAD_ID))
2314 return *(iter.second);
2315 }
2316
2317 LLDB_LOG(log, "traceid not being traced: {0}", traceid);
2318 return Status("tracing not active for this thread").ToError();
2319}
2320
2321Status NativeProcessLinux::GetMetaData(lldb::user_id_t traceid,
2322 lldb::tid_t thread,
2323 llvm::MutableArrayRef<uint8_t> &buffer,
2324 size_t offset) {
2325 TraceOptions trace_options;
2326 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2327 Status error;
2328
2329 LLDB_LOG(log, "traceid {0}", traceid);
2330
2331 auto perf_monitor = LookupProcessorTraceInstance(traceid, thread);
2332 if (!perf_monitor) {
2333 LLDB_LOG(log, "traceid not being traced: {0}", traceid);
2334 buffer = buffer.slice(buffer.size());
2335 error = perf_monitor.takeError();
2336 return error;
2337 }
2338 return (*perf_monitor).ReadPerfTraceData(buffer, offset);
2339}
2340
2341Status NativeProcessLinux::GetData(lldb::user_id_t traceid, lldb::tid_t thread,
2342 llvm::MutableArrayRef<uint8_t> &buffer,
2343 size_t offset) {
2344 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2345 Status error;
2346
2347 LLDB_LOG(log, "traceid {0}", traceid);
2348
2349 auto perf_monitor = LookupProcessorTraceInstance(traceid, thread);
2350 if (!perf_monitor) {
2351 LLDB_LOG(log, "traceid not being traced: {0}", traceid);
2352 buffer = buffer.slice(buffer.size());
2353 error = perf_monitor.takeError();
2354 return error;
2355 }
2356 return (*perf_monitor).ReadPerfTraceAux(buffer, offset);
2357}
2358
2359Status NativeProcessLinux::GetTraceConfig(lldb::user_id_t traceid,
2360 TraceOptions &config) {
2361 Status error;
2362 if (config.getThreadID() == LLDB_INVALID_THREAD_ID &&
2363 m_pt_proces_trace_id == traceid) {
2364 if (m_pt_proces_trace_id == LLDB_INVALID_UID) {
2365 error.SetErrorString("tracing not active for this process");
2366 return error;
2367 }
2368 config = m_pt_process_trace_config;
2369 } else {
2370 auto perf_monitor =
2371 LookupProcessorTraceInstance(traceid, config.getThreadID());
2372 if (!perf_monitor) {
2373 error = perf_monitor.takeError();
2374 return error;
2375 }
2376 error = (*perf_monitor).GetTraceConfig(config);
2377 }
2378 return error;
2379}
2380
2381lldb::user_id_t
2382NativeProcessLinux::StartTraceGroup(const TraceOptions &config,
2383 Status &error) {
2384
2385 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2386 if (config.getType() != TraceType::eTraceTypeProcessorTrace)
2387 return LLDB_INVALID_UID;
2388
2389 if (m_pt_proces_trace_id != LLDB_INVALID_UID) {
2390 error.SetErrorString("tracing already active on this process");
2391 return m_pt_proces_trace_id;
2392 }
2393
2394 for (const auto &thread_sp : m_threads) {
2395 if (auto traceInstance = ProcessorTraceMonitor::Create(
2396 GetID(), thread_sp->GetID(), config, true)) {
2397 m_pt_traced_thread_group.insert(thread_sp->GetID());
2398 m_processor_trace_monitor.insert(
2399 std::make_pair(thread_sp->GetID(), std::move(*traceInstance)));
2400 }
2401 }
2402
2403 m_pt_process_trace_config = config;
2404 error = ProcessorTraceMonitor::GetCPUType(m_pt_process_trace_config);
2405
2406 // Trace on Complete process will have traceid of 0
2407 m_pt_proces_trace_id = 0;
2408
2409 LLDB_LOG(log, "Process Trace ID {0}", m_pt_proces_trace_id);
2410 return m_pt_proces_trace_id;
2411}
2412
2413lldb::user_id_t NativeProcessLinux::StartTrace(const TraceOptions &config,
2414 Status &error) {
2415 if (config.getType() != TraceType::eTraceTypeProcessorTrace)
2416 return NativeProcessProtocol::StartTrace(config, error);
2417
2418 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2419
2420 lldb::tid_t threadid = config.getThreadID();
2421
2422 if (threadid == LLDB_INVALID_THREAD_ID)
2423 return StartTraceGroup(config, error);
2424
2425 auto thread_sp = GetThreadByID(threadid);
2426 if (!thread_sp) {
2427 // Thread not tracked by lldb so don't trace.
2428 error.SetErrorString("invalid thread id");
2429 return LLDB_INVALID_UID;
2430 }
2431
2432 const auto &iter = m_processor_trace_monitor.find(threadid);
2433 if (iter != m_processor_trace_monitor.end()) {
2434 LLDB_LOG(log, "Thread already being traced");
2435 error.SetErrorString("tracing already active on this thread");
2436 return LLDB_INVALID_UID;
2437 }
2438
2439 auto traceMonitor =
2440 ProcessorTraceMonitor::Create(GetID(), threadid, config, false);
2441 if (!traceMonitor) {
2442 error = traceMonitor.takeError();
2443 LLDB_LOG(log, "error {0}", error);
2444 return LLDB_INVALID_UID;
2445 }
2446 lldb::user_id_t ret_trace_id = (*traceMonitor)->GetTraceID();
2447 m_processor_trace_monitor.insert(
2448 std::make_pair(threadid, std::move(*traceMonitor)));
2449 return ret_trace_id;
2450}
2451
2452Status NativeProcessLinux::StopTracingForThread(lldb::tid_t thread) {
2453 Status error;
2454 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2455 LLDB_LOG(log, "Thread {0}", thread);
2456
2457 const auto& iter = m_processor_trace_monitor.find(thread);
2458 if (iter == m_processor_trace_monitor.end()) {
2459 error.SetErrorString("tracing not active for this thread");
2460 return error;
2461 }
2462
2463 if (iter->second->GetTraceID() == m_pt_proces_trace_id) {
2464 // traceid maps to the whole process so we have to erase it from the
2465 // thread group.
2466 LLDB_LOG(log, "traceid maps to process");
2467 m_pt_traced_thread_group.erase(thread);
2468 }
2469 m_processor_trace_monitor.erase(iter);
2470
2471 return error;
2472}
2473
2474Status NativeProcessLinux::StopTrace(lldb::user_id_t traceid,
2475 lldb::tid_t thread) {
2476 Status error;
2477
2478 TraceOptions trace_options;
2479 trace_options.setThreadID(thread);
2480 error = NativeProcessLinux::GetTraceConfig(traceid, trace_options);
2481
2482 if (error.Fail())
2483 return error;
2484
2485 switch (trace_options.getType()) {
2486 case lldb::TraceType::eTraceTypeProcessorTrace:
2487 if (traceid == m_pt_proces_trace_id &&
2488 thread == LLDB_INVALID_THREAD_ID)
2489 StopProcessorTracingOnProcess();
2490 else
2491 error = StopProcessorTracingOnThread(traceid, thread);
2492 break;
2493 default:
2494 error.SetErrorString("trace not supported");
2495 break;
2496 }
2497
2498 return error;
2499}
2500
2501void NativeProcessLinux::StopProcessorTracingOnProcess() {
2502 for (auto thread_id_iter : m_pt_traced_thread_group)
2503 m_processor_trace_monitor.erase(thread_id_iter);
2504 m_pt_traced_thread_group.clear();
2505 m_pt_proces_trace_id = LLDB_INVALID_UID;
2506}
2507
2508Status NativeProcessLinux::StopProcessorTracingOnThread(lldb::user_id_t traceid,
2509 lldb::tid_t thread) {
2510 Status error;
2511 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2512
2513 if (thread == LLDB_INVALID_THREAD_ID) {
2514 for (auto& iter : m_processor_trace_monitor) {
2515 if (iter.second->GetTraceID() == traceid) {
2516 // Stopping a trace instance for an individual thread
2517 // hence there will only be one traceid that can match.
2518 m_processor_trace_monitor.erase(iter.first);
2519 return error;
2520 }
2521 LLDB_LOG(log, "Trace ID {0}", iter.second->GetTraceID());
2522 }
2523
2524 LLDB_LOG(log, "Invalid TraceID");
2525 error.SetErrorString("invalid trace id");
2526 return error;
2527 }
2528
2529 // thread is specified so we can use find function on the map.
2530 const auto& iter = m_processor_trace_monitor.find(thread);
2531 if (iter == m_processor_trace_monitor.end()) {
2532 // thread not found in our map.
2533 LLDB_LOG(log, "thread not being traced");
2534 error.SetErrorString("tracing not active for this thread");
2535 return error;
2536 }
2537 if (iter->second->GetTraceID() != traceid) {
2538 // traceid did not match so it has to be invalid.
2539 LLDB_LOG(log, "Invalid TraceID");
2540 error.SetErrorString("invalid trace id");
2541 return error;
2542 }
2543
2544 LLDB_LOG(log, "UID - {0} , Thread -{1}", traceid, thread);
2545
2546 if (traceid == m_pt_proces_trace_id) {
2547 // traceid maps to the whole process so we have to erase it from the
2548 // thread group.
2549 LLDB_LOG(log, "traceid maps to process");
2550 m_pt_traced_thread_group.erase(thread);
2551 }
2552 m_processor_trace_monitor.erase(iter);
2553
2554 return error;
2555}