blob: feab1ad7d57b8f2a85b7ce24e8714fe7eb737bdc [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"
28#include "lldb/Core/Module.h"
Oleksiy Vyalov6edef202014-11-17 22:16:42 +000029#include "lldb/Core/ModuleSpec.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000030#include "lldb/Core/RegisterValue.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000031#include "lldb/Core/State.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000032#include "lldb/Host/common/NativeBreakpoint.h"
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +000033#include "lldb/Host/common/NativeRegisterContext.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000034#include "lldb/Host/Host.h"
Zachary Turner39de3112014-09-09 20:54:56 +000035#include "lldb/Host/ThreadLauncher.h"
Pavel Labath5b981ab2015-05-29 12:53:54 +000036#include "lldb/Target/Platform.h"
Zachary Turner90aff472015-03-03 23:36:51 +000037#include "lldb/Target/Process.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000038#include "lldb/Target/ProcessLaunchInfo.h"
Pavel Labath5b981ab2015-05-29 12:53:54 +000039#include "lldb/Target/Target.h"
Chaoren Linc16f5dc2015-03-19 23:28:10 +000040#include "lldb/Utility/LLDBAssert.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000041#include "lldb/Utility/PseudoTerminal.h"
Pavel Labathf805e192015-07-07 10:08:41 +000042#include "lldb/Utility/StringExtractor.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000043
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000044#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000045#include "NativeThreadLinux.h"
46#include "ProcFileReader.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000047#include "Procfs.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000048
Tamas Berghammerd8584872015-02-06 10:57:40 +000049// System includes - They have to be included after framework includes because they define some
50// macros which collide with variable names in other modules
51#include <linux/unistd.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000052#include <sys/socket.h>
Vince Harron8b335672015-05-12 01:10:56 +000053
Pavel Labathdf7c6992015-06-17 18:38:49 +000054#include <sys/syscall.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000055#include <sys/types.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000056#include <sys/user.h>
57#include <sys/wait.h>
58
Vince Harron8b335672015-05-12 01:10:56 +000059#include "lldb/Host/linux/Personality.h"
60#include "lldb/Host/linux/Ptrace.h"
Pavel Labathdf7c6992015-06-17 18:38:49 +000061#include "lldb/Host/linux/Uio.h"
Vince Harron8b335672015-05-12 01:10:56 +000062#include "lldb/Host/android/Android.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000063
Todd Fiala0bce1b62014-08-17 00:10:50 +000064#define LLDB_PERSONALITY_GET_CURRENT_SETTINGS 0xffffffff
Todd Fialaaf245d12014-06-30 21:05:18 +000065
66// Support hardware breakpoints in case it has not been defined
67#ifndef TRAP_HWBKPT
68 #define TRAP_HWBKPT 4
69#endif
70
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000071using namespace lldb;
72using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000073using namespace lldb_private::process_linux;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000074using namespace llvm;
75
Todd Fialaaf245d12014-06-30 21:05:18 +000076// Private bits we only need internally.
Pavel Labathdf7c6992015-06-17 18:38:49 +000077
78static bool ProcessVmReadvSupported()
79{
80 static bool is_supported;
81 static std::once_flag flag;
82
83 std::call_once(flag, [] {
84 Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
85
86 uint32_t source = 0x47424742;
87 uint32_t dest = 0;
88
89 struct iovec local, remote;
90 remote.iov_base = &source;
91 local.iov_base = &dest;
92 remote.iov_len = local.iov_len = sizeof source;
93
94 // We shall try if cross-process-memory reads work by attempting to read a value from our own process.
95 ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
96 is_supported = (res == sizeof(source) && source == dest);
97 if (log)
98 {
99 if (is_supported)
100 log->Printf("%s: Detected kernel support for process_vm_readv syscall. Fast memory reads enabled.",
101 __FUNCTION__);
102 else
103 log->Printf("%s: syscall process_vm_readv failed (error: %s). Fast memory reads disabled.",
104 __FUNCTION__, strerror(errno));
105 }
106 });
107
108 return is_supported;
109}
110
Todd Fialaaf245d12014-06-30 21:05:18 +0000111namespace
112{
Todd Fialaaf245d12014-06-30 21:05:18 +0000113 Error
114 ResolveProcessArchitecture (lldb::pid_t pid, Platform &platform, ArchSpec &arch)
115 {
116 // Grab process info for the running process.
117 ProcessInstanceInfo process_info;
118 if (!platform.GetProcessInfo (pid, process_info))
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000119 return Error("failed to get process info");
Todd Fialaaf245d12014-06-30 21:05:18 +0000120
121 // Resolve the executable module.
122 ModuleSP exe_module_sp;
Chaoren Line56f6dc2015-03-01 04:31:16 +0000123 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Todd Fialaaf245d12014-06-30 21:05:18 +0000124 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths ());
125 Error error = platform.ResolveExecutable(
Oleksiy Vyalov54539332014-11-17 22:42:28 +0000126 exe_module_spec,
Todd Fialaaf245d12014-06-30 21:05:18 +0000127 exe_module_sp,
128 executable_search_paths.GetSize () ? &executable_search_paths : NULL);
129
130 if (!error.Success ())
131 return error;
132
133 // Check if we've got our architecture from the exe_module.
134 arch = exe_module_sp->GetArchitecture ();
135 if (arch.IsValid ())
136 return Error();
137 else
138 return Error("failed to retrieve a valid architecture from the exe module");
139 }
140
141 void
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000142 DisplayBytes (StreamString &s, void *bytes, uint32_t count)
Todd Fialaaf245d12014-06-30 21:05:18 +0000143 {
144 uint8_t *ptr = (uint8_t *)bytes;
145 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
146 for(uint32_t i=0; i<loop_count; i++)
147 {
148 s.Printf ("[%x]", *ptr);
149 ptr++;
150 }
151 }
152
153 void
154 PtraceDisplayBytes(int &req, void *data, size_t data_size)
155 {
156 StreamString buf;
157 Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
158 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
159
160 if (verbose_log)
161 {
162 switch(req)
163 {
164 case PTRACE_POKETEXT:
165 {
166 DisplayBytes(buf, &data, 8);
167 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
168 break;
169 }
170 case PTRACE_POKEDATA:
171 {
172 DisplayBytes(buf, &data, 8);
173 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
174 break;
175 }
176 case PTRACE_POKEUSER:
177 {
178 DisplayBytes(buf, &data, 8);
179 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
180 break;
181 }
182 case PTRACE_SETREGS:
183 {
184 DisplayBytes(buf, data, data_size);
185 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
186 break;
187 }
188 case PTRACE_SETFPREGS:
189 {
190 DisplayBytes(buf, data, data_size);
191 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
192 break;
193 }
194 case PTRACE_SETSIGINFO:
195 {
196 DisplayBytes(buf, data, sizeof(siginfo_t));
197 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
198 break;
199 }
200 case PTRACE_SETREGSET:
201 {
202 // Extract iov_base from data, which is a pointer to the struct IOVEC
203 DisplayBytes(buf, *(void **)data, data_size);
204 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
205 break;
206 }
207 default:
208 {
209 }
210 }
211 }
212 }
213
Pavel Labath19cbe962015-07-21 13:20:32 +0000214 static constexpr unsigned k_ptrace_word_size = sizeof(void*);
215 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 +0000216} // end of anonymous namespace
217
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000218// Simple helper function to ensure flags are enabled on the given file
219// descriptor.
220static Error
221EnsureFDFlags(int fd, int flags)
222{
223 Error error;
224
225 int status = fcntl(fd, F_GETFL);
226 if (status == -1)
227 {
228 error.SetErrorToErrno();
229 return error;
230 }
231
232 if (fcntl(fd, F_SETFL, status | flags) == -1)
233 {
234 error.SetErrorToErrno();
235 return error;
236 }
237
238 return error;
239}
240
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000241NativeProcessLinux::LaunchArgs::LaunchArgs(Module *module,
Todd Fialaaf245d12014-06-30 21:05:18 +0000242 char const **argv,
243 char const **envp,
Chaoren Lind3173f32015-05-29 19:52:29 +0000244 const FileSpec &stdin_file_spec,
245 const FileSpec &stdout_file_spec,
246 const FileSpec &stderr_file_spec,
247 const FileSpec &working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000248 const ProcessLaunchInfo &launch_info)
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000249 : m_module(module),
Todd Fialaaf245d12014-06-30 21:05:18 +0000250 m_argv(argv),
251 m_envp(envp),
Chaoren Lind3173f32015-05-29 19:52:29 +0000252 m_stdin_file_spec(stdin_file_spec),
253 m_stdout_file_spec(stdout_file_spec),
254 m_stderr_file_spec(stderr_file_spec),
Todd Fiala0bce1b62014-08-17 00:10:50 +0000255 m_working_dir(working_dir),
256 m_launch_info(launch_info)
257{
258}
Todd Fialaaf245d12014-06-30 21:05:18 +0000259
260NativeProcessLinux::LaunchArgs::~LaunchArgs()
261{ }
262
Todd Fialaaf245d12014-06-30 21:05:18 +0000263// -----------------------------------------------------------------------------
264// Public Static Methods
265// -----------------------------------------------------------------------------
266
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000267Error
Pavel Labathd5b310f2015-07-09 11:51:11 +0000268NativeProcessProtocol::Launch (
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000269 ProcessLaunchInfo &launch_info,
270 NativeProcessProtocol::NativeDelegate &native_delegate,
Pavel Labath19cbe962015-07-21 13:20:32 +0000271 MainLoop &mainloop,
Todd Fialaaf245d12014-06-30 21:05:18 +0000272 NativeProcessProtocolSP &native_process_sp)
273{
274 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
275
Pavel Labathd5b310f2015-07-09 11:51:11 +0000276 lldb::ModuleSP exe_module_sp;
277 PlatformSP platform_sp (Platform::GetHostPlatform ());
278 Error error = platform_sp->ResolveExecutable(
279 ModuleSpec(launch_info.GetExecutableFile(), launch_info.GetArchitecture()),
280 exe_module_sp,
281 nullptr);
282
283 if (! error.Success())
284 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000285
286 // Verify the working directory is valid if one was specified.
Chaoren Lind3173f32015-05-29 19:52:29 +0000287 FileSpec working_dir{launch_info.GetWorkingDirectory()};
288 if (working_dir &&
289 (!working_dir.ResolvePath() ||
290 working_dir.GetFileType() != FileSpec::eFileTypeDirectory))
Todd Fialaaf245d12014-06-30 21:05:18 +0000291 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000292 error.SetErrorStringWithFormat ("No such file or directory: %s",
293 working_dir.GetCString());
294 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000295 }
296
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000297 const FileAction *file_action;
Todd Fialaaf245d12014-06-30 21:05:18 +0000298
Chaoren Lind3173f32015-05-29 19:52:29 +0000299 // Default of empty will mean to use existing open file descriptors.
300 FileSpec stdin_file_spec{};
301 FileSpec stdout_file_spec{};
302 FileSpec stderr_file_spec{};
Todd Fialaaf245d12014-06-30 21:05:18 +0000303
304 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +0000305 if (file_action)
Chaoren Lind3173f32015-05-29 19:52:29 +0000306 stdin_file_spec = file_action->GetFileSpec();
Todd Fialaaf245d12014-06-30 21:05:18 +0000307
308 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +0000309 if (file_action)
Chaoren Lind3173f32015-05-29 19:52:29 +0000310 stdout_file_spec = file_action->GetFileSpec();
Todd Fialaaf245d12014-06-30 21:05:18 +0000311
312 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +0000313 if (file_action)
Chaoren Lind3173f32015-05-29 19:52:29 +0000314 stderr_file_spec = file_action->GetFileSpec();
Todd Fiala75f47c32014-10-11 21:42:09 +0000315
316 if (log)
317 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000318 if (stdin_file_spec)
319 log->Printf ("NativeProcessLinux::%s setting STDIN to '%s'",
320 __FUNCTION__, stdin_file_spec.GetCString());
Todd Fiala75f47c32014-10-11 21:42:09 +0000321 else
322 log->Printf ("NativeProcessLinux::%s leaving STDIN as is", __FUNCTION__);
323
Chaoren Lind3173f32015-05-29 19:52:29 +0000324 if (stdout_file_spec)
325 log->Printf ("NativeProcessLinux::%s setting STDOUT to '%s'",
326 __FUNCTION__, stdout_file_spec.GetCString());
Todd Fiala75f47c32014-10-11 21:42:09 +0000327 else
328 log->Printf ("NativeProcessLinux::%s leaving STDOUT as is", __FUNCTION__);
329
Chaoren Lind3173f32015-05-29 19:52:29 +0000330 if (stderr_file_spec)
331 log->Printf ("NativeProcessLinux::%s setting STDERR to '%s'",
332 __FUNCTION__, stderr_file_spec.GetCString());
Todd Fiala75f47c32014-10-11 21:42:09 +0000333 else
334 log->Printf ("NativeProcessLinux::%s leaving STDERR as is", __FUNCTION__);
335 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000336
337 // Create the NativeProcessLinux in launch mode.
338 native_process_sp.reset (new NativeProcessLinux ());
339
340 if (log)
341 {
342 int i = 0;
343 for (const char **args = launch_info.GetArguments ().GetConstArgumentVector (); *args; ++args, ++i)
344 {
345 log->Printf ("NativeProcessLinux::%s arg %d: \"%s\"", __FUNCTION__, i, *args ? *args : "nullptr");
346 ++i;
347 }
348 }
349
350 if (!native_process_sp->RegisterNativeDelegate (native_delegate))
351 {
352 native_process_sp.reset ();
353 error.SetErrorStringWithFormat ("failed to register the native delegate");
354 return error;
355 }
356
Tamas Berghammercb84eeb2015-03-17 15:05:31 +0000357 std::static_pointer_cast<NativeProcessLinux> (native_process_sp)->LaunchInferior (
Pavel Labath19cbe962015-07-21 13:20:32 +0000358 mainloop,
Pavel Labathd5b310f2015-07-09 11:51:11 +0000359 exe_module_sp.get(),
Todd Fialaaf245d12014-06-30 21:05:18 +0000360 launch_info.GetArguments ().GetConstArgumentVector (),
361 launch_info.GetEnvironmentEntries ().GetConstArgumentVector (),
Chaoren Lind3173f32015-05-29 19:52:29 +0000362 stdin_file_spec,
363 stdout_file_spec,
364 stderr_file_spec,
Todd Fialaaf245d12014-06-30 21:05:18 +0000365 working_dir,
Todd Fiala0bce1b62014-08-17 00:10:50 +0000366 launch_info,
Todd Fialaaf245d12014-06-30 21:05:18 +0000367 error);
368
369 if (error.Fail ())
370 {
371 native_process_sp.reset ();
372 if (log)
373 log->Printf ("NativeProcessLinux::%s failed to launch process: %s", __FUNCTION__, error.AsCString ());
374 return error;
375 }
376
377 launch_info.SetProcessID (native_process_sp->GetID ());
378
379 return error;
380}
381
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000382Error
Pavel Labathd5b310f2015-07-09 11:51:11 +0000383NativeProcessProtocol::Attach (
Todd Fialaaf245d12014-06-30 21:05:18 +0000384 lldb::pid_t pid,
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000385 NativeProcessProtocol::NativeDelegate &native_delegate,
Pavel Labath19cbe962015-07-21 13:20:32 +0000386 MainLoop &mainloop,
Todd Fialaaf245d12014-06-30 21:05:18 +0000387 NativeProcessProtocolSP &native_process_sp)
388{
389 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
390 if (log && log->GetMask ().Test (POSIX_LOG_VERBOSE))
391 log->Printf ("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
392
393 // Grab the current platform architecture. This should be Linux,
394 // since this code is only intended to run on a Linux host.
Greg Clayton615eb7e2014-09-19 20:11:50 +0000395 PlatformSP platform_sp (Platform::GetHostPlatform ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000396 if (!platform_sp)
397 return Error("failed to get a valid default platform");
398
399 // Retrieve the architecture for the running process.
400 ArchSpec process_arch;
401 Error error = ResolveProcessArchitecture (pid, *platform_sp.get (), process_arch);
402 if (!error.Success ())
403 return error;
404
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +0000405 std::shared_ptr<NativeProcessLinux> native_process_linux_sp (new NativeProcessLinux ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000406
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +0000407 if (!native_process_linux_sp->RegisterNativeDelegate (native_delegate))
Todd Fialaaf245d12014-06-30 21:05:18 +0000408 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000409 error.SetErrorStringWithFormat ("failed to register the native delegate");
410 return error;
411 }
412
Pavel Labath19cbe962015-07-21 13:20:32 +0000413 native_process_linux_sp->AttachToInferior (mainloop, pid, error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000414 if (!error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +0000415 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000416
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +0000417 native_process_sp = native_process_linux_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +0000418 return error;
419}
420
421// -----------------------------------------------------------------------------
422// Public Instance Methods
423// -----------------------------------------------------------------------------
424
425NativeProcessLinux::NativeProcessLinux () :
426 NativeProcessProtocol (LLDB_INVALID_PROCESS_ID),
427 m_arch (),
Todd Fialaaf245d12014-06-30 21:05:18 +0000428 m_supports_mem_region (eLazyBoolCalculate),
429 m_mem_region_cache (),
Pavel Labath0e1d7292015-08-20 09:06:12 +0000430 m_pending_notification_tid(LLDB_INVALID_THREAD_ID)
Todd Fialaaf245d12014-06-30 21:05:18 +0000431{
432}
433
Todd Fialaaf245d12014-06-30 21:05:18 +0000434void
435NativeProcessLinux::LaunchInferior (
Pavel Labath19cbe962015-07-21 13:20:32 +0000436 MainLoop &mainloop,
Todd Fialaaf245d12014-06-30 21:05:18 +0000437 Module *module,
438 const char *argv[],
439 const char *envp[],
Chaoren Lind3173f32015-05-29 19:52:29 +0000440 const FileSpec &stdin_file_spec,
441 const FileSpec &stdout_file_spec,
442 const FileSpec &stderr_file_spec,
443 const FileSpec &working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000444 const ProcessLaunchInfo &launch_info,
445 Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000446{
Pavel Labath19cbe962015-07-21 13:20:32 +0000447 m_sigchld_handle = mainloop.RegisterSignal(SIGCHLD,
448 [this] (MainLoopBase &) { SigchldHandler(); }, error);
449 if (! m_sigchld_handle)
450 return;
451
Todd Fialaaf245d12014-06-30 21:05:18 +0000452 if (module)
453 m_arch = module->GetArchitecture ();
454
Chaoren Linfa03ad22015-02-03 01:50:42 +0000455 SetState (eStateLaunching);
Todd Fialaaf245d12014-06-30 21:05:18 +0000456
457 std::unique_ptr<LaunchArgs> args(
Chaoren Lind3173f32015-05-29 19:52:29 +0000458 new LaunchArgs(module, argv, envp,
459 stdin_file_spec,
460 stdout_file_spec,
461 stderr_file_spec,
462 working_dir,
463 launch_info));
Todd Fialaaf245d12014-06-30 21:05:18 +0000464
Pavel Labath19cbe962015-07-21 13:20:32 +0000465 Launch(args.get(), error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000466}
467
468void
Pavel Labath19cbe962015-07-21 13:20:32 +0000469NativeProcessLinux::AttachToInferior (MainLoop &mainloop, lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000470{
471 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
472 if (log)
473 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
474
Pavel Labath19cbe962015-07-21 13:20:32 +0000475 m_sigchld_handle = mainloop.RegisterSignal(SIGCHLD,
476 [this] (MainLoopBase &) { SigchldHandler(); }, error);
477 if (! m_sigchld_handle)
478 return;
479
Todd Fialaaf245d12014-06-30 21:05:18 +0000480 // We can use the Host for everything except the ResolveExecutable portion.
Greg Clayton615eb7e2014-09-19 20:11:50 +0000481 PlatformSP platform_sp = Platform::GetHostPlatform ();
Todd Fialaaf245d12014-06-30 21:05:18 +0000482 if (!platform_sp)
483 {
484 if (log)
485 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): no default platform set", __FUNCTION__, pid);
486 error.SetErrorString ("no default platform available");
Shawn Best50d60be2014-11-11 00:28:52 +0000487 return;
Todd Fialaaf245d12014-06-30 21:05:18 +0000488 }
489
490 // Gather info about the process.
491 ProcessInstanceInfo process_info;
Shawn Best50d60be2014-11-11 00:28:52 +0000492 if (!platform_sp->GetProcessInfo (pid, process_info))
493 {
494 if (log)
495 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): failed to get process info", __FUNCTION__, pid);
496 error.SetErrorString ("failed to get process info");
497 return;
498 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000499
500 // Resolve the executable module
501 ModuleSP exe_module_sp;
502 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
Chaoren Line56f6dc2015-03-01 04:31:16 +0000503 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Oleksiy Vyalov6edef202014-11-17 22:16:42 +0000504 error = platform_sp->ResolveExecutable(exe_module_spec, exe_module_sp,
Zachary Turner13b18262014-08-20 16:42:51 +0000505 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
Todd Fialaaf245d12014-06-30 21:05:18 +0000506 if (!error.Success())
507 return;
508
509 // Set the architecture to the exe architecture.
510 m_arch = exe_module_sp->GetArchitecture();
511 if (log)
512 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
513
514 m_pid = pid;
515 SetState(eStateAttaching);
516
Pavel Labath19cbe962015-07-21 13:20:32 +0000517 Attach(pid, error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000518}
519
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000520::pid_t
521NativeProcessLinux::Launch(LaunchArgs *args, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000522{
Todd Fiala0bce1b62014-08-17 00:10:50 +0000523 assert (args && "null args");
Todd Fialaaf245d12014-06-30 21:05:18 +0000524
525 const char **argv = args->m_argv;
526 const char **envp = args->m_envp;
Chaoren Lind3173f32015-05-29 19:52:29 +0000527 const FileSpec working_dir = args->m_working_dir;
Todd Fialaaf245d12014-06-30 21:05:18 +0000528
529 lldb_utility::PseudoTerminal terminal;
530 const size_t err_len = 1024;
531 char err_str[err_len];
532 lldb::pid_t pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000533
534 // Propagate the environment if one is not supplied.
535 if (envp == NULL || envp[0] == NULL)
536 envp = const_cast<const char **>(environ);
537
538 if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
539 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000540 error.SetErrorToGenericError();
541 error.SetErrorStringWithFormat("Process fork failed: %s", err_str);
542 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000543 }
544
545 // Recognized child exit status codes.
546 enum {
547 ePtraceFailed = 1,
548 eDupStdinFailed,
549 eDupStdoutFailed,
550 eDupStderrFailed,
551 eChdirFailed,
552 eExecFailed,
Pavel Labath78856472015-08-19 13:47:57 +0000553 eSetGidFailed,
554 eSetSigMaskFailed
Todd Fialaaf245d12014-06-30 21:05:18 +0000555 };
556
557 // Child process.
558 if (pid == 0)
559 {
Pavel Labathd2c4c9b2015-08-18 08:23:35 +0000560 // First, make sure we disable all logging. If we are logging to stdout, our logs can be
561 // mistaken for inferior output.
562 Log::DisableAllLogChannels(nullptr);
Todd Fiala75f47c32014-10-11 21:42:09 +0000563 // FIXME consider opening a pipe between parent/child and have this forked child
Pavel Labathd2c4c9b2015-08-18 08:23:35 +0000564 // send log info to parent re: launch status.
Todd Fialaaf245d12014-06-30 21:05:18 +0000565
Todd Fiala75f47c32014-10-11 21:42:09 +0000566 // Start tracing this child that is about to exec.
Pavel Labath4a9babb2015-06-30 17:04:49 +0000567 error = PtraceWrapper(PTRACE_TRACEME, 0);
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000568 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000569 exit(ePtraceFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +0000570
Pavel Labath493c3a12015-02-04 10:36:57 +0000571 // terminal has already dupped the tty descriptors to stdin/out/err.
572 // This closes original fd from which they were copied (and avoids
573 // leaking descriptors to the debugged process.
574 terminal.CloseSlaveFileDescriptor();
575
Todd Fialaaf245d12014-06-30 21:05:18 +0000576 // Do not inherit setgid powers.
Todd Fialaaf245d12014-06-30 21:05:18 +0000577 if (setgid(getgid()) != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +0000578 exit(eSetGidFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +0000579
580 // Attempt to have our own process group.
Todd Fialaaf245d12014-06-30 21:05:18 +0000581 if (setpgid(0, 0) != 0)
582 {
Todd Fiala75f47c32014-10-11 21:42:09 +0000583 // FIXME log that this failed. This is common.
Todd Fialaaf245d12014-06-30 21:05:18 +0000584 // Don't allow this to prevent an inferior exec.
585 }
586
587 // Dup file descriptors if needed.
Chaoren Lind3173f32015-05-29 19:52:29 +0000588 if (args->m_stdin_file_spec)
589 if (!DupDescriptor(args->m_stdin_file_spec, STDIN_FILENO, O_RDONLY))
Todd Fialaaf245d12014-06-30 21:05:18 +0000590 exit(eDupStdinFailed);
591
Chaoren Lind3173f32015-05-29 19:52:29 +0000592 if (args->m_stdout_file_spec)
593 if (!DupDescriptor(args->m_stdout_file_spec, STDOUT_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +0000594 exit(eDupStdoutFailed);
595
Chaoren Lind3173f32015-05-29 19:52:29 +0000596 if (args->m_stderr_file_spec)
597 if (!DupDescriptor(args->m_stderr_file_spec, STDERR_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +0000598 exit(eDupStderrFailed);
599
Chaoren Lin9cf4f2c2015-04-23 18:28:04 +0000600 // Close everything besides stdin, stdout, and stderr that has no file
601 // action to avoid leaking
602 for (int fd = 3; fd < sysconf(_SC_OPEN_MAX); ++fd)
603 if (!args->m_launch_info.GetFileActionForFD(fd))
604 close(fd);
605
Todd Fialaaf245d12014-06-30 21:05:18 +0000606 // Change working directory
Chaoren Lind3173f32015-05-29 19:52:29 +0000607 if (working_dir && 0 != ::chdir(working_dir.GetCString()))
Todd Fialaaf245d12014-06-30 21:05:18 +0000608 exit(eChdirFailed);
609
Todd Fiala0bce1b62014-08-17 00:10:50 +0000610 // Disable ASLR if requested.
611 if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR))
612 {
613 const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
614 if (old_personality == -1)
615 {
Todd Fiala75f47c32014-10-11 21:42:09 +0000616 // Can't retrieve Linux personality. Cannot disable ASLR.
Todd Fiala0bce1b62014-08-17 00:10:50 +0000617 }
618 else
619 {
620 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality);
621 if (new_personality == -1)
622 {
Todd Fiala75f47c32014-10-11 21:42:09 +0000623 // Disabling ASLR failed.
Todd Fiala0bce1b62014-08-17 00:10:50 +0000624 }
625 else
626 {
Todd Fiala75f47c32014-10-11 21:42:09 +0000627 // Disabling ASLR succeeded.
Todd Fiala0bce1b62014-08-17 00:10:50 +0000628 }
629 }
630 }
631
Pavel Labath78856472015-08-19 13:47:57 +0000632 // Clear the signal mask to prevent the child from being affected by
633 // any masking done by the parent.
634 sigset_t set;
635 if (sigemptyset(&set) != 0 || pthread_sigmask(SIG_SETMASK, &set, nullptr) != 0)
636 exit(eSetSigMaskFailed);
637
Todd Fiala75f47c32014-10-11 21:42:09 +0000638 // Execute. We should never return...
Todd Fialaaf245d12014-06-30 21:05:18 +0000639 execve(argv[0],
640 const_cast<char *const *>(argv),
641 const_cast<char *const *>(envp));
Todd Fiala75f47c32014-10-11 21:42:09 +0000642
643 // ...unless exec fails. In which case we definitely need to end the child here.
Todd Fialaaf245d12014-06-30 21:05:18 +0000644 exit(eExecFailed);
645 }
646
Todd Fiala75f47c32014-10-11 21:42:09 +0000647 //
648 // This is the parent code here.
649 //
650 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
651
Todd Fialaaf245d12014-06-30 21:05:18 +0000652 // Wait for the child process to trap on its call to execve.
653 ::pid_t wpid;
654 int status;
655 if ((wpid = waitpid(pid, &status, 0)) < 0)
656 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000657 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +0000658 if (log)
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000659 log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s",
660 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000661
662 // Mark the inferior as invalid.
663 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000664 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000665
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000666 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000667 }
668 else if (WIFEXITED(status))
669 {
670 // open, dup or execve likely failed for some reason.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000671 error.SetErrorToGenericError();
Todd Fialaaf245d12014-06-30 21:05:18 +0000672 switch (WEXITSTATUS(status))
673 {
674 case ePtraceFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000675 error.SetErrorString("Child ptrace failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000676 break;
677 case eDupStdinFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000678 error.SetErrorString("Child open stdin failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000679 break;
680 case eDupStdoutFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000681 error.SetErrorString("Child open stdout failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000682 break;
683 case eDupStderrFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000684 error.SetErrorString("Child open stderr failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000685 break;
686 case eChdirFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000687 error.SetErrorString("Child failed to set working directory.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000688 break;
689 case eExecFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000690 error.SetErrorString("Child exec failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000691 break;
692 case eSetGidFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000693 error.SetErrorString("Child setgid failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000694 break;
Pavel Labath78856472015-08-19 13:47:57 +0000695 case eSetSigMaskFailed:
696 error.SetErrorString("Child failed to set signal mask.");
697 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000698 default:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000699 error.SetErrorString("Child returned unknown exit status.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000700 break;
701 }
702
703 if (log)
704 {
705 log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
706 __FUNCTION__,
707 WEXITSTATUS(status));
708 }
709
710 // Mark the inferior as invalid.
711 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000712 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000713
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000714 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000715 }
Todd Fiala202ecd22014-07-10 04:39:13 +0000716 assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
Todd Fialaaf245d12014-06-30 21:05:18 +0000717 "Could not sync with inferior process.");
718
719 if (log)
720 log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
721
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000722 error = SetDefaultPtraceOpts(pid);
723 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000724 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000725 if (log)
726 log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000727 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000728
729 // Mark the inferior as invalid.
730 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000731 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000732
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000733 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000734 }
735
736 // Release the master terminal descriptor and pass it off to the
737 // NativeProcessLinux instance. Similarly stash the inferior pid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000738 m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
739 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000740
741 // Set the terminal fd to be in non blocking mode (it simplifies the
742 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
743 // descriptor to read from).
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000744 error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
745 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000746 {
747 if (log)
748 log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000749 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000750
751 // Mark the inferior as invalid.
752 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000753 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000754
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000755 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000756 }
757
758 if (log)
759 log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
760
Pavel Labathf9077782015-08-21 09:13:53 +0000761 NativeThreadLinuxSP thread_sp = AddThread(pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000762 assert (thread_sp && "AddThread() returned a nullptr thread");
Pavel Labathf9077782015-08-21 09:13:53 +0000763 thread_sp->SetStoppedBySignal(SIGSTOP);
764 ThreadWasCreated(*thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +0000765
766 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000767 SetCurrentThreadID (thread_sp->GetID ());
768 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +0000769
Todd Fialaaf245d12014-06-30 21:05:18 +0000770 if (log)
771 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000772 if (error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +0000773 {
774 log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
775 }
776 else
777 {
778 log->Printf ("NativeProcessLinux::%s inferior launching failed: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000779 __FUNCTION__, error.AsCString ());
780 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000781 }
782 }
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000783 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000784}
785
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000786::pid_t
787NativeProcessLinux::Attach(lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000788{
Todd Fialaaf245d12014-06-30 21:05:18 +0000789 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
790
791 // Use a map to keep track of the threads which we have attached/need to attach.
792 Host::TidMap tids_to_attach;
793 if (pid <= 1)
794 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000795 error.SetErrorToGenericError();
796 error.SetErrorString("Attaching to process 1 is not allowed.");
797 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000798 }
799
800 while (Host::FindProcessThreads(pid, tids_to_attach))
801 {
802 for (Host::TidMap::iterator it = tids_to_attach.begin();
803 it != tids_to_attach.end();)
804 {
805 if (it->second == false)
806 {
807 lldb::tid_t tid = it->first;
808
809 // Attach to the requested process.
810 // An attach will cause the thread to stop with a SIGSTOP.
Pavel Labath4a9babb2015-06-30 17:04:49 +0000811 error = PtraceWrapper(PTRACE_ATTACH, tid);
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000812 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000813 {
814 // No such thread. The thread may have exited.
815 // More error handling may be needed.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000816 if (error.GetError() == ESRCH)
Todd Fialaaf245d12014-06-30 21:05:18 +0000817 {
818 it = tids_to_attach.erase(it);
819 continue;
820 }
821 else
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000822 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000823 }
824
825 int status;
826 // Need to use __WALL otherwise we receive an error with errno=ECHLD
827 // At this point we should have a thread stopped if waitpid succeeds.
828 if ((status = waitpid(tid, NULL, __WALL)) < 0)
829 {
830 // No such thread. The thread may have exited.
831 // More error handling may be needed.
832 if (errno == ESRCH)
833 {
834 it = tids_to_attach.erase(it);
835 continue;
836 }
837 else
838 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000839 error.SetErrorToErrno();
840 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000841 }
842 }
843
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000844 error = SetDefaultPtraceOpts(tid);
845 if (error.Fail())
846 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000847
848 if (log)
849 log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
850
851 it->second = true;
852
853 // Create the thread, mark it as stopped.
Pavel Labathf9077782015-08-21 09:13:53 +0000854 NativeThreadLinuxSP thread_sp (AddThread(static_cast<lldb::tid_t>(tid)));
Todd Fialaaf245d12014-06-30 21:05:18 +0000855 assert (thread_sp && "AddThread() returned a nullptr");
Chaoren Linfa03ad22015-02-03 01:50:42 +0000856
857 // This will notify this is a new thread and tell the system it is stopped.
Pavel Labathf9077782015-08-21 09:13:53 +0000858 thread_sp->SetStoppedBySignal(SIGSTOP);
859 ThreadWasCreated(*thread_sp);
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000860 SetCurrentThreadID (thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000861 }
862
863 // move the loop forward
864 ++it;
865 }
866 }
867
868 if (tids_to_attach.size() > 0)
869 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000870 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000871 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000872 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +0000873 }
874 else
875 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000876 error.SetErrorToGenericError();
877 error.SetErrorString("No such process.");
878 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000879 }
880
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000881 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000882}
883
Chaoren Lin97ccc292015-02-03 01:51:12 +0000884Error
Todd Fialaaf245d12014-06-30 21:05:18 +0000885NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
886{
887 long ptrace_opts = 0;
888
889 // Have the child raise an event on exit. This is used to keep the child in
890 // limbo until it is destroyed.
891 ptrace_opts |= PTRACE_O_TRACEEXIT;
892
893 // Have the tracer trace threads which spawn in the inferior process.
894 // TODO: if we want to support tracing the inferiors' child, add the
895 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
896 ptrace_opts |= PTRACE_O_TRACECLONE;
897
898 // Have the tracer notify us before execve returns
899 // (needed to disable legacy SIGTRAP generation)
900 ptrace_opts |= PTRACE_O_TRACEEXEC;
901
Pavel Labath4a9babb2015-06-30 17:04:49 +0000902 return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts);
Todd Fialaaf245d12014-06-30 21:05:18 +0000903}
904
905static ExitType convert_pid_status_to_exit_type (int status)
906{
907 if (WIFEXITED (status))
908 return ExitType::eExitTypeExit;
909 else if (WIFSIGNALED (status))
910 return ExitType::eExitTypeSignal;
911 else if (WIFSTOPPED (status))
912 return ExitType::eExitTypeStop;
913 else
914 {
915 // We don't know what this is.
916 return ExitType::eExitTypeInvalid;
917 }
918}
919
920static int convert_pid_status_to_return_code (int status)
921{
922 if (WIFEXITED (status))
923 return WEXITSTATUS (status);
924 else if (WIFSIGNALED (status))
925 return WTERMSIG (status);
926 else if (WIFSTOPPED (status))
927 return WSTOPSIG (status);
928 else
929 {
930 // We don't know what this is.
931 return ExitType::eExitTypeInvalid;
932 }
933}
934
Pavel Labath1107b5a2015-04-17 14:07:49 +0000935// Handles all waitpid events from the inferior process.
936void
937NativeProcessLinux::MonitorCallback(lldb::pid_t pid,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000938 bool exited,
939 int signal,
940 int status)
Todd Fialaaf245d12014-06-30 21:05:18 +0000941{
942 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
943
Todd Fialaaf245d12014-06-30 21:05:18 +0000944 // Certain activities differ based on whether the pid is the tid of the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000945 const bool is_main_thread = (pid == GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000946
947 // Handle when the thread exits.
948 if (exited)
949 {
950 if (log)
Chaoren Lin86fd8e42015-02-03 01:51:15 +0000951 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 +0000952
953 // This is a thread that exited. Ensure we're not tracking it anymore.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000954 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000955
956 if (is_main_thread)
957 {
958 // We only set the exit status and notify the delegate if we haven't already set the process
959 // state to an exited state. We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
960 // for the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000961 const bool already_notified = (GetState() == StateType::eStateExited) || (GetState () == StateType::eStateCrashed);
Todd Fialaaf245d12014-06-30 21:05:18 +0000962 if (!already_notified)
963 {
964 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +0000965 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 +0000966 // The main thread exited. We're done monitoring. Report to delegate.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000967 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +0000968
969 // Notify delegate that our process has exited.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000970 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +0000971 }
972 else
973 {
974 if (log)
975 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
976 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000977 }
978 else
979 {
980 // Do we want to report to the delegate in this case? I think not. If this was an orderly
981 // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
982 // and we would have done an all-stop then.
983 if (log)
984 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 +0000985 }
Pavel Labath1107b5a2015-04-17 14:07:49 +0000986 return;
Todd Fialaaf245d12014-06-30 21:05:18 +0000987 }
988
Todd Fialaaf245d12014-06-30 21:05:18 +0000989 siginfo_t info;
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000990 const auto info_err = GetSignalInfo(pid, &info);
991 auto thread_sp = GetThreadByID(pid);
992
993 if (! thread_sp)
994 {
995 // Normally, the only situation when we cannot find the thread is if we have just
996 // received a new thread notification. This is indicated by GetSignalInfo() returning
997 // si_code == SI_USER and si_pid == 0
998 if (log)
999 log->Printf("NativeProcessLinux::%s received notification about an unknown tid %" PRIu64 ".", __FUNCTION__, pid);
1000
1001 if (info_err.Fail())
1002 {
1003 if (log)
1004 log->Printf("NativeProcessLinux::%s (tid %" PRIu64 ") GetSignalInfo failed (%s). Ingoring this notification.", __FUNCTION__, pid, info_err.AsCString());
1005 return;
1006 }
1007
1008 if (log && (info.si_code != SI_USER || info.si_pid != 0))
1009 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);
1010
1011 auto thread_sp = AddThread(pid);
1012 // Resume the newly created thread.
1013 ResumeThread(*thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
1014 ThreadWasCreated(*thread_sp);
1015 return;
1016 }
1017
1018 // Get details on the signal raised.
1019 if (info_err.Success())
Chaoren Linfa03ad22015-02-03 01:50:42 +00001020 {
1021 // We have retrieved the signal info. Dispatch appropriately.
1022 if (info.si_signo == SIGTRAP)
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001023 MonitorSIGTRAP(info, *thread_sp);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001024 else
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001025 MonitorSignal(info, *thread_sp, exited);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001026 }
1027 else
Todd Fialaaf245d12014-06-30 21:05:18 +00001028 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001029 if (info_err.GetError() == EINVAL)
Todd Fialaaf245d12014-06-30 21:05:18 +00001030 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00001031 // This is a group stop reception for this tid.
Pavel Labath39036ac2015-05-21 08:32:18 +00001032 // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the
1033 // tracee, triggering the group-stop mechanism. Normally receiving these would stop
1034 // the process, pending a SIGCONT. Simulating this state in a debugger is hard and is
1035 // generally not needed (one use case is debugging background task being managed by a
1036 // shell). For general use, it is sufficient to stop the process in a signal-delivery
1037 // stop which happens before the group stop. This done by MonitorSignal and works
1038 // correctly for all signals.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001039 if (log)
Pavel Labath39036ac2015-05-21 08:32:18 +00001040 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 +00001041 ResumeThread(*thread_sp, thread_sp->GetState(), LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001042 }
1043 else
1044 {
1045 // ptrace(GETSIGINFO) failed (but not due to group-stop).
1046
1047 // A return value of ESRCH means the thread/process is no longer on the system,
1048 // so it was killed somehow outside of our control. Either way, we can't do anything
1049 // with it anymore.
1050
Todd Fialaaf245d12014-06-30 21:05:18 +00001051 // Stop tracking the metadata for the thread since it's entirely off the system now.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001052 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001053
1054 if (log)
1055 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001056 __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 +00001057
1058 if (is_main_thread)
1059 {
1060 // Notify the delegate - our process is not available but appears to have been killed outside
1061 // our control. Is eStateExited the right exit state in this case?
Pavel Labath1107b5a2015-04-17 14:07:49 +00001062 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
1063 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001064 }
1065 else
1066 {
1067 // This thread was pulled out from underneath us. Anything to do here? Do we want to do an all stop?
1068 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +00001069 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 +00001070 }
1071 }
1072 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001073}
1074
1075void
Pavel Labath426bdf82015-04-28 07:51:52 +00001076NativeProcessLinux::WaitForNewThread(::pid_t tid)
1077{
1078 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1079
Pavel Labathf9077782015-08-21 09:13:53 +00001080 NativeThreadLinuxSP new_thread_sp = GetThreadByID(tid);
Pavel Labath426bdf82015-04-28 07:51:52 +00001081
1082 if (new_thread_sp)
1083 {
1084 // We are already tracking the thread - we got the event on the new thread (see
1085 // MonitorSignal) before this one. We are done.
1086 return;
1087 }
1088
1089 // The thread is not tracked yet, let's wait for it to appear.
1090 int status = -1;
1091 ::pid_t wait_pid;
1092 do
1093 {
1094 if (log)
1095 log->Printf ("NativeProcessLinux::%s() received thread creation event for tid %" PRIu32 ". tid not tracked yet, waiting for thread to appear...", __FUNCTION__, tid);
1096 wait_pid = waitpid(tid, &status, __WALL);
1097 }
1098 while (wait_pid == -1 && errno == EINTR);
1099 // Since we are waiting on a specific tid, this must be the creation event. But let's do
1100 // some checks just in case.
1101 if (wait_pid != tid) {
1102 if (log)
1103 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime", __FUNCTION__, tid);
1104 // The only way I know of this could happen is if the whole process was
1105 // SIGKILLed in the mean time. In any case, we can't do anything about that now.
1106 return;
1107 }
1108 if (WIFEXITED(status))
1109 {
1110 if (log)
1111 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " returned an 'exited' event. Not tracking the thread.", __FUNCTION__, tid);
1112 // Also a very improbable event.
1113 return;
1114 }
1115
1116 siginfo_t info;
1117 Error error = GetSignalInfo(tid, &info);
1118 if (error.Fail())
1119 {
1120 if (log)
1121 log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime.", __FUNCTION__, tid);
1122 return;
1123 }
1124
1125 if (((info.si_pid != 0) || (info.si_code != SI_USER)) && log)
1126 {
1127 // We should be getting a thread creation signal here, but we received something
1128 // else. There isn't much we can do about it now, so we will just log that. Since the
1129 // thread is alive and we are receiving events from it, we shall pretend that it was
1130 // created properly.
1131 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);
1132 }
1133
1134 if (log)
1135 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 ": tracking new thread tid %" PRIu32,
1136 __FUNCTION__, GetID (), tid);
1137
Pavel Labathf9077782015-08-21 09:13:53 +00001138 new_thread_sp = AddThread(tid);
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001139 ResumeThread(*new_thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
Pavel Labathf9077782015-08-21 09:13:53 +00001140 ThreadWasCreated(*new_thread_sp);
Pavel Labath426bdf82015-04-28 07:51:52 +00001141}
1142
1143void
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001144NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info, NativeThreadLinux &thread)
Todd Fialaaf245d12014-06-30 21:05:18 +00001145{
1146 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001147 const bool is_main_thread = (thread.GetID() == GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001148
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001149 assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
Todd Fialaaf245d12014-06-30 21:05:18 +00001150
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001151 switch (info.si_code)
Todd Fialaaf245d12014-06-30 21:05:18 +00001152 {
1153 // TODO: these two cases are required if we want to support tracing of the inferiors' children. We'd need this to debug a monitor.
1154 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
1155 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
1156
1157 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
1158 {
Pavel Labath5fd24c62015-04-23 09:04:35 +00001159 // This is the notification on the parent thread which informs us of new thread
Pavel Labath426bdf82015-04-28 07:51:52 +00001160 // creation.
1161 // We don't want to do anything with the parent thread so we just resume it. In case we
1162 // want to implement "break on thread creation" functionality, we would need to stop
1163 // here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001164
Pavel Labath426bdf82015-04-28 07:51:52 +00001165 unsigned long event_message = 0;
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001166 if (GetEventMessage(thread.GetID(), &event_message).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001167 {
Pavel Labath426bdf82015-04-28 07:51:52 +00001168 if (log)
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001169 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 +00001170 } else
1171 WaitForNewThread(event_message);
Todd Fialaaf245d12014-06-30 21:05:18 +00001172
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001173 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001174 break;
1175 }
1176
1177 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
Todd Fialaa9882ce2014-08-28 15:46:54 +00001178 {
Pavel Labathf9077782015-08-21 09:13:53 +00001179 NativeThreadLinuxSP main_thread_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001180 if (log)
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001181 log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info.si_code ^ SIGTRAP);
Todd Fialaa9882ce2014-08-28 15:46:54 +00001182
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001183 // Exec clears any pending notifications.
Pavel Labath0e1d7292015-08-20 09:06:12 +00001184 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
Chaoren Linfa03ad22015-02-03 01:50:42 +00001185
Pavel Labath57a77112016-05-16 09:18:30 +00001186 // 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 +00001187 if (log)
1188 log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
1189
1190 for (auto thread_sp : m_threads)
Todd Fialaa9882ce2014-08-28 15:46:54 +00001191 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001192 const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
1193 if (is_main_thread)
Todd Fialaa9882ce2014-08-28 15:46:54 +00001194 {
Pavel Labathf9077782015-08-21 09:13:53 +00001195 main_thread_sp = std::static_pointer_cast<NativeThreadLinux>(thread_sp);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001196 if (log)
1197 log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00001198 }
1199 else
1200 {
Todd Fialaa9882ce2014-08-28 15:46:54 +00001201 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001202 log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00001203 }
1204 }
1205
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001206 m_threads.clear ();
1207
1208 if (main_thread_sp)
1209 {
1210 m_threads.push_back (main_thread_sp);
1211 SetCurrentThreadID (main_thread_sp->GetID ());
Pavel Labathf9077782015-08-21 09:13:53 +00001212 main_thread_sp->SetStoppedByExec();
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001213 }
1214 else
1215 {
1216 SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
1217 if (log)
1218 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
1219 }
1220
Chaoren Linfa03ad22015-02-03 01:50:42 +00001221 // Tell coordinator about about the "new" (since exec) stopped main thread.
Pavel Labathf9077782015-08-21 09:13:53 +00001222 ThreadWasCreated(*main_thread_sp);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001223
Todd Fialaa9882ce2014-08-28 15:46:54 +00001224 // Let our delegate know we have just exec'd.
1225 NotifyDidExec ();
1226
1227 // If we have a main thread, indicate we are stopped.
1228 assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001229
1230 // Let the process know we're stopped.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001231 StopRunningThreads(main_thread_sp->GetID());
Todd Fialaa9882ce2014-08-28 15:46:54 +00001232
Todd Fialaaf245d12014-06-30 21:05:18 +00001233 break;
Todd Fialaa9882ce2014-08-28 15:46:54 +00001234 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001235
1236 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
1237 {
1238 // The inferior process or one of its threads is about to exit.
Pavel Labath6e351632015-05-15 13:30:59 +00001239 // We don't want to do anything with the thread so we just resume it. In case we
1240 // want to implement "break on thread exit" functionality, we would need to stop
1241 // here.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001242
Todd Fialaaf245d12014-06-30 21:05:18 +00001243 unsigned long data = 0;
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001244 if (GetEventMessage(thread.GetID(), &data).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001245 data = -1;
1246
1247 if (log)
1248 {
1249 log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
1250 __FUNCTION__,
1251 data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001252 thread.GetID(),
Todd Fialaaf245d12014-06-30 21:05:18 +00001253 is_main_thread ? "is main thread" : "not main thread");
1254 }
1255
Todd Fialaaf245d12014-06-30 21:05:18 +00001256 if (is_main_thread)
1257 {
1258 SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001259 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001260
Pavel Labath86852d32015-09-01 10:59:36 +00001261 StateType state = thread.GetState();
1262 if (! StateIsRunningState(state))
1263 {
1264 // Due to a kernel bug, we may sometimes get this stop after the inferior gets a
1265 // SIGKILL. This confuses our state tracking logic in ResumeThread(), since normally,
1266 // we should not be receiving any ptrace events while the inferior is stopped. This
1267 // makes sure that the inferior is resumed and exits normally.
1268 state = eStateRunning;
1269 }
1270 ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001271
1272 break;
1273 }
1274
1275 case 0:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001276 case TRAP_TRACE: // We receive this on single stepping.
1277 case TRAP_HWBKPT: // We receive this on watchpoint hit
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001278 {
1279 // If a watchpoint was hit, report it
1280 uint32_t wp_index;
Tamas Berghammer1fa5c4b2015-10-13 16:48:04 +00001281 Error error = thread.GetRegisterContext()->GetWatchpointHitIndex(wp_index, (uintptr_t)info.si_addr);
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001282 if (error.Fail() && log)
1283 log->Printf("NativeProcessLinux::%s() "
1284 "received error while checking for watchpoint hits, "
1285 "pid = %" PRIu64 " error = %s",
1286 __FUNCTION__, thread.GetID(), error.AsCString());
1287 if (wp_index != LLDB_INVALID_INDEX32)
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001288 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001289 MonitorWatchpoint(thread, wp_index);
1290 break;
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001291 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001292
Tamas Berghammerbe379e12016-02-16 15:14:36 +00001293 // Otherwise, report step over
1294 MonitorTrace(thread);
Todd Fialaaf245d12014-06-30 21:05:18 +00001295 break;
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001296 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001297
1298 case SI_KERNEL:
Mohit K. Bhakkad35799962015-06-18 04:53:18 +00001299#if defined __mips__
1300 // For mips there is no special signal for watchpoint
1301 // So we check for watchpoint in kernel trap
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001302 {
1303 // If a watchpoint was hit, report it
1304 uint32_t wp_index;
1305 Error error = thread.GetRegisterContext()->GetWatchpointHitIndex(wp_index, LLDB_INVALID_ADDRESS);
1306 if (error.Fail() && log)
1307 log->Printf("NativeProcessLinux::%s() "
1308 "received error while checking for watchpoint hits, "
1309 "pid = %" PRIu64 " error = %s",
Mohit K. Bhakkad16ad0322015-08-28 12:08:26 +00001310 __FUNCTION__, thread.GetID(), error.AsCString());
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001311 if (wp_index != LLDB_INVALID_INDEX32)
Mohit K. Bhakkad35799962015-06-18 04:53:18 +00001312 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001313 MonitorWatchpoint(thread, wp_index);
1314 break;
Mohit K. Bhakkad35799962015-06-18 04:53:18 +00001315 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001316 }
Mohit K. Bhakkad35799962015-06-18 04:53:18 +00001317 // NO BREAK
1318#endif
Todd Fialaaf245d12014-06-30 21:05:18 +00001319 case TRAP_BRKPT:
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001320 MonitorBreakpoint(thread);
Todd Fialaaf245d12014-06-30 21:05:18 +00001321 break;
1322
1323 case SIGTRAP:
1324 case (SIGTRAP | 0x80):
1325 if (log)
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001326 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 +00001327
Todd Fialaaf245d12014-06-30 21:05:18 +00001328 // Ignore these signals until we know more about them.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001329 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001330 break;
1331
1332 default:
1333 assert(false && "Unexpected SIGTRAP code!");
1334 if (log)
Pavel Labath6e351632015-05-15 13:30:59 +00001335 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 "tid %" PRIu64 " received unhandled SIGTRAP code: 0x%d",
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001336 __FUNCTION__, GetID(), thread.GetID(), info.si_code);
Todd Fialaaf245d12014-06-30 21:05:18 +00001337 break;
1338
1339 }
1340}
1341
1342void
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001343NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread)
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001344{
1345 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1346 if (log)
1347 log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)",
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001348 __FUNCTION__, thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001349
Pavel Labath0e1d7292015-08-20 09:06:12 +00001350 // This thread is currently stopped.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001351 thread.SetStoppedByTrace();
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001352
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001353 StopRunningThreads(thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001354}
1355
1356void
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001357NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread)
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001358{
1359 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
1360 if (log)
1361 log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001362 __FUNCTION__, thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001363
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001364 // Mark the thread as stopped at breakpoint.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001365 thread.SetStoppedByBreakpoint();
1366 Error error = FixupBreakpointPCAsNeeded(thread);
1367 if (error.Fail())
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001368 if (log)
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001369 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
1370 __FUNCTION__, thread.GetID(), error.AsCString());
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001371
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001372 if (m_threads_stepping_with_breakpoint.find(thread.GetID()) != m_threads_stepping_with_breakpoint.end())
1373 thread.SetStoppedByTrace();
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001374
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001375 StopRunningThreads(thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001376}
1377
1378void
Pavel Labathf9077782015-08-21 09:13:53 +00001379NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread, uint32_t wp_index)
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001380{
1381 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
1382 if (log)
1383 log->Printf("NativeProcessLinux::%s() received watchpoint event, "
1384 "pid = %" PRIu64 ", wp_index = %" PRIu32,
Pavel Labathf9077782015-08-21 09:13:53 +00001385 __FUNCTION__, thread.GetID(), wp_index);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001386
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001387 // Mark the thread as stopped at watchpoint.
1388 // The address is at (lldb::addr_t)info->si_addr if we need it.
Pavel Labathf9077782015-08-21 09:13:53 +00001389 thread.SetStoppedByWatchpoint(wp_index);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001390
1391 // We need to tell all other running threads before we notify the delegate about this stop.
Pavel Labathf9077782015-08-21 09:13:53 +00001392 StopRunningThreads(thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001393}
1394
1395void
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001396NativeProcessLinux::MonitorSignal(const siginfo_t &info, NativeThreadLinux &thread, bool exited)
Todd Fialaaf245d12014-06-30 21:05:18 +00001397{
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001398 const int signo = info.si_signo;
1399 const bool is_from_llgs = info.si_pid == getpid ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001400
1401 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1402
1403 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1404 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1405 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
1406 //
1407 // IOW, user generated signals never generate what we consider to be a
1408 // "crash".
1409 //
1410 // Similarly, ACK signals generated by this monitor.
1411
Todd Fialaaf245d12014-06-30 21:05:18 +00001412 // Handle the signal.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001413 if (info.si_code == SI_TKILL || info.si_code == SI_USER)
Todd Fialaaf245d12014-06-30 21:05:18 +00001414 {
1415 if (log)
1416 log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
1417 __FUNCTION__,
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001418 Host::GetSignalAsCString(signo),
Todd Fialaaf245d12014-06-30 21:05:18 +00001419 signo,
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001420 (info.si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
1421 info.si_pid,
Todd Fiala511e5cd2014-09-11 23:29:14 +00001422 is_from_llgs ? "from llgs" : "not from llgs",
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001423 thread.GetID());
Todd Fiala58a2f662014-08-12 17:02:07 +00001424 }
1425
1426 // Check for thread stop notification.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001427 if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP))
Todd Fiala58a2f662014-08-12 17:02:07 +00001428 {
1429 // This is a tgkill()-based stop.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001430 if (log)
1431 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
1432 __FUNCTION__,
1433 GetID (),
1434 thread.GetID());
1435
1436 // Check that we're not already marked with a stop reason.
1437 // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
1438 // the kernel signaled us with the thread stopping which we handled and marked as stopped,
1439 // and that, without an intervening resume, we received another stop. It is more likely
1440 // that we are missing the marking of a run state somewhere if we find that the thread was
1441 // marked as stopped.
1442 const StateType thread_state = thread.GetState();
1443 if (!StateIsStoppedState (thread_state, false))
Todd Fiala58a2f662014-08-12 17:02:07 +00001444 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001445 // An inferior thread has stopped because of a SIGSTOP we have sent it.
1446 // Generally, these are not important stops and we don't want to report them as
1447 // they are just used to stop other threads when one thread (the one with the
1448 // *real* stop reason) hits a breakpoint (watchpoint, etc...). However, in the
1449 // case of an asynchronous Interrupt(), this *is* the real stop reason, so we
1450 // leave the signal intact if this is the thread that was chosen as the
1451 // triggering thread.
1452 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID)
Chaoren Linaab58632015-02-03 01:50:57 +00001453 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001454 if (m_pending_notification_tid == thread.GetID())
1455 thread.SetStoppedBySignal(SIGSTOP, &info);
Pavel Labath0e1d7292015-08-20 09:06:12 +00001456 else
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001457 thread.SetStoppedWithNoReason();
1458
1459 SetCurrentThreadID (thread.GetID ());
1460 SignalIfAllThreadsStopped();
Chaoren Linaab58632015-02-03 01:50:57 +00001461 }
1462 else
1463 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001464 // We can end up here if stop was initiated by LLGS but by this time a
1465 // thread stop has occurred - maybe initiated by another event.
1466 Error error = ResumeThread(thread, thread.GetState(), 0);
1467 if (error.Fail() && log)
Chaoren Linaab58632015-02-03 01:50:57 +00001468 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001469 log->Printf("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s",
1470 __FUNCTION__, thread.GetID(), error.AsCString());
Chaoren Linaab58632015-02-03 01:50:57 +00001471 }
1472 }
Todd Fiala58a2f662014-08-12 17:02:07 +00001473 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001474 else
1475 {
1476 if (log)
1477 {
1478 // Retrieve the signal name if the thread was stopped by a signal.
1479 int stop_signo = 0;
1480 const bool stopped_by_signal = thread.IsStopped(&stop_signo);
1481 const char *signal_name = stopped_by_signal ? Host::GetSignalAsCString(stop_signo) : "<not stopped by signal>";
1482 if (!signal_name)
1483 signal_name = "<no-signal-name>";
1484
1485 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",
1486 __FUNCTION__,
1487 GetID (),
1488 thread.GetID(),
1489 StateAsCString (thread_state),
1490 stop_signo,
1491 signal_name);
1492 }
1493 SignalIfAllThreadsStopped();
1494 }
Todd Fiala58a2f662014-08-12 17:02:07 +00001495
1496 // Done handling.
Todd Fialaaf245d12014-06-30 21:05:18 +00001497 return;
1498 }
1499
1500 if (log)
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001501 log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, Host::GetSignalAsCString(signo));
Todd Fialaaf245d12014-06-30 21:05:18 +00001502
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001503 // This thread is stopped.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001504 thread.SetStoppedBySignal(signo, &info);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001505
1506 // Send a stop to the debugger after we get all other threads to stop.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001507 StopRunningThreads(thread.GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +00001508}
1509
Tamas Berghammere7708682015-04-22 10:00:23 +00001510namespace {
1511
1512struct EmulatorBaton
1513{
1514 NativeProcessLinux* m_process;
1515 NativeRegisterContext* m_reg_context;
Tamas Berghammere7708682015-04-22 10:00:23 +00001516
Pavel Labath6648fcc2015-04-27 09:21:14 +00001517 // eRegisterKindDWARF -> RegsiterValue
1518 std::unordered_map<uint32_t, RegisterValue> m_register_values;
1519
1520 EmulatorBaton(NativeProcessLinux* process, NativeRegisterContext* reg_context) :
Tamas Berghammere7708682015-04-22 10:00:23 +00001521 m_process(process), m_reg_context(reg_context) {}
1522};
1523
1524} // anonymous namespace
1525
1526static size_t
1527ReadMemoryCallback (EmulateInstruction *instruction,
1528 void *baton,
1529 const EmulateInstruction::Context &context,
1530 lldb::addr_t addr,
1531 void *dst,
1532 size_t length)
1533{
1534 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
1535
Chaoren Lin3eb4b452015-04-29 17:24:48 +00001536 size_t bytes_read;
Tamas Berghammere7708682015-04-22 10:00:23 +00001537 emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
1538 return bytes_read;
1539}
1540
1541static bool
1542ReadRegisterCallback (EmulateInstruction *instruction,
1543 void *baton,
1544 const RegisterInfo *reg_info,
1545 RegisterValue &reg_value)
1546{
1547 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
1548
Pavel Labath6648fcc2015-04-27 09:21:14 +00001549 auto it = emulator_baton->m_register_values.find(reg_info->kinds[eRegisterKindDWARF]);
1550 if (it != emulator_baton->m_register_values.end())
1551 {
1552 reg_value = it->second;
1553 return true;
1554 }
1555
Tamas Berghammere7708682015-04-22 10:00:23 +00001556 // The emulator only fill in the dwarf regsiter numbers (and in some case
1557 // the generic register numbers). Get the full register info from the
1558 // register context based on the dwarf register numbers.
1559 const RegisterInfo* full_reg_info = emulator_baton->m_reg_context->GetRegisterInfo(
1560 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
1561
1562 Error error = emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
Pavel Labath6648fcc2015-04-27 09:21:14 +00001563 if (error.Success())
Pavel Labath6648fcc2015-04-27 09:21:14 +00001564 return true;
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001565
Pavel Labath6648fcc2015-04-27 09:21:14 +00001566 return false;
Tamas Berghammere7708682015-04-22 10:00:23 +00001567}
1568
1569static bool
1570WriteRegisterCallback (EmulateInstruction *instruction,
1571 void *baton,
1572 const EmulateInstruction::Context &context,
1573 const RegisterInfo *reg_info,
1574 const RegisterValue &reg_value)
1575{
1576 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
Pavel Labath6648fcc2015-04-27 09:21:14 +00001577 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = reg_value;
Tamas Berghammere7708682015-04-22 10:00:23 +00001578 return true;
1579}
1580
1581static size_t
1582WriteMemoryCallback (EmulateInstruction *instruction,
1583 void *baton,
1584 const EmulateInstruction::Context &context,
1585 lldb::addr_t addr,
1586 const void *dst,
1587 size_t length)
1588{
1589 return length;
1590}
1591
1592static lldb::addr_t
1593ReadFlags (NativeRegisterContext* regsiter_context)
1594{
1595 const RegisterInfo* flags_info = regsiter_context->GetRegisterInfo(
1596 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1597 return regsiter_context->ReadRegisterAsUnsigned(flags_info, LLDB_INVALID_ADDRESS);
1598}
1599
1600Error
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001601NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadLinux &thread)
Tamas Berghammere7708682015-04-22 10:00:23 +00001602{
1603 Error error;
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001604 NativeRegisterContextSP register_context_sp = thread.GetRegisterContext();
Tamas Berghammere7708682015-04-22 10:00:23 +00001605
1606 std::unique_ptr<EmulateInstruction> emulator_ap(
1607 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, nullptr));
1608
1609 if (emulator_ap == nullptr)
1610 return Error("Instruction emulator not found!");
1611
1612 EmulatorBaton baton(this, register_context_sp.get());
1613 emulator_ap->SetBaton(&baton);
1614 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
1615 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
1616 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
1617 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
1618
1619 if (!emulator_ap->ReadInstruction())
1620 return Error("Read instruction failed!");
1621
Pavel Labath6648fcc2015-04-27 09:21:14 +00001622 bool emulation_result = emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
1623
1624 const RegisterInfo* reg_info_pc = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1625 const RegisterInfo* reg_info_flags = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1626
1627 auto pc_it = baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1628 auto flags_it = baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
1629
Tamas Berghammere7708682015-04-22 10:00:23 +00001630 lldb::addr_t next_pc;
1631 lldb::addr_t next_flags;
Pavel Labath6648fcc2015-04-27 09:21:14 +00001632 if (emulation_result)
Tamas Berghammere7708682015-04-22 10:00:23 +00001633 {
Pavel Labath6648fcc2015-04-27 09:21:14 +00001634 assert(pc_it != baton.m_register_values.end() && "Emulation was successfull but PC wasn't updated");
1635 next_pc = pc_it->second.GetAsUInt64();
1636
1637 if (flags_it != baton.m_register_values.end())
1638 next_flags = flags_it->second.GetAsUInt64();
Tamas Berghammere7708682015-04-22 10:00:23 +00001639 else
1640 next_flags = ReadFlags (register_context_sp.get());
1641 }
Pavel Labath6648fcc2015-04-27 09:21:14 +00001642 else if (pc_it == baton.m_register_values.end())
Tamas Berghammere7708682015-04-22 10:00:23 +00001643 {
1644 // Emulate instruction failed and it haven't changed PC. Advance PC
1645 // with the size of the current opcode because the emulation of all
1646 // PC modifying instruction should be successful. The failure most
1647 // likely caused by a not supported instruction which don't modify PC.
1648 next_pc = register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
1649 next_flags = ReadFlags (register_context_sp.get());
1650 }
1651 else
1652 {
1653 // The instruction emulation failed after it modified the PC. It is an
1654 // unknown error where we can't continue because the next instruction is
1655 // modifying the PC but we don't know how.
1656 return Error ("Instruction emulation failed unexpectedly.");
1657 }
1658
1659 if (m_arch.GetMachine() == llvm::Triple::arm)
1660 {
1661 if (next_flags & 0x20)
1662 {
1663 // Thumb mode
1664 error = SetSoftwareBreakpoint(next_pc, 2);
1665 }
1666 else
1667 {
1668 // Arm mode
1669 error = SetSoftwareBreakpoint(next_pc, 4);
1670 }
1671 }
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001672 else if (m_arch.GetMachine() == llvm::Triple::mips64
Jaydeep Patilc60c9452015-06-23 03:37:08 +00001673 || m_arch.GetMachine() == llvm::Triple::mips64el
1674 || m_arch.GetMachine() == llvm::Triple::mips
1675 || m_arch.GetMachine() == llvm::Triple::mipsel)
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001676 error = SetSoftwareBreakpoint(next_pc, 4);
Tamas Berghammere7708682015-04-22 10:00:23 +00001677 else
1678 {
1679 // No size hint is given for the next breakpoint
1680 error = SetSoftwareBreakpoint(next_pc, 0);
1681 }
1682
Tamas Berghammere7708682015-04-22 10:00:23 +00001683 if (error.Fail())
1684 return error;
1685
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001686 m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
Tamas Berghammere7708682015-04-22 10:00:23 +00001687
1688 return Error();
1689}
1690
1691bool
1692NativeProcessLinux::SupportHardwareSingleStepping() const
1693{
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001694 if (m_arch.GetMachine() == llvm::Triple::arm
Jaydeep Patilc60c9452015-06-23 03:37:08 +00001695 || m_arch.GetMachine() == llvm::Triple::mips64 || m_arch.GetMachine() == llvm::Triple::mips64el
1696 || m_arch.GetMachine() == llvm::Triple::mips || m_arch.GetMachine() == llvm::Triple::mipsel)
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001697 return false;
1698 return true;
Tamas Berghammere7708682015-04-22 10:00:23 +00001699}
1700
Todd Fialaaf245d12014-06-30 21:05:18 +00001701Error
1702NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
1703{
Todd Fialaaf245d12014-06-30 21:05:18 +00001704 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1705 if (log)
1706 log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
1707
Tamas Berghammere7708682015-04-22 10:00:23 +00001708 bool software_single_step = !SupportHardwareSingleStepping();
Todd Fialaaf245d12014-06-30 21:05:18 +00001709
Tamas Berghammere7708682015-04-22 10:00:23 +00001710 if (software_single_step)
1711 {
1712 for (auto thread_sp : m_threads)
1713 {
1714 assert (thread_sp && "thread list should not contain NULL threads");
1715
1716 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
1717 if (action == nullptr)
1718 continue;
1719
1720 if (action->state == eStateStepping)
1721 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001722 Error error = SetupSoftwareSingleStepping(static_cast<NativeThreadLinux &>(*thread_sp));
Tamas Berghammere7708682015-04-22 10:00:23 +00001723 if (error.Fail())
1724 return error;
1725 }
1726 }
1727 }
1728
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001729 for (auto thread_sp : m_threads)
Todd Fialaaf245d12014-06-30 21:05:18 +00001730 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001731 assert (thread_sp && "thread list should not contain NULL threads");
1732
1733 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
1734
1735 if (action == nullptr)
Todd Fialaaf245d12014-06-30 21:05:18 +00001736 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00001737 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001738 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
1739 __FUNCTION__, GetID (), thread_sp->GetID ());
1740 continue;
1741 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001742
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001743 if (log)
1744 {
1745 log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
1746 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
1747 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001748
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001749 switch (action->state)
1750 {
1751 case eStateRunning:
Pavel Labath0e1d7292015-08-20 09:06:12 +00001752 case eStateStepping:
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001753 {
1754 // Run the thread, possibly feeding it the signal.
1755 const int signo = action->signal;
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001756 ResumeThread(static_cast<NativeThreadLinux &>(*thread_sp), action->state, signo);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001757 break;
1758 }
1759
1760 case eStateSuspended:
1761 case eStateStopped:
Pavel Labath108c3252015-05-12 09:03:18 +00001762 lldbassert(0 && "Unexpected state");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001763
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001764 default:
1765 return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
1766 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001767 }
1768 }
1769
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001770 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00001771}
1772
1773Error
1774NativeProcessLinux::Halt ()
1775{
1776 Error error;
1777
Todd Fialaaf245d12014-06-30 21:05:18 +00001778 if (kill (GetID (), SIGSTOP) != 0)
1779 error.SetErrorToErrno ();
1780
1781 return error;
1782}
1783
1784Error
1785NativeProcessLinux::Detach ()
1786{
1787 Error error;
1788
Todd Fialaaf245d12014-06-30 21:05:18 +00001789 // Stop monitoring the inferior.
Pavel Labath19cbe962015-07-21 13:20:32 +00001790 m_sigchld_handle.reset();
Todd Fialaaf245d12014-06-30 21:05:18 +00001791
Pavel Labath7a9495b2015-09-01 15:00:51 +00001792 // Tell ptrace to detach from the process.
1793 if (GetID () == LLDB_INVALID_PROCESS_ID)
1794 return error;
1795
1796 for (auto thread_sp : m_threads)
1797 {
1798 Error e = Detach(thread_sp->GetID());
1799 if (e.Fail())
1800 error = e; // Save the error, but still attempt to detach from other threads.
1801 }
1802
Todd Fialaaf245d12014-06-30 21:05:18 +00001803 return error;
1804}
1805
1806Error
1807NativeProcessLinux::Signal (int signo)
1808{
1809 Error error;
1810
1811 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1812 if (log)
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001813 log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
1814 __FUNCTION__, signo, Host::GetSignalAsCString(signo), GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +00001815
1816 if (kill(GetID(), signo))
1817 error.SetErrorToErrno();
1818
1819 return error;
1820}
1821
1822Error
Chaoren Line9547b82015-02-03 01:51:00 +00001823NativeProcessLinux::Interrupt ()
1824{
1825 // Pick a running thread (or if none, a not-dead stopped thread) as
1826 // the chosen thread that will be the stop-reason thread.
Chaoren Line9547b82015-02-03 01:51:00 +00001827 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1828
1829 NativeThreadProtocolSP running_thread_sp;
1830 NativeThreadProtocolSP stopped_thread_sp;
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001831
1832 if (log)
1833 log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
1834
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001835 for (auto thread_sp : m_threads)
Chaoren Line9547b82015-02-03 01:51:00 +00001836 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001837 // The thread shouldn't be null but lets just cover that here.
1838 if (!thread_sp)
1839 continue;
Chaoren Line9547b82015-02-03 01:51:00 +00001840
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001841 // If we have a running or stepping thread, we'll call that the
1842 // target of the interrupt.
1843 const auto thread_state = thread_sp->GetState ();
1844 if (thread_state == eStateRunning ||
1845 thread_state == eStateStepping)
Chaoren Line9547b82015-02-03 01:51:00 +00001846 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001847 running_thread_sp = thread_sp;
1848 break;
1849 }
1850 else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
1851 {
1852 // Remember the first non-dead stopped thread. We'll use that as a backup if there are no running threads.
1853 stopped_thread_sp = thread_sp;
Chaoren Line9547b82015-02-03 01:51:00 +00001854 }
1855 }
1856
1857 if (!running_thread_sp && !stopped_thread_sp)
1858 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001859 Error error("found no running/stepping or live stopped threads as target for interrupt");
Chaoren Line9547b82015-02-03 01:51:00 +00001860 if (log)
Chaoren Line9547b82015-02-03 01:51:00 +00001861 log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001862
Chaoren Line9547b82015-02-03 01:51:00 +00001863 return error;
1864 }
1865
1866 NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
1867
1868 if (log)
1869 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
1870 __FUNCTION__,
1871 GetID (),
1872 running_thread_sp ? "running" : "stopped",
1873 deferred_signal_thread_sp->GetID ());
1874
Pavel Labathed89c7f2015-05-06 12:22:37 +00001875 StopRunningThreads(deferred_signal_thread_sp->GetID());
Pavel Labath45f5cb32015-05-05 15:05:50 +00001876
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001877 return Error();
Chaoren Line9547b82015-02-03 01:51:00 +00001878}
1879
1880Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001881NativeProcessLinux::Kill ()
1882{
1883 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1884 if (log)
1885 log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
1886
1887 Error error;
1888
1889 switch (m_state)
1890 {
1891 case StateType::eStateInvalid:
1892 case StateType::eStateExited:
1893 case StateType::eStateCrashed:
1894 case StateType::eStateDetached:
1895 case StateType::eStateUnloaded:
1896 // Nothing to do - the process is already dead.
1897 if (log)
1898 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
1899 return error;
1900
1901 case StateType::eStateConnected:
1902 case StateType::eStateAttaching:
1903 case StateType::eStateLaunching:
1904 case StateType::eStateStopped:
1905 case StateType::eStateRunning:
1906 case StateType::eStateStepping:
1907 case StateType::eStateSuspended:
1908 // We can try to kill a process in these states.
1909 break;
1910 }
1911
1912 if (kill (GetID (), SIGKILL) != 0)
1913 {
1914 error.SetErrorToErrno ();
1915 return error;
1916 }
1917
1918 return error;
1919}
1920
1921static Error
1922ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
1923{
1924 memory_region_info.Clear();
1925
1926 StringExtractor line_extractor (maps_line.c_str ());
1927
1928 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode pathname
1929 // perms: rwxp (letter is present if set, '-' if not, final character is p=private, s=shared).
1930
1931 // Parse out the starting address
1932 lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
1933
1934 // Parse out hyphen separating start and end address from range.
1935 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
1936 return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
1937
1938 // Parse out the ending address
1939 lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
1940
1941 // Parse out the space after the address.
1942 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
1943 return Error ("malformed /proc/{pid}/maps entry, missing space after range");
1944
1945 // Save the range.
1946 memory_region_info.GetRange ().SetRangeBase (start_address);
1947 memory_region_info.GetRange ().SetRangeEnd (end_address);
1948
1949 // Parse out each permission entry.
1950 if (line_extractor.GetBytesLeft () < 4)
1951 return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
1952
1953 // Handle read permission.
1954 const char read_perm_char = line_extractor.GetChar ();
1955 if (read_perm_char == 'r')
1956 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
1957 else
1958 {
1959 assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
1960 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
1961 }
1962
1963 // Handle write permission.
1964 const char write_perm_char = line_extractor.GetChar ();
1965 if (write_perm_char == 'w')
1966 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
1967 else
1968 {
1969 assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
1970 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
1971 }
1972
1973 // Handle execute permission.
1974 const char exec_perm_char = line_extractor.GetChar ();
1975 if (exec_perm_char == 'x')
1976 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
1977 else
1978 {
1979 assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
1980 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
1981 }
1982
1983 return Error ();
1984}
1985
1986Error
1987NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
1988{
1989 // FIXME review that the final memory region returned extends to the end of the virtual address space,
1990 // with no perms if it is not mapped.
1991
1992 // Use an approach that reads memory regions from /proc/{pid}/maps.
1993 // Assume proc maps entries are in ascending order.
1994 // FIXME assert if we find differently.
Todd Fialaaf245d12014-06-30 21:05:18 +00001995
1996 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1997 Error error;
1998
1999 if (m_supports_mem_region == LazyBool::eLazyBoolNo)
2000 {
2001 // We're done.
2002 error.SetErrorString ("unsupported");
2003 return error;
2004 }
2005
2006 // If our cache is empty, pull the latest. There should always be at least one memory region
2007 // if memory region handling is supported.
2008 if (m_mem_region_cache.empty ())
2009 {
2010 error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
2011 [&] (const std::string &line) -> bool
2012 {
2013 MemoryRegionInfo info;
2014 const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
2015 if (parse_error.Success ())
2016 {
2017 m_mem_region_cache.push_back (info);
2018 return true;
2019 }
2020 else
2021 {
2022 if (log)
2023 log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
2024 return false;
2025 }
2026 });
2027
2028 // If we had an error, we'll mark unsupported.
2029 if (error.Fail ())
2030 {
2031 m_supports_mem_region = LazyBool::eLazyBoolNo;
2032 return error;
2033 }
2034 else if (m_mem_region_cache.empty ())
2035 {
2036 // No entries after attempting to read them. This shouldn't happen if /proc/{pid}/maps
2037 // is supported. Assume we don't support map entries via procfs.
2038 if (log)
2039 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
2040 m_supports_mem_region = LazyBool::eLazyBoolNo;
2041 error.SetErrorString ("not supported");
2042 return error;
2043 }
2044
2045 if (log)
2046 log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ());
2047
2048 // We support memory retrieval, remember that.
2049 m_supports_mem_region = LazyBool::eLazyBoolYes;
2050 }
2051 else
2052 {
2053 if (log)
2054 log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2055 }
2056
2057 lldb::addr_t prev_base_address = 0;
2058
2059 // FIXME start by finding the last region that is <= target address using binary search. Data is sorted.
2060 // There can be a ton of regions on pthreads apps with lots of threads.
2061 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
2062 {
2063 MemoryRegionInfo &proc_entry_info = *it;
2064
2065 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
2066 assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
2067 prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
2068
2069 // If the target address comes before this entry, indicate distance to next region.
2070 if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
2071 {
2072 range_info.GetRange ().SetRangeBase (load_addr);
2073 range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
2074 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2075 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2076 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2077
2078 return error;
2079 }
2080 else if (proc_entry_info.GetRange ().Contains (load_addr))
2081 {
2082 // The target address is within the memory region we're processing here.
2083 range_info = proc_entry_info;
2084 return error;
2085 }
2086
2087 // The target memory address comes somewhere after the region we just parsed.
2088 }
2089
Tamas Berghammer09839c32015-07-03 09:30:19 +00002090 // If we made it here, we didn't find an entry that contained the given address. Return the
2091 // load_addr as start and the amount of bytes betwwen load address and the end of the memory as
2092 // size.
2093 range_info.GetRange ().SetRangeBase (load_addr);
2094 switch (m_arch.GetAddressByteSize())
2095 {
2096 case 4:
2097 range_info.GetRange ().SetByteSize (0x100000000ull - load_addr);
2098 break;
2099 case 8:
2100 range_info.GetRange ().SetByteSize (0ull - load_addr);
2101 break;
2102 default:
2103 assert(false && "Unrecognized data byte size");
2104 break;
2105 }
2106 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2107 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2108 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
Todd Fialaaf245d12014-06-30 21:05:18 +00002109 return error;
2110}
2111
2112void
2113NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
2114{
2115 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2116 if (log)
2117 log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
2118
Todd Fialaaf245d12014-06-30 21:05:18 +00002119 if (log)
2120 log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2121 m_mem_region_cache.clear ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002122}
2123
2124Error
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002125NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr)
Todd Fialaaf245d12014-06-30 21:05:18 +00002126{
2127 // FIXME implementing this requires the equivalent of
2128 // InferiorCallPOSIX::InferiorCallMmap, which depends on
2129 // functional ThreadPlans working with Native*Protocol.
2130#if 1
2131 return Error ("not implemented yet");
2132#else
2133 addr = LLDB_INVALID_ADDRESS;
2134
2135 unsigned prot = 0;
2136 if (permissions & lldb::ePermissionsReadable)
2137 prot |= eMmapProtRead;
2138 if (permissions & lldb::ePermissionsWritable)
2139 prot |= eMmapProtWrite;
2140 if (permissions & lldb::ePermissionsExecutable)
2141 prot |= eMmapProtExec;
2142
2143 // TODO implement this directly in NativeProcessLinux
2144 // (and lift to NativeProcessPOSIX if/when that class is
2145 // refactored out).
2146 if (InferiorCallMmap(this, addr, 0, size, prot,
2147 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
2148 m_addr_to_mmap_size[addr] = size;
2149 return Error ();
2150 } else {
2151 addr = LLDB_INVALID_ADDRESS;
2152 return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
2153 }
2154#endif
2155}
2156
2157Error
2158NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
2159{
2160 // FIXME see comments in AllocateMemory - required lower-level
2161 // bits not in place yet (ThreadPlans)
2162 return Error ("not implemented");
2163}
2164
2165lldb::addr_t
2166NativeProcessLinux::GetSharedLibraryInfoAddress ()
2167{
2168#if 1
2169 // punt on this for now
2170 return LLDB_INVALID_ADDRESS;
2171#else
2172 // Return the image info address for the exe module
2173#if 1
2174 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2175
2176 ModuleSP module_sp;
2177 Error error = GetExeModuleSP (module_sp);
2178 if (error.Fail ())
2179 {
2180 if (log)
2181 log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ());
2182 return LLDB_INVALID_ADDRESS;
2183 }
2184
2185 if (module_sp == nullptr)
2186 {
2187 if (log)
2188 log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__);
2189 return LLDB_INVALID_ADDRESS;
2190 }
2191
2192 ObjectFileSP object_file_sp = module_sp->GetObjectFile ();
2193 if (object_file_sp == nullptr)
2194 {
2195 if (log)
2196 log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__);
2197 return LLDB_INVALID_ADDRESS;
2198 }
2199
2200 return obj_file_sp->GetImageInfoAddress();
2201#else
2202 Target *target = &GetTarget();
2203 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
2204 Address addr = obj_file->GetImageInfoAddress(target);
2205
2206 if (addr.IsValid())
2207 return addr.GetLoadAddress(target);
2208 return LLDB_INVALID_ADDRESS;
2209#endif
2210#endif // punt on this for now
2211}
2212
2213size_t
2214NativeProcessLinux::UpdateThreads ()
2215{
2216 // The NativeProcessLinux monitoring threads are always up to date
2217 // with respect to thread state and they keep the thread list
2218 // populated properly. All this method needs to do is return the
2219 // thread count.
Todd Fialaaf245d12014-06-30 21:05:18 +00002220 return m_threads.size ();
2221}
2222
2223bool
2224NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
2225{
2226 arch = m_arch;
2227 return true;
2228}
2229
2230Error
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002231NativeProcessLinux::GetSoftwareBreakpointPCOffset(uint32_t &actual_opcode_size)
Todd Fialaaf245d12014-06-30 21:05:18 +00002232{
2233 // FIXME put this behind a breakpoint protocol class that can be
2234 // set per architecture. Need ARM, MIPS support here.
2235 static const uint8_t g_i386_opcode [] = { 0xCC };
Ulrich Weigandbb00d0b2016-04-14 14:28:34 +00002236 static const uint8_t g_s390x_opcode[] = { 0x00, 0x01 };
Todd Fialaaf245d12014-06-30 21:05:18 +00002237
2238 switch (m_arch.GetMachine ())
2239 {
2240 case llvm::Triple::x86:
2241 case llvm::Triple::x86_64:
2242 actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
2243 return Error ();
2244
Ulrich Weigandbb00d0b2016-04-14 14:28:34 +00002245 case llvm::Triple::systemz:
2246 actual_opcode_size = static_cast<uint32_t> (sizeof(g_s390x_opcode));
2247 return Error ();
2248
Tamas Berghammerff7fd902015-07-03 12:51:30 +00002249 case llvm::Triple::arm:
2250 case llvm::Triple::aarch64:
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00002251 case llvm::Triple::mips64:
2252 case llvm::Triple::mips64el:
Sagar Thakurce815e42015-06-03 10:14:24 +00002253 case llvm::Triple::mips:
2254 case llvm::Triple::mipsel:
Tamas Berghammerff7fd902015-07-03 12:51:30 +00002255 // On these architectures the PC don't get updated for breakpoint hits
Jaydeep Patilc60c9452015-06-23 03:37:08 +00002256 actual_opcode_size = 0;
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00002257 return Error ();
2258
Todd Fialaaf245d12014-06-30 21:05:18 +00002259 default:
2260 assert(false && "CPU type not supported!");
2261 return Error ("CPU type not supported");
2262 }
2263}
2264
2265Error
2266NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
2267{
2268 if (hardware)
2269 return Error ("NativeProcessLinux does not support hardware breakpoints");
2270 else
2271 return SetSoftwareBreakpoint (addr, size);
2272}
2273
2274Error
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002275NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint,
2276 size_t &actual_opcode_size,
2277 const uint8_t *&trap_opcode_bytes)
Todd Fialaaf245d12014-06-30 21:05:18 +00002278{
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002279 // FIXME put this behind a breakpoint protocol class that can be set per
2280 // architecture. Need MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00002281 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Tamas Berghammerbe379e12016-02-16 15:14:36 +00002282 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
2283 // linux kernel does otherwise.
2284 static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 };
Todd Fialaaf245d12014-06-30 21:05:18 +00002285 static const uint8_t g_i386_opcode [] = { 0xCC };
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00002286 static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00002287 static const uint8_t g_mips64el_opcode[] = { 0x0d, 0x00, 0x00, 0x00 };
Ulrich Weigandbb00d0b2016-04-14 14:28:34 +00002288 static const uint8_t g_s390x_opcode[] = { 0x00, 0x01 };
Tamas Berghammerbe379e12016-02-16 15:14:36 +00002289 static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde };
Todd Fialaaf245d12014-06-30 21:05:18 +00002290
2291 switch (m_arch.GetMachine ())
2292 {
Todd Fiala2afc5962014-08-21 16:42:31 +00002293 case llvm::Triple::aarch64:
2294 trap_opcode_bytes = g_aarch64_opcode;
2295 actual_opcode_size = sizeof(g_aarch64_opcode);
2296 return Error ();
2297
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002298 case llvm::Triple::arm:
2299 switch (trap_opcode_size_hint)
2300 {
2301 case 2:
2302 trap_opcode_bytes = g_thumb_breakpoint_opcode;
2303 actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
2304 return Error ();
2305 case 4:
2306 trap_opcode_bytes = g_arm_breakpoint_opcode;
2307 actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
2308 return Error ();
2309 default:
2310 assert(false && "Unrecognised trap opcode size hint!");
2311 return Error ("Unrecognised trap opcode size hint!");
2312 }
2313
Todd Fialaaf245d12014-06-30 21:05:18 +00002314 case llvm::Triple::x86:
2315 case llvm::Triple::x86_64:
2316 trap_opcode_bytes = g_i386_opcode;
2317 actual_opcode_size = sizeof(g_i386_opcode);
2318 return Error ();
2319
Sagar Thakurce815e42015-06-03 10:14:24 +00002320 case llvm::Triple::mips:
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00002321 case llvm::Triple::mips64:
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00002322 trap_opcode_bytes = g_mips64_opcode;
2323 actual_opcode_size = sizeof(g_mips64_opcode);
2324 return Error ();
2325
Sagar Thakurce815e42015-06-03 10:14:24 +00002326 case llvm::Triple::mipsel:
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00002327 case llvm::Triple::mips64el:
2328 trap_opcode_bytes = g_mips64el_opcode;
2329 actual_opcode_size = sizeof(g_mips64el_opcode);
2330 return Error ();
2331
Ulrich Weigandbb00d0b2016-04-14 14:28:34 +00002332 case llvm::Triple::systemz:
2333 trap_opcode_bytes = g_s390x_opcode;
2334 actual_opcode_size = sizeof(g_s390x_opcode);
2335 return Error ();
2336
Todd Fialaaf245d12014-06-30 21:05:18 +00002337 default:
2338 assert(false && "CPU type not supported!");
2339 return Error ("CPU type not supported");
2340 }
2341}
2342
2343#if 0
2344ProcessMessage::CrashReason
2345NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
2346{
2347 ProcessMessage::CrashReason reason;
2348 assert(info->si_signo == SIGSEGV);
2349
2350 reason = ProcessMessage::eInvalidCrashReason;
2351
2352 switch (info->si_code)
2353 {
2354 default:
2355 assert(false && "unexpected si_code for SIGSEGV");
2356 break;
2357 case SI_KERNEL:
2358 // Linux will occasionally send spurious SI_KERNEL codes.
2359 // (this is poorly documented in sigaction)
2360 // One way to get this is via unaligned SIMD loads.
2361 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
2362 break;
2363 case SEGV_MAPERR:
2364 reason = ProcessMessage::eInvalidAddress;
2365 break;
2366 case SEGV_ACCERR:
2367 reason = ProcessMessage::ePrivilegedAddress;
2368 break;
2369 }
2370
2371 return reason;
2372}
2373#endif
2374
2375
2376#if 0
2377ProcessMessage::CrashReason
2378NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
2379{
2380 ProcessMessage::CrashReason reason;
2381 assert(info->si_signo == SIGILL);
2382
2383 reason = ProcessMessage::eInvalidCrashReason;
2384
2385 switch (info->si_code)
2386 {
2387 default:
2388 assert(false && "unexpected si_code for SIGILL");
2389 break;
2390 case ILL_ILLOPC:
2391 reason = ProcessMessage::eIllegalOpcode;
2392 break;
2393 case ILL_ILLOPN:
2394 reason = ProcessMessage::eIllegalOperand;
2395 break;
2396 case ILL_ILLADR:
2397 reason = ProcessMessage::eIllegalAddressingMode;
2398 break;
2399 case ILL_ILLTRP:
2400 reason = ProcessMessage::eIllegalTrap;
2401 break;
2402 case ILL_PRVOPC:
2403 reason = ProcessMessage::ePrivilegedOpcode;
2404 break;
2405 case ILL_PRVREG:
2406 reason = ProcessMessage::ePrivilegedRegister;
2407 break;
2408 case ILL_COPROC:
2409 reason = ProcessMessage::eCoprocessorError;
2410 break;
2411 case ILL_BADSTK:
2412 reason = ProcessMessage::eInternalStackError;
2413 break;
2414 }
2415
2416 return reason;
2417}
2418#endif
2419
2420#if 0
2421ProcessMessage::CrashReason
2422NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
2423{
2424 ProcessMessage::CrashReason reason;
2425 assert(info->si_signo == SIGFPE);
2426
2427 reason = ProcessMessage::eInvalidCrashReason;
2428
2429 switch (info->si_code)
2430 {
2431 default:
2432 assert(false && "unexpected si_code for SIGFPE");
2433 break;
2434 case FPE_INTDIV:
2435 reason = ProcessMessage::eIntegerDivideByZero;
2436 break;
2437 case FPE_INTOVF:
2438 reason = ProcessMessage::eIntegerOverflow;
2439 break;
2440 case FPE_FLTDIV:
2441 reason = ProcessMessage::eFloatDivideByZero;
2442 break;
2443 case FPE_FLTOVF:
2444 reason = ProcessMessage::eFloatOverflow;
2445 break;
2446 case FPE_FLTUND:
2447 reason = ProcessMessage::eFloatUnderflow;
2448 break;
2449 case FPE_FLTRES:
2450 reason = ProcessMessage::eFloatInexactResult;
2451 break;
2452 case FPE_FLTINV:
2453 reason = ProcessMessage::eFloatInvalidOperation;
2454 break;
2455 case FPE_FLTSUB:
2456 reason = ProcessMessage::eFloatSubscriptRange;
2457 break;
2458 }
2459
2460 return reason;
2461}
2462#endif
2463
2464#if 0
2465ProcessMessage::CrashReason
2466NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
2467{
2468 ProcessMessage::CrashReason reason;
2469 assert(info->si_signo == SIGBUS);
2470
2471 reason = ProcessMessage::eInvalidCrashReason;
2472
2473 switch (info->si_code)
2474 {
2475 default:
2476 assert(false && "unexpected si_code for SIGBUS");
2477 break;
2478 case BUS_ADRALN:
2479 reason = ProcessMessage::eIllegalAlignment;
2480 break;
2481 case BUS_ADRERR:
2482 reason = ProcessMessage::eIllegalAddress;
2483 break;
2484 case BUS_OBJERR:
2485 reason = ProcessMessage::eHardwareError;
2486 break;
2487 }
2488
2489 return reason;
2490}
2491#endif
2492
Todd Fialaaf245d12014-06-30 21:05:18 +00002493Error
Chaoren Lin26438d22015-05-05 17:50:53 +00002494NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
Todd Fialaaf245d12014-06-30 21:05:18 +00002495{
Pavel Labathdf7c6992015-06-17 18:38:49 +00002496 if (ProcessVmReadvSupported()) {
2497 // The process_vm_readv path is about 50 times faster than ptrace api. We want to use
2498 // this syscall if it is supported.
2499
2500 const ::pid_t pid = GetID();
2501
2502 struct iovec local_iov, remote_iov;
2503 local_iov.iov_base = buf;
2504 local_iov.iov_len = size;
2505 remote_iov.iov_base = reinterpret_cast<void *>(addr);
2506 remote_iov.iov_len = size;
2507
2508 bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
2509 const bool success = bytes_read == size;
2510
2511 Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2512 if (log)
2513 log->Printf ("NativeProcessLinux::%s using process_vm_readv to read %zd bytes from inferior address 0x%" PRIx64": %s",
2514 __FUNCTION__, size, addr, success ? "Success" : strerror(errno));
2515
2516 if (success)
2517 return Error();
2518 // else
2519 // the call failed for some reason, let's retry the read using ptrace api.
2520 }
2521
Pavel Labath19cbe962015-07-21 13:20:32 +00002522 unsigned char *dst = static_cast<unsigned char*>(buf);
2523 size_t remainder;
2524 long data;
2525
2526 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
2527 if (log)
2528 ProcessPOSIXLog::IncNestLevel();
2529 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
2530 log->Printf ("NativeProcessLinux::%s(%p, %p, %zd, _)", __FUNCTION__, (void*)addr, buf, size);
2531
2532 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
2533 {
2534 Error error = NativeProcessLinux::PtraceWrapper(PTRACE_PEEKDATA, GetID(), (void*)addr, nullptr, 0, &data);
2535 if (error.Fail())
2536 {
2537 if (log)
2538 ProcessPOSIXLog::DecNestLevel();
2539 return error;
2540 }
2541
2542 remainder = size - bytes_read;
2543 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
2544
2545 // Copy the data into our buffer
Mohit K. Bhakkadf6ef1872015-12-23 12:34:58 +00002546 memcpy(dst, &data, remainder);
Pavel Labath19cbe962015-07-21 13:20:32 +00002547
2548 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2549 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
2550 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2551 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
2552 {
2553 uintptr_t print_dst = 0;
2554 // Format bytes from data by moving into print_dst for log output
2555 for (unsigned i = 0; i < remainder; ++i)
2556 print_dst |= (((data >> i*8) & 0xFF) << i*8);
Pavel Labath79203992015-07-23 13:07:37 +00002557 log->Printf ("NativeProcessLinux::%s() [0x%" PRIx64 "]:0x%" PRIx64 " (0x%" PRIx64 ")",
2558 __FUNCTION__, addr, uint64_t(print_dst), uint64_t(data));
Pavel Labath19cbe962015-07-21 13:20:32 +00002559 }
2560 addr += k_ptrace_word_size;
2561 dst += k_ptrace_word_size;
2562 }
2563
2564 if (log)
2565 ProcessPOSIXLog::DecNestLevel();
2566 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00002567}
2568
2569Error
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002570NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
2571{
2572 Error error = ReadMemory(addr, buf, size, bytes_read);
2573 if (error.Fail()) return error;
2574 return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
2575}
2576
2577Error
2578NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written)
Todd Fialaaf245d12014-06-30 21:05:18 +00002579{
Pavel Labath19cbe962015-07-21 13:20:32 +00002580 const unsigned char *src = static_cast<const unsigned char*>(buf);
2581 size_t remainder;
2582 Error error;
2583
2584 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
2585 if (log)
2586 ProcessPOSIXLog::IncNestLevel();
2587 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
Pavel Labath79203992015-07-23 13:07:37 +00002588 log->Printf ("NativeProcessLinux::%s(0x%" PRIx64 ", %p, %zu)", __FUNCTION__, addr, buf, size);
Pavel Labath19cbe962015-07-21 13:20:32 +00002589
2590 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
2591 {
2592 remainder = size - bytes_written;
2593 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
2594
2595 if (remainder == k_ptrace_word_size)
2596 {
2597 unsigned long data = 0;
Mohit K. Bhakkadf6ef1872015-12-23 12:34:58 +00002598 memcpy(&data, src, k_ptrace_word_size);
Pavel Labath19cbe962015-07-21 13:20:32 +00002599
2600 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2601 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
2602 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2603 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
2604 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
2605 (void*)addr, *(const unsigned long*)src, data);
2606
2607 error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(), (void*)addr, (void*)data);
2608 if (error.Fail())
2609 {
2610 if (log)
2611 ProcessPOSIXLog::DecNestLevel();
2612 return error;
2613 }
2614 }
2615 else
2616 {
2617 unsigned char buff[8];
2618 size_t bytes_read;
2619 error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
2620 if (error.Fail())
2621 {
2622 if (log)
2623 ProcessPOSIXLog::DecNestLevel();
2624 return error;
2625 }
2626
2627 memcpy(buff, src, remainder);
2628
2629 size_t bytes_written_rec;
2630 error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
2631 if (error.Fail())
2632 {
2633 if (log)
2634 ProcessPOSIXLog::DecNestLevel();
2635 return error;
2636 }
2637
2638 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2639 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
2640 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2641 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
2642 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
2643 (void*)addr, *(const unsigned long*)src, *(unsigned long*)buff);
2644 }
2645
2646 addr += k_ptrace_word_size;
2647 src += k_ptrace_word_size;
2648 }
2649 if (log)
2650 ProcessPOSIXLog::DecNestLevel();
2651 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002652}
2653
Chaoren Lin97ccc292015-02-03 01:51:12 +00002654Error
Chaoren Lin97ccc292015-02-03 01:51:12 +00002655NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
Todd Fialaaf245d12014-06-30 21:05:18 +00002656{
Pavel Labath19cbe962015-07-21 13:20:32 +00002657 return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
Todd Fialaaf245d12014-06-30 21:05:18 +00002658}
2659
Chaoren Lin97ccc292015-02-03 01:51:12 +00002660Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002661NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
2662{
Pavel Labath19cbe962015-07-21 13:20:32 +00002663 return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
Todd Fialaaf245d12014-06-30 21:05:18 +00002664}
2665
Tamas Berghammerdb264a62015-03-31 09:52:22 +00002666Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002667NativeProcessLinux::Detach(lldb::tid_t tid)
2668{
Chaoren Lin97ccc292015-02-03 01:51:12 +00002669 if (tid == LLDB_INVALID_THREAD_ID)
2670 return Error();
2671
Pavel Labath19cbe962015-07-21 13:20:32 +00002672 return PtraceWrapper(PTRACE_DETACH, tid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002673}
2674
2675bool
Chaoren Lind3173f32015-05-29 19:52:29 +00002676NativeProcessLinux::DupDescriptor(const FileSpec &file_spec, int fd, int flags)
Todd Fialaaf245d12014-06-30 21:05:18 +00002677{
Chaoren Lind3173f32015-05-29 19:52:29 +00002678 int target_fd = open(file_spec.GetCString(), flags, 0666);
Todd Fialaaf245d12014-06-30 21:05:18 +00002679
2680 if (target_fd == -1)
2681 return false;
2682
Pavel Labath493c3a12015-02-04 10:36:57 +00002683 if (dup2(target_fd, fd) == -1)
2684 return false;
2685
2686 return (close(target_fd) == -1) ? false : true;
Todd Fialaaf245d12014-06-30 21:05:18 +00002687}
2688
Todd Fialaaf245d12014-06-30 21:05:18 +00002689bool
2690NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
2691{
2692 for (auto thread_sp : m_threads)
2693 {
2694 assert (thread_sp && "thread list should not contain NULL threads");
2695 if (thread_sp->GetID () == thread_id)
2696 {
2697 // We have this thread.
2698 return true;
2699 }
2700 }
2701
2702 // We don't have this thread.
2703 return false;
2704}
2705
Todd Fialaaf245d12014-06-30 21:05:18 +00002706bool
2707NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
2708{
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002709 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
2710
2711 if (log)
2712 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, thread_id);
2713
2714 bool found = false;
2715
Todd Fialaaf245d12014-06-30 21:05:18 +00002716 for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
2717 {
2718 if (*it && ((*it)->GetID () == thread_id))
2719 {
2720 m_threads.erase (it);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002721 found = true;
2722 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00002723 }
2724 }
2725
Pavel Labath0e1d7292015-08-20 09:06:12 +00002726 SignalIfAllThreadsStopped();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002727
2728 return found;
Todd Fialaaf245d12014-06-30 21:05:18 +00002729}
2730
Pavel Labathf9077782015-08-21 09:13:53 +00002731NativeThreadLinuxSP
Todd Fialaaf245d12014-06-30 21:05:18 +00002732NativeProcessLinux::AddThread (lldb::tid_t thread_id)
2733{
2734 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
2735
Todd Fialaaf245d12014-06-30 21:05:18 +00002736 if (log)
2737 {
2738 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
2739 __FUNCTION__,
2740 GetID (),
2741 thread_id);
2742 }
2743
2744 assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
2745
2746 // If this is the first thread, save it as the current thread
2747 if (m_threads.empty ())
2748 SetCurrentThreadID (thread_id);
2749
Pavel Labathf9077782015-08-21 09:13:53 +00002750 auto thread_sp = std::make_shared<NativeThreadLinux>(this, thread_id);
Todd Fialaaf245d12014-06-30 21:05:18 +00002751 m_threads.push_back (thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00002752 return thread_sp;
2753}
2754
Todd Fialaaf245d12014-06-30 21:05:18 +00002755Error
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002756NativeProcessLinux::FixupBreakpointPCAsNeeded(NativeThreadLinux &thread)
Todd Fialaaf245d12014-06-30 21:05:18 +00002757{
Todd Fiala75f47c32014-10-11 21:42:09 +00002758 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Todd Fialaaf245d12014-06-30 21:05:18 +00002759
2760 Error error;
2761
Todd Fialaaf245d12014-06-30 21:05:18 +00002762 // Find out the size of a breakpoint (might depend on where we are in the code).
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002763 NativeRegisterContextSP context_sp = thread.GetRegisterContext();
Todd Fialaaf245d12014-06-30 21:05:18 +00002764 if (!context_sp)
2765 {
2766 error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
2767 if (log)
2768 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
2769 return error;
2770 }
2771
2772 uint32_t breakpoint_size = 0;
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002773 error = GetSoftwareBreakpointPCOffset(breakpoint_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00002774 if (error.Fail ())
2775 {
2776 if (log)
2777 log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
2778 return error;
2779 }
2780 else
2781 {
2782 if (log)
2783 log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
2784 }
2785
2786 // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
Jaydeep Patilc60c9452015-06-23 03:37:08 +00002787 const lldb::addr_t initial_pc_addr = context_sp->GetPCfromBreakpointLocation ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002788 lldb::addr_t breakpoint_addr = initial_pc_addr;
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002789 if (breakpoint_size > 0)
Todd Fialaaf245d12014-06-30 21:05:18 +00002790 {
2791 // Do not allow breakpoint probe to wrap around.
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002792 if (breakpoint_addr >= breakpoint_size)
2793 breakpoint_addr -= breakpoint_size;
Todd Fialaaf245d12014-06-30 21:05:18 +00002794 }
2795
2796 // Check if we stopped because of a breakpoint.
2797 NativeBreakpointSP breakpoint_sp;
2798 error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
2799 if (!error.Success () || !breakpoint_sp)
2800 {
2801 // We didn't find one at a software probe location. Nothing to do.
2802 if (log)
2803 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
2804 return Error ();
2805 }
2806
2807 // If the breakpoint is not a software breakpoint, nothing to do.
2808 if (!breakpoint_sp->IsSoftwareBreakpoint ())
2809 {
2810 if (log)
2811 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
2812 return Error ();
2813 }
2814
2815 //
2816 // We have a software breakpoint and need to adjust the PC.
2817 //
2818
2819 // Sanity check.
2820 if (breakpoint_size == 0)
2821 {
2822 // Nothing to do! How did we get here?
2823 if (log)
2824 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);
2825 return Error ();
2826 }
2827
2828 // Change the program counter.
2829 if (log)
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002830 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 +00002831
2832 error = context_sp->SetPC (breakpoint_addr);
2833 if (error.Fail ())
2834 {
2835 if (log)
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002836 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 +00002837 return error;
2838 }
2839
2840 return error;
2841}
Chaoren Linfa03ad22015-02-03 01:50:42 +00002842
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00002843Error
2844NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec)
2845{
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00002846 FileSpec module_file_spec(module_path, true);
2847
Pavel Labath162fb8e2015-07-23 14:47:33 +00002848 bool found = false;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00002849 file_spec.Clear();
Pavel Labath162fb8e2015-07-23 14:47:33 +00002850 ProcFileReader::ProcessLineByLine(GetID(), "maps",
2851 [&] (const std::string &line)
2852 {
2853 SmallVector<StringRef, 16> columns;
2854 StringRef(line).split(columns, " ", -1, false);
2855 if (columns.size() < 6)
2856 return true; // continue searching
2857
2858 FileSpec this_file_spec(columns[5].str().c_str(), false);
2859 if (this_file_spec.GetFilename() != module_file_spec.GetFilename())
2860 return true; // continue searching
2861
2862 file_spec = this_file_spec;
2863 found = true;
2864 return false; // we are done
2865 });
2866
2867 if (! found)
2868 return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
2869 module_file_spec.GetFilename().AsCString(), GetID());
2870
2871 return Error();
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00002872}
Pavel Labathc0765592015-05-06 10:46:34 +00002873
Pavel Labath5eb721e2015-05-07 08:30:31 +00002874Error
Tamas Berghammer783bfc82015-06-18 20:43:56 +00002875NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef& file_name, lldb::addr_t& load_addr)
2876{
2877 load_addr = LLDB_INVALID_ADDRESS;
2878 Error error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
2879 [&] (const std::string &line) -> bool
2880 {
2881 StringRef maps_row(line);
2882
2883 SmallVector<StringRef, 16> maps_columns;
2884 maps_row.split(maps_columns, StringRef(" "), -1, false);
2885
2886 if (maps_columns.size() < 6)
2887 {
2888 // Return true to continue reading the proc file
2889 return true;
2890 }
2891
2892 if (maps_columns[5] == file_name)
2893 {
2894 StringExtractor addr_extractor(maps_columns[0].str().c_str());
2895 load_addr = addr_extractor.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2896
2897 // Return false to stop reading the proc file further
2898 return false;
2899 }
2900
2901 // Return true to continue reading the proc file
2902 return true;
2903 });
2904 return error;
2905}
2906
Pavel Labathf9077782015-08-21 09:13:53 +00002907NativeThreadLinuxSP
2908NativeProcessLinux::GetThreadByID(lldb::tid_t tid)
2909{
2910 return std::static_pointer_cast<NativeThreadLinux>(NativeProcessProtocol::GetThreadByID(tid));
2911}
2912
Tamas Berghammer783bfc82015-06-18 20:43:56 +00002913Error
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002914NativeProcessLinux::ResumeThread(NativeThreadLinux &thread, lldb::StateType state, int signo)
Pavel Labathc0765592015-05-06 10:46:34 +00002915{
Pavel Labath5eb721e2015-05-07 08:30:31 +00002916 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002917
2918 if (log)
Pavel Labath0e1d7292015-08-20 09:06:12 +00002919 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")",
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002920 __FUNCTION__, thread.GetID());
Pavel Labath5eb721e2015-05-07 08:30:31 +00002921
Pavel Labathc0765592015-05-06 10:46:34 +00002922 // Before we do the resume below, first check if we have a pending
Pavel Labath108c3252015-05-12 09:03:18 +00002923 // stop notification that is currently waiting for
Pavel Labath0e1d7292015-08-20 09:06:12 +00002924 // all threads to stop. This is potentially a buggy situation since
Pavel Labathc0765592015-05-06 10:46:34 +00002925 // we're ostensibly waiting for threads to stop before we send out the
2926 // pending notification, and here we are resuming one before we send
2927 // out the pending stop notification.
Pavel Labath0e1d7292015-08-20 09:06:12 +00002928 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID && log)
Pavel Labathc0765592015-05-06 10:46:34 +00002929 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002930 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 +00002931 }
2932
2933 // Request a resume. We expect this to be synchronous and the system
2934 // to reflect it is running after this completes.
Pavel Labath0e1d7292015-08-20 09:06:12 +00002935 switch (state)
Pavel Labathc0765592015-05-06 10:46:34 +00002936 {
Pavel Labath0e1d7292015-08-20 09:06:12 +00002937 case eStateRunning:
2938 {
Pavel Labath605b51b2016-02-23 13:56:30 +00002939 const auto resume_result = thread.Resume(signo);
Pavel Labath0e1d7292015-08-20 09:06:12 +00002940 if (resume_result.Success())
2941 SetState(eStateRunning, true);
2942 return resume_result;
Pavel Labathc0765592015-05-06 10:46:34 +00002943 }
Pavel Labath0e1d7292015-08-20 09:06:12 +00002944 case eStateStepping:
2945 {
Pavel Labath605b51b2016-02-23 13:56:30 +00002946 const auto step_result = thread.SingleStep(signo);
Pavel Labath0e1d7292015-08-20 09:06:12 +00002947 if (step_result.Success())
2948 SetState(eStateRunning, true);
2949 return step_result;
2950 }
2951 default:
2952 if (log)
2953 log->Printf("NativeProcessLinux::%s Unhandled state %s.",
2954 __FUNCTION__, StateAsCString(state));
2955 llvm_unreachable("Unhandled state for resume");
2956 }
Pavel Labathc0765592015-05-06 10:46:34 +00002957}
2958
2959//===----------------------------------------------------------------------===//
2960
2961void
Pavel Labath337f3eb2015-05-08 08:57:45 +00002962NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid)
Pavel Labathc0765592015-05-06 10:46:34 +00002963{
Pavel Labath5eb721e2015-05-07 08:30:31 +00002964 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00002965
Pavel Labath5eb721e2015-05-07 08:30:31 +00002966 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00002967 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00002968 log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ")",
Pavel Labathc0765592015-05-06 10:46:34 +00002969 __FUNCTION__, triggering_tid);
2970 }
2971
Pavel Labath0e1d7292015-08-20 09:06:12 +00002972 m_pending_notification_tid = triggering_tid;
2973
2974 // Request a stop for all the thread stops that need to be stopped
2975 // and are not already known to be stopped.
2976 for (const auto &thread_sp: m_threads)
2977 {
2978 if (StateIsRunningState(thread_sp->GetState()))
2979 static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
2980 }
2981
2982 SignalIfAllThreadsStopped();
Pavel Labathc0765592015-05-06 10:46:34 +00002983
Pavel Labath5eb721e2015-05-07 08:30:31 +00002984 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00002985 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00002986 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00002987 }
2988}
2989
2990void
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00002991NativeProcessLinux::SignalIfAllThreadsStopped()
Pavel Labathc0765592015-05-06 10:46:34 +00002992{
Pavel Labath0e1d7292015-08-20 09:06:12 +00002993 if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
2994 return; // No pending notification. Nothing to do.
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00002995
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00002996 for (const auto &thread_sp: m_threads)
Pavel Labathc0765592015-05-06 10:46:34 +00002997 {
Pavel Labath0e1d7292015-08-20 09:06:12 +00002998 if (StateIsRunningState(thread_sp->GetState()))
2999 return; // Some threads are still running. Don't signal yet.
Pavel Labathc0765592015-05-06 10:46:34 +00003000 }
3001
Pavel Labath0e1d7292015-08-20 09:06:12 +00003002 // We have a pending notification and all threads have stopped.
3003 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
Pavel Labathc0765592015-05-06 10:46:34 +00003004
Pavel Labath0e1d7292015-08-20 09:06:12 +00003005 // Clear any temporary breakpoints we used to implement software single stepping.
3006 for (const auto &thread_info: m_threads_stepping_with_breakpoint)
Pavel Labathc0765592015-05-06 10:46:34 +00003007 {
Pavel Labath0e1d7292015-08-20 09:06:12 +00003008 Error error = RemoveBreakpoint (thread_info.second);
3009 if (error.Fail())
3010 if (log)
3011 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " remove stepping breakpoint: %s",
3012 __FUNCTION__, thread_info.first, error.AsCString());
Pavel Labathc0765592015-05-06 10:46:34 +00003013 }
Pavel Labath0e1d7292015-08-20 09:06:12 +00003014 m_threads_stepping_with_breakpoint.clear();
Pavel Labathc0765592015-05-06 10:46:34 +00003015
Pavel Labath0e1d7292015-08-20 09:06:12 +00003016 // Notify the delegate about the stop
3017 SetCurrentThreadID(m_pending_notification_tid);
3018 SetState(StateType::eStateStopped, true);
3019 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
Pavel Labathc0765592015-05-06 10:46:34 +00003020}
3021
3022void
Pavel Labathf9077782015-08-21 09:13:53 +00003023NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread)
Pavel Labathc0765592015-05-06 10:46:34 +00003024{
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003025 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3026
3027 if (log)
Pavel Labathf9077782015-08-21 09:13:53 +00003028 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, thread.GetID());
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003029
Pavel Labathf9077782015-08-21 09:13:53 +00003030 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID && StateIsRunningState(thread.GetState()))
Pavel Labathc0765592015-05-06 10:46:34 +00003031 {
3032 // We will need to wait for this new thread to stop as well before firing the
3033 // notification.
Pavel Labathf9077782015-08-21 09:13:53 +00003034 thread.RequestStop();
Pavel Labathc0765592015-05-06 10:46:34 +00003035 }
3036}
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003037
Pavel Labath19cbe962015-07-21 13:20:32 +00003038void
3039NativeProcessLinux::SigchldHandler()
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003040{
Pavel Labath19cbe962015-07-21 13:20:32 +00003041 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3042 // Process all pending waitpid notifications.
3043 while (true)
3044 {
3045 int status = -1;
3046 ::pid_t wait_pid = waitpid(-1, &status, __WALL | __WNOTHREAD | WNOHANG);
3047
3048 if (wait_pid == 0)
3049 break; // We are done.
3050
3051 if (wait_pid == -1)
3052 {
3053 if (errno == EINTR)
3054 continue;
3055
3056 Error error(errno, eErrorTypePOSIX);
3057 if (log)
3058 log->Printf("NativeProcessLinux::%s waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG) failed: %s",
3059 __FUNCTION__, error.AsCString());
3060 break;
3061 }
3062
3063 bool exited = false;
3064 int signal = 0;
3065 int exit_status = 0;
3066 const char *status_cstr = nullptr;
3067 if (WIFSTOPPED(status))
3068 {
3069 signal = WSTOPSIG(status);
3070 status_cstr = "STOPPED";
3071 }
3072 else if (WIFEXITED(status))
3073 {
3074 exit_status = WEXITSTATUS(status);
3075 status_cstr = "EXITED";
3076 exited = true;
3077 }
3078 else if (WIFSIGNALED(status))
3079 {
3080 signal = WTERMSIG(status);
3081 status_cstr = "SIGNALED";
Omair Javaiddee4a862015-08-19 10:44:16 +00003082 if (wait_pid == static_cast< ::pid_t>(GetID())) {
Pavel Labath19cbe962015-07-21 13:20:32 +00003083 exited = true;
3084 exit_status = -1;
3085 }
3086 }
3087 else
3088 status_cstr = "(\?\?\?)";
3089
3090 if (log)
3091 log->Printf("NativeProcessLinux::%s: waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG)"
3092 "=> pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
3093 __FUNCTION__, wait_pid, status, status_cstr, signal, exit_status);
3094
3095 MonitorCallback (wait_pid, exited, signal, exit_status);
3096 }
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003097}
3098
3099// Wrapper for ptrace to catch errors and log calls.
3100// 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 +00003101Error
3102NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, long *result)
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003103{
Pavel Labath4a9babb2015-06-30 17:04:49 +00003104 Error error;
3105 long int ret;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003106
3107 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
3108
3109 PtraceDisplayBytes(req, data, data_size);
3110
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003111 errno = 0;
3112 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Pavel Labath4a9babb2015-06-30 17:04:49 +00003113 ret = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003114 else
Pavel Labath4a9babb2015-06-30 17:04:49 +00003115 ret = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003116
Pavel Labath4a9babb2015-06-30 17:04:49 +00003117 if (ret == -1)
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003118 error.SetErrorToErrno();
3119
Pavel Labath4a9babb2015-06-30 17:04:49 +00003120 if (result)
3121 *result = ret;
3122
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003123 if (log)
Pavel Labath4a9babb2015-06-30 17:04:49 +00003124 log->Printf("ptrace(%d, %" PRIu64 ", %p, %p, %zu)=%lX", req, pid, addr, data, data_size, ret);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003125
3126 PtraceDisplayBytes(req, data, data_size);
3127
3128 if (log && error.GetError() != 0)
3129 {
3130 const char* str;
3131 switch (error.GetError())
3132 {
3133 case ESRCH: str = "ESRCH"; break;
3134 case EINVAL: str = "EINVAL"; break;
3135 case EBUSY: str = "EBUSY"; break;
3136 case EPERM: str = "EPERM"; break;
3137 default: str = error.AsCString();
3138 }
3139 log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
3140 }
3141
Pavel Labath4a9babb2015-06-30 17:04:49 +00003142 return error;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003143}