blob: 58a5941ac9d2eef66beea28e08b618715a301439 [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 Labath96e600f2017-07-07 11:02:19 +0000217llvm::Expected<NativeProcessProtocolSP>
218NativeProcessLinux::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 Labath96e600f2017-07-07 11:02:19 +0000262 std::shared_ptr<NativeProcessLinux> process_sp(new NativeProcessLinux(
263 pid, launch_info.GetPTY().ReleaseMasterFileDescriptor(), native_delegate,
264 arch, mainloop));
265 process_sp->InitializeThreads({pid});
266 return process_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +0000267}
268
Pavel Labath96e600f2017-07-07 11:02:19 +0000269llvm::Expected<NativeProcessProtocolSP> NativeProcessLinux::Factory::Attach(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000270 lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
Pavel Labath96e600f2017-07-07 11:02:19 +0000271 MainLoop &mainloop) const {
Pavel Labatha6321a82017-01-19 15:26:04 +0000272 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
273 LLDB_LOG(log, "pid = {0:x}", pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000274
Kate Stoneb9c1b512016-09-06 20:57:50 +0000275 // Retrieve the architecture for the running process.
Pavel Labath96e600f2017-07-07 11:02:19 +0000276 ArchSpec arch;
277 Status status = ResolveProcessArchitecture(pid, arch);
278 if (!status.Success())
279 return status.ToError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000280
Pavel Labath96e600f2017-07-07 11:02:19 +0000281 auto tids_or = NativeProcessLinux::Attach(pid);
282 if (!tids_or)
283 return tids_or.takeError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000284
Pavel Labath96e600f2017-07-07 11:02:19 +0000285 std::shared_ptr<NativeProcessLinux> process_sp(
286 new NativeProcessLinux(pid, -1, native_delegate, arch, mainloop));
287 process_sp->InitializeThreads(*tids_or);
288 return process_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +0000289}
290
291// -----------------------------------------------------------------------------
292// Public Instance Methods
293// -----------------------------------------------------------------------------
294
Pavel Labath96e600f2017-07-07 11:02:19 +0000295NativeProcessLinux::NativeProcessLinux(::pid_t pid, int terminal_fd,
296 NativeDelegate &delegate,
297 const ArchSpec &arch, MainLoop &mainloop)
298 : NativeProcessProtocol(pid, terminal_fd, delegate), m_arch(arch) {
299 if (m_terminal_fd != -1) {
300 Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
301 assert(status.Success());
302 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000303
Pavel Labath96e600f2017-07-07 11:02:19 +0000304 Status status;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000305 m_sigchld_handle = mainloop.RegisterSignal(
Pavel Labath96e600f2017-07-07 11:02:19 +0000306 SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status);
307 assert(m_sigchld_handle && status.Success());
Todd Fialaaf245d12014-06-30 21:05:18 +0000308}
309
Pavel Labath96e600f2017-07-07 11:02:19 +0000310void NativeProcessLinux::InitializeThreads(llvm::ArrayRef<::pid_t> tids) {
311 for (const auto &tid : tids) {
312 NativeThreadLinuxSP thread_sp = AddThread(tid);
313 assert(thread_sp && "AddThread() returned a nullptr thread");
314 thread_sp->SetStoppedBySignal(SIGSTOP);
315 ThreadWasCreated(*thread_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000316 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000317
Kate Stoneb9c1b512016-09-06 20:57:50 +0000318 // Let our process instance know the thread has stopped.
Pavel Labath96e600f2017-07-07 11:02:19 +0000319 SetCurrentThreadID(tids[0]);
320 SetState(StateType::eStateStopped, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000321
Pavel Labath96e600f2017-07-07 11:02:19 +0000322 // Proccess any signals we received before installing our handler
323 SigchldHandler();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000324}
325
Pavel Labath96e600f2017-07-07 11:02:19 +0000326llvm::Expected<std::vector<::pid_t>> NativeProcessLinux::Attach(::pid_t pid) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000327 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000328
Pavel Labath96e600f2017-07-07 11:02:19 +0000329 Status status;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000330 // Use a map to keep track of the threads which we have attached/need to
331 // attach.
332 Host::TidMap tids_to_attach;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000333 while (Host::FindProcessThreads(pid, tids_to_attach)) {
334 for (Host::TidMap::iterator it = tids_to_attach.begin();
335 it != tids_to_attach.end();) {
336 if (it->second == false) {
337 lldb::tid_t tid = it->first;
338
339 // Attach to the requested process.
340 // An attach will cause the thread to stop with a SIGSTOP.
Pavel Labath96e600f2017-07-07 11:02:19 +0000341 if ((status = PtraceWrapper(PTRACE_ATTACH, tid)).Fail()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000342 // No such thread. The thread may have exited.
343 // More error handling may be needed.
Pavel Labath96e600f2017-07-07 11:02:19 +0000344 if (status.GetError() == ESRCH) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000345 it = tids_to_attach.erase(it);
346 continue;
Pavel Labath96e600f2017-07-07 11:02:19 +0000347 }
348 return status.ToError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000349 }
350
Pavel Labath96e600f2017-07-07 11:02:19 +0000351 int wpid =
352 llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, nullptr, __WALL);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000353 // Need to use __WALL otherwise we receive an error with errno=ECHLD
354 // At this point we should have a thread stopped if waitpid succeeds.
Pavel Labath96e600f2017-07-07 11:02:19 +0000355 if (wpid < 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000356 // No such thread. The thread may have exited.
357 // More error handling may be needed.
358 if (errno == ESRCH) {
359 it = tids_to_attach.erase(it);
360 continue;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000361 }
Pavel Labath96e600f2017-07-07 11:02:19 +0000362 return llvm::errorCodeToError(
363 std::error_code(errno, std::generic_category()));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000364 }
365
Pavel Labath96e600f2017-07-07 11:02:19 +0000366 if ((status = SetDefaultPtraceOpts(tid)).Fail())
367 return status.ToError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000368
Pavel Labatha6321a82017-01-19 15:26:04 +0000369 LLDB_LOG(log, "adding tid = {0}", tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000370 it->second = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000371 }
372
373 // move the loop forward
374 ++it;
375 }
376 }
377
Pavel Labath96e600f2017-07-07 11:02:19 +0000378 size_t tid_count = tids_to_attach.size();
379 if (tid_count == 0)
380 return llvm::make_error<StringError>("No such process",
381 llvm::inconvertibleErrorCode());
Todd Fialaaf245d12014-06-30 21:05:18 +0000382
Pavel Labath96e600f2017-07-07 11:02:19 +0000383 std::vector<::pid_t> tids;
384 tids.reserve(tid_count);
385 for (const auto &p : tids_to_attach)
386 tids.push_back(p.first);
387 return std::move(tids);
Todd Fialaaf245d12014-06-30 21:05:18 +0000388}
389
Zachary Turner97206d52017-05-12 04:51:55 +0000390Status NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000391 long ptrace_opts = 0;
Todd Fialaaf245d12014-06-30 21:05:18 +0000392
Kate Stoneb9c1b512016-09-06 20:57:50 +0000393 // Have the child raise an event on exit. This is used to keep the child in
394 // limbo until it is destroyed.
395 ptrace_opts |= PTRACE_O_TRACEEXIT;
Todd Fialaaf245d12014-06-30 21:05:18 +0000396
Kate Stoneb9c1b512016-09-06 20:57:50 +0000397 // Have the tracer trace threads which spawn in the inferior process.
398 // TODO: if we want to support tracing the inferiors' child, add the
399 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
400 ptrace_opts |= PTRACE_O_TRACECLONE;
Todd Fialaaf245d12014-06-30 21:05:18 +0000401
Kate Stoneb9c1b512016-09-06 20:57:50 +0000402 // Have the tracer notify us before execve returns
403 // (needed to disable legacy SIGTRAP generation)
404 ptrace_opts |= PTRACE_O_TRACEEXEC;
Todd Fialaaf245d12014-06-30 21:05:18 +0000405
Kate Stoneb9c1b512016-09-06 20:57:50 +0000406 return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void *)ptrace_opts);
Todd Fialaaf245d12014-06-30 21:05:18 +0000407}
408
Pavel Labath1107b5a2015-04-17 14:07:49 +0000409// Handles all waitpid events from the inferior process.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000410void NativeProcessLinux::MonitorCallback(lldb::pid_t pid, bool exited,
Pavel Labath3508fc82017-06-19 12:47:50 +0000411 WaitStatus status) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000412 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Todd Fialaaf245d12014-06-30 21:05:18 +0000413
Kate Stoneb9c1b512016-09-06 20:57:50 +0000414 // Certain activities differ based on whether the pid is the tid of the main
415 // thread.
416 const bool is_main_thread = (pid == GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000417
Kate Stoneb9c1b512016-09-06 20:57:50 +0000418 // Handle when the thread exits.
419 if (exited) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000420 LLDB_LOG(log, "got exit signal({0}) , tid = {1} ({2} main thread)", signal,
421 pid, is_main_thread ? "is" : "is not");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000422
423 // This is a thread that exited. Ensure we're not tracking it anymore.
424 const bool thread_found = StopTrackingThread(pid);
425
426 if (is_main_thread) {
427 // We only set the exit status and notify the delegate if we haven't
428 // already set the process
429 // state to an exited state. We normally should have received a SIGTRAP |
430 // (PTRACE_EVENT_EXIT << 8)
431 // for the main thread.
432 const bool already_notified = (GetState() == StateType::eStateExited) ||
433 (GetState() == StateType::eStateCrashed);
434 if (!already_notified) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000435 LLDB_LOG(
436 log,
437 "tid = {0} handling main thread exit ({1}), expected exit state "
438 "already set but state was {2} instead, setting exit state now",
439 pid,
440 thread_found ? "stopped tracking thread metadata"
441 : "thread metadata not found",
Pavel Labath8198db32017-01-24 11:48:25 +0000442 GetState());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000443 // The main thread exited. We're done monitoring. Report to delegate.
Pavel Labath3508fc82017-06-19 12:47:50 +0000444 SetExitStatus(status, true);
Todd Fialaaf245d12014-06-30 21:05:18 +0000445
Kate Stoneb9c1b512016-09-06 20:57:50 +0000446 // Notify delegate that our process has exited.
447 SetState(StateType::eStateExited, true);
Pavel Labatha6321a82017-01-19 15:26:04 +0000448 } else
449 LLDB_LOG(log, "tid = {0} main thread now exited (%s)", pid,
450 thread_found ? "stopped tracking thread metadata"
451 : "thread metadata not found");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000452 } else {
453 // Do we want to report to the delegate in this case? I think not. If
Pavel Labatha6321a82017-01-19 15:26:04 +0000454 // this was an orderly thread exit, we would already have received the
455 // SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal, and we would have done an
456 // all-stop then.
457 LLDB_LOG(log, "tid = {0} handling non-main thread exit (%s)", pid,
458 thread_found ? "stopped tracking thread metadata"
459 : "thread metadata not found");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000460 }
461 return;
462 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000463
Kate Stoneb9c1b512016-09-06 20:57:50 +0000464 siginfo_t info;
465 const auto info_err = GetSignalInfo(pid, &info);
466 auto thread_sp = GetThreadByID(pid);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000467
Kate Stoneb9c1b512016-09-06 20:57:50 +0000468 if (!thread_sp) {
469 // Normally, the only situation when we cannot find the thread is if we have
Pavel Labatha6321a82017-01-19 15:26:04 +0000470 // just received a new thread notification. This is indicated by
471 // GetSignalInfo() returning si_code == SI_USER and si_pid == 0
472 LLDB_LOG(log, "received notification about an unknown tid {0}.", pid);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000473
Kate Stoneb9c1b512016-09-06 20:57:50 +0000474 if (info_err.Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000475 LLDB_LOG(log,
476 "(tid {0}) GetSignalInfo failed ({1}). "
477 "Ingoring this notification.",
478 pid, info_err);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000479 return;
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000480 }
481
Pavel Labatha6321a82017-01-19 15:26:04 +0000482 LLDB_LOG(log, "tid {0}, si_code: {1}, si_pid: {2}", pid, info.si_code,
483 info.si_pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000484
485 auto thread_sp = AddThread(pid);
Ravitheja Addepally99e37692017-06-28 07:58:31 +0000486
Kate Stoneb9c1b512016-09-06 20:57:50 +0000487 // Resume the newly created thread.
488 ResumeThread(*thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
489 ThreadWasCreated(*thread_sp);
490 return;
491 }
492
493 // Get details on the signal raised.
494 if (info_err.Success()) {
495 // We have retrieved the signal info. Dispatch appropriately.
496 if (info.si_signo == SIGTRAP)
497 MonitorSIGTRAP(info, *thread_sp);
Chaoren Linfa03ad22015-02-03 01:50:42 +0000498 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000499 MonitorSignal(info, *thread_sp, exited);
500 } else {
501 if (info_err.GetError() == EINVAL) {
502 // This is a group stop reception for this tid.
503 // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU
Pavel Labatha6321a82017-01-19 15:26:04 +0000504 // into the tracee, triggering the group-stop mechanism. Normally
505 // receiving these would stop the process, pending a SIGCONT. Simulating
506 // this state in a debugger is hard and is generally not needed (one use
507 // case is debugging background task being managed by a shell). For
508 // general use, it is sufficient to stop the process in a signal-delivery
Kate Stoneb9c1b512016-09-06 20:57:50 +0000509 // stop which happens before the group stop. This done by MonitorSignal
Pavel Labatha6321a82017-01-19 15:26:04 +0000510 // and works correctly for all signals.
511 LLDB_LOG(log,
512 "received a group stop for pid {0} tid {1}. Transparent "
513 "handling of group stops not supported, resuming the "
514 "thread.",
515 GetID(), pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000516 ResumeThread(*thread_sp, thread_sp->GetState(),
517 LLDB_INVALID_SIGNAL_NUMBER);
518 } else {
519 // ptrace(GETSIGINFO) failed (but not due to group-stop).
Todd Fialaaf245d12014-06-30 21:05:18 +0000520
Kate Stoneb9c1b512016-09-06 20:57:50 +0000521 // A return value of ESRCH means the thread/process is no longer on the
Pavel Labatha6321a82017-01-19 15:26:04 +0000522 // system, so it was killed somehow outside of our control. Either way,
523 // we can't do anything with it anymore.
Todd Fialaaf245d12014-06-30 21:05:18 +0000524
Kate Stoneb9c1b512016-09-06 20:57:50 +0000525 // Stop tracking the metadata for the thread since it's entirely off the
526 // system now.
527 const bool thread_found = StopTrackingThread(pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000528
Pavel Labatha6321a82017-01-19 15:26:04 +0000529 LLDB_LOG(log,
530 "GetSignalInfo failed: {0}, tid = {1}, signal = {2}, "
531 "status = {3}, main_thread = {4}, thread_found: {5}",
532 info_err, pid, signal, status, is_main_thread, thread_found);
Todd Fialaaf245d12014-06-30 21:05:18 +0000533
Kate Stoneb9c1b512016-09-06 20:57:50 +0000534 if (is_main_thread) {
535 // Notify the delegate - our process is not available but appears to
536 // have been killed outside
537 // our control. Is eStateExited the right exit state in this case?
Pavel Labath3508fc82017-06-19 12:47:50 +0000538 SetExitStatus(status, true);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000539 SetState(StateType::eStateExited, true);
540 } else {
541 // This thread was pulled out from underneath us. Anything to do here?
542 // Do we want to do an all stop?
Pavel Labatha6321a82017-01-19 15:26:04 +0000543 LLDB_LOG(log,
544 "pid {0} tid {1} non-main thread exit occurred, didn't "
545 "tell delegate anything since thread disappeared out "
546 "from underneath us",
547 GetID(), pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000548 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000549 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000550 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000551}
552
Kate Stoneb9c1b512016-09-06 20:57:50 +0000553void NativeProcessLinux::WaitForNewThread(::pid_t tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000554 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Pavel Labath426bdf82015-04-28 07:51:52 +0000555
Kate Stoneb9c1b512016-09-06 20:57:50 +0000556 NativeThreadLinuxSP new_thread_sp = GetThreadByID(tid);
Pavel Labath426bdf82015-04-28 07:51:52 +0000557
Kate Stoneb9c1b512016-09-06 20:57:50 +0000558 if (new_thread_sp) {
559 // We are already tracking the thread - we got the event on the new thread
560 // (see
561 // MonitorSignal) before this one. We are done.
562 return;
563 }
Pavel Labath426bdf82015-04-28 07:51:52 +0000564
Kate Stoneb9c1b512016-09-06 20:57:50 +0000565 // The thread is not tracked yet, let's wait for it to appear.
566 int status = -1;
Pavel Labathc1a6b122017-07-03 09:25:55 +0000567 LLDB_LOG(log,
568 "received thread creation event for tid {0}. tid not tracked "
569 "yet, waiting for thread to appear...",
570 tid);
571 ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, &status, __WALL);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000572 // Since we are waiting on a specific tid, this must be the creation event.
Pavel Labatha6321a82017-01-19 15:26:04 +0000573 // But let's do some checks just in case.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000574 if (wait_pid != tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000575 LLDB_LOG(log,
576 "waiting for tid {0} failed. Assuming the thread has "
577 "disappeared in the meantime",
578 tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000579 // The only way I know of this could happen is if the whole process was
580 // SIGKILLed in the mean time. In any case, we can't do anything about that
581 // now.
582 return;
583 }
584 if (WIFEXITED(status)) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000585 LLDB_LOG(log,
586 "waiting for tid {0} returned an 'exited' event. Not "
587 "tracking the thread.",
588 tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000589 // Also a very improbable event.
590 return;
591 }
Pavel Labath426bdf82015-04-28 07:51:52 +0000592
Pavel Labatha6321a82017-01-19 15:26:04 +0000593 LLDB_LOG(log, "pid = {0}: tracking new thread tid {1}", GetID(), tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000594 new_thread_sp = AddThread(tid);
Ravitheja Addepally99e37692017-06-28 07:58:31 +0000595
Kate Stoneb9c1b512016-09-06 20:57:50 +0000596 ResumeThread(*new_thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
597 ThreadWasCreated(*new_thread_sp);
Pavel Labath426bdf82015-04-28 07:51:52 +0000598}
599
Kate Stoneb9c1b512016-09-06 20:57:50 +0000600void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info,
601 NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000602 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000603 const bool is_main_thread = (thread.GetID() == GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000604
Kate Stoneb9c1b512016-09-06 20:57:50 +0000605 assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
Todd Fialaaf245d12014-06-30 21:05:18 +0000606
Kate Stoneb9c1b512016-09-06 20:57:50 +0000607 switch (info.si_code) {
608 // TODO: these two cases are required if we want to support tracing of the
609 // inferiors' children. We'd need this to debug a monitor.
610 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
611 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
Todd Fialaaf245d12014-06-30 21:05:18 +0000612
Kate Stoneb9c1b512016-09-06 20:57:50 +0000613 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): {
614 // This is the notification on the parent thread which informs us of new
615 // thread
616 // creation.
617 // We don't want to do anything with the parent thread so we just resume it.
618 // In case we
619 // want to implement "break on thread creation" functionality, we would need
620 // to stop
621 // here.
Todd Fialaaf245d12014-06-30 21:05:18 +0000622
Kate Stoneb9c1b512016-09-06 20:57:50 +0000623 unsigned long event_message = 0;
624 if (GetEventMessage(thread.GetID(), &event_message).Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000625 LLDB_LOG(log,
626 "pid {0} received thread creation event but "
627 "GetEventMessage failed so we don't know the new tid",
628 thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000629 } else
630 WaitForNewThread(event_message);
Todd Fialaaf245d12014-06-30 21:05:18 +0000631
Kate Stoneb9c1b512016-09-06 20:57:50 +0000632 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
633 break;
634 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000635
Kate Stoneb9c1b512016-09-06 20:57:50 +0000636 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): {
637 NativeThreadLinuxSP main_thread_sp;
Pavel Labatha6321a82017-01-19 15:26:04 +0000638 LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000639
640 // Exec clears any pending notifications.
641 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
642
643 // Remove all but the main thread here. Linux fork creates a new process
644 // which only copies the main thread.
Pavel Labatha6321a82017-01-19 15:26:04 +0000645 LLDB_LOG(log, "exec received, stop tracking all but main thread");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000646
647 for (auto thread_sp : m_threads) {
648 const bool is_main_thread = thread_sp && thread_sp->GetID() == GetID();
649 if (is_main_thread) {
650 main_thread_sp = std::static_pointer_cast<NativeThreadLinux>(thread_sp);
Pavel Labatha6321a82017-01-19 15:26:04 +0000651 LLDB_LOG(log, "found main thread with tid {0}, keeping",
652 main_thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000653 } else {
Pavel Labatha6321a82017-01-19 15:26:04 +0000654 LLDB_LOG(log, "discarding non-main-thread tid {0} due to exec",
655 thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000656 }
Todd Fialaa9882ce2014-08-28 15:46:54 +0000657 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000658
Kate Stoneb9c1b512016-09-06 20:57:50 +0000659 m_threads.clear();
Chaoren Linfa03ad22015-02-03 01:50:42 +0000660
Kate Stoneb9c1b512016-09-06 20:57:50 +0000661 if (main_thread_sp) {
662 m_threads.push_back(main_thread_sp);
663 SetCurrentThreadID(main_thread_sp->GetID());
664 main_thread_sp->SetStoppedByExec();
665 } else {
666 SetCurrentThreadID(LLDB_INVALID_THREAD_ID);
Pavel Labatha6321a82017-01-19 15:26:04 +0000667 LLDB_LOG(log,
668 "pid {0} no main thread found, discarded all threads, "
669 "we're in a no-thread state!",
670 GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000671 }
672
Kate Stoneb9c1b512016-09-06 20:57:50 +0000673 // Tell coordinator about about the "new" (since exec) stopped main thread.
674 ThreadWasCreated(*main_thread_sp);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000675
Kate Stoneb9c1b512016-09-06 20:57:50 +0000676 // Let our delegate know we have just exec'd.
677 NotifyDidExec();
678
679 // If we have a main thread, indicate we are stopped.
680 assert(main_thread_sp && "exec called during ptraced process but no main "
681 "thread metadata tracked");
682
683 // Let the process know we're stopped.
684 StopRunningThreads(main_thread_sp->GetID());
685
686 break;
687 }
688
689 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): {
690 // The inferior process or one of its threads is about to exit.
691 // We don't want to do anything with the thread so we just resume it. In
692 // case we
693 // want to implement "break on thread exit" functionality, we would need to
694 // stop
695 // here.
696
697 unsigned long data = 0;
698 if (GetEventMessage(thread.GetID(), &data).Fail())
699 data = -1;
700
Pavel Labatha6321a82017-01-19 15:26:04 +0000701 LLDB_LOG(log,
702 "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
703 "WIFSIGNALED={2}, pid = {3}, main_thread = {4}",
704 data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(),
705 is_main_thread);
Todd Fialaaf245d12014-06-30 21:05:18 +0000706
Pavel Labath3508fc82017-06-19 12:47:50 +0000707 if (is_main_thread)
708 SetExitStatus(WaitStatus::Decode(data), true);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000709
710 StateType state = thread.GetState();
711 if (!StateIsRunningState(state)) {
712 // Due to a kernel bug, we may sometimes get this stop after the inferior
713 // gets a
714 // SIGKILL. This confuses our state tracking logic in ResumeThread(),
715 // since normally,
716 // we should not be receiving any ptrace events while the inferior is
717 // stopped. This
718 // makes sure that the inferior is resumed and exits normally.
719 state = eStateRunning;
720 }
721 ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
722
723 break;
724 }
725
726 case 0:
727 case TRAP_TRACE: // We receive this on single stepping.
728 case TRAP_HWBKPT: // We receive this on watchpoint hit
729 {
730 // If a watchpoint was hit, report it
731 uint32_t wp_index;
Zachary Turner97206d52017-05-12 04:51:55 +0000732 Status error = thread.GetRegisterContext()->GetWatchpointHitIndex(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000733 wp_index, (uintptr_t)info.si_addr);
Pavel Labatha6321a82017-01-19 15:26:04 +0000734 if (error.Fail())
735 LLDB_LOG(log,
736 "received error while checking for watchpoint hits, pid = "
737 "{0}, error = {1}",
738 thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000739 if (wp_index != LLDB_INVALID_INDEX32) {
740 MonitorWatchpoint(thread, wp_index);
741 break;
742 }
743
Omair Javaidd5ffbad2017-02-24 13:27:31 +0000744 // If a breakpoint was hit, report it
745 uint32_t bp_index;
746 error = thread.GetRegisterContext()->GetHardwareBreakHitIndex(
747 bp_index, (uintptr_t)info.si_addr);
748 if (error.Fail())
749 LLDB_LOG(log, "received error while checking for hardware "
750 "breakpoint hits, pid = {0}, error = {1}",
751 thread.GetID(), error);
752 if (bp_index != LLDB_INVALID_INDEX32) {
753 MonitorBreakpoint(thread);
754 break;
755 }
756
Kate Stoneb9c1b512016-09-06 20:57:50 +0000757 // Otherwise, report step over
758 MonitorTrace(thread);
759 break;
760 }
761
762 case SI_KERNEL:
Mohit K. Bhakkad35799962015-06-18 04:53:18 +0000763#if defined __mips__
Kate Stoneb9c1b512016-09-06 20:57:50 +0000764 // For mips there is no special signal for watchpoint
765 // So we check for watchpoint in kernel trap
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000766 {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000767 // If a watchpoint was hit, report it
768 uint32_t wp_index;
Zachary Turner97206d52017-05-12 04:51:55 +0000769 Status error = thread.GetRegisterContext()->GetWatchpointHitIndex(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000770 wp_index, LLDB_INVALID_ADDRESS);
Pavel Labatha6321a82017-01-19 15:26:04 +0000771 if (error.Fail())
772 LLDB_LOG(log,
773 "received error while checking for watchpoint hits, pid = "
774 "{0}, error = {1}",
775 thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000776 if (wp_index != LLDB_INVALID_INDEX32) {
777 MonitorWatchpoint(thread, wp_index);
778 break;
779 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000780 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000781// NO BREAK
Mohit K. Bhakkad35799962015-06-18 04:53:18 +0000782#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000783 case TRAP_BRKPT:
784 MonitorBreakpoint(thread);
785 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000786
Kate Stoneb9c1b512016-09-06 20:57:50 +0000787 case SIGTRAP:
788 case (SIGTRAP | 0x80):
Pavel Labatha6321a82017-01-19 15:26:04 +0000789 LLDB_LOG(
790 log,
791 "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",
792 info.si_code, GetID(), thread.GetID());
Chaoren Linfa03ad22015-02-03 01:50:42 +0000793
Kate Stoneb9c1b512016-09-06 20:57:50 +0000794 // Ignore these signals until we know more about them.
795 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
796 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000797
Kate Stoneb9c1b512016-09-06 20:57:50 +0000798 default:
Pavel Labatha6321a82017-01-19 15:26:04 +0000799 LLDB_LOG(
800 log,
801 "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",
802 info.si_code, GetID(), thread.GetID());
803 llvm_unreachable("Unexpected SIGTRAP code!");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000804 break;
805 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000806}
807
Kate Stoneb9c1b512016-09-06 20:57:50 +0000808void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000809 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
810 LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000811
Kate Stoneb9c1b512016-09-06 20:57:50 +0000812 // This thread is currently stopped.
813 thread.SetStoppedByTrace();
814
815 StopRunningThreads(thread.GetID());
816}
817
818void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) {
819 Log *log(
820 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
Pavel Labatha6321a82017-01-19 15:26:04 +0000821 LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000822
823 // Mark the thread as stopped at breakpoint.
824 thread.SetStoppedByBreakpoint();
Zachary Turner97206d52017-05-12 04:51:55 +0000825 Status error = FixupBreakpointPCAsNeeded(thread);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000826 if (error.Fail())
Pavel Labatha6321a82017-01-19 15:26:04 +0000827 LLDB_LOG(log, "pid = {0} fixup: {1}", thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000828
829 if (m_threads_stepping_with_breakpoint.find(thread.GetID()) !=
830 m_threads_stepping_with_breakpoint.end())
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000831 thread.SetStoppedByTrace();
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000832
Kate Stoneb9c1b512016-09-06 20:57:50 +0000833 StopRunningThreads(thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000834}
835
Kate Stoneb9c1b512016-09-06 20:57:50 +0000836void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread,
837 uint32_t wp_index) {
838 Log *log(
839 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
Pavel Labatha6321a82017-01-19 15:26:04 +0000840 LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}",
841 thread.GetID(), wp_index);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000842
843 // Mark the thread as stopped at watchpoint.
844 // The address is at (lldb::addr_t)info->si_addr if we need it.
845 thread.SetStoppedByWatchpoint(wp_index);
846
847 // We need to tell all other running threads before we notify the delegate
848 // about this stop.
849 StopRunningThreads(thread.GetID());
850}
851
852void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
853 NativeThreadLinux &thread, bool exited) {
854 const int signo = info.si_signo;
855 const bool is_from_llgs = info.si_pid == getpid();
856
Pavel Labatha6321a82017-01-19 15:26:04 +0000857 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000858
859 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
860 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
861 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
862 //
863 // IOW, user generated signals never generate what we consider to be a
864 // "crash".
865 //
866 // Similarly, ACK signals generated by this monitor.
867
868 // Handle the signal.
Pavel Labatha6321a82017-01-19 15:26:04 +0000869 LLDB_LOG(log,
870 "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
871 "waitpid pid = {4})",
872 Host::GetSignalAsCString(signo), signo, info.si_code,
873 thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000874
Kate Stoneb9c1b512016-09-06 20:57:50 +0000875 // Check for thread stop notification.
876 if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) {
877 // This is a tgkill()-based stop.
Pavel Labatha6321a82017-01-19 15:26:04 +0000878 LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000879
Kate Stoneb9c1b512016-09-06 20:57:50 +0000880 // Check that we're not already marked with a stop reason.
881 // Note this thread really shouldn't already be marked as stopped - if we
Pavel Labatha6321a82017-01-19 15:26:04 +0000882 // were, that would imply that the kernel signaled us with the thread
883 // stopping which we handled and marked as stopped, and that, without an
884 // intervening resume, we received another stop. It is more likely that we
885 // are missing the marking of a run state somewhere if we find that the
886 // thread was marked as stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000887 const StateType thread_state = thread.GetState();
888 if (!StateIsStoppedState(thread_state, false)) {
889 // An inferior thread has stopped because of a SIGSTOP we have sent it.
890 // Generally, these are not important stops and we don't want to report
Pavel Labatha6321a82017-01-19 15:26:04 +0000891 // them as they are just used to stop other threads when one thread (the
892 // one with the *real* stop reason) hits a breakpoint (watchpoint,
893 // etc...). However, in the case of an asynchronous Interrupt(), this *is*
894 // the real stop reason, so we leave the signal intact if this is the
895 // thread that was chosen as the triggering thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000896 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
897 if (m_pending_notification_tid == thread.GetID())
898 thread.SetStoppedBySignal(SIGSTOP, &info);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000899 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000900 thread.SetStoppedWithNoReason();
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000901
Kate Stoneb9c1b512016-09-06 20:57:50 +0000902 SetCurrentThreadID(thread.GetID());
903 SignalIfAllThreadsStopped();
904 } else {
905 // We can end up here if stop was initiated by LLGS but by this time a
906 // thread stop has occurred - maybe initiated by another event.
Zachary Turner97206d52017-05-12 04:51:55 +0000907 Status error = ResumeThread(thread, thread.GetState(), 0);
Pavel Labatha6321a82017-01-19 15:26:04 +0000908 if (error.Fail())
909 LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(),
910 error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000911 }
912 } else {
Pavel Labatha6321a82017-01-19 15:26:04 +0000913 LLDB_LOG(log,
914 "pid {0} tid {1}, thread was already marked as a stopped "
915 "state (state={2}), leaving stop signal as is",
Pavel Labath8198db32017-01-24 11:48:25 +0000916 GetID(), thread.GetID(), thread_state);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000917 SignalIfAllThreadsStopped();
Todd Fialaaf245d12014-06-30 21:05:18 +0000918 }
919
Kate Stoneb9c1b512016-09-06 20:57:50 +0000920 // Done handling.
921 return;
922 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000923
Pavel Labath4a705e72017-02-24 09:29:14 +0000924 // Check if debugger should stop at this signal or just ignore it
925 // and resume the inferior.
926 if (m_signals_to_ignore.find(signo) != m_signals_to_ignore.end()) {
927 ResumeThread(thread, thread.GetState(), signo);
928 return;
929 }
930
Kate Stoneb9c1b512016-09-06 20:57:50 +0000931 // This thread is stopped.
Pavel Labatha6321a82017-01-19 15:26:04 +0000932 LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000933 thread.SetStoppedBySignal(signo, &info);
934
935 // Send a stop to the debugger after we get all other threads to stop.
936 StopRunningThreads(thread.GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000937}
938
Tamas Berghammere7708682015-04-22 10:00:23 +0000939namespace {
940
Kate Stoneb9c1b512016-09-06 20:57:50 +0000941struct EmulatorBaton {
942 NativeProcessLinux *m_process;
943 NativeRegisterContext *m_reg_context;
Tamas Berghammere7708682015-04-22 10:00:23 +0000944
Kate Stoneb9c1b512016-09-06 20:57:50 +0000945 // eRegisterKindDWARF -> RegsiterValue
946 std::unordered_map<uint32_t, RegisterValue> m_register_values;
Pavel Labath6648fcc2015-04-27 09:21:14 +0000947
Kate Stoneb9c1b512016-09-06 20:57:50 +0000948 EmulatorBaton(NativeProcessLinux *process, NativeRegisterContext *reg_context)
949 : m_process(process), m_reg_context(reg_context) {}
Tamas Berghammere7708682015-04-22 10:00:23 +0000950};
951
952} // anonymous namespace
953
Kate Stoneb9c1b512016-09-06 20:57:50 +0000954static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
955 const EmulateInstruction::Context &context,
956 lldb::addr_t addr, void *dst, size_t length) {
957 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
Tamas Berghammere7708682015-04-22 10:00:23 +0000958
Kate Stoneb9c1b512016-09-06 20:57:50 +0000959 size_t bytes_read;
960 emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
961 return bytes_read;
Tamas Berghammere7708682015-04-22 10:00:23 +0000962}
963
Kate Stoneb9c1b512016-09-06 20:57:50 +0000964static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
965 const RegisterInfo *reg_info,
966 RegisterValue &reg_value) {
967 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
Tamas Berghammere7708682015-04-22 10:00:23 +0000968
Kate Stoneb9c1b512016-09-06 20:57:50 +0000969 auto it = emulator_baton->m_register_values.find(
970 reg_info->kinds[eRegisterKindDWARF]);
971 if (it != emulator_baton->m_register_values.end()) {
972 reg_value = it->second;
973 return true;
974 }
975
976 // The emulator only fill in the dwarf regsiter numbers (and in some case
977 // the generic register numbers). Get the full register info from the
978 // register context based on the dwarf register numbers.
979 const RegisterInfo *full_reg_info =
980 emulator_baton->m_reg_context->GetRegisterInfo(
981 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
982
Zachary Turner97206d52017-05-12 04:51:55 +0000983 Status error =
Kate Stoneb9c1b512016-09-06 20:57:50 +0000984 emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
985 if (error.Success())
986 return true;
987
988 return false;
989}
990
991static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
992 const EmulateInstruction::Context &context,
993 const RegisterInfo *reg_info,
994 const RegisterValue &reg_value) {
995 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
996 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
997 reg_value;
998 return true;
999}
1000
1001static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
1002 const EmulateInstruction::Context &context,
1003 lldb::addr_t addr, const void *dst,
1004 size_t length) {
1005 return length;
1006}
1007
1008static lldb::addr_t ReadFlags(NativeRegisterContext *regsiter_context) {
1009 const RegisterInfo *flags_info = regsiter_context->GetRegisterInfo(
1010 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1011 return regsiter_context->ReadRegisterAsUnsigned(flags_info,
1012 LLDB_INVALID_ADDRESS);
1013}
1014
Zachary Turner97206d52017-05-12 04:51:55 +00001015Status
1016NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadLinux &thread) {
1017 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001018 NativeRegisterContextSP register_context_sp = thread.GetRegisterContext();
1019
1020 std::unique_ptr<EmulateInstruction> emulator_ap(
1021 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying,
1022 nullptr));
1023
1024 if (emulator_ap == nullptr)
Zachary Turner97206d52017-05-12 04:51:55 +00001025 return Status("Instruction emulator not found!");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001026
1027 EmulatorBaton baton(this, register_context_sp.get());
1028 emulator_ap->SetBaton(&baton);
1029 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
1030 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
1031 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
1032 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
1033
1034 if (!emulator_ap->ReadInstruction())
Zachary Turner97206d52017-05-12 04:51:55 +00001035 return Status("Read instruction failed!");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001036
1037 bool emulation_result =
1038 emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
1039
1040 const RegisterInfo *reg_info_pc = register_context_sp->GetRegisterInfo(
1041 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1042 const RegisterInfo *reg_info_flags = register_context_sp->GetRegisterInfo(
1043 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1044
1045 auto pc_it =
1046 baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1047 auto flags_it =
1048 baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
1049
1050 lldb::addr_t next_pc;
1051 lldb::addr_t next_flags;
1052 if (emulation_result) {
1053 assert(pc_it != baton.m_register_values.end() &&
1054 "Emulation was successfull but PC wasn't updated");
1055 next_pc = pc_it->second.GetAsUInt64();
1056
1057 if (flags_it != baton.m_register_values.end())
1058 next_flags = flags_it->second.GetAsUInt64();
1059 else
1060 next_flags = ReadFlags(register_context_sp.get());
1061 } else if (pc_it == baton.m_register_values.end()) {
1062 // Emulate instruction failed and it haven't changed PC. Advance PC
1063 // with the size of the current opcode because the emulation of all
1064 // PC modifying instruction should be successful. The failure most
1065 // likely caused by a not supported instruction which don't modify PC.
1066 next_pc =
1067 register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
1068 next_flags = ReadFlags(register_context_sp.get());
1069 } else {
1070 // The instruction emulation failed after it modified the PC. It is an
1071 // unknown error where we can't continue because the next instruction is
1072 // modifying the PC but we don't know how.
Zachary Turner97206d52017-05-12 04:51:55 +00001073 return Status("Instruction emulation failed unexpectedly.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001074 }
1075
1076 if (m_arch.GetMachine() == llvm::Triple::arm) {
1077 if (next_flags & 0x20) {
1078 // Thumb mode
1079 error = SetSoftwareBreakpoint(next_pc, 2);
1080 } else {
1081 // Arm mode
1082 error = SetSoftwareBreakpoint(next_pc, 4);
Pavel Labath6648fcc2015-04-27 09:21:14 +00001083 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001084 } else if (m_arch.GetMachine() == llvm::Triple::mips64 ||
1085 m_arch.GetMachine() == llvm::Triple::mips64el ||
1086 m_arch.GetMachine() == llvm::Triple::mips ||
1087 m_arch.GetMachine() == llvm::Triple::mipsel)
1088 error = SetSoftwareBreakpoint(next_pc, 4);
1089 else {
1090 // No size hint is given for the next breakpoint
1091 error = SetSoftwareBreakpoint(next_pc, 0);
1092 }
Pavel Labath6648fcc2015-04-27 09:21:14 +00001093
Pavel Labath42eb6902016-10-26 11:13:56 +00001094 // If setting the breakpoint fails because next_pc is out of
1095 // the address space, ignore it and let the debugee segfault.
1096 if (error.GetError() == EIO || error.GetError() == EFAULT) {
Zachary Turner97206d52017-05-12 04:51:55 +00001097 return Status();
Pavel Labath42eb6902016-10-26 11:13:56 +00001098 } else if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001099 return error;
Tamas Berghammere7708682015-04-22 10:00:23 +00001100
Kate Stoneb9c1b512016-09-06 20:57:50 +00001101 m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001102
Zachary Turner97206d52017-05-12 04:51:55 +00001103 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001104}
1105
1106bool NativeProcessLinux::SupportHardwareSingleStepping() const {
1107 if (m_arch.GetMachine() == llvm::Triple::arm ||
1108 m_arch.GetMachine() == llvm::Triple::mips64 ||
1109 m_arch.GetMachine() == llvm::Triple::mips64el ||
1110 m_arch.GetMachine() == llvm::Triple::mips ||
1111 m_arch.GetMachine() == llvm::Triple::mipsel)
Pavel Labath6648fcc2015-04-27 09:21:14 +00001112 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001113 return true;
Tamas Berghammere7708682015-04-22 10:00:23 +00001114}
1115
Zachary Turner97206d52017-05-12 04:51:55 +00001116Status NativeProcessLinux::Resume(const ResumeActionList &resume_actions) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001117 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1118 LLDB_LOG(log, "pid {0}", GetID());
Tamas Berghammere7708682015-04-22 10:00:23 +00001119
Kate Stoneb9c1b512016-09-06 20:57:50 +00001120 bool software_single_step = !SupportHardwareSingleStepping();
Tamas Berghammere7708682015-04-22 10:00:23 +00001121
Kate Stoneb9c1b512016-09-06 20:57:50 +00001122 if (software_single_step) {
1123 for (auto thread_sp : m_threads) {
1124 assert(thread_sp && "thread list should not contain NULL threads");
Tamas Berghammere7708682015-04-22 10:00:23 +00001125
Kate Stoneb9c1b512016-09-06 20:57:50 +00001126 const ResumeAction *const action =
1127 resume_actions.GetActionForThread(thread_sp->GetID(), true);
1128 if (action == nullptr)
1129 continue;
Tamas Berghammere7708682015-04-22 10:00:23 +00001130
Kate Stoneb9c1b512016-09-06 20:57:50 +00001131 if (action->state == eStateStepping) {
Zachary Turner97206d52017-05-12 04:51:55 +00001132 Status error = SetupSoftwareSingleStepping(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001133 static_cast<NativeThreadLinux &>(*thread_sp));
1134 if (error.Fail())
1135 return error;
1136 }
Tamas Berghammere7708682015-04-22 10:00:23 +00001137 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001138 }
1139
1140 for (auto thread_sp : m_threads) {
1141 assert(thread_sp && "thread list should not contain NULL threads");
1142
1143 const ResumeAction *const action =
1144 resume_actions.GetActionForThread(thread_sp->GetID(), true);
1145
1146 if (action == nullptr) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001147 LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
1148 thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001149 continue;
Tamas Berghammere7708682015-04-22 10:00:23 +00001150 }
1151
Pavel Labatha6321a82017-01-19 15:26:04 +00001152 LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}",
Pavel Labath8198db32017-01-24 11:48:25 +00001153 action->state, GetID(), thread_sp->GetID());
Tamas Berghammere7708682015-04-22 10:00:23 +00001154
Kate Stoneb9c1b512016-09-06 20:57:50 +00001155 switch (action->state) {
1156 case eStateRunning:
1157 case eStateStepping: {
1158 // Run the thread, possibly feeding it the signal.
1159 const int signo = action->signal;
1160 ResumeThread(static_cast<NativeThreadLinux &>(*thread_sp), action->state,
1161 signo);
1162 break;
1163 }
Tamas Berghammere7708682015-04-22 10:00:23 +00001164
Kate Stoneb9c1b512016-09-06 20:57:50 +00001165 case eStateSuspended:
1166 case eStateStopped:
Pavel Labatha6321a82017-01-19 15:26:04 +00001167 llvm_unreachable("Unexpected state");
Tamas Berghammere7708682015-04-22 10:00:23 +00001168
Kate Stoneb9c1b512016-09-06 20:57:50 +00001169 default:
Zachary Turner97206d52017-05-12 04:51:55 +00001170 return Status("NativeProcessLinux::%s (): unexpected state %s specified "
1171 "for pid %" PRIu64 ", tid %" PRIu64,
1172 __FUNCTION__, StateAsCString(action->state), GetID(),
1173 thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001174 }
1175 }
1176
Zachary Turner97206d52017-05-12 04:51:55 +00001177 return Status();
Tamas Berghammere7708682015-04-22 10:00:23 +00001178}
1179
Zachary Turner97206d52017-05-12 04:51:55 +00001180Status NativeProcessLinux::Halt() {
1181 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001182
1183 if (kill(GetID(), SIGSTOP) != 0)
1184 error.SetErrorToErrno();
1185
1186 return error;
Tamas Berghammere7708682015-04-22 10:00:23 +00001187}
1188
Zachary Turner97206d52017-05-12 04:51:55 +00001189Status NativeProcessLinux::Detach() {
1190 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001191
1192 // Stop monitoring the inferior.
1193 m_sigchld_handle.reset();
1194
1195 // Tell ptrace to detach from the process.
1196 if (GetID() == LLDB_INVALID_PROCESS_ID)
1197 return error;
1198
1199 for (auto thread_sp : m_threads) {
Zachary Turner97206d52017-05-12 04:51:55 +00001200 Status e = Detach(thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001201 if (e.Fail())
1202 error =
1203 e; // Save the error, but still attempt to detach from other threads.
1204 }
1205
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001206 m_processor_trace_monitor.clear();
1207 m_pt_proces_trace_id = LLDB_INVALID_UID;
1208
Kate Stoneb9c1b512016-09-06 20:57:50 +00001209 return error;
1210}
1211
Zachary Turner97206d52017-05-12 04:51:55 +00001212Status NativeProcessLinux::Signal(int signo) {
1213 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001214
Pavel Labatha6321a82017-01-19 15:26:04 +00001215 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1216 LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo,
1217 Host::GetSignalAsCString(signo), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001218
1219 if (kill(GetID(), signo))
1220 error.SetErrorToErrno();
1221
1222 return error;
1223}
1224
Zachary Turner97206d52017-05-12 04:51:55 +00001225Status NativeProcessLinux::Interrupt() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001226 // Pick a running thread (or if none, a not-dead stopped thread) as
1227 // the chosen thread that will be the stop-reason thread.
Pavel Labatha6321a82017-01-19 15:26:04 +00001228 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001229
1230 NativeThreadProtocolSP running_thread_sp;
1231 NativeThreadProtocolSP stopped_thread_sp;
1232
Pavel Labatha6321a82017-01-19 15:26:04 +00001233 LLDB_LOG(log, "selecting running thread for interrupt target");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001234 for (auto thread_sp : m_threads) {
1235 // The thread shouldn't be null but lets just cover that here.
1236 if (!thread_sp)
1237 continue;
1238
1239 // If we have a running or stepping thread, we'll call that the
1240 // target of the interrupt.
1241 const auto thread_state = thread_sp->GetState();
1242 if (thread_state == eStateRunning || thread_state == eStateStepping) {
1243 running_thread_sp = thread_sp;
1244 break;
1245 } else if (!stopped_thread_sp && StateIsStoppedState(thread_state, true)) {
1246 // Remember the first non-dead stopped thread. We'll use that as a backup
1247 // if there are no running threads.
1248 stopped_thread_sp = thread_sp;
1249 }
1250 }
1251
1252 if (!running_thread_sp && !stopped_thread_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00001253 Status error("found no running/stepping or live stopped threads as target "
1254 "for interrupt");
Pavel Labatha6321a82017-01-19 15:26:04 +00001255 LLDB_LOG(log, "skipping due to error: {0}", error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001256
1257 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001258 }
1259
1260 NativeThreadProtocolSP deferred_signal_thread_sp =
1261 running_thread_sp ? running_thread_sp : stopped_thread_sp;
1262
Pavel Labatha6321a82017-01-19 15:26:04 +00001263 LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(),
1264 running_thread_sp ? "running" : "stopped",
1265 deferred_signal_thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001266
1267 StopRunningThreads(deferred_signal_thread_sp->GetID());
1268
Zachary Turner97206d52017-05-12 04:51:55 +00001269 return Status();
Todd Fialaaf245d12014-06-30 21:05:18 +00001270}
1271
Zachary Turner97206d52017-05-12 04:51:55 +00001272Status NativeProcessLinux::Kill() {
Pavel Labatha6321a82017-01-19 15:26:04 +00001273 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1274 LLDB_LOG(log, "pid {0}", GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +00001275
Zachary Turner97206d52017-05-12 04:51:55 +00001276 Status error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001277
Kate Stoneb9c1b512016-09-06 20:57:50 +00001278 switch (m_state) {
1279 case StateType::eStateInvalid:
1280 case StateType::eStateExited:
1281 case StateType::eStateCrashed:
1282 case StateType::eStateDetached:
1283 case StateType::eStateUnloaded:
1284 // Nothing to do - the process is already dead.
Pavel Labatha6321a82017-01-19 15:26:04 +00001285 LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
Pavel Labath8198db32017-01-24 11:48:25 +00001286 m_state);
Todd Fialaaf245d12014-06-30 21:05:18 +00001287 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001288
Kate Stoneb9c1b512016-09-06 20:57:50 +00001289 case StateType::eStateConnected:
1290 case StateType::eStateAttaching:
1291 case StateType::eStateLaunching:
1292 case StateType::eStateStopped:
1293 case StateType::eStateRunning:
1294 case StateType::eStateStepping:
1295 case StateType::eStateSuspended:
1296 // We can try to kill a process in these states.
1297 break;
1298 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001299
Kate Stoneb9c1b512016-09-06 20:57:50 +00001300 if (kill(GetID(), SIGKILL) != 0) {
1301 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +00001302 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001303 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001304
Kate Stoneb9c1b512016-09-06 20:57:50 +00001305 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001306}
1307
Zachary Turner97206d52017-05-12 04:51:55 +00001308static Status
Pavel Labath15930862017-03-21 13:49:45 +00001309ParseMemoryRegionInfoFromProcMapsLine(llvm::StringRef &maps_line,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001310 MemoryRegionInfo &memory_region_info) {
1311 memory_region_info.Clear();
Todd Fialaaf245d12014-06-30 21:05:18 +00001312
Pavel Labath15930862017-03-21 13:49:45 +00001313 StringExtractor line_extractor(maps_line);
Todd Fialaaf245d12014-06-30 21:05:18 +00001314
Kate Stoneb9c1b512016-09-06 20:57:50 +00001315 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode
1316 // pathname
1317 // perms: rwxp (letter is present if set, '-' if not, final character is
1318 // p=private, s=shared).
Todd Fialaaf245d12014-06-30 21:05:18 +00001319
Kate Stoneb9c1b512016-09-06 20:57:50 +00001320 // Parse out the starting address
1321 lldb::addr_t start_address = line_extractor.GetHexMaxU64(false, 0);
Todd Fialaaf245d12014-06-30 21:05:18 +00001322
Kate Stoneb9c1b512016-09-06 20:57:50 +00001323 // Parse out hyphen separating start and end address from range.
1324 if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != '-'))
Zachary Turner97206d52017-05-12 04:51:55 +00001325 return Status(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001326 "malformed /proc/{pid}/maps entry, missing dash between address range");
Todd Fialaaf245d12014-06-30 21:05:18 +00001327
Kate Stoneb9c1b512016-09-06 20:57:50 +00001328 // Parse out the ending address
1329 lldb::addr_t end_address = line_extractor.GetHexMaxU64(false, start_address);
Todd Fialaaf245d12014-06-30 21:05:18 +00001330
Kate Stoneb9c1b512016-09-06 20:57:50 +00001331 // Parse out the space after the address.
1332 if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != ' '))
Zachary Turner97206d52017-05-12 04:51:55 +00001333 return Status(
1334 "malformed /proc/{pid}/maps entry, missing space after range");
Todd Fialaaf245d12014-06-30 21:05:18 +00001335
Kate Stoneb9c1b512016-09-06 20:57:50 +00001336 // Save the range.
1337 memory_region_info.GetRange().SetRangeBase(start_address);
1338 memory_region_info.GetRange().SetRangeEnd(end_address);
Todd Fialaaf245d12014-06-30 21:05:18 +00001339
Kate Stoneb9c1b512016-09-06 20:57:50 +00001340 // Any memory region in /proc/{pid}/maps is by definition mapped into the
1341 // process.
1342 memory_region_info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
Howard Hellyerad007562016-07-07 08:21:28 +00001343
Kate Stoneb9c1b512016-09-06 20:57:50 +00001344 // Parse out each permission entry.
1345 if (line_extractor.GetBytesLeft() < 4)
Zachary Turner97206d52017-05-12 04:51:55 +00001346 return Status("malformed /proc/{pid}/maps entry, missing some portion of "
1347 "permissions");
Todd Fialaaf245d12014-06-30 21:05:18 +00001348
Kate Stoneb9c1b512016-09-06 20:57:50 +00001349 // Handle read permission.
1350 const char read_perm_char = line_extractor.GetChar();
1351 if (read_perm_char == 'r')
1352 memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eYes);
1353 else if (read_perm_char == '-')
1354 memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1355 else
Zachary Turner97206d52017-05-12 04:51:55 +00001356 return Status("unexpected /proc/{pid}/maps read permission char");
Todd Fialaaf245d12014-06-30 21:05:18 +00001357
Kate Stoneb9c1b512016-09-06 20:57:50 +00001358 // Handle write permission.
1359 const char write_perm_char = line_extractor.GetChar();
1360 if (write_perm_char == 'w')
1361 memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eYes);
1362 else if (write_perm_char == '-')
1363 memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1364 else
Zachary Turner97206d52017-05-12 04:51:55 +00001365 return Status("unexpected /proc/{pid}/maps write permission char");
Todd Fialaaf245d12014-06-30 21:05:18 +00001366
Kate Stoneb9c1b512016-09-06 20:57:50 +00001367 // Handle execute permission.
1368 const char exec_perm_char = line_extractor.GetChar();
1369 if (exec_perm_char == 'x')
1370 memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes);
1371 else if (exec_perm_char == '-')
1372 memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1373 else
Zachary Turner97206d52017-05-12 04:51:55 +00001374 return Status("unexpected /proc/{pid}/maps exec permission char");
Todd Fialaaf245d12014-06-30 21:05:18 +00001375
Kate Stoneb9c1b512016-09-06 20:57:50 +00001376 line_extractor.GetChar(); // Read the private bit
1377 line_extractor.SkipSpaces(); // Skip the separator
1378 line_extractor.GetHexMaxU64(false, 0); // Read the offset
1379 line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1380 line_extractor.GetChar(); // Read the device id separator
1381 line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1382 line_extractor.SkipSpaces(); // Skip the separator
1383 line_extractor.GetU64(0, 10); // Read the inode number
Tamas Berghammerd7d69f82016-07-22 12:55:35 +00001384
Kate Stoneb9c1b512016-09-06 20:57:50 +00001385 line_extractor.SkipSpaces();
1386 const char *name = line_extractor.Peek();
1387 if (name)
1388 memory_region_info.SetName(name);
Tamas Berghammerd7d69f82016-07-22 12:55:35 +00001389
Zachary Turner97206d52017-05-12 04:51:55 +00001390 return Status();
Todd Fialaaf245d12014-06-30 21:05:18 +00001391}
1392
Zachary Turner97206d52017-05-12 04:51:55 +00001393Status NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr,
1394 MemoryRegionInfo &range_info) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001395 // FIXME review that the final memory region returned extends to the end of
1396 // the virtual address space,
1397 // with no perms if it is not mapped.
Todd Fialaaf245d12014-06-30 21:05:18 +00001398
Kate Stoneb9c1b512016-09-06 20:57:50 +00001399 // Use an approach that reads memory regions from /proc/{pid}/maps.
1400 // Assume proc maps entries are in ascending order.
1401 // FIXME assert if we find differently.
Todd Fialaaf245d12014-06-30 21:05:18 +00001402
Kate Stoneb9c1b512016-09-06 20:57:50 +00001403 if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
1404 // We're done.
Zachary Turner97206d52017-05-12 04:51:55 +00001405 return Status("unsupported");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001406 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001407
Zachary Turner97206d52017-05-12 04:51:55 +00001408 Status error = PopulateMemoryRegionCache();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001409 if (error.Fail()) {
1410 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001411 }
1412
1413 lldb::addr_t prev_base_address = 0;
1414
1415 // FIXME start by finding the last region that is <= target address using
1416 // binary search. Data is sorted.
1417 // There can be a ton of regions on pthreads apps with lots of threads.
1418 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1419 ++it) {
Tamas Berghammera6f57952017-01-03 16:29:43 +00001420 MemoryRegionInfo &proc_entry_info = it->first;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001421
1422 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1423 assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
1424 "descending /proc/pid/maps entries detected, unexpected");
1425 prev_base_address = proc_entry_info.GetRange().GetRangeBase();
Hafiz Abid Qadeerb1554312017-01-20 10:24:03 +00001426 UNUSED_IF_ASSERT_DISABLED(prev_base_address);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001427
1428 // If the target address comes before this entry, indicate distance to next
1429 // region.
1430 if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1431 range_info.GetRange().SetRangeBase(load_addr);
1432 range_info.GetRange().SetByteSize(
1433 proc_entry_info.GetRange().GetRangeBase() - load_addr);
1434 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1435 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1436 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1437 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1438
1439 return error;
1440 } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1441 // The target address is within the memory region we're processing here.
1442 range_info = proc_entry_info;
1443 return error;
1444 }
1445
1446 // The target memory address comes somewhere after the region we just
1447 // parsed.
1448 }
1449
1450 // If we made it here, we didn't find an entry that contained the given
1451 // address. Return the
1452 // load_addr as start and the amount of bytes betwwen load address and the end
1453 // of the memory as
1454 // size.
1455 range_info.GetRange().SetRangeBase(load_addr);
1456 range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
1457 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1458 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1459 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1460 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1461 return error;
1462}
1463
Zachary Turner97206d52017-05-12 04:51:55 +00001464Status NativeProcessLinux::PopulateMemoryRegionCache() {
Pavel Labatha6321a82017-01-19 15:26:04 +00001465 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Tamas Berghammera6f57952017-01-03 16:29:43 +00001466
1467 // If our cache is empty, pull the latest. There should always be at least
1468 // one memory region if memory region handling is supported.
1469 if (!m_mem_region_cache.empty()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001470 LLDB_LOG(log, "reusing {0} cached memory region entries",
1471 m_mem_region_cache.size());
Zachary Turner97206d52017-05-12 04:51:55 +00001472 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001473 }
1474
Pavel Labath15930862017-03-21 13:49:45 +00001475 auto BufferOrError = getProcFile(GetID(), "maps");
1476 if (!BufferOrError) {
Tamas Berghammera6f57952017-01-03 16:29:43 +00001477 m_supports_mem_region = LazyBool::eLazyBoolNo;
Pavel Labath15930862017-03-21 13:49:45 +00001478 return BufferOrError.getError();
1479 }
1480 StringRef Rest = BufferOrError.get()->getBuffer();
1481 while (! Rest.empty()) {
1482 StringRef Line;
1483 std::tie(Line, Rest) = Rest.split('\n');
1484 MemoryRegionInfo info;
Zachary Turner97206d52017-05-12 04:51:55 +00001485 const Status parse_error =
1486 ParseMemoryRegionInfoFromProcMapsLine(Line, info);
Pavel Labath15930862017-03-21 13:49:45 +00001487 if (parse_error.Fail()) {
1488 LLDB_LOG(log, "failed to parse proc maps line '{0}': {1}", Line,
1489 parse_error);
1490 m_supports_mem_region = LazyBool::eLazyBoolNo;
1491 return parse_error;
1492 }
1493 m_mem_region_cache.emplace_back(
1494 info, FileSpec(info.GetName().GetCString(), true));
1495 }
1496
1497 if (m_mem_region_cache.empty()) {
Tamas Berghammera6f57952017-01-03 16:29:43 +00001498 // No entries after attempting to read them. This shouldn't happen if
1499 // /proc/{pid}/maps is supported. Assume we don't support map entries
1500 // via procfs.
Pavel Labath15930862017-03-21 13:49:45 +00001501 m_supports_mem_region = LazyBool::eLazyBoolNo;
Pavel Labatha6321a82017-01-19 15:26:04 +00001502 LLDB_LOG(log,
1503 "failed to find any procfs maps entries, assuming no support "
1504 "for memory region metadata retrieval");
Zachary Turner97206d52017-05-12 04:51:55 +00001505 return Status("not supported");
Tamas Berghammera6f57952017-01-03 16:29:43 +00001506 }
1507
Pavel Labatha6321a82017-01-19 15:26:04 +00001508 LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps",
1509 m_mem_region_cache.size(), GetID());
Tamas Berghammera6f57952017-01-03 16:29:43 +00001510
1511 // We support memory retrieval, remember that.
1512 m_supports_mem_region = LazyBool::eLazyBoolYes;
Zachary Turner97206d52017-05-12 04:51:55 +00001513 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001514}
1515
Kate Stoneb9c1b512016-09-06 20:57:50 +00001516void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001517 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1518 LLDB_LOG(log, "newBumpId={0}", newBumpId);
1519 LLDB_LOG(log, "clearing {0} entries from memory region cache",
1520 m_mem_region_cache.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001521 m_mem_region_cache.clear();
1522}
1523
Zachary Turner97206d52017-05-12 04:51:55 +00001524Status NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions,
1525 lldb::addr_t &addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001526// FIXME implementing this requires the equivalent of
1527// InferiorCallPOSIX::InferiorCallMmap, which depends on
1528// functional ThreadPlans working with Native*Protocol.
1529#if 1
Zachary Turner97206d52017-05-12 04:51:55 +00001530 return Status("not implemented yet");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001531#else
1532 addr = LLDB_INVALID_ADDRESS;
1533
1534 unsigned prot = 0;
1535 if (permissions & lldb::ePermissionsReadable)
1536 prot |= eMmapProtRead;
1537 if (permissions & lldb::ePermissionsWritable)
1538 prot |= eMmapProtWrite;
1539 if (permissions & lldb::ePermissionsExecutable)
1540 prot |= eMmapProtExec;
1541
1542 // TODO implement this directly in NativeProcessLinux
1543 // (and lift to NativeProcessPOSIX if/when that class is
1544 // refactored out).
1545 if (InferiorCallMmap(this, addr, 0, size, prot,
1546 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
1547 m_addr_to_mmap_size[addr] = size;
Zachary Turner97206d52017-05-12 04:51:55 +00001548 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001549 } else {
1550 addr = LLDB_INVALID_ADDRESS;
Zachary Turner97206d52017-05-12 04:51:55 +00001551 return Status("unable to allocate %" PRIu64
1552 " bytes of memory with permissions %s",
1553 size, GetPermissionsAsCString(permissions));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001554 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001555#endif
1556}
1557
Zachary Turner97206d52017-05-12 04:51:55 +00001558Status NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001559 // FIXME see comments in AllocateMemory - required lower-level
1560 // bits not in place yet (ThreadPlans)
Zachary Turner97206d52017-05-12 04:51:55 +00001561 return Status("not implemented");
Todd Fialaaf245d12014-06-30 21:05:18 +00001562}
1563
Kate Stoneb9c1b512016-09-06 20:57:50 +00001564lldb::addr_t NativeProcessLinux::GetSharedLibraryInfoAddress() {
1565 // punt on this for now
1566 return LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00001567}
1568
Kate Stoneb9c1b512016-09-06 20:57:50 +00001569size_t NativeProcessLinux::UpdateThreads() {
1570 // The NativeProcessLinux monitoring threads are always up to date
1571 // with respect to thread state and they keep the thread list
1572 // populated properly. All this method needs to do is return the
1573 // thread count.
1574 return m_threads.size();
Todd Fialaaf245d12014-06-30 21:05:18 +00001575}
1576
Kate Stoneb9c1b512016-09-06 20:57:50 +00001577bool NativeProcessLinux::GetArchitecture(ArchSpec &arch) const {
1578 arch = m_arch;
1579 return true;
Todd Fialaaf245d12014-06-30 21:05:18 +00001580}
1581
Zachary Turner97206d52017-05-12 04:51:55 +00001582Status NativeProcessLinux::GetSoftwareBreakpointPCOffset(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001583 uint32_t &actual_opcode_size) {
1584 // FIXME put this behind a breakpoint protocol class that can be
1585 // set per architecture. Need ARM, MIPS support here.
1586 static const uint8_t g_i386_opcode[] = {0xCC};
1587 static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
Todd Fialaaf245d12014-06-30 21:05:18 +00001588
Kate Stoneb9c1b512016-09-06 20:57:50 +00001589 switch (m_arch.GetMachine()) {
1590 case llvm::Triple::x86:
1591 case llvm::Triple::x86_64:
1592 actual_opcode_size = static_cast<uint32_t>(sizeof(g_i386_opcode));
Zachary Turner97206d52017-05-12 04:51:55 +00001593 return Status();
Todd Fialaaf245d12014-06-30 21:05:18 +00001594
Kate Stoneb9c1b512016-09-06 20:57:50 +00001595 case llvm::Triple::systemz:
1596 actual_opcode_size = static_cast<uint32_t>(sizeof(g_s390x_opcode));
Zachary Turner97206d52017-05-12 04:51:55 +00001597 return Status();
Ulrich Weigandbb00d0b2016-04-14 14:28:34 +00001598
Kate Stoneb9c1b512016-09-06 20:57:50 +00001599 case llvm::Triple::arm:
1600 case llvm::Triple::aarch64:
1601 case llvm::Triple::mips64:
1602 case llvm::Triple::mips64el:
1603 case llvm::Triple::mips:
1604 case llvm::Triple::mipsel:
1605 // On these architectures the PC don't get updated for breakpoint hits
1606 actual_opcode_size = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00001607 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001608
1609 default:
1610 assert(false && "CPU type not supported!");
Zachary Turner97206d52017-05-12 04:51:55 +00001611 return Status("CPU type not supported");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001612 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001613}
1614
Zachary Turner97206d52017-05-12 04:51:55 +00001615Status NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,
1616 bool hardware) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001617 if (hardware)
Omair Javaidd5ffbad2017-02-24 13:27:31 +00001618 return SetHardwareBreakpoint(addr, size);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001619 else
1620 return SetSoftwareBreakpoint(addr, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00001621}
1622
Zachary Turner97206d52017-05-12 04:51:55 +00001623Status NativeProcessLinux::RemoveBreakpoint(lldb::addr_t addr, bool hardware) {
Omair Javaidd5ffbad2017-02-24 13:27:31 +00001624 if (hardware)
1625 return RemoveHardwareBreakpoint(addr);
1626 else
1627 return NativeProcessProtocol::RemoveBreakpoint(addr);
1628}
1629
Zachary Turner97206d52017-05-12 04:51:55 +00001630Status NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001631 size_t trap_opcode_size_hint, size_t &actual_opcode_size,
1632 const uint8_t *&trap_opcode_bytes) {
1633 // FIXME put this behind a breakpoint protocol class that can be set per
1634 // architecture. Need MIPS support here.
1635 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};
1636 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1637 // linux kernel does otherwise.
1638 static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1639 static const uint8_t g_i386_opcode[] = {0xCC};
1640 static const uint8_t g_mips64_opcode[] = {0x00, 0x00, 0x00, 0x0d};
1641 static const uint8_t g_mips64el_opcode[] = {0x0d, 0x00, 0x00, 0x00};
1642 static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
1643 static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
Todd Fialaaf245d12014-06-30 21:05:18 +00001644
Kate Stoneb9c1b512016-09-06 20:57:50 +00001645 switch (m_arch.GetMachine()) {
1646 case llvm::Triple::aarch64:
1647 trap_opcode_bytes = g_aarch64_opcode;
1648 actual_opcode_size = sizeof(g_aarch64_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001649 return Status();
Todd Fiala2afc5962014-08-21 16:42:31 +00001650
Kate Stoneb9c1b512016-09-06 20:57:50 +00001651 case llvm::Triple::arm:
1652 switch (trap_opcode_size_hint) {
1653 case 2:
1654 trap_opcode_bytes = g_thumb_breakpoint_opcode;
1655 actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001656 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001657 case 4:
1658 trap_opcode_bytes = g_arm_breakpoint_opcode;
1659 actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001660 return Status();
Todd Fialaaf245d12014-06-30 21:05:18 +00001661 default:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001662 assert(false && "Unrecognised trap opcode size hint!");
Zachary Turner97206d52017-05-12 04:51:55 +00001663 return Status("Unrecognised trap opcode size hint!");
Todd Fialaaf245d12014-06-30 21:05:18 +00001664 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001665
1666 case llvm::Triple::x86:
1667 case llvm::Triple::x86_64:
1668 trap_opcode_bytes = g_i386_opcode;
1669 actual_opcode_size = sizeof(g_i386_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001670 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001671
1672 case llvm::Triple::mips:
1673 case llvm::Triple::mips64:
1674 trap_opcode_bytes = g_mips64_opcode;
1675 actual_opcode_size = sizeof(g_mips64_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001676 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001677
1678 case llvm::Triple::mipsel:
1679 case llvm::Triple::mips64el:
1680 trap_opcode_bytes = g_mips64el_opcode;
1681 actual_opcode_size = sizeof(g_mips64el_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001682 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001683
1684 case llvm::Triple::systemz:
1685 trap_opcode_bytes = g_s390x_opcode;
1686 actual_opcode_size = sizeof(g_s390x_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001687 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001688
1689 default:
1690 assert(false && "CPU type not supported!");
Zachary Turner97206d52017-05-12 04:51:55 +00001691 return Status("CPU type not supported");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001692 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001693}
1694
1695#if 0
1696ProcessMessage::CrashReason
1697NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
1698{
1699 ProcessMessage::CrashReason reason;
1700 assert(info->si_signo == SIGSEGV);
1701
1702 reason = ProcessMessage::eInvalidCrashReason;
1703
1704 switch (info->si_code)
1705 {
1706 default:
1707 assert(false && "unexpected si_code for SIGSEGV");
1708 break;
1709 case SI_KERNEL:
1710 // Linux will occasionally send spurious SI_KERNEL codes.
1711 // (this is poorly documented in sigaction)
1712 // One way to get this is via unaligned SIMD loads.
1713 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
1714 break;
1715 case SEGV_MAPERR:
1716 reason = ProcessMessage::eInvalidAddress;
1717 break;
1718 case SEGV_ACCERR:
1719 reason = ProcessMessage::ePrivilegedAddress;
1720 break;
1721 }
1722
1723 return reason;
1724}
1725#endif
1726
Todd Fialaaf245d12014-06-30 21:05:18 +00001727#if 0
1728ProcessMessage::CrashReason
1729NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
1730{
1731 ProcessMessage::CrashReason reason;
1732 assert(info->si_signo == SIGILL);
1733
1734 reason = ProcessMessage::eInvalidCrashReason;
1735
1736 switch (info->si_code)
1737 {
1738 default:
1739 assert(false && "unexpected si_code for SIGILL");
1740 break;
1741 case ILL_ILLOPC:
1742 reason = ProcessMessage::eIllegalOpcode;
1743 break;
1744 case ILL_ILLOPN:
1745 reason = ProcessMessage::eIllegalOperand;
1746 break;
1747 case ILL_ILLADR:
1748 reason = ProcessMessage::eIllegalAddressingMode;
1749 break;
1750 case ILL_ILLTRP:
1751 reason = ProcessMessage::eIllegalTrap;
1752 break;
1753 case ILL_PRVOPC:
1754 reason = ProcessMessage::ePrivilegedOpcode;
1755 break;
1756 case ILL_PRVREG:
1757 reason = ProcessMessage::ePrivilegedRegister;
1758 break;
1759 case ILL_COPROC:
1760 reason = ProcessMessage::eCoprocessorError;
1761 break;
1762 case ILL_BADSTK:
1763 reason = ProcessMessage::eInternalStackError;
1764 break;
1765 }
1766
1767 return reason;
1768}
1769#endif
1770
1771#if 0
1772ProcessMessage::CrashReason
1773NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
1774{
1775 ProcessMessage::CrashReason reason;
1776 assert(info->si_signo == SIGFPE);
1777
1778 reason = ProcessMessage::eInvalidCrashReason;
1779
1780 switch (info->si_code)
1781 {
1782 default:
1783 assert(false && "unexpected si_code for SIGFPE");
1784 break;
1785 case FPE_INTDIV:
1786 reason = ProcessMessage::eIntegerDivideByZero;
1787 break;
1788 case FPE_INTOVF:
1789 reason = ProcessMessage::eIntegerOverflow;
1790 break;
1791 case FPE_FLTDIV:
1792 reason = ProcessMessage::eFloatDivideByZero;
1793 break;
1794 case FPE_FLTOVF:
1795 reason = ProcessMessage::eFloatOverflow;
1796 break;
1797 case FPE_FLTUND:
1798 reason = ProcessMessage::eFloatUnderflow;
1799 break;
1800 case FPE_FLTRES:
1801 reason = ProcessMessage::eFloatInexactResult;
1802 break;
1803 case FPE_FLTINV:
1804 reason = ProcessMessage::eFloatInvalidOperation;
1805 break;
1806 case FPE_FLTSUB:
1807 reason = ProcessMessage::eFloatSubscriptRange;
1808 break;
1809 }
1810
1811 return reason;
1812}
1813#endif
1814
1815#if 0
1816ProcessMessage::CrashReason
1817NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
1818{
1819 ProcessMessage::CrashReason reason;
1820 assert(info->si_signo == SIGBUS);
1821
1822 reason = ProcessMessage::eInvalidCrashReason;
1823
1824 switch (info->si_code)
1825 {
1826 default:
1827 assert(false && "unexpected si_code for SIGBUS");
1828 break;
1829 case BUS_ADRALN:
1830 reason = ProcessMessage::eIllegalAlignment;
1831 break;
1832 case BUS_ADRERR:
1833 reason = ProcessMessage::eIllegalAddress;
1834 break;
1835 case BUS_OBJERR:
1836 reason = ProcessMessage::eHardwareError;
1837 break;
1838 }
1839
1840 return reason;
1841}
1842#endif
1843
Zachary Turner97206d52017-05-12 04:51:55 +00001844Status NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
1845 size_t &bytes_read) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001846 if (ProcessVmReadvSupported()) {
1847 // The process_vm_readv path is about 50 times faster than ptrace api. We
1848 // want to use
1849 // this syscall if it is supported.
Pavel Labathdf7c6992015-06-17 18:38:49 +00001850
Kate Stoneb9c1b512016-09-06 20:57:50 +00001851 const ::pid_t pid = GetID();
Pavel Labathdf7c6992015-06-17 18:38:49 +00001852
Kate Stoneb9c1b512016-09-06 20:57:50 +00001853 struct iovec local_iov, remote_iov;
1854 local_iov.iov_base = buf;
1855 local_iov.iov_len = size;
1856 remote_iov.iov_base = reinterpret_cast<void *>(addr);
1857 remote_iov.iov_len = size;
Pavel Labathdf7c6992015-06-17 18:38:49 +00001858
Kate Stoneb9c1b512016-09-06 20:57:50 +00001859 bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
1860 const bool success = bytes_read == size;
Pavel Labathdf7c6992015-06-17 18:38:49 +00001861
Pavel Labatha6321a82017-01-19 15:26:04 +00001862 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1863 LLDB_LOG(log,
1864 "using process_vm_readv to read {0} bytes from inferior "
1865 "address {1:x}: {2}",
Pavel Labath10c41f32017-06-06 14:06:17 +00001866 size, addr, success ? "Success" : llvm::sys::StrError(errno));
Pavel Labath19cbe962015-07-21 13:20:32 +00001867
Kate Stoneb9c1b512016-09-06 20:57:50 +00001868 if (success)
Zachary Turner97206d52017-05-12 04:51:55 +00001869 return Status();
Pavel Labatha6321a82017-01-19 15:26:04 +00001870 // else the call failed for some reason, let's retry the read using ptrace
1871 // api.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001872 }
Pavel Labath19cbe962015-07-21 13:20:32 +00001873
Kate Stoneb9c1b512016-09-06 20:57:50 +00001874 unsigned char *dst = static_cast<unsigned char *>(buf);
1875 size_t remainder;
1876 long data;
Pavel Labath19cbe962015-07-21 13:20:32 +00001877
Pavel Labatha6321a82017-01-19 15:26:04 +00001878 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1879 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
Pavel Labath19cbe962015-07-21 13:20:32 +00001880
Kate Stoneb9c1b512016-09-06 20:57:50 +00001881 for (bytes_read = 0; bytes_read < size; bytes_read += remainder) {
Zachary Turner97206d52017-05-12 04:51:55 +00001882 Status error = NativeProcessLinux::PtraceWrapper(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001883 PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data);
Pavel Labatha6321a82017-01-19 15:26:04 +00001884 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001885 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001886
1887 remainder = size - bytes_read;
1888 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
1889
1890 // Copy the data into our buffer
1891 memcpy(dst, &data, remainder);
1892
Pavel Labatha6321a82017-01-19 15:26:04 +00001893 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001894 addr += k_ptrace_word_size;
1895 dst += k_ptrace_word_size;
1896 }
Zachary Turner97206d52017-05-12 04:51:55 +00001897 return Status();
Todd Fialaaf245d12014-06-30 21:05:18 +00001898}
1899
Zachary Turner97206d52017-05-12 04:51:55 +00001900Status NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf,
1901 size_t size,
1902 size_t &bytes_read) {
1903 Status error = ReadMemory(addr, buf, size, bytes_read);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001904 if (error.Fail())
Pavel Labath19cbe962015-07-21 13:20:32 +00001905 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001906 return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00001907}
1908
Zachary Turner97206d52017-05-12 04:51:55 +00001909Status NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,
1910 size_t size, size_t &bytes_written) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001911 const unsigned char *src = static_cast<const unsigned char *>(buf);
1912 size_t remainder;
Zachary Turner97206d52017-05-12 04:51:55 +00001913 Status error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001914
Pavel Labatha6321a82017-01-19 15:26:04 +00001915 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1916 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00001917
Kate Stoneb9c1b512016-09-06 20:57:50 +00001918 for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
1919 remainder = size - bytes_written;
1920 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
Chaoren Lin97ccc292015-02-03 01:51:12 +00001921
Kate Stoneb9c1b512016-09-06 20:57:50 +00001922 if (remainder == k_ptrace_word_size) {
1923 unsigned long data = 0;
1924 memcpy(&data, src, k_ptrace_word_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00001925
Pavel Labatha6321a82017-01-19 15:26:04 +00001926 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001927 error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(),
1928 (void *)addr, (void *)data);
Pavel Labatha6321a82017-01-19 15:26:04 +00001929 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001930 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001931 } else {
1932 unsigned char buff[8];
1933 size_t bytes_read;
1934 error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
Pavel Labatha6321a82017-01-19 15:26:04 +00001935 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001936 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001937
1938 memcpy(buff, src, remainder);
1939
1940 size_t bytes_written_rec;
1941 error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
Pavel Labatha6321a82017-01-19 15:26:04 +00001942 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001943 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001944
Pavel Labatha6321a82017-01-19 15:26:04 +00001945 LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src,
1946 *(unsigned long *)buff);
Todd Fialaaf245d12014-06-30 21:05:18 +00001947 }
1948
Kate Stoneb9c1b512016-09-06 20:57:50 +00001949 addr += k_ptrace_word_size;
1950 src += k_ptrace_word_size;
1951 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001952 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001953}
1954
Zachary Turner97206d52017-05-12 04:51:55 +00001955Status NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001956 return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
1957}
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001958
Zachary Turner97206d52017-05-12 04:51:55 +00001959Status NativeProcessLinux::GetEventMessage(lldb::tid_t tid,
1960 unsigned long *message) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001961 return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
1962}
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001963
Zachary Turner97206d52017-05-12 04:51:55 +00001964Status NativeProcessLinux::Detach(lldb::tid_t tid) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001965 if (tid == LLDB_INVALID_THREAD_ID)
Zachary Turner97206d52017-05-12 04:51:55 +00001966 return Status();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001967
Kate Stoneb9c1b512016-09-06 20:57:50 +00001968 return PtraceWrapper(PTRACE_DETACH, tid);
1969}
1970
1971bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {
1972 for (auto thread_sp : m_threads) {
1973 assert(thread_sp && "thread list should not contain NULL threads");
1974 if (thread_sp->GetID() == thread_id) {
1975 // We have this thread.
1976 return true;
Todd Fialaaf245d12014-06-30 21:05:18 +00001977 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001978 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001979
Kate Stoneb9c1b512016-09-06 20:57:50 +00001980 // We don't have this thread.
1981 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001982}
1983
Kate Stoneb9c1b512016-09-06 20:57:50 +00001984bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001985 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1986 LLDB_LOG(log, "tid: {0})", thread_id);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001987
1988 bool found = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001989 for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
1990 if (*it && ((*it)->GetID() == thread_id)) {
1991 m_threads.erase(it);
1992 found = true;
1993 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00001994 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001995 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001996
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001997 if (found)
1998 StopTracingForThread(thread_id);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001999 SignalIfAllThreadsStopped();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002000 return found;
Todd Fialaaf245d12014-06-30 21:05:18 +00002001}
2002
Kate Stoneb9c1b512016-09-06 20:57:50 +00002003NativeThreadLinuxSP NativeProcessLinux::AddThread(lldb::tid_t thread_id) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002004 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
2005 LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
Todd Fialaaf245d12014-06-30 21:05:18 +00002006
Kate Stoneb9c1b512016-09-06 20:57:50 +00002007 assert(!HasThreadNoLock(thread_id) &&
2008 "attempted to add a thread by id that already exists");
Todd Fialaaf245d12014-06-30 21:05:18 +00002009
Kate Stoneb9c1b512016-09-06 20:57:50 +00002010 // If this is the first thread, save it as the current thread
2011 if (m_threads.empty())
2012 SetCurrentThreadID(thread_id);
Todd Fialaaf245d12014-06-30 21:05:18 +00002013
Kate Stoneb9c1b512016-09-06 20:57:50 +00002014 auto thread_sp = std::make_shared<NativeThreadLinux>(this, thread_id);
2015 m_threads.push_back(thread_sp);
Ravitheja Addepally99e37692017-06-28 07:58:31 +00002016
2017 if (m_pt_proces_trace_id != LLDB_INVALID_UID) {
2018 auto traceMonitor = ProcessorTraceMonitor::Create(
2019 GetID(), thread_id, m_pt_process_trace_config, true);
2020 if (traceMonitor) {
2021 m_pt_traced_thread_group.insert(thread_id);
2022 m_processor_trace_monitor.insert(
2023 std::make_pair(thread_id, std::move(*traceMonitor)));
2024 } else {
2025 LLDB_LOG(log, "failed to start trace on thread {0}", thread_id);
2026 Status error(traceMonitor.takeError());
2027 LLDB_LOG(log, "error {0}", error);
2028 }
2029 }
2030
Kate Stoneb9c1b512016-09-06 20:57:50 +00002031 return thread_sp;
2032}
Todd Fialaaf245d12014-06-30 21:05:18 +00002033
Zachary Turner97206d52017-05-12 04:51:55 +00002034Status
2035NativeProcessLinux::FixupBreakpointPCAsNeeded(NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002036 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_BREAKPOINTS));
Todd Fialaaf245d12014-06-30 21:05:18 +00002037
Zachary Turner97206d52017-05-12 04:51:55 +00002038 Status error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002039
Kate Stoneb9c1b512016-09-06 20:57:50 +00002040 // Find out the size of a breakpoint (might depend on where we are in the
2041 // code).
2042 NativeRegisterContextSP context_sp = thread.GetRegisterContext();
2043 if (!context_sp) {
2044 error.SetErrorString("cannot get a NativeRegisterContext for the thread");
Pavel Labatha6321a82017-01-19 15:26:04 +00002045 LLDB_LOG(log, "failed: {0}", error);
Todd Fialaaf245d12014-06-30 21:05:18 +00002046 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002047 }
Chaoren Linfa03ad22015-02-03 01:50:42 +00002048
Kate Stoneb9c1b512016-09-06 20:57:50 +00002049 uint32_t breakpoint_size = 0;
2050 error = GetSoftwareBreakpointPCOffset(breakpoint_size);
2051 if (error.Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002052 LLDB_LOG(log, "GetBreakpointSize() failed: {0}", error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002053 return error;
Pavel Labatha6321a82017-01-19 15:26:04 +00002054 } else
2055 LLDB_LOG(log, "breakpoint size: {0}", breakpoint_size);
Pavel Labathc0765592015-05-06 10:46:34 +00002056
Kate Stoneb9c1b512016-09-06 20:57:50 +00002057 // First try probing for a breakpoint at a software breakpoint location: PC -
2058 // breakpoint size.
2059 const lldb::addr_t initial_pc_addr =
2060 context_sp->GetPCfromBreakpointLocation();
2061 lldb::addr_t breakpoint_addr = initial_pc_addr;
2062 if (breakpoint_size > 0) {
2063 // Do not allow breakpoint probe to wrap around.
2064 if (breakpoint_addr >= breakpoint_size)
2065 breakpoint_addr -= breakpoint_size;
2066 }
2067
2068 // Check if we stopped because of a breakpoint.
2069 NativeBreakpointSP breakpoint_sp;
2070 error = m_breakpoint_list.GetBreakpoint(breakpoint_addr, breakpoint_sp);
2071 if (!error.Success() || !breakpoint_sp) {
2072 // We didn't find one at a software probe location. Nothing to do.
Pavel Labatha6321a82017-01-19 15:26:04 +00002073 LLDB_LOG(log,
2074 "pid {0} no lldb breakpoint found at current pc with "
2075 "adjustment: {1}",
2076 GetID(), breakpoint_addr);
Zachary Turner97206d52017-05-12 04:51:55 +00002077 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002078 }
2079
2080 // If the breakpoint is not a software breakpoint, nothing to do.
2081 if (!breakpoint_sp->IsSoftwareBreakpoint()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002082 LLDB_LOG(
2083 log,
2084 "pid {0} breakpoint found at {1:x}, not software, nothing to adjust",
2085 GetID(), breakpoint_addr);
Zachary Turner97206d52017-05-12 04:51:55 +00002086 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002087 }
2088
2089 //
2090 // We have a software breakpoint and need to adjust the PC.
2091 //
2092
2093 // Sanity check.
2094 if (breakpoint_size == 0) {
2095 // Nothing to do! How did we get here?
Pavel Labatha6321a82017-01-19 15:26:04 +00002096 LLDB_LOG(log,
2097 "pid {0} breakpoint found at {1:x}, it is software, but the "
2098 "size is zero, nothing to do (unexpected)",
2099 GetID(), breakpoint_addr);
Zachary Turner97206d52017-05-12 04:51:55 +00002100 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002101 }
2102
2103 // Change the program counter.
Pavel Labatha6321a82017-01-19 15:26:04 +00002104 LLDB_LOG(log, "pid {0} tid {1}: changing PC from {2:x} to {3:x}", GetID(),
2105 thread.GetID(), initial_pc_addr, breakpoint_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002106
2107 error = context_sp->SetPC(breakpoint_addr);
2108 if (error.Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002109 LLDB_LOG(log, "pid {0} tid {1}: failed to set PC: {2}", GetID(),
2110 thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002111 return error;
2112 }
2113
2114 return error;
2115}
2116
Zachary Turner97206d52017-05-12 04:51:55 +00002117Status NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,
2118 FileSpec &file_spec) {
2119 Status error = PopulateMemoryRegionCache();
Tamas Berghammera6f57952017-01-03 16:29:43 +00002120 if (error.Fail())
2121 return error;
2122
Kate Stoneb9c1b512016-09-06 20:57:50 +00002123 FileSpec module_file_spec(module_path, true);
2124
Kate Stoneb9c1b512016-09-06 20:57:50 +00002125 file_spec.Clear();
Tamas Berghammera6f57952017-01-03 16:29:43 +00002126 for (const auto &it : m_mem_region_cache) {
2127 if (it.second.GetFilename() == module_file_spec.GetFilename()) {
2128 file_spec = it.second;
Zachary Turner97206d52017-05-12 04:51:55 +00002129 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00002130 }
2131 }
Zachary Turner97206d52017-05-12 04:51:55 +00002132 return Status("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
2133 module_file_spec.GetFilename().AsCString(), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002134}
2135
Zachary Turner97206d52017-05-12 04:51:55 +00002136Status NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
2137 lldb::addr_t &load_addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002138 load_addr = LLDB_INVALID_ADDRESS;
Zachary Turner97206d52017-05-12 04:51:55 +00002139 Status error = PopulateMemoryRegionCache();
Tamas Berghammera6f57952017-01-03 16:29:43 +00002140 if (error.Fail())
2141 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002142
Tamas Berghammera6f57952017-01-03 16:29:43 +00002143 FileSpec file(file_name, false);
2144 for (const auto &it : m_mem_region_cache) {
2145 if (it.second == file) {
2146 load_addr = it.first.GetRange().GetRangeBase();
Zachary Turner97206d52017-05-12 04:51:55 +00002147 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00002148 }
2149 }
Zachary Turner97206d52017-05-12 04:51:55 +00002150 return Status("No load address found for specified file.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002151}
2152
2153NativeThreadLinuxSP NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {
2154 return std::static_pointer_cast<NativeThreadLinux>(
2155 NativeProcessProtocol::GetThreadByID(tid));
2156}
2157
Zachary Turner97206d52017-05-12 04:51:55 +00002158Status NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,
2159 lldb::StateType state, int signo) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002160 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2161 LLDB_LOG(log, "tid: {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002162
2163 // Before we do the resume below, first check if we have a pending
2164 // stop notification that is currently waiting for
2165 // all threads to stop. This is potentially a buggy situation since
2166 // we're ostensibly waiting for threads to stop before we send out the
2167 // pending notification, and here we are resuming one before we send
2168 // out the pending stop notification.
Pavel Labatha6321a82017-01-19 15:26:04 +00002169 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
2170 LLDB_LOG(log,
2171 "about to resume tid {0} per explicit request but we have a "
2172 "pending stop notification (tid {1}) that is actively "
2173 "waiting for this thread to stop. Valid sequence of events?",
2174 thread.GetID(), m_pending_notification_tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002175 }
2176
2177 // Request a resume. We expect this to be synchronous and the system
2178 // to reflect it is running after this completes.
2179 switch (state) {
2180 case eStateRunning: {
2181 const auto resume_result = thread.Resume(signo);
2182 if (resume_result.Success())
2183 SetState(eStateRunning, true);
2184 return resume_result;
2185 }
2186 case eStateStepping: {
2187 const auto step_result = thread.SingleStep(signo);
2188 if (step_result.Success())
2189 SetState(eStateRunning, true);
2190 return step_result;
2191 }
2192 default:
Pavel Labath8198db32017-01-24 11:48:25 +00002193 LLDB_LOG(log, "Unhandled state {0}.", state);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002194 llvm_unreachable("Unhandled state for resume");
2195 }
Pavel Labathc0765592015-05-06 10:46:34 +00002196}
2197
2198//===----------------------------------------------------------------------===//
2199
Kate Stoneb9c1b512016-09-06 20:57:50 +00002200void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002201 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2202 LLDB_LOG(log, "about to process event: (triggering_tid: {0})",
2203 triggering_tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002204
2205 m_pending_notification_tid = triggering_tid;
2206
2207 // Request a stop for all the thread stops that need to be stopped
2208 // and are not already known to be stopped.
2209 for (const auto &thread_sp : m_threads) {
2210 if (StateIsRunningState(thread_sp->GetState()))
2211 static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
2212 }
2213
2214 SignalIfAllThreadsStopped();
Pavel Labatha6321a82017-01-19 15:26:04 +00002215 LLDB_LOG(log, "event processing done");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002216}
2217
2218void NativeProcessLinux::SignalIfAllThreadsStopped() {
2219 if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
2220 return; // No pending notification. Nothing to do.
2221
2222 for (const auto &thread_sp : m_threads) {
2223 if (StateIsRunningState(thread_sp->GetState()))
2224 return; // Some threads are still running. Don't signal yet.
2225 }
2226
2227 // We have a pending notification and all threads have stopped.
2228 Log *log(
2229 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
2230
2231 // Clear any temporary breakpoints we used to implement software single
2232 // stepping.
2233 for (const auto &thread_info : m_threads_stepping_with_breakpoint) {
Zachary Turner97206d52017-05-12 04:51:55 +00002234 Status error = RemoveBreakpoint(thread_info.second);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002235 if (error.Fail())
Pavel Labatha6321a82017-01-19 15:26:04 +00002236 LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}",
2237 thread_info.first, error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002238 }
2239 m_threads_stepping_with_breakpoint.clear();
2240
2241 // Notify the delegate about the stop
2242 SetCurrentThreadID(m_pending_notification_tid);
2243 SetState(StateType::eStateStopped, true);
2244 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
2245}
2246
2247void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002248 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2249 LLDB_LOG(log, "tid: {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002250
2251 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID &&
2252 StateIsRunningState(thread.GetState())) {
2253 // We will need to wait for this new thread to stop as well before firing
2254 // the
2255 // notification.
2256 thread.RequestStop();
2257 }
2258}
2259
2260void NativeProcessLinux::SigchldHandler() {
Pavel Labatha6321a82017-01-19 15:26:04 +00002261 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002262 // Process all pending waitpid notifications.
2263 while (true) {
2264 int status = -1;
Pavel Labathc1a6b122017-07-03 09:25:55 +00002265 ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, -1, &status,
2266 __WALL | __WNOTHREAD | WNOHANG);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002267
2268 if (wait_pid == 0)
2269 break; // We are done.
2270
2271 if (wait_pid == -1) {
Zachary Turner97206d52017-05-12 04:51:55 +00002272 Status error(errno, eErrorTypePOSIX);
Pavel Labatha6321a82017-01-19 15:26:04 +00002273 LLDB_LOG(log, "waitpid (-1, &status, _) failed: {0}", error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002274 break;
Pavel Labathc0765592015-05-06 10:46:34 +00002275 }
2276
Pavel Labath3508fc82017-06-19 12:47:50 +00002277 WaitStatus wait_status = WaitStatus::Decode(status);
2278 bool exited = wait_status.type == WaitStatus::Exit ||
2279 (wait_status.type == WaitStatus::Signal &&
2280 wait_pid == static_cast<::pid_t>(GetID()));
Pavel Labathc0765592015-05-06 10:46:34 +00002281
Pavel Labath3508fc82017-06-19 12:47:50 +00002282 LLDB_LOG(
2283 log,
2284 "waitpid (-1, &status, _) => pid = {0}, status = {1}, exited = {2}",
2285 wait_pid, wait_status, exited);
Pavel Labathc0765592015-05-06 10:46:34 +00002286
Pavel Labath3508fc82017-06-19 12:47:50 +00002287 MonitorCallback(wait_pid, exited, wait_status);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002288 }
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002289}
2290
2291// Wrapper for ptrace to catch errors and log calls.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002292// Note that ptrace sets errno on error because -1 can be a valid result (i.e.
2293// for PTRACE_PEEK*)
Zachary Turner97206d52017-05-12 04:51:55 +00002294Status NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
2295 void *data, size_t data_size,
2296 long *result) {
2297 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002298 long int ret;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002299
Kate Stoneb9c1b512016-09-06 20:57:50 +00002300 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002301
Kate Stoneb9c1b512016-09-06 20:57:50 +00002302 PtraceDisplayBytes(req, data, data_size);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002303
Kate Stoneb9c1b512016-09-06 20:57:50 +00002304 errno = 0;
2305 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
2306 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2307 *(unsigned int *)addr, data);
2308 else
2309 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2310 addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002311
Kate Stoneb9c1b512016-09-06 20:57:50 +00002312 if (ret == -1)
2313 error.SetErrorToErrno();
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002314
Kate Stoneb9c1b512016-09-06 20:57:50 +00002315 if (result)
2316 *result = ret;
Pavel Labath4a9babb2015-06-30 17:04:49 +00002317
Pavel Labath28096202017-02-17 16:09:10 +00002318 LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data,
2319 data_size, ret);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002320
Kate Stoneb9c1b512016-09-06 20:57:50 +00002321 PtraceDisplayBytes(req, data, data_size);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002322
Pavel Labatha6321a82017-01-19 15:26:04 +00002323 if (error.Fail())
2324 LLDB_LOG(log, "ptrace() failed: {0}", error);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002325
Kate Stoneb9c1b512016-09-06 20:57:50 +00002326 return error;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002327}
Ravitheja Addepally99e37692017-06-28 07:58:31 +00002328
2329llvm::Expected<ProcessorTraceMonitor &>
2330NativeProcessLinux::LookupProcessorTraceInstance(lldb::user_id_t traceid,
2331 lldb::tid_t thread) {
2332 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2333 if (thread == LLDB_INVALID_THREAD_ID && traceid == m_pt_proces_trace_id) {
2334 LLDB_LOG(log, "thread not specified: {0}", traceid);
2335 return Status("tracing not active thread not specified").ToError();
2336 }
2337
2338 for (auto& iter : m_processor_trace_monitor) {
2339 if (traceid == iter.second->GetTraceID() &&
2340 (thread == iter.first || thread == LLDB_INVALID_THREAD_ID))
2341 return *(iter.second);
2342 }
2343
2344 LLDB_LOG(log, "traceid not being traced: {0}", traceid);
2345 return Status("tracing not active for this thread").ToError();
2346}
2347
2348Status NativeProcessLinux::GetMetaData(lldb::user_id_t traceid,
2349 lldb::tid_t thread,
2350 llvm::MutableArrayRef<uint8_t> &buffer,
2351 size_t offset) {
2352 TraceOptions trace_options;
2353 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2354 Status error;
2355
2356 LLDB_LOG(log, "traceid {0}", traceid);
2357
2358 auto perf_monitor = LookupProcessorTraceInstance(traceid, thread);
2359 if (!perf_monitor) {
2360 LLDB_LOG(log, "traceid not being traced: {0}", traceid);
2361 buffer = buffer.slice(buffer.size());
2362 error = perf_monitor.takeError();
2363 return error;
2364 }
2365 return (*perf_monitor).ReadPerfTraceData(buffer, offset);
2366}
2367
2368Status NativeProcessLinux::GetData(lldb::user_id_t traceid, lldb::tid_t thread,
2369 llvm::MutableArrayRef<uint8_t> &buffer,
2370 size_t offset) {
2371 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2372 Status error;
2373
2374 LLDB_LOG(log, "traceid {0}", traceid);
2375
2376 auto perf_monitor = LookupProcessorTraceInstance(traceid, thread);
2377 if (!perf_monitor) {
2378 LLDB_LOG(log, "traceid not being traced: {0}", traceid);
2379 buffer = buffer.slice(buffer.size());
2380 error = perf_monitor.takeError();
2381 return error;
2382 }
2383 return (*perf_monitor).ReadPerfTraceAux(buffer, offset);
2384}
2385
2386Status NativeProcessLinux::GetTraceConfig(lldb::user_id_t traceid,
2387 TraceOptions &config) {
2388 Status error;
2389 if (config.getThreadID() == LLDB_INVALID_THREAD_ID &&
2390 m_pt_proces_trace_id == traceid) {
2391 if (m_pt_proces_trace_id == LLDB_INVALID_UID) {
2392 error.SetErrorString("tracing not active for this process");
2393 return error;
2394 }
2395 config = m_pt_process_trace_config;
2396 } else {
2397 auto perf_monitor =
2398 LookupProcessorTraceInstance(traceid, config.getThreadID());
2399 if (!perf_monitor) {
2400 error = perf_monitor.takeError();
2401 return error;
2402 }
2403 error = (*perf_monitor).GetTraceConfig(config);
2404 }
2405 return error;
2406}
2407
2408lldb::user_id_t
2409NativeProcessLinux::StartTraceGroup(const TraceOptions &config,
2410 Status &error) {
2411
2412 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2413 if (config.getType() != TraceType::eTraceTypeProcessorTrace)
2414 return LLDB_INVALID_UID;
2415
2416 if (m_pt_proces_trace_id != LLDB_INVALID_UID) {
2417 error.SetErrorString("tracing already active on this process");
2418 return m_pt_proces_trace_id;
2419 }
2420
2421 for (const auto &thread_sp : m_threads) {
2422 if (auto traceInstance = ProcessorTraceMonitor::Create(
2423 GetID(), thread_sp->GetID(), config, true)) {
2424 m_pt_traced_thread_group.insert(thread_sp->GetID());
2425 m_processor_trace_monitor.insert(
2426 std::make_pair(thread_sp->GetID(), std::move(*traceInstance)));
2427 }
2428 }
2429
2430 m_pt_process_trace_config = config;
2431 error = ProcessorTraceMonitor::GetCPUType(m_pt_process_trace_config);
2432
2433 // Trace on Complete process will have traceid of 0
2434 m_pt_proces_trace_id = 0;
2435
2436 LLDB_LOG(log, "Process Trace ID {0}", m_pt_proces_trace_id);
2437 return m_pt_proces_trace_id;
2438}
2439
2440lldb::user_id_t NativeProcessLinux::StartTrace(const TraceOptions &config,
2441 Status &error) {
2442 if (config.getType() != TraceType::eTraceTypeProcessorTrace)
2443 return NativeProcessProtocol::StartTrace(config, error);
2444
2445 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2446
2447 lldb::tid_t threadid = config.getThreadID();
2448
2449 if (threadid == LLDB_INVALID_THREAD_ID)
2450 return StartTraceGroup(config, error);
2451
2452 auto thread_sp = GetThreadByID(threadid);
2453 if (!thread_sp) {
2454 // Thread not tracked by lldb so don't trace.
2455 error.SetErrorString("invalid thread id");
2456 return LLDB_INVALID_UID;
2457 }
2458
2459 const auto &iter = m_processor_trace_monitor.find(threadid);
2460 if (iter != m_processor_trace_monitor.end()) {
2461 LLDB_LOG(log, "Thread already being traced");
2462 error.SetErrorString("tracing already active on this thread");
2463 return LLDB_INVALID_UID;
2464 }
2465
2466 auto traceMonitor =
2467 ProcessorTraceMonitor::Create(GetID(), threadid, config, false);
2468 if (!traceMonitor) {
2469 error = traceMonitor.takeError();
2470 LLDB_LOG(log, "error {0}", error);
2471 return LLDB_INVALID_UID;
2472 }
2473 lldb::user_id_t ret_trace_id = (*traceMonitor)->GetTraceID();
2474 m_processor_trace_monitor.insert(
2475 std::make_pair(threadid, std::move(*traceMonitor)));
2476 return ret_trace_id;
2477}
2478
2479Status NativeProcessLinux::StopTracingForThread(lldb::tid_t thread) {
2480 Status error;
2481 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2482 LLDB_LOG(log, "Thread {0}", thread);
2483
2484 const auto& iter = m_processor_trace_monitor.find(thread);
2485 if (iter == m_processor_trace_monitor.end()) {
2486 error.SetErrorString("tracing not active for this thread");
2487 return error;
2488 }
2489
2490 if (iter->second->GetTraceID() == m_pt_proces_trace_id) {
2491 // traceid maps to the whole process so we have to erase it from the
2492 // thread group.
2493 LLDB_LOG(log, "traceid maps to process");
2494 m_pt_traced_thread_group.erase(thread);
2495 }
2496 m_processor_trace_monitor.erase(iter);
2497
2498 return error;
2499}
2500
2501Status NativeProcessLinux::StopTrace(lldb::user_id_t traceid,
2502 lldb::tid_t thread) {
2503 Status error;
2504
2505 TraceOptions trace_options;
2506 trace_options.setThreadID(thread);
2507 error = NativeProcessLinux::GetTraceConfig(traceid, trace_options);
2508
2509 if (error.Fail())
2510 return error;
2511
2512 switch (trace_options.getType()) {
2513 case lldb::TraceType::eTraceTypeProcessorTrace:
2514 if (traceid == m_pt_proces_trace_id &&
2515 thread == LLDB_INVALID_THREAD_ID)
2516 StopProcessorTracingOnProcess();
2517 else
2518 error = StopProcessorTracingOnThread(traceid, thread);
2519 break;
2520 default:
2521 error.SetErrorString("trace not supported");
2522 break;
2523 }
2524
2525 return error;
2526}
2527
2528void NativeProcessLinux::StopProcessorTracingOnProcess() {
2529 for (auto thread_id_iter : m_pt_traced_thread_group)
2530 m_processor_trace_monitor.erase(thread_id_iter);
2531 m_pt_traced_thread_group.clear();
2532 m_pt_proces_trace_id = LLDB_INVALID_UID;
2533}
2534
2535Status NativeProcessLinux::StopProcessorTracingOnThread(lldb::user_id_t traceid,
2536 lldb::tid_t thread) {
2537 Status error;
2538 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2539
2540 if (thread == LLDB_INVALID_THREAD_ID) {
2541 for (auto& iter : m_processor_trace_monitor) {
2542 if (iter.second->GetTraceID() == traceid) {
2543 // Stopping a trace instance for an individual thread
2544 // hence there will only be one traceid that can match.
2545 m_processor_trace_monitor.erase(iter.first);
2546 return error;
2547 }
2548 LLDB_LOG(log, "Trace ID {0}", iter.second->GetTraceID());
2549 }
2550
2551 LLDB_LOG(log, "Invalid TraceID");
2552 error.SetErrorString("invalid trace id");
2553 return error;
2554 }
2555
2556 // thread is specified so we can use find function on the map.
2557 const auto& iter = m_processor_trace_monitor.find(thread);
2558 if (iter == m_processor_trace_monitor.end()) {
2559 // thread not found in our map.
2560 LLDB_LOG(log, "thread not being traced");
2561 error.SetErrorString("tracing not active for this thread");
2562 return error;
2563 }
2564 if (iter->second->GetTraceID() != traceid) {
2565 // traceid did not match so it has to be invalid.
2566 LLDB_LOG(log, "Invalid TraceID");
2567 error.SetErrorString("invalid trace id");
2568 return error;
2569 }
2570
2571 LLDB_LOG(log, "UID - {0} , Thread -{1}", traceid, thread);
2572
2573 if (traceid == m_pt_proces_trace_id) {
2574 // traceid maps to the whole process so we have to erase it from the
2575 // thread group.
2576 LLDB_LOG(log, "traceid maps to process");
2577 m_pt_traced_thread_group.erase(thread);
2578 }
2579 m_processor_trace_monitor.erase(iter);
2580
2581 return error;
2582}