blob: 713d56d2bf591b114ab337f46de0f8e3b3feee3a [file] [log] [blame]
Todd Fialaaf245d12014-06-30 21:05:18 +00001//===-- NativeProcessLinux.cpp -------------------------------- -*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Todd Fialaaf245d12014-06-30 21:05:18 +000010#include "NativeProcessLinux.h"
11
12// C Includes
13#include <errno.h>
Todd Fialaaf245d12014-06-30 21:05:18 +000014#include <stdint.h>
Kate Stoneb9c1b512016-09-06 20:57:50 +000015#include <string.h>
Todd Fialaaf245d12014-06-30 21:05:18 +000016#include <unistd.h>
Todd Fialaaf245d12014-06-30 21:05:18 +000017
18// C++ Includes
19#include <fstream>
Pavel Labathdf7c6992015-06-17 18:38:49 +000020#include <mutex>
Pavel Labathc0765592015-05-06 10:46:34 +000021#include <sstream>
Todd Fialaaf245d12014-06-30 21:05:18 +000022#include <string>
Pavel Labath5b981ab2015-05-29 12:53:54 +000023#include <unordered_map>
Todd Fialaaf245d12014-06-30 21:05:18 +000024
25// Other libraries and framework includes
Tamas Berghammerd8c338d2015-04-15 09:47:02 +000026#include "lldb/Core/EmulateInstruction.h"
Oleksiy Vyalov6edef202014-11-17 22:16:42 +000027#include "lldb/Core/ModuleSpec.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000028#include "lldb/Core/RegisterValue.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000029#include "lldb/Core/State.h"
30#include "lldb/Host/Host.h"
Pavel Labath5ad891f2016-07-21 14:54:03 +000031#include "lldb/Host/HostProcess.h"
Zachary Turner24ae6292017-02-16 19:38:21 +000032#include "lldb/Host/PseudoTerminal.h"
Zachary Turner39de3112014-09-09 20:54:56 +000033#include "lldb/Host/ThreadLauncher.h"
Pavel Labath2a86b552016-06-14 17:30:52 +000034#include "lldb/Host/common/NativeBreakpoint.h"
35#include "lldb/Host/common/NativeRegisterContext.h"
Pavel Labath4ee1c952017-02-06 18:36:58 +000036#include "lldb/Host/linux/Ptrace.h"
37#include "lldb/Host/linux/Uio.h"
Kamil Rytarowski816ae4b2017-02-01 14:30:40 +000038#include "lldb/Host/posix/ProcessLauncherPosixFork.h"
Pavel Labath2a86b552016-06-14 17:30:52 +000039#include "lldb/Symbol/ObjectFile.h"
Zachary Turner90aff472015-03-03 23:36:51 +000040#include "lldb/Target/Process.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000041#include "lldb/Target/ProcessLaunchInfo.h"
Pavel Labath5b981ab2015-05-29 12:53:54 +000042#include "lldb/Target/Target.h"
Chaoren Linc16f5dc2015-03-19 23:28:10 +000043#include "lldb/Utility/LLDBAssert.h"
Zachary Turner97206d52017-05-12 04:51:55 +000044#include "lldb/Utility/Status.h"
Pavel Labathf805e192015-07-07 10:08:41 +000045#include "lldb/Utility/StringExtractor.h"
Pavel Labath10c41f32017-06-06 14:06:17 +000046#include "llvm/Support/Errno.h"
47#include "llvm/Support/FileSystem.h"
48#include "llvm/Support/Threading.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000049
Todd Fialaaf245d12014-06-30 21:05:18 +000050#include "NativeThreadLinux.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000051#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000052#include "Procfs.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000053
Tamas Berghammerd8584872015-02-06 10:57:40 +000054#include <linux/unistd.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000055#include <sys/socket.h>
Pavel Labathdf7c6992015-06-17 18:38:49 +000056#include <sys/syscall.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000057#include <sys/types.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000058#include <sys/user.h>
59#include <sys/wait.h>
60
Todd Fialaaf245d12014-06-30 21:05:18 +000061// Support hardware breakpoints in case it has not been defined
62#ifndef TRAP_HWBKPT
Kate Stoneb9c1b512016-09-06 20:57:50 +000063#define TRAP_HWBKPT 4
Todd Fialaaf245d12014-06-30 21:05:18 +000064#endif
65
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000066using namespace lldb;
67using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000068using namespace lldb_private::process_linux;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000069using namespace llvm;
70
Todd Fialaaf245d12014-06-30 21:05:18 +000071// Private bits we only need internally.
Pavel Labathdf7c6992015-06-17 18:38:49 +000072
Kate Stoneb9c1b512016-09-06 20:57:50 +000073static bool ProcessVmReadvSupported() {
74 static bool is_supported;
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000075 static llvm::once_flag flag;
Pavel Labathdf7c6992015-06-17 18:38:49 +000076
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000077 llvm::call_once(flag, [] {
Pavel Labatha6321a82017-01-19 15:26:04 +000078 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Pavel Labath4abe5d62016-07-15 10:18:15 +000079
Kate Stoneb9c1b512016-09-06 20:57:50 +000080 uint32_t source = 0x47424742;
81 uint32_t dest = 0;
Pavel Labath4abe5d62016-07-15 10:18:15 +000082
Kate Stoneb9c1b512016-09-06 20:57:50 +000083 struct iovec local, remote;
84 remote.iov_base = &source;
85 local.iov_base = &dest;
86 remote.iov_len = local.iov_len = sizeof source;
Pavel Labath4abe5d62016-07-15 10:18:15 +000087
Kate Stoneb9c1b512016-09-06 20:57:50 +000088 // We shall try if cross-process-memory reads work by attempting to read a
89 // value from our own process.
90 ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
91 is_supported = (res == sizeof(source) && source == dest);
Pavel Labatha6321a82017-01-19 15:26:04 +000092 if (is_supported)
93 LLDB_LOG(log,
94 "Detected kernel support for process_vm_readv syscall. "
95 "Fast memory reads enabled.");
96 else
97 LLDB_LOG(log,
98 "syscall process_vm_readv failed (error: {0}). Fast memory "
99 "reads disabled.",
Pavel Labath10c41f32017-06-06 14:06:17 +0000100 llvm::sys::StrError());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000101 });
Pavel Labath4abe5d62016-07-15 10:18:15 +0000102
Kate Stoneb9c1b512016-09-06 20:57:50 +0000103 return is_supported;
Pavel Labath4abe5d62016-07-15 10:18:15 +0000104}
105
Kate Stoneb9c1b512016-09-06 20:57:50 +0000106namespace {
107void MaybeLogLaunchInfo(const ProcessLaunchInfo &info) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000108 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000109 if (!log)
110 return;
111
112 if (const FileAction *action = info.GetFileActionForFD(STDIN_FILENO))
Pavel Labatha6321a82017-01-19 15:26:04 +0000113 LLDB_LOG(log, "setting STDIN to '{0}'", action->GetFileSpec());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000114 else
Pavel Labatha6321a82017-01-19 15:26:04 +0000115 LLDB_LOG(log, "leaving STDIN as is");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000116
117 if (const FileAction *action = info.GetFileActionForFD(STDOUT_FILENO))
Pavel Labatha6321a82017-01-19 15:26:04 +0000118 LLDB_LOG(log, "setting STDOUT to '{0}'", action->GetFileSpec());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000119 else
Pavel Labatha6321a82017-01-19 15:26:04 +0000120 LLDB_LOG(log, "leaving STDOUT as is");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000121
122 if (const FileAction *action = info.GetFileActionForFD(STDERR_FILENO))
Pavel Labatha6321a82017-01-19 15:26:04 +0000123 LLDB_LOG(log, "setting STDERR to '{0}'", action->GetFileSpec());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000124 else
Pavel Labatha6321a82017-01-19 15:26:04 +0000125 LLDB_LOG(log, "leaving STDERR as is");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000126
127 int i = 0;
128 for (const char **args = info.GetArguments().GetConstArgumentVector(); *args;
129 ++args, ++i)
Pavel Labatha6321a82017-01-19 15:26:04 +0000130 LLDB_LOG(log, "arg {0}: '{1}'", i, *args);
Pavel Labath4abe5d62016-07-15 10:18:15 +0000131}
Todd Fialaaf245d12014-06-30 21:05:18 +0000132
Kate Stoneb9c1b512016-09-06 20:57:50 +0000133void DisplayBytes(StreamString &s, void *bytes, uint32_t count) {
134 uint8_t *ptr = (uint8_t *)bytes;
135 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
136 for (uint32_t i = 0; i < loop_count; i++) {
137 s.Printf("[%x]", *ptr);
138 ptr++;
139 }
140}
Todd Fialaaf245d12014-06-30 21:05:18 +0000141
Kate Stoneb9c1b512016-09-06 20:57:50 +0000142void PtraceDisplayBytes(int &req, void *data, size_t data_size) {
Pavel Labathaafe0532017-02-06 19:31:05 +0000143 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
Pavel Labatha6321a82017-01-19 15:26:04 +0000144 if (!log)
145 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000146 StreamString buf;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000147
Pavel Labatha6321a82017-01-19 15:26:04 +0000148 switch (req) {
149 case PTRACE_POKETEXT: {
150 DisplayBytes(buf, &data, 8);
Pavel Labathaafe0532017-02-06 19:31:05 +0000151 LLDB_LOGV(log, "PTRACE_POKETEXT {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000152 break;
153 }
154 case PTRACE_POKEDATA: {
155 DisplayBytes(buf, &data, 8);
Pavel Labathaafe0532017-02-06 19:31:05 +0000156 LLDB_LOGV(log, "PTRACE_POKEDATA {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000157 break;
158 }
159 case PTRACE_POKEUSER: {
160 DisplayBytes(buf, &data, 8);
Pavel Labathaafe0532017-02-06 19:31:05 +0000161 LLDB_LOGV(log, "PTRACE_POKEUSER {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000162 break;
163 }
164 case PTRACE_SETREGS: {
165 DisplayBytes(buf, data, data_size);
Pavel Labathaafe0532017-02-06 19:31:05 +0000166 LLDB_LOGV(log, "PTRACE_SETREGS {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000167 break;
168 }
169 case PTRACE_SETFPREGS: {
170 DisplayBytes(buf, data, data_size);
Pavel Labathaafe0532017-02-06 19:31:05 +0000171 LLDB_LOGV(log, "PTRACE_SETFPREGS {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000172 break;
173 }
174 case PTRACE_SETSIGINFO: {
175 DisplayBytes(buf, data, sizeof(siginfo_t));
Pavel Labathaafe0532017-02-06 19:31:05 +0000176 LLDB_LOGV(log, "PTRACE_SETSIGINFO {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000177 break;
178 }
179 case PTRACE_SETREGSET: {
180 // Extract iov_base from data, which is a pointer to the struct IOVEC
181 DisplayBytes(buf, *(void **)data, data_size);
Pavel Labathaafe0532017-02-06 19:31:05 +0000182 LLDB_LOGV(log, "PTRACE_SETREGSET {0}", buf.GetData());
Pavel Labatha6321a82017-01-19 15:26:04 +0000183 break;
184 }
185 default: {}
Kate Stoneb9c1b512016-09-06 20:57:50 +0000186 }
187}
Todd Fialaaf245d12014-06-30 21:05:18 +0000188
Kate Stoneb9c1b512016-09-06 20:57:50 +0000189static constexpr unsigned k_ptrace_word_size = sizeof(void *);
190static_assert(sizeof(long) >= k_ptrace_word_size,
191 "Size of long must be larger than ptrace word size");
Pavel Labath1107b5a2015-04-17 14:07:49 +0000192} // end of anonymous namespace
193
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000194// Simple helper function to ensure flags are enabled on the given file
195// descriptor.
Zachary Turner97206d52017-05-12 04:51:55 +0000196static Status EnsureFDFlags(int fd, int flags) {
197 Status error;
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000198
Kate Stoneb9c1b512016-09-06 20:57:50 +0000199 int status = fcntl(fd, F_GETFL);
200 if (status == -1) {
201 error.SetErrorToErrno();
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000202 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000203 }
204
205 if (fcntl(fd, F_SETFL, status | flags) == -1) {
206 error.SetErrorToErrno();
207 return error;
208 }
209
210 return error;
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000211}
212
Todd Fialaaf245d12014-06-30 21:05:18 +0000213// -----------------------------------------------------------------------------
214// Public Static Methods
215// -----------------------------------------------------------------------------
216
Zachary Turner97206d52017-05-12 04:51:55 +0000217Status NativeProcessProtocol::Launch(
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000218 ProcessLaunchInfo &launch_info,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000219 NativeProcessProtocol::NativeDelegate &native_delegate, MainLoop &mainloop,
220 NativeProcessProtocolSP &native_process_sp) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000221 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Todd Fialaaf245d12014-06-30 21:05:18 +0000222
Zachary Turner97206d52017-05-12 04:51:55 +0000223 Status error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000224
Kate Stoneb9c1b512016-09-06 20:57:50 +0000225 // Verify the working directory is valid if one was specified.
226 FileSpec working_dir{launch_info.GetWorkingDirectory()};
Zachary Turner7d86ee52017-03-08 17:56:08 +0000227 if (working_dir && (!working_dir.ResolvePath() ||
228 !llvm::sys::fs::is_directory(working_dir.GetPath()))) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000229 error.SetErrorStringWithFormat("No such file or directory: %s",
230 working_dir.GetCString());
Todd Fialaaf245d12014-06-30 21:05:18 +0000231 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000232 }
233
234 // Create the NativeProcessLinux in launch mode.
235 native_process_sp.reset(new NativeProcessLinux());
236
237 if (!native_process_sp->RegisterNativeDelegate(native_delegate)) {
238 native_process_sp.reset();
239 error.SetErrorStringWithFormat("failed to register the native delegate");
240 return error;
241 }
242
243 error = std::static_pointer_cast<NativeProcessLinux>(native_process_sp)
244 ->LaunchInferior(mainloop, launch_info);
245
246 if (error.Fail()) {
247 native_process_sp.reset();
Pavel Labatha6321a82017-01-19 15:26:04 +0000248 LLDB_LOG(log, "failed to launch process: {0}", error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000249 return error;
250 }
251
252 launch_info.SetProcessID(native_process_sp->GetID());
253
254 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000255}
256
Zachary Turner97206d52017-05-12 04:51:55 +0000257Status NativeProcessProtocol::Attach(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000258 lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
259 MainLoop &mainloop, NativeProcessProtocolSP &native_process_sp) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000260 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
261 LLDB_LOG(log, "pid = {0:x}", pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000262
Kate Stoneb9c1b512016-09-06 20:57:50 +0000263 // Retrieve the architecture for the running process.
264 ArchSpec process_arch;
Zachary Turner97206d52017-05-12 04:51:55 +0000265 Status error = ResolveProcessArchitecture(pid, process_arch);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000266 if (!error.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +0000267 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000268
269 std::shared_ptr<NativeProcessLinux> native_process_linux_sp(
270 new NativeProcessLinux());
271
272 if (!native_process_linux_sp->RegisterNativeDelegate(native_delegate)) {
273 error.SetErrorStringWithFormat("failed to register the native delegate");
274 return error;
275 }
276
277 native_process_linux_sp->AttachToInferior(mainloop, pid, error);
278 if (!error.Success())
279 return error;
280
281 native_process_sp = native_process_linux_sp;
282 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000283}
284
285// -----------------------------------------------------------------------------
286// Public Instance Methods
287// -----------------------------------------------------------------------------
288
Kate Stoneb9c1b512016-09-06 20:57:50 +0000289NativeProcessLinux::NativeProcessLinux()
290 : NativeProcessProtocol(LLDB_INVALID_PROCESS_ID), m_arch(),
291 m_supports_mem_region(eLazyBoolCalculate), m_mem_region_cache(),
Ravitheja Addepally99e37692017-06-28 07:58:31 +0000292 m_pending_notification_tid(LLDB_INVALID_THREAD_ID),
293 m_pt_proces_trace_id(LLDB_INVALID_UID) {}
Kate Stoneb9c1b512016-09-06 20:57:50 +0000294
295void NativeProcessLinux::AttachToInferior(MainLoop &mainloop, lldb::pid_t pid,
Zachary Turner97206d52017-05-12 04:51:55 +0000296 Status &error) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000297 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
298 LLDB_LOG(log, "pid = {0:x}", pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000299
300 m_sigchld_handle = mainloop.RegisterSignal(
301 SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, error);
302 if (!m_sigchld_handle)
303 return;
304
305 error = ResolveProcessArchitecture(pid, m_arch);
306 if (!error.Success())
307 return;
308
309 // Set the architecture to the exe architecture.
Pavel Labatha6321a82017-01-19 15:26:04 +0000310 LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid,
311 m_arch.GetArchitectureName());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000312 m_pid = pid;
313 SetState(eStateAttaching);
314
315 Attach(pid, error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000316}
317
Zachary Turner97206d52017-05-12 04:51:55 +0000318Status NativeProcessLinux::LaunchInferior(MainLoop &mainloop,
319 ProcessLaunchInfo &launch_info) {
320 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000321 m_sigchld_handle = mainloop.RegisterSignal(
322 SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, error);
323 if (!m_sigchld_handle)
324 return error;
325
326 SetState(eStateLaunching);
327
328 MaybeLogLaunchInfo(launch_info);
329
330 ::pid_t pid =
Kamil Rytarowski816ae4b2017-02-01 14:30:40 +0000331 ProcessLauncherPosixFork().LaunchProcess(launch_info, error).GetProcessId();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000332 if (error.Fail())
333 return error;
334
Pavel Labatha6321a82017-01-19 15:26:04 +0000335 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000336
337 // Wait for the child process to trap on its call to execve.
338 ::pid_t wpid;
339 int status;
340 if ((wpid = waitpid(pid, &status, 0)) < 0) {
341 error.SetErrorToErrno();
Pavel Labatha6321a82017-01-19 15:26:04 +0000342 LLDB_LOG(log, "waitpid for inferior failed with %s", error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000343
Kate Stoneb9c1b512016-09-06 20:57:50 +0000344 // Mark the inferior as invalid.
345 // FIXME this could really use a new state - eStateLaunchFailure. For now,
346 // using eStateInvalid.
347 SetState(StateType::eStateInvalid);
Pavel Labath19cbe962015-07-21 13:20:32 +0000348
Kate Stoneb9c1b512016-09-06 20:57:50 +0000349 return error;
350 }
351 assert(WIFSTOPPED(status) && (wpid == static_cast<::pid_t>(pid)) &&
352 "Could not sync with inferior process.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000353
Pavel Labatha6321a82017-01-19 15:26:04 +0000354 LLDB_LOG(log, "inferior started, now in stopped state");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000355 error = SetDefaultPtraceOpts(pid);
356 if (error.Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000357 LLDB_LOG(log, "failed to set default ptrace options: {0}", error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000358
Kate Stoneb9c1b512016-09-06 20:57:50 +0000359 // Mark the inferior as invalid.
360 // FIXME this could really use a new state - eStateLaunchFailure. For now,
361 // using eStateInvalid.
362 SetState(StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000363
Kate Stoneb9c1b512016-09-06 20:57:50 +0000364 return error;
365 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000366
Kate Stoneb9c1b512016-09-06 20:57:50 +0000367 // Release the master terminal descriptor and pass it off to the
368 // NativeProcessLinux instance. Similarly stash the inferior pid.
369 m_terminal_fd = launch_info.GetPTY().ReleaseMasterFileDescriptor();
370 m_pid = pid;
371 launch_info.SetProcessID(pid);
Pavel Labath4abe5d62016-07-15 10:18:15 +0000372
Kate Stoneb9c1b512016-09-06 20:57:50 +0000373 if (m_terminal_fd != -1) {
374 error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
375 if (error.Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000376 LLDB_LOG(log,
377 "inferior EnsureFDFlags failed for ensuring terminal "
378 "O_NONBLOCK setting: {0}",
379 error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000380
Kate Stoneb9c1b512016-09-06 20:57:50 +0000381 // Mark the inferior as invalid.
382 // FIXME this could really use a new state - eStateLaunchFailure. For
383 // now, using eStateInvalid.
384 SetState(StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000385
Kate Stoneb9c1b512016-09-06 20:57:50 +0000386 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000387 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000388 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000389
Pavel Labatha6321a82017-01-19 15:26:04 +0000390 LLDB_LOG(log, "adding pid = {0}", pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000391 ResolveProcessArchitecture(m_pid, m_arch);
392 NativeThreadLinuxSP thread_sp = AddThread(pid);
393 assert(thread_sp && "AddThread() returned a nullptr thread");
394 thread_sp->SetStoppedBySignal(SIGSTOP);
395 ThreadWasCreated(*thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +0000396
Kate Stoneb9c1b512016-09-06 20:57:50 +0000397 // Let our process instance know the thread has stopped.
398 SetCurrentThreadID(thread_sp->GetID());
399 SetState(StateType::eStateStopped);
400
Pavel Labatha6321a82017-01-19 15:26:04 +0000401 if (error.Fail())
402 LLDB_LOG(log, "inferior launching failed {0}", error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000403 return error;
404}
405
Zachary Turner97206d52017-05-12 04:51:55 +0000406::pid_t NativeProcessLinux::Attach(lldb::pid_t pid, Status &error) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000407 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000408
409 // Use a map to keep track of the threads which we have attached/need to
410 // attach.
411 Host::TidMap tids_to_attach;
412 if (pid <= 1) {
413 error.SetErrorToGenericError();
414 error.SetErrorString("Attaching to process 1 is not allowed.");
415 return -1;
416 }
417
418 while (Host::FindProcessThreads(pid, tids_to_attach)) {
419 for (Host::TidMap::iterator it = tids_to_attach.begin();
420 it != tids_to_attach.end();) {
421 if (it->second == false) {
422 lldb::tid_t tid = it->first;
423
424 // Attach to the requested process.
425 // An attach will cause the thread to stop with a SIGSTOP.
426 error = PtraceWrapper(PTRACE_ATTACH, tid);
427 if (error.Fail()) {
428 // No such thread. The thread may have exited.
429 // More error handling may be needed.
430 if (error.GetError() == ESRCH) {
431 it = tids_to_attach.erase(it);
432 continue;
433 } else
434 return -1;
435 }
436
437 int status;
438 // Need to use __WALL otherwise we receive an error with errno=ECHLD
439 // At this point we should have a thread stopped if waitpid succeeds.
440 if ((status = waitpid(tid, NULL, __WALL)) < 0) {
441 // No such thread. The thread may have exited.
442 // More error handling may be needed.
443 if (errno == ESRCH) {
444 it = tids_to_attach.erase(it);
445 continue;
446 } else {
447 error.SetErrorToErrno();
448 return -1;
449 }
450 }
451
452 error = SetDefaultPtraceOpts(tid);
453 if (error.Fail())
454 return -1;
455
Pavel Labatha6321a82017-01-19 15:26:04 +0000456 LLDB_LOG(log, "adding tid = {0}", tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000457 it->second = true;
458
459 // Create the thread, mark it as stopped.
460 NativeThreadLinuxSP thread_sp(AddThread(static_cast<lldb::tid_t>(tid)));
461 assert(thread_sp && "AddThread() returned a nullptr");
462
463 // This will notify this is a new thread and tell the system it is
464 // stopped.
465 thread_sp->SetStoppedBySignal(SIGSTOP);
466 ThreadWasCreated(*thread_sp);
467 SetCurrentThreadID(thread_sp->GetID());
468 }
469
470 // move the loop forward
471 ++it;
472 }
473 }
474
475 if (tids_to_attach.size() > 0) {
476 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000477 // Let our process instance know the thread has stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000478 SetState(StateType::eStateStopped);
479 } else {
480 error.SetErrorToGenericError();
481 error.SetErrorString("No such process.");
482 return -1;
483 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000484
Kate Stoneb9c1b512016-09-06 20:57:50 +0000485 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000486}
487
Zachary Turner97206d52017-05-12 04:51:55 +0000488Status NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000489 long ptrace_opts = 0;
Todd Fialaaf245d12014-06-30 21:05:18 +0000490
Kate Stoneb9c1b512016-09-06 20:57:50 +0000491 // Have the child raise an event on exit. This is used to keep the child in
492 // limbo until it is destroyed.
493 ptrace_opts |= PTRACE_O_TRACEEXIT;
Todd Fialaaf245d12014-06-30 21:05:18 +0000494
Kate Stoneb9c1b512016-09-06 20:57:50 +0000495 // Have the tracer trace threads which spawn in the inferior process.
496 // TODO: if we want to support tracing the inferiors' child, add the
497 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
498 ptrace_opts |= PTRACE_O_TRACECLONE;
Todd Fialaaf245d12014-06-30 21:05:18 +0000499
Kate Stoneb9c1b512016-09-06 20:57:50 +0000500 // Have the tracer notify us before execve returns
501 // (needed to disable legacy SIGTRAP generation)
502 ptrace_opts |= PTRACE_O_TRACEEXEC;
Todd Fialaaf245d12014-06-30 21:05:18 +0000503
Kate Stoneb9c1b512016-09-06 20:57:50 +0000504 return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void *)ptrace_opts);
Todd Fialaaf245d12014-06-30 21:05:18 +0000505}
506
Pavel Labath1107b5a2015-04-17 14:07:49 +0000507// Handles all waitpid events from the inferior process.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000508void NativeProcessLinux::MonitorCallback(lldb::pid_t pid, bool exited,
Pavel Labath3508fc82017-06-19 12:47:50 +0000509 WaitStatus status) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000510 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Todd Fialaaf245d12014-06-30 21:05:18 +0000511
Kate Stoneb9c1b512016-09-06 20:57:50 +0000512 // Certain activities differ based on whether the pid is the tid of the main
513 // thread.
514 const bool is_main_thread = (pid == GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000515
Kate Stoneb9c1b512016-09-06 20:57:50 +0000516 // Handle when the thread exits.
517 if (exited) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000518 LLDB_LOG(log, "got exit signal({0}) , tid = {1} ({2} main thread)", signal,
519 pid, is_main_thread ? "is" : "is not");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000520
521 // This is a thread that exited. Ensure we're not tracking it anymore.
522 const bool thread_found = StopTrackingThread(pid);
523
524 if (is_main_thread) {
525 // We only set the exit status and notify the delegate if we haven't
526 // already set the process
527 // state to an exited state. We normally should have received a SIGTRAP |
528 // (PTRACE_EVENT_EXIT << 8)
529 // for the main thread.
530 const bool already_notified = (GetState() == StateType::eStateExited) ||
531 (GetState() == StateType::eStateCrashed);
532 if (!already_notified) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000533 LLDB_LOG(
534 log,
535 "tid = {0} handling main thread exit ({1}), expected exit state "
536 "already set but state was {2} instead, setting exit state now",
537 pid,
538 thread_found ? "stopped tracking thread metadata"
539 : "thread metadata not found",
Pavel Labath8198db32017-01-24 11:48:25 +0000540 GetState());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000541 // The main thread exited. We're done monitoring. Report to delegate.
Pavel Labath3508fc82017-06-19 12:47:50 +0000542 SetExitStatus(status, true);
Todd Fialaaf245d12014-06-30 21:05:18 +0000543
Kate Stoneb9c1b512016-09-06 20:57:50 +0000544 // Notify delegate that our process has exited.
545 SetState(StateType::eStateExited, true);
Pavel Labatha6321a82017-01-19 15:26:04 +0000546 } else
547 LLDB_LOG(log, "tid = {0} main thread now exited (%s)", pid,
548 thread_found ? "stopped tracking thread metadata"
549 : "thread metadata not found");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000550 } else {
551 // Do we want to report to the delegate in this case? I think not. If
Pavel Labatha6321a82017-01-19 15:26:04 +0000552 // this was an orderly thread exit, we would already have received the
553 // SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal, and we would have done an
554 // all-stop then.
555 LLDB_LOG(log, "tid = {0} handling non-main thread exit (%s)", pid,
556 thread_found ? "stopped tracking thread metadata"
557 : "thread metadata not found");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000558 }
559 return;
560 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000561
Kate Stoneb9c1b512016-09-06 20:57:50 +0000562 siginfo_t info;
563 const auto info_err = GetSignalInfo(pid, &info);
564 auto thread_sp = GetThreadByID(pid);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000565
Kate Stoneb9c1b512016-09-06 20:57:50 +0000566 if (!thread_sp) {
567 // Normally, the only situation when we cannot find the thread is if we have
Pavel Labatha6321a82017-01-19 15:26:04 +0000568 // just received a new thread notification. This is indicated by
569 // GetSignalInfo() returning si_code == SI_USER and si_pid == 0
570 LLDB_LOG(log, "received notification about an unknown tid {0}.", pid);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000571
Kate Stoneb9c1b512016-09-06 20:57:50 +0000572 if (info_err.Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000573 LLDB_LOG(log,
574 "(tid {0}) GetSignalInfo failed ({1}). "
575 "Ingoring this notification.",
576 pid, info_err);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000577 return;
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000578 }
579
Pavel Labatha6321a82017-01-19 15:26:04 +0000580 LLDB_LOG(log, "tid {0}, si_code: {1}, si_pid: {2}", pid, info.si_code,
581 info.si_pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000582
583 auto thread_sp = AddThread(pid);
Ravitheja Addepally99e37692017-06-28 07:58:31 +0000584
Kate Stoneb9c1b512016-09-06 20:57:50 +0000585 // Resume the newly created thread.
586 ResumeThread(*thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
587 ThreadWasCreated(*thread_sp);
588 return;
589 }
590
591 // Get details on the signal raised.
592 if (info_err.Success()) {
593 // We have retrieved the signal info. Dispatch appropriately.
594 if (info.si_signo == SIGTRAP)
595 MonitorSIGTRAP(info, *thread_sp);
Chaoren Linfa03ad22015-02-03 01:50:42 +0000596 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000597 MonitorSignal(info, *thread_sp, exited);
598 } else {
599 if (info_err.GetError() == EINVAL) {
600 // This is a group stop reception for this tid.
601 // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU
Pavel Labatha6321a82017-01-19 15:26:04 +0000602 // into the tracee, triggering the group-stop mechanism. Normally
603 // receiving these would stop the process, pending a SIGCONT. Simulating
604 // this state in a debugger is hard and is generally not needed (one use
605 // case is debugging background task being managed by a shell). For
606 // general use, it is sufficient to stop the process in a signal-delivery
Kate Stoneb9c1b512016-09-06 20:57:50 +0000607 // stop which happens before the group stop. This done by MonitorSignal
Pavel Labatha6321a82017-01-19 15:26:04 +0000608 // and works correctly for all signals.
609 LLDB_LOG(log,
610 "received a group stop for pid {0} tid {1}. Transparent "
611 "handling of group stops not supported, resuming the "
612 "thread.",
613 GetID(), pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000614 ResumeThread(*thread_sp, thread_sp->GetState(),
615 LLDB_INVALID_SIGNAL_NUMBER);
616 } else {
617 // ptrace(GETSIGINFO) failed (but not due to group-stop).
Todd Fialaaf245d12014-06-30 21:05:18 +0000618
Kate Stoneb9c1b512016-09-06 20:57:50 +0000619 // A return value of ESRCH means the thread/process is no longer on the
Pavel Labatha6321a82017-01-19 15:26:04 +0000620 // system, so it was killed somehow outside of our control. Either way,
621 // we can't do anything with it anymore.
Todd Fialaaf245d12014-06-30 21:05:18 +0000622
Kate Stoneb9c1b512016-09-06 20:57:50 +0000623 // Stop tracking the metadata for the thread since it's entirely off the
624 // system now.
625 const bool thread_found = StopTrackingThread(pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000626
Pavel Labatha6321a82017-01-19 15:26:04 +0000627 LLDB_LOG(log,
628 "GetSignalInfo failed: {0}, tid = {1}, signal = {2}, "
629 "status = {3}, main_thread = {4}, thread_found: {5}",
630 info_err, pid, signal, status, is_main_thread, thread_found);
Todd Fialaaf245d12014-06-30 21:05:18 +0000631
Kate Stoneb9c1b512016-09-06 20:57:50 +0000632 if (is_main_thread) {
633 // Notify the delegate - our process is not available but appears to
634 // have been killed outside
635 // our control. Is eStateExited the right exit state in this case?
Pavel Labath3508fc82017-06-19 12:47:50 +0000636 SetExitStatus(status, true);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000637 SetState(StateType::eStateExited, true);
638 } else {
639 // This thread was pulled out from underneath us. Anything to do here?
640 // Do we want to do an all stop?
Pavel Labatha6321a82017-01-19 15:26:04 +0000641 LLDB_LOG(log,
642 "pid {0} tid {1} non-main thread exit occurred, didn't "
643 "tell delegate anything since thread disappeared out "
644 "from underneath us",
645 GetID(), pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000646 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000647 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000648 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000649}
650
Kate Stoneb9c1b512016-09-06 20:57:50 +0000651void NativeProcessLinux::WaitForNewThread(::pid_t tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000652 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Pavel Labath426bdf82015-04-28 07:51:52 +0000653
Kate Stoneb9c1b512016-09-06 20:57:50 +0000654 NativeThreadLinuxSP new_thread_sp = GetThreadByID(tid);
Pavel Labath426bdf82015-04-28 07:51:52 +0000655
Kate Stoneb9c1b512016-09-06 20:57:50 +0000656 if (new_thread_sp) {
657 // We are already tracking the thread - we got the event on the new thread
658 // (see
659 // MonitorSignal) before this one. We are done.
660 return;
661 }
Pavel Labath426bdf82015-04-28 07:51:52 +0000662
Kate Stoneb9c1b512016-09-06 20:57:50 +0000663 // The thread is not tracked yet, let's wait for it to appear.
664 int status = -1;
Pavel Labathc1a6b122017-07-03 09:25:55 +0000665 LLDB_LOG(log,
666 "received thread creation event for tid {0}. tid not tracked "
667 "yet, waiting for thread to appear...",
668 tid);
669 ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, &status, __WALL);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000670 // Since we are waiting on a specific tid, this must be the creation event.
Pavel Labatha6321a82017-01-19 15:26:04 +0000671 // But let's do some checks just in case.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000672 if (wait_pid != tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000673 LLDB_LOG(log,
674 "waiting for tid {0} failed. Assuming the thread has "
675 "disappeared in the meantime",
676 tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000677 // The only way I know of this could happen is if the whole process was
678 // SIGKILLed in the mean time. In any case, we can't do anything about that
679 // now.
680 return;
681 }
682 if (WIFEXITED(status)) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000683 LLDB_LOG(log,
684 "waiting for tid {0} returned an 'exited' event. Not "
685 "tracking the thread.",
686 tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000687 // Also a very improbable event.
688 return;
689 }
Pavel Labath426bdf82015-04-28 07:51:52 +0000690
Pavel Labatha6321a82017-01-19 15:26:04 +0000691 LLDB_LOG(log, "pid = {0}: tracking new thread tid {1}", GetID(), tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000692 new_thread_sp = AddThread(tid);
Ravitheja Addepally99e37692017-06-28 07:58:31 +0000693
Kate Stoneb9c1b512016-09-06 20:57:50 +0000694 ResumeThread(*new_thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
695 ThreadWasCreated(*new_thread_sp);
Pavel Labath426bdf82015-04-28 07:51:52 +0000696}
697
Kate Stoneb9c1b512016-09-06 20:57:50 +0000698void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info,
699 NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000700 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000701 const bool is_main_thread = (thread.GetID() == GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000702
Kate Stoneb9c1b512016-09-06 20:57:50 +0000703 assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
Todd Fialaaf245d12014-06-30 21:05:18 +0000704
Kate Stoneb9c1b512016-09-06 20:57:50 +0000705 switch (info.si_code) {
706 // TODO: these two cases are required if we want to support tracing of the
707 // inferiors' children. We'd need this to debug a monitor.
708 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
709 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
Todd Fialaaf245d12014-06-30 21:05:18 +0000710
Kate Stoneb9c1b512016-09-06 20:57:50 +0000711 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): {
712 // This is the notification on the parent thread which informs us of new
713 // thread
714 // creation.
715 // We don't want to do anything with the parent thread so we just resume it.
716 // In case we
717 // want to implement "break on thread creation" functionality, we would need
718 // to stop
719 // here.
Todd Fialaaf245d12014-06-30 21:05:18 +0000720
Kate Stoneb9c1b512016-09-06 20:57:50 +0000721 unsigned long event_message = 0;
722 if (GetEventMessage(thread.GetID(), &event_message).Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000723 LLDB_LOG(log,
724 "pid {0} received thread creation event but "
725 "GetEventMessage failed so we don't know the new tid",
726 thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000727 } else
728 WaitForNewThread(event_message);
Todd Fialaaf245d12014-06-30 21:05:18 +0000729
Kate Stoneb9c1b512016-09-06 20:57:50 +0000730 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
731 break;
732 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000733
Kate Stoneb9c1b512016-09-06 20:57:50 +0000734 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): {
735 NativeThreadLinuxSP main_thread_sp;
Pavel Labatha6321a82017-01-19 15:26:04 +0000736 LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000737
738 // Exec clears any pending notifications.
739 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
740
741 // Remove all but the main thread here. Linux fork creates a new process
742 // which only copies the main thread.
Pavel Labatha6321a82017-01-19 15:26:04 +0000743 LLDB_LOG(log, "exec received, stop tracking all but main thread");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000744
745 for (auto thread_sp : m_threads) {
746 const bool is_main_thread = thread_sp && thread_sp->GetID() == GetID();
747 if (is_main_thread) {
748 main_thread_sp = std::static_pointer_cast<NativeThreadLinux>(thread_sp);
Pavel Labatha6321a82017-01-19 15:26:04 +0000749 LLDB_LOG(log, "found main thread with tid {0}, keeping",
750 main_thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000751 } else {
Pavel Labatha6321a82017-01-19 15:26:04 +0000752 LLDB_LOG(log, "discarding non-main-thread tid {0} due to exec",
753 thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000754 }
Todd Fialaa9882ce2014-08-28 15:46:54 +0000755 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000756
Kate Stoneb9c1b512016-09-06 20:57:50 +0000757 m_threads.clear();
Chaoren Linfa03ad22015-02-03 01:50:42 +0000758
Kate Stoneb9c1b512016-09-06 20:57:50 +0000759 if (main_thread_sp) {
760 m_threads.push_back(main_thread_sp);
761 SetCurrentThreadID(main_thread_sp->GetID());
762 main_thread_sp->SetStoppedByExec();
763 } else {
764 SetCurrentThreadID(LLDB_INVALID_THREAD_ID);
Pavel Labatha6321a82017-01-19 15:26:04 +0000765 LLDB_LOG(log,
766 "pid {0} no main thread found, discarded all threads, "
767 "we're in a no-thread state!",
768 GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000769 }
770
Kate Stoneb9c1b512016-09-06 20:57:50 +0000771 // Tell coordinator about about the "new" (since exec) stopped main thread.
772 ThreadWasCreated(*main_thread_sp);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000773
Kate Stoneb9c1b512016-09-06 20:57:50 +0000774 // Let our delegate know we have just exec'd.
775 NotifyDidExec();
776
777 // If we have a main thread, indicate we are stopped.
778 assert(main_thread_sp && "exec called during ptraced process but no main "
779 "thread metadata tracked");
780
781 // Let the process know we're stopped.
782 StopRunningThreads(main_thread_sp->GetID());
783
784 break;
785 }
786
787 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): {
788 // The inferior process or one of its threads is about to exit.
789 // We don't want to do anything with the thread so we just resume it. In
790 // case we
791 // want to implement "break on thread exit" functionality, we would need to
792 // stop
793 // here.
794
795 unsigned long data = 0;
796 if (GetEventMessage(thread.GetID(), &data).Fail())
797 data = -1;
798
Pavel Labatha6321a82017-01-19 15:26:04 +0000799 LLDB_LOG(log,
800 "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
801 "WIFSIGNALED={2}, pid = {3}, main_thread = {4}",
802 data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(),
803 is_main_thread);
Todd Fialaaf245d12014-06-30 21:05:18 +0000804
Pavel Labath3508fc82017-06-19 12:47:50 +0000805 if (is_main_thread)
806 SetExitStatus(WaitStatus::Decode(data), true);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000807
808 StateType state = thread.GetState();
809 if (!StateIsRunningState(state)) {
810 // Due to a kernel bug, we may sometimes get this stop after the inferior
811 // gets a
812 // SIGKILL. This confuses our state tracking logic in ResumeThread(),
813 // since normally,
814 // we should not be receiving any ptrace events while the inferior is
815 // stopped. This
816 // makes sure that the inferior is resumed and exits normally.
817 state = eStateRunning;
818 }
819 ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
820
821 break;
822 }
823
824 case 0:
825 case TRAP_TRACE: // We receive this on single stepping.
826 case TRAP_HWBKPT: // We receive this on watchpoint hit
827 {
828 // If a watchpoint was hit, report it
829 uint32_t wp_index;
Zachary Turner97206d52017-05-12 04:51:55 +0000830 Status error = thread.GetRegisterContext()->GetWatchpointHitIndex(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000831 wp_index, (uintptr_t)info.si_addr);
Pavel Labatha6321a82017-01-19 15:26:04 +0000832 if (error.Fail())
833 LLDB_LOG(log,
834 "received error while checking for watchpoint hits, pid = "
835 "{0}, error = {1}",
836 thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000837 if (wp_index != LLDB_INVALID_INDEX32) {
838 MonitorWatchpoint(thread, wp_index);
839 break;
840 }
841
Omair Javaidd5ffbad2017-02-24 13:27:31 +0000842 // If a breakpoint was hit, report it
843 uint32_t bp_index;
844 error = thread.GetRegisterContext()->GetHardwareBreakHitIndex(
845 bp_index, (uintptr_t)info.si_addr);
846 if (error.Fail())
847 LLDB_LOG(log, "received error while checking for hardware "
848 "breakpoint hits, pid = {0}, error = {1}",
849 thread.GetID(), error);
850 if (bp_index != LLDB_INVALID_INDEX32) {
851 MonitorBreakpoint(thread);
852 break;
853 }
854
Kate Stoneb9c1b512016-09-06 20:57:50 +0000855 // Otherwise, report step over
856 MonitorTrace(thread);
857 break;
858 }
859
860 case SI_KERNEL:
Mohit K. Bhakkad35799962015-06-18 04:53:18 +0000861#if defined __mips__
Kate Stoneb9c1b512016-09-06 20:57:50 +0000862 // For mips there is no special signal for watchpoint
863 // So we check for watchpoint in kernel trap
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000864 {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000865 // If a watchpoint was hit, report it
866 uint32_t wp_index;
Zachary Turner97206d52017-05-12 04:51:55 +0000867 Status error = thread.GetRegisterContext()->GetWatchpointHitIndex(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000868 wp_index, LLDB_INVALID_ADDRESS);
Pavel Labatha6321a82017-01-19 15:26:04 +0000869 if (error.Fail())
870 LLDB_LOG(log,
871 "received error while checking for watchpoint hits, pid = "
872 "{0}, error = {1}",
873 thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000874 if (wp_index != LLDB_INVALID_INDEX32) {
875 MonitorWatchpoint(thread, wp_index);
876 break;
877 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000878 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000879// NO BREAK
Mohit K. Bhakkad35799962015-06-18 04:53:18 +0000880#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000881 case TRAP_BRKPT:
882 MonitorBreakpoint(thread);
883 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000884
Kate Stoneb9c1b512016-09-06 20:57:50 +0000885 case SIGTRAP:
886 case (SIGTRAP | 0x80):
Pavel Labatha6321a82017-01-19 15:26:04 +0000887 LLDB_LOG(
888 log,
889 "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",
890 info.si_code, GetID(), thread.GetID());
Chaoren Linfa03ad22015-02-03 01:50:42 +0000891
Kate Stoneb9c1b512016-09-06 20:57:50 +0000892 // Ignore these signals until we know more about them.
893 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
894 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000895
Kate Stoneb9c1b512016-09-06 20:57:50 +0000896 default:
Pavel Labatha6321a82017-01-19 15:26:04 +0000897 LLDB_LOG(
898 log,
899 "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",
900 info.si_code, GetID(), thread.GetID());
901 llvm_unreachable("Unexpected SIGTRAP code!");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000902 break;
903 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000904}
905
Kate Stoneb9c1b512016-09-06 20:57:50 +0000906void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000907 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
908 LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000909
Kate Stoneb9c1b512016-09-06 20:57:50 +0000910 // This thread is currently stopped.
911 thread.SetStoppedByTrace();
912
913 StopRunningThreads(thread.GetID());
914}
915
916void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) {
917 Log *log(
918 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
Pavel Labatha6321a82017-01-19 15:26:04 +0000919 LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000920
921 // Mark the thread as stopped at breakpoint.
922 thread.SetStoppedByBreakpoint();
Zachary Turner97206d52017-05-12 04:51:55 +0000923 Status error = FixupBreakpointPCAsNeeded(thread);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000924 if (error.Fail())
Pavel Labatha6321a82017-01-19 15:26:04 +0000925 LLDB_LOG(log, "pid = {0} fixup: {1}", thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000926
927 if (m_threads_stepping_with_breakpoint.find(thread.GetID()) !=
928 m_threads_stepping_with_breakpoint.end())
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000929 thread.SetStoppedByTrace();
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000930
Kate Stoneb9c1b512016-09-06 20:57:50 +0000931 StopRunningThreads(thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000932}
933
Kate Stoneb9c1b512016-09-06 20:57:50 +0000934void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread,
935 uint32_t wp_index) {
936 Log *log(
937 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
Pavel Labatha6321a82017-01-19 15:26:04 +0000938 LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}",
939 thread.GetID(), wp_index);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000940
941 // Mark the thread as stopped at watchpoint.
942 // The address is at (lldb::addr_t)info->si_addr if we need it.
943 thread.SetStoppedByWatchpoint(wp_index);
944
945 // We need to tell all other running threads before we notify the delegate
946 // about this stop.
947 StopRunningThreads(thread.GetID());
948}
949
950void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
951 NativeThreadLinux &thread, bool exited) {
952 const int signo = info.si_signo;
953 const bool is_from_llgs = info.si_pid == getpid();
954
Pavel Labatha6321a82017-01-19 15:26:04 +0000955 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000956
957 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
958 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
959 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
960 //
961 // IOW, user generated signals never generate what we consider to be a
962 // "crash".
963 //
964 // Similarly, ACK signals generated by this monitor.
965
966 // Handle the signal.
Pavel Labatha6321a82017-01-19 15:26:04 +0000967 LLDB_LOG(log,
968 "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
969 "waitpid pid = {4})",
970 Host::GetSignalAsCString(signo), signo, info.si_code,
971 thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000972
Kate Stoneb9c1b512016-09-06 20:57:50 +0000973 // Check for thread stop notification.
974 if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) {
975 // This is a tgkill()-based stop.
Pavel Labatha6321a82017-01-19 15:26:04 +0000976 LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000977
Kate Stoneb9c1b512016-09-06 20:57:50 +0000978 // Check that we're not already marked with a stop reason.
979 // Note this thread really shouldn't already be marked as stopped - if we
Pavel Labatha6321a82017-01-19 15:26:04 +0000980 // were, that would imply that the kernel signaled us with the thread
981 // stopping which we handled and marked as stopped, and that, without an
982 // intervening resume, we received another stop. It is more likely that we
983 // are missing the marking of a run state somewhere if we find that the
984 // thread was marked as stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000985 const StateType thread_state = thread.GetState();
986 if (!StateIsStoppedState(thread_state, false)) {
987 // An inferior thread has stopped because of a SIGSTOP we have sent it.
988 // Generally, these are not important stops and we don't want to report
Pavel Labatha6321a82017-01-19 15:26:04 +0000989 // them as they are just used to stop other threads when one thread (the
990 // one with the *real* stop reason) hits a breakpoint (watchpoint,
991 // etc...). However, in the case of an asynchronous Interrupt(), this *is*
992 // the real stop reason, so we leave the signal intact if this is the
993 // thread that was chosen as the triggering thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000994 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
995 if (m_pending_notification_tid == thread.GetID())
996 thread.SetStoppedBySignal(SIGSTOP, &info);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000997 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000998 thread.SetStoppedWithNoReason();
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000999
Kate Stoneb9c1b512016-09-06 20:57:50 +00001000 SetCurrentThreadID(thread.GetID());
1001 SignalIfAllThreadsStopped();
1002 } else {
1003 // We can end up here if stop was initiated by LLGS but by this time a
1004 // thread stop has occurred - maybe initiated by another event.
Zachary Turner97206d52017-05-12 04:51:55 +00001005 Status error = ResumeThread(thread, thread.GetState(), 0);
Pavel Labatha6321a82017-01-19 15:26:04 +00001006 if (error.Fail())
1007 LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(),
1008 error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001009 }
1010 } else {
Pavel Labatha6321a82017-01-19 15:26:04 +00001011 LLDB_LOG(log,
1012 "pid {0} tid {1}, thread was already marked as a stopped "
1013 "state (state={2}), leaving stop signal as is",
Pavel Labath8198db32017-01-24 11:48:25 +00001014 GetID(), thread.GetID(), thread_state);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001015 SignalIfAllThreadsStopped();
Todd Fialaaf245d12014-06-30 21:05:18 +00001016 }
1017
Kate Stoneb9c1b512016-09-06 20:57:50 +00001018 // Done handling.
1019 return;
1020 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001021
Pavel Labath4a705e72017-02-24 09:29:14 +00001022 // Check if debugger should stop at this signal or just ignore it
1023 // and resume the inferior.
1024 if (m_signals_to_ignore.find(signo) != m_signals_to_ignore.end()) {
1025 ResumeThread(thread, thread.GetState(), signo);
1026 return;
1027 }
1028
Kate Stoneb9c1b512016-09-06 20:57:50 +00001029 // This thread is stopped.
Pavel Labatha6321a82017-01-19 15:26:04 +00001030 LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001031 thread.SetStoppedBySignal(signo, &info);
1032
1033 // Send a stop to the debugger after we get all other threads to stop.
1034 StopRunningThreads(thread.GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +00001035}
1036
Tamas Berghammere7708682015-04-22 10:00:23 +00001037namespace {
1038
Kate Stoneb9c1b512016-09-06 20:57:50 +00001039struct EmulatorBaton {
1040 NativeProcessLinux *m_process;
1041 NativeRegisterContext *m_reg_context;
Tamas Berghammere7708682015-04-22 10:00:23 +00001042
Kate Stoneb9c1b512016-09-06 20:57:50 +00001043 // eRegisterKindDWARF -> RegsiterValue
1044 std::unordered_map<uint32_t, RegisterValue> m_register_values;
Pavel Labath6648fcc2015-04-27 09:21:14 +00001045
Kate Stoneb9c1b512016-09-06 20:57:50 +00001046 EmulatorBaton(NativeProcessLinux *process, NativeRegisterContext *reg_context)
1047 : m_process(process), m_reg_context(reg_context) {}
Tamas Berghammere7708682015-04-22 10:00:23 +00001048};
1049
1050} // anonymous namespace
1051
Kate Stoneb9c1b512016-09-06 20:57:50 +00001052static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
1053 const EmulateInstruction::Context &context,
1054 lldb::addr_t addr, void *dst, size_t length) {
1055 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
Tamas Berghammere7708682015-04-22 10:00:23 +00001056
Kate Stoneb9c1b512016-09-06 20:57:50 +00001057 size_t bytes_read;
1058 emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
1059 return bytes_read;
Tamas Berghammere7708682015-04-22 10:00:23 +00001060}
1061
Kate Stoneb9c1b512016-09-06 20:57:50 +00001062static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
1063 const RegisterInfo *reg_info,
1064 RegisterValue &reg_value) {
1065 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
Tamas Berghammere7708682015-04-22 10:00:23 +00001066
Kate Stoneb9c1b512016-09-06 20:57:50 +00001067 auto it = emulator_baton->m_register_values.find(
1068 reg_info->kinds[eRegisterKindDWARF]);
1069 if (it != emulator_baton->m_register_values.end()) {
1070 reg_value = it->second;
1071 return true;
1072 }
1073
1074 // The emulator only fill in the dwarf regsiter numbers (and in some case
1075 // the generic register numbers). Get the full register info from the
1076 // register context based on the dwarf register numbers.
1077 const RegisterInfo *full_reg_info =
1078 emulator_baton->m_reg_context->GetRegisterInfo(
1079 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
1080
Zachary Turner97206d52017-05-12 04:51:55 +00001081 Status error =
Kate Stoneb9c1b512016-09-06 20:57:50 +00001082 emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
1083 if (error.Success())
1084 return true;
1085
1086 return false;
1087}
1088
1089static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
1090 const EmulateInstruction::Context &context,
1091 const RegisterInfo *reg_info,
1092 const RegisterValue &reg_value) {
1093 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
1094 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
1095 reg_value;
1096 return true;
1097}
1098
1099static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
1100 const EmulateInstruction::Context &context,
1101 lldb::addr_t addr, const void *dst,
1102 size_t length) {
1103 return length;
1104}
1105
1106static lldb::addr_t ReadFlags(NativeRegisterContext *regsiter_context) {
1107 const RegisterInfo *flags_info = regsiter_context->GetRegisterInfo(
1108 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1109 return regsiter_context->ReadRegisterAsUnsigned(flags_info,
1110 LLDB_INVALID_ADDRESS);
1111}
1112
Zachary Turner97206d52017-05-12 04:51:55 +00001113Status
1114NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadLinux &thread) {
1115 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001116 NativeRegisterContextSP register_context_sp = thread.GetRegisterContext();
1117
1118 std::unique_ptr<EmulateInstruction> emulator_ap(
1119 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying,
1120 nullptr));
1121
1122 if (emulator_ap == nullptr)
Zachary Turner97206d52017-05-12 04:51:55 +00001123 return Status("Instruction emulator not found!");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001124
1125 EmulatorBaton baton(this, register_context_sp.get());
1126 emulator_ap->SetBaton(&baton);
1127 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
1128 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
1129 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
1130 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
1131
1132 if (!emulator_ap->ReadInstruction())
Zachary Turner97206d52017-05-12 04:51:55 +00001133 return Status("Read instruction failed!");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001134
1135 bool emulation_result =
1136 emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
1137
1138 const RegisterInfo *reg_info_pc = register_context_sp->GetRegisterInfo(
1139 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1140 const RegisterInfo *reg_info_flags = register_context_sp->GetRegisterInfo(
1141 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1142
1143 auto pc_it =
1144 baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1145 auto flags_it =
1146 baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
1147
1148 lldb::addr_t next_pc;
1149 lldb::addr_t next_flags;
1150 if (emulation_result) {
1151 assert(pc_it != baton.m_register_values.end() &&
1152 "Emulation was successfull but PC wasn't updated");
1153 next_pc = pc_it->second.GetAsUInt64();
1154
1155 if (flags_it != baton.m_register_values.end())
1156 next_flags = flags_it->second.GetAsUInt64();
1157 else
1158 next_flags = ReadFlags(register_context_sp.get());
1159 } else if (pc_it == baton.m_register_values.end()) {
1160 // Emulate instruction failed and it haven't changed PC. Advance PC
1161 // with the size of the current opcode because the emulation of all
1162 // PC modifying instruction should be successful. The failure most
1163 // likely caused by a not supported instruction which don't modify PC.
1164 next_pc =
1165 register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
1166 next_flags = ReadFlags(register_context_sp.get());
1167 } else {
1168 // The instruction emulation failed after it modified the PC. It is an
1169 // unknown error where we can't continue because the next instruction is
1170 // modifying the PC but we don't know how.
Zachary Turner97206d52017-05-12 04:51:55 +00001171 return Status("Instruction emulation failed unexpectedly.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001172 }
1173
1174 if (m_arch.GetMachine() == llvm::Triple::arm) {
1175 if (next_flags & 0x20) {
1176 // Thumb mode
1177 error = SetSoftwareBreakpoint(next_pc, 2);
1178 } else {
1179 // Arm mode
1180 error = SetSoftwareBreakpoint(next_pc, 4);
Pavel Labath6648fcc2015-04-27 09:21:14 +00001181 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001182 } else if (m_arch.GetMachine() == llvm::Triple::mips64 ||
1183 m_arch.GetMachine() == llvm::Triple::mips64el ||
1184 m_arch.GetMachine() == llvm::Triple::mips ||
1185 m_arch.GetMachine() == llvm::Triple::mipsel)
1186 error = SetSoftwareBreakpoint(next_pc, 4);
1187 else {
1188 // No size hint is given for the next breakpoint
1189 error = SetSoftwareBreakpoint(next_pc, 0);
1190 }
Pavel Labath6648fcc2015-04-27 09:21:14 +00001191
Pavel Labath42eb6902016-10-26 11:13:56 +00001192 // If setting the breakpoint fails because next_pc is out of
1193 // the address space, ignore it and let the debugee segfault.
1194 if (error.GetError() == EIO || error.GetError() == EFAULT) {
Zachary Turner97206d52017-05-12 04:51:55 +00001195 return Status();
Pavel Labath42eb6902016-10-26 11:13:56 +00001196 } else if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001197 return error;
Tamas Berghammere7708682015-04-22 10:00:23 +00001198
Kate Stoneb9c1b512016-09-06 20:57:50 +00001199 m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001200
Zachary Turner97206d52017-05-12 04:51:55 +00001201 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001202}
1203
1204bool NativeProcessLinux::SupportHardwareSingleStepping() const {
1205 if (m_arch.GetMachine() == llvm::Triple::arm ||
1206 m_arch.GetMachine() == llvm::Triple::mips64 ||
1207 m_arch.GetMachine() == llvm::Triple::mips64el ||
1208 m_arch.GetMachine() == llvm::Triple::mips ||
1209 m_arch.GetMachine() == llvm::Triple::mipsel)
Pavel Labath6648fcc2015-04-27 09:21:14 +00001210 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001211 return true;
Tamas Berghammere7708682015-04-22 10:00:23 +00001212}
1213
Zachary Turner97206d52017-05-12 04:51:55 +00001214Status NativeProcessLinux::Resume(const ResumeActionList &resume_actions) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001215 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1216 LLDB_LOG(log, "pid {0}", GetID());
Tamas Berghammere7708682015-04-22 10:00:23 +00001217
Kate Stoneb9c1b512016-09-06 20:57:50 +00001218 bool software_single_step = !SupportHardwareSingleStepping();
Tamas Berghammere7708682015-04-22 10:00:23 +00001219
Kate Stoneb9c1b512016-09-06 20:57:50 +00001220 if (software_single_step) {
1221 for (auto thread_sp : m_threads) {
1222 assert(thread_sp && "thread list should not contain NULL threads");
Tamas Berghammere7708682015-04-22 10:00:23 +00001223
Kate Stoneb9c1b512016-09-06 20:57:50 +00001224 const ResumeAction *const action =
1225 resume_actions.GetActionForThread(thread_sp->GetID(), true);
1226 if (action == nullptr)
1227 continue;
Tamas Berghammere7708682015-04-22 10:00:23 +00001228
Kate Stoneb9c1b512016-09-06 20:57:50 +00001229 if (action->state == eStateStepping) {
Zachary Turner97206d52017-05-12 04:51:55 +00001230 Status error = SetupSoftwareSingleStepping(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001231 static_cast<NativeThreadLinux &>(*thread_sp));
1232 if (error.Fail())
1233 return error;
1234 }
Tamas Berghammere7708682015-04-22 10:00:23 +00001235 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001236 }
1237
1238 for (auto thread_sp : m_threads) {
1239 assert(thread_sp && "thread list should not contain NULL threads");
1240
1241 const ResumeAction *const action =
1242 resume_actions.GetActionForThread(thread_sp->GetID(), true);
1243
1244 if (action == nullptr) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001245 LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
1246 thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001247 continue;
Tamas Berghammere7708682015-04-22 10:00:23 +00001248 }
1249
Pavel Labatha6321a82017-01-19 15:26:04 +00001250 LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}",
Pavel Labath8198db32017-01-24 11:48:25 +00001251 action->state, GetID(), thread_sp->GetID());
Tamas Berghammere7708682015-04-22 10:00:23 +00001252
Kate Stoneb9c1b512016-09-06 20:57:50 +00001253 switch (action->state) {
1254 case eStateRunning:
1255 case eStateStepping: {
1256 // Run the thread, possibly feeding it the signal.
1257 const int signo = action->signal;
1258 ResumeThread(static_cast<NativeThreadLinux &>(*thread_sp), action->state,
1259 signo);
1260 break;
1261 }
Tamas Berghammere7708682015-04-22 10:00:23 +00001262
Kate Stoneb9c1b512016-09-06 20:57:50 +00001263 case eStateSuspended:
1264 case eStateStopped:
Pavel Labatha6321a82017-01-19 15:26:04 +00001265 llvm_unreachable("Unexpected state");
Tamas Berghammere7708682015-04-22 10:00:23 +00001266
Kate Stoneb9c1b512016-09-06 20:57:50 +00001267 default:
Zachary Turner97206d52017-05-12 04:51:55 +00001268 return Status("NativeProcessLinux::%s (): unexpected state %s specified "
1269 "for pid %" PRIu64 ", tid %" PRIu64,
1270 __FUNCTION__, StateAsCString(action->state), GetID(),
1271 thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001272 }
1273 }
1274
Zachary Turner97206d52017-05-12 04:51:55 +00001275 return Status();
Tamas Berghammere7708682015-04-22 10:00:23 +00001276}
1277
Zachary Turner97206d52017-05-12 04:51:55 +00001278Status NativeProcessLinux::Halt() {
1279 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001280
1281 if (kill(GetID(), SIGSTOP) != 0)
1282 error.SetErrorToErrno();
1283
1284 return error;
Tamas Berghammere7708682015-04-22 10:00:23 +00001285}
1286
Zachary Turner97206d52017-05-12 04:51:55 +00001287Status NativeProcessLinux::Detach() {
1288 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001289
1290 // Stop monitoring the inferior.
1291 m_sigchld_handle.reset();
1292
1293 // Tell ptrace to detach from the process.
1294 if (GetID() == LLDB_INVALID_PROCESS_ID)
1295 return error;
1296
1297 for (auto thread_sp : m_threads) {
Zachary Turner97206d52017-05-12 04:51:55 +00001298 Status e = Detach(thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001299 if (e.Fail())
1300 error =
1301 e; // Save the error, but still attempt to detach from other threads.
1302 }
1303
Ravitheja Addepally99e37692017-06-28 07:58:31 +00001304 m_processor_trace_monitor.clear();
1305 m_pt_proces_trace_id = LLDB_INVALID_UID;
1306
Kate Stoneb9c1b512016-09-06 20:57:50 +00001307 return error;
1308}
1309
Zachary Turner97206d52017-05-12 04:51:55 +00001310Status NativeProcessLinux::Signal(int signo) {
1311 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001312
Pavel Labatha6321a82017-01-19 15:26:04 +00001313 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1314 LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo,
1315 Host::GetSignalAsCString(signo), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001316
1317 if (kill(GetID(), signo))
1318 error.SetErrorToErrno();
1319
1320 return error;
1321}
1322
Zachary Turner97206d52017-05-12 04:51:55 +00001323Status NativeProcessLinux::Interrupt() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001324 // Pick a running thread (or if none, a not-dead stopped thread) as
1325 // the chosen thread that will be the stop-reason thread.
Pavel Labatha6321a82017-01-19 15:26:04 +00001326 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001327
1328 NativeThreadProtocolSP running_thread_sp;
1329 NativeThreadProtocolSP stopped_thread_sp;
1330
Pavel Labatha6321a82017-01-19 15:26:04 +00001331 LLDB_LOG(log, "selecting running thread for interrupt target");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001332 for (auto thread_sp : m_threads) {
1333 // The thread shouldn't be null but lets just cover that here.
1334 if (!thread_sp)
1335 continue;
1336
1337 // If we have a running or stepping thread, we'll call that the
1338 // target of the interrupt.
1339 const auto thread_state = thread_sp->GetState();
1340 if (thread_state == eStateRunning || thread_state == eStateStepping) {
1341 running_thread_sp = thread_sp;
1342 break;
1343 } else if (!stopped_thread_sp && StateIsStoppedState(thread_state, true)) {
1344 // Remember the first non-dead stopped thread. We'll use that as a backup
1345 // if there are no running threads.
1346 stopped_thread_sp = thread_sp;
1347 }
1348 }
1349
1350 if (!running_thread_sp && !stopped_thread_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00001351 Status error("found no running/stepping or live stopped threads as target "
1352 "for interrupt");
Pavel Labatha6321a82017-01-19 15:26:04 +00001353 LLDB_LOG(log, "skipping due to error: {0}", error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001354
1355 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001356 }
1357
1358 NativeThreadProtocolSP deferred_signal_thread_sp =
1359 running_thread_sp ? running_thread_sp : stopped_thread_sp;
1360
Pavel Labatha6321a82017-01-19 15:26:04 +00001361 LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(),
1362 running_thread_sp ? "running" : "stopped",
1363 deferred_signal_thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001364
1365 StopRunningThreads(deferred_signal_thread_sp->GetID());
1366
Zachary Turner97206d52017-05-12 04:51:55 +00001367 return Status();
Todd Fialaaf245d12014-06-30 21:05:18 +00001368}
1369
Zachary Turner97206d52017-05-12 04:51:55 +00001370Status NativeProcessLinux::Kill() {
Pavel Labatha6321a82017-01-19 15:26:04 +00001371 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1372 LLDB_LOG(log, "pid {0}", GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +00001373
Zachary Turner97206d52017-05-12 04:51:55 +00001374 Status error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001375
Kate Stoneb9c1b512016-09-06 20:57:50 +00001376 switch (m_state) {
1377 case StateType::eStateInvalid:
1378 case StateType::eStateExited:
1379 case StateType::eStateCrashed:
1380 case StateType::eStateDetached:
1381 case StateType::eStateUnloaded:
1382 // Nothing to do - the process is already dead.
Pavel Labatha6321a82017-01-19 15:26:04 +00001383 LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
Pavel Labath8198db32017-01-24 11:48:25 +00001384 m_state);
Todd Fialaaf245d12014-06-30 21:05:18 +00001385 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001386
Kate Stoneb9c1b512016-09-06 20:57:50 +00001387 case StateType::eStateConnected:
1388 case StateType::eStateAttaching:
1389 case StateType::eStateLaunching:
1390 case StateType::eStateStopped:
1391 case StateType::eStateRunning:
1392 case StateType::eStateStepping:
1393 case StateType::eStateSuspended:
1394 // We can try to kill a process in these states.
1395 break;
1396 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001397
Kate Stoneb9c1b512016-09-06 20:57:50 +00001398 if (kill(GetID(), SIGKILL) != 0) {
1399 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +00001400 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001401 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001402
Kate Stoneb9c1b512016-09-06 20:57:50 +00001403 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001404}
1405
Zachary Turner97206d52017-05-12 04:51:55 +00001406static Status
Pavel Labath15930862017-03-21 13:49:45 +00001407ParseMemoryRegionInfoFromProcMapsLine(llvm::StringRef &maps_line,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001408 MemoryRegionInfo &memory_region_info) {
1409 memory_region_info.Clear();
Todd Fialaaf245d12014-06-30 21:05:18 +00001410
Pavel Labath15930862017-03-21 13:49:45 +00001411 StringExtractor line_extractor(maps_line);
Todd Fialaaf245d12014-06-30 21:05:18 +00001412
Kate Stoneb9c1b512016-09-06 20:57:50 +00001413 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode
1414 // pathname
1415 // perms: rwxp (letter is present if set, '-' if not, final character is
1416 // p=private, s=shared).
Todd Fialaaf245d12014-06-30 21:05:18 +00001417
Kate Stoneb9c1b512016-09-06 20:57:50 +00001418 // Parse out the starting address
1419 lldb::addr_t start_address = line_extractor.GetHexMaxU64(false, 0);
Todd Fialaaf245d12014-06-30 21:05:18 +00001420
Kate Stoneb9c1b512016-09-06 20:57:50 +00001421 // Parse out hyphen separating start and end address from range.
1422 if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != '-'))
Zachary Turner97206d52017-05-12 04:51:55 +00001423 return Status(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001424 "malformed /proc/{pid}/maps entry, missing dash between address range");
Todd Fialaaf245d12014-06-30 21:05:18 +00001425
Kate Stoneb9c1b512016-09-06 20:57:50 +00001426 // Parse out the ending address
1427 lldb::addr_t end_address = line_extractor.GetHexMaxU64(false, start_address);
Todd Fialaaf245d12014-06-30 21:05:18 +00001428
Kate Stoneb9c1b512016-09-06 20:57:50 +00001429 // Parse out the space after the address.
1430 if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != ' '))
Zachary Turner97206d52017-05-12 04:51:55 +00001431 return Status(
1432 "malformed /proc/{pid}/maps entry, missing space after range");
Todd Fialaaf245d12014-06-30 21:05:18 +00001433
Kate Stoneb9c1b512016-09-06 20:57:50 +00001434 // Save the range.
1435 memory_region_info.GetRange().SetRangeBase(start_address);
1436 memory_region_info.GetRange().SetRangeEnd(end_address);
Todd Fialaaf245d12014-06-30 21:05:18 +00001437
Kate Stoneb9c1b512016-09-06 20:57:50 +00001438 // Any memory region in /proc/{pid}/maps is by definition mapped into the
1439 // process.
1440 memory_region_info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
Howard Hellyerad007562016-07-07 08:21:28 +00001441
Kate Stoneb9c1b512016-09-06 20:57:50 +00001442 // Parse out each permission entry.
1443 if (line_extractor.GetBytesLeft() < 4)
Zachary Turner97206d52017-05-12 04:51:55 +00001444 return Status("malformed /proc/{pid}/maps entry, missing some portion of "
1445 "permissions");
Todd Fialaaf245d12014-06-30 21:05:18 +00001446
Kate Stoneb9c1b512016-09-06 20:57:50 +00001447 // Handle read permission.
1448 const char read_perm_char = line_extractor.GetChar();
1449 if (read_perm_char == 'r')
1450 memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eYes);
1451 else if (read_perm_char == '-')
1452 memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1453 else
Zachary Turner97206d52017-05-12 04:51:55 +00001454 return Status("unexpected /proc/{pid}/maps read permission char");
Todd Fialaaf245d12014-06-30 21:05:18 +00001455
Kate Stoneb9c1b512016-09-06 20:57:50 +00001456 // Handle write permission.
1457 const char write_perm_char = line_extractor.GetChar();
1458 if (write_perm_char == 'w')
1459 memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eYes);
1460 else if (write_perm_char == '-')
1461 memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1462 else
Zachary Turner97206d52017-05-12 04:51:55 +00001463 return Status("unexpected /proc/{pid}/maps write permission char");
Todd Fialaaf245d12014-06-30 21:05:18 +00001464
Kate Stoneb9c1b512016-09-06 20:57:50 +00001465 // Handle execute permission.
1466 const char exec_perm_char = line_extractor.GetChar();
1467 if (exec_perm_char == 'x')
1468 memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes);
1469 else if (exec_perm_char == '-')
1470 memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1471 else
Zachary Turner97206d52017-05-12 04:51:55 +00001472 return Status("unexpected /proc/{pid}/maps exec permission char");
Todd Fialaaf245d12014-06-30 21:05:18 +00001473
Kate Stoneb9c1b512016-09-06 20:57:50 +00001474 line_extractor.GetChar(); // Read the private bit
1475 line_extractor.SkipSpaces(); // Skip the separator
1476 line_extractor.GetHexMaxU64(false, 0); // Read the offset
1477 line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1478 line_extractor.GetChar(); // Read the device id separator
1479 line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1480 line_extractor.SkipSpaces(); // Skip the separator
1481 line_extractor.GetU64(0, 10); // Read the inode number
Tamas Berghammerd7d69f82016-07-22 12:55:35 +00001482
Kate Stoneb9c1b512016-09-06 20:57:50 +00001483 line_extractor.SkipSpaces();
1484 const char *name = line_extractor.Peek();
1485 if (name)
1486 memory_region_info.SetName(name);
Tamas Berghammerd7d69f82016-07-22 12:55:35 +00001487
Zachary Turner97206d52017-05-12 04:51:55 +00001488 return Status();
Todd Fialaaf245d12014-06-30 21:05:18 +00001489}
1490
Zachary Turner97206d52017-05-12 04:51:55 +00001491Status NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr,
1492 MemoryRegionInfo &range_info) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001493 // FIXME review that the final memory region returned extends to the end of
1494 // the virtual address space,
1495 // with no perms if it is not mapped.
Todd Fialaaf245d12014-06-30 21:05:18 +00001496
Kate Stoneb9c1b512016-09-06 20:57:50 +00001497 // Use an approach that reads memory regions from /proc/{pid}/maps.
1498 // Assume proc maps entries are in ascending order.
1499 // FIXME assert if we find differently.
Todd Fialaaf245d12014-06-30 21:05:18 +00001500
Kate Stoneb9c1b512016-09-06 20:57:50 +00001501 if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
1502 // We're done.
Zachary Turner97206d52017-05-12 04:51:55 +00001503 return Status("unsupported");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001504 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001505
Zachary Turner97206d52017-05-12 04:51:55 +00001506 Status error = PopulateMemoryRegionCache();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001507 if (error.Fail()) {
1508 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001509 }
1510
1511 lldb::addr_t prev_base_address = 0;
1512
1513 // FIXME start by finding the last region that is <= target address using
1514 // binary search. Data is sorted.
1515 // There can be a ton of regions on pthreads apps with lots of threads.
1516 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1517 ++it) {
Tamas Berghammera6f57952017-01-03 16:29:43 +00001518 MemoryRegionInfo &proc_entry_info = it->first;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001519
1520 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1521 assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
1522 "descending /proc/pid/maps entries detected, unexpected");
1523 prev_base_address = proc_entry_info.GetRange().GetRangeBase();
Hafiz Abid Qadeerb1554312017-01-20 10:24:03 +00001524 UNUSED_IF_ASSERT_DISABLED(prev_base_address);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001525
1526 // If the target address comes before this entry, indicate distance to next
1527 // region.
1528 if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1529 range_info.GetRange().SetRangeBase(load_addr);
1530 range_info.GetRange().SetByteSize(
1531 proc_entry_info.GetRange().GetRangeBase() - load_addr);
1532 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1533 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1534 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1535 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1536
1537 return error;
1538 } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1539 // The target address is within the memory region we're processing here.
1540 range_info = proc_entry_info;
1541 return error;
1542 }
1543
1544 // The target memory address comes somewhere after the region we just
1545 // parsed.
1546 }
1547
1548 // If we made it here, we didn't find an entry that contained the given
1549 // address. Return the
1550 // load_addr as start and the amount of bytes betwwen load address and the end
1551 // of the memory as
1552 // size.
1553 range_info.GetRange().SetRangeBase(load_addr);
1554 range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
1555 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1556 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1557 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1558 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1559 return error;
1560}
1561
Zachary Turner97206d52017-05-12 04:51:55 +00001562Status NativeProcessLinux::PopulateMemoryRegionCache() {
Pavel Labatha6321a82017-01-19 15:26:04 +00001563 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Tamas Berghammera6f57952017-01-03 16:29:43 +00001564
1565 // If our cache is empty, pull the latest. There should always be at least
1566 // one memory region if memory region handling is supported.
1567 if (!m_mem_region_cache.empty()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001568 LLDB_LOG(log, "reusing {0} cached memory region entries",
1569 m_mem_region_cache.size());
Zachary Turner97206d52017-05-12 04:51:55 +00001570 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001571 }
1572
Pavel Labath15930862017-03-21 13:49:45 +00001573 auto BufferOrError = getProcFile(GetID(), "maps");
1574 if (!BufferOrError) {
Tamas Berghammera6f57952017-01-03 16:29:43 +00001575 m_supports_mem_region = LazyBool::eLazyBoolNo;
Pavel Labath15930862017-03-21 13:49:45 +00001576 return BufferOrError.getError();
1577 }
1578 StringRef Rest = BufferOrError.get()->getBuffer();
1579 while (! Rest.empty()) {
1580 StringRef Line;
1581 std::tie(Line, Rest) = Rest.split('\n');
1582 MemoryRegionInfo info;
Zachary Turner97206d52017-05-12 04:51:55 +00001583 const Status parse_error =
1584 ParseMemoryRegionInfoFromProcMapsLine(Line, info);
Pavel Labath15930862017-03-21 13:49:45 +00001585 if (parse_error.Fail()) {
1586 LLDB_LOG(log, "failed to parse proc maps line '{0}': {1}", Line,
1587 parse_error);
1588 m_supports_mem_region = LazyBool::eLazyBoolNo;
1589 return parse_error;
1590 }
1591 m_mem_region_cache.emplace_back(
1592 info, FileSpec(info.GetName().GetCString(), true));
1593 }
1594
1595 if (m_mem_region_cache.empty()) {
Tamas Berghammera6f57952017-01-03 16:29:43 +00001596 // No entries after attempting to read them. This shouldn't happen if
1597 // /proc/{pid}/maps is supported. Assume we don't support map entries
1598 // via procfs.
Pavel Labath15930862017-03-21 13:49:45 +00001599 m_supports_mem_region = LazyBool::eLazyBoolNo;
Pavel Labatha6321a82017-01-19 15:26:04 +00001600 LLDB_LOG(log,
1601 "failed to find any procfs maps entries, assuming no support "
1602 "for memory region metadata retrieval");
Zachary Turner97206d52017-05-12 04:51:55 +00001603 return Status("not supported");
Tamas Berghammera6f57952017-01-03 16:29:43 +00001604 }
1605
Pavel Labatha6321a82017-01-19 15:26:04 +00001606 LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps",
1607 m_mem_region_cache.size(), GetID());
Tamas Berghammera6f57952017-01-03 16:29:43 +00001608
1609 // We support memory retrieval, remember that.
1610 m_supports_mem_region = LazyBool::eLazyBoolYes;
Zachary Turner97206d52017-05-12 04:51:55 +00001611 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00001612}
1613
Kate Stoneb9c1b512016-09-06 20:57:50 +00001614void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001615 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1616 LLDB_LOG(log, "newBumpId={0}", newBumpId);
1617 LLDB_LOG(log, "clearing {0} entries from memory region cache",
1618 m_mem_region_cache.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001619 m_mem_region_cache.clear();
1620}
1621
Zachary Turner97206d52017-05-12 04:51:55 +00001622Status NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions,
1623 lldb::addr_t &addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001624// FIXME implementing this requires the equivalent of
1625// InferiorCallPOSIX::InferiorCallMmap, which depends on
1626// functional ThreadPlans working with Native*Protocol.
1627#if 1
Zachary Turner97206d52017-05-12 04:51:55 +00001628 return Status("not implemented yet");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001629#else
1630 addr = LLDB_INVALID_ADDRESS;
1631
1632 unsigned prot = 0;
1633 if (permissions & lldb::ePermissionsReadable)
1634 prot |= eMmapProtRead;
1635 if (permissions & lldb::ePermissionsWritable)
1636 prot |= eMmapProtWrite;
1637 if (permissions & lldb::ePermissionsExecutable)
1638 prot |= eMmapProtExec;
1639
1640 // TODO implement this directly in NativeProcessLinux
1641 // (and lift to NativeProcessPOSIX if/when that class is
1642 // refactored out).
1643 if (InferiorCallMmap(this, addr, 0, size, prot,
1644 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
1645 m_addr_to_mmap_size[addr] = size;
Zachary Turner97206d52017-05-12 04:51:55 +00001646 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001647 } else {
1648 addr = LLDB_INVALID_ADDRESS;
Zachary Turner97206d52017-05-12 04:51:55 +00001649 return Status("unable to allocate %" PRIu64
1650 " bytes of memory with permissions %s",
1651 size, GetPermissionsAsCString(permissions));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001652 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001653#endif
1654}
1655
Zachary Turner97206d52017-05-12 04:51:55 +00001656Status NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001657 // FIXME see comments in AllocateMemory - required lower-level
1658 // bits not in place yet (ThreadPlans)
Zachary Turner97206d52017-05-12 04:51:55 +00001659 return Status("not implemented");
Todd Fialaaf245d12014-06-30 21:05:18 +00001660}
1661
Kate Stoneb9c1b512016-09-06 20:57:50 +00001662lldb::addr_t NativeProcessLinux::GetSharedLibraryInfoAddress() {
1663 // punt on this for now
1664 return LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00001665}
1666
Kate Stoneb9c1b512016-09-06 20:57:50 +00001667size_t NativeProcessLinux::UpdateThreads() {
1668 // The NativeProcessLinux monitoring threads are always up to date
1669 // with respect to thread state and they keep the thread list
1670 // populated properly. All this method needs to do is return the
1671 // thread count.
1672 return m_threads.size();
Todd Fialaaf245d12014-06-30 21:05:18 +00001673}
1674
Kate Stoneb9c1b512016-09-06 20:57:50 +00001675bool NativeProcessLinux::GetArchitecture(ArchSpec &arch) const {
1676 arch = m_arch;
1677 return true;
Todd Fialaaf245d12014-06-30 21:05:18 +00001678}
1679
Zachary Turner97206d52017-05-12 04:51:55 +00001680Status NativeProcessLinux::GetSoftwareBreakpointPCOffset(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001681 uint32_t &actual_opcode_size) {
1682 // FIXME put this behind a breakpoint protocol class that can be
1683 // set per architecture. Need ARM, MIPS support here.
1684 static const uint8_t g_i386_opcode[] = {0xCC};
1685 static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
Todd Fialaaf245d12014-06-30 21:05:18 +00001686
Kate Stoneb9c1b512016-09-06 20:57:50 +00001687 switch (m_arch.GetMachine()) {
1688 case llvm::Triple::x86:
1689 case llvm::Triple::x86_64:
1690 actual_opcode_size = static_cast<uint32_t>(sizeof(g_i386_opcode));
Zachary Turner97206d52017-05-12 04:51:55 +00001691 return Status();
Todd Fialaaf245d12014-06-30 21:05:18 +00001692
Kate Stoneb9c1b512016-09-06 20:57:50 +00001693 case llvm::Triple::systemz:
1694 actual_opcode_size = static_cast<uint32_t>(sizeof(g_s390x_opcode));
Zachary Turner97206d52017-05-12 04:51:55 +00001695 return Status();
Ulrich Weigandbb00d0b2016-04-14 14:28:34 +00001696
Kate Stoneb9c1b512016-09-06 20:57:50 +00001697 case llvm::Triple::arm:
1698 case llvm::Triple::aarch64:
1699 case llvm::Triple::mips64:
1700 case llvm::Triple::mips64el:
1701 case llvm::Triple::mips:
1702 case llvm::Triple::mipsel:
1703 // On these architectures the PC don't get updated for breakpoint hits
1704 actual_opcode_size = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00001705 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001706
1707 default:
1708 assert(false && "CPU type not supported!");
Zachary Turner97206d52017-05-12 04:51:55 +00001709 return Status("CPU type not supported");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001710 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001711}
1712
Zachary Turner97206d52017-05-12 04:51:55 +00001713Status NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,
1714 bool hardware) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001715 if (hardware)
Omair Javaidd5ffbad2017-02-24 13:27:31 +00001716 return SetHardwareBreakpoint(addr, size);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001717 else
1718 return SetSoftwareBreakpoint(addr, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00001719}
1720
Zachary Turner97206d52017-05-12 04:51:55 +00001721Status NativeProcessLinux::RemoveBreakpoint(lldb::addr_t addr, bool hardware) {
Omair Javaidd5ffbad2017-02-24 13:27:31 +00001722 if (hardware)
1723 return RemoveHardwareBreakpoint(addr);
1724 else
1725 return NativeProcessProtocol::RemoveBreakpoint(addr);
1726}
1727
Zachary Turner97206d52017-05-12 04:51:55 +00001728Status NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001729 size_t trap_opcode_size_hint, size_t &actual_opcode_size,
1730 const uint8_t *&trap_opcode_bytes) {
1731 // FIXME put this behind a breakpoint protocol class that can be set per
1732 // architecture. Need MIPS support here.
1733 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};
1734 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1735 // linux kernel does otherwise.
1736 static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1737 static const uint8_t g_i386_opcode[] = {0xCC};
1738 static const uint8_t g_mips64_opcode[] = {0x00, 0x00, 0x00, 0x0d};
1739 static const uint8_t g_mips64el_opcode[] = {0x0d, 0x00, 0x00, 0x00};
1740 static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
1741 static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
Todd Fialaaf245d12014-06-30 21:05:18 +00001742
Kate Stoneb9c1b512016-09-06 20:57:50 +00001743 switch (m_arch.GetMachine()) {
1744 case llvm::Triple::aarch64:
1745 trap_opcode_bytes = g_aarch64_opcode;
1746 actual_opcode_size = sizeof(g_aarch64_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001747 return Status();
Todd Fiala2afc5962014-08-21 16:42:31 +00001748
Kate Stoneb9c1b512016-09-06 20:57:50 +00001749 case llvm::Triple::arm:
1750 switch (trap_opcode_size_hint) {
1751 case 2:
1752 trap_opcode_bytes = g_thumb_breakpoint_opcode;
1753 actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001754 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001755 case 4:
1756 trap_opcode_bytes = g_arm_breakpoint_opcode;
1757 actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001758 return Status();
Todd Fialaaf245d12014-06-30 21:05:18 +00001759 default:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001760 assert(false && "Unrecognised trap opcode size hint!");
Zachary Turner97206d52017-05-12 04:51:55 +00001761 return Status("Unrecognised trap opcode size hint!");
Todd Fialaaf245d12014-06-30 21:05:18 +00001762 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001763
1764 case llvm::Triple::x86:
1765 case llvm::Triple::x86_64:
1766 trap_opcode_bytes = g_i386_opcode;
1767 actual_opcode_size = sizeof(g_i386_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001768 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001769
1770 case llvm::Triple::mips:
1771 case llvm::Triple::mips64:
1772 trap_opcode_bytes = g_mips64_opcode;
1773 actual_opcode_size = sizeof(g_mips64_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001774 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001775
1776 case llvm::Triple::mipsel:
1777 case llvm::Triple::mips64el:
1778 trap_opcode_bytes = g_mips64el_opcode;
1779 actual_opcode_size = sizeof(g_mips64el_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001780 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001781
1782 case llvm::Triple::systemz:
1783 trap_opcode_bytes = g_s390x_opcode;
1784 actual_opcode_size = sizeof(g_s390x_opcode);
Zachary Turner97206d52017-05-12 04:51:55 +00001785 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001786
1787 default:
1788 assert(false && "CPU type not supported!");
Zachary Turner97206d52017-05-12 04:51:55 +00001789 return Status("CPU type not supported");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001790 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001791}
1792
1793#if 0
1794ProcessMessage::CrashReason
1795NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
1796{
1797 ProcessMessage::CrashReason reason;
1798 assert(info->si_signo == SIGSEGV);
1799
1800 reason = ProcessMessage::eInvalidCrashReason;
1801
1802 switch (info->si_code)
1803 {
1804 default:
1805 assert(false && "unexpected si_code for SIGSEGV");
1806 break;
1807 case SI_KERNEL:
1808 // Linux will occasionally send spurious SI_KERNEL codes.
1809 // (this is poorly documented in sigaction)
1810 // One way to get this is via unaligned SIMD loads.
1811 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
1812 break;
1813 case SEGV_MAPERR:
1814 reason = ProcessMessage::eInvalidAddress;
1815 break;
1816 case SEGV_ACCERR:
1817 reason = ProcessMessage::ePrivilegedAddress;
1818 break;
1819 }
1820
1821 return reason;
1822}
1823#endif
1824
Todd Fialaaf245d12014-06-30 21:05:18 +00001825#if 0
1826ProcessMessage::CrashReason
1827NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
1828{
1829 ProcessMessage::CrashReason reason;
1830 assert(info->si_signo == SIGILL);
1831
1832 reason = ProcessMessage::eInvalidCrashReason;
1833
1834 switch (info->si_code)
1835 {
1836 default:
1837 assert(false && "unexpected si_code for SIGILL");
1838 break;
1839 case ILL_ILLOPC:
1840 reason = ProcessMessage::eIllegalOpcode;
1841 break;
1842 case ILL_ILLOPN:
1843 reason = ProcessMessage::eIllegalOperand;
1844 break;
1845 case ILL_ILLADR:
1846 reason = ProcessMessage::eIllegalAddressingMode;
1847 break;
1848 case ILL_ILLTRP:
1849 reason = ProcessMessage::eIllegalTrap;
1850 break;
1851 case ILL_PRVOPC:
1852 reason = ProcessMessage::ePrivilegedOpcode;
1853 break;
1854 case ILL_PRVREG:
1855 reason = ProcessMessage::ePrivilegedRegister;
1856 break;
1857 case ILL_COPROC:
1858 reason = ProcessMessage::eCoprocessorError;
1859 break;
1860 case ILL_BADSTK:
1861 reason = ProcessMessage::eInternalStackError;
1862 break;
1863 }
1864
1865 return reason;
1866}
1867#endif
1868
1869#if 0
1870ProcessMessage::CrashReason
1871NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
1872{
1873 ProcessMessage::CrashReason reason;
1874 assert(info->si_signo == SIGFPE);
1875
1876 reason = ProcessMessage::eInvalidCrashReason;
1877
1878 switch (info->si_code)
1879 {
1880 default:
1881 assert(false && "unexpected si_code for SIGFPE");
1882 break;
1883 case FPE_INTDIV:
1884 reason = ProcessMessage::eIntegerDivideByZero;
1885 break;
1886 case FPE_INTOVF:
1887 reason = ProcessMessage::eIntegerOverflow;
1888 break;
1889 case FPE_FLTDIV:
1890 reason = ProcessMessage::eFloatDivideByZero;
1891 break;
1892 case FPE_FLTOVF:
1893 reason = ProcessMessage::eFloatOverflow;
1894 break;
1895 case FPE_FLTUND:
1896 reason = ProcessMessage::eFloatUnderflow;
1897 break;
1898 case FPE_FLTRES:
1899 reason = ProcessMessage::eFloatInexactResult;
1900 break;
1901 case FPE_FLTINV:
1902 reason = ProcessMessage::eFloatInvalidOperation;
1903 break;
1904 case FPE_FLTSUB:
1905 reason = ProcessMessage::eFloatSubscriptRange;
1906 break;
1907 }
1908
1909 return reason;
1910}
1911#endif
1912
1913#if 0
1914ProcessMessage::CrashReason
1915NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
1916{
1917 ProcessMessage::CrashReason reason;
1918 assert(info->si_signo == SIGBUS);
1919
1920 reason = ProcessMessage::eInvalidCrashReason;
1921
1922 switch (info->si_code)
1923 {
1924 default:
1925 assert(false && "unexpected si_code for SIGBUS");
1926 break;
1927 case BUS_ADRALN:
1928 reason = ProcessMessage::eIllegalAlignment;
1929 break;
1930 case BUS_ADRERR:
1931 reason = ProcessMessage::eIllegalAddress;
1932 break;
1933 case BUS_OBJERR:
1934 reason = ProcessMessage::eHardwareError;
1935 break;
1936 }
1937
1938 return reason;
1939}
1940#endif
1941
Zachary Turner97206d52017-05-12 04:51:55 +00001942Status NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
1943 size_t &bytes_read) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001944 if (ProcessVmReadvSupported()) {
1945 // The process_vm_readv path is about 50 times faster than ptrace api. We
1946 // want to use
1947 // this syscall if it is supported.
Pavel Labathdf7c6992015-06-17 18:38:49 +00001948
Kate Stoneb9c1b512016-09-06 20:57:50 +00001949 const ::pid_t pid = GetID();
Pavel Labathdf7c6992015-06-17 18:38:49 +00001950
Kate Stoneb9c1b512016-09-06 20:57:50 +00001951 struct iovec local_iov, remote_iov;
1952 local_iov.iov_base = buf;
1953 local_iov.iov_len = size;
1954 remote_iov.iov_base = reinterpret_cast<void *>(addr);
1955 remote_iov.iov_len = size;
Pavel Labathdf7c6992015-06-17 18:38:49 +00001956
Kate Stoneb9c1b512016-09-06 20:57:50 +00001957 bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
1958 const bool success = bytes_read == size;
Pavel Labathdf7c6992015-06-17 18:38:49 +00001959
Pavel Labatha6321a82017-01-19 15:26:04 +00001960 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1961 LLDB_LOG(log,
1962 "using process_vm_readv to read {0} bytes from inferior "
1963 "address {1:x}: {2}",
Pavel Labath10c41f32017-06-06 14:06:17 +00001964 size, addr, success ? "Success" : llvm::sys::StrError(errno));
Pavel Labath19cbe962015-07-21 13:20:32 +00001965
Kate Stoneb9c1b512016-09-06 20:57:50 +00001966 if (success)
Zachary Turner97206d52017-05-12 04:51:55 +00001967 return Status();
Pavel Labatha6321a82017-01-19 15:26:04 +00001968 // else the call failed for some reason, let's retry the read using ptrace
1969 // api.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001970 }
Pavel Labath19cbe962015-07-21 13:20:32 +00001971
Kate Stoneb9c1b512016-09-06 20:57:50 +00001972 unsigned char *dst = static_cast<unsigned char *>(buf);
1973 size_t remainder;
1974 long data;
Pavel Labath19cbe962015-07-21 13:20:32 +00001975
Pavel Labatha6321a82017-01-19 15:26:04 +00001976 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1977 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
Pavel Labath19cbe962015-07-21 13:20:32 +00001978
Kate Stoneb9c1b512016-09-06 20:57:50 +00001979 for (bytes_read = 0; bytes_read < size; bytes_read += remainder) {
Zachary Turner97206d52017-05-12 04:51:55 +00001980 Status error = NativeProcessLinux::PtraceWrapper(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001981 PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data);
Pavel Labatha6321a82017-01-19 15:26:04 +00001982 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001983 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001984
1985 remainder = size - bytes_read;
1986 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
1987
1988 // Copy the data into our buffer
1989 memcpy(dst, &data, remainder);
1990
Pavel Labatha6321a82017-01-19 15:26:04 +00001991 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001992 addr += k_ptrace_word_size;
1993 dst += k_ptrace_word_size;
1994 }
Zachary Turner97206d52017-05-12 04:51:55 +00001995 return Status();
Todd Fialaaf245d12014-06-30 21:05:18 +00001996}
1997
Zachary Turner97206d52017-05-12 04:51:55 +00001998Status NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf,
1999 size_t size,
2000 size_t &bytes_read) {
2001 Status error = ReadMemory(addr, buf, size, bytes_read);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002002 if (error.Fail())
Pavel Labath19cbe962015-07-21 13:20:32 +00002003 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002004 return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00002005}
2006
Zachary Turner97206d52017-05-12 04:51:55 +00002007Status NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,
2008 size_t size, size_t &bytes_written) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002009 const unsigned char *src = static_cast<const unsigned char *>(buf);
2010 size_t remainder;
Zachary Turner97206d52017-05-12 04:51:55 +00002011 Status error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002012
Pavel Labatha6321a82017-01-19 15:26:04 +00002013 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
2014 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00002015
Kate Stoneb9c1b512016-09-06 20:57:50 +00002016 for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
2017 remainder = size - bytes_written;
2018 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
Chaoren Lin97ccc292015-02-03 01:51:12 +00002019
Kate Stoneb9c1b512016-09-06 20:57:50 +00002020 if (remainder == k_ptrace_word_size) {
2021 unsigned long data = 0;
2022 memcpy(&data, src, k_ptrace_word_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00002023
Pavel Labatha6321a82017-01-19 15:26:04 +00002024 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002025 error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(),
2026 (void *)addr, (void *)data);
Pavel Labatha6321a82017-01-19 15:26:04 +00002027 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00002028 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002029 } else {
2030 unsigned char buff[8];
2031 size_t bytes_read;
2032 error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
Pavel Labatha6321a82017-01-19 15:26:04 +00002033 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00002034 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002035
2036 memcpy(buff, src, remainder);
2037
2038 size_t bytes_written_rec;
2039 error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
Pavel Labatha6321a82017-01-19 15:26:04 +00002040 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00002041 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002042
Pavel Labatha6321a82017-01-19 15:26:04 +00002043 LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src,
2044 *(unsigned long *)buff);
Todd Fialaaf245d12014-06-30 21:05:18 +00002045 }
2046
Kate Stoneb9c1b512016-09-06 20:57:50 +00002047 addr += k_ptrace_word_size;
2048 src += k_ptrace_word_size;
2049 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002050 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002051}
2052
Zachary Turner97206d52017-05-12 04:51:55 +00002053Status NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002054 return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
2055}
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002056
Zachary Turner97206d52017-05-12 04:51:55 +00002057Status NativeProcessLinux::GetEventMessage(lldb::tid_t tid,
2058 unsigned long *message) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002059 return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
2060}
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002061
Zachary Turner97206d52017-05-12 04:51:55 +00002062Status NativeProcessLinux::Detach(lldb::tid_t tid) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002063 if (tid == LLDB_INVALID_THREAD_ID)
Zachary Turner97206d52017-05-12 04:51:55 +00002064 return Status();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002065
Kate Stoneb9c1b512016-09-06 20:57:50 +00002066 return PtraceWrapper(PTRACE_DETACH, tid);
2067}
2068
2069bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {
2070 for (auto thread_sp : m_threads) {
2071 assert(thread_sp && "thread list should not contain NULL threads");
2072 if (thread_sp->GetID() == thread_id) {
2073 // We have this thread.
2074 return true;
Todd Fialaaf245d12014-06-30 21:05:18 +00002075 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002076 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002077
Kate Stoneb9c1b512016-09-06 20:57:50 +00002078 // We don't have this thread.
2079 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00002080}
2081
Kate Stoneb9c1b512016-09-06 20:57:50 +00002082bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002083 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2084 LLDB_LOG(log, "tid: {0})", thread_id);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002085
2086 bool found = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002087 for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
2088 if (*it && ((*it)->GetID() == thread_id)) {
2089 m_threads.erase(it);
2090 found = true;
2091 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00002092 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002093 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002094
Ravitheja Addepally99e37692017-06-28 07:58:31 +00002095 if (found)
2096 StopTracingForThread(thread_id);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002097 SignalIfAllThreadsStopped();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002098 return found;
Todd Fialaaf245d12014-06-30 21:05:18 +00002099}
2100
Kate Stoneb9c1b512016-09-06 20:57:50 +00002101NativeThreadLinuxSP NativeProcessLinux::AddThread(lldb::tid_t thread_id) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002102 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
2103 LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
Todd Fialaaf245d12014-06-30 21:05:18 +00002104
Kate Stoneb9c1b512016-09-06 20:57:50 +00002105 assert(!HasThreadNoLock(thread_id) &&
2106 "attempted to add a thread by id that already exists");
Todd Fialaaf245d12014-06-30 21:05:18 +00002107
Kate Stoneb9c1b512016-09-06 20:57:50 +00002108 // If this is the first thread, save it as the current thread
2109 if (m_threads.empty())
2110 SetCurrentThreadID(thread_id);
Todd Fialaaf245d12014-06-30 21:05:18 +00002111
Kate Stoneb9c1b512016-09-06 20:57:50 +00002112 auto thread_sp = std::make_shared<NativeThreadLinux>(this, thread_id);
2113 m_threads.push_back(thread_sp);
Ravitheja Addepally99e37692017-06-28 07:58:31 +00002114
2115 if (m_pt_proces_trace_id != LLDB_INVALID_UID) {
2116 auto traceMonitor = ProcessorTraceMonitor::Create(
2117 GetID(), thread_id, m_pt_process_trace_config, true);
2118 if (traceMonitor) {
2119 m_pt_traced_thread_group.insert(thread_id);
2120 m_processor_trace_monitor.insert(
2121 std::make_pair(thread_id, std::move(*traceMonitor)));
2122 } else {
2123 LLDB_LOG(log, "failed to start trace on thread {0}", thread_id);
2124 Status error(traceMonitor.takeError());
2125 LLDB_LOG(log, "error {0}", error);
2126 }
2127 }
2128
Kate Stoneb9c1b512016-09-06 20:57:50 +00002129 return thread_sp;
2130}
Todd Fialaaf245d12014-06-30 21:05:18 +00002131
Zachary Turner97206d52017-05-12 04:51:55 +00002132Status
2133NativeProcessLinux::FixupBreakpointPCAsNeeded(NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002134 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_BREAKPOINTS));
Todd Fialaaf245d12014-06-30 21:05:18 +00002135
Zachary Turner97206d52017-05-12 04:51:55 +00002136 Status error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002137
Kate Stoneb9c1b512016-09-06 20:57:50 +00002138 // Find out the size of a breakpoint (might depend on where we are in the
2139 // code).
2140 NativeRegisterContextSP context_sp = thread.GetRegisterContext();
2141 if (!context_sp) {
2142 error.SetErrorString("cannot get a NativeRegisterContext for the thread");
Pavel Labatha6321a82017-01-19 15:26:04 +00002143 LLDB_LOG(log, "failed: {0}", error);
Todd Fialaaf245d12014-06-30 21:05:18 +00002144 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002145 }
Chaoren Linfa03ad22015-02-03 01:50:42 +00002146
Kate Stoneb9c1b512016-09-06 20:57:50 +00002147 uint32_t breakpoint_size = 0;
2148 error = GetSoftwareBreakpointPCOffset(breakpoint_size);
2149 if (error.Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002150 LLDB_LOG(log, "GetBreakpointSize() failed: {0}", error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002151 return error;
Pavel Labatha6321a82017-01-19 15:26:04 +00002152 } else
2153 LLDB_LOG(log, "breakpoint size: {0}", breakpoint_size);
Pavel Labathc0765592015-05-06 10:46:34 +00002154
Kate Stoneb9c1b512016-09-06 20:57:50 +00002155 // First try probing for a breakpoint at a software breakpoint location: PC -
2156 // breakpoint size.
2157 const lldb::addr_t initial_pc_addr =
2158 context_sp->GetPCfromBreakpointLocation();
2159 lldb::addr_t breakpoint_addr = initial_pc_addr;
2160 if (breakpoint_size > 0) {
2161 // Do not allow breakpoint probe to wrap around.
2162 if (breakpoint_addr >= breakpoint_size)
2163 breakpoint_addr -= breakpoint_size;
2164 }
2165
2166 // Check if we stopped because of a breakpoint.
2167 NativeBreakpointSP breakpoint_sp;
2168 error = m_breakpoint_list.GetBreakpoint(breakpoint_addr, breakpoint_sp);
2169 if (!error.Success() || !breakpoint_sp) {
2170 // We didn't find one at a software probe location. Nothing to do.
Pavel Labatha6321a82017-01-19 15:26:04 +00002171 LLDB_LOG(log,
2172 "pid {0} no lldb breakpoint found at current pc with "
2173 "adjustment: {1}",
2174 GetID(), breakpoint_addr);
Zachary Turner97206d52017-05-12 04:51:55 +00002175 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002176 }
2177
2178 // If the breakpoint is not a software breakpoint, nothing to do.
2179 if (!breakpoint_sp->IsSoftwareBreakpoint()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002180 LLDB_LOG(
2181 log,
2182 "pid {0} breakpoint found at {1:x}, not software, nothing to adjust",
2183 GetID(), breakpoint_addr);
Zachary Turner97206d52017-05-12 04:51:55 +00002184 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002185 }
2186
2187 //
2188 // We have a software breakpoint and need to adjust the PC.
2189 //
2190
2191 // Sanity check.
2192 if (breakpoint_size == 0) {
2193 // Nothing to do! How did we get here?
Pavel Labatha6321a82017-01-19 15:26:04 +00002194 LLDB_LOG(log,
2195 "pid {0} breakpoint found at {1:x}, it is software, but the "
2196 "size is zero, nothing to do (unexpected)",
2197 GetID(), breakpoint_addr);
Zachary Turner97206d52017-05-12 04:51:55 +00002198 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002199 }
2200
2201 // Change the program counter.
Pavel Labatha6321a82017-01-19 15:26:04 +00002202 LLDB_LOG(log, "pid {0} tid {1}: changing PC from {2:x} to {3:x}", GetID(),
2203 thread.GetID(), initial_pc_addr, breakpoint_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002204
2205 error = context_sp->SetPC(breakpoint_addr);
2206 if (error.Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002207 LLDB_LOG(log, "pid {0} tid {1}: failed to set PC: {2}", GetID(),
2208 thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002209 return error;
2210 }
2211
2212 return error;
2213}
2214
Zachary Turner97206d52017-05-12 04:51:55 +00002215Status NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,
2216 FileSpec &file_spec) {
2217 Status error = PopulateMemoryRegionCache();
Tamas Berghammera6f57952017-01-03 16:29:43 +00002218 if (error.Fail())
2219 return error;
2220
Kate Stoneb9c1b512016-09-06 20:57:50 +00002221 FileSpec module_file_spec(module_path, true);
2222
Kate Stoneb9c1b512016-09-06 20:57:50 +00002223 file_spec.Clear();
Tamas Berghammera6f57952017-01-03 16:29:43 +00002224 for (const auto &it : m_mem_region_cache) {
2225 if (it.second.GetFilename() == module_file_spec.GetFilename()) {
2226 file_spec = it.second;
Zachary Turner97206d52017-05-12 04:51:55 +00002227 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00002228 }
2229 }
Zachary Turner97206d52017-05-12 04:51:55 +00002230 return Status("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
2231 module_file_spec.GetFilename().AsCString(), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002232}
2233
Zachary Turner97206d52017-05-12 04:51:55 +00002234Status NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
2235 lldb::addr_t &load_addr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002236 load_addr = LLDB_INVALID_ADDRESS;
Zachary Turner97206d52017-05-12 04:51:55 +00002237 Status error = PopulateMemoryRegionCache();
Tamas Berghammera6f57952017-01-03 16:29:43 +00002238 if (error.Fail())
2239 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002240
Tamas Berghammera6f57952017-01-03 16:29:43 +00002241 FileSpec file(file_name, false);
2242 for (const auto &it : m_mem_region_cache) {
2243 if (it.second == file) {
2244 load_addr = it.first.GetRange().GetRangeBase();
Zachary Turner97206d52017-05-12 04:51:55 +00002245 return Status();
Tamas Berghammera6f57952017-01-03 16:29:43 +00002246 }
2247 }
Zachary Turner97206d52017-05-12 04:51:55 +00002248 return Status("No load address found for specified file.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002249}
2250
2251NativeThreadLinuxSP NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {
2252 return std::static_pointer_cast<NativeThreadLinux>(
2253 NativeProcessProtocol::GetThreadByID(tid));
2254}
2255
Zachary Turner97206d52017-05-12 04:51:55 +00002256Status NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,
2257 lldb::StateType state, int signo) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002258 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2259 LLDB_LOG(log, "tid: {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002260
2261 // Before we do the resume below, first check if we have a pending
2262 // stop notification that is currently waiting for
2263 // all threads to stop. This is potentially a buggy situation since
2264 // we're ostensibly waiting for threads to stop before we send out the
2265 // pending notification, and here we are resuming one before we send
2266 // out the pending stop notification.
Pavel Labatha6321a82017-01-19 15:26:04 +00002267 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
2268 LLDB_LOG(log,
2269 "about to resume tid {0} per explicit request but we have a "
2270 "pending stop notification (tid {1}) that is actively "
2271 "waiting for this thread to stop. Valid sequence of events?",
2272 thread.GetID(), m_pending_notification_tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002273 }
2274
2275 // Request a resume. We expect this to be synchronous and the system
2276 // to reflect it is running after this completes.
2277 switch (state) {
2278 case eStateRunning: {
2279 const auto resume_result = thread.Resume(signo);
2280 if (resume_result.Success())
2281 SetState(eStateRunning, true);
2282 return resume_result;
2283 }
2284 case eStateStepping: {
2285 const auto step_result = thread.SingleStep(signo);
2286 if (step_result.Success())
2287 SetState(eStateRunning, true);
2288 return step_result;
2289 }
2290 default:
Pavel Labath8198db32017-01-24 11:48:25 +00002291 LLDB_LOG(log, "Unhandled state {0}.", state);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002292 llvm_unreachable("Unhandled state for resume");
2293 }
Pavel Labathc0765592015-05-06 10:46:34 +00002294}
2295
2296//===----------------------------------------------------------------------===//
2297
Kate Stoneb9c1b512016-09-06 20:57:50 +00002298void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002299 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2300 LLDB_LOG(log, "about to process event: (triggering_tid: {0})",
2301 triggering_tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002302
2303 m_pending_notification_tid = triggering_tid;
2304
2305 // Request a stop for all the thread stops that need to be stopped
2306 // and are not already known to be stopped.
2307 for (const auto &thread_sp : m_threads) {
2308 if (StateIsRunningState(thread_sp->GetState()))
2309 static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
2310 }
2311
2312 SignalIfAllThreadsStopped();
Pavel Labatha6321a82017-01-19 15:26:04 +00002313 LLDB_LOG(log, "event processing done");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002314}
2315
2316void NativeProcessLinux::SignalIfAllThreadsStopped() {
2317 if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
2318 return; // No pending notification. Nothing to do.
2319
2320 for (const auto &thread_sp : m_threads) {
2321 if (StateIsRunningState(thread_sp->GetState()))
2322 return; // Some threads are still running. Don't signal yet.
2323 }
2324
2325 // We have a pending notification and all threads have stopped.
2326 Log *log(
2327 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
2328
2329 // Clear any temporary breakpoints we used to implement software single
2330 // stepping.
2331 for (const auto &thread_info : m_threads_stepping_with_breakpoint) {
Zachary Turner97206d52017-05-12 04:51:55 +00002332 Status error = RemoveBreakpoint(thread_info.second);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002333 if (error.Fail())
Pavel Labatha6321a82017-01-19 15:26:04 +00002334 LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}",
2335 thread_info.first, error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002336 }
2337 m_threads_stepping_with_breakpoint.clear();
2338
2339 // Notify the delegate about the stop
2340 SetCurrentThreadID(m_pending_notification_tid);
2341 SetState(StateType::eStateStopped, true);
2342 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
2343}
2344
2345void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002346 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2347 LLDB_LOG(log, "tid: {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002348
2349 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID &&
2350 StateIsRunningState(thread.GetState())) {
2351 // We will need to wait for this new thread to stop as well before firing
2352 // the
2353 // notification.
2354 thread.RequestStop();
2355 }
2356}
2357
2358void NativeProcessLinux::SigchldHandler() {
Pavel Labatha6321a82017-01-19 15:26:04 +00002359 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002360 // Process all pending waitpid notifications.
2361 while (true) {
2362 int status = -1;
Pavel Labathc1a6b122017-07-03 09:25:55 +00002363 ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, -1, &status,
2364 __WALL | __WNOTHREAD | WNOHANG);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002365
2366 if (wait_pid == 0)
2367 break; // We are done.
2368
2369 if (wait_pid == -1) {
Zachary Turner97206d52017-05-12 04:51:55 +00002370 Status error(errno, eErrorTypePOSIX);
Pavel Labatha6321a82017-01-19 15:26:04 +00002371 LLDB_LOG(log, "waitpid (-1, &status, _) failed: {0}", error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002372 break;
Pavel Labathc0765592015-05-06 10:46:34 +00002373 }
2374
Pavel Labath3508fc82017-06-19 12:47:50 +00002375 WaitStatus wait_status = WaitStatus::Decode(status);
2376 bool exited = wait_status.type == WaitStatus::Exit ||
2377 (wait_status.type == WaitStatus::Signal &&
2378 wait_pid == static_cast<::pid_t>(GetID()));
Pavel Labathc0765592015-05-06 10:46:34 +00002379
Pavel Labath3508fc82017-06-19 12:47:50 +00002380 LLDB_LOG(
2381 log,
2382 "waitpid (-1, &status, _) => pid = {0}, status = {1}, exited = {2}",
2383 wait_pid, wait_status, exited);
Pavel Labathc0765592015-05-06 10:46:34 +00002384
Pavel Labath3508fc82017-06-19 12:47:50 +00002385 MonitorCallback(wait_pid, exited, wait_status);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002386 }
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002387}
2388
2389// Wrapper for ptrace to catch errors and log calls.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002390// Note that ptrace sets errno on error because -1 can be a valid result (i.e.
2391// for PTRACE_PEEK*)
Zachary Turner97206d52017-05-12 04:51:55 +00002392Status NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
2393 void *data, size_t data_size,
2394 long *result) {
2395 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002396 long int ret;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002397
Kate Stoneb9c1b512016-09-06 20:57:50 +00002398 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002399
Kate Stoneb9c1b512016-09-06 20:57:50 +00002400 PtraceDisplayBytes(req, data, data_size);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002401
Kate Stoneb9c1b512016-09-06 20:57:50 +00002402 errno = 0;
2403 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
2404 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2405 *(unsigned int *)addr, data);
2406 else
2407 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2408 addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002409
Kate Stoneb9c1b512016-09-06 20:57:50 +00002410 if (ret == -1)
2411 error.SetErrorToErrno();
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002412
Kate Stoneb9c1b512016-09-06 20:57:50 +00002413 if (result)
2414 *result = ret;
Pavel Labath4a9babb2015-06-30 17:04:49 +00002415
Pavel Labath28096202017-02-17 16:09:10 +00002416 LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data,
2417 data_size, ret);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002418
Kate Stoneb9c1b512016-09-06 20:57:50 +00002419 PtraceDisplayBytes(req, data, data_size);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002420
Pavel Labatha6321a82017-01-19 15:26:04 +00002421 if (error.Fail())
2422 LLDB_LOG(log, "ptrace() failed: {0}", error);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002423
Kate Stoneb9c1b512016-09-06 20:57:50 +00002424 return error;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002425}
Ravitheja Addepally99e37692017-06-28 07:58:31 +00002426
2427llvm::Expected<ProcessorTraceMonitor &>
2428NativeProcessLinux::LookupProcessorTraceInstance(lldb::user_id_t traceid,
2429 lldb::tid_t thread) {
2430 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2431 if (thread == LLDB_INVALID_THREAD_ID && traceid == m_pt_proces_trace_id) {
2432 LLDB_LOG(log, "thread not specified: {0}", traceid);
2433 return Status("tracing not active thread not specified").ToError();
2434 }
2435
2436 for (auto& iter : m_processor_trace_monitor) {
2437 if (traceid == iter.second->GetTraceID() &&
2438 (thread == iter.first || thread == LLDB_INVALID_THREAD_ID))
2439 return *(iter.second);
2440 }
2441
2442 LLDB_LOG(log, "traceid not being traced: {0}", traceid);
2443 return Status("tracing not active for this thread").ToError();
2444}
2445
2446Status NativeProcessLinux::GetMetaData(lldb::user_id_t traceid,
2447 lldb::tid_t thread,
2448 llvm::MutableArrayRef<uint8_t> &buffer,
2449 size_t offset) {
2450 TraceOptions trace_options;
2451 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2452 Status error;
2453
2454 LLDB_LOG(log, "traceid {0}", traceid);
2455
2456 auto perf_monitor = LookupProcessorTraceInstance(traceid, thread);
2457 if (!perf_monitor) {
2458 LLDB_LOG(log, "traceid not being traced: {0}", traceid);
2459 buffer = buffer.slice(buffer.size());
2460 error = perf_monitor.takeError();
2461 return error;
2462 }
2463 return (*perf_monitor).ReadPerfTraceData(buffer, offset);
2464}
2465
2466Status NativeProcessLinux::GetData(lldb::user_id_t traceid, lldb::tid_t thread,
2467 llvm::MutableArrayRef<uint8_t> &buffer,
2468 size_t offset) {
2469 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2470 Status error;
2471
2472 LLDB_LOG(log, "traceid {0}", traceid);
2473
2474 auto perf_monitor = LookupProcessorTraceInstance(traceid, thread);
2475 if (!perf_monitor) {
2476 LLDB_LOG(log, "traceid not being traced: {0}", traceid);
2477 buffer = buffer.slice(buffer.size());
2478 error = perf_monitor.takeError();
2479 return error;
2480 }
2481 return (*perf_monitor).ReadPerfTraceAux(buffer, offset);
2482}
2483
2484Status NativeProcessLinux::GetTraceConfig(lldb::user_id_t traceid,
2485 TraceOptions &config) {
2486 Status error;
2487 if (config.getThreadID() == LLDB_INVALID_THREAD_ID &&
2488 m_pt_proces_trace_id == traceid) {
2489 if (m_pt_proces_trace_id == LLDB_INVALID_UID) {
2490 error.SetErrorString("tracing not active for this process");
2491 return error;
2492 }
2493 config = m_pt_process_trace_config;
2494 } else {
2495 auto perf_monitor =
2496 LookupProcessorTraceInstance(traceid, config.getThreadID());
2497 if (!perf_monitor) {
2498 error = perf_monitor.takeError();
2499 return error;
2500 }
2501 error = (*perf_monitor).GetTraceConfig(config);
2502 }
2503 return error;
2504}
2505
2506lldb::user_id_t
2507NativeProcessLinux::StartTraceGroup(const TraceOptions &config,
2508 Status &error) {
2509
2510 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2511 if (config.getType() != TraceType::eTraceTypeProcessorTrace)
2512 return LLDB_INVALID_UID;
2513
2514 if (m_pt_proces_trace_id != LLDB_INVALID_UID) {
2515 error.SetErrorString("tracing already active on this process");
2516 return m_pt_proces_trace_id;
2517 }
2518
2519 for (const auto &thread_sp : m_threads) {
2520 if (auto traceInstance = ProcessorTraceMonitor::Create(
2521 GetID(), thread_sp->GetID(), config, true)) {
2522 m_pt_traced_thread_group.insert(thread_sp->GetID());
2523 m_processor_trace_monitor.insert(
2524 std::make_pair(thread_sp->GetID(), std::move(*traceInstance)));
2525 }
2526 }
2527
2528 m_pt_process_trace_config = config;
2529 error = ProcessorTraceMonitor::GetCPUType(m_pt_process_trace_config);
2530
2531 // Trace on Complete process will have traceid of 0
2532 m_pt_proces_trace_id = 0;
2533
2534 LLDB_LOG(log, "Process Trace ID {0}", m_pt_proces_trace_id);
2535 return m_pt_proces_trace_id;
2536}
2537
2538lldb::user_id_t NativeProcessLinux::StartTrace(const TraceOptions &config,
2539 Status &error) {
2540 if (config.getType() != TraceType::eTraceTypeProcessorTrace)
2541 return NativeProcessProtocol::StartTrace(config, error);
2542
2543 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2544
2545 lldb::tid_t threadid = config.getThreadID();
2546
2547 if (threadid == LLDB_INVALID_THREAD_ID)
2548 return StartTraceGroup(config, error);
2549
2550 auto thread_sp = GetThreadByID(threadid);
2551 if (!thread_sp) {
2552 // Thread not tracked by lldb so don't trace.
2553 error.SetErrorString("invalid thread id");
2554 return LLDB_INVALID_UID;
2555 }
2556
2557 const auto &iter = m_processor_trace_monitor.find(threadid);
2558 if (iter != m_processor_trace_monitor.end()) {
2559 LLDB_LOG(log, "Thread already being traced");
2560 error.SetErrorString("tracing already active on this thread");
2561 return LLDB_INVALID_UID;
2562 }
2563
2564 auto traceMonitor =
2565 ProcessorTraceMonitor::Create(GetID(), threadid, config, false);
2566 if (!traceMonitor) {
2567 error = traceMonitor.takeError();
2568 LLDB_LOG(log, "error {0}", error);
2569 return LLDB_INVALID_UID;
2570 }
2571 lldb::user_id_t ret_trace_id = (*traceMonitor)->GetTraceID();
2572 m_processor_trace_monitor.insert(
2573 std::make_pair(threadid, std::move(*traceMonitor)));
2574 return ret_trace_id;
2575}
2576
2577Status NativeProcessLinux::StopTracingForThread(lldb::tid_t thread) {
2578 Status error;
2579 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2580 LLDB_LOG(log, "Thread {0}", thread);
2581
2582 const auto& iter = m_processor_trace_monitor.find(thread);
2583 if (iter == m_processor_trace_monitor.end()) {
2584 error.SetErrorString("tracing not active for this thread");
2585 return error;
2586 }
2587
2588 if (iter->second->GetTraceID() == m_pt_proces_trace_id) {
2589 // traceid maps to the whole process so we have to erase it from the
2590 // thread group.
2591 LLDB_LOG(log, "traceid maps to process");
2592 m_pt_traced_thread_group.erase(thread);
2593 }
2594 m_processor_trace_monitor.erase(iter);
2595
2596 return error;
2597}
2598
2599Status NativeProcessLinux::StopTrace(lldb::user_id_t traceid,
2600 lldb::tid_t thread) {
2601 Status error;
2602
2603 TraceOptions trace_options;
2604 trace_options.setThreadID(thread);
2605 error = NativeProcessLinux::GetTraceConfig(traceid, trace_options);
2606
2607 if (error.Fail())
2608 return error;
2609
2610 switch (trace_options.getType()) {
2611 case lldb::TraceType::eTraceTypeProcessorTrace:
2612 if (traceid == m_pt_proces_trace_id &&
2613 thread == LLDB_INVALID_THREAD_ID)
2614 StopProcessorTracingOnProcess();
2615 else
2616 error = StopProcessorTracingOnThread(traceid, thread);
2617 break;
2618 default:
2619 error.SetErrorString("trace not supported");
2620 break;
2621 }
2622
2623 return error;
2624}
2625
2626void NativeProcessLinux::StopProcessorTracingOnProcess() {
2627 for (auto thread_id_iter : m_pt_traced_thread_group)
2628 m_processor_trace_monitor.erase(thread_id_iter);
2629 m_pt_traced_thread_group.clear();
2630 m_pt_proces_trace_id = LLDB_INVALID_UID;
2631}
2632
2633Status NativeProcessLinux::StopProcessorTracingOnThread(lldb::user_id_t traceid,
2634 lldb::tid_t thread) {
2635 Status error;
2636 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2637
2638 if (thread == LLDB_INVALID_THREAD_ID) {
2639 for (auto& iter : m_processor_trace_monitor) {
2640 if (iter.second->GetTraceID() == traceid) {
2641 // Stopping a trace instance for an individual thread
2642 // hence there will only be one traceid that can match.
2643 m_processor_trace_monitor.erase(iter.first);
2644 return error;
2645 }
2646 LLDB_LOG(log, "Trace ID {0}", iter.second->GetTraceID());
2647 }
2648
2649 LLDB_LOG(log, "Invalid TraceID");
2650 error.SetErrorString("invalid trace id");
2651 return error;
2652 }
2653
2654 // thread is specified so we can use find function on the map.
2655 const auto& iter = m_processor_trace_monitor.find(thread);
2656 if (iter == m_processor_trace_monitor.end()) {
2657 // thread not found in our map.
2658 LLDB_LOG(log, "thread not being traced");
2659 error.SetErrorString("tracing not active for this thread");
2660 return error;
2661 }
2662 if (iter->second->GetTraceID() != traceid) {
2663 // traceid did not match so it has to be invalid.
2664 LLDB_LOG(log, "Invalid TraceID");
2665 error.SetErrorString("invalid trace id");
2666 return error;
2667 }
2668
2669 LLDB_LOG(log, "UID - {0} , Thread -{1}", traceid, thread);
2670
2671 if (traceid == m_pt_proces_trace_id) {
2672 // traceid maps to the whole process so we have to erase it from the
2673 // thread group.
2674 LLDB_LOG(log, "traceid maps to process");
2675 m_pt_traced_thread_group.erase(thread);
2676 }
2677 m_processor_trace_monitor.erase(iter);
2678
2679 return error;
2680}