blob: 7637237aa16bb3c1e598a1865bc7877ef238a6b8 [file] [log] [blame]
Todd Fialaaf245d12014-06-30 21:05:18 +00001//===-- NativeProcessLinux.cpp -------------------------------- -*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Todd Fialaaf245d12014-06-30 21:05:18 +00006//
7//===----------------------------------------------------------------------===//
8
Todd Fialaaf245d12014-06-30 21:05:18 +00009#include "NativeProcessLinux.h"
10
Todd Fialaaf245d12014-06-30 21:05:18 +000011#include <errno.h>
Todd Fialaaf245d12014-06-30 21:05:18 +000012#include <stdint.h>
Kate Stoneb9c1b512016-09-06 20:57:50 +000013#include <string.h>
Todd Fialaaf245d12014-06-30 21:05:18 +000014#include <unistd.h>
Todd Fialaaf245d12014-06-30 21:05:18 +000015
Todd Fialaaf245d12014-06-30 21:05:18 +000016#include <fstream>
Pavel Labathdf7c6992015-06-17 18:38:49 +000017#include <mutex>
Pavel Labathc0765592015-05-06 10:46:34 +000018#include <sstream>
Todd Fialaaf245d12014-06-30 21:05:18 +000019#include <string>
Pavel Labath5b981ab2015-05-29 12:53:54 +000020#include <unordered_map>
Todd Fialaaf245d12014-06-30 21:05:18 +000021
Tamas Berghammerd8c338d2015-04-15 09:47:02 +000022#include "lldb/Core/EmulateInstruction.h"
Oleksiy Vyalov6edef202014-11-17 22:16:42 +000023#include "lldb/Core/ModuleSpec.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000024#include "lldb/Host/Host.h"
Pavel Labath5ad891f2016-07-21 14:54:03 +000025#include "lldb/Host/HostProcess.h"
Pavel Labatheef758e2019-02-04 14:28:08 +000026#include "lldb/Host/ProcessLaunchInfo.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"
Pavel Labath5b981ab2015-05-29 12:53:54 +000035#include "lldb/Target/Target.h"
Chaoren Linc16f5dc2015-03-19 23:28:10 +000036#include "lldb/Utility/LLDBAssert.h"
Pavel Labathd821c992018-08-07 11:07:21 +000037#include "lldb/Utility/RegisterValue.h"
38#include "lldb/Utility/State.h"
Zachary Turner97206d52017-05-12 04:51:55 +000039#include "lldb/Utility/Status.h"
Pavel Labathf805e192015-07-07 10:08:41 +000040#include "lldb/Utility/StringExtractor.h"
Pavel Labath10c41f32017-06-06 14:06:17 +000041#include "llvm/Support/Errno.h"
42#include "llvm/Support/FileSystem.h"
43#include "llvm/Support/Threading.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000044
Todd Fialaaf245d12014-06-30 21:05:18 +000045#include "NativeThreadLinux.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000046#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
Pavel Labathc8e364e82018-12-15 13:38:16 +000047#include "Plugins/Process/Utility/LinuxProcMaps.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000048#include "Procfs.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000049
Tamas Berghammerd8584872015-02-06 10:57:40 +000050#include <linux/unistd.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000051#include <sys/socket.h>
Pavel Labathdf7c6992015-06-17 18:38:49 +000052#include <sys/syscall.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000053#include <sys/types.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000054#include <sys/user.h>
55#include <sys/wait.h>
56
Todd Fialaaf245d12014-06-30 21:05:18 +000057// Support hardware breakpoints in case it has not been defined
58#ifndef TRAP_HWBKPT
Kate Stoneb9c1b512016-09-06 20:57:50 +000059#define TRAP_HWBKPT 4
Todd Fialaaf245d12014-06-30 21:05:18 +000060#endif
61
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000062using namespace lldb;
63using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000064using namespace lldb_private::process_linux;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000065using namespace llvm;
66
Todd Fialaaf245d12014-06-30 21:05:18 +000067// Private bits we only need internally.
Pavel Labathdf7c6992015-06-17 18:38:49 +000068
Kate Stoneb9c1b512016-09-06 20:57:50 +000069static bool ProcessVmReadvSupported() {
70 static bool is_supported;
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000071 static llvm::once_flag flag;
Pavel Labathdf7c6992015-06-17 18:38:49 +000072
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000073 llvm::call_once(flag, [] {
Pavel Labatha6321a82017-01-19 15:26:04 +000074 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Pavel Labath4abe5d62016-07-15 10:18:15 +000075
Kate Stoneb9c1b512016-09-06 20:57:50 +000076 uint32_t source = 0x47424742;
77 uint32_t dest = 0;
Pavel Labath4abe5d62016-07-15 10:18:15 +000078
Kate Stoneb9c1b512016-09-06 20:57:50 +000079 struct iovec local, remote;
80 remote.iov_base = &source;
81 local.iov_base = &dest;
82 remote.iov_len = local.iov_len = sizeof source;
Pavel Labath4abe5d62016-07-15 10:18:15 +000083
Kate Stoneb9c1b512016-09-06 20:57:50 +000084 // We shall try if cross-process-memory reads work by attempting to read a
85 // value from our own process.
86 ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
87 is_supported = (res == sizeof(source) && source == dest);
Pavel Labatha6321a82017-01-19 15:26:04 +000088 if (is_supported)
89 LLDB_LOG(log,
90 "Detected kernel support for process_vm_readv syscall. "
91 "Fast memory reads enabled.");
92 else
93 LLDB_LOG(log,
94 "syscall process_vm_readv failed (error: {0}). Fast memory "
95 "reads disabled.",
Pavel Labath10c41f32017-06-06 14:06:17 +000096 llvm::sys::StrError());
Kate Stoneb9c1b512016-09-06 20:57:50 +000097 });
Pavel Labath4abe5d62016-07-15 10:18:15 +000098
Kate Stoneb9c1b512016-09-06 20:57:50 +000099 return is_supported;
Pavel Labath4abe5d62016-07-15 10:18:15 +0000100}
101
Kate Stoneb9c1b512016-09-06 20:57:50 +0000102namespace {
103void MaybeLogLaunchInfo(const ProcessLaunchInfo &info) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000104 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000105 if (!log)
106 return;
107
108 if (const FileAction *action = info.GetFileActionForFD(STDIN_FILENO))
Pavel Labatha6321a82017-01-19 15:26:04 +0000109 LLDB_LOG(log, "setting STDIN to '{0}'", action->GetFileSpec());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000110 else
Pavel Labatha6321a82017-01-19 15:26:04 +0000111 LLDB_LOG(log, "leaving STDIN as is");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000112
113 if (const FileAction *action = info.GetFileActionForFD(STDOUT_FILENO))
Pavel Labatha6321a82017-01-19 15:26:04 +0000114 LLDB_LOG(log, "setting STDOUT to '{0}'", action->GetFileSpec());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000115 else
Pavel Labatha6321a82017-01-19 15:26:04 +0000116 LLDB_LOG(log, "leaving STDOUT as is");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000117
118 if (const FileAction *action = info.GetFileActionForFD(STDERR_FILENO))
Pavel Labatha6321a82017-01-19 15:26:04 +0000119 LLDB_LOG(log, "setting STDERR to '{0}'", action->GetFileSpec());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000120 else
Pavel Labatha6321a82017-01-19 15:26:04 +0000121 LLDB_LOG(log, "leaving STDERR as is");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000122
123 int i = 0;
124 for (const char **args = info.GetArguments().GetConstArgumentVector(); *args;
125 ++args, ++i)
Pavel Labatha6321a82017-01-19 15:26:04 +0000126 LLDB_LOG(log, "arg {0}: '{1}'", i, *args);
Pavel Labath4abe5d62016-07-15 10:18:15 +0000127}
Todd Fialaaf245d12014-06-30 21:05:18 +0000128
Kate Stoneb9c1b512016-09-06 20:57:50 +0000129void DisplayBytes(StreamString &s, void *bytes, uint32_t count) {
130 uint8_t *ptr = (uint8_t *)bytes;
131 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
132 for (uint32_t i = 0; i < loop_count; i++) {
133 s.Printf("[%x]", *ptr);
134 ptr++;
135 }
136}
Todd Fialaaf245d12014-06-30 21:05:18 +0000137
Kate Stoneb9c1b512016-09-06 20:57:50 +0000138void PtraceDisplayBytes(int &req, void *data, size_t data_size) {
Pavel Labathaafe0532017-02-06 19:31:05 +0000139 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
Pavel Labatha6321a82017-01-19 15:26:04 +0000140 if (!log)
141 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000142 StreamString buf;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000143
Pavel Labatha6321a82017-01-19 15:26:04 +0000144 switch (req) {
145 case PTRACE_POKETEXT: {
146 DisplayBytes(buf, &data, 8);
Pavel Labathaafe0532017-02-06 19:31:05 +0000147 LLDB_LOGV(log, "PTRACE_POKETEXT {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000148 break;
149 }
150 case PTRACE_POKEDATA: {
151 DisplayBytes(buf, &data, 8);
Pavel Labathaafe0532017-02-06 19:31:05 +0000152 LLDB_LOGV(log, "PTRACE_POKEDATA {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000153 break;
154 }
155 case PTRACE_POKEUSER: {
156 DisplayBytes(buf, &data, 8);
Pavel Labathaafe0532017-02-06 19:31:05 +0000157 LLDB_LOGV(log, "PTRACE_POKEUSER {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000158 break;
159 }
160 case PTRACE_SETREGS: {
161 DisplayBytes(buf, data, data_size);
Pavel Labathaafe0532017-02-06 19:31:05 +0000162 LLDB_LOGV(log, "PTRACE_SETREGS {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000163 break;
164 }
165 case PTRACE_SETFPREGS: {
166 DisplayBytes(buf, data, data_size);
Pavel Labathaafe0532017-02-06 19:31:05 +0000167 LLDB_LOGV(log, "PTRACE_SETFPREGS {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000168 break;
169 }
170 case PTRACE_SETSIGINFO: {
171 DisplayBytes(buf, data, sizeof(siginfo_t));
Pavel Labathaafe0532017-02-06 19:31:05 +0000172 LLDB_LOGV(log, "PTRACE_SETSIGINFO {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000173 break;
174 }
175 case PTRACE_SETREGSET: {
Pavel Labath11edb4e2017-12-01 12:05:00 +0000176 // Extract iov_base from data, which is a pointer to the struct iovec
Pavel Labatha6321a82017-01-19 15:26:04 +0000177 DisplayBytes(buf, *(void **)data, data_size);
Pavel Labathaafe0532017-02-06 19:31:05 +0000178 LLDB_LOGV(log, "PTRACE_SETREGSET {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000179 break;
180 }
181 default: {}
Kate Stoneb9c1b512016-09-06 20:57:50 +0000182 }
183}
Todd Fialaaf245d12014-06-30 21:05:18 +0000184
Kate Stoneb9c1b512016-09-06 20:57:50 +0000185static constexpr unsigned k_ptrace_word_size = sizeof(void *);
186static_assert(sizeof(long) >= k_ptrace_word_size,
187 "Size of long must be larger than ptrace word size");
Pavel Labath1107b5a2015-04-17 14:07:49 +0000188} // end of anonymous namespace
189
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000190// Simple helper function to ensure flags are enabled on the given file
191// descriptor.
Zachary Turner97206d52017-05-12 04:51:55 +0000192static Status EnsureFDFlags(int fd, int flags) {
193 Status error;
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000194
Kate Stoneb9c1b512016-09-06 20:57:50 +0000195 int status = fcntl(fd, F_GETFL);
196 if (status == -1) {
197 error.SetErrorToErrno();
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000198 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000199 }
200
201 if (fcntl(fd, F_SETFL, status | flags) == -1) {
202 error.SetErrorToErrno();
203 return error;
204 }
205
206 return error;
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000207}
208
Todd Fialaaf245d12014-06-30 21:05:18 +0000209// Public Static Methods
Todd Fialaaf245d12014-06-30 21:05:18 +0000210
Pavel Labath82abefa2017-07-18 09:24:48 +0000211llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
Pavel Labath96e600f2017-07-07 11:02:19 +0000212NativeProcessLinux::Factory::Launch(ProcessLaunchInfo &launch_info,
213 NativeDelegate &native_delegate,
214 MainLoop &mainloop) const {
Pavel Labatha6321a82017-01-19 15:26:04 +0000215 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Todd Fialaaf245d12014-06-30 21:05:18 +0000216
Pavel Labath96e600f2017-07-07 11:02:19 +0000217 MaybeLogLaunchInfo(launch_info);
Todd Fialaaf245d12014-06-30 21:05:18 +0000218
Pavel Labath96e600f2017-07-07 11:02:19 +0000219 Status status;
220 ::pid_t pid = ProcessLauncherPosixFork()
221 .LaunchProcess(launch_info, status)
222 .GetProcessId();
223 LLDB_LOG(log, "pid = {0:x}", pid);
224 if (status.Fail()) {
225 LLDB_LOG(log, "failed to launch process: {0}", status);
226 return status.ToError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000227 }
228
Pavel Labath96e600f2017-07-07 11:02:19 +0000229 // Wait for the child process to trap on its call to execve.
230 int wstatus;
231 ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0);
232 assert(wpid == pid);
233 (void)wpid;
234 if (!WIFSTOPPED(wstatus)) {
235 LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}",
236 WaitStatus::Decode(wstatus));
237 return llvm::make_error<StringError>("Could not sync with inferior process",
238 llvm::inconvertibleErrorCode());
239 }
240 LLDB_LOG(log, "inferior started, now in stopped state");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000241
Pavel Labath36e82202018-01-29 10:46:00 +0000242 ProcessInstanceInfo Info;
243 if (!Host::GetProcessInfo(pid, Info)) {
244 return llvm::make_error<StringError>("Cannot get process architecture",
245 llvm::inconvertibleErrorCode());
246 }
Pavel Labath96e600f2017-07-07 11:02:19 +0000247
248 // Set the architecture to the exe architecture.
249 LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid,
Pavel Labath36e82202018-01-29 10:46:00 +0000250 Info.GetArchitecture().GetArchitectureName());
Pavel Labath96e600f2017-07-07 11:02:19 +0000251
252 status = SetDefaultPtraceOpts(pid);
253 if (status.Fail()) {
254 LLDB_LOG(log, "failed to set default ptrace options: {0}", status);
255 return status.ToError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000256 }
257
Pavel Labath82abefa2017-07-18 09:24:48 +0000258 return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
Pavel Labath96e600f2017-07-07 11:02:19 +0000259 pid, launch_info.GetPTY().ReleaseMasterFileDescriptor(), native_delegate,
Pavel Labath36e82202018-01-29 10:46:00 +0000260 Info.GetArchitecture(), mainloop, {pid}));
Todd Fialaaf245d12014-06-30 21:05:18 +0000261}
262
Pavel Labath82abefa2017-07-18 09:24:48 +0000263llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
264NativeProcessLinux::Factory::Attach(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000265 lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
Pavel Labath96e600f2017-07-07 11:02:19 +0000266 MainLoop &mainloop) const {
Pavel Labatha6321a82017-01-19 15:26:04 +0000267 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
268 LLDB_LOG(log, "pid = {0:x}", pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000269
Kate Stoneb9c1b512016-09-06 20:57:50 +0000270 // Retrieve the architecture for the running process.
Pavel Labath36e82202018-01-29 10:46:00 +0000271 ProcessInstanceInfo Info;
272 if (!Host::GetProcessInfo(pid, Info)) {
273 return llvm::make_error<StringError>("Cannot get process architecture",
274 llvm::inconvertibleErrorCode());
275 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000276
Pavel Labath96e600f2017-07-07 11:02:19 +0000277 auto tids_or = NativeProcessLinux::Attach(pid);
278 if (!tids_or)
279 return tids_or.takeError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000280
Pavel Labath82abefa2017-07-18 09:24:48 +0000281 return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
Pavel Labath36e82202018-01-29 10:46:00 +0000282 pid, -1, native_delegate, Info.GetArchitecture(), mainloop, *tids_or));
Todd Fialaaf245d12014-06-30 21:05:18 +0000283}
284
Todd Fialaaf245d12014-06-30 21:05:18 +0000285// Public Instance Methods
Todd Fialaaf245d12014-06-30 21:05:18 +0000286
Pavel Labath96e600f2017-07-07 11:02:19 +0000287NativeProcessLinux::NativeProcessLinux(::pid_t pid, int terminal_fd,
288 NativeDelegate &delegate,
Pavel Labath82abefa2017-07-18 09:24:48 +0000289 const ArchSpec &arch, MainLoop &mainloop,
290 llvm::ArrayRef<::pid_t> tids)
Antonio Afonsof4335b82019-06-14 21:15:08 +0000291 : NativeProcessELF(pid, terminal_fd, delegate), m_arch(arch) {
Pavel Labath96e600f2017-07-07 11:02:19 +0000292 if (m_terminal_fd != -1) {
293 Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
294 assert(status.Success());
295 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000296
Pavel Labath96e600f2017-07-07 11:02:19 +0000297 Status status;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000298 m_sigchld_handle = mainloop.RegisterSignal(
Pavel Labath96e600f2017-07-07 11:02:19 +0000299 SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status);
300 assert(m_sigchld_handle && status.Success());
Todd Fialaaf245d12014-06-30 21:05:18 +0000301
Pavel Labath96e600f2017-07-07 11:02:19 +0000302 for (const auto &tid : tids) {
Pavel Labatha5be48b2017-10-17 15:52:16 +0000303 NativeThreadLinux &thread = AddThread(tid);
304 thread.SetStoppedBySignal(SIGSTOP);
305 ThreadWasCreated(thread);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000306 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000307
Kate Stoneb9c1b512016-09-06 20:57:50 +0000308 // Let our process instance know the thread has stopped.
Pavel Labath96e600f2017-07-07 11:02:19 +0000309 SetCurrentThreadID(tids[0]);
310 SetState(StateType::eStateStopped, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000311
Pavel Labath96e600f2017-07-07 11:02:19 +0000312 // Proccess any signals we received before installing our handler
313 SigchldHandler();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000314}
315
Pavel Labath96e600f2017-07-07 11:02:19 +0000316llvm::Expected<std::vector<::pid_t>> NativeProcessLinux::Attach(::pid_t pid) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000317 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000318
Pavel Labath96e600f2017-07-07 11:02:19 +0000319 Status status;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000320 // Use a map to keep track of the threads which we have attached/need to
321 // attach.
322 Host::TidMap tids_to_attach;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000323 while (Host::FindProcessThreads(pid, tids_to_attach)) {
324 for (Host::TidMap::iterator it = tids_to_attach.begin();
325 it != tids_to_attach.end();) {
326 if (it->second == false) {
327 lldb::tid_t tid = it->first;
328
329 // Attach to the requested process.
330 // An attach will cause the thread to stop with a SIGSTOP.
Pavel Labath96e600f2017-07-07 11:02:19 +0000331 if ((status = PtraceWrapper(PTRACE_ATTACH, tid)).Fail()) {
Adrian Prantl05097242018-04-30 16:49:04 +0000332 // No such thread. The thread may have exited. More error handling
333 // may be needed.
Pavel Labath96e600f2017-07-07 11:02:19 +0000334 if (status.GetError() == ESRCH) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000335 it = tids_to_attach.erase(it);
336 continue;
Pavel Labath96e600f2017-07-07 11:02:19 +0000337 }
338 return status.ToError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000339 }
340
Pavel Labath96e600f2017-07-07 11:02:19 +0000341 int wpid =
342 llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, nullptr, __WALL);
Adrian Prantl05097242018-04-30 16:49:04 +0000343 // Need to use __WALL otherwise we receive an error with errno=ECHLD At
344 // this point we should have a thread stopped if waitpid succeeds.
Pavel Labath96e600f2017-07-07 11:02:19 +0000345 if (wpid < 0) {
Adrian Prantl05097242018-04-30 16:49:04 +0000346 // No such thread. The thread may have exited. More error handling
347 // may be needed.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000348 if (errno == ESRCH) {
349 it = tids_to_attach.erase(it);
350 continue;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000351 }
Pavel Labath96e600f2017-07-07 11:02:19 +0000352 return llvm::errorCodeToError(
353 std::error_code(errno, std::generic_category()));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000354 }
355
Pavel Labath96e600f2017-07-07 11:02:19 +0000356 if ((status = SetDefaultPtraceOpts(tid)).Fail())
357 return status.ToError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000358
Pavel Labatha6321a82017-01-19 15:26:04 +0000359 LLDB_LOG(log, "adding tid = {0}", tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000360 it->second = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000361 }
362
363 // move the loop forward
364 ++it;
365 }
366 }
367
Pavel Labath96e600f2017-07-07 11:02:19 +0000368 size_t tid_count = tids_to_attach.size();
369 if (tid_count == 0)
370 return llvm::make_error<StringError>("No such process",
371 llvm::inconvertibleErrorCode());
Todd Fialaaf245d12014-06-30 21:05:18 +0000372
Pavel Labath96e600f2017-07-07 11:02:19 +0000373 std::vector<::pid_t> tids;
374 tids.reserve(tid_count);
375 for (const auto &p : tids_to_attach)
376 tids.push_back(p.first);
377 return std::move(tids);
Todd Fialaaf245d12014-06-30 21:05:18 +0000378}
379
Zachary Turner97206d52017-05-12 04:51:55 +0000380Status NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000381 long ptrace_opts = 0;
Todd Fialaaf245d12014-06-30 21:05:18 +0000382
Kate Stoneb9c1b512016-09-06 20:57:50 +0000383 // Have the child raise an event on exit. This is used to keep the child in
384 // limbo until it is destroyed.
385 ptrace_opts |= PTRACE_O_TRACEEXIT;
Todd Fialaaf245d12014-06-30 21:05:18 +0000386
Kate Stoneb9c1b512016-09-06 20:57:50 +0000387 // Have the tracer trace threads which spawn in the inferior process.
388 // TODO: if we want to support tracing the inferiors' child, add the
389 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
390 ptrace_opts |= PTRACE_O_TRACECLONE;
Todd Fialaaf245d12014-06-30 21:05:18 +0000391
Adrian Prantl05097242018-04-30 16:49:04 +0000392 // Have the tracer notify us before execve returns (needed to disable legacy
393 // SIGTRAP generation)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000394 ptrace_opts |= PTRACE_O_TRACEEXEC;
Todd Fialaaf245d12014-06-30 21:05:18 +0000395
Kate Stoneb9c1b512016-09-06 20:57:50 +0000396 return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void *)ptrace_opts);
Todd Fialaaf245d12014-06-30 21:05:18 +0000397}
398
Pavel Labath1107b5a2015-04-17 14:07:49 +0000399// Handles all waitpid events from the inferior process.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000400void NativeProcessLinux::MonitorCallback(lldb::pid_t pid, bool exited,
Pavel Labath3508fc82017-06-19 12:47:50 +0000401 WaitStatus status) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000402 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Todd Fialaaf245d12014-06-30 21:05:18 +0000403
Kate Stoneb9c1b512016-09-06 20:57:50 +0000404 // Certain activities differ based on whether the pid is the tid of the main
405 // thread.
406 const bool is_main_thread = (pid == GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000407
Kate Stoneb9c1b512016-09-06 20:57:50 +0000408 // Handle when the thread exits.
409 if (exited) {
Pavel Labathd8b3c1a2017-12-18 09:44:29 +0000410 LLDB_LOG(log,
Pavel Labath9303afb2019-02-07 15:56:35 +0000411 "got exit status({0}) , tid = {1} ({2} main thread), process "
Pavel Labathd8b3c1a2017-12-18 09:44:29 +0000412 "state = {3}",
Pavel Labath9303afb2019-02-07 15:56:35 +0000413 status, pid, is_main_thread ? "is" : "is not", GetState());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000414
415 // This is a thread that exited. Ensure we're not tracking it anymore.
Pavel Labathd8b3c1a2017-12-18 09:44:29 +0000416 StopTrackingThread(pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000417
418 if (is_main_thread) {
Pavel Labathd8b3c1a2017-12-18 09:44:29 +0000419 // The main thread exited. We're done monitoring. Report to delegate.
420 SetExitStatus(status, true);
Todd Fialaaf245d12014-06-30 21:05:18 +0000421
Pavel Labathd8b3c1a2017-12-18 09:44:29 +0000422 // Notify delegate that our process has exited.
423 SetState(StateType::eStateExited, true);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000424 }
425 return;
426 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000427
Kate Stoneb9c1b512016-09-06 20:57:50 +0000428 siginfo_t info;
429 const auto info_err = GetSignalInfo(pid, &info);
430 auto thread_sp = GetThreadByID(pid);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000431
Kate Stoneb9c1b512016-09-06 20:57:50 +0000432 if (!thread_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +0000433 // Normally, the only situation when we cannot find the thread is if we
434 // have just received a new thread notification. This is indicated by
Pavel Labatha6321a82017-01-19 15:26:04 +0000435 // GetSignalInfo() returning si_code == SI_USER and si_pid == 0
436 LLDB_LOG(log, "received notification about an unknown tid {0}.", pid);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000437
Kate Stoneb9c1b512016-09-06 20:57:50 +0000438 if (info_err.Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000439 LLDB_LOG(log,
440 "(tid {0}) GetSignalInfo failed ({1}). "
441 "Ingoring this notification.",
442 pid, info_err);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000443 return;
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000444 }
445
Pavel Labatha6321a82017-01-19 15:26:04 +0000446 LLDB_LOG(log, "tid {0}, si_code: {1}, si_pid: {2}", pid, info.si_code,
447 info.si_pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000448
Pavel Labatha5be48b2017-10-17 15:52:16 +0000449 NativeThreadLinux &thread = AddThread(pid);
Ravitheja Addepally99e37692017-06-28 07:58:31 +0000450
Kate Stoneb9c1b512016-09-06 20:57:50 +0000451 // Resume the newly created thread.
Pavel Labatha5be48b2017-10-17 15:52:16 +0000452 ResumeThread(thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
453 ThreadWasCreated(thread);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000454 return;
455 }
456
457 // Get details on the signal raised.
458 if (info_err.Success()) {
459 // We have retrieved the signal info. Dispatch appropriately.
460 if (info.si_signo == SIGTRAP)
461 MonitorSIGTRAP(info, *thread_sp);
Chaoren Linfa03ad22015-02-03 01:50:42 +0000462 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000463 MonitorSignal(info, *thread_sp, exited);
464 } else {
465 if (info_err.GetError() == EINVAL) {
Adrian Prantl05097242018-04-30 16:49:04 +0000466 // This is a group stop reception for this tid. We can reach here if we
467 // reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the tracee,
468 // triggering the group-stop mechanism. Normally receiving these would
469 // stop the process, pending a SIGCONT. Simulating this state in a
470 // debugger is hard and is generally not needed (one use case is
471 // debugging background task being managed by a shell). For general use,
472 // it is sufficient to stop the process in a signal-delivery stop which
473 // happens before the group stop. This done by MonitorSignal and works
474 // correctly for all signals.
Pavel Labatha6321a82017-01-19 15:26:04 +0000475 LLDB_LOG(log,
476 "received a group stop for pid {0} tid {1}. Transparent "
477 "handling of group stops not supported, resuming the "
478 "thread.",
479 GetID(), pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000480 ResumeThread(*thread_sp, thread_sp->GetState(),
481 LLDB_INVALID_SIGNAL_NUMBER);
482 } else {
483 // ptrace(GETSIGINFO) failed (but not due to group-stop).
Todd Fialaaf245d12014-06-30 21:05:18 +0000484
Kate Stoneb9c1b512016-09-06 20:57:50 +0000485 // A return value of ESRCH means the thread/process is no longer on the
Pavel Labatha6321a82017-01-19 15:26:04 +0000486 // system, so it was killed somehow outside of our control. Either way,
487 // we can't do anything with it anymore.
Todd Fialaaf245d12014-06-30 21:05:18 +0000488
Kate Stoneb9c1b512016-09-06 20:57:50 +0000489 // Stop tracking the metadata for the thread since it's entirely off the
490 // system now.
491 const bool thread_found = StopTrackingThread(pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000492
Pavel Labatha6321a82017-01-19 15:26:04 +0000493 LLDB_LOG(log,
Pavel Labath9303afb2019-02-07 15:56:35 +0000494 "GetSignalInfo failed: {0}, tid = {1}, status = {2}, "
Pavel Labatha6321a82017-01-19 15:26:04 +0000495 "status = {3}, main_thread = {4}, thread_found: {5}",
Pavel Labath9303afb2019-02-07 15:56:35 +0000496 info_err, pid, status, status, is_main_thread, thread_found);
Todd Fialaaf245d12014-06-30 21:05:18 +0000497
Kate Stoneb9c1b512016-09-06 20:57:50 +0000498 if (is_main_thread) {
499 // Notify the delegate - our process is not available but appears to
Adrian Prantl05097242018-04-30 16:49:04 +0000500 // have been killed outside our control. Is eStateExited the right
501 // exit state in this case?
Pavel Labath3508fc82017-06-19 12:47:50 +0000502 SetExitStatus(status, true);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000503 SetState(StateType::eStateExited, true);
504 } else {
505 // This thread was pulled out from underneath us. Anything to do here?
506 // Do we want to do an all stop?
Pavel Labatha6321a82017-01-19 15:26:04 +0000507 LLDB_LOG(log,
508 "pid {0} tid {1} non-main thread exit occurred, didn't "
509 "tell delegate anything since thread disappeared out "
510 "from underneath us",
511 GetID(), pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000512 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000513 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000514 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000515}
516
Kate Stoneb9c1b512016-09-06 20:57:50 +0000517void NativeProcessLinux::WaitForNewThread(::pid_t tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000518 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Pavel Labath426bdf82015-04-28 07:51:52 +0000519
Pavel Labatha5be48b2017-10-17 15:52:16 +0000520 if (GetThreadByID(tid)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000521 // We are already tracking the thread - we got the event on the new thread
Pavel Labatha5be48b2017-10-17 15:52:16 +0000522 // (see MonitorSignal) before this one. We are done.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000523 return;
524 }
Pavel Labath426bdf82015-04-28 07:51:52 +0000525
Kate Stoneb9c1b512016-09-06 20:57:50 +0000526 // The thread is not tracked yet, let's wait for it to appear.
527 int status = -1;
Pavel Labathc1a6b122017-07-03 09:25:55 +0000528 LLDB_LOG(log,
529 "received thread creation event for tid {0}. tid not tracked "
530 "yet, waiting for thread to appear...",
531 tid);
532 ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, &status, __WALL);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000533 // Since we are waiting on a specific tid, this must be the creation event.
Pavel Labatha6321a82017-01-19 15:26:04 +0000534 // But let's do some checks just in case.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000535 if (wait_pid != tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000536 LLDB_LOG(log,
537 "waiting for tid {0} failed. Assuming the thread has "
538 "disappeared in the meantime",
539 tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000540 // The only way I know of this could happen is if the whole process was
541 // SIGKILLed in the mean time. In any case, we can't do anything about that
542 // now.
543 return;
544 }
545 if (WIFEXITED(status)) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000546 LLDB_LOG(log,
547 "waiting for tid {0} returned an 'exited' event. Not "
548 "tracking the thread.",
549 tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000550 // Also a very improbable event.
551 return;
552 }
Pavel Labath426bdf82015-04-28 07:51:52 +0000553
Pavel Labatha6321a82017-01-19 15:26:04 +0000554 LLDB_LOG(log, "pid = {0}: tracking new thread tid {1}", GetID(), tid);
Pavel Labatha5be48b2017-10-17 15:52:16 +0000555 NativeThreadLinux &new_thread = AddThread(tid);
Ravitheja Addepally99e37692017-06-28 07:58:31 +0000556
Pavel Labatha5be48b2017-10-17 15:52:16 +0000557 ResumeThread(new_thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
558 ThreadWasCreated(new_thread);
Pavel Labath426bdf82015-04-28 07:51:52 +0000559}
560
Kate Stoneb9c1b512016-09-06 20:57:50 +0000561void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info,
562 NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000563 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000564 const bool is_main_thread = (thread.GetID() == GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000565
Kate Stoneb9c1b512016-09-06 20:57:50 +0000566 assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
Todd Fialaaf245d12014-06-30 21:05:18 +0000567
Kate Stoneb9c1b512016-09-06 20:57:50 +0000568 switch (info.si_code) {
569 // TODO: these two cases are required if we want to support tracing of the
Adrian Prantl05097242018-04-30 16:49:04 +0000570 // inferiors' children. We'd need this to debug a monitor. case (SIGTRAP |
571 // (PTRACE_EVENT_FORK << 8)): case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
Todd Fialaaf245d12014-06-30 21:05:18 +0000572
Kate Stoneb9c1b512016-09-06 20:57:50 +0000573 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): {
574 // This is the notification on the parent thread which informs us of new
Adrian Prantl05097242018-04-30 16:49:04 +0000575 // thread creation. We don't want to do anything with the parent thread so
576 // we just resume it. In case we want to implement "break on thread
577 // creation" functionality, we would need to stop here.
Todd Fialaaf245d12014-06-30 21:05:18 +0000578
Kate Stoneb9c1b512016-09-06 20:57:50 +0000579 unsigned long event_message = 0;
580 if (GetEventMessage(thread.GetID(), &event_message).Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000581 LLDB_LOG(log,
582 "pid {0} received thread creation event but "
583 "GetEventMessage failed so we don't know the new tid",
584 thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000585 } else
586 WaitForNewThread(event_message);
Todd Fialaaf245d12014-06-30 21:05:18 +0000587
Kate Stoneb9c1b512016-09-06 20:57:50 +0000588 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
589 break;
590 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000591
Kate Stoneb9c1b512016-09-06 20:57:50 +0000592 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): {
Pavel Labatha6321a82017-01-19 15:26:04 +0000593 LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000594
595 // Exec clears any pending notifications.
596 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
597
598 // Remove all but the main thread here. Linux fork creates a new process
599 // which only copies the main thread.
Pavel Labatha6321a82017-01-19 15:26:04 +0000600 LLDB_LOG(log, "exec received, stop tracking all but main thread");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000601
Pavel Labatha5be48b2017-10-17 15:52:16 +0000602 for (auto i = m_threads.begin(); i != m_threads.end();) {
603 if ((*i)->GetID() == GetID())
604 i = m_threads.erase(i);
605 else
606 ++i;
Todd Fialaa9882ce2014-08-28 15:46:54 +0000607 }
Pavel Labatha5be48b2017-10-17 15:52:16 +0000608 assert(m_threads.size() == 1);
609 auto *main_thread = static_cast<NativeThreadLinux *>(m_threads[0].get());
Todd Fialaaf245d12014-06-30 21:05:18 +0000610
Pavel Labatha5be48b2017-10-17 15:52:16 +0000611 SetCurrentThreadID(main_thread->GetID());
612 main_thread->SetStoppedByExec();
Todd Fialaaf245d12014-06-30 21:05:18 +0000613
Kate Stoneb9c1b512016-09-06 20:57:50 +0000614 // Tell coordinator about about the "new" (since exec) stopped main thread.
Pavel Labatha5be48b2017-10-17 15:52:16 +0000615 ThreadWasCreated(*main_thread);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000616
Kate Stoneb9c1b512016-09-06 20:57:50 +0000617 // Let our delegate know we have just exec'd.
618 NotifyDidExec();
619
Kate Stoneb9c1b512016-09-06 20:57:50 +0000620 // Let the process know we're stopped.
Pavel Labatha5be48b2017-10-17 15:52:16 +0000621 StopRunningThreads(main_thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000622
623 break;
624 }
625
626 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): {
Adrian Prantl05097242018-04-30 16:49:04 +0000627 // The inferior process or one of its threads is about to exit. We don't
628 // want to do anything with the thread so we just resume it. In case we
629 // want to implement "break on thread exit" functionality, we would need to
630 // stop here.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000631
632 unsigned long data = 0;
633 if (GetEventMessage(thread.GetID(), &data).Fail())
634 data = -1;
635
Pavel Labatha6321a82017-01-19 15:26:04 +0000636 LLDB_LOG(log,
637 "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
638 "WIFSIGNALED={2}, pid = {3}, main_thread = {4}",
639 data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(),
640 is_main_thread);
Todd Fialaaf245d12014-06-30 21:05:18 +0000641
Kate Stoneb9c1b512016-09-06 20:57:50 +0000642
643 StateType state = thread.GetState();
644 if (!StateIsRunningState(state)) {
645 // Due to a kernel bug, we may sometimes get this stop after the inferior
Pavel Labathd8b3c1a2017-12-18 09:44:29 +0000646 // gets a SIGKILL. This confuses our state tracking logic in
647 // ResumeThread(), since normally, we should not be receiving any ptrace
Adrian Prantl05097242018-04-30 16:49:04 +0000648 // events while the inferior is stopped. This makes sure that the
649 // inferior is resumed and exits normally.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000650 state = eStateRunning;
651 }
652 ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
653
654 break;
655 }
656
657 case 0:
658 case TRAP_TRACE: // We receive this on single stepping.
659 case TRAP_HWBKPT: // We receive this on watchpoint hit
660 {
661 // If a watchpoint was hit, report it
662 uint32_t wp_index;
Pavel Labathd37349f2017-11-10 11:05:49 +0000663 Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000664 wp_index, (uintptr_t)info.si_addr);
Pavel Labatha6321a82017-01-19 15:26:04 +0000665 if (error.Fail())
666 LLDB_LOG(log,
667 "received error while checking for watchpoint hits, pid = "
668 "{0}, error = {1}",
669 thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000670 if (wp_index != LLDB_INVALID_INDEX32) {
671 MonitorWatchpoint(thread, wp_index);
672 break;
673 }
674
Omair Javaidd5ffbad2017-02-24 13:27:31 +0000675 // If a breakpoint was hit, report it
676 uint32_t bp_index;
Pavel Labathd37349f2017-11-10 11:05:49 +0000677 error = thread.GetRegisterContext().GetHardwareBreakHitIndex(
Omair Javaidd5ffbad2017-02-24 13:27:31 +0000678 bp_index, (uintptr_t)info.si_addr);
679 if (error.Fail())
680 LLDB_LOG(log, "received error while checking for hardware "
681 "breakpoint hits, pid = {0}, error = {1}",
682 thread.GetID(), error);
683 if (bp_index != LLDB_INVALID_INDEX32) {
684 MonitorBreakpoint(thread);
685 break;
686 }
687
Kate Stoneb9c1b512016-09-06 20:57:50 +0000688 // Otherwise, report step over
689 MonitorTrace(thread);
690 break;
691 }
692
693 case SI_KERNEL:
Mohit K. Bhakkad35799962015-06-18 04:53:18 +0000694#if defined __mips__
Adrian Prantl05097242018-04-30 16:49:04 +0000695 // For mips there is no special signal for watchpoint So we check for
696 // watchpoint in kernel trap
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000697 {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000698 // If a watchpoint was hit, report it
699 uint32_t wp_index;
Pavel Labathd37349f2017-11-10 11:05:49 +0000700 Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000701 wp_index, LLDB_INVALID_ADDRESS);
Pavel Labatha6321a82017-01-19 15:26:04 +0000702 if (error.Fail())
703 LLDB_LOG(log,
704 "received error while checking for watchpoint hits, pid = "
705 "{0}, error = {1}",
706 thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000707 if (wp_index != LLDB_INVALID_INDEX32) {
708 MonitorWatchpoint(thread, wp_index);
709 break;
710 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000711 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000712// NO BREAK
Mohit K. Bhakkad35799962015-06-18 04:53:18 +0000713#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000714 case TRAP_BRKPT:
715 MonitorBreakpoint(thread);
716 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000717
Kate Stoneb9c1b512016-09-06 20:57:50 +0000718 case SIGTRAP:
719 case (SIGTRAP | 0x80):
Pavel Labatha6321a82017-01-19 15:26:04 +0000720 LLDB_LOG(
721 log,
722 "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",
723 info.si_code, GetID(), thread.GetID());
Chaoren Linfa03ad22015-02-03 01:50:42 +0000724
Kate Stoneb9c1b512016-09-06 20:57:50 +0000725 // Ignore these signals until we know more about them.
726 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
727 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000728
Kate Stoneb9c1b512016-09-06 20:57:50 +0000729 default:
Pavel Labath21a365b2017-07-11 10:38:40 +0000730 LLDB_LOG(log, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}",
731 info.si_code, GetID(), thread.GetID());
732 MonitorSignal(info, thread, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000733 break;
734 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000735}
736
Kate Stoneb9c1b512016-09-06 20:57:50 +0000737void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000738 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
739 LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000740
Kate Stoneb9c1b512016-09-06 20:57:50 +0000741 // This thread is currently stopped.
742 thread.SetStoppedByTrace();
743
744 StopRunningThreads(thread.GetID());
745}
746
747void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) {
748 Log *log(
749 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
Pavel Labatha6321a82017-01-19 15:26:04 +0000750 LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000751
752 // Mark the thread as stopped at breakpoint.
753 thread.SetStoppedByBreakpoint();
Pavel Labathaef79082018-10-03 12:29:33 +0000754 FixupBreakpointPCAsNeeded(thread);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000755
756 if (m_threads_stepping_with_breakpoint.find(thread.GetID()) !=
757 m_threads_stepping_with_breakpoint.end())
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000758 thread.SetStoppedByTrace();
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000759
Kate Stoneb9c1b512016-09-06 20:57:50 +0000760 StopRunningThreads(thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000761}
762
Kate Stoneb9c1b512016-09-06 20:57:50 +0000763void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread,
764 uint32_t wp_index) {
765 Log *log(
766 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
Pavel Labatha6321a82017-01-19 15:26:04 +0000767 LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}",
768 thread.GetID(), wp_index);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000769
Adrian Prantl05097242018-04-30 16:49:04 +0000770 // Mark the thread as stopped at watchpoint. The address is at
771 // (lldb::addr_t)info->si_addr if we need it.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000772 thread.SetStoppedByWatchpoint(wp_index);
773
774 // We need to tell all other running threads before we notify the delegate
775 // about this stop.
776 StopRunningThreads(thread.GetID());
777}
778
779void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
780 NativeThreadLinux &thread, bool exited) {
781 const int signo = info.si_signo;
782 const bool is_from_llgs = info.si_pid == getpid();
783
Pavel Labatha6321a82017-01-19 15:26:04 +0000784 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000785
786 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
Adrian Prantl05097242018-04-30 16:49:04 +0000787 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a kill(2)
788 // or raise(3). Similarly for tgkill(2) on Linux.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000789 //
790 // IOW, user generated signals never generate what we consider to be a
791 // "crash".
792 //
793 // Similarly, ACK signals generated by this monitor.
794
795 // Handle the signal.
Pavel Labatha6321a82017-01-19 15:26:04 +0000796 LLDB_LOG(log,
797 "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
798 "waitpid pid = {4})",
799 Host::GetSignalAsCString(signo), signo, info.si_code,
800 thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000801
Kate Stoneb9c1b512016-09-06 20:57:50 +0000802 // Check for thread stop notification.
803 if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) {
804 // This is a tgkill()-based stop.
Pavel Labatha6321a82017-01-19 15:26:04 +0000805 LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000806
Adrian Prantl05097242018-04-30 16:49:04 +0000807 // Check that we're not already marked with a stop reason. Note this thread
808 // really shouldn't already be marked as stopped - if we were, that would
809 // imply that the kernel signaled us with the thread stopping which we
810 // handled and marked as stopped, and that, without an intervening resume,
811 // we received another stop. It is more likely that we are missing the
812 // marking of a run state somewhere if we find that the thread was marked
813 // as stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000814 const StateType thread_state = thread.GetState();
815 if (!StateIsStoppedState(thread_state, false)) {
816 // An inferior thread has stopped because of a SIGSTOP we have sent it.
817 // Generally, these are not important stops and we don't want to report
Pavel Labatha6321a82017-01-19 15:26:04 +0000818 // them as they are just used to stop other threads when one thread (the
819 // one with the *real* stop reason) hits a breakpoint (watchpoint,
Adrian Prantl05097242018-04-30 16:49:04 +0000820 // etc...). However, in the case of an asynchronous Interrupt(), this
821 // *is* the real stop reason, so we leave the signal intact if this is
822 // the thread that was chosen as the triggering thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000823 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
824 if (m_pending_notification_tid == thread.GetID())
825 thread.SetStoppedBySignal(SIGSTOP, &info);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000826 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000827 thread.SetStoppedWithNoReason();
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000828
Kate Stoneb9c1b512016-09-06 20:57:50 +0000829 SetCurrentThreadID(thread.GetID());
830 SignalIfAllThreadsStopped();
831 } else {
832 // We can end up here if stop was initiated by LLGS but by this time a
833 // thread stop has occurred - maybe initiated by another event.
Zachary Turner97206d52017-05-12 04:51:55 +0000834 Status error = ResumeThread(thread, thread.GetState(), 0);
Pavel Labatha6321a82017-01-19 15:26:04 +0000835 if (error.Fail())
836 LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(),
837 error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000838 }
839 } else {
Pavel Labatha6321a82017-01-19 15:26:04 +0000840 LLDB_LOG(log,
841 "pid {0} tid {1}, thread was already marked as a stopped "
842 "state (state={2}), leaving stop signal as is",
Pavel Labath8198db32017-01-24 11:48:25 +0000843 GetID(), thread.GetID(), thread_state);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000844 SignalIfAllThreadsStopped();
Todd Fialaaf245d12014-06-30 21:05:18 +0000845 }
846
Kate Stoneb9c1b512016-09-06 20:57:50 +0000847 // Done handling.
848 return;
849 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000850
Adrian Prantl05097242018-04-30 16:49:04 +0000851 // Check if debugger should stop at this signal or just ignore it and resume
852 // the inferior.
Pavel Labath4a705e72017-02-24 09:29:14 +0000853 if (m_signals_to_ignore.find(signo) != m_signals_to_ignore.end()) {
854 ResumeThread(thread, thread.GetState(), signo);
855 return;
856 }
857
Kate Stoneb9c1b512016-09-06 20:57:50 +0000858 // This thread is stopped.
Pavel Labatha6321a82017-01-19 15:26:04 +0000859 LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000860 thread.SetStoppedBySignal(signo, &info);
861
862 // Send a stop to the debugger after we get all other threads to stop.
863 StopRunningThreads(thread.GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000864}
865
Tamas Berghammere7708682015-04-22 10:00:23 +0000866namespace {
867
Kate Stoneb9c1b512016-09-06 20:57:50 +0000868struct EmulatorBaton {
Pavel Labathd37349f2017-11-10 11:05:49 +0000869 NativeProcessLinux &m_process;
870 NativeRegisterContext &m_reg_context;
Tamas Berghammere7708682015-04-22 10:00:23 +0000871
Kate Stoneb9c1b512016-09-06 20:57:50 +0000872 // eRegisterKindDWARF -> RegsiterValue
873 std::unordered_map<uint32_t, RegisterValue> m_register_values;
Pavel Labath6648fcc2015-04-27 09:21:14 +0000874
Pavel Labathd37349f2017-11-10 11:05:49 +0000875 EmulatorBaton(NativeProcessLinux &process, NativeRegisterContext &reg_context)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000876 : m_process(process), m_reg_context(reg_context) {}
Tamas Berghammere7708682015-04-22 10:00:23 +0000877};
878
879} // anonymous namespace
880
Kate Stoneb9c1b512016-09-06 20:57:50 +0000881static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
882 const EmulateInstruction::Context &context,
883 lldb::addr_t addr, void *dst, size_t length) {
884 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
Tamas Berghammere7708682015-04-22 10:00:23 +0000885
Kate Stoneb9c1b512016-09-06 20:57:50 +0000886 size_t bytes_read;
Pavel Labathd37349f2017-11-10 11:05:49 +0000887 emulator_baton->m_process.ReadMemory(addr, dst, length, bytes_read);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000888 return bytes_read;
Tamas Berghammere7708682015-04-22 10:00:23 +0000889}
890
Kate Stoneb9c1b512016-09-06 20:57:50 +0000891static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
892 const RegisterInfo *reg_info,
893 RegisterValue &reg_value) {
894 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
Tamas Berghammere7708682015-04-22 10:00:23 +0000895
Kate Stoneb9c1b512016-09-06 20:57:50 +0000896 auto it = emulator_baton->m_register_values.find(
897 reg_info->kinds[eRegisterKindDWARF]);
898 if (it != emulator_baton->m_register_values.end()) {
899 reg_value = it->second;
900 return true;
901 }
902
Adrian Prantl05097242018-04-30 16:49:04 +0000903 // The emulator only fill in the dwarf regsiter numbers (and in some case the
904 // generic register numbers). Get the full register info from the register
905 // context based on the dwarf register numbers.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000906 const RegisterInfo *full_reg_info =
Pavel Labathd37349f2017-11-10 11:05:49 +0000907 emulator_baton->m_reg_context.GetRegisterInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000908 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
909
Zachary Turner97206d52017-05-12 04:51:55 +0000910 Status error =
Pavel Labathd37349f2017-11-10 11:05:49 +0000911 emulator_baton->m_reg_context.ReadRegister(full_reg_info, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000912 if (error.Success())
913 return true;
914
915 return false;
916}
917
918static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
919 const EmulateInstruction::Context &context,
920 const RegisterInfo *reg_info,
921 const RegisterValue &reg_value) {
922 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
923 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
924 reg_value;
925 return true;
926}
927
928static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
929 const EmulateInstruction::Context &context,
930 lldb::addr_t addr, const void *dst,
931 size_t length) {
932 return length;
933}
934
Pavel Labathd37349f2017-11-10 11:05:49 +0000935static lldb::addr_t ReadFlags(NativeRegisterContext &regsiter_context) {
936 const RegisterInfo *flags_info = regsiter_context.GetRegisterInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000937 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
Pavel Labathd37349f2017-11-10 11:05:49 +0000938 return regsiter_context.ReadRegisterAsUnsigned(flags_info,
939 LLDB_INVALID_ADDRESS);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000940}
941
Zachary Turner97206d52017-05-12 04:51:55 +0000942Status
943NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadLinux &thread) {
944 Status error;
Pavel Labathd37349f2017-11-10 11:05:49 +0000945 NativeRegisterContext& register_context = thread.GetRegisterContext();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000946
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000947 std::unique_ptr<EmulateInstruction> emulator_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000948 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying,
949 nullptr));
950
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000951 if (emulator_up == nullptr)
Zachary Turner97206d52017-05-12 04:51:55 +0000952 return Status("Instruction emulator not found!");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000953
Pavel Labathd37349f2017-11-10 11:05:49 +0000954 EmulatorBaton baton(*this, register_context);
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000955 emulator_up->SetBaton(&baton);
956 emulator_up->SetReadMemCallback(&ReadMemoryCallback);
957 emulator_up->SetReadRegCallback(&ReadRegisterCallback);
958 emulator_up->SetWriteMemCallback(&WriteMemoryCallback);
959 emulator_up->SetWriteRegCallback(&WriteRegisterCallback);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000960
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000961 if (!emulator_up->ReadInstruction())
Zachary Turner97206d52017-05-12 04:51:55 +0000962 return Status("Read instruction failed!");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000963
964 bool emulation_result =
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000965 emulator_up->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000966
Pavel Labathd37349f2017-11-10 11:05:49 +0000967 const RegisterInfo *reg_info_pc = register_context.GetRegisterInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000968 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
Pavel Labathd37349f2017-11-10 11:05:49 +0000969 const RegisterInfo *reg_info_flags = register_context.GetRegisterInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000970 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
971
972 auto pc_it =
973 baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
974 auto flags_it =
975 baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
976
977 lldb::addr_t next_pc;
978 lldb::addr_t next_flags;
979 if (emulation_result) {
980 assert(pc_it != baton.m_register_values.end() &&
981 "Emulation was successfull but PC wasn't updated");
982 next_pc = pc_it->second.GetAsUInt64();
983
984 if (flags_it != baton.m_register_values.end())
985 next_flags = flags_it->second.GetAsUInt64();
986 else
Pavel Labathd37349f2017-11-10 11:05:49 +0000987 next_flags = ReadFlags(register_context);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000988 } else if (pc_it == baton.m_register_values.end()) {
Adrian Prantl05097242018-04-30 16:49:04 +0000989 // Emulate instruction failed and it haven't changed PC. Advance PC with
990 // the size of the current opcode because the emulation of all
Kate Stoneb9c1b512016-09-06 20:57:50 +0000991 // PC modifying instruction should be successful. The failure most
992 // likely caused by a not supported instruction which don't modify PC.
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000993 next_pc = register_context.GetPC() + emulator_up->GetOpcode().GetByteSize();
Pavel Labathd37349f2017-11-10 11:05:49 +0000994 next_flags = ReadFlags(register_context);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000995 } else {
996 // The instruction emulation failed after it modified the PC. It is an
997 // unknown error where we can't continue because the next instruction is
998 // modifying the PC but we don't know how.
Zachary Turner97206d52017-05-12 04:51:55 +0000999 return Status("Instruction emulation failed unexpectedly.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001000 }
1001
1002 if (m_arch.GetMachine() == llvm::Triple::arm) {
1003 if (next_flags & 0x20) {
1004 // Thumb mode
1005 error = SetSoftwareBreakpoint(next_pc, 2);
1006 } else {
1007 // Arm mode
1008 error = SetSoftwareBreakpoint(next_pc, 4);
Pavel Labath6648fcc2015-04-27 09:21:14 +00001009 }
Fangrui Song2f677ab2019-05-16 09:07:33 +00001010 } else if (m_arch.IsMIPS() || m_arch.GetTriple().isPPC64())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001011 error = SetSoftwareBreakpoint(next_pc, 4);
1012 else {
1013 // No size hint is given for the next breakpoint
1014 error = SetSoftwareBreakpoint(next_pc, 0);
1015 }
Pavel Labath6648fcc2015-04-27 09:21:14 +00001016
Adrian Prantl05097242018-04-30 16:49:04 +00001017 // If setting the breakpoint fails because next_pc is out of the address
1018 // space, ignore it and let the debugee segfault.
Pavel Labath42eb6902016-10-26 11:13:56 +00001019 if (error.GetError() == EIO || error.GetError() == EFAULT) {
Zachary Turner97206d52017-05-12 04:51:55 +00001020 return Status();
Pavel Labath42eb6902016-10-26 11:13:56 +00001021 } else if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001022 return error;
Tamas Berghammere7708682015-04-22 10:00:23 +00001023
Kate Stoneb9c1b512016-09-06 20:57:50 +00001024 m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001025
Zachary Turner97206d52017-05-12 04:51:55 +00001026 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001027}
1028
1029bool NativeProcessLinux::SupportHardwareSingleStepping() const {
Fangrui Songddb93b62019-05-16 08:37:32 +00001030 if (m_arch.GetMachine() == llvm::Triple::arm || m_arch.IsMIPS())
Pavel Labath6648fcc2015-04-27 09:21:14 +00001031 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001032 return true;
Tamas Berghammere7708682015-04-22 10:00:23 +00001033}
1034
Zachary Turner97206d52017-05-12 04:51:55 +00001035Status NativeProcessLinux::Resume(const ResumeActionList &resume_actions) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001036 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1037 LLDB_LOG(log, "pid {0}", GetID());
Tamas Berghammere7708682015-04-22 10:00:23 +00001038
Kate Stoneb9c1b512016-09-06 20:57:50 +00001039 bool software_single_step = !SupportHardwareSingleStepping();
Tamas Berghammere7708682015-04-22 10:00:23 +00001040
Kate Stoneb9c1b512016-09-06 20:57:50 +00001041 if (software_single_step) {
Pavel Labatha5be48b2017-10-17 15:52:16 +00001042 for (const auto &thread : m_threads) {
1043 assert(thread && "thread list should not contain NULL threads");
Tamas Berghammere7708682015-04-22 10:00:23 +00001044
Kate Stoneb9c1b512016-09-06 20:57:50 +00001045 const ResumeAction *const action =
Pavel Labatha5be48b2017-10-17 15:52:16 +00001046 resume_actions.GetActionForThread(thread->GetID(), true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001047 if (action == nullptr)
1048 continue;
Tamas Berghammere7708682015-04-22 10:00:23 +00001049
Kate Stoneb9c1b512016-09-06 20:57:50 +00001050 if (action->state == eStateStepping) {
Zachary Turner97206d52017-05-12 04:51:55 +00001051 Status error = SetupSoftwareSingleStepping(
Pavel Labatha5be48b2017-10-17 15:52:16 +00001052 static_cast<NativeThreadLinux &>(*thread));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001053 if (error.Fail())
1054 return error;
1055 }
Tamas Berghammere7708682015-04-22 10:00:23 +00001056 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001057 }
1058
Pavel Labatha5be48b2017-10-17 15:52:16 +00001059 for (const auto &thread : m_threads) {
1060 assert(thread && "thread list should not contain NULL threads");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001061
1062 const ResumeAction *const action =
Pavel Labatha5be48b2017-10-17 15:52:16 +00001063 resume_actions.GetActionForThread(thread->GetID(), true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001064
1065 if (action == nullptr) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001066 LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
Pavel Labatha5be48b2017-10-17 15:52:16 +00001067 thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001068 continue;
Tamas Berghammere7708682015-04-22 10:00:23 +00001069 }
1070
Pavel Labatha6321a82017-01-19 15:26:04 +00001071 LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}",
Pavel Labatha5be48b2017-10-17 15:52:16 +00001072 action->state, GetID(), thread->GetID());
Tamas Berghammere7708682015-04-22 10:00:23 +00001073
Kate Stoneb9c1b512016-09-06 20:57:50 +00001074 switch (action->state) {
1075 case eStateRunning:
1076 case eStateStepping: {
1077 // Run the thread, possibly feeding it the signal.
1078 const int signo = action->signal;
Pavel Labatha5be48b2017-10-17 15:52:16 +00001079 ResumeThread(static_cast<NativeThreadLinux &>(*thread), action->state,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001080 signo);
1081 break;
1082 }
Tamas Berghammere7708682015-04-22 10:00:23 +00001083
Kate Stoneb9c1b512016-09-06 20:57:50 +00001084 case eStateSuspended:
1085 case eStateStopped:
Pavel Labatha6321a82017-01-19 15:26:04 +00001086 llvm_unreachable("Unexpected state");
Tamas Berghammere7708682015-04-22 10:00:23 +00001087
Kate Stoneb9c1b512016-09-06 20:57:50 +00001088 default:
Zachary Turner97206d52017-05-12 04:51:55 +00001089 return Status("NativeProcessLinux::%s (): unexpected state %s specified "
1090 "for pid %" PRIu64 ", tid %" PRIu64,
1091 __FUNCTION__, StateAsCString(action->state), GetID(),
Pavel Labatha5be48b2017-10-17 15:52:16 +00001092 thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001093 }
1094 }
1095
Zachary Turner97206d52017-05-12 04:51:55 +00001096 return Status();
Tamas Berghammere7708682015-04-22 10:00:23 +00001097}
1098
Zachary Turner97206d52017-05-12 04:51:55 +00001099Status NativeProcessLinux::Halt() {
1100 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001101
1102 if (kill(GetID(), SIGSTOP) != 0)
1103 error.SetErrorToErrno();
1104
1105 return error;
Tamas Berghammere7708682015-04-22 10:00:23 +00001106}
1107
Zachary Turner97206d52017-05-12 04:51:55 +00001108Status NativeProcessLinux::Detach() {
1109 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001110
1111 // Stop monitoring the inferior.
1112 m_sigchld_handle.reset();
1113
1114 // Tell ptrace to detach from the process.
1115 if (GetID() == LLDB_INVALID_PROCESS_ID)
1116 return error;
1117
Pavel Labatha5be48b2017-10-17 15:52:16 +00001118 for (const auto &thread : m_threads) {
1119 Status e = Detach(thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001120 if (e.Fail())
1121 error =
1122 e; // Save the error, but still attempt to detach from other threads.
1123 }
1124
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001125 m_processor_trace_monitor.clear();
1126 m_pt_proces_trace_id = LLDB_INVALID_UID;
1127
Kate Stoneb9c1b512016-09-06 20:57:50 +00001128 return error;
1129}
1130
Zachary Turner97206d52017-05-12 04:51:55 +00001131Status NativeProcessLinux::Signal(int signo) {
1132 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001133
Pavel Labatha6321a82017-01-19 15:26:04 +00001134 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1135 LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo,
1136 Host::GetSignalAsCString(signo), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001137
1138 if (kill(GetID(), signo))
1139 error.SetErrorToErrno();
1140
1141 return error;
1142}
1143
Zachary Turner97206d52017-05-12 04:51:55 +00001144Status NativeProcessLinux::Interrupt() {
Adrian Prantl05097242018-04-30 16:49:04 +00001145 // Pick a running thread (or if none, a not-dead stopped thread) as the
1146 // chosen thread that will be the stop-reason thread.
Pavel Labatha6321a82017-01-19 15:26:04 +00001147 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001148
Pavel Labatha5be48b2017-10-17 15:52:16 +00001149 NativeThreadProtocol *running_thread = nullptr;
1150 NativeThreadProtocol *stopped_thread = nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001151
Pavel Labatha6321a82017-01-19 15:26:04 +00001152 LLDB_LOG(log, "selecting running thread for interrupt target");
Pavel Labatha5be48b2017-10-17 15:52:16 +00001153 for (const auto &thread : m_threads) {
Adrian Prantl05097242018-04-30 16:49:04 +00001154 // If we have a running or stepping thread, we'll call that the target of
1155 // the interrupt.
Pavel Labatha5be48b2017-10-17 15:52:16 +00001156 const auto thread_state = thread->GetState();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001157 if (thread_state == eStateRunning || thread_state == eStateStepping) {
Pavel Labatha5be48b2017-10-17 15:52:16 +00001158 running_thread = thread.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001159 break;
Pavel Labatha5be48b2017-10-17 15:52:16 +00001160 } else if (!stopped_thread && StateIsStoppedState(thread_state, true)) {
Adrian Prantl05097242018-04-30 16:49:04 +00001161 // Remember the first non-dead stopped thread. We'll use that as a
1162 // backup if there are no running threads.
Pavel Labatha5be48b2017-10-17 15:52:16 +00001163 stopped_thread = thread.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001164 }
1165 }
1166
Pavel Labatha5be48b2017-10-17 15:52:16 +00001167 if (!running_thread && !stopped_thread) {
Zachary Turner97206d52017-05-12 04:51:55 +00001168 Status error("found no running/stepping or live stopped threads as target "
1169 "for interrupt");
Pavel Labatha6321a82017-01-19 15:26:04 +00001170 LLDB_LOG(log, "skipping due to error: {0}", error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001171
1172 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001173 }
1174
Pavel Labatha5be48b2017-10-17 15:52:16 +00001175 NativeThreadProtocol *deferred_signal_thread =
1176 running_thread ? running_thread : stopped_thread;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001177
Pavel Labatha6321a82017-01-19 15:26:04 +00001178 LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(),
Pavel Labatha5be48b2017-10-17 15:52:16 +00001179 running_thread ? "running" : "stopped",
1180 deferred_signal_thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001181
Pavel Labatha5be48b2017-10-17 15:52:16 +00001182 StopRunningThreads(deferred_signal_thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001183
Zachary Turner97206d52017-05-12 04:51:55 +00001184 return Status();
Todd Fialaaf245d12014-06-30 21:05:18 +00001185}
1186
Zachary Turner97206d52017-05-12 04:51:55 +00001187Status NativeProcessLinux::Kill() {
Pavel Labatha6321a82017-01-19 15:26:04 +00001188 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1189 LLDB_LOG(log, "pid {0}", GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +00001190
Zachary Turner97206d52017-05-12 04:51:55 +00001191 Status error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001192
Kate Stoneb9c1b512016-09-06 20:57:50 +00001193 switch (m_state) {
1194 case StateType::eStateInvalid:
1195 case StateType::eStateExited:
1196 case StateType::eStateCrashed:
1197 case StateType::eStateDetached:
1198 case StateType::eStateUnloaded:
1199 // Nothing to do - the process is already dead.
Pavel Labatha6321a82017-01-19 15:26:04 +00001200 LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
Pavel Labath8198db32017-01-24 11:48:25 +00001201 m_state);
Todd Fialaaf245d12014-06-30 21:05:18 +00001202 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001203
Kate Stoneb9c1b512016-09-06 20:57:50 +00001204 case StateType::eStateConnected:
1205 case StateType::eStateAttaching:
1206 case StateType::eStateLaunching:
1207 case StateType::eStateStopped:
1208 case StateType::eStateRunning:
1209 case StateType::eStateStepping:
1210 case StateType::eStateSuspended:
1211 // We can try to kill a process in these states.
1212 break;
1213 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001214
Kate Stoneb9c1b512016-09-06 20:57:50 +00001215 if (kill(GetID(), SIGKILL) != 0) {
1216 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +00001217 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001218 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001219
Kate Stoneb9c1b512016-09-06 20:57:50 +00001220 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001221}
1222
Zachary Turner97206d52017-05-12 04:51:55 +00001223Status NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr,
1224 MemoryRegionInfo &range_info) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001225 // FIXME review that the final memory region returned extends to the end of
1226 // the virtual address space,
1227 // with no perms if it is not mapped.
Todd Fialaaf245d12014-06-30 21:05:18 +00001228
Adrian Prantl05097242018-04-30 16:49:04 +00001229 // Use an approach that reads memory regions from /proc/{pid}/maps. Assume
1230 // proc maps entries are in ascending order.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001231 // FIXME assert if we find differently.
Todd Fialaaf245d12014-06-30 21:05:18 +00001232
Kate Stoneb9c1b512016-09-06 20:57:50 +00001233 if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
1234 // We're done.
Zachary Turner97206d52017-05-12 04:51:55 +00001235 return Status("unsupported");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001236 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001237
Zachary Turner97206d52017-05-12 04:51:55 +00001238 Status error = PopulateMemoryRegionCache();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001239 if (error.Fail()) {
1240 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001241 }
1242
1243 lldb::addr_t prev_base_address = 0;
1244
1245 // FIXME start by finding the last region that is <= target address using
1246 // binary search. Data is sorted.
1247 // There can be a ton of regions on pthreads apps with lots of threads.
1248 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1249 ++it) {
Tamas Berghammera6f57952017-01-03 16:29:43 +00001250 MemoryRegionInfo &proc_entry_info = it->first;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001251
1252 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1253 assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
1254 "descending /proc/pid/maps entries detected, unexpected");
1255 prev_base_address = proc_entry_info.GetRange().GetRangeBase();
Hafiz Abid Qadeerb1554312017-01-20 10:24:03 +00001256 UNUSED_IF_ASSERT_DISABLED(prev_base_address);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001257
1258 // If the target address comes before this entry, indicate distance to next
1259 // region.
1260 if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1261 range_info.GetRange().SetRangeBase(load_addr);
1262 range_info.GetRange().SetByteSize(
1263 proc_entry_info.GetRange().GetRangeBase() - load_addr);
1264 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1265 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1266 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1267 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1268
1269 return error;
1270 } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1271 // The target address is within the memory region we're processing here.
1272 range_info = proc_entry_info;
1273 return error;
1274 }
1275
1276 // The target memory address comes somewhere after the region we just
1277 // parsed.
1278 }
1279
1280 // If we made it here, we didn't find an entry that contained the given
Adrian Prantl05097242018-04-30 16:49:04 +00001281 // address. Return the load_addr as start and the amount of bytes betwwen
1282 // load address and the end of the memory as size.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001283 range_info.GetRange().SetRangeBase(load_addr);
1284 range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
1285 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1286 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1287 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1288 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1289 return error;
1290}
1291
Zachary Turner97206d52017-05-12 04:51:55 +00001292Status NativeProcessLinux::PopulateMemoryRegionCache() {
Pavel Labatha6321a82017-01-19 15:26:04 +00001293 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Tamas Berghammera6f57952017-01-03 16:29:43 +00001294
1295 // If our cache is empty, pull the latest. There should always be at least
1296 // one memory region if memory region handling is supported.
1297 if (!m_mem_region_cache.empty()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001298 LLDB_LOG(log, "reusing {0} cached memory region entries",
1299 m_mem_region_cache.size());
Zachary Turner97206d52017-05-12 04:51:55 +00001300 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001301 }
1302
Pavel Labath15930862017-03-21 13:49:45 +00001303 auto BufferOrError = getProcFile(GetID(), "maps");
1304 if (!BufferOrError) {
Tamas Berghammera6f57952017-01-03 16:29:43 +00001305 m_supports_mem_region = LazyBool::eLazyBoolNo;
Pavel Labath15930862017-03-21 13:49:45 +00001306 return BufferOrError.getError();
1307 }
Pavel Labathc8e364e82018-12-15 13:38:16 +00001308 Status Result;
1309 ParseLinuxMapRegions(BufferOrError.get()->getBuffer(),
1310 [&](const MemoryRegionInfo &Info, const Status &ST) {
1311 if (ST.Success()) {
1312 FileSpec file_spec(Info.GetName().GetCString());
1313 FileSystem::Instance().Resolve(file_spec);
1314 m_mem_region_cache.emplace_back(Info, file_spec);
1315 return true;
1316 } else {
1317 m_supports_mem_region = LazyBool::eLazyBoolNo;
1318 LLDB_LOG(log, "failed to parse proc maps: {0}", ST);
1319 Result = ST;
1320 return false;
1321 }
1322 });
1323 if (Result.Fail())
1324 return Result;
Pavel Labath15930862017-03-21 13:49:45 +00001325
1326 if (m_mem_region_cache.empty()) {
Tamas Berghammera6f57952017-01-03 16:29:43 +00001327 // No entries after attempting to read them. This shouldn't happen if
Adrian Prantl05097242018-04-30 16:49:04 +00001328 // /proc/{pid}/maps is supported. Assume we don't support map entries via
1329 // procfs.
Pavel Labath15930862017-03-21 13:49:45 +00001330 m_supports_mem_region = LazyBool::eLazyBoolNo;
Pavel Labatha6321a82017-01-19 15:26:04 +00001331 LLDB_LOG(log,
1332 "failed to find any procfs maps entries, assuming no support "
1333 "for memory region metadata retrieval");
Zachary Turner97206d52017-05-12 04:51:55 +00001334 return Status("not supported");
Tamas Berghammera6f57952017-01-03 16:29:43 +00001335 }
1336
Pavel Labatha6321a82017-01-19 15:26:04 +00001337 LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps",
1338 m_mem_region_cache.size(), GetID());
Tamas Berghammera6f57952017-01-03 16:29:43 +00001339
1340 // We support memory retrieval, remember that.
1341 m_supports_mem_region = LazyBool::eLazyBoolYes;
Zachary Turner97206d52017-05-12 04:51:55 +00001342 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001343}
1344
Kate Stoneb9c1b512016-09-06 20:57:50 +00001345void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001346 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1347 LLDB_LOG(log, "newBumpId={0}", newBumpId);
1348 LLDB_LOG(log, "clearing {0} entries from memory region cache",
1349 m_mem_region_cache.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001350 m_mem_region_cache.clear();
1351}
1352
Zachary Turner97206d52017-05-12 04:51:55 +00001353Status NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions,
1354 lldb::addr_t &addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001355// FIXME implementing this requires the equivalent of
Adrian Prantl05097242018-04-30 16:49:04 +00001356// InferiorCallPOSIX::InferiorCallMmap, which depends on functional ThreadPlans
1357// working with Native*Protocol.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001358#if 1
Zachary Turner97206d52017-05-12 04:51:55 +00001359 return Status("not implemented yet");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001360#else
1361 addr = LLDB_INVALID_ADDRESS;
1362
1363 unsigned prot = 0;
1364 if (permissions & lldb::ePermissionsReadable)
1365 prot |= eMmapProtRead;
1366 if (permissions & lldb::ePermissionsWritable)
1367 prot |= eMmapProtWrite;
1368 if (permissions & lldb::ePermissionsExecutable)
1369 prot |= eMmapProtExec;
1370
1371 // TODO implement this directly in NativeProcessLinux
Adrian Prantl05097242018-04-30 16:49:04 +00001372 // (and lift to NativeProcessPOSIX if/when that class is refactored out).
Kate Stoneb9c1b512016-09-06 20:57:50 +00001373 if (InferiorCallMmap(this, addr, 0, size, prot,
1374 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
1375 m_addr_to_mmap_size[addr] = size;
Zachary Turner97206d52017-05-12 04:51:55 +00001376 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001377 } else {
1378 addr = LLDB_INVALID_ADDRESS;
Zachary Turner97206d52017-05-12 04:51:55 +00001379 return Status("unable to allocate %" PRIu64
1380 " bytes of memory with permissions %s",
1381 size, GetPermissionsAsCString(permissions));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001382 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001383#endif
1384}
1385
Zachary Turner97206d52017-05-12 04:51:55 +00001386Status NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001387 // FIXME see comments in AllocateMemory - required lower-level
1388 // bits not in place yet (ThreadPlans)
Zachary Turner97206d52017-05-12 04:51:55 +00001389 return Status("not implemented");
Todd Fialaaf245d12014-06-30 21:05:18 +00001390}
1391
Kate Stoneb9c1b512016-09-06 20:57:50 +00001392size_t NativeProcessLinux::UpdateThreads() {
Adrian Prantl05097242018-04-30 16:49:04 +00001393 // The NativeProcessLinux monitoring threads are always up to date with
1394 // respect to thread state and they keep the thread list populated properly.
1395 // All this method needs to do is return the thread count.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001396 return m_threads.size();
Todd Fialaaf245d12014-06-30 21:05:18 +00001397}
1398
Zachary Turner97206d52017-05-12 04:51:55 +00001399Status NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,
1400 bool hardware) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001401 if (hardware)
Omair Javaidd5ffbad2017-02-24 13:27:31 +00001402 return SetHardwareBreakpoint(addr, size);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001403 else
1404 return SetSoftwareBreakpoint(addr, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00001405}
1406
Zachary Turner97206d52017-05-12 04:51:55 +00001407Status NativeProcessLinux::RemoveBreakpoint(lldb::addr_t addr, bool hardware) {
Omair Javaidd5ffbad2017-02-24 13:27:31 +00001408 if (hardware)
1409 return RemoveHardwareBreakpoint(addr);
1410 else
1411 return NativeProcessProtocol::RemoveBreakpoint(addr);
1412}
1413
Pavel Labathf8b825f2018-09-09 06:01:12 +00001414llvm::Expected<llvm::ArrayRef<uint8_t>>
1415NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(size_t size_hint) {
Pavel Labath12286a22018-09-08 10:33:14 +00001416 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1417 // linux kernel does otherwise.
Pavel Labathf8b825f2018-09-09 06:01:12 +00001418 static const uint8_t g_arm_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1419 static const uint8_t g_thumb_opcode[] = {0x01, 0xde};
Todd Fialaaf245d12014-06-30 21:05:18 +00001420
Pavel Labathf8b825f2018-09-09 06:01:12 +00001421 switch (GetArchitecture().GetMachine()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001422 case llvm::Triple::arm:
Pavel Labathf8b825f2018-09-09 06:01:12 +00001423 switch (size_hint) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001424 case 2:
Pavel Labath4f545072018-09-09 08:42:00 +00001425 return llvm::makeArrayRef(g_thumb_opcode);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001426 case 4:
Pavel Labath4f545072018-09-09 08:42:00 +00001427 return llvm::makeArrayRef(g_arm_opcode);
Todd Fialaaf245d12014-06-30 21:05:18 +00001428 default:
Pavel Labathf8b825f2018-09-09 06:01:12 +00001429 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1430 "Unrecognised trap opcode size hint!");
Todd Fialaaf245d12014-06-30 21:05:18 +00001431 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001432 default:
Pavel Labathf8b825f2018-09-09 06:01:12 +00001433 return NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_hint);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001434 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001435}
1436
Zachary Turner97206d52017-05-12 04:51:55 +00001437Status NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
1438 size_t &bytes_read) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001439 if (ProcessVmReadvSupported()) {
1440 // The process_vm_readv path is about 50 times faster than ptrace api. We
Adrian Prantl05097242018-04-30 16:49:04 +00001441 // want to use this syscall if it is supported.
Pavel Labathdf7c6992015-06-17 18:38:49 +00001442
Kate Stoneb9c1b512016-09-06 20:57:50 +00001443 const ::pid_t pid = GetID();
Pavel Labathdf7c6992015-06-17 18:38:49 +00001444
Kate Stoneb9c1b512016-09-06 20:57:50 +00001445 struct iovec local_iov, remote_iov;
1446 local_iov.iov_base = buf;
1447 local_iov.iov_len = size;
1448 remote_iov.iov_base = reinterpret_cast<void *>(addr);
1449 remote_iov.iov_len = size;
Pavel Labathdf7c6992015-06-17 18:38:49 +00001450
Kate Stoneb9c1b512016-09-06 20:57:50 +00001451 bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
1452 const bool success = bytes_read == size;
Pavel Labathdf7c6992015-06-17 18:38:49 +00001453
Pavel Labatha6321a82017-01-19 15:26:04 +00001454 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1455 LLDB_LOG(log,
1456 "using process_vm_readv to read {0} bytes from inferior "
1457 "address {1:x}: {2}",
Pavel Labath10c41f32017-06-06 14:06:17 +00001458 size, addr, success ? "Success" : llvm::sys::StrError(errno));
Pavel Labath19cbe962015-07-21 13:20:32 +00001459
Kate Stoneb9c1b512016-09-06 20:57:50 +00001460 if (success)
Zachary Turner97206d52017-05-12 04:51:55 +00001461 return Status();
Pavel Labatha6321a82017-01-19 15:26:04 +00001462 // else the call failed for some reason, let's retry the read using ptrace
1463 // api.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001464 }
Pavel Labath19cbe962015-07-21 13:20:32 +00001465
Kate Stoneb9c1b512016-09-06 20:57:50 +00001466 unsigned char *dst = static_cast<unsigned char *>(buf);
1467 size_t remainder;
1468 long data;
Pavel Labath19cbe962015-07-21 13:20:32 +00001469
Pavel Labatha6321a82017-01-19 15:26:04 +00001470 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1471 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
Pavel Labath19cbe962015-07-21 13:20:32 +00001472
Kate Stoneb9c1b512016-09-06 20:57:50 +00001473 for (bytes_read = 0; bytes_read < size; bytes_read += remainder) {
Zachary Turner97206d52017-05-12 04:51:55 +00001474 Status error = NativeProcessLinux::PtraceWrapper(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001475 PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data);
Pavel Labatha6321a82017-01-19 15:26:04 +00001476 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001477 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001478
1479 remainder = size - bytes_read;
1480 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
1481
1482 // Copy the data into our buffer
1483 memcpy(dst, &data, remainder);
1484
Pavel Labatha6321a82017-01-19 15:26:04 +00001485 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001486 addr += k_ptrace_word_size;
1487 dst += k_ptrace_word_size;
1488 }
Zachary Turner97206d52017-05-12 04:51:55 +00001489 return Status();
Todd Fialaaf245d12014-06-30 21:05:18 +00001490}
1491
Zachary Turner97206d52017-05-12 04:51:55 +00001492Status NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,
1493 size_t size, size_t &bytes_written) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001494 const unsigned char *src = static_cast<const unsigned char *>(buf);
1495 size_t remainder;
Zachary Turner97206d52017-05-12 04:51:55 +00001496 Status error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001497
Pavel Labatha6321a82017-01-19 15:26:04 +00001498 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1499 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00001500
Kate Stoneb9c1b512016-09-06 20:57:50 +00001501 for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
1502 remainder = size - bytes_written;
1503 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
Chaoren Lin97ccc292015-02-03 01:51:12 +00001504
Kate Stoneb9c1b512016-09-06 20:57:50 +00001505 if (remainder == k_ptrace_word_size) {
1506 unsigned long data = 0;
1507 memcpy(&data, src, k_ptrace_word_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00001508
Pavel Labatha6321a82017-01-19 15:26:04 +00001509 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001510 error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(),
1511 (void *)addr, (void *)data);
Pavel Labatha6321a82017-01-19 15:26:04 +00001512 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001513 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001514 } else {
1515 unsigned char buff[8];
1516 size_t bytes_read;
1517 error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
Pavel Labatha6321a82017-01-19 15:26:04 +00001518 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001519 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001520
1521 memcpy(buff, src, remainder);
1522
1523 size_t bytes_written_rec;
1524 error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
Pavel Labatha6321a82017-01-19 15:26:04 +00001525 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001526 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001527
Pavel Labatha6321a82017-01-19 15:26:04 +00001528 LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src,
1529 *(unsigned long *)buff);
Todd Fialaaf245d12014-06-30 21:05:18 +00001530 }
1531
Kate Stoneb9c1b512016-09-06 20:57:50 +00001532 addr += k_ptrace_word_size;
1533 src += k_ptrace_word_size;
1534 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001535 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001536}
1537
Zachary Turner97206d52017-05-12 04:51:55 +00001538Status NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001539 return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
1540}
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001541
Zachary Turner97206d52017-05-12 04:51:55 +00001542Status NativeProcessLinux::GetEventMessage(lldb::tid_t tid,
1543 unsigned long *message) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001544 return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
1545}
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001546
Zachary Turner97206d52017-05-12 04:51:55 +00001547Status NativeProcessLinux::Detach(lldb::tid_t tid) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001548 if (tid == LLDB_INVALID_THREAD_ID)
Zachary Turner97206d52017-05-12 04:51:55 +00001549 return Status();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001550
Kate Stoneb9c1b512016-09-06 20:57:50 +00001551 return PtraceWrapper(PTRACE_DETACH, tid);
1552}
1553
1554bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {
Pavel Labatha5be48b2017-10-17 15:52:16 +00001555 for (const auto &thread : m_threads) {
1556 assert(thread && "thread list should not contain NULL threads");
1557 if (thread->GetID() == thread_id) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001558 // We have this thread.
1559 return true;
Todd Fialaaf245d12014-06-30 21:05:18 +00001560 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001561 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001562
Kate Stoneb9c1b512016-09-06 20:57:50 +00001563 // We don't have this thread.
1564 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001565}
1566
Kate Stoneb9c1b512016-09-06 20:57:50 +00001567bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001568 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1569 LLDB_LOG(log, "tid: {0})", thread_id);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001570
1571 bool found = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001572 for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
1573 if (*it && ((*it)->GetID() == thread_id)) {
1574 m_threads.erase(it);
1575 found = true;
1576 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00001577 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001578 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001579
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001580 if (found)
1581 StopTracingForThread(thread_id);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001582 SignalIfAllThreadsStopped();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001583 return found;
Todd Fialaaf245d12014-06-30 21:05:18 +00001584}
1585
Pavel Labatha5be48b2017-10-17 15:52:16 +00001586NativeThreadLinux &NativeProcessLinux::AddThread(lldb::tid_t thread_id) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001587 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
1588 LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
Todd Fialaaf245d12014-06-30 21:05:18 +00001589
Kate Stoneb9c1b512016-09-06 20:57:50 +00001590 assert(!HasThreadNoLock(thread_id) &&
1591 "attempted to add a thread by id that already exists");
Todd Fialaaf245d12014-06-30 21:05:18 +00001592
Kate Stoneb9c1b512016-09-06 20:57:50 +00001593 // If this is the first thread, save it as the current thread
1594 if (m_threads.empty())
1595 SetCurrentThreadID(thread_id);
Todd Fialaaf245d12014-06-30 21:05:18 +00001596
Pavel Labatha5be48b2017-10-17 15:52:16 +00001597 m_threads.push_back(llvm::make_unique<NativeThreadLinux>(*this, thread_id));
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001598
1599 if (m_pt_proces_trace_id != LLDB_INVALID_UID) {
1600 auto traceMonitor = ProcessorTraceMonitor::Create(
1601 GetID(), thread_id, m_pt_process_trace_config, true);
1602 if (traceMonitor) {
1603 m_pt_traced_thread_group.insert(thread_id);
1604 m_processor_trace_monitor.insert(
1605 std::make_pair(thread_id, std::move(*traceMonitor)));
1606 } else {
1607 LLDB_LOG(log, "failed to start trace on thread {0}", thread_id);
1608 Status error(traceMonitor.takeError());
1609 LLDB_LOG(log, "error {0}", error);
1610 }
1611 }
1612
Pavel Labatha5be48b2017-10-17 15:52:16 +00001613 return static_cast<NativeThreadLinux &>(*m_threads.back());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001614}
Todd Fialaaf245d12014-06-30 21:05:18 +00001615
Zachary Turner97206d52017-05-12 04:51:55 +00001616Status NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,
1617 FileSpec &file_spec) {
1618 Status error = PopulateMemoryRegionCache();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001619 if (error.Fail())
1620 return error;
1621
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00001622 FileSpec module_file_spec(module_path);
1623 FileSystem::Instance().Resolve(module_file_spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001624
Kate Stoneb9c1b512016-09-06 20:57:50 +00001625 file_spec.Clear();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001626 for (const auto &it : m_mem_region_cache) {
1627 if (it.second.GetFilename() == module_file_spec.GetFilename()) {
1628 file_spec = it.second;
Zachary Turner97206d52017-05-12 04:51:55 +00001629 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001630 }
1631 }
Zachary Turner97206d52017-05-12 04:51:55 +00001632 return Status("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
1633 module_file_spec.GetFilename().AsCString(), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001634}
1635
Zachary Turner97206d52017-05-12 04:51:55 +00001636Status NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
1637 lldb::addr_t &load_addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001638 load_addr = LLDB_INVALID_ADDRESS;
Zachary Turner97206d52017-05-12 04:51:55 +00001639 Status error = PopulateMemoryRegionCache();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001640 if (error.Fail())
1641 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001642
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00001643 FileSpec file(file_name);
Tamas Berghammera6f57952017-01-03 16:29:43 +00001644 for (const auto &it : m_mem_region_cache) {
1645 if (it.second == file) {
1646 load_addr = it.first.GetRange().GetRangeBase();
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("No load address found for specified file.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001651}
1652
Pavel Labatha5be48b2017-10-17 15:52:16 +00001653NativeThreadLinux *NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {
1654 return static_cast<NativeThreadLinux *>(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001655 NativeProcessProtocol::GetThreadByID(tid));
1656}
1657
Zachary Turner97206d52017-05-12 04:51:55 +00001658Status NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,
1659 lldb::StateType state, int signo) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001660 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1661 LLDB_LOG(log, "tid: {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001662
Adrian Prantl05097242018-04-30 16:49:04 +00001663 // Before we do the resume below, first check if we have a pending stop
1664 // notification that is currently waiting for all threads to stop. This is
1665 // potentially a buggy situation since we're ostensibly waiting for threads
1666 // to stop before we send out the pending notification, and here we are
1667 // resuming one before we send out the pending stop notification.
Pavel Labatha6321a82017-01-19 15:26:04 +00001668 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
1669 LLDB_LOG(log,
1670 "about to resume tid {0} per explicit request but we have a "
1671 "pending stop notification (tid {1}) that is actively "
1672 "waiting for this thread to stop. Valid sequence of events?",
1673 thread.GetID(), m_pending_notification_tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001674 }
1675
Adrian Prantl05097242018-04-30 16:49:04 +00001676 // Request a resume. We expect this to be synchronous and the system to
1677 // reflect it is running after this completes.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001678 switch (state) {
1679 case eStateRunning: {
1680 const auto resume_result = thread.Resume(signo);
1681 if (resume_result.Success())
1682 SetState(eStateRunning, true);
1683 return resume_result;
1684 }
1685 case eStateStepping: {
1686 const auto step_result = thread.SingleStep(signo);
1687 if (step_result.Success())
1688 SetState(eStateRunning, true);
1689 return step_result;
1690 }
1691 default:
Pavel Labath8198db32017-01-24 11:48:25 +00001692 LLDB_LOG(log, "Unhandled state {0}.", state);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001693 llvm_unreachable("Unhandled state for resume");
1694 }
Pavel Labathc0765592015-05-06 10:46:34 +00001695}
1696
1697//===----------------------------------------------------------------------===//
1698
Kate Stoneb9c1b512016-09-06 20:57:50 +00001699void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001700 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1701 LLDB_LOG(log, "about to process event: (triggering_tid: {0})",
1702 triggering_tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001703
1704 m_pending_notification_tid = triggering_tid;
1705
Adrian Prantl05097242018-04-30 16:49:04 +00001706 // Request a stop for all the thread stops that need to be stopped and are
1707 // not already known to be stopped.
Pavel Labatha5be48b2017-10-17 15:52:16 +00001708 for (const auto &thread : m_threads) {
1709 if (StateIsRunningState(thread->GetState()))
1710 static_cast<NativeThreadLinux *>(thread.get())->RequestStop();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001711 }
1712
1713 SignalIfAllThreadsStopped();
Pavel Labatha6321a82017-01-19 15:26:04 +00001714 LLDB_LOG(log, "event processing done");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001715}
1716
1717void NativeProcessLinux::SignalIfAllThreadsStopped() {
1718 if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
1719 return; // No pending notification. Nothing to do.
1720
1721 for (const auto &thread_sp : m_threads) {
1722 if (StateIsRunningState(thread_sp->GetState()))
1723 return; // Some threads are still running. Don't signal yet.
1724 }
1725
1726 // We have a pending notification and all threads have stopped.
1727 Log *log(
1728 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
1729
1730 // Clear any temporary breakpoints we used to implement software single
1731 // stepping.
1732 for (const auto &thread_info : m_threads_stepping_with_breakpoint) {
Zachary Turner97206d52017-05-12 04:51:55 +00001733 Status error = RemoveBreakpoint(thread_info.second);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001734 if (error.Fail())
Pavel Labatha6321a82017-01-19 15:26:04 +00001735 LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}",
1736 thread_info.first, error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001737 }
1738 m_threads_stepping_with_breakpoint.clear();
1739
1740 // Notify the delegate about the stop
1741 SetCurrentThreadID(m_pending_notification_tid);
1742 SetState(StateType::eStateStopped, true);
1743 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
1744}
1745
1746void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001747 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1748 LLDB_LOG(log, "tid: {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001749
1750 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID &&
1751 StateIsRunningState(thread.GetState())) {
1752 // We will need to wait for this new thread to stop as well before firing
Adrian Prantl05097242018-04-30 16:49:04 +00001753 // the notification.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001754 thread.RequestStop();
1755 }
1756}
1757
1758void NativeProcessLinux::SigchldHandler() {
Pavel Labatha6321a82017-01-19 15:26:04 +00001759 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001760 // Process all pending waitpid notifications.
1761 while (true) {
1762 int status = -1;
Pavel Labathc1a6b122017-07-03 09:25:55 +00001763 ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, -1, &status,
1764 __WALL | __WNOTHREAD | WNOHANG);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001765
1766 if (wait_pid == 0)
1767 break; // We are done.
1768
1769 if (wait_pid == -1) {
Zachary Turner97206d52017-05-12 04:51:55 +00001770 Status error(errno, eErrorTypePOSIX);
Pavel Labatha6321a82017-01-19 15:26:04 +00001771 LLDB_LOG(log, "waitpid (-1, &status, _) failed: {0}", error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001772 break;
Pavel Labathc0765592015-05-06 10:46:34 +00001773 }
1774
Pavel Labath3508fc82017-06-19 12:47:50 +00001775 WaitStatus wait_status = WaitStatus::Decode(status);
1776 bool exited = wait_status.type == WaitStatus::Exit ||
1777 (wait_status.type == WaitStatus::Signal &&
1778 wait_pid == static_cast<::pid_t>(GetID()));
Pavel Labathc0765592015-05-06 10:46:34 +00001779
Pavel Labath3508fc82017-06-19 12:47:50 +00001780 LLDB_LOG(
1781 log,
1782 "waitpid (-1, &status, _) => pid = {0}, status = {1}, exited = {2}",
1783 wait_pid, wait_status, exited);
Pavel Labathc0765592015-05-06 10:46:34 +00001784
Pavel Labath3508fc82017-06-19 12:47:50 +00001785 MonitorCallback(wait_pid, exited, wait_status);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001786 }
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001787}
1788
Adrian Prantl05097242018-04-30 16:49:04 +00001789// Wrapper for ptrace to catch errors and log calls. Note that ptrace sets
1790// errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
Zachary Turner97206d52017-05-12 04:51:55 +00001791Status NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
1792 void *data, size_t data_size,
1793 long *result) {
1794 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001795 long int ret;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001796
Kate Stoneb9c1b512016-09-06 20:57:50 +00001797 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001798
Kate Stoneb9c1b512016-09-06 20:57:50 +00001799 PtraceDisplayBytes(req, data, data_size);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001800
Kate Stoneb9c1b512016-09-06 20:57:50 +00001801 errno = 0;
1802 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
1803 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
1804 *(unsigned int *)addr, data);
1805 else
1806 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
1807 addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001808
Kate Stoneb9c1b512016-09-06 20:57:50 +00001809 if (ret == -1)
1810 error.SetErrorToErrno();
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001811
Kate Stoneb9c1b512016-09-06 20:57:50 +00001812 if (result)
1813 *result = ret;
Pavel Labath4a9babb2015-06-30 17:04:49 +00001814
Pavel Labath28096202017-02-17 16:09:10 +00001815 LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data,
1816 data_size, ret);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001817
Kate Stoneb9c1b512016-09-06 20:57:50 +00001818 PtraceDisplayBytes(req, data, data_size);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001819
Pavel Labatha6321a82017-01-19 15:26:04 +00001820 if (error.Fail())
1821 LLDB_LOG(log, "ptrace() failed: {0}", error);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001822
Kate Stoneb9c1b512016-09-06 20:57:50 +00001823 return error;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001824}
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001825
1826llvm::Expected<ProcessorTraceMonitor &>
1827NativeProcessLinux::LookupProcessorTraceInstance(lldb::user_id_t traceid,
1828 lldb::tid_t thread) {
1829 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
1830 if (thread == LLDB_INVALID_THREAD_ID && traceid == m_pt_proces_trace_id) {
1831 LLDB_LOG(log, "thread not specified: {0}", traceid);
1832 return Status("tracing not active thread not specified").ToError();
1833 }
1834
1835 for (auto& iter : m_processor_trace_monitor) {
1836 if (traceid == iter.second->GetTraceID() &&
1837 (thread == iter.first || thread == LLDB_INVALID_THREAD_ID))
1838 return *(iter.second);
1839 }
1840
1841 LLDB_LOG(log, "traceid not being traced: {0}", traceid);
1842 return Status("tracing not active for this thread").ToError();
1843}
1844
1845Status NativeProcessLinux::GetMetaData(lldb::user_id_t traceid,
1846 lldb::tid_t thread,
1847 llvm::MutableArrayRef<uint8_t> &buffer,
1848 size_t offset) {
1849 TraceOptions trace_options;
1850 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
1851 Status error;
1852
1853 LLDB_LOG(log, "traceid {0}", traceid);
1854
1855 auto perf_monitor = LookupProcessorTraceInstance(traceid, thread);
1856 if (!perf_monitor) {
1857 LLDB_LOG(log, "traceid not being traced: {0}", traceid);
1858 buffer = buffer.slice(buffer.size());
1859 error = perf_monitor.takeError();
1860 return error;
1861 }
1862 return (*perf_monitor).ReadPerfTraceData(buffer, offset);
1863}
1864
1865Status NativeProcessLinux::GetData(lldb::user_id_t traceid, lldb::tid_t thread,
1866 llvm::MutableArrayRef<uint8_t> &buffer,
1867 size_t offset) {
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).ReadPerfTraceAux(buffer, offset);
1881}
1882
1883Status NativeProcessLinux::GetTraceConfig(lldb::user_id_t traceid,
1884 TraceOptions &config) {
1885 Status error;
1886 if (config.getThreadID() == LLDB_INVALID_THREAD_ID &&
1887 m_pt_proces_trace_id == traceid) {
1888 if (m_pt_proces_trace_id == LLDB_INVALID_UID) {
1889 error.SetErrorString("tracing not active for this process");
1890 return error;
1891 }
1892 config = m_pt_process_trace_config;
1893 } else {
1894 auto perf_monitor =
1895 LookupProcessorTraceInstance(traceid, config.getThreadID());
1896 if (!perf_monitor) {
1897 error = perf_monitor.takeError();
1898 return error;
1899 }
1900 error = (*perf_monitor).GetTraceConfig(config);
1901 }
1902 return error;
1903}
1904
1905lldb::user_id_t
1906NativeProcessLinux::StartTraceGroup(const TraceOptions &config,
1907 Status &error) {
1908
1909 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
1910 if (config.getType() != TraceType::eTraceTypeProcessorTrace)
1911 return LLDB_INVALID_UID;
1912
1913 if (m_pt_proces_trace_id != LLDB_INVALID_UID) {
1914 error.SetErrorString("tracing already active on this process");
1915 return m_pt_proces_trace_id;
1916 }
1917
1918 for (const auto &thread_sp : m_threads) {
1919 if (auto traceInstance = ProcessorTraceMonitor::Create(
1920 GetID(), thread_sp->GetID(), config, true)) {
1921 m_pt_traced_thread_group.insert(thread_sp->GetID());
1922 m_processor_trace_monitor.insert(
1923 std::make_pair(thread_sp->GetID(), std::move(*traceInstance)));
1924 }
1925 }
1926
1927 m_pt_process_trace_config = config;
1928 error = ProcessorTraceMonitor::GetCPUType(m_pt_process_trace_config);
1929
1930 // Trace on Complete process will have traceid of 0
1931 m_pt_proces_trace_id = 0;
1932
1933 LLDB_LOG(log, "Process Trace ID {0}", m_pt_proces_trace_id);
1934 return m_pt_proces_trace_id;
1935}
1936
1937lldb::user_id_t NativeProcessLinux::StartTrace(const TraceOptions &config,
1938 Status &error) {
1939 if (config.getType() != TraceType::eTraceTypeProcessorTrace)
1940 return NativeProcessProtocol::StartTrace(config, error);
1941
1942 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
1943
1944 lldb::tid_t threadid = config.getThreadID();
1945
1946 if (threadid == LLDB_INVALID_THREAD_ID)
1947 return StartTraceGroup(config, error);
1948
1949 auto thread_sp = GetThreadByID(threadid);
1950 if (!thread_sp) {
1951 // Thread not tracked by lldb so don't trace.
1952 error.SetErrorString("invalid thread id");
1953 return LLDB_INVALID_UID;
1954 }
1955
1956 const auto &iter = m_processor_trace_monitor.find(threadid);
1957 if (iter != m_processor_trace_monitor.end()) {
1958 LLDB_LOG(log, "Thread already being traced");
1959 error.SetErrorString("tracing already active on this thread");
1960 return LLDB_INVALID_UID;
1961 }
1962
1963 auto traceMonitor =
1964 ProcessorTraceMonitor::Create(GetID(), threadid, config, false);
1965 if (!traceMonitor) {
1966 error = traceMonitor.takeError();
1967 LLDB_LOG(log, "error {0}", error);
1968 return LLDB_INVALID_UID;
1969 }
1970 lldb::user_id_t ret_trace_id = (*traceMonitor)->GetTraceID();
1971 m_processor_trace_monitor.insert(
1972 std::make_pair(threadid, std::move(*traceMonitor)));
1973 return ret_trace_id;
1974}
1975
1976Status NativeProcessLinux::StopTracingForThread(lldb::tid_t thread) {
1977 Status error;
1978 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
1979 LLDB_LOG(log, "Thread {0}", thread);
1980
1981 const auto& iter = m_processor_trace_monitor.find(thread);
1982 if (iter == m_processor_trace_monitor.end()) {
1983 error.SetErrorString("tracing not active for this thread");
1984 return error;
1985 }
1986
1987 if (iter->second->GetTraceID() == m_pt_proces_trace_id) {
Adrian Prantl05097242018-04-30 16:49:04 +00001988 // traceid maps to the whole process so we have to erase it from the thread
1989 // group.
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001990 LLDB_LOG(log, "traceid maps to process");
1991 m_pt_traced_thread_group.erase(thread);
1992 }
1993 m_processor_trace_monitor.erase(iter);
1994
1995 return error;
1996}
1997
1998Status NativeProcessLinux::StopTrace(lldb::user_id_t traceid,
1999 lldb::tid_t thread) {
2000 Status error;
2001
2002 TraceOptions trace_options;
2003 trace_options.setThreadID(thread);
2004 error = NativeProcessLinux::GetTraceConfig(traceid, trace_options);
2005
2006 if (error.Fail())
2007 return error;
2008
2009 switch (trace_options.getType()) {
2010 case lldb::TraceType::eTraceTypeProcessorTrace:
2011 if (traceid == m_pt_proces_trace_id &&
2012 thread == LLDB_INVALID_THREAD_ID)
2013 StopProcessorTracingOnProcess();
2014 else
2015 error = StopProcessorTracingOnThread(traceid, thread);
2016 break;
2017 default:
2018 error.SetErrorString("trace not supported");
2019 break;
2020 }
2021
2022 return error;
2023}
2024
2025void NativeProcessLinux::StopProcessorTracingOnProcess() {
2026 for (auto thread_id_iter : m_pt_traced_thread_group)
2027 m_processor_trace_monitor.erase(thread_id_iter);
2028 m_pt_traced_thread_group.clear();
2029 m_pt_proces_trace_id = LLDB_INVALID_UID;
2030}
2031
2032Status NativeProcessLinux::StopProcessorTracingOnThread(lldb::user_id_t traceid,
2033 lldb::tid_t thread) {
2034 Status error;
2035 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2036
2037 if (thread == LLDB_INVALID_THREAD_ID) {
2038 for (auto& iter : m_processor_trace_monitor) {
2039 if (iter.second->GetTraceID() == traceid) {
Adrian Prantl05097242018-04-30 16:49:04 +00002040 // Stopping a trace instance for an individual thread hence there will
2041 // only be one traceid that can match.
Ravitheja Addepally99e37692017-06-28 07:58:31 +00002042 m_processor_trace_monitor.erase(iter.first);
2043 return error;
2044 }
2045 LLDB_LOG(log, "Trace ID {0}", iter.second->GetTraceID());
2046 }
2047
2048 LLDB_LOG(log, "Invalid TraceID");
2049 error.SetErrorString("invalid trace id");
2050 return error;
2051 }
2052
2053 // thread is specified so we can use find function on the map.
2054 const auto& iter = m_processor_trace_monitor.find(thread);
2055 if (iter == m_processor_trace_monitor.end()) {
2056 // thread not found in our map.
2057 LLDB_LOG(log, "thread not being traced");
2058 error.SetErrorString("tracing not active for this thread");
2059 return error;
2060 }
2061 if (iter->second->GetTraceID() != traceid) {
2062 // traceid did not match so it has to be invalid.
2063 LLDB_LOG(log, "Invalid TraceID");
2064 error.SetErrorString("invalid trace id");
2065 return error;
2066 }
2067
2068 LLDB_LOG(log, "UID - {0} , Thread -{1}", traceid, thread);
2069
2070 if (traceid == m_pt_proces_trace_id) {
Adrian Prantl05097242018-04-30 16:49:04 +00002071 // traceid maps to the whole process so we have to erase it from the thread
2072 // group.
Ravitheja Addepally99e37692017-06-28 07:58:31 +00002073 LLDB_LOG(log, "traceid maps to process");
2074 m_pt_traced_thread_group.erase(thread);
2075 }
2076 m_processor_trace_monitor.erase(iter);
2077
2078 return error;
Pavel Labath08c38f72019-07-01 12:41:20 +00002079}