blob: 1ff8893192f0e877fbce21cdcb876ebcf77d2e65 [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"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000043#include "lldb/Utility/Error.h"
Chaoren Linc16f5dc2015-03-19 23:28:10 +000044#include "lldb/Utility/LLDBAssert.h"
Pavel Labathf805e192015-07-07 10:08:41 +000045#include "lldb/Utility/StringExtractor.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000046
Todd Fialaaf245d12014-06-30 21:05:18 +000047#include "NativeThreadLinux.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000048#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000049#include "ProcFileReader.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000050#include "Procfs.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000051
Pavel Labath4ee1c952017-02-06 18:36:58 +000052#include "llvm/Support/Threading.h"
53
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.",
100 strerror(errno));
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.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000196static Error EnsureFDFlags(int fd, int flags) {
197 Error 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
Kate Stoneb9c1b512016-09-06 20:57:50 +0000217Error 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
Kate Stoneb9c1b512016-09-06 20:57:50 +0000223 Error 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()};
227 if (working_dir &&
228 (!working_dir.ResolvePath() ||
229 working_dir.GetFileType() != FileSpec::eFileTypeDirectory)) {
230 error.SetErrorStringWithFormat("No such file or directory: %s",
231 working_dir.GetCString());
Todd Fialaaf245d12014-06-30 21:05:18 +0000232 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000233 }
234
235 // Create the NativeProcessLinux in launch mode.
236 native_process_sp.reset(new NativeProcessLinux());
237
238 if (!native_process_sp->RegisterNativeDelegate(native_delegate)) {
239 native_process_sp.reset();
240 error.SetErrorStringWithFormat("failed to register the native delegate");
241 return error;
242 }
243
244 error = std::static_pointer_cast<NativeProcessLinux>(native_process_sp)
245 ->LaunchInferior(mainloop, launch_info);
246
247 if (error.Fail()) {
248 native_process_sp.reset();
Pavel Labatha6321a82017-01-19 15:26:04 +0000249 LLDB_LOG(log, "failed to launch process: {0}", error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000250 return error;
251 }
252
253 launch_info.SetProcessID(native_process_sp->GetID());
254
255 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000256}
257
Kate Stoneb9c1b512016-09-06 20:57:50 +0000258Error NativeProcessProtocol::Attach(
259 lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
260 MainLoop &mainloop, NativeProcessProtocolSP &native_process_sp) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000261 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
262 LLDB_LOG(log, "pid = {0:x}", pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000263
Kate Stoneb9c1b512016-09-06 20:57:50 +0000264 // Retrieve the architecture for the running process.
265 ArchSpec process_arch;
266 Error error = ResolveProcessArchitecture(pid, process_arch);
267 if (!error.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +0000268 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000269
270 std::shared_ptr<NativeProcessLinux> native_process_linux_sp(
271 new NativeProcessLinux());
272
273 if (!native_process_linux_sp->RegisterNativeDelegate(native_delegate)) {
274 error.SetErrorStringWithFormat("failed to register the native delegate");
275 return error;
276 }
277
278 native_process_linux_sp->AttachToInferior(mainloop, pid, error);
279 if (!error.Success())
280 return error;
281
282 native_process_sp = native_process_linux_sp;
283 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000284}
285
286// -----------------------------------------------------------------------------
287// Public Instance Methods
288// -----------------------------------------------------------------------------
289
Kate Stoneb9c1b512016-09-06 20:57:50 +0000290NativeProcessLinux::NativeProcessLinux()
291 : NativeProcessProtocol(LLDB_INVALID_PROCESS_ID), m_arch(),
292 m_supports_mem_region(eLazyBoolCalculate), m_mem_region_cache(),
293 m_pending_notification_tid(LLDB_INVALID_THREAD_ID) {}
294
295void NativeProcessLinux::AttachToInferior(MainLoop &mainloop, lldb::pid_t pid,
296 Error &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
Kate Stoneb9c1b512016-09-06 20:57:50 +0000318Error NativeProcessLinux::LaunchInferior(MainLoop &mainloop,
319 ProcessLaunchInfo &launch_info) {
320 Error error;
321 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
406::pid_t NativeProcessLinux::Attach(lldb::pid_t pid, Error &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
Kate Stoneb9c1b512016-09-06 20:57:50 +0000488Error NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid) {
489 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
Kate Stoneb9c1b512016-09-06 20:57:50 +0000507static ExitType convert_pid_status_to_exit_type(int status) {
508 if (WIFEXITED(status))
509 return ExitType::eExitTypeExit;
510 else if (WIFSIGNALED(status))
511 return ExitType::eExitTypeSignal;
512 else if (WIFSTOPPED(status))
513 return ExitType::eExitTypeStop;
514 else {
515 // We don't know what this is.
516 return ExitType::eExitTypeInvalid;
517 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000518}
519
Kate Stoneb9c1b512016-09-06 20:57:50 +0000520static int convert_pid_status_to_return_code(int status) {
521 if (WIFEXITED(status))
522 return WEXITSTATUS(status);
523 else if (WIFSIGNALED(status))
524 return WTERMSIG(status);
525 else if (WIFSTOPPED(status))
526 return WSTOPSIG(status);
527 else {
528 // We don't know what this is.
529 return ExitType::eExitTypeInvalid;
530 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000531}
532
Pavel Labath1107b5a2015-04-17 14:07:49 +0000533// Handles all waitpid events from the inferior process.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000534void NativeProcessLinux::MonitorCallback(lldb::pid_t pid, bool exited,
535 int signal, int status) {
536 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Todd Fialaaf245d12014-06-30 21:05:18 +0000537
Kate Stoneb9c1b512016-09-06 20:57:50 +0000538 // Certain activities differ based on whether the pid is the tid of the main
539 // thread.
540 const bool is_main_thread = (pid == GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000541
Kate Stoneb9c1b512016-09-06 20:57:50 +0000542 // Handle when the thread exits.
543 if (exited) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000544 LLDB_LOG(log, "got exit signal({0}) , tid = {1} ({2} main thread)", signal,
545 pid, is_main_thread ? "is" : "is not");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000546
547 // This is a thread that exited. Ensure we're not tracking it anymore.
548 const bool thread_found = StopTrackingThread(pid);
549
550 if (is_main_thread) {
551 // We only set the exit status and notify the delegate if we haven't
552 // already set the process
553 // state to an exited state. We normally should have received a SIGTRAP |
554 // (PTRACE_EVENT_EXIT << 8)
555 // for the main thread.
556 const bool already_notified = (GetState() == StateType::eStateExited) ||
557 (GetState() == StateType::eStateCrashed);
558 if (!already_notified) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000559 LLDB_LOG(
560 log,
561 "tid = {0} handling main thread exit ({1}), expected exit state "
562 "already set but state was {2} instead, setting exit state now",
563 pid,
564 thread_found ? "stopped tracking thread metadata"
565 : "thread metadata not found",
Pavel Labath8198db32017-01-24 11:48:25 +0000566 GetState());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000567 // The main thread exited. We're done monitoring. Report to delegate.
568 SetExitStatus(convert_pid_status_to_exit_type(status),
569 convert_pid_status_to_return_code(status), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +0000570
Kate Stoneb9c1b512016-09-06 20:57:50 +0000571 // Notify delegate that our process has exited.
572 SetState(StateType::eStateExited, true);
Pavel Labatha6321a82017-01-19 15:26:04 +0000573 } else
574 LLDB_LOG(log, "tid = {0} main thread now exited (%s)", pid,
575 thread_found ? "stopped tracking thread metadata"
576 : "thread metadata not found");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000577 } else {
578 // Do we want to report to the delegate in this case? I think not. If
Pavel Labatha6321a82017-01-19 15:26:04 +0000579 // this was an orderly thread exit, we would already have received the
580 // SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal, and we would have done an
581 // all-stop then.
582 LLDB_LOG(log, "tid = {0} handling non-main thread exit (%s)", pid,
583 thread_found ? "stopped tracking thread metadata"
584 : "thread metadata not found");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000585 }
586 return;
587 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000588
Kate Stoneb9c1b512016-09-06 20:57:50 +0000589 siginfo_t info;
590 const auto info_err = GetSignalInfo(pid, &info);
591 auto thread_sp = GetThreadByID(pid);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000592
Kate Stoneb9c1b512016-09-06 20:57:50 +0000593 if (!thread_sp) {
594 // Normally, the only situation when we cannot find the thread is if we have
Pavel Labatha6321a82017-01-19 15:26:04 +0000595 // just received a new thread notification. This is indicated by
596 // GetSignalInfo() returning si_code == SI_USER and si_pid == 0
597 LLDB_LOG(log, "received notification about an unknown tid {0}.", pid);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000598
Kate Stoneb9c1b512016-09-06 20:57:50 +0000599 if (info_err.Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000600 LLDB_LOG(log,
601 "(tid {0}) GetSignalInfo failed ({1}). "
602 "Ingoring this notification.",
603 pid, info_err);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000604 return;
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000605 }
606
Pavel Labatha6321a82017-01-19 15:26:04 +0000607 LLDB_LOG(log, "tid {0}, si_code: {1}, si_pid: {2}", pid, info.si_code,
608 info.si_pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000609
610 auto thread_sp = AddThread(pid);
611 // Resume the newly created thread.
612 ResumeThread(*thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
613 ThreadWasCreated(*thread_sp);
614 return;
615 }
616
617 // Get details on the signal raised.
618 if (info_err.Success()) {
619 // We have retrieved the signal info. Dispatch appropriately.
620 if (info.si_signo == SIGTRAP)
621 MonitorSIGTRAP(info, *thread_sp);
Chaoren Linfa03ad22015-02-03 01:50:42 +0000622 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000623 MonitorSignal(info, *thread_sp, exited);
624 } else {
625 if (info_err.GetError() == EINVAL) {
626 // This is a group stop reception for this tid.
627 // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU
Pavel Labatha6321a82017-01-19 15:26:04 +0000628 // into the tracee, triggering the group-stop mechanism. Normally
629 // receiving these would stop the process, pending a SIGCONT. Simulating
630 // this state in a debugger is hard and is generally not needed (one use
631 // case is debugging background task being managed by a shell). For
632 // general use, it is sufficient to stop the process in a signal-delivery
Kate Stoneb9c1b512016-09-06 20:57:50 +0000633 // stop which happens before the group stop. This done by MonitorSignal
Pavel Labatha6321a82017-01-19 15:26:04 +0000634 // and works correctly for all signals.
635 LLDB_LOG(log,
636 "received a group stop for pid {0} tid {1}. Transparent "
637 "handling of group stops not supported, resuming the "
638 "thread.",
639 GetID(), pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000640 ResumeThread(*thread_sp, thread_sp->GetState(),
641 LLDB_INVALID_SIGNAL_NUMBER);
642 } else {
643 // ptrace(GETSIGINFO) failed (but not due to group-stop).
Todd Fialaaf245d12014-06-30 21:05:18 +0000644
Kate Stoneb9c1b512016-09-06 20:57:50 +0000645 // A return value of ESRCH means the thread/process is no longer on the
Pavel Labatha6321a82017-01-19 15:26:04 +0000646 // system, so it was killed somehow outside of our control. Either way,
647 // we can't do anything with it anymore.
Todd Fialaaf245d12014-06-30 21:05:18 +0000648
Kate Stoneb9c1b512016-09-06 20:57:50 +0000649 // Stop tracking the metadata for the thread since it's entirely off the
650 // system now.
651 const bool thread_found = StopTrackingThread(pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000652
Pavel Labatha6321a82017-01-19 15:26:04 +0000653 LLDB_LOG(log,
654 "GetSignalInfo failed: {0}, tid = {1}, signal = {2}, "
655 "status = {3}, main_thread = {4}, thread_found: {5}",
656 info_err, pid, signal, status, is_main_thread, thread_found);
Todd Fialaaf245d12014-06-30 21:05:18 +0000657
Kate Stoneb9c1b512016-09-06 20:57:50 +0000658 if (is_main_thread) {
659 // Notify the delegate - our process is not available but appears to
660 // have been killed outside
661 // our control. Is eStateExited the right exit state in this case?
662 SetExitStatus(convert_pid_status_to_exit_type(status),
663 convert_pid_status_to_return_code(status), nullptr, true);
664 SetState(StateType::eStateExited, true);
665 } else {
666 // This thread was pulled out from underneath us. Anything to do here?
667 // Do we want to do an all stop?
Pavel Labatha6321a82017-01-19 15:26:04 +0000668 LLDB_LOG(log,
669 "pid {0} tid {1} non-main thread exit occurred, didn't "
670 "tell delegate anything since thread disappeared out "
671 "from underneath us",
672 GetID(), pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000673 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000674 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000675 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000676}
677
Kate Stoneb9c1b512016-09-06 20:57:50 +0000678void NativeProcessLinux::WaitForNewThread(::pid_t tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000679 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Pavel Labath426bdf82015-04-28 07:51:52 +0000680
Kate Stoneb9c1b512016-09-06 20:57:50 +0000681 NativeThreadLinuxSP new_thread_sp = GetThreadByID(tid);
Pavel Labath426bdf82015-04-28 07:51:52 +0000682
Kate Stoneb9c1b512016-09-06 20:57:50 +0000683 if (new_thread_sp) {
684 // We are already tracking the thread - we got the event on the new thread
685 // (see
686 // MonitorSignal) before this one. We are done.
687 return;
688 }
Pavel Labath426bdf82015-04-28 07:51:52 +0000689
Kate Stoneb9c1b512016-09-06 20:57:50 +0000690 // The thread is not tracked yet, let's wait for it to appear.
691 int status = -1;
692 ::pid_t wait_pid;
693 do {
Pavel Labatha6321a82017-01-19 15:26:04 +0000694 LLDB_LOG(log,
695 "received thread creation event for tid {0}. tid not tracked "
696 "yet, waiting for thread to appear...",
697 tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000698 wait_pid = waitpid(tid, &status, __WALL);
699 } while (wait_pid == -1 && errno == EINTR);
700 // Since we are waiting on a specific tid, this must be the creation event.
Pavel Labatha6321a82017-01-19 15:26:04 +0000701 // But let's do some checks just in case.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000702 if (wait_pid != tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000703 LLDB_LOG(log,
704 "waiting for tid {0} failed. Assuming the thread has "
705 "disappeared in the meantime",
706 tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000707 // The only way I know of this could happen is if the whole process was
708 // SIGKILLed in the mean time. In any case, we can't do anything about that
709 // now.
710 return;
711 }
712 if (WIFEXITED(status)) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000713 LLDB_LOG(log,
714 "waiting for tid {0} returned an 'exited' event. Not "
715 "tracking the thread.",
716 tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000717 // Also a very improbable event.
718 return;
719 }
Pavel Labath426bdf82015-04-28 07:51:52 +0000720
Pavel Labatha6321a82017-01-19 15:26:04 +0000721 LLDB_LOG(log, "pid = {0}: tracking new thread tid {1}", GetID(), tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000722 new_thread_sp = AddThread(tid);
723 ResumeThread(*new_thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
724 ThreadWasCreated(*new_thread_sp);
Pavel Labath426bdf82015-04-28 07:51:52 +0000725}
726
Kate Stoneb9c1b512016-09-06 20:57:50 +0000727void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info,
728 NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000729 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000730 const bool is_main_thread = (thread.GetID() == GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000731
Kate Stoneb9c1b512016-09-06 20:57:50 +0000732 assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
Todd Fialaaf245d12014-06-30 21:05:18 +0000733
Kate Stoneb9c1b512016-09-06 20:57:50 +0000734 switch (info.si_code) {
735 // TODO: these two cases are required if we want to support tracing of the
736 // inferiors' children. We'd need this to debug a monitor.
737 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
738 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
Todd Fialaaf245d12014-06-30 21:05:18 +0000739
Kate Stoneb9c1b512016-09-06 20:57:50 +0000740 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): {
741 // This is the notification on the parent thread which informs us of new
742 // thread
743 // creation.
744 // We don't want to do anything with the parent thread so we just resume it.
745 // In case we
746 // want to implement "break on thread creation" functionality, we would need
747 // to stop
748 // here.
Todd Fialaaf245d12014-06-30 21:05:18 +0000749
Kate Stoneb9c1b512016-09-06 20:57:50 +0000750 unsigned long event_message = 0;
751 if (GetEventMessage(thread.GetID(), &event_message).Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000752 LLDB_LOG(log,
753 "pid {0} received thread creation event but "
754 "GetEventMessage failed so we don't know the new tid",
755 thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000756 } else
757 WaitForNewThread(event_message);
Todd Fialaaf245d12014-06-30 21:05:18 +0000758
Kate Stoneb9c1b512016-09-06 20:57:50 +0000759 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
760 break;
761 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000762
Kate Stoneb9c1b512016-09-06 20:57:50 +0000763 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): {
764 NativeThreadLinuxSP main_thread_sp;
Pavel Labatha6321a82017-01-19 15:26:04 +0000765 LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000766
767 // Exec clears any pending notifications.
768 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
769
770 // Remove all but the main thread here. Linux fork creates a new process
771 // which only copies the main thread.
Pavel Labatha6321a82017-01-19 15:26:04 +0000772 LLDB_LOG(log, "exec received, stop tracking all but main thread");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000773
774 for (auto thread_sp : m_threads) {
775 const bool is_main_thread = thread_sp && thread_sp->GetID() == GetID();
776 if (is_main_thread) {
777 main_thread_sp = std::static_pointer_cast<NativeThreadLinux>(thread_sp);
Pavel Labatha6321a82017-01-19 15:26:04 +0000778 LLDB_LOG(log, "found main thread with tid {0}, keeping",
779 main_thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000780 } else {
Pavel Labatha6321a82017-01-19 15:26:04 +0000781 LLDB_LOG(log, "discarding non-main-thread tid {0} due to exec",
782 thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000783 }
Todd Fialaa9882ce2014-08-28 15:46:54 +0000784 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000785
Kate Stoneb9c1b512016-09-06 20:57:50 +0000786 m_threads.clear();
Chaoren Linfa03ad22015-02-03 01:50:42 +0000787
Kate Stoneb9c1b512016-09-06 20:57:50 +0000788 if (main_thread_sp) {
789 m_threads.push_back(main_thread_sp);
790 SetCurrentThreadID(main_thread_sp->GetID());
791 main_thread_sp->SetStoppedByExec();
792 } else {
793 SetCurrentThreadID(LLDB_INVALID_THREAD_ID);
Pavel Labatha6321a82017-01-19 15:26:04 +0000794 LLDB_LOG(log,
795 "pid {0} no main thread found, discarded all threads, "
796 "we're in a no-thread state!",
797 GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000798 }
799
Kate Stoneb9c1b512016-09-06 20:57:50 +0000800 // Tell coordinator about about the "new" (since exec) stopped main thread.
801 ThreadWasCreated(*main_thread_sp);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000802
Kate Stoneb9c1b512016-09-06 20:57:50 +0000803 // Let our delegate know we have just exec'd.
804 NotifyDidExec();
805
806 // If we have a main thread, indicate we are stopped.
807 assert(main_thread_sp && "exec called during ptraced process but no main "
808 "thread metadata tracked");
809
810 // Let the process know we're stopped.
811 StopRunningThreads(main_thread_sp->GetID());
812
813 break;
814 }
815
816 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): {
817 // The inferior process or one of its threads is about to exit.
818 // We don't want to do anything with the thread so we just resume it. In
819 // case we
820 // want to implement "break on thread exit" functionality, we would need to
821 // stop
822 // here.
823
824 unsigned long data = 0;
825 if (GetEventMessage(thread.GetID(), &data).Fail())
826 data = -1;
827
Pavel Labatha6321a82017-01-19 15:26:04 +0000828 LLDB_LOG(log,
829 "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
830 "WIFSIGNALED={2}, pid = {3}, main_thread = {4}",
831 data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(),
832 is_main_thread);
Todd Fialaaf245d12014-06-30 21:05:18 +0000833
Kate Stoneb9c1b512016-09-06 20:57:50 +0000834 if (is_main_thread) {
835 SetExitStatus(convert_pid_status_to_exit_type(data),
836 convert_pid_status_to_return_code(data), nullptr, true);
837 }
838
839 StateType state = thread.GetState();
840 if (!StateIsRunningState(state)) {
841 // Due to a kernel bug, we may sometimes get this stop after the inferior
842 // gets a
843 // SIGKILL. This confuses our state tracking logic in ResumeThread(),
844 // since normally,
845 // we should not be receiving any ptrace events while the inferior is
846 // stopped. This
847 // makes sure that the inferior is resumed and exits normally.
848 state = eStateRunning;
849 }
850 ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
851
852 break;
853 }
854
855 case 0:
856 case TRAP_TRACE: // We receive this on single stepping.
857 case TRAP_HWBKPT: // We receive this on watchpoint hit
858 {
859 // If a watchpoint was hit, report it
860 uint32_t wp_index;
861 Error error = thread.GetRegisterContext()->GetWatchpointHitIndex(
862 wp_index, (uintptr_t)info.si_addr);
Pavel Labatha6321a82017-01-19 15:26:04 +0000863 if (error.Fail())
864 LLDB_LOG(log,
865 "received error while checking for watchpoint hits, pid = "
866 "{0}, error = {1}",
867 thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000868 if (wp_index != LLDB_INVALID_INDEX32) {
869 MonitorWatchpoint(thread, wp_index);
870 break;
871 }
872
873 // Otherwise, report step over
874 MonitorTrace(thread);
875 break;
876 }
877
878 case SI_KERNEL:
Mohit K. Bhakkad35799962015-06-18 04:53:18 +0000879#if defined __mips__
Kate Stoneb9c1b512016-09-06 20:57:50 +0000880 // For mips there is no special signal for watchpoint
881 // So we check for watchpoint in kernel trap
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000882 {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000883 // If a watchpoint was hit, report it
884 uint32_t wp_index;
885 Error error = thread.GetRegisterContext()->GetWatchpointHitIndex(
886 wp_index, LLDB_INVALID_ADDRESS);
Pavel Labatha6321a82017-01-19 15:26:04 +0000887 if (error.Fail())
888 LLDB_LOG(log,
889 "received error while checking for watchpoint hits, pid = "
890 "{0}, error = {1}",
891 thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000892 if (wp_index != LLDB_INVALID_INDEX32) {
893 MonitorWatchpoint(thread, wp_index);
894 break;
895 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000896 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000897// NO BREAK
Mohit K. Bhakkad35799962015-06-18 04:53:18 +0000898#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000899 case TRAP_BRKPT:
900 MonitorBreakpoint(thread);
901 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000902
Kate Stoneb9c1b512016-09-06 20:57:50 +0000903 case SIGTRAP:
904 case (SIGTRAP | 0x80):
Pavel Labatha6321a82017-01-19 15:26:04 +0000905 LLDB_LOG(
906 log,
907 "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",
908 info.si_code, GetID(), thread.GetID());
Chaoren Linfa03ad22015-02-03 01:50:42 +0000909
Kate Stoneb9c1b512016-09-06 20:57:50 +0000910 // Ignore these signals until we know more about them.
911 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
912 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000913
Kate Stoneb9c1b512016-09-06 20:57:50 +0000914 default:
Pavel Labatha6321a82017-01-19 15:26:04 +0000915 LLDB_LOG(
916 log,
917 "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",
918 info.si_code, GetID(), thread.GetID());
919 llvm_unreachable("Unexpected SIGTRAP code!");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000920 break;
921 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000922}
923
Kate Stoneb9c1b512016-09-06 20:57:50 +0000924void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000925 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
926 LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000927
Kate Stoneb9c1b512016-09-06 20:57:50 +0000928 // This thread is currently stopped.
929 thread.SetStoppedByTrace();
930
931 StopRunningThreads(thread.GetID());
932}
933
934void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) {
935 Log *log(
936 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
Pavel Labatha6321a82017-01-19 15:26:04 +0000937 LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000938
939 // Mark the thread as stopped at breakpoint.
940 thread.SetStoppedByBreakpoint();
941 Error error = FixupBreakpointPCAsNeeded(thread);
942 if (error.Fail())
Pavel Labatha6321a82017-01-19 15:26:04 +0000943 LLDB_LOG(log, "pid = {0} fixup: {1}", thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000944
945 if (m_threads_stepping_with_breakpoint.find(thread.GetID()) !=
946 m_threads_stepping_with_breakpoint.end())
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000947 thread.SetStoppedByTrace();
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000948
Kate Stoneb9c1b512016-09-06 20:57:50 +0000949 StopRunningThreads(thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000950}
951
Kate Stoneb9c1b512016-09-06 20:57:50 +0000952void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread,
953 uint32_t wp_index) {
954 Log *log(
955 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
Pavel Labatha6321a82017-01-19 15:26:04 +0000956 LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}",
957 thread.GetID(), wp_index);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000958
959 // Mark the thread as stopped at watchpoint.
960 // The address is at (lldb::addr_t)info->si_addr if we need it.
961 thread.SetStoppedByWatchpoint(wp_index);
962
963 // We need to tell all other running threads before we notify the delegate
964 // about this stop.
965 StopRunningThreads(thread.GetID());
966}
967
968void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
969 NativeThreadLinux &thread, bool exited) {
970 const int signo = info.si_signo;
971 const bool is_from_llgs = info.si_pid == getpid();
972
Pavel Labatha6321a82017-01-19 15:26:04 +0000973 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000974
975 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
976 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
977 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
978 //
979 // IOW, user generated signals never generate what we consider to be a
980 // "crash".
981 //
982 // Similarly, ACK signals generated by this monitor.
983
984 // Handle the signal.
Pavel Labatha6321a82017-01-19 15:26:04 +0000985 LLDB_LOG(log,
986 "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
987 "waitpid pid = {4})",
988 Host::GetSignalAsCString(signo), signo, info.si_code,
989 thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000990
Kate Stoneb9c1b512016-09-06 20:57:50 +0000991 // Check for thread stop notification.
992 if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) {
993 // This is a tgkill()-based stop.
Pavel Labatha6321a82017-01-19 15:26:04 +0000994 LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000995
Kate Stoneb9c1b512016-09-06 20:57:50 +0000996 // Check that we're not already marked with a stop reason.
997 // Note this thread really shouldn't already be marked as stopped - if we
Pavel Labatha6321a82017-01-19 15:26:04 +0000998 // were, that would imply that the kernel signaled us with the thread
999 // stopping which we handled and marked as stopped, and that, without an
1000 // intervening resume, we received another stop. It is more likely that we
1001 // are missing the marking of a run state somewhere if we find that the
1002 // thread was marked as stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001003 const StateType thread_state = thread.GetState();
1004 if (!StateIsStoppedState(thread_state, false)) {
1005 // An inferior thread has stopped because of a SIGSTOP we have sent it.
1006 // Generally, these are not important stops and we don't want to report
Pavel Labatha6321a82017-01-19 15:26:04 +00001007 // them as they are just used to stop other threads when one thread (the
1008 // one with the *real* stop reason) hits a breakpoint (watchpoint,
1009 // etc...). However, in the case of an asynchronous Interrupt(), this *is*
1010 // the real stop reason, so we leave the signal intact if this is the
1011 // thread that was chosen as the triggering thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001012 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
1013 if (m_pending_notification_tid == thread.GetID())
1014 thread.SetStoppedBySignal(SIGSTOP, &info);
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001015 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001016 thread.SetStoppedWithNoReason();
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001017
Kate Stoneb9c1b512016-09-06 20:57:50 +00001018 SetCurrentThreadID(thread.GetID());
1019 SignalIfAllThreadsStopped();
1020 } else {
1021 // We can end up here if stop was initiated by LLGS but by this time a
1022 // thread stop has occurred - maybe initiated by another event.
1023 Error error = ResumeThread(thread, thread.GetState(), 0);
Pavel Labatha6321a82017-01-19 15:26:04 +00001024 if (error.Fail())
1025 LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(),
1026 error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001027 }
1028 } else {
Pavel Labatha6321a82017-01-19 15:26:04 +00001029 LLDB_LOG(log,
1030 "pid {0} tid {1}, thread was already marked as a stopped "
1031 "state (state={2}), leaving stop signal as is",
Pavel Labath8198db32017-01-24 11:48:25 +00001032 GetID(), thread.GetID(), thread_state);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001033 SignalIfAllThreadsStopped();
Todd Fialaaf245d12014-06-30 21:05:18 +00001034 }
1035
Kate Stoneb9c1b512016-09-06 20:57:50 +00001036 // Done handling.
1037 return;
1038 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001039
Pavel Labath4a705e72017-02-24 09:29:14 +00001040 // Check if debugger should stop at this signal or just ignore it
1041 // and resume the inferior.
1042 if (m_signals_to_ignore.find(signo) != m_signals_to_ignore.end()) {
1043 ResumeThread(thread, thread.GetState(), signo);
1044 return;
1045 }
1046
Kate Stoneb9c1b512016-09-06 20:57:50 +00001047 // This thread is stopped.
Pavel Labatha6321a82017-01-19 15:26:04 +00001048 LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001049 thread.SetStoppedBySignal(signo, &info);
1050
1051 // Send a stop to the debugger after we get all other threads to stop.
1052 StopRunningThreads(thread.GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +00001053}
1054
Tamas Berghammere7708682015-04-22 10:00:23 +00001055namespace {
1056
Kate Stoneb9c1b512016-09-06 20:57:50 +00001057struct EmulatorBaton {
1058 NativeProcessLinux *m_process;
1059 NativeRegisterContext *m_reg_context;
Tamas Berghammere7708682015-04-22 10:00:23 +00001060
Kate Stoneb9c1b512016-09-06 20:57:50 +00001061 // eRegisterKindDWARF -> RegsiterValue
1062 std::unordered_map<uint32_t, RegisterValue> m_register_values;
Pavel Labath6648fcc2015-04-27 09:21:14 +00001063
Kate Stoneb9c1b512016-09-06 20:57:50 +00001064 EmulatorBaton(NativeProcessLinux *process, NativeRegisterContext *reg_context)
1065 : m_process(process), m_reg_context(reg_context) {}
Tamas Berghammere7708682015-04-22 10:00:23 +00001066};
1067
1068} // anonymous namespace
1069
Kate Stoneb9c1b512016-09-06 20:57:50 +00001070static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
1071 const EmulateInstruction::Context &context,
1072 lldb::addr_t addr, void *dst, size_t length) {
1073 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
Tamas Berghammere7708682015-04-22 10:00:23 +00001074
Kate Stoneb9c1b512016-09-06 20:57:50 +00001075 size_t bytes_read;
1076 emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
1077 return bytes_read;
Tamas Berghammere7708682015-04-22 10:00:23 +00001078}
1079
Kate Stoneb9c1b512016-09-06 20:57:50 +00001080static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
1081 const RegisterInfo *reg_info,
1082 RegisterValue &reg_value) {
1083 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
Tamas Berghammere7708682015-04-22 10:00:23 +00001084
Kate Stoneb9c1b512016-09-06 20:57:50 +00001085 auto it = emulator_baton->m_register_values.find(
1086 reg_info->kinds[eRegisterKindDWARF]);
1087 if (it != emulator_baton->m_register_values.end()) {
1088 reg_value = it->second;
1089 return true;
1090 }
1091
1092 // The emulator only fill in the dwarf regsiter numbers (and in some case
1093 // the generic register numbers). Get the full register info from the
1094 // register context based on the dwarf register numbers.
1095 const RegisterInfo *full_reg_info =
1096 emulator_baton->m_reg_context->GetRegisterInfo(
1097 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
1098
1099 Error error =
1100 emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
1101 if (error.Success())
1102 return true;
1103
1104 return false;
1105}
1106
1107static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
1108 const EmulateInstruction::Context &context,
1109 const RegisterInfo *reg_info,
1110 const RegisterValue &reg_value) {
1111 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
1112 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
1113 reg_value;
1114 return true;
1115}
1116
1117static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
1118 const EmulateInstruction::Context &context,
1119 lldb::addr_t addr, const void *dst,
1120 size_t length) {
1121 return length;
1122}
1123
1124static lldb::addr_t ReadFlags(NativeRegisterContext *regsiter_context) {
1125 const RegisterInfo *flags_info = regsiter_context->GetRegisterInfo(
1126 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1127 return regsiter_context->ReadRegisterAsUnsigned(flags_info,
1128 LLDB_INVALID_ADDRESS);
1129}
1130
1131Error NativeProcessLinux::SetupSoftwareSingleStepping(
1132 NativeThreadLinux &thread) {
1133 Error error;
1134 NativeRegisterContextSP register_context_sp = thread.GetRegisterContext();
1135
1136 std::unique_ptr<EmulateInstruction> emulator_ap(
1137 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying,
1138 nullptr));
1139
1140 if (emulator_ap == nullptr)
1141 return Error("Instruction emulator not found!");
1142
1143 EmulatorBaton baton(this, register_context_sp.get());
1144 emulator_ap->SetBaton(&baton);
1145 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
1146 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
1147 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
1148 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
1149
1150 if (!emulator_ap->ReadInstruction())
1151 return Error("Read instruction failed!");
1152
1153 bool emulation_result =
1154 emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
1155
1156 const RegisterInfo *reg_info_pc = register_context_sp->GetRegisterInfo(
1157 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1158 const RegisterInfo *reg_info_flags = register_context_sp->GetRegisterInfo(
1159 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1160
1161 auto pc_it =
1162 baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1163 auto flags_it =
1164 baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
1165
1166 lldb::addr_t next_pc;
1167 lldb::addr_t next_flags;
1168 if (emulation_result) {
1169 assert(pc_it != baton.m_register_values.end() &&
1170 "Emulation was successfull but PC wasn't updated");
1171 next_pc = pc_it->second.GetAsUInt64();
1172
1173 if (flags_it != baton.m_register_values.end())
1174 next_flags = flags_it->second.GetAsUInt64();
1175 else
1176 next_flags = ReadFlags(register_context_sp.get());
1177 } else if (pc_it == baton.m_register_values.end()) {
1178 // Emulate instruction failed and it haven't changed PC. Advance PC
1179 // with the size of the current opcode because the emulation of all
1180 // PC modifying instruction should be successful. The failure most
1181 // likely caused by a not supported instruction which don't modify PC.
1182 next_pc =
1183 register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
1184 next_flags = ReadFlags(register_context_sp.get());
1185 } else {
1186 // The instruction emulation failed after it modified the PC. It is an
1187 // unknown error where we can't continue because the next instruction is
1188 // modifying the PC but we don't know how.
1189 return Error("Instruction emulation failed unexpectedly.");
1190 }
1191
1192 if (m_arch.GetMachine() == llvm::Triple::arm) {
1193 if (next_flags & 0x20) {
1194 // Thumb mode
1195 error = SetSoftwareBreakpoint(next_pc, 2);
1196 } else {
1197 // Arm mode
1198 error = SetSoftwareBreakpoint(next_pc, 4);
Pavel Labath6648fcc2015-04-27 09:21:14 +00001199 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001200 } else if (m_arch.GetMachine() == llvm::Triple::mips64 ||
1201 m_arch.GetMachine() == llvm::Triple::mips64el ||
1202 m_arch.GetMachine() == llvm::Triple::mips ||
1203 m_arch.GetMachine() == llvm::Triple::mipsel)
1204 error = SetSoftwareBreakpoint(next_pc, 4);
1205 else {
1206 // No size hint is given for the next breakpoint
1207 error = SetSoftwareBreakpoint(next_pc, 0);
1208 }
Pavel Labath6648fcc2015-04-27 09:21:14 +00001209
Pavel Labath42eb6902016-10-26 11:13:56 +00001210 // If setting the breakpoint fails because next_pc is out of
1211 // the address space, ignore it and let the debugee segfault.
1212 if (error.GetError() == EIO || error.GetError() == EFAULT) {
Mehdi Amini665be502016-11-11 05:07:57 +00001213 return Error();
Pavel Labath42eb6902016-10-26 11:13:56 +00001214 } else if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001215 return error;
Tamas Berghammere7708682015-04-22 10:00:23 +00001216
Kate Stoneb9c1b512016-09-06 20:57:50 +00001217 m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001218
Mehdi Amini665be502016-11-11 05:07:57 +00001219 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001220}
1221
1222bool NativeProcessLinux::SupportHardwareSingleStepping() const {
1223 if (m_arch.GetMachine() == llvm::Triple::arm ||
1224 m_arch.GetMachine() == llvm::Triple::mips64 ||
1225 m_arch.GetMachine() == llvm::Triple::mips64el ||
1226 m_arch.GetMachine() == llvm::Triple::mips ||
1227 m_arch.GetMachine() == llvm::Triple::mipsel)
Pavel Labath6648fcc2015-04-27 09:21:14 +00001228 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001229 return true;
Tamas Berghammere7708682015-04-22 10:00:23 +00001230}
1231
Kate Stoneb9c1b512016-09-06 20:57:50 +00001232Error NativeProcessLinux::Resume(const ResumeActionList &resume_actions) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001233 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1234 LLDB_LOG(log, "pid {0}", GetID());
Tamas Berghammere7708682015-04-22 10:00:23 +00001235
Kate Stoneb9c1b512016-09-06 20:57:50 +00001236 bool software_single_step = !SupportHardwareSingleStepping();
Tamas Berghammere7708682015-04-22 10:00:23 +00001237
Kate Stoneb9c1b512016-09-06 20:57:50 +00001238 if (software_single_step) {
1239 for (auto thread_sp : m_threads) {
1240 assert(thread_sp && "thread list should not contain NULL threads");
Tamas Berghammere7708682015-04-22 10:00:23 +00001241
Kate Stoneb9c1b512016-09-06 20:57:50 +00001242 const ResumeAction *const action =
1243 resume_actions.GetActionForThread(thread_sp->GetID(), true);
1244 if (action == nullptr)
1245 continue;
Tamas Berghammere7708682015-04-22 10:00:23 +00001246
Kate Stoneb9c1b512016-09-06 20:57:50 +00001247 if (action->state == eStateStepping) {
1248 Error error = SetupSoftwareSingleStepping(
1249 static_cast<NativeThreadLinux &>(*thread_sp));
1250 if (error.Fail())
1251 return error;
1252 }
Tamas Berghammere7708682015-04-22 10:00:23 +00001253 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001254 }
1255
1256 for (auto thread_sp : m_threads) {
1257 assert(thread_sp && "thread list should not contain NULL threads");
1258
1259 const ResumeAction *const action =
1260 resume_actions.GetActionForThread(thread_sp->GetID(), true);
1261
1262 if (action == nullptr) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001263 LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
1264 thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001265 continue;
Tamas Berghammere7708682015-04-22 10:00:23 +00001266 }
1267
Pavel Labatha6321a82017-01-19 15:26:04 +00001268 LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}",
Pavel Labath8198db32017-01-24 11:48:25 +00001269 action->state, GetID(), thread_sp->GetID());
Tamas Berghammere7708682015-04-22 10:00:23 +00001270
Kate Stoneb9c1b512016-09-06 20:57:50 +00001271 switch (action->state) {
1272 case eStateRunning:
1273 case eStateStepping: {
1274 // Run the thread, possibly feeding it the signal.
1275 const int signo = action->signal;
1276 ResumeThread(static_cast<NativeThreadLinux &>(*thread_sp), action->state,
1277 signo);
1278 break;
1279 }
Tamas Berghammere7708682015-04-22 10:00:23 +00001280
Kate Stoneb9c1b512016-09-06 20:57:50 +00001281 case eStateSuspended:
1282 case eStateStopped:
Pavel Labatha6321a82017-01-19 15:26:04 +00001283 llvm_unreachable("Unexpected state");
Tamas Berghammere7708682015-04-22 10:00:23 +00001284
Kate Stoneb9c1b512016-09-06 20:57:50 +00001285 default:
1286 return Error("NativeProcessLinux::%s (): unexpected state %s specified "
1287 "for pid %" PRIu64 ", tid %" PRIu64,
1288 __FUNCTION__, StateAsCString(action->state), GetID(),
1289 thread_sp->GetID());
1290 }
1291 }
1292
Mehdi Amini665be502016-11-11 05:07:57 +00001293 return Error();
Tamas Berghammere7708682015-04-22 10:00:23 +00001294}
1295
Kate Stoneb9c1b512016-09-06 20:57:50 +00001296Error NativeProcessLinux::Halt() {
1297 Error error;
1298
1299 if (kill(GetID(), SIGSTOP) != 0)
1300 error.SetErrorToErrno();
1301
1302 return error;
Tamas Berghammere7708682015-04-22 10:00:23 +00001303}
1304
Kate Stoneb9c1b512016-09-06 20:57:50 +00001305Error NativeProcessLinux::Detach() {
1306 Error error;
1307
1308 // Stop monitoring the inferior.
1309 m_sigchld_handle.reset();
1310
1311 // Tell ptrace to detach from the process.
1312 if (GetID() == LLDB_INVALID_PROCESS_ID)
1313 return error;
1314
1315 for (auto thread_sp : m_threads) {
1316 Error e = Detach(thread_sp->GetID());
1317 if (e.Fail())
1318 error =
1319 e; // Save the error, but still attempt to detach from other threads.
1320 }
1321
1322 return error;
1323}
1324
1325Error NativeProcessLinux::Signal(int signo) {
1326 Error error;
1327
Pavel Labatha6321a82017-01-19 15:26:04 +00001328 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1329 LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo,
1330 Host::GetSignalAsCString(signo), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001331
1332 if (kill(GetID(), signo))
1333 error.SetErrorToErrno();
1334
1335 return error;
1336}
1337
1338Error NativeProcessLinux::Interrupt() {
1339 // Pick a running thread (or if none, a not-dead stopped thread) as
1340 // the chosen thread that will be the stop-reason thread.
Pavel Labatha6321a82017-01-19 15:26:04 +00001341 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001342
1343 NativeThreadProtocolSP running_thread_sp;
1344 NativeThreadProtocolSP stopped_thread_sp;
1345
Pavel Labatha6321a82017-01-19 15:26:04 +00001346 LLDB_LOG(log, "selecting running thread for interrupt target");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001347 for (auto thread_sp : m_threads) {
1348 // The thread shouldn't be null but lets just cover that here.
1349 if (!thread_sp)
1350 continue;
1351
1352 // If we have a running or stepping thread, we'll call that the
1353 // target of the interrupt.
1354 const auto thread_state = thread_sp->GetState();
1355 if (thread_state == eStateRunning || thread_state == eStateStepping) {
1356 running_thread_sp = thread_sp;
1357 break;
1358 } else if (!stopped_thread_sp && StateIsStoppedState(thread_state, true)) {
1359 // Remember the first non-dead stopped thread. We'll use that as a backup
1360 // if there are no running threads.
1361 stopped_thread_sp = thread_sp;
1362 }
1363 }
1364
1365 if (!running_thread_sp && !stopped_thread_sp) {
1366 Error error("found no running/stepping or live stopped threads as target "
1367 "for interrupt");
Pavel Labatha6321a82017-01-19 15:26:04 +00001368 LLDB_LOG(log, "skipping due to error: {0}", error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001369
1370 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001371 }
1372
1373 NativeThreadProtocolSP deferred_signal_thread_sp =
1374 running_thread_sp ? running_thread_sp : stopped_thread_sp;
1375
Pavel Labatha6321a82017-01-19 15:26:04 +00001376 LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(),
1377 running_thread_sp ? "running" : "stopped",
1378 deferred_signal_thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001379
1380 StopRunningThreads(deferred_signal_thread_sp->GetID());
1381
Mehdi Amini665be502016-11-11 05:07:57 +00001382 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00001383}
1384
Kate Stoneb9c1b512016-09-06 20:57:50 +00001385Error NativeProcessLinux::Kill() {
Pavel Labatha6321a82017-01-19 15:26:04 +00001386 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1387 LLDB_LOG(log, "pid {0}", GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +00001388
Kate Stoneb9c1b512016-09-06 20:57:50 +00001389 Error error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001390
Kate Stoneb9c1b512016-09-06 20:57:50 +00001391 switch (m_state) {
1392 case StateType::eStateInvalid:
1393 case StateType::eStateExited:
1394 case StateType::eStateCrashed:
1395 case StateType::eStateDetached:
1396 case StateType::eStateUnloaded:
1397 // Nothing to do - the process is already dead.
Pavel Labatha6321a82017-01-19 15:26:04 +00001398 LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
Pavel Labath8198db32017-01-24 11:48:25 +00001399 m_state);
Todd Fialaaf245d12014-06-30 21:05:18 +00001400 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001401
Kate Stoneb9c1b512016-09-06 20:57:50 +00001402 case StateType::eStateConnected:
1403 case StateType::eStateAttaching:
1404 case StateType::eStateLaunching:
1405 case StateType::eStateStopped:
1406 case StateType::eStateRunning:
1407 case StateType::eStateStepping:
1408 case StateType::eStateSuspended:
1409 // We can try to kill a process in these states.
1410 break;
1411 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001412
Kate Stoneb9c1b512016-09-06 20:57:50 +00001413 if (kill(GetID(), SIGKILL) != 0) {
1414 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +00001415 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001416 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001417
Kate Stoneb9c1b512016-09-06 20:57:50 +00001418 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001419}
1420
1421static Error
Kate Stoneb9c1b512016-09-06 20:57:50 +00001422ParseMemoryRegionInfoFromProcMapsLine(const std::string &maps_line,
1423 MemoryRegionInfo &memory_region_info) {
1424 memory_region_info.Clear();
Todd Fialaaf245d12014-06-30 21:05:18 +00001425
Kate Stoneb9c1b512016-09-06 20:57:50 +00001426 StringExtractor line_extractor(maps_line.c_str());
Todd Fialaaf245d12014-06-30 21:05:18 +00001427
Kate Stoneb9c1b512016-09-06 20:57:50 +00001428 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode
1429 // pathname
1430 // perms: rwxp (letter is present if set, '-' if not, final character is
1431 // p=private, s=shared).
Todd Fialaaf245d12014-06-30 21:05:18 +00001432
Kate Stoneb9c1b512016-09-06 20:57:50 +00001433 // Parse out the starting address
1434 lldb::addr_t start_address = line_extractor.GetHexMaxU64(false, 0);
Todd Fialaaf245d12014-06-30 21:05:18 +00001435
Kate Stoneb9c1b512016-09-06 20:57:50 +00001436 // Parse out hyphen separating start and end address from range.
1437 if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != '-'))
1438 return Error(
1439 "malformed /proc/{pid}/maps entry, missing dash between address range");
Todd Fialaaf245d12014-06-30 21:05:18 +00001440
Kate Stoneb9c1b512016-09-06 20:57:50 +00001441 // Parse out the ending address
1442 lldb::addr_t end_address = line_extractor.GetHexMaxU64(false, start_address);
Todd Fialaaf245d12014-06-30 21:05:18 +00001443
Kate Stoneb9c1b512016-09-06 20:57:50 +00001444 // Parse out the space after the address.
1445 if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != ' '))
1446 return Error("malformed /proc/{pid}/maps entry, missing space after range");
Todd Fialaaf245d12014-06-30 21:05:18 +00001447
Kate Stoneb9c1b512016-09-06 20:57:50 +00001448 // Save the range.
1449 memory_region_info.GetRange().SetRangeBase(start_address);
1450 memory_region_info.GetRange().SetRangeEnd(end_address);
Todd Fialaaf245d12014-06-30 21:05:18 +00001451
Kate Stoneb9c1b512016-09-06 20:57:50 +00001452 // Any memory region in /proc/{pid}/maps is by definition mapped into the
1453 // process.
1454 memory_region_info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
Howard Hellyerad007562016-07-07 08:21:28 +00001455
Kate Stoneb9c1b512016-09-06 20:57:50 +00001456 // Parse out each permission entry.
1457 if (line_extractor.GetBytesLeft() < 4)
1458 return Error("malformed /proc/{pid}/maps entry, missing some portion of "
1459 "permissions");
Todd Fialaaf245d12014-06-30 21:05:18 +00001460
Kate Stoneb9c1b512016-09-06 20:57:50 +00001461 // Handle read permission.
1462 const char read_perm_char = line_extractor.GetChar();
1463 if (read_perm_char == 'r')
1464 memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eYes);
1465 else if (read_perm_char == '-')
1466 memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1467 else
1468 return Error("unexpected /proc/{pid}/maps read permission char");
Todd Fialaaf245d12014-06-30 21:05:18 +00001469
Kate Stoneb9c1b512016-09-06 20:57:50 +00001470 // Handle write permission.
1471 const char write_perm_char = line_extractor.GetChar();
1472 if (write_perm_char == 'w')
1473 memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eYes);
1474 else if (write_perm_char == '-')
1475 memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1476 else
1477 return Error("unexpected /proc/{pid}/maps write permission char");
Todd Fialaaf245d12014-06-30 21:05:18 +00001478
Kate Stoneb9c1b512016-09-06 20:57:50 +00001479 // Handle execute permission.
1480 const char exec_perm_char = line_extractor.GetChar();
1481 if (exec_perm_char == 'x')
1482 memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes);
1483 else if (exec_perm_char == '-')
1484 memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1485 else
1486 return Error("unexpected /proc/{pid}/maps exec permission char");
Todd Fialaaf245d12014-06-30 21:05:18 +00001487
Kate Stoneb9c1b512016-09-06 20:57:50 +00001488 line_extractor.GetChar(); // Read the private bit
1489 line_extractor.SkipSpaces(); // Skip the separator
1490 line_extractor.GetHexMaxU64(false, 0); // Read the offset
1491 line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1492 line_extractor.GetChar(); // Read the device id separator
1493 line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1494 line_extractor.SkipSpaces(); // Skip the separator
1495 line_extractor.GetU64(0, 10); // Read the inode number
Tamas Berghammerd7d69f82016-07-22 12:55:35 +00001496
Kate Stoneb9c1b512016-09-06 20:57:50 +00001497 line_extractor.SkipSpaces();
1498 const char *name = line_extractor.Peek();
1499 if (name)
1500 memory_region_info.SetName(name);
Tamas Berghammerd7d69f82016-07-22 12:55:35 +00001501
Mehdi Amini665be502016-11-11 05:07:57 +00001502 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00001503}
1504
Kate Stoneb9c1b512016-09-06 20:57:50 +00001505Error NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr,
1506 MemoryRegionInfo &range_info) {
1507 // FIXME review that the final memory region returned extends to the end of
1508 // the virtual address space,
1509 // with no perms if it is not mapped.
Todd Fialaaf245d12014-06-30 21:05:18 +00001510
Kate Stoneb9c1b512016-09-06 20:57:50 +00001511 // Use an approach that reads memory regions from /proc/{pid}/maps.
1512 // Assume proc maps entries are in ascending order.
1513 // FIXME assert if we find differently.
Todd Fialaaf245d12014-06-30 21:05:18 +00001514
Kate Stoneb9c1b512016-09-06 20:57:50 +00001515 if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
1516 // We're done.
Tamas Berghammera6f57952017-01-03 16:29:43 +00001517 return Error("unsupported");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001518 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001519
Tamas Berghammera6f57952017-01-03 16:29:43 +00001520 Error error = PopulateMemoryRegionCache();
1521 if (error.Fail()) {
1522 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001523 }
1524
1525 lldb::addr_t prev_base_address = 0;
1526
1527 // FIXME start by finding the last region that is <= target address using
1528 // binary search. Data is sorted.
1529 // There can be a ton of regions on pthreads apps with lots of threads.
1530 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1531 ++it) {
Tamas Berghammera6f57952017-01-03 16:29:43 +00001532 MemoryRegionInfo &proc_entry_info = it->first;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001533
1534 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1535 assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
1536 "descending /proc/pid/maps entries detected, unexpected");
1537 prev_base_address = proc_entry_info.GetRange().GetRangeBase();
Hafiz Abid Qadeerb1554312017-01-20 10:24:03 +00001538 UNUSED_IF_ASSERT_DISABLED(prev_base_address);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001539
1540 // If the target address comes before this entry, indicate distance to next
1541 // region.
1542 if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1543 range_info.GetRange().SetRangeBase(load_addr);
1544 range_info.GetRange().SetByteSize(
1545 proc_entry_info.GetRange().GetRangeBase() - load_addr);
1546 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1547 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1548 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1549 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1550
1551 return error;
1552 } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1553 // The target address is within the memory region we're processing here.
1554 range_info = proc_entry_info;
1555 return error;
1556 }
1557
1558 // The target memory address comes somewhere after the region we just
1559 // parsed.
1560 }
1561
1562 // If we made it here, we didn't find an entry that contained the given
1563 // address. Return the
1564 // load_addr as start and the amount of bytes betwwen load address and the end
1565 // of the memory as
1566 // size.
1567 range_info.GetRange().SetRangeBase(load_addr);
1568 range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
1569 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1570 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1571 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1572 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1573 return error;
1574}
1575
Tamas Berghammera6f57952017-01-03 16:29:43 +00001576Error NativeProcessLinux::PopulateMemoryRegionCache() {
Pavel Labatha6321a82017-01-19 15:26:04 +00001577 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Tamas Berghammera6f57952017-01-03 16:29:43 +00001578
1579 // If our cache is empty, pull the latest. There should always be at least
1580 // one memory region if memory region handling is supported.
1581 if (!m_mem_region_cache.empty()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001582 LLDB_LOG(log, "reusing {0} cached memory region entries",
1583 m_mem_region_cache.size());
Tamas Berghammera6f57952017-01-03 16:29:43 +00001584 return Error();
1585 }
1586
1587 Error error = ProcFileReader::ProcessLineByLine(
1588 GetID(), "maps", [&](const std::string &line) -> bool {
1589 MemoryRegionInfo info;
1590 const Error parse_error =
1591 ParseMemoryRegionInfoFromProcMapsLine(line, info);
1592 if (parse_error.Success()) {
1593 m_mem_region_cache.emplace_back(
1594 info, FileSpec(info.GetName().GetCString(), true));
1595 return true;
1596 } else {
Pavel Labatha6321a82017-01-19 15:26:04 +00001597 LLDB_LOG(log, "failed to parse proc maps line '{0}': {1}", line,
1598 parse_error);
Tamas Berghammera6f57952017-01-03 16:29:43 +00001599 return false;
1600 }
1601 });
1602
1603 // If we had an error, we'll mark unsupported.
1604 if (error.Fail()) {
1605 m_supports_mem_region = LazyBool::eLazyBoolNo;
1606 return error;
1607 } else if (m_mem_region_cache.empty()) {
1608 // No entries after attempting to read them. This shouldn't happen if
1609 // /proc/{pid}/maps is supported. Assume we don't support map entries
1610 // via procfs.
Pavel Labatha6321a82017-01-19 15:26:04 +00001611 LLDB_LOG(log,
1612 "failed to find any procfs maps entries, assuming no support "
1613 "for memory region metadata retrieval");
Tamas Berghammera6f57952017-01-03 16:29:43 +00001614 m_supports_mem_region = LazyBool::eLazyBoolNo;
1615 error.SetErrorString("not supported");
1616 return error;
1617 }
1618
Pavel Labatha6321a82017-01-19 15:26:04 +00001619 LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps",
1620 m_mem_region_cache.size(), GetID());
Tamas Berghammera6f57952017-01-03 16:29:43 +00001621
1622 // We support memory retrieval, remember that.
1623 m_supports_mem_region = LazyBool::eLazyBoolYes;
1624 return Error();
1625}
1626
Kate Stoneb9c1b512016-09-06 20:57:50 +00001627void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001628 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1629 LLDB_LOG(log, "newBumpId={0}", newBumpId);
1630 LLDB_LOG(log, "clearing {0} entries from memory region cache",
1631 m_mem_region_cache.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001632 m_mem_region_cache.clear();
1633}
1634
1635Error NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions,
1636 lldb::addr_t &addr) {
1637// FIXME implementing this requires the equivalent of
1638// InferiorCallPOSIX::InferiorCallMmap, which depends on
1639// functional ThreadPlans working with Native*Protocol.
1640#if 1
1641 return Error("not implemented yet");
1642#else
1643 addr = LLDB_INVALID_ADDRESS;
1644
1645 unsigned prot = 0;
1646 if (permissions & lldb::ePermissionsReadable)
1647 prot |= eMmapProtRead;
1648 if (permissions & lldb::ePermissionsWritable)
1649 prot |= eMmapProtWrite;
1650 if (permissions & lldb::ePermissionsExecutable)
1651 prot |= eMmapProtExec;
1652
1653 // TODO implement this directly in NativeProcessLinux
1654 // (and lift to NativeProcessPOSIX if/when that class is
1655 // refactored out).
1656 if (InferiorCallMmap(this, addr, 0, size, prot,
1657 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
1658 m_addr_to_mmap_size[addr] = size;
Mehdi Amini665be502016-11-11 05:07:57 +00001659 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001660 } else {
1661 addr = LLDB_INVALID_ADDRESS;
1662 return Error("unable to allocate %" PRIu64
1663 " bytes of memory with permissions %s",
1664 size, GetPermissionsAsCString(permissions));
1665 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001666#endif
1667}
1668
Kate Stoneb9c1b512016-09-06 20:57:50 +00001669Error NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {
1670 // FIXME see comments in AllocateMemory - required lower-level
1671 // bits not in place yet (ThreadPlans)
1672 return Error("not implemented");
Todd Fialaaf245d12014-06-30 21:05:18 +00001673}
1674
Kate Stoneb9c1b512016-09-06 20:57:50 +00001675lldb::addr_t NativeProcessLinux::GetSharedLibraryInfoAddress() {
1676 // punt on this for now
1677 return LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00001678}
1679
Kate Stoneb9c1b512016-09-06 20:57:50 +00001680size_t NativeProcessLinux::UpdateThreads() {
1681 // The NativeProcessLinux monitoring threads are always up to date
1682 // with respect to thread state and they keep the thread list
1683 // populated properly. All this method needs to do is return the
1684 // thread count.
1685 return m_threads.size();
Todd Fialaaf245d12014-06-30 21:05:18 +00001686}
1687
Kate Stoneb9c1b512016-09-06 20:57:50 +00001688bool NativeProcessLinux::GetArchitecture(ArchSpec &arch) const {
1689 arch = m_arch;
1690 return true;
Todd Fialaaf245d12014-06-30 21:05:18 +00001691}
1692
Kate Stoneb9c1b512016-09-06 20:57:50 +00001693Error NativeProcessLinux::GetSoftwareBreakpointPCOffset(
1694 uint32_t &actual_opcode_size) {
1695 // FIXME put this behind a breakpoint protocol class that can be
1696 // set per architecture. Need ARM, MIPS support here.
1697 static const uint8_t g_i386_opcode[] = {0xCC};
1698 static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
Todd Fialaaf245d12014-06-30 21:05:18 +00001699
Kate Stoneb9c1b512016-09-06 20:57:50 +00001700 switch (m_arch.GetMachine()) {
1701 case llvm::Triple::x86:
1702 case llvm::Triple::x86_64:
1703 actual_opcode_size = static_cast<uint32_t>(sizeof(g_i386_opcode));
Mehdi Amini665be502016-11-11 05:07:57 +00001704 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00001705
Kate Stoneb9c1b512016-09-06 20:57:50 +00001706 case llvm::Triple::systemz:
1707 actual_opcode_size = static_cast<uint32_t>(sizeof(g_s390x_opcode));
Mehdi Amini665be502016-11-11 05:07:57 +00001708 return Error();
Ulrich Weigandbb00d0b2016-04-14 14:28:34 +00001709
Kate Stoneb9c1b512016-09-06 20:57:50 +00001710 case llvm::Triple::arm:
1711 case llvm::Triple::aarch64:
1712 case llvm::Triple::mips64:
1713 case llvm::Triple::mips64el:
1714 case llvm::Triple::mips:
1715 case llvm::Triple::mipsel:
1716 // On these architectures the PC don't get updated for breakpoint hits
1717 actual_opcode_size = 0;
Mehdi Amini665be502016-11-11 05:07:57 +00001718 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001719
1720 default:
1721 assert(false && "CPU type not supported!");
1722 return Error("CPU type not supported");
1723 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001724}
1725
Kate Stoneb9c1b512016-09-06 20:57:50 +00001726Error NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,
1727 bool hardware) {
1728 if (hardware)
1729 return Error("NativeProcessLinux does not support hardware breakpoints");
1730 else
1731 return SetSoftwareBreakpoint(addr, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00001732}
1733
Kate Stoneb9c1b512016-09-06 20:57:50 +00001734Error NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(
1735 size_t trap_opcode_size_hint, size_t &actual_opcode_size,
1736 const uint8_t *&trap_opcode_bytes) {
1737 // FIXME put this behind a breakpoint protocol class that can be set per
1738 // architecture. Need MIPS support here.
1739 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};
1740 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1741 // linux kernel does otherwise.
1742 static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1743 static const uint8_t g_i386_opcode[] = {0xCC};
1744 static const uint8_t g_mips64_opcode[] = {0x00, 0x00, 0x00, 0x0d};
1745 static const uint8_t g_mips64el_opcode[] = {0x0d, 0x00, 0x00, 0x00};
1746 static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
1747 static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
Todd Fialaaf245d12014-06-30 21:05:18 +00001748
Kate Stoneb9c1b512016-09-06 20:57:50 +00001749 switch (m_arch.GetMachine()) {
1750 case llvm::Triple::aarch64:
1751 trap_opcode_bytes = g_aarch64_opcode;
1752 actual_opcode_size = sizeof(g_aarch64_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001753 return Error();
Todd Fiala2afc5962014-08-21 16:42:31 +00001754
Kate Stoneb9c1b512016-09-06 20:57:50 +00001755 case llvm::Triple::arm:
1756 switch (trap_opcode_size_hint) {
1757 case 2:
1758 trap_opcode_bytes = g_thumb_breakpoint_opcode;
1759 actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001760 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001761 case 4:
1762 trap_opcode_bytes = g_arm_breakpoint_opcode;
1763 actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001764 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00001765 default:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001766 assert(false && "Unrecognised trap opcode size hint!");
1767 return Error("Unrecognised trap opcode size hint!");
Todd Fialaaf245d12014-06-30 21:05:18 +00001768 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001769
1770 case llvm::Triple::x86:
1771 case llvm::Triple::x86_64:
1772 trap_opcode_bytes = g_i386_opcode;
1773 actual_opcode_size = sizeof(g_i386_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001774 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001775
1776 case llvm::Triple::mips:
1777 case llvm::Triple::mips64:
1778 trap_opcode_bytes = g_mips64_opcode;
1779 actual_opcode_size = sizeof(g_mips64_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001780 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001781
1782 case llvm::Triple::mipsel:
1783 case llvm::Triple::mips64el:
1784 trap_opcode_bytes = g_mips64el_opcode;
1785 actual_opcode_size = sizeof(g_mips64el_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001786 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001787
1788 case llvm::Triple::systemz:
1789 trap_opcode_bytes = g_s390x_opcode;
1790 actual_opcode_size = sizeof(g_s390x_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001791 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001792
1793 default:
1794 assert(false && "CPU type not supported!");
1795 return Error("CPU type not supported");
1796 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001797}
1798
1799#if 0
1800ProcessMessage::CrashReason
1801NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
1802{
1803 ProcessMessage::CrashReason reason;
1804 assert(info->si_signo == SIGSEGV);
1805
1806 reason = ProcessMessage::eInvalidCrashReason;
1807
1808 switch (info->si_code)
1809 {
1810 default:
1811 assert(false && "unexpected si_code for SIGSEGV");
1812 break;
1813 case SI_KERNEL:
1814 // Linux will occasionally send spurious SI_KERNEL codes.
1815 // (this is poorly documented in sigaction)
1816 // One way to get this is via unaligned SIMD loads.
1817 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
1818 break;
1819 case SEGV_MAPERR:
1820 reason = ProcessMessage::eInvalidAddress;
1821 break;
1822 case SEGV_ACCERR:
1823 reason = ProcessMessage::ePrivilegedAddress;
1824 break;
1825 }
1826
1827 return reason;
1828}
1829#endif
1830
Todd Fialaaf245d12014-06-30 21:05:18 +00001831#if 0
1832ProcessMessage::CrashReason
1833NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
1834{
1835 ProcessMessage::CrashReason reason;
1836 assert(info->si_signo == SIGILL);
1837
1838 reason = ProcessMessage::eInvalidCrashReason;
1839
1840 switch (info->si_code)
1841 {
1842 default:
1843 assert(false && "unexpected si_code for SIGILL");
1844 break;
1845 case ILL_ILLOPC:
1846 reason = ProcessMessage::eIllegalOpcode;
1847 break;
1848 case ILL_ILLOPN:
1849 reason = ProcessMessage::eIllegalOperand;
1850 break;
1851 case ILL_ILLADR:
1852 reason = ProcessMessage::eIllegalAddressingMode;
1853 break;
1854 case ILL_ILLTRP:
1855 reason = ProcessMessage::eIllegalTrap;
1856 break;
1857 case ILL_PRVOPC:
1858 reason = ProcessMessage::ePrivilegedOpcode;
1859 break;
1860 case ILL_PRVREG:
1861 reason = ProcessMessage::ePrivilegedRegister;
1862 break;
1863 case ILL_COPROC:
1864 reason = ProcessMessage::eCoprocessorError;
1865 break;
1866 case ILL_BADSTK:
1867 reason = ProcessMessage::eInternalStackError;
1868 break;
1869 }
1870
1871 return reason;
1872}
1873#endif
1874
1875#if 0
1876ProcessMessage::CrashReason
1877NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
1878{
1879 ProcessMessage::CrashReason reason;
1880 assert(info->si_signo == SIGFPE);
1881
1882 reason = ProcessMessage::eInvalidCrashReason;
1883
1884 switch (info->si_code)
1885 {
1886 default:
1887 assert(false && "unexpected si_code for SIGFPE");
1888 break;
1889 case FPE_INTDIV:
1890 reason = ProcessMessage::eIntegerDivideByZero;
1891 break;
1892 case FPE_INTOVF:
1893 reason = ProcessMessage::eIntegerOverflow;
1894 break;
1895 case FPE_FLTDIV:
1896 reason = ProcessMessage::eFloatDivideByZero;
1897 break;
1898 case FPE_FLTOVF:
1899 reason = ProcessMessage::eFloatOverflow;
1900 break;
1901 case FPE_FLTUND:
1902 reason = ProcessMessage::eFloatUnderflow;
1903 break;
1904 case FPE_FLTRES:
1905 reason = ProcessMessage::eFloatInexactResult;
1906 break;
1907 case FPE_FLTINV:
1908 reason = ProcessMessage::eFloatInvalidOperation;
1909 break;
1910 case FPE_FLTSUB:
1911 reason = ProcessMessage::eFloatSubscriptRange;
1912 break;
1913 }
1914
1915 return reason;
1916}
1917#endif
1918
1919#if 0
1920ProcessMessage::CrashReason
1921NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
1922{
1923 ProcessMessage::CrashReason reason;
1924 assert(info->si_signo == SIGBUS);
1925
1926 reason = ProcessMessage::eInvalidCrashReason;
1927
1928 switch (info->si_code)
1929 {
1930 default:
1931 assert(false && "unexpected si_code for SIGBUS");
1932 break;
1933 case BUS_ADRALN:
1934 reason = ProcessMessage::eIllegalAlignment;
1935 break;
1936 case BUS_ADRERR:
1937 reason = ProcessMessage::eIllegalAddress;
1938 break;
1939 case BUS_OBJERR:
1940 reason = ProcessMessage::eHardwareError;
1941 break;
1942 }
1943
1944 return reason;
1945}
1946#endif
1947
Kate Stoneb9c1b512016-09-06 20:57:50 +00001948Error NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
1949 size_t &bytes_read) {
1950 if (ProcessVmReadvSupported()) {
1951 // The process_vm_readv path is about 50 times faster than ptrace api. We
1952 // want to use
1953 // this syscall if it is supported.
Pavel Labathdf7c6992015-06-17 18:38:49 +00001954
Kate Stoneb9c1b512016-09-06 20:57:50 +00001955 const ::pid_t pid = GetID();
Pavel Labathdf7c6992015-06-17 18:38:49 +00001956
Kate Stoneb9c1b512016-09-06 20:57:50 +00001957 struct iovec local_iov, remote_iov;
1958 local_iov.iov_base = buf;
1959 local_iov.iov_len = size;
1960 remote_iov.iov_base = reinterpret_cast<void *>(addr);
1961 remote_iov.iov_len = size;
Pavel Labathdf7c6992015-06-17 18:38:49 +00001962
Kate Stoneb9c1b512016-09-06 20:57:50 +00001963 bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
1964 const bool success = bytes_read == size;
Pavel Labathdf7c6992015-06-17 18:38:49 +00001965
Pavel Labatha6321a82017-01-19 15:26:04 +00001966 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1967 LLDB_LOG(log,
1968 "using process_vm_readv to read {0} bytes from inferior "
1969 "address {1:x}: {2}",
1970 size, addr, success ? "Success" : strerror(errno));
Pavel Labath19cbe962015-07-21 13:20:32 +00001971
Kate Stoneb9c1b512016-09-06 20:57:50 +00001972 if (success)
Mehdi Amini665be502016-11-11 05:07:57 +00001973 return Error();
Pavel Labatha6321a82017-01-19 15:26:04 +00001974 // else the call failed for some reason, let's retry the read using ptrace
1975 // api.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001976 }
Pavel Labath19cbe962015-07-21 13:20:32 +00001977
Kate Stoneb9c1b512016-09-06 20:57:50 +00001978 unsigned char *dst = static_cast<unsigned char *>(buf);
1979 size_t remainder;
1980 long data;
Pavel Labath19cbe962015-07-21 13:20:32 +00001981
Pavel Labatha6321a82017-01-19 15:26:04 +00001982 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1983 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
Pavel Labath19cbe962015-07-21 13:20:32 +00001984
Kate Stoneb9c1b512016-09-06 20:57:50 +00001985 for (bytes_read = 0; bytes_read < size; bytes_read += remainder) {
1986 Error error = NativeProcessLinux::PtraceWrapper(
1987 PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data);
Pavel Labatha6321a82017-01-19 15:26:04 +00001988 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001989 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001990
1991 remainder = size - bytes_read;
1992 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
1993
1994 // Copy the data into our buffer
1995 memcpy(dst, &data, remainder);
1996
Pavel Labatha6321a82017-01-19 15:26:04 +00001997 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001998 addr += k_ptrace_word_size;
1999 dst += k_ptrace_word_size;
2000 }
Mehdi Amini665be502016-11-11 05:07:57 +00002001 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00002002}
2003
Kate Stoneb9c1b512016-09-06 20:57:50 +00002004Error NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf,
2005 size_t size,
2006 size_t &bytes_read) {
2007 Error error = ReadMemory(addr, buf, size, bytes_read);
2008 if (error.Fail())
Pavel Labath19cbe962015-07-21 13:20:32 +00002009 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002010 return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00002011}
2012
Kate Stoneb9c1b512016-09-06 20:57:50 +00002013Error NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,
2014 size_t size, size_t &bytes_written) {
2015 const unsigned char *src = static_cast<const unsigned char *>(buf);
2016 size_t remainder;
2017 Error error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002018
Pavel Labatha6321a82017-01-19 15:26:04 +00002019 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
2020 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00002021
Kate Stoneb9c1b512016-09-06 20:57:50 +00002022 for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
2023 remainder = size - bytes_written;
2024 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
Chaoren Lin97ccc292015-02-03 01:51:12 +00002025
Kate Stoneb9c1b512016-09-06 20:57:50 +00002026 if (remainder == k_ptrace_word_size) {
2027 unsigned long data = 0;
2028 memcpy(&data, src, k_ptrace_word_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00002029
Pavel Labatha6321a82017-01-19 15:26:04 +00002030 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002031 error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(),
2032 (void *)addr, (void *)data);
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 } else {
2036 unsigned char buff[8];
2037 size_t bytes_read;
2038 error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
Pavel Labatha6321a82017-01-19 15:26:04 +00002039 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00002040 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002041
2042 memcpy(buff, src, remainder);
2043
2044 size_t bytes_written_rec;
2045 error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
Pavel Labatha6321a82017-01-19 15:26:04 +00002046 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00002047 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002048
Pavel Labatha6321a82017-01-19 15:26:04 +00002049 LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src,
2050 *(unsigned long *)buff);
Todd Fialaaf245d12014-06-30 21:05:18 +00002051 }
2052
Kate Stoneb9c1b512016-09-06 20:57:50 +00002053 addr += k_ptrace_word_size;
2054 src += k_ptrace_word_size;
2055 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002056 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002057}
2058
Kate Stoneb9c1b512016-09-06 20:57:50 +00002059Error NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) {
2060 return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
2061}
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002062
Kate Stoneb9c1b512016-09-06 20:57:50 +00002063Error NativeProcessLinux::GetEventMessage(lldb::tid_t tid,
2064 unsigned long *message) {
2065 return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
2066}
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002067
Kate Stoneb9c1b512016-09-06 20:57:50 +00002068Error NativeProcessLinux::Detach(lldb::tid_t tid) {
2069 if (tid == LLDB_INVALID_THREAD_ID)
Mehdi Amini665be502016-11-11 05:07:57 +00002070 return Error();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002071
Kate Stoneb9c1b512016-09-06 20:57:50 +00002072 return PtraceWrapper(PTRACE_DETACH, tid);
2073}
2074
2075bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {
2076 for (auto thread_sp : m_threads) {
2077 assert(thread_sp && "thread list should not contain NULL threads");
2078 if (thread_sp->GetID() == thread_id) {
2079 // We have this thread.
2080 return true;
Todd Fialaaf245d12014-06-30 21:05:18 +00002081 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002082 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002083
Kate Stoneb9c1b512016-09-06 20:57:50 +00002084 // We don't have this thread.
2085 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00002086}
2087
Kate Stoneb9c1b512016-09-06 20:57:50 +00002088bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002089 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2090 LLDB_LOG(log, "tid: {0})", thread_id);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002091
2092 bool found = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002093 for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
2094 if (*it && ((*it)->GetID() == thread_id)) {
2095 m_threads.erase(it);
2096 found = true;
2097 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00002098 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002099 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002100
Kate Stoneb9c1b512016-09-06 20:57:50 +00002101 SignalIfAllThreadsStopped();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002102 return found;
Todd Fialaaf245d12014-06-30 21:05:18 +00002103}
2104
Kate Stoneb9c1b512016-09-06 20:57:50 +00002105NativeThreadLinuxSP NativeProcessLinux::AddThread(lldb::tid_t thread_id) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002106 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
2107 LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
Todd Fialaaf245d12014-06-30 21:05:18 +00002108
Kate Stoneb9c1b512016-09-06 20:57:50 +00002109 assert(!HasThreadNoLock(thread_id) &&
2110 "attempted to add a thread by id that already exists");
Todd Fialaaf245d12014-06-30 21:05:18 +00002111
Kate Stoneb9c1b512016-09-06 20:57:50 +00002112 // If this is the first thread, save it as the current thread
2113 if (m_threads.empty())
2114 SetCurrentThreadID(thread_id);
Todd Fialaaf245d12014-06-30 21:05:18 +00002115
Kate Stoneb9c1b512016-09-06 20:57:50 +00002116 auto thread_sp = std::make_shared<NativeThreadLinux>(this, thread_id);
2117 m_threads.push_back(thread_sp);
2118 return thread_sp;
2119}
Todd Fialaaf245d12014-06-30 21:05:18 +00002120
Kate Stoneb9c1b512016-09-06 20:57:50 +00002121Error NativeProcessLinux::FixupBreakpointPCAsNeeded(NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002122 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_BREAKPOINTS));
Todd Fialaaf245d12014-06-30 21:05:18 +00002123
Kate Stoneb9c1b512016-09-06 20:57:50 +00002124 Error error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002125
Kate Stoneb9c1b512016-09-06 20:57:50 +00002126 // Find out the size of a breakpoint (might depend on where we are in the
2127 // code).
2128 NativeRegisterContextSP context_sp = thread.GetRegisterContext();
2129 if (!context_sp) {
2130 error.SetErrorString("cannot get a NativeRegisterContext for the thread");
Pavel Labatha6321a82017-01-19 15:26:04 +00002131 LLDB_LOG(log, "failed: {0}", error);
Todd Fialaaf245d12014-06-30 21:05:18 +00002132 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002133 }
Chaoren Linfa03ad22015-02-03 01:50:42 +00002134
Kate Stoneb9c1b512016-09-06 20:57:50 +00002135 uint32_t breakpoint_size = 0;
2136 error = GetSoftwareBreakpointPCOffset(breakpoint_size);
2137 if (error.Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002138 LLDB_LOG(log, "GetBreakpointSize() failed: {0}", error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002139 return error;
Pavel Labatha6321a82017-01-19 15:26:04 +00002140 } else
2141 LLDB_LOG(log, "breakpoint size: {0}", breakpoint_size);
Pavel Labathc0765592015-05-06 10:46:34 +00002142
Kate Stoneb9c1b512016-09-06 20:57:50 +00002143 // First try probing for a breakpoint at a software breakpoint location: PC -
2144 // breakpoint size.
2145 const lldb::addr_t initial_pc_addr =
2146 context_sp->GetPCfromBreakpointLocation();
2147 lldb::addr_t breakpoint_addr = initial_pc_addr;
2148 if (breakpoint_size > 0) {
2149 // Do not allow breakpoint probe to wrap around.
2150 if (breakpoint_addr >= breakpoint_size)
2151 breakpoint_addr -= breakpoint_size;
2152 }
2153
2154 // Check if we stopped because of a breakpoint.
2155 NativeBreakpointSP breakpoint_sp;
2156 error = m_breakpoint_list.GetBreakpoint(breakpoint_addr, breakpoint_sp);
2157 if (!error.Success() || !breakpoint_sp) {
2158 // We didn't find one at a software probe location. Nothing to do.
Pavel Labatha6321a82017-01-19 15:26:04 +00002159 LLDB_LOG(log,
2160 "pid {0} no lldb breakpoint found at current pc with "
2161 "adjustment: {1}",
2162 GetID(), breakpoint_addr);
Mehdi Amini665be502016-11-11 05:07:57 +00002163 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002164 }
2165
2166 // If the breakpoint is not a software breakpoint, nothing to do.
2167 if (!breakpoint_sp->IsSoftwareBreakpoint()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002168 LLDB_LOG(
2169 log,
2170 "pid {0} breakpoint found at {1:x}, not software, nothing to adjust",
2171 GetID(), breakpoint_addr);
Mehdi Amini665be502016-11-11 05:07:57 +00002172 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002173 }
2174
2175 //
2176 // We have a software breakpoint and need to adjust the PC.
2177 //
2178
2179 // Sanity check.
2180 if (breakpoint_size == 0) {
2181 // Nothing to do! How did we get here?
Pavel Labatha6321a82017-01-19 15:26:04 +00002182 LLDB_LOG(log,
2183 "pid {0} breakpoint found at {1:x}, it is software, but the "
2184 "size is zero, nothing to do (unexpected)",
2185 GetID(), breakpoint_addr);
Mehdi Amini665be502016-11-11 05:07:57 +00002186 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002187 }
2188
2189 // Change the program counter.
Pavel Labatha6321a82017-01-19 15:26:04 +00002190 LLDB_LOG(log, "pid {0} tid {1}: changing PC from {2:x} to {3:x}", GetID(),
2191 thread.GetID(), initial_pc_addr, breakpoint_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002192
2193 error = context_sp->SetPC(breakpoint_addr);
2194 if (error.Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002195 LLDB_LOG(log, "pid {0} tid {1}: failed to set PC: {2}", GetID(),
2196 thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002197 return error;
2198 }
2199
2200 return error;
2201}
2202
2203Error NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,
2204 FileSpec &file_spec) {
Tamas Berghammera6f57952017-01-03 16:29:43 +00002205 Error error = PopulateMemoryRegionCache();
2206 if (error.Fail())
2207 return error;
2208
Kate Stoneb9c1b512016-09-06 20:57:50 +00002209 FileSpec module_file_spec(module_path, true);
2210
Kate Stoneb9c1b512016-09-06 20:57:50 +00002211 file_spec.Clear();
Tamas Berghammera6f57952017-01-03 16:29:43 +00002212 for (const auto &it : m_mem_region_cache) {
2213 if (it.second.GetFilename() == module_file_spec.GetFilename()) {
2214 file_spec = it.second;
2215 return Error();
2216 }
2217 }
2218 return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
2219 module_file_spec.GetFilename().AsCString(), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002220}
2221
2222Error NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
2223 lldb::addr_t &load_addr) {
2224 load_addr = LLDB_INVALID_ADDRESS;
Tamas Berghammera6f57952017-01-03 16:29:43 +00002225 Error error = PopulateMemoryRegionCache();
2226 if (error.Fail())
2227 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002228
Tamas Berghammera6f57952017-01-03 16:29:43 +00002229 FileSpec file(file_name, false);
2230 for (const auto &it : m_mem_region_cache) {
2231 if (it.second == file) {
2232 load_addr = it.first.GetRange().GetRangeBase();
2233 return Error();
2234 }
2235 }
2236 return Error("No load address found for specified file.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002237}
2238
2239NativeThreadLinuxSP NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {
2240 return std::static_pointer_cast<NativeThreadLinux>(
2241 NativeProcessProtocol::GetThreadByID(tid));
2242}
2243
2244Error NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,
2245 lldb::StateType state, int signo) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002246 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2247 LLDB_LOG(log, "tid: {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002248
2249 // Before we do the resume below, first check if we have a pending
2250 // stop notification that is currently waiting for
2251 // all threads to stop. This is potentially a buggy situation since
2252 // we're ostensibly waiting for threads to stop before we send out the
2253 // pending notification, and here we are resuming one before we send
2254 // out the pending stop notification.
Pavel Labatha6321a82017-01-19 15:26:04 +00002255 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
2256 LLDB_LOG(log,
2257 "about to resume tid {0} per explicit request but we have a "
2258 "pending stop notification (tid {1}) that is actively "
2259 "waiting for this thread to stop. Valid sequence of events?",
2260 thread.GetID(), m_pending_notification_tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002261 }
2262
2263 // Request a resume. We expect this to be synchronous and the system
2264 // to reflect it is running after this completes.
2265 switch (state) {
2266 case eStateRunning: {
2267 const auto resume_result = thread.Resume(signo);
2268 if (resume_result.Success())
2269 SetState(eStateRunning, true);
2270 return resume_result;
2271 }
2272 case eStateStepping: {
2273 const auto step_result = thread.SingleStep(signo);
2274 if (step_result.Success())
2275 SetState(eStateRunning, true);
2276 return step_result;
2277 }
2278 default:
Pavel Labath8198db32017-01-24 11:48:25 +00002279 LLDB_LOG(log, "Unhandled state {0}.", state);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002280 llvm_unreachable("Unhandled state for resume");
2281 }
Pavel Labathc0765592015-05-06 10:46:34 +00002282}
2283
2284//===----------------------------------------------------------------------===//
2285
Kate Stoneb9c1b512016-09-06 20:57:50 +00002286void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002287 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2288 LLDB_LOG(log, "about to process event: (triggering_tid: {0})",
2289 triggering_tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002290
2291 m_pending_notification_tid = triggering_tid;
2292
2293 // Request a stop for all the thread stops that need to be stopped
2294 // and are not already known to be stopped.
2295 for (const auto &thread_sp : m_threads) {
2296 if (StateIsRunningState(thread_sp->GetState()))
2297 static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
2298 }
2299
2300 SignalIfAllThreadsStopped();
Pavel Labatha6321a82017-01-19 15:26:04 +00002301 LLDB_LOG(log, "event processing done");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002302}
2303
2304void NativeProcessLinux::SignalIfAllThreadsStopped() {
2305 if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
2306 return; // No pending notification. Nothing to do.
2307
2308 for (const auto &thread_sp : m_threads) {
2309 if (StateIsRunningState(thread_sp->GetState()))
2310 return; // Some threads are still running. Don't signal yet.
2311 }
2312
2313 // We have a pending notification and all threads have stopped.
2314 Log *log(
2315 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
2316
2317 // Clear any temporary breakpoints we used to implement software single
2318 // stepping.
2319 for (const auto &thread_info : m_threads_stepping_with_breakpoint) {
2320 Error error = RemoveBreakpoint(thread_info.second);
2321 if (error.Fail())
Pavel Labatha6321a82017-01-19 15:26:04 +00002322 LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}",
2323 thread_info.first, error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002324 }
2325 m_threads_stepping_with_breakpoint.clear();
2326
2327 // Notify the delegate about the stop
2328 SetCurrentThreadID(m_pending_notification_tid);
2329 SetState(StateType::eStateStopped, true);
2330 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
2331}
2332
2333void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002334 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2335 LLDB_LOG(log, "tid: {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002336
2337 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID &&
2338 StateIsRunningState(thread.GetState())) {
2339 // We will need to wait for this new thread to stop as well before firing
2340 // the
2341 // notification.
2342 thread.RequestStop();
2343 }
2344}
2345
2346void NativeProcessLinux::SigchldHandler() {
Pavel Labatha6321a82017-01-19 15:26:04 +00002347 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002348 // Process all pending waitpid notifications.
2349 while (true) {
2350 int status = -1;
2351 ::pid_t wait_pid = waitpid(-1, &status, __WALL | __WNOTHREAD | WNOHANG);
2352
2353 if (wait_pid == 0)
2354 break; // We are done.
2355
2356 if (wait_pid == -1) {
2357 if (errno == EINTR)
2358 continue;
2359
2360 Error error(errno, eErrorTypePOSIX);
Pavel Labatha6321a82017-01-19 15:26:04 +00002361 LLDB_LOG(log, "waitpid (-1, &status, _) failed: {0}", error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002362 break;
Pavel Labathc0765592015-05-06 10:46:34 +00002363 }
2364
Kate Stoneb9c1b512016-09-06 20:57:50 +00002365 bool exited = false;
2366 int signal = 0;
2367 int exit_status = 0;
2368 const char *status_cstr = nullptr;
2369 if (WIFSTOPPED(status)) {
2370 signal = WSTOPSIG(status);
2371 status_cstr = "STOPPED";
2372 } else if (WIFEXITED(status)) {
2373 exit_status = WEXITSTATUS(status);
2374 status_cstr = "EXITED";
2375 exited = true;
2376 } else if (WIFSIGNALED(status)) {
2377 signal = WTERMSIG(status);
2378 status_cstr = "SIGNALED";
2379 if (wait_pid == static_cast<::pid_t>(GetID())) {
2380 exited = true;
2381 exit_status = -1;
2382 }
2383 } else
2384 status_cstr = "(\?\?\?)";
Pavel Labathc0765592015-05-06 10:46:34 +00002385
Pavel Labatha6321a82017-01-19 15:26:04 +00002386 LLDB_LOG(log,
2387 "waitpid (-1, &status, _) => pid = {0}, status = {1:x} "
2388 "({2}), signal = {3}, exit_state = {4}",
2389 wait_pid, status, status_cstr, signal, exit_status);
Pavel Labathc0765592015-05-06 10:46:34 +00002390
Kate Stoneb9c1b512016-09-06 20:57:50 +00002391 MonitorCallback(wait_pid, exited, signal, exit_status);
2392 }
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002393}
2394
2395// Wrapper for ptrace to catch errors and log calls.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002396// Note that ptrace sets errno on error because -1 can be a valid result (i.e.
2397// for PTRACE_PEEK*)
2398Error NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
2399 void *data, size_t data_size,
2400 long *result) {
2401 Error error;
2402 long int ret;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002403
Kate Stoneb9c1b512016-09-06 20:57:50 +00002404 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002405
Kate Stoneb9c1b512016-09-06 20:57:50 +00002406 PtraceDisplayBytes(req, data, data_size);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002407
Kate Stoneb9c1b512016-09-06 20:57:50 +00002408 errno = 0;
2409 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
2410 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2411 *(unsigned int *)addr, data);
2412 else
2413 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2414 addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002415
Kate Stoneb9c1b512016-09-06 20:57:50 +00002416 if (ret == -1)
2417 error.SetErrorToErrno();
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002418
Kate Stoneb9c1b512016-09-06 20:57:50 +00002419 if (result)
2420 *result = ret;
Pavel Labath4a9babb2015-06-30 17:04:49 +00002421
Pavel Labath28096202017-02-17 16:09:10 +00002422 LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data,
2423 data_size, ret);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002424
Kate Stoneb9c1b512016-09-06 20:57:50 +00002425 PtraceDisplayBytes(req, data, data_size);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002426
Pavel Labatha6321a82017-01-19 15:26:04 +00002427 if (error.Fail())
2428 LLDB_LOG(log, "ptrace() failed: {0}", error);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002429
Kate Stoneb9c1b512016-09-06 20:57:50 +00002430 return error;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002431}