blob: bab2a71de3dce28b5cb7313fb999dc22b712f254 [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// -----------------------------------------------------------------------------
210// Public Static Methods
211// -----------------------------------------------------------------------------
212
Pavel Labath82abefa2017-07-18 09:24:48 +0000213llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
Pavel Labath96e600f2017-07-07 11:02:19 +0000214NativeProcessLinux::Factory::Launch(ProcessLaunchInfo &launch_info,
215 NativeDelegate &native_delegate,
216 MainLoop &mainloop) const {
Pavel Labatha6321a82017-01-19 15:26:04 +0000217 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Todd Fialaaf245d12014-06-30 21:05:18 +0000218
Pavel Labath96e600f2017-07-07 11:02:19 +0000219 MaybeLogLaunchInfo(launch_info);
Todd Fialaaf245d12014-06-30 21:05:18 +0000220
Pavel Labath96e600f2017-07-07 11:02:19 +0000221 Status status;
222 ::pid_t pid = ProcessLauncherPosixFork()
223 .LaunchProcess(launch_info, status)
224 .GetProcessId();
225 LLDB_LOG(log, "pid = {0:x}", pid);
226 if (status.Fail()) {
227 LLDB_LOG(log, "failed to launch process: {0}", status);
228 return status.ToError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000229 }
230
Pavel Labath96e600f2017-07-07 11:02:19 +0000231 // Wait for the child process to trap on its call to execve.
232 int wstatus;
233 ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0);
234 assert(wpid == pid);
235 (void)wpid;
236 if (!WIFSTOPPED(wstatus)) {
237 LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}",
238 WaitStatus::Decode(wstatus));
239 return llvm::make_error<StringError>("Could not sync with inferior process",
240 llvm::inconvertibleErrorCode());
241 }
242 LLDB_LOG(log, "inferior started, now in stopped state");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000243
Pavel Labath36e82202018-01-29 10:46:00 +0000244 ProcessInstanceInfo Info;
245 if (!Host::GetProcessInfo(pid, Info)) {
246 return llvm::make_error<StringError>("Cannot get process architecture",
247 llvm::inconvertibleErrorCode());
248 }
Pavel Labath96e600f2017-07-07 11:02:19 +0000249
250 // Set the architecture to the exe architecture.
251 LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid,
Pavel Labath36e82202018-01-29 10:46:00 +0000252 Info.GetArchitecture().GetArchitectureName());
Pavel Labath96e600f2017-07-07 11:02:19 +0000253
254 status = SetDefaultPtraceOpts(pid);
255 if (status.Fail()) {
256 LLDB_LOG(log, "failed to set default ptrace options: {0}", status);
257 return status.ToError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000258 }
259
Pavel Labath82abefa2017-07-18 09:24:48 +0000260 return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
Pavel Labath96e600f2017-07-07 11:02:19 +0000261 pid, launch_info.GetPTY().ReleaseMasterFileDescriptor(), native_delegate,
Pavel Labath36e82202018-01-29 10:46:00 +0000262 Info.GetArchitecture(), mainloop, {pid}));
Todd Fialaaf245d12014-06-30 21:05:18 +0000263}
264
Pavel Labath82abefa2017-07-18 09:24:48 +0000265llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
266NativeProcessLinux::Factory::Attach(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000267 lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
Pavel Labath96e600f2017-07-07 11:02:19 +0000268 MainLoop &mainloop) const {
Pavel Labatha6321a82017-01-19 15:26:04 +0000269 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
270 LLDB_LOG(log, "pid = {0:x}", pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000271
Kate Stoneb9c1b512016-09-06 20:57:50 +0000272 // Retrieve the architecture for the running process.
Pavel Labath36e82202018-01-29 10:46:00 +0000273 ProcessInstanceInfo Info;
274 if (!Host::GetProcessInfo(pid, Info)) {
275 return llvm::make_error<StringError>("Cannot get process architecture",
276 llvm::inconvertibleErrorCode());
277 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000278
Pavel Labath96e600f2017-07-07 11:02:19 +0000279 auto tids_or = NativeProcessLinux::Attach(pid);
280 if (!tids_or)
281 return tids_or.takeError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000282
Pavel Labath82abefa2017-07-18 09:24:48 +0000283 return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux(
Pavel Labath36e82202018-01-29 10:46:00 +0000284 pid, -1, native_delegate, Info.GetArchitecture(), mainloop, *tids_or));
Todd Fialaaf245d12014-06-30 21:05:18 +0000285}
286
287// -----------------------------------------------------------------------------
288// Public Instance Methods
289// -----------------------------------------------------------------------------
290
Pavel Labath96e600f2017-07-07 11:02:19 +0000291NativeProcessLinux::NativeProcessLinux(::pid_t pid, int terminal_fd,
292 NativeDelegate &delegate,
Pavel Labath82abefa2017-07-18 09:24:48 +0000293 const ArchSpec &arch, MainLoop &mainloop,
294 llvm::ArrayRef<::pid_t> tids)
Pavel Labath96e600f2017-07-07 11:02:19 +0000295 : NativeProcessProtocol(pid, terminal_fd, delegate), m_arch(arch) {
296 if (m_terminal_fd != -1) {
297 Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
298 assert(status.Success());
299 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000300
Pavel Labath96e600f2017-07-07 11:02:19 +0000301 Status status;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000302 m_sigchld_handle = mainloop.RegisterSignal(
Pavel Labath96e600f2017-07-07 11:02:19 +0000303 SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status);
304 assert(m_sigchld_handle && status.Success());
Todd Fialaaf245d12014-06-30 21:05:18 +0000305
Pavel Labath96e600f2017-07-07 11:02:19 +0000306 for (const auto &tid : tids) {
Pavel Labatha5be48b2017-10-17 15:52:16 +0000307 NativeThreadLinux &thread = AddThread(tid);
308 thread.SetStoppedBySignal(SIGSTOP);
309 ThreadWasCreated(thread);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000310 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000311
Kate Stoneb9c1b512016-09-06 20:57:50 +0000312 // Let our process instance know the thread has stopped.
Pavel Labath96e600f2017-07-07 11:02:19 +0000313 SetCurrentThreadID(tids[0]);
314 SetState(StateType::eStateStopped, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000315
Pavel Labath96e600f2017-07-07 11:02:19 +0000316 // Proccess any signals we received before installing our handler
317 SigchldHandler();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000318}
319
Pavel Labath96e600f2017-07-07 11:02:19 +0000320llvm::Expected<std::vector<::pid_t>> NativeProcessLinux::Attach(::pid_t pid) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000321 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000322
Pavel Labath96e600f2017-07-07 11:02:19 +0000323 Status status;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000324 // Use a map to keep track of the threads which we have attached/need to
325 // attach.
326 Host::TidMap tids_to_attach;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000327 while (Host::FindProcessThreads(pid, tids_to_attach)) {
328 for (Host::TidMap::iterator it = tids_to_attach.begin();
329 it != tids_to_attach.end();) {
330 if (it->second == false) {
331 lldb::tid_t tid = it->first;
332
333 // Attach to the requested process.
334 // An attach will cause the thread to stop with a SIGSTOP.
Pavel Labath96e600f2017-07-07 11:02:19 +0000335 if ((status = PtraceWrapper(PTRACE_ATTACH, tid)).Fail()) {
Adrian Prantl05097242018-04-30 16:49:04 +0000336 // No such thread. The thread may have exited. More error handling
337 // may be needed.
Pavel Labath96e600f2017-07-07 11:02:19 +0000338 if (status.GetError() == ESRCH) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000339 it = tids_to_attach.erase(it);
340 continue;
Pavel Labath96e600f2017-07-07 11:02:19 +0000341 }
342 return status.ToError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000343 }
344
Pavel Labath96e600f2017-07-07 11:02:19 +0000345 int wpid =
346 llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, nullptr, __WALL);
Adrian Prantl05097242018-04-30 16:49:04 +0000347 // Need to use __WALL otherwise we receive an error with errno=ECHLD At
348 // this point we should have a thread stopped if waitpid succeeds.
Pavel Labath96e600f2017-07-07 11:02:19 +0000349 if (wpid < 0) {
Adrian Prantl05097242018-04-30 16:49:04 +0000350 // No such thread. The thread may have exited. More error handling
351 // may be needed.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000352 if (errno == ESRCH) {
353 it = tids_to_attach.erase(it);
354 continue;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000355 }
Pavel Labath96e600f2017-07-07 11:02:19 +0000356 return llvm::errorCodeToError(
357 std::error_code(errno, std::generic_category()));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000358 }
359
Pavel Labath96e600f2017-07-07 11:02:19 +0000360 if ((status = SetDefaultPtraceOpts(tid)).Fail())
361 return status.ToError();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000362
Pavel Labatha6321a82017-01-19 15:26:04 +0000363 LLDB_LOG(log, "adding tid = {0}", tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000364 it->second = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000365 }
366
367 // move the loop forward
368 ++it;
369 }
370 }
371
Pavel Labath96e600f2017-07-07 11:02:19 +0000372 size_t tid_count = tids_to_attach.size();
373 if (tid_count == 0)
374 return llvm::make_error<StringError>("No such process",
375 llvm::inconvertibleErrorCode());
Todd Fialaaf245d12014-06-30 21:05:18 +0000376
Pavel Labath96e600f2017-07-07 11:02:19 +0000377 std::vector<::pid_t> tids;
378 tids.reserve(tid_count);
379 for (const auto &p : tids_to_attach)
380 tids.push_back(p.first);
381 return std::move(tids);
Todd Fialaaf245d12014-06-30 21:05:18 +0000382}
383
Zachary Turner97206d52017-05-12 04:51:55 +0000384Status NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000385 long ptrace_opts = 0;
Todd Fialaaf245d12014-06-30 21:05:18 +0000386
Kate Stoneb9c1b512016-09-06 20:57:50 +0000387 // Have the child raise an event on exit. This is used to keep the child in
388 // limbo until it is destroyed.
389 ptrace_opts |= PTRACE_O_TRACEEXIT;
Todd Fialaaf245d12014-06-30 21:05:18 +0000390
Kate Stoneb9c1b512016-09-06 20:57:50 +0000391 // Have the tracer trace threads which spawn in the inferior process.
392 // TODO: if we want to support tracing the inferiors' child, add the
393 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
394 ptrace_opts |= PTRACE_O_TRACECLONE;
Todd Fialaaf245d12014-06-30 21:05:18 +0000395
Adrian Prantl05097242018-04-30 16:49:04 +0000396 // Have the tracer notify us before execve returns (needed to disable legacy
397 // SIGTRAP generation)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000398 ptrace_opts |= PTRACE_O_TRACEEXEC;
Todd Fialaaf245d12014-06-30 21:05:18 +0000399
Kate Stoneb9c1b512016-09-06 20:57:50 +0000400 return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void *)ptrace_opts);
Todd Fialaaf245d12014-06-30 21:05:18 +0000401}
402
Pavel Labath1107b5a2015-04-17 14:07:49 +0000403// Handles all waitpid events from the inferior process.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000404void NativeProcessLinux::MonitorCallback(lldb::pid_t pid, bool exited,
Pavel Labath3508fc82017-06-19 12:47:50 +0000405 WaitStatus status) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000406 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Todd Fialaaf245d12014-06-30 21:05:18 +0000407
Kate Stoneb9c1b512016-09-06 20:57:50 +0000408 // Certain activities differ based on whether the pid is the tid of the main
409 // thread.
410 const bool is_main_thread = (pid == GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000411
Kate Stoneb9c1b512016-09-06 20:57:50 +0000412 // Handle when the thread exits.
413 if (exited) {
Pavel Labathd8b3c1a2017-12-18 09:44:29 +0000414 LLDB_LOG(log,
Pavel Labath9303afb2019-02-07 15:56:35 +0000415 "got exit status({0}) , tid = {1} ({2} main thread), process "
Pavel Labathd8b3c1a2017-12-18 09:44:29 +0000416 "state = {3}",
Pavel Labath9303afb2019-02-07 15:56:35 +0000417 status, pid, is_main_thread ? "is" : "is not", GetState());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000418
419 // This is a thread that exited. Ensure we're not tracking it anymore.
Pavel Labathd8b3c1a2017-12-18 09:44:29 +0000420 StopTrackingThread(pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000421
422 if (is_main_thread) {
Pavel Labathd8b3c1a2017-12-18 09:44:29 +0000423 // The main thread exited. We're done monitoring. Report to delegate.
424 SetExitStatus(status, true);
Todd Fialaaf245d12014-06-30 21:05:18 +0000425
Pavel Labathd8b3c1a2017-12-18 09:44:29 +0000426 // Notify delegate that our process has exited.
427 SetState(StateType::eStateExited, true);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000428 }
429 return;
430 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000431
Kate Stoneb9c1b512016-09-06 20:57:50 +0000432 siginfo_t info;
433 const auto info_err = GetSignalInfo(pid, &info);
434 auto thread_sp = GetThreadByID(pid);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000435
Kate Stoneb9c1b512016-09-06 20:57:50 +0000436 if (!thread_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +0000437 // Normally, the only situation when we cannot find the thread is if we
438 // have just received a new thread notification. This is indicated by
Pavel Labatha6321a82017-01-19 15:26:04 +0000439 // GetSignalInfo() returning si_code == SI_USER and si_pid == 0
440 LLDB_LOG(log, "received notification about an unknown tid {0}.", pid);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000441
Kate Stoneb9c1b512016-09-06 20:57:50 +0000442 if (info_err.Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000443 LLDB_LOG(log,
444 "(tid {0}) GetSignalInfo failed ({1}). "
445 "Ingoring this notification.",
446 pid, info_err);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000447 return;
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000448 }
449
Pavel Labatha6321a82017-01-19 15:26:04 +0000450 LLDB_LOG(log, "tid {0}, si_code: {1}, si_pid: {2}", pid, info.si_code,
451 info.si_pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000452
Pavel Labatha5be48b2017-10-17 15:52:16 +0000453 NativeThreadLinux &thread = AddThread(pid);
Ravitheja Addepally99e37692017-06-28 07:58:31 +0000454
Kate Stoneb9c1b512016-09-06 20:57:50 +0000455 // Resume the newly created thread.
Pavel Labatha5be48b2017-10-17 15:52:16 +0000456 ResumeThread(thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
457 ThreadWasCreated(thread);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000458 return;
459 }
460
461 // Get details on the signal raised.
462 if (info_err.Success()) {
463 // We have retrieved the signal info. Dispatch appropriately.
464 if (info.si_signo == SIGTRAP)
465 MonitorSIGTRAP(info, *thread_sp);
Chaoren Linfa03ad22015-02-03 01:50:42 +0000466 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000467 MonitorSignal(info, *thread_sp, exited);
468 } else {
469 if (info_err.GetError() == EINVAL) {
Adrian Prantl05097242018-04-30 16:49:04 +0000470 // This is a group stop reception for this tid. We can reach here if we
471 // reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the tracee,
472 // triggering the group-stop mechanism. Normally receiving these would
473 // stop the process, pending a SIGCONT. Simulating this state in a
474 // debugger is hard and is generally not needed (one use case is
475 // debugging background task being managed by a shell). For general use,
476 // it is sufficient to stop the process in a signal-delivery stop which
477 // happens before the group stop. This done by MonitorSignal and works
478 // correctly for all signals.
Pavel Labatha6321a82017-01-19 15:26:04 +0000479 LLDB_LOG(log,
480 "received a group stop for pid {0} tid {1}. Transparent "
481 "handling of group stops not supported, resuming the "
482 "thread.",
483 GetID(), pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000484 ResumeThread(*thread_sp, thread_sp->GetState(),
485 LLDB_INVALID_SIGNAL_NUMBER);
486 } else {
487 // ptrace(GETSIGINFO) failed (but not due to group-stop).
Todd Fialaaf245d12014-06-30 21:05:18 +0000488
Kate Stoneb9c1b512016-09-06 20:57:50 +0000489 // A return value of ESRCH means the thread/process is no longer on the
Pavel Labatha6321a82017-01-19 15:26:04 +0000490 // system, so it was killed somehow outside of our control. Either way,
491 // we can't do anything with it anymore.
Todd Fialaaf245d12014-06-30 21:05:18 +0000492
Kate Stoneb9c1b512016-09-06 20:57:50 +0000493 // Stop tracking the metadata for the thread since it's entirely off the
494 // system now.
495 const bool thread_found = StopTrackingThread(pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000496
Pavel Labatha6321a82017-01-19 15:26:04 +0000497 LLDB_LOG(log,
Pavel Labath9303afb2019-02-07 15:56:35 +0000498 "GetSignalInfo failed: {0}, tid = {1}, status = {2}, "
Pavel Labatha6321a82017-01-19 15:26:04 +0000499 "status = {3}, main_thread = {4}, thread_found: {5}",
Pavel Labath9303afb2019-02-07 15:56:35 +0000500 info_err, pid, status, status, is_main_thread, thread_found);
Todd Fialaaf245d12014-06-30 21:05:18 +0000501
Kate Stoneb9c1b512016-09-06 20:57:50 +0000502 if (is_main_thread) {
503 // Notify the delegate - our process is not available but appears to
Adrian Prantl05097242018-04-30 16:49:04 +0000504 // have been killed outside our control. Is eStateExited the right
505 // exit state in this case?
Pavel Labath3508fc82017-06-19 12:47:50 +0000506 SetExitStatus(status, true);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000507 SetState(StateType::eStateExited, true);
508 } else {
509 // This thread was pulled out from underneath us. Anything to do here?
510 // Do we want to do an all stop?
Pavel Labatha6321a82017-01-19 15:26:04 +0000511 LLDB_LOG(log,
512 "pid {0} tid {1} non-main thread exit occurred, didn't "
513 "tell delegate anything since thread disappeared out "
514 "from underneath us",
515 GetID(), pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000516 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000517 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000518 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000519}
520
Kate Stoneb9c1b512016-09-06 20:57:50 +0000521void NativeProcessLinux::WaitForNewThread(::pid_t tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000522 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Pavel Labath426bdf82015-04-28 07:51:52 +0000523
Pavel Labatha5be48b2017-10-17 15:52:16 +0000524 if (GetThreadByID(tid)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000525 // We are already tracking the thread - we got the event on the new thread
Pavel Labatha5be48b2017-10-17 15:52:16 +0000526 // (see MonitorSignal) before this one. We are done.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000527 return;
528 }
Pavel Labath426bdf82015-04-28 07:51:52 +0000529
Kate Stoneb9c1b512016-09-06 20:57:50 +0000530 // The thread is not tracked yet, let's wait for it to appear.
531 int status = -1;
Pavel Labathc1a6b122017-07-03 09:25:55 +0000532 LLDB_LOG(log,
533 "received thread creation event for tid {0}. tid not tracked "
534 "yet, waiting for thread to appear...",
535 tid);
536 ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, &status, __WALL);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000537 // Since we are waiting on a specific tid, this must be the creation event.
Pavel Labatha6321a82017-01-19 15:26:04 +0000538 // But let's do some checks just in case.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000539 if (wait_pid != tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000540 LLDB_LOG(log,
541 "waiting for tid {0} failed. Assuming the thread has "
542 "disappeared in the meantime",
543 tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000544 // The only way I know of this could happen is if the whole process was
545 // SIGKILLed in the mean time. In any case, we can't do anything about that
546 // now.
547 return;
548 }
549 if (WIFEXITED(status)) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000550 LLDB_LOG(log,
551 "waiting for tid {0} returned an 'exited' event. Not "
552 "tracking the thread.",
553 tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000554 // Also a very improbable event.
555 return;
556 }
Pavel Labath426bdf82015-04-28 07:51:52 +0000557
Pavel Labatha6321a82017-01-19 15:26:04 +0000558 LLDB_LOG(log, "pid = {0}: tracking new thread tid {1}", GetID(), tid);
Pavel Labatha5be48b2017-10-17 15:52:16 +0000559 NativeThreadLinux &new_thread = AddThread(tid);
Ravitheja Addepally99e37692017-06-28 07:58:31 +0000560
Pavel Labatha5be48b2017-10-17 15:52:16 +0000561 ResumeThread(new_thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
562 ThreadWasCreated(new_thread);
Pavel Labath426bdf82015-04-28 07:51:52 +0000563}
564
Kate Stoneb9c1b512016-09-06 20:57:50 +0000565void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info,
566 NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000567 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000568 const bool is_main_thread = (thread.GetID() == GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000569
Kate Stoneb9c1b512016-09-06 20:57:50 +0000570 assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
Todd Fialaaf245d12014-06-30 21:05:18 +0000571
Kate Stoneb9c1b512016-09-06 20:57:50 +0000572 switch (info.si_code) {
573 // TODO: these two cases are required if we want to support tracing of the
Adrian Prantl05097242018-04-30 16:49:04 +0000574 // inferiors' children. We'd need this to debug a monitor. case (SIGTRAP |
575 // (PTRACE_EVENT_FORK << 8)): case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
Todd Fialaaf245d12014-06-30 21:05:18 +0000576
Kate Stoneb9c1b512016-09-06 20:57:50 +0000577 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): {
578 // This is the notification on the parent thread which informs us of new
Adrian Prantl05097242018-04-30 16:49:04 +0000579 // thread creation. We don't want to do anything with the parent thread so
580 // we just resume it. In case we want to implement "break on thread
581 // creation" functionality, we would need to stop here.
Todd Fialaaf245d12014-06-30 21:05:18 +0000582
Kate Stoneb9c1b512016-09-06 20:57:50 +0000583 unsigned long event_message = 0;
584 if (GetEventMessage(thread.GetID(), &event_message).Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000585 LLDB_LOG(log,
586 "pid {0} received thread creation event but "
587 "GetEventMessage failed so we don't know the new tid",
588 thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000589 } else
590 WaitForNewThread(event_message);
Todd Fialaaf245d12014-06-30 21:05:18 +0000591
Kate Stoneb9c1b512016-09-06 20:57:50 +0000592 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
593 break;
594 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000595
Kate Stoneb9c1b512016-09-06 20:57:50 +0000596 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): {
Pavel Labatha6321a82017-01-19 15:26:04 +0000597 LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000598
599 // Exec clears any pending notifications.
600 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
601
602 // Remove all but the main thread here. Linux fork creates a new process
603 // which only copies the main thread.
Pavel Labatha6321a82017-01-19 15:26:04 +0000604 LLDB_LOG(log, "exec received, stop tracking all but main thread");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000605
Pavel Labatha5be48b2017-10-17 15:52:16 +0000606 for (auto i = m_threads.begin(); i != m_threads.end();) {
607 if ((*i)->GetID() == GetID())
608 i = m_threads.erase(i);
609 else
610 ++i;
Todd Fialaa9882ce2014-08-28 15:46:54 +0000611 }
Pavel Labatha5be48b2017-10-17 15:52:16 +0000612 assert(m_threads.size() == 1);
613 auto *main_thread = static_cast<NativeThreadLinux *>(m_threads[0].get());
Todd Fialaaf245d12014-06-30 21:05:18 +0000614
Pavel Labatha5be48b2017-10-17 15:52:16 +0000615 SetCurrentThreadID(main_thread->GetID());
616 main_thread->SetStoppedByExec();
Todd Fialaaf245d12014-06-30 21:05:18 +0000617
Kate Stoneb9c1b512016-09-06 20:57:50 +0000618 // Tell coordinator about about the "new" (since exec) stopped main thread.
Pavel Labatha5be48b2017-10-17 15:52:16 +0000619 ThreadWasCreated(*main_thread);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000620
Kate Stoneb9c1b512016-09-06 20:57:50 +0000621 // Let our delegate know we have just exec'd.
622 NotifyDidExec();
623
Kate Stoneb9c1b512016-09-06 20:57:50 +0000624 // Let the process know we're stopped.
Pavel Labatha5be48b2017-10-17 15:52:16 +0000625 StopRunningThreads(main_thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000626
627 break;
628 }
629
630 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): {
Adrian Prantl05097242018-04-30 16:49:04 +0000631 // The inferior process or one of its threads is about to exit. We don't
632 // want to do anything with the thread so we just resume it. In case we
633 // want to implement "break on thread exit" functionality, we would need to
634 // stop here.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000635
636 unsigned long data = 0;
637 if (GetEventMessage(thread.GetID(), &data).Fail())
638 data = -1;
639
Pavel Labatha6321a82017-01-19 15:26:04 +0000640 LLDB_LOG(log,
641 "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
642 "WIFSIGNALED={2}, pid = {3}, main_thread = {4}",
643 data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(),
644 is_main_thread);
Todd Fialaaf245d12014-06-30 21:05:18 +0000645
Kate Stoneb9c1b512016-09-06 20:57:50 +0000646
647 StateType state = thread.GetState();
648 if (!StateIsRunningState(state)) {
649 // Due to a kernel bug, we may sometimes get this stop after the inferior
Pavel Labathd8b3c1a2017-12-18 09:44:29 +0000650 // gets a SIGKILL. This confuses our state tracking logic in
651 // ResumeThread(), since normally, we should not be receiving any ptrace
Adrian Prantl05097242018-04-30 16:49:04 +0000652 // events while the inferior is stopped. This makes sure that the
653 // inferior is resumed and exits normally.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000654 state = eStateRunning;
655 }
656 ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
657
658 break;
659 }
660
661 case 0:
662 case TRAP_TRACE: // We receive this on single stepping.
663 case TRAP_HWBKPT: // We receive this on watchpoint hit
664 {
665 // If a watchpoint was hit, report it
666 uint32_t wp_index;
Pavel Labathd37349f2017-11-10 11:05:49 +0000667 Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000668 wp_index, (uintptr_t)info.si_addr);
Pavel Labatha6321a82017-01-19 15:26:04 +0000669 if (error.Fail())
670 LLDB_LOG(log,
671 "received error while checking for watchpoint hits, pid = "
672 "{0}, error = {1}",
673 thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000674 if (wp_index != LLDB_INVALID_INDEX32) {
675 MonitorWatchpoint(thread, wp_index);
676 break;
677 }
678
Omair Javaidd5ffbad2017-02-24 13:27:31 +0000679 // If a breakpoint was hit, report it
680 uint32_t bp_index;
Pavel Labathd37349f2017-11-10 11:05:49 +0000681 error = thread.GetRegisterContext().GetHardwareBreakHitIndex(
Omair Javaidd5ffbad2017-02-24 13:27:31 +0000682 bp_index, (uintptr_t)info.si_addr);
683 if (error.Fail())
684 LLDB_LOG(log, "received error while checking for hardware "
685 "breakpoint hits, pid = {0}, error = {1}",
686 thread.GetID(), error);
687 if (bp_index != LLDB_INVALID_INDEX32) {
688 MonitorBreakpoint(thread);
689 break;
690 }
691
Kate Stoneb9c1b512016-09-06 20:57:50 +0000692 // Otherwise, report step over
693 MonitorTrace(thread);
694 break;
695 }
696
697 case SI_KERNEL:
Mohit K. Bhakkad35799962015-06-18 04:53:18 +0000698#if defined __mips__
Adrian Prantl05097242018-04-30 16:49:04 +0000699 // For mips there is no special signal for watchpoint So we check for
700 // watchpoint in kernel trap
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000701 {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000702 // If a watchpoint was hit, report it
703 uint32_t wp_index;
Pavel Labathd37349f2017-11-10 11:05:49 +0000704 Status error = thread.GetRegisterContext().GetWatchpointHitIndex(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000705 wp_index, LLDB_INVALID_ADDRESS);
Pavel Labatha6321a82017-01-19 15:26:04 +0000706 if (error.Fail())
707 LLDB_LOG(log,
708 "received error while checking for watchpoint hits, pid = "
709 "{0}, error = {1}",
710 thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000711 if (wp_index != LLDB_INVALID_INDEX32) {
712 MonitorWatchpoint(thread, wp_index);
713 break;
714 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000715 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000716// NO BREAK
Mohit K. Bhakkad35799962015-06-18 04:53:18 +0000717#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000718 case TRAP_BRKPT:
719 MonitorBreakpoint(thread);
720 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000721
Kate Stoneb9c1b512016-09-06 20:57:50 +0000722 case SIGTRAP:
723 case (SIGTRAP | 0x80):
Pavel Labatha6321a82017-01-19 15:26:04 +0000724 LLDB_LOG(
725 log,
726 "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",
727 info.si_code, GetID(), thread.GetID());
Chaoren Linfa03ad22015-02-03 01:50:42 +0000728
Kate Stoneb9c1b512016-09-06 20:57:50 +0000729 // Ignore these signals until we know more about them.
730 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
731 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000732
Kate Stoneb9c1b512016-09-06 20:57:50 +0000733 default:
Pavel Labath21a365b2017-07-11 10:38:40 +0000734 LLDB_LOG(log, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}",
735 info.si_code, GetID(), thread.GetID());
736 MonitorSignal(info, thread, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000737 break;
738 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000739}
740
Kate Stoneb9c1b512016-09-06 20:57:50 +0000741void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000742 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
743 LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000744
Kate Stoneb9c1b512016-09-06 20:57:50 +0000745 // This thread is currently stopped.
746 thread.SetStoppedByTrace();
747
748 StopRunningThreads(thread.GetID());
749}
750
751void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) {
752 Log *log(
753 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
Pavel Labatha6321a82017-01-19 15:26:04 +0000754 LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000755
756 // Mark the thread as stopped at breakpoint.
757 thread.SetStoppedByBreakpoint();
Pavel Labathaef79082018-10-03 12:29:33 +0000758 FixupBreakpointPCAsNeeded(thread);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000759
760 if (m_threads_stepping_with_breakpoint.find(thread.GetID()) !=
761 m_threads_stepping_with_breakpoint.end())
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000762 thread.SetStoppedByTrace();
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000763
Kate Stoneb9c1b512016-09-06 20:57:50 +0000764 StopRunningThreads(thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000765}
766
Kate Stoneb9c1b512016-09-06 20:57:50 +0000767void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread,
768 uint32_t wp_index) {
769 Log *log(
770 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
Pavel Labatha6321a82017-01-19 15:26:04 +0000771 LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}",
772 thread.GetID(), wp_index);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000773
Adrian Prantl05097242018-04-30 16:49:04 +0000774 // Mark the thread as stopped at watchpoint. The address is at
775 // (lldb::addr_t)info->si_addr if we need it.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000776 thread.SetStoppedByWatchpoint(wp_index);
777
778 // We need to tell all other running threads before we notify the delegate
779 // about this stop.
780 StopRunningThreads(thread.GetID());
781}
782
783void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
784 NativeThreadLinux &thread, bool exited) {
785 const int signo = info.si_signo;
786 const bool is_from_llgs = info.si_pid == getpid();
787
Pavel Labatha6321a82017-01-19 15:26:04 +0000788 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000789
790 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
Adrian Prantl05097242018-04-30 16:49:04 +0000791 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a kill(2)
792 // or raise(3). Similarly for tgkill(2) on Linux.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000793 //
794 // IOW, user generated signals never generate what we consider to be a
795 // "crash".
796 //
797 // Similarly, ACK signals generated by this monitor.
798
799 // Handle the signal.
Pavel Labatha6321a82017-01-19 15:26:04 +0000800 LLDB_LOG(log,
801 "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
802 "waitpid pid = {4})",
803 Host::GetSignalAsCString(signo), signo, info.si_code,
804 thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000805
Kate Stoneb9c1b512016-09-06 20:57:50 +0000806 // Check for thread stop notification.
807 if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) {
808 // This is a tgkill()-based stop.
Pavel Labatha6321a82017-01-19 15:26:04 +0000809 LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000810
Adrian Prantl05097242018-04-30 16:49:04 +0000811 // Check that we're not already marked with a stop reason. Note this thread
812 // really shouldn't already be marked as stopped - if we were, that would
813 // imply that the kernel signaled us with the thread stopping which we
814 // handled and marked as stopped, and that, without an intervening resume,
815 // we received another stop. It is more likely that we are missing the
816 // marking of a run state somewhere if we find that the thread was marked
817 // as stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000818 const StateType thread_state = thread.GetState();
819 if (!StateIsStoppedState(thread_state, false)) {
820 // An inferior thread has stopped because of a SIGSTOP we have sent it.
821 // Generally, these are not important stops and we don't want to report
Pavel Labatha6321a82017-01-19 15:26:04 +0000822 // them as they are just used to stop other threads when one thread (the
823 // one with the *real* stop reason) hits a breakpoint (watchpoint,
Adrian Prantl05097242018-04-30 16:49:04 +0000824 // etc...). However, in the case of an asynchronous Interrupt(), this
825 // *is* the real stop reason, so we leave the signal intact if this is
826 // the thread that was chosen as the triggering thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000827 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
828 if (m_pending_notification_tid == thread.GetID())
829 thread.SetStoppedBySignal(SIGSTOP, &info);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000830 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000831 thread.SetStoppedWithNoReason();
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000832
Kate Stoneb9c1b512016-09-06 20:57:50 +0000833 SetCurrentThreadID(thread.GetID());
834 SignalIfAllThreadsStopped();
835 } else {
836 // We can end up here if stop was initiated by LLGS but by this time a
837 // thread stop has occurred - maybe initiated by another event.
Zachary Turner97206d52017-05-12 04:51:55 +0000838 Status error = ResumeThread(thread, thread.GetState(), 0);
Pavel Labatha6321a82017-01-19 15:26:04 +0000839 if (error.Fail())
840 LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(),
841 error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000842 }
843 } else {
Pavel Labatha6321a82017-01-19 15:26:04 +0000844 LLDB_LOG(log,
845 "pid {0} tid {1}, thread was already marked as a stopped "
846 "state (state={2}), leaving stop signal as is",
Pavel Labath8198db32017-01-24 11:48:25 +0000847 GetID(), thread.GetID(), thread_state);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000848 SignalIfAllThreadsStopped();
Todd Fialaaf245d12014-06-30 21:05:18 +0000849 }
850
Kate Stoneb9c1b512016-09-06 20:57:50 +0000851 // Done handling.
852 return;
853 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000854
Adrian Prantl05097242018-04-30 16:49:04 +0000855 // Check if debugger should stop at this signal or just ignore it and resume
856 // the inferior.
Pavel Labath4a705e72017-02-24 09:29:14 +0000857 if (m_signals_to_ignore.find(signo) != m_signals_to_ignore.end()) {
858 ResumeThread(thread, thread.GetState(), signo);
859 return;
860 }
861
Kate Stoneb9c1b512016-09-06 20:57:50 +0000862 // This thread is stopped.
Pavel Labatha6321a82017-01-19 15:26:04 +0000863 LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000864 thread.SetStoppedBySignal(signo, &info);
865
866 // Send a stop to the debugger after we get all other threads to stop.
867 StopRunningThreads(thread.GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000868}
869
Tamas Berghammere7708682015-04-22 10:00:23 +0000870namespace {
871
Kate Stoneb9c1b512016-09-06 20:57:50 +0000872struct EmulatorBaton {
Pavel Labathd37349f2017-11-10 11:05:49 +0000873 NativeProcessLinux &m_process;
874 NativeRegisterContext &m_reg_context;
Tamas Berghammere7708682015-04-22 10:00:23 +0000875
Kate Stoneb9c1b512016-09-06 20:57:50 +0000876 // eRegisterKindDWARF -> RegsiterValue
877 std::unordered_map<uint32_t, RegisterValue> m_register_values;
Pavel Labath6648fcc2015-04-27 09:21:14 +0000878
Pavel Labathd37349f2017-11-10 11:05:49 +0000879 EmulatorBaton(NativeProcessLinux &process, NativeRegisterContext &reg_context)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000880 : m_process(process), m_reg_context(reg_context) {}
Tamas Berghammere7708682015-04-22 10:00:23 +0000881};
882
883} // anonymous namespace
884
Kate Stoneb9c1b512016-09-06 20:57:50 +0000885static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
886 const EmulateInstruction::Context &context,
887 lldb::addr_t addr, void *dst, size_t length) {
888 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
Tamas Berghammere7708682015-04-22 10:00:23 +0000889
Kate Stoneb9c1b512016-09-06 20:57:50 +0000890 size_t bytes_read;
Pavel Labathd37349f2017-11-10 11:05:49 +0000891 emulator_baton->m_process.ReadMemory(addr, dst, length, bytes_read);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000892 return bytes_read;
Tamas Berghammere7708682015-04-22 10:00:23 +0000893}
894
Kate Stoneb9c1b512016-09-06 20:57:50 +0000895static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
896 const RegisterInfo *reg_info,
897 RegisterValue &reg_value) {
898 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
Tamas Berghammere7708682015-04-22 10:00:23 +0000899
Kate Stoneb9c1b512016-09-06 20:57:50 +0000900 auto it = emulator_baton->m_register_values.find(
901 reg_info->kinds[eRegisterKindDWARF]);
902 if (it != emulator_baton->m_register_values.end()) {
903 reg_value = it->second;
904 return true;
905 }
906
Adrian Prantl05097242018-04-30 16:49:04 +0000907 // The emulator only fill in the dwarf regsiter numbers (and in some case the
908 // generic register numbers). Get the full register info from the register
909 // context based on the dwarf register numbers.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000910 const RegisterInfo *full_reg_info =
Pavel Labathd37349f2017-11-10 11:05:49 +0000911 emulator_baton->m_reg_context.GetRegisterInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000912 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
913
Zachary Turner97206d52017-05-12 04:51:55 +0000914 Status error =
Pavel Labathd37349f2017-11-10 11:05:49 +0000915 emulator_baton->m_reg_context.ReadRegister(full_reg_info, reg_value);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000916 if (error.Success())
917 return true;
918
919 return false;
920}
921
922static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
923 const EmulateInstruction::Context &context,
924 const RegisterInfo *reg_info,
925 const RegisterValue &reg_value) {
926 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
927 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
928 reg_value;
929 return true;
930}
931
932static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
933 const EmulateInstruction::Context &context,
934 lldb::addr_t addr, const void *dst,
935 size_t length) {
936 return length;
937}
938
Pavel Labathd37349f2017-11-10 11:05:49 +0000939static lldb::addr_t ReadFlags(NativeRegisterContext &regsiter_context) {
940 const RegisterInfo *flags_info = regsiter_context.GetRegisterInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000941 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
Pavel Labathd37349f2017-11-10 11:05:49 +0000942 return regsiter_context.ReadRegisterAsUnsigned(flags_info,
943 LLDB_INVALID_ADDRESS);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000944}
945
Zachary Turner97206d52017-05-12 04:51:55 +0000946Status
947NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadLinux &thread) {
948 Status error;
Pavel Labathd37349f2017-11-10 11:05:49 +0000949 NativeRegisterContext& register_context = thread.GetRegisterContext();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000950
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000951 std::unique_ptr<EmulateInstruction> emulator_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000952 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying,
953 nullptr));
954
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000955 if (emulator_up == nullptr)
Zachary Turner97206d52017-05-12 04:51:55 +0000956 return Status("Instruction emulator not found!");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000957
Pavel Labathd37349f2017-11-10 11:05:49 +0000958 EmulatorBaton baton(*this, register_context);
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000959 emulator_up->SetBaton(&baton);
960 emulator_up->SetReadMemCallback(&ReadMemoryCallback);
961 emulator_up->SetReadRegCallback(&ReadRegisterCallback);
962 emulator_up->SetWriteMemCallback(&WriteMemoryCallback);
963 emulator_up->SetWriteRegCallback(&WriteRegisterCallback);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000964
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000965 if (!emulator_up->ReadInstruction())
Zachary Turner97206d52017-05-12 04:51:55 +0000966 return Status("Read instruction failed!");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000967
968 bool emulation_result =
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000969 emulator_up->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000970
Pavel Labathd37349f2017-11-10 11:05:49 +0000971 const RegisterInfo *reg_info_pc = register_context.GetRegisterInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000972 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
Pavel Labathd37349f2017-11-10 11:05:49 +0000973 const RegisterInfo *reg_info_flags = register_context.GetRegisterInfo(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000974 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
975
976 auto pc_it =
977 baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
978 auto flags_it =
979 baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
980
981 lldb::addr_t next_pc;
982 lldb::addr_t next_flags;
983 if (emulation_result) {
984 assert(pc_it != baton.m_register_values.end() &&
985 "Emulation was successfull but PC wasn't updated");
986 next_pc = pc_it->second.GetAsUInt64();
987
988 if (flags_it != baton.m_register_values.end())
989 next_flags = flags_it->second.GetAsUInt64();
990 else
Pavel Labathd37349f2017-11-10 11:05:49 +0000991 next_flags = ReadFlags(register_context);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000992 } else if (pc_it == baton.m_register_values.end()) {
Adrian Prantl05097242018-04-30 16:49:04 +0000993 // Emulate instruction failed and it haven't changed PC. Advance PC with
994 // the size of the current opcode because the emulation of all
Kate Stoneb9c1b512016-09-06 20:57:50 +0000995 // PC modifying instruction should be successful. The failure most
996 // likely caused by a not supported instruction which don't modify PC.
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000997 next_pc = register_context.GetPC() + emulator_up->GetOpcode().GetByteSize();
Pavel Labathd37349f2017-11-10 11:05:49 +0000998 next_flags = ReadFlags(register_context);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000999 } else {
1000 // The instruction emulation failed after it modified the PC. It is an
1001 // unknown error where we can't continue because the next instruction is
1002 // modifying the PC but we don't know how.
Zachary Turner97206d52017-05-12 04:51:55 +00001003 return Status("Instruction emulation failed unexpectedly.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001004 }
1005
1006 if (m_arch.GetMachine() == llvm::Triple::arm) {
1007 if (next_flags & 0x20) {
1008 // Thumb mode
1009 error = SetSoftwareBreakpoint(next_pc, 2);
1010 } else {
1011 // Arm mode
1012 error = SetSoftwareBreakpoint(next_pc, 4);
Pavel Labath6648fcc2015-04-27 09:21:14 +00001013 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001014 } else if (m_arch.GetMachine() == llvm::Triple::mips64 ||
1015 m_arch.GetMachine() == llvm::Triple::mips64el ||
1016 m_arch.GetMachine() == llvm::Triple::mips ||
Eugene Zemtsovaae0a752017-10-05 19:44:05 +00001017 m_arch.GetMachine() == llvm::Triple::mipsel ||
1018 m_arch.GetMachine() == llvm::Triple::ppc64le)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001019 error = SetSoftwareBreakpoint(next_pc, 4);
1020 else {
1021 // No size hint is given for the next breakpoint
1022 error = SetSoftwareBreakpoint(next_pc, 0);
1023 }
Pavel Labath6648fcc2015-04-27 09:21:14 +00001024
Adrian Prantl05097242018-04-30 16:49:04 +00001025 // If setting the breakpoint fails because next_pc is out of the address
1026 // space, ignore it and let the debugee segfault.
Pavel Labath42eb6902016-10-26 11:13:56 +00001027 if (error.GetError() == EIO || error.GetError() == EFAULT) {
Zachary Turner97206d52017-05-12 04:51:55 +00001028 return Status();
Pavel Labath42eb6902016-10-26 11:13:56 +00001029 } else if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001030 return error;
Tamas Berghammere7708682015-04-22 10:00:23 +00001031
Kate Stoneb9c1b512016-09-06 20:57:50 +00001032 m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001033
Zachary Turner97206d52017-05-12 04:51:55 +00001034 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001035}
1036
1037bool NativeProcessLinux::SupportHardwareSingleStepping() const {
1038 if (m_arch.GetMachine() == llvm::Triple::arm ||
1039 m_arch.GetMachine() == llvm::Triple::mips64 ||
1040 m_arch.GetMachine() == llvm::Triple::mips64el ||
1041 m_arch.GetMachine() == llvm::Triple::mips ||
1042 m_arch.GetMachine() == llvm::Triple::mipsel)
Pavel Labath6648fcc2015-04-27 09:21:14 +00001043 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001044 return true;
Tamas Berghammere7708682015-04-22 10:00:23 +00001045}
1046
Zachary Turner97206d52017-05-12 04:51:55 +00001047Status NativeProcessLinux::Resume(const ResumeActionList &resume_actions) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001048 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1049 LLDB_LOG(log, "pid {0}", GetID());
Tamas Berghammere7708682015-04-22 10:00:23 +00001050
Kate Stoneb9c1b512016-09-06 20:57:50 +00001051 bool software_single_step = !SupportHardwareSingleStepping();
Tamas Berghammere7708682015-04-22 10:00:23 +00001052
Kate Stoneb9c1b512016-09-06 20:57:50 +00001053 if (software_single_step) {
Pavel Labatha5be48b2017-10-17 15:52:16 +00001054 for (const auto &thread : m_threads) {
1055 assert(thread && "thread list should not contain NULL threads");
Tamas Berghammere7708682015-04-22 10:00:23 +00001056
Kate Stoneb9c1b512016-09-06 20:57:50 +00001057 const ResumeAction *const action =
Pavel Labatha5be48b2017-10-17 15:52:16 +00001058 resume_actions.GetActionForThread(thread->GetID(), true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001059 if (action == nullptr)
1060 continue;
Tamas Berghammere7708682015-04-22 10:00:23 +00001061
Kate Stoneb9c1b512016-09-06 20:57:50 +00001062 if (action->state == eStateStepping) {
Zachary Turner97206d52017-05-12 04:51:55 +00001063 Status error = SetupSoftwareSingleStepping(
Pavel Labatha5be48b2017-10-17 15:52:16 +00001064 static_cast<NativeThreadLinux &>(*thread));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001065 if (error.Fail())
1066 return error;
1067 }
Tamas Berghammere7708682015-04-22 10:00:23 +00001068 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001069 }
1070
Pavel Labatha5be48b2017-10-17 15:52:16 +00001071 for (const auto &thread : m_threads) {
1072 assert(thread && "thread list should not contain NULL threads");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001073
1074 const ResumeAction *const action =
Pavel Labatha5be48b2017-10-17 15:52:16 +00001075 resume_actions.GetActionForThread(thread->GetID(), true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001076
1077 if (action == nullptr) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001078 LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
Pavel Labatha5be48b2017-10-17 15:52:16 +00001079 thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001080 continue;
Tamas Berghammere7708682015-04-22 10:00:23 +00001081 }
1082
Pavel Labatha6321a82017-01-19 15:26:04 +00001083 LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}",
Pavel Labatha5be48b2017-10-17 15:52:16 +00001084 action->state, GetID(), thread->GetID());
Tamas Berghammere7708682015-04-22 10:00:23 +00001085
Kate Stoneb9c1b512016-09-06 20:57:50 +00001086 switch (action->state) {
1087 case eStateRunning:
1088 case eStateStepping: {
1089 // Run the thread, possibly feeding it the signal.
1090 const int signo = action->signal;
Pavel Labatha5be48b2017-10-17 15:52:16 +00001091 ResumeThread(static_cast<NativeThreadLinux &>(*thread), action->state,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001092 signo);
1093 break;
1094 }
Tamas Berghammere7708682015-04-22 10:00:23 +00001095
Kate Stoneb9c1b512016-09-06 20:57:50 +00001096 case eStateSuspended:
1097 case eStateStopped:
Pavel Labatha6321a82017-01-19 15:26:04 +00001098 llvm_unreachable("Unexpected state");
Tamas Berghammere7708682015-04-22 10:00:23 +00001099
Kate Stoneb9c1b512016-09-06 20:57:50 +00001100 default:
Zachary Turner97206d52017-05-12 04:51:55 +00001101 return Status("NativeProcessLinux::%s (): unexpected state %s specified "
1102 "for pid %" PRIu64 ", tid %" PRIu64,
1103 __FUNCTION__, StateAsCString(action->state), GetID(),
Pavel Labatha5be48b2017-10-17 15:52:16 +00001104 thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001105 }
1106 }
1107
Zachary Turner97206d52017-05-12 04:51:55 +00001108 return Status();
Tamas Berghammere7708682015-04-22 10:00:23 +00001109}
1110
Zachary Turner97206d52017-05-12 04:51:55 +00001111Status NativeProcessLinux::Halt() {
1112 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001113
1114 if (kill(GetID(), SIGSTOP) != 0)
1115 error.SetErrorToErrno();
1116
1117 return error;
Tamas Berghammere7708682015-04-22 10:00:23 +00001118}
1119
Zachary Turner97206d52017-05-12 04:51:55 +00001120Status NativeProcessLinux::Detach() {
1121 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001122
1123 // Stop monitoring the inferior.
1124 m_sigchld_handle.reset();
1125
1126 // Tell ptrace to detach from the process.
1127 if (GetID() == LLDB_INVALID_PROCESS_ID)
1128 return error;
1129
Pavel Labatha5be48b2017-10-17 15:52:16 +00001130 for (const auto &thread : m_threads) {
1131 Status e = Detach(thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001132 if (e.Fail())
1133 error =
1134 e; // Save the error, but still attempt to detach from other threads.
1135 }
1136
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001137 m_processor_trace_monitor.clear();
1138 m_pt_proces_trace_id = LLDB_INVALID_UID;
1139
Kate Stoneb9c1b512016-09-06 20:57:50 +00001140 return error;
1141}
1142
Zachary Turner97206d52017-05-12 04:51:55 +00001143Status NativeProcessLinux::Signal(int signo) {
1144 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001145
Pavel Labatha6321a82017-01-19 15:26:04 +00001146 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1147 LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo,
1148 Host::GetSignalAsCString(signo), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001149
1150 if (kill(GetID(), signo))
1151 error.SetErrorToErrno();
1152
1153 return error;
1154}
1155
Zachary Turner97206d52017-05-12 04:51:55 +00001156Status NativeProcessLinux::Interrupt() {
Adrian Prantl05097242018-04-30 16:49:04 +00001157 // Pick a running thread (or if none, a not-dead stopped thread) as the
1158 // chosen thread that will be the stop-reason thread.
Pavel Labatha6321a82017-01-19 15:26:04 +00001159 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001160
Pavel Labatha5be48b2017-10-17 15:52:16 +00001161 NativeThreadProtocol *running_thread = nullptr;
1162 NativeThreadProtocol *stopped_thread = nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001163
Pavel Labatha6321a82017-01-19 15:26:04 +00001164 LLDB_LOG(log, "selecting running thread for interrupt target");
Pavel Labatha5be48b2017-10-17 15:52:16 +00001165 for (const auto &thread : m_threads) {
Adrian Prantl05097242018-04-30 16:49:04 +00001166 // If we have a running or stepping thread, we'll call that the target of
1167 // the interrupt.
Pavel Labatha5be48b2017-10-17 15:52:16 +00001168 const auto thread_state = thread->GetState();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001169 if (thread_state == eStateRunning || thread_state == eStateStepping) {
Pavel Labatha5be48b2017-10-17 15:52:16 +00001170 running_thread = thread.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001171 break;
Pavel Labatha5be48b2017-10-17 15:52:16 +00001172 } else if (!stopped_thread && StateIsStoppedState(thread_state, true)) {
Adrian Prantl05097242018-04-30 16:49:04 +00001173 // Remember the first non-dead stopped thread. We'll use that as a
1174 // backup if there are no running threads.
Pavel Labatha5be48b2017-10-17 15:52:16 +00001175 stopped_thread = thread.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001176 }
1177 }
1178
Pavel Labatha5be48b2017-10-17 15:52:16 +00001179 if (!running_thread && !stopped_thread) {
Zachary Turner97206d52017-05-12 04:51:55 +00001180 Status error("found no running/stepping or live stopped threads as target "
1181 "for interrupt");
Pavel Labatha6321a82017-01-19 15:26:04 +00001182 LLDB_LOG(log, "skipping due to error: {0}", error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001183
1184 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001185 }
1186
Pavel Labatha5be48b2017-10-17 15:52:16 +00001187 NativeThreadProtocol *deferred_signal_thread =
1188 running_thread ? running_thread : stopped_thread;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001189
Pavel Labatha6321a82017-01-19 15:26:04 +00001190 LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(),
Pavel Labatha5be48b2017-10-17 15:52:16 +00001191 running_thread ? "running" : "stopped",
1192 deferred_signal_thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001193
Pavel Labatha5be48b2017-10-17 15:52:16 +00001194 StopRunningThreads(deferred_signal_thread->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001195
Zachary Turner97206d52017-05-12 04:51:55 +00001196 return Status();
Todd Fialaaf245d12014-06-30 21:05:18 +00001197}
1198
Zachary Turner97206d52017-05-12 04:51:55 +00001199Status NativeProcessLinux::Kill() {
Pavel Labatha6321a82017-01-19 15:26:04 +00001200 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1201 LLDB_LOG(log, "pid {0}", GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +00001202
Zachary Turner97206d52017-05-12 04:51:55 +00001203 Status error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001204
Kate Stoneb9c1b512016-09-06 20:57:50 +00001205 switch (m_state) {
1206 case StateType::eStateInvalid:
1207 case StateType::eStateExited:
1208 case StateType::eStateCrashed:
1209 case StateType::eStateDetached:
1210 case StateType::eStateUnloaded:
1211 // Nothing to do - the process is already dead.
Pavel Labatha6321a82017-01-19 15:26:04 +00001212 LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
Pavel Labath8198db32017-01-24 11:48:25 +00001213 m_state);
Todd Fialaaf245d12014-06-30 21:05:18 +00001214 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001215
Kate Stoneb9c1b512016-09-06 20:57:50 +00001216 case StateType::eStateConnected:
1217 case StateType::eStateAttaching:
1218 case StateType::eStateLaunching:
1219 case StateType::eStateStopped:
1220 case StateType::eStateRunning:
1221 case StateType::eStateStepping:
1222 case StateType::eStateSuspended:
1223 // We can try to kill a process in these states.
1224 break;
1225 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001226
Kate Stoneb9c1b512016-09-06 20:57:50 +00001227 if (kill(GetID(), SIGKILL) != 0) {
1228 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +00001229 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001230 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001231
Kate Stoneb9c1b512016-09-06 20:57:50 +00001232 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001233}
1234
Zachary Turner97206d52017-05-12 04:51:55 +00001235Status NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr,
1236 MemoryRegionInfo &range_info) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001237 // FIXME review that the final memory region returned extends to the end of
1238 // the virtual address space,
1239 // with no perms if it is not mapped.
Todd Fialaaf245d12014-06-30 21:05:18 +00001240
Adrian Prantl05097242018-04-30 16:49:04 +00001241 // Use an approach that reads memory regions from /proc/{pid}/maps. Assume
1242 // proc maps entries are in ascending order.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001243 // FIXME assert if we find differently.
Todd Fialaaf245d12014-06-30 21:05:18 +00001244
Kate Stoneb9c1b512016-09-06 20:57:50 +00001245 if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
1246 // We're done.
Zachary Turner97206d52017-05-12 04:51:55 +00001247 return Status("unsupported");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001248 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001249
Zachary Turner97206d52017-05-12 04:51:55 +00001250 Status error = PopulateMemoryRegionCache();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001251 if (error.Fail()) {
1252 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001253 }
1254
1255 lldb::addr_t prev_base_address = 0;
1256
1257 // FIXME start by finding the last region that is <= target address using
1258 // binary search. Data is sorted.
1259 // There can be a ton of regions on pthreads apps with lots of threads.
1260 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1261 ++it) {
Tamas Berghammera6f57952017-01-03 16:29:43 +00001262 MemoryRegionInfo &proc_entry_info = it->first;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001263
1264 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1265 assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
1266 "descending /proc/pid/maps entries detected, unexpected");
1267 prev_base_address = proc_entry_info.GetRange().GetRangeBase();
Hafiz Abid Qadeerb1554312017-01-20 10:24:03 +00001268 UNUSED_IF_ASSERT_DISABLED(prev_base_address);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001269
1270 // If the target address comes before this entry, indicate distance to next
1271 // region.
1272 if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1273 range_info.GetRange().SetRangeBase(load_addr);
1274 range_info.GetRange().SetByteSize(
1275 proc_entry_info.GetRange().GetRangeBase() - load_addr);
1276 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1277 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1278 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1279 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1280
1281 return error;
1282 } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1283 // The target address is within the memory region we're processing here.
1284 range_info = proc_entry_info;
1285 return error;
1286 }
1287
1288 // The target memory address comes somewhere after the region we just
1289 // parsed.
1290 }
1291
1292 // If we made it here, we didn't find an entry that contained the given
Adrian Prantl05097242018-04-30 16:49:04 +00001293 // address. Return the load_addr as start and the amount of bytes betwwen
1294 // load address and the end of the memory as size.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001295 range_info.GetRange().SetRangeBase(load_addr);
1296 range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
1297 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1298 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1299 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1300 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1301 return error;
1302}
1303
Zachary Turner97206d52017-05-12 04:51:55 +00001304Status NativeProcessLinux::PopulateMemoryRegionCache() {
Pavel Labatha6321a82017-01-19 15:26:04 +00001305 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Tamas Berghammera6f57952017-01-03 16:29:43 +00001306
1307 // If our cache is empty, pull the latest. There should always be at least
1308 // one memory region if memory region handling is supported.
1309 if (!m_mem_region_cache.empty()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001310 LLDB_LOG(log, "reusing {0} cached memory region entries",
1311 m_mem_region_cache.size());
Zachary Turner97206d52017-05-12 04:51:55 +00001312 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001313 }
1314
Pavel Labath15930862017-03-21 13:49:45 +00001315 auto BufferOrError = getProcFile(GetID(), "maps");
1316 if (!BufferOrError) {
Tamas Berghammera6f57952017-01-03 16:29:43 +00001317 m_supports_mem_region = LazyBool::eLazyBoolNo;
Pavel Labath15930862017-03-21 13:49:45 +00001318 return BufferOrError.getError();
1319 }
Pavel Labathc8e364e82018-12-15 13:38:16 +00001320 Status Result;
1321 ParseLinuxMapRegions(BufferOrError.get()->getBuffer(),
1322 [&](const MemoryRegionInfo &Info, const Status &ST) {
1323 if (ST.Success()) {
1324 FileSpec file_spec(Info.GetName().GetCString());
1325 FileSystem::Instance().Resolve(file_spec);
1326 m_mem_region_cache.emplace_back(Info, file_spec);
1327 return true;
1328 } else {
1329 m_supports_mem_region = LazyBool::eLazyBoolNo;
1330 LLDB_LOG(log, "failed to parse proc maps: {0}", ST);
1331 Result = ST;
1332 return false;
1333 }
1334 });
1335 if (Result.Fail())
1336 return Result;
Pavel Labath15930862017-03-21 13:49:45 +00001337
1338 if (m_mem_region_cache.empty()) {
Tamas Berghammera6f57952017-01-03 16:29:43 +00001339 // No entries after attempting to read them. This shouldn't happen if
Adrian Prantl05097242018-04-30 16:49:04 +00001340 // /proc/{pid}/maps is supported. Assume we don't support map entries via
1341 // procfs.
Pavel Labath15930862017-03-21 13:49:45 +00001342 m_supports_mem_region = LazyBool::eLazyBoolNo;
Pavel Labatha6321a82017-01-19 15:26:04 +00001343 LLDB_LOG(log,
1344 "failed to find any procfs maps entries, assuming no support "
1345 "for memory region metadata retrieval");
Zachary Turner97206d52017-05-12 04:51:55 +00001346 return Status("not supported");
Tamas Berghammera6f57952017-01-03 16:29:43 +00001347 }
1348
Pavel Labatha6321a82017-01-19 15:26:04 +00001349 LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps",
1350 m_mem_region_cache.size(), GetID());
Tamas Berghammera6f57952017-01-03 16:29:43 +00001351
1352 // We support memory retrieval, remember that.
1353 m_supports_mem_region = LazyBool::eLazyBoolYes;
Zachary Turner97206d52017-05-12 04:51:55 +00001354 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001355}
1356
Kate Stoneb9c1b512016-09-06 20:57:50 +00001357void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001358 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1359 LLDB_LOG(log, "newBumpId={0}", newBumpId);
1360 LLDB_LOG(log, "clearing {0} entries from memory region cache",
1361 m_mem_region_cache.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001362 m_mem_region_cache.clear();
1363}
1364
Zachary Turner97206d52017-05-12 04:51:55 +00001365Status NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions,
1366 lldb::addr_t &addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001367// FIXME implementing this requires the equivalent of
Adrian Prantl05097242018-04-30 16:49:04 +00001368// InferiorCallPOSIX::InferiorCallMmap, which depends on functional ThreadPlans
1369// working with Native*Protocol.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001370#if 1
Zachary Turner97206d52017-05-12 04:51:55 +00001371 return Status("not implemented yet");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001372#else
1373 addr = LLDB_INVALID_ADDRESS;
1374
1375 unsigned prot = 0;
1376 if (permissions & lldb::ePermissionsReadable)
1377 prot |= eMmapProtRead;
1378 if (permissions & lldb::ePermissionsWritable)
1379 prot |= eMmapProtWrite;
1380 if (permissions & lldb::ePermissionsExecutable)
1381 prot |= eMmapProtExec;
1382
1383 // TODO implement this directly in NativeProcessLinux
Adrian Prantl05097242018-04-30 16:49:04 +00001384 // (and lift to NativeProcessPOSIX if/when that class is refactored out).
Kate Stoneb9c1b512016-09-06 20:57:50 +00001385 if (InferiorCallMmap(this, addr, 0, size, prot,
1386 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
1387 m_addr_to_mmap_size[addr] = size;
Zachary Turner97206d52017-05-12 04:51:55 +00001388 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001389 } else {
1390 addr = LLDB_INVALID_ADDRESS;
Zachary Turner97206d52017-05-12 04:51:55 +00001391 return Status("unable to allocate %" PRIu64
1392 " bytes of memory with permissions %s",
1393 size, GetPermissionsAsCString(permissions));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001394 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001395#endif
1396}
1397
Zachary Turner97206d52017-05-12 04:51:55 +00001398Status NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001399 // FIXME see comments in AllocateMemory - required lower-level
1400 // bits not in place yet (ThreadPlans)
Zachary Turner97206d52017-05-12 04:51:55 +00001401 return Status("not implemented");
Todd Fialaaf245d12014-06-30 21:05:18 +00001402}
1403
Kate Stoneb9c1b512016-09-06 20:57:50 +00001404lldb::addr_t NativeProcessLinux::GetSharedLibraryInfoAddress() {
1405 // punt on this for now
1406 return LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00001407}
1408
Kate Stoneb9c1b512016-09-06 20:57:50 +00001409size_t NativeProcessLinux::UpdateThreads() {
Adrian Prantl05097242018-04-30 16:49:04 +00001410 // The NativeProcessLinux monitoring threads are always up to date with
1411 // respect to thread state and they keep the thread list populated properly.
1412 // All this method needs to do is return the thread count.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001413 return m_threads.size();
Todd Fialaaf245d12014-06-30 21:05:18 +00001414}
1415
Zachary Turner97206d52017-05-12 04:51:55 +00001416Status NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,
1417 bool hardware) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001418 if (hardware)
Omair Javaidd5ffbad2017-02-24 13:27:31 +00001419 return SetHardwareBreakpoint(addr, size);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001420 else
1421 return SetSoftwareBreakpoint(addr, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00001422}
1423
Zachary Turner97206d52017-05-12 04:51:55 +00001424Status NativeProcessLinux::RemoveBreakpoint(lldb::addr_t addr, bool hardware) {
Omair Javaidd5ffbad2017-02-24 13:27:31 +00001425 if (hardware)
1426 return RemoveHardwareBreakpoint(addr);
1427 else
1428 return NativeProcessProtocol::RemoveBreakpoint(addr);
1429}
1430
Pavel Labathf8b825f2018-09-09 06:01:12 +00001431llvm::Expected<llvm::ArrayRef<uint8_t>>
1432NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(size_t size_hint) {
Pavel Labath12286a22018-09-08 10:33:14 +00001433 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1434 // linux kernel does otherwise.
Pavel Labathf8b825f2018-09-09 06:01:12 +00001435 static const uint8_t g_arm_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1436 static const uint8_t g_thumb_opcode[] = {0x01, 0xde};
Todd Fialaaf245d12014-06-30 21:05:18 +00001437
Pavel Labathf8b825f2018-09-09 06:01:12 +00001438 switch (GetArchitecture().GetMachine()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001439 case llvm::Triple::arm:
Pavel Labathf8b825f2018-09-09 06:01:12 +00001440 switch (size_hint) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001441 case 2:
Pavel Labath4f545072018-09-09 08:42:00 +00001442 return llvm::makeArrayRef(g_thumb_opcode);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001443 case 4:
Pavel Labath4f545072018-09-09 08:42:00 +00001444 return llvm::makeArrayRef(g_arm_opcode);
Todd Fialaaf245d12014-06-30 21:05:18 +00001445 default:
Pavel Labathf8b825f2018-09-09 06:01:12 +00001446 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1447 "Unrecognised trap opcode size hint!");
Todd Fialaaf245d12014-06-30 21:05:18 +00001448 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001449 default:
Pavel Labathf8b825f2018-09-09 06:01:12 +00001450 return NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_hint);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001451 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001452}
1453
Zachary Turner97206d52017-05-12 04:51:55 +00001454Status NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
1455 size_t &bytes_read) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001456 if (ProcessVmReadvSupported()) {
1457 // The process_vm_readv path is about 50 times faster than ptrace api. We
Adrian Prantl05097242018-04-30 16:49:04 +00001458 // want to use this syscall if it is supported.
Pavel Labathdf7c6992015-06-17 18:38:49 +00001459
Kate Stoneb9c1b512016-09-06 20:57:50 +00001460 const ::pid_t pid = GetID();
Pavel Labathdf7c6992015-06-17 18:38:49 +00001461
Kate Stoneb9c1b512016-09-06 20:57:50 +00001462 struct iovec local_iov, remote_iov;
1463 local_iov.iov_base = buf;
1464 local_iov.iov_len = size;
1465 remote_iov.iov_base = reinterpret_cast<void *>(addr);
1466 remote_iov.iov_len = size;
Pavel Labathdf7c6992015-06-17 18:38:49 +00001467
Kate Stoneb9c1b512016-09-06 20:57:50 +00001468 bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
1469 const bool success = bytes_read == size;
Pavel Labathdf7c6992015-06-17 18:38:49 +00001470
Pavel Labatha6321a82017-01-19 15:26:04 +00001471 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1472 LLDB_LOG(log,
1473 "using process_vm_readv to read {0} bytes from inferior "
1474 "address {1:x}: {2}",
Pavel Labath10c41f32017-06-06 14:06:17 +00001475 size, addr, success ? "Success" : llvm::sys::StrError(errno));
Pavel Labath19cbe962015-07-21 13:20:32 +00001476
Kate Stoneb9c1b512016-09-06 20:57:50 +00001477 if (success)
Zachary Turner97206d52017-05-12 04:51:55 +00001478 return Status();
Pavel Labatha6321a82017-01-19 15:26:04 +00001479 // else the call failed for some reason, let's retry the read using ptrace
1480 // api.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001481 }
Pavel Labath19cbe962015-07-21 13:20:32 +00001482
Kate Stoneb9c1b512016-09-06 20:57:50 +00001483 unsigned char *dst = static_cast<unsigned char *>(buf);
1484 size_t remainder;
1485 long data;
Pavel Labath19cbe962015-07-21 13:20:32 +00001486
Pavel Labatha6321a82017-01-19 15:26:04 +00001487 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1488 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
Pavel Labath19cbe962015-07-21 13:20:32 +00001489
Kate Stoneb9c1b512016-09-06 20:57:50 +00001490 for (bytes_read = 0; bytes_read < size; bytes_read += remainder) {
Zachary Turner97206d52017-05-12 04:51:55 +00001491 Status error = NativeProcessLinux::PtraceWrapper(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001492 PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data);
Pavel Labatha6321a82017-01-19 15:26:04 +00001493 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001494 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001495
1496 remainder = size - bytes_read;
1497 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
1498
1499 // Copy the data into our buffer
1500 memcpy(dst, &data, remainder);
1501
Pavel Labatha6321a82017-01-19 15:26:04 +00001502 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001503 addr += k_ptrace_word_size;
1504 dst += k_ptrace_word_size;
1505 }
Zachary Turner97206d52017-05-12 04:51:55 +00001506 return Status();
Todd Fialaaf245d12014-06-30 21:05:18 +00001507}
1508
Zachary Turner97206d52017-05-12 04:51:55 +00001509Status NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,
1510 size_t size, size_t &bytes_written) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001511 const unsigned char *src = static_cast<const unsigned char *>(buf);
1512 size_t remainder;
Zachary Turner97206d52017-05-12 04:51:55 +00001513 Status error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001514
Pavel Labatha6321a82017-01-19 15:26:04 +00001515 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1516 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00001517
Kate Stoneb9c1b512016-09-06 20:57:50 +00001518 for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
1519 remainder = size - bytes_written;
1520 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
Chaoren Lin97ccc292015-02-03 01:51:12 +00001521
Kate Stoneb9c1b512016-09-06 20:57:50 +00001522 if (remainder == k_ptrace_word_size) {
1523 unsigned long data = 0;
1524 memcpy(&data, src, k_ptrace_word_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00001525
Pavel Labatha6321a82017-01-19 15:26:04 +00001526 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001527 error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(),
1528 (void *)addr, (void *)data);
Pavel Labatha6321a82017-01-19 15:26:04 +00001529 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001530 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001531 } else {
1532 unsigned char buff[8];
1533 size_t bytes_read;
1534 error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
Pavel Labatha6321a82017-01-19 15:26:04 +00001535 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001536 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001537
1538 memcpy(buff, src, remainder);
1539
1540 size_t bytes_written_rec;
1541 error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
Pavel Labatha6321a82017-01-19 15:26:04 +00001542 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001543 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001544
Pavel Labatha6321a82017-01-19 15:26:04 +00001545 LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src,
1546 *(unsigned long *)buff);
Todd Fialaaf245d12014-06-30 21:05:18 +00001547 }
1548
Kate Stoneb9c1b512016-09-06 20:57:50 +00001549 addr += k_ptrace_word_size;
1550 src += k_ptrace_word_size;
1551 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001552 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001553}
1554
Zachary Turner97206d52017-05-12 04:51:55 +00001555Status NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001556 return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
1557}
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001558
Zachary Turner97206d52017-05-12 04:51:55 +00001559Status NativeProcessLinux::GetEventMessage(lldb::tid_t tid,
1560 unsigned long *message) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001561 return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
1562}
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001563
Zachary Turner97206d52017-05-12 04:51:55 +00001564Status NativeProcessLinux::Detach(lldb::tid_t tid) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001565 if (tid == LLDB_INVALID_THREAD_ID)
Zachary Turner97206d52017-05-12 04:51:55 +00001566 return Status();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001567
Kate Stoneb9c1b512016-09-06 20:57:50 +00001568 return PtraceWrapper(PTRACE_DETACH, tid);
1569}
1570
1571bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {
Pavel Labatha5be48b2017-10-17 15:52:16 +00001572 for (const auto &thread : m_threads) {
1573 assert(thread && "thread list should not contain NULL threads");
1574 if (thread->GetID() == thread_id) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001575 // We have this thread.
1576 return true;
Todd Fialaaf245d12014-06-30 21:05:18 +00001577 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001578 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001579
Kate Stoneb9c1b512016-09-06 20:57:50 +00001580 // We don't have this thread.
1581 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00001582}
1583
Kate Stoneb9c1b512016-09-06 20:57:50 +00001584bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001585 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1586 LLDB_LOG(log, "tid: {0})", thread_id);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001587
1588 bool found = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001589 for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
1590 if (*it && ((*it)->GetID() == thread_id)) {
1591 m_threads.erase(it);
1592 found = true;
1593 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00001594 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001595 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001596
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001597 if (found)
1598 StopTracingForThread(thread_id);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001599 SignalIfAllThreadsStopped();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001600 return found;
Todd Fialaaf245d12014-06-30 21:05:18 +00001601}
1602
Pavel Labatha5be48b2017-10-17 15:52:16 +00001603NativeThreadLinux &NativeProcessLinux::AddThread(lldb::tid_t thread_id) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001604 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
1605 LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
Todd Fialaaf245d12014-06-30 21:05:18 +00001606
Kate Stoneb9c1b512016-09-06 20:57:50 +00001607 assert(!HasThreadNoLock(thread_id) &&
1608 "attempted to add a thread by id that already exists");
Todd Fialaaf245d12014-06-30 21:05:18 +00001609
Kate Stoneb9c1b512016-09-06 20:57:50 +00001610 // If this is the first thread, save it as the current thread
1611 if (m_threads.empty())
1612 SetCurrentThreadID(thread_id);
Todd Fialaaf245d12014-06-30 21:05:18 +00001613
Pavel Labatha5be48b2017-10-17 15:52:16 +00001614 m_threads.push_back(llvm::make_unique<NativeThreadLinux>(*this, thread_id));
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001615
1616 if (m_pt_proces_trace_id != LLDB_INVALID_UID) {
1617 auto traceMonitor = ProcessorTraceMonitor::Create(
1618 GetID(), thread_id, m_pt_process_trace_config, true);
1619 if (traceMonitor) {
1620 m_pt_traced_thread_group.insert(thread_id);
1621 m_processor_trace_monitor.insert(
1622 std::make_pair(thread_id, std::move(*traceMonitor)));
1623 } else {
1624 LLDB_LOG(log, "failed to start trace on thread {0}", thread_id);
1625 Status error(traceMonitor.takeError());
1626 LLDB_LOG(log, "error {0}", error);
1627 }
1628 }
1629
Pavel Labatha5be48b2017-10-17 15:52:16 +00001630 return static_cast<NativeThreadLinux &>(*m_threads.back());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001631}
Todd Fialaaf245d12014-06-30 21:05:18 +00001632
Zachary Turner97206d52017-05-12 04:51:55 +00001633Status NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,
1634 FileSpec &file_spec) {
1635 Status error = PopulateMemoryRegionCache();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001636 if (error.Fail())
1637 return error;
1638
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00001639 FileSpec module_file_spec(module_path);
1640 FileSystem::Instance().Resolve(module_file_spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001641
Kate Stoneb9c1b512016-09-06 20:57:50 +00001642 file_spec.Clear();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001643 for (const auto &it : m_mem_region_cache) {
1644 if (it.second.GetFilename() == module_file_spec.GetFilename()) {
1645 file_spec = it.second;
Zachary Turner97206d52017-05-12 04:51:55 +00001646 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001647 }
1648 }
Zachary Turner97206d52017-05-12 04:51:55 +00001649 return Status("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
1650 module_file_spec.GetFilename().AsCString(), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001651}
1652
Zachary Turner97206d52017-05-12 04:51:55 +00001653Status NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
1654 lldb::addr_t &load_addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001655 load_addr = LLDB_INVALID_ADDRESS;
Zachary Turner97206d52017-05-12 04:51:55 +00001656 Status error = PopulateMemoryRegionCache();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001657 if (error.Fail())
1658 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001659
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00001660 FileSpec file(file_name);
Tamas Berghammera6f57952017-01-03 16:29:43 +00001661 for (const auto &it : m_mem_region_cache) {
1662 if (it.second == file) {
1663 load_addr = it.first.GetRange().GetRangeBase();
Zachary Turner97206d52017-05-12 04:51:55 +00001664 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001665 }
1666 }
Zachary Turner97206d52017-05-12 04:51:55 +00001667 return Status("No load address found for specified file.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001668}
1669
Pavel Labatha5be48b2017-10-17 15:52:16 +00001670NativeThreadLinux *NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {
1671 return static_cast<NativeThreadLinux *>(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001672 NativeProcessProtocol::GetThreadByID(tid));
1673}
1674
Zachary Turner97206d52017-05-12 04:51:55 +00001675Status NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,
1676 lldb::StateType state, int signo) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001677 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1678 LLDB_LOG(log, "tid: {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001679
Adrian Prantl05097242018-04-30 16:49:04 +00001680 // Before we do the resume below, first check if we have a pending stop
1681 // notification that is currently waiting for all threads to stop. This is
1682 // potentially a buggy situation since we're ostensibly waiting for threads
1683 // to stop before we send out the pending notification, and here we are
1684 // resuming one before we send out the pending stop notification.
Pavel Labatha6321a82017-01-19 15:26:04 +00001685 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
1686 LLDB_LOG(log,
1687 "about to resume tid {0} per explicit request but we have a "
1688 "pending stop notification (tid {1}) that is actively "
1689 "waiting for this thread to stop. Valid sequence of events?",
1690 thread.GetID(), m_pending_notification_tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001691 }
1692
Adrian Prantl05097242018-04-30 16:49:04 +00001693 // Request a resume. We expect this to be synchronous and the system to
1694 // reflect it is running after this completes.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001695 switch (state) {
1696 case eStateRunning: {
1697 const auto resume_result = thread.Resume(signo);
1698 if (resume_result.Success())
1699 SetState(eStateRunning, true);
1700 return resume_result;
1701 }
1702 case eStateStepping: {
1703 const auto step_result = thread.SingleStep(signo);
1704 if (step_result.Success())
1705 SetState(eStateRunning, true);
1706 return step_result;
1707 }
1708 default:
Pavel Labath8198db32017-01-24 11:48:25 +00001709 LLDB_LOG(log, "Unhandled state {0}.", state);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001710 llvm_unreachable("Unhandled state for resume");
1711 }
Pavel Labathc0765592015-05-06 10:46:34 +00001712}
1713
1714//===----------------------------------------------------------------------===//
1715
Kate Stoneb9c1b512016-09-06 20:57:50 +00001716void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001717 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1718 LLDB_LOG(log, "about to process event: (triggering_tid: {0})",
1719 triggering_tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001720
1721 m_pending_notification_tid = triggering_tid;
1722
Adrian Prantl05097242018-04-30 16:49:04 +00001723 // Request a stop for all the thread stops that need to be stopped and are
1724 // not already known to be stopped.
Pavel Labatha5be48b2017-10-17 15:52:16 +00001725 for (const auto &thread : m_threads) {
1726 if (StateIsRunningState(thread->GetState()))
1727 static_cast<NativeThreadLinux *>(thread.get())->RequestStop();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001728 }
1729
1730 SignalIfAllThreadsStopped();
Pavel Labatha6321a82017-01-19 15:26:04 +00001731 LLDB_LOG(log, "event processing done");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001732}
1733
1734void NativeProcessLinux::SignalIfAllThreadsStopped() {
1735 if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
1736 return; // No pending notification. Nothing to do.
1737
1738 for (const auto &thread_sp : m_threads) {
1739 if (StateIsRunningState(thread_sp->GetState()))
1740 return; // Some threads are still running. Don't signal yet.
1741 }
1742
1743 // We have a pending notification and all threads have stopped.
1744 Log *log(
1745 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
1746
1747 // Clear any temporary breakpoints we used to implement software single
1748 // stepping.
1749 for (const auto &thread_info : m_threads_stepping_with_breakpoint) {
Zachary Turner97206d52017-05-12 04:51:55 +00001750 Status error = RemoveBreakpoint(thread_info.second);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001751 if (error.Fail())
Pavel Labatha6321a82017-01-19 15:26:04 +00001752 LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}",
1753 thread_info.first, error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001754 }
1755 m_threads_stepping_with_breakpoint.clear();
1756
1757 // Notify the delegate about the stop
1758 SetCurrentThreadID(m_pending_notification_tid);
1759 SetState(StateType::eStateStopped, true);
1760 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
1761}
1762
1763void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001764 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
1765 LLDB_LOG(log, "tid: {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001766
1767 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID &&
1768 StateIsRunningState(thread.GetState())) {
1769 // We will need to wait for this new thread to stop as well before firing
Adrian Prantl05097242018-04-30 16:49:04 +00001770 // the notification.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001771 thread.RequestStop();
1772 }
1773}
1774
1775void NativeProcessLinux::SigchldHandler() {
Pavel Labatha6321a82017-01-19 15:26:04 +00001776 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001777 // Process all pending waitpid notifications.
1778 while (true) {
1779 int status = -1;
Pavel Labathc1a6b122017-07-03 09:25:55 +00001780 ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, -1, &status,
1781 __WALL | __WNOTHREAD | WNOHANG);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001782
1783 if (wait_pid == 0)
1784 break; // We are done.
1785
1786 if (wait_pid == -1) {
Zachary Turner97206d52017-05-12 04:51:55 +00001787 Status error(errno, eErrorTypePOSIX);
Pavel Labatha6321a82017-01-19 15:26:04 +00001788 LLDB_LOG(log, "waitpid (-1, &status, _) failed: {0}", error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001789 break;
Pavel Labathc0765592015-05-06 10:46:34 +00001790 }
1791
Pavel Labath3508fc82017-06-19 12:47:50 +00001792 WaitStatus wait_status = WaitStatus::Decode(status);
1793 bool exited = wait_status.type == WaitStatus::Exit ||
1794 (wait_status.type == WaitStatus::Signal &&
1795 wait_pid == static_cast<::pid_t>(GetID()));
Pavel Labathc0765592015-05-06 10:46:34 +00001796
Pavel Labath3508fc82017-06-19 12:47:50 +00001797 LLDB_LOG(
1798 log,
1799 "waitpid (-1, &status, _) => pid = {0}, status = {1}, exited = {2}",
1800 wait_pid, wait_status, exited);
Pavel Labathc0765592015-05-06 10:46:34 +00001801
Pavel Labath3508fc82017-06-19 12:47:50 +00001802 MonitorCallback(wait_pid, exited, wait_status);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001803 }
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001804}
1805
Adrian Prantl05097242018-04-30 16:49:04 +00001806// Wrapper for ptrace to catch errors and log calls. Note that ptrace sets
1807// errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
Zachary Turner97206d52017-05-12 04:51:55 +00001808Status NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
1809 void *data, size_t data_size,
1810 long *result) {
1811 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001812 long int ret;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001813
Kate Stoneb9c1b512016-09-06 20:57:50 +00001814 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001815
Kate Stoneb9c1b512016-09-06 20:57:50 +00001816 PtraceDisplayBytes(req, data, data_size);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001817
Kate Stoneb9c1b512016-09-06 20:57:50 +00001818 errno = 0;
1819 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
1820 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
1821 *(unsigned int *)addr, data);
1822 else
1823 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
1824 addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001825
Kate Stoneb9c1b512016-09-06 20:57:50 +00001826 if (ret == -1)
1827 error.SetErrorToErrno();
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001828
Kate Stoneb9c1b512016-09-06 20:57:50 +00001829 if (result)
1830 *result = ret;
Pavel Labath4a9babb2015-06-30 17:04:49 +00001831
Pavel Labath28096202017-02-17 16:09:10 +00001832 LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data,
1833 data_size, ret);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001834
Kate Stoneb9c1b512016-09-06 20:57:50 +00001835 PtraceDisplayBytes(req, data, data_size);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001836
Pavel Labatha6321a82017-01-19 15:26:04 +00001837 if (error.Fail())
1838 LLDB_LOG(log, "ptrace() failed: {0}", error);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001839
Kate Stoneb9c1b512016-09-06 20:57:50 +00001840 return error;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00001841}
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001842
1843llvm::Expected<ProcessorTraceMonitor &>
1844NativeProcessLinux::LookupProcessorTraceInstance(lldb::user_id_t traceid,
1845 lldb::tid_t thread) {
1846 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
1847 if (thread == LLDB_INVALID_THREAD_ID && traceid == m_pt_proces_trace_id) {
1848 LLDB_LOG(log, "thread not specified: {0}", traceid);
1849 return Status("tracing not active thread not specified").ToError();
1850 }
1851
1852 for (auto& iter : m_processor_trace_monitor) {
1853 if (traceid == iter.second->GetTraceID() &&
1854 (thread == iter.first || thread == LLDB_INVALID_THREAD_ID))
1855 return *(iter.second);
1856 }
1857
1858 LLDB_LOG(log, "traceid not being traced: {0}", traceid);
1859 return Status("tracing not active for this thread").ToError();
1860}
1861
1862Status NativeProcessLinux::GetMetaData(lldb::user_id_t traceid,
1863 lldb::tid_t thread,
1864 llvm::MutableArrayRef<uint8_t> &buffer,
1865 size_t offset) {
1866 TraceOptions trace_options;
1867 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
1868 Status error;
1869
1870 LLDB_LOG(log, "traceid {0}", traceid);
1871
1872 auto perf_monitor = LookupProcessorTraceInstance(traceid, thread);
1873 if (!perf_monitor) {
1874 LLDB_LOG(log, "traceid not being traced: {0}", traceid);
1875 buffer = buffer.slice(buffer.size());
1876 error = perf_monitor.takeError();
1877 return error;
1878 }
1879 return (*perf_monitor).ReadPerfTraceData(buffer, offset);
1880}
1881
1882Status NativeProcessLinux::GetData(lldb::user_id_t traceid, lldb::tid_t thread,
1883 llvm::MutableArrayRef<uint8_t> &buffer,
1884 size_t offset) {
1885 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
1886 Status error;
1887
1888 LLDB_LOG(log, "traceid {0}", traceid);
1889
1890 auto perf_monitor = LookupProcessorTraceInstance(traceid, thread);
1891 if (!perf_monitor) {
1892 LLDB_LOG(log, "traceid not being traced: {0}", traceid);
1893 buffer = buffer.slice(buffer.size());
1894 error = perf_monitor.takeError();
1895 return error;
1896 }
1897 return (*perf_monitor).ReadPerfTraceAux(buffer, offset);
1898}
1899
1900Status NativeProcessLinux::GetTraceConfig(lldb::user_id_t traceid,
1901 TraceOptions &config) {
1902 Status error;
1903 if (config.getThreadID() == LLDB_INVALID_THREAD_ID &&
1904 m_pt_proces_trace_id == traceid) {
1905 if (m_pt_proces_trace_id == LLDB_INVALID_UID) {
1906 error.SetErrorString("tracing not active for this process");
1907 return error;
1908 }
1909 config = m_pt_process_trace_config;
1910 } else {
1911 auto perf_monitor =
1912 LookupProcessorTraceInstance(traceid, config.getThreadID());
1913 if (!perf_monitor) {
1914 error = perf_monitor.takeError();
1915 return error;
1916 }
1917 error = (*perf_monitor).GetTraceConfig(config);
1918 }
1919 return error;
1920}
1921
1922lldb::user_id_t
1923NativeProcessLinux::StartTraceGroup(const TraceOptions &config,
1924 Status &error) {
1925
1926 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
1927 if (config.getType() != TraceType::eTraceTypeProcessorTrace)
1928 return LLDB_INVALID_UID;
1929
1930 if (m_pt_proces_trace_id != LLDB_INVALID_UID) {
1931 error.SetErrorString("tracing already active on this process");
1932 return m_pt_proces_trace_id;
1933 }
1934
1935 for (const auto &thread_sp : m_threads) {
1936 if (auto traceInstance = ProcessorTraceMonitor::Create(
1937 GetID(), thread_sp->GetID(), config, true)) {
1938 m_pt_traced_thread_group.insert(thread_sp->GetID());
1939 m_processor_trace_monitor.insert(
1940 std::make_pair(thread_sp->GetID(), std::move(*traceInstance)));
1941 }
1942 }
1943
1944 m_pt_process_trace_config = config;
1945 error = ProcessorTraceMonitor::GetCPUType(m_pt_process_trace_config);
1946
1947 // Trace on Complete process will have traceid of 0
1948 m_pt_proces_trace_id = 0;
1949
1950 LLDB_LOG(log, "Process Trace ID {0}", m_pt_proces_trace_id);
1951 return m_pt_proces_trace_id;
1952}
1953
1954lldb::user_id_t NativeProcessLinux::StartTrace(const TraceOptions &config,
1955 Status &error) {
1956 if (config.getType() != TraceType::eTraceTypeProcessorTrace)
1957 return NativeProcessProtocol::StartTrace(config, error);
1958
1959 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
1960
1961 lldb::tid_t threadid = config.getThreadID();
1962
1963 if (threadid == LLDB_INVALID_THREAD_ID)
1964 return StartTraceGroup(config, error);
1965
1966 auto thread_sp = GetThreadByID(threadid);
1967 if (!thread_sp) {
1968 // Thread not tracked by lldb so don't trace.
1969 error.SetErrorString("invalid thread id");
1970 return LLDB_INVALID_UID;
1971 }
1972
1973 const auto &iter = m_processor_trace_monitor.find(threadid);
1974 if (iter != m_processor_trace_monitor.end()) {
1975 LLDB_LOG(log, "Thread already being traced");
1976 error.SetErrorString("tracing already active on this thread");
1977 return LLDB_INVALID_UID;
1978 }
1979
1980 auto traceMonitor =
1981 ProcessorTraceMonitor::Create(GetID(), threadid, config, false);
1982 if (!traceMonitor) {
1983 error = traceMonitor.takeError();
1984 LLDB_LOG(log, "error {0}", error);
1985 return LLDB_INVALID_UID;
1986 }
1987 lldb::user_id_t ret_trace_id = (*traceMonitor)->GetTraceID();
1988 m_processor_trace_monitor.insert(
1989 std::make_pair(threadid, std::move(*traceMonitor)));
1990 return ret_trace_id;
1991}
1992
1993Status NativeProcessLinux::StopTracingForThread(lldb::tid_t thread) {
1994 Status error;
1995 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
1996 LLDB_LOG(log, "Thread {0}", thread);
1997
1998 const auto& iter = m_processor_trace_monitor.find(thread);
1999 if (iter == m_processor_trace_monitor.end()) {
2000 error.SetErrorString("tracing not active for this thread");
2001 return error;
2002 }
2003
2004 if (iter->second->GetTraceID() == m_pt_proces_trace_id) {
Adrian Prantl05097242018-04-30 16:49:04 +00002005 // traceid maps to the whole process so we have to erase it from the thread
2006 // group.
Ravitheja Addepally99e37692017-06-28 07:58:31 +00002007 LLDB_LOG(log, "traceid maps to process");
2008 m_pt_traced_thread_group.erase(thread);
2009 }
2010 m_processor_trace_monitor.erase(iter);
2011
2012 return error;
2013}
2014
2015Status NativeProcessLinux::StopTrace(lldb::user_id_t traceid,
2016 lldb::tid_t thread) {
2017 Status error;
2018
2019 TraceOptions trace_options;
2020 trace_options.setThreadID(thread);
2021 error = NativeProcessLinux::GetTraceConfig(traceid, trace_options);
2022
2023 if (error.Fail())
2024 return error;
2025
2026 switch (trace_options.getType()) {
2027 case lldb::TraceType::eTraceTypeProcessorTrace:
2028 if (traceid == m_pt_proces_trace_id &&
2029 thread == LLDB_INVALID_THREAD_ID)
2030 StopProcessorTracingOnProcess();
2031 else
2032 error = StopProcessorTracingOnThread(traceid, thread);
2033 break;
2034 default:
2035 error.SetErrorString("trace not supported");
2036 break;
2037 }
2038
2039 return error;
2040}
2041
2042void NativeProcessLinux::StopProcessorTracingOnProcess() {
2043 for (auto thread_id_iter : m_pt_traced_thread_group)
2044 m_processor_trace_monitor.erase(thread_id_iter);
2045 m_pt_traced_thread_group.clear();
2046 m_pt_proces_trace_id = LLDB_INVALID_UID;
2047}
2048
2049Status NativeProcessLinux::StopProcessorTracingOnThread(lldb::user_id_t traceid,
2050 lldb::tid_t thread) {
2051 Status error;
2052 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2053
2054 if (thread == LLDB_INVALID_THREAD_ID) {
2055 for (auto& iter : m_processor_trace_monitor) {
2056 if (iter.second->GetTraceID() == traceid) {
Adrian Prantl05097242018-04-30 16:49:04 +00002057 // Stopping a trace instance for an individual thread hence there will
2058 // only be one traceid that can match.
Ravitheja Addepally99e37692017-06-28 07:58:31 +00002059 m_processor_trace_monitor.erase(iter.first);
2060 return error;
2061 }
2062 LLDB_LOG(log, "Trace ID {0}", iter.second->GetTraceID());
2063 }
2064
2065 LLDB_LOG(log, "Invalid TraceID");
2066 error.SetErrorString("invalid trace id");
2067 return error;
2068 }
2069
2070 // thread is specified so we can use find function on the map.
2071 const auto& iter = m_processor_trace_monitor.find(thread);
2072 if (iter == m_processor_trace_monitor.end()) {
2073 // thread not found in our map.
2074 LLDB_LOG(log, "thread not being traced");
2075 error.SetErrorString("tracing not active for this thread");
2076 return error;
2077 }
2078 if (iter->second->GetTraceID() != traceid) {
2079 // traceid did not match so it has to be invalid.
2080 LLDB_LOG(log, "Invalid TraceID");
2081 error.SetErrorString("invalid trace id");
2082 return error;
2083 }
2084
2085 LLDB_LOG(log, "UID - {0} , Thread -{1}", traceid, thread);
2086
2087 if (traceid == m_pt_proces_trace_id) {
Adrian Prantl05097242018-04-30 16:49:04 +00002088 // traceid maps to the whole process so we have to erase it from the thread
2089 // group.
Ravitheja Addepally99e37692017-06-28 07:58:31 +00002090 LLDB_LOG(log, "traceid maps to process");
2091 m_pt_traced_thread_group.erase(thread);
2092 }
2093 m_processor_trace_monitor.erase(iter);
2094
2095 return error;
2096}