blob: fc0e312c6c76736b1f587b0ee23bc5f53093d005 [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"
Kamil Rytarowski816ae4b2017-02-01 14:30:40 +000035#include "lldb/Host/posix/ProcessLauncherPosixFork.h"
Pavel Labath2a86b552016-06-14 17:30:52 +000036#include "lldb/Symbol/ObjectFile.h"
Zachary Turner90aff472015-03-03 23:36:51 +000037#include "lldb/Target/Process.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000038#include "lldb/Target/ProcessLaunchInfo.h"
Pavel Labath5b981ab2015-05-29 12:53:54 +000039#include "lldb/Target/Target.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000040#include "lldb/Utility/Error.h"
Chaoren Linc16f5dc2015-03-19 23:28:10 +000041#include "lldb/Utility/LLDBAssert.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000042#include "lldb/Utility/PseudoTerminal.h"
Pavel Labathf805e192015-07-07 10:08:41 +000043#include "lldb/Utility/StringExtractor.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000044
Todd Fialaaf245d12014-06-30 21:05:18 +000045#include "NativeThreadLinux.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000046#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000047#include "ProcFileReader.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000048#include "Procfs.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000049
Kate Stoneb9c1b512016-09-06 20:57:50 +000050// System includes - They have to be included after framework includes because
51// they define some
Tamas Berghammerd8584872015-02-06 10:57:40 +000052// macros which collide with variable names in other modules
53#include <linux/unistd.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000054#include <sys/socket.h>
Vince Harron8b335672015-05-12 01:10:56 +000055
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
Vince Harron8b335672015-05-12 01:10:56 +000061#include "lldb/Host/linux/Ptrace.h"
Pavel Labathdf7c6992015-06-17 18:38:49 +000062#include "lldb/Host/linux/Uio.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000063
Todd Fialaaf245d12014-06-30 21:05:18 +000064// Support hardware breakpoints in case it has not been defined
65#ifndef TRAP_HWBKPT
Kate Stoneb9c1b512016-09-06 20:57:50 +000066#define TRAP_HWBKPT 4
Todd Fialaaf245d12014-06-30 21:05:18 +000067#endif
68
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000069using namespace lldb;
70using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000071using namespace lldb_private::process_linux;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000072using namespace llvm;
73
Todd Fialaaf245d12014-06-30 21:05:18 +000074// Private bits we only need internally.
Pavel Labathdf7c6992015-06-17 18:38:49 +000075
Kate Stoneb9c1b512016-09-06 20:57:50 +000076static bool ProcessVmReadvSupported() {
77 static bool is_supported;
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000078 static llvm::once_flag flag;
Pavel Labathdf7c6992015-06-17 18:38:49 +000079
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000080 llvm::call_once(flag, [] {
Pavel Labatha6321a82017-01-19 15:26:04 +000081 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Pavel Labath4abe5d62016-07-15 10:18:15 +000082
Kate Stoneb9c1b512016-09-06 20:57:50 +000083 uint32_t source = 0x47424742;
84 uint32_t dest = 0;
Pavel Labath4abe5d62016-07-15 10:18:15 +000085
Kate Stoneb9c1b512016-09-06 20:57:50 +000086 struct iovec local, remote;
87 remote.iov_base = &source;
88 local.iov_base = &dest;
89 remote.iov_len = local.iov_len = sizeof source;
Pavel Labath4abe5d62016-07-15 10:18:15 +000090
Kate Stoneb9c1b512016-09-06 20:57:50 +000091 // We shall try if cross-process-memory reads work by attempting to read a
92 // value from our own process.
93 ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
94 is_supported = (res == sizeof(source) && source == dest);
Pavel Labatha6321a82017-01-19 15:26:04 +000095 if (is_supported)
96 LLDB_LOG(log,
97 "Detected kernel support for process_vm_readv syscall. "
98 "Fast memory reads enabled.");
99 else
100 LLDB_LOG(log,
101 "syscall process_vm_readv failed (error: {0}). Fast memory "
102 "reads disabled.",
103 strerror(errno));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000104 });
Pavel Labath4abe5d62016-07-15 10:18:15 +0000105
Kate Stoneb9c1b512016-09-06 20:57:50 +0000106 return is_supported;
Pavel Labath4abe5d62016-07-15 10:18:15 +0000107}
108
Kate Stoneb9c1b512016-09-06 20:57:50 +0000109namespace {
110void MaybeLogLaunchInfo(const ProcessLaunchInfo &info) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000111 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000112 if (!log)
113 return;
114
115 if (const FileAction *action = info.GetFileActionForFD(STDIN_FILENO))
Pavel Labatha6321a82017-01-19 15:26:04 +0000116 LLDB_LOG(log, "setting STDIN to '{0}'", action->GetFileSpec());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000117 else
Pavel Labatha6321a82017-01-19 15:26:04 +0000118 LLDB_LOG(log, "leaving STDIN as is");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000119
120 if (const FileAction *action = info.GetFileActionForFD(STDOUT_FILENO))
Pavel Labatha6321a82017-01-19 15:26:04 +0000121 LLDB_LOG(log, "setting STDOUT to '{0}'", action->GetFileSpec());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000122 else
Pavel Labatha6321a82017-01-19 15:26:04 +0000123 LLDB_LOG(log, "leaving STDOUT as is");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000124
125 if (const FileAction *action = info.GetFileActionForFD(STDERR_FILENO))
Pavel Labatha6321a82017-01-19 15:26:04 +0000126 LLDB_LOG(log, "setting STDERR to '{0}'", action->GetFileSpec());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000127 else
Pavel Labatha6321a82017-01-19 15:26:04 +0000128 LLDB_LOG(log, "leaving STDERR as is");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000129
130 int i = 0;
131 for (const char **args = info.GetArguments().GetConstArgumentVector(); *args;
132 ++args, ++i)
Pavel Labatha6321a82017-01-19 15:26:04 +0000133 LLDB_LOG(log, "arg {0}: '{1}'", i, *args);
Pavel Labath4abe5d62016-07-15 10:18:15 +0000134}
Todd Fialaaf245d12014-06-30 21:05:18 +0000135
Kate Stoneb9c1b512016-09-06 20:57:50 +0000136void DisplayBytes(StreamString &s, void *bytes, uint32_t count) {
137 uint8_t *ptr = (uint8_t *)bytes;
138 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
139 for (uint32_t i = 0; i < loop_count; i++) {
140 s.Printf("[%x]", *ptr);
141 ptr++;
142 }
143}
Todd Fialaaf245d12014-06-30 21:05:18 +0000144
Kate Stoneb9c1b512016-09-06 20:57:50 +0000145void PtraceDisplayBytes(int &req, void *data, size_t data_size) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000146 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE |
147 POSIX_LOG_VERBOSE));
148 if (!log)
149 return;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000150 StreamString buf;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000151
Pavel Labatha6321a82017-01-19 15:26:04 +0000152 switch (req) {
153 case PTRACE_POKETEXT: {
154 DisplayBytes(buf, &data, 8);
155 LLDB_LOG(log, "PTRACE_POKETEXT {0}", buf.GetData());
156 break;
157 }
158 case PTRACE_POKEDATA: {
159 DisplayBytes(buf, &data, 8);
160 LLDB_LOG(log, "PTRACE_POKEDATA {0}", buf.GetData());
161 break;
162 }
163 case PTRACE_POKEUSER: {
164 DisplayBytes(buf, &data, 8);
165 LLDB_LOG(log, "PTRACE_POKEUSER {0}", buf.GetData());
166 break;
167 }
168 case PTRACE_SETREGS: {
169 DisplayBytes(buf, data, data_size);
170 LLDB_LOG(log, "PTRACE_SETREGS {0}", buf.GetData());
171 break;
172 }
173 case PTRACE_SETFPREGS: {
174 DisplayBytes(buf, data, data_size);
175 LLDB_LOG(log, "PTRACE_SETFPREGS {0}", buf.GetData());
176 break;
177 }
178 case PTRACE_SETSIGINFO: {
179 DisplayBytes(buf, data, sizeof(siginfo_t));
180 LLDB_LOG(log, "PTRACE_SETSIGINFO {0}", buf.GetData());
181 break;
182 }
183 case PTRACE_SETREGSET: {
184 // Extract iov_base from data, which is a pointer to the struct IOVEC
185 DisplayBytes(buf, *(void **)data, data_size);
186 LLDB_LOG(log, "PTRACE_SETREGSET {0}", buf.GetData());
187 break;
188 }
189 default: {}
Kate Stoneb9c1b512016-09-06 20:57:50 +0000190 }
191}
Todd Fialaaf245d12014-06-30 21:05:18 +0000192
Kate Stoneb9c1b512016-09-06 20:57:50 +0000193static constexpr unsigned k_ptrace_word_size = sizeof(void *);
194static_assert(sizeof(long) >= k_ptrace_word_size,
195 "Size of long must be larger than ptrace word size");
Pavel Labath1107b5a2015-04-17 14:07:49 +0000196} // end of anonymous namespace
197
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000198// Simple helper function to ensure flags are enabled on the given file
199// descriptor.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000200static Error EnsureFDFlags(int fd, int flags) {
201 Error error;
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000202
Kate Stoneb9c1b512016-09-06 20:57:50 +0000203 int status = fcntl(fd, F_GETFL);
204 if (status == -1) {
205 error.SetErrorToErrno();
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000206 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000207 }
208
209 if (fcntl(fd, F_SETFL, status | flags) == -1) {
210 error.SetErrorToErrno();
211 return error;
212 }
213
214 return error;
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000215}
216
Todd Fialaaf245d12014-06-30 21:05:18 +0000217// -----------------------------------------------------------------------------
218// Public Static Methods
219// -----------------------------------------------------------------------------
220
Kate Stoneb9c1b512016-09-06 20:57:50 +0000221Error NativeProcessProtocol::Launch(
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000222 ProcessLaunchInfo &launch_info,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000223 NativeProcessProtocol::NativeDelegate &native_delegate, MainLoop &mainloop,
224 NativeProcessProtocolSP &native_process_sp) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000225 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Todd Fialaaf245d12014-06-30 21:05:18 +0000226
Kate Stoneb9c1b512016-09-06 20:57:50 +0000227 Error error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000228
Kate Stoneb9c1b512016-09-06 20:57:50 +0000229 // Verify the working directory is valid if one was specified.
230 FileSpec working_dir{launch_info.GetWorkingDirectory()};
231 if (working_dir &&
232 (!working_dir.ResolvePath() ||
233 working_dir.GetFileType() != FileSpec::eFileTypeDirectory)) {
234 error.SetErrorStringWithFormat("No such file or directory: %s",
235 working_dir.GetCString());
Todd Fialaaf245d12014-06-30 21:05:18 +0000236 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000237 }
238
239 // Create the NativeProcessLinux in launch mode.
240 native_process_sp.reset(new NativeProcessLinux());
241
242 if (!native_process_sp->RegisterNativeDelegate(native_delegate)) {
243 native_process_sp.reset();
244 error.SetErrorStringWithFormat("failed to register the native delegate");
245 return error;
246 }
247
248 error = std::static_pointer_cast<NativeProcessLinux>(native_process_sp)
249 ->LaunchInferior(mainloop, launch_info);
250
251 if (error.Fail()) {
252 native_process_sp.reset();
Pavel Labatha6321a82017-01-19 15:26:04 +0000253 LLDB_LOG(log, "failed to launch process: {0}", error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000254 return error;
255 }
256
257 launch_info.SetProcessID(native_process_sp->GetID());
258
259 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000260}
261
Kate Stoneb9c1b512016-09-06 20:57:50 +0000262Error NativeProcessProtocol::Attach(
263 lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
264 MainLoop &mainloop, NativeProcessProtocolSP &native_process_sp) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000265 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
266 LLDB_LOG(log, "pid = {0:x}", pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000267
Kate Stoneb9c1b512016-09-06 20:57:50 +0000268 // Retrieve the architecture for the running process.
269 ArchSpec process_arch;
270 Error error = ResolveProcessArchitecture(pid, process_arch);
271 if (!error.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +0000272 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000273
274 std::shared_ptr<NativeProcessLinux> native_process_linux_sp(
275 new NativeProcessLinux());
276
277 if (!native_process_linux_sp->RegisterNativeDelegate(native_delegate)) {
278 error.SetErrorStringWithFormat("failed to register the native delegate");
279 return error;
280 }
281
282 native_process_linux_sp->AttachToInferior(mainloop, pid, error);
283 if (!error.Success())
284 return error;
285
286 native_process_sp = native_process_linux_sp;
287 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000288}
289
290// -----------------------------------------------------------------------------
291// Public Instance Methods
292// -----------------------------------------------------------------------------
293
Kate Stoneb9c1b512016-09-06 20:57:50 +0000294NativeProcessLinux::NativeProcessLinux()
295 : NativeProcessProtocol(LLDB_INVALID_PROCESS_ID), m_arch(),
296 m_supports_mem_region(eLazyBoolCalculate), m_mem_region_cache(),
297 m_pending_notification_tid(LLDB_INVALID_THREAD_ID) {}
298
299void NativeProcessLinux::AttachToInferior(MainLoop &mainloop, lldb::pid_t pid,
300 Error &error) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000301 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
302 LLDB_LOG(log, "pid = {0:x}", pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000303
304 m_sigchld_handle = mainloop.RegisterSignal(
305 SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, error);
306 if (!m_sigchld_handle)
307 return;
308
309 error = ResolveProcessArchitecture(pid, m_arch);
310 if (!error.Success())
311 return;
312
313 // Set the architecture to the exe architecture.
Pavel Labatha6321a82017-01-19 15:26:04 +0000314 LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid,
315 m_arch.GetArchitectureName());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000316 m_pid = pid;
317 SetState(eStateAttaching);
318
319 Attach(pid, error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000320}
321
Kate Stoneb9c1b512016-09-06 20:57:50 +0000322Error NativeProcessLinux::LaunchInferior(MainLoop &mainloop,
323 ProcessLaunchInfo &launch_info) {
324 Error error;
325 m_sigchld_handle = mainloop.RegisterSignal(
326 SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, error);
327 if (!m_sigchld_handle)
328 return error;
329
330 SetState(eStateLaunching);
331
332 MaybeLogLaunchInfo(launch_info);
333
334 ::pid_t pid =
Kamil Rytarowski816ae4b2017-02-01 14:30:40 +0000335 ProcessLauncherPosixFork().LaunchProcess(launch_info, error).GetProcessId();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000336 if (error.Fail())
337 return error;
338
Pavel Labatha6321a82017-01-19 15:26:04 +0000339 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000340
341 // Wait for the child process to trap on its call to execve.
342 ::pid_t wpid;
343 int status;
344 if ((wpid = waitpid(pid, &status, 0)) < 0) {
345 error.SetErrorToErrno();
Pavel Labatha6321a82017-01-19 15:26:04 +0000346 LLDB_LOG(log, "waitpid for inferior failed with %s", error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000347
Kate Stoneb9c1b512016-09-06 20:57:50 +0000348 // Mark the inferior as invalid.
349 // FIXME this could really use a new state - eStateLaunchFailure. For now,
350 // using eStateInvalid.
351 SetState(StateType::eStateInvalid);
Pavel Labath19cbe962015-07-21 13:20:32 +0000352
Kate Stoneb9c1b512016-09-06 20:57:50 +0000353 return error;
354 }
355 assert(WIFSTOPPED(status) && (wpid == static_cast<::pid_t>(pid)) &&
356 "Could not sync with inferior process.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000357
Pavel Labatha6321a82017-01-19 15:26:04 +0000358 LLDB_LOG(log, "inferior started, now in stopped state");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000359 error = SetDefaultPtraceOpts(pid);
360 if (error.Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000361 LLDB_LOG(log, "failed to set default ptrace options: {0}", error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000362
Kate Stoneb9c1b512016-09-06 20:57:50 +0000363 // Mark the inferior as invalid.
364 // FIXME this could really use a new state - eStateLaunchFailure. For now,
365 // using eStateInvalid.
366 SetState(StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000367
Kate Stoneb9c1b512016-09-06 20:57:50 +0000368 return error;
369 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000370
Kate Stoneb9c1b512016-09-06 20:57:50 +0000371 // Release the master terminal descriptor and pass it off to the
372 // NativeProcessLinux instance. Similarly stash the inferior pid.
373 m_terminal_fd = launch_info.GetPTY().ReleaseMasterFileDescriptor();
374 m_pid = pid;
375 launch_info.SetProcessID(pid);
Pavel Labath4abe5d62016-07-15 10:18:15 +0000376
Kate Stoneb9c1b512016-09-06 20:57:50 +0000377 if (m_terminal_fd != -1) {
378 error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
379 if (error.Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000380 LLDB_LOG(log,
381 "inferior EnsureFDFlags failed for ensuring terminal "
382 "O_NONBLOCK setting: {0}",
383 error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000384
Kate Stoneb9c1b512016-09-06 20:57:50 +0000385 // Mark the inferior as invalid.
386 // FIXME this could really use a new state - eStateLaunchFailure. For
387 // now, using eStateInvalid.
388 SetState(StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000389
Kate Stoneb9c1b512016-09-06 20:57:50 +0000390 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000391 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000392 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000393
Pavel Labatha6321a82017-01-19 15:26:04 +0000394 LLDB_LOG(log, "adding pid = {0}", pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000395 ResolveProcessArchitecture(m_pid, m_arch);
396 NativeThreadLinuxSP thread_sp = AddThread(pid);
397 assert(thread_sp && "AddThread() returned a nullptr thread");
398 thread_sp->SetStoppedBySignal(SIGSTOP);
399 ThreadWasCreated(*thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +0000400
Kate Stoneb9c1b512016-09-06 20:57:50 +0000401 // Let our process instance know the thread has stopped.
402 SetCurrentThreadID(thread_sp->GetID());
403 SetState(StateType::eStateStopped);
404
Pavel Labatha6321a82017-01-19 15:26:04 +0000405 if (error.Fail())
406 LLDB_LOG(log, "inferior launching failed {0}", error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000407 return error;
408}
409
410::pid_t NativeProcessLinux::Attach(lldb::pid_t pid, Error &error) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000411 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000412
413 // Use a map to keep track of the threads which we have attached/need to
414 // attach.
415 Host::TidMap tids_to_attach;
416 if (pid <= 1) {
417 error.SetErrorToGenericError();
418 error.SetErrorString("Attaching to process 1 is not allowed.");
419 return -1;
420 }
421
422 while (Host::FindProcessThreads(pid, tids_to_attach)) {
423 for (Host::TidMap::iterator it = tids_to_attach.begin();
424 it != tids_to_attach.end();) {
425 if (it->second == false) {
426 lldb::tid_t tid = it->first;
427
428 // Attach to the requested process.
429 // An attach will cause the thread to stop with a SIGSTOP.
430 error = PtraceWrapper(PTRACE_ATTACH, tid);
431 if (error.Fail()) {
432 // No such thread. The thread may have exited.
433 // More error handling may be needed.
434 if (error.GetError() == ESRCH) {
435 it = tids_to_attach.erase(it);
436 continue;
437 } else
438 return -1;
439 }
440
441 int status;
442 // Need to use __WALL otherwise we receive an error with errno=ECHLD
443 // At this point we should have a thread stopped if waitpid succeeds.
444 if ((status = waitpid(tid, NULL, __WALL)) < 0) {
445 // No such thread. The thread may have exited.
446 // More error handling may be needed.
447 if (errno == ESRCH) {
448 it = tids_to_attach.erase(it);
449 continue;
450 } else {
451 error.SetErrorToErrno();
452 return -1;
453 }
454 }
455
456 error = SetDefaultPtraceOpts(tid);
457 if (error.Fail())
458 return -1;
459
Pavel Labatha6321a82017-01-19 15:26:04 +0000460 LLDB_LOG(log, "adding tid = {0}", tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000461 it->second = true;
462
463 // Create the thread, mark it as stopped.
464 NativeThreadLinuxSP thread_sp(AddThread(static_cast<lldb::tid_t>(tid)));
465 assert(thread_sp && "AddThread() returned a nullptr");
466
467 // This will notify this is a new thread and tell the system it is
468 // stopped.
469 thread_sp->SetStoppedBySignal(SIGSTOP);
470 ThreadWasCreated(*thread_sp);
471 SetCurrentThreadID(thread_sp->GetID());
472 }
473
474 // move the loop forward
475 ++it;
476 }
477 }
478
479 if (tids_to_attach.size() > 0) {
480 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000481 // Let our process instance know the thread has stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000482 SetState(StateType::eStateStopped);
483 } else {
484 error.SetErrorToGenericError();
485 error.SetErrorString("No such process.");
486 return -1;
487 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000488
Kate Stoneb9c1b512016-09-06 20:57:50 +0000489 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000490}
491
Kate Stoneb9c1b512016-09-06 20:57:50 +0000492Error NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid) {
493 long ptrace_opts = 0;
Todd Fialaaf245d12014-06-30 21:05:18 +0000494
Kate Stoneb9c1b512016-09-06 20:57:50 +0000495 // Have the child raise an event on exit. This is used to keep the child in
496 // limbo until it is destroyed.
497 ptrace_opts |= PTRACE_O_TRACEEXIT;
Todd Fialaaf245d12014-06-30 21:05:18 +0000498
Kate Stoneb9c1b512016-09-06 20:57:50 +0000499 // Have the tracer trace threads which spawn in the inferior process.
500 // TODO: if we want to support tracing the inferiors' child, add the
501 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
502 ptrace_opts |= PTRACE_O_TRACECLONE;
Todd Fialaaf245d12014-06-30 21:05:18 +0000503
Kate Stoneb9c1b512016-09-06 20:57:50 +0000504 // Have the tracer notify us before execve returns
505 // (needed to disable legacy SIGTRAP generation)
506 ptrace_opts |= PTRACE_O_TRACEEXEC;
Todd Fialaaf245d12014-06-30 21:05:18 +0000507
Kate Stoneb9c1b512016-09-06 20:57:50 +0000508 return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void *)ptrace_opts);
Todd Fialaaf245d12014-06-30 21:05:18 +0000509}
510
Kate Stoneb9c1b512016-09-06 20:57:50 +0000511static ExitType convert_pid_status_to_exit_type(int status) {
512 if (WIFEXITED(status))
513 return ExitType::eExitTypeExit;
514 else if (WIFSIGNALED(status))
515 return ExitType::eExitTypeSignal;
516 else if (WIFSTOPPED(status))
517 return ExitType::eExitTypeStop;
518 else {
519 // We don't know what this is.
520 return ExitType::eExitTypeInvalid;
521 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000522}
523
Kate Stoneb9c1b512016-09-06 20:57:50 +0000524static int convert_pid_status_to_return_code(int status) {
525 if (WIFEXITED(status))
526 return WEXITSTATUS(status);
527 else if (WIFSIGNALED(status))
528 return WTERMSIG(status);
529 else if (WIFSTOPPED(status))
530 return WSTOPSIG(status);
531 else {
532 // We don't know what this is.
533 return ExitType::eExitTypeInvalid;
534 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000535}
536
Pavel Labath1107b5a2015-04-17 14:07:49 +0000537// Handles all waitpid events from the inferior process.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000538void NativeProcessLinux::MonitorCallback(lldb::pid_t pid, bool exited,
539 int signal, int status) {
540 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Todd Fialaaf245d12014-06-30 21:05:18 +0000541
Kate Stoneb9c1b512016-09-06 20:57:50 +0000542 // Certain activities differ based on whether the pid is the tid of the main
543 // thread.
544 const bool is_main_thread = (pid == GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000545
Kate Stoneb9c1b512016-09-06 20:57:50 +0000546 // Handle when the thread exits.
547 if (exited) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000548 LLDB_LOG(log, "got exit signal({0}) , tid = {1} ({2} main thread)", signal,
549 pid, is_main_thread ? "is" : "is not");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000550
551 // This is a thread that exited. Ensure we're not tracking it anymore.
552 const bool thread_found = StopTrackingThread(pid);
553
554 if (is_main_thread) {
555 // We only set the exit status and notify the delegate if we haven't
556 // already set the process
557 // state to an exited state. We normally should have received a SIGTRAP |
558 // (PTRACE_EVENT_EXIT << 8)
559 // for the main thread.
560 const bool already_notified = (GetState() == StateType::eStateExited) ||
561 (GetState() == StateType::eStateCrashed);
562 if (!already_notified) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000563 LLDB_LOG(
564 log,
565 "tid = {0} handling main thread exit ({1}), expected exit state "
566 "already set but state was {2} instead, setting exit state now",
567 pid,
568 thread_found ? "stopped tracking thread metadata"
569 : "thread metadata not found",
Pavel Labath8198db32017-01-24 11:48:25 +0000570 GetState());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000571 // The main thread exited. We're done monitoring. Report to delegate.
572 SetExitStatus(convert_pid_status_to_exit_type(status),
573 convert_pid_status_to_return_code(status), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +0000574
Kate Stoneb9c1b512016-09-06 20:57:50 +0000575 // Notify delegate that our process has exited.
576 SetState(StateType::eStateExited, true);
Pavel Labatha6321a82017-01-19 15:26:04 +0000577 } else
578 LLDB_LOG(log, "tid = {0} main thread now exited (%s)", pid,
579 thread_found ? "stopped tracking thread metadata"
580 : "thread metadata not found");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000581 } else {
582 // Do we want to report to the delegate in this case? I think not. If
Pavel Labatha6321a82017-01-19 15:26:04 +0000583 // this was an orderly thread exit, we would already have received the
584 // SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal, and we would have done an
585 // all-stop then.
586 LLDB_LOG(log, "tid = {0} handling non-main thread exit (%s)", pid,
587 thread_found ? "stopped tracking thread metadata"
588 : "thread metadata not found");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000589 }
590 return;
591 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000592
Kate Stoneb9c1b512016-09-06 20:57:50 +0000593 siginfo_t info;
594 const auto info_err = GetSignalInfo(pid, &info);
595 auto thread_sp = GetThreadByID(pid);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000596
Kate Stoneb9c1b512016-09-06 20:57:50 +0000597 if (!thread_sp) {
598 // Normally, the only situation when we cannot find the thread is if we have
Pavel Labatha6321a82017-01-19 15:26:04 +0000599 // just received a new thread notification. This is indicated by
600 // GetSignalInfo() returning si_code == SI_USER and si_pid == 0
601 LLDB_LOG(log, "received notification about an unknown tid {0}.", pid);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000602
Kate Stoneb9c1b512016-09-06 20:57:50 +0000603 if (info_err.Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000604 LLDB_LOG(log,
605 "(tid {0}) GetSignalInfo failed ({1}). "
606 "Ingoring this notification.",
607 pid, info_err);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000608 return;
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000609 }
610
Pavel Labatha6321a82017-01-19 15:26:04 +0000611 LLDB_LOG(log, "tid {0}, si_code: {1}, si_pid: {2}", pid, info.si_code,
612 info.si_pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000613
614 auto thread_sp = AddThread(pid);
615 // Resume the newly created thread.
616 ResumeThread(*thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
617 ThreadWasCreated(*thread_sp);
618 return;
619 }
620
621 // Get details on the signal raised.
622 if (info_err.Success()) {
623 // We have retrieved the signal info. Dispatch appropriately.
624 if (info.si_signo == SIGTRAP)
625 MonitorSIGTRAP(info, *thread_sp);
Chaoren Linfa03ad22015-02-03 01:50:42 +0000626 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000627 MonitorSignal(info, *thread_sp, exited);
628 } else {
629 if (info_err.GetError() == EINVAL) {
630 // This is a group stop reception for this tid.
631 // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU
Pavel Labatha6321a82017-01-19 15:26:04 +0000632 // into the tracee, triggering the group-stop mechanism. Normally
633 // receiving these would stop the process, pending a SIGCONT. Simulating
634 // this state in a debugger is hard and is generally not needed (one use
635 // case is debugging background task being managed by a shell). For
636 // general use, it is sufficient to stop the process in a signal-delivery
Kate Stoneb9c1b512016-09-06 20:57:50 +0000637 // stop which happens before the group stop. This done by MonitorSignal
Pavel Labatha6321a82017-01-19 15:26:04 +0000638 // and works correctly for all signals.
639 LLDB_LOG(log,
640 "received a group stop for pid {0} tid {1}. Transparent "
641 "handling of group stops not supported, resuming the "
642 "thread.",
643 GetID(), pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000644 ResumeThread(*thread_sp, thread_sp->GetState(),
645 LLDB_INVALID_SIGNAL_NUMBER);
646 } else {
647 // ptrace(GETSIGINFO) failed (but not due to group-stop).
Todd Fialaaf245d12014-06-30 21:05:18 +0000648
Kate Stoneb9c1b512016-09-06 20:57:50 +0000649 // A return value of ESRCH means the thread/process is no longer on the
Pavel Labatha6321a82017-01-19 15:26:04 +0000650 // system, so it was killed somehow outside of our control. Either way,
651 // we can't do anything with it anymore.
Todd Fialaaf245d12014-06-30 21:05:18 +0000652
Kate Stoneb9c1b512016-09-06 20:57:50 +0000653 // Stop tracking the metadata for the thread since it's entirely off the
654 // system now.
655 const bool thread_found = StopTrackingThread(pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000656
Pavel Labatha6321a82017-01-19 15:26:04 +0000657 LLDB_LOG(log,
658 "GetSignalInfo failed: {0}, tid = {1}, signal = {2}, "
659 "status = {3}, main_thread = {4}, thread_found: {5}",
660 info_err, pid, signal, status, is_main_thread, thread_found);
Todd Fialaaf245d12014-06-30 21:05:18 +0000661
Kate Stoneb9c1b512016-09-06 20:57:50 +0000662 if (is_main_thread) {
663 // Notify the delegate - our process is not available but appears to
664 // have been killed outside
665 // our control. Is eStateExited the right exit state in this case?
666 SetExitStatus(convert_pid_status_to_exit_type(status),
667 convert_pid_status_to_return_code(status), nullptr, true);
668 SetState(StateType::eStateExited, true);
669 } else {
670 // This thread was pulled out from underneath us. Anything to do here?
671 // Do we want to do an all stop?
Pavel Labatha6321a82017-01-19 15:26:04 +0000672 LLDB_LOG(log,
673 "pid {0} tid {1} non-main thread exit occurred, didn't "
674 "tell delegate anything since thread disappeared out "
675 "from underneath us",
676 GetID(), pid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000677 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000678 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000679 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000680}
681
Kate Stoneb9c1b512016-09-06 20:57:50 +0000682void NativeProcessLinux::WaitForNewThread(::pid_t tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000683 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Pavel Labath426bdf82015-04-28 07:51:52 +0000684
Kate Stoneb9c1b512016-09-06 20:57:50 +0000685 NativeThreadLinuxSP new_thread_sp = GetThreadByID(tid);
Pavel Labath426bdf82015-04-28 07:51:52 +0000686
Kate Stoneb9c1b512016-09-06 20:57:50 +0000687 if (new_thread_sp) {
688 // We are already tracking the thread - we got the event on the new thread
689 // (see
690 // MonitorSignal) before this one. We are done.
691 return;
692 }
Pavel Labath426bdf82015-04-28 07:51:52 +0000693
Kate Stoneb9c1b512016-09-06 20:57:50 +0000694 // The thread is not tracked yet, let's wait for it to appear.
695 int status = -1;
696 ::pid_t wait_pid;
697 do {
Pavel Labatha6321a82017-01-19 15:26:04 +0000698 LLDB_LOG(log,
699 "received thread creation event for tid {0}. tid not tracked "
700 "yet, waiting for thread to appear...",
701 tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000702 wait_pid = waitpid(tid, &status, __WALL);
703 } while (wait_pid == -1 && errno == EINTR);
704 // Since we are waiting on a specific tid, this must be the creation event.
Pavel Labatha6321a82017-01-19 15:26:04 +0000705 // But let's do some checks just in case.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000706 if (wait_pid != tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000707 LLDB_LOG(log,
708 "waiting for tid {0} failed. Assuming the thread has "
709 "disappeared in the meantime",
710 tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000711 // The only way I know of this could happen is if the whole process was
712 // SIGKILLed in the mean time. In any case, we can't do anything about that
713 // now.
714 return;
715 }
716 if (WIFEXITED(status)) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000717 LLDB_LOG(log,
718 "waiting for tid {0} returned an 'exited' event. Not "
719 "tracking the thread.",
720 tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000721 // Also a very improbable event.
722 return;
723 }
Pavel Labath426bdf82015-04-28 07:51:52 +0000724
Pavel Labatha6321a82017-01-19 15:26:04 +0000725 LLDB_LOG(log, "pid = {0}: tracking new thread tid {1}", GetID(), tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000726 new_thread_sp = AddThread(tid);
727 ResumeThread(*new_thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
728 ThreadWasCreated(*new_thread_sp);
Pavel Labath426bdf82015-04-28 07:51:52 +0000729}
730
Kate Stoneb9c1b512016-09-06 20:57:50 +0000731void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info,
732 NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000733 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000734 const bool is_main_thread = (thread.GetID() == GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000735
Kate Stoneb9c1b512016-09-06 20:57:50 +0000736 assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
Todd Fialaaf245d12014-06-30 21:05:18 +0000737
Kate Stoneb9c1b512016-09-06 20:57:50 +0000738 switch (info.si_code) {
739 // TODO: these two cases are required if we want to support tracing of the
740 // inferiors' children. We'd need this to debug a monitor.
741 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
742 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
Todd Fialaaf245d12014-06-30 21:05:18 +0000743
Kate Stoneb9c1b512016-09-06 20:57:50 +0000744 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): {
745 // This is the notification on the parent thread which informs us of new
746 // thread
747 // creation.
748 // We don't want to do anything with the parent thread so we just resume it.
749 // In case we
750 // want to implement "break on thread creation" functionality, we would need
751 // to stop
752 // here.
Todd Fialaaf245d12014-06-30 21:05:18 +0000753
Kate Stoneb9c1b512016-09-06 20:57:50 +0000754 unsigned long event_message = 0;
755 if (GetEventMessage(thread.GetID(), &event_message).Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000756 LLDB_LOG(log,
757 "pid {0} received thread creation event but "
758 "GetEventMessage failed so we don't know the new tid",
759 thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000760 } else
761 WaitForNewThread(event_message);
Todd Fialaaf245d12014-06-30 21:05:18 +0000762
Kate Stoneb9c1b512016-09-06 20:57:50 +0000763 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
764 break;
765 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000766
Kate Stoneb9c1b512016-09-06 20:57:50 +0000767 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): {
768 NativeThreadLinuxSP main_thread_sp;
Pavel Labatha6321a82017-01-19 15:26:04 +0000769 LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000770
771 // Exec clears any pending notifications.
772 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
773
774 // Remove all but the main thread here. Linux fork creates a new process
775 // which only copies the main thread.
Pavel Labatha6321a82017-01-19 15:26:04 +0000776 LLDB_LOG(log, "exec received, stop tracking all but main thread");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000777
778 for (auto thread_sp : m_threads) {
779 const bool is_main_thread = thread_sp && thread_sp->GetID() == GetID();
780 if (is_main_thread) {
781 main_thread_sp = std::static_pointer_cast<NativeThreadLinux>(thread_sp);
Pavel Labatha6321a82017-01-19 15:26:04 +0000782 LLDB_LOG(log, "found main thread with tid {0}, keeping",
783 main_thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000784 } else {
Pavel Labatha6321a82017-01-19 15:26:04 +0000785 LLDB_LOG(log, "discarding non-main-thread tid {0} due to exec",
786 thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000787 }
Todd Fialaa9882ce2014-08-28 15:46:54 +0000788 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000789
Kate Stoneb9c1b512016-09-06 20:57:50 +0000790 m_threads.clear();
Chaoren Linfa03ad22015-02-03 01:50:42 +0000791
Kate Stoneb9c1b512016-09-06 20:57:50 +0000792 if (main_thread_sp) {
793 m_threads.push_back(main_thread_sp);
794 SetCurrentThreadID(main_thread_sp->GetID());
795 main_thread_sp->SetStoppedByExec();
796 } else {
797 SetCurrentThreadID(LLDB_INVALID_THREAD_ID);
Pavel Labatha6321a82017-01-19 15:26:04 +0000798 LLDB_LOG(log,
799 "pid {0} no main thread found, discarded all threads, "
800 "we're in a no-thread state!",
801 GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000802 }
803
Kate Stoneb9c1b512016-09-06 20:57:50 +0000804 // Tell coordinator about about the "new" (since exec) stopped main thread.
805 ThreadWasCreated(*main_thread_sp);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000806
Kate Stoneb9c1b512016-09-06 20:57:50 +0000807 // Let our delegate know we have just exec'd.
808 NotifyDidExec();
809
810 // If we have a main thread, indicate we are stopped.
811 assert(main_thread_sp && "exec called during ptraced process but no main "
812 "thread metadata tracked");
813
814 // Let the process know we're stopped.
815 StopRunningThreads(main_thread_sp->GetID());
816
817 break;
818 }
819
820 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): {
821 // The inferior process or one of its threads is about to exit.
822 // We don't want to do anything with the thread so we just resume it. In
823 // case we
824 // want to implement "break on thread exit" functionality, we would need to
825 // stop
826 // here.
827
828 unsigned long data = 0;
829 if (GetEventMessage(thread.GetID(), &data).Fail())
830 data = -1;
831
Pavel Labatha6321a82017-01-19 15:26:04 +0000832 LLDB_LOG(log,
833 "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, "
834 "WIFSIGNALED={2}, pid = {3}, main_thread = {4}",
835 data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(),
836 is_main_thread);
Todd Fialaaf245d12014-06-30 21:05:18 +0000837
Kate Stoneb9c1b512016-09-06 20:57:50 +0000838 if (is_main_thread) {
839 SetExitStatus(convert_pid_status_to_exit_type(data),
840 convert_pid_status_to_return_code(data), nullptr, true);
841 }
842
843 StateType state = thread.GetState();
844 if (!StateIsRunningState(state)) {
845 // Due to a kernel bug, we may sometimes get this stop after the inferior
846 // gets a
847 // SIGKILL. This confuses our state tracking logic in ResumeThread(),
848 // since normally,
849 // we should not be receiving any ptrace events while the inferior is
850 // stopped. This
851 // makes sure that the inferior is resumed and exits normally.
852 state = eStateRunning;
853 }
854 ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
855
856 break;
857 }
858
859 case 0:
860 case TRAP_TRACE: // We receive this on single stepping.
861 case TRAP_HWBKPT: // We receive this on watchpoint hit
862 {
863 // If a watchpoint was hit, report it
864 uint32_t wp_index;
865 Error error = thread.GetRegisterContext()->GetWatchpointHitIndex(
866 wp_index, (uintptr_t)info.si_addr);
Pavel Labatha6321a82017-01-19 15:26:04 +0000867 if (error.Fail())
868 LLDB_LOG(log,
869 "received error while checking for watchpoint hits, pid = "
870 "{0}, error = {1}",
871 thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000872 if (wp_index != LLDB_INVALID_INDEX32) {
873 MonitorWatchpoint(thread, wp_index);
874 break;
875 }
876
877 // Otherwise, report step over
878 MonitorTrace(thread);
879 break;
880 }
881
882 case SI_KERNEL:
Mohit K. Bhakkad35799962015-06-18 04:53:18 +0000883#if defined __mips__
Kate Stoneb9c1b512016-09-06 20:57:50 +0000884 // For mips there is no special signal for watchpoint
885 // So we check for watchpoint in kernel trap
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000886 {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000887 // If a watchpoint was hit, report it
888 uint32_t wp_index;
889 Error error = thread.GetRegisterContext()->GetWatchpointHitIndex(
890 wp_index, LLDB_INVALID_ADDRESS);
Pavel Labatha6321a82017-01-19 15:26:04 +0000891 if (error.Fail())
892 LLDB_LOG(log,
893 "received error while checking for watchpoint hits, pid = "
894 "{0}, error = {1}",
895 thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000896 if (wp_index != LLDB_INVALID_INDEX32) {
897 MonitorWatchpoint(thread, wp_index);
898 break;
899 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000900 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000901// NO BREAK
Mohit K. Bhakkad35799962015-06-18 04:53:18 +0000902#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000903 case TRAP_BRKPT:
904 MonitorBreakpoint(thread);
905 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000906
Kate Stoneb9c1b512016-09-06 20:57:50 +0000907 case SIGTRAP:
908 case (SIGTRAP | 0x80):
Pavel Labatha6321a82017-01-19 15:26:04 +0000909 LLDB_LOG(
910 log,
911 "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",
912 info.si_code, GetID(), thread.GetID());
Chaoren Linfa03ad22015-02-03 01:50:42 +0000913
Kate Stoneb9c1b512016-09-06 20:57:50 +0000914 // Ignore these signals until we know more about them.
915 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
916 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000917
Kate Stoneb9c1b512016-09-06 20:57:50 +0000918 default:
Pavel Labatha6321a82017-01-19 15:26:04 +0000919 LLDB_LOG(
920 log,
921 "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming",
922 info.si_code, GetID(), thread.GetID());
923 llvm_unreachable("Unexpected SIGTRAP code!");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000924 break;
925 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000926}
927
Kate Stoneb9c1b512016-09-06 20:57:50 +0000928void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +0000929 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
930 LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000931
Kate Stoneb9c1b512016-09-06 20:57:50 +0000932 // This thread is currently stopped.
933 thread.SetStoppedByTrace();
934
935 StopRunningThreads(thread.GetID());
936}
937
938void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) {
939 Log *log(
940 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
Pavel Labatha6321a82017-01-19 15:26:04 +0000941 LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000942
943 // Mark the thread as stopped at breakpoint.
944 thread.SetStoppedByBreakpoint();
945 Error error = FixupBreakpointPCAsNeeded(thread);
946 if (error.Fail())
Pavel Labatha6321a82017-01-19 15:26:04 +0000947 LLDB_LOG(log, "pid = {0} fixup: {1}", thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000948
949 if (m_threads_stepping_with_breakpoint.find(thread.GetID()) !=
950 m_threads_stepping_with_breakpoint.end())
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000951 thread.SetStoppedByTrace();
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000952
Kate Stoneb9c1b512016-09-06 20:57:50 +0000953 StopRunningThreads(thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000954}
955
Kate Stoneb9c1b512016-09-06 20:57:50 +0000956void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread,
957 uint32_t wp_index) {
958 Log *log(
959 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
Pavel Labatha6321a82017-01-19 15:26:04 +0000960 LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}",
961 thread.GetID(), wp_index);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000962
963 // Mark the thread as stopped at watchpoint.
964 // The address is at (lldb::addr_t)info->si_addr if we need it.
965 thread.SetStoppedByWatchpoint(wp_index);
966
967 // We need to tell all other running threads before we notify the delegate
968 // about this stop.
969 StopRunningThreads(thread.GetID());
970}
971
972void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
973 NativeThreadLinux &thread, bool exited) {
974 const int signo = info.si_signo;
975 const bool is_from_llgs = info.si_pid == getpid();
976
Pavel Labatha6321a82017-01-19 15:26:04 +0000977 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000978
979 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
980 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
981 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
982 //
983 // IOW, user generated signals never generate what we consider to be a
984 // "crash".
985 //
986 // Similarly, ACK signals generated by this monitor.
987
988 // Handle the signal.
Pavel Labatha6321a82017-01-19 15:26:04 +0000989 LLDB_LOG(log,
990 "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, "
991 "waitpid pid = {4})",
992 Host::GetSignalAsCString(signo), signo, info.si_code,
993 thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000994
Kate Stoneb9c1b512016-09-06 20:57:50 +0000995 // Check for thread stop notification.
996 if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) {
997 // This is a tgkill()-based stop.
Pavel Labatha6321a82017-01-19 15:26:04 +0000998 LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +0000999
Kate Stoneb9c1b512016-09-06 20:57:50 +00001000 // Check that we're not already marked with a stop reason.
1001 // Note this thread really shouldn't already be marked as stopped - if we
Pavel Labatha6321a82017-01-19 15:26:04 +00001002 // were, that would imply that the kernel signaled us with the thread
1003 // stopping which we handled and marked as stopped, and that, without an
1004 // intervening resume, we received another stop. It is more likely that we
1005 // are missing the marking of a run state somewhere if we find that the
1006 // thread was marked as stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001007 const StateType thread_state = thread.GetState();
1008 if (!StateIsStoppedState(thread_state, false)) {
1009 // An inferior thread has stopped because of a SIGSTOP we have sent it.
1010 // Generally, these are not important stops and we don't want to report
Pavel Labatha6321a82017-01-19 15:26:04 +00001011 // them as they are just used to stop other threads when one thread (the
1012 // one with the *real* stop reason) hits a breakpoint (watchpoint,
1013 // etc...). However, in the case of an asynchronous Interrupt(), this *is*
1014 // the real stop reason, so we leave the signal intact if this is the
1015 // thread that was chosen as the triggering thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001016 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
1017 if (m_pending_notification_tid == thread.GetID())
1018 thread.SetStoppedBySignal(SIGSTOP, &info);
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001019 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001020 thread.SetStoppedWithNoReason();
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001021
Kate Stoneb9c1b512016-09-06 20:57:50 +00001022 SetCurrentThreadID(thread.GetID());
1023 SignalIfAllThreadsStopped();
1024 } else {
1025 // We can end up here if stop was initiated by LLGS but by this time a
1026 // thread stop has occurred - maybe initiated by another event.
1027 Error error = ResumeThread(thread, thread.GetState(), 0);
Pavel Labatha6321a82017-01-19 15:26:04 +00001028 if (error.Fail())
1029 LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(),
1030 error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001031 }
1032 } else {
Pavel Labatha6321a82017-01-19 15:26:04 +00001033 LLDB_LOG(log,
1034 "pid {0} tid {1}, thread was already marked as a stopped "
1035 "state (state={2}), leaving stop signal as is",
Pavel Labath8198db32017-01-24 11:48:25 +00001036 GetID(), thread.GetID(), thread_state);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001037 SignalIfAllThreadsStopped();
Todd Fialaaf245d12014-06-30 21:05:18 +00001038 }
1039
Kate Stoneb9c1b512016-09-06 20:57:50 +00001040 // Done handling.
1041 return;
1042 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001043
Kate Stoneb9c1b512016-09-06 20:57:50 +00001044 // This thread is stopped.
Pavel Labatha6321a82017-01-19 15:26:04 +00001045 LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001046 thread.SetStoppedBySignal(signo, &info);
1047
1048 // Send a stop to the debugger after we get all other threads to stop.
1049 StopRunningThreads(thread.GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +00001050}
1051
Tamas Berghammere7708682015-04-22 10:00:23 +00001052namespace {
1053
Kate Stoneb9c1b512016-09-06 20:57:50 +00001054struct EmulatorBaton {
1055 NativeProcessLinux *m_process;
1056 NativeRegisterContext *m_reg_context;
Tamas Berghammere7708682015-04-22 10:00:23 +00001057
Kate Stoneb9c1b512016-09-06 20:57:50 +00001058 // eRegisterKindDWARF -> RegsiterValue
1059 std::unordered_map<uint32_t, RegisterValue> m_register_values;
Pavel Labath6648fcc2015-04-27 09:21:14 +00001060
Kate Stoneb9c1b512016-09-06 20:57:50 +00001061 EmulatorBaton(NativeProcessLinux *process, NativeRegisterContext *reg_context)
1062 : m_process(process), m_reg_context(reg_context) {}
Tamas Berghammere7708682015-04-22 10:00:23 +00001063};
1064
1065} // anonymous namespace
1066
Kate Stoneb9c1b512016-09-06 20:57:50 +00001067static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
1068 const EmulateInstruction::Context &context,
1069 lldb::addr_t addr, void *dst, size_t length) {
1070 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
Tamas Berghammere7708682015-04-22 10:00:23 +00001071
Kate Stoneb9c1b512016-09-06 20:57:50 +00001072 size_t bytes_read;
1073 emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
1074 return bytes_read;
Tamas Berghammere7708682015-04-22 10:00:23 +00001075}
1076
Kate Stoneb9c1b512016-09-06 20:57:50 +00001077static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
1078 const RegisterInfo *reg_info,
1079 RegisterValue &reg_value) {
1080 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
Tamas Berghammere7708682015-04-22 10:00:23 +00001081
Kate Stoneb9c1b512016-09-06 20:57:50 +00001082 auto it = emulator_baton->m_register_values.find(
1083 reg_info->kinds[eRegisterKindDWARF]);
1084 if (it != emulator_baton->m_register_values.end()) {
1085 reg_value = it->second;
1086 return true;
1087 }
1088
1089 // The emulator only fill in the dwarf regsiter numbers (and in some case
1090 // the generic register numbers). Get the full register info from the
1091 // register context based on the dwarf register numbers.
1092 const RegisterInfo *full_reg_info =
1093 emulator_baton->m_reg_context->GetRegisterInfo(
1094 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
1095
1096 Error error =
1097 emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
1098 if (error.Success())
1099 return true;
1100
1101 return false;
1102}
1103
1104static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
1105 const EmulateInstruction::Context &context,
1106 const RegisterInfo *reg_info,
1107 const RegisterValue &reg_value) {
1108 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
1109 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
1110 reg_value;
1111 return true;
1112}
1113
1114static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
1115 const EmulateInstruction::Context &context,
1116 lldb::addr_t addr, const void *dst,
1117 size_t length) {
1118 return length;
1119}
1120
1121static lldb::addr_t ReadFlags(NativeRegisterContext *regsiter_context) {
1122 const RegisterInfo *flags_info = regsiter_context->GetRegisterInfo(
1123 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1124 return regsiter_context->ReadRegisterAsUnsigned(flags_info,
1125 LLDB_INVALID_ADDRESS);
1126}
1127
1128Error NativeProcessLinux::SetupSoftwareSingleStepping(
1129 NativeThreadLinux &thread) {
1130 Error error;
1131 NativeRegisterContextSP register_context_sp = thread.GetRegisterContext();
1132
1133 std::unique_ptr<EmulateInstruction> emulator_ap(
1134 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying,
1135 nullptr));
1136
1137 if (emulator_ap == nullptr)
1138 return Error("Instruction emulator not found!");
1139
1140 EmulatorBaton baton(this, register_context_sp.get());
1141 emulator_ap->SetBaton(&baton);
1142 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
1143 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
1144 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
1145 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
1146
1147 if (!emulator_ap->ReadInstruction())
1148 return Error("Read instruction failed!");
1149
1150 bool emulation_result =
1151 emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
1152
1153 const RegisterInfo *reg_info_pc = register_context_sp->GetRegisterInfo(
1154 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1155 const RegisterInfo *reg_info_flags = register_context_sp->GetRegisterInfo(
1156 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1157
1158 auto pc_it =
1159 baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1160 auto flags_it =
1161 baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
1162
1163 lldb::addr_t next_pc;
1164 lldb::addr_t next_flags;
1165 if (emulation_result) {
1166 assert(pc_it != baton.m_register_values.end() &&
1167 "Emulation was successfull but PC wasn't updated");
1168 next_pc = pc_it->second.GetAsUInt64();
1169
1170 if (flags_it != baton.m_register_values.end())
1171 next_flags = flags_it->second.GetAsUInt64();
1172 else
1173 next_flags = ReadFlags(register_context_sp.get());
1174 } else if (pc_it == baton.m_register_values.end()) {
1175 // Emulate instruction failed and it haven't changed PC. Advance PC
1176 // with the size of the current opcode because the emulation of all
1177 // PC modifying instruction should be successful. The failure most
1178 // likely caused by a not supported instruction which don't modify PC.
1179 next_pc =
1180 register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
1181 next_flags = ReadFlags(register_context_sp.get());
1182 } else {
1183 // The instruction emulation failed after it modified the PC. It is an
1184 // unknown error where we can't continue because the next instruction is
1185 // modifying the PC but we don't know how.
1186 return Error("Instruction emulation failed unexpectedly.");
1187 }
1188
1189 if (m_arch.GetMachine() == llvm::Triple::arm) {
1190 if (next_flags & 0x20) {
1191 // Thumb mode
1192 error = SetSoftwareBreakpoint(next_pc, 2);
1193 } else {
1194 // Arm mode
1195 error = SetSoftwareBreakpoint(next_pc, 4);
Pavel Labath6648fcc2015-04-27 09:21:14 +00001196 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001197 } else if (m_arch.GetMachine() == llvm::Triple::mips64 ||
1198 m_arch.GetMachine() == llvm::Triple::mips64el ||
1199 m_arch.GetMachine() == llvm::Triple::mips ||
1200 m_arch.GetMachine() == llvm::Triple::mipsel)
1201 error = SetSoftwareBreakpoint(next_pc, 4);
1202 else {
1203 // No size hint is given for the next breakpoint
1204 error = SetSoftwareBreakpoint(next_pc, 0);
1205 }
Pavel Labath6648fcc2015-04-27 09:21:14 +00001206
Pavel Labath42eb6902016-10-26 11:13:56 +00001207 // If setting the breakpoint fails because next_pc is out of
1208 // the address space, ignore it and let the debugee segfault.
1209 if (error.GetError() == EIO || error.GetError() == EFAULT) {
Mehdi Amini665be502016-11-11 05:07:57 +00001210 return Error();
Pavel Labath42eb6902016-10-26 11:13:56 +00001211 } else if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001212 return error;
Tamas Berghammere7708682015-04-22 10:00:23 +00001213
Kate Stoneb9c1b512016-09-06 20:57:50 +00001214 m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001215
Mehdi Amini665be502016-11-11 05:07:57 +00001216 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001217}
1218
1219bool NativeProcessLinux::SupportHardwareSingleStepping() const {
1220 if (m_arch.GetMachine() == llvm::Triple::arm ||
1221 m_arch.GetMachine() == llvm::Triple::mips64 ||
1222 m_arch.GetMachine() == llvm::Triple::mips64el ||
1223 m_arch.GetMachine() == llvm::Triple::mips ||
1224 m_arch.GetMachine() == llvm::Triple::mipsel)
Pavel Labath6648fcc2015-04-27 09:21:14 +00001225 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001226 return true;
Tamas Berghammere7708682015-04-22 10:00:23 +00001227}
1228
Kate Stoneb9c1b512016-09-06 20:57:50 +00001229Error NativeProcessLinux::Resume(const ResumeActionList &resume_actions) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001230 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1231 LLDB_LOG(log, "pid {0}", GetID());
Tamas Berghammere7708682015-04-22 10:00:23 +00001232
Kate Stoneb9c1b512016-09-06 20:57:50 +00001233 bool software_single_step = !SupportHardwareSingleStepping();
Tamas Berghammere7708682015-04-22 10:00:23 +00001234
Kate Stoneb9c1b512016-09-06 20:57:50 +00001235 if (software_single_step) {
1236 for (auto thread_sp : m_threads) {
1237 assert(thread_sp && "thread list should not contain NULL threads");
Tamas Berghammere7708682015-04-22 10:00:23 +00001238
Kate Stoneb9c1b512016-09-06 20:57:50 +00001239 const ResumeAction *const action =
1240 resume_actions.GetActionForThread(thread_sp->GetID(), true);
1241 if (action == nullptr)
1242 continue;
Tamas Berghammere7708682015-04-22 10:00:23 +00001243
Kate Stoneb9c1b512016-09-06 20:57:50 +00001244 if (action->state == eStateStepping) {
1245 Error error = SetupSoftwareSingleStepping(
1246 static_cast<NativeThreadLinux &>(*thread_sp));
1247 if (error.Fail())
1248 return error;
1249 }
Tamas Berghammere7708682015-04-22 10:00:23 +00001250 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001251 }
1252
1253 for (auto thread_sp : m_threads) {
1254 assert(thread_sp && "thread list should not contain NULL threads");
1255
1256 const ResumeAction *const action =
1257 resume_actions.GetActionForThread(thread_sp->GetID(), true);
1258
1259 if (action == nullptr) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001260 LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
1261 thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001262 continue;
Tamas Berghammere7708682015-04-22 10:00:23 +00001263 }
1264
Pavel Labatha6321a82017-01-19 15:26:04 +00001265 LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}",
Pavel Labath8198db32017-01-24 11:48:25 +00001266 action->state, GetID(), thread_sp->GetID());
Tamas Berghammere7708682015-04-22 10:00:23 +00001267
Kate Stoneb9c1b512016-09-06 20:57:50 +00001268 switch (action->state) {
1269 case eStateRunning:
1270 case eStateStepping: {
1271 // Run the thread, possibly feeding it the signal.
1272 const int signo = action->signal;
1273 ResumeThread(static_cast<NativeThreadLinux &>(*thread_sp), action->state,
1274 signo);
1275 break;
1276 }
Tamas Berghammere7708682015-04-22 10:00:23 +00001277
Kate Stoneb9c1b512016-09-06 20:57:50 +00001278 case eStateSuspended:
1279 case eStateStopped:
Pavel Labatha6321a82017-01-19 15:26:04 +00001280 llvm_unreachable("Unexpected state");
Tamas Berghammere7708682015-04-22 10:00:23 +00001281
Kate Stoneb9c1b512016-09-06 20:57:50 +00001282 default:
1283 return Error("NativeProcessLinux::%s (): unexpected state %s specified "
1284 "for pid %" PRIu64 ", tid %" PRIu64,
1285 __FUNCTION__, StateAsCString(action->state), GetID(),
1286 thread_sp->GetID());
1287 }
1288 }
1289
Mehdi Amini665be502016-11-11 05:07:57 +00001290 return Error();
Tamas Berghammere7708682015-04-22 10:00:23 +00001291}
1292
Kate Stoneb9c1b512016-09-06 20:57:50 +00001293Error NativeProcessLinux::Halt() {
1294 Error error;
1295
1296 if (kill(GetID(), SIGSTOP) != 0)
1297 error.SetErrorToErrno();
1298
1299 return error;
Tamas Berghammere7708682015-04-22 10:00:23 +00001300}
1301
Kate Stoneb9c1b512016-09-06 20:57:50 +00001302Error NativeProcessLinux::Detach() {
1303 Error error;
1304
1305 // Stop monitoring the inferior.
1306 m_sigchld_handle.reset();
1307
1308 // Tell ptrace to detach from the process.
1309 if (GetID() == LLDB_INVALID_PROCESS_ID)
1310 return error;
1311
1312 for (auto thread_sp : m_threads) {
1313 Error e = Detach(thread_sp->GetID());
1314 if (e.Fail())
1315 error =
1316 e; // Save the error, but still attempt to detach from other threads.
1317 }
1318
1319 return error;
1320}
1321
1322Error NativeProcessLinux::Signal(int signo) {
1323 Error error;
1324
Pavel Labatha6321a82017-01-19 15:26:04 +00001325 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1326 LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo,
1327 Host::GetSignalAsCString(signo), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001328
1329 if (kill(GetID(), signo))
1330 error.SetErrorToErrno();
1331
1332 return error;
1333}
1334
1335Error NativeProcessLinux::Interrupt() {
1336 // Pick a running thread (or if none, a not-dead stopped thread) as
1337 // the chosen thread that will be the stop-reason thread.
Pavel Labatha6321a82017-01-19 15:26:04 +00001338 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001339
1340 NativeThreadProtocolSP running_thread_sp;
1341 NativeThreadProtocolSP stopped_thread_sp;
1342
Pavel Labatha6321a82017-01-19 15:26:04 +00001343 LLDB_LOG(log, "selecting running thread for interrupt target");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001344 for (auto thread_sp : m_threads) {
1345 // The thread shouldn't be null but lets just cover that here.
1346 if (!thread_sp)
1347 continue;
1348
1349 // If we have a running or stepping thread, we'll call that the
1350 // target of the interrupt.
1351 const auto thread_state = thread_sp->GetState();
1352 if (thread_state == eStateRunning || thread_state == eStateStepping) {
1353 running_thread_sp = thread_sp;
1354 break;
1355 } else if (!stopped_thread_sp && StateIsStoppedState(thread_state, true)) {
1356 // Remember the first non-dead stopped thread. We'll use that as a backup
1357 // if there are no running threads.
1358 stopped_thread_sp = thread_sp;
1359 }
1360 }
1361
1362 if (!running_thread_sp && !stopped_thread_sp) {
1363 Error error("found no running/stepping or live stopped threads as target "
1364 "for interrupt");
Pavel Labatha6321a82017-01-19 15:26:04 +00001365 LLDB_LOG(log, "skipping due to error: {0}", error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001366
1367 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001368 }
1369
1370 NativeThreadProtocolSP deferred_signal_thread_sp =
1371 running_thread_sp ? running_thread_sp : stopped_thread_sp;
1372
Pavel Labatha6321a82017-01-19 15:26:04 +00001373 LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(),
1374 running_thread_sp ? "running" : "stopped",
1375 deferred_signal_thread_sp->GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001376
1377 StopRunningThreads(deferred_signal_thread_sp->GetID());
1378
Mehdi Amini665be502016-11-11 05:07:57 +00001379 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00001380}
1381
Kate Stoneb9c1b512016-09-06 20:57:50 +00001382Error NativeProcessLinux::Kill() {
Pavel Labatha6321a82017-01-19 15:26:04 +00001383 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1384 LLDB_LOG(log, "pid {0}", GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +00001385
Kate Stoneb9c1b512016-09-06 20:57:50 +00001386 Error error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001387
Kate Stoneb9c1b512016-09-06 20:57:50 +00001388 switch (m_state) {
1389 case StateType::eStateInvalid:
1390 case StateType::eStateExited:
1391 case StateType::eStateCrashed:
1392 case StateType::eStateDetached:
1393 case StateType::eStateUnloaded:
1394 // Nothing to do - the process is already dead.
Pavel Labatha6321a82017-01-19 15:26:04 +00001395 LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
Pavel Labath8198db32017-01-24 11:48:25 +00001396 m_state);
Todd Fialaaf245d12014-06-30 21:05:18 +00001397 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001398
Kate Stoneb9c1b512016-09-06 20:57:50 +00001399 case StateType::eStateConnected:
1400 case StateType::eStateAttaching:
1401 case StateType::eStateLaunching:
1402 case StateType::eStateStopped:
1403 case StateType::eStateRunning:
1404 case StateType::eStateStepping:
1405 case StateType::eStateSuspended:
1406 // We can try to kill a process in these states.
1407 break;
1408 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001409
Kate Stoneb9c1b512016-09-06 20:57:50 +00001410 if (kill(GetID(), SIGKILL) != 0) {
1411 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +00001412 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001413 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001414
Kate Stoneb9c1b512016-09-06 20:57:50 +00001415 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001416}
1417
1418static Error
Kate Stoneb9c1b512016-09-06 20:57:50 +00001419ParseMemoryRegionInfoFromProcMapsLine(const std::string &maps_line,
1420 MemoryRegionInfo &memory_region_info) {
1421 memory_region_info.Clear();
Todd Fialaaf245d12014-06-30 21:05:18 +00001422
Kate Stoneb9c1b512016-09-06 20:57:50 +00001423 StringExtractor line_extractor(maps_line.c_str());
Todd Fialaaf245d12014-06-30 21:05:18 +00001424
Kate Stoneb9c1b512016-09-06 20:57:50 +00001425 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode
1426 // pathname
1427 // perms: rwxp (letter is present if set, '-' if not, final character is
1428 // p=private, s=shared).
Todd Fialaaf245d12014-06-30 21:05:18 +00001429
Kate Stoneb9c1b512016-09-06 20:57:50 +00001430 // Parse out the starting address
1431 lldb::addr_t start_address = line_extractor.GetHexMaxU64(false, 0);
Todd Fialaaf245d12014-06-30 21:05:18 +00001432
Kate Stoneb9c1b512016-09-06 20:57:50 +00001433 // Parse out hyphen separating start and end address from range.
1434 if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != '-'))
1435 return Error(
1436 "malformed /proc/{pid}/maps entry, missing dash between address range");
Todd Fialaaf245d12014-06-30 21:05:18 +00001437
Kate Stoneb9c1b512016-09-06 20:57:50 +00001438 // Parse out the ending address
1439 lldb::addr_t end_address = line_extractor.GetHexMaxU64(false, start_address);
Todd Fialaaf245d12014-06-30 21:05:18 +00001440
Kate Stoneb9c1b512016-09-06 20:57:50 +00001441 // Parse out the space after the address.
1442 if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != ' '))
1443 return Error("malformed /proc/{pid}/maps entry, missing space after range");
Todd Fialaaf245d12014-06-30 21:05:18 +00001444
Kate Stoneb9c1b512016-09-06 20:57:50 +00001445 // Save the range.
1446 memory_region_info.GetRange().SetRangeBase(start_address);
1447 memory_region_info.GetRange().SetRangeEnd(end_address);
Todd Fialaaf245d12014-06-30 21:05:18 +00001448
Kate Stoneb9c1b512016-09-06 20:57:50 +00001449 // Any memory region in /proc/{pid}/maps is by definition mapped into the
1450 // process.
1451 memory_region_info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
Howard Hellyerad007562016-07-07 08:21:28 +00001452
Kate Stoneb9c1b512016-09-06 20:57:50 +00001453 // Parse out each permission entry.
1454 if (line_extractor.GetBytesLeft() < 4)
1455 return Error("malformed /proc/{pid}/maps entry, missing some portion of "
1456 "permissions");
Todd Fialaaf245d12014-06-30 21:05:18 +00001457
Kate Stoneb9c1b512016-09-06 20:57:50 +00001458 // Handle read permission.
1459 const char read_perm_char = line_extractor.GetChar();
1460 if (read_perm_char == 'r')
1461 memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eYes);
1462 else if (read_perm_char == '-')
1463 memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1464 else
1465 return Error("unexpected /proc/{pid}/maps read permission char");
Todd Fialaaf245d12014-06-30 21:05:18 +00001466
Kate Stoneb9c1b512016-09-06 20:57:50 +00001467 // Handle write permission.
1468 const char write_perm_char = line_extractor.GetChar();
1469 if (write_perm_char == 'w')
1470 memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eYes);
1471 else if (write_perm_char == '-')
1472 memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1473 else
1474 return Error("unexpected /proc/{pid}/maps write permission char");
Todd Fialaaf245d12014-06-30 21:05:18 +00001475
Kate Stoneb9c1b512016-09-06 20:57:50 +00001476 // Handle execute permission.
1477 const char exec_perm_char = line_extractor.GetChar();
1478 if (exec_perm_char == 'x')
1479 memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes);
1480 else if (exec_perm_char == '-')
1481 memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1482 else
1483 return Error("unexpected /proc/{pid}/maps exec permission char");
Todd Fialaaf245d12014-06-30 21:05:18 +00001484
Kate Stoneb9c1b512016-09-06 20:57:50 +00001485 line_extractor.GetChar(); // Read the private bit
1486 line_extractor.SkipSpaces(); // Skip the separator
1487 line_extractor.GetHexMaxU64(false, 0); // Read the offset
1488 line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1489 line_extractor.GetChar(); // Read the device id separator
1490 line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1491 line_extractor.SkipSpaces(); // Skip the separator
1492 line_extractor.GetU64(0, 10); // Read the inode number
Tamas Berghammerd7d69f82016-07-22 12:55:35 +00001493
Kate Stoneb9c1b512016-09-06 20:57:50 +00001494 line_extractor.SkipSpaces();
1495 const char *name = line_extractor.Peek();
1496 if (name)
1497 memory_region_info.SetName(name);
Tamas Berghammerd7d69f82016-07-22 12:55:35 +00001498
Mehdi Amini665be502016-11-11 05:07:57 +00001499 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00001500}
1501
Kate Stoneb9c1b512016-09-06 20:57:50 +00001502Error NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr,
1503 MemoryRegionInfo &range_info) {
1504 // FIXME review that the final memory region returned extends to the end of
1505 // the virtual address space,
1506 // with no perms if it is not mapped.
Todd Fialaaf245d12014-06-30 21:05:18 +00001507
Kate Stoneb9c1b512016-09-06 20:57:50 +00001508 // Use an approach that reads memory regions from /proc/{pid}/maps.
1509 // Assume proc maps entries are in ascending order.
1510 // FIXME assert if we find differently.
Todd Fialaaf245d12014-06-30 21:05:18 +00001511
Kate Stoneb9c1b512016-09-06 20:57:50 +00001512 if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
1513 // We're done.
Tamas Berghammera6f57952017-01-03 16:29:43 +00001514 return Error("unsupported");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001515 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001516
Tamas Berghammera6f57952017-01-03 16:29:43 +00001517 Error error = PopulateMemoryRegionCache();
1518 if (error.Fail()) {
1519 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001520 }
1521
1522 lldb::addr_t prev_base_address = 0;
1523
1524 // FIXME start by finding the last region that is <= target address using
1525 // binary search. Data is sorted.
1526 // There can be a ton of regions on pthreads apps with lots of threads.
1527 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1528 ++it) {
Tamas Berghammera6f57952017-01-03 16:29:43 +00001529 MemoryRegionInfo &proc_entry_info = it->first;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001530
1531 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1532 assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
1533 "descending /proc/pid/maps entries detected, unexpected");
1534 prev_base_address = proc_entry_info.GetRange().GetRangeBase();
Hafiz Abid Qadeerb1554312017-01-20 10:24:03 +00001535 UNUSED_IF_ASSERT_DISABLED(prev_base_address);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001536
1537 // If the target address comes before this entry, indicate distance to next
1538 // region.
1539 if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1540 range_info.GetRange().SetRangeBase(load_addr);
1541 range_info.GetRange().SetByteSize(
1542 proc_entry_info.GetRange().GetRangeBase() - load_addr);
1543 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1544 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1545 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1546 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1547
1548 return error;
1549 } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1550 // The target address is within the memory region we're processing here.
1551 range_info = proc_entry_info;
1552 return error;
1553 }
1554
1555 // The target memory address comes somewhere after the region we just
1556 // parsed.
1557 }
1558
1559 // If we made it here, we didn't find an entry that contained the given
1560 // address. Return the
1561 // load_addr as start and the amount of bytes betwwen load address and the end
1562 // of the memory as
1563 // size.
1564 range_info.GetRange().SetRangeBase(load_addr);
1565 range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
1566 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1567 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1568 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1569 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1570 return error;
1571}
1572
Tamas Berghammera6f57952017-01-03 16:29:43 +00001573Error NativeProcessLinux::PopulateMemoryRegionCache() {
Pavel Labatha6321a82017-01-19 15:26:04 +00001574 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Tamas Berghammera6f57952017-01-03 16:29:43 +00001575
1576 // If our cache is empty, pull the latest. There should always be at least
1577 // one memory region if memory region handling is supported.
1578 if (!m_mem_region_cache.empty()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001579 LLDB_LOG(log, "reusing {0} cached memory region entries",
1580 m_mem_region_cache.size());
Tamas Berghammera6f57952017-01-03 16:29:43 +00001581 return Error();
1582 }
1583
1584 Error error = ProcFileReader::ProcessLineByLine(
1585 GetID(), "maps", [&](const std::string &line) -> bool {
1586 MemoryRegionInfo info;
1587 const Error parse_error =
1588 ParseMemoryRegionInfoFromProcMapsLine(line, info);
1589 if (parse_error.Success()) {
1590 m_mem_region_cache.emplace_back(
1591 info, FileSpec(info.GetName().GetCString(), true));
1592 return true;
1593 } else {
Pavel Labatha6321a82017-01-19 15:26:04 +00001594 LLDB_LOG(log, "failed to parse proc maps line '{0}': {1}", line,
1595 parse_error);
Tamas Berghammera6f57952017-01-03 16:29:43 +00001596 return false;
1597 }
1598 });
1599
1600 // If we had an error, we'll mark unsupported.
1601 if (error.Fail()) {
1602 m_supports_mem_region = LazyBool::eLazyBoolNo;
1603 return error;
1604 } else if (m_mem_region_cache.empty()) {
1605 // No entries after attempting to read them. This shouldn't happen if
1606 // /proc/{pid}/maps is supported. Assume we don't support map entries
1607 // via procfs.
Pavel Labatha6321a82017-01-19 15:26:04 +00001608 LLDB_LOG(log,
1609 "failed to find any procfs maps entries, assuming no support "
1610 "for memory region metadata retrieval");
Tamas Berghammera6f57952017-01-03 16:29:43 +00001611 m_supports_mem_region = LazyBool::eLazyBoolNo;
1612 error.SetErrorString("not supported");
1613 return error;
1614 }
1615
Pavel Labatha6321a82017-01-19 15:26:04 +00001616 LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps",
1617 m_mem_region_cache.size(), GetID());
Tamas Berghammera6f57952017-01-03 16:29:43 +00001618
1619 // We support memory retrieval, remember that.
1620 m_supports_mem_region = LazyBool::eLazyBoolYes;
1621 return Error();
1622}
1623
Kate Stoneb9c1b512016-09-06 20:57:50 +00001624void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001625 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1626 LLDB_LOG(log, "newBumpId={0}", newBumpId);
1627 LLDB_LOG(log, "clearing {0} entries from memory region cache",
1628 m_mem_region_cache.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001629 m_mem_region_cache.clear();
1630}
1631
1632Error NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions,
1633 lldb::addr_t &addr) {
1634// FIXME implementing this requires the equivalent of
1635// InferiorCallPOSIX::InferiorCallMmap, which depends on
1636// functional ThreadPlans working with Native*Protocol.
1637#if 1
1638 return Error("not implemented yet");
1639#else
1640 addr = LLDB_INVALID_ADDRESS;
1641
1642 unsigned prot = 0;
1643 if (permissions & lldb::ePermissionsReadable)
1644 prot |= eMmapProtRead;
1645 if (permissions & lldb::ePermissionsWritable)
1646 prot |= eMmapProtWrite;
1647 if (permissions & lldb::ePermissionsExecutable)
1648 prot |= eMmapProtExec;
1649
1650 // TODO implement this directly in NativeProcessLinux
1651 // (and lift to NativeProcessPOSIX if/when that class is
1652 // refactored out).
1653 if (InferiorCallMmap(this, addr, 0, size, prot,
1654 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
1655 m_addr_to_mmap_size[addr] = size;
Mehdi Amini665be502016-11-11 05:07:57 +00001656 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001657 } else {
1658 addr = LLDB_INVALID_ADDRESS;
1659 return Error("unable to allocate %" PRIu64
1660 " bytes of memory with permissions %s",
1661 size, GetPermissionsAsCString(permissions));
1662 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001663#endif
1664}
1665
Kate Stoneb9c1b512016-09-06 20:57:50 +00001666Error NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {
1667 // FIXME see comments in AllocateMemory - required lower-level
1668 // bits not in place yet (ThreadPlans)
1669 return Error("not implemented");
Todd Fialaaf245d12014-06-30 21:05:18 +00001670}
1671
Kate Stoneb9c1b512016-09-06 20:57:50 +00001672lldb::addr_t NativeProcessLinux::GetSharedLibraryInfoAddress() {
1673 // punt on this for now
1674 return LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00001675}
1676
Kate Stoneb9c1b512016-09-06 20:57:50 +00001677size_t NativeProcessLinux::UpdateThreads() {
1678 // The NativeProcessLinux monitoring threads are always up to date
1679 // with respect to thread state and they keep the thread list
1680 // populated properly. All this method needs to do is return the
1681 // thread count.
1682 return m_threads.size();
Todd Fialaaf245d12014-06-30 21:05:18 +00001683}
1684
Kate Stoneb9c1b512016-09-06 20:57:50 +00001685bool NativeProcessLinux::GetArchitecture(ArchSpec &arch) const {
1686 arch = m_arch;
1687 return true;
Todd Fialaaf245d12014-06-30 21:05:18 +00001688}
1689
Kate Stoneb9c1b512016-09-06 20:57:50 +00001690Error NativeProcessLinux::GetSoftwareBreakpointPCOffset(
1691 uint32_t &actual_opcode_size) {
1692 // FIXME put this behind a breakpoint protocol class that can be
1693 // set per architecture. Need ARM, MIPS support here.
1694 static const uint8_t g_i386_opcode[] = {0xCC};
1695 static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
Todd Fialaaf245d12014-06-30 21:05:18 +00001696
Kate Stoneb9c1b512016-09-06 20:57:50 +00001697 switch (m_arch.GetMachine()) {
1698 case llvm::Triple::x86:
1699 case llvm::Triple::x86_64:
1700 actual_opcode_size = static_cast<uint32_t>(sizeof(g_i386_opcode));
Mehdi Amini665be502016-11-11 05:07:57 +00001701 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00001702
Kate Stoneb9c1b512016-09-06 20:57:50 +00001703 case llvm::Triple::systemz:
1704 actual_opcode_size = static_cast<uint32_t>(sizeof(g_s390x_opcode));
Mehdi Amini665be502016-11-11 05:07:57 +00001705 return Error();
Ulrich Weigandbb00d0b2016-04-14 14:28:34 +00001706
Kate Stoneb9c1b512016-09-06 20:57:50 +00001707 case llvm::Triple::arm:
1708 case llvm::Triple::aarch64:
1709 case llvm::Triple::mips64:
1710 case llvm::Triple::mips64el:
1711 case llvm::Triple::mips:
1712 case llvm::Triple::mipsel:
1713 // On these architectures the PC don't get updated for breakpoint hits
1714 actual_opcode_size = 0;
Mehdi Amini665be502016-11-11 05:07:57 +00001715 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001716
1717 default:
1718 assert(false && "CPU type not supported!");
1719 return Error("CPU type not supported");
1720 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001721}
1722
Kate Stoneb9c1b512016-09-06 20:57:50 +00001723Error NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,
1724 bool hardware) {
1725 if (hardware)
1726 return Error("NativeProcessLinux does not support hardware breakpoints");
1727 else
1728 return SetSoftwareBreakpoint(addr, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00001729}
1730
Kate Stoneb9c1b512016-09-06 20:57:50 +00001731Error NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(
1732 size_t trap_opcode_size_hint, size_t &actual_opcode_size,
1733 const uint8_t *&trap_opcode_bytes) {
1734 // FIXME put this behind a breakpoint protocol class that can be set per
1735 // architecture. Need MIPS support here.
1736 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};
1737 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1738 // linux kernel does otherwise.
1739 static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1740 static const uint8_t g_i386_opcode[] = {0xCC};
1741 static const uint8_t g_mips64_opcode[] = {0x00, 0x00, 0x00, 0x0d};
1742 static const uint8_t g_mips64el_opcode[] = {0x0d, 0x00, 0x00, 0x00};
1743 static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
1744 static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
Todd Fialaaf245d12014-06-30 21:05:18 +00001745
Kate Stoneb9c1b512016-09-06 20:57:50 +00001746 switch (m_arch.GetMachine()) {
1747 case llvm::Triple::aarch64:
1748 trap_opcode_bytes = g_aarch64_opcode;
1749 actual_opcode_size = sizeof(g_aarch64_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001750 return Error();
Todd Fiala2afc5962014-08-21 16:42:31 +00001751
Kate Stoneb9c1b512016-09-06 20:57:50 +00001752 case llvm::Triple::arm:
1753 switch (trap_opcode_size_hint) {
1754 case 2:
1755 trap_opcode_bytes = g_thumb_breakpoint_opcode;
1756 actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001757 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001758 case 4:
1759 trap_opcode_bytes = g_arm_breakpoint_opcode;
1760 actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001761 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00001762 default:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001763 assert(false && "Unrecognised trap opcode size hint!");
1764 return Error("Unrecognised trap opcode size hint!");
Todd Fialaaf245d12014-06-30 21:05:18 +00001765 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001766
1767 case llvm::Triple::x86:
1768 case llvm::Triple::x86_64:
1769 trap_opcode_bytes = g_i386_opcode;
1770 actual_opcode_size = sizeof(g_i386_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001771 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001772
1773 case llvm::Triple::mips:
1774 case llvm::Triple::mips64:
1775 trap_opcode_bytes = g_mips64_opcode;
1776 actual_opcode_size = sizeof(g_mips64_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001777 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001778
1779 case llvm::Triple::mipsel:
1780 case llvm::Triple::mips64el:
1781 trap_opcode_bytes = g_mips64el_opcode;
1782 actual_opcode_size = sizeof(g_mips64el_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001783 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001784
1785 case llvm::Triple::systemz:
1786 trap_opcode_bytes = g_s390x_opcode;
1787 actual_opcode_size = sizeof(g_s390x_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001788 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001789
1790 default:
1791 assert(false && "CPU type not supported!");
1792 return Error("CPU type not supported");
1793 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001794}
1795
1796#if 0
1797ProcessMessage::CrashReason
1798NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
1799{
1800 ProcessMessage::CrashReason reason;
1801 assert(info->si_signo == SIGSEGV);
1802
1803 reason = ProcessMessage::eInvalidCrashReason;
1804
1805 switch (info->si_code)
1806 {
1807 default:
1808 assert(false && "unexpected si_code for SIGSEGV");
1809 break;
1810 case SI_KERNEL:
1811 // Linux will occasionally send spurious SI_KERNEL codes.
1812 // (this is poorly documented in sigaction)
1813 // One way to get this is via unaligned SIMD loads.
1814 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
1815 break;
1816 case SEGV_MAPERR:
1817 reason = ProcessMessage::eInvalidAddress;
1818 break;
1819 case SEGV_ACCERR:
1820 reason = ProcessMessage::ePrivilegedAddress;
1821 break;
1822 }
1823
1824 return reason;
1825}
1826#endif
1827
Todd Fialaaf245d12014-06-30 21:05:18 +00001828#if 0
1829ProcessMessage::CrashReason
1830NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
1831{
1832 ProcessMessage::CrashReason reason;
1833 assert(info->si_signo == SIGILL);
1834
1835 reason = ProcessMessage::eInvalidCrashReason;
1836
1837 switch (info->si_code)
1838 {
1839 default:
1840 assert(false && "unexpected si_code for SIGILL");
1841 break;
1842 case ILL_ILLOPC:
1843 reason = ProcessMessage::eIllegalOpcode;
1844 break;
1845 case ILL_ILLOPN:
1846 reason = ProcessMessage::eIllegalOperand;
1847 break;
1848 case ILL_ILLADR:
1849 reason = ProcessMessage::eIllegalAddressingMode;
1850 break;
1851 case ILL_ILLTRP:
1852 reason = ProcessMessage::eIllegalTrap;
1853 break;
1854 case ILL_PRVOPC:
1855 reason = ProcessMessage::ePrivilegedOpcode;
1856 break;
1857 case ILL_PRVREG:
1858 reason = ProcessMessage::ePrivilegedRegister;
1859 break;
1860 case ILL_COPROC:
1861 reason = ProcessMessage::eCoprocessorError;
1862 break;
1863 case ILL_BADSTK:
1864 reason = ProcessMessage::eInternalStackError;
1865 break;
1866 }
1867
1868 return reason;
1869}
1870#endif
1871
1872#if 0
1873ProcessMessage::CrashReason
1874NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
1875{
1876 ProcessMessage::CrashReason reason;
1877 assert(info->si_signo == SIGFPE);
1878
1879 reason = ProcessMessage::eInvalidCrashReason;
1880
1881 switch (info->si_code)
1882 {
1883 default:
1884 assert(false && "unexpected si_code for SIGFPE");
1885 break;
1886 case FPE_INTDIV:
1887 reason = ProcessMessage::eIntegerDivideByZero;
1888 break;
1889 case FPE_INTOVF:
1890 reason = ProcessMessage::eIntegerOverflow;
1891 break;
1892 case FPE_FLTDIV:
1893 reason = ProcessMessage::eFloatDivideByZero;
1894 break;
1895 case FPE_FLTOVF:
1896 reason = ProcessMessage::eFloatOverflow;
1897 break;
1898 case FPE_FLTUND:
1899 reason = ProcessMessage::eFloatUnderflow;
1900 break;
1901 case FPE_FLTRES:
1902 reason = ProcessMessage::eFloatInexactResult;
1903 break;
1904 case FPE_FLTINV:
1905 reason = ProcessMessage::eFloatInvalidOperation;
1906 break;
1907 case FPE_FLTSUB:
1908 reason = ProcessMessage::eFloatSubscriptRange;
1909 break;
1910 }
1911
1912 return reason;
1913}
1914#endif
1915
1916#if 0
1917ProcessMessage::CrashReason
1918NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
1919{
1920 ProcessMessage::CrashReason reason;
1921 assert(info->si_signo == SIGBUS);
1922
1923 reason = ProcessMessage::eInvalidCrashReason;
1924
1925 switch (info->si_code)
1926 {
1927 default:
1928 assert(false && "unexpected si_code for SIGBUS");
1929 break;
1930 case BUS_ADRALN:
1931 reason = ProcessMessage::eIllegalAlignment;
1932 break;
1933 case BUS_ADRERR:
1934 reason = ProcessMessage::eIllegalAddress;
1935 break;
1936 case BUS_OBJERR:
1937 reason = ProcessMessage::eHardwareError;
1938 break;
1939 }
1940
1941 return reason;
1942}
1943#endif
1944
Kate Stoneb9c1b512016-09-06 20:57:50 +00001945Error NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
1946 size_t &bytes_read) {
1947 if (ProcessVmReadvSupported()) {
1948 // The process_vm_readv path is about 50 times faster than ptrace api. We
1949 // want to use
1950 // this syscall if it is supported.
Pavel Labathdf7c6992015-06-17 18:38:49 +00001951
Kate Stoneb9c1b512016-09-06 20:57:50 +00001952 const ::pid_t pid = GetID();
Pavel Labathdf7c6992015-06-17 18:38:49 +00001953
Kate Stoneb9c1b512016-09-06 20:57:50 +00001954 struct iovec local_iov, remote_iov;
1955 local_iov.iov_base = buf;
1956 local_iov.iov_len = size;
1957 remote_iov.iov_base = reinterpret_cast<void *>(addr);
1958 remote_iov.iov_len = size;
Pavel Labathdf7c6992015-06-17 18:38:49 +00001959
Kate Stoneb9c1b512016-09-06 20:57:50 +00001960 bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
1961 const bool success = bytes_read == size;
Pavel Labathdf7c6992015-06-17 18:38:49 +00001962
Pavel Labatha6321a82017-01-19 15:26:04 +00001963 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1964 LLDB_LOG(log,
1965 "using process_vm_readv to read {0} bytes from inferior "
1966 "address {1:x}: {2}",
1967 size, addr, success ? "Success" : strerror(errno));
Pavel Labath19cbe962015-07-21 13:20:32 +00001968
Kate Stoneb9c1b512016-09-06 20:57:50 +00001969 if (success)
Mehdi Amini665be502016-11-11 05:07:57 +00001970 return Error();
Pavel Labatha6321a82017-01-19 15:26:04 +00001971 // else the call failed for some reason, let's retry the read using ptrace
1972 // api.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001973 }
Pavel Labath19cbe962015-07-21 13:20:32 +00001974
Kate Stoneb9c1b512016-09-06 20:57:50 +00001975 unsigned char *dst = static_cast<unsigned char *>(buf);
1976 size_t remainder;
1977 long data;
Pavel Labath19cbe962015-07-21 13:20:32 +00001978
Pavel Labatha6321a82017-01-19 15:26:04 +00001979 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1980 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
Pavel Labath19cbe962015-07-21 13:20:32 +00001981
Kate Stoneb9c1b512016-09-06 20:57:50 +00001982 for (bytes_read = 0; bytes_read < size; bytes_read += remainder) {
1983 Error error = NativeProcessLinux::PtraceWrapper(
1984 PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data);
Pavel Labatha6321a82017-01-19 15:26:04 +00001985 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001986 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001987
1988 remainder = size - bytes_read;
1989 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
1990
1991 // Copy the data into our buffer
1992 memcpy(dst, &data, remainder);
1993
Pavel Labatha6321a82017-01-19 15:26:04 +00001994 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001995 addr += k_ptrace_word_size;
1996 dst += k_ptrace_word_size;
1997 }
Mehdi Amini665be502016-11-11 05:07:57 +00001998 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00001999}
2000
Kate Stoneb9c1b512016-09-06 20:57:50 +00002001Error NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf,
2002 size_t size,
2003 size_t &bytes_read) {
2004 Error error = ReadMemory(addr, buf, size, bytes_read);
2005 if (error.Fail())
Pavel Labath19cbe962015-07-21 13:20:32 +00002006 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002007 return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00002008}
2009
Kate Stoneb9c1b512016-09-06 20:57:50 +00002010Error NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,
2011 size_t size, size_t &bytes_written) {
2012 const unsigned char *src = static_cast<const unsigned char *>(buf);
2013 size_t remainder;
2014 Error error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002015
Pavel Labatha6321a82017-01-19 15:26:04 +00002016 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
2017 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00002018
Kate Stoneb9c1b512016-09-06 20:57:50 +00002019 for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
2020 remainder = size - bytes_written;
2021 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
Chaoren Lin97ccc292015-02-03 01:51:12 +00002022
Kate Stoneb9c1b512016-09-06 20:57:50 +00002023 if (remainder == k_ptrace_word_size) {
2024 unsigned long data = 0;
2025 memcpy(&data, src, k_ptrace_word_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00002026
Pavel Labatha6321a82017-01-19 15:26:04 +00002027 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002028 error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(),
2029 (void *)addr, (void *)data);
Pavel Labatha6321a82017-01-19 15:26:04 +00002030 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00002031 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002032 } else {
2033 unsigned char buff[8];
2034 size_t bytes_read;
2035 error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
Pavel Labatha6321a82017-01-19 15:26:04 +00002036 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00002037 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002038
2039 memcpy(buff, src, remainder);
2040
2041 size_t bytes_written_rec;
2042 error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
Pavel Labatha6321a82017-01-19 15:26:04 +00002043 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00002044 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002045
Pavel Labatha6321a82017-01-19 15:26:04 +00002046 LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src,
2047 *(unsigned long *)buff);
Todd Fialaaf245d12014-06-30 21:05:18 +00002048 }
2049
Kate Stoneb9c1b512016-09-06 20:57:50 +00002050 addr += k_ptrace_word_size;
2051 src += k_ptrace_word_size;
2052 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002053 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002054}
2055
Kate Stoneb9c1b512016-09-06 20:57:50 +00002056Error NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) {
2057 return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
2058}
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002059
Kate Stoneb9c1b512016-09-06 20:57:50 +00002060Error NativeProcessLinux::GetEventMessage(lldb::tid_t tid,
2061 unsigned long *message) {
2062 return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
2063}
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002064
Kate Stoneb9c1b512016-09-06 20:57:50 +00002065Error NativeProcessLinux::Detach(lldb::tid_t tid) {
2066 if (tid == LLDB_INVALID_THREAD_ID)
Mehdi Amini665be502016-11-11 05:07:57 +00002067 return Error();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002068
Kate Stoneb9c1b512016-09-06 20:57:50 +00002069 return PtraceWrapper(PTRACE_DETACH, tid);
2070}
2071
2072bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {
2073 for (auto thread_sp : m_threads) {
2074 assert(thread_sp && "thread list should not contain NULL threads");
2075 if (thread_sp->GetID() == thread_id) {
2076 // We have this thread.
2077 return true;
Todd Fialaaf245d12014-06-30 21:05:18 +00002078 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002079 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002080
Kate Stoneb9c1b512016-09-06 20:57:50 +00002081 // We don't have this thread.
2082 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00002083}
2084
Kate Stoneb9c1b512016-09-06 20:57:50 +00002085bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002086 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2087 LLDB_LOG(log, "tid: {0})", thread_id);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002088
2089 bool found = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002090 for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
2091 if (*it && ((*it)->GetID() == thread_id)) {
2092 m_threads.erase(it);
2093 found = true;
2094 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00002095 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002096 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002097
Kate Stoneb9c1b512016-09-06 20:57:50 +00002098 SignalIfAllThreadsStopped();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002099 return found;
Todd Fialaaf245d12014-06-30 21:05:18 +00002100}
2101
Kate Stoneb9c1b512016-09-06 20:57:50 +00002102NativeThreadLinuxSP NativeProcessLinux::AddThread(lldb::tid_t thread_id) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002103 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
2104 LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
Todd Fialaaf245d12014-06-30 21:05:18 +00002105
Kate Stoneb9c1b512016-09-06 20:57:50 +00002106 assert(!HasThreadNoLock(thread_id) &&
2107 "attempted to add a thread by id that already exists");
Todd Fialaaf245d12014-06-30 21:05:18 +00002108
Kate Stoneb9c1b512016-09-06 20:57:50 +00002109 // If this is the first thread, save it as the current thread
2110 if (m_threads.empty())
2111 SetCurrentThreadID(thread_id);
Todd Fialaaf245d12014-06-30 21:05:18 +00002112
Kate Stoneb9c1b512016-09-06 20:57:50 +00002113 auto thread_sp = std::make_shared<NativeThreadLinux>(this, thread_id);
2114 m_threads.push_back(thread_sp);
2115 return thread_sp;
2116}
Todd Fialaaf245d12014-06-30 21:05:18 +00002117
Kate Stoneb9c1b512016-09-06 20:57:50 +00002118Error NativeProcessLinux::FixupBreakpointPCAsNeeded(NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002119 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_BREAKPOINTS));
Todd Fialaaf245d12014-06-30 21:05:18 +00002120
Kate Stoneb9c1b512016-09-06 20:57:50 +00002121 Error error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002122
Kate Stoneb9c1b512016-09-06 20:57:50 +00002123 // Find out the size of a breakpoint (might depend on where we are in the
2124 // code).
2125 NativeRegisterContextSP context_sp = thread.GetRegisterContext();
2126 if (!context_sp) {
2127 error.SetErrorString("cannot get a NativeRegisterContext for the thread");
Pavel Labatha6321a82017-01-19 15:26:04 +00002128 LLDB_LOG(log, "failed: {0}", error);
Todd Fialaaf245d12014-06-30 21:05:18 +00002129 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002130 }
Chaoren Linfa03ad22015-02-03 01:50:42 +00002131
Kate Stoneb9c1b512016-09-06 20:57:50 +00002132 uint32_t breakpoint_size = 0;
2133 error = GetSoftwareBreakpointPCOffset(breakpoint_size);
2134 if (error.Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002135 LLDB_LOG(log, "GetBreakpointSize() failed: {0}", error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002136 return error;
Pavel Labatha6321a82017-01-19 15:26:04 +00002137 } else
2138 LLDB_LOG(log, "breakpoint size: {0}", breakpoint_size);
Pavel Labathc0765592015-05-06 10:46:34 +00002139
Kate Stoneb9c1b512016-09-06 20:57:50 +00002140 // First try probing for a breakpoint at a software breakpoint location: PC -
2141 // breakpoint size.
2142 const lldb::addr_t initial_pc_addr =
2143 context_sp->GetPCfromBreakpointLocation();
2144 lldb::addr_t breakpoint_addr = initial_pc_addr;
2145 if (breakpoint_size > 0) {
2146 // Do not allow breakpoint probe to wrap around.
2147 if (breakpoint_addr >= breakpoint_size)
2148 breakpoint_addr -= breakpoint_size;
2149 }
2150
2151 // Check if we stopped because of a breakpoint.
2152 NativeBreakpointSP breakpoint_sp;
2153 error = m_breakpoint_list.GetBreakpoint(breakpoint_addr, breakpoint_sp);
2154 if (!error.Success() || !breakpoint_sp) {
2155 // We didn't find one at a software probe location. Nothing to do.
Pavel Labatha6321a82017-01-19 15:26:04 +00002156 LLDB_LOG(log,
2157 "pid {0} no lldb breakpoint found at current pc with "
2158 "adjustment: {1}",
2159 GetID(), breakpoint_addr);
Mehdi Amini665be502016-11-11 05:07:57 +00002160 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002161 }
2162
2163 // If the breakpoint is not a software breakpoint, nothing to do.
2164 if (!breakpoint_sp->IsSoftwareBreakpoint()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002165 LLDB_LOG(
2166 log,
2167 "pid {0} breakpoint found at {1:x}, not software, nothing to adjust",
2168 GetID(), breakpoint_addr);
Mehdi Amini665be502016-11-11 05:07:57 +00002169 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002170 }
2171
2172 //
2173 // We have a software breakpoint and need to adjust the PC.
2174 //
2175
2176 // Sanity check.
2177 if (breakpoint_size == 0) {
2178 // Nothing to do! How did we get here?
Pavel Labatha6321a82017-01-19 15:26:04 +00002179 LLDB_LOG(log,
2180 "pid {0} breakpoint found at {1:x}, it is software, but the "
2181 "size is zero, nothing to do (unexpected)",
2182 GetID(), breakpoint_addr);
Mehdi Amini665be502016-11-11 05:07:57 +00002183 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002184 }
2185
2186 // Change the program counter.
Pavel Labatha6321a82017-01-19 15:26:04 +00002187 LLDB_LOG(log, "pid {0} tid {1}: changing PC from {2:x} to {3:x}", GetID(),
2188 thread.GetID(), initial_pc_addr, breakpoint_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002189
2190 error = context_sp->SetPC(breakpoint_addr);
2191 if (error.Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002192 LLDB_LOG(log, "pid {0} tid {1}: failed to set PC: {2}", GetID(),
2193 thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002194 return error;
2195 }
2196
2197 return error;
2198}
2199
2200Error NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,
2201 FileSpec &file_spec) {
Tamas Berghammera6f57952017-01-03 16:29:43 +00002202 Error error = PopulateMemoryRegionCache();
2203 if (error.Fail())
2204 return error;
2205
Kate Stoneb9c1b512016-09-06 20:57:50 +00002206 FileSpec module_file_spec(module_path, true);
2207
Kate Stoneb9c1b512016-09-06 20:57:50 +00002208 file_spec.Clear();
Tamas Berghammera6f57952017-01-03 16:29:43 +00002209 for (const auto &it : m_mem_region_cache) {
2210 if (it.second.GetFilename() == module_file_spec.GetFilename()) {
2211 file_spec = it.second;
2212 return Error();
2213 }
2214 }
2215 return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
2216 module_file_spec.GetFilename().AsCString(), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002217}
2218
2219Error NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
2220 lldb::addr_t &load_addr) {
2221 load_addr = LLDB_INVALID_ADDRESS;
Tamas Berghammera6f57952017-01-03 16:29:43 +00002222 Error error = PopulateMemoryRegionCache();
2223 if (error.Fail())
2224 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002225
Tamas Berghammera6f57952017-01-03 16:29:43 +00002226 FileSpec file(file_name, false);
2227 for (const auto &it : m_mem_region_cache) {
2228 if (it.second == file) {
2229 load_addr = it.first.GetRange().GetRangeBase();
2230 return Error();
2231 }
2232 }
2233 return Error("No load address found for specified file.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002234}
2235
2236NativeThreadLinuxSP NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {
2237 return std::static_pointer_cast<NativeThreadLinux>(
2238 NativeProcessProtocol::GetThreadByID(tid));
2239}
2240
2241Error NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,
2242 lldb::StateType state, int signo) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002243 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2244 LLDB_LOG(log, "tid: {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002245
2246 // Before we do the resume below, first check if we have a pending
2247 // stop notification that is currently waiting for
2248 // all threads to stop. This is potentially a buggy situation since
2249 // we're ostensibly waiting for threads to stop before we send out the
2250 // pending notification, and here we are resuming one before we send
2251 // out the pending stop notification.
Pavel Labatha6321a82017-01-19 15:26:04 +00002252 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
2253 LLDB_LOG(log,
2254 "about to resume tid {0} per explicit request but we have a "
2255 "pending stop notification (tid {1}) that is actively "
2256 "waiting for this thread to stop. Valid sequence of events?",
2257 thread.GetID(), m_pending_notification_tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002258 }
2259
2260 // Request a resume. We expect this to be synchronous and the system
2261 // to reflect it is running after this completes.
2262 switch (state) {
2263 case eStateRunning: {
2264 const auto resume_result = thread.Resume(signo);
2265 if (resume_result.Success())
2266 SetState(eStateRunning, true);
2267 return resume_result;
2268 }
2269 case eStateStepping: {
2270 const auto step_result = thread.SingleStep(signo);
2271 if (step_result.Success())
2272 SetState(eStateRunning, true);
2273 return step_result;
2274 }
2275 default:
Pavel Labath8198db32017-01-24 11:48:25 +00002276 LLDB_LOG(log, "Unhandled state {0}.", state);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002277 llvm_unreachable("Unhandled state for resume");
2278 }
Pavel Labathc0765592015-05-06 10:46:34 +00002279}
2280
2281//===----------------------------------------------------------------------===//
2282
Kate Stoneb9c1b512016-09-06 20:57:50 +00002283void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002284 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2285 LLDB_LOG(log, "about to process event: (triggering_tid: {0})",
2286 triggering_tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002287
2288 m_pending_notification_tid = triggering_tid;
2289
2290 // Request a stop for all the thread stops that need to be stopped
2291 // and are not already known to be stopped.
2292 for (const auto &thread_sp : m_threads) {
2293 if (StateIsRunningState(thread_sp->GetState()))
2294 static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
2295 }
2296
2297 SignalIfAllThreadsStopped();
Pavel Labatha6321a82017-01-19 15:26:04 +00002298 LLDB_LOG(log, "event processing done");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002299}
2300
2301void NativeProcessLinux::SignalIfAllThreadsStopped() {
2302 if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
2303 return; // No pending notification. Nothing to do.
2304
2305 for (const auto &thread_sp : m_threads) {
2306 if (StateIsRunningState(thread_sp->GetState()))
2307 return; // Some threads are still running. Don't signal yet.
2308 }
2309
2310 // We have a pending notification and all threads have stopped.
2311 Log *log(
2312 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
2313
2314 // Clear any temporary breakpoints we used to implement software single
2315 // stepping.
2316 for (const auto &thread_info : m_threads_stepping_with_breakpoint) {
2317 Error error = RemoveBreakpoint(thread_info.second);
2318 if (error.Fail())
Pavel Labatha6321a82017-01-19 15:26:04 +00002319 LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}",
2320 thread_info.first, error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002321 }
2322 m_threads_stepping_with_breakpoint.clear();
2323
2324 // Notify the delegate about the stop
2325 SetCurrentThreadID(m_pending_notification_tid);
2326 SetState(StateType::eStateStopped, true);
2327 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
2328}
2329
2330void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002331 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2332 LLDB_LOG(log, "tid: {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002333
2334 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID &&
2335 StateIsRunningState(thread.GetState())) {
2336 // We will need to wait for this new thread to stop as well before firing
2337 // the
2338 // notification.
2339 thread.RequestStop();
2340 }
2341}
2342
2343void NativeProcessLinux::SigchldHandler() {
Pavel Labatha6321a82017-01-19 15:26:04 +00002344 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002345 // Process all pending waitpid notifications.
2346 while (true) {
2347 int status = -1;
2348 ::pid_t wait_pid = waitpid(-1, &status, __WALL | __WNOTHREAD | WNOHANG);
2349
2350 if (wait_pid == 0)
2351 break; // We are done.
2352
2353 if (wait_pid == -1) {
2354 if (errno == EINTR)
2355 continue;
2356
2357 Error error(errno, eErrorTypePOSIX);
Pavel Labatha6321a82017-01-19 15:26:04 +00002358 LLDB_LOG(log, "waitpid (-1, &status, _) failed: {0}", error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002359 break;
Pavel Labathc0765592015-05-06 10:46:34 +00002360 }
2361
Kate Stoneb9c1b512016-09-06 20:57:50 +00002362 bool exited = false;
2363 int signal = 0;
2364 int exit_status = 0;
2365 const char *status_cstr = nullptr;
2366 if (WIFSTOPPED(status)) {
2367 signal = WSTOPSIG(status);
2368 status_cstr = "STOPPED";
2369 } else if (WIFEXITED(status)) {
2370 exit_status = WEXITSTATUS(status);
2371 status_cstr = "EXITED";
2372 exited = true;
2373 } else if (WIFSIGNALED(status)) {
2374 signal = WTERMSIG(status);
2375 status_cstr = "SIGNALED";
2376 if (wait_pid == static_cast<::pid_t>(GetID())) {
2377 exited = true;
2378 exit_status = -1;
2379 }
2380 } else
2381 status_cstr = "(\?\?\?)";
Pavel Labathc0765592015-05-06 10:46:34 +00002382
Pavel Labatha6321a82017-01-19 15:26:04 +00002383 LLDB_LOG(log,
2384 "waitpid (-1, &status, _) => pid = {0}, status = {1:x} "
2385 "({2}), signal = {3}, exit_state = {4}",
2386 wait_pid, status, status_cstr, signal, exit_status);
Pavel Labathc0765592015-05-06 10:46:34 +00002387
Kate Stoneb9c1b512016-09-06 20:57:50 +00002388 MonitorCallback(wait_pid, exited, signal, exit_status);
2389 }
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002390}
2391
2392// Wrapper for ptrace to catch errors and log calls.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002393// Note that ptrace sets errno on error because -1 can be a valid result (i.e.
2394// for PTRACE_PEEK*)
2395Error NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
2396 void *data, size_t data_size,
2397 long *result) {
2398 Error error;
2399 long int ret;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002400
Kate Stoneb9c1b512016-09-06 20:57:50 +00002401 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002402
Kate Stoneb9c1b512016-09-06 20:57:50 +00002403 PtraceDisplayBytes(req, data, data_size);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002404
Kate Stoneb9c1b512016-09-06 20:57:50 +00002405 errno = 0;
2406 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
2407 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2408 *(unsigned int *)addr, data);
2409 else
2410 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2411 addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002412
Kate Stoneb9c1b512016-09-06 20:57:50 +00002413 if (ret == -1)
2414 error.SetErrorToErrno();
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002415
Kate Stoneb9c1b512016-09-06 20:57:50 +00002416 if (result)
2417 *result = ret;
Pavel Labath4a9babb2015-06-30 17:04:49 +00002418
Pavel Labatha6321a82017-01-19 15:26:04 +00002419 LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4}, {5})={6:x}", req, pid, addr,
2420 data, data_size, ret);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002421
Kate Stoneb9c1b512016-09-06 20:57:50 +00002422 PtraceDisplayBytes(req, data, data_size);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002423
Pavel Labatha6321a82017-01-19 15:26:04 +00002424 if (error.Fail())
2425 LLDB_LOG(log, "ptrace() failed: {0}", error);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002426
Kate Stoneb9c1b512016-09-06 20:57:50 +00002427 return error;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002428}