blob: 8c6c95380e814e2e05ac02421338962bcd0fef93 [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
Todd Fialaaf245d12014-06-30 21:05:18 +000012#include <errno.h>
Todd Fialaaf245d12014-06-30 21:05:18 +000013#include <stdint.h>
Kate Stoneb9c1b512016-09-06 20:57:50 +000014#include <string.h>
Todd Fialaaf245d12014-06-30 21:05:18 +000015#include <unistd.h>
Todd Fialaaf245d12014-06-30 21:05:18 +000016
Todd Fialaaf245d12014-06-30 21:05:18 +000017#include <fstream>
Pavel Labathdf7c6992015-06-17 18:38:49 +000018#include <mutex>
Pavel Labathc0765592015-05-06 10:46:34 +000019#include <sstream>
Todd Fialaaf245d12014-06-30 21:05:18 +000020#include <string>
Pavel Labath5b981ab2015-05-29 12:53:54 +000021#include <unordered_map>
Todd Fialaaf245d12014-06-30 21:05:18 +000022
Tamas Berghammerd8c338d2015-04-15 09:47:02 +000023#include "lldb/Core/EmulateInstruction.h"
Oleksiy Vyalov6edef202014-11-17 22:16:42 +000024#include "lldb/Core/ModuleSpec.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000025#include "lldb/Host/Host.h"
Pavel Labath5ad891f2016-07-21 14:54:03 +000026#include "lldb/Host/HostProcess.h"
Zachary Turner24ae6292017-02-16 19:38:21 +000027#include "lldb/Host/PseudoTerminal.h"
Zachary Turner39de3112014-09-09 20:54:56 +000028#include "lldb/Host/ThreadLauncher.h"
Pavel Labath2a86b552016-06-14 17:30:52 +000029#include "lldb/Host/common/NativeRegisterContext.h"
Pavel Labath4ee1c952017-02-06 18:36:58 +000030#include "lldb/Host/linux/Ptrace.h"
31#include "lldb/Host/linux/Uio.h"
Kamil Rytarowski816ae4b2017-02-01 14:30:40 +000032#include "lldb/Host/posix/ProcessLauncherPosixFork.h"
Pavel Labath2a86b552016-06-14 17:30:52 +000033#include "lldb/Symbol/ObjectFile.h"
Zachary Turner90aff472015-03-03 23:36:51 +000034#include "lldb/Target/Process.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000035#include "lldb/Target/ProcessLaunchInfo.h"
Pavel Labath5b981ab2015-05-29 12:53:54 +000036#include "lldb/Target/Target.h"
Chaoren Linc16f5dc2015-03-19 23:28:10 +000037#include "lldb/Utility/LLDBAssert.h"
Pavel Labathd821c992018-08-07 11:07:21 +000038#include "lldb/Utility/RegisterValue.h"
39#include "lldb/Utility/State.h"
Zachary Turner97206d52017-05-12 04:51:55 +000040#include "lldb/Utility/Status.h"
Pavel Labathf805e192015-07-07 10:08:41 +000041#include "lldb/Utility/StringExtractor.h"
Pavel Labath10c41f32017-06-06 14:06:17 +000042#include "llvm/Support/Errno.h"
43#include "llvm/Support/FileSystem.h"
44#include "llvm/Support/Threading.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000045
Todd Fialaaf245d12014-06-30 21:05:18 +000046#include "NativeThreadLinux.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000047#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
Pavel Labathc8e364e82018-12-15 13:38:16 +000048#include "Plugins/Process/Utility/LinuxProcMaps.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000049#include "Procfs.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000050
Tamas Berghammerd8584872015-02-06 10:57:40 +000051#include <linux/unistd.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000052#include <sys/socket.h>
Pavel Labathdf7c6992015-06-17 18:38:49 +000053#include <sys/syscall.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000054#include <sys/types.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000055#include <sys/user.h>
56#include <sys/wait.h>
57
Todd Fialaaf245d12014-06-30 21:05:18 +000058// Support hardware breakpoints in case it has not been defined
59#ifndef TRAP_HWBKPT
Kate Stoneb9c1b512016-09-06 20:57:50 +000060#define TRAP_HWBKPT 4
Todd Fialaaf245d12014-06-30 21:05:18 +000061#endif
62
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000063using namespace lldb;
64using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000065using namespace lldb_private::process_linux;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000066using namespace llvm;
67
Todd Fialaaf245d12014-06-30 21:05:18 +000068// Private bits we only need internally.
Pavel Labathdf7c6992015-06-17 18:38:49 +000069
Kate Stoneb9c1b512016-09-06 20:57:50 +000070static bool ProcessVmReadvSupported() {
71 static bool is_supported;
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000072 static llvm::once_flag flag;
Pavel Labathdf7c6992015-06-17 18:38:49 +000073
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000074 llvm::call_once(flag, [] {
Pavel Labatha6321a82017-01-19 15:26:04 +000075 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Pavel Labath4abe5d62016-07-15 10:18:15 +000076
Kate Stoneb9c1b512016-09-06 20:57:50 +000077 uint32_t source = 0x47424742;
78 uint32_t dest = 0;
Pavel Labath4abe5d62016-07-15 10:18:15 +000079
Kate Stoneb9c1b512016-09-06 20:57:50 +000080 struct iovec local, remote;
81 remote.iov_base = &source;
82 local.iov_base = &dest;
83 remote.iov_len = local.iov_len = sizeof source;
Pavel Labath4abe5d62016-07-15 10:18:15 +000084
Kate Stoneb9c1b512016-09-06 20:57:50 +000085 // We shall try if cross-process-memory reads work by attempting to read a
86 // value from our own process.
87 ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
88 is_supported = (res == sizeof(source) && source == dest);
Pavel Labatha6321a82017-01-19 15:26:04 +000089 if (is_supported)
90 LLDB_LOG(log,
91 "Detected kernel support for process_vm_readv syscall. "
92 "Fast memory reads enabled.");
93 else
94 LLDB_LOG(log,
95 "syscall process_vm_readv failed (error: {0}). Fast memory "
96 "reads disabled.",
Pavel Labath10c41f32017-06-06 14:06:17 +000097 llvm::sys::StrError());
Kate Stoneb9c1b512016-09-06 20:57:50 +000098 });
Pavel Labath4abe5d62016-07-15 10:18:15 +000099
Kate Stoneb9c1b512016-09-06 20:57:50 +0000100 return is_supported;
Pavel Labath4abe5d62016-07-15 10:18:15 +0000101}
102
Kate Stoneb9c1b512016-09-06 20:57:50 +0000103namespace {
104void MaybeLogLaunchInfo(const ProcessLaunchInfo &info) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000105 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000106 if (!log)
107 return;
108
109 if (const FileAction *action = info.GetFileActionForFD(STDIN_FILENO))
Pavel Labatha6321a82017-01-19 15:26:04 +0000110 LLDB_LOG(log, "setting STDIN to '{0}'", action->GetFileSpec());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000111 else
Pavel Labatha6321a82017-01-19 15:26:04 +0000112 LLDB_LOG(log, "leaving STDIN as is");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000113
114 if (const FileAction *action = info.GetFileActionForFD(STDOUT_FILENO))
Pavel Labatha6321a82017-01-19 15:26:04 +0000115 LLDB_LOG(log, "setting STDOUT to '{0}'", action->GetFileSpec());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000116 else
Pavel Labatha6321a82017-01-19 15:26:04 +0000117 LLDB_LOG(log, "leaving STDOUT as is");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000118
119 if (const FileAction *action = info.GetFileActionForFD(STDERR_FILENO))
Pavel Labatha6321a82017-01-19 15:26:04 +0000120 LLDB_LOG(log, "setting STDERR to '{0}'", action->GetFileSpec());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000121 else
Pavel Labatha6321a82017-01-19 15:26:04 +0000122 LLDB_LOG(log, "leaving STDERR as is");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000123
124 int i = 0;
125 for (const char **args = info.GetArguments().GetConstArgumentVector(); *args;
126 ++args, ++i)
Pavel Labatha6321a82017-01-19 15:26:04 +0000127 LLDB_LOG(log, "arg {0}: '{1}'", i, *args);
Pavel Labath4abe5d62016-07-15 10:18:15 +0000128}
Todd Fialaaf245d12014-06-30 21:05:18 +0000129
Kate Stoneb9c1b512016-09-06 20:57:50 +0000130void DisplayBytes(StreamString &s, void *bytes, uint32_t count) {
131 uint8_t *ptr = (uint8_t *)bytes;
132 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
133 for (uint32_t i = 0; i < loop_count; i++) {
134 s.Printf("[%x]", *ptr);
135 ptr++;
136 }
137}
Todd Fialaaf245d12014-06-30 21:05:18 +0000138
Kate Stoneb9c1b512016-09-06 20:57:50 +0000139void PtraceDisplayBytes(int &req, void *data, size_t data_size) {
Pavel Labathaafe0532017-02-06 19:31:05 +0000140 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
Pavel Labatha6321a82017-01-19 15:26:04 +0000141 if (!log)
142 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000143 StreamString buf;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000144
Pavel Labatha6321a82017-01-19 15:26:04 +0000145 switch (req) {
146 case PTRACE_POKETEXT: {
147 DisplayBytes(buf, &data, 8);
Pavel Labathaafe0532017-02-06 19:31:05 +0000148 LLDB_LOGV(log, "PTRACE_POKETEXT {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000149 break;
150 }
151 case PTRACE_POKEDATA: {
152 DisplayBytes(buf, &data, 8);
Pavel Labathaafe0532017-02-06 19:31:05 +0000153 LLDB_LOGV(log, "PTRACE_POKEDATA {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000154 break;
155 }
156 case PTRACE_POKEUSER: {
157 DisplayBytes(buf, &data, 8);
Pavel Labathaafe0532017-02-06 19:31:05 +0000158 LLDB_LOGV(log, "PTRACE_POKEUSER {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000159 break;
160 }
161 case PTRACE_SETREGS: {
162 DisplayBytes(buf, data, data_size);
Pavel Labathaafe0532017-02-06 19:31:05 +0000163 LLDB_LOGV(log, "PTRACE_SETREGS {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000164 break;
165 }
166 case PTRACE_SETFPREGS: {
167 DisplayBytes(buf, data, data_size);
Pavel Labathaafe0532017-02-06 19:31:05 +0000168 LLDB_LOGV(log, "PTRACE_SETFPREGS {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000169 break;
170 }
171 case PTRACE_SETSIGINFO: {
172 DisplayBytes(buf, data, sizeof(siginfo_t));
Pavel Labathaafe0532017-02-06 19:31:05 +0000173 LLDB_LOGV(log, "PTRACE_SETSIGINFO {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000174 break;
175 }
176 case PTRACE_SETREGSET: {
Pavel Labath11edb4e2017-12-01 12:05:00 +0000177 // Extract iov_base from data, which is a pointer to the struct iovec
Pavel Labatha6321a82017-01-19 15:26:04 +0000178 DisplayBytes(buf, *(void **)data, data_size);
Pavel Labathaafe0532017-02-06 19:31:05 +0000179 LLDB_LOGV(log, "PTRACE_SETREGSET {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000180 break;
181 }
182 default: {}
Kate Stoneb9c1b512016-09-06 20:57:50 +0000183 }
184}
Todd Fialaaf245d12014-06-30 21:05:18 +0000185
Kate Stoneb9c1b512016-09-06 20:57:50 +0000186static constexpr unsigned k_ptrace_word_size = sizeof(void *);
187static_assert(sizeof(long) >= k_ptrace_word_size,
188 "Size of long must be larger than ptrace word size");
Pavel Labath1107b5a2015-04-17 14:07:49 +0000189} // end of anonymous namespace
190
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000191// Simple helper function to ensure flags are enabled on the given file
192// descriptor.
Zachary Turner97206d52017-05-12 04:51:55 +0000193static Status EnsureFDFlags(int fd, int flags) {
194 Status error;
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000195
Kate Stoneb9c1b512016-09-06 20:57:50 +0000196 int status = fcntl(fd, F_GETFL);
197 if (status == -1) {
198 error.SetErrorToErrno();
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000199 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000200 }
201
202 if (fcntl(fd, F_SETFL, status | flags) == -1) {
203 error.SetErrorToErrno();
204 return error;
205 }
206
207 return error;
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000208}
209
Todd Fialaaf245d12014-06-30 21:05:18 +0000210// -----------------------------------------------------------------------------
211// Public Static Methods
212// -----------------------------------------------------------------------------
213
Pavel Labath82abefa2017-07-18 09:24:48 +0000214llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
Pavel Labath96e600f2017-07-07 11:02:19 +0000215NativeProcessLinux::Factory::Launch(ProcessLaunchInfo &launch_info,
216 NativeDelegate &native_delegate,
217 MainLoop &mainloop) const {
Pavel Labatha6321a82017-01-19 15:26:04 +0000218 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Todd Fialaaf245d12014-06-30 21:05:18 +0000219
Pavel Labath96e600f2017-07-07 11:02:19 +0000220 MaybeLogLaunchInfo(launch_info);
Todd Fialaaf245d12014-06-30 21:05:18 +0000221
Pavel Labath96e600f2017-07-07 11:02:19 +0000222 Status status;
223 ::pid_t pid = ProcessLauncherPosixFork()
224 .LaunchProcess(launch_info, status)
225 .GetProcessId();
226 LLDB_LOG(log, "pid = {0:x}", pid);
227 if (status.Fail()) {
228 LLDB_LOG(log, "failed to launch process: {0}", status);
229 return status.ToError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000230 }
231
Pavel Labath96e600f2017-07-07 11:02:19 +0000232 // Wait for the child process to trap on its call to execve.
233 int wstatus;
234 ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0);
235 assert(wpid == pid);
236 (void)wpid;
237 if (!WIFSTOPPED(wstatus)) {
238 LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}",
239 WaitStatus::Decode(wstatus));
240 return llvm::make_error<StringError>("Could not sync with inferior process",
241 llvm::inconvertibleErrorCode());
242 }
243 LLDB_LOG(log, "inferior started, now in stopped state");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000244
Pavel Labath36e82202018-01-29 10:46:00 +0000245 ProcessInstanceInfo Info;
246 if (!Host::GetProcessInfo(pid, Info)) {
247 return llvm::make_error<StringError>("Cannot get process architecture",
248 llvm::inconvertibleErrorCode());
249 }
Pavel Labath96e600f2017-07-07 11:02:19 +0000250
251 // Set the architecture to the exe architecture.
252 LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid,
Pavel Labath36e82202018-01-29 10:46:00 +0000253 Info.GetArchitecture().GetArchitectureName());
Pavel Labath96e600f2017-07-07 11:02:19 +0000254
255 status = SetDefaultPtraceOpts(pid);
256 if (status.Fail()) {
257 LLDB_LOG(log, "failed to set default ptrace options: {0}", status);
258 return status.ToError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000259 }
260
Pavel Labath82abefa2017-07-18 09:24:48 +0000261 return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
Pavel Labath96e600f2017-07-07 11:02:19 +0000262 pid, launch_info.GetPTY().ReleaseMasterFileDescriptor(), native_delegate,
Pavel Labath36e82202018-01-29 10:46:00 +0000263 Info.GetArchitecture(), mainloop, {pid}));
Todd Fialaaf245d12014-06-30 21:05:18 +0000264}
265
Pavel Labath82abefa2017-07-18 09:24:48 +0000266llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
267NativeProcessLinux::Factory::Attach(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000268 lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
Pavel Labath96e600f2017-07-07 11:02:19 +0000269 MainLoop &mainloop) const {
Pavel Labatha6321a82017-01-19 15:26:04 +0000270 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
271 LLDB_LOG(log, "pid = {0:x}", pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000272
Kate Stoneb9c1b512016-09-06 20:57:50 +0000273 // Retrieve the architecture for the running process.
Pavel Labath36e82202018-01-29 10:46:00 +0000274 ProcessInstanceInfo Info;
275 if (!Host::GetProcessInfo(pid, Info)) {
276 return llvm::make_error<StringError>("Cannot get process architecture",
277 llvm::inconvertibleErrorCode());
278 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000279
Pavel Labath96e600f2017-07-07 11:02:19 +0000280 auto tids_or = NativeProcessLinux::Attach(pid);
281 if (!tids_or)
282 return tids_or.takeError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000283
Pavel Labath82abefa2017-07-18 09:24:48 +0000284 return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
Pavel Labath36e82202018-01-29 10:46:00 +0000285 pid, -1, native_delegate, Info.GetArchitecture(), mainloop, *tids_or));
Todd Fialaaf245d12014-06-30 21:05:18 +0000286}
287
288// -----------------------------------------------------------------------------
289// Public Instance Methods
290// -----------------------------------------------------------------------------
291
Pavel Labath96e600f2017-07-07 11:02:19 +0000292NativeProcessLinux::NativeProcessLinux(::pid_t pid, int terminal_fd,
293 NativeDelegate &delegate,
Pavel Labath82abefa2017-07-18 09:24:48 +0000294 const ArchSpec &arch, MainLoop &mainloop,
295 llvm::ArrayRef<::pid_t> tids)
Pavel Labath96e600f2017-07-07 11:02:19 +0000296 : NativeProcessProtocol(pid, terminal_fd, delegate), m_arch(arch) {
297 if (m_terminal_fd != -1) {
298 Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
299 assert(status.Success());
300 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000301
Pavel Labath96e600f2017-07-07 11:02:19 +0000302 Status status;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000303 m_sigchld_handle = mainloop.RegisterSignal(
Pavel Labath96e600f2017-07-07 11:02:19 +0000304 SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status);
305 assert(m_sigchld_handle && status.Success());
Todd Fialaaf245d12014-06-30 21:05:18 +0000306
Pavel Labath96e600f2017-07-07 11:02:19 +0000307 for (const auto &tid : tids) {
Pavel Labatha5be48b2017-10-17 15:52:16 +0000308 NativeThreadLinux &thread = AddThread(tid);
309 thread.SetStoppedBySignal(SIGSTOP);
310 ThreadWasCreated(thread);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000311 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000312
Kate Stoneb9c1b512016-09-06 20:57:50 +0000313 // Let our process instance know the thread has stopped.
Pavel Labath96e600f2017-07-07 11:02:19 +0000314 SetCurrentThreadID(tids[0]);
315 SetState(StateType::eStateStopped, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000316
Pavel Labath96e600f2017-07-07 11:02:19 +0000317 // Proccess any signals we received before installing our handler
318 SigchldHandler();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000319}
320
Pavel Labath96e600f2017-07-07 11:02:19 +0000321llvm::Expected<std::vector<::pid_t>> NativeProcessLinux::Attach(::pid_t pid) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000322 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000323
Pavel Labath96e600f2017-07-07 11:02:19 +0000324 Status status;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000325 // Use a map to keep track of the threads which we have attached/need to
326 // attach.
327 Host::TidMap tids_to_attach;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000328 while (Host::FindProcessThreads(pid, tids_to_attach)) {
329 for (Host::TidMap::iterator it = tids_to_attach.begin();
330 it != tids_to_attach.end();) {
331 if (it->second == false) {
332 lldb::tid_t tid = it->first;
333
334 // Attach to the requested process.
335 // An attach will cause the thread to stop with a SIGSTOP.
Pavel Labath96e600f2017-07-07 11:02:19 +0000336 if ((status = PtraceWrapper(PTRACE_ATTACH, tid)).Fail()) {
Adrian Prantl05097242018-04-30 16:49:04 +0000337 // No such thread. The thread may have exited. More error handling
338 // may be needed.
Pavel Labath96e600f2017-07-07 11:02:19 +0000339 if (status.GetError() == ESRCH) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000340 it = tids_to_attach.erase(it);
341 continue;
Pavel Labath96e600f2017-07-07 11:02:19 +0000342 }
343 return status.ToError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000344 }
345
Pavel Labath96e600f2017-07-07 11:02:19 +0000346 int wpid =
347 llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, nullptr, __WALL);
Adrian Prantl05097242018-04-30 16:49:04 +0000348 // Need to use __WALL otherwise we receive an error with errno=ECHLD At
349 // this point we should have a thread stopped if waitpid succeeds.
Pavel Labath96e600f2017-07-07 11:02:19 +0000350 if (wpid < 0) {
Adrian Prantl05097242018-04-30 16:49:04 +0000351 // No such thread. The thread may have exited. More error handling
352 // may be needed.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000353 if (errno == ESRCH) {
354 it = tids_to_attach.erase(it);
355 continue;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000356 }
Pavel Labath96e600f2017-07-07 11:02:19 +0000357 return llvm::errorCodeToError(
358 std::error_code(errno, std::generic_category()));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000359 }
360
Pavel Labath96e600f2017-07-07 11:02:19 +0000361 if ((status = SetDefaultPtraceOpts(tid)).Fail())
362 return status.ToError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000363
Pavel Labatha6321a82017-01-19 15:26:04 +0000364 LLDB_LOG(log, "adding tid = {0}", tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000365 it->second = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000366 }
367
368 // move the loop forward
369 ++it;
370 }
371 }
372
Pavel Labath96e600f2017-07-07 11:02:19 +0000373 size_t tid_count = tids_to_attach.size();
374 if (tid_count == 0)
375 return llvm::make_error<StringError>("No such process",
376 llvm::inconvertibleErrorCode());
Todd Fialaaf245d12014-06-30 21:05:18 +0000377
Pavel Labath96e600f2017-07-07 11:02:19 +0000378 std::vector<::pid_t> tids;
379 tids.reserve(tid_count);
380 for (const auto &p : tids_to_attach)
381 tids.push_back(p.first);
382 return std::move(tids);
Todd Fialaaf245d12014-06-30 21:05:18 +0000383}
384
Zachary Turner97206d52017-05-12 04:51:55 +0000385Status NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000386 long ptrace_opts = 0;
Todd Fialaaf245d12014-06-30 21:05:18 +0000387
Kate Stoneb9c1b512016-09-06 20:57:50 +0000388 // Have the child raise an event on exit. This is used to keep the child in
389 // limbo until it is destroyed.
390 ptrace_opts |= PTRACE_O_TRACEEXIT;
Todd Fialaaf245d12014-06-30 21:05:18 +0000391
Kate Stoneb9c1b512016-09-06 20:57:50 +0000392 // Have the tracer trace threads which spawn in the inferior process.
393 // TODO: if we want to support tracing the inferiors' child, add the
394 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
395 ptrace_opts |= PTRACE_O_TRACECLONE;
Todd Fialaaf245d12014-06-30 21:05:18 +0000396
Adrian Prantl05097242018-04-30 16:49:04 +0000397 // Have the tracer notify us before execve returns (needed to disable legacy
398 // SIGTRAP generation)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000399 ptrace_opts |= PTRACE_O_TRACEEXEC;
Todd Fialaaf245d12014-06-30 21:05:18 +0000400
Kate Stoneb9c1b512016-09-06 20:57:50 +0000401 return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void *)ptrace_opts);
Todd Fialaaf245d12014-06-30 21:05:18 +0000402}
403
Pavel Labath1107b5a2015-04-17 14:07:49 +0000404// Handles all waitpid events from the inferior process.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000405void NativeProcessLinux::MonitorCallback(lldb::pid_t pid, bool exited,
Pavel Labath3508fc82017-06-19 12:47:50 +0000406 WaitStatus status) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000407 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Todd Fialaaf245d12014-06-30 21:05:18 +0000408
Kate Stoneb9c1b512016-09-06 20:57:50 +0000409 // Certain activities differ based on whether the pid is the tid of the main
410 // thread.
411 const bool is_main_thread = (pid == GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000412
Kate Stoneb9c1b512016-09-06 20:57:50 +0000413 // Handle when the thread exits.
414 if (exited) {
Pavel Labathd8b3c1a2017-12-18 09:44:29 +0000415 LLDB_LOG(log,
416 "got exit signal({0}) , tid = {1} ({2} main thread), process "
417 "state = {3}",
418 signal, pid, is_main_thread ? "is" : "is not", GetState());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000419
420 // This is a thread that exited. Ensure we're not tracking it anymore.
Pavel Labathd8b3c1a2017-12-18 09:44:29 +0000421 StopTrackingThread(pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000422
423 if (is_main_thread) {
Pavel Labathd8b3c1a2017-12-18 09:44:29 +0000424 // The main thread exited. We're done monitoring. Report to delegate.
425 SetExitStatus(status, true);
Todd Fialaaf245d12014-06-30 21:05:18 +0000426
Pavel Labathd8b3c1a2017-12-18 09:44:29 +0000427 // Notify delegate that our process has exited.
428 SetState(StateType::eStateExited, true);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000429 }
430 return;
431 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000432
Kate Stoneb9c1b512016-09-06 20:57:50 +0000433 siginfo_t info;
434 const auto info_err = GetSignalInfo(pid, &info);
435 auto thread_sp = GetThreadByID(pid);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000436
Kate Stoneb9c1b512016-09-06 20:57:50 +0000437 if (!thread_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +0000438 // Normally, the only situation when we cannot find the thread is if we
439 // have just received a new thread notification. This is indicated by
Pavel Labatha6321a82017-01-19 15:26:04 +0000440 // GetSignalInfo() returning si_code == SI_USER and si_pid == 0
441 LLDB_LOG(log, "received notification about an unknown tid {0}.", pid);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000442
Kate Stoneb9c1b512016-09-06 20:57:50 +0000443 if (info_err.Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000444 LLDB_LOG(log,
445 "(tid {0}) GetSignalInfo failed ({1}). "
446 "Ingoring this notification.",
447 pid, info_err);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000448 return;
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000449 }
450
Pavel Labatha6321a82017-01-19 15:26:04 +0000451 LLDB_LOG(log, "tid {0}, si_code: {1}, si_pid: {2}", pid, info.si_code,
452 info.si_pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000453
Pavel Labatha5be48b2017-10-17 15:52:16 +0000454 NativeThreadLinux &thread = AddThread(pid);
Ravitheja Addepally99e37692017-06-28 07:58:31 +0000455
Kate Stoneb9c1b512016-09-06 20:57:50 +0000456 // Resume the newly created thread.
Pavel Labatha5be48b2017-10-17 15:52:16 +0000457 ResumeThread(thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
458 ThreadWasCreated(thread);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000459 return;
460 }
461
462 // Get details on the signal raised.
463 if (info_err.Success()) {
464 // We have retrieved the signal info. Dispatch appropriately.
465 if (info.si_signo == SIGTRAP)
466 MonitorSIGTRAP(info, *thread_sp);
Chaoren Linfa03ad22015-02-03 01:50:42 +0000467 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000468 MonitorSignal(info, *thread_sp, exited);
469 } else {
470 if (info_err.GetError() == EINVAL) {
Adrian Prantl05097242018-04-30 16:49:04 +0000471 // This is a group stop reception for this tid. We can reach here if we
472 // reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the tracee,
473 // triggering the group-stop mechanism. Normally receiving these would
474 // stop the process, pending a SIGCONT. Simulating this state in a
475 // debugger is hard and is generally not needed (one use case is
476 // debugging background task being managed by a shell). For general use,
477 // it is sufficient to stop the process in a signal-delivery stop which
478 // happens before the group stop. This done by MonitorSignal and works
479 // correctly for all signals.
Pavel Labatha6321a82017-01-19 15:26:04 +0000480 LLDB_LOG(log,
481 "received a group stop for pid {0} tid {1}. Transparent "
482 "handling of group stops not supported, resuming the "
483 "thread.",
484 GetID(), pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000485 ResumeThread(*thread_sp, thread_sp->GetState(),
486 LLDB_INVALID_SIGNAL_NUMBER);
487 } else {
488 // ptrace(GETSIGINFO) failed (but not due to group-stop).
Todd Fialaaf245d12014-06-30 21:05:18 +0000489
Kate Stoneb9c1b512016-09-06 20:57:50 +0000490 // A return value of ESRCH means the thread/process is no longer on the
Pavel Labatha6321a82017-01-19 15:26:04 +0000491 // system, so it was killed somehow outside of our control. Either way,
492 // we can't do anything with it anymore.
Todd Fialaaf245d12014-06-30 21:05:18 +0000493
Kate Stoneb9c1b512016-09-06 20:57:50 +0000494 // Stop tracking the metadata for the thread since it's entirely off the
495 // system now.
496 const bool thread_found = StopTrackingThread(pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000497
Pavel Labatha6321a82017-01-19 15:26:04 +0000498 LLDB_LOG(log,
499 "GetSignalInfo failed: {0}, tid = {1}, signal = {2}, "
500 "status = {3}, main_thread = {4}, thread_found: {5}",
501 info_err, pid, signal, status, is_main_thread, thread_found);
Todd Fialaaf245d12014-06-30 21:05:18 +0000502
Kate Stoneb9c1b512016-09-06 20:57:50 +0000503 if (is_main_thread) {
504 // Notify the delegate - our process is not available but appears to
Adrian Prantl05097242018-04-30 16:49:04 +0000505 // have been killed outside our control. Is eStateExited the right
506 // exit state in this case?
Pavel Labath3508fc82017-06-19 12:47:50 +0000507 SetExitStatus(status, true);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000508 SetState(StateType::eStateExited, true);
509 } else {
510 // This thread was pulled out from underneath us. Anything to do here?
511 // Do we want to do an all stop?
Pavel Labatha6321a82017-01-19 15:26:04 +0000512 LLDB_LOG(log,
513 "pid {0} tid {1} non-main thread exit occurred, didn't "
514 "tell delegate anything since thread disappeared out "
515 "from underneath us",
516 GetID(), pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000517 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000518 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000519 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000520}
521
Kate Stoneb9c1b512016-09-06 20:57:50 +0000522void NativeProcessLinux::WaitForNewThread(::pid_t tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000523 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Pavel Labath426bdf82015-04-28 07:51:52 +0000524
Pavel Labatha5be48b2017-10-17 15:52:16 +0000525 if (GetThreadByID(tid)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000526 // We are already tracking the thread - we got the event on the new thread
Pavel Labatha5be48b2017-10-17 15:52:16 +0000527 // (see MonitorSignal) before this one. We are done.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000528 return;
529 }
Pavel Labath426bdf82015-04-28 07:51:52 +0000530
Kate Stoneb9c1b512016-09-06 20:57:50 +0000531 // The thread is not tracked yet, let's wait for it to appear.
532 int status = -1;
Pavel Labathc1a6b122017-07-03 09:25:55 +0000533 LLDB_LOG(log,
534 "received thread creation event for tid {0}. tid not tracked "
535 "yet, waiting for thread to appear...",
536 tid);
537 ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, &status, __WALL);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000538 // Since we are waiting on a specific tid, this must be the creation event.
Pavel Labatha6321a82017-01-19 15:26:04 +0000539 // But let's do some checks just in case.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000540 if (wait_pid != tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000541 LLDB_LOG(log,
542 "waiting for tid {0} failed. Assuming the thread has "
543 "disappeared in the meantime",
544 tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000545 // The only way I know of this could happen is if the whole process was
546 // SIGKILLed in the mean time. In any case, we can't do anything about that
547 // now.
548 return;
549 }
550 if (WIFEXITED(status)) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000551 LLDB_LOG(log,
552 "waiting for tid {0} returned an 'exited' event. Not "
553 "tracking the thread.",
554 tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000555 // Also a very improbable event.
556 return;
557 }
Pavel Labath426bdf82015-04-28 07:51:52 +0000558
Pavel Labatha6321a82017-01-19 15:26:04 +0000559 LLDB_LOG(log, "pid = {0}: tracking new thread tid {1}", GetID(), tid);
Pavel Labatha5be48b2017-10-17 15:52:16 +0000560 NativeThreadLinux &new_thread = AddThread(tid);
Ravitheja Addepally99e37692017-06-28 07:58:31 +0000561
Pavel Labatha5be48b2017-10-17 15:52:16 +0000562 ResumeThread(new_thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
563 ThreadWasCreated(new_thread);
Pavel Labath426bdf82015-04-28 07:51:52 +0000564}
565
Kate Stoneb9c1b512016-09-06 20:57:50 +0000566void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info,
567 NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000568 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000569 const bool is_main_thread = (thread.GetID() == GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000570
Kate Stoneb9c1b512016-09-06 20:57:50 +0000571 assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
Todd Fialaaf245d12014-06-30 21:05:18 +0000572
Kate Stoneb9c1b512016-09-06 20:57:50 +0000573 switch (info.si_code) {
574 // TODO: these two cases are required if we want to support tracing of the
Adrian Prantl05097242018-04-30 16:49:04 +0000575 // inferiors' children. We'd need this to debug a monitor. case (SIGTRAP |
576 // (PTRACE_EVENT_FORK << 8)): case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
Todd Fialaaf245d12014-06-30 21:05:18 +0000577
Kate Stoneb9c1b512016-09-06 20:57:50 +0000578 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): {
579 // This is the notification on the parent thread which informs us of new
Adrian Prantl05097242018-04-30 16:49:04 +0000580 // thread creation. We don't want to do anything with the parent thread so
581 // we just resume it. In case we want to implement "break on thread
582 // creation" functionality, we would need to stop here.
Todd Fialaaf245d12014-06-30 21:05:18 +0000583
Kate Stoneb9c1b512016-09-06 20:57:50 +0000584 unsigned long event_message = 0;
585 if (GetEventMessage(thread.GetID(), &event_message).Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000586 LLDB_LOG(log,
587 "pid {0} received thread creation event but "
588 "GetEventMessage failed so we don't know the new tid",
589 thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000590 } else
591 WaitForNewThread(event_message);
Todd Fialaaf245d12014-06-30 21:05:18 +0000592
Kate Stoneb9c1b512016-09-06 20:57:50 +0000593 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
594 break;
595 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000596
Kate Stoneb9c1b512016-09-06 20:57:50 +0000597 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): {
Pavel Labatha6321a82017-01-19 15:26:04 +0000598 LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000599
600 // Exec clears any pending notifications.
601 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
602
603 // Remove all but the main thread here. Linux fork creates a new process
604 // which only copies the main thread.
Pavel Labatha6321a82017-01-19 15:26:04 +0000605 LLDB_LOG(log, "exec received, stop tracking all but main thread");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000606
Pavel Labatha5be48b2017-10-17 15:52:16 +0000607 for (auto i = m_threads.begin(); i != m_threads.end();) {
608 if ((*i)->GetID() == GetID())
609 i = m_threads.erase(i);
610 else
611 ++i;
Todd Fialaa9882ce2014-08-28 15:46:54 +0000612 }
Pavel Labatha5be48b2017-10-17 15:52:16 +0000613 assert(m_threads.size() == 1);
614 auto *main_thread = static_cast<NativeThreadLinux *>(m_threads[0].get());
Todd Fialaaf245d12014-06-30 21:05:18 +0000615
Pavel Labatha5be48b2017-10-17 15:52:16 +0000616 SetCurrentThreadID(main_thread->GetID());
617 main_thread->SetStoppedByExec();
Todd Fialaaf245d12014-06-30 21:05:18 +0000618
Kate Stoneb9c1b512016-09-06 20:57:50 +0000619 // Tell coordinator about about the "new" (since exec) stopped main thread.
Pavel Labatha5be48b2017-10-17 15:52:16 +0000620 ThreadWasCreated(*main_thread);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000621
Kate Stoneb9c1b512016-09-06 20:57:50 +0000622 // Let our delegate know we have just exec'd.
623 NotifyDidExec();
624
Kate Stoneb9c1b512016-09-06 20:57:50 +0000625 // Let the process know we're stopped.
Pavel Labatha5be48b2017-10-17 15:52:16 +0000626 StopRunningThreads(main_thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000627
628 break;
629 }
630
631 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): {
Adrian Prantl05097242018-04-30 16:49:04 +0000632 // The inferior process or one of its threads is about to exit. We don't
633 // want to do anything with the thread so we just resume it. In case we
634 // want to implement "break on thread exit" functionality, we would need to
635 // stop here.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000636
637 unsigned long data = 0;
638 if (GetEventMessage(thread.GetID(), &data).Fail())
639 data = -1;
640
Pavel Labatha6321a82017-01-19 15:26:04 +0000641 LLDB_LOG(log,
642 "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
643 "WIFSIGNALED={2}, pid = {3}, main_thread = {4}",
644 data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(),
645 is_main_thread);
Todd Fialaaf245d12014-06-30 21:05:18 +0000646
Kate Stoneb9c1b512016-09-06 20:57:50 +0000647
648 StateType state = thread.GetState();
649 if (!StateIsRunningState(state)) {
650 // Due to a kernel bug, we may sometimes get this stop after the inferior
Pavel Labathd8b3c1a2017-12-18 09:44:29 +0000651 // gets a SIGKILL. This confuses our state tracking logic in
652 // ResumeThread(), since normally, we should not be receiving any ptrace
Adrian Prantl05097242018-04-30 16:49:04 +0000653 // events while the inferior is stopped. This makes sure that the
654 // inferior is resumed and exits normally.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000655 state = eStateRunning;
656 }
657 ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
658
659 break;
660 }
661
662 case 0:
663 case TRAP_TRACE: // We receive this on single stepping.
664 case TRAP_HWBKPT: // We receive this on watchpoint hit
665 {
666 // If a watchpoint was hit, report it
667 uint32_t wp_index;
Pavel Labathd37349f2017-11-10 11:05:49 +0000668 Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000669 wp_index, (uintptr_t)info.si_addr);
Pavel Labatha6321a82017-01-19 15:26:04 +0000670 if (error.Fail())
671 LLDB_LOG(log,
672 "received error while checking for watchpoint hits, pid = "
673 "{0}, error = {1}",
674 thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000675 if (wp_index != LLDB_INVALID_INDEX32) {
676 MonitorWatchpoint(thread, wp_index);
677 break;
678 }
679
Omair Javaidd5ffbad2017-02-24 13:27:31 +0000680 // If a breakpoint was hit, report it
681 uint32_t bp_index;
Pavel Labathd37349f2017-11-10 11:05:49 +0000682 error = thread.GetRegisterContext().GetHardwareBreakHitIndex(
Omair Javaidd5ffbad2017-02-24 13:27:31 +0000683 bp_index, (uintptr_t)info.si_addr);
684 if (error.Fail())
685 LLDB_LOG(log, "received error while checking for hardware "
686 "breakpoint hits, pid = {0}, error = {1}",
687 thread.GetID(), error);
688 if (bp_index != LLDB_INVALID_INDEX32) {
689 MonitorBreakpoint(thread);
690 break;
691 }
692
Kate Stoneb9c1b512016-09-06 20:57:50 +0000693 // Otherwise, report step over
694 MonitorTrace(thread);
695 break;
696 }
697
698 case SI_KERNEL:
Mohit K. Bhakkad35799962015-06-18 04:53:18 +0000699#if defined __mips__
Adrian Prantl05097242018-04-30 16:49:04 +0000700 // For mips there is no special signal for watchpoint So we check for
701 // watchpoint in kernel trap
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000702 {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000703 // If a watchpoint was hit, report it
704 uint32_t wp_index;
Pavel Labathd37349f2017-11-10 11:05:49 +0000705 Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000706 wp_index, LLDB_INVALID_ADDRESS);
Pavel Labatha6321a82017-01-19 15:26:04 +0000707 if (error.Fail())
708 LLDB_LOG(log,
709 "received error while checking for watchpoint hits, pid = "
710 "{0}, error = {1}",
711 thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000712 if (wp_index != LLDB_INVALID_INDEX32) {
713 MonitorWatchpoint(thread, wp_index);
714 break;
715 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000716 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000717// NO BREAK
Mohit K. Bhakkad35799962015-06-18 04:53:18 +0000718#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000719 case TRAP_BRKPT:
720 MonitorBreakpoint(thread);
721 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000722
Kate Stoneb9c1b512016-09-06 20:57:50 +0000723 case SIGTRAP:
724 case (SIGTRAP | 0x80):
Pavel Labatha6321a82017-01-19 15:26:04 +0000725 LLDB_LOG(
726 log,
727 "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",
728 info.si_code, GetID(), thread.GetID());
Chaoren Linfa03ad22015-02-03 01:50:42 +0000729
Kate Stoneb9c1b512016-09-06 20:57:50 +0000730 // Ignore these signals until we know more about them.
731 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
732 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000733
Kate Stoneb9c1b512016-09-06 20:57:50 +0000734 default:
Pavel Labath21a365b2017-07-11 10:38:40 +0000735 LLDB_LOG(log, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}",
736 info.si_code, GetID(), thread.GetID());
737 MonitorSignal(info, thread, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000738 break;
739 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000740}
741
Kate Stoneb9c1b512016-09-06 20:57:50 +0000742void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000743 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
744 LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000745
Kate Stoneb9c1b512016-09-06 20:57:50 +0000746 // This thread is currently stopped.
747 thread.SetStoppedByTrace();
748
749 StopRunningThreads(thread.GetID());
750}
751
752void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) {
753 Log *log(
754 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
Pavel Labatha6321a82017-01-19 15:26:04 +0000755 LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000756
757 // Mark the thread as stopped at breakpoint.
758 thread.SetStoppedByBreakpoint();
Pavel Labathaef79082018-10-03 12:29:33 +0000759 FixupBreakpointPCAsNeeded(thread);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000760
761 if (m_threads_stepping_with_breakpoint.find(thread.GetID()) !=
762 m_threads_stepping_with_breakpoint.end())
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000763 thread.SetStoppedByTrace();
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000764
Kate Stoneb9c1b512016-09-06 20:57:50 +0000765 StopRunningThreads(thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000766}
767
Kate Stoneb9c1b512016-09-06 20:57:50 +0000768void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread,
769 uint32_t wp_index) {
770 Log *log(
771 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
Pavel Labatha6321a82017-01-19 15:26:04 +0000772 LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}",
773 thread.GetID(), wp_index);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000774
Adrian Prantl05097242018-04-30 16:49:04 +0000775 // Mark the thread as stopped at watchpoint. The address is at
776 // (lldb::addr_t)info->si_addr if we need it.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000777 thread.SetStoppedByWatchpoint(wp_index);
778
779 // We need to tell all other running threads before we notify the delegate
780 // about this stop.
781 StopRunningThreads(thread.GetID());
782}
783
784void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
785 NativeThreadLinux &thread, bool exited) {
786 const int signo = info.si_signo;
787 const bool is_from_llgs = info.si_pid == getpid();
788
Pavel Labatha6321a82017-01-19 15:26:04 +0000789 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000790
791 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
Adrian Prantl05097242018-04-30 16:49:04 +0000792 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a kill(2)
793 // or raise(3). Similarly for tgkill(2) on Linux.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000794 //
795 // IOW, user generated signals never generate what we consider to be a
796 // "crash".
797 //
798 // Similarly, ACK signals generated by this monitor.
799
800 // Handle the signal.
Pavel Labatha6321a82017-01-19 15:26:04 +0000801 LLDB_LOG(log,
802 "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
803 "waitpid pid = {4})",
804 Host::GetSignalAsCString(signo), signo, info.si_code,
805 thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000806
Kate Stoneb9c1b512016-09-06 20:57:50 +0000807 // Check for thread stop notification.
808 if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) {
809 // This is a tgkill()-based stop.
Pavel Labatha6321a82017-01-19 15:26:04 +0000810 LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000811
Adrian Prantl05097242018-04-30 16:49:04 +0000812 // Check that we're not already marked with a stop reason. Note this thread
813 // really shouldn't already be marked as stopped - if we were, that would
814 // imply that the kernel signaled us with the thread stopping which we
815 // handled and marked as stopped, and that, without an intervening resume,
816 // we received another stop. It is more likely that we are missing the
817 // marking of a run state somewhere if we find that the thread was marked
818 // as stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000819 const StateType thread_state = thread.GetState();
820 if (!StateIsStoppedState(thread_state, false)) {
821 // An inferior thread has stopped because of a SIGSTOP we have sent it.
822 // Generally, these are not important stops and we don't want to report
Pavel Labatha6321a82017-01-19 15:26:04 +0000823 // them as they are just used to stop other threads when one thread (the
824 // one with the *real* stop reason) hits a breakpoint (watchpoint,
Adrian Prantl05097242018-04-30 16:49:04 +0000825 // etc...). However, in the case of an asynchronous Interrupt(), this
826 // *is* the real stop reason, so we leave the signal intact if this is
827 // the thread that was chosen as the triggering thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000828 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
829 if (m_pending_notification_tid == thread.GetID())
830 thread.SetStoppedBySignal(SIGSTOP, &info);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000831 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000832 thread.SetStoppedWithNoReason();
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000833
Kate Stoneb9c1b512016-09-06 20:57:50 +0000834 SetCurrentThreadID(thread.GetID());
835 SignalIfAllThreadsStopped();
836 } else {
837 // We can end up here if stop was initiated by LLGS but by this time a
838 // thread stop has occurred - maybe initiated by another event.
Zachary Turner97206d52017-05-12 04:51:55 +0000839 Status error = ResumeThread(thread, thread.GetState(), 0);
Pavel Labatha6321a82017-01-19 15:26:04 +0000840 if (error.Fail())
841 LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(),
842 error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000843 }
844 } else {
Pavel Labatha6321a82017-01-19 15:26:04 +0000845 LLDB_LOG(log,
846 "pid {0} tid {1}, thread was already marked as a stopped "
847 "state (state={2}), leaving stop signal as is",
Pavel Labath8198db32017-01-24 11:48:25 +0000848 GetID(), thread.GetID(), thread_state);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000849 SignalIfAllThreadsStopped();
Todd Fialaaf245d12014-06-30 21:05:18 +0000850 }
851
Kate Stoneb9c1b512016-09-06 20:57:50 +0000852 // Done handling.
853 return;
854 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000855
Adrian Prantl05097242018-04-30 16:49:04 +0000856 // Check if debugger should stop at this signal or just ignore it and resume
857 // the inferior.
Pavel Labath4a705e72017-02-24 09:29:14 +0000858 if (m_signals_to_ignore.find(signo) != m_signals_to_ignore.end()) {
859 ResumeThread(thread, thread.GetState(), signo);
860 return;
861 }
862
Kate Stoneb9c1b512016-09-06 20:57:50 +0000863 // This thread is stopped.
Pavel Labatha6321a82017-01-19 15:26:04 +0000864 LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000865 thread.SetStoppedBySignal(signo, &info);
866
867 // Send a stop to the debugger after we get all other threads to stop.
868 StopRunningThreads(thread.GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000869}
870
Tamas Berghammere7708682015-04-22 10:00:23 +0000871namespace {
872
Kate Stoneb9c1b512016-09-06 20:57:50 +0000873struct EmulatorBaton {
Pavel Labathd37349f2017-11-10 11:05:49 +0000874 NativeProcessLinux &m_process;
875 NativeRegisterContext &m_reg_context;
Tamas Berghammere7708682015-04-22 10:00:23 +0000876
Kate Stoneb9c1b512016-09-06 20:57:50 +0000877 // eRegisterKindDWARF -> RegsiterValue
878 std::unordered_map<uint32_t, RegisterValue> m_register_values;
Pavel Labath6648fcc2015-04-27 09:21:14 +0000879
Pavel Labathd37349f2017-11-10 11:05:49 +0000880 EmulatorBaton(NativeProcessLinux &process, NativeRegisterContext &reg_context)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000881 : m_process(process), m_reg_context(reg_context) {}
Tamas Berghammere7708682015-04-22 10:00:23 +0000882};
883
884} // anonymous namespace
885
Kate Stoneb9c1b512016-09-06 20:57:50 +0000886static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
887 const EmulateInstruction::Context &context,
888 lldb::addr_t addr, void *dst, size_t length) {
889 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
Tamas Berghammere7708682015-04-22 10:00:23 +0000890
Kate Stoneb9c1b512016-09-06 20:57:50 +0000891 size_t bytes_read;
Pavel Labathd37349f2017-11-10 11:05:49 +0000892 emulator_baton->m_process.ReadMemory(addr, dst, length, bytes_read);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000893 return bytes_read;
Tamas Berghammere7708682015-04-22 10:00:23 +0000894}
895
Kate Stoneb9c1b512016-09-06 20:57:50 +0000896static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
897 const RegisterInfo *reg_info,
898 RegisterValue &reg_value) {
899 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
Tamas Berghammere7708682015-04-22 10:00:23 +0000900
Kate Stoneb9c1b512016-09-06 20:57:50 +0000901 auto it = emulator_baton->m_register_values.find(
902 reg_info->kinds[eRegisterKindDWARF]);
903 if (it != emulator_baton->m_register_values.end()) {
904 reg_value = it->second;
905 return true;
906 }
907
Adrian Prantl05097242018-04-30 16:49:04 +0000908 // The emulator only fill in the dwarf regsiter numbers (and in some case the
909 // generic register numbers). Get the full register info from the register
910 // context based on the dwarf register numbers.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000911 const RegisterInfo *full_reg_info =
Pavel Labathd37349f2017-11-10 11:05:49 +0000912 emulator_baton->m_reg_context.GetRegisterInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000913 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
914
Zachary Turner97206d52017-05-12 04:51:55 +0000915 Status error =
Pavel Labathd37349f2017-11-10 11:05:49 +0000916 emulator_baton->m_reg_context.ReadRegister(full_reg_info, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000917 if (error.Success())
918 return true;
919
920 return false;
921}
922
923static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
924 const EmulateInstruction::Context &context,
925 const RegisterInfo *reg_info,
926 const RegisterValue &reg_value) {
927 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
928 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
929 reg_value;
930 return true;
931}
932
933static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
934 const EmulateInstruction::Context &context,
935 lldb::addr_t addr, const void *dst,
936 size_t length) {
937 return length;
938}
939
Pavel Labathd37349f2017-11-10 11:05:49 +0000940static lldb::addr_t ReadFlags(NativeRegisterContext &regsiter_context) {
941 const RegisterInfo *flags_info = regsiter_context.GetRegisterInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000942 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
Pavel Labathd37349f2017-11-10 11:05:49 +0000943 return regsiter_context.ReadRegisterAsUnsigned(flags_info,
944 LLDB_INVALID_ADDRESS);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000945}
946
Zachary Turner97206d52017-05-12 04:51:55 +0000947Status
948NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadLinux &thread) {
949 Status error;
Pavel Labathd37349f2017-11-10 11:05:49 +0000950 NativeRegisterContext& register_context = thread.GetRegisterContext();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000951
952 std::unique_ptr<EmulateInstruction> emulator_ap(
953 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying,
954 nullptr));
955
956 if (emulator_ap == nullptr)
Zachary Turner97206d52017-05-12 04:51:55 +0000957 return Status("Instruction emulator not found!");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000958
Pavel Labathd37349f2017-11-10 11:05:49 +0000959 EmulatorBaton baton(*this, register_context);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000960 emulator_ap->SetBaton(&baton);
961 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
962 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
963 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
964 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
965
966 if (!emulator_ap->ReadInstruction())
Zachary Turner97206d52017-05-12 04:51:55 +0000967 return Status("Read instruction failed!");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000968
969 bool emulation_result =
970 emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
971
Pavel Labathd37349f2017-11-10 11:05:49 +0000972 const RegisterInfo *reg_info_pc = register_context.GetRegisterInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000973 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
Pavel Labathd37349f2017-11-10 11:05:49 +0000974 const RegisterInfo *reg_info_flags = register_context.GetRegisterInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000975 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
976
977 auto pc_it =
978 baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
979 auto flags_it =
980 baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
981
982 lldb::addr_t next_pc;
983 lldb::addr_t next_flags;
984 if (emulation_result) {
985 assert(pc_it != baton.m_register_values.end() &&
986 "Emulation was successfull but PC wasn't updated");
987 next_pc = pc_it->second.GetAsUInt64();
988
989 if (flags_it != baton.m_register_values.end())
990 next_flags = flags_it->second.GetAsUInt64();
991 else
Pavel Labathd37349f2017-11-10 11:05:49 +0000992 next_flags = ReadFlags(register_context);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000993 } else if (pc_it == baton.m_register_values.end()) {
Adrian Prantl05097242018-04-30 16:49:04 +0000994 // Emulate instruction failed and it haven't changed PC. Advance PC with
995 // the size of the current opcode because the emulation of all
Kate Stoneb9c1b512016-09-06 20:57:50 +0000996 // PC modifying instruction should be successful. The failure most
997 // likely caused by a not supported instruction which don't modify PC.
Pavel Labathd37349f2017-11-10 11:05:49 +0000998 next_pc = register_context.GetPC() + emulator_ap->GetOpcode().GetByteSize();
999 next_flags = ReadFlags(register_context);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001000 } else {
1001 // The instruction emulation failed after it modified the PC. It is an
1002 // unknown error where we can't continue because the next instruction is
1003 // modifying the PC but we don't know how.
Zachary Turner97206d52017-05-12 04:51:55 +00001004 return Status("Instruction emulation failed unexpectedly.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001005 }
1006
1007 if (m_arch.GetMachine() == llvm::Triple::arm) {
1008 if (next_flags & 0x20) {
1009 // Thumb mode
1010 error = SetSoftwareBreakpoint(next_pc, 2);
1011 } else {
1012 // Arm mode
1013 error = SetSoftwareBreakpoint(next_pc, 4);
Pavel Labath6648fcc2015-04-27 09:21:14 +00001014 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001015 } else if (m_arch.GetMachine() == llvm::Triple::mips64 ||
1016 m_arch.GetMachine() == llvm::Triple::mips64el ||
1017 m_arch.GetMachine() == llvm::Triple::mips ||
Eugene Zemtsovaae0a752017-10-05 19:44:05 +00001018 m_arch.GetMachine() == llvm::Triple::mipsel ||
1019 m_arch.GetMachine() == llvm::Triple::ppc64le)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001020 error = SetSoftwareBreakpoint(next_pc, 4);
1021 else {
1022 // No size hint is given for the next breakpoint
1023 error = SetSoftwareBreakpoint(next_pc, 0);
1024 }
Pavel Labath6648fcc2015-04-27 09:21:14 +00001025
Adrian Prantl05097242018-04-30 16:49:04 +00001026 // If setting the breakpoint fails because next_pc is out of the address
1027 // space, ignore it and let the debugee segfault.
Pavel Labath42eb6902016-10-26 11:13:56 +00001028 if (error.GetError() == EIO || error.GetError() == EFAULT) {
Zachary Turner97206d52017-05-12 04:51:55 +00001029 return Status();
Pavel Labath42eb6902016-10-26 11:13:56 +00001030 } else if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001031 return error;
Tamas Berghammere7708682015-04-22 10:00:23 +00001032
Kate Stoneb9c1b512016-09-06 20:57:50 +00001033 m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001034
Zachary Turner97206d52017-05-12 04:51:55 +00001035 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001036}
1037
1038bool NativeProcessLinux::SupportHardwareSingleStepping() const {
1039 if (m_arch.GetMachine() == llvm::Triple::arm ||
1040 m_arch.GetMachine() == llvm::Triple::mips64 ||
1041 m_arch.GetMachine() == llvm::Triple::mips64el ||
1042 m_arch.GetMachine() == llvm::Triple::mips ||
1043 m_arch.GetMachine() == llvm::Triple::mipsel)
Pavel Labath6648fcc2015-04-27 09:21:14 +00001044 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001045 return true;
Tamas Berghammere7708682015-04-22 10:00:23 +00001046}
1047
Zachary Turner97206d52017-05-12 04:51:55 +00001048Status NativeProcessLinux::Resume(const ResumeActionList &resume_actions) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001049 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1050 LLDB_LOG(log, "pid {0}", GetID());
Tamas Berghammere7708682015-04-22 10:00:23 +00001051
Kate Stoneb9c1b512016-09-06 20:57:50 +00001052 bool software_single_step = !SupportHardwareSingleStepping();
Tamas Berghammere7708682015-04-22 10:00:23 +00001053
Kate Stoneb9c1b512016-09-06 20:57:50 +00001054 if (software_single_step) {
Pavel Labatha5be48b2017-10-17 15:52:16 +00001055 for (const auto &thread : m_threads) {
1056 assert(thread && "thread list should not contain NULL threads");
Tamas Berghammere7708682015-04-22 10:00:23 +00001057
Kate Stoneb9c1b512016-09-06 20:57:50 +00001058 const ResumeAction *const action =
Pavel Labatha5be48b2017-10-17 15:52:16 +00001059 resume_actions.GetActionForThread(thread->GetID(), true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001060 if (action == nullptr)
1061 continue;
Tamas Berghammere7708682015-04-22 10:00:23 +00001062
Kate Stoneb9c1b512016-09-06 20:57:50 +00001063 if (action->state == eStateStepping) {
Zachary Turner97206d52017-05-12 04:51:55 +00001064 Status error = SetupSoftwareSingleStepping(
Pavel Labatha5be48b2017-10-17 15:52:16 +00001065 static_cast<NativeThreadLinux &>(*thread));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001066 if (error.Fail())
1067 return error;
1068 }
Tamas Berghammere7708682015-04-22 10:00:23 +00001069 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001070 }
1071
Pavel Labatha5be48b2017-10-17 15:52:16 +00001072 for (const auto &thread : m_threads) {
1073 assert(thread && "thread list should not contain NULL threads");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001074
1075 const ResumeAction *const action =
Pavel Labatha5be48b2017-10-17 15:52:16 +00001076 resume_actions.GetActionForThread(thread->GetID(), true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001077
1078 if (action == nullptr) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001079 LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
Pavel Labatha5be48b2017-10-17 15:52:16 +00001080 thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001081 continue;
Tamas Berghammere7708682015-04-22 10:00:23 +00001082 }
1083
Pavel Labatha6321a82017-01-19 15:26:04 +00001084 LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}",
Pavel Labatha5be48b2017-10-17 15:52:16 +00001085 action->state, GetID(), thread->GetID());
Tamas Berghammere7708682015-04-22 10:00:23 +00001086
Kate Stoneb9c1b512016-09-06 20:57:50 +00001087 switch (action->state) {
1088 case eStateRunning:
1089 case eStateStepping: {
1090 // Run the thread, possibly feeding it the signal.
1091 const int signo = action->signal;
Pavel Labatha5be48b2017-10-17 15:52:16 +00001092 ResumeThread(static_cast<NativeThreadLinux &>(*thread), action->state,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001093 signo);
1094 break;
1095 }
Tamas Berghammere7708682015-04-22 10:00:23 +00001096
Kate Stoneb9c1b512016-09-06 20:57:50 +00001097 case eStateSuspended:
1098 case eStateStopped:
Pavel Labatha6321a82017-01-19 15:26:04 +00001099 llvm_unreachable("Unexpected state");
Tamas Berghammere7708682015-04-22 10:00:23 +00001100
Kate Stoneb9c1b512016-09-06 20:57:50 +00001101 default:
Zachary Turner97206d52017-05-12 04:51:55 +00001102 return Status("NativeProcessLinux::%s (): unexpected state %s specified "
1103 "for pid %" PRIu64 ", tid %" PRIu64,
1104 __FUNCTION__, StateAsCString(action->state), GetID(),
Pavel Labatha5be48b2017-10-17 15:52:16 +00001105 thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001106 }
1107 }
1108
Zachary Turner97206d52017-05-12 04:51:55 +00001109 return Status();
Tamas Berghammere7708682015-04-22 10:00:23 +00001110}
1111
Zachary Turner97206d52017-05-12 04:51:55 +00001112Status NativeProcessLinux::Halt() {
1113 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001114
1115 if (kill(GetID(), SIGSTOP) != 0)
1116 error.SetErrorToErrno();
1117
1118 return error;
Tamas Berghammere7708682015-04-22 10:00:23 +00001119}
1120
Zachary Turner97206d52017-05-12 04:51:55 +00001121Status NativeProcessLinux::Detach() {
1122 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001123
1124 // Stop monitoring the inferior.
1125 m_sigchld_handle.reset();
1126
1127 // Tell ptrace to detach from the process.
1128 if (GetID() == LLDB_INVALID_PROCESS_ID)
1129 return error;
1130
Pavel Labatha5be48b2017-10-17 15:52:16 +00001131 for (const auto &thread : m_threads) {
1132 Status e = Detach(thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001133 if (e.Fail())
1134 error =
1135 e; // Save the error, but still attempt to detach from other threads.
1136 }
1137
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001138 m_processor_trace_monitor.clear();
1139 m_pt_proces_trace_id = LLDB_INVALID_UID;
1140
Kate Stoneb9c1b512016-09-06 20:57:50 +00001141 return error;
1142}
1143
Zachary Turner97206d52017-05-12 04:51:55 +00001144Status NativeProcessLinux::Signal(int signo) {
1145 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001146
Pavel Labatha6321a82017-01-19 15:26:04 +00001147 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1148 LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo,
1149 Host::GetSignalAsCString(signo), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001150
1151 if (kill(GetID(), signo))
1152 error.SetErrorToErrno();
1153
1154 return error;
1155}
1156
Zachary Turner97206d52017-05-12 04:51:55 +00001157Status NativeProcessLinux::Interrupt() {
Adrian Prantl05097242018-04-30 16:49:04 +00001158 // Pick a running thread (or if none, a not-dead stopped thread) as the
1159 // chosen thread that will be the stop-reason thread.
Pavel Labatha6321a82017-01-19 15:26:04 +00001160 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001161
Pavel Labatha5be48b2017-10-17 15:52:16 +00001162 NativeThreadProtocol *running_thread = nullptr;
1163 NativeThreadProtocol *stopped_thread = nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001164
Pavel Labatha6321a82017-01-19 15:26:04 +00001165 LLDB_LOG(log, "selecting running thread for interrupt target");
Pavel Labatha5be48b2017-10-17 15:52:16 +00001166 for (const auto &thread : m_threads) {
Adrian Prantl05097242018-04-30 16:49:04 +00001167 // If we have a running or stepping thread, we'll call that the target of
1168 // the interrupt.
Pavel Labatha5be48b2017-10-17 15:52:16 +00001169 const auto thread_state = thread->GetState();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001170 if (thread_state == eStateRunning || thread_state == eStateStepping) {
Pavel Labatha5be48b2017-10-17 15:52:16 +00001171 running_thread = thread.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001172 break;
Pavel Labatha5be48b2017-10-17 15:52:16 +00001173 } else if (!stopped_thread && StateIsStoppedState(thread_state, true)) {
Adrian Prantl05097242018-04-30 16:49:04 +00001174 // Remember the first non-dead stopped thread. We'll use that as a
1175 // backup if there are no running threads.
Pavel Labatha5be48b2017-10-17 15:52:16 +00001176 stopped_thread = thread.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001177 }
1178 }
1179
Pavel Labatha5be48b2017-10-17 15:52:16 +00001180 if (!running_thread && !stopped_thread) {
Zachary Turner97206d52017-05-12 04:51:55 +00001181 Status error("found no running/stepping or live stopped threads as target "
1182 "for interrupt");
Pavel Labatha6321a82017-01-19 15:26:04 +00001183 LLDB_LOG(log, "skipping due to error: {0}", error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001184
1185 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001186 }
1187
Pavel Labatha5be48b2017-10-17 15:52:16 +00001188 NativeThreadProtocol *deferred_signal_thread =
1189 running_thread ? running_thread : stopped_thread;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001190
Pavel Labatha6321a82017-01-19 15:26:04 +00001191 LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(),
Pavel Labatha5be48b2017-10-17 15:52:16 +00001192 running_thread ? "running" : "stopped",
1193 deferred_signal_thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001194
Pavel Labatha5be48b2017-10-17 15:52:16 +00001195 StopRunningThreads(deferred_signal_thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001196
Zachary Turner97206d52017-05-12 04:51:55 +00001197 return Status();
Todd Fialaaf245d12014-06-30 21:05:18 +00001198}
1199
Zachary Turner97206d52017-05-12 04:51:55 +00001200Status NativeProcessLinux::Kill() {
Pavel Labatha6321a82017-01-19 15:26:04 +00001201 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1202 LLDB_LOG(log, "pid {0}", GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +00001203
Zachary Turner97206d52017-05-12 04:51:55 +00001204 Status error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001205
Kate Stoneb9c1b512016-09-06 20:57:50 +00001206 switch (m_state) {
1207 case StateType::eStateInvalid:
1208 case StateType::eStateExited:
1209 case StateType::eStateCrashed:
1210 case StateType::eStateDetached:
1211 case StateType::eStateUnloaded:
1212 // Nothing to do - the process is already dead.
Pavel Labatha6321a82017-01-19 15:26:04 +00001213 LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
Pavel Labath8198db32017-01-24 11:48:25 +00001214 m_state);
Todd Fialaaf245d12014-06-30 21:05:18 +00001215 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001216
Kate Stoneb9c1b512016-09-06 20:57:50 +00001217 case StateType::eStateConnected:
1218 case StateType::eStateAttaching:
1219 case StateType::eStateLaunching:
1220 case StateType::eStateStopped:
1221 case StateType::eStateRunning:
1222 case StateType::eStateStepping:
1223 case StateType::eStateSuspended:
1224 // We can try to kill a process in these states.
1225 break;
1226 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001227
Kate Stoneb9c1b512016-09-06 20:57:50 +00001228 if (kill(GetID(), SIGKILL) != 0) {
1229 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +00001230 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001231 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001232
Kate Stoneb9c1b512016-09-06 20:57:50 +00001233 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001234}
1235
Zachary Turner97206d52017-05-12 04:51:55 +00001236Status NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr,
1237 MemoryRegionInfo &range_info) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001238 // FIXME review that the final memory region returned extends to the end of
1239 // the virtual address space,
1240 // with no perms if it is not mapped.
Todd Fialaaf245d12014-06-30 21:05:18 +00001241
Adrian Prantl05097242018-04-30 16:49:04 +00001242 // Use an approach that reads memory regions from /proc/{pid}/maps. Assume
1243 // proc maps entries are in ascending order.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001244 // FIXME assert if we find differently.
Todd Fialaaf245d12014-06-30 21:05:18 +00001245
Kate Stoneb9c1b512016-09-06 20:57:50 +00001246 if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
1247 // We're done.
Zachary Turner97206d52017-05-12 04:51:55 +00001248 return Status("unsupported");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001249 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001250
Zachary Turner97206d52017-05-12 04:51:55 +00001251 Status error = PopulateMemoryRegionCache();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001252 if (error.Fail()) {
1253 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001254 }
1255
1256 lldb::addr_t prev_base_address = 0;
1257
1258 // FIXME start by finding the last region that is <= target address using
1259 // binary search. Data is sorted.
1260 // There can be a ton of regions on pthreads apps with lots of threads.
1261 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1262 ++it) {
Tamas Berghammera6f57952017-01-03 16:29:43 +00001263 MemoryRegionInfo &proc_entry_info = it->first;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001264
1265 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1266 assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
1267 "descending /proc/pid/maps entries detected, unexpected");
1268 prev_base_address = proc_entry_info.GetRange().GetRangeBase();
Hafiz Abid Qadeerb1554312017-01-20 10:24:03 +00001269 UNUSED_IF_ASSERT_DISABLED(prev_base_address);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001270
1271 // If the target address comes before this entry, indicate distance to next
1272 // region.
1273 if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1274 range_info.GetRange().SetRangeBase(load_addr);
1275 range_info.GetRange().SetByteSize(
1276 proc_entry_info.GetRange().GetRangeBase() - load_addr);
1277 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1278 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1279 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1280 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1281
1282 return error;
1283 } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1284 // The target address is within the memory region we're processing here.
1285 range_info = proc_entry_info;
1286 return error;
1287 }
1288
1289 // The target memory address comes somewhere after the region we just
1290 // parsed.
1291 }
1292
1293 // If we made it here, we didn't find an entry that contained the given
Adrian Prantl05097242018-04-30 16:49:04 +00001294 // address. Return the load_addr as start and the amount of bytes betwwen
1295 // load address and the end of the memory as size.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001296 range_info.GetRange().SetRangeBase(load_addr);
1297 range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
1298 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1299 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1300 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1301 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1302 return error;
1303}
1304
Zachary Turner97206d52017-05-12 04:51:55 +00001305Status NativeProcessLinux::PopulateMemoryRegionCache() {
Pavel Labatha6321a82017-01-19 15:26:04 +00001306 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Tamas Berghammera6f57952017-01-03 16:29:43 +00001307
1308 // If our cache is empty, pull the latest. There should always be at least
1309 // one memory region if memory region handling is supported.
1310 if (!m_mem_region_cache.empty()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001311 LLDB_LOG(log, "reusing {0} cached memory region entries",
1312 m_mem_region_cache.size());
Zachary Turner97206d52017-05-12 04:51:55 +00001313 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001314 }
1315
Pavel Labath15930862017-03-21 13:49:45 +00001316 auto BufferOrError = getProcFile(GetID(), "maps");
1317 if (!BufferOrError) {
Tamas Berghammera6f57952017-01-03 16:29:43 +00001318 m_supports_mem_region = LazyBool::eLazyBoolNo;
Pavel Labath15930862017-03-21 13:49:45 +00001319 return BufferOrError.getError();
1320 }
Pavel Labathc8e364e82018-12-15 13:38:16 +00001321 Status Result;
1322 ParseLinuxMapRegions(BufferOrError.get()->getBuffer(),
1323 [&](const MemoryRegionInfo &Info, const Status &ST) {
1324 if (ST.Success()) {
1325 FileSpec file_spec(Info.GetName().GetCString());
1326 FileSystem::Instance().Resolve(file_spec);
1327 m_mem_region_cache.emplace_back(Info, file_spec);
1328 return true;
1329 } else {
1330 m_supports_mem_region = LazyBool::eLazyBoolNo;
1331 LLDB_LOG(log, "failed to parse proc maps: {0}", ST);
1332 Result = ST;
1333 return false;
1334 }
1335 });
1336 if (Result.Fail())
1337 return Result;
Pavel Labath15930862017-03-21 13:49:45 +00001338
1339 if (m_mem_region_cache.empty()) {
Tamas Berghammera6f57952017-01-03 16:29:43 +00001340 // No entries after attempting to read them. This shouldn't happen if
Adrian Prantl05097242018-04-30 16:49:04 +00001341 // /proc/{pid}/maps is supported. Assume we don't support map entries via
1342 // procfs.
Pavel Labath15930862017-03-21 13:49:45 +00001343 m_supports_mem_region = LazyBool::eLazyBoolNo;
Pavel Labatha6321a82017-01-19 15:26:04 +00001344 LLDB_LOG(log,
1345 "failed to find any procfs maps entries, assuming no support "
1346 "for memory region metadata retrieval");
Zachary Turner97206d52017-05-12 04:51:55 +00001347 return Status("not supported");
Tamas Berghammera6f57952017-01-03 16:29:43 +00001348 }
1349
Pavel Labatha6321a82017-01-19 15:26:04 +00001350 LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps",
1351 m_mem_region_cache.size(), GetID());
Tamas Berghammera6f57952017-01-03 16:29:43 +00001352
1353 // We support memory retrieval, remember that.
1354 m_supports_mem_region = LazyBool::eLazyBoolYes;
Zachary Turner97206d52017-05-12 04:51:55 +00001355 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001356}
1357
Kate Stoneb9c1b512016-09-06 20:57:50 +00001358void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001359 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1360 LLDB_LOG(log, "newBumpId={0}", newBumpId);
1361 LLDB_LOG(log, "clearing {0} entries from memory region cache",
1362 m_mem_region_cache.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001363 m_mem_region_cache.clear();
1364}
1365
Zachary Turner97206d52017-05-12 04:51:55 +00001366Status NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions,
1367 lldb::addr_t &addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001368// FIXME implementing this requires the equivalent of
Adrian Prantl05097242018-04-30 16:49:04 +00001369// InferiorCallPOSIX::InferiorCallMmap, which depends on functional ThreadPlans
1370// working with Native*Protocol.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001371#if 1
Zachary Turner97206d52017-05-12 04:51:55 +00001372 return Status("not implemented yet");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001373#else
1374 addr = LLDB_INVALID_ADDRESS;
1375
1376 unsigned prot = 0;
1377 if (permissions & lldb::ePermissionsReadable)
1378 prot |= eMmapProtRead;
1379 if (permissions & lldb::ePermissionsWritable)
1380 prot |= eMmapProtWrite;
1381 if (permissions & lldb::ePermissionsExecutable)
1382 prot |= eMmapProtExec;
1383
1384 // TODO implement this directly in NativeProcessLinux
Adrian Prantl05097242018-04-30 16:49:04 +00001385 // (and lift to NativeProcessPOSIX if/when that class is refactored out).
Kate Stoneb9c1b512016-09-06 20:57:50 +00001386 if (InferiorCallMmap(this, addr, 0, size, prot,
1387 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
1388 m_addr_to_mmap_size[addr] = size;
Zachary Turner97206d52017-05-12 04:51:55 +00001389 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001390 } else {
1391 addr = LLDB_INVALID_ADDRESS;
Zachary Turner97206d52017-05-12 04:51:55 +00001392 return Status("unable to allocate %" PRIu64
1393 " bytes of memory with permissions %s",
1394 size, GetPermissionsAsCString(permissions));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001395 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001396#endif
1397}
1398
Zachary Turner97206d52017-05-12 04:51:55 +00001399Status NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001400 // FIXME see comments in AllocateMemory - required lower-level
1401 // bits not in place yet (ThreadPlans)
Zachary Turner97206d52017-05-12 04:51:55 +00001402 return Status("not implemented");
Todd Fialaaf245d12014-06-30 21:05:18 +00001403}
1404
Kate Stoneb9c1b512016-09-06 20:57:50 +00001405lldb::addr_t NativeProcessLinux::GetSharedLibraryInfoAddress() {
1406 // punt on this for now
1407 return LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00001408}
1409
Kate Stoneb9c1b512016-09-06 20:57:50 +00001410size_t NativeProcessLinux::UpdateThreads() {
Adrian Prantl05097242018-04-30 16:49:04 +00001411 // The NativeProcessLinux monitoring threads are always up to date with
1412 // respect to thread state and they keep the thread list populated properly.
1413 // All this method needs to do is return the thread count.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001414 return m_threads.size();
Todd Fialaaf245d12014-06-30 21:05:18 +00001415}
1416
Zachary Turner97206d52017-05-12 04:51:55 +00001417Status NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,
1418 bool hardware) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001419 if (hardware)
Omair Javaidd5ffbad2017-02-24 13:27:31 +00001420 return SetHardwareBreakpoint(addr, size);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001421 else
1422 return SetSoftwareBreakpoint(addr, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00001423}
1424
Zachary Turner97206d52017-05-12 04:51:55 +00001425Status NativeProcessLinux::RemoveBreakpoint(lldb::addr_t addr, bool hardware) {
Omair Javaidd5ffbad2017-02-24 13:27:31 +00001426 if (hardware)
1427 return RemoveHardwareBreakpoint(addr);
1428 else
1429 return NativeProcessProtocol::RemoveBreakpoint(addr);
1430}
1431
Pavel Labathf8b825f2018-09-09 06:01:12 +00001432llvm::Expected<llvm::ArrayRef<uint8_t>>
1433NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(size_t size_hint) {
Pavel Labath12286a22018-09-08 10:33:14 +00001434 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1435 // linux kernel does otherwise.
Pavel Labathf8b825f2018-09-09 06:01:12 +00001436 static const uint8_t g_arm_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1437 static const uint8_t g_thumb_opcode[] = {0x01, 0xde};
Todd Fialaaf245d12014-06-30 21:05:18 +00001438
Pavel Labathf8b825f2018-09-09 06:01:12 +00001439 switch (GetArchitecture().GetMachine()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001440 case llvm::Triple::arm:
Pavel Labathf8b825f2018-09-09 06:01:12 +00001441 switch (size_hint) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001442 case 2:
Pavel Labath4f545072018-09-09 08:42:00 +00001443 return llvm::makeArrayRef(g_thumb_opcode);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001444 case 4:
Pavel Labath4f545072018-09-09 08:42:00 +00001445 return llvm::makeArrayRef(g_arm_opcode);
Todd Fialaaf245d12014-06-30 21:05:18 +00001446 default:
Pavel Labathf8b825f2018-09-09 06:01:12 +00001447 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1448 "Unrecognised trap opcode size hint!");
Todd Fialaaf245d12014-06-30 21:05:18 +00001449 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001450 default:
Pavel Labathf8b825f2018-09-09 06:01:12 +00001451 return NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_hint);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001452 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001453}
1454
Zachary Turner97206d52017-05-12 04:51:55 +00001455Status NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
1456 size_t &bytes_read) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001457 if (ProcessVmReadvSupported()) {
1458 // The process_vm_readv path is about 50 times faster than ptrace api. We
Adrian Prantl05097242018-04-30 16:49:04 +00001459 // want to use this syscall if it is supported.
Pavel Labathdf7c6992015-06-17 18:38:49 +00001460
Kate Stoneb9c1b512016-09-06 20:57:50 +00001461 const ::pid_t pid = GetID();
Pavel Labathdf7c6992015-06-17 18:38:49 +00001462
Kate Stoneb9c1b512016-09-06 20:57:50 +00001463 struct iovec local_iov, remote_iov;
1464 local_iov.iov_base = buf;
1465 local_iov.iov_len = size;
1466 remote_iov.iov_base = reinterpret_cast<void *>(addr);
1467 remote_iov.iov_len = size;
Pavel Labathdf7c6992015-06-17 18:38:49 +00001468
Kate Stoneb9c1b512016-09-06 20:57:50 +00001469 bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
1470 const bool success = bytes_read == size;
Pavel Labathdf7c6992015-06-17 18:38:49 +00001471
Pavel Labatha6321a82017-01-19 15:26:04 +00001472 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1473 LLDB_LOG(log,
1474 "using process_vm_readv to read {0} bytes from inferior "
1475 "address {1:x}: {2}",
Pavel Labath10c41f32017-06-06 14:06:17 +00001476 size, addr, success ? "Success" : llvm::sys::StrError(errno));
Pavel Labath19cbe962015-07-21 13:20:32 +00001477
Kate Stoneb9c1b512016-09-06 20:57:50 +00001478 if (success)
Zachary Turner97206d52017-05-12 04:51:55 +00001479 return Status();
Pavel Labatha6321a82017-01-19 15:26:04 +00001480 // else the call failed for some reason, let's retry the read using ptrace
1481 // api.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001482 }
Pavel Labath19cbe962015-07-21 13:20:32 +00001483
Kate Stoneb9c1b512016-09-06 20:57:50 +00001484 unsigned char *dst = static_cast<unsigned char *>(buf);
1485 size_t remainder;
1486 long data;
Pavel Labath19cbe962015-07-21 13:20:32 +00001487
Pavel Labatha6321a82017-01-19 15:26:04 +00001488 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1489 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
Pavel Labath19cbe962015-07-21 13:20:32 +00001490
Kate Stoneb9c1b512016-09-06 20:57:50 +00001491 for (bytes_read = 0; bytes_read < size; bytes_read += remainder) {
Zachary Turner97206d52017-05-12 04:51:55 +00001492 Status error = NativeProcessLinux::PtraceWrapper(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001493 PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data);
Pavel Labatha6321a82017-01-19 15:26:04 +00001494 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001495 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001496
1497 remainder = size - bytes_read;
1498 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
1499
1500 // Copy the data into our buffer
1501 memcpy(dst, &data, remainder);
1502
Pavel Labatha6321a82017-01-19 15:26:04 +00001503 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001504 addr += k_ptrace_word_size;
1505 dst += k_ptrace_word_size;
1506 }
Zachary Turner97206d52017-05-12 04:51:55 +00001507 return Status();
Todd Fialaaf245d12014-06-30 21:05:18 +00001508}
1509
Zachary Turner97206d52017-05-12 04:51:55 +00001510Status NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,
1511 size_t size, size_t &bytes_written) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001512 const unsigned char *src = static_cast<const unsigned char *>(buf);
1513 size_t remainder;
Zachary Turner97206d52017-05-12 04:51:55 +00001514 Status error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001515
Pavel Labatha6321a82017-01-19 15:26:04 +00001516 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1517 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00001518
Kate Stoneb9c1b512016-09-06 20:57:50 +00001519 for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
1520 remainder = size - bytes_written;
1521 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
Chaoren Lin97ccc292015-02-03 01:51:12 +00001522
Kate Stoneb9c1b512016-09-06 20:57:50 +00001523 if (remainder == k_ptrace_word_size) {
1524 unsigned long data = 0;
1525 memcpy(&data, src, k_ptrace_word_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00001526
Pavel Labatha6321a82017-01-19 15:26:04 +00001527 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001528 error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(),
1529 (void *)addr, (void *)data);
Pavel Labatha6321a82017-01-19 15:26:04 +00001530 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001531 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001532 } else {
1533 unsigned char buff[8];
1534 size_t bytes_read;
1535 error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
Pavel Labatha6321a82017-01-19 15:26:04 +00001536 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001537 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001538
1539 memcpy(buff, src, remainder);
1540
1541 size_t bytes_written_rec;
1542 error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
Pavel Labatha6321a82017-01-19 15:26:04 +00001543 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001544 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001545
Pavel Labatha6321a82017-01-19 15:26:04 +00001546 LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src,
1547 *(unsigned long *)buff);
Todd Fialaaf245d12014-06-30 21:05:18 +00001548 }
1549
Kate Stoneb9c1b512016-09-06 20:57:50 +00001550 addr += k_ptrace_word_size;
1551 src += k_ptrace_word_size;
1552 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001553 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001554}
1555
Zachary Turner97206d52017-05-12 04:51:55 +00001556Status NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001557 return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
1558}
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001559
Zachary Turner97206d52017-05-12 04:51:55 +00001560Status NativeProcessLinux::GetEventMessage(lldb::tid_t tid,
1561 unsigned long *message) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001562 return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
1563}
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001564
Zachary Turner97206d52017-05-12 04:51:55 +00001565Status NativeProcessLinux::Detach(lldb::tid_t tid) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001566 if (tid == LLDB_INVALID_THREAD_ID)
Zachary Turner97206d52017-05-12 04:51:55 +00001567 return Status();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001568
Kate Stoneb9c1b512016-09-06 20:57:50 +00001569 return PtraceWrapper(PTRACE_DETACH, tid);
1570}
1571
1572bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {
Pavel Labatha5be48b2017-10-17 15:52:16 +00001573 for (const auto &thread : m_threads) {
1574 assert(thread && "thread list should not contain NULL threads");
1575 if (thread->GetID() == thread_id) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001576 // We have this thread.
1577 return true;
Todd Fialaaf245d12014-06-30 21:05:18 +00001578 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001579 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001580
Kate Stoneb9c1b512016-09-06 20:57:50 +00001581 // We don't have this thread.
1582 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001583}
1584
Kate Stoneb9c1b512016-09-06 20:57:50 +00001585bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001586 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1587 LLDB_LOG(log, "tid: {0})", thread_id);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001588
1589 bool found = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001590 for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
1591 if (*it && ((*it)->GetID() == thread_id)) {
1592 m_threads.erase(it);
1593 found = true;
1594 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00001595 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001596 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001597
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001598 if (found)
1599 StopTracingForThread(thread_id);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001600 SignalIfAllThreadsStopped();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001601 return found;
Todd Fialaaf245d12014-06-30 21:05:18 +00001602}
1603
Pavel Labatha5be48b2017-10-17 15:52:16 +00001604NativeThreadLinux &NativeProcessLinux::AddThread(lldb::tid_t thread_id) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001605 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
1606 LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
Todd Fialaaf245d12014-06-30 21:05:18 +00001607
Kate Stoneb9c1b512016-09-06 20:57:50 +00001608 assert(!HasThreadNoLock(thread_id) &&
1609 "attempted to add a thread by id that already exists");
Todd Fialaaf245d12014-06-30 21:05:18 +00001610
Kate Stoneb9c1b512016-09-06 20:57:50 +00001611 // If this is the first thread, save it as the current thread
1612 if (m_threads.empty())
1613 SetCurrentThreadID(thread_id);
Todd Fialaaf245d12014-06-30 21:05:18 +00001614
Pavel Labatha5be48b2017-10-17 15:52:16 +00001615 m_threads.push_back(llvm::make_unique<NativeThreadLinux>(*this, thread_id));
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001616
1617 if (m_pt_proces_trace_id != LLDB_INVALID_UID) {
1618 auto traceMonitor = ProcessorTraceMonitor::Create(
1619 GetID(), thread_id, m_pt_process_trace_config, true);
1620 if (traceMonitor) {
1621 m_pt_traced_thread_group.insert(thread_id);
1622 m_processor_trace_monitor.insert(
1623 std::make_pair(thread_id, std::move(*traceMonitor)));
1624 } else {
1625 LLDB_LOG(log, "failed to start trace on thread {0}", thread_id);
1626 Status error(traceMonitor.takeError());
1627 LLDB_LOG(log, "error {0}", error);
1628 }
1629 }
1630
Pavel Labatha5be48b2017-10-17 15:52:16 +00001631 return static_cast<NativeThreadLinux &>(*m_threads.back());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001632}
Todd Fialaaf245d12014-06-30 21:05:18 +00001633
Zachary Turner97206d52017-05-12 04:51:55 +00001634Status NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,
1635 FileSpec &file_spec) {
1636 Status error = PopulateMemoryRegionCache();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001637 if (error.Fail())
1638 return error;
1639
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00001640 FileSpec module_file_spec(module_path);
1641 FileSystem::Instance().Resolve(module_file_spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001642
Kate Stoneb9c1b512016-09-06 20:57:50 +00001643 file_spec.Clear();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001644 for (const auto &it : m_mem_region_cache) {
1645 if (it.second.GetFilename() == module_file_spec.GetFilename()) {
1646 file_spec = it.second;
Zachary Turner97206d52017-05-12 04:51:55 +00001647 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001648 }
1649 }
Zachary Turner97206d52017-05-12 04:51:55 +00001650 return Status("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
1651 module_file_spec.GetFilename().AsCString(), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001652}
1653
Zachary Turner97206d52017-05-12 04:51:55 +00001654Status NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
1655 lldb::addr_t &load_addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001656 load_addr = LLDB_INVALID_ADDRESS;
Zachary Turner97206d52017-05-12 04:51:55 +00001657 Status error = PopulateMemoryRegionCache();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001658 if (error.Fail())
1659 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001660
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00001661 FileSpec file(file_name);
Tamas Berghammera6f57952017-01-03 16:29:43 +00001662 for (const auto &it : m_mem_region_cache) {
1663 if (it.second == file) {
1664 load_addr = it.first.GetRange().GetRangeBase();
Zachary Turner97206d52017-05-12 04:51:55 +00001665 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001666 }
1667 }
Zachary Turner97206d52017-05-12 04:51:55 +00001668 return Status("No load address found for specified file.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001669}
1670
Pavel Labatha5be48b2017-10-17 15:52:16 +00001671NativeThreadLinux *NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {
1672 return static_cast<NativeThreadLinux *>(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001673 NativeProcessProtocol::GetThreadByID(tid));
1674}
1675
Zachary Turner97206d52017-05-12 04:51:55 +00001676Status NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,
1677 lldb::StateType state, int signo) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001678 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1679 LLDB_LOG(log, "tid: {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001680
Adrian Prantl05097242018-04-30 16:49:04 +00001681 // Before we do the resume below, first check if we have a pending stop
1682 // notification that is currently waiting for all threads to stop. This is
1683 // potentially a buggy situation since we're ostensibly waiting for threads
1684 // to stop before we send out the pending notification, and here we are
1685 // resuming one before we send out the pending stop notification.
Pavel Labatha6321a82017-01-19 15:26:04 +00001686 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
1687 LLDB_LOG(log,
1688 "about to resume tid {0} per explicit request but we have a "
1689 "pending stop notification (tid {1}) that is actively "
1690 "waiting for this thread to stop. Valid sequence of events?",
1691 thread.GetID(), m_pending_notification_tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001692 }
1693
Adrian Prantl05097242018-04-30 16:49:04 +00001694 // Request a resume. We expect this to be synchronous and the system to
1695 // reflect it is running after this completes.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001696 switch (state) {
1697 case eStateRunning: {
1698 const auto resume_result = thread.Resume(signo);
1699 if (resume_result.Success())
1700 SetState(eStateRunning, true);
1701 return resume_result;
1702 }
1703 case eStateStepping: {
1704 const auto step_result = thread.SingleStep(signo);
1705 if (step_result.Success())
1706 SetState(eStateRunning, true);
1707 return step_result;
1708 }
1709 default:
Pavel Labath8198db32017-01-24 11:48:25 +00001710 LLDB_LOG(log, "Unhandled state {0}.", state);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001711 llvm_unreachable("Unhandled state for resume");
1712 }
Pavel Labathc0765592015-05-06 10:46:34 +00001713}
1714
1715//===----------------------------------------------------------------------===//
1716
Kate Stoneb9c1b512016-09-06 20:57:50 +00001717void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001718 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1719 LLDB_LOG(log, "about to process event: (triggering_tid: {0})",
1720 triggering_tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001721
1722 m_pending_notification_tid = triggering_tid;
1723
Adrian Prantl05097242018-04-30 16:49:04 +00001724 // Request a stop for all the thread stops that need to be stopped and are
1725 // not already known to be stopped.
Pavel Labatha5be48b2017-10-17 15:52:16 +00001726 for (const auto &thread : m_threads) {
1727 if (StateIsRunningState(thread->GetState()))
1728 static_cast<NativeThreadLinux *>(thread.get())->RequestStop();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001729 }
1730
1731 SignalIfAllThreadsStopped();
Pavel Labatha6321a82017-01-19 15:26:04 +00001732 LLDB_LOG(log, "event processing done");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001733}
1734
1735void NativeProcessLinux::SignalIfAllThreadsStopped() {
1736 if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
1737 return; // No pending notification. Nothing to do.
1738
1739 for (const auto &thread_sp : m_threads) {
1740 if (StateIsRunningState(thread_sp->GetState()))
1741 return; // Some threads are still running. Don't signal yet.
1742 }
1743
1744 // We have a pending notification and all threads have stopped.
1745 Log *log(
1746 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
1747
1748 // Clear any temporary breakpoints we used to implement software single
1749 // stepping.
1750 for (const auto &thread_info : m_threads_stepping_with_breakpoint) {
Zachary Turner97206d52017-05-12 04:51:55 +00001751 Status error = RemoveBreakpoint(thread_info.second);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001752 if (error.Fail())
Pavel Labatha6321a82017-01-19 15:26:04 +00001753 LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}",
1754 thread_info.first, error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001755 }
1756 m_threads_stepping_with_breakpoint.clear();
1757
1758 // Notify the delegate about the stop
1759 SetCurrentThreadID(m_pending_notification_tid);
1760 SetState(StateType::eStateStopped, true);
1761 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
1762}
1763
1764void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001765 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1766 LLDB_LOG(log, "tid: {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001767
1768 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID &&
1769 StateIsRunningState(thread.GetState())) {
1770 // We will need to wait for this new thread to stop as well before firing
Adrian Prantl05097242018-04-30 16:49:04 +00001771 // the notification.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001772 thread.RequestStop();
1773 }
1774}
1775
1776void NativeProcessLinux::SigchldHandler() {
Pavel Labatha6321a82017-01-19 15:26:04 +00001777 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001778 // Process all pending waitpid notifications.
1779 while (true) {
1780 int status = -1;
Pavel Labathc1a6b122017-07-03 09:25:55 +00001781 ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, -1, &status,
1782 __WALL | __WNOTHREAD | WNOHANG);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001783
1784 if (wait_pid == 0)
1785 break; // We are done.
1786
1787 if (wait_pid == -1) {
Zachary Turner97206d52017-05-12 04:51:55 +00001788 Status error(errno, eErrorTypePOSIX);
Pavel Labatha6321a82017-01-19 15:26:04 +00001789 LLDB_LOG(log, "waitpid (-1, &status, _) failed: {0}", error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001790 break;
Pavel Labathc0765592015-05-06 10:46:34 +00001791 }
1792
Pavel Labath3508fc82017-06-19 12:47:50 +00001793 WaitStatus wait_status = WaitStatus::Decode(status);
1794 bool exited = wait_status.type == WaitStatus::Exit ||
1795 (wait_status.type == WaitStatus::Signal &&
1796 wait_pid == static_cast<::pid_t>(GetID()));
Pavel Labathc0765592015-05-06 10:46:34 +00001797
Pavel Labath3508fc82017-06-19 12:47:50 +00001798 LLDB_LOG(
1799 log,
1800 "waitpid (-1, &status, _) => pid = {0}, status = {1}, exited = {2}",
1801 wait_pid, wait_status, exited);
Pavel Labathc0765592015-05-06 10:46:34 +00001802
Pavel Labath3508fc82017-06-19 12:47:50 +00001803 MonitorCallback(wait_pid, exited, wait_status);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001804 }
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001805}
1806
Adrian Prantl05097242018-04-30 16:49:04 +00001807// Wrapper for ptrace to catch errors and log calls. Note that ptrace sets
1808// errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
Zachary Turner97206d52017-05-12 04:51:55 +00001809Status NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
1810 void *data, size_t data_size,
1811 long *result) {
1812 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001813 long int ret;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001814
Kate Stoneb9c1b512016-09-06 20:57:50 +00001815 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001816
Kate Stoneb9c1b512016-09-06 20:57:50 +00001817 PtraceDisplayBytes(req, data, data_size);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001818
Kate Stoneb9c1b512016-09-06 20:57:50 +00001819 errno = 0;
1820 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
1821 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
1822 *(unsigned int *)addr, data);
1823 else
1824 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
1825 addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001826
Kate Stoneb9c1b512016-09-06 20:57:50 +00001827 if (ret == -1)
1828 error.SetErrorToErrno();
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001829
Kate Stoneb9c1b512016-09-06 20:57:50 +00001830 if (result)
1831 *result = ret;
Pavel Labath4a9babb2015-06-30 17:04:49 +00001832
Pavel Labath28096202017-02-17 16:09:10 +00001833 LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data,
1834 data_size, ret);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001835
Kate Stoneb9c1b512016-09-06 20:57:50 +00001836 PtraceDisplayBytes(req, data, data_size);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001837
Pavel Labatha6321a82017-01-19 15:26:04 +00001838 if (error.Fail())
1839 LLDB_LOG(log, "ptrace() failed: {0}", error);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001840
Kate Stoneb9c1b512016-09-06 20:57:50 +00001841 return error;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001842}
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001843
1844llvm::Expected<ProcessorTraceMonitor &>
1845NativeProcessLinux::LookupProcessorTraceInstance(lldb::user_id_t traceid,
1846 lldb::tid_t thread) {
1847 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
1848 if (thread == LLDB_INVALID_THREAD_ID && traceid == m_pt_proces_trace_id) {
1849 LLDB_LOG(log, "thread not specified: {0}", traceid);
1850 return Status("tracing not active thread not specified").ToError();
1851 }
1852
1853 for (auto& iter : m_processor_trace_monitor) {
1854 if (traceid == iter.second->GetTraceID() &&
1855 (thread == iter.first || thread == LLDB_INVALID_THREAD_ID))
1856 return *(iter.second);
1857 }
1858
1859 LLDB_LOG(log, "traceid not being traced: {0}", traceid);
1860 return Status("tracing not active for this thread").ToError();
1861}
1862
1863Status NativeProcessLinux::GetMetaData(lldb::user_id_t traceid,
1864 lldb::tid_t thread,
1865 llvm::MutableArrayRef<uint8_t> &buffer,
1866 size_t offset) {
1867 TraceOptions trace_options;
1868 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
1869 Status error;
1870
1871 LLDB_LOG(log, "traceid {0}", traceid);
1872
1873 auto perf_monitor = LookupProcessorTraceInstance(traceid, thread);
1874 if (!perf_monitor) {
1875 LLDB_LOG(log, "traceid not being traced: {0}", traceid);
1876 buffer = buffer.slice(buffer.size());
1877 error = perf_monitor.takeError();
1878 return error;
1879 }
1880 return (*perf_monitor).ReadPerfTraceData(buffer, offset);
1881}
1882
1883Status NativeProcessLinux::GetData(lldb::user_id_t traceid, lldb::tid_t thread,
1884 llvm::MutableArrayRef<uint8_t> &buffer,
1885 size_t offset) {
1886 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
1887 Status error;
1888
1889 LLDB_LOG(log, "traceid {0}", traceid);
1890
1891 auto perf_monitor = LookupProcessorTraceInstance(traceid, thread);
1892 if (!perf_monitor) {
1893 LLDB_LOG(log, "traceid not being traced: {0}", traceid);
1894 buffer = buffer.slice(buffer.size());
1895 error = perf_monitor.takeError();
1896 return error;
1897 }
1898 return (*perf_monitor).ReadPerfTraceAux(buffer, offset);
1899}
1900
1901Status NativeProcessLinux::GetTraceConfig(lldb::user_id_t traceid,
1902 TraceOptions &config) {
1903 Status error;
1904 if (config.getThreadID() == LLDB_INVALID_THREAD_ID &&
1905 m_pt_proces_trace_id == traceid) {
1906 if (m_pt_proces_trace_id == LLDB_INVALID_UID) {
1907 error.SetErrorString("tracing not active for this process");
1908 return error;
1909 }
1910 config = m_pt_process_trace_config;
1911 } else {
1912 auto perf_monitor =
1913 LookupProcessorTraceInstance(traceid, config.getThreadID());
1914 if (!perf_monitor) {
1915 error = perf_monitor.takeError();
1916 return error;
1917 }
1918 error = (*perf_monitor).GetTraceConfig(config);
1919 }
1920 return error;
1921}
1922
1923lldb::user_id_t
1924NativeProcessLinux::StartTraceGroup(const TraceOptions &config,
1925 Status &error) {
1926
1927 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
1928 if (config.getType() != TraceType::eTraceTypeProcessorTrace)
1929 return LLDB_INVALID_UID;
1930
1931 if (m_pt_proces_trace_id != LLDB_INVALID_UID) {
1932 error.SetErrorString("tracing already active on this process");
1933 return m_pt_proces_trace_id;
1934 }
1935
1936 for (const auto &thread_sp : m_threads) {
1937 if (auto traceInstance = ProcessorTraceMonitor::Create(
1938 GetID(), thread_sp->GetID(), config, true)) {
1939 m_pt_traced_thread_group.insert(thread_sp->GetID());
1940 m_processor_trace_monitor.insert(
1941 std::make_pair(thread_sp->GetID(), std::move(*traceInstance)));
1942 }
1943 }
1944
1945 m_pt_process_trace_config = config;
1946 error = ProcessorTraceMonitor::GetCPUType(m_pt_process_trace_config);
1947
1948 // Trace on Complete process will have traceid of 0
1949 m_pt_proces_trace_id = 0;
1950
1951 LLDB_LOG(log, "Process Trace ID {0}", m_pt_proces_trace_id);
1952 return m_pt_proces_trace_id;
1953}
1954
1955lldb::user_id_t NativeProcessLinux::StartTrace(const TraceOptions &config,
1956 Status &error) {
1957 if (config.getType() != TraceType::eTraceTypeProcessorTrace)
1958 return NativeProcessProtocol::StartTrace(config, error);
1959
1960 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
1961
1962 lldb::tid_t threadid = config.getThreadID();
1963
1964 if (threadid == LLDB_INVALID_THREAD_ID)
1965 return StartTraceGroup(config, error);
1966
1967 auto thread_sp = GetThreadByID(threadid);
1968 if (!thread_sp) {
1969 // Thread not tracked by lldb so don't trace.
1970 error.SetErrorString("invalid thread id");
1971 return LLDB_INVALID_UID;
1972 }
1973
1974 const auto &iter = m_processor_trace_monitor.find(threadid);
1975 if (iter != m_processor_trace_monitor.end()) {
1976 LLDB_LOG(log, "Thread already being traced");
1977 error.SetErrorString("tracing already active on this thread");
1978 return LLDB_INVALID_UID;
1979 }
1980
1981 auto traceMonitor =
1982 ProcessorTraceMonitor::Create(GetID(), threadid, config, false);
1983 if (!traceMonitor) {
1984 error = traceMonitor.takeError();
1985 LLDB_LOG(log, "error {0}", error);
1986 return LLDB_INVALID_UID;
1987 }
1988 lldb::user_id_t ret_trace_id = (*traceMonitor)->GetTraceID();
1989 m_processor_trace_monitor.insert(
1990 std::make_pair(threadid, std::move(*traceMonitor)));
1991 return ret_trace_id;
1992}
1993
1994Status NativeProcessLinux::StopTracingForThread(lldb::tid_t thread) {
1995 Status error;
1996 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
1997 LLDB_LOG(log, "Thread {0}", thread);
1998
1999 const auto& iter = m_processor_trace_monitor.find(thread);
2000 if (iter == m_processor_trace_monitor.end()) {
2001 error.SetErrorString("tracing not active for this thread");
2002 return error;
2003 }
2004
2005 if (iter->second->GetTraceID() == m_pt_proces_trace_id) {
Adrian Prantl05097242018-04-30 16:49:04 +00002006 // traceid maps to the whole process so we have to erase it from the thread
2007 // group.
Ravitheja Addepally99e37692017-06-28 07:58:31 +00002008 LLDB_LOG(log, "traceid maps to process");
2009 m_pt_traced_thread_group.erase(thread);
2010 }
2011 m_processor_trace_monitor.erase(iter);
2012
2013 return error;
2014}
2015
2016Status NativeProcessLinux::StopTrace(lldb::user_id_t traceid,
2017 lldb::tid_t thread) {
2018 Status error;
2019
2020 TraceOptions trace_options;
2021 trace_options.setThreadID(thread);
2022 error = NativeProcessLinux::GetTraceConfig(traceid, trace_options);
2023
2024 if (error.Fail())
2025 return error;
2026
2027 switch (trace_options.getType()) {
2028 case lldb::TraceType::eTraceTypeProcessorTrace:
2029 if (traceid == m_pt_proces_trace_id &&
2030 thread == LLDB_INVALID_THREAD_ID)
2031 StopProcessorTracingOnProcess();
2032 else
2033 error = StopProcessorTracingOnThread(traceid, thread);
2034 break;
2035 default:
2036 error.SetErrorString("trace not supported");
2037 break;
2038 }
2039
2040 return error;
2041}
2042
2043void NativeProcessLinux::StopProcessorTracingOnProcess() {
2044 for (auto thread_id_iter : m_pt_traced_thread_group)
2045 m_processor_trace_monitor.erase(thread_id_iter);
2046 m_pt_traced_thread_group.clear();
2047 m_pt_proces_trace_id = LLDB_INVALID_UID;
2048}
2049
2050Status NativeProcessLinux::StopProcessorTracingOnThread(lldb::user_id_t traceid,
2051 lldb::tid_t thread) {
2052 Status error;
2053 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2054
2055 if (thread == LLDB_INVALID_THREAD_ID) {
2056 for (auto& iter : m_processor_trace_monitor) {
2057 if (iter.second->GetTraceID() == traceid) {
Adrian Prantl05097242018-04-30 16:49:04 +00002058 // Stopping a trace instance for an individual thread hence there will
2059 // only be one traceid that can match.
Ravitheja Addepally99e37692017-06-28 07:58:31 +00002060 m_processor_trace_monitor.erase(iter.first);
2061 return error;
2062 }
2063 LLDB_LOG(log, "Trace ID {0}", iter.second->GetTraceID());
2064 }
2065
2066 LLDB_LOG(log, "Invalid TraceID");
2067 error.SetErrorString("invalid trace id");
2068 return error;
2069 }
2070
2071 // thread is specified so we can use find function on the map.
2072 const auto& iter = m_processor_trace_monitor.find(thread);
2073 if (iter == m_processor_trace_monitor.end()) {
2074 // thread not found in our map.
2075 LLDB_LOG(log, "thread not being traced");
2076 error.SetErrorString("tracing not active for this thread");
2077 return error;
2078 }
2079 if (iter->second->GetTraceID() != traceid) {
2080 // traceid did not match so it has to be invalid.
2081 LLDB_LOG(log, "Invalid TraceID");
2082 error.SetErrorString("invalid trace id");
2083 return error;
2084 }
2085
2086 LLDB_LOG(log, "UID - {0} , Thread -{1}", traceid, thread);
2087
2088 if (traceid == m_pt_proces_trace_id) {
Adrian Prantl05097242018-04-30 16:49:04 +00002089 // traceid maps to the whole process so we have to erase it from the thread
2090 // group.
Ravitheja Addepally99e37692017-06-28 07:58:31 +00002091 LLDB_LOG(log, "traceid maps to process");
2092 m_pt_traced_thread_group.erase(thread);
2093 }
2094 m_processor_trace_monitor.erase(iter);
2095
2096 return error;
2097}