blob: 665b257535645e0f4b332661f83fca32bd9df7e3 [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 <string.h>
15#include <stdint.h>
16#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"
Zachary Turner39de3112014-09-09 20:54:56 +000032#include "lldb/Host/ThreadLauncher.h"
Pavel Labath2a86b552016-06-14 17:30:52 +000033#include "lldb/Host/common/NativeBreakpoint.h"
34#include "lldb/Host/common/NativeRegisterContext.h"
35#include "lldb/Symbol/ObjectFile.h"
Zachary Turner90aff472015-03-03 23:36:51 +000036#include "lldb/Target/Process.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000037#include "lldb/Target/ProcessLaunchInfo.h"
Pavel Labath5b981ab2015-05-29 12:53:54 +000038#include "lldb/Target/Target.h"
Chaoren Linc16f5dc2015-03-19 23:28:10 +000039#include "lldb/Utility/LLDBAssert.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000040#include "lldb/Utility/PseudoTerminal.h"
Pavel Labathf805e192015-07-07 10:08:41 +000041#include "lldb/Utility/StringExtractor.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000042
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000043#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000044#include "NativeThreadLinux.h"
45#include "ProcFileReader.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000046#include "Procfs.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000047
Tamas Berghammerd8584872015-02-06 10:57:40 +000048// System includes - They have to be included after framework includes because they define some
49// macros which collide with variable names in other modules
50#include <linux/unistd.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000051#include <sys/socket.h>
Vince Harron8b335672015-05-12 01:10:56 +000052
Pavel Labathdf7c6992015-06-17 18:38:49 +000053#include <sys/syscall.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000054#include <sys/types.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000055#include <sys/user.h>
56#include <sys/wait.h>
57
Vince Harron8b335672015-05-12 01:10:56 +000058#include "lldb/Host/linux/Personality.h"
59#include "lldb/Host/linux/Ptrace.h"
Pavel Labathdf7c6992015-06-17 18:38:49 +000060#include "lldb/Host/linux/Uio.h"
Vince Harron8b335672015-05-12 01:10:56 +000061#include "lldb/Host/android/Android.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000062
Todd Fiala0bce1b62014-08-17 00:10:50 +000063#define LLDB_PERSONALITY_GET_CURRENT_SETTINGS 0xffffffff
Todd Fialaaf245d12014-06-30 21:05:18 +000064
65// Support hardware breakpoints in case it has not been defined
66#ifndef TRAP_HWBKPT
67 #define TRAP_HWBKPT 4
68#endif
69
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000070using namespace lldb;
71using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000072using namespace lldb_private::process_linux;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000073using namespace llvm;
74
Todd Fialaaf245d12014-06-30 21:05:18 +000075// Private bits we only need internally.
Pavel Labathdf7c6992015-06-17 18:38:49 +000076
77static bool ProcessVmReadvSupported()
78{
79 static bool is_supported;
80 static std::once_flag flag;
81
82 std::call_once(flag, [] {
83 Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
84
85 uint32_t source = 0x47424742;
86 uint32_t dest = 0;
87
88 struct iovec local, remote;
89 remote.iov_base = &source;
90 local.iov_base = &dest;
91 remote.iov_len = local.iov_len = sizeof source;
92
93 // We shall try if cross-process-memory reads work by attempting to read a value from our own process.
94 ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
95 is_supported = (res == sizeof(source) && source == dest);
96 if (log)
97 {
98 if (is_supported)
99 log->Printf("%s: Detected kernel support for process_vm_readv syscall. Fast memory reads enabled.",
100 __FUNCTION__);
101 else
102 log->Printf("%s: syscall process_vm_readv failed (error: %s). Fast memory reads disabled.",
103 __FUNCTION__, strerror(errno));
104 }
105 });
106
107 return is_supported;
108}
109
Todd Fialaaf245d12014-06-30 21:05:18 +0000110namespace
111{
Pavel Labath2a86b552016-06-14 17:30:52 +0000112Error
113ResolveProcessArchitecture(lldb::pid_t pid, ArchSpec &arch)
114{
115 // Grab process info for the running process.
116 ProcessInstanceInfo process_info;
117 if (!Host::GetProcessInfo(pid, process_info))
118 return Error("failed to get process info");
Todd Fialaaf245d12014-06-30 21:05:18 +0000119
Pavel Labath2a86b552016-06-14 17:30:52 +0000120 // Resolve the executable module.
121 ModuleSpecList module_specs;
122 if (!ObjectFile::GetModuleSpecifications(process_info.GetExecutableFile(), 0, 0, module_specs))
123 return Error("failed to get module specifications");
124 assert(module_specs.GetSize() == 1);
Todd Fialaaf245d12014-06-30 21:05:18 +0000125
Pavel Labath2a86b552016-06-14 17:30:52 +0000126 arch = module_specs.GetModuleSpecRefAtIndex(0).GetArchitecture();
127 if (arch.IsValid())
128 return Error();
129 else
130 return Error("failed to retrieve a valid architecture from the exe module");
131}
Todd Fialaaf245d12014-06-30 21:05:18 +0000132
Pavel Labath0c4f01d2016-07-06 13:18:50 +0000133// Used to notify the parent about which part of the launch sequence failed.
134enum LaunchCallSpecifier
135{
136 ePtraceFailed,
137 eDupStdinFailed,
138 eDupStdoutFailed,
139 eDupStderrFailed,
140 eChdirFailed,
141 eExecFailed,
142 eSetGidFailed,
143 eSetSigMaskFailed,
144 eLaunchCallMax = eSetSigMaskFailed
145};
146
147static uint8_t LLVM_ATTRIBUTE_NORETURN
148ExitChildAbnormally(LaunchCallSpecifier spec)
149{
150 static_assert(eLaunchCallMax < 0x8, "Have more launch calls than we are able to represent");
151 // This may truncate the topmost bits of the errno because the exit code is only 8 bits wide.
152 // However, it should still give us a pretty good indication of what went wrong. (And the
153 // most common errors have small numbers anyway).
154 _exit(unsigned(spec) | (errno << 3));
155}
156
157// The second member is the errno (or its 5 lowermost bits anyway).
158inline std::pair<LaunchCallSpecifier, uint8_t>
159DecodeChildExitCode(int exit_code)
160{
161 return std::make_pair(LaunchCallSpecifier(exit_code & 0x7), exit_code >> 3);
162}
163
Todd Fialaaf245d12014-06-30 21:05:18 +0000164 void
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000165 DisplayBytes (StreamString &s, void *bytes, uint32_t count)
Todd Fialaaf245d12014-06-30 21:05:18 +0000166 {
167 uint8_t *ptr = (uint8_t *)bytes;
168 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
169 for(uint32_t i=0; i<loop_count; i++)
170 {
171 s.Printf ("[%x]", *ptr);
172 ptr++;
173 }
174 }
175
176 void
177 PtraceDisplayBytes(int &req, void *data, size_t data_size)
178 {
179 StreamString buf;
180 Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
181 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
182
183 if (verbose_log)
184 {
185 switch(req)
186 {
187 case PTRACE_POKETEXT:
188 {
189 DisplayBytes(buf, &data, 8);
190 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
191 break;
192 }
193 case PTRACE_POKEDATA:
194 {
195 DisplayBytes(buf, &data, 8);
196 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
197 break;
198 }
199 case PTRACE_POKEUSER:
200 {
201 DisplayBytes(buf, &data, 8);
202 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
203 break;
204 }
205 case PTRACE_SETREGS:
206 {
207 DisplayBytes(buf, data, data_size);
208 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
209 break;
210 }
211 case PTRACE_SETFPREGS:
212 {
213 DisplayBytes(buf, data, data_size);
214 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
215 break;
216 }
217 case PTRACE_SETSIGINFO:
218 {
219 DisplayBytes(buf, data, sizeof(siginfo_t));
220 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
221 break;
222 }
223 case PTRACE_SETREGSET:
224 {
225 // Extract iov_base from data, which is a pointer to the struct IOVEC
226 DisplayBytes(buf, *(void **)data, data_size);
227 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
228 break;
229 }
230 default:
231 {
232 }
233 }
234 }
235 }
236
Pavel Labath19cbe962015-07-21 13:20:32 +0000237 static constexpr unsigned k_ptrace_word_size = sizeof(void*);
238 static_assert(sizeof(long) >= k_ptrace_word_size, "Size of long must be larger than ptrace word size");
Pavel Labath1107b5a2015-04-17 14:07:49 +0000239} // end of anonymous namespace
240
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000241// Simple helper function to ensure flags are enabled on the given file
242// descriptor.
243static Error
244EnsureFDFlags(int fd, int flags)
245{
246 Error error;
247
248 int status = fcntl(fd, F_GETFL);
249 if (status == -1)
250 {
251 error.SetErrorToErrno();
252 return error;
253 }
254
255 if (fcntl(fd, F_SETFL, status | flags) == -1)
256 {
257 error.SetErrorToErrno();
258 return error;
259 }
260
261 return error;
262}
263
Pavel Labath2a86b552016-06-14 17:30:52 +0000264NativeProcessLinux::LaunchArgs::LaunchArgs(char const **argv, char const **envp, const FileSpec &stdin_file_spec,
265 const FileSpec &stdout_file_spec, const FileSpec &stderr_file_spec,
266 const FileSpec &working_dir, const ProcessLaunchInfo &launch_info)
267 : m_argv(argv),
Todd Fialaaf245d12014-06-30 21:05:18 +0000268 m_envp(envp),
Chaoren Lind3173f32015-05-29 19:52:29 +0000269 m_stdin_file_spec(stdin_file_spec),
270 m_stdout_file_spec(stdout_file_spec),
271 m_stderr_file_spec(stderr_file_spec),
Todd Fiala0bce1b62014-08-17 00:10:50 +0000272 m_working_dir(working_dir),
273 m_launch_info(launch_info)
274{
275}
Todd Fialaaf245d12014-06-30 21:05:18 +0000276
277NativeProcessLinux::LaunchArgs::~LaunchArgs()
278{ }
279
Todd Fialaaf245d12014-06-30 21:05:18 +0000280// -----------------------------------------------------------------------------
281// Public Static Methods
282// -----------------------------------------------------------------------------
283
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000284Error
Pavel Labathd5b310f2015-07-09 11:51:11 +0000285NativeProcessProtocol::Launch (
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000286 ProcessLaunchInfo &launch_info,
287 NativeProcessProtocol::NativeDelegate &native_delegate,
Pavel Labath19cbe962015-07-21 13:20:32 +0000288 MainLoop &mainloop,
Todd Fialaaf245d12014-06-30 21:05:18 +0000289 NativeProcessProtocolSP &native_process_sp)
290{
291 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
292
Pavel Labath2a86b552016-06-14 17:30:52 +0000293 Error error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000294
295 // Verify the working directory is valid if one was specified.
Chaoren Lind3173f32015-05-29 19:52:29 +0000296 FileSpec working_dir{launch_info.GetWorkingDirectory()};
297 if (working_dir &&
298 (!working_dir.ResolvePath() ||
299 working_dir.GetFileType() != FileSpec::eFileTypeDirectory))
Todd Fialaaf245d12014-06-30 21:05:18 +0000300 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000301 error.SetErrorStringWithFormat ("No such file or directory: %s",
302 working_dir.GetCString());
303 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000304 }
305
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000306 const FileAction *file_action;
Todd Fialaaf245d12014-06-30 21:05:18 +0000307
Chaoren Lind3173f32015-05-29 19:52:29 +0000308 // Default of empty will mean to use existing open file descriptors.
309 FileSpec stdin_file_spec{};
310 FileSpec stdout_file_spec{};
311 FileSpec stderr_file_spec{};
Todd Fialaaf245d12014-06-30 21:05:18 +0000312
313 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +0000314 if (file_action)
Chaoren Lind3173f32015-05-29 19:52:29 +0000315 stdin_file_spec = file_action->GetFileSpec();
Todd Fialaaf245d12014-06-30 21:05:18 +0000316
317 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +0000318 if (file_action)
Chaoren Lind3173f32015-05-29 19:52:29 +0000319 stdout_file_spec = file_action->GetFileSpec();
Todd Fialaaf245d12014-06-30 21:05:18 +0000320
321 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +0000322 if (file_action)
Chaoren Lind3173f32015-05-29 19:52:29 +0000323 stderr_file_spec = file_action->GetFileSpec();
Todd Fiala75f47c32014-10-11 21:42:09 +0000324
325 if (log)
326 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000327 if (stdin_file_spec)
328 log->Printf ("NativeProcessLinux::%s setting STDIN to '%s'",
329 __FUNCTION__, stdin_file_spec.GetCString());
Todd Fiala75f47c32014-10-11 21:42:09 +0000330 else
331 log->Printf ("NativeProcessLinux::%s leaving STDIN as is", __FUNCTION__);
332
Chaoren Lind3173f32015-05-29 19:52:29 +0000333 if (stdout_file_spec)
334 log->Printf ("NativeProcessLinux::%s setting STDOUT to '%s'",
335 __FUNCTION__, stdout_file_spec.GetCString());
Todd Fiala75f47c32014-10-11 21:42:09 +0000336 else
337 log->Printf ("NativeProcessLinux::%s leaving STDOUT as is", __FUNCTION__);
338
Chaoren Lind3173f32015-05-29 19:52:29 +0000339 if (stderr_file_spec)
340 log->Printf ("NativeProcessLinux::%s setting STDERR to '%s'",
341 __FUNCTION__, stderr_file_spec.GetCString());
Todd Fiala75f47c32014-10-11 21:42:09 +0000342 else
343 log->Printf ("NativeProcessLinux::%s leaving STDERR as is", __FUNCTION__);
344 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000345
346 // Create the NativeProcessLinux in launch mode.
347 native_process_sp.reset (new NativeProcessLinux ());
348
349 if (log)
350 {
351 int i = 0;
352 for (const char **args = launch_info.GetArguments ().GetConstArgumentVector (); *args; ++args, ++i)
353 {
354 log->Printf ("NativeProcessLinux::%s arg %d: \"%s\"", __FUNCTION__, i, *args ? *args : "nullptr");
355 ++i;
356 }
357 }
358
359 if (!native_process_sp->RegisterNativeDelegate (native_delegate))
360 {
361 native_process_sp.reset ();
362 error.SetErrorStringWithFormat ("failed to register the native delegate");
363 return error;
364 }
365
Tamas Berghammercb84eeb2015-03-17 15:05:31 +0000366 std::static_pointer_cast<NativeProcessLinux> (native_process_sp)->LaunchInferior (
Pavel Labath19cbe962015-07-21 13:20:32 +0000367 mainloop,
Todd Fialaaf245d12014-06-30 21:05:18 +0000368 launch_info.GetArguments ().GetConstArgumentVector (),
369 launch_info.GetEnvironmentEntries ().GetConstArgumentVector (),
Chaoren Lind3173f32015-05-29 19:52:29 +0000370 stdin_file_spec,
371 stdout_file_spec,
372 stderr_file_spec,
Todd Fialaaf245d12014-06-30 21:05:18 +0000373 working_dir,
Todd Fiala0bce1b62014-08-17 00:10:50 +0000374 launch_info,
Todd Fialaaf245d12014-06-30 21:05:18 +0000375 error);
376
377 if (error.Fail ())
378 {
379 native_process_sp.reset ();
380 if (log)
381 log->Printf ("NativeProcessLinux::%s failed to launch process: %s", __FUNCTION__, error.AsCString ());
382 return error;
383 }
384
385 launch_info.SetProcessID (native_process_sp->GetID ());
386
387 return error;
388}
389
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000390Error
Pavel Labathd5b310f2015-07-09 11:51:11 +0000391NativeProcessProtocol::Attach (
Todd Fialaaf245d12014-06-30 21:05:18 +0000392 lldb::pid_t pid,
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000393 NativeProcessProtocol::NativeDelegate &native_delegate,
Pavel Labath19cbe962015-07-21 13:20:32 +0000394 MainLoop &mainloop,
Todd Fialaaf245d12014-06-30 21:05:18 +0000395 NativeProcessProtocolSP &native_process_sp)
396{
397 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
398 if (log && log->GetMask ().Test (POSIX_LOG_VERBOSE))
399 log->Printf ("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
400
Todd Fialaaf245d12014-06-30 21:05:18 +0000401 // Retrieve the architecture for the running process.
402 ArchSpec process_arch;
Pavel Labath2a86b552016-06-14 17:30:52 +0000403 Error error = ResolveProcessArchitecture(pid, process_arch);
Todd Fialaaf245d12014-06-30 21:05:18 +0000404 if (!error.Success ())
405 return error;
406
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +0000407 std::shared_ptr<NativeProcessLinux> native_process_linux_sp (new NativeProcessLinux ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000408
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +0000409 if (!native_process_linux_sp->RegisterNativeDelegate (native_delegate))
Todd Fialaaf245d12014-06-30 21:05:18 +0000410 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000411 error.SetErrorStringWithFormat ("failed to register the native delegate");
412 return error;
413 }
414
Pavel Labath19cbe962015-07-21 13:20:32 +0000415 native_process_linux_sp->AttachToInferior (mainloop, pid, error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000416 if (!error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +0000417 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000418
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +0000419 native_process_sp = native_process_linux_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +0000420 return error;
421}
422
423// -----------------------------------------------------------------------------
424// Public Instance Methods
425// -----------------------------------------------------------------------------
426
427NativeProcessLinux::NativeProcessLinux () :
428 NativeProcessProtocol (LLDB_INVALID_PROCESS_ID),
429 m_arch (),
Todd Fialaaf245d12014-06-30 21:05:18 +0000430 m_supports_mem_region (eLazyBoolCalculate),
431 m_mem_region_cache (),
Pavel Labath0e1d7292015-08-20 09:06:12 +0000432 m_pending_notification_tid(LLDB_INVALID_THREAD_ID)
Todd Fialaaf245d12014-06-30 21:05:18 +0000433{
434}
435
Todd Fialaaf245d12014-06-30 21:05:18 +0000436void
437NativeProcessLinux::LaunchInferior (
Pavel Labath19cbe962015-07-21 13:20:32 +0000438 MainLoop &mainloop,
Todd Fialaaf245d12014-06-30 21:05:18 +0000439 const char *argv[],
440 const char *envp[],
Chaoren Lind3173f32015-05-29 19:52:29 +0000441 const FileSpec &stdin_file_spec,
442 const FileSpec &stdout_file_spec,
443 const FileSpec &stderr_file_spec,
444 const FileSpec &working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000445 const ProcessLaunchInfo &launch_info,
446 Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000447{
Pavel Labath19cbe962015-07-21 13:20:32 +0000448 m_sigchld_handle = mainloop.RegisterSignal(SIGCHLD,
449 [this] (MainLoopBase &) { SigchldHandler(); }, error);
450 if (! m_sigchld_handle)
451 return;
452
Chaoren Linfa03ad22015-02-03 01:50:42 +0000453 SetState (eStateLaunching);
Todd Fialaaf245d12014-06-30 21:05:18 +0000454
455 std::unique_ptr<LaunchArgs> args(
Pavel Labath2a86b552016-06-14 17:30:52 +0000456 new LaunchArgs(argv, envp, stdin_file_spec, stdout_file_spec, stderr_file_spec, working_dir, launch_info));
Todd Fialaaf245d12014-06-30 21:05:18 +0000457
Pavel Labath19cbe962015-07-21 13:20:32 +0000458 Launch(args.get(), error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000459}
460
461void
Pavel Labath19cbe962015-07-21 13:20:32 +0000462NativeProcessLinux::AttachToInferior (MainLoop &mainloop, lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000463{
464 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
465 if (log)
466 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
467
Pavel Labath19cbe962015-07-21 13:20:32 +0000468 m_sigchld_handle = mainloop.RegisterSignal(SIGCHLD,
469 [this] (MainLoopBase &) { SigchldHandler(); }, error);
470 if (! m_sigchld_handle)
471 return;
472
Pavel Labath2a86b552016-06-14 17:30:52 +0000473 error = ResolveProcessArchitecture(pid, m_arch);
Todd Fialaaf245d12014-06-30 21:05:18 +0000474 if (!error.Success())
475 return;
476
477 // Set the architecture to the exe architecture.
Todd Fialaaf245d12014-06-30 21:05:18 +0000478 if (log)
479 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
480
481 m_pid = pid;
482 SetState(eStateAttaching);
483
Pavel Labath19cbe962015-07-21 13:20:32 +0000484 Attach(pid, error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000485}
486
Pavel Labath0c4f01d2016-07-06 13:18:50 +0000487void
488NativeProcessLinux::ChildFunc(const LaunchArgs &args)
489{
490 // Start tracing this child that is about to exec.
491 if (ptrace(PTRACE_TRACEME, 0, nullptr, nullptr) == -1)
492 ExitChildAbnormally(ePtraceFailed);
493
494 // Do not inherit setgid powers.
495 if (setgid(getgid()) != 0)
496 ExitChildAbnormally(eSetGidFailed);
497
498 // Attempt to have our own process group.
499 if (setpgid(0, 0) != 0)
500 {
501 // FIXME log that this failed. This is common.
502 // Don't allow this to prevent an inferior exec.
503 }
504
505 // Dup file descriptors if needed.
506 if (args.m_stdin_file_spec)
507 if (!DupDescriptor(args.m_stdin_file_spec, STDIN_FILENO, O_RDONLY))
508 ExitChildAbnormally(eDupStdinFailed);
509
510 if (args.m_stdout_file_spec)
511 if (!DupDescriptor(args.m_stdout_file_spec, STDOUT_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
512 ExitChildAbnormally(eDupStdoutFailed);
513
514 if (args.m_stderr_file_spec)
515 if (!DupDescriptor(args.m_stderr_file_spec, STDERR_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
516 ExitChildAbnormally(eDupStderrFailed);
517
518 // Close everything besides stdin, stdout, and stderr that has no file
519 // action to avoid leaking
520 for (int fd = 3; fd < sysconf(_SC_OPEN_MAX); ++fd)
521 if (!args.m_launch_info.GetFileActionForFD(fd))
522 close(fd);
523
524 // Change working directory
525 if (args.m_working_dir && 0 != ::chdir(args.m_working_dir.GetCString()))
526 ExitChildAbnormally(eChdirFailed);
527
528 // Disable ASLR if requested.
529 if (args.m_launch_info.GetFlags().Test(lldb::eLaunchFlagDisableASLR))
530 {
531 const int old_personality = personality(LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
532 if (old_personality == -1)
533 {
534 // Can't retrieve Linux personality. Cannot disable ASLR.
535 }
536 else
537 {
538 const int new_personality = personality(ADDR_NO_RANDOMIZE | old_personality);
539 if (new_personality == -1)
540 {
541 // Disabling ASLR failed.
542 }
543 else
544 {
545 // Disabling ASLR succeeded.
546 }
547 }
548 }
549
550 // Clear the signal mask to prevent the child from being affected by
551 // any masking done by the parent.
552 sigset_t set;
553 if (sigemptyset(&set) != 0 || pthread_sigmask(SIG_SETMASK, &set, nullptr) != 0)
554 ExitChildAbnormally(eSetSigMaskFailed);
555
556 // Propagate the environment if one is not supplied.
557 const char **envp = args.m_envp;
558 if (envp == NULL || envp[0] == NULL)
559 envp = const_cast<const char **>(environ);
560
561 // Execute. We should never return...
562 execve(args.m_argv[0], const_cast<char *const *>(args.m_argv), const_cast<char *const *>(envp));
563
Pavel Labathca92aed2016-07-07 15:46:00 +0000564 if (errno == ETXTBSY)
565 {
566 // On android M and earlier we can get this error because the adb deamon can hold a write
567 // handle on the executable even after it has finished uploading it. This state lasts
568 // only a short time and happens only when there are many concurrent adb commands being
569 // issued, such as when running the test suite. (The file remains open when someone does
570 // an "adb shell" command in the fork() child before it has had a chance to exec.) Since
571 // this state should clear up quickly, wait a while and then give it one more go.
572 usleep(10000);
573 execve(args.m_argv[0], const_cast<char *const *>(args.m_argv), const_cast<char *const *>(envp));
574 }
575
Pavel Labath0c4f01d2016-07-06 13:18:50 +0000576 // ...unless exec fails. In which case we definitely need to end the child here.
577 ExitChildAbnormally(eExecFailed);
578}
579
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000580::pid_t
581NativeProcessLinux::Launch(LaunchArgs *args, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000582{
Todd Fiala0bce1b62014-08-17 00:10:50 +0000583 assert (args && "null args");
Todd Fialaaf245d12014-06-30 21:05:18 +0000584
Todd Fialaaf245d12014-06-30 21:05:18 +0000585 lldb_utility::PseudoTerminal terminal;
586 const size_t err_len = 1024;
587 char err_str[err_len];
588 lldb::pid_t pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000589
Todd Fialaaf245d12014-06-30 21:05:18 +0000590 if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
591 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000592 error.SetErrorToGenericError();
593 error.SetErrorStringWithFormat("Process fork failed: %s", err_str);
594 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000595 }
596
Todd Fialaaf245d12014-06-30 21:05:18 +0000597 // Child process.
598 if (pid == 0)
599 {
Pavel Labathd2c4c9b2015-08-18 08:23:35 +0000600 // First, make sure we disable all logging. If we are logging to stdout, our logs can be
601 // mistaken for inferior output.
602 Log::DisableAllLogChannels(nullptr);
Todd Fialaaf245d12014-06-30 21:05:18 +0000603
Pavel Labath493c3a12015-02-04 10:36:57 +0000604 // terminal has already dupped the tty descriptors to stdin/out/err.
605 // This closes original fd from which they were copied (and avoids
606 // leaking descriptors to the debugged process.
607 terminal.CloseSlaveFileDescriptor();
608
Pavel Labath0c4f01d2016-07-06 13:18:50 +0000609 ChildFunc(*args);
Todd Fialaaf245d12014-06-30 21:05:18 +0000610 }
611
Todd Fiala75f47c32014-10-11 21:42:09 +0000612 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
613
Todd Fialaaf245d12014-06-30 21:05:18 +0000614 // Wait for the child process to trap on its call to execve.
615 ::pid_t wpid;
616 int status;
617 if ((wpid = waitpid(pid, &status, 0)) < 0)
618 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000619 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +0000620 if (log)
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000621 log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s",
622 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000623
624 // Mark the inferior as invalid.
625 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000626 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000627
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000628 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000629 }
630 else if (WIFEXITED(status))
631 {
Pavel Labath0c4f01d2016-07-06 13:18:50 +0000632 auto p = DecodeChildExitCode(WEXITSTATUS(status));
633 Error child_error(p.second, eErrorTypePOSIX);
634 const char *failure_reason;
635 switch (p.first)
Todd Fialaaf245d12014-06-30 21:05:18 +0000636 {
637 case ePtraceFailed:
Pavel Labath0c4f01d2016-07-06 13:18:50 +0000638 failure_reason = "Child ptrace failed";
Todd Fialaaf245d12014-06-30 21:05:18 +0000639 break;
640 case eDupStdinFailed:
Pavel Labath0c4f01d2016-07-06 13:18:50 +0000641 failure_reason = "Child open stdin failed";
Todd Fialaaf245d12014-06-30 21:05:18 +0000642 break;
643 case eDupStdoutFailed:
Pavel Labath0c4f01d2016-07-06 13:18:50 +0000644 failure_reason = "Child open stdout failed";
Todd Fialaaf245d12014-06-30 21:05:18 +0000645 break;
646 case eDupStderrFailed:
Pavel Labath0c4f01d2016-07-06 13:18:50 +0000647 failure_reason = "Child open stderr failed";
Todd Fialaaf245d12014-06-30 21:05:18 +0000648 break;
649 case eChdirFailed:
Pavel Labath0c4f01d2016-07-06 13:18:50 +0000650 failure_reason = "Child failed to set working directory";
Todd Fialaaf245d12014-06-30 21:05:18 +0000651 break;
652 case eExecFailed:
Pavel Labath0c4f01d2016-07-06 13:18:50 +0000653 failure_reason = "Child exec failed";
Todd Fialaaf245d12014-06-30 21:05:18 +0000654 break;
655 case eSetGidFailed:
Pavel Labath0c4f01d2016-07-06 13:18:50 +0000656 failure_reason = "Child setgid failed";
Todd Fialaaf245d12014-06-30 21:05:18 +0000657 break;
Pavel Labath78856472015-08-19 13:47:57 +0000658 case eSetSigMaskFailed:
Pavel Labath0c4f01d2016-07-06 13:18:50 +0000659 failure_reason = "Child failed to set signal mask";
Todd Fialaaf245d12014-06-30 21:05:18 +0000660 break;
661 }
Pavel Labath0c4f01d2016-07-06 13:18:50 +0000662 error.SetErrorStringWithFormat("%s: %d - %s (error code truncated)", failure_reason, child_error.GetError(), child_error.AsCString());
Todd Fialaaf245d12014-06-30 21:05:18 +0000663
664 if (log)
665 {
666 log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
667 __FUNCTION__,
668 WEXITSTATUS(status));
669 }
670
671 // Mark the inferior as invalid.
672 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000673 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000674
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000675 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000676 }
Todd Fiala202ecd22014-07-10 04:39:13 +0000677 assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
Todd Fialaaf245d12014-06-30 21:05:18 +0000678 "Could not sync with inferior process.");
679
680 if (log)
681 log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
682
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000683 error = SetDefaultPtraceOpts(pid);
684 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000685 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000686 if (log)
687 log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000688 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000689
690 // Mark the inferior as invalid.
691 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000692 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000693
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000694 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000695 }
696
697 // Release the master terminal descriptor and pass it off to the
698 // NativeProcessLinux instance. Similarly stash the inferior pid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000699 m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
700 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000701
702 // Set the terminal fd to be in non blocking mode (it simplifies the
703 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
704 // descriptor to read from).
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000705 error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
706 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000707 {
708 if (log)
709 log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000710 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000711
712 // Mark the inferior as invalid.
713 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000714 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000715
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000716 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000717 }
718
719 if (log)
720 log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
721
Pavel Labath2a86b552016-06-14 17:30:52 +0000722 ResolveProcessArchitecture(m_pid, m_arch);
Pavel Labathf9077782015-08-21 09:13:53 +0000723 NativeThreadLinuxSP thread_sp = AddThread(pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000724 assert (thread_sp && "AddThread() returned a nullptr thread");
Pavel Labathf9077782015-08-21 09:13:53 +0000725 thread_sp->SetStoppedBySignal(SIGSTOP);
726 ThreadWasCreated(*thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +0000727
728 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000729 SetCurrentThreadID (thread_sp->GetID ());
730 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +0000731
Todd Fialaaf245d12014-06-30 21:05:18 +0000732 if (log)
733 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000734 if (error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +0000735 {
736 log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
737 }
738 else
739 {
740 log->Printf ("NativeProcessLinux::%s inferior launching failed: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000741 __FUNCTION__, error.AsCString ());
742 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000743 }
744 }
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000745 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000746}
747
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000748::pid_t
749NativeProcessLinux::Attach(lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000750{
Todd Fialaaf245d12014-06-30 21:05:18 +0000751 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
752
753 // Use a map to keep track of the threads which we have attached/need to attach.
754 Host::TidMap tids_to_attach;
755 if (pid <= 1)
756 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000757 error.SetErrorToGenericError();
758 error.SetErrorString("Attaching to process 1 is not allowed.");
759 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000760 }
761
762 while (Host::FindProcessThreads(pid, tids_to_attach))
763 {
764 for (Host::TidMap::iterator it = tids_to_attach.begin();
765 it != tids_to_attach.end();)
766 {
767 if (it->second == false)
768 {
769 lldb::tid_t tid = it->first;
770
771 // Attach to the requested process.
772 // An attach will cause the thread to stop with a SIGSTOP.
Pavel Labath4a9babb2015-06-30 17:04:49 +0000773 error = PtraceWrapper(PTRACE_ATTACH, tid);
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000774 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000775 {
776 // No such thread. The thread may have exited.
777 // More error handling may be needed.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000778 if (error.GetError() == ESRCH)
Todd Fialaaf245d12014-06-30 21:05:18 +0000779 {
780 it = tids_to_attach.erase(it);
781 continue;
782 }
783 else
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000784 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000785 }
786
787 int status;
788 // Need to use __WALL otherwise we receive an error with errno=ECHLD
789 // At this point we should have a thread stopped if waitpid succeeds.
790 if ((status = waitpid(tid, NULL, __WALL)) < 0)
791 {
792 // No such thread. The thread may have exited.
793 // More error handling may be needed.
794 if (errno == ESRCH)
795 {
796 it = tids_to_attach.erase(it);
797 continue;
798 }
799 else
800 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000801 error.SetErrorToErrno();
802 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000803 }
804 }
805
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000806 error = SetDefaultPtraceOpts(tid);
807 if (error.Fail())
808 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000809
810 if (log)
811 log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
812
813 it->second = true;
814
815 // Create the thread, mark it as stopped.
Pavel Labathf9077782015-08-21 09:13:53 +0000816 NativeThreadLinuxSP thread_sp (AddThread(static_cast<lldb::tid_t>(tid)));
Todd Fialaaf245d12014-06-30 21:05:18 +0000817 assert (thread_sp && "AddThread() returned a nullptr");
Chaoren Linfa03ad22015-02-03 01:50:42 +0000818
819 // This will notify this is a new thread and tell the system it is stopped.
Pavel Labathf9077782015-08-21 09:13:53 +0000820 thread_sp->SetStoppedBySignal(SIGSTOP);
821 ThreadWasCreated(*thread_sp);
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000822 SetCurrentThreadID (thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000823 }
824
825 // move the loop forward
826 ++it;
827 }
828 }
829
830 if (tids_to_attach.size() > 0)
831 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000832 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000833 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000834 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +0000835 }
836 else
837 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000838 error.SetErrorToGenericError();
839 error.SetErrorString("No such process.");
840 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000841 }
842
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000843 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000844}
845
Chaoren Lin97ccc292015-02-03 01:51:12 +0000846Error
Todd Fialaaf245d12014-06-30 21:05:18 +0000847NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
848{
849 long ptrace_opts = 0;
850
851 // Have the child raise an event on exit. This is used to keep the child in
852 // limbo until it is destroyed.
853 ptrace_opts |= PTRACE_O_TRACEEXIT;
854
855 // Have the tracer trace threads which spawn in the inferior process.
856 // TODO: if we want to support tracing the inferiors' child, add the
857 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
858 ptrace_opts |= PTRACE_O_TRACECLONE;
859
860 // Have the tracer notify us before execve returns
861 // (needed to disable legacy SIGTRAP generation)
862 ptrace_opts |= PTRACE_O_TRACEEXEC;
863
Pavel Labath4a9babb2015-06-30 17:04:49 +0000864 return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts);
Todd Fialaaf245d12014-06-30 21:05:18 +0000865}
866
867static ExitType convert_pid_status_to_exit_type (int status)
868{
869 if (WIFEXITED (status))
870 return ExitType::eExitTypeExit;
871 else if (WIFSIGNALED (status))
872 return ExitType::eExitTypeSignal;
873 else if (WIFSTOPPED (status))
874 return ExitType::eExitTypeStop;
875 else
876 {
877 // We don't know what this is.
878 return ExitType::eExitTypeInvalid;
879 }
880}
881
882static int convert_pid_status_to_return_code (int status)
883{
884 if (WIFEXITED (status))
885 return WEXITSTATUS (status);
886 else if (WIFSIGNALED (status))
887 return WTERMSIG (status);
888 else if (WIFSTOPPED (status))
889 return WSTOPSIG (status);
890 else
891 {
892 // We don't know what this is.
893 return ExitType::eExitTypeInvalid;
894 }
895}
896
Pavel Labath1107b5a2015-04-17 14:07:49 +0000897// Handles all waitpid events from the inferior process.
898void
899NativeProcessLinux::MonitorCallback(lldb::pid_t pid,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000900 bool exited,
901 int signal,
902 int status)
Todd Fialaaf245d12014-06-30 21:05:18 +0000903{
904 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
905
Todd Fialaaf245d12014-06-30 21:05:18 +0000906 // Certain activities differ based on whether the pid is the tid of the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000907 const bool is_main_thread = (pid == GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000908
909 // Handle when the thread exits.
910 if (exited)
911 {
912 if (log)
Chaoren Lin86fd8e42015-02-03 01:51:15 +0000913 log->Printf ("NativeProcessLinux::%s() got exit signal(%d) , tid = %" PRIu64 " (%s main thread)", __FUNCTION__, signal, pid, is_main_thread ? "is" : "is not");
Todd Fialaaf245d12014-06-30 21:05:18 +0000914
915 // This is a thread that exited. Ensure we're not tracking it anymore.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000916 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000917
918 if (is_main_thread)
919 {
920 // We only set the exit status and notify the delegate if we haven't already set the process
921 // state to an exited state. We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
922 // for the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000923 const bool already_notified = (GetState() == StateType::eStateExited) || (GetState () == StateType::eStateCrashed);
Todd Fialaaf245d12014-06-30 21:05:18 +0000924 if (!already_notified)
925 {
926 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +0000927 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " handling main thread exit (%s), expected exit state already set but state was %s instead, setting exit state now", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found", StateAsCString (GetState ()));
Todd Fialaaf245d12014-06-30 21:05:18 +0000928 // The main thread exited. We're done monitoring. Report to delegate.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000929 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +0000930
931 // Notify delegate that our process has exited.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000932 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +0000933 }
934 else
935 {
936 if (log)
937 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
938 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000939 }
940 else
941 {
942 // Do we want to report to the delegate in this case? I think not. If this was an orderly
943 // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
944 // and we would have done an all-stop then.
945 if (log)
946 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " handling non-main thread exit (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
Todd Fialaaf245d12014-06-30 21:05:18 +0000947 }
Pavel Labath1107b5a2015-04-17 14:07:49 +0000948 return;
Todd Fialaaf245d12014-06-30 21:05:18 +0000949 }
950
Todd Fialaaf245d12014-06-30 21:05:18 +0000951 siginfo_t info;
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000952 const auto info_err = GetSignalInfo(pid, &info);
953 auto thread_sp = GetThreadByID(pid);
954
955 if (! thread_sp)
956 {
957 // Normally, the only situation when we cannot find the thread is if we have just
958 // received a new thread notification. This is indicated by GetSignalInfo() returning
959 // si_code == SI_USER and si_pid == 0
960 if (log)
961 log->Printf("NativeProcessLinux::%s received notification about an unknown tid %" PRIu64 ".", __FUNCTION__, pid);
962
963 if (info_err.Fail())
964 {
965 if (log)
966 log->Printf("NativeProcessLinux::%s (tid %" PRIu64 ") GetSignalInfo failed (%s). Ingoring this notification.", __FUNCTION__, pid, info_err.AsCString());
967 return;
968 }
969
970 if (log && (info.si_code != SI_USER || info.si_pid != 0))
971 log->Printf("NativeProcessLinux::%s (tid %" PRIu64 ") unexpected signal info (si_code: %d, si_pid: %d). Treating as a new thread notification anyway.", __FUNCTION__, pid, info.si_code, info.si_pid);
972
973 auto thread_sp = AddThread(pid);
974 // Resume the newly created thread.
975 ResumeThread(*thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
976 ThreadWasCreated(*thread_sp);
977 return;
978 }
979
980 // Get details on the signal raised.
981 if (info_err.Success())
Chaoren Linfa03ad22015-02-03 01:50:42 +0000982 {
983 // We have retrieved the signal info. Dispatch appropriately.
984 if (info.si_signo == SIGTRAP)
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000985 MonitorSIGTRAP(info, *thread_sp);
Chaoren Linfa03ad22015-02-03 01:50:42 +0000986 else
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000987 MonitorSignal(info, *thread_sp, exited);
Chaoren Linfa03ad22015-02-03 01:50:42 +0000988 }
989 else
Todd Fialaaf245d12014-06-30 21:05:18 +0000990 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000991 if (info_err.GetError() == EINVAL)
Todd Fialaaf245d12014-06-30 21:05:18 +0000992 {
Chaoren Linfa03ad22015-02-03 01:50:42 +0000993 // This is a group stop reception for this tid.
Pavel Labath39036ac2015-05-21 08:32:18 +0000994 // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the
995 // tracee, triggering the group-stop mechanism. Normally receiving these would stop
996 // the process, pending a SIGCONT. Simulating this state in a debugger is hard and is
997 // generally not needed (one use case is debugging background task being managed by a
998 // shell). For general use, it is sufficient to stop the process in a signal-delivery
999 // stop which happens before the group stop. This done by MonitorSignal and works
1000 // correctly for all signals.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001001 if (log)
Pavel Labath39036ac2015-05-21 08:32:18 +00001002 log->Printf("NativeProcessLinux::%s received a group stop for pid %" PRIu64 " tid %" PRIu64 ". Transparent handling of group stops not supported, resuming the thread.", __FUNCTION__, GetID (), pid);
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001003 ResumeThread(*thread_sp, thread_sp->GetState(), LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001004 }
1005 else
1006 {
1007 // ptrace(GETSIGINFO) failed (but not due to group-stop).
1008
1009 // A return value of ESRCH means the thread/process is no longer on the system,
1010 // so it was killed somehow outside of our control. Either way, we can't do anything
1011 // with it anymore.
1012
Todd Fialaaf245d12014-06-30 21:05:18 +00001013 // Stop tracking the metadata for the thread since it's entirely off the system now.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001014 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001015
1016 if (log)
1017 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001018 __FUNCTION__, info_err.AsCString(), pid, signal, status, info_err.GetError() == ESRCH ? "thread/process killed" : "unknown reason", is_main_thread ? "is main thread" : "is not main thread", thread_found ? "thread metadata removed" : "thread metadata not found");
Todd Fialaaf245d12014-06-30 21:05:18 +00001019
1020 if (is_main_thread)
1021 {
1022 // Notify the delegate - our process is not available but appears to have been killed outside
1023 // our control. Is eStateExited the right exit state in this case?
Pavel Labath1107b5a2015-04-17 14:07:49 +00001024 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
1025 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001026 }
1027 else
1028 {
1029 // This thread was pulled out from underneath us. Anything to do here? Do we want to do an all stop?
1030 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +00001031 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 " non-main thread exit occurred, didn't tell delegate anything since thread disappeared out from underneath us", __FUNCTION__, GetID (), pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001032 }
1033 }
1034 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001035}
1036
1037void
Pavel Labath426bdf82015-04-28 07:51:52 +00001038NativeProcessLinux::WaitForNewThread(::pid_t tid)
1039{
1040 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1041
Pavel Labathf9077782015-08-21 09:13:53 +00001042 NativeThreadLinuxSP new_thread_sp = GetThreadByID(tid);
Pavel Labath426bdf82015-04-28 07:51:52 +00001043
1044 if (new_thread_sp)
1045 {
1046 // We are already tracking the thread - we got the event on the new thread (see
1047 // MonitorSignal) before this one. We are done.
1048 return;
1049 }
1050
1051 // The thread is not tracked yet, let's wait for it to appear.
1052 int status = -1;
1053 ::pid_t wait_pid;
1054 do
1055 {
1056 if (log)
1057 log->Printf ("NativeProcessLinux::%s() received thread creation event for tid %" PRIu32 ". tid not tracked yet, waiting for thread to appear...", __FUNCTION__, tid);
1058 wait_pid = waitpid(tid, &status, __WALL);
1059 }
1060 while (wait_pid == -1 && errno == EINTR);
1061 // Since we are waiting on a specific tid, this must be the creation event. But let's do
1062 // some checks just in case.
1063 if (wait_pid != tid) {
1064 if (log)
1065 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime", __FUNCTION__, tid);
1066 // The only way I know of this could happen is if the whole process was
1067 // SIGKILLed in the mean time. In any case, we can't do anything about that now.
1068 return;
1069 }
1070 if (WIFEXITED(status))
1071 {
1072 if (log)
1073 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " returned an 'exited' event. Not tracking the thread.", __FUNCTION__, tid);
1074 // Also a very improbable event.
1075 return;
1076 }
1077
1078 siginfo_t info;
1079 Error error = GetSignalInfo(tid, &info);
1080 if (error.Fail())
1081 {
1082 if (log)
1083 log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime.", __FUNCTION__, tid);
1084 return;
1085 }
1086
1087 if (((info.si_pid != 0) || (info.si_code != SI_USER)) && log)
1088 {
1089 // We should be getting a thread creation signal here, but we received something
1090 // else. There isn't much we can do about it now, so we will just log that. Since the
1091 // thread is alive and we are receiving events from it, we shall pretend that it was
1092 // created properly.
1093 log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " received unexpected signal with code %d from pid %d.", __FUNCTION__, tid, info.si_code, info.si_pid);
1094 }
1095
1096 if (log)
1097 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 ": tracking new thread tid %" PRIu32,
1098 __FUNCTION__, GetID (), tid);
1099
Pavel Labathf9077782015-08-21 09:13:53 +00001100 new_thread_sp = AddThread(tid);
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001101 ResumeThread(*new_thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
Pavel Labathf9077782015-08-21 09:13:53 +00001102 ThreadWasCreated(*new_thread_sp);
Pavel Labath426bdf82015-04-28 07:51:52 +00001103}
1104
1105void
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001106NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info, NativeThreadLinux &thread)
Todd Fialaaf245d12014-06-30 21:05:18 +00001107{
1108 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001109 const bool is_main_thread = (thread.GetID() == GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001110
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001111 assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
Todd Fialaaf245d12014-06-30 21:05:18 +00001112
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001113 switch (info.si_code)
Todd Fialaaf245d12014-06-30 21:05:18 +00001114 {
1115 // TODO: these two cases are required if we want to support tracing of the inferiors' children. We'd need this to debug a monitor.
1116 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
1117 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
1118
1119 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
1120 {
Pavel Labath5fd24c62015-04-23 09:04:35 +00001121 // This is the notification on the parent thread which informs us of new thread
Pavel Labath426bdf82015-04-28 07:51:52 +00001122 // creation.
1123 // We don't want to do anything with the parent thread so we just resume it. In case we
1124 // want to implement "break on thread creation" functionality, we would need to stop
1125 // here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001126
Pavel Labath426bdf82015-04-28 07:51:52 +00001127 unsigned long event_message = 0;
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001128 if (GetEventMessage(thread.GetID(), &event_message).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001129 {
Pavel Labath426bdf82015-04-28 07:51:52 +00001130 if (log)
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001131 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " received thread creation event but GetEventMessage failed so we don't know the new tid", __FUNCTION__, thread.GetID());
Pavel Labath426bdf82015-04-28 07:51:52 +00001132 } else
1133 WaitForNewThread(event_message);
Todd Fialaaf245d12014-06-30 21:05:18 +00001134
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001135 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001136 break;
1137 }
1138
1139 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
Todd Fialaa9882ce2014-08-28 15:46:54 +00001140 {
Pavel Labathf9077782015-08-21 09:13:53 +00001141 NativeThreadLinuxSP main_thread_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001142 if (log)
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001143 log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info.si_code ^ SIGTRAP);
Todd Fialaa9882ce2014-08-28 15:46:54 +00001144
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001145 // Exec clears any pending notifications.
Pavel Labath0e1d7292015-08-20 09:06:12 +00001146 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
Chaoren Linfa03ad22015-02-03 01:50:42 +00001147
Pavel Labath57a77112016-05-16 09:18:30 +00001148 // Remove all but the main thread here. Linux fork creates a new process which only copies the main thread.
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001149 if (log)
1150 log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
1151
1152 for (auto thread_sp : m_threads)
Todd Fialaa9882ce2014-08-28 15:46:54 +00001153 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001154 const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
1155 if (is_main_thread)
Todd Fialaa9882ce2014-08-28 15:46:54 +00001156 {
Pavel Labathf9077782015-08-21 09:13:53 +00001157 main_thread_sp = std::static_pointer_cast<NativeThreadLinux>(thread_sp);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001158 if (log)
1159 log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00001160 }
1161 else
1162 {
Todd Fialaa9882ce2014-08-28 15:46:54 +00001163 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001164 log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00001165 }
1166 }
1167
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001168 m_threads.clear ();
1169
1170 if (main_thread_sp)
1171 {
1172 m_threads.push_back (main_thread_sp);
1173 SetCurrentThreadID (main_thread_sp->GetID ());
Pavel Labathf9077782015-08-21 09:13:53 +00001174 main_thread_sp->SetStoppedByExec();
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001175 }
1176 else
1177 {
1178 SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
1179 if (log)
1180 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
1181 }
1182
Chaoren Linfa03ad22015-02-03 01:50:42 +00001183 // Tell coordinator about about the "new" (since exec) stopped main thread.
Pavel Labathf9077782015-08-21 09:13:53 +00001184 ThreadWasCreated(*main_thread_sp);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001185
Todd Fialaa9882ce2014-08-28 15:46:54 +00001186 // Let our delegate know we have just exec'd.
1187 NotifyDidExec ();
1188
1189 // If we have a main thread, indicate we are stopped.
1190 assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001191
1192 // Let the process know we're stopped.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001193 StopRunningThreads(main_thread_sp->GetID());
Todd Fialaa9882ce2014-08-28 15:46:54 +00001194
Todd Fialaaf245d12014-06-30 21:05:18 +00001195 break;
Todd Fialaa9882ce2014-08-28 15:46:54 +00001196 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001197
1198 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
1199 {
1200 // The inferior process or one of its threads is about to exit.
Pavel Labath6e351632015-05-15 13:30:59 +00001201 // We don't want to do anything with the thread so we just resume it. In case we
1202 // want to implement "break on thread exit" functionality, we would need to stop
1203 // here.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001204
Todd Fialaaf245d12014-06-30 21:05:18 +00001205 unsigned long data = 0;
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001206 if (GetEventMessage(thread.GetID(), &data).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001207 data = -1;
1208
1209 if (log)
1210 {
1211 log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
1212 __FUNCTION__,
1213 data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001214 thread.GetID(),
Todd Fialaaf245d12014-06-30 21:05:18 +00001215 is_main_thread ? "is main thread" : "not main thread");
1216 }
1217
Todd Fialaaf245d12014-06-30 21:05:18 +00001218 if (is_main_thread)
1219 {
1220 SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001221 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001222
Pavel Labath86852d32015-09-01 10:59:36 +00001223 StateType state = thread.GetState();
1224 if (! StateIsRunningState(state))
1225 {
1226 // Due to a kernel bug, we may sometimes get this stop after the inferior gets a
1227 // SIGKILL. This confuses our state tracking logic in ResumeThread(), since normally,
1228 // we should not be receiving any ptrace events while the inferior is stopped. This
1229 // makes sure that the inferior is resumed and exits normally.
1230 state = eStateRunning;
1231 }
1232 ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001233
1234 break;
1235 }
1236
1237 case 0:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001238 case TRAP_TRACE: // We receive this on single stepping.
1239 case TRAP_HWBKPT: // We receive this on watchpoint hit
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001240 {
1241 // If a watchpoint was hit, report it
1242 uint32_t wp_index;
Tamas Berghammer1fa5c4b2015-10-13 16:48:04 +00001243 Error error = thread.GetRegisterContext()->GetWatchpointHitIndex(wp_index, (uintptr_t)info.si_addr);
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001244 if (error.Fail() && log)
1245 log->Printf("NativeProcessLinux::%s() "
1246 "received error while checking for watchpoint hits, "
1247 "pid = %" PRIu64 " error = %s",
1248 __FUNCTION__, thread.GetID(), error.AsCString());
1249 if (wp_index != LLDB_INVALID_INDEX32)
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001250 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001251 MonitorWatchpoint(thread, wp_index);
1252 break;
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001253 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001254
Tamas Berghammerbe379e12016-02-16 15:14:36 +00001255 // Otherwise, report step over
1256 MonitorTrace(thread);
Todd Fialaaf245d12014-06-30 21:05:18 +00001257 break;
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001258 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001259
1260 case SI_KERNEL:
Mohit K. Bhakkad35799962015-06-18 04:53:18 +00001261#if defined __mips__
1262 // For mips there is no special signal for watchpoint
1263 // So we check for watchpoint in kernel trap
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001264 {
1265 // If a watchpoint was hit, report it
1266 uint32_t wp_index;
1267 Error error = thread.GetRegisterContext()->GetWatchpointHitIndex(wp_index, LLDB_INVALID_ADDRESS);
1268 if (error.Fail() && log)
1269 log->Printf("NativeProcessLinux::%s() "
1270 "received error while checking for watchpoint hits, "
1271 "pid = %" PRIu64 " error = %s",
Mohit K. Bhakkad16ad0322015-08-28 12:08:26 +00001272 __FUNCTION__, thread.GetID(), error.AsCString());
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001273 if (wp_index != LLDB_INVALID_INDEX32)
Mohit K. Bhakkad35799962015-06-18 04:53:18 +00001274 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001275 MonitorWatchpoint(thread, wp_index);
1276 break;
Mohit K. Bhakkad35799962015-06-18 04:53:18 +00001277 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001278 }
Mohit K. Bhakkad35799962015-06-18 04:53:18 +00001279 // NO BREAK
1280#endif
Todd Fialaaf245d12014-06-30 21:05:18 +00001281 case TRAP_BRKPT:
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001282 MonitorBreakpoint(thread);
Todd Fialaaf245d12014-06-30 21:05:18 +00001283 break;
1284
1285 case SIGTRAP:
1286 case (SIGTRAP | 0x80):
1287 if (log)
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001288 log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), thread.GetID());
Chaoren Linfa03ad22015-02-03 01:50:42 +00001289
Todd Fialaaf245d12014-06-30 21:05:18 +00001290 // Ignore these signals until we know more about them.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001291 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001292 break;
1293
1294 default:
1295 assert(false && "Unexpected SIGTRAP code!");
1296 if (log)
Pavel Labath6e351632015-05-15 13:30:59 +00001297 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 "tid %" PRIu64 " received unhandled SIGTRAP code: 0x%d",
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001298 __FUNCTION__, GetID(), thread.GetID(), info.si_code);
Todd Fialaaf245d12014-06-30 21:05:18 +00001299 break;
1300
1301 }
1302}
1303
1304void
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001305NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread)
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001306{
1307 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1308 if (log)
1309 log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)",
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001310 __FUNCTION__, thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001311
Pavel Labath0e1d7292015-08-20 09:06:12 +00001312 // This thread is currently stopped.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001313 thread.SetStoppedByTrace();
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001314
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001315 StopRunningThreads(thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001316}
1317
1318void
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001319NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread)
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001320{
1321 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
1322 if (log)
1323 log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001324 __FUNCTION__, thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001325
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001326 // Mark the thread as stopped at breakpoint.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001327 thread.SetStoppedByBreakpoint();
1328 Error error = FixupBreakpointPCAsNeeded(thread);
1329 if (error.Fail())
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001330 if (log)
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001331 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
1332 __FUNCTION__, thread.GetID(), error.AsCString());
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001333
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001334 if (m_threads_stepping_with_breakpoint.find(thread.GetID()) != m_threads_stepping_with_breakpoint.end())
1335 thread.SetStoppedByTrace();
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001336
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001337 StopRunningThreads(thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001338}
1339
1340void
Pavel Labathf9077782015-08-21 09:13:53 +00001341NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread, uint32_t wp_index)
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001342{
1343 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
1344 if (log)
1345 log->Printf("NativeProcessLinux::%s() received watchpoint event, "
1346 "pid = %" PRIu64 ", wp_index = %" PRIu32,
Pavel Labathf9077782015-08-21 09:13:53 +00001347 __FUNCTION__, thread.GetID(), wp_index);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001348
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001349 // Mark the thread as stopped at watchpoint.
1350 // The address is at (lldb::addr_t)info->si_addr if we need it.
Pavel Labathf9077782015-08-21 09:13:53 +00001351 thread.SetStoppedByWatchpoint(wp_index);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001352
1353 // We need to tell all other running threads before we notify the delegate about this stop.
Pavel Labathf9077782015-08-21 09:13:53 +00001354 StopRunningThreads(thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001355}
1356
1357void
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001358NativeProcessLinux::MonitorSignal(const siginfo_t &info, NativeThreadLinux &thread, bool exited)
Todd Fialaaf245d12014-06-30 21:05:18 +00001359{
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001360 const int signo = info.si_signo;
1361 const bool is_from_llgs = info.si_pid == getpid ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001362
1363 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1364
1365 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1366 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1367 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
1368 //
1369 // IOW, user generated signals never generate what we consider to be a
1370 // "crash".
1371 //
1372 // Similarly, ACK signals generated by this monitor.
1373
Todd Fialaaf245d12014-06-30 21:05:18 +00001374 // Handle the signal.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001375 if (info.si_code == SI_TKILL || info.si_code == SI_USER)
Todd Fialaaf245d12014-06-30 21:05:18 +00001376 {
1377 if (log)
1378 log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
1379 __FUNCTION__,
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001380 Host::GetSignalAsCString(signo),
Todd Fialaaf245d12014-06-30 21:05:18 +00001381 signo,
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001382 (info.si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
1383 info.si_pid,
Todd Fiala511e5cd2014-09-11 23:29:14 +00001384 is_from_llgs ? "from llgs" : "not from llgs",
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001385 thread.GetID());
Todd Fiala58a2f662014-08-12 17:02:07 +00001386 }
1387
1388 // Check for thread stop notification.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001389 if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP))
Todd Fiala58a2f662014-08-12 17:02:07 +00001390 {
1391 // This is a tgkill()-based stop.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001392 if (log)
1393 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
1394 __FUNCTION__,
1395 GetID (),
1396 thread.GetID());
1397
1398 // Check that we're not already marked with a stop reason.
1399 // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
1400 // the kernel signaled us with the thread stopping which we handled and marked as stopped,
1401 // and that, without an intervening resume, we received another stop. It is more likely
1402 // that we are missing the marking of a run state somewhere if we find that the thread was
1403 // marked as stopped.
1404 const StateType thread_state = thread.GetState();
1405 if (!StateIsStoppedState (thread_state, false))
Todd Fiala58a2f662014-08-12 17:02:07 +00001406 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001407 // An inferior thread has stopped because of a SIGSTOP we have sent it.
1408 // Generally, these are not important stops and we don't want to report them as
1409 // they are just used to stop other threads when one thread (the one with the
1410 // *real* stop reason) hits a breakpoint (watchpoint, etc...). However, in the
1411 // case of an asynchronous Interrupt(), this *is* the real stop reason, so we
1412 // leave the signal intact if this is the thread that was chosen as the
1413 // triggering thread.
1414 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID)
Chaoren Linaab58632015-02-03 01:50:57 +00001415 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001416 if (m_pending_notification_tid == thread.GetID())
1417 thread.SetStoppedBySignal(SIGSTOP, &info);
Pavel Labath0e1d7292015-08-20 09:06:12 +00001418 else
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001419 thread.SetStoppedWithNoReason();
1420
1421 SetCurrentThreadID (thread.GetID ());
1422 SignalIfAllThreadsStopped();
Chaoren Linaab58632015-02-03 01:50:57 +00001423 }
1424 else
1425 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001426 // We can end up here if stop was initiated by LLGS but by this time a
1427 // thread stop has occurred - maybe initiated by another event.
1428 Error error = ResumeThread(thread, thread.GetState(), 0);
1429 if (error.Fail() && log)
Chaoren Linaab58632015-02-03 01:50:57 +00001430 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001431 log->Printf("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s",
1432 __FUNCTION__, thread.GetID(), error.AsCString());
Chaoren Linaab58632015-02-03 01:50:57 +00001433 }
1434 }
Todd Fiala58a2f662014-08-12 17:02:07 +00001435 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001436 else
1437 {
1438 if (log)
1439 {
1440 // Retrieve the signal name if the thread was stopped by a signal.
1441 int stop_signo = 0;
1442 const bool stopped_by_signal = thread.IsStopped(&stop_signo);
1443 const char *signal_name = stopped_by_signal ? Host::GetSignalAsCString(stop_signo) : "<not stopped by signal>";
1444 if (!signal_name)
1445 signal_name = "<no-signal-name>";
1446
1447 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread was already marked as a stopped state (state=%s, signal=%d (%s)), leaving stop signal as is",
1448 __FUNCTION__,
1449 GetID (),
1450 thread.GetID(),
1451 StateAsCString (thread_state),
1452 stop_signo,
1453 signal_name);
1454 }
1455 SignalIfAllThreadsStopped();
1456 }
Todd Fiala58a2f662014-08-12 17:02:07 +00001457
1458 // Done handling.
Todd Fialaaf245d12014-06-30 21:05:18 +00001459 return;
1460 }
1461
1462 if (log)
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001463 log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, Host::GetSignalAsCString(signo));
Todd Fialaaf245d12014-06-30 21:05:18 +00001464
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001465 // This thread is stopped.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001466 thread.SetStoppedBySignal(signo, &info);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001467
1468 // Send a stop to the debugger after we get all other threads to stop.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001469 StopRunningThreads(thread.GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +00001470}
1471
Tamas Berghammere7708682015-04-22 10:00:23 +00001472namespace {
1473
1474struct EmulatorBaton
1475{
1476 NativeProcessLinux* m_process;
1477 NativeRegisterContext* m_reg_context;
Tamas Berghammere7708682015-04-22 10:00:23 +00001478
Pavel Labath6648fcc2015-04-27 09:21:14 +00001479 // eRegisterKindDWARF -> RegsiterValue
1480 std::unordered_map<uint32_t, RegisterValue> m_register_values;
1481
1482 EmulatorBaton(NativeProcessLinux* process, NativeRegisterContext* reg_context) :
Tamas Berghammere7708682015-04-22 10:00:23 +00001483 m_process(process), m_reg_context(reg_context) {}
1484};
1485
1486} // anonymous namespace
1487
1488static size_t
1489ReadMemoryCallback (EmulateInstruction *instruction,
1490 void *baton,
1491 const EmulateInstruction::Context &context,
1492 lldb::addr_t addr,
1493 void *dst,
1494 size_t length)
1495{
1496 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
1497
Chaoren Lin3eb4b452015-04-29 17:24:48 +00001498 size_t bytes_read;
Tamas Berghammere7708682015-04-22 10:00:23 +00001499 emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
1500 return bytes_read;
1501}
1502
1503static bool
1504ReadRegisterCallback (EmulateInstruction *instruction,
1505 void *baton,
1506 const RegisterInfo *reg_info,
1507 RegisterValue &reg_value)
1508{
1509 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
1510
Pavel Labath6648fcc2015-04-27 09:21:14 +00001511 auto it = emulator_baton->m_register_values.find(reg_info->kinds[eRegisterKindDWARF]);
1512 if (it != emulator_baton->m_register_values.end())
1513 {
1514 reg_value = it->second;
1515 return true;
1516 }
1517
Tamas Berghammere7708682015-04-22 10:00:23 +00001518 // The emulator only fill in the dwarf regsiter numbers (and in some case
1519 // the generic register numbers). Get the full register info from the
1520 // register context based on the dwarf register numbers.
1521 const RegisterInfo* full_reg_info = emulator_baton->m_reg_context->GetRegisterInfo(
1522 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
1523
1524 Error error = emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
Pavel Labath6648fcc2015-04-27 09:21:14 +00001525 if (error.Success())
Pavel Labath6648fcc2015-04-27 09:21:14 +00001526 return true;
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001527
Pavel Labath6648fcc2015-04-27 09:21:14 +00001528 return false;
Tamas Berghammere7708682015-04-22 10:00:23 +00001529}
1530
1531static bool
1532WriteRegisterCallback (EmulateInstruction *instruction,
1533 void *baton,
1534 const EmulateInstruction::Context &context,
1535 const RegisterInfo *reg_info,
1536 const RegisterValue &reg_value)
1537{
1538 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
Pavel Labath6648fcc2015-04-27 09:21:14 +00001539 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = reg_value;
Tamas Berghammere7708682015-04-22 10:00:23 +00001540 return true;
1541}
1542
1543static size_t
1544WriteMemoryCallback (EmulateInstruction *instruction,
1545 void *baton,
1546 const EmulateInstruction::Context &context,
1547 lldb::addr_t addr,
1548 const void *dst,
1549 size_t length)
1550{
1551 return length;
1552}
1553
1554static lldb::addr_t
1555ReadFlags (NativeRegisterContext* regsiter_context)
1556{
1557 const RegisterInfo* flags_info = regsiter_context->GetRegisterInfo(
1558 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1559 return regsiter_context->ReadRegisterAsUnsigned(flags_info, LLDB_INVALID_ADDRESS);
1560}
1561
1562Error
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001563NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadLinux &thread)
Tamas Berghammere7708682015-04-22 10:00:23 +00001564{
1565 Error error;
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001566 NativeRegisterContextSP register_context_sp = thread.GetRegisterContext();
Tamas Berghammere7708682015-04-22 10:00:23 +00001567
1568 std::unique_ptr<EmulateInstruction> emulator_ap(
1569 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, nullptr));
1570
1571 if (emulator_ap == nullptr)
1572 return Error("Instruction emulator not found!");
1573
1574 EmulatorBaton baton(this, register_context_sp.get());
1575 emulator_ap->SetBaton(&baton);
1576 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
1577 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
1578 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
1579 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
1580
1581 if (!emulator_ap->ReadInstruction())
1582 return Error("Read instruction failed!");
1583
Pavel Labath6648fcc2015-04-27 09:21:14 +00001584 bool emulation_result = emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
1585
1586 const RegisterInfo* reg_info_pc = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1587 const RegisterInfo* reg_info_flags = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1588
1589 auto pc_it = baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1590 auto flags_it = baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
1591
Tamas Berghammere7708682015-04-22 10:00:23 +00001592 lldb::addr_t next_pc;
1593 lldb::addr_t next_flags;
Pavel Labath6648fcc2015-04-27 09:21:14 +00001594 if (emulation_result)
Tamas Berghammere7708682015-04-22 10:00:23 +00001595 {
Pavel Labath6648fcc2015-04-27 09:21:14 +00001596 assert(pc_it != baton.m_register_values.end() && "Emulation was successfull but PC wasn't updated");
1597 next_pc = pc_it->second.GetAsUInt64();
1598
1599 if (flags_it != baton.m_register_values.end())
1600 next_flags = flags_it->second.GetAsUInt64();
Tamas Berghammere7708682015-04-22 10:00:23 +00001601 else
1602 next_flags = ReadFlags (register_context_sp.get());
1603 }
Pavel Labath6648fcc2015-04-27 09:21:14 +00001604 else if (pc_it == baton.m_register_values.end())
Tamas Berghammere7708682015-04-22 10:00:23 +00001605 {
1606 // Emulate instruction failed and it haven't changed PC. Advance PC
1607 // with the size of the current opcode because the emulation of all
1608 // PC modifying instruction should be successful. The failure most
1609 // likely caused by a not supported instruction which don't modify PC.
1610 next_pc = register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
1611 next_flags = ReadFlags (register_context_sp.get());
1612 }
1613 else
1614 {
1615 // The instruction emulation failed after it modified the PC. It is an
1616 // unknown error where we can't continue because the next instruction is
1617 // modifying the PC but we don't know how.
1618 return Error ("Instruction emulation failed unexpectedly.");
1619 }
1620
1621 if (m_arch.GetMachine() == llvm::Triple::arm)
1622 {
1623 if (next_flags & 0x20)
1624 {
1625 // Thumb mode
1626 error = SetSoftwareBreakpoint(next_pc, 2);
1627 }
1628 else
1629 {
1630 // Arm mode
1631 error = SetSoftwareBreakpoint(next_pc, 4);
1632 }
1633 }
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001634 else if (m_arch.GetMachine() == llvm::Triple::mips64
Jaydeep Patilc60c9452015-06-23 03:37:08 +00001635 || m_arch.GetMachine() == llvm::Triple::mips64el
1636 || m_arch.GetMachine() == llvm::Triple::mips
1637 || m_arch.GetMachine() == llvm::Triple::mipsel)
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001638 error = SetSoftwareBreakpoint(next_pc, 4);
Tamas Berghammere7708682015-04-22 10:00:23 +00001639 else
1640 {
1641 // No size hint is given for the next breakpoint
1642 error = SetSoftwareBreakpoint(next_pc, 0);
1643 }
1644
Tamas Berghammere7708682015-04-22 10:00:23 +00001645 if (error.Fail())
1646 return error;
1647
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001648 m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
Tamas Berghammere7708682015-04-22 10:00:23 +00001649
1650 return Error();
1651}
1652
1653bool
1654NativeProcessLinux::SupportHardwareSingleStepping() const
1655{
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001656 if (m_arch.GetMachine() == llvm::Triple::arm
Jaydeep Patilc60c9452015-06-23 03:37:08 +00001657 || m_arch.GetMachine() == llvm::Triple::mips64 || m_arch.GetMachine() == llvm::Triple::mips64el
1658 || m_arch.GetMachine() == llvm::Triple::mips || m_arch.GetMachine() == llvm::Triple::mipsel)
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001659 return false;
1660 return true;
Tamas Berghammere7708682015-04-22 10:00:23 +00001661}
1662
Todd Fialaaf245d12014-06-30 21:05:18 +00001663Error
1664NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
1665{
Todd Fialaaf245d12014-06-30 21:05:18 +00001666 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1667 if (log)
1668 log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
1669
Tamas Berghammere7708682015-04-22 10:00:23 +00001670 bool software_single_step = !SupportHardwareSingleStepping();
Todd Fialaaf245d12014-06-30 21:05:18 +00001671
Tamas Berghammere7708682015-04-22 10:00:23 +00001672 if (software_single_step)
1673 {
1674 for (auto thread_sp : m_threads)
1675 {
1676 assert (thread_sp && "thread list should not contain NULL threads");
1677
1678 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
1679 if (action == nullptr)
1680 continue;
1681
1682 if (action->state == eStateStepping)
1683 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001684 Error error = SetupSoftwareSingleStepping(static_cast<NativeThreadLinux &>(*thread_sp));
Tamas Berghammere7708682015-04-22 10:00:23 +00001685 if (error.Fail())
1686 return error;
1687 }
1688 }
1689 }
1690
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001691 for (auto thread_sp : m_threads)
Todd Fialaaf245d12014-06-30 21:05:18 +00001692 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001693 assert (thread_sp && "thread list should not contain NULL threads");
1694
1695 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
1696
1697 if (action == nullptr)
Todd Fialaaf245d12014-06-30 21:05:18 +00001698 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00001699 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001700 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
1701 __FUNCTION__, GetID (), thread_sp->GetID ());
1702 continue;
1703 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001704
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001705 if (log)
1706 {
1707 log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
1708 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
1709 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001710
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001711 switch (action->state)
1712 {
1713 case eStateRunning:
Pavel Labath0e1d7292015-08-20 09:06:12 +00001714 case eStateStepping:
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001715 {
1716 // Run the thread, possibly feeding it the signal.
1717 const int signo = action->signal;
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001718 ResumeThread(static_cast<NativeThreadLinux &>(*thread_sp), action->state, signo);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001719 break;
1720 }
1721
1722 case eStateSuspended:
1723 case eStateStopped:
Pavel Labath108c3252015-05-12 09:03:18 +00001724 lldbassert(0 && "Unexpected state");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001725
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001726 default:
1727 return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
1728 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001729 }
1730 }
1731
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001732 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00001733}
1734
1735Error
1736NativeProcessLinux::Halt ()
1737{
1738 Error error;
1739
Todd Fialaaf245d12014-06-30 21:05:18 +00001740 if (kill (GetID (), SIGSTOP) != 0)
1741 error.SetErrorToErrno ();
1742
1743 return error;
1744}
1745
1746Error
1747NativeProcessLinux::Detach ()
1748{
1749 Error error;
1750
Todd Fialaaf245d12014-06-30 21:05:18 +00001751 // Stop monitoring the inferior.
Pavel Labath19cbe962015-07-21 13:20:32 +00001752 m_sigchld_handle.reset();
Todd Fialaaf245d12014-06-30 21:05:18 +00001753
Pavel Labath7a9495b2015-09-01 15:00:51 +00001754 // Tell ptrace to detach from the process.
1755 if (GetID () == LLDB_INVALID_PROCESS_ID)
1756 return error;
1757
1758 for (auto thread_sp : m_threads)
1759 {
1760 Error e = Detach(thread_sp->GetID());
1761 if (e.Fail())
1762 error = e; // Save the error, but still attempt to detach from other threads.
1763 }
1764
Todd Fialaaf245d12014-06-30 21:05:18 +00001765 return error;
1766}
1767
1768Error
1769NativeProcessLinux::Signal (int signo)
1770{
1771 Error error;
1772
1773 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1774 if (log)
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001775 log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
1776 __FUNCTION__, signo, Host::GetSignalAsCString(signo), GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +00001777
1778 if (kill(GetID(), signo))
1779 error.SetErrorToErrno();
1780
1781 return error;
1782}
1783
1784Error
Chaoren Line9547b82015-02-03 01:51:00 +00001785NativeProcessLinux::Interrupt ()
1786{
1787 // Pick a running thread (or if none, a not-dead stopped thread) as
1788 // the chosen thread that will be the stop-reason thread.
Chaoren Line9547b82015-02-03 01:51:00 +00001789 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1790
1791 NativeThreadProtocolSP running_thread_sp;
1792 NativeThreadProtocolSP stopped_thread_sp;
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001793
1794 if (log)
1795 log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
1796
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001797 for (auto thread_sp : m_threads)
Chaoren Line9547b82015-02-03 01:51:00 +00001798 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001799 // The thread shouldn't be null but lets just cover that here.
1800 if (!thread_sp)
1801 continue;
Chaoren Line9547b82015-02-03 01:51:00 +00001802
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001803 // If we have a running or stepping thread, we'll call that the
1804 // target of the interrupt.
1805 const auto thread_state = thread_sp->GetState ();
1806 if (thread_state == eStateRunning ||
1807 thread_state == eStateStepping)
Chaoren Line9547b82015-02-03 01:51:00 +00001808 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001809 running_thread_sp = thread_sp;
1810 break;
1811 }
1812 else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
1813 {
1814 // Remember the first non-dead stopped thread. We'll use that as a backup if there are no running threads.
1815 stopped_thread_sp = thread_sp;
Chaoren Line9547b82015-02-03 01:51:00 +00001816 }
1817 }
1818
1819 if (!running_thread_sp && !stopped_thread_sp)
1820 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001821 Error error("found no running/stepping or live stopped threads as target for interrupt");
Chaoren Line9547b82015-02-03 01:51:00 +00001822 if (log)
Chaoren Line9547b82015-02-03 01:51:00 +00001823 log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001824
Chaoren Line9547b82015-02-03 01:51:00 +00001825 return error;
1826 }
1827
1828 NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
1829
1830 if (log)
1831 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
1832 __FUNCTION__,
1833 GetID (),
1834 running_thread_sp ? "running" : "stopped",
1835 deferred_signal_thread_sp->GetID ());
1836
Pavel Labathed89c7f2015-05-06 12:22:37 +00001837 StopRunningThreads(deferred_signal_thread_sp->GetID());
Pavel Labath45f5cb32015-05-05 15:05:50 +00001838
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001839 return Error();
Chaoren Line9547b82015-02-03 01:51:00 +00001840}
1841
1842Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001843NativeProcessLinux::Kill ()
1844{
1845 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1846 if (log)
1847 log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
1848
1849 Error error;
1850
1851 switch (m_state)
1852 {
1853 case StateType::eStateInvalid:
1854 case StateType::eStateExited:
1855 case StateType::eStateCrashed:
1856 case StateType::eStateDetached:
1857 case StateType::eStateUnloaded:
1858 // Nothing to do - the process is already dead.
1859 if (log)
1860 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
1861 return error;
1862
1863 case StateType::eStateConnected:
1864 case StateType::eStateAttaching:
1865 case StateType::eStateLaunching:
1866 case StateType::eStateStopped:
1867 case StateType::eStateRunning:
1868 case StateType::eStateStepping:
1869 case StateType::eStateSuspended:
1870 // We can try to kill a process in these states.
1871 break;
1872 }
1873
1874 if (kill (GetID (), SIGKILL) != 0)
1875 {
1876 error.SetErrorToErrno ();
1877 return error;
1878 }
1879
1880 return error;
1881}
1882
1883static Error
1884ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
1885{
1886 memory_region_info.Clear();
1887
1888 StringExtractor line_extractor (maps_line.c_str ());
1889
1890 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode pathname
1891 // perms: rwxp (letter is present if set, '-' if not, final character is p=private, s=shared).
1892
1893 // Parse out the starting address
1894 lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
1895
1896 // Parse out hyphen separating start and end address from range.
1897 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
1898 return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
1899
1900 // Parse out the ending address
1901 lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
1902
1903 // Parse out the space after the address.
1904 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
1905 return Error ("malformed /proc/{pid}/maps entry, missing space after range");
1906
1907 // Save the range.
1908 memory_region_info.GetRange ().SetRangeBase (start_address);
1909 memory_region_info.GetRange ().SetRangeEnd (end_address);
1910
Howard Hellyerad007562016-07-07 08:21:28 +00001911 // Any memory region in /proc/{pid}/maps is by definition mapped into the process.
1912 memory_region_info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
1913
Todd Fialaaf245d12014-06-30 21:05:18 +00001914 // Parse out each permission entry.
1915 if (line_extractor.GetBytesLeft () < 4)
1916 return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
1917
1918 // Handle read permission.
1919 const char read_perm_char = line_extractor.GetChar ();
1920 if (read_perm_char == 'r')
1921 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
Tamas Berghammerc73301b2016-07-11 13:43:27 +00001922 else if (read_perm_char == '-')
Todd Fialaaf245d12014-06-30 21:05:18 +00001923 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
Tamas Berghammerc73301b2016-07-11 13:43:27 +00001924 else
1925 return Error ("unexpected /proc/{pid}/maps read permission char");
Todd Fialaaf245d12014-06-30 21:05:18 +00001926
1927 // Handle write permission.
1928 const char write_perm_char = line_extractor.GetChar ();
1929 if (write_perm_char == 'w')
1930 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
Tamas Berghammerc73301b2016-07-11 13:43:27 +00001931 else if (write_perm_char == '-')
Todd Fialaaf245d12014-06-30 21:05:18 +00001932 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
Tamas Berghammerc73301b2016-07-11 13:43:27 +00001933 else
1934 return Error ("unexpected /proc/{pid}/maps write permission char");
Todd Fialaaf245d12014-06-30 21:05:18 +00001935
1936 // Handle execute permission.
1937 const char exec_perm_char = line_extractor.GetChar ();
1938 if (exec_perm_char == 'x')
1939 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
Tamas Berghammerc73301b2016-07-11 13:43:27 +00001940 else if (exec_perm_char == '-')
Todd Fialaaf245d12014-06-30 21:05:18 +00001941 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
Tamas Berghammerc73301b2016-07-11 13:43:27 +00001942 else
1943 return Error ("unexpected /proc/{pid}/maps exec permission char");
Todd Fialaaf245d12014-06-30 21:05:18 +00001944
1945 return Error ();
1946}
1947
1948Error
1949NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
1950{
1951 // FIXME review that the final memory region returned extends to the end of the virtual address space,
1952 // with no perms if it is not mapped.
1953
1954 // Use an approach that reads memory regions from /proc/{pid}/maps.
1955 // Assume proc maps entries are in ascending order.
1956 // FIXME assert if we find differently.
Todd Fialaaf245d12014-06-30 21:05:18 +00001957
1958 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1959 Error error;
1960
1961 if (m_supports_mem_region == LazyBool::eLazyBoolNo)
1962 {
1963 // We're done.
1964 error.SetErrorString ("unsupported");
1965 return error;
1966 }
1967
1968 // If our cache is empty, pull the latest. There should always be at least one memory region
1969 // if memory region handling is supported.
1970 if (m_mem_region_cache.empty ())
1971 {
1972 error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
1973 [&] (const std::string &line) -> bool
1974 {
1975 MemoryRegionInfo info;
1976 const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
1977 if (parse_error.Success ())
1978 {
1979 m_mem_region_cache.push_back (info);
1980 return true;
1981 }
1982 else
1983 {
1984 if (log)
1985 log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
1986 return false;
1987 }
1988 });
1989
1990 // If we had an error, we'll mark unsupported.
1991 if (error.Fail ())
1992 {
1993 m_supports_mem_region = LazyBool::eLazyBoolNo;
1994 return error;
1995 }
1996 else if (m_mem_region_cache.empty ())
1997 {
1998 // No entries after attempting to read them. This shouldn't happen if /proc/{pid}/maps
1999 // is supported. Assume we don't support map entries via procfs.
2000 if (log)
2001 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
2002 m_supports_mem_region = LazyBool::eLazyBoolNo;
2003 error.SetErrorString ("not supported");
2004 return error;
2005 }
2006
2007 if (log)
2008 log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ());
2009
2010 // We support memory retrieval, remember that.
2011 m_supports_mem_region = LazyBool::eLazyBoolYes;
2012 }
2013 else
2014 {
2015 if (log)
2016 log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2017 }
2018
2019 lldb::addr_t prev_base_address = 0;
2020
2021 // FIXME start by finding the last region that is <= target address using binary search. Data is sorted.
2022 // There can be a ton of regions on pthreads apps with lots of threads.
2023 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
2024 {
2025 MemoryRegionInfo &proc_entry_info = *it;
2026
2027 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
2028 assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
2029 prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
2030
2031 // If the target address comes before this entry, indicate distance to next region.
2032 if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
2033 {
2034 range_info.GetRange ().SetRangeBase (load_addr);
2035 range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
2036 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2037 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2038 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
Howard Hellyerad007562016-07-07 08:21:28 +00002039 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
Todd Fialaaf245d12014-06-30 21:05:18 +00002040
2041 return error;
2042 }
2043 else if (proc_entry_info.GetRange ().Contains (load_addr))
2044 {
2045 // The target address is within the memory region we're processing here.
2046 range_info = proc_entry_info;
2047 return error;
2048 }
2049
2050 // The target memory address comes somewhere after the region we just parsed.
2051 }
2052
Tamas Berghammer09839c32015-07-03 09:30:19 +00002053 // If we made it here, we didn't find an entry that contained the given address. Return the
2054 // load_addr as start and the amount of bytes betwwen load address and the end of the memory as
2055 // size.
2056 range_info.GetRange ().SetRangeBase (load_addr);
Howard Hellyerad007562016-07-07 08:21:28 +00002057 range_info.GetRange ().SetRangeEnd(LLDB_INVALID_ADDRESS);
Tamas Berghammer09839c32015-07-03 09:30:19 +00002058 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2059 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2060 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
Howard Hellyerad007562016-07-07 08:21:28 +00002061 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
Todd Fialaaf245d12014-06-30 21:05:18 +00002062 return error;
2063}
2064
2065void
2066NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
2067{
2068 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2069 if (log)
2070 log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
2071
Todd Fialaaf245d12014-06-30 21:05:18 +00002072 if (log)
2073 log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2074 m_mem_region_cache.clear ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002075}
2076
2077Error
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002078NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr)
Todd Fialaaf245d12014-06-30 21:05:18 +00002079{
2080 // FIXME implementing this requires the equivalent of
2081 // InferiorCallPOSIX::InferiorCallMmap, which depends on
2082 // functional ThreadPlans working with Native*Protocol.
2083#if 1
2084 return Error ("not implemented yet");
2085#else
2086 addr = LLDB_INVALID_ADDRESS;
2087
2088 unsigned prot = 0;
2089 if (permissions & lldb::ePermissionsReadable)
2090 prot |= eMmapProtRead;
2091 if (permissions & lldb::ePermissionsWritable)
2092 prot |= eMmapProtWrite;
2093 if (permissions & lldb::ePermissionsExecutable)
2094 prot |= eMmapProtExec;
2095
2096 // TODO implement this directly in NativeProcessLinux
2097 // (and lift to NativeProcessPOSIX if/when that class is
2098 // refactored out).
2099 if (InferiorCallMmap(this, addr, 0, size, prot,
2100 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
2101 m_addr_to_mmap_size[addr] = size;
2102 return Error ();
2103 } else {
2104 addr = LLDB_INVALID_ADDRESS;
2105 return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
2106 }
2107#endif
2108}
2109
2110Error
2111NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
2112{
2113 // FIXME see comments in AllocateMemory - required lower-level
2114 // bits not in place yet (ThreadPlans)
2115 return Error ("not implemented");
2116}
2117
2118lldb::addr_t
2119NativeProcessLinux::GetSharedLibraryInfoAddress ()
2120{
Todd Fialaaf245d12014-06-30 21:05:18 +00002121 // punt on this for now
2122 return LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00002123}
2124
2125size_t
2126NativeProcessLinux::UpdateThreads ()
2127{
2128 // The NativeProcessLinux monitoring threads are always up to date
2129 // with respect to thread state and they keep the thread list
2130 // populated properly. All this method needs to do is return the
2131 // thread count.
Todd Fialaaf245d12014-06-30 21:05:18 +00002132 return m_threads.size ();
2133}
2134
2135bool
2136NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
2137{
2138 arch = m_arch;
2139 return true;
2140}
2141
2142Error
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002143NativeProcessLinux::GetSoftwareBreakpointPCOffset(uint32_t &actual_opcode_size)
Todd Fialaaf245d12014-06-30 21:05:18 +00002144{
2145 // FIXME put this behind a breakpoint protocol class that can be
2146 // set per architecture. Need ARM, MIPS support here.
2147 static const uint8_t g_i386_opcode [] = { 0xCC };
Ulrich Weigandbb00d0b2016-04-14 14:28:34 +00002148 static const uint8_t g_s390x_opcode[] = { 0x00, 0x01 };
Todd Fialaaf245d12014-06-30 21:05:18 +00002149
2150 switch (m_arch.GetMachine ())
2151 {
2152 case llvm::Triple::x86:
2153 case llvm::Triple::x86_64:
2154 actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
2155 return Error ();
2156
Ulrich Weigandbb00d0b2016-04-14 14:28:34 +00002157 case llvm::Triple::systemz:
2158 actual_opcode_size = static_cast<uint32_t> (sizeof(g_s390x_opcode));
2159 return Error ();
2160
Tamas Berghammerff7fd902015-07-03 12:51:30 +00002161 case llvm::Triple::arm:
2162 case llvm::Triple::aarch64:
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00002163 case llvm::Triple::mips64:
2164 case llvm::Triple::mips64el:
Sagar Thakurce815e42015-06-03 10:14:24 +00002165 case llvm::Triple::mips:
2166 case llvm::Triple::mipsel:
Tamas Berghammerff7fd902015-07-03 12:51:30 +00002167 // On these architectures the PC don't get updated for breakpoint hits
Jaydeep Patilc60c9452015-06-23 03:37:08 +00002168 actual_opcode_size = 0;
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00002169 return Error ();
2170
Todd Fialaaf245d12014-06-30 21:05:18 +00002171 default:
2172 assert(false && "CPU type not supported!");
2173 return Error ("CPU type not supported");
2174 }
2175}
2176
2177Error
2178NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
2179{
2180 if (hardware)
2181 return Error ("NativeProcessLinux does not support hardware breakpoints");
2182 else
2183 return SetSoftwareBreakpoint (addr, size);
2184}
2185
2186Error
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002187NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint,
2188 size_t &actual_opcode_size,
2189 const uint8_t *&trap_opcode_bytes)
Todd Fialaaf245d12014-06-30 21:05:18 +00002190{
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002191 // FIXME put this behind a breakpoint protocol class that can be set per
2192 // architecture. Need MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00002193 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Tamas Berghammerbe379e12016-02-16 15:14:36 +00002194 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
2195 // linux kernel does otherwise.
2196 static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 };
Todd Fialaaf245d12014-06-30 21:05:18 +00002197 static const uint8_t g_i386_opcode [] = { 0xCC };
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00002198 static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00002199 static const uint8_t g_mips64el_opcode[] = { 0x0d, 0x00, 0x00, 0x00 };
Ulrich Weigandbb00d0b2016-04-14 14:28:34 +00002200 static const uint8_t g_s390x_opcode[] = { 0x00, 0x01 };
Tamas Berghammerbe379e12016-02-16 15:14:36 +00002201 static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde };
Todd Fialaaf245d12014-06-30 21:05:18 +00002202
2203 switch (m_arch.GetMachine ())
2204 {
Todd Fiala2afc5962014-08-21 16:42:31 +00002205 case llvm::Triple::aarch64:
2206 trap_opcode_bytes = g_aarch64_opcode;
2207 actual_opcode_size = sizeof(g_aarch64_opcode);
2208 return Error ();
2209
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002210 case llvm::Triple::arm:
2211 switch (trap_opcode_size_hint)
2212 {
2213 case 2:
2214 trap_opcode_bytes = g_thumb_breakpoint_opcode;
2215 actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
2216 return Error ();
2217 case 4:
2218 trap_opcode_bytes = g_arm_breakpoint_opcode;
2219 actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
2220 return Error ();
2221 default:
2222 assert(false && "Unrecognised trap opcode size hint!");
2223 return Error ("Unrecognised trap opcode size hint!");
2224 }
2225
Todd Fialaaf245d12014-06-30 21:05:18 +00002226 case llvm::Triple::x86:
2227 case llvm::Triple::x86_64:
2228 trap_opcode_bytes = g_i386_opcode;
2229 actual_opcode_size = sizeof(g_i386_opcode);
2230 return Error ();
2231
Sagar Thakurce815e42015-06-03 10:14:24 +00002232 case llvm::Triple::mips:
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00002233 case llvm::Triple::mips64:
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00002234 trap_opcode_bytes = g_mips64_opcode;
2235 actual_opcode_size = sizeof(g_mips64_opcode);
2236 return Error ();
2237
Sagar Thakurce815e42015-06-03 10:14:24 +00002238 case llvm::Triple::mipsel:
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00002239 case llvm::Triple::mips64el:
2240 trap_opcode_bytes = g_mips64el_opcode;
2241 actual_opcode_size = sizeof(g_mips64el_opcode);
2242 return Error ();
2243
Ulrich Weigandbb00d0b2016-04-14 14:28:34 +00002244 case llvm::Triple::systemz:
2245 trap_opcode_bytes = g_s390x_opcode;
2246 actual_opcode_size = sizeof(g_s390x_opcode);
2247 return Error ();
2248
Todd Fialaaf245d12014-06-30 21:05:18 +00002249 default:
2250 assert(false && "CPU type not supported!");
2251 return Error ("CPU type not supported");
2252 }
2253}
2254
2255#if 0
2256ProcessMessage::CrashReason
2257NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
2258{
2259 ProcessMessage::CrashReason reason;
2260 assert(info->si_signo == SIGSEGV);
2261
2262 reason = ProcessMessage::eInvalidCrashReason;
2263
2264 switch (info->si_code)
2265 {
2266 default:
2267 assert(false && "unexpected si_code for SIGSEGV");
2268 break;
2269 case SI_KERNEL:
2270 // Linux will occasionally send spurious SI_KERNEL codes.
2271 // (this is poorly documented in sigaction)
2272 // One way to get this is via unaligned SIMD loads.
2273 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
2274 break;
2275 case SEGV_MAPERR:
2276 reason = ProcessMessage::eInvalidAddress;
2277 break;
2278 case SEGV_ACCERR:
2279 reason = ProcessMessage::ePrivilegedAddress;
2280 break;
2281 }
2282
2283 return reason;
2284}
2285#endif
2286
2287
2288#if 0
2289ProcessMessage::CrashReason
2290NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
2291{
2292 ProcessMessage::CrashReason reason;
2293 assert(info->si_signo == SIGILL);
2294
2295 reason = ProcessMessage::eInvalidCrashReason;
2296
2297 switch (info->si_code)
2298 {
2299 default:
2300 assert(false && "unexpected si_code for SIGILL");
2301 break;
2302 case ILL_ILLOPC:
2303 reason = ProcessMessage::eIllegalOpcode;
2304 break;
2305 case ILL_ILLOPN:
2306 reason = ProcessMessage::eIllegalOperand;
2307 break;
2308 case ILL_ILLADR:
2309 reason = ProcessMessage::eIllegalAddressingMode;
2310 break;
2311 case ILL_ILLTRP:
2312 reason = ProcessMessage::eIllegalTrap;
2313 break;
2314 case ILL_PRVOPC:
2315 reason = ProcessMessage::ePrivilegedOpcode;
2316 break;
2317 case ILL_PRVREG:
2318 reason = ProcessMessage::ePrivilegedRegister;
2319 break;
2320 case ILL_COPROC:
2321 reason = ProcessMessage::eCoprocessorError;
2322 break;
2323 case ILL_BADSTK:
2324 reason = ProcessMessage::eInternalStackError;
2325 break;
2326 }
2327
2328 return reason;
2329}
2330#endif
2331
2332#if 0
2333ProcessMessage::CrashReason
2334NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
2335{
2336 ProcessMessage::CrashReason reason;
2337 assert(info->si_signo == SIGFPE);
2338
2339 reason = ProcessMessage::eInvalidCrashReason;
2340
2341 switch (info->si_code)
2342 {
2343 default:
2344 assert(false && "unexpected si_code for SIGFPE");
2345 break;
2346 case FPE_INTDIV:
2347 reason = ProcessMessage::eIntegerDivideByZero;
2348 break;
2349 case FPE_INTOVF:
2350 reason = ProcessMessage::eIntegerOverflow;
2351 break;
2352 case FPE_FLTDIV:
2353 reason = ProcessMessage::eFloatDivideByZero;
2354 break;
2355 case FPE_FLTOVF:
2356 reason = ProcessMessage::eFloatOverflow;
2357 break;
2358 case FPE_FLTUND:
2359 reason = ProcessMessage::eFloatUnderflow;
2360 break;
2361 case FPE_FLTRES:
2362 reason = ProcessMessage::eFloatInexactResult;
2363 break;
2364 case FPE_FLTINV:
2365 reason = ProcessMessage::eFloatInvalidOperation;
2366 break;
2367 case FPE_FLTSUB:
2368 reason = ProcessMessage::eFloatSubscriptRange;
2369 break;
2370 }
2371
2372 return reason;
2373}
2374#endif
2375
2376#if 0
2377ProcessMessage::CrashReason
2378NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
2379{
2380 ProcessMessage::CrashReason reason;
2381 assert(info->si_signo == SIGBUS);
2382
2383 reason = ProcessMessage::eInvalidCrashReason;
2384
2385 switch (info->si_code)
2386 {
2387 default:
2388 assert(false && "unexpected si_code for SIGBUS");
2389 break;
2390 case BUS_ADRALN:
2391 reason = ProcessMessage::eIllegalAlignment;
2392 break;
2393 case BUS_ADRERR:
2394 reason = ProcessMessage::eIllegalAddress;
2395 break;
2396 case BUS_OBJERR:
2397 reason = ProcessMessage::eHardwareError;
2398 break;
2399 }
2400
2401 return reason;
2402}
2403#endif
2404
Todd Fialaaf245d12014-06-30 21:05:18 +00002405Error
Chaoren Lin26438d22015-05-05 17:50:53 +00002406NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
Todd Fialaaf245d12014-06-30 21:05:18 +00002407{
Pavel Labathdf7c6992015-06-17 18:38:49 +00002408 if (ProcessVmReadvSupported()) {
2409 // The process_vm_readv path is about 50 times faster than ptrace api. We want to use
2410 // this syscall if it is supported.
2411
2412 const ::pid_t pid = GetID();
2413
2414 struct iovec local_iov, remote_iov;
2415 local_iov.iov_base = buf;
2416 local_iov.iov_len = size;
2417 remote_iov.iov_base = reinterpret_cast<void *>(addr);
2418 remote_iov.iov_len = size;
2419
2420 bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
2421 const bool success = bytes_read == size;
2422
2423 Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2424 if (log)
2425 log->Printf ("NativeProcessLinux::%s using process_vm_readv to read %zd bytes from inferior address 0x%" PRIx64": %s",
2426 __FUNCTION__, size, addr, success ? "Success" : strerror(errno));
2427
2428 if (success)
2429 return Error();
2430 // else
2431 // the call failed for some reason, let's retry the read using ptrace api.
2432 }
2433
Pavel Labath19cbe962015-07-21 13:20:32 +00002434 unsigned char *dst = static_cast<unsigned char*>(buf);
2435 size_t remainder;
2436 long data;
2437
2438 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
2439 if (log)
2440 ProcessPOSIXLog::IncNestLevel();
2441 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
2442 log->Printf ("NativeProcessLinux::%s(%p, %p, %zd, _)", __FUNCTION__, (void*)addr, buf, size);
2443
2444 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
2445 {
2446 Error error = NativeProcessLinux::PtraceWrapper(PTRACE_PEEKDATA, GetID(), (void*)addr, nullptr, 0, &data);
2447 if (error.Fail())
2448 {
2449 if (log)
2450 ProcessPOSIXLog::DecNestLevel();
2451 return error;
2452 }
2453
2454 remainder = size - bytes_read;
2455 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
2456
2457 // Copy the data into our buffer
Mohit K. Bhakkadf6ef1872015-12-23 12:34:58 +00002458 memcpy(dst, &data, remainder);
Pavel Labath19cbe962015-07-21 13:20:32 +00002459
2460 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2461 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
2462 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2463 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
2464 {
2465 uintptr_t print_dst = 0;
2466 // Format bytes from data by moving into print_dst for log output
2467 for (unsigned i = 0; i < remainder; ++i)
2468 print_dst |= (((data >> i*8) & 0xFF) << i*8);
Pavel Labath79203992015-07-23 13:07:37 +00002469 log->Printf ("NativeProcessLinux::%s() [0x%" PRIx64 "]:0x%" PRIx64 " (0x%" PRIx64 ")",
2470 __FUNCTION__, addr, uint64_t(print_dst), uint64_t(data));
Pavel Labath19cbe962015-07-21 13:20:32 +00002471 }
2472 addr += k_ptrace_word_size;
2473 dst += k_ptrace_word_size;
2474 }
2475
2476 if (log)
2477 ProcessPOSIXLog::DecNestLevel();
2478 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00002479}
2480
2481Error
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002482NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
2483{
2484 Error error = ReadMemory(addr, buf, size, bytes_read);
2485 if (error.Fail()) return error;
2486 return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
2487}
2488
2489Error
2490NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written)
Todd Fialaaf245d12014-06-30 21:05:18 +00002491{
Pavel Labath19cbe962015-07-21 13:20:32 +00002492 const unsigned char *src = static_cast<const unsigned char*>(buf);
2493 size_t remainder;
2494 Error error;
2495
2496 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
2497 if (log)
2498 ProcessPOSIXLog::IncNestLevel();
2499 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
Pavel Labath79203992015-07-23 13:07:37 +00002500 log->Printf ("NativeProcessLinux::%s(0x%" PRIx64 ", %p, %zu)", __FUNCTION__, addr, buf, size);
Pavel Labath19cbe962015-07-21 13:20:32 +00002501
2502 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
2503 {
2504 remainder = size - bytes_written;
2505 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
2506
2507 if (remainder == k_ptrace_word_size)
2508 {
2509 unsigned long data = 0;
Mohit K. Bhakkadf6ef1872015-12-23 12:34:58 +00002510 memcpy(&data, src, k_ptrace_word_size);
Pavel Labath19cbe962015-07-21 13:20:32 +00002511
2512 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2513 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
2514 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2515 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
2516 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
2517 (void*)addr, *(const unsigned long*)src, data);
2518
2519 error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(), (void*)addr, (void*)data);
2520 if (error.Fail())
2521 {
2522 if (log)
2523 ProcessPOSIXLog::DecNestLevel();
2524 return error;
2525 }
2526 }
2527 else
2528 {
2529 unsigned char buff[8];
2530 size_t bytes_read;
2531 error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
2532 if (error.Fail())
2533 {
2534 if (log)
2535 ProcessPOSIXLog::DecNestLevel();
2536 return error;
2537 }
2538
2539 memcpy(buff, src, remainder);
2540
2541 size_t bytes_written_rec;
2542 error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
2543 if (error.Fail())
2544 {
2545 if (log)
2546 ProcessPOSIXLog::DecNestLevel();
2547 return error;
2548 }
2549
2550 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2551 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
2552 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2553 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
2554 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
2555 (void*)addr, *(const unsigned long*)src, *(unsigned long*)buff);
2556 }
2557
2558 addr += k_ptrace_word_size;
2559 src += k_ptrace_word_size;
2560 }
2561 if (log)
2562 ProcessPOSIXLog::DecNestLevel();
2563 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002564}
2565
Chaoren Lin97ccc292015-02-03 01:51:12 +00002566Error
Chaoren Lin97ccc292015-02-03 01:51:12 +00002567NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
Todd Fialaaf245d12014-06-30 21:05:18 +00002568{
Pavel Labath19cbe962015-07-21 13:20:32 +00002569 return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
Todd Fialaaf245d12014-06-30 21:05:18 +00002570}
2571
Chaoren Lin97ccc292015-02-03 01:51:12 +00002572Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002573NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
2574{
Pavel Labath19cbe962015-07-21 13:20:32 +00002575 return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
Todd Fialaaf245d12014-06-30 21:05:18 +00002576}
2577
Tamas Berghammerdb264a62015-03-31 09:52:22 +00002578Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002579NativeProcessLinux::Detach(lldb::tid_t tid)
2580{
Chaoren Lin97ccc292015-02-03 01:51:12 +00002581 if (tid == LLDB_INVALID_THREAD_ID)
2582 return Error();
2583
Pavel Labath19cbe962015-07-21 13:20:32 +00002584 return PtraceWrapper(PTRACE_DETACH, tid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002585}
2586
2587bool
Chaoren Lind3173f32015-05-29 19:52:29 +00002588NativeProcessLinux::DupDescriptor(const FileSpec &file_spec, int fd, int flags)
Todd Fialaaf245d12014-06-30 21:05:18 +00002589{
Chaoren Lind3173f32015-05-29 19:52:29 +00002590 int target_fd = open(file_spec.GetCString(), flags, 0666);
Todd Fialaaf245d12014-06-30 21:05:18 +00002591
2592 if (target_fd == -1)
2593 return false;
2594
Pavel Labath493c3a12015-02-04 10:36:57 +00002595 if (dup2(target_fd, fd) == -1)
2596 return false;
2597
2598 return (close(target_fd) == -1) ? false : true;
Todd Fialaaf245d12014-06-30 21:05:18 +00002599}
2600
Todd Fialaaf245d12014-06-30 21:05:18 +00002601bool
2602NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
2603{
2604 for (auto thread_sp : m_threads)
2605 {
2606 assert (thread_sp && "thread list should not contain NULL threads");
2607 if (thread_sp->GetID () == thread_id)
2608 {
2609 // We have this thread.
2610 return true;
2611 }
2612 }
2613
2614 // We don't have this thread.
2615 return false;
2616}
2617
Todd Fialaaf245d12014-06-30 21:05:18 +00002618bool
2619NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
2620{
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002621 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
2622
2623 if (log)
2624 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, thread_id);
2625
2626 bool found = false;
2627
Todd Fialaaf245d12014-06-30 21:05:18 +00002628 for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
2629 {
2630 if (*it && ((*it)->GetID () == thread_id))
2631 {
2632 m_threads.erase (it);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002633 found = true;
2634 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00002635 }
2636 }
2637
Pavel Labath0e1d7292015-08-20 09:06:12 +00002638 SignalIfAllThreadsStopped();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002639
2640 return found;
Todd Fialaaf245d12014-06-30 21:05:18 +00002641}
2642
Pavel Labathf9077782015-08-21 09:13:53 +00002643NativeThreadLinuxSP
Todd Fialaaf245d12014-06-30 21:05:18 +00002644NativeProcessLinux::AddThread (lldb::tid_t thread_id)
2645{
2646 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
2647
Todd Fialaaf245d12014-06-30 21:05:18 +00002648 if (log)
2649 {
2650 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
2651 __FUNCTION__,
2652 GetID (),
2653 thread_id);
2654 }
2655
2656 assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
2657
2658 // If this is the first thread, save it as the current thread
2659 if (m_threads.empty ())
2660 SetCurrentThreadID (thread_id);
2661
Pavel Labathf9077782015-08-21 09:13:53 +00002662 auto thread_sp = std::make_shared<NativeThreadLinux>(this, thread_id);
Todd Fialaaf245d12014-06-30 21:05:18 +00002663 m_threads.push_back (thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00002664 return thread_sp;
2665}
2666
Todd Fialaaf245d12014-06-30 21:05:18 +00002667Error
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002668NativeProcessLinux::FixupBreakpointPCAsNeeded(NativeThreadLinux &thread)
Todd Fialaaf245d12014-06-30 21:05:18 +00002669{
Todd Fiala75f47c32014-10-11 21:42:09 +00002670 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Todd Fialaaf245d12014-06-30 21:05:18 +00002671
2672 Error error;
2673
Todd Fialaaf245d12014-06-30 21:05:18 +00002674 // Find out the size of a breakpoint (might depend on where we are in the code).
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002675 NativeRegisterContextSP context_sp = thread.GetRegisterContext();
Todd Fialaaf245d12014-06-30 21:05:18 +00002676 if (!context_sp)
2677 {
2678 error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
2679 if (log)
2680 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
2681 return error;
2682 }
2683
2684 uint32_t breakpoint_size = 0;
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002685 error = GetSoftwareBreakpointPCOffset(breakpoint_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00002686 if (error.Fail ())
2687 {
2688 if (log)
2689 log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
2690 return error;
2691 }
2692 else
2693 {
2694 if (log)
2695 log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
2696 }
2697
2698 // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
Jaydeep Patilc60c9452015-06-23 03:37:08 +00002699 const lldb::addr_t initial_pc_addr = context_sp->GetPCfromBreakpointLocation ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002700 lldb::addr_t breakpoint_addr = initial_pc_addr;
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002701 if (breakpoint_size > 0)
Todd Fialaaf245d12014-06-30 21:05:18 +00002702 {
2703 // Do not allow breakpoint probe to wrap around.
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002704 if (breakpoint_addr >= breakpoint_size)
2705 breakpoint_addr -= breakpoint_size;
Todd Fialaaf245d12014-06-30 21:05:18 +00002706 }
2707
2708 // Check if we stopped because of a breakpoint.
2709 NativeBreakpointSP breakpoint_sp;
2710 error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
2711 if (!error.Success () || !breakpoint_sp)
2712 {
2713 // We didn't find one at a software probe location. Nothing to do.
2714 if (log)
2715 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
2716 return Error ();
2717 }
2718
2719 // If the breakpoint is not a software breakpoint, nothing to do.
2720 if (!breakpoint_sp->IsSoftwareBreakpoint ())
2721 {
2722 if (log)
2723 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
2724 return Error ();
2725 }
2726
2727 //
2728 // We have a software breakpoint and need to adjust the PC.
2729 //
2730
2731 // Sanity check.
2732 if (breakpoint_size == 0)
2733 {
2734 // Nothing to do! How did we get here?
2735 if (log)
2736 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", it is software, but the size is zero, nothing to do (unexpected)", __FUNCTION__, GetID (), breakpoint_addr);
2737 return Error ();
2738 }
2739
2740 // Change the program counter.
2741 if (log)
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002742 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": changing PC from 0x%" PRIx64 " to 0x%" PRIx64, __FUNCTION__, GetID(), thread.GetID(), initial_pc_addr, breakpoint_addr);
Todd Fialaaf245d12014-06-30 21:05:18 +00002743
2744 error = context_sp->SetPC (breakpoint_addr);
2745 if (error.Fail ())
2746 {
2747 if (log)
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002748 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": failed to set PC: %s", __FUNCTION__, GetID(), thread.GetID(), error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00002749 return error;
2750 }
2751
2752 return error;
2753}
Chaoren Linfa03ad22015-02-03 01:50:42 +00002754
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00002755Error
2756NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec)
2757{
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00002758 FileSpec module_file_spec(module_path, true);
2759
Pavel Labath162fb8e2015-07-23 14:47:33 +00002760 bool found = false;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00002761 file_spec.Clear();
Pavel Labath162fb8e2015-07-23 14:47:33 +00002762 ProcFileReader::ProcessLineByLine(GetID(), "maps",
2763 [&] (const std::string &line)
2764 {
2765 SmallVector<StringRef, 16> columns;
2766 StringRef(line).split(columns, " ", -1, false);
2767 if (columns.size() < 6)
2768 return true; // continue searching
2769
2770 FileSpec this_file_spec(columns[5].str().c_str(), false);
2771 if (this_file_spec.GetFilename() != module_file_spec.GetFilename())
2772 return true; // continue searching
2773
2774 file_spec = this_file_spec;
2775 found = true;
2776 return false; // we are done
2777 });
2778
2779 if (! found)
2780 return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
2781 module_file_spec.GetFilename().AsCString(), GetID());
2782
2783 return Error();
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00002784}
Pavel Labathc0765592015-05-06 10:46:34 +00002785
Pavel Labath5eb721e2015-05-07 08:30:31 +00002786Error
Tamas Berghammer783bfc82015-06-18 20:43:56 +00002787NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef& file_name, lldb::addr_t& load_addr)
2788{
2789 load_addr = LLDB_INVALID_ADDRESS;
2790 Error error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
2791 [&] (const std::string &line) -> bool
2792 {
2793 StringRef maps_row(line);
2794
2795 SmallVector<StringRef, 16> maps_columns;
2796 maps_row.split(maps_columns, StringRef(" "), -1, false);
2797
2798 if (maps_columns.size() < 6)
2799 {
2800 // Return true to continue reading the proc file
2801 return true;
2802 }
2803
2804 if (maps_columns[5] == file_name)
2805 {
2806 StringExtractor addr_extractor(maps_columns[0].str().c_str());
2807 load_addr = addr_extractor.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2808
2809 // Return false to stop reading the proc file further
2810 return false;
2811 }
2812
2813 // Return true to continue reading the proc file
2814 return true;
2815 });
2816 return error;
2817}
2818
Pavel Labathf9077782015-08-21 09:13:53 +00002819NativeThreadLinuxSP
2820NativeProcessLinux::GetThreadByID(lldb::tid_t tid)
2821{
2822 return std::static_pointer_cast<NativeThreadLinux>(NativeProcessProtocol::GetThreadByID(tid));
2823}
2824
Tamas Berghammer783bfc82015-06-18 20:43:56 +00002825Error
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002826NativeProcessLinux::ResumeThread(NativeThreadLinux &thread, lldb::StateType state, int signo)
Pavel Labathc0765592015-05-06 10:46:34 +00002827{
Pavel Labath5eb721e2015-05-07 08:30:31 +00002828 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002829
2830 if (log)
Pavel Labath0e1d7292015-08-20 09:06:12 +00002831 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")",
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002832 __FUNCTION__, thread.GetID());
Pavel Labath5eb721e2015-05-07 08:30:31 +00002833
Pavel Labathc0765592015-05-06 10:46:34 +00002834 // Before we do the resume below, first check if we have a pending
Pavel Labath108c3252015-05-12 09:03:18 +00002835 // stop notification that is currently waiting for
Pavel Labath0e1d7292015-08-20 09:06:12 +00002836 // all threads to stop. This is potentially a buggy situation since
Pavel Labathc0765592015-05-06 10:46:34 +00002837 // we're ostensibly waiting for threads to stop before we send out the
2838 // pending notification, and here we are resuming one before we send
2839 // out the pending stop notification.
Pavel Labath0e1d7292015-08-20 09:06:12 +00002840 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID && log)
Pavel Labathc0765592015-05-06 10:46:34 +00002841 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002842 log->Printf("NativeProcessLinux::%s about to resume tid %" PRIu64 " per explicit request but we have a pending stop notification (tid %" PRIu64 ") that is actively waiting for this thread to stop. Valid sequence of events?", __FUNCTION__, thread.GetID(), m_pending_notification_tid);
Pavel Labathc0765592015-05-06 10:46:34 +00002843 }
2844
2845 // Request a resume. We expect this to be synchronous and the system
2846 // to reflect it is running after this completes.
Pavel Labath0e1d7292015-08-20 09:06:12 +00002847 switch (state)
Pavel Labathc0765592015-05-06 10:46:34 +00002848 {
Pavel Labath0e1d7292015-08-20 09:06:12 +00002849 case eStateRunning:
2850 {
Pavel Labath605b51b2016-02-23 13:56:30 +00002851 const auto resume_result = thread.Resume(signo);
Pavel Labath0e1d7292015-08-20 09:06:12 +00002852 if (resume_result.Success())
2853 SetState(eStateRunning, true);
2854 return resume_result;
Pavel Labathc0765592015-05-06 10:46:34 +00002855 }
Pavel Labath0e1d7292015-08-20 09:06:12 +00002856 case eStateStepping:
2857 {
Pavel Labath605b51b2016-02-23 13:56:30 +00002858 const auto step_result = thread.SingleStep(signo);
Pavel Labath0e1d7292015-08-20 09:06:12 +00002859 if (step_result.Success())
2860 SetState(eStateRunning, true);
2861 return step_result;
2862 }
2863 default:
2864 if (log)
2865 log->Printf("NativeProcessLinux::%s Unhandled state %s.",
2866 __FUNCTION__, StateAsCString(state));
2867 llvm_unreachable("Unhandled state for resume");
2868 }
Pavel Labathc0765592015-05-06 10:46:34 +00002869}
2870
2871//===----------------------------------------------------------------------===//
2872
2873void
Pavel Labath337f3eb2015-05-08 08:57:45 +00002874NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid)
Pavel Labathc0765592015-05-06 10:46:34 +00002875{
Pavel Labath5eb721e2015-05-07 08:30:31 +00002876 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00002877
Pavel Labath5eb721e2015-05-07 08:30:31 +00002878 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00002879 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00002880 log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ")",
Pavel Labathc0765592015-05-06 10:46:34 +00002881 __FUNCTION__, triggering_tid);
2882 }
2883
Pavel Labath0e1d7292015-08-20 09:06:12 +00002884 m_pending_notification_tid = triggering_tid;
2885
2886 // Request a stop for all the thread stops that need to be stopped
2887 // and are not already known to be stopped.
2888 for (const auto &thread_sp: m_threads)
2889 {
2890 if (StateIsRunningState(thread_sp->GetState()))
2891 static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
2892 }
2893
2894 SignalIfAllThreadsStopped();
Pavel Labathc0765592015-05-06 10:46:34 +00002895
Pavel Labath5eb721e2015-05-07 08:30:31 +00002896 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00002897 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00002898 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00002899 }
2900}
2901
2902void
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00002903NativeProcessLinux::SignalIfAllThreadsStopped()
Pavel Labathc0765592015-05-06 10:46:34 +00002904{
Pavel Labath0e1d7292015-08-20 09:06:12 +00002905 if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
2906 return; // No pending notification. Nothing to do.
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00002907
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00002908 for (const auto &thread_sp: m_threads)
Pavel Labathc0765592015-05-06 10:46:34 +00002909 {
Pavel Labath0e1d7292015-08-20 09:06:12 +00002910 if (StateIsRunningState(thread_sp->GetState()))
2911 return; // Some threads are still running. Don't signal yet.
Pavel Labathc0765592015-05-06 10:46:34 +00002912 }
2913
Pavel Labath0e1d7292015-08-20 09:06:12 +00002914 // We have a pending notification and all threads have stopped.
2915 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
Pavel Labathc0765592015-05-06 10:46:34 +00002916
Pavel Labath0e1d7292015-08-20 09:06:12 +00002917 // Clear any temporary breakpoints we used to implement software single stepping.
2918 for (const auto &thread_info: m_threads_stepping_with_breakpoint)
Pavel Labathc0765592015-05-06 10:46:34 +00002919 {
Pavel Labath0e1d7292015-08-20 09:06:12 +00002920 Error error = RemoveBreakpoint (thread_info.second);
2921 if (error.Fail())
2922 if (log)
2923 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " remove stepping breakpoint: %s",
2924 __FUNCTION__, thread_info.first, error.AsCString());
Pavel Labathc0765592015-05-06 10:46:34 +00002925 }
Pavel Labath0e1d7292015-08-20 09:06:12 +00002926 m_threads_stepping_with_breakpoint.clear();
Pavel Labathc0765592015-05-06 10:46:34 +00002927
Pavel Labath0e1d7292015-08-20 09:06:12 +00002928 // Notify the delegate about the stop
2929 SetCurrentThreadID(m_pending_notification_tid);
2930 SetState(StateType::eStateStopped, true);
2931 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
Pavel Labathc0765592015-05-06 10:46:34 +00002932}
2933
2934void
Pavel Labathf9077782015-08-21 09:13:53 +00002935NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread)
Pavel Labathc0765592015-05-06 10:46:34 +00002936{
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002937 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
2938
2939 if (log)
Pavel Labathf9077782015-08-21 09:13:53 +00002940 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, thread.GetID());
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002941
Pavel Labathf9077782015-08-21 09:13:53 +00002942 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID && StateIsRunningState(thread.GetState()))
Pavel Labathc0765592015-05-06 10:46:34 +00002943 {
2944 // We will need to wait for this new thread to stop as well before firing the
2945 // notification.
Pavel Labathf9077782015-08-21 09:13:53 +00002946 thread.RequestStop();
Pavel Labathc0765592015-05-06 10:46:34 +00002947 }
2948}
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002949
Pavel Labath19cbe962015-07-21 13:20:32 +00002950void
2951NativeProcessLinux::SigchldHandler()
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002952{
Pavel Labath19cbe962015-07-21 13:20:32 +00002953 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2954 // Process all pending waitpid notifications.
2955 while (true)
2956 {
2957 int status = -1;
2958 ::pid_t wait_pid = waitpid(-1, &status, __WALL | __WNOTHREAD | WNOHANG);
2959
2960 if (wait_pid == 0)
2961 break; // We are done.
2962
2963 if (wait_pid == -1)
2964 {
2965 if (errno == EINTR)
2966 continue;
2967
2968 Error error(errno, eErrorTypePOSIX);
2969 if (log)
2970 log->Printf("NativeProcessLinux::%s waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG) failed: %s",
2971 __FUNCTION__, error.AsCString());
2972 break;
2973 }
2974
2975 bool exited = false;
2976 int signal = 0;
2977 int exit_status = 0;
2978 const char *status_cstr = nullptr;
2979 if (WIFSTOPPED(status))
2980 {
2981 signal = WSTOPSIG(status);
2982 status_cstr = "STOPPED";
2983 }
2984 else if (WIFEXITED(status))
2985 {
2986 exit_status = WEXITSTATUS(status);
2987 status_cstr = "EXITED";
2988 exited = true;
2989 }
2990 else if (WIFSIGNALED(status))
2991 {
2992 signal = WTERMSIG(status);
2993 status_cstr = "SIGNALED";
Omair Javaiddee4a862015-08-19 10:44:16 +00002994 if (wait_pid == static_cast< ::pid_t>(GetID())) {
Pavel Labath19cbe962015-07-21 13:20:32 +00002995 exited = true;
2996 exit_status = -1;
2997 }
2998 }
2999 else
3000 status_cstr = "(\?\?\?)";
3001
3002 if (log)
3003 log->Printf("NativeProcessLinux::%s: waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG)"
3004 "=> pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
3005 __FUNCTION__, wait_pid, status, status_cstr, signal, exit_status);
3006
3007 MonitorCallback (wait_pid, exited, signal, exit_status);
3008 }
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003009}
3010
3011// Wrapper for ptrace to catch errors and log calls.
3012// Note that ptrace sets errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
Pavel Labath4a9babb2015-06-30 17:04:49 +00003013Error
3014NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, long *result)
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003015{
Pavel Labath4a9babb2015-06-30 17:04:49 +00003016 Error error;
3017 long int ret;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003018
3019 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
3020
3021 PtraceDisplayBytes(req, data, data_size);
3022
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003023 errno = 0;
3024 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Pavel Labath4a9babb2015-06-30 17:04:49 +00003025 ret = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003026 else
Pavel Labath4a9babb2015-06-30 17:04:49 +00003027 ret = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003028
Pavel Labath4a9babb2015-06-30 17:04:49 +00003029 if (ret == -1)
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003030 error.SetErrorToErrno();
3031
Pavel Labath4a9babb2015-06-30 17:04:49 +00003032 if (result)
3033 *result = ret;
3034
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003035 if (log)
Pavel Labath4a9babb2015-06-30 17:04:49 +00003036 log->Printf("ptrace(%d, %" PRIu64 ", %p, %p, %zu)=%lX", req, pid, addr, data, data_size, ret);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003037
3038 PtraceDisplayBytes(req, data, data_size);
3039
3040 if (log && error.GetError() != 0)
3041 {
3042 const char* str;
3043 switch (error.GetError())
3044 {
3045 case ESRCH: str = "ESRCH"; break;
3046 case EINVAL: str = "EINVAL"; break;
3047 case EBUSY: str = "EBUSY"; break;
3048 case EPERM: str = "EPERM"; break;
3049 default: str = error.AsCString();
3050 }
3051 log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
3052 }
3053
Pavel Labath4a9babb2015-06-30 17:04:49 +00003054 return error;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003055}