blob: f7636502604f6b435458f6e8542a49481078efc8 [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 Turner39de3112014-09-09 20:54:56 +000032#include "lldb/Host/ThreadLauncher.h"
Pavel Labath2a86b552016-06-14 17:30:52 +000033#include "lldb/Host/common/NativeBreakpoint.h"
34#include "lldb/Host/common/NativeRegisterContext.h"
Pavel Labath4ee1c952017-02-06 18:36:58 +000035#include "lldb/Host/linux/Ptrace.h"
36#include "lldb/Host/linux/Uio.h"
Kamil Rytarowski816ae4b2017-02-01 14:30:40 +000037#include "lldb/Host/posix/ProcessLauncherPosixFork.h"
Pavel Labath2a86b552016-06-14 17:30:52 +000038#include "lldb/Symbol/ObjectFile.h"
Zachary Turner90aff472015-03-03 23:36:51 +000039#include "lldb/Target/Process.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000040#include "lldb/Target/ProcessLaunchInfo.h"
Pavel Labath5b981ab2015-05-29 12:53:54 +000041#include "lldb/Target/Target.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000042#include "lldb/Utility/Error.h"
Chaoren Linc16f5dc2015-03-19 23:28:10 +000043#include "lldb/Utility/LLDBAssert.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000044#include "lldb/Utility/PseudoTerminal.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
Kate Stoneb9c1b512016-09-06 20:57:50 +00001040 // This thread is stopped.
Pavel Labatha6321a82017-01-19 15:26:04 +00001041 LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001042 thread.SetStoppedBySignal(signo, &info);
1043
1044 // Send a stop to the debugger after we get all other threads to stop.
1045 StopRunningThreads(thread.GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +00001046}
1047
Tamas Berghammere7708682015-04-22 10:00:23 +00001048namespace {
1049
Kate Stoneb9c1b512016-09-06 20:57:50 +00001050struct EmulatorBaton {
1051 NativeProcessLinux *m_process;
1052 NativeRegisterContext *m_reg_context;
Tamas Berghammere7708682015-04-22 10:00:23 +00001053
Kate Stoneb9c1b512016-09-06 20:57:50 +00001054 // eRegisterKindDWARF -> RegsiterValue
1055 std::unordered_map<uint32_t, RegisterValue> m_register_values;
Pavel Labath6648fcc2015-04-27 09:21:14 +00001056
Kate Stoneb9c1b512016-09-06 20:57:50 +00001057 EmulatorBaton(NativeProcessLinux *process, NativeRegisterContext *reg_context)
1058 : m_process(process), m_reg_context(reg_context) {}
Tamas Berghammere7708682015-04-22 10:00:23 +00001059};
1060
1061} // anonymous namespace
1062
Kate Stoneb9c1b512016-09-06 20:57:50 +00001063static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
1064 const EmulateInstruction::Context &context,
1065 lldb::addr_t addr, void *dst, size_t length) {
1066 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
Tamas Berghammere7708682015-04-22 10:00:23 +00001067
Kate Stoneb9c1b512016-09-06 20:57:50 +00001068 size_t bytes_read;
1069 emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
1070 return bytes_read;
Tamas Berghammere7708682015-04-22 10:00:23 +00001071}
1072
Kate Stoneb9c1b512016-09-06 20:57:50 +00001073static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
1074 const RegisterInfo *reg_info,
1075 RegisterValue &reg_value) {
1076 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
Tamas Berghammere7708682015-04-22 10:00:23 +00001077
Kate Stoneb9c1b512016-09-06 20:57:50 +00001078 auto it = emulator_baton->m_register_values.find(
1079 reg_info->kinds[eRegisterKindDWARF]);
1080 if (it != emulator_baton->m_register_values.end()) {
1081 reg_value = it->second;
1082 return true;
1083 }
1084
1085 // The emulator only fill in the dwarf regsiter numbers (and in some case
1086 // the generic register numbers). Get the full register info from the
1087 // register context based on the dwarf register numbers.
1088 const RegisterInfo *full_reg_info =
1089 emulator_baton->m_reg_context->GetRegisterInfo(
1090 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
1091
1092 Error error =
1093 emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
1094 if (error.Success())
1095 return true;
1096
1097 return false;
1098}
1099
1100static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
1101 const EmulateInstruction::Context &context,
1102 const RegisterInfo *reg_info,
1103 const RegisterValue &reg_value) {
1104 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
1105 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
1106 reg_value;
1107 return true;
1108}
1109
1110static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
1111 const EmulateInstruction::Context &context,
1112 lldb::addr_t addr, const void *dst,
1113 size_t length) {
1114 return length;
1115}
1116
1117static lldb::addr_t ReadFlags(NativeRegisterContext *regsiter_context) {
1118 const RegisterInfo *flags_info = regsiter_context->GetRegisterInfo(
1119 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1120 return regsiter_context->ReadRegisterAsUnsigned(flags_info,
1121 LLDB_INVALID_ADDRESS);
1122}
1123
1124Error NativeProcessLinux::SetupSoftwareSingleStepping(
1125 NativeThreadLinux &thread) {
1126 Error error;
1127 NativeRegisterContextSP register_context_sp = thread.GetRegisterContext();
1128
1129 std::unique_ptr<EmulateInstruction> emulator_ap(
1130 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying,
1131 nullptr));
1132
1133 if (emulator_ap == nullptr)
1134 return Error("Instruction emulator not found!");
1135
1136 EmulatorBaton baton(this, register_context_sp.get());
1137 emulator_ap->SetBaton(&baton);
1138 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
1139 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
1140 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
1141 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
1142
1143 if (!emulator_ap->ReadInstruction())
1144 return Error("Read instruction failed!");
1145
1146 bool emulation_result =
1147 emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
1148
1149 const RegisterInfo *reg_info_pc = register_context_sp->GetRegisterInfo(
1150 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1151 const RegisterInfo *reg_info_flags = register_context_sp->GetRegisterInfo(
1152 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1153
1154 auto pc_it =
1155 baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1156 auto flags_it =
1157 baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
1158
1159 lldb::addr_t next_pc;
1160 lldb::addr_t next_flags;
1161 if (emulation_result) {
1162 assert(pc_it != baton.m_register_values.end() &&
1163 "Emulation was successfull but PC wasn't updated");
1164 next_pc = pc_it->second.GetAsUInt64();
1165
1166 if (flags_it != baton.m_register_values.end())
1167 next_flags = flags_it->second.GetAsUInt64();
1168 else
1169 next_flags = ReadFlags(register_context_sp.get());
1170 } else if (pc_it == baton.m_register_values.end()) {
1171 // Emulate instruction failed and it haven't changed PC. Advance PC
1172 // with the size of the current opcode because the emulation of all
1173 // PC modifying instruction should be successful. The failure most
1174 // likely caused by a not supported instruction which don't modify PC.
1175 next_pc =
1176 register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
1177 next_flags = ReadFlags(register_context_sp.get());
1178 } else {
1179 // The instruction emulation failed after it modified the PC. It is an
1180 // unknown error where we can't continue because the next instruction is
1181 // modifying the PC but we don't know how.
1182 return Error("Instruction emulation failed unexpectedly.");
1183 }
1184
1185 if (m_arch.GetMachine() == llvm::Triple::arm) {
1186 if (next_flags & 0x20) {
1187 // Thumb mode
1188 error = SetSoftwareBreakpoint(next_pc, 2);
1189 } else {
1190 // Arm mode
1191 error = SetSoftwareBreakpoint(next_pc, 4);
Pavel Labath6648fcc2015-04-27 09:21:14 +00001192 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001193 } else if (m_arch.GetMachine() == llvm::Triple::mips64 ||
1194 m_arch.GetMachine() == llvm::Triple::mips64el ||
1195 m_arch.GetMachine() == llvm::Triple::mips ||
1196 m_arch.GetMachine() == llvm::Triple::mipsel)
1197 error = SetSoftwareBreakpoint(next_pc, 4);
1198 else {
1199 // No size hint is given for the next breakpoint
1200 error = SetSoftwareBreakpoint(next_pc, 0);
1201 }
Pavel Labath6648fcc2015-04-27 09:21:14 +00001202
Pavel Labath42eb6902016-10-26 11:13:56 +00001203 // If setting the breakpoint fails because next_pc is out of
1204 // the address space, ignore it and let the debugee segfault.
1205 if (error.GetError() == EIO || error.GetError() == EFAULT) {
Mehdi Amini665be502016-11-11 05:07:57 +00001206 return Error();
Pavel Labath42eb6902016-10-26 11:13:56 +00001207 } else if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001208 return error;
Tamas Berghammere7708682015-04-22 10:00:23 +00001209
Kate Stoneb9c1b512016-09-06 20:57:50 +00001210 m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001211
Mehdi Amini665be502016-11-11 05:07:57 +00001212 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001213}
1214
1215bool NativeProcessLinux::SupportHardwareSingleStepping() const {
1216 if (m_arch.GetMachine() == llvm::Triple::arm ||
1217 m_arch.GetMachine() == llvm::Triple::mips64 ||
1218 m_arch.GetMachine() == llvm::Triple::mips64el ||
1219 m_arch.GetMachine() == llvm::Triple::mips ||
1220 m_arch.GetMachine() == llvm::Triple::mipsel)
Pavel Labath6648fcc2015-04-27 09:21:14 +00001221 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001222 return true;
Tamas Berghammere7708682015-04-22 10:00:23 +00001223}
1224
Kate Stoneb9c1b512016-09-06 20:57:50 +00001225Error NativeProcessLinux::Resume(const ResumeActionList &resume_actions) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001226 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1227 LLDB_LOG(log, "pid {0}", GetID());
Tamas Berghammere7708682015-04-22 10:00:23 +00001228
Kate Stoneb9c1b512016-09-06 20:57:50 +00001229 bool software_single_step = !SupportHardwareSingleStepping();
Tamas Berghammere7708682015-04-22 10:00:23 +00001230
Kate Stoneb9c1b512016-09-06 20:57:50 +00001231 if (software_single_step) {
1232 for (auto thread_sp : m_threads) {
1233 assert(thread_sp && "thread list should not contain NULL threads");
Tamas Berghammere7708682015-04-22 10:00:23 +00001234
Kate Stoneb9c1b512016-09-06 20:57:50 +00001235 const ResumeAction *const action =
1236 resume_actions.GetActionForThread(thread_sp->GetID(), true);
1237 if (action == nullptr)
1238 continue;
Tamas Berghammere7708682015-04-22 10:00:23 +00001239
Kate Stoneb9c1b512016-09-06 20:57:50 +00001240 if (action->state == eStateStepping) {
1241 Error error = SetupSoftwareSingleStepping(
1242 static_cast<NativeThreadLinux &>(*thread_sp));
1243 if (error.Fail())
1244 return error;
1245 }
Tamas Berghammere7708682015-04-22 10:00:23 +00001246 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001247 }
1248
1249 for (auto thread_sp : m_threads) {
1250 assert(thread_sp && "thread list should not contain NULL threads");
1251
1252 const ResumeAction *const action =
1253 resume_actions.GetActionForThread(thread_sp->GetID(), true);
1254
1255 if (action == nullptr) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001256 LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
1257 thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001258 continue;
Tamas Berghammere7708682015-04-22 10:00:23 +00001259 }
1260
Pavel Labatha6321a82017-01-19 15:26:04 +00001261 LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}",
Pavel Labath8198db32017-01-24 11:48:25 +00001262 action->state, GetID(), thread_sp->GetID());
Tamas Berghammere7708682015-04-22 10:00:23 +00001263
Kate Stoneb9c1b512016-09-06 20:57:50 +00001264 switch (action->state) {
1265 case eStateRunning:
1266 case eStateStepping: {
1267 // Run the thread, possibly feeding it the signal.
1268 const int signo = action->signal;
1269 ResumeThread(static_cast<NativeThreadLinux &>(*thread_sp), action->state,
1270 signo);
1271 break;
1272 }
Tamas Berghammere7708682015-04-22 10:00:23 +00001273
Kate Stoneb9c1b512016-09-06 20:57:50 +00001274 case eStateSuspended:
1275 case eStateStopped:
Pavel Labatha6321a82017-01-19 15:26:04 +00001276 llvm_unreachable("Unexpected state");
Tamas Berghammere7708682015-04-22 10:00:23 +00001277
Kate Stoneb9c1b512016-09-06 20:57:50 +00001278 default:
1279 return Error("NativeProcessLinux::%s (): unexpected state %s specified "
1280 "for pid %" PRIu64 ", tid %" PRIu64,
1281 __FUNCTION__, StateAsCString(action->state), GetID(),
1282 thread_sp->GetID());
1283 }
1284 }
1285
Mehdi Amini665be502016-11-11 05:07:57 +00001286 return Error();
Tamas Berghammere7708682015-04-22 10:00:23 +00001287}
1288
Kate Stoneb9c1b512016-09-06 20:57:50 +00001289Error NativeProcessLinux::Halt() {
1290 Error error;
1291
1292 if (kill(GetID(), SIGSTOP) != 0)
1293 error.SetErrorToErrno();
1294
1295 return error;
Tamas Berghammere7708682015-04-22 10:00:23 +00001296}
1297
Kate Stoneb9c1b512016-09-06 20:57:50 +00001298Error NativeProcessLinux::Detach() {
1299 Error error;
1300
1301 // Stop monitoring the inferior.
1302 m_sigchld_handle.reset();
1303
1304 // Tell ptrace to detach from the process.
1305 if (GetID() == LLDB_INVALID_PROCESS_ID)
1306 return error;
1307
1308 for (auto thread_sp : m_threads) {
1309 Error e = Detach(thread_sp->GetID());
1310 if (e.Fail())
1311 error =
1312 e; // Save the error, but still attempt to detach from other threads.
1313 }
1314
1315 return error;
1316}
1317
1318Error NativeProcessLinux::Signal(int signo) {
1319 Error error;
1320
Pavel Labatha6321a82017-01-19 15:26:04 +00001321 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1322 LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo,
1323 Host::GetSignalAsCString(signo), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001324
1325 if (kill(GetID(), signo))
1326 error.SetErrorToErrno();
1327
1328 return error;
1329}
1330
1331Error NativeProcessLinux::Interrupt() {
1332 // Pick a running thread (or if none, a not-dead stopped thread) as
1333 // the chosen thread that will be the stop-reason thread.
Pavel Labatha6321a82017-01-19 15:26:04 +00001334 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001335
1336 NativeThreadProtocolSP running_thread_sp;
1337 NativeThreadProtocolSP stopped_thread_sp;
1338
Pavel Labatha6321a82017-01-19 15:26:04 +00001339 LLDB_LOG(log, "selecting running thread for interrupt target");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001340 for (auto thread_sp : m_threads) {
1341 // The thread shouldn't be null but lets just cover that here.
1342 if (!thread_sp)
1343 continue;
1344
1345 // If we have a running or stepping thread, we'll call that the
1346 // target of the interrupt.
1347 const auto thread_state = thread_sp->GetState();
1348 if (thread_state == eStateRunning || thread_state == eStateStepping) {
1349 running_thread_sp = thread_sp;
1350 break;
1351 } else if (!stopped_thread_sp && StateIsStoppedState(thread_state, true)) {
1352 // Remember the first non-dead stopped thread. We'll use that as a backup
1353 // if there are no running threads.
1354 stopped_thread_sp = thread_sp;
1355 }
1356 }
1357
1358 if (!running_thread_sp && !stopped_thread_sp) {
1359 Error error("found no running/stepping or live stopped threads as target "
1360 "for interrupt");
Pavel Labatha6321a82017-01-19 15:26:04 +00001361 LLDB_LOG(log, "skipping due to error: {0}", error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001362
1363 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001364 }
1365
1366 NativeThreadProtocolSP deferred_signal_thread_sp =
1367 running_thread_sp ? running_thread_sp : stopped_thread_sp;
1368
Pavel Labatha6321a82017-01-19 15:26:04 +00001369 LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(),
1370 running_thread_sp ? "running" : "stopped",
1371 deferred_signal_thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001372
1373 StopRunningThreads(deferred_signal_thread_sp->GetID());
1374
Mehdi Amini665be502016-11-11 05:07:57 +00001375 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00001376}
1377
Kate Stoneb9c1b512016-09-06 20:57:50 +00001378Error NativeProcessLinux::Kill() {
Pavel Labatha6321a82017-01-19 15:26:04 +00001379 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1380 LLDB_LOG(log, "pid {0}", GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +00001381
Kate Stoneb9c1b512016-09-06 20:57:50 +00001382 Error error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001383
Kate Stoneb9c1b512016-09-06 20:57:50 +00001384 switch (m_state) {
1385 case StateType::eStateInvalid:
1386 case StateType::eStateExited:
1387 case StateType::eStateCrashed:
1388 case StateType::eStateDetached:
1389 case StateType::eStateUnloaded:
1390 // Nothing to do - the process is already dead.
Pavel Labatha6321a82017-01-19 15:26:04 +00001391 LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
Pavel Labath8198db32017-01-24 11:48:25 +00001392 m_state);
Todd Fialaaf245d12014-06-30 21:05:18 +00001393 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001394
Kate Stoneb9c1b512016-09-06 20:57:50 +00001395 case StateType::eStateConnected:
1396 case StateType::eStateAttaching:
1397 case StateType::eStateLaunching:
1398 case StateType::eStateStopped:
1399 case StateType::eStateRunning:
1400 case StateType::eStateStepping:
1401 case StateType::eStateSuspended:
1402 // We can try to kill a process in these states.
1403 break;
1404 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001405
Kate Stoneb9c1b512016-09-06 20:57:50 +00001406 if (kill(GetID(), SIGKILL) != 0) {
1407 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +00001408 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001409 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001410
Kate Stoneb9c1b512016-09-06 20:57:50 +00001411 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001412}
1413
1414static Error
Kate Stoneb9c1b512016-09-06 20:57:50 +00001415ParseMemoryRegionInfoFromProcMapsLine(const std::string &maps_line,
1416 MemoryRegionInfo &memory_region_info) {
1417 memory_region_info.Clear();
Todd Fialaaf245d12014-06-30 21:05:18 +00001418
Kate Stoneb9c1b512016-09-06 20:57:50 +00001419 StringExtractor line_extractor(maps_line.c_str());
Todd Fialaaf245d12014-06-30 21:05:18 +00001420
Kate Stoneb9c1b512016-09-06 20:57:50 +00001421 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode
1422 // pathname
1423 // perms: rwxp (letter is present if set, '-' if not, final character is
1424 // p=private, s=shared).
Todd Fialaaf245d12014-06-30 21:05:18 +00001425
Kate Stoneb9c1b512016-09-06 20:57:50 +00001426 // Parse out the starting address
1427 lldb::addr_t start_address = line_extractor.GetHexMaxU64(false, 0);
Todd Fialaaf245d12014-06-30 21:05:18 +00001428
Kate Stoneb9c1b512016-09-06 20:57:50 +00001429 // Parse out hyphen separating start and end address from range.
1430 if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != '-'))
1431 return Error(
1432 "malformed /proc/{pid}/maps entry, missing dash between address range");
Todd Fialaaf245d12014-06-30 21:05:18 +00001433
Kate Stoneb9c1b512016-09-06 20:57:50 +00001434 // Parse out the ending address
1435 lldb::addr_t end_address = line_extractor.GetHexMaxU64(false, start_address);
Todd Fialaaf245d12014-06-30 21:05:18 +00001436
Kate Stoneb9c1b512016-09-06 20:57:50 +00001437 // Parse out the space after the address.
1438 if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != ' '))
1439 return Error("malformed /proc/{pid}/maps entry, missing space after range");
Todd Fialaaf245d12014-06-30 21:05:18 +00001440
Kate Stoneb9c1b512016-09-06 20:57:50 +00001441 // Save the range.
1442 memory_region_info.GetRange().SetRangeBase(start_address);
1443 memory_region_info.GetRange().SetRangeEnd(end_address);
Todd Fialaaf245d12014-06-30 21:05:18 +00001444
Kate Stoneb9c1b512016-09-06 20:57:50 +00001445 // Any memory region in /proc/{pid}/maps is by definition mapped into the
1446 // process.
1447 memory_region_info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
Howard Hellyerad007562016-07-07 08:21:28 +00001448
Kate Stoneb9c1b512016-09-06 20:57:50 +00001449 // Parse out each permission entry.
1450 if (line_extractor.GetBytesLeft() < 4)
1451 return Error("malformed /proc/{pid}/maps entry, missing some portion of "
1452 "permissions");
Todd Fialaaf245d12014-06-30 21:05:18 +00001453
Kate Stoneb9c1b512016-09-06 20:57:50 +00001454 // Handle read permission.
1455 const char read_perm_char = line_extractor.GetChar();
1456 if (read_perm_char == 'r')
1457 memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eYes);
1458 else if (read_perm_char == '-')
1459 memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1460 else
1461 return Error("unexpected /proc/{pid}/maps read permission char");
Todd Fialaaf245d12014-06-30 21:05:18 +00001462
Kate Stoneb9c1b512016-09-06 20:57:50 +00001463 // Handle write permission.
1464 const char write_perm_char = line_extractor.GetChar();
1465 if (write_perm_char == 'w')
1466 memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eYes);
1467 else if (write_perm_char == '-')
1468 memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1469 else
1470 return Error("unexpected /proc/{pid}/maps write permission char");
Todd Fialaaf245d12014-06-30 21:05:18 +00001471
Kate Stoneb9c1b512016-09-06 20:57:50 +00001472 // Handle execute permission.
1473 const char exec_perm_char = line_extractor.GetChar();
1474 if (exec_perm_char == 'x')
1475 memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes);
1476 else if (exec_perm_char == '-')
1477 memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1478 else
1479 return Error("unexpected /proc/{pid}/maps exec permission char");
Todd Fialaaf245d12014-06-30 21:05:18 +00001480
Kate Stoneb9c1b512016-09-06 20:57:50 +00001481 line_extractor.GetChar(); // Read the private bit
1482 line_extractor.SkipSpaces(); // Skip the separator
1483 line_extractor.GetHexMaxU64(false, 0); // Read the offset
1484 line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1485 line_extractor.GetChar(); // Read the device id separator
1486 line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1487 line_extractor.SkipSpaces(); // Skip the separator
1488 line_extractor.GetU64(0, 10); // Read the inode number
Tamas Berghammerd7d69f82016-07-22 12:55:35 +00001489
Kate Stoneb9c1b512016-09-06 20:57:50 +00001490 line_extractor.SkipSpaces();
1491 const char *name = line_extractor.Peek();
1492 if (name)
1493 memory_region_info.SetName(name);
Tamas Berghammerd7d69f82016-07-22 12:55:35 +00001494
Mehdi Amini665be502016-11-11 05:07:57 +00001495 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00001496}
1497
Kate Stoneb9c1b512016-09-06 20:57:50 +00001498Error NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr,
1499 MemoryRegionInfo &range_info) {
1500 // FIXME review that the final memory region returned extends to the end of
1501 // the virtual address space,
1502 // with no perms if it is not mapped.
Todd Fialaaf245d12014-06-30 21:05:18 +00001503
Kate Stoneb9c1b512016-09-06 20:57:50 +00001504 // Use an approach that reads memory regions from /proc/{pid}/maps.
1505 // Assume proc maps entries are in ascending order.
1506 // FIXME assert if we find differently.
Todd Fialaaf245d12014-06-30 21:05:18 +00001507
Kate Stoneb9c1b512016-09-06 20:57:50 +00001508 if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
1509 // We're done.
Tamas Berghammera6f57952017-01-03 16:29:43 +00001510 return Error("unsupported");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001511 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001512
Tamas Berghammera6f57952017-01-03 16:29:43 +00001513 Error error = PopulateMemoryRegionCache();
1514 if (error.Fail()) {
1515 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001516 }
1517
1518 lldb::addr_t prev_base_address = 0;
1519
1520 // FIXME start by finding the last region that is <= target address using
1521 // binary search. Data is sorted.
1522 // There can be a ton of regions on pthreads apps with lots of threads.
1523 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1524 ++it) {
Tamas Berghammera6f57952017-01-03 16:29:43 +00001525 MemoryRegionInfo &proc_entry_info = it->first;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001526
1527 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1528 assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
1529 "descending /proc/pid/maps entries detected, unexpected");
1530 prev_base_address = proc_entry_info.GetRange().GetRangeBase();
Hafiz Abid Qadeerb1554312017-01-20 10:24:03 +00001531 UNUSED_IF_ASSERT_DISABLED(prev_base_address);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001532
1533 // If the target address comes before this entry, indicate distance to next
1534 // region.
1535 if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1536 range_info.GetRange().SetRangeBase(load_addr);
1537 range_info.GetRange().SetByteSize(
1538 proc_entry_info.GetRange().GetRangeBase() - load_addr);
1539 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1540 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1541 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1542 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1543
1544 return error;
1545 } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1546 // The target address is within the memory region we're processing here.
1547 range_info = proc_entry_info;
1548 return error;
1549 }
1550
1551 // The target memory address comes somewhere after the region we just
1552 // parsed.
1553 }
1554
1555 // If we made it here, we didn't find an entry that contained the given
1556 // address. Return the
1557 // load_addr as start and the amount of bytes betwwen load address and the end
1558 // of the memory as
1559 // size.
1560 range_info.GetRange().SetRangeBase(load_addr);
1561 range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
1562 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1563 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1564 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1565 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1566 return error;
1567}
1568
Tamas Berghammera6f57952017-01-03 16:29:43 +00001569Error NativeProcessLinux::PopulateMemoryRegionCache() {
Pavel Labatha6321a82017-01-19 15:26:04 +00001570 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Tamas Berghammera6f57952017-01-03 16:29:43 +00001571
1572 // If our cache is empty, pull the latest. There should always be at least
1573 // one memory region if memory region handling is supported.
1574 if (!m_mem_region_cache.empty()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001575 LLDB_LOG(log, "reusing {0} cached memory region entries",
1576 m_mem_region_cache.size());
Tamas Berghammera6f57952017-01-03 16:29:43 +00001577 return Error();
1578 }
1579
1580 Error error = ProcFileReader::ProcessLineByLine(
1581 GetID(), "maps", [&](const std::string &line) -> bool {
1582 MemoryRegionInfo info;
1583 const Error parse_error =
1584 ParseMemoryRegionInfoFromProcMapsLine(line, info);
1585 if (parse_error.Success()) {
1586 m_mem_region_cache.emplace_back(
1587 info, FileSpec(info.GetName().GetCString(), true));
1588 return true;
1589 } else {
Pavel Labatha6321a82017-01-19 15:26:04 +00001590 LLDB_LOG(log, "failed to parse proc maps line '{0}': {1}", line,
1591 parse_error);
Tamas Berghammera6f57952017-01-03 16:29:43 +00001592 return false;
1593 }
1594 });
1595
1596 // If we had an error, we'll mark unsupported.
1597 if (error.Fail()) {
1598 m_supports_mem_region = LazyBool::eLazyBoolNo;
1599 return error;
1600 } else if (m_mem_region_cache.empty()) {
1601 // No entries after attempting to read them. This shouldn't happen if
1602 // /proc/{pid}/maps is supported. Assume we don't support map entries
1603 // via procfs.
Pavel Labatha6321a82017-01-19 15:26:04 +00001604 LLDB_LOG(log,
1605 "failed to find any procfs maps entries, assuming no support "
1606 "for memory region metadata retrieval");
Tamas Berghammera6f57952017-01-03 16:29:43 +00001607 m_supports_mem_region = LazyBool::eLazyBoolNo;
1608 error.SetErrorString("not supported");
1609 return error;
1610 }
1611
Pavel Labatha6321a82017-01-19 15:26:04 +00001612 LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps",
1613 m_mem_region_cache.size(), GetID());
Tamas Berghammera6f57952017-01-03 16:29:43 +00001614
1615 // We support memory retrieval, remember that.
1616 m_supports_mem_region = LazyBool::eLazyBoolYes;
1617 return Error();
1618}
1619
Kate Stoneb9c1b512016-09-06 20:57:50 +00001620void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001621 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1622 LLDB_LOG(log, "newBumpId={0}", newBumpId);
1623 LLDB_LOG(log, "clearing {0} entries from memory region cache",
1624 m_mem_region_cache.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001625 m_mem_region_cache.clear();
1626}
1627
1628Error NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions,
1629 lldb::addr_t &addr) {
1630// FIXME implementing this requires the equivalent of
1631// InferiorCallPOSIX::InferiorCallMmap, which depends on
1632// functional ThreadPlans working with Native*Protocol.
1633#if 1
1634 return Error("not implemented yet");
1635#else
1636 addr = LLDB_INVALID_ADDRESS;
1637
1638 unsigned prot = 0;
1639 if (permissions & lldb::ePermissionsReadable)
1640 prot |= eMmapProtRead;
1641 if (permissions & lldb::ePermissionsWritable)
1642 prot |= eMmapProtWrite;
1643 if (permissions & lldb::ePermissionsExecutable)
1644 prot |= eMmapProtExec;
1645
1646 // TODO implement this directly in NativeProcessLinux
1647 // (and lift to NativeProcessPOSIX if/when that class is
1648 // refactored out).
1649 if (InferiorCallMmap(this, addr, 0, size, prot,
1650 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
1651 m_addr_to_mmap_size[addr] = size;
Mehdi Amini665be502016-11-11 05:07:57 +00001652 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001653 } else {
1654 addr = LLDB_INVALID_ADDRESS;
1655 return Error("unable to allocate %" PRIu64
1656 " bytes of memory with permissions %s",
1657 size, GetPermissionsAsCString(permissions));
1658 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001659#endif
1660}
1661
Kate Stoneb9c1b512016-09-06 20:57:50 +00001662Error NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {
1663 // FIXME see comments in AllocateMemory - required lower-level
1664 // bits not in place yet (ThreadPlans)
1665 return Error("not implemented");
Todd Fialaaf245d12014-06-30 21:05:18 +00001666}
1667
Kate Stoneb9c1b512016-09-06 20:57:50 +00001668lldb::addr_t NativeProcessLinux::GetSharedLibraryInfoAddress() {
1669 // punt on this for now
1670 return LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00001671}
1672
Kate Stoneb9c1b512016-09-06 20:57:50 +00001673size_t NativeProcessLinux::UpdateThreads() {
1674 // The NativeProcessLinux monitoring threads are always up to date
1675 // with respect to thread state and they keep the thread list
1676 // populated properly. All this method needs to do is return the
1677 // thread count.
1678 return m_threads.size();
Todd Fialaaf245d12014-06-30 21:05:18 +00001679}
1680
Kate Stoneb9c1b512016-09-06 20:57:50 +00001681bool NativeProcessLinux::GetArchitecture(ArchSpec &arch) const {
1682 arch = m_arch;
1683 return true;
Todd Fialaaf245d12014-06-30 21:05:18 +00001684}
1685
Kate Stoneb9c1b512016-09-06 20:57:50 +00001686Error NativeProcessLinux::GetSoftwareBreakpointPCOffset(
1687 uint32_t &actual_opcode_size) {
1688 // FIXME put this behind a breakpoint protocol class that can be
1689 // set per architecture. Need ARM, MIPS support here.
1690 static const uint8_t g_i386_opcode[] = {0xCC};
1691 static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
Todd Fialaaf245d12014-06-30 21:05:18 +00001692
Kate Stoneb9c1b512016-09-06 20:57:50 +00001693 switch (m_arch.GetMachine()) {
1694 case llvm::Triple::x86:
1695 case llvm::Triple::x86_64:
1696 actual_opcode_size = static_cast<uint32_t>(sizeof(g_i386_opcode));
Mehdi Amini665be502016-11-11 05:07:57 +00001697 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00001698
Kate Stoneb9c1b512016-09-06 20:57:50 +00001699 case llvm::Triple::systemz:
1700 actual_opcode_size = static_cast<uint32_t>(sizeof(g_s390x_opcode));
Mehdi Amini665be502016-11-11 05:07:57 +00001701 return Error();
Ulrich Weigandbb00d0b2016-04-14 14:28:34 +00001702
Kate Stoneb9c1b512016-09-06 20:57:50 +00001703 case llvm::Triple::arm:
1704 case llvm::Triple::aarch64:
1705 case llvm::Triple::mips64:
1706 case llvm::Triple::mips64el:
1707 case llvm::Triple::mips:
1708 case llvm::Triple::mipsel:
1709 // On these architectures the PC don't get updated for breakpoint hits
1710 actual_opcode_size = 0;
Mehdi Amini665be502016-11-11 05:07:57 +00001711 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001712
1713 default:
1714 assert(false && "CPU type not supported!");
1715 return Error("CPU type not supported");
1716 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001717}
1718
Kate Stoneb9c1b512016-09-06 20:57:50 +00001719Error NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,
1720 bool hardware) {
1721 if (hardware)
1722 return Error("NativeProcessLinux does not support hardware breakpoints");
1723 else
1724 return SetSoftwareBreakpoint(addr, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00001725}
1726
Kate Stoneb9c1b512016-09-06 20:57:50 +00001727Error NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(
1728 size_t trap_opcode_size_hint, size_t &actual_opcode_size,
1729 const uint8_t *&trap_opcode_bytes) {
1730 // FIXME put this behind a breakpoint protocol class that can be set per
1731 // architecture. Need MIPS support here.
1732 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};
1733 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1734 // linux kernel does otherwise.
1735 static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1736 static const uint8_t g_i386_opcode[] = {0xCC};
1737 static const uint8_t g_mips64_opcode[] = {0x00, 0x00, 0x00, 0x0d};
1738 static const uint8_t g_mips64el_opcode[] = {0x0d, 0x00, 0x00, 0x00};
1739 static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
1740 static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
Todd Fialaaf245d12014-06-30 21:05:18 +00001741
Kate Stoneb9c1b512016-09-06 20:57:50 +00001742 switch (m_arch.GetMachine()) {
1743 case llvm::Triple::aarch64:
1744 trap_opcode_bytes = g_aarch64_opcode;
1745 actual_opcode_size = sizeof(g_aarch64_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001746 return Error();
Todd Fiala2afc5962014-08-21 16:42:31 +00001747
Kate Stoneb9c1b512016-09-06 20:57:50 +00001748 case llvm::Triple::arm:
1749 switch (trap_opcode_size_hint) {
1750 case 2:
1751 trap_opcode_bytes = g_thumb_breakpoint_opcode;
1752 actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001753 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001754 case 4:
1755 trap_opcode_bytes = g_arm_breakpoint_opcode;
1756 actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001757 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00001758 default:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001759 assert(false && "Unrecognised trap opcode size hint!");
1760 return Error("Unrecognised trap opcode size hint!");
Todd Fialaaf245d12014-06-30 21:05:18 +00001761 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001762
1763 case llvm::Triple::x86:
1764 case llvm::Triple::x86_64:
1765 trap_opcode_bytes = g_i386_opcode;
1766 actual_opcode_size = sizeof(g_i386_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001767 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001768
1769 case llvm::Triple::mips:
1770 case llvm::Triple::mips64:
1771 trap_opcode_bytes = g_mips64_opcode;
1772 actual_opcode_size = sizeof(g_mips64_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001773 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001774
1775 case llvm::Triple::mipsel:
1776 case llvm::Triple::mips64el:
1777 trap_opcode_bytes = g_mips64el_opcode;
1778 actual_opcode_size = sizeof(g_mips64el_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001779 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001780
1781 case llvm::Triple::systemz:
1782 trap_opcode_bytes = g_s390x_opcode;
1783 actual_opcode_size = sizeof(g_s390x_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001784 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001785
1786 default:
1787 assert(false && "CPU type not supported!");
1788 return Error("CPU type not supported");
1789 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001790}
1791
1792#if 0
1793ProcessMessage::CrashReason
1794NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
1795{
1796 ProcessMessage::CrashReason reason;
1797 assert(info->si_signo == SIGSEGV);
1798
1799 reason = ProcessMessage::eInvalidCrashReason;
1800
1801 switch (info->si_code)
1802 {
1803 default:
1804 assert(false && "unexpected si_code for SIGSEGV");
1805 break;
1806 case SI_KERNEL:
1807 // Linux will occasionally send spurious SI_KERNEL codes.
1808 // (this is poorly documented in sigaction)
1809 // One way to get this is via unaligned SIMD loads.
1810 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
1811 break;
1812 case SEGV_MAPERR:
1813 reason = ProcessMessage::eInvalidAddress;
1814 break;
1815 case SEGV_ACCERR:
1816 reason = ProcessMessage::ePrivilegedAddress;
1817 break;
1818 }
1819
1820 return reason;
1821}
1822#endif
1823
Todd Fialaaf245d12014-06-30 21:05:18 +00001824#if 0
1825ProcessMessage::CrashReason
1826NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
1827{
1828 ProcessMessage::CrashReason reason;
1829 assert(info->si_signo == SIGILL);
1830
1831 reason = ProcessMessage::eInvalidCrashReason;
1832
1833 switch (info->si_code)
1834 {
1835 default:
1836 assert(false && "unexpected si_code for SIGILL");
1837 break;
1838 case ILL_ILLOPC:
1839 reason = ProcessMessage::eIllegalOpcode;
1840 break;
1841 case ILL_ILLOPN:
1842 reason = ProcessMessage::eIllegalOperand;
1843 break;
1844 case ILL_ILLADR:
1845 reason = ProcessMessage::eIllegalAddressingMode;
1846 break;
1847 case ILL_ILLTRP:
1848 reason = ProcessMessage::eIllegalTrap;
1849 break;
1850 case ILL_PRVOPC:
1851 reason = ProcessMessage::ePrivilegedOpcode;
1852 break;
1853 case ILL_PRVREG:
1854 reason = ProcessMessage::ePrivilegedRegister;
1855 break;
1856 case ILL_COPROC:
1857 reason = ProcessMessage::eCoprocessorError;
1858 break;
1859 case ILL_BADSTK:
1860 reason = ProcessMessage::eInternalStackError;
1861 break;
1862 }
1863
1864 return reason;
1865}
1866#endif
1867
1868#if 0
1869ProcessMessage::CrashReason
1870NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
1871{
1872 ProcessMessage::CrashReason reason;
1873 assert(info->si_signo == SIGFPE);
1874
1875 reason = ProcessMessage::eInvalidCrashReason;
1876
1877 switch (info->si_code)
1878 {
1879 default:
1880 assert(false && "unexpected si_code for SIGFPE");
1881 break;
1882 case FPE_INTDIV:
1883 reason = ProcessMessage::eIntegerDivideByZero;
1884 break;
1885 case FPE_INTOVF:
1886 reason = ProcessMessage::eIntegerOverflow;
1887 break;
1888 case FPE_FLTDIV:
1889 reason = ProcessMessage::eFloatDivideByZero;
1890 break;
1891 case FPE_FLTOVF:
1892 reason = ProcessMessage::eFloatOverflow;
1893 break;
1894 case FPE_FLTUND:
1895 reason = ProcessMessage::eFloatUnderflow;
1896 break;
1897 case FPE_FLTRES:
1898 reason = ProcessMessage::eFloatInexactResult;
1899 break;
1900 case FPE_FLTINV:
1901 reason = ProcessMessage::eFloatInvalidOperation;
1902 break;
1903 case FPE_FLTSUB:
1904 reason = ProcessMessage::eFloatSubscriptRange;
1905 break;
1906 }
1907
1908 return reason;
1909}
1910#endif
1911
1912#if 0
1913ProcessMessage::CrashReason
1914NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
1915{
1916 ProcessMessage::CrashReason reason;
1917 assert(info->si_signo == SIGBUS);
1918
1919 reason = ProcessMessage::eInvalidCrashReason;
1920
1921 switch (info->si_code)
1922 {
1923 default:
1924 assert(false && "unexpected si_code for SIGBUS");
1925 break;
1926 case BUS_ADRALN:
1927 reason = ProcessMessage::eIllegalAlignment;
1928 break;
1929 case BUS_ADRERR:
1930 reason = ProcessMessage::eIllegalAddress;
1931 break;
1932 case BUS_OBJERR:
1933 reason = ProcessMessage::eHardwareError;
1934 break;
1935 }
1936
1937 return reason;
1938}
1939#endif
1940
Kate Stoneb9c1b512016-09-06 20:57:50 +00001941Error NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
1942 size_t &bytes_read) {
1943 if (ProcessVmReadvSupported()) {
1944 // The process_vm_readv path is about 50 times faster than ptrace api. We
1945 // want to use
1946 // this syscall if it is supported.
Pavel Labathdf7c6992015-06-17 18:38:49 +00001947
Kate Stoneb9c1b512016-09-06 20:57:50 +00001948 const ::pid_t pid = GetID();
Pavel Labathdf7c6992015-06-17 18:38:49 +00001949
Kate Stoneb9c1b512016-09-06 20:57:50 +00001950 struct iovec local_iov, remote_iov;
1951 local_iov.iov_base = buf;
1952 local_iov.iov_len = size;
1953 remote_iov.iov_base = reinterpret_cast<void *>(addr);
1954 remote_iov.iov_len = size;
Pavel Labathdf7c6992015-06-17 18:38:49 +00001955
Kate Stoneb9c1b512016-09-06 20:57:50 +00001956 bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
1957 const bool success = bytes_read == size;
Pavel Labathdf7c6992015-06-17 18:38:49 +00001958
Pavel Labatha6321a82017-01-19 15:26:04 +00001959 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1960 LLDB_LOG(log,
1961 "using process_vm_readv to read {0} bytes from inferior "
1962 "address {1:x}: {2}",
1963 size, addr, success ? "Success" : strerror(errno));
Pavel Labath19cbe962015-07-21 13:20:32 +00001964
Kate Stoneb9c1b512016-09-06 20:57:50 +00001965 if (success)
Mehdi Amini665be502016-11-11 05:07:57 +00001966 return Error();
Pavel Labatha6321a82017-01-19 15:26:04 +00001967 // else the call failed for some reason, let's retry the read using ptrace
1968 // api.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001969 }
Pavel Labath19cbe962015-07-21 13:20:32 +00001970
Kate Stoneb9c1b512016-09-06 20:57:50 +00001971 unsigned char *dst = static_cast<unsigned char *>(buf);
1972 size_t remainder;
1973 long data;
Pavel Labath19cbe962015-07-21 13:20:32 +00001974
Pavel Labatha6321a82017-01-19 15:26:04 +00001975 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1976 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
Pavel Labath19cbe962015-07-21 13:20:32 +00001977
Kate Stoneb9c1b512016-09-06 20:57:50 +00001978 for (bytes_read = 0; bytes_read < size; bytes_read += remainder) {
1979 Error error = NativeProcessLinux::PtraceWrapper(
1980 PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data);
Pavel Labatha6321a82017-01-19 15:26:04 +00001981 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001982 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001983
1984 remainder = size - bytes_read;
1985 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
1986
1987 // Copy the data into our buffer
1988 memcpy(dst, &data, remainder);
1989
Pavel Labatha6321a82017-01-19 15:26:04 +00001990 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001991 addr += k_ptrace_word_size;
1992 dst += k_ptrace_word_size;
1993 }
Mehdi Amini665be502016-11-11 05:07:57 +00001994 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00001995}
1996
Kate Stoneb9c1b512016-09-06 20:57:50 +00001997Error NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf,
1998 size_t size,
1999 size_t &bytes_read) {
2000 Error error = ReadMemory(addr, buf, size, bytes_read);
2001 if (error.Fail())
Pavel Labath19cbe962015-07-21 13:20:32 +00002002 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002003 return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00002004}
2005
Kate Stoneb9c1b512016-09-06 20:57:50 +00002006Error NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,
2007 size_t size, size_t &bytes_written) {
2008 const unsigned char *src = static_cast<const unsigned char *>(buf);
2009 size_t remainder;
2010 Error error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002011
Pavel Labatha6321a82017-01-19 15:26:04 +00002012 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
2013 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00002014
Kate Stoneb9c1b512016-09-06 20:57:50 +00002015 for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
2016 remainder = size - bytes_written;
2017 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
Chaoren Lin97ccc292015-02-03 01:51:12 +00002018
Kate Stoneb9c1b512016-09-06 20:57:50 +00002019 if (remainder == k_ptrace_word_size) {
2020 unsigned long data = 0;
2021 memcpy(&data, src, k_ptrace_word_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00002022
Pavel Labatha6321a82017-01-19 15:26:04 +00002023 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002024 error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(),
2025 (void *)addr, (void *)data);
Pavel Labatha6321a82017-01-19 15:26:04 +00002026 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00002027 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002028 } else {
2029 unsigned char buff[8];
2030 size_t bytes_read;
2031 error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
Pavel Labatha6321a82017-01-19 15:26:04 +00002032 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00002033 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002034
2035 memcpy(buff, src, remainder);
2036
2037 size_t bytes_written_rec;
2038 error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
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
Pavel Labatha6321a82017-01-19 15:26:04 +00002042 LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src,
2043 *(unsigned long *)buff);
Todd Fialaaf245d12014-06-30 21:05:18 +00002044 }
2045
Kate Stoneb9c1b512016-09-06 20:57:50 +00002046 addr += k_ptrace_word_size;
2047 src += k_ptrace_word_size;
2048 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002049 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002050}
2051
Kate Stoneb9c1b512016-09-06 20:57:50 +00002052Error NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) {
2053 return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
2054}
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002055
Kate Stoneb9c1b512016-09-06 20:57:50 +00002056Error NativeProcessLinux::GetEventMessage(lldb::tid_t tid,
2057 unsigned long *message) {
2058 return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
2059}
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002060
Kate Stoneb9c1b512016-09-06 20:57:50 +00002061Error NativeProcessLinux::Detach(lldb::tid_t tid) {
2062 if (tid == LLDB_INVALID_THREAD_ID)
Mehdi Amini665be502016-11-11 05:07:57 +00002063 return Error();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002064
Kate Stoneb9c1b512016-09-06 20:57:50 +00002065 return PtraceWrapper(PTRACE_DETACH, tid);
2066}
2067
2068bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {
2069 for (auto thread_sp : m_threads) {
2070 assert(thread_sp && "thread list should not contain NULL threads");
2071 if (thread_sp->GetID() == thread_id) {
2072 // We have this thread.
2073 return true;
Todd Fialaaf245d12014-06-30 21:05:18 +00002074 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002075 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002076
Kate Stoneb9c1b512016-09-06 20:57:50 +00002077 // We don't have this thread.
2078 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00002079}
2080
Kate Stoneb9c1b512016-09-06 20:57:50 +00002081bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002082 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2083 LLDB_LOG(log, "tid: {0})", thread_id);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002084
2085 bool found = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002086 for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
2087 if (*it && ((*it)->GetID() == thread_id)) {
2088 m_threads.erase(it);
2089 found = true;
2090 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00002091 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002092 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002093
Kate Stoneb9c1b512016-09-06 20:57:50 +00002094 SignalIfAllThreadsStopped();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002095 return found;
Todd Fialaaf245d12014-06-30 21:05:18 +00002096}
2097
Kate Stoneb9c1b512016-09-06 20:57:50 +00002098NativeThreadLinuxSP NativeProcessLinux::AddThread(lldb::tid_t thread_id) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002099 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
2100 LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
Todd Fialaaf245d12014-06-30 21:05:18 +00002101
Kate Stoneb9c1b512016-09-06 20:57:50 +00002102 assert(!HasThreadNoLock(thread_id) &&
2103 "attempted to add a thread by id that already exists");
Todd Fialaaf245d12014-06-30 21:05:18 +00002104
Kate Stoneb9c1b512016-09-06 20:57:50 +00002105 // If this is the first thread, save it as the current thread
2106 if (m_threads.empty())
2107 SetCurrentThreadID(thread_id);
Todd Fialaaf245d12014-06-30 21:05:18 +00002108
Kate Stoneb9c1b512016-09-06 20:57:50 +00002109 auto thread_sp = std::make_shared<NativeThreadLinux>(this, thread_id);
2110 m_threads.push_back(thread_sp);
2111 return thread_sp;
2112}
Todd Fialaaf245d12014-06-30 21:05:18 +00002113
Kate Stoneb9c1b512016-09-06 20:57:50 +00002114Error NativeProcessLinux::FixupBreakpointPCAsNeeded(NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002115 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_BREAKPOINTS));
Todd Fialaaf245d12014-06-30 21:05:18 +00002116
Kate Stoneb9c1b512016-09-06 20:57:50 +00002117 Error error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002118
Kate Stoneb9c1b512016-09-06 20:57:50 +00002119 // Find out the size of a breakpoint (might depend on where we are in the
2120 // code).
2121 NativeRegisterContextSP context_sp = thread.GetRegisterContext();
2122 if (!context_sp) {
2123 error.SetErrorString("cannot get a NativeRegisterContext for the thread");
Pavel Labatha6321a82017-01-19 15:26:04 +00002124 LLDB_LOG(log, "failed: {0}", error);
Todd Fialaaf245d12014-06-30 21:05:18 +00002125 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002126 }
Chaoren Linfa03ad22015-02-03 01:50:42 +00002127
Kate Stoneb9c1b512016-09-06 20:57:50 +00002128 uint32_t breakpoint_size = 0;
2129 error = GetSoftwareBreakpointPCOffset(breakpoint_size);
2130 if (error.Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002131 LLDB_LOG(log, "GetBreakpointSize() failed: {0}", error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002132 return error;
Pavel Labatha6321a82017-01-19 15:26:04 +00002133 } else
2134 LLDB_LOG(log, "breakpoint size: {0}", breakpoint_size);
Pavel Labathc0765592015-05-06 10:46:34 +00002135
Kate Stoneb9c1b512016-09-06 20:57:50 +00002136 // First try probing for a breakpoint at a software breakpoint location: PC -
2137 // breakpoint size.
2138 const lldb::addr_t initial_pc_addr =
2139 context_sp->GetPCfromBreakpointLocation();
2140 lldb::addr_t breakpoint_addr = initial_pc_addr;
2141 if (breakpoint_size > 0) {
2142 // Do not allow breakpoint probe to wrap around.
2143 if (breakpoint_addr >= breakpoint_size)
2144 breakpoint_addr -= breakpoint_size;
2145 }
2146
2147 // Check if we stopped because of a breakpoint.
2148 NativeBreakpointSP breakpoint_sp;
2149 error = m_breakpoint_list.GetBreakpoint(breakpoint_addr, breakpoint_sp);
2150 if (!error.Success() || !breakpoint_sp) {
2151 // We didn't find one at a software probe location. Nothing to do.
Pavel Labatha6321a82017-01-19 15:26:04 +00002152 LLDB_LOG(log,
2153 "pid {0} no lldb breakpoint found at current pc with "
2154 "adjustment: {1}",
2155 GetID(), breakpoint_addr);
Mehdi Amini665be502016-11-11 05:07:57 +00002156 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002157 }
2158
2159 // If the breakpoint is not a software breakpoint, nothing to do.
2160 if (!breakpoint_sp->IsSoftwareBreakpoint()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002161 LLDB_LOG(
2162 log,
2163 "pid {0} breakpoint found at {1:x}, not software, nothing to adjust",
2164 GetID(), breakpoint_addr);
Mehdi Amini665be502016-11-11 05:07:57 +00002165 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002166 }
2167
2168 //
2169 // We have a software breakpoint and need to adjust the PC.
2170 //
2171
2172 // Sanity check.
2173 if (breakpoint_size == 0) {
2174 // Nothing to do! How did we get here?
Pavel Labatha6321a82017-01-19 15:26:04 +00002175 LLDB_LOG(log,
2176 "pid {0} breakpoint found at {1:x}, it is software, but the "
2177 "size is zero, nothing to do (unexpected)",
2178 GetID(), breakpoint_addr);
Mehdi Amini665be502016-11-11 05:07:57 +00002179 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002180 }
2181
2182 // Change the program counter.
Pavel Labatha6321a82017-01-19 15:26:04 +00002183 LLDB_LOG(log, "pid {0} tid {1}: changing PC from {2:x} to {3:x}", GetID(),
2184 thread.GetID(), initial_pc_addr, breakpoint_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002185
2186 error = context_sp->SetPC(breakpoint_addr);
2187 if (error.Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002188 LLDB_LOG(log, "pid {0} tid {1}: failed to set PC: {2}", GetID(),
2189 thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002190 return error;
2191 }
2192
2193 return error;
2194}
2195
2196Error NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,
2197 FileSpec &file_spec) {
Tamas Berghammera6f57952017-01-03 16:29:43 +00002198 Error error = PopulateMemoryRegionCache();
2199 if (error.Fail())
2200 return error;
2201
Kate Stoneb9c1b512016-09-06 20:57:50 +00002202 FileSpec module_file_spec(module_path, true);
2203
Kate Stoneb9c1b512016-09-06 20:57:50 +00002204 file_spec.Clear();
Tamas Berghammera6f57952017-01-03 16:29:43 +00002205 for (const auto &it : m_mem_region_cache) {
2206 if (it.second.GetFilename() == module_file_spec.GetFilename()) {
2207 file_spec = it.second;
2208 return Error();
2209 }
2210 }
2211 return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
2212 module_file_spec.GetFilename().AsCString(), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002213}
2214
2215Error NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
2216 lldb::addr_t &load_addr) {
2217 load_addr = LLDB_INVALID_ADDRESS;
Tamas Berghammera6f57952017-01-03 16:29:43 +00002218 Error error = PopulateMemoryRegionCache();
2219 if (error.Fail())
2220 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002221
Tamas Berghammera6f57952017-01-03 16:29:43 +00002222 FileSpec file(file_name, false);
2223 for (const auto &it : m_mem_region_cache) {
2224 if (it.second == file) {
2225 load_addr = it.first.GetRange().GetRangeBase();
2226 return Error();
2227 }
2228 }
2229 return Error("No load address found for specified file.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002230}
2231
2232NativeThreadLinuxSP NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {
2233 return std::static_pointer_cast<NativeThreadLinux>(
2234 NativeProcessProtocol::GetThreadByID(tid));
2235}
2236
2237Error NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,
2238 lldb::StateType state, int signo) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002239 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2240 LLDB_LOG(log, "tid: {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002241
2242 // Before we do the resume below, first check if we have a pending
2243 // stop notification that is currently waiting for
2244 // all threads to stop. This is potentially a buggy situation since
2245 // we're ostensibly waiting for threads to stop before we send out the
2246 // pending notification, and here we are resuming one before we send
2247 // out the pending stop notification.
Pavel Labatha6321a82017-01-19 15:26:04 +00002248 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
2249 LLDB_LOG(log,
2250 "about to resume tid {0} per explicit request but we have a "
2251 "pending stop notification (tid {1}) that is actively "
2252 "waiting for this thread to stop. Valid sequence of events?",
2253 thread.GetID(), m_pending_notification_tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002254 }
2255
2256 // Request a resume. We expect this to be synchronous and the system
2257 // to reflect it is running after this completes.
2258 switch (state) {
2259 case eStateRunning: {
2260 const auto resume_result = thread.Resume(signo);
2261 if (resume_result.Success())
2262 SetState(eStateRunning, true);
2263 return resume_result;
2264 }
2265 case eStateStepping: {
2266 const auto step_result = thread.SingleStep(signo);
2267 if (step_result.Success())
2268 SetState(eStateRunning, true);
2269 return step_result;
2270 }
2271 default:
Pavel Labath8198db32017-01-24 11:48:25 +00002272 LLDB_LOG(log, "Unhandled state {0}.", state);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002273 llvm_unreachable("Unhandled state for resume");
2274 }
Pavel Labathc0765592015-05-06 10:46:34 +00002275}
2276
2277//===----------------------------------------------------------------------===//
2278
Kate Stoneb9c1b512016-09-06 20:57:50 +00002279void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002280 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2281 LLDB_LOG(log, "about to process event: (triggering_tid: {0})",
2282 triggering_tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002283
2284 m_pending_notification_tid = triggering_tid;
2285
2286 // Request a stop for all the thread stops that need to be stopped
2287 // and are not already known to be stopped.
2288 for (const auto &thread_sp : m_threads) {
2289 if (StateIsRunningState(thread_sp->GetState()))
2290 static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
2291 }
2292
2293 SignalIfAllThreadsStopped();
Pavel Labatha6321a82017-01-19 15:26:04 +00002294 LLDB_LOG(log, "event processing done");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002295}
2296
2297void NativeProcessLinux::SignalIfAllThreadsStopped() {
2298 if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
2299 return; // No pending notification. Nothing to do.
2300
2301 for (const auto &thread_sp : m_threads) {
2302 if (StateIsRunningState(thread_sp->GetState()))
2303 return; // Some threads are still running. Don't signal yet.
2304 }
2305
2306 // We have a pending notification and all threads have stopped.
2307 Log *log(
2308 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
2309
2310 // Clear any temporary breakpoints we used to implement software single
2311 // stepping.
2312 for (const auto &thread_info : m_threads_stepping_with_breakpoint) {
2313 Error error = RemoveBreakpoint(thread_info.second);
2314 if (error.Fail())
Pavel Labatha6321a82017-01-19 15:26:04 +00002315 LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}",
2316 thread_info.first, error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002317 }
2318 m_threads_stepping_with_breakpoint.clear();
2319
2320 // Notify the delegate about the stop
2321 SetCurrentThreadID(m_pending_notification_tid);
2322 SetState(StateType::eStateStopped, true);
2323 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
2324}
2325
2326void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002327 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2328 LLDB_LOG(log, "tid: {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002329
2330 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID &&
2331 StateIsRunningState(thread.GetState())) {
2332 // We will need to wait for this new thread to stop as well before firing
2333 // the
2334 // notification.
2335 thread.RequestStop();
2336 }
2337}
2338
2339void NativeProcessLinux::SigchldHandler() {
Pavel Labatha6321a82017-01-19 15:26:04 +00002340 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002341 // Process all pending waitpid notifications.
2342 while (true) {
2343 int status = -1;
2344 ::pid_t wait_pid = waitpid(-1, &status, __WALL | __WNOTHREAD | WNOHANG);
2345
2346 if (wait_pid == 0)
2347 break; // We are done.
2348
2349 if (wait_pid == -1) {
2350 if (errno == EINTR)
2351 continue;
2352
2353 Error error(errno, eErrorTypePOSIX);
Pavel Labatha6321a82017-01-19 15:26:04 +00002354 LLDB_LOG(log, "waitpid (-1, &status, _) failed: {0}", error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002355 break;
Pavel Labathc0765592015-05-06 10:46:34 +00002356 }
2357
Kate Stoneb9c1b512016-09-06 20:57:50 +00002358 bool exited = false;
2359 int signal = 0;
2360 int exit_status = 0;
2361 const char *status_cstr = nullptr;
2362 if (WIFSTOPPED(status)) {
2363 signal = WSTOPSIG(status);
2364 status_cstr = "STOPPED";
2365 } else if (WIFEXITED(status)) {
2366 exit_status = WEXITSTATUS(status);
2367 status_cstr = "EXITED";
2368 exited = true;
2369 } else if (WIFSIGNALED(status)) {
2370 signal = WTERMSIG(status);
2371 status_cstr = "SIGNALED";
2372 if (wait_pid == static_cast<::pid_t>(GetID())) {
2373 exited = true;
2374 exit_status = -1;
2375 }
2376 } else
2377 status_cstr = "(\?\?\?)";
Pavel Labathc0765592015-05-06 10:46:34 +00002378
Pavel Labatha6321a82017-01-19 15:26:04 +00002379 LLDB_LOG(log,
2380 "waitpid (-1, &status, _) => pid = {0}, status = {1:x} "
2381 "({2}), signal = {3}, exit_state = {4}",
2382 wait_pid, status, status_cstr, signal, exit_status);
Pavel Labathc0765592015-05-06 10:46:34 +00002383
Kate Stoneb9c1b512016-09-06 20:57:50 +00002384 MonitorCallback(wait_pid, exited, signal, exit_status);
2385 }
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002386}
2387
2388// Wrapper for ptrace to catch errors and log calls.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002389// Note that ptrace sets errno on error because -1 can be a valid result (i.e.
2390// for PTRACE_PEEK*)
2391Error NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
2392 void *data, size_t data_size,
2393 long *result) {
2394 Error error;
2395 long int ret;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002396
Kate Stoneb9c1b512016-09-06 20:57:50 +00002397 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002398
Kate Stoneb9c1b512016-09-06 20:57:50 +00002399 PtraceDisplayBytes(req, data, data_size);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002400
Kate Stoneb9c1b512016-09-06 20:57:50 +00002401 errno = 0;
2402 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
2403 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2404 *(unsigned int *)addr, data);
2405 else
2406 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2407 addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002408
Kate Stoneb9c1b512016-09-06 20:57:50 +00002409 if (ret == -1)
2410 error.SetErrorToErrno();
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002411
Kate Stoneb9c1b512016-09-06 20:57:50 +00002412 if (result)
2413 *result = ret;
Pavel Labath4a9babb2015-06-30 17:04:49 +00002414
Pavel Labatha6321a82017-01-19 15:26:04 +00002415 LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4}, {5})={6:x}", req, pid, addr,
2416 data, data_size, ret);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002417
Kate Stoneb9c1b512016-09-06 20:57:50 +00002418 PtraceDisplayBytes(req, data, data_size);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002419
Pavel Labatha6321a82017-01-19 15:26:04 +00002420 if (error.Fail())
2421 LLDB_LOG(log, "ptrace() failed: {0}", error);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002422
Kate Stoneb9c1b512016-09-06 20:57:50 +00002423 return error;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002424}