blob: 32e6765b4a1dce3f63f766acc55612d8c83f57ec [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"
Todd Fialaaf245d12014-06-30 21:05:18 +000027#include "lldb/Core/Error.h"
Oleksiy Vyalov6edef202014-11-17 22:16:42 +000028#include "lldb/Core/ModuleSpec.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000029#include "lldb/Core/RegisterValue.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000030#include "lldb/Core/State.h"
31#include "lldb/Host/Host.h"
Pavel Labath5ad891f2016-07-21 14:54:03 +000032#include "lldb/Host/HostProcess.h"
Zachary Turner39de3112014-09-09 20:54:56 +000033#include "lldb/Host/ThreadLauncher.h"
Pavel Labath2a86b552016-06-14 17:30:52 +000034#include "lldb/Host/common/NativeBreakpoint.h"
35#include "lldb/Host/common/NativeRegisterContext.h"
Pavel Labath5ad891f2016-07-21 14:54:03 +000036#include "lldb/Host/linux/ProcessLauncherLinux.h"
Pavel Labath2a86b552016-06-14 17:30:52 +000037#include "lldb/Symbol/ObjectFile.h"
Zachary Turner90aff472015-03-03 23:36:51 +000038#include "lldb/Target/Process.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000039#include "lldb/Target/ProcessLaunchInfo.h"
Pavel Labath5b981ab2015-05-29 12:53:54 +000040#include "lldb/Target/Target.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;
78 static std::once_flag flag;
Pavel Labathdf7c6992015-06-17 18:38:49 +000079
Kate Stoneb9c1b512016-09-06 20:57:50 +000080 std::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 =
335 ProcessLauncherLinux().LaunchProcess(launch_info, error).GetProcessId();
336 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",
570 StateAsCString(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",
1036 GetID(), thread.GetID(), StateAsCString(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}",
1266 StateAsCString(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(),
1396 StateAsCString(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();
1535
1536 // If the target address comes before this entry, indicate distance to next
1537 // region.
1538 if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1539 range_info.GetRange().SetRangeBase(load_addr);
1540 range_info.GetRange().SetByteSize(
1541 proc_entry_info.GetRange().GetRangeBase() - load_addr);
1542 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1543 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1544 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1545 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1546
1547 return error;
1548 } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1549 // The target address is within the memory region we're processing here.
1550 range_info = proc_entry_info;
1551 return error;
1552 }
1553
1554 // The target memory address comes somewhere after the region we just
1555 // parsed.
1556 }
1557
1558 // If we made it here, we didn't find an entry that contained the given
1559 // address. Return the
1560 // load_addr as start and the amount of bytes betwwen load address and the end
1561 // of the memory as
1562 // size.
1563 range_info.GetRange().SetRangeBase(load_addr);
1564 range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
1565 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1566 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1567 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1568 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1569 return error;
1570}
1571
Tamas Berghammera6f57952017-01-03 16:29:43 +00001572Error NativeProcessLinux::PopulateMemoryRegionCache() {
Pavel Labatha6321a82017-01-19 15:26:04 +00001573 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Tamas Berghammera6f57952017-01-03 16:29:43 +00001574
1575 // If our cache is empty, pull the latest. There should always be at least
1576 // one memory region if memory region handling is supported.
1577 if (!m_mem_region_cache.empty()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001578 LLDB_LOG(log, "reusing {0} cached memory region entries",
1579 m_mem_region_cache.size());
Tamas Berghammera6f57952017-01-03 16:29:43 +00001580 return Error();
1581 }
1582
1583 Error error = ProcFileReader::ProcessLineByLine(
1584 GetID(), "maps", [&](const std::string &line) -> bool {
1585 MemoryRegionInfo info;
1586 const Error parse_error =
1587 ParseMemoryRegionInfoFromProcMapsLine(line, info);
1588 if (parse_error.Success()) {
1589 m_mem_region_cache.emplace_back(
1590 info, FileSpec(info.GetName().GetCString(), true));
1591 return true;
1592 } else {
Pavel Labatha6321a82017-01-19 15:26:04 +00001593 LLDB_LOG(log, "failed to parse proc maps line '{0}': {1}", line,
1594 parse_error);
Tamas Berghammera6f57952017-01-03 16:29:43 +00001595 return false;
1596 }
1597 });
1598
1599 // If we had an error, we'll mark unsupported.
1600 if (error.Fail()) {
1601 m_supports_mem_region = LazyBool::eLazyBoolNo;
1602 return error;
1603 } else if (m_mem_region_cache.empty()) {
1604 // No entries after attempting to read them. This shouldn't happen if
1605 // /proc/{pid}/maps is supported. Assume we don't support map entries
1606 // via procfs.
Pavel Labatha6321a82017-01-19 15:26:04 +00001607 LLDB_LOG(log,
1608 "failed to find any procfs maps entries, assuming no support "
1609 "for memory region metadata retrieval");
Tamas Berghammera6f57952017-01-03 16:29:43 +00001610 m_supports_mem_region = LazyBool::eLazyBoolNo;
1611 error.SetErrorString("not supported");
1612 return error;
1613 }
1614
Pavel Labatha6321a82017-01-19 15:26:04 +00001615 LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps",
1616 m_mem_region_cache.size(), GetID());
Tamas Berghammera6f57952017-01-03 16:29:43 +00001617
1618 // We support memory retrieval, remember that.
1619 m_supports_mem_region = LazyBool::eLazyBoolYes;
1620 return Error();
1621}
1622
Kate Stoneb9c1b512016-09-06 20:57:50 +00001623void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
Pavel Labatha6321a82017-01-19 15:26:04 +00001624 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1625 LLDB_LOG(log, "newBumpId={0}", newBumpId);
1626 LLDB_LOG(log, "clearing {0} entries from memory region cache",
1627 m_mem_region_cache.size());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001628 m_mem_region_cache.clear();
1629}
1630
1631Error NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions,
1632 lldb::addr_t &addr) {
1633// FIXME implementing this requires the equivalent of
1634// InferiorCallPOSIX::InferiorCallMmap, which depends on
1635// functional ThreadPlans working with Native*Protocol.
1636#if 1
1637 return Error("not implemented yet");
1638#else
1639 addr = LLDB_INVALID_ADDRESS;
1640
1641 unsigned prot = 0;
1642 if (permissions & lldb::ePermissionsReadable)
1643 prot |= eMmapProtRead;
1644 if (permissions & lldb::ePermissionsWritable)
1645 prot |= eMmapProtWrite;
1646 if (permissions & lldb::ePermissionsExecutable)
1647 prot |= eMmapProtExec;
1648
1649 // TODO implement this directly in NativeProcessLinux
1650 // (and lift to NativeProcessPOSIX if/when that class is
1651 // refactored out).
1652 if (InferiorCallMmap(this, addr, 0, size, prot,
1653 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
1654 m_addr_to_mmap_size[addr] = size;
Mehdi Amini665be502016-11-11 05:07:57 +00001655 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001656 } else {
1657 addr = LLDB_INVALID_ADDRESS;
1658 return Error("unable to allocate %" PRIu64
1659 " bytes of memory with permissions %s",
1660 size, GetPermissionsAsCString(permissions));
1661 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001662#endif
1663}
1664
Kate Stoneb9c1b512016-09-06 20:57:50 +00001665Error NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {
1666 // FIXME see comments in AllocateMemory - required lower-level
1667 // bits not in place yet (ThreadPlans)
1668 return Error("not implemented");
Todd Fialaaf245d12014-06-30 21:05:18 +00001669}
1670
Kate Stoneb9c1b512016-09-06 20:57:50 +00001671lldb::addr_t NativeProcessLinux::GetSharedLibraryInfoAddress() {
1672 // punt on this for now
1673 return LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00001674}
1675
Kate Stoneb9c1b512016-09-06 20:57:50 +00001676size_t NativeProcessLinux::UpdateThreads() {
1677 // The NativeProcessLinux monitoring threads are always up to date
1678 // with respect to thread state and they keep the thread list
1679 // populated properly. All this method needs to do is return the
1680 // thread count.
1681 return m_threads.size();
Todd Fialaaf245d12014-06-30 21:05:18 +00001682}
1683
Kate Stoneb9c1b512016-09-06 20:57:50 +00001684bool NativeProcessLinux::GetArchitecture(ArchSpec &arch) const {
1685 arch = m_arch;
1686 return true;
Todd Fialaaf245d12014-06-30 21:05:18 +00001687}
1688
Kate Stoneb9c1b512016-09-06 20:57:50 +00001689Error NativeProcessLinux::GetSoftwareBreakpointPCOffset(
1690 uint32_t &actual_opcode_size) {
1691 // FIXME put this behind a breakpoint protocol class that can be
1692 // set per architecture. Need ARM, MIPS support here.
1693 static const uint8_t g_i386_opcode[] = {0xCC};
1694 static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
Todd Fialaaf245d12014-06-30 21:05:18 +00001695
Kate Stoneb9c1b512016-09-06 20:57:50 +00001696 switch (m_arch.GetMachine()) {
1697 case llvm::Triple::x86:
1698 case llvm::Triple::x86_64:
1699 actual_opcode_size = static_cast<uint32_t>(sizeof(g_i386_opcode));
Mehdi Amini665be502016-11-11 05:07:57 +00001700 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00001701
Kate Stoneb9c1b512016-09-06 20:57:50 +00001702 case llvm::Triple::systemz:
1703 actual_opcode_size = static_cast<uint32_t>(sizeof(g_s390x_opcode));
Mehdi Amini665be502016-11-11 05:07:57 +00001704 return Error();
Ulrich Weigandbb00d0b2016-04-14 14:28:34 +00001705
Kate Stoneb9c1b512016-09-06 20:57:50 +00001706 case llvm::Triple::arm:
1707 case llvm::Triple::aarch64:
1708 case llvm::Triple::mips64:
1709 case llvm::Triple::mips64el:
1710 case llvm::Triple::mips:
1711 case llvm::Triple::mipsel:
1712 // On these architectures the PC don't get updated for breakpoint hits
1713 actual_opcode_size = 0;
Mehdi Amini665be502016-11-11 05:07:57 +00001714 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001715
1716 default:
1717 assert(false && "CPU type not supported!");
1718 return Error("CPU type not supported");
1719 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001720}
1721
Kate Stoneb9c1b512016-09-06 20:57:50 +00001722Error NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,
1723 bool hardware) {
1724 if (hardware)
1725 return Error("NativeProcessLinux does not support hardware breakpoints");
1726 else
1727 return SetSoftwareBreakpoint(addr, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00001728}
1729
Kate Stoneb9c1b512016-09-06 20:57:50 +00001730Error NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(
1731 size_t trap_opcode_size_hint, size_t &actual_opcode_size,
1732 const uint8_t *&trap_opcode_bytes) {
1733 // FIXME put this behind a breakpoint protocol class that can be set per
1734 // architecture. Need MIPS support here.
1735 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};
1736 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1737 // linux kernel does otherwise.
1738 static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1739 static const uint8_t g_i386_opcode[] = {0xCC};
1740 static const uint8_t g_mips64_opcode[] = {0x00, 0x00, 0x00, 0x0d};
1741 static const uint8_t g_mips64el_opcode[] = {0x0d, 0x00, 0x00, 0x00};
1742 static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
1743 static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
Todd Fialaaf245d12014-06-30 21:05:18 +00001744
Kate Stoneb9c1b512016-09-06 20:57:50 +00001745 switch (m_arch.GetMachine()) {
1746 case llvm::Triple::aarch64:
1747 trap_opcode_bytes = g_aarch64_opcode;
1748 actual_opcode_size = sizeof(g_aarch64_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001749 return Error();
Todd Fiala2afc5962014-08-21 16:42:31 +00001750
Kate Stoneb9c1b512016-09-06 20:57:50 +00001751 case llvm::Triple::arm:
1752 switch (trap_opcode_size_hint) {
1753 case 2:
1754 trap_opcode_bytes = g_thumb_breakpoint_opcode;
1755 actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001756 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001757 case 4:
1758 trap_opcode_bytes = g_arm_breakpoint_opcode;
1759 actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001760 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00001761 default:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001762 assert(false && "Unrecognised trap opcode size hint!");
1763 return Error("Unrecognised trap opcode size hint!");
Todd Fialaaf245d12014-06-30 21:05:18 +00001764 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001765
1766 case llvm::Triple::x86:
1767 case llvm::Triple::x86_64:
1768 trap_opcode_bytes = g_i386_opcode;
1769 actual_opcode_size = sizeof(g_i386_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001770 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001771
1772 case llvm::Triple::mips:
1773 case llvm::Triple::mips64:
1774 trap_opcode_bytes = g_mips64_opcode;
1775 actual_opcode_size = sizeof(g_mips64_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001776 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001777
1778 case llvm::Triple::mipsel:
1779 case llvm::Triple::mips64el:
1780 trap_opcode_bytes = g_mips64el_opcode;
1781 actual_opcode_size = sizeof(g_mips64el_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001782 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001783
1784 case llvm::Triple::systemz:
1785 trap_opcode_bytes = g_s390x_opcode;
1786 actual_opcode_size = sizeof(g_s390x_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001787 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001788
1789 default:
1790 assert(false && "CPU type not supported!");
1791 return Error("CPU type not supported");
1792 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001793}
1794
1795#if 0
1796ProcessMessage::CrashReason
1797NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
1798{
1799 ProcessMessage::CrashReason reason;
1800 assert(info->si_signo == SIGSEGV);
1801
1802 reason = ProcessMessage::eInvalidCrashReason;
1803
1804 switch (info->si_code)
1805 {
1806 default:
1807 assert(false && "unexpected si_code for SIGSEGV");
1808 break;
1809 case SI_KERNEL:
1810 // Linux will occasionally send spurious SI_KERNEL codes.
1811 // (this is poorly documented in sigaction)
1812 // One way to get this is via unaligned SIMD loads.
1813 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
1814 break;
1815 case SEGV_MAPERR:
1816 reason = ProcessMessage::eInvalidAddress;
1817 break;
1818 case SEGV_ACCERR:
1819 reason = ProcessMessage::ePrivilegedAddress;
1820 break;
1821 }
1822
1823 return reason;
1824}
1825#endif
1826
Todd Fialaaf245d12014-06-30 21:05:18 +00001827#if 0
1828ProcessMessage::CrashReason
1829NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
1830{
1831 ProcessMessage::CrashReason reason;
1832 assert(info->si_signo == SIGILL);
1833
1834 reason = ProcessMessage::eInvalidCrashReason;
1835
1836 switch (info->si_code)
1837 {
1838 default:
1839 assert(false && "unexpected si_code for SIGILL");
1840 break;
1841 case ILL_ILLOPC:
1842 reason = ProcessMessage::eIllegalOpcode;
1843 break;
1844 case ILL_ILLOPN:
1845 reason = ProcessMessage::eIllegalOperand;
1846 break;
1847 case ILL_ILLADR:
1848 reason = ProcessMessage::eIllegalAddressingMode;
1849 break;
1850 case ILL_ILLTRP:
1851 reason = ProcessMessage::eIllegalTrap;
1852 break;
1853 case ILL_PRVOPC:
1854 reason = ProcessMessage::ePrivilegedOpcode;
1855 break;
1856 case ILL_PRVREG:
1857 reason = ProcessMessage::ePrivilegedRegister;
1858 break;
1859 case ILL_COPROC:
1860 reason = ProcessMessage::eCoprocessorError;
1861 break;
1862 case ILL_BADSTK:
1863 reason = ProcessMessage::eInternalStackError;
1864 break;
1865 }
1866
1867 return reason;
1868}
1869#endif
1870
1871#if 0
1872ProcessMessage::CrashReason
1873NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
1874{
1875 ProcessMessage::CrashReason reason;
1876 assert(info->si_signo == SIGFPE);
1877
1878 reason = ProcessMessage::eInvalidCrashReason;
1879
1880 switch (info->si_code)
1881 {
1882 default:
1883 assert(false && "unexpected si_code for SIGFPE");
1884 break;
1885 case FPE_INTDIV:
1886 reason = ProcessMessage::eIntegerDivideByZero;
1887 break;
1888 case FPE_INTOVF:
1889 reason = ProcessMessage::eIntegerOverflow;
1890 break;
1891 case FPE_FLTDIV:
1892 reason = ProcessMessage::eFloatDivideByZero;
1893 break;
1894 case FPE_FLTOVF:
1895 reason = ProcessMessage::eFloatOverflow;
1896 break;
1897 case FPE_FLTUND:
1898 reason = ProcessMessage::eFloatUnderflow;
1899 break;
1900 case FPE_FLTRES:
1901 reason = ProcessMessage::eFloatInexactResult;
1902 break;
1903 case FPE_FLTINV:
1904 reason = ProcessMessage::eFloatInvalidOperation;
1905 break;
1906 case FPE_FLTSUB:
1907 reason = ProcessMessage::eFloatSubscriptRange;
1908 break;
1909 }
1910
1911 return reason;
1912}
1913#endif
1914
1915#if 0
1916ProcessMessage::CrashReason
1917NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
1918{
1919 ProcessMessage::CrashReason reason;
1920 assert(info->si_signo == SIGBUS);
1921
1922 reason = ProcessMessage::eInvalidCrashReason;
1923
1924 switch (info->si_code)
1925 {
1926 default:
1927 assert(false && "unexpected si_code for SIGBUS");
1928 break;
1929 case BUS_ADRALN:
1930 reason = ProcessMessage::eIllegalAlignment;
1931 break;
1932 case BUS_ADRERR:
1933 reason = ProcessMessage::eIllegalAddress;
1934 break;
1935 case BUS_OBJERR:
1936 reason = ProcessMessage::eHardwareError;
1937 break;
1938 }
1939
1940 return reason;
1941}
1942#endif
1943
Kate Stoneb9c1b512016-09-06 20:57:50 +00001944Error NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
1945 size_t &bytes_read) {
1946 if (ProcessVmReadvSupported()) {
1947 // The process_vm_readv path is about 50 times faster than ptrace api. We
1948 // want to use
1949 // this syscall if it is supported.
Pavel Labathdf7c6992015-06-17 18:38:49 +00001950
Kate Stoneb9c1b512016-09-06 20:57:50 +00001951 const ::pid_t pid = GetID();
Pavel Labathdf7c6992015-06-17 18:38:49 +00001952
Kate Stoneb9c1b512016-09-06 20:57:50 +00001953 struct iovec local_iov, remote_iov;
1954 local_iov.iov_base = buf;
1955 local_iov.iov_len = size;
1956 remote_iov.iov_base = reinterpret_cast<void *>(addr);
1957 remote_iov.iov_len = size;
Pavel Labathdf7c6992015-06-17 18:38:49 +00001958
Kate Stoneb9c1b512016-09-06 20:57:50 +00001959 bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
1960 const bool success = bytes_read == size;
Pavel Labathdf7c6992015-06-17 18:38:49 +00001961
Pavel Labatha6321a82017-01-19 15:26:04 +00001962 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1963 LLDB_LOG(log,
1964 "using process_vm_readv to read {0} bytes from inferior "
1965 "address {1:x}: {2}",
1966 size, addr, success ? "Success" : strerror(errno));
Pavel Labath19cbe962015-07-21 13:20:32 +00001967
Kate Stoneb9c1b512016-09-06 20:57:50 +00001968 if (success)
Mehdi Amini665be502016-11-11 05:07:57 +00001969 return Error();
Pavel Labatha6321a82017-01-19 15:26:04 +00001970 // else the call failed for some reason, let's retry the read using ptrace
1971 // api.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001972 }
Pavel Labath19cbe962015-07-21 13:20:32 +00001973
Kate Stoneb9c1b512016-09-06 20:57:50 +00001974 unsigned char *dst = static_cast<unsigned char *>(buf);
1975 size_t remainder;
1976 long data;
Pavel Labath19cbe962015-07-21 13:20:32 +00001977
Pavel Labatha6321a82017-01-19 15:26:04 +00001978 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
1979 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
Pavel Labath19cbe962015-07-21 13:20:32 +00001980
Kate Stoneb9c1b512016-09-06 20:57:50 +00001981 for (bytes_read = 0; bytes_read < size; bytes_read += remainder) {
1982 Error error = NativeProcessLinux::PtraceWrapper(
1983 PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data);
Pavel Labatha6321a82017-01-19 15:26:04 +00001984 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001985 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001986
1987 remainder = size - bytes_read;
1988 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
1989
1990 // Copy the data into our buffer
1991 memcpy(dst, &data, remainder);
1992
Pavel Labatha6321a82017-01-19 15:26:04 +00001993 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001994 addr += k_ptrace_word_size;
1995 dst += k_ptrace_word_size;
1996 }
Mehdi Amini665be502016-11-11 05:07:57 +00001997 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00001998}
1999
Kate Stoneb9c1b512016-09-06 20:57:50 +00002000Error NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf,
2001 size_t size,
2002 size_t &bytes_read) {
2003 Error error = ReadMemory(addr, buf, size, bytes_read);
2004 if (error.Fail())
Pavel Labath19cbe962015-07-21 13:20:32 +00002005 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002006 return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00002007}
2008
Kate Stoneb9c1b512016-09-06 20:57:50 +00002009Error NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,
2010 size_t size, size_t &bytes_written) {
2011 const unsigned char *src = static_cast<const unsigned char *>(buf);
2012 size_t remainder;
2013 Error error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002014
Pavel Labatha6321a82017-01-19 15:26:04 +00002015 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
2016 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00002017
Kate Stoneb9c1b512016-09-06 20:57:50 +00002018 for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
2019 remainder = size - bytes_written;
2020 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
Chaoren Lin97ccc292015-02-03 01:51:12 +00002021
Kate Stoneb9c1b512016-09-06 20:57:50 +00002022 if (remainder == k_ptrace_word_size) {
2023 unsigned long data = 0;
2024 memcpy(&data, src, k_ptrace_word_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00002025
Pavel Labatha6321a82017-01-19 15:26:04 +00002026 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002027 error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(),
2028 (void *)addr, (void *)data);
Pavel Labatha6321a82017-01-19 15:26:04 +00002029 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00002030 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002031 } else {
2032 unsigned char buff[8];
2033 size_t bytes_read;
2034 error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
Pavel Labatha6321a82017-01-19 15:26:04 +00002035 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00002036 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002037
2038 memcpy(buff, src, remainder);
2039
2040 size_t bytes_written_rec;
2041 error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
Pavel Labatha6321a82017-01-19 15:26:04 +00002042 if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00002043 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002044
Pavel Labatha6321a82017-01-19 15:26:04 +00002045 LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src,
2046 *(unsigned long *)buff);
Todd Fialaaf245d12014-06-30 21:05:18 +00002047 }
2048
Kate Stoneb9c1b512016-09-06 20:57:50 +00002049 addr += k_ptrace_word_size;
2050 src += k_ptrace_word_size;
2051 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002052 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002053}
2054
Kate Stoneb9c1b512016-09-06 20:57:50 +00002055Error NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) {
2056 return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
2057}
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002058
Kate Stoneb9c1b512016-09-06 20:57:50 +00002059Error NativeProcessLinux::GetEventMessage(lldb::tid_t tid,
2060 unsigned long *message) {
2061 return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
2062}
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002063
Kate Stoneb9c1b512016-09-06 20:57:50 +00002064Error NativeProcessLinux::Detach(lldb::tid_t tid) {
2065 if (tid == LLDB_INVALID_THREAD_ID)
Mehdi Amini665be502016-11-11 05:07:57 +00002066 return Error();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002067
Kate Stoneb9c1b512016-09-06 20:57:50 +00002068 return PtraceWrapper(PTRACE_DETACH, tid);
2069}
2070
2071bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {
2072 for (auto thread_sp : m_threads) {
2073 assert(thread_sp && "thread list should not contain NULL threads");
2074 if (thread_sp->GetID() == thread_id) {
2075 // We have this thread.
2076 return true;
Todd Fialaaf245d12014-06-30 21:05:18 +00002077 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002078 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002079
Kate Stoneb9c1b512016-09-06 20:57:50 +00002080 // We don't have this thread.
2081 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00002082}
2083
Kate Stoneb9c1b512016-09-06 20:57:50 +00002084bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002085 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2086 LLDB_LOG(log, "tid: {0})", thread_id);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002087
2088 bool found = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002089 for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
2090 if (*it && ((*it)->GetID() == thread_id)) {
2091 m_threads.erase(it);
2092 found = true;
2093 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00002094 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002095 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002096
Kate Stoneb9c1b512016-09-06 20:57:50 +00002097 SignalIfAllThreadsStopped();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002098 return found;
Todd Fialaaf245d12014-06-30 21:05:18 +00002099}
2100
Kate Stoneb9c1b512016-09-06 20:57:50 +00002101NativeThreadLinuxSP NativeProcessLinux::AddThread(lldb::tid_t thread_id) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002102 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
2103 LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
Todd Fialaaf245d12014-06-30 21:05:18 +00002104
Kate Stoneb9c1b512016-09-06 20:57:50 +00002105 assert(!HasThreadNoLock(thread_id) &&
2106 "attempted to add a thread by id that already exists");
Todd Fialaaf245d12014-06-30 21:05:18 +00002107
Kate Stoneb9c1b512016-09-06 20:57:50 +00002108 // If this is the first thread, save it as the current thread
2109 if (m_threads.empty())
2110 SetCurrentThreadID(thread_id);
Todd Fialaaf245d12014-06-30 21:05:18 +00002111
Kate Stoneb9c1b512016-09-06 20:57:50 +00002112 auto thread_sp = std::make_shared<NativeThreadLinux>(this, thread_id);
2113 m_threads.push_back(thread_sp);
2114 return thread_sp;
2115}
Todd Fialaaf245d12014-06-30 21:05:18 +00002116
Kate Stoneb9c1b512016-09-06 20:57:50 +00002117Error NativeProcessLinux::FixupBreakpointPCAsNeeded(NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002118 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_BREAKPOINTS));
Todd Fialaaf245d12014-06-30 21:05:18 +00002119
Kate Stoneb9c1b512016-09-06 20:57:50 +00002120 Error error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002121
Kate Stoneb9c1b512016-09-06 20:57:50 +00002122 // Find out the size of a breakpoint (might depend on where we are in the
2123 // code).
2124 NativeRegisterContextSP context_sp = thread.GetRegisterContext();
2125 if (!context_sp) {
2126 error.SetErrorString("cannot get a NativeRegisterContext for the thread");
Pavel Labatha6321a82017-01-19 15:26:04 +00002127 LLDB_LOG(log, "failed: {0}", error);
Todd Fialaaf245d12014-06-30 21:05:18 +00002128 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002129 }
Chaoren Linfa03ad22015-02-03 01:50:42 +00002130
Kate Stoneb9c1b512016-09-06 20:57:50 +00002131 uint32_t breakpoint_size = 0;
2132 error = GetSoftwareBreakpointPCOffset(breakpoint_size);
2133 if (error.Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002134 LLDB_LOG(log, "GetBreakpointSize() failed: {0}", error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002135 return error;
Pavel Labatha6321a82017-01-19 15:26:04 +00002136 } else
2137 LLDB_LOG(log, "breakpoint size: {0}", breakpoint_size);
Pavel Labathc0765592015-05-06 10:46:34 +00002138
Kate Stoneb9c1b512016-09-06 20:57:50 +00002139 // First try probing for a breakpoint at a software breakpoint location: PC -
2140 // breakpoint size.
2141 const lldb::addr_t initial_pc_addr =
2142 context_sp->GetPCfromBreakpointLocation();
2143 lldb::addr_t breakpoint_addr = initial_pc_addr;
2144 if (breakpoint_size > 0) {
2145 // Do not allow breakpoint probe to wrap around.
2146 if (breakpoint_addr >= breakpoint_size)
2147 breakpoint_addr -= breakpoint_size;
2148 }
2149
2150 // Check if we stopped because of a breakpoint.
2151 NativeBreakpointSP breakpoint_sp;
2152 error = m_breakpoint_list.GetBreakpoint(breakpoint_addr, breakpoint_sp);
2153 if (!error.Success() || !breakpoint_sp) {
2154 // We didn't find one at a software probe location. Nothing to do.
Pavel Labatha6321a82017-01-19 15:26:04 +00002155 LLDB_LOG(log,
2156 "pid {0} no lldb breakpoint found at current pc with "
2157 "adjustment: {1}",
2158 GetID(), breakpoint_addr);
Mehdi Amini665be502016-11-11 05:07:57 +00002159 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002160 }
2161
2162 // If the breakpoint is not a software breakpoint, nothing to do.
2163 if (!breakpoint_sp->IsSoftwareBreakpoint()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002164 LLDB_LOG(
2165 log,
2166 "pid {0} breakpoint found at {1:x}, not software, nothing to adjust",
2167 GetID(), breakpoint_addr);
Mehdi Amini665be502016-11-11 05:07:57 +00002168 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002169 }
2170
2171 //
2172 // We have a software breakpoint and need to adjust the PC.
2173 //
2174
2175 // Sanity check.
2176 if (breakpoint_size == 0) {
2177 // Nothing to do! How did we get here?
Pavel Labatha6321a82017-01-19 15:26:04 +00002178 LLDB_LOG(log,
2179 "pid {0} breakpoint found at {1:x}, it is software, but the "
2180 "size is zero, nothing to do (unexpected)",
2181 GetID(), breakpoint_addr);
Mehdi Amini665be502016-11-11 05:07:57 +00002182 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002183 }
2184
2185 // Change the program counter.
Pavel Labatha6321a82017-01-19 15:26:04 +00002186 LLDB_LOG(log, "pid {0} tid {1}: changing PC from {2:x} to {3:x}", GetID(),
2187 thread.GetID(), initial_pc_addr, breakpoint_addr);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002188
2189 error = context_sp->SetPC(breakpoint_addr);
2190 if (error.Fail()) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002191 LLDB_LOG(log, "pid {0} tid {1}: failed to set PC: {2}", GetID(),
2192 thread.GetID(), error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002193 return error;
2194 }
2195
2196 return error;
2197}
2198
2199Error NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,
2200 FileSpec &file_spec) {
Tamas Berghammera6f57952017-01-03 16:29:43 +00002201 Error error = PopulateMemoryRegionCache();
2202 if (error.Fail())
2203 return error;
2204
Kate Stoneb9c1b512016-09-06 20:57:50 +00002205 FileSpec module_file_spec(module_path, true);
2206
Kate Stoneb9c1b512016-09-06 20:57:50 +00002207 file_spec.Clear();
Tamas Berghammera6f57952017-01-03 16:29:43 +00002208 for (const auto &it : m_mem_region_cache) {
2209 if (it.second.GetFilename() == module_file_spec.GetFilename()) {
2210 file_spec = it.second;
2211 return Error();
2212 }
2213 }
2214 return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
2215 module_file_spec.GetFilename().AsCString(), GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002216}
2217
2218Error NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
2219 lldb::addr_t &load_addr) {
2220 load_addr = LLDB_INVALID_ADDRESS;
Tamas Berghammera6f57952017-01-03 16:29:43 +00002221 Error error = PopulateMemoryRegionCache();
2222 if (error.Fail())
2223 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002224
Tamas Berghammera6f57952017-01-03 16:29:43 +00002225 FileSpec file(file_name, false);
2226 for (const auto &it : m_mem_region_cache) {
2227 if (it.second == file) {
2228 load_addr = it.first.GetRange().GetRangeBase();
2229 return Error();
2230 }
2231 }
2232 return Error("No load address found for specified file.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002233}
2234
2235NativeThreadLinuxSP NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {
2236 return std::static_pointer_cast<NativeThreadLinux>(
2237 NativeProcessProtocol::GetThreadByID(tid));
2238}
2239
2240Error NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,
2241 lldb::StateType state, int signo) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002242 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2243 LLDB_LOG(log, "tid: {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002244
2245 // Before we do the resume below, first check if we have a pending
2246 // stop notification that is currently waiting for
2247 // all threads to stop. This is potentially a buggy situation since
2248 // we're ostensibly waiting for threads to stop before we send out the
2249 // pending notification, and here we are resuming one before we send
2250 // out the pending stop notification.
Pavel Labatha6321a82017-01-19 15:26:04 +00002251 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
2252 LLDB_LOG(log,
2253 "about to resume tid {0} per explicit request but we have a "
2254 "pending stop notification (tid {1}) that is actively "
2255 "waiting for this thread to stop. Valid sequence of events?",
2256 thread.GetID(), m_pending_notification_tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002257 }
2258
2259 // Request a resume. We expect this to be synchronous and the system
2260 // to reflect it is running after this completes.
2261 switch (state) {
2262 case eStateRunning: {
2263 const auto resume_result = thread.Resume(signo);
2264 if (resume_result.Success())
2265 SetState(eStateRunning, true);
2266 return resume_result;
2267 }
2268 case eStateStepping: {
2269 const auto step_result = thread.SingleStep(signo);
2270 if (step_result.Success())
2271 SetState(eStateRunning, true);
2272 return step_result;
2273 }
2274 default:
Pavel Labatha6321a82017-01-19 15:26:04 +00002275 LLDB_LOG(log, "Unhandled state {0}.", StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002276 llvm_unreachable("Unhandled state for resume");
2277 }
Pavel Labathc0765592015-05-06 10:46:34 +00002278}
2279
2280//===----------------------------------------------------------------------===//
2281
Kate Stoneb9c1b512016-09-06 20:57:50 +00002282void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002283 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2284 LLDB_LOG(log, "about to process event: (triggering_tid: {0})",
2285 triggering_tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002286
2287 m_pending_notification_tid = triggering_tid;
2288
2289 // Request a stop for all the thread stops that need to be stopped
2290 // and are not already known to be stopped.
2291 for (const auto &thread_sp : m_threads) {
2292 if (StateIsRunningState(thread_sp->GetState()))
2293 static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
2294 }
2295
2296 SignalIfAllThreadsStopped();
Pavel Labatha6321a82017-01-19 15:26:04 +00002297 LLDB_LOG(log, "event processing done");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002298}
2299
2300void NativeProcessLinux::SignalIfAllThreadsStopped() {
2301 if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
2302 return; // No pending notification. Nothing to do.
2303
2304 for (const auto &thread_sp : m_threads) {
2305 if (StateIsRunningState(thread_sp->GetState()))
2306 return; // Some threads are still running. Don't signal yet.
2307 }
2308
2309 // We have a pending notification and all threads have stopped.
2310 Log *log(
2311 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
2312
2313 // Clear any temporary breakpoints we used to implement software single
2314 // stepping.
2315 for (const auto &thread_info : m_threads_stepping_with_breakpoint) {
2316 Error error = RemoveBreakpoint(thread_info.second);
2317 if (error.Fail())
Pavel Labatha6321a82017-01-19 15:26:04 +00002318 LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}",
2319 thread_info.first, error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002320 }
2321 m_threads_stepping_with_breakpoint.clear();
2322
2323 // Notify the delegate about the stop
2324 SetCurrentThreadID(m_pending_notification_tid);
2325 SetState(StateType::eStateStopped, true);
2326 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
2327}
2328
2329void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {
Pavel Labatha6321a82017-01-19 15:26:04 +00002330 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD);
2331 LLDB_LOG(log, "tid: {0}", thread.GetID());
Kate Stoneb9c1b512016-09-06 20:57:50 +00002332
2333 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID &&
2334 StateIsRunningState(thread.GetState())) {
2335 // We will need to wait for this new thread to stop as well before firing
2336 // the
2337 // notification.
2338 thread.RequestStop();
2339 }
2340}
2341
2342void NativeProcessLinux::SigchldHandler() {
Pavel Labatha6321a82017-01-19 15:26:04 +00002343 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002344 // Process all pending waitpid notifications.
2345 while (true) {
2346 int status = -1;
2347 ::pid_t wait_pid = waitpid(-1, &status, __WALL | __WNOTHREAD | WNOHANG);
2348
2349 if (wait_pid == 0)
2350 break; // We are done.
2351
2352 if (wait_pid == -1) {
2353 if (errno == EINTR)
2354 continue;
2355
2356 Error error(errno, eErrorTypePOSIX);
Pavel Labatha6321a82017-01-19 15:26:04 +00002357 LLDB_LOG(log, "waitpid (-1, &status, _) failed: {0}", error);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002358 break;
Pavel Labathc0765592015-05-06 10:46:34 +00002359 }
2360
Kate Stoneb9c1b512016-09-06 20:57:50 +00002361 bool exited = false;
2362 int signal = 0;
2363 int exit_status = 0;
2364 const char *status_cstr = nullptr;
2365 if (WIFSTOPPED(status)) {
2366 signal = WSTOPSIG(status);
2367 status_cstr = "STOPPED";
2368 } else if (WIFEXITED(status)) {
2369 exit_status = WEXITSTATUS(status);
2370 status_cstr = "EXITED";
2371 exited = true;
2372 } else if (WIFSIGNALED(status)) {
2373 signal = WTERMSIG(status);
2374 status_cstr = "SIGNALED";
2375 if (wait_pid == static_cast<::pid_t>(GetID())) {
2376 exited = true;
2377 exit_status = -1;
2378 }
2379 } else
2380 status_cstr = "(\?\?\?)";
Pavel Labathc0765592015-05-06 10:46:34 +00002381
Pavel Labatha6321a82017-01-19 15:26:04 +00002382 LLDB_LOG(log,
2383 "waitpid (-1, &status, _) => pid = {0}, status = {1:x} "
2384 "({2}), signal = {3}, exit_state = {4}",
2385 wait_pid, status, status_cstr, signal, exit_status);
Pavel Labathc0765592015-05-06 10:46:34 +00002386
Kate Stoneb9c1b512016-09-06 20:57:50 +00002387 MonitorCallback(wait_pid, exited, signal, exit_status);
2388 }
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002389}
2390
2391// Wrapper for ptrace to catch errors and log calls.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002392// Note that ptrace sets errno on error because -1 can be a valid result (i.e.
2393// for PTRACE_PEEK*)
2394Error NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
2395 void *data, size_t data_size,
2396 long *result) {
2397 Error error;
2398 long int ret;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002399
Kate Stoneb9c1b512016-09-06 20:57:50 +00002400 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002401
Kate Stoneb9c1b512016-09-06 20:57:50 +00002402 PtraceDisplayBytes(req, data, data_size);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002403
Kate Stoneb9c1b512016-09-06 20:57:50 +00002404 errno = 0;
2405 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
2406 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2407 *(unsigned int *)addr, data);
2408 else
2409 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2410 addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002411
Kate Stoneb9c1b512016-09-06 20:57:50 +00002412 if (ret == -1)
2413 error.SetErrorToErrno();
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002414
Kate Stoneb9c1b512016-09-06 20:57:50 +00002415 if (result)
2416 *result = ret;
Pavel Labath4a9babb2015-06-30 17:04:49 +00002417
Pavel Labatha6321a82017-01-19 15:26:04 +00002418 LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4}, {5})={6:x}", req, pid, addr,
2419 data, data_size, ret);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002420
Kate Stoneb9c1b512016-09-06 20:57:50 +00002421 PtraceDisplayBytes(req, data, data_size);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002422
Pavel Labatha6321a82017-01-19 15:26:04 +00002423 if (error.Fail())
2424 LLDB_LOG(log, "ptrace() failed: {0}", error);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002425
Kate Stoneb9c1b512016-09-06 20:57:50 +00002426 return error;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002427}