blob: 94b9efc2b2b010651f8f56cc79a70d8102b30d65 [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 Labath4abe5d62016-07-15 10:18:15 +000081 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_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);
95 if (log) {
96 if (is_supported)
97 log->Printf("%s: Detected kernel support for process_vm_readv syscall. "
98 "Fast memory reads enabled.",
99 __FUNCTION__);
100 else
101 log->Printf("%s: syscall process_vm_readv failed (error: %s). Fast "
102 "memory reads disabled.",
103 __FUNCTION__, strerror(errno));
104 }
105 });
Pavel Labath4abe5d62016-07-15 10:18:15 +0000106
Kate Stoneb9c1b512016-09-06 20:57:50 +0000107 return is_supported;
Pavel Labath4abe5d62016-07-15 10:18:15 +0000108}
109
Kate Stoneb9c1b512016-09-06 20:57:50 +0000110namespace {
111void MaybeLogLaunchInfo(const ProcessLaunchInfo &info) {
112 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
113 if (!log)
114 return;
115
116 if (const FileAction *action = info.GetFileActionForFD(STDIN_FILENO))
117 log->Printf("%s: setting STDIN to '%s'", __FUNCTION__,
118 action->GetFileSpec().GetCString());
119 else
120 log->Printf("%s leaving STDIN as is", __FUNCTION__);
121
122 if (const FileAction *action = info.GetFileActionForFD(STDOUT_FILENO))
123 log->Printf("%s setting STDOUT to '%s'", __FUNCTION__,
124 action->GetFileSpec().GetCString());
125 else
126 log->Printf("%s leaving STDOUT as is", __FUNCTION__);
127
128 if (const FileAction *action = info.GetFileActionForFD(STDERR_FILENO))
129 log->Printf("%s setting STDERR to '%s'", __FUNCTION__,
130 action->GetFileSpec().GetCString());
131 else
132 log->Printf("%s leaving STDERR as is", __FUNCTION__);
133
134 int i = 0;
135 for (const char **args = info.GetArguments().GetConstArgumentVector(); *args;
136 ++args, ++i)
137 log->Printf("%s arg %d: \"%s\"", __FUNCTION__, i,
138 *args ? *args : "nullptr");
Pavel Labath4abe5d62016-07-15 10:18:15 +0000139}
Todd Fialaaf245d12014-06-30 21:05:18 +0000140
Kate Stoneb9c1b512016-09-06 20:57:50 +0000141void DisplayBytes(StreamString &s, void *bytes, uint32_t count) {
142 uint8_t *ptr = (uint8_t *)bytes;
143 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
144 for (uint32_t i = 0; i < loop_count; i++) {
145 s.Printf("[%x]", *ptr);
146 ptr++;
147 }
148}
Todd Fialaaf245d12014-06-30 21:05:18 +0000149
Kate Stoneb9c1b512016-09-06 20:57:50 +0000150void PtraceDisplayBytes(int &req, void *data, size_t data_size) {
151 StreamString buf;
152 Log *verbose_log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(
153 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
154
155 if (verbose_log) {
156 switch (req) {
157 case PTRACE_POKETEXT: {
158 DisplayBytes(buf, &data, 8);
159 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
160 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000161 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000162 case PTRACE_POKEDATA: {
163 DisplayBytes(buf, &data, 8);
164 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
165 break;
166 }
167 case PTRACE_POKEUSER: {
168 DisplayBytes(buf, &data, 8);
169 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
170 break;
171 }
172 case PTRACE_SETREGS: {
173 DisplayBytes(buf, data, data_size);
174 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
175 break;
176 }
177 case PTRACE_SETFPREGS: {
178 DisplayBytes(buf, data, data_size);
179 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
180 break;
181 }
182 case PTRACE_SETSIGINFO: {
183 DisplayBytes(buf, data, sizeof(siginfo_t));
184 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
185 break;
186 }
187 case PTRACE_SETREGSET: {
188 // Extract iov_base from data, which is a pointer to the struct IOVEC
189 DisplayBytes(buf, *(void **)data, data_size);
190 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
191 break;
192 }
193 default: {}
194 }
195 }
196}
Todd Fialaaf245d12014-06-30 21:05:18 +0000197
Kate Stoneb9c1b512016-09-06 20:57:50 +0000198static constexpr unsigned k_ptrace_word_size = sizeof(void *);
199static_assert(sizeof(long) >= k_ptrace_word_size,
200 "Size of long must be larger than ptrace word size");
Pavel Labath1107b5a2015-04-17 14:07:49 +0000201} // end of anonymous namespace
202
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000203// Simple helper function to ensure flags are enabled on the given file
204// descriptor.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000205static Error EnsureFDFlags(int fd, int flags) {
206 Error error;
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000207
Kate Stoneb9c1b512016-09-06 20:57:50 +0000208 int status = fcntl(fd, F_GETFL);
209 if (status == -1) {
210 error.SetErrorToErrno();
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000211 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000212 }
213
214 if (fcntl(fd, F_SETFL, status | flags) == -1) {
215 error.SetErrorToErrno();
216 return error;
217 }
218
219 return error;
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000220}
221
Todd Fialaaf245d12014-06-30 21:05:18 +0000222// -----------------------------------------------------------------------------
223// Public Static Methods
224// -----------------------------------------------------------------------------
225
Kate Stoneb9c1b512016-09-06 20:57:50 +0000226Error NativeProcessProtocol::Launch(
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000227 ProcessLaunchInfo &launch_info,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000228 NativeProcessProtocol::NativeDelegate &native_delegate, MainLoop &mainloop,
229 NativeProcessProtocolSP &native_process_sp) {
230 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Todd Fialaaf245d12014-06-30 21:05:18 +0000231
Kate Stoneb9c1b512016-09-06 20:57:50 +0000232 Error error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000233
Kate Stoneb9c1b512016-09-06 20:57:50 +0000234 // Verify the working directory is valid if one was specified.
235 FileSpec working_dir{launch_info.GetWorkingDirectory()};
236 if (working_dir &&
237 (!working_dir.ResolvePath() ||
238 working_dir.GetFileType() != FileSpec::eFileTypeDirectory)) {
239 error.SetErrorStringWithFormat("No such file or directory: %s",
240 working_dir.GetCString());
Todd Fialaaf245d12014-06-30 21:05:18 +0000241 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000242 }
243
244 // Create the NativeProcessLinux in launch mode.
245 native_process_sp.reset(new NativeProcessLinux());
246
247 if (!native_process_sp->RegisterNativeDelegate(native_delegate)) {
248 native_process_sp.reset();
249 error.SetErrorStringWithFormat("failed to register the native delegate");
250 return error;
251 }
252
253 error = std::static_pointer_cast<NativeProcessLinux>(native_process_sp)
254 ->LaunchInferior(mainloop, launch_info);
255
256 if (error.Fail()) {
257 native_process_sp.reset();
258 if (log)
259 log->Printf("NativeProcessLinux::%s failed to launch process: %s",
260 __FUNCTION__, error.AsCString());
261 return error;
262 }
263
264 launch_info.SetProcessID(native_process_sp->GetID());
265
266 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000267}
268
Kate Stoneb9c1b512016-09-06 20:57:50 +0000269Error NativeProcessProtocol::Attach(
270 lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
271 MainLoop &mainloop, NativeProcessProtocolSP &native_process_sp) {
272 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
273 if (log && log->GetMask().Test(POSIX_LOG_VERBOSE))
274 log->Printf("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000275
Kate Stoneb9c1b512016-09-06 20:57:50 +0000276 // Retrieve the architecture for the running process.
277 ArchSpec process_arch;
278 Error error = ResolveProcessArchitecture(pid, process_arch);
279 if (!error.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +0000280 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000281
282 std::shared_ptr<NativeProcessLinux> native_process_linux_sp(
283 new NativeProcessLinux());
284
285 if (!native_process_linux_sp->RegisterNativeDelegate(native_delegate)) {
286 error.SetErrorStringWithFormat("failed to register the native delegate");
287 return error;
288 }
289
290 native_process_linux_sp->AttachToInferior(mainloop, pid, error);
291 if (!error.Success())
292 return error;
293
294 native_process_sp = native_process_linux_sp;
295 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000296}
297
298// -----------------------------------------------------------------------------
299// Public Instance Methods
300// -----------------------------------------------------------------------------
301
Kate Stoneb9c1b512016-09-06 20:57:50 +0000302NativeProcessLinux::NativeProcessLinux()
303 : NativeProcessProtocol(LLDB_INVALID_PROCESS_ID), m_arch(),
304 m_supports_mem_region(eLazyBoolCalculate), m_mem_region_cache(),
305 m_pending_notification_tid(LLDB_INVALID_THREAD_ID) {}
306
307void NativeProcessLinux::AttachToInferior(MainLoop &mainloop, lldb::pid_t pid,
308 Error &error) {
309 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
310 if (log)
311 log->Printf("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__,
312 pid);
313
314 m_sigchld_handle = mainloop.RegisterSignal(
315 SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, error);
316 if (!m_sigchld_handle)
317 return;
318
319 error = ResolveProcessArchitecture(pid, m_arch);
320 if (!error.Success())
321 return;
322
323 // Set the architecture to the exe architecture.
324 if (log)
325 log->Printf("NativeProcessLinux::%s (pid = %" PRIi64
326 ") detected architecture %s",
327 __FUNCTION__, pid, m_arch.GetArchitectureName());
328
329 m_pid = pid;
330 SetState(eStateAttaching);
331
332 Attach(pid, error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000333}
334
Kate Stoneb9c1b512016-09-06 20:57:50 +0000335Error NativeProcessLinux::LaunchInferior(MainLoop &mainloop,
336 ProcessLaunchInfo &launch_info) {
337 Error error;
338 m_sigchld_handle = mainloop.RegisterSignal(
339 SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, error);
340 if (!m_sigchld_handle)
341 return error;
342
343 SetState(eStateLaunching);
344
345 MaybeLogLaunchInfo(launch_info);
346
347 ::pid_t pid =
348 ProcessLauncherLinux().LaunchProcess(launch_info, error).GetProcessId();
349 if (error.Fail())
350 return error;
351
352 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
353
354 // Wait for the child process to trap on its call to execve.
355 ::pid_t wpid;
356 int status;
357 if ((wpid = waitpid(pid, &status, 0)) < 0) {
358 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +0000359 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000360 log->Printf("NativeProcessLinux::%s waitpid for inferior failed with %s",
361 __FUNCTION__, error.AsCString());
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);
Pavel Labath19cbe962015-07-21 13:20:32 +0000367
Kate Stoneb9c1b512016-09-06 20:57:50 +0000368 return error;
369 }
370 assert(WIFSTOPPED(status) && (wpid == static_cast<::pid_t>(pid)) &&
371 "Could not sync with inferior process.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000372
Kate Stoneb9c1b512016-09-06 20:57:50 +0000373 if (log)
374 log->Printf("NativeProcessLinux::%s inferior started, now in stopped state",
375 __FUNCTION__);
376
377 error = SetDefaultPtraceOpts(pid);
378 if (error.Fail()) {
Todd Fialaaf245d12014-06-30 21:05:18 +0000379 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000380 log->Printf("NativeProcessLinux::%s inferior failed to set default "
381 "ptrace options: %s",
382 __FUNCTION__, error.AsCString());
Todd Fialaaf245d12014-06-30 21:05:18 +0000383
Kate Stoneb9c1b512016-09-06 20:57:50 +0000384 // Mark the inferior as invalid.
385 // FIXME this could really use a new state - eStateLaunchFailure. For now,
386 // using eStateInvalid.
387 SetState(StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000388
Kate Stoneb9c1b512016-09-06 20:57:50 +0000389 return error;
390 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000391
Kate Stoneb9c1b512016-09-06 20:57:50 +0000392 // Release the master terminal descriptor and pass it off to the
393 // NativeProcessLinux instance. Similarly stash the inferior pid.
394 m_terminal_fd = launch_info.GetPTY().ReleaseMasterFileDescriptor();
395 m_pid = pid;
396 launch_info.SetProcessID(pid);
Pavel Labath4abe5d62016-07-15 10:18:15 +0000397
Kate Stoneb9c1b512016-09-06 20:57:50 +0000398 if (m_terminal_fd != -1) {
399 error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
400 if (error.Fail()) {
401 if (log)
402 log->Printf("NativeProcessLinux::%s inferior EnsureFDFlags failed for "
403 "ensuring terminal O_NONBLOCK setting: %s",
Pavel Labath5ad891f2016-07-21 14:54:03 +0000404 __FUNCTION__, error.AsCString());
Todd Fialaaf245d12014-06-30 21:05:18 +0000405
Kate Stoneb9c1b512016-09-06 20:57:50 +0000406 // Mark the inferior as invalid.
407 // FIXME this could really use a new state - eStateLaunchFailure. For
408 // now, using eStateInvalid.
409 SetState(StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000410
Kate Stoneb9c1b512016-09-06 20:57:50 +0000411 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000412 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000413 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000414
Kate Stoneb9c1b512016-09-06 20:57:50 +0000415 if (log)
416 log->Printf("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__,
417 uint64_t(pid));
Todd Fialaaf245d12014-06-30 21:05:18 +0000418
Kate Stoneb9c1b512016-09-06 20:57:50 +0000419 ResolveProcessArchitecture(m_pid, m_arch);
420 NativeThreadLinuxSP thread_sp = AddThread(pid);
421 assert(thread_sp && "AddThread() returned a nullptr thread");
422 thread_sp->SetStoppedBySignal(SIGSTOP);
423 ThreadWasCreated(*thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +0000424
Kate Stoneb9c1b512016-09-06 20:57:50 +0000425 // Let our process instance know the thread has stopped.
426 SetCurrentThreadID(thread_sp->GetID());
427 SetState(StateType::eStateStopped);
428
429 if (log) {
430 if (error.Success())
431 log->Printf("NativeProcessLinux::%s inferior launching succeeded",
432 __FUNCTION__);
433 else
434 log->Printf("NativeProcessLinux::%s inferior launching failed: %s",
435 __FUNCTION__, error.AsCString());
436 }
437 return error;
438}
439
440::pid_t NativeProcessLinux::Attach(lldb::pid_t pid, Error &error) {
441 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
442
443 // Use a map to keep track of the threads which we have attached/need to
444 // attach.
445 Host::TidMap tids_to_attach;
446 if (pid <= 1) {
447 error.SetErrorToGenericError();
448 error.SetErrorString("Attaching to process 1 is not allowed.");
449 return -1;
450 }
451
452 while (Host::FindProcessThreads(pid, tids_to_attach)) {
453 for (Host::TidMap::iterator it = tids_to_attach.begin();
454 it != tids_to_attach.end();) {
455 if (it->second == false) {
456 lldb::tid_t tid = it->first;
457
458 // Attach to the requested process.
459 // An attach will cause the thread to stop with a SIGSTOP.
460 error = PtraceWrapper(PTRACE_ATTACH, tid);
461 if (error.Fail()) {
462 // No such thread. The thread may have exited.
463 // More error handling may be needed.
464 if (error.GetError() == ESRCH) {
465 it = tids_to_attach.erase(it);
466 continue;
467 } else
468 return -1;
469 }
470
471 int status;
472 // Need to use __WALL otherwise we receive an error with errno=ECHLD
473 // At this point we should have a thread stopped if waitpid succeeds.
474 if ((status = waitpid(tid, NULL, __WALL)) < 0) {
475 // No such thread. The thread may have exited.
476 // More error handling may be needed.
477 if (errno == ESRCH) {
478 it = tids_to_attach.erase(it);
479 continue;
480 } else {
481 error.SetErrorToErrno();
482 return -1;
483 }
484 }
485
486 error = SetDefaultPtraceOpts(tid);
487 if (error.Fail())
488 return -1;
489
490 if (log)
491 log->Printf("NativeProcessLinux::%s() adding tid = %" PRIu64,
492 __FUNCTION__, tid);
493
494 it->second = true;
495
496 // Create the thread, mark it as stopped.
497 NativeThreadLinuxSP thread_sp(AddThread(static_cast<lldb::tid_t>(tid)));
498 assert(thread_sp && "AddThread() returned a nullptr");
499
500 // This will notify this is a new thread and tell the system it is
501 // stopped.
502 thread_sp->SetStoppedBySignal(SIGSTOP);
503 ThreadWasCreated(*thread_sp);
504 SetCurrentThreadID(thread_sp->GetID());
505 }
506
507 // move the loop forward
508 ++it;
509 }
510 }
511
512 if (tids_to_attach.size() > 0) {
513 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000514 // Let our process instance know the thread has stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000515 SetState(StateType::eStateStopped);
516 } else {
517 error.SetErrorToGenericError();
518 error.SetErrorString("No such process.");
519 return -1;
520 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000521
Kate Stoneb9c1b512016-09-06 20:57:50 +0000522 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000523}
524
Kate Stoneb9c1b512016-09-06 20:57:50 +0000525Error NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid) {
526 long ptrace_opts = 0;
Todd Fialaaf245d12014-06-30 21:05:18 +0000527
Kate Stoneb9c1b512016-09-06 20:57:50 +0000528 // Have the child raise an event on exit. This is used to keep the child in
529 // limbo until it is destroyed.
530 ptrace_opts |= PTRACE_O_TRACEEXIT;
Todd Fialaaf245d12014-06-30 21:05:18 +0000531
Kate Stoneb9c1b512016-09-06 20:57:50 +0000532 // Have the tracer trace threads which spawn in the inferior process.
533 // TODO: if we want to support tracing the inferiors' child, add the
534 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
535 ptrace_opts |= PTRACE_O_TRACECLONE;
Todd Fialaaf245d12014-06-30 21:05:18 +0000536
Kate Stoneb9c1b512016-09-06 20:57:50 +0000537 // Have the tracer notify us before execve returns
538 // (needed to disable legacy SIGTRAP generation)
539 ptrace_opts |= PTRACE_O_TRACEEXEC;
Todd Fialaaf245d12014-06-30 21:05:18 +0000540
Kate Stoneb9c1b512016-09-06 20:57:50 +0000541 return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void *)ptrace_opts);
Todd Fialaaf245d12014-06-30 21:05:18 +0000542}
543
Kate Stoneb9c1b512016-09-06 20:57:50 +0000544static ExitType convert_pid_status_to_exit_type(int status) {
545 if (WIFEXITED(status))
546 return ExitType::eExitTypeExit;
547 else if (WIFSIGNALED(status))
548 return ExitType::eExitTypeSignal;
549 else if (WIFSTOPPED(status))
550 return ExitType::eExitTypeStop;
551 else {
552 // We don't know what this is.
553 return ExitType::eExitTypeInvalid;
554 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000555}
556
Kate Stoneb9c1b512016-09-06 20:57:50 +0000557static int convert_pid_status_to_return_code(int status) {
558 if (WIFEXITED(status))
559 return WEXITSTATUS(status);
560 else if (WIFSIGNALED(status))
561 return WTERMSIG(status);
562 else if (WIFSTOPPED(status))
563 return WSTOPSIG(status);
564 else {
565 // We don't know what this is.
566 return ExitType::eExitTypeInvalid;
567 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000568}
569
Pavel Labath1107b5a2015-04-17 14:07:49 +0000570// Handles all waitpid events from the inferior process.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000571void NativeProcessLinux::MonitorCallback(lldb::pid_t pid, bool exited,
572 int signal, int status) {
573 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
Todd Fialaaf245d12014-06-30 21:05:18 +0000574
Kate Stoneb9c1b512016-09-06 20:57:50 +0000575 // Certain activities differ based on whether the pid is the tid of the main
576 // thread.
577 const bool is_main_thread = (pid == GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000578
Kate Stoneb9c1b512016-09-06 20:57:50 +0000579 // Handle when the thread exits.
580 if (exited) {
581 if (log)
582 log->Printf(
583 "NativeProcessLinux::%s() got exit signal(%d) , tid = %" PRIu64
584 " (%s main thread)",
585 __FUNCTION__, signal, pid, is_main_thread ? "is" : "is not");
586
587 // This is a thread that exited. Ensure we're not tracking it anymore.
588 const bool thread_found = StopTrackingThread(pid);
589
590 if (is_main_thread) {
591 // We only set the exit status and notify the delegate if we haven't
592 // already set the process
593 // state to an exited state. We normally should have received a SIGTRAP |
594 // (PTRACE_EVENT_EXIT << 8)
595 // for the main thread.
596 const bool already_notified = (GetState() == StateType::eStateExited) ||
597 (GetState() == StateType::eStateCrashed);
598 if (!already_notified) {
Todd Fialaaf245d12014-06-30 21:05:18 +0000599 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000600 log->Printf("NativeProcessLinux::%s() tid = %" PRIu64
601 " handling main thread exit (%s), expected exit state "
602 "already set but state was %s instead, setting exit "
603 "state now",
604 __FUNCTION__, pid,
605 thread_found ? "stopped tracking thread metadata"
606 : "thread metadata not found",
607 StateAsCString(GetState()));
608 // The main thread exited. We're done monitoring. Report to delegate.
609 SetExitStatus(convert_pid_status_to_exit_type(status),
610 convert_pid_status_to_return_code(status), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +0000611
Kate Stoneb9c1b512016-09-06 20:57:50 +0000612 // Notify delegate that our process has exited.
613 SetState(StateType::eStateExited, true);
614 } else {
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000615 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000616 log->Printf("NativeProcessLinux::%s() tid = %" PRIu64
617 " main thread now exited (%s)",
618 __FUNCTION__, pid,
619 thread_found ? "stopped tracking thread metadata"
620 : "thread metadata not found");
621 }
622 } else {
623 // Do we want to report to the delegate in this case? I think not. If
624 // this was an orderly
625 // thread exit, we would already have received the SIGTRAP |
626 // (PTRACE_EVENT_EXIT << 8) signal,
627 // and we would have done an all-stop then.
628 if (log)
629 log->Printf("NativeProcessLinux::%s() tid = %" PRIu64
630 " handling non-main thread exit (%s)",
631 __FUNCTION__, pid,
632 thread_found ? "stopped tracking thread metadata"
633 : "thread metadata not found");
634 }
635 return;
636 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000637
Kate Stoneb9c1b512016-09-06 20:57:50 +0000638 siginfo_t info;
639 const auto info_err = GetSignalInfo(pid, &info);
640 auto thread_sp = GetThreadByID(pid);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000641
Kate Stoneb9c1b512016-09-06 20:57:50 +0000642 if (!thread_sp) {
643 // Normally, the only situation when we cannot find the thread is if we have
644 // just
645 // received a new thread notification. This is indicated by GetSignalInfo()
646 // returning
647 // si_code == SI_USER and si_pid == 0
648 if (log)
649 log->Printf("NativeProcessLinux::%s received notification about an "
650 "unknown tid %" PRIu64 ".",
651 __FUNCTION__, pid);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000652
Kate Stoneb9c1b512016-09-06 20:57:50 +0000653 if (info_err.Fail()) {
654 if (log)
655 log->Printf("NativeProcessLinux::%s (tid %" PRIu64
656 ") GetSignalInfo failed (%s). Ingoring this notification.",
657 __FUNCTION__, pid, info_err.AsCString());
658 return;
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000659 }
660
Kate Stoneb9c1b512016-09-06 20:57:50 +0000661 if (log && (info.si_code != SI_USER || info.si_pid != 0))
662 log->Printf("NativeProcessLinux::%s (tid %" PRIu64
663 ") unexpected signal info (si_code: %d, si_pid: %d). "
664 "Treating as a new thread notification anyway.",
665 __FUNCTION__, pid, info.si_code, info.si_pid);
666
667 auto thread_sp = AddThread(pid);
668 // Resume the newly created thread.
669 ResumeThread(*thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
670 ThreadWasCreated(*thread_sp);
671 return;
672 }
673
674 // Get details on the signal raised.
675 if (info_err.Success()) {
676 // We have retrieved the signal info. Dispatch appropriately.
677 if (info.si_signo == SIGTRAP)
678 MonitorSIGTRAP(info, *thread_sp);
Chaoren Linfa03ad22015-02-03 01:50:42 +0000679 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000680 MonitorSignal(info, *thread_sp, exited);
681 } else {
682 if (info_err.GetError() == EINVAL) {
683 // This is a group stop reception for this tid.
684 // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU
685 // into the
686 // tracee, triggering the group-stop mechanism. Normally receiving these
687 // would stop
688 // the process, pending a SIGCONT. Simulating this state in a debugger is
689 // hard and is
690 // generally not needed (one use case is debugging background task being
691 // managed by a
692 // shell). For general use, it is sufficient to stop the process in a
693 // signal-delivery
694 // stop which happens before the group stop. This done by MonitorSignal
695 // and works
696 // correctly for all signals.
697 if (log)
698 log->Printf(
699 "NativeProcessLinux::%s received a group stop for pid %" PRIu64
700 " tid %" PRIu64 ". Transparent handling of group stops not "
701 "supported, resuming the thread.",
702 __FUNCTION__, GetID(), pid);
703 ResumeThread(*thread_sp, thread_sp->GetState(),
704 LLDB_INVALID_SIGNAL_NUMBER);
705 } else {
706 // ptrace(GETSIGINFO) failed (but not due to group-stop).
Todd Fialaaf245d12014-06-30 21:05:18 +0000707
Kate Stoneb9c1b512016-09-06 20:57:50 +0000708 // A return value of ESRCH means the thread/process is no longer on the
709 // system,
710 // so it was killed somehow outside of our control. Either way, we can't
711 // do anything
712 // with it anymore.
Todd Fialaaf245d12014-06-30 21:05:18 +0000713
Kate Stoneb9c1b512016-09-06 20:57:50 +0000714 // Stop tracking the metadata for the thread since it's entirely off the
715 // system now.
716 const bool thread_found = StopTrackingThread(pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000717
Kate Stoneb9c1b512016-09-06 20:57:50 +0000718 if (log)
719 log->Printf(
720 "NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64
721 ", signal = %d, status = %d (%s, %s, %s)",
722 __FUNCTION__, info_err.AsCString(), pid, signal, status,
723 info_err.GetError() == ESRCH ? "thread/process killed"
724 : "unknown reason",
725 is_main_thread ? "is main thread" : "is not main thread",
726 thread_found ? "thread metadata removed"
727 : "thread metadata not found");
Todd Fialaaf245d12014-06-30 21:05:18 +0000728
Kate Stoneb9c1b512016-09-06 20:57:50 +0000729 if (is_main_thread) {
730 // Notify the delegate - our process is not available but appears to
731 // have been killed outside
732 // our control. Is eStateExited the right exit state in this case?
733 SetExitStatus(convert_pid_status_to_exit_type(status),
734 convert_pid_status_to_return_code(status), nullptr, true);
735 SetState(StateType::eStateExited, true);
736 } else {
737 // This thread was pulled out from underneath us. Anything to do here?
738 // Do we want to do an all stop?
739 if (log)
740 log->Printf("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64
741 " non-main thread exit occurred, didn't tell delegate "
742 "anything since thread disappeared out from underneath "
743 "us",
744 __FUNCTION__, GetID(), pid);
745 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000746 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000747 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000748}
749
Kate Stoneb9c1b512016-09-06 20:57:50 +0000750void NativeProcessLinux::WaitForNewThread(::pid_t tid) {
751 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labath426bdf82015-04-28 07:51:52 +0000752
Kate Stoneb9c1b512016-09-06 20:57:50 +0000753 NativeThreadLinuxSP new_thread_sp = GetThreadByID(tid);
Pavel Labath426bdf82015-04-28 07:51:52 +0000754
Kate Stoneb9c1b512016-09-06 20:57:50 +0000755 if (new_thread_sp) {
756 // We are already tracking the thread - we got the event on the new thread
757 // (see
758 // MonitorSignal) before this one. We are done.
759 return;
760 }
Pavel Labath426bdf82015-04-28 07:51:52 +0000761
Kate Stoneb9c1b512016-09-06 20:57:50 +0000762 // The thread is not tracked yet, let's wait for it to appear.
763 int status = -1;
764 ::pid_t wait_pid;
765 do {
Pavel Labath426bdf82015-04-28 07:51:52 +0000766 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000767 log->Printf("NativeProcessLinux::%s() received thread creation event for "
768 "tid %" PRIu32
769 ". tid not tracked yet, waiting for thread to appear...",
770 __FUNCTION__, tid);
771 wait_pid = waitpid(tid, &status, __WALL);
772 } while (wait_pid == -1 && errno == EINTR);
773 // Since we are waiting on a specific tid, this must be the creation event.
774 // But let's do
775 // some checks just in case.
776 if (wait_pid != tid) {
777 if (log)
778 log->Printf(
779 "NativeProcessLinux::%s() waiting for tid %" PRIu32
780 " failed. Assuming the thread has disappeared in the meantime",
781 __FUNCTION__, tid);
782 // The only way I know of this could happen is if the whole process was
783 // SIGKILLed in the mean time. In any case, we can't do anything about that
784 // now.
785 return;
786 }
787 if (WIFEXITED(status)) {
788 if (log)
789 log->Printf("NativeProcessLinux::%s() waiting for tid %" PRIu32
790 " returned an 'exited' event. Not tracking the thread.",
791 __FUNCTION__, tid);
792 // Also a very improbable event.
793 return;
794 }
Pavel Labath426bdf82015-04-28 07:51:52 +0000795
Kate Stoneb9c1b512016-09-06 20:57:50 +0000796 siginfo_t info;
797 Error error = GetSignalInfo(tid, &info);
798 if (error.Fail()) {
799 if (log)
800 log->Printf(
801 "NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32
802 " failed. Assuming the thread has disappeared in the meantime.",
803 __FUNCTION__, tid);
804 return;
805 }
806
807 if (((info.si_pid != 0) || (info.si_code != SI_USER)) && log) {
808 // We should be getting a thread creation signal here, but we received
809 // something
810 // else. There isn't much we can do about it now, so we will just log that.
811 // Since the
812 // thread is alive and we are receiving events from it, we shall pretend
813 // that it was
814 // created properly.
815 log->Printf("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32
816 " received unexpected signal with code %d from pid %d.",
817 __FUNCTION__, tid, info.si_code, info.si_pid);
818 }
819
820 if (log)
821 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64
822 ": tracking new thread tid %" PRIu32,
823 __FUNCTION__, GetID(), tid);
824
825 new_thread_sp = AddThread(tid);
826 ResumeThread(*new_thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
827 ThreadWasCreated(*new_thread_sp);
Pavel Labath426bdf82015-04-28 07:51:52 +0000828}
829
Kate Stoneb9c1b512016-09-06 20:57:50 +0000830void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info,
831 NativeThreadLinux &thread) {
832 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
833 const bool is_main_thread = (thread.GetID() == GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000834
Kate Stoneb9c1b512016-09-06 20:57:50 +0000835 assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
Todd Fialaaf245d12014-06-30 21:05:18 +0000836
Kate Stoneb9c1b512016-09-06 20:57:50 +0000837 switch (info.si_code) {
838 // TODO: these two cases are required if we want to support tracing of the
839 // inferiors' children. We'd need this to debug a monitor.
840 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
841 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
Todd Fialaaf245d12014-06-30 21:05:18 +0000842
Kate Stoneb9c1b512016-09-06 20:57:50 +0000843 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): {
844 // This is the notification on the parent thread which informs us of new
845 // thread
846 // creation.
847 // We don't want to do anything with the parent thread so we just resume it.
848 // In case we
849 // want to implement "break on thread creation" functionality, we would need
850 // to stop
851 // here.
Todd Fialaaf245d12014-06-30 21:05:18 +0000852
Kate Stoneb9c1b512016-09-06 20:57:50 +0000853 unsigned long event_message = 0;
854 if (GetEventMessage(thread.GetID(), &event_message).Fail()) {
855 if (log)
856 log->Printf("NativeProcessLinux::%s() pid %" PRIu64
857 " received thread creation event but GetEventMessage "
858 "failed so we don't know the new tid",
859 __FUNCTION__, thread.GetID());
860 } else
861 WaitForNewThread(event_message);
Todd Fialaaf245d12014-06-30 21:05:18 +0000862
Kate Stoneb9c1b512016-09-06 20:57:50 +0000863 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
864 break;
865 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000866
Kate Stoneb9c1b512016-09-06 20:57:50 +0000867 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): {
868 NativeThreadLinuxSP main_thread_sp;
869 if (log)
870 log->Printf("NativeProcessLinux::%s() received exec event, code = %d",
871 __FUNCTION__, info.si_code ^ SIGTRAP);
872
873 // Exec clears any pending notifications.
874 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
875
876 // Remove all but the main thread here. Linux fork creates a new process
877 // which only copies the main thread.
878 if (log)
879 log->Printf("NativeProcessLinux::%s exec received, stop tracking all but "
880 "main thread",
881 __FUNCTION__);
882
883 for (auto thread_sp : m_threads) {
884 const bool is_main_thread = thread_sp && thread_sp->GetID() == GetID();
885 if (is_main_thread) {
886 main_thread_sp = std::static_pointer_cast<NativeThreadLinux>(thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +0000887 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000888 log->Printf(
889 "NativeProcessLinux::%s found main thread with tid %" PRIu64
890 ", keeping",
891 __FUNCTION__, main_thread_sp->GetID());
892 } else {
Tamas Berghammer5830aa72015-02-06 10:42:33 +0000893 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000894 log->Printf(
895 "NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64
896 " due to exec",
897 __FUNCTION__, thread_sp->GetID());
898 }
Todd Fialaa9882ce2014-08-28 15:46:54 +0000899 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000900
Kate Stoneb9c1b512016-09-06 20:57:50 +0000901 m_threads.clear();
Chaoren Linfa03ad22015-02-03 01:50:42 +0000902
Kate Stoneb9c1b512016-09-06 20:57:50 +0000903 if (main_thread_sp) {
904 m_threads.push_back(main_thread_sp);
905 SetCurrentThreadID(main_thread_sp->GetID());
906 main_thread_sp->SetStoppedByExec();
907 } else {
908 SetCurrentThreadID(LLDB_INVALID_THREAD_ID);
909 if (log)
910 log->Printf("NativeProcessLinux::%s pid %" PRIu64
911 "no main thread found, discarded all threads, we're in a "
912 "no-thread state!",
913 __FUNCTION__, GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +0000914 }
915
Kate Stoneb9c1b512016-09-06 20:57:50 +0000916 // Tell coordinator about about the "new" (since exec) stopped main thread.
917 ThreadWasCreated(*main_thread_sp);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000918
Kate Stoneb9c1b512016-09-06 20:57:50 +0000919 // Let our delegate know we have just exec'd.
920 NotifyDidExec();
921
922 // If we have a main thread, indicate we are stopped.
923 assert(main_thread_sp && "exec called during ptraced process but no main "
924 "thread metadata tracked");
925
926 // Let the process know we're stopped.
927 StopRunningThreads(main_thread_sp->GetID());
928
929 break;
930 }
931
932 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): {
933 // The inferior process or one of its threads is about to exit.
934 // We don't want to do anything with the thread so we just resume it. In
935 // case we
936 // want to implement "break on thread exit" functionality, we would need to
937 // stop
938 // here.
939
940 unsigned long data = 0;
941 if (GetEventMessage(thread.GetID(), &data).Fail())
942 data = -1;
943
944 if (log) {
945 log->Printf("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = "
946 "%lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
947 __FUNCTION__, data, WIFEXITED(data) ? "true" : "false",
948 WIFSIGNALED(data) ? "true" : "false", thread.GetID(),
949 is_main_thread ? "is main thread" : "not main thread");
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000950 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000951
Kate Stoneb9c1b512016-09-06 20:57:50 +0000952 if (is_main_thread) {
953 SetExitStatus(convert_pid_status_to_exit_type(data),
954 convert_pid_status_to_return_code(data), nullptr, true);
955 }
956
957 StateType state = thread.GetState();
958 if (!StateIsRunningState(state)) {
959 // Due to a kernel bug, we may sometimes get this stop after the inferior
960 // gets a
961 // SIGKILL. This confuses our state tracking logic in ResumeThread(),
962 // since normally,
963 // we should not be receiving any ptrace events while the inferior is
964 // stopped. This
965 // makes sure that the inferior is resumed and exits normally.
966 state = eStateRunning;
967 }
968 ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
969
970 break;
971 }
972
973 case 0:
974 case TRAP_TRACE: // We receive this on single stepping.
975 case TRAP_HWBKPT: // We receive this on watchpoint hit
976 {
977 // If a watchpoint was hit, report it
978 uint32_t wp_index;
979 Error error = thread.GetRegisterContext()->GetWatchpointHitIndex(
980 wp_index, (uintptr_t)info.si_addr);
981 if (error.Fail() && log)
982 log->Printf("NativeProcessLinux::%s() "
983 "received error while checking for watchpoint hits, "
984 "pid = %" PRIu64 " error = %s",
985 __FUNCTION__, thread.GetID(), error.AsCString());
986 if (wp_index != LLDB_INVALID_INDEX32) {
987 MonitorWatchpoint(thread, wp_index);
988 break;
989 }
990
991 // Otherwise, report step over
992 MonitorTrace(thread);
993 break;
994 }
995
996 case SI_KERNEL:
Mohit K. Bhakkad35799962015-06-18 04:53:18 +0000997#if defined __mips__
Kate Stoneb9c1b512016-09-06 20:57:50 +0000998 // For mips there is no special signal for watchpoint
999 // So we check for watchpoint in kernel trap
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001000 {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001001 // If a watchpoint was hit, report it
1002 uint32_t wp_index;
1003 Error error = thread.GetRegisterContext()->GetWatchpointHitIndex(
1004 wp_index, LLDB_INVALID_ADDRESS);
1005 if (error.Fail() && log)
1006 log->Printf("NativeProcessLinux::%s() "
1007 "received error while checking for watchpoint hits, "
1008 "pid = %" PRIu64 " error = %s",
1009 __FUNCTION__, thread.GetID(), error.AsCString());
1010 if (wp_index != LLDB_INVALID_INDEX32) {
1011 MonitorWatchpoint(thread, wp_index);
1012 break;
1013 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001014 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001015// NO BREAK
Mohit K. Bhakkad35799962015-06-18 04:53:18 +00001016#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00001017 case TRAP_BRKPT:
1018 MonitorBreakpoint(thread);
1019 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00001020
Kate Stoneb9c1b512016-09-06 20:57:50 +00001021 case SIGTRAP:
1022 case (SIGTRAP | 0x80):
1023 if (log)
1024 log->Printf("NativeProcessLinux::%s() received unknown SIGTRAP system "
1025 "call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming",
1026 __FUNCTION__, GetID(), thread.GetID());
Chaoren Linfa03ad22015-02-03 01:50:42 +00001027
Kate Stoneb9c1b512016-09-06 20:57:50 +00001028 // Ignore these signals until we know more about them.
1029 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
1030 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00001031
Kate Stoneb9c1b512016-09-06 20:57:50 +00001032 default:
1033 assert(false && "Unexpected SIGTRAP code!");
1034 if (log)
1035 log->Printf("NativeProcessLinux::%s() pid %" PRIu64 "tid %" PRIu64
1036 " received unhandled SIGTRAP code: 0x%d",
1037 __FUNCTION__, GetID(), thread.GetID(), info.si_code);
1038 break;
1039 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001040}
1041
Kate Stoneb9c1b512016-09-06 20:57:50 +00001042void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) {
1043 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1044 if (log)
1045 log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64
1046 " (single stepping)",
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001047 __FUNCTION__, thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001048
Kate Stoneb9c1b512016-09-06 20:57:50 +00001049 // This thread is currently stopped.
1050 thread.SetStoppedByTrace();
1051
1052 StopRunningThreads(thread.GetID());
1053}
1054
1055void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) {
1056 Log *log(
1057 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
1058 if (log)
1059 log->Printf(
1060 "NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
1061 __FUNCTION__, thread.GetID());
1062
1063 // Mark the thread as stopped at breakpoint.
1064 thread.SetStoppedByBreakpoint();
1065 Error error = FixupBreakpointPCAsNeeded(thread);
1066 if (error.Fail())
1067 if (log)
1068 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
1069 __FUNCTION__, thread.GetID(), error.AsCString());
1070
1071 if (m_threads_stepping_with_breakpoint.find(thread.GetID()) !=
1072 m_threads_stepping_with_breakpoint.end())
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001073 thread.SetStoppedByTrace();
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001074
Kate Stoneb9c1b512016-09-06 20:57:50 +00001075 StopRunningThreads(thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001076}
1077
Kate Stoneb9c1b512016-09-06 20:57:50 +00001078void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread,
1079 uint32_t wp_index) {
1080 Log *log(
1081 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
1082 if (log)
1083 log->Printf("NativeProcessLinux::%s() received watchpoint event, "
1084 "pid = %" PRIu64 ", wp_index = %" PRIu32,
1085 __FUNCTION__, thread.GetID(), wp_index);
1086
1087 // Mark the thread as stopped at watchpoint.
1088 // The address is at (lldb::addr_t)info->si_addr if we need it.
1089 thread.SetStoppedByWatchpoint(wp_index);
1090
1091 // We need to tell all other running threads before we notify the delegate
1092 // about this stop.
1093 StopRunningThreads(thread.GetID());
1094}
1095
1096void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
1097 NativeThreadLinux &thread, bool exited) {
1098 const int signo = info.si_signo;
1099 const bool is_from_llgs = info.si_pid == getpid();
1100
1101 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1102
1103 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1104 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1105 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
1106 //
1107 // IOW, user generated signals never generate what we consider to be a
1108 // "crash".
1109 //
1110 // Similarly, ACK signals generated by this monitor.
1111
1112 // Handle the signal.
1113 if (info.si_code == SI_TKILL || info.si_code == SI_USER) {
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001114 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001115 log->Printf("NativeProcessLinux::%s() received signal %s (%d) with code "
1116 "%s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
1117 __FUNCTION__, Host::GetSignalAsCString(signo), signo,
1118 (info.si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
1119 info.si_pid, is_from_llgs ? "from llgs" : "not from llgs",
1120 thread.GetID());
1121 }
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001122
Kate Stoneb9c1b512016-09-06 20:57:50 +00001123 // Check for thread stop notification.
1124 if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) {
1125 // This is a tgkill()-based stop.
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001126 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001127 log->Printf("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64
1128 ", thread stopped",
1129 __FUNCTION__, GetID(), thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001130
Kate Stoneb9c1b512016-09-06 20:57:50 +00001131 // Check that we're not already marked with a stop reason.
1132 // Note this thread really shouldn't already be marked as stopped - if we
1133 // were, that would imply that
1134 // the kernel signaled us with the thread stopping which we handled and
1135 // marked as stopped,
1136 // and that, without an intervening resume, we received another stop. It is
1137 // more likely
1138 // that we are missing the marking of a run state somewhere if we find that
1139 // the thread was
1140 // marked as stopped.
1141 const StateType thread_state = thread.GetState();
1142 if (!StateIsStoppedState(thread_state, false)) {
1143 // An inferior thread has stopped because of a SIGSTOP we have sent it.
1144 // Generally, these are not important stops and we don't want to report
1145 // them as
1146 // they are just used to stop other threads when one thread (the one with
1147 // the
1148 // *real* stop reason) hits a breakpoint (watchpoint, etc...). However, in
1149 // the
1150 // case of an asynchronous Interrupt(), this *is* the real stop reason, so
1151 // we
1152 // leave the signal intact if this is the thread that was chosen as the
1153 // triggering thread.
1154 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
1155 if (m_pending_notification_tid == thread.GetID())
1156 thread.SetStoppedBySignal(SIGSTOP, &info);
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001157 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001158 thread.SetStoppedWithNoReason();
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001159
Kate Stoneb9c1b512016-09-06 20:57:50 +00001160 SetCurrentThreadID(thread.GetID());
1161 SignalIfAllThreadsStopped();
1162 } else {
1163 // We can end up here if stop was initiated by LLGS but by this time a
1164 // thread stop has occurred - maybe initiated by another event.
1165 Error error = ResumeThread(thread, thread.GetState(), 0);
1166 if (error.Fail() && log) {
1167 log->Printf(
1168 "NativeProcessLinux::%s failed to resume thread tid %" PRIu64
1169 ": %s",
1170 __FUNCTION__, thread.GetID(), error.AsCString());
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001171 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001172 }
1173 } else {
1174 if (log) {
1175 // Retrieve the signal name if the thread was stopped by a signal.
1176 int stop_signo = 0;
1177 const bool stopped_by_signal = thread.IsStopped(&stop_signo);
1178 const char *signal_name = stopped_by_signal
1179 ? Host::GetSignalAsCString(stop_signo)
1180 : "<not stopped by signal>";
1181 if (!signal_name)
1182 signal_name = "<no-signal-name>";
Todd Fiala58a2f662014-08-12 17:02:07 +00001183
Kate Stoneb9c1b512016-09-06 20:57:50 +00001184 log->Printf("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64
1185 ", thread was already marked as a stopped state (state=%s, "
1186 "signal=%d (%s)), leaving stop signal as is",
1187 __FUNCTION__, GetID(), thread.GetID(),
1188 StateAsCString(thread_state), stop_signo, signal_name);
1189 }
1190 SignalIfAllThreadsStopped();
Todd Fialaaf245d12014-06-30 21:05:18 +00001191 }
1192
Kate Stoneb9c1b512016-09-06 20:57:50 +00001193 // Done handling.
1194 return;
1195 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001196
Kate Stoneb9c1b512016-09-06 20:57:50 +00001197 if (log)
1198 log->Printf("NativeProcessLinux::%s() received signal %s", __FUNCTION__,
1199 Host::GetSignalAsCString(signo));
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001200
Kate Stoneb9c1b512016-09-06 20:57:50 +00001201 // This thread is stopped.
1202 thread.SetStoppedBySignal(signo, &info);
1203
1204 // Send a stop to the debugger after we get all other threads to stop.
1205 StopRunningThreads(thread.GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +00001206}
1207
Tamas Berghammere7708682015-04-22 10:00:23 +00001208namespace {
1209
Kate Stoneb9c1b512016-09-06 20:57:50 +00001210struct EmulatorBaton {
1211 NativeProcessLinux *m_process;
1212 NativeRegisterContext *m_reg_context;
Tamas Berghammere7708682015-04-22 10:00:23 +00001213
Kate Stoneb9c1b512016-09-06 20:57:50 +00001214 // eRegisterKindDWARF -> RegsiterValue
1215 std::unordered_map<uint32_t, RegisterValue> m_register_values;
Pavel Labath6648fcc2015-04-27 09:21:14 +00001216
Kate Stoneb9c1b512016-09-06 20:57:50 +00001217 EmulatorBaton(NativeProcessLinux *process, NativeRegisterContext *reg_context)
1218 : m_process(process), m_reg_context(reg_context) {}
Tamas Berghammere7708682015-04-22 10:00:23 +00001219};
1220
1221} // anonymous namespace
1222
Kate Stoneb9c1b512016-09-06 20:57:50 +00001223static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
1224 const EmulateInstruction::Context &context,
1225 lldb::addr_t addr, void *dst, size_t length) {
1226 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
Tamas Berghammere7708682015-04-22 10:00:23 +00001227
Kate Stoneb9c1b512016-09-06 20:57:50 +00001228 size_t bytes_read;
1229 emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
1230 return bytes_read;
Tamas Berghammere7708682015-04-22 10:00:23 +00001231}
1232
Kate Stoneb9c1b512016-09-06 20:57:50 +00001233static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
1234 const RegisterInfo *reg_info,
1235 RegisterValue &reg_value) {
1236 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
Tamas Berghammere7708682015-04-22 10:00:23 +00001237
Kate Stoneb9c1b512016-09-06 20:57:50 +00001238 auto it = emulator_baton->m_register_values.find(
1239 reg_info->kinds[eRegisterKindDWARF]);
1240 if (it != emulator_baton->m_register_values.end()) {
1241 reg_value = it->second;
1242 return true;
1243 }
1244
1245 // The emulator only fill in the dwarf regsiter numbers (and in some case
1246 // the generic register numbers). Get the full register info from the
1247 // register context based on the dwarf register numbers.
1248 const RegisterInfo *full_reg_info =
1249 emulator_baton->m_reg_context->GetRegisterInfo(
1250 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
1251
1252 Error error =
1253 emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
1254 if (error.Success())
1255 return true;
1256
1257 return false;
1258}
1259
1260static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
1261 const EmulateInstruction::Context &context,
1262 const RegisterInfo *reg_info,
1263 const RegisterValue &reg_value) {
1264 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
1265 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
1266 reg_value;
1267 return true;
1268}
1269
1270static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
1271 const EmulateInstruction::Context &context,
1272 lldb::addr_t addr, const void *dst,
1273 size_t length) {
1274 return length;
1275}
1276
1277static lldb::addr_t ReadFlags(NativeRegisterContext *regsiter_context) {
1278 const RegisterInfo *flags_info = regsiter_context->GetRegisterInfo(
1279 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1280 return regsiter_context->ReadRegisterAsUnsigned(flags_info,
1281 LLDB_INVALID_ADDRESS);
1282}
1283
1284Error NativeProcessLinux::SetupSoftwareSingleStepping(
1285 NativeThreadLinux &thread) {
1286 Error error;
1287 NativeRegisterContextSP register_context_sp = thread.GetRegisterContext();
1288
1289 std::unique_ptr<EmulateInstruction> emulator_ap(
1290 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying,
1291 nullptr));
1292
1293 if (emulator_ap == nullptr)
1294 return Error("Instruction emulator not found!");
1295
1296 EmulatorBaton baton(this, register_context_sp.get());
1297 emulator_ap->SetBaton(&baton);
1298 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
1299 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
1300 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
1301 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
1302
1303 if (!emulator_ap->ReadInstruction())
1304 return Error("Read instruction failed!");
1305
1306 bool emulation_result =
1307 emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
1308
1309 const RegisterInfo *reg_info_pc = register_context_sp->GetRegisterInfo(
1310 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1311 const RegisterInfo *reg_info_flags = register_context_sp->GetRegisterInfo(
1312 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1313
1314 auto pc_it =
1315 baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1316 auto flags_it =
1317 baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
1318
1319 lldb::addr_t next_pc;
1320 lldb::addr_t next_flags;
1321 if (emulation_result) {
1322 assert(pc_it != baton.m_register_values.end() &&
1323 "Emulation was successfull but PC wasn't updated");
1324 next_pc = pc_it->second.GetAsUInt64();
1325
1326 if (flags_it != baton.m_register_values.end())
1327 next_flags = flags_it->second.GetAsUInt64();
1328 else
1329 next_flags = ReadFlags(register_context_sp.get());
1330 } else if (pc_it == baton.m_register_values.end()) {
1331 // Emulate instruction failed and it haven't changed PC. Advance PC
1332 // with the size of the current opcode because the emulation of all
1333 // PC modifying instruction should be successful. The failure most
1334 // likely caused by a not supported instruction which don't modify PC.
1335 next_pc =
1336 register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
1337 next_flags = ReadFlags(register_context_sp.get());
1338 } else {
1339 // The instruction emulation failed after it modified the PC. It is an
1340 // unknown error where we can't continue because the next instruction is
1341 // modifying the PC but we don't know how.
1342 return Error("Instruction emulation failed unexpectedly.");
1343 }
1344
1345 if (m_arch.GetMachine() == llvm::Triple::arm) {
1346 if (next_flags & 0x20) {
1347 // Thumb mode
1348 error = SetSoftwareBreakpoint(next_pc, 2);
1349 } else {
1350 // Arm mode
1351 error = SetSoftwareBreakpoint(next_pc, 4);
Pavel Labath6648fcc2015-04-27 09:21:14 +00001352 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001353 } else if (m_arch.GetMachine() == llvm::Triple::mips64 ||
1354 m_arch.GetMachine() == llvm::Triple::mips64el ||
1355 m_arch.GetMachine() == llvm::Triple::mips ||
1356 m_arch.GetMachine() == llvm::Triple::mipsel)
1357 error = SetSoftwareBreakpoint(next_pc, 4);
1358 else {
1359 // No size hint is given for the next breakpoint
1360 error = SetSoftwareBreakpoint(next_pc, 0);
1361 }
Pavel Labath6648fcc2015-04-27 09:21:14 +00001362
Pavel Labath42eb6902016-10-26 11:13:56 +00001363 // If setting the breakpoint fails because next_pc is out of
1364 // the address space, ignore it and let the debugee segfault.
1365 if (error.GetError() == EIO || error.GetError() == EFAULT) {
Mehdi Amini665be502016-11-11 05:07:57 +00001366 return Error();
Pavel Labath42eb6902016-10-26 11:13:56 +00001367 } else if (error.Fail())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001368 return error;
Tamas Berghammere7708682015-04-22 10:00:23 +00001369
Kate Stoneb9c1b512016-09-06 20:57:50 +00001370 m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001371
Mehdi Amini665be502016-11-11 05:07:57 +00001372 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001373}
1374
1375bool NativeProcessLinux::SupportHardwareSingleStepping() const {
1376 if (m_arch.GetMachine() == llvm::Triple::arm ||
1377 m_arch.GetMachine() == llvm::Triple::mips64 ||
1378 m_arch.GetMachine() == llvm::Triple::mips64el ||
1379 m_arch.GetMachine() == llvm::Triple::mips ||
1380 m_arch.GetMachine() == llvm::Triple::mipsel)
Pavel Labath6648fcc2015-04-27 09:21:14 +00001381 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001382 return true;
Tamas Berghammere7708682015-04-22 10:00:23 +00001383}
1384
Kate Stoneb9c1b512016-09-06 20:57:50 +00001385Error NativeProcessLinux::Resume(const ResumeActionList &resume_actions) {
1386 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1387 if (log)
1388 log->Printf("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__,
1389 GetID());
Tamas Berghammere7708682015-04-22 10:00:23 +00001390
Kate Stoneb9c1b512016-09-06 20:57:50 +00001391 bool software_single_step = !SupportHardwareSingleStepping();
Tamas Berghammere7708682015-04-22 10:00:23 +00001392
Kate Stoneb9c1b512016-09-06 20:57:50 +00001393 if (software_single_step) {
1394 for (auto thread_sp : m_threads) {
1395 assert(thread_sp && "thread list should not contain NULL threads");
Tamas Berghammere7708682015-04-22 10:00:23 +00001396
Kate Stoneb9c1b512016-09-06 20:57:50 +00001397 const ResumeAction *const action =
1398 resume_actions.GetActionForThread(thread_sp->GetID(), true);
1399 if (action == nullptr)
1400 continue;
Tamas Berghammere7708682015-04-22 10:00:23 +00001401
Kate Stoneb9c1b512016-09-06 20:57:50 +00001402 if (action->state == eStateStepping) {
1403 Error error = SetupSoftwareSingleStepping(
1404 static_cast<NativeThreadLinux &>(*thread_sp));
1405 if (error.Fail())
1406 return error;
1407 }
Tamas Berghammere7708682015-04-22 10:00:23 +00001408 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001409 }
1410
1411 for (auto thread_sp : m_threads) {
1412 assert(thread_sp && "thread list should not contain NULL threads");
1413
1414 const ResumeAction *const action =
1415 resume_actions.GetActionForThread(thread_sp->GetID(), true);
1416
1417 if (action == nullptr) {
1418 if (log)
1419 log->Printf(
1420 "NativeProcessLinux::%s no action specified for pid %" PRIu64
1421 " tid %" PRIu64,
1422 __FUNCTION__, GetID(), thread_sp->GetID());
1423 continue;
Tamas Berghammere7708682015-04-22 10:00:23 +00001424 }
1425
Kate Stoneb9c1b512016-09-06 20:57:50 +00001426 if (log) {
1427 log->Printf("NativeProcessLinux::%s processing resume action state %s "
1428 "for pid %" PRIu64 " tid %" PRIu64,
1429 __FUNCTION__, StateAsCString(action->state), GetID(),
1430 thread_sp->GetID());
Tamas Berghammere7708682015-04-22 10:00:23 +00001431 }
1432
Kate Stoneb9c1b512016-09-06 20:57:50 +00001433 switch (action->state) {
1434 case eStateRunning:
1435 case eStateStepping: {
1436 // Run the thread, possibly feeding it the signal.
1437 const int signo = action->signal;
1438 ResumeThread(static_cast<NativeThreadLinux &>(*thread_sp), action->state,
1439 signo);
1440 break;
1441 }
Tamas Berghammere7708682015-04-22 10:00:23 +00001442
Kate Stoneb9c1b512016-09-06 20:57:50 +00001443 case eStateSuspended:
1444 case eStateStopped:
1445 lldbassert(0 && "Unexpected state");
Tamas Berghammere7708682015-04-22 10:00:23 +00001446
Kate Stoneb9c1b512016-09-06 20:57:50 +00001447 default:
1448 return Error("NativeProcessLinux::%s (): unexpected state %s specified "
1449 "for pid %" PRIu64 ", tid %" PRIu64,
1450 __FUNCTION__, StateAsCString(action->state), GetID(),
1451 thread_sp->GetID());
1452 }
1453 }
1454
Mehdi Amini665be502016-11-11 05:07:57 +00001455 return Error();
Tamas Berghammere7708682015-04-22 10:00:23 +00001456}
1457
Kate Stoneb9c1b512016-09-06 20:57:50 +00001458Error NativeProcessLinux::Halt() {
1459 Error error;
1460
1461 if (kill(GetID(), SIGSTOP) != 0)
1462 error.SetErrorToErrno();
1463
1464 return error;
Tamas Berghammere7708682015-04-22 10:00:23 +00001465}
1466
Kate Stoneb9c1b512016-09-06 20:57:50 +00001467Error NativeProcessLinux::Detach() {
1468 Error error;
1469
1470 // Stop monitoring the inferior.
1471 m_sigchld_handle.reset();
1472
1473 // Tell ptrace to detach from the process.
1474 if (GetID() == LLDB_INVALID_PROCESS_ID)
1475 return error;
1476
1477 for (auto thread_sp : m_threads) {
1478 Error e = Detach(thread_sp->GetID());
1479 if (e.Fail())
1480 error =
1481 e; // Save the error, but still attempt to detach from other threads.
1482 }
1483
1484 return error;
1485}
1486
1487Error NativeProcessLinux::Signal(int signo) {
1488 Error error;
1489
1490 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1491 if (log)
1492 log->Printf(
1493 "NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
1494 __FUNCTION__, signo, Host::GetSignalAsCString(signo), GetID());
1495
1496 if (kill(GetID(), signo))
1497 error.SetErrorToErrno();
1498
1499 return error;
1500}
1501
1502Error NativeProcessLinux::Interrupt() {
1503 // Pick a running thread (or if none, a not-dead stopped thread) as
1504 // the chosen thread that will be the stop-reason thread.
1505 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1506
1507 NativeThreadProtocolSP running_thread_sp;
1508 NativeThreadProtocolSP stopped_thread_sp;
1509
1510 if (log)
1511 log->Printf(
1512 "NativeProcessLinux::%s selecting running thread for interrupt target",
1513 __FUNCTION__);
1514
1515 for (auto thread_sp : m_threads) {
1516 // The thread shouldn't be null but lets just cover that here.
1517 if (!thread_sp)
1518 continue;
1519
1520 // If we have a running or stepping thread, we'll call that the
1521 // target of the interrupt.
1522 const auto thread_state = thread_sp->GetState();
1523 if (thread_state == eStateRunning || thread_state == eStateStepping) {
1524 running_thread_sp = thread_sp;
1525 break;
1526 } else if (!stopped_thread_sp && StateIsStoppedState(thread_state, true)) {
1527 // Remember the first non-dead stopped thread. We'll use that as a backup
1528 // if there are no running threads.
1529 stopped_thread_sp = thread_sp;
1530 }
1531 }
1532
1533 if (!running_thread_sp && !stopped_thread_sp) {
1534 Error error("found no running/stepping or live stopped threads as target "
1535 "for interrupt");
Todd Fialaaf245d12014-06-30 21:05:18 +00001536 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001537 log->Printf("NativeProcessLinux::%s skipping due to error: %s",
1538 __FUNCTION__, error.AsCString());
Todd Fialaaf245d12014-06-30 21:05:18 +00001539
1540 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001541 }
1542
1543 NativeThreadProtocolSP deferred_signal_thread_sp =
1544 running_thread_sp ? running_thread_sp : stopped_thread_sp;
1545
1546 if (log)
1547 log->Printf("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64
1548 " chosen for interrupt target",
1549 __FUNCTION__, GetID(),
1550 running_thread_sp ? "running" : "stopped",
1551 deferred_signal_thread_sp->GetID());
1552
1553 StopRunningThreads(deferred_signal_thread_sp->GetID());
1554
Mehdi Amini665be502016-11-11 05:07:57 +00001555 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00001556}
1557
Kate Stoneb9c1b512016-09-06 20:57:50 +00001558Error NativeProcessLinux::Kill() {
1559 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1560 if (log)
1561 log->Printf("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__,
1562 GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +00001563
Kate Stoneb9c1b512016-09-06 20:57:50 +00001564 Error error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001565
Kate Stoneb9c1b512016-09-06 20:57:50 +00001566 switch (m_state) {
1567 case StateType::eStateInvalid:
1568 case StateType::eStateExited:
1569 case StateType::eStateCrashed:
1570 case StateType::eStateDetached:
1571 case StateType::eStateUnloaded:
1572 // Nothing to do - the process is already dead.
1573 if (log)
1574 log->Printf("NativeProcessLinux::%s ignored for PID %" PRIu64
1575 " due to current state: %s",
1576 __FUNCTION__, GetID(), StateAsCString(m_state));
Todd Fialaaf245d12014-06-30 21:05:18 +00001577 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001578
Kate Stoneb9c1b512016-09-06 20:57:50 +00001579 case StateType::eStateConnected:
1580 case StateType::eStateAttaching:
1581 case StateType::eStateLaunching:
1582 case StateType::eStateStopped:
1583 case StateType::eStateRunning:
1584 case StateType::eStateStepping:
1585 case StateType::eStateSuspended:
1586 // We can try to kill a process in these states.
1587 break;
1588 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001589
Kate Stoneb9c1b512016-09-06 20:57:50 +00001590 if (kill(GetID(), SIGKILL) != 0) {
1591 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +00001592 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001593 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001594
Kate Stoneb9c1b512016-09-06 20:57:50 +00001595 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001596}
1597
1598static Error
Kate Stoneb9c1b512016-09-06 20:57:50 +00001599ParseMemoryRegionInfoFromProcMapsLine(const std::string &maps_line,
1600 MemoryRegionInfo &memory_region_info) {
1601 memory_region_info.Clear();
Todd Fialaaf245d12014-06-30 21:05:18 +00001602
Kate Stoneb9c1b512016-09-06 20:57:50 +00001603 StringExtractor line_extractor(maps_line.c_str());
Todd Fialaaf245d12014-06-30 21:05:18 +00001604
Kate Stoneb9c1b512016-09-06 20:57:50 +00001605 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode
1606 // pathname
1607 // perms: rwxp (letter is present if set, '-' if not, final character is
1608 // p=private, s=shared).
Todd Fialaaf245d12014-06-30 21:05:18 +00001609
Kate Stoneb9c1b512016-09-06 20:57:50 +00001610 // Parse out the starting address
1611 lldb::addr_t start_address = line_extractor.GetHexMaxU64(false, 0);
Todd Fialaaf245d12014-06-30 21:05:18 +00001612
Kate Stoneb9c1b512016-09-06 20:57:50 +00001613 // Parse out hyphen separating start and end address from range.
1614 if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != '-'))
1615 return Error(
1616 "malformed /proc/{pid}/maps entry, missing dash between address range");
Todd Fialaaf245d12014-06-30 21:05:18 +00001617
Kate Stoneb9c1b512016-09-06 20:57:50 +00001618 // Parse out the ending address
1619 lldb::addr_t end_address = line_extractor.GetHexMaxU64(false, start_address);
Todd Fialaaf245d12014-06-30 21:05:18 +00001620
Kate Stoneb9c1b512016-09-06 20:57:50 +00001621 // Parse out the space after the address.
1622 if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != ' '))
1623 return Error("malformed /proc/{pid}/maps entry, missing space after range");
Todd Fialaaf245d12014-06-30 21:05:18 +00001624
Kate Stoneb9c1b512016-09-06 20:57:50 +00001625 // Save the range.
1626 memory_region_info.GetRange().SetRangeBase(start_address);
1627 memory_region_info.GetRange().SetRangeEnd(end_address);
Todd Fialaaf245d12014-06-30 21:05:18 +00001628
Kate Stoneb9c1b512016-09-06 20:57:50 +00001629 // Any memory region in /proc/{pid}/maps is by definition mapped into the
1630 // process.
1631 memory_region_info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
Howard Hellyerad007562016-07-07 08:21:28 +00001632
Kate Stoneb9c1b512016-09-06 20:57:50 +00001633 // Parse out each permission entry.
1634 if (line_extractor.GetBytesLeft() < 4)
1635 return Error("malformed /proc/{pid}/maps entry, missing some portion of "
1636 "permissions");
Todd Fialaaf245d12014-06-30 21:05:18 +00001637
Kate Stoneb9c1b512016-09-06 20:57:50 +00001638 // Handle read permission.
1639 const char read_perm_char = line_extractor.GetChar();
1640 if (read_perm_char == 'r')
1641 memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eYes);
1642 else if (read_perm_char == '-')
1643 memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1644 else
1645 return Error("unexpected /proc/{pid}/maps read permission char");
Todd Fialaaf245d12014-06-30 21:05:18 +00001646
Kate Stoneb9c1b512016-09-06 20:57:50 +00001647 // Handle write permission.
1648 const char write_perm_char = line_extractor.GetChar();
1649 if (write_perm_char == 'w')
1650 memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eYes);
1651 else if (write_perm_char == '-')
1652 memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1653 else
1654 return Error("unexpected /proc/{pid}/maps write permission char");
Todd Fialaaf245d12014-06-30 21:05:18 +00001655
Kate Stoneb9c1b512016-09-06 20:57:50 +00001656 // Handle execute permission.
1657 const char exec_perm_char = line_extractor.GetChar();
1658 if (exec_perm_char == 'x')
1659 memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes);
1660 else if (exec_perm_char == '-')
1661 memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1662 else
1663 return Error("unexpected /proc/{pid}/maps exec permission char");
Todd Fialaaf245d12014-06-30 21:05:18 +00001664
Kate Stoneb9c1b512016-09-06 20:57:50 +00001665 line_extractor.GetChar(); // Read the private bit
1666 line_extractor.SkipSpaces(); // Skip the separator
1667 line_extractor.GetHexMaxU64(false, 0); // Read the offset
1668 line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1669 line_extractor.GetChar(); // Read the device id separator
1670 line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1671 line_extractor.SkipSpaces(); // Skip the separator
1672 line_extractor.GetU64(0, 10); // Read the inode number
Tamas Berghammerd7d69f82016-07-22 12:55:35 +00001673
Kate Stoneb9c1b512016-09-06 20:57:50 +00001674 line_extractor.SkipSpaces();
1675 const char *name = line_extractor.Peek();
1676 if (name)
1677 memory_region_info.SetName(name);
Tamas Berghammerd7d69f82016-07-22 12:55:35 +00001678
Mehdi Amini665be502016-11-11 05:07:57 +00001679 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00001680}
1681
Kate Stoneb9c1b512016-09-06 20:57:50 +00001682Error NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr,
1683 MemoryRegionInfo &range_info) {
1684 // FIXME review that the final memory region returned extends to the end of
1685 // the virtual address space,
1686 // with no perms if it is not mapped.
Todd Fialaaf245d12014-06-30 21:05:18 +00001687
Kate Stoneb9c1b512016-09-06 20:57:50 +00001688 // Use an approach that reads memory regions from /proc/{pid}/maps.
1689 // Assume proc maps entries are in ascending order.
1690 // FIXME assert if we find differently.
Todd Fialaaf245d12014-06-30 21:05:18 +00001691
Kate Stoneb9c1b512016-09-06 20:57:50 +00001692 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1693 Error error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001694
Kate Stoneb9c1b512016-09-06 20:57:50 +00001695 if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
1696 // We're done.
1697 error.SetErrorString("unsupported");
Todd Fialaaf245d12014-06-30 21:05:18 +00001698 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001699 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001700
Kate Stoneb9c1b512016-09-06 20:57:50 +00001701 // If our cache is empty, pull the latest. There should always be at least
1702 // one memory region
1703 // if memory region handling is supported.
1704 if (m_mem_region_cache.empty()) {
1705 error = ProcFileReader::ProcessLineByLine(
1706 GetID(), "maps", [&](const std::string &line) -> bool {
1707 MemoryRegionInfo info;
1708 const Error parse_error =
1709 ParseMemoryRegionInfoFromProcMapsLine(line, info);
1710 if (parse_error.Success()) {
1711 m_mem_region_cache.push_back(info);
1712 return true;
1713 } else {
1714 if (log)
1715 log->Printf("NativeProcessLinux::%s failed to parse proc maps "
1716 "line '%s': %s",
1717 __FUNCTION__, line.c_str(), error.AsCString());
1718 return false;
1719 }
1720 });
Todd Fialaaf245d12014-06-30 21:05:18 +00001721
Kate Stoneb9c1b512016-09-06 20:57:50 +00001722 // If we had an error, we'll mark unsupported.
1723 if (error.Fail()) {
1724 m_supports_mem_region = LazyBool::eLazyBoolNo;
1725 return error;
1726 } else if (m_mem_region_cache.empty()) {
1727 // No entries after attempting to read them. This shouldn't happen if
1728 // /proc/{pid}/maps
1729 // is supported. Assume we don't support map entries via procfs.
1730 if (log)
1731 log->Printf("NativeProcessLinux::%s failed to find any procfs maps "
1732 "entries, assuming no support for memory region metadata "
1733 "retrieval",
1734 __FUNCTION__);
1735 m_supports_mem_region = LazyBool::eLazyBoolNo;
1736 error.SetErrorString("not supported");
1737 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001738 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001739
1740 if (log)
1741 log->Printf("NativeProcessLinux::%s read %" PRIu64
1742 " memory region entries from /proc/%" PRIu64 "/maps",
1743 __FUNCTION__,
1744 static_cast<uint64_t>(m_mem_region_cache.size()), GetID());
1745
1746 // We support memory retrieval, remember that.
1747 m_supports_mem_region = LazyBool::eLazyBoolYes;
1748 } else {
1749 if (log)
1750 log->Printf("NativeProcessLinux::%s reusing %" PRIu64
1751 " cached memory region entries",
1752 __FUNCTION__,
1753 static_cast<uint64_t>(m_mem_region_cache.size()));
1754 }
1755
1756 lldb::addr_t prev_base_address = 0;
1757
1758 // FIXME start by finding the last region that is <= target address using
1759 // binary search. Data is sorted.
1760 // There can be a ton of regions on pthreads apps with lots of threads.
1761 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1762 ++it) {
1763 MemoryRegionInfo &proc_entry_info = *it;
1764
1765 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1766 assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
1767 "descending /proc/pid/maps entries detected, unexpected");
1768 prev_base_address = proc_entry_info.GetRange().GetRangeBase();
1769
1770 // If the target address comes before this entry, indicate distance to next
1771 // region.
1772 if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1773 range_info.GetRange().SetRangeBase(load_addr);
1774 range_info.GetRange().SetByteSize(
1775 proc_entry_info.GetRange().GetRangeBase() - load_addr);
1776 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1777 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1778 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1779 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1780
1781 return error;
1782 } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1783 // The target address is within the memory region we're processing here.
1784 range_info = proc_entry_info;
1785 return error;
1786 }
1787
1788 // The target memory address comes somewhere after the region we just
1789 // parsed.
1790 }
1791
1792 // If we made it here, we didn't find an entry that contained the given
1793 // address. Return the
1794 // load_addr as start and the amount of bytes betwwen load address and the end
1795 // of the memory as
1796 // size.
1797 range_info.GetRange().SetRangeBase(load_addr);
1798 range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
1799 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1800 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1801 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1802 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1803 return error;
1804}
1805
1806void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
1807 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1808 if (log)
1809 log->Printf("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called",
1810 __FUNCTION__, newBumpId);
1811
1812 if (log)
1813 log->Printf("NativeProcessLinux::%s clearing %" PRIu64
1814 " entries from the cache",
1815 __FUNCTION__, static_cast<uint64_t>(m_mem_region_cache.size()));
1816 m_mem_region_cache.clear();
1817}
1818
1819Error NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions,
1820 lldb::addr_t &addr) {
1821// FIXME implementing this requires the equivalent of
1822// InferiorCallPOSIX::InferiorCallMmap, which depends on
1823// functional ThreadPlans working with Native*Protocol.
1824#if 1
1825 return Error("not implemented yet");
1826#else
1827 addr = LLDB_INVALID_ADDRESS;
1828
1829 unsigned prot = 0;
1830 if (permissions & lldb::ePermissionsReadable)
1831 prot |= eMmapProtRead;
1832 if (permissions & lldb::ePermissionsWritable)
1833 prot |= eMmapProtWrite;
1834 if (permissions & lldb::ePermissionsExecutable)
1835 prot |= eMmapProtExec;
1836
1837 // TODO implement this directly in NativeProcessLinux
1838 // (and lift to NativeProcessPOSIX if/when that class is
1839 // refactored out).
1840 if (InferiorCallMmap(this, addr, 0, size, prot,
1841 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
1842 m_addr_to_mmap_size[addr] = size;
Mehdi Amini665be502016-11-11 05:07:57 +00001843 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001844 } else {
1845 addr = LLDB_INVALID_ADDRESS;
1846 return Error("unable to allocate %" PRIu64
1847 " bytes of memory with permissions %s",
1848 size, GetPermissionsAsCString(permissions));
1849 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001850#endif
1851}
1852
Kate Stoneb9c1b512016-09-06 20:57:50 +00001853Error NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {
1854 // FIXME see comments in AllocateMemory - required lower-level
1855 // bits not in place yet (ThreadPlans)
1856 return Error("not implemented");
Todd Fialaaf245d12014-06-30 21:05:18 +00001857}
1858
Kate Stoneb9c1b512016-09-06 20:57:50 +00001859lldb::addr_t NativeProcessLinux::GetSharedLibraryInfoAddress() {
1860 // punt on this for now
1861 return LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00001862}
1863
Kate Stoneb9c1b512016-09-06 20:57:50 +00001864size_t NativeProcessLinux::UpdateThreads() {
1865 // The NativeProcessLinux monitoring threads are always up to date
1866 // with respect to thread state and they keep the thread list
1867 // populated properly. All this method needs to do is return the
1868 // thread count.
1869 return m_threads.size();
Todd Fialaaf245d12014-06-30 21:05:18 +00001870}
1871
Kate Stoneb9c1b512016-09-06 20:57:50 +00001872bool NativeProcessLinux::GetArchitecture(ArchSpec &arch) const {
1873 arch = m_arch;
1874 return true;
Todd Fialaaf245d12014-06-30 21:05:18 +00001875}
1876
Kate Stoneb9c1b512016-09-06 20:57:50 +00001877Error NativeProcessLinux::GetSoftwareBreakpointPCOffset(
1878 uint32_t &actual_opcode_size) {
1879 // FIXME put this behind a breakpoint protocol class that can be
1880 // set per architecture. Need ARM, MIPS support here.
1881 static const uint8_t g_i386_opcode[] = {0xCC};
1882 static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
Todd Fialaaf245d12014-06-30 21:05:18 +00001883
Kate Stoneb9c1b512016-09-06 20:57:50 +00001884 switch (m_arch.GetMachine()) {
1885 case llvm::Triple::x86:
1886 case llvm::Triple::x86_64:
1887 actual_opcode_size = static_cast<uint32_t>(sizeof(g_i386_opcode));
Mehdi Amini665be502016-11-11 05:07:57 +00001888 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00001889
Kate Stoneb9c1b512016-09-06 20:57:50 +00001890 case llvm::Triple::systemz:
1891 actual_opcode_size = static_cast<uint32_t>(sizeof(g_s390x_opcode));
Mehdi Amini665be502016-11-11 05:07:57 +00001892 return Error();
Ulrich Weigandbb00d0b2016-04-14 14:28:34 +00001893
Kate Stoneb9c1b512016-09-06 20:57:50 +00001894 case llvm::Triple::arm:
1895 case llvm::Triple::aarch64:
1896 case llvm::Triple::mips64:
1897 case llvm::Triple::mips64el:
1898 case llvm::Triple::mips:
1899 case llvm::Triple::mipsel:
1900 // On these architectures the PC don't get updated for breakpoint hits
1901 actual_opcode_size = 0;
Mehdi Amini665be502016-11-11 05:07:57 +00001902 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001903
1904 default:
1905 assert(false && "CPU type not supported!");
1906 return Error("CPU type not supported");
1907 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001908}
1909
Kate Stoneb9c1b512016-09-06 20:57:50 +00001910Error NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,
1911 bool hardware) {
1912 if (hardware)
1913 return Error("NativeProcessLinux does not support hardware breakpoints");
1914 else
1915 return SetSoftwareBreakpoint(addr, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00001916}
1917
Kate Stoneb9c1b512016-09-06 20:57:50 +00001918Error NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(
1919 size_t trap_opcode_size_hint, size_t &actual_opcode_size,
1920 const uint8_t *&trap_opcode_bytes) {
1921 // FIXME put this behind a breakpoint protocol class that can be set per
1922 // architecture. Need MIPS support here.
1923 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};
1924 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1925 // linux kernel does otherwise.
1926 static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1927 static const uint8_t g_i386_opcode[] = {0xCC};
1928 static const uint8_t g_mips64_opcode[] = {0x00, 0x00, 0x00, 0x0d};
1929 static const uint8_t g_mips64el_opcode[] = {0x0d, 0x00, 0x00, 0x00};
1930 static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
1931 static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
Todd Fialaaf245d12014-06-30 21:05:18 +00001932
Kate Stoneb9c1b512016-09-06 20:57:50 +00001933 switch (m_arch.GetMachine()) {
1934 case llvm::Triple::aarch64:
1935 trap_opcode_bytes = g_aarch64_opcode;
1936 actual_opcode_size = sizeof(g_aarch64_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001937 return Error();
Todd Fiala2afc5962014-08-21 16:42:31 +00001938
Kate Stoneb9c1b512016-09-06 20:57:50 +00001939 case llvm::Triple::arm:
1940 switch (trap_opcode_size_hint) {
1941 case 2:
1942 trap_opcode_bytes = g_thumb_breakpoint_opcode;
1943 actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001944 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001945 case 4:
1946 trap_opcode_bytes = g_arm_breakpoint_opcode;
1947 actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001948 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00001949 default:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001950 assert(false && "Unrecognised trap opcode size hint!");
1951 return Error("Unrecognised trap opcode size hint!");
Todd Fialaaf245d12014-06-30 21:05:18 +00001952 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001953
1954 case llvm::Triple::x86:
1955 case llvm::Triple::x86_64:
1956 trap_opcode_bytes = g_i386_opcode;
1957 actual_opcode_size = sizeof(g_i386_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001958 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001959
1960 case llvm::Triple::mips:
1961 case llvm::Triple::mips64:
1962 trap_opcode_bytes = g_mips64_opcode;
1963 actual_opcode_size = sizeof(g_mips64_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001964 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001965
1966 case llvm::Triple::mipsel:
1967 case llvm::Triple::mips64el:
1968 trap_opcode_bytes = g_mips64el_opcode;
1969 actual_opcode_size = sizeof(g_mips64el_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001970 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001971
1972 case llvm::Triple::systemz:
1973 trap_opcode_bytes = g_s390x_opcode;
1974 actual_opcode_size = sizeof(g_s390x_opcode);
Mehdi Amini665be502016-11-11 05:07:57 +00001975 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001976
1977 default:
1978 assert(false && "CPU type not supported!");
1979 return Error("CPU type not supported");
1980 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001981}
1982
1983#if 0
1984ProcessMessage::CrashReason
1985NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
1986{
1987 ProcessMessage::CrashReason reason;
1988 assert(info->si_signo == SIGSEGV);
1989
1990 reason = ProcessMessage::eInvalidCrashReason;
1991
1992 switch (info->si_code)
1993 {
1994 default:
1995 assert(false && "unexpected si_code for SIGSEGV");
1996 break;
1997 case SI_KERNEL:
1998 // Linux will occasionally send spurious SI_KERNEL codes.
1999 // (this is poorly documented in sigaction)
2000 // One way to get this is via unaligned SIMD loads.
2001 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
2002 break;
2003 case SEGV_MAPERR:
2004 reason = ProcessMessage::eInvalidAddress;
2005 break;
2006 case SEGV_ACCERR:
2007 reason = ProcessMessage::ePrivilegedAddress;
2008 break;
2009 }
2010
2011 return reason;
2012}
2013#endif
2014
Todd Fialaaf245d12014-06-30 21:05:18 +00002015#if 0
2016ProcessMessage::CrashReason
2017NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
2018{
2019 ProcessMessage::CrashReason reason;
2020 assert(info->si_signo == SIGILL);
2021
2022 reason = ProcessMessage::eInvalidCrashReason;
2023
2024 switch (info->si_code)
2025 {
2026 default:
2027 assert(false && "unexpected si_code for SIGILL");
2028 break;
2029 case ILL_ILLOPC:
2030 reason = ProcessMessage::eIllegalOpcode;
2031 break;
2032 case ILL_ILLOPN:
2033 reason = ProcessMessage::eIllegalOperand;
2034 break;
2035 case ILL_ILLADR:
2036 reason = ProcessMessage::eIllegalAddressingMode;
2037 break;
2038 case ILL_ILLTRP:
2039 reason = ProcessMessage::eIllegalTrap;
2040 break;
2041 case ILL_PRVOPC:
2042 reason = ProcessMessage::ePrivilegedOpcode;
2043 break;
2044 case ILL_PRVREG:
2045 reason = ProcessMessage::ePrivilegedRegister;
2046 break;
2047 case ILL_COPROC:
2048 reason = ProcessMessage::eCoprocessorError;
2049 break;
2050 case ILL_BADSTK:
2051 reason = ProcessMessage::eInternalStackError;
2052 break;
2053 }
2054
2055 return reason;
2056}
2057#endif
2058
2059#if 0
2060ProcessMessage::CrashReason
2061NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
2062{
2063 ProcessMessage::CrashReason reason;
2064 assert(info->si_signo == SIGFPE);
2065
2066 reason = ProcessMessage::eInvalidCrashReason;
2067
2068 switch (info->si_code)
2069 {
2070 default:
2071 assert(false && "unexpected si_code for SIGFPE");
2072 break;
2073 case FPE_INTDIV:
2074 reason = ProcessMessage::eIntegerDivideByZero;
2075 break;
2076 case FPE_INTOVF:
2077 reason = ProcessMessage::eIntegerOverflow;
2078 break;
2079 case FPE_FLTDIV:
2080 reason = ProcessMessage::eFloatDivideByZero;
2081 break;
2082 case FPE_FLTOVF:
2083 reason = ProcessMessage::eFloatOverflow;
2084 break;
2085 case FPE_FLTUND:
2086 reason = ProcessMessage::eFloatUnderflow;
2087 break;
2088 case FPE_FLTRES:
2089 reason = ProcessMessage::eFloatInexactResult;
2090 break;
2091 case FPE_FLTINV:
2092 reason = ProcessMessage::eFloatInvalidOperation;
2093 break;
2094 case FPE_FLTSUB:
2095 reason = ProcessMessage::eFloatSubscriptRange;
2096 break;
2097 }
2098
2099 return reason;
2100}
2101#endif
2102
2103#if 0
2104ProcessMessage::CrashReason
2105NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
2106{
2107 ProcessMessage::CrashReason reason;
2108 assert(info->si_signo == SIGBUS);
2109
2110 reason = ProcessMessage::eInvalidCrashReason;
2111
2112 switch (info->si_code)
2113 {
2114 default:
2115 assert(false && "unexpected si_code for SIGBUS");
2116 break;
2117 case BUS_ADRALN:
2118 reason = ProcessMessage::eIllegalAlignment;
2119 break;
2120 case BUS_ADRERR:
2121 reason = ProcessMessage::eIllegalAddress;
2122 break;
2123 case BUS_OBJERR:
2124 reason = ProcessMessage::eHardwareError;
2125 break;
2126 }
2127
2128 return reason;
2129}
2130#endif
2131
Kate Stoneb9c1b512016-09-06 20:57:50 +00002132Error NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
2133 size_t &bytes_read) {
2134 if (ProcessVmReadvSupported()) {
2135 // The process_vm_readv path is about 50 times faster than ptrace api. We
2136 // want to use
2137 // this syscall if it is supported.
Pavel Labathdf7c6992015-06-17 18:38:49 +00002138
Kate Stoneb9c1b512016-09-06 20:57:50 +00002139 const ::pid_t pid = GetID();
Pavel Labathdf7c6992015-06-17 18:38:49 +00002140
Kate Stoneb9c1b512016-09-06 20:57:50 +00002141 struct iovec local_iov, remote_iov;
2142 local_iov.iov_base = buf;
2143 local_iov.iov_len = size;
2144 remote_iov.iov_base = reinterpret_cast<void *>(addr);
2145 remote_iov.iov_len = size;
Pavel Labathdf7c6992015-06-17 18:38:49 +00002146
Kate Stoneb9c1b512016-09-06 20:57:50 +00002147 bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
2148 const bool success = bytes_read == size;
Pavel Labathdf7c6992015-06-17 18:38:49 +00002149
Kate Stoneb9c1b512016-09-06 20:57:50 +00002150 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labath19cbe962015-07-21 13:20:32 +00002151 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002152 log->Printf("NativeProcessLinux::%s using process_vm_readv to read %zd "
2153 "bytes from inferior address 0x%" PRIx64 ": %s",
2154 __FUNCTION__, size, addr,
2155 success ? "Success" : strerror(errno));
Pavel Labath19cbe962015-07-21 13:20:32 +00002156
Kate Stoneb9c1b512016-09-06 20:57:50 +00002157 if (success)
Mehdi Amini665be502016-11-11 05:07:57 +00002158 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002159 // else
2160 // the call failed for some reason, let's retry the read using ptrace
2161 // api.
2162 }
Pavel Labath19cbe962015-07-21 13:20:32 +00002163
Kate Stoneb9c1b512016-09-06 20:57:50 +00002164 unsigned char *dst = static_cast<unsigned char *>(buf);
2165 size_t remainder;
2166 long data;
Pavel Labath19cbe962015-07-21 13:20:32 +00002167
Kate Stoneb9c1b512016-09-06 20:57:50 +00002168 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_ALL));
2169 if (log)
2170 ProcessPOSIXLog::IncNestLevel();
2171 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2172 log->GetMask().Test(POSIX_LOG_MEMORY))
2173 log->Printf("NativeProcessLinux::%s(%p, %p, %zd, _)", __FUNCTION__,
2174 (void *)addr, buf, size);
Pavel Labath19cbe962015-07-21 13:20:32 +00002175
Kate Stoneb9c1b512016-09-06 20:57:50 +00002176 for (bytes_read = 0; bytes_read < size; bytes_read += remainder) {
2177 Error error = NativeProcessLinux::PtraceWrapper(
2178 PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data);
2179 if (error.Fail()) {
2180 if (log)
Pavel Labath19cbe962015-07-21 13:20:32 +00002181 ProcessPOSIXLog::DecNestLevel();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002182 return error;
2183 }
2184
2185 remainder = size - bytes_read;
2186 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
2187
2188 // Copy the data into our buffer
2189 memcpy(dst, &data, remainder);
2190
2191 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2192 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
2193 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2194 size <= POSIX_LOG_MEMORY_SHORT_BYTES))) {
2195 uintptr_t print_dst = 0;
2196 // Format bytes from data by moving into print_dst for log output
2197 for (unsigned i = 0; i < remainder; ++i)
2198 print_dst |= (((data >> i * 8) & 0xFF) << i * 8);
2199 log->Printf("NativeProcessLinux::%s() [0x%" PRIx64 "]:0x%" PRIx64
2200 " (0x%" PRIx64 ")",
2201 __FUNCTION__, addr, uint64_t(print_dst), uint64_t(data));
2202 }
2203 addr += k_ptrace_word_size;
2204 dst += k_ptrace_word_size;
2205 }
2206
2207 if (log)
2208 ProcessPOSIXLog::DecNestLevel();
Mehdi Amini665be502016-11-11 05:07:57 +00002209 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00002210}
2211
Kate Stoneb9c1b512016-09-06 20:57:50 +00002212Error NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf,
2213 size_t size,
2214 size_t &bytes_read) {
2215 Error error = ReadMemory(addr, buf, size, bytes_read);
2216 if (error.Fail())
Pavel Labath19cbe962015-07-21 13:20:32 +00002217 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002218 return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00002219}
2220
Kate Stoneb9c1b512016-09-06 20:57:50 +00002221Error NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,
2222 size_t size, size_t &bytes_written) {
2223 const unsigned char *src = static_cast<const unsigned char *>(buf);
2224 size_t remainder;
2225 Error error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002226
Kate Stoneb9c1b512016-09-06 20:57:50 +00002227 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_ALL));
2228 if (log)
2229 ProcessPOSIXLog::IncNestLevel();
2230 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2231 log->GetMask().Test(POSIX_LOG_MEMORY))
2232 log->Printf("NativeProcessLinux::%s(0x%" PRIx64 ", %p, %zu)", __FUNCTION__,
2233 addr, buf, size);
Todd Fialaaf245d12014-06-30 21:05:18 +00002234
Kate Stoneb9c1b512016-09-06 20:57:50 +00002235 for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
2236 remainder = size - bytes_written;
2237 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
Chaoren Lin97ccc292015-02-03 01:51:12 +00002238
Kate Stoneb9c1b512016-09-06 20:57:50 +00002239 if (remainder == k_ptrace_word_size) {
2240 unsigned long data = 0;
2241 memcpy(&data, src, k_ptrace_word_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00002242
Kate Stoneb9c1b512016-09-06 20:57:50 +00002243 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2244 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
2245 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2246 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
2247 log->Printf("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
2248 (void *)addr, *(const unsigned long *)src, data);
2249
2250 error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(),
2251 (void *)addr, (void *)data);
2252 if (error.Fail()) {
2253 if (log)
2254 ProcessPOSIXLog::DecNestLevel();
2255 return error;
2256 }
2257 } else {
2258 unsigned char buff[8];
2259 size_t bytes_read;
2260 error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
2261 if (error.Fail()) {
2262 if (log)
2263 ProcessPOSIXLog::DecNestLevel();
2264 return error;
2265 }
2266
2267 memcpy(buff, src, remainder);
2268
2269 size_t bytes_written_rec;
2270 error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
2271 if (error.Fail()) {
2272 if (log)
2273 ProcessPOSIXLog::DecNestLevel();
2274 return error;
2275 }
2276
2277 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2278 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
2279 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2280 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
2281 log->Printf("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
2282 (void *)addr, *(const unsigned long *)src,
2283 *(unsigned long *)buff);
Todd Fialaaf245d12014-06-30 21:05:18 +00002284 }
2285
Kate Stoneb9c1b512016-09-06 20:57:50 +00002286 addr += k_ptrace_word_size;
2287 src += k_ptrace_word_size;
2288 }
2289 if (log)
2290 ProcessPOSIXLog::DecNestLevel();
2291 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002292}
2293
Kate Stoneb9c1b512016-09-06 20:57:50 +00002294Error NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) {
2295 return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
2296}
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002297
Kate Stoneb9c1b512016-09-06 20:57:50 +00002298Error NativeProcessLinux::GetEventMessage(lldb::tid_t tid,
2299 unsigned long *message) {
2300 return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
2301}
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002302
Kate Stoneb9c1b512016-09-06 20:57:50 +00002303Error NativeProcessLinux::Detach(lldb::tid_t tid) {
2304 if (tid == LLDB_INVALID_THREAD_ID)
Mehdi Amini665be502016-11-11 05:07:57 +00002305 return Error();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002306
Kate Stoneb9c1b512016-09-06 20:57:50 +00002307 return PtraceWrapper(PTRACE_DETACH, tid);
2308}
2309
2310bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {
2311 for (auto thread_sp : m_threads) {
2312 assert(thread_sp && "thread list should not contain NULL threads");
2313 if (thread_sp->GetID() == thread_id) {
2314 // We have this thread.
2315 return true;
Todd Fialaaf245d12014-06-30 21:05:18 +00002316 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002317 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002318
Kate Stoneb9c1b512016-09-06 20:57:50 +00002319 // We don't have this thread.
2320 return false;
Todd Fialaaf245d12014-06-30 21:05:18 +00002321}
2322
Kate Stoneb9c1b512016-09-06 20:57:50 +00002323bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) {
2324 Log *const log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD);
Todd Fialaaf245d12014-06-30 21:05:18 +00002325
Kate Stoneb9c1b512016-09-06 20:57:50 +00002326 if (log)
2327 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__,
Todd Fialaaf245d12014-06-30 21:05:18 +00002328 thread_id);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002329
2330 bool found = false;
2331
2332 for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
2333 if (*it && ((*it)->GetID() == thread_id)) {
2334 m_threads.erase(it);
2335 found = true;
2336 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00002337 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002338 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002339
Kate Stoneb9c1b512016-09-06 20:57:50 +00002340 SignalIfAllThreadsStopped();
Todd Fialaaf245d12014-06-30 21:05:18 +00002341
Kate Stoneb9c1b512016-09-06 20:57:50 +00002342 return found;
Todd Fialaaf245d12014-06-30 21:05:18 +00002343}
2344
Kate Stoneb9c1b512016-09-06 20:57:50 +00002345NativeThreadLinuxSP NativeProcessLinux::AddThread(lldb::tid_t thread_id) {
2346 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD));
Todd Fialaaf245d12014-06-30 21:05:18 +00002347
Kate Stoneb9c1b512016-09-06 20:57:50 +00002348 if (log) {
2349 log->Printf("NativeProcessLinux::%s pid %" PRIu64
2350 " adding thread with tid %" PRIu64,
2351 __FUNCTION__, GetID(), thread_id);
2352 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002353
Kate Stoneb9c1b512016-09-06 20:57:50 +00002354 assert(!HasThreadNoLock(thread_id) &&
2355 "attempted to add a thread by id that already exists");
Todd Fialaaf245d12014-06-30 21:05:18 +00002356
Kate Stoneb9c1b512016-09-06 20:57:50 +00002357 // If this is the first thread, save it as the current thread
2358 if (m_threads.empty())
2359 SetCurrentThreadID(thread_id);
Todd Fialaaf245d12014-06-30 21:05:18 +00002360
Kate Stoneb9c1b512016-09-06 20:57:50 +00002361 auto thread_sp = std::make_shared<NativeThreadLinux>(this, thread_id);
2362 m_threads.push_back(thread_sp);
2363 return thread_sp;
2364}
Todd Fialaaf245d12014-06-30 21:05:18 +00002365
Kate Stoneb9c1b512016-09-06 20:57:50 +00002366Error NativeProcessLinux::FixupBreakpointPCAsNeeded(NativeThreadLinux &thread) {
2367 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
Todd Fialaaf245d12014-06-30 21:05:18 +00002368
Kate Stoneb9c1b512016-09-06 20:57:50 +00002369 Error error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002370
Kate Stoneb9c1b512016-09-06 20:57:50 +00002371 // Find out the size of a breakpoint (might depend on where we are in the
2372 // code).
2373 NativeRegisterContextSP context_sp = thread.GetRegisterContext();
2374 if (!context_sp) {
2375 error.SetErrorString("cannot get a NativeRegisterContext for the thread");
Todd Fialaaf245d12014-06-30 21:05:18 +00002376 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002377 log->Printf("NativeProcessLinux::%s failed: %s", __FUNCTION__,
2378 error.AsCString());
Todd Fialaaf245d12014-06-30 21:05:18 +00002379 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002380 }
Chaoren Linfa03ad22015-02-03 01:50:42 +00002381
Kate Stoneb9c1b512016-09-06 20:57:50 +00002382 uint32_t breakpoint_size = 0;
2383 error = GetSoftwareBreakpointPCOffset(breakpoint_size);
2384 if (error.Fail()) {
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002385 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002386 log->Printf("NativeProcessLinux::%s GetBreakpointSize() failed: %s",
2387 __FUNCTION__, error.AsCString());
2388 return error;
2389 } else {
2390 if (log)
2391 log->Printf("NativeProcessLinux::%s breakpoint size: %" PRIu32,
2392 __FUNCTION__, breakpoint_size);
2393 }
Pavel Labathc0765592015-05-06 10:46:34 +00002394
Kate Stoneb9c1b512016-09-06 20:57:50 +00002395 // First try probing for a breakpoint at a software breakpoint location: PC -
2396 // breakpoint size.
2397 const lldb::addr_t initial_pc_addr =
2398 context_sp->GetPCfromBreakpointLocation();
2399 lldb::addr_t breakpoint_addr = initial_pc_addr;
2400 if (breakpoint_size > 0) {
2401 // Do not allow breakpoint probe to wrap around.
2402 if (breakpoint_addr >= breakpoint_size)
2403 breakpoint_addr -= breakpoint_size;
2404 }
2405
2406 // Check if we stopped because of a breakpoint.
2407 NativeBreakpointSP breakpoint_sp;
2408 error = m_breakpoint_list.GetBreakpoint(breakpoint_addr, breakpoint_sp);
2409 if (!error.Success() || !breakpoint_sp) {
2410 // We didn't find one at a software probe location. Nothing to do.
2411 if (log)
2412 log->Printf(
2413 "NativeProcessLinux::%s pid %" PRIu64
2414 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64,
2415 __FUNCTION__, GetID(), breakpoint_addr);
Mehdi Amini665be502016-11-11 05:07:57 +00002416 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002417 }
2418
2419 // If the breakpoint is not a software breakpoint, nothing to do.
2420 if (!breakpoint_sp->IsSoftwareBreakpoint()) {
2421 if (log)
2422 log->Printf("NativeProcessLinux::%s pid %" PRIu64
2423 " breakpoint found at 0x%" PRIx64
2424 ", not software, nothing to adjust",
2425 __FUNCTION__, GetID(), breakpoint_addr);
Mehdi Amini665be502016-11-11 05:07:57 +00002426 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002427 }
2428
2429 //
2430 // We have a software breakpoint and need to adjust the PC.
2431 //
2432
2433 // Sanity check.
2434 if (breakpoint_size == 0) {
2435 // Nothing to do! How did we get here?
2436 if (log)
2437 log->Printf(
2438 "NativeProcessLinux::%s pid %" PRIu64
2439 " breakpoint found at 0x%" PRIx64
2440 ", it is software, but the size is zero, nothing to do (unexpected)",
2441 __FUNCTION__, GetID(), breakpoint_addr);
Mehdi Amini665be502016-11-11 05:07:57 +00002442 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002443 }
2444
2445 // Change the program counter.
2446 if (log)
2447 log->Printf("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64
2448 ": changing PC from 0x%" PRIx64 " to 0x%" PRIx64,
2449 __FUNCTION__, GetID(), thread.GetID(), initial_pc_addr,
2450 breakpoint_addr);
2451
2452 error = context_sp->SetPC(breakpoint_addr);
2453 if (error.Fail()) {
2454 if (log)
2455 log->Printf("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64
2456 ": failed to set PC: %s",
2457 __FUNCTION__, GetID(), thread.GetID(), error.AsCString());
2458 return error;
2459 }
2460
2461 return error;
2462}
2463
2464Error NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,
2465 FileSpec &file_spec) {
2466 FileSpec module_file_spec(module_path, true);
2467
2468 bool found = false;
2469 file_spec.Clear();
2470 ProcFileReader::ProcessLineByLine(
2471 GetID(), "maps", [&](const std::string &line) {
2472 SmallVector<StringRef, 16> columns;
2473 StringRef(line).split(columns, " ", -1, false);
2474 if (columns.size() < 6)
2475 return true; // continue searching
2476
Malcolm Parsons771ef6d2016-11-02 20:34:10 +00002477 FileSpec this_file_spec(columns[5].str(), false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002478 if (this_file_spec.GetFilename() != module_file_spec.GetFilename())
2479 return true; // continue searching
2480
2481 file_spec = this_file_spec;
2482 found = true;
2483 return false; // we are done
2484 });
2485
2486 if (!found)
2487 return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
2488 module_file_spec.GetFilename().AsCString(), GetID());
2489
Mehdi Amini665be502016-11-11 05:07:57 +00002490 return Error();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002491}
2492
2493Error NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
2494 lldb::addr_t &load_addr) {
2495 load_addr = LLDB_INVALID_ADDRESS;
2496 Error error = ProcFileReader::ProcessLineByLine(
2497 GetID(), "maps", [&](const std::string &line) -> bool {
2498 StringRef maps_row(line);
2499
2500 SmallVector<StringRef, 16> maps_columns;
2501 maps_row.split(maps_columns, StringRef(" "), -1, false);
2502
2503 if (maps_columns.size() < 6) {
2504 // Return true to continue reading the proc file
2505 return true;
2506 }
2507
2508 if (maps_columns[5] == file_name) {
2509 StringExtractor addr_extractor(maps_columns[0].str().c_str());
2510 load_addr = addr_extractor.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2511
2512 // Return false to stop reading the proc file further
2513 return false;
2514 }
2515
2516 // Return true to continue reading the proc file
2517 return true;
2518 });
2519 return error;
2520}
2521
2522NativeThreadLinuxSP NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {
2523 return std::static_pointer_cast<NativeThreadLinux>(
2524 NativeProcessProtocol::GetThreadByID(tid));
2525}
2526
2527Error NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,
2528 lldb::StateType state, int signo) {
2529 Log *const log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD);
2530
2531 if (log)
2532 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__,
2533 thread.GetID());
2534
2535 // Before we do the resume below, first check if we have a pending
2536 // stop notification that is currently waiting for
2537 // all threads to stop. This is potentially a buggy situation since
2538 // we're ostensibly waiting for threads to stop before we send out the
2539 // pending notification, and here we are resuming one before we send
2540 // out the pending stop notification.
2541 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID && log) {
2542 log->Printf("NativeProcessLinux::%s about to resume tid %" PRIu64
2543 " per explicit request but we have a pending stop notification "
2544 "(tid %" PRIu64 ") that is actively waiting for this thread to "
2545 "stop. Valid sequence of events?",
2546 __FUNCTION__, thread.GetID(), m_pending_notification_tid);
2547 }
2548
2549 // Request a resume. We expect this to be synchronous and the system
2550 // to reflect it is running after this completes.
2551 switch (state) {
2552 case eStateRunning: {
2553 const auto resume_result = thread.Resume(signo);
2554 if (resume_result.Success())
2555 SetState(eStateRunning, true);
2556 return resume_result;
2557 }
2558 case eStateStepping: {
2559 const auto step_result = thread.SingleStep(signo);
2560 if (step_result.Success())
2561 SetState(eStateRunning, true);
2562 return step_result;
2563 }
2564 default:
2565 if (log)
2566 log->Printf("NativeProcessLinux::%s Unhandled state %s.", __FUNCTION__,
2567 StateAsCString(state));
2568 llvm_unreachable("Unhandled state for resume");
2569 }
Pavel Labathc0765592015-05-06 10:46:34 +00002570}
2571
2572//===----------------------------------------------------------------------===//
2573
Kate Stoneb9c1b512016-09-06 20:57:50 +00002574void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {
2575 Log *const log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00002576
Kate Stoneb9c1b512016-09-06 20:57:50 +00002577 if (log) {
2578 log->Printf("NativeProcessLinux::%s about to process event: "
2579 "(triggering_tid: %" PRIu64 ")",
Pavel Labathc0765592015-05-06 10:46:34 +00002580 __FUNCTION__, triggering_tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002581 }
2582
2583 m_pending_notification_tid = triggering_tid;
2584
2585 // Request a stop for all the thread stops that need to be stopped
2586 // and are not already known to be stopped.
2587 for (const auto &thread_sp : m_threads) {
2588 if (StateIsRunningState(thread_sp->GetState()))
2589 static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
2590 }
2591
2592 SignalIfAllThreadsStopped();
2593
2594 if (log) {
2595 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
2596 }
2597}
2598
2599void NativeProcessLinux::SignalIfAllThreadsStopped() {
2600 if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
2601 return; // No pending notification. Nothing to do.
2602
2603 for (const auto &thread_sp : m_threads) {
2604 if (StateIsRunningState(thread_sp->GetState()))
2605 return; // Some threads are still running. Don't signal yet.
2606 }
2607
2608 // We have a pending notification and all threads have stopped.
2609 Log *log(
2610 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
2611
2612 // Clear any temporary breakpoints we used to implement software single
2613 // stepping.
2614 for (const auto &thread_info : m_threads_stepping_with_breakpoint) {
2615 Error error = RemoveBreakpoint(thread_info.second);
2616 if (error.Fail())
2617 if (log)
2618 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64
2619 " remove stepping breakpoint: %s",
2620 __FUNCTION__, thread_info.first, error.AsCString());
2621 }
2622 m_threads_stepping_with_breakpoint.clear();
2623
2624 // Notify the delegate about the stop
2625 SetCurrentThreadID(m_pending_notification_tid);
2626 SetState(StateType::eStateStopped, true);
2627 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
2628}
2629
2630void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {
2631 Log *const log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD);
2632
2633 if (log)
2634 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__,
2635 thread.GetID());
2636
2637 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID &&
2638 StateIsRunningState(thread.GetState())) {
2639 // We will need to wait for this new thread to stop as well before firing
2640 // the
2641 // notification.
2642 thread.RequestStop();
2643 }
2644}
2645
2646void NativeProcessLinux::SigchldHandler() {
2647 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2648 // Process all pending waitpid notifications.
2649 while (true) {
2650 int status = -1;
2651 ::pid_t wait_pid = waitpid(-1, &status, __WALL | __WNOTHREAD | WNOHANG);
2652
2653 if (wait_pid == 0)
2654 break; // We are done.
2655
2656 if (wait_pid == -1) {
2657 if (errno == EINTR)
2658 continue;
2659
2660 Error error(errno, eErrorTypePOSIX);
2661 if (log)
2662 log->Printf("NativeProcessLinux::%s waitpid (-1, &status, __WALL | "
2663 "__WNOTHREAD | WNOHANG) failed: %s",
2664 __FUNCTION__, error.AsCString());
2665 break;
Pavel Labathc0765592015-05-06 10:46:34 +00002666 }
2667
Kate Stoneb9c1b512016-09-06 20:57:50 +00002668 bool exited = false;
2669 int signal = 0;
2670 int exit_status = 0;
2671 const char *status_cstr = nullptr;
2672 if (WIFSTOPPED(status)) {
2673 signal = WSTOPSIG(status);
2674 status_cstr = "STOPPED";
2675 } else if (WIFEXITED(status)) {
2676 exit_status = WEXITSTATUS(status);
2677 status_cstr = "EXITED";
2678 exited = true;
2679 } else if (WIFSIGNALED(status)) {
2680 signal = WTERMSIG(status);
2681 status_cstr = "SIGNALED";
2682 if (wait_pid == static_cast<::pid_t>(GetID())) {
2683 exited = true;
2684 exit_status = -1;
2685 }
2686 } else
2687 status_cstr = "(\?\?\?)";
Pavel Labathc0765592015-05-06 10:46:34 +00002688
Pavel Labath5eb721e2015-05-07 08:30:31 +00002689 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002690 log->Printf("NativeProcessLinux::%s: waitpid (-1, &status, __WALL | "
2691 "__WNOTHREAD | WNOHANG)"
2692 "=> pid = %" PRIi32
2693 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
2694 __FUNCTION__, wait_pid, status, status_cstr, signal,
2695 exit_status);
Pavel Labathc0765592015-05-06 10:46:34 +00002696
Kate Stoneb9c1b512016-09-06 20:57:50 +00002697 MonitorCallback(wait_pid, exited, signal, exit_status);
2698 }
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002699}
2700
2701// Wrapper for ptrace to catch errors and log calls.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002702// Note that ptrace sets errno on error because -1 can be a valid result (i.e.
2703// for PTRACE_PEEK*)
2704Error NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
2705 void *data, size_t data_size,
2706 long *result) {
2707 Error error;
2708 long int ret;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002709
Kate Stoneb9c1b512016-09-06 20:57:50 +00002710 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002711
Kate Stoneb9c1b512016-09-06 20:57:50 +00002712 PtraceDisplayBytes(req, data, data_size);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002713
Kate Stoneb9c1b512016-09-06 20:57:50 +00002714 errno = 0;
2715 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
2716 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2717 *(unsigned int *)addr, data);
2718 else
2719 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2720 addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002721
Kate Stoneb9c1b512016-09-06 20:57:50 +00002722 if (ret == -1)
2723 error.SetErrorToErrno();
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002724
Kate Stoneb9c1b512016-09-06 20:57:50 +00002725 if (result)
2726 *result = ret;
Pavel Labath4a9babb2015-06-30 17:04:49 +00002727
Kate Stoneb9c1b512016-09-06 20:57:50 +00002728 if (log)
2729 log->Printf("ptrace(%d, %" PRIu64 ", %p, %p, %zu)=%lX", req, pid, addr,
2730 data, data_size, ret);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002731
Kate Stoneb9c1b512016-09-06 20:57:50 +00002732 PtraceDisplayBytes(req, data, data_size);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002733
Kate Stoneb9c1b512016-09-06 20:57:50 +00002734 if (log && error.GetError() != 0) {
2735 const char *str;
2736 switch (error.GetError()) {
2737 case ESRCH:
2738 str = "ESRCH";
2739 break;
2740 case EINVAL:
2741 str = "EINVAL";
2742 break;
2743 case EBUSY:
2744 str = "EBUSY";
2745 break;
2746 case EPERM:
2747 str = "EPERM";
2748 break;
2749 default:
2750 str = error.AsCString();
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002751 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002752 log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
2753 }
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002754
Kate Stoneb9c1b512016-09-06 20:57:50 +00002755 return error;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002756}