blob: 15498eab838add44f862b47a41f8c36a3c281137 [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_mem_region_cache_mutex(),
431 m_pending_notification_tid(LLDB_INVALID_THREAD_ID)
Todd Fialaaf245d12014-06-30 21:05:18 +0000432{
433}
434
Todd Fialaaf245d12014-06-30 21:05:18 +0000435void
436NativeProcessLinux::LaunchInferior (
Pavel Labath19cbe962015-07-21 13:20:32 +0000437 MainLoop &mainloop,
Todd Fialaaf245d12014-06-30 21:05:18 +0000438 Module *module,
439 const char *argv[],
440 const char *envp[],
Chaoren Lind3173f32015-05-29 19:52:29 +0000441 const FileSpec &stdin_file_spec,
442 const FileSpec &stdout_file_spec,
443 const FileSpec &stderr_file_spec,
444 const FileSpec &working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000445 const ProcessLaunchInfo &launch_info,
446 Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000447{
Pavel Labath19cbe962015-07-21 13:20:32 +0000448 m_sigchld_handle = mainloop.RegisterSignal(SIGCHLD,
449 [this] (MainLoopBase &) { SigchldHandler(); }, error);
450 if (! m_sigchld_handle)
451 return;
452
Todd Fialaaf245d12014-06-30 21:05:18 +0000453 if (module)
454 m_arch = module->GetArchitecture ();
455
Chaoren Linfa03ad22015-02-03 01:50:42 +0000456 SetState (eStateLaunching);
Todd Fialaaf245d12014-06-30 21:05:18 +0000457
458 std::unique_ptr<LaunchArgs> args(
Chaoren Lind3173f32015-05-29 19:52:29 +0000459 new LaunchArgs(module, argv, envp,
460 stdin_file_spec,
461 stdout_file_spec,
462 stderr_file_spec,
463 working_dir,
464 launch_info));
Todd Fialaaf245d12014-06-30 21:05:18 +0000465
Pavel Labath19cbe962015-07-21 13:20:32 +0000466 Launch(args.get(), error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000467}
468
469void
Pavel Labath19cbe962015-07-21 13:20:32 +0000470NativeProcessLinux::AttachToInferior (MainLoop &mainloop, lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000471{
472 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
473 if (log)
474 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
475
Pavel Labath19cbe962015-07-21 13:20:32 +0000476 m_sigchld_handle = mainloop.RegisterSignal(SIGCHLD,
477 [this] (MainLoopBase &) { SigchldHandler(); }, error);
478 if (! m_sigchld_handle)
479 return;
480
Todd Fialaaf245d12014-06-30 21:05:18 +0000481 // We can use the Host for everything except the ResolveExecutable portion.
Greg Clayton615eb7e2014-09-19 20:11:50 +0000482 PlatformSP platform_sp = Platform::GetHostPlatform ();
Todd Fialaaf245d12014-06-30 21:05:18 +0000483 if (!platform_sp)
484 {
485 if (log)
486 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): no default platform set", __FUNCTION__, pid);
487 error.SetErrorString ("no default platform available");
Shawn Best50d60be2014-11-11 00:28:52 +0000488 return;
Todd Fialaaf245d12014-06-30 21:05:18 +0000489 }
490
491 // Gather info about the process.
492 ProcessInstanceInfo process_info;
Shawn Best50d60be2014-11-11 00:28:52 +0000493 if (!platform_sp->GetProcessInfo (pid, process_info))
494 {
495 if (log)
496 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): failed to get process info", __FUNCTION__, pid);
497 error.SetErrorString ("failed to get process info");
498 return;
499 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000500
501 // Resolve the executable module
502 ModuleSP exe_module_sp;
503 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
Chaoren Line56f6dc2015-03-01 04:31:16 +0000504 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Oleksiy Vyalov6edef202014-11-17 22:16:42 +0000505 error = platform_sp->ResolveExecutable(exe_module_spec, exe_module_sp,
Zachary Turner13b18262014-08-20 16:42:51 +0000506 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
Todd Fialaaf245d12014-06-30 21:05:18 +0000507 if (!error.Success())
508 return;
509
510 // Set the architecture to the exe architecture.
511 m_arch = exe_module_sp->GetArchitecture();
512 if (log)
513 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
514
515 m_pid = pid;
516 SetState(eStateAttaching);
517
Pavel Labath19cbe962015-07-21 13:20:32 +0000518 Attach(pid, error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000519}
520
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000521::pid_t
522NativeProcessLinux::Launch(LaunchArgs *args, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000523{
Todd Fiala0bce1b62014-08-17 00:10:50 +0000524 assert (args && "null args");
Todd Fialaaf245d12014-06-30 21:05:18 +0000525
526 const char **argv = args->m_argv;
527 const char **envp = args->m_envp;
Chaoren Lind3173f32015-05-29 19:52:29 +0000528 const FileSpec working_dir = args->m_working_dir;
Todd Fialaaf245d12014-06-30 21:05:18 +0000529
530 lldb_utility::PseudoTerminal terminal;
531 const size_t err_len = 1024;
532 char err_str[err_len];
533 lldb::pid_t pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000534
535 // Propagate the environment if one is not supplied.
536 if (envp == NULL || envp[0] == NULL)
537 envp = const_cast<const char **>(environ);
538
539 if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
540 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000541 error.SetErrorToGenericError();
542 error.SetErrorStringWithFormat("Process fork failed: %s", err_str);
543 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000544 }
545
546 // Recognized child exit status codes.
547 enum {
548 ePtraceFailed = 1,
549 eDupStdinFailed,
550 eDupStdoutFailed,
551 eDupStderrFailed,
552 eChdirFailed,
553 eExecFailed,
Pavel Labath78856472015-08-19 13:47:57 +0000554 eSetGidFailed,
555 eSetSigMaskFailed
Todd Fialaaf245d12014-06-30 21:05:18 +0000556 };
557
558 // Child process.
559 if (pid == 0)
560 {
Pavel Labathd2c4c9b2015-08-18 08:23:35 +0000561 // First, make sure we disable all logging. If we are logging to stdout, our logs can be
562 // mistaken for inferior output.
563 Log::DisableAllLogChannels(nullptr);
Todd Fiala75f47c32014-10-11 21:42:09 +0000564 // FIXME consider opening a pipe between parent/child and have this forked child
Pavel Labathd2c4c9b2015-08-18 08:23:35 +0000565 // send log info to parent re: launch status.
Todd Fialaaf245d12014-06-30 21:05:18 +0000566
Todd Fiala75f47c32014-10-11 21:42:09 +0000567 // Start tracing this child that is about to exec.
Pavel Labath4a9babb2015-06-30 17:04:49 +0000568 error = PtraceWrapper(PTRACE_TRACEME, 0);
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000569 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000570 exit(ePtraceFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +0000571
Pavel Labath493c3a12015-02-04 10:36:57 +0000572 // terminal has already dupped the tty descriptors to stdin/out/err.
573 // This closes original fd from which they were copied (and avoids
574 // leaking descriptors to the debugged process.
575 terminal.CloseSlaveFileDescriptor();
576
Todd Fialaaf245d12014-06-30 21:05:18 +0000577 // Do not inherit setgid powers.
Todd Fialaaf245d12014-06-30 21:05:18 +0000578 if (setgid(getgid()) != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +0000579 exit(eSetGidFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +0000580
581 // Attempt to have our own process group.
Todd Fialaaf245d12014-06-30 21:05:18 +0000582 if (setpgid(0, 0) != 0)
583 {
Todd Fiala75f47c32014-10-11 21:42:09 +0000584 // FIXME log that this failed. This is common.
Todd Fialaaf245d12014-06-30 21:05:18 +0000585 // Don't allow this to prevent an inferior exec.
586 }
587
588 // Dup file descriptors if needed.
Chaoren Lind3173f32015-05-29 19:52:29 +0000589 if (args->m_stdin_file_spec)
590 if (!DupDescriptor(args->m_stdin_file_spec, STDIN_FILENO, O_RDONLY))
Todd Fialaaf245d12014-06-30 21:05:18 +0000591 exit(eDupStdinFailed);
592
Chaoren Lind3173f32015-05-29 19:52:29 +0000593 if (args->m_stdout_file_spec)
594 if (!DupDescriptor(args->m_stdout_file_spec, STDOUT_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +0000595 exit(eDupStdoutFailed);
596
Chaoren Lind3173f32015-05-29 19:52:29 +0000597 if (args->m_stderr_file_spec)
598 if (!DupDescriptor(args->m_stderr_file_spec, STDERR_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +0000599 exit(eDupStderrFailed);
600
Chaoren Lin9cf4f2c2015-04-23 18:28:04 +0000601 // Close everything besides stdin, stdout, and stderr that has no file
602 // action to avoid leaking
603 for (int fd = 3; fd < sysconf(_SC_OPEN_MAX); ++fd)
604 if (!args->m_launch_info.GetFileActionForFD(fd))
605 close(fd);
606
Todd Fialaaf245d12014-06-30 21:05:18 +0000607 // Change working directory
Chaoren Lind3173f32015-05-29 19:52:29 +0000608 if (working_dir && 0 != ::chdir(working_dir.GetCString()))
Todd Fialaaf245d12014-06-30 21:05:18 +0000609 exit(eChdirFailed);
610
Todd Fiala0bce1b62014-08-17 00:10:50 +0000611 // Disable ASLR if requested.
612 if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR))
613 {
614 const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
615 if (old_personality == -1)
616 {
Todd Fiala75f47c32014-10-11 21:42:09 +0000617 // Can't retrieve Linux personality. Cannot disable ASLR.
Todd Fiala0bce1b62014-08-17 00:10:50 +0000618 }
619 else
620 {
621 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality);
622 if (new_personality == -1)
623 {
Todd Fiala75f47c32014-10-11 21:42:09 +0000624 // Disabling ASLR failed.
Todd Fiala0bce1b62014-08-17 00:10:50 +0000625 }
626 else
627 {
Todd Fiala75f47c32014-10-11 21:42:09 +0000628 // Disabling ASLR succeeded.
Todd Fiala0bce1b62014-08-17 00:10:50 +0000629 }
630 }
631 }
632
Pavel Labath78856472015-08-19 13:47:57 +0000633 // Clear the signal mask to prevent the child from being affected by
634 // any masking done by the parent.
635 sigset_t set;
636 if (sigemptyset(&set) != 0 || pthread_sigmask(SIG_SETMASK, &set, nullptr) != 0)
637 exit(eSetSigMaskFailed);
638
Todd Fiala75f47c32014-10-11 21:42:09 +0000639 // Execute. We should never return...
Todd Fialaaf245d12014-06-30 21:05:18 +0000640 execve(argv[0],
641 const_cast<char *const *>(argv),
642 const_cast<char *const *>(envp));
Todd Fiala75f47c32014-10-11 21:42:09 +0000643
644 // ...unless exec fails. In which case we definitely need to end the child here.
Todd Fialaaf245d12014-06-30 21:05:18 +0000645 exit(eExecFailed);
646 }
647
Todd Fiala75f47c32014-10-11 21:42:09 +0000648 //
649 // This is the parent code here.
650 //
651 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
652
Todd Fialaaf245d12014-06-30 21:05:18 +0000653 // Wait for the child process to trap on its call to execve.
654 ::pid_t wpid;
655 int status;
656 if ((wpid = waitpid(pid, &status, 0)) < 0)
657 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000658 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +0000659 if (log)
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000660 log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s",
661 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000662
663 // Mark the inferior as invalid.
664 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000665 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000666
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000667 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000668 }
669 else if (WIFEXITED(status))
670 {
671 // open, dup or execve likely failed for some reason.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000672 error.SetErrorToGenericError();
Todd Fialaaf245d12014-06-30 21:05:18 +0000673 switch (WEXITSTATUS(status))
674 {
675 case ePtraceFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000676 error.SetErrorString("Child ptrace failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000677 break;
678 case eDupStdinFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000679 error.SetErrorString("Child open stdin failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000680 break;
681 case eDupStdoutFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000682 error.SetErrorString("Child open stdout failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000683 break;
684 case eDupStderrFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000685 error.SetErrorString("Child open stderr failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000686 break;
687 case eChdirFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000688 error.SetErrorString("Child failed to set working directory.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000689 break;
690 case eExecFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000691 error.SetErrorString("Child exec failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000692 break;
693 case eSetGidFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000694 error.SetErrorString("Child setgid failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000695 break;
Pavel Labath78856472015-08-19 13:47:57 +0000696 case eSetSigMaskFailed:
697 error.SetErrorString("Child failed to set signal mask.");
698 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000699 default:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000700 error.SetErrorString("Child returned unknown exit status.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000701 break;
702 }
703
704 if (log)
705 {
706 log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
707 __FUNCTION__,
708 WEXITSTATUS(status));
709 }
710
711 // Mark the inferior as invalid.
712 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000713 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000714
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000715 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000716 }
Todd Fiala202ecd22014-07-10 04:39:13 +0000717 assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
Todd Fialaaf245d12014-06-30 21:05:18 +0000718 "Could not sync with inferior process.");
719
720 if (log)
721 log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
722
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000723 error = SetDefaultPtraceOpts(pid);
724 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000725 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000726 if (log)
727 log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000728 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000729
730 // Mark the inferior as invalid.
731 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000732 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000733
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000734 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000735 }
736
737 // Release the master terminal descriptor and pass it off to the
738 // NativeProcessLinux instance. Similarly stash the inferior pid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000739 m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
740 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000741
742 // Set the terminal fd to be in non blocking mode (it simplifies the
743 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
744 // descriptor to read from).
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000745 error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
746 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000747 {
748 if (log)
749 log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000750 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000751
752 // Mark the inferior as invalid.
753 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000754 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000755
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000756 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000757 }
758
759 if (log)
760 log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
761
Pavel Labathf9077782015-08-21 09:13:53 +0000762 NativeThreadLinuxSP thread_sp = AddThread(pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000763 assert (thread_sp && "AddThread() returned a nullptr thread");
Pavel Labathf9077782015-08-21 09:13:53 +0000764 thread_sp->SetStoppedBySignal(SIGSTOP);
765 ThreadWasCreated(*thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +0000766
767 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000768 SetCurrentThreadID (thread_sp->GetID ());
769 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +0000770
Todd Fialaaf245d12014-06-30 21:05:18 +0000771 if (log)
772 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000773 if (error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +0000774 {
775 log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
776 }
777 else
778 {
779 log->Printf ("NativeProcessLinux::%s inferior launching failed: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000780 __FUNCTION__, error.AsCString ());
781 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000782 }
783 }
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000784 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000785}
786
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000787::pid_t
788NativeProcessLinux::Attach(lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000789{
Todd Fialaaf245d12014-06-30 21:05:18 +0000790 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
791
792 // Use a map to keep track of the threads which we have attached/need to attach.
793 Host::TidMap tids_to_attach;
794 if (pid <= 1)
795 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000796 error.SetErrorToGenericError();
797 error.SetErrorString("Attaching to process 1 is not allowed.");
798 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000799 }
800
801 while (Host::FindProcessThreads(pid, tids_to_attach))
802 {
803 for (Host::TidMap::iterator it = tids_to_attach.begin();
804 it != tids_to_attach.end();)
805 {
806 if (it->second == false)
807 {
808 lldb::tid_t tid = it->first;
809
810 // Attach to the requested process.
811 // An attach will cause the thread to stop with a SIGSTOP.
Pavel Labath4a9babb2015-06-30 17:04:49 +0000812 error = PtraceWrapper(PTRACE_ATTACH, tid);
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000813 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000814 {
815 // No such thread. The thread may have exited.
816 // More error handling may be needed.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000817 if (error.GetError() == ESRCH)
Todd Fialaaf245d12014-06-30 21:05:18 +0000818 {
819 it = tids_to_attach.erase(it);
820 continue;
821 }
822 else
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000823 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000824 }
825
826 int status;
827 // Need to use __WALL otherwise we receive an error with errno=ECHLD
828 // At this point we should have a thread stopped if waitpid succeeds.
829 if ((status = waitpid(tid, NULL, __WALL)) < 0)
830 {
831 // No such thread. The thread may have exited.
832 // More error handling may be needed.
833 if (errno == ESRCH)
834 {
835 it = tids_to_attach.erase(it);
836 continue;
837 }
838 else
839 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000840 error.SetErrorToErrno();
841 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000842 }
843 }
844
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000845 error = SetDefaultPtraceOpts(tid);
846 if (error.Fail())
847 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000848
849 if (log)
850 log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
851
852 it->second = true;
853
854 // Create the thread, mark it as stopped.
Pavel Labathf9077782015-08-21 09:13:53 +0000855 NativeThreadLinuxSP thread_sp (AddThread(static_cast<lldb::tid_t>(tid)));
Todd Fialaaf245d12014-06-30 21:05:18 +0000856 assert (thread_sp && "AddThread() returned a nullptr");
Chaoren Linfa03ad22015-02-03 01:50:42 +0000857
858 // This will notify this is a new thread and tell the system it is stopped.
Pavel Labathf9077782015-08-21 09:13:53 +0000859 thread_sp->SetStoppedBySignal(SIGSTOP);
860 ThreadWasCreated(*thread_sp);
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000861 SetCurrentThreadID (thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000862 }
863
864 // move the loop forward
865 ++it;
866 }
867 }
868
869 if (tids_to_attach.size() > 0)
870 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000871 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000872 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000873 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +0000874 }
875 else
876 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000877 error.SetErrorToGenericError();
878 error.SetErrorString("No such process.");
879 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000880 }
881
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000882 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000883}
884
Chaoren Lin97ccc292015-02-03 01:51:12 +0000885Error
Todd Fialaaf245d12014-06-30 21:05:18 +0000886NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
887{
888 long ptrace_opts = 0;
889
890 // Have the child raise an event on exit. This is used to keep the child in
891 // limbo until it is destroyed.
892 ptrace_opts |= PTRACE_O_TRACEEXIT;
893
894 // Have the tracer trace threads which spawn in the inferior process.
895 // TODO: if we want to support tracing the inferiors' child, add the
896 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
897 ptrace_opts |= PTRACE_O_TRACECLONE;
898
899 // Have the tracer notify us before execve returns
900 // (needed to disable legacy SIGTRAP generation)
901 ptrace_opts |= PTRACE_O_TRACEEXEC;
902
Pavel Labath4a9babb2015-06-30 17:04:49 +0000903 return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts);
Todd Fialaaf245d12014-06-30 21:05:18 +0000904}
905
906static ExitType convert_pid_status_to_exit_type (int status)
907{
908 if (WIFEXITED (status))
909 return ExitType::eExitTypeExit;
910 else if (WIFSIGNALED (status))
911 return ExitType::eExitTypeSignal;
912 else if (WIFSTOPPED (status))
913 return ExitType::eExitTypeStop;
914 else
915 {
916 // We don't know what this is.
917 return ExitType::eExitTypeInvalid;
918 }
919}
920
921static int convert_pid_status_to_return_code (int status)
922{
923 if (WIFEXITED (status))
924 return WEXITSTATUS (status);
925 else if (WIFSIGNALED (status))
926 return WTERMSIG (status);
927 else if (WIFSTOPPED (status))
928 return WSTOPSIG (status);
929 else
930 {
931 // We don't know what this is.
932 return ExitType::eExitTypeInvalid;
933 }
934}
935
Pavel Labath1107b5a2015-04-17 14:07:49 +0000936// Handles all waitpid events from the inferior process.
937void
938NativeProcessLinux::MonitorCallback(lldb::pid_t pid,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000939 bool exited,
940 int signal,
941 int status)
Todd Fialaaf245d12014-06-30 21:05:18 +0000942{
943 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
944
Todd Fialaaf245d12014-06-30 21:05:18 +0000945 // Certain activities differ based on whether the pid is the tid of the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000946 const bool is_main_thread = (pid == GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000947
948 // Handle when the thread exits.
949 if (exited)
950 {
951 if (log)
Chaoren Lin86fd8e42015-02-03 01:51:15 +0000952 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 +0000953
954 // This is a thread that exited. Ensure we're not tracking it anymore.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000955 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000956
957 if (is_main_thread)
958 {
959 // We only set the exit status and notify the delegate if we haven't already set the process
960 // state to an exited state. We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
961 // for the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000962 const bool already_notified = (GetState() == StateType::eStateExited) || (GetState () == StateType::eStateCrashed);
Todd Fialaaf245d12014-06-30 21:05:18 +0000963 if (!already_notified)
964 {
965 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +0000966 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 +0000967 // The main thread exited. We're done monitoring. Report to delegate.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000968 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +0000969
970 // Notify delegate that our process has exited.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000971 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +0000972 }
973 else
974 {
975 if (log)
976 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
977 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000978 }
979 else
980 {
981 // Do we want to report to the delegate in this case? I think not. If this was an orderly
982 // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
983 // and we would have done an all-stop then.
984 if (log)
985 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 +0000986 }
Pavel Labath1107b5a2015-04-17 14:07:49 +0000987 return;
Todd Fialaaf245d12014-06-30 21:05:18 +0000988 }
989
Todd Fialaaf245d12014-06-30 21:05:18 +0000990 siginfo_t info;
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000991 const auto info_err = GetSignalInfo(pid, &info);
992 auto thread_sp = GetThreadByID(pid);
993
994 if (! thread_sp)
995 {
996 // Normally, the only situation when we cannot find the thread is if we have just
997 // received a new thread notification. This is indicated by GetSignalInfo() returning
998 // si_code == SI_USER and si_pid == 0
999 if (log)
1000 log->Printf("NativeProcessLinux::%s received notification about an unknown tid %" PRIu64 ".", __FUNCTION__, pid);
1001
1002 if (info_err.Fail())
1003 {
1004 if (log)
1005 log->Printf("NativeProcessLinux::%s (tid %" PRIu64 ") GetSignalInfo failed (%s). Ingoring this notification.", __FUNCTION__, pid, info_err.AsCString());
1006 return;
1007 }
1008
1009 if (log && (info.si_code != SI_USER || info.si_pid != 0))
1010 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);
1011
1012 auto thread_sp = AddThread(pid);
1013 // Resume the newly created thread.
1014 ResumeThread(*thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
1015 ThreadWasCreated(*thread_sp);
1016 return;
1017 }
1018
1019 // Get details on the signal raised.
1020 if (info_err.Success())
Chaoren Linfa03ad22015-02-03 01:50:42 +00001021 {
1022 // We have retrieved the signal info. Dispatch appropriately.
1023 if (info.si_signo == SIGTRAP)
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001024 MonitorSIGTRAP(info, *thread_sp);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001025 else
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001026 MonitorSignal(info, *thread_sp, exited);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001027 }
1028 else
Todd Fialaaf245d12014-06-30 21:05:18 +00001029 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001030 if (info_err.GetError() == EINVAL)
Todd Fialaaf245d12014-06-30 21:05:18 +00001031 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00001032 // This is a group stop reception for this tid.
Pavel Labath39036ac2015-05-21 08:32:18 +00001033 // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the
1034 // tracee, triggering the group-stop mechanism. Normally receiving these would stop
1035 // the process, pending a SIGCONT. Simulating this state in a debugger is hard and is
1036 // generally not needed (one use case is debugging background task being managed by a
1037 // shell). For general use, it is sufficient to stop the process in a signal-delivery
1038 // stop which happens before the group stop. This done by MonitorSignal and works
1039 // correctly for all signals.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001040 if (log)
Pavel Labath39036ac2015-05-21 08:32:18 +00001041 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 +00001042 ResumeThread(*thread_sp, thread_sp->GetState(), LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001043 }
1044 else
1045 {
1046 // ptrace(GETSIGINFO) failed (but not due to group-stop).
1047
1048 // A return value of ESRCH means the thread/process is no longer on the system,
1049 // so it was killed somehow outside of our control. Either way, we can't do anything
1050 // with it anymore.
1051
Todd Fialaaf245d12014-06-30 21:05:18 +00001052 // Stop tracking the metadata for the thread since it's entirely off the system now.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001053 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001054
1055 if (log)
1056 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001057 __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 +00001058
1059 if (is_main_thread)
1060 {
1061 // Notify the delegate - our process is not available but appears to have been killed outside
1062 // our control. Is eStateExited the right exit state in this case?
Pavel Labath1107b5a2015-04-17 14:07:49 +00001063 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
1064 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001065 }
1066 else
1067 {
1068 // This thread was pulled out from underneath us. Anything to do here? Do we want to do an all stop?
1069 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +00001070 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 +00001071 }
1072 }
1073 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001074}
1075
1076void
Pavel Labath426bdf82015-04-28 07:51:52 +00001077NativeProcessLinux::WaitForNewThread(::pid_t tid)
1078{
1079 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1080
Pavel Labathf9077782015-08-21 09:13:53 +00001081 NativeThreadLinuxSP new_thread_sp = GetThreadByID(tid);
Pavel Labath426bdf82015-04-28 07:51:52 +00001082
1083 if (new_thread_sp)
1084 {
1085 // We are already tracking the thread - we got the event on the new thread (see
1086 // MonitorSignal) before this one. We are done.
1087 return;
1088 }
1089
1090 // The thread is not tracked yet, let's wait for it to appear.
1091 int status = -1;
1092 ::pid_t wait_pid;
1093 do
1094 {
1095 if (log)
1096 log->Printf ("NativeProcessLinux::%s() received thread creation event for tid %" PRIu32 ". tid not tracked yet, waiting for thread to appear...", __FUNCTION__, tid);
1097 wait_pid = waitpid(tid, &status, __WALL);
1098 }
1099 while (wait_pid == -1 && errno == EINTR);
1100 // Since we are waiting on a specific tid, this must be the creation event. But let's do
1101 // some checks just in case.
1102 if (wait_pid != tid) {
1103 if (log)
1104 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime", __FUNCTION__, tid);
1105 // The only way I know of this could happen is if the whole process was
1106 // SIGKILLed in the mean time. In any case, we can't do anything about that now.
1107 return;
1108 }
1109 if (WIFEXITED(status))
1110 {
1111 if (log)
1112 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " returned an 'exited' event. Not tracking the thread.", __FUNCTION__, tid);
1113 // Also a very improbable event.
1114 return;
1115 }
1116
1117 siginfo_t info;
1118 Error error = GetSignalInfo(tid, &info);
1119 if (error.Fail())
1120 {
1121 if (log)
1122 log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime.", __FUNCTION__, tid);
1123 return;
1124 }
1125
1126 if (((info.si_pid != 0) || (info.si_code != SI_USER)) && log)
1127 {
1128 // We should be getting a thread creation signal here, but we received something
1129 // else. There isn't much we can do about it now, so we will just log that. Since the
1130 // thread is alive and we are receiving events from it, we shall pretend that it was
1131 // created properly.
1132 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);
1133 }
1134
1135 if (log)
1136 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 ": tracking new thread tid %" PRIu32,
1137 __FUNCTION__, GetID (), tid);
1138
Pavel Labathf9077782015-08-21 09:13:53 +00001139 new_thread_sp = AddThread(tid);
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001140 ResumeThread(*new_thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
Pavel Labathf9077782015-08-21 09:13:53 +00001141 ThreadWasCreated(*new_thread_sp);
Pavel Labath426bdf82015-04-28 07:51:52 +00001142}
1143
1144void
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001145NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info, NativeThreadLinux &thread)
Todd Fialaaf245d12014-06-30 21:05:18 +00001146{
1147 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001148 const bool is_main_thread = (thread.GetID() == GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001149
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001150 assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
Todd Fialaaf245d12014-06-30 21:05:18 +00001151
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001152 Mutex::Locker locker (m_threads_mutex);
1153
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001154 switch (info.si_code)
Todd Fialaaf245d12014-06-30 21:05:18 +00001155 {
1156 // TODO: these two cases are required if we want to support tracing of the inferiors' children. We'd need this to debug a monitor.
1157 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
1158 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
1159
1160 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
1161 {
Pavel Labath5fd24c62015-04-23 09:04:35 +00001162 // This is the notification on the parent thread which informs us of new thread
Pavel Labath426bdf82015-04-28 07:51:52 +00001163 // creation.
1164 // We don't want to do anything with the parent thread so we just resume it. In case we
1165 // want to implement "break on thread creation" functionality, we would need to stop
1166 // here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001167
Pavel Labath426bdf82015-04-28 07:51:52 +00001168 unsigned long event_message = 0;
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001169 if (GetEventMessage(thread.GetID(), &event_message).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001170 {
Pavel Labath426bdf82015-04-28 07:51:52 +00001171 if (log)
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001172 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 +00001173 } else
1174 WaitForNewThread(event_message);
Todd Fialaaf245d12014-06-30 21:05:18 +00001175
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001176 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001177 break;
1178 }
1179
1180 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
Todd Fialaa9882ce2014-08-28 15:46:54 +00001181 {
Pavel Labathf9077782015-08-21 09:13:53 +00001182 NativeThreadLinuxSP main_thread_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001183 if (log)
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001184 log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info.si_code ^ SIGTRAP);
Todd Fialaa9882ce2014-08-28 15:46:54 +00001185
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001186 // Exec clears any pending notifications.
Pavel Labath0e1d7292015-08-20 09:06:12 +00001187 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
Chaoren Linfa03ad22015-02-03 01:50:42 +00001188
1189 // Remove all but the main thread here. Linux fork creates a new process which only copies the main thread. Mutexes are in undefined state.
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001190 if (log)
1191 log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
1192
1193 for (auto thread_sp : m_threads)
Todd Fialaa9882ce2014-08-28 15:46:54 +00001194 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001195 const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
1196 if (is_main_thread)
Todd Fialaa9882ce2014-08-28 15:46:54 +00001197 {
Pavel Labathf9077782015-08-21 09:13:53 +00001198 main_thread_sp = std::static_pointer_cast<NativeThreadLinux>(thread_sp);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001199 if (log)
1200 log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00001201 }
1202 else
1203 {
Todd Fialaa9882ce2014-08-28 15:46:54 +00001204 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001205 log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00001206 }
1207 }
1208
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001209 m_threads.clear ();
1210
1211 if (main_thread_sp)
1212 {
1213 m_threads.push_back (main_thread_sp);
1214 SetCurrentThreadID (main_thread_sp->GetID ());
Pavel Labathf9077782015-08-21 09:13:53 +00001215 main_thread_sp->SetStoppedByExec();
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001216 }
1217 else
1218 {
1219 SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
1220 if (log)
1221 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
1222 }
1223
Chaoren Linfa03ad22015-02-03 01:50:42 +00001224 // Tell coordinator about about the "new" (since exec) stopped main thread.
Pavel Labathf9077782015-08-21 09:13:53 +00001225 ThreadWasCreated(*main_thread_sp);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001226
Todd Fialaa9882ce2014-08-28 15:46:54 +00001227 // Let our delegate know we have just exec'd.
1228 NotifyDidExec ();
1229
1230 // If we have a main thread, indicate we are stopped.
1231 assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001232
1233 // Let the process know we're stopped.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001234 StopRunningThreads(main_thread_sp->GetID());
Todd Fialaa9882ce2014-08-28 15:46:54 +00001235
Todd Fialaaf245d12014-06-30 21:05:18 +00001236 break;
Todd Fialaa9882ce2014-08-28 15:46:54 +00001237 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001238
1239 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
1240 {
1241 // The inferior process or one of its threads is about to exit.
Pavel Labath6e351632015-05-15 13:30:59 +00001242 // We don't want to do anything with the thread so we just resume it. In case we
1243 // want to implement "break on thread exit" functionality, we would need to stop
1244 // here.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001245
Todd Fialaaf245d12014-06-30 21:05:18 +00001246 unsigned long data = 0;
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001247 if (GetEventMessage(thread.GetID(), &data).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001248 data = -1;
1249
1250 if (log)
1251 {
1252 log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
1253 __FUNCTION__,
1254 data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001255 thread.GetID(),
Todd Fialaaf245d12014-06-30 21:05:18 +00001256 is_main_thread ? "is main thread" : "not main thread");
1257 }
1258
Todd Fialaaf245d12014-06-30 21:05:18 +00001259 if (is_main_thread)
1260 {
1261 SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001262 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001263
Pavel Labath86852d32015-09-01 10:59:36 +00001264 StateType state = thread.GetState();
1265 if (! StateIsRunningState(state))
1266 {
1267 // Due to a kernel bug, we may sometimes get this stop after the inferior gets a
1268 // SIGKILL. This confuses our state tracking logic in ResumeThread(), since normally,
1269 // we should not be receiving any ptrace events while the inferior is stopped. This
1270 // makes sure that the inferior is resumed and exits normally.
1271 state = eStateRunning;
1272 }
1273 ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001274
1275 break;
1276 }
1277
1278 case 0:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001279 case TRAP_TRACE: // We receive this on single stepping.
1280 case TRAP_HWBKPT: // We receive this on watchpoint hit
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001281 {
1282 // If a watchpoint was hit, report it
1283 uint32_t wp_index;
Tamas Berghammer1fa5c4b2015-10-13 16:48:04 +00001284 Error error = thread.GetRegisterContext()->GetWatchpointHitIndex(wp_index, (uintptr_t)info.si_addr);
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001285 if (error.Fail() && log)
1286 log->Printf("NativeProcessLinux::%s() "
1287 "received error while checking for watchpoint hits, "
1288 "pid = %" PRIu64 " error = %s",
1289 __FUNCTION__, thread.GetID(), error.AsCString());
1290 if (wp_index != LLDB_INVALID_INDEX32)
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001291 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001292 MonitorWatchpoint(thread, wp_index);
1293 break;
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001294 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001295
Tamas Berghammerbe379e12016-02-16 15:14:36 +00001296 // Otherwise, report step over
1297 MonitorTrace(thread);
Todd Fialaaf245d12014-06-30 21:05:18 +00001298 break;
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001299 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001300
1301 case SI_KERNEL:
Mohit K. Bhakkad35799962015-06-18 04:53:18 +00001302#if defined __mips__
1303 // For mips there is no special signal for watchpoint
1304 // So we check for watchpoint in kernel trap
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001305 {
1306 // If a watchpoint was hit, report it
1307 uint32_t wp_index;
1308 Error error = thread.GetRegisterContext()->GetWatchpointHitIndex(wp_index, LLDB_INVALID_ADDRESS);
1309 if (error.Fail() && log)
1310 log->Printf("NativeProcessLinux::%s() "
1311 "received error while checking for watchpoint hits, "
1312 "pid = %" PRIu64 " error = %s",
Mohit K. Bhakkad16ad0322015-08-28 12:08:26 +00001313 __FUNCTION__, thread.GetID(), error.AsCString());
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001314 if (wp_index != LLDB_INVALID_INDEX32)
Mohit K. Bhakkad35799962015-06-18 04:53:18 +00001315 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001316 MonitorWatchpoint(thread, wp_index);
1317 break;
Mohit K. Bhakkad35799962015-06-18 04:53:18 +00001318 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001319 }
Mohit K. Bhakkad35799962015-06-18 04:53:18 +00001320 // NO BREAK
1321#endif
Todd Fialaaf245d12014-06-30 21:05:18 +00001322 case TRAP_BRKPT:
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001323 MonitorBreakpoint(thread);
Todd Fialaaf245d12014-06-30 21:05:18 +00001324 break;
1325
1326 case SIGTRAP:
1327 case (SIGTRAP | 0x80):
1328 if (log)
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001329 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 +00001330
Todd Fialaaf245d12014-06-30 21:05:18 +00001331 // Ignore these signals until we know more about them.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001332 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001333 break;
1334
1335 default:
1336 assert(false && "Unexpected SIGTRAP code!");
1337 if (log)
Pavel Labath6e351632015-05-15 13:30:59 +00001338 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 "tid %" PRIu64 " received unhandled SIGTRAP code: 0x%d",
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001339 __FUNCTION__, GetID(), thread.GetID(), info.si_code);
Todd Fialaaf245d12014-06-30 21:05:18 +00001340 break;
1341
1342 }
1343}
1344
1345void
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001346NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread)
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001347{
1348 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1349 if (log)
1350 log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)",
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001351 __FUNCTION__, thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001352
Pavel Labath0e1d7292015-08-20 09:06:12 +00001353 // This thread is currently stopped.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001354 thread.SetStoppedByTrace();
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001355
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001356 StopRunningThreads(thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001357}
1358
1359void
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001360NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread)
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001361{
1362 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
1363 if (log)
1364 log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001365 __FUNCTION__, thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001366
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001367 // Mark the thread as stopped at breakpoint.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001368 thread.SetStoppedByBreakpoint();
1369 Error error = FixupBreakpointPCAsNeeded(thread);
1370 if (error.Fail())
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001371 if (log)
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001372 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
1373 __FUNCTION__, thread.GetID(), error.AsCString());
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001374
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001375 if (m_threads_stepping_with_breakpoint.find(thread.GetID()) != m_threads_stepping_with_breakpoint.end())
1376 thread.SetStoppedByTrace();
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001377
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001378 StopRunningThreads(thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001379}
1380
1381void
Pavel Labathf9077782015-08-21 09:13:53 +00001382NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread, uint32_t wp_index)
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001383{
1384 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
1385 if (log)
1386 log->Printf("NativeProcessLinux::%s() received watchpoint event, "
1387 "pid = %" PRIu64 ", wp_index = %" PRIu32,
Pavel Labathf9077782015-08-21 09:13:53 +00001388 __FUNCTION__, thread.GetID(), wp_index);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001389
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001390 // Mark the thread as stopped at watchpoint.
1391 // The address is at (lldb::addr_t)info->si_addr if we need it.
Pavel Labathf9077782015-08-21 09:13:53 +00001392 thread.SetStoppedByWatchpoint(wp_index);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001393
1394 // We need to tell all other running threads before we notify the delegate about this stop.
Pavel Labathf9077782015-08-21 09:13:53 +00001395 StopRunningThreads(thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001396}
1397
1398void
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001399NativeProcessLinux::MonitorSignal(const siginfo_t &info, NativeThreadLinux &thread, bool exited)
Todd Fialaaf245d12014-06-30 21:05:18 +00001400{
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001401 const int signo = info.si_signo;
1402 const bool is_from_llgs = info.si_pid == getpid ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001403
1404 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1405
1406 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1407 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1408 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
1409 //
1410 // IOW, user generated signals never generate what we consider to be a
1411 // "crash".
1412 //
1413 // Similarly, ACK signals generated by this monitor.
1414
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001415 Mutex::Locker locker (m_threads_mutex);
1416
Todd Fialaaf245d12014-06-30 21:05:18 +00001417 // Handle the signal.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001418 if (info.si_code == SI_TKILL || info.si_code == SI_USER)
Todd Fialaaf245d12014-06-30 21:05:18 +00001419 {
1420 if (log)
1421 log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
1422 __FUNCTION__,
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001423 Host::GetSignalAsCString(signo),
Todd Fialaaf245d12014-06-30 21:05:18 +00001424 signo,
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001425 (info.si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
1426 info.si_pid,
Todd Fiala511e5cd2014-09-11 23:29:14 +00001427 is_from_llgs ? "from llgs" : "not from llgs",
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001428 thread.GetID());
Todd Fiala58a2f662014-08-12 17:02:07 +00001429 }
1430
1431 // Check for thread stop notification.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001432 if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP))
Todd Fiala58a2f662014-08-12 17:02:07 +00001433 {
1434 // This is a tgkill()-based stop.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001435 if (log)
1436 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
1437 __FUNCTION__,
1438 GetID (),
1439 thread.GetID());
1440
1441 // Check that we're not already marked with a stop reason.
1442 // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
1443 // the kernel signaled us with the thread stopping which we handled and marked as stopped,
1444 // and that, without an intervening resume, we received another stop. It is more likely
1445 // that we are missing the marking of a run state somewhere if we find that the thread was
1446 // marked as stopped.
1447 const StateType thread_state = thread.GetState();
1448 if (!StateIsStoppedState (thread_state, false))
Todd Fiala58a2f662014-08-12 17:02:07 +00001449 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001450 // An inferior thread has stopped because of a SIGSTOP we have sent it.
1451 // Generally, these are not important stops and we don't want to report them as
1452 // they are just used to stop other threads when one thread (the one with the
1453 // *real* stop reason) hits a breakpoint (watchpoint, etc...). However, in the
1454 // case of an asynchronous Interrupt(), this *is* the real stop reason, so we
1455 // leave the signal intact if this is the thread that was chosen as the
1456 // triggering thread.
1457 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID)
Chaoren Linaab58632015-02-03 01:50:57 +00001458 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001459 if (m_pending_notification_tid == thread.GetID())
1460 thread.SetStoppedBySignal(SIGSTOP, &info);
Pavel Labath0e1d7292015-08-20 09:06:12 +00001461 else
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001462 thread.SetStoppedWithNoReason();
1463
1464 SetCurrentThreadID (thread.GetID ());
1465 SignalIfAllThreadsStopped();
Chaoren Linaab58632015-02-03 01:50:57 +00001466 }
1467 else
1468 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001469 // We can end up here if stop was initiated by LLGS but by this time a
1470 // thread stop has occurred - maybe initiated by another event.
1471 Error error = ResumeThread(thread, thread.GetState(), 0);
1472 if (error.Fail() && log)
Chaoren Linaab58632015-02-03 01:50:57 +00001473 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001474 log->Printf("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s",
1475 __FUNCTION__, thread.GetID(), error.AsCString());
Chaoren Linaab58632015-02-03 01:50:57 +00001476 }
1477 }
Todd Fiala58a2f662014-08-12 17:02:07 +00001478 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001479 else
1480 {
1481 if (log)
1482 {
1483 // Retrieve the signal name if the thread was stopped by a signal.
1484 int stop_signo = 0;
1485 const bool stopped_by_signal = thread.IsStopped(&stop_signo);
1486 const char *signal_name = stopped_by_signal ? Host::GetSignalAsCString(stop_signo) : "<not stopped by signal>";
1487 if (!signal_name)
1488 signal_name = "<no-signal-name>";
1489
1490 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",
1491 __FUNCTION__,
1492 GetID (),
1493 thread.GetID(),
1494 StateAsCString (thread_state),
1495 stop_signo,
1496 signal_name);
1497 }
1498 SignalIfAllThreadsStopped();
1499 }
Todd Fiala58a2f662014-08-12 17:02:07 +00001500
1501 // Done handling.
Todd Fialaaf245d12014-06-30 21:05:18 +00001502 return;
1503 }
1504
1505 if (log)
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001506 log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, Host::GetSignalAsCString(signo));
Todd Fialaaf245d12014-06-30 21:05:18 +00001507
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001508 // This thread is stopped.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001509 thread.SetStoppedBySignal(signo, &info);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001510
1511 // Send a stop to the debugger after we get all other threads to stop.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001512 StopRunningThreads(thread.GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +00001513}
1514
Tamas Berghammere7708682015-04-22 10:00:23 +00001515namespace {
1516
1517struct EmulatorBaton
1518{
1519 NativeProcessLinux* m_process;
1520 NativeRegisterContext* m_reg_context;
Tamas Berghammere7708682015-04-22 10:00:23 +00001521
Pavel Labath6648fcc2015-04-27 09:21:14 +00001522 // eRegisterKindDWARF -> RegsiterValue
1523 std::unordered_map<uint32_t, RegisterValue> m_register_values;
1524
1525 EmulatorBaton(NativeProcessLinux* process, NativeRegisterContext* reg_context) :
Tamas Berghammere7708682015-04-22 10:00:23 +00001526 m_process(process), m_reg_context(reg_context) {}
1527};
1528
1529} // anonymous namespace
1530
1531static size_t
1532ReadMemoryCallback (EmulateInstruction *instruction,
1533 void *baton,
1534 const EmulateInstruction::Context &context,
1535 lldb::addr_t addr,
1536 void *dst,
1537 size_t length)
1538{
1539 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
1540
Chaoren Lin3eb4b452015-04-29 17:24:48 +00001541 size_t bytes_read;
Tamas Berghammere7708682015-04-22 10:00:23 +00001542 emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
1543 return bytes_read;
1544}
1545
1546static bool
1547ReadRegisterCallback (EmulateInstruction *instruction,
1548 void *baton,
1549 const RegisterInfo *reg_info,
1550 RegisterValue &reg_value)
1551{
1552 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
1553
Pavel Labath6648fcc2015-04-27 09:21:14 +00001554 auto it = emulator_baton->m_register_values.find(reg_info->kinds[eRegisterKindDWARF]);
1555 if (it != emulator_baton->m_register_values.end())
1556 {
1557 reg_value = it->second;
1558 return true;
1559 }
1560
Tamas Berghammere7708682015-04-22 10:00:23 +00001561 // The emulator only fill in the dwarf regsiter numbers (and in some case
1562 // the generic register numbers). Get the full register info from the
1563 // register context based on the dwarf register numbers.
1564 const RegisterInfo* full_reg_info = emulator_baton->m_reg_context->GetRegisterInfo(
1565 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
1566
1567 Error error = emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
Pavel Labath6648fcc2015-04-27 09:21:14 +00001568 if (error.Success())
Pavel Labath6648fcc2015-04-27 09:21:14 +00001569 return true;
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001570
Pavel Labath6648fcc2015-04-27 09:21:14 +00001571 return false;
Tamas Berghammere7708682015-04-22 10:00:23 +00001572}
1573
1574static bool
1575WriteRegisterCallback (EmulateInstruction *instruction,
1576 void *baton,
1577 const EmulateInstruction::Context &context,
1578 const RegisterInfo *reg_info,
1579 const RegisterValue &reg_value)
1580{
1581 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
Pavel Labath6648fcc2015-04-27 09:21:14 +00001582 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = reg_value;
Tamas Berghammere7708682015-04-22 10:00:23 +00001583 return true;
1584}
1585
1586static size_t
1587WriteMemoryCallback (EmulateInstruction *instruction,
1588 void *baton,
1589 const EmulateInstruction::Context &context,
1590 lldb::addr_t addr,
1591 const void *dst,
1592 size_t length)
1593{
1594 return length;
1595}
1596
1597static lldb::addr_t
1598ReadFlags (NativeRegisterContext* regsiter_context)
1599{
1600 const RegisterInfo* flags_info = regsiter_context->GetRegisterInfo(
1601 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1602 return regsiter_context->ReadRegisterAsUnsigned(flags_info, LLDB_INVALID_ADDRESS);
1603}
1604
1605Error
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001606NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadLinux &thread)
Tamas Berghammere7708682015-04-22 10:00:23 +00001607{
1608 Error error;
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001609 NativeRegisterContextSP register_context_sp = thread.GetRegisterContext();
Tamas Berghammere7708682015-04-22 10:00:23 +00001610
1611 std::unique_ptr<EmulateInstruction> emulator_ap(
1612 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, nullptr));
1613
1614 if (emulator_ap == nullptr)
1615 return Error("Instruction emulator not found!");
1616
1617 EmulatorBaton baton(this, register_context_sp.get());
1618 emulator_ap->SetBaton(&baton);
1619 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
1620 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
1621 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
1622 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
1623
1624 if (!emulator_ap->ReadInstruction())
1625 return Error("Read instruction failed!");
1626
Pavel Labath6648fcc2015-04-27 09:21:14 +00001627 bool emulation_result = emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
1628
1629 const RegisterInfo* reg_info_pc = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1630 const RegisterInfo* reg_info_flags = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1631
1632 auto pc_it = baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1633 auto flags_it = baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
1634
Tamas Berghammere7708682015-04-22 10:00:23 +00001635 lldb::addr_t next_pc;
1636 lldb::addr_t next_flags;
Pavel Labath6648fcc2015-04-27 09:21:14 +00001637 if (emulation_result)
Tamas Berghammere7708682015-04-22 10:00:23 +00001638 {
Pavel Labath6648fcc2015-04-27 09:21:14 +00001639 assert(pc_it != baton.m_register_values.end() && "Emulation was successfull but PC wasn't updated");
1640 next_pc = pc_it->second.GetAsUInt64();
1641
1642 if (flags_it != baton.m_register_values.end())
1643 next_flags = flags_it->second.GetAsUInt64();
Tamas Berghammere7708682015-04-22 10:00:23 +00001644 else
1645 next_flags = ReadFlags (register_context_sp.get());
1646 }
Pavel Labath6648fcc2015-04-27 09:21:14 +00001647 else if (pc_it == baton.m_register_values.end())
Tamas Berghammere7708682015-04-22 10:00:23 +00001648 {
1649 // Emulate instruction failed and it haven't changed PC. Advance PC
1650 // with the size of the current opcode because the emulation of all
1651 // PC modifying instruction should be successful. The failure most
1652 // likely caused by a not supported instruction which don't modify PC.
1653 next_pc = register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
1654 next_flags = ReadFlags (register_context_sp.get());
1655 }
1656 else
1657 {
1658 // The instruction emulation failed after it modified the PC. It is an
1659 // unknown error where we can't continue because the next instruction is
1660 // modifying the PC but we don't know how.
1661 return Error ("Instruction emulation failed unexpectedly.");
1662 }
1663
1664 if (m_arch.GetMachine() == llvm::Triple::arm)
1665 {
1666 if (next_flags & 0x20)
1667 {
1668 // Thumb mode
1669 error = SetSoftwareBreakpoint(next_pc, 2);
1670 }
1671 else
1672 {
1673 // Arm mode
1674 error = SetSoftwareBreakpoint(next_pc, 4);
1675 }
1676 }
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001677 else if (m_arch.GetMachine() == llvm::Triple::mips64
Jaydeep Patilc60c9452015-06-23 03:37:08 +00001678 || m_arch.GetMachine() == llvm::Triple::mips64el
1679 || m_arch.GetMachine() == llvm::Triple::mips
1680 || m_arch.GetMachine() == llvm::Triple::mipsel)
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001681 error = SetSoftwareBreakpoint(next_pc, 4);
Tamas Berghammere7708682015-04-22 10:00:23 +00001682 else
1683 {
1684 // No size hint is given for the next breakpoint
1685 error = SetSoftwareBreakpoint(next_pc, 0);
1686 }
1687
Tamas Berghammere7708682015-04-22 10:00:23 +00001688 if (error.Fail())
1689 return error;
1690
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001691 m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
Tamas Berghammere7708682015-04-22 10:00:23 +00001692
1693 return Error();
1694}
1695
1696bool
1697NativeProcessLinux::SupportHardwareSingleStepping() const
1698{
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001699 if (m_arch.GetMachine() == llvm::Triple::arm
Jaydeep Patilc60c9452015-06-23 03:37:08 +00001700 || m_arch.GetMachine() == llvm::Triple::mips64 || m_arch.GetMachine() == llvm::Triple::mips64el
1701 || m_arch.GetMachine() == llvm::Triple::mips || m_arch.GetMachine() == llvm::Triple::mipsel)
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001702 return false;
1703 return true;
Tamas Berghammere7708682015-04-22 10:00:23 +00001704}
1705
Todd Fialaaf245d12014-06-30 21:05:18 +00001706Error
1707NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
1708{
Todd Fialaaf245d12014-06-30 21:05:18 +00001709 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1710 if (log)
1711 log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
1712
Tamas Berghammere7708682015-04-22 10:00:23 +00001713 bool software_single_step = !SupportHardwareSingleStepping();
Todd Fialaaf245d12014-06-30 21:05:18 +00001714
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001715 Mutex::Locker locker (m_threads_mutex);
Chaoren Lin03f12d62015-02-03 01:50:49 +00001716
Tamas Berghammere7708682015-04-22 10:00:23 +00001717 if (software_single_step)
1718 {
1719 for (auto thread_sp : m_threads)
1720 {
1721 assert (thread_sp && "thread list should not contain NULL threads");
1722
1723 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
1724 if (action == nullptr)
1725 continue;
1726
1727 if (action->state == eStateStepping)
1728 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001729 Error error = SetupSoftwareSingleStepping(static_cast<NativeThreadLinux &>(*thread_sp));
Tamas Berghammere7708682015-04-22 10:00:23 +00001730 if (error.Fail())
1731 return error;
1732 }
1733 }
1734 }
1735
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001736 for (auto thread_sp : m_threads)
Todd Fialaaf245d12014-06-30 21:05:18 +00001737 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001738 assert (thread_sp && "thread list should not contain NULL threads");
1739
1740 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
1741
1742 if (action == nullptr)
Todd Fialaaf245d12014-06-30 21:05:18 +00001743 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00001744 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001745 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
1746 __FUNCTION__, GetID (), thread_sp->GetID ());
1747 continue;
1748 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001749
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001750 if (log)
1751 {
1752 log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
1753 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
1754 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001755
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001756 switch (action->state)
1757 {
1758 case eStateRunning:
Pavel Labath0e1d7292015-08-20 09:06:12 +00001759 case eStateStepping:
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001760 {
1761 // Run the thread, possibly feeding it the signal.
1762 const int signo = action->signal;
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001763 ResumeThread(static_cast<NativeThreadLinux &>(*thread_sp), action->state, signo);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001764 break;
1765 }
1766
1767 case eStateSuspended:
1768 case eStateStopped:
Pavel Labath108c3252015-05-12 09:03:18 +00001769 lldbassert(0 && "Unexpected state");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001770
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001771 default:
1772 return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
1773 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001774 }
1775 }
1776
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001777 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00001778}
1779
1780Error
1781NativeProcessLinux::Halt ()
1782{
1783 Error error;
1784
Todd Fialaaf245d12014-06-30 21:05:18 +00001785 if (kill (GetID (), SIGSTOP) != 0)
1786 error.SetErrorToErrno ();
1787
1788 return error;
1789}
1790
1791Error
1792NativeProcessLinux::Detach ()
1793{
1794 Error error;
1795
Todd Fialaaf245d12014-06-30 21:05:18 +00001796 // Stop monitoring the inferior.
Pavel Labath19cbe962015-07-21 13:20:32 +00001797 m_sigchld_handle.reset();
Todd Fialaaf245d12014-06-30 21:05:18 +00001798
Pavel Labath7a9495b2015-09-01 15:00:51 +00001799 // Tell ptrace to detach from the process.
1800 if (GetID () == LLDB_INVALID_PROCESS_ID)
1801 return error;
1802
1803 for (auto thread_sp : m_threads)
1804 {
1805 Error e = Detach(thread_sp->GetID());
1806 if (e.Fail())
1807 error = e; // Save the error, but still attempt to detach from other threads.
1808 }
1809
Todd Fialaaf245d12014-06-30 21:05:18 +00001810 return error;
1811}
1812
1813Error
1814NativeProcessLinux::Signal (int signo)
1815{
1816 Error error;
1817
1818 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1819 if (log)
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001820 log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
1821 __FUNCTION__, signo, Host::GetSignalAsCString(signo), GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +00001822
1823 if (kill(GetID(), signo))
1824 error.SetErrorToErrno();
1825
1826 return error;
1827}
1828
1829Error
Chaoren Line9547b82015-02-03 01:51:00 +00001830NativeProcessLinux::Interrupt ()
1831{
1832 // Pick a running thread (or if none, a not-dead stopped thread) as
1833 // the chosen thread that will be the stop-reason thread.
Chaoren Line9547b82015-02-03 01:51:00 +00001834 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1835
1836 NativeThreadProtocolSP running_thread_sp;
1837 NativeThreadProtocolSP stopped_thread_sp;
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001838
1839 if (log)
1840 log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
1841
1842 Mutex::Locker locker (m_threads_mutex);
1843
1844 for (auto thread_sp : m_threads)
Chaoren Line9547b82015-02-03 01:51:00 +00001845 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001846 // The thread shouldn't be null but lets just cover that here.
1847 if (!thread_sp)
1848 continue;
Chaoren Line9547b82015-02-03 01:51:00 +00001849
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001850 // If we have a running or stepping thread, we'll call that the
1851 // target of the interrupt.
1852 const auto thread_state = thread_sp->GetState ();
1853 if (thread_state == eStateRunning ||
1854 thread_state == eStateStepping)
Chaoren Line9547b82015-02-03 01:51:00 +00001855 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001856 running_thread_sp = thread_sp;
1857 break;
1858 }
1859 else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
1860 {
1861 // Remember the first non-dead stopped thread. We'll use that as a backup if there are no running threads.
1862 stopped_thread_sp = thread_sp;
Chaoren Line9547b82015-02-03 01:51:00 +00001863 }
1864 }
1865
1866 if (!running_thread_sp && !stopped_thread_sp)
1867 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001868 Error error("found no running/stepping or live stopped threads as target for interrupt");
Chaoren Line9547b82015-02-03 01:51:00 +00001869 if (log)
Chaoren Line9547b82015-02-03 01:51:00 +00001870 log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001871
Chaoren Line9547b82015-02-03 01:51:00 +00001872 return error;
1873 }
1874
1875 NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
1876
1877 if (log)
1878 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
1879 __FUNCTION__,
1880 GetID (),
1881 running_thread_sp ? "running" : "stopped",
1882 deferred_signal_thread_sp->GetID ());
1883
Pavel Labathed89c7f2015-05-06 12:22:37 +00001884 StopRunningThreads(deferred_signal_thread_sp->GetID());
Pavel Labath45f5cb32015-05-05 15:05:50 +00001885
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001886 return Error();
Chaoren Line9547b82015-02-03 01:51:00 +00001887}
1888
1889Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001890NativeProcessLinux::Kill ()
1891{
1892 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1893 if (log)
1894 log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
1895
1896 Error error;
1897
1898 switch (m_state)
1899 {
1900 case StateType::eStateInvalid:
1901 case StateType::eStateExited:
1902 case StateType::eStateCrashed:
1903 case StateType::eStateDetached:
1904 case StateType::eStateUnloaded:
1905 // Nothing to do - the process is already dead.
1906 if (log)
1907 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
1908 return error;
1909
1910 case StateType::eStateConnected:
1911 case StateType::eStateAttaching:
1912 case StateType::eStateLaunching:
1913 case StateType::eStateStopped:
1914 case StateType::eStateRunning:
1915 case StateType::eStateStepping:
1916 case StateType::eStateSuspended:
1917 // We can try to kill a process in these states.
1918 break;
1919 }
1920
1921 if (kill (GetID (), SIGKILL) != 0)
1922 {
1923 error.SetErrorToErrno ();
1924 return error;
1925 }
1926
1927 return error;
1928}
1929
1930static Error
1931ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
1932{
1933 memory_region_info.Clear();
1934
1935 StringExtractor line_extractor (maps_line.c_str ());
1936
1937 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode pathname
1938 // perms: rwxp (letter is present if set, '-' if not, final character is p=private, s=shared).
1939
1940 // Parse out the starting address
1941 lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
1942
1943 // Parse out hyphen separating start and end address from range.
1944 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
1945 return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
1946
1947 // Parse out the ending address
1948 lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
1949
1950 // Parse out the space after the address.
1951 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
1952 return Error ("malformed /proc/{pid}/maps entry, missing space after range");
1953
1954 // Save the range.
1955 memory_region_info.GetRange ().SetRangeBase (start_address);
1956 memory_region_info.GetRange ().SetRangeEnd (end_address);
1957
1958 // Parse out each permission entry.
1959 if (line_extractor.GetBytesLeft () < 4)
1960 return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
1961
1962 // Handle read permission.
1963 const char read_perm_char = line_extractor.GetChar ();
1964 if (read_perm_char == 'r')
1965 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
1966 else
1967 {
1968 assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
1969 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
1970 }
1971
1972 // Handle write permission.
1973 const char write_perm_char = line_extractor.GetChar ();
1974 if (write_perm_char == 'w')
1975 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
1976 else
1977 {
1978 assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
1979 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
1980 }
1981
1982 // Handle execute permission.
1983 const char exec_perm_char = line_extractor.GetChar ();
1984 if (exec_perm_char == 'x')
1985 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
1986 else
1987 {
1988 assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
1989 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
1990 }
1991
1992 return Error ();
1993}
1994
1995Error
1996NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
1997{
1998 // FIXME review that the final memory region returned extends to the end of the virtual address space,
1999 // with no perms if it is not mapped.
2000
2001 // Use an approach that reads memory regions from /proc/{pid}/maps.
2002 // Assume proc maps entries are in ascending order.
2003 // FIXME assert if we find differently.
2004 Mutex::Locker locker (m_mem_region_cache_mutex);
2005
2006 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2007 Error error;
2008
2009 if (m_supports_mem_region == LazyBool::eLazyBoolNo)
2010 {
2011 // We're done.
2012 error.SetErrorString ("unsupported");
2013 return error;
2014 }
2015
2016 // If our cache is empty, pull the latest. There should always be at least one memory region
2017 // if memory region handling is supported.
2018 if (m_mem_region_cache.empty ())
2019 {
2020 error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
2021 [&] (const std::string &line) -> bool
2022 {
2023 MemoryRegionInfo info;
2024 const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
2025 if (parse_error.Success ())
2026 {
2027 m_mem_region_cache.push_back (info);
2028 return true;
2029 }
2030 else
2031 {
2032 if (log)
2033 log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
2034 return false;
2035 }
2036 });
2037
2038 // If we had an error, we'll mark unsupported.
2039 if (error.Fail ())
2040 {
2041 m_supports_mem_region = LazyBool::eLazyBoolNo;
2042 return error;
2043 }
2044 else if (m_mem_region_cache.empty ())
2045 {
2046 // No entries after attempting to read them. This shouldn't happen if /proc/{pid}/maps
2047 // is supported. Assume we don't support map entries via procfs.
2048 if (log)
2049 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
2050 m_supports_mem_region = LazyBool::eLazyBoolNo;
2051 error.SetErrorString ("not supported");
2052 return error;
2053 }
2054
2055 if (log)
2056 log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ());
2057
2058 // We support memory retrieval, remember that.
2059 m_supports_mem_region = LazyBool::eLazyBoolYes;
2060 }
2061 else
2062 {
2063 if (log)
2064 log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2065 }
2066
2067 lldb::addr_t prev_base_address = 0;
2068
2069 // FIXME start by finding the last region that is <= target address using binary search. Data is sorted.
2070 // There can be a ton of regions on pthreads apps with lots of threads.
2071 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
2072 {
2073 MemoryRegionInfo &proc_entry_info = *it;
2074
2075 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
2076 assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
2077 prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
2078
2079 // If the target address comes before this entry, indicate distance to next region.
2080 if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
2081 {
2082 range_info.GetRange ().SetRangeBase (load_addr);
2083 range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
2084 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2085 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2086 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2087
2088 return error;
2089 }
2090 else if (proc_entry_info.GetRange ().Contains (load_addr))
2091 {
2092 // The target address is within the memory region we're processing here.
2093 range_info = proc_entry_info;
2094 return error;
2095 }
2096
2097 // The target memory address comes somewhere after the region we just parsed.
2098 }
2099
Tamas Berghammer09839c32015-07-03 09:30:19 +00002100 // If we made it here, we didn't find an entry that contained the given address. Return the
2101 // load_addr as start and the amount of bytes betwwen load address and the end of the memory as
2102 // size.
2103 range_info.GetRange ().SetRangeBase (load_addr);
2104 switch (m_arch.GetAddressByteSize())
2105 {
2106 case 4:
2107 range_info.GetRange ().SetByteSize (0x100000000ull - load_addr);
2108 break;
2109 case 8:
2110 range_info.GetRange ().SetByteSize (0ull - load_addr);
2111 break;
2112 default:
2113 assert(false && "Unrecognized data byte size");
2114 break;
2115 }
2116 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2117 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2118 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
Todd Fialaaf245d12014-06-30 21:05:18 +00002119 return error;
2120}
2121
2122void
2123NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
2124{
2125 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2126 if (log)
2127 log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
2128
2129 {
2130 Mutex::Locker locker (m_mem_region_cache_mutex);
2131 if (log)
2132 log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2133 m_mem_region_cache.clear ();
2134 }
2135}
2136
2137Error
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002138NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr)
Todd Fialaaf245d12014-06-30 21:05:18 +00002139{
2140 // FIXME implementing this requires the equivalent of
2141 // InferiorCallPOSIX::InferiorCallMmap, which depends on
2142 // functional ThreadPlans working with Native*Protocol.
2143#if 1
2144 return Error ("not implemented yet");
2145#else
2146 addr = LLDB_INVALID_ADDRESS;
2147
2148 unsigned prot = 0;
2149 if (permissions & lldb::ePermissionsReadable)
2150 prot |= eMmapProtRead;
2151 if (permissions & lldb::ePermissionsWritable)
2152 prot |= eMmapProtWrite;
2153 if (permissions & lldb::ePermissionsExecutable)
2154 prot |= eMmapProtExec;
2155
2156 // TODO implement this directly in NativeProcessLinux
2157 // (and lift to NativeProcessPOSIX if/when that class is
2158 // refactored out).
2159 if (InferiorCallMmap(this, addr, 0, size, prot,
2160 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
2161 m_addr_to_mmap_size[addr] = size;
2162 return Error ();
2163 } else {
2164 addr = LLDB_INVALID_ADDRESS;
2165 return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
2166 }
2167#endif
2168}
2169
2170Error
2171NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
2172{
2173 // FIXME see comments in AllocateMemory - required lower-level
2174 // bits not in place yet (ThreadPlans)
2175 return Error ("not implemented");
2176}
2177
2178lldb::addr_t
2179NativeProcessLinux::GetSharedLibraryInfoAddress ()
2180{
2181#if 1
2182 // punt on this for now
2183 return LLDB_INVALID_ADDRESS;
2184#else
2185 // Return the image info address for the exe module
2186#if 1
2187 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2188
2189 ModuleSP module_sp;
2190 Error error = GetExeModuleSP (module_sp);
2191 if (error.Fail ())
2192 {
2193 if (log)
2194 log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ());
2195 return LLDB_INVALID_ADDRESS;
2196 }
2197
2198 if (module_sp == nullptr)
2199 {
2200 if (log)
2201 log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__);
2202 return LLDB_INVALID_ADDRESS;
2203 }
2204
2205 ObjectFileSP object_file_sp = module_sp->GetObjectFile ();
2206 if (object_file_sp == nullptr)
2207 {
2208 if (log)
2209 log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__);
2210 return LLDB_INVALID_ADDRESS;
2211 }
2212
2213 return obj_file_sp->GetImageInfoAddress();
2214#else
2215 Target *target = &GetTarget();
2216 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
2217 Address addr = obj_file->GetImageInfoAddress(target);
2218
2219 if (addr.IsValid())
2220 return addr.GetLoadAddress(target);
2221 return LLDB_INVALID_ADDRESS;
2222#endif
2223#endif // punt on this for now
2224}
2225
2226size_t
2227NativeProcessLinux::UpdateThreads ()
2228{
2229 // The NativeProcessLinux monitoring threads are always up to date
2230 // with respect to thread state and they keep the thread list
2231 // populated properly. All this method needs to do is return the
2232 // thread count.
2233 Mutex::Locker locker (m_threads_mutex);
2234 return m_threads.size ();
2235}
2236
2237bool
2238NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
2239{
2240 arch = m_arch;
2241 return true;
2242}
2243
2244Error
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002245NativeProcessLinux::GetSoftwareBreakpointPCOffset(uint32_t &actual_opcode_size)
Todd Fialaaf245d12014-06-30 21:05:18 +00002246{
2247 // FIXME put this behind a breakpoint protocol class that can be
2248 // set per architecture. Need ARM, MIPS support here.
2249 static const uint8_t g_i386_opcode [] = { 0xCC };
Ulrich Weigandbb00d0b2016-04-14 14:28:34 +00002250 static const uint8_t g_s390x_opcode[] = { 0x00, 0x01 };
Todd Fialaaf245d12014-06-30 21:05:18 +00002251
2252 switch (m_arch.GetMachine ())
2253 {
2254 case llvm::Triple::x86:
2255 case llvm::Triple::x86_64:
2256 actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
2257 return Error ();
2258
Ulrich Weigandbb00d0b2016-04-14 14:28:34 +00002259 case llvm::Triple::systemz:
2260 actual_opcode_size = static_cast<uint32_t> (sizeof(g_s390x_opcode));
2261 return Error ();
2262
Tamas Berghammerff7fd902015-07-03 12:51:30 +00002263 case llvm::Triple::arm:
2264 case llvm::Triple::aarch64:
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00002265 case llvm::Triple::mips64:
2266 case llvm::Triple::mips64el:
Sagar Thakurce815e42015-06-03 10:14:24 +00002267 case llvm::Triple::mips:
2268 case llvm::Triple::mipsel:
Tamas Berghammerff7fd902015-07-03 12:51:30 +00002269 // On these architectures the PC don't get updated for breakpoint hits
Jaydeep Patilc60c9452015-06-23 03:37:08 +00002270 actual_opcode_size = 0;
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00002271 return Error ();
2272
Todd Fialaaf245d12014-06-30 21:05:18 +00002273 default:
2274 assert(false && "CPU type not supported!");
2275 return Error ("CPU type not supported");
2276 }
2277}
2278
2279Error
2280NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
2281{
2282 if (hardware)
2283 return Error ("NativeProcessLinux does not support hardware breakpoints");
2284 else
2285 return SetSoftwareBreakpoint (addr, size);
2286}
2287
2288Error
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002289NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint,
2290 size_t &actual_opcode_size,
2291 const uint8_t *&trap_opcode_bytes)
Todd Fialaaf245d12014-06-30 21:05:18 +00002292{
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002293 // FIXME put this behind a breakpoint protocol class that can be set per
2294 // architecture. Need MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00002295 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Tamas Berghammerbe379e12016-02-16 15:14:36 +00002296 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
2297 // linux kernel does otherwise.
2298 static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 };
Todd Fialaaf245d12014-06-30 21:05:18 +00002299 static const uint8_t g_i386_opcode [] = { 0xCC };
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00002300 static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00002301 static const uint8_t g_mips64el_opcode[] = { 0x0d, 0x00, 0x00, 0x00 };
Ulrich Weigandbb00d0b2016-04-14 14:28:34 +00002302 static const uint8_t g_s390x_opcode[] = { 0x00, 0x01 };
Tamas Berghammerbe379e12016-02-16 15:14:36 +00002303 static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde };
Todd Fialaaf245d12014-06-30 21:05:18 +00002304
2305 switch (m_arch.GetMachine ())
2306 {
Todd Fiala2afc5962014-08-21 16:42:31 +00002307 case llvm::Triple::aarch64:
2308 trap_opcode_bytes = g_aarch64_opcode;
2309 actual_opcode_size = sizeof(g_aarch64_opcode);
2310 return Error ();
2311
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002312 case llvm::Triple::arm:
2313 switch (trap_opcode_size_hint)
2314 {
2315 case 2:
2316 trap_opcode_bytes = g_thumb_breakpoint_opcode;
2317 actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
2318 return Error ();
2319 case 4:
2320 trap_opcode_bytes = g_arm_breakpoint_opcode;
2321 actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
2322 return Error ();
2323 default:
2324 assert(false && "Unrecognised trap opcode size hint!");
2325 return Error ("Unrecognised trap opcode size hint!");
2326 }
2327
Todd Fialaaf245d12014-06-30 21:05:18 +00002328 case llvm::Triple::x86:
2329 case llvm::Triple::x86_64:
2330 trap_opcode_bytes = g_i386_opcode;
2331 actual_opcode_size = sizeof(g_i386_opcode);
2332 return Error ();
2333
Sagar Thakurce815e42015-06-03 10:14:24 +00002334 case llvm::Triple::mips:
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00002335 case llvm::Triple::mips64:
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00002336 trap_opcode_bytes = g_mips64_opcode;
2337 actual_opcode_size = sizeof(g_mips64_opcode);
2338 return Error ();
2339
Sagar Thakurce815e42015-06-03 10:14:24 +00002340 case llvm::Triple::mipsel:
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00002341 case llvm::Triple::mips64el:
2342 trap_opcode_bytes = g_mips64el_opcode;
2343 actual_opcode_size = sizeof(g_mips64el_opcode);
2344 return Error ();
2345
Ulrich Weigandbb00d0b2016-04-14 14:28:34 +00002346 case llvm::Triple::systemz:
2347 trap_opcode_bytes = g_s390x_opcode;
2348 actual_opcode_size = sizeof(g_s390x_opcode);
2349 return Error ();
2350
Todd Fialaaf245d12014-06-30 21:05:18 +00002351 default:
2352 assert(false && "CPU type not supported!");
2353 return Error ("CPU type not supported");
2354 }
2355}
2356
2357#if 0
2358ProcessMessage::CrashReason
2359NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
2360{
2361 ProcessMessage::CrashReason reason;
2362 assert(info->si_signo == SIGSEGV);
2363
2364 reason = ProcessMessage::eInvalidCrashReason;
2365
2366 switch (info->si_code)
2367 {
2368 default:
2369 assert(false && "unexpected si_code for SIGSEGV");
2370 break;
2371 case SI_KERNEL:
2372 // Linux will occasionally send spurious SI_KERNEL codes.
2373 // (this is poorly documented in sigaction)
2374 // One way to get this is via unaligned SIMD loads.
2375 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
2376 break;
2377 case SEGV_MAPERR:
2378 reason = ProcessMessage::eInvalidAddress;
2379 break;
2380 case SEGV_ACCERR:
2381 reason = ProcessMessage::ePrivilegedAddress;
2382 break;
2383 }
2384
2385 return reason;
2386}
2387#endif
2388
2389
2390#if 0
2391ProcessMessage::CrashReason
2392NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
2393{
2394 ProcessMessage::CrashReason reason;
2395 assert(info->si_signo == SIGILL);
2396
2397 reason = ProcessMessage::eInvalidCrashReason;
2398
2399 switch (info->si_code)
2400 {
2401 default:
2402 assert(false && "unexpected si_code for SIGILL");
2403 break;
2404 case ILL_ILLOPC:
2405 reason = ProcessMessage::eIllegalOpcode;
2406 break;
2407 case ILL_ILLOPN:
2408 reason = ProcessMessage::eIllegalOperand;
2409 break;
2410 case ILL_ILLADR:
2411 reason = ProcessMessage::eIllegalAddressingMode;
2412 break;
2413 case ILL_ILLTRP:
2414 reason = ProcessMessage::eIllegalTrap;
2415 break;
2416 case ILL_PRVOPC:
2417 reason = ProcessMessage::ePrivilegedOpcode;
2418 break;
2419 case ILL_PRVREG:
2420 reason = ProcessMessage::ePrivilegedRegister;
2421 break;
2422 case ILL_COPROC:
2423 reason = ProcessMessage::eCoprocessorError;
2424 break;
2425 case ILL_BADSTK:
2426 reason = ProcessMessage::eInternalStackError;
2427 break;
2428 }
2429
2430 return reason;
2431}
2432#endif
2433
2434#if 0
2435ProcessMessage::CrashReason
2436NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
2437{
2438 ProcessMessage::CrashReason reason;
2439 assert(info->si_signo == SIGFPE);
2440
2441 reason = ProcessMessage::eInvalidCrashReason;
2442
2443 switch (info->si_code)
2444 {
2445 default:
2446 assert(false && "unexpected si_code for SIGFPE");
2447 break;
2448 case FPE_INTDIV:
2449 reason = ProcessMessage::eIntegerDivideByZero;
2450 break;
2451 case FPE_INTOVF:
2452 reason = ProcessMessage::eIntegerOverflow;
2453 break;
2454 case FPE_FLTDIV:
2455 reason = ProcessMessage::eFloatDivideByZero;
2456 break;
2457 case FPE_FLTOVF:
2458 reason = ProcessMessage::eFloatOverflow;
2459 break;
2460 case FPE_FLTUND:
2461 reason = ProcessMessage::eFloatUnderflow;
2462 break;
2463 case FPE_FLTRES:
2464 reason = ProcessMessage::eFloatInexactResult;
2465 break;
2466 case FPE_FLTINV:
2467 reason = ProcessMessage::eFloatInvalidOperation;
2468 break;
2469 case FPE_FLTSUB:
2470 reason = ProcessMessage::eFloatSubscriptRange;
2471 break;
2472 }
2473
2474 return reason;
2475}
2476#endif
2477
2478#if 0
2479ProcessMessage::CrashReason
2480NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
2481{
2482 ProcessMessage::CrashReason reason;
2483 assert(info->si_signo == SIGBUS);
2484
2485 reason = ProcessMessage::eInvalidCrashReason;
2486
2487 switch (info->si_code)
2488 {
2489 default:
2490 assert(false && "unexpected si_code for SIGBUS");
2491 break;
2492 case BUS_ADRALN:
2493 reason = ProcessMessage::eIllegalAlignment;
2494 break;
2495 case BUS_ADRERR:
2496 reason = ProcessMessage::eIllegalAddress;
2497 break;
2498 case BUS_OBJERR:
2499 reason = ProcessMessage::eHardwareError;
2500 break;
2501 }
2502
2503 return reason;
2504}
2505#endif
2506
Todd Fialaaf245d12014-06-30 21:05:18 +00002507Error
Chaoren Lin26438d22015-05-05 17:50:53 +00002508NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
Todd Fialaaf245d12014-06-30 21:05:18 +00002509{
Pavel Labathdf7c6992015-06-17 18:38:49 +00002510 if (ProcessVmReadvSupported()) {
2511 // The process_vm_readv path is about 50 times faster than ptrace api. We want to use
2512 // this syscall if it is supported.
2513
2514 const ::pid_t pid = GetID();
2515
2516 struct iovec local_iov, remote_iov;
2517 local_iov.iov_base = buf;
2518 local_iov.iov_len = size;
2519 remote_iov.iov_base = reinterpret_cast<void *>(addr);
2520 remote_iov.iov_len = size;
2521
2522 bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
2523 const bool success = bytes_read == size;
2524
2525 Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2526 if (log)
2527 log->Printf ("NativeProcessLinux::%s using process_vm_readv to read %zd bytes from inferior address 0x%" PRIx64": %s",
2528 __FUNCTION__, size, addr, success ? "Success" : strerror(errno));
2529
2530 if (success)
2531 return Error();
2532 // else
2533 // the call failed for some reason, let's retry the read using ptrace api.
2534 }
2535
Pavel Labath19cbe962015-07-21 13:20:32 +00002536 unsigned char *dst = static_cast<unsigned char*>(buf);
2537 size_t remainder;
2538 long data;
2539
2540 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
2541 if (log)
2542 ProcessPOSIXLog::IncNestLevel();
2543 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
2544 log->Printf ("NativeProcessLinux::%s(%p, %p, %zd, _)", __FUNCTION__, (void*)addr, buf, size);
2545
2546 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
2547 {
2548 Error error = NativeProcessLinux::PtraceWrapper(PTRACE_PEEKDATA, GetID(), (void*)addr, nullptr, 0, &data);
2549 if (error.Fail())
2550 {
2551 if (log)
2552 ProcessPOSIXLog::DecNestLevel();
2553 return error;
2554 }
2555
2556 remainder = size - bytes_read;
2557 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
2558
2559 // Copy the data into our buffer
Mohit K. Bhakkadf6ef1872015-12-23 12:34:58 +00002560 memcpy(dst, &data, remainder);
Pavel Labath19cbe962015-07-21 13:20:32 +00002561
2562 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2563 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
2564 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2565 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
2566 {
2567 uintptr_t print_dst = 0;
2568 // Format bytes from data by moving into print_dst for log output
2569 for (unsigned i = 0; i < remainder; ++i)
2570 print_dst |= (((data >> i*8) & 0xFF) << i*8);
Pavel Labath79203992015-07-23 13:07:37 +00002571 log->Printf ("NativeProcessLinux::%s() [0x%" PRIx64 "]:0x%" PRIx64 " (0x%" PRIx64 ")",
2572 __FUNCTION__, addr, uint64_t(print_dst), uint64_t(data));
Pavel Labath19cbe962015-07-21 13:20:32 +00002573 }
2574 addr += k_ptrace_word_size;
2575 dst += k_ptrace_word_size;
2576 }
2577
2578 if (log)
2579 ProcessPOSIXLog::DecNestLevel();
2580 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00002581}
2582
2583Error
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002584NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
2585{
2586 Error error = ReadMemory(addr, buf, size, bytes_read);
2587 if (error.Fail()) return error;
2588 return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
2589}
2590
2591Error
2592NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written)
Todd Fialaaf245d12014-06-30 21:05:18 +00002593{
Pavel Labath19cbe962015-07-21 13:20:32 +00002594 const unsigned char *src = static_cast<const unsigned char*>(buf);
2595 size_t remainder;
2596 Error error;
2597
2598 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
2599 if (log)
2600 ProcessPOSIXLog::IncNestLevel();
2601 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
Pavel Labath79203992015-07-23 13:07:37 +00002602 log->Printf ("NativeProcessLinux::%s(0x%" PRIx64 ", %p, %zu)", __FUNCTION__, addr, buf, size);
Pavel Labath19cbe962015-07-21 13:20:32 +00002603
2604 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
2605 {
2606 remainder = size - bytes_written;
2607 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
2608
2609 if (remainder == k_ptrace_word_size)
2610 {
2611 unsigned long data = 0;
Mohit K. Bhakkadf6ef1872015-12-23 12:34:58 +00002612 memcpy(&data, src, k_ptrace_word_size);
Pavel Labath19cbe962015-07-21 13:20:32 +00002613
2614 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2615 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
2616 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2617 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
2618 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
2619 (void*)addr, *(const unsigned long*)src, data);
2620
2621 error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(), (void*)addr, (void*)data);
2622 if (error.Fail())
2623 {
2624 if (log)
2625 ProcessPOSIXLog::DecNestLevel();
2626 return error;
2627 }
2628 }
2629 else
2630 {
2631 unsigned char buff[8];
2632 size_t bytes_read;
2633 error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
2634 if (error.Fail())
2635 {
2636 if (log)
2637 ProcessPOSIXLog::DecNestLevel();
2638 return error;
2639 }
2640
2641 memcpy(buff, src, remainder);
2642
2643 size_t bytes_written_rec;
2644 error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
2645 if (error.Fail())
2646 {
2647 if (log)
2648 ProcessPOSIXLog::DecNestLevel();
2649 return error;
2650 }
2651
2652 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2653 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
2654 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2655 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
2656 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
2657 (void*)addr, *(const unsigned long*)src, *(unsigned long*)buff);
2658 }
2659
2660 addr += k_ptrace_word_size;
2661 src += k_ptrace_word_size;
2662 }
2663 if (log)
2664 ProcessPOSIXLog::DecNestLevel();
2665 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002666}
2667
Chaoren Lin97ccc292015-02-03 01:51:12 +00002668Error
Chaoren Lin97ccc292015-02-03 01:51:12 +00002669NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
Todd Fialaaf245d12014-06-30 21:05:18 +00002670{
Pavel Labath19cbe962015-07-21 13:20:32 +00002671 return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
Todd Fialaaf245d12014-06-30 21:05:18 +00002672}
2673
Chaoren Lin97ccc292015-02-03 01:51:12 +00002674Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002675NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
2676{
Pavel Labath19cbe962015-07-21 13:20:32 +00002677 return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
Todd Fialaaf245d12014-06-30 21:05:18 +00002678}
2679
Tamas Berghammerdb264a62015-03-31 09:52:22 +00002680Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002681NativeProcessLinux::Detach(lldb::tid_t tid)
2682{
Chaoren Lin97ccc292015-02-03 01:51:12 +00002683 if (tid == LLDB_INVALID_THREAD_ID)
2684 return Error();
2685
Pavel Labath19cbe962015-07-21 13:20:32 +00002686 return PtraceWrapper(PTRACE_DETACH, tid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002687}
2688
2689bool
Chaoren Lind3173f32015-05-29 19:52:29 +00002690NativeProcessLinux::DupDescriptor(const FileSpec &file_spec, int fd, int flags)
Todd Fialaaf245d12014-06-30 21:05:18 +00002691{
Chaoren Lind3173f32015-05-29 19:52:29 +00002692 int target_fd = open(file_spec.GetCString(), flags, 0666);
Todd Fialaaf245d12014-06-30 21:05:18 +00002693
2694 if (target_fd == -1)
2695 return false;
2696
Pavel Labath493c3a12015-02-04 10:36:57 +00002697 if (dup2(target_fd, fd) == -1)
2698 return false;
2699
2700 return (close(target_fd) == -1) ? false : true;
Todd Fialaaf245d12014-06-30 21:05:18 +00002701}
2702
Todd Fialaaf245d12014-06-30 21:05:18 +00002703bool
2704NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
2705{
2706 for (auto thread_sp : m_threads)
2707 {
2708 assert (thread_sp && "thread list should not contain NULL threads");
2709 if (thread_sp->GetID () == thread_id)
2710 {
2711 // We have this thread.
2712 return true;
2713 }
2714 }
2715
2716 // We don't have this thread.
2717 return false;
2718}
2719
Todd Fialaaf245d12014-06-30 21:05:18 +00002720bool
2721NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
2722{
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002723 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
2724
2725 if (log)
2726 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, thread_id);
2727
2728 bool found = false;
2729
Todd Fialaaf245d12014-06-30 21:05:18 +00002730 Mutex::Locker locker (m_threads_mutex);
2731 for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
2732 {
2733 if (*it && ((*it)->GetID () == thread_id))
2734 {
2735 m_threads.erase (it);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002736 found = true;
2737 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00002738 }
2739 }
2740
Pavel Labath0e1d7292015-08-20 09:06:12 +00002741 SignalIfAllThreadsStopped();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002742
2743 return found;
Todd Fialaaf245d12014-06-30 21:05:18 +00002744}
2745
Pavel Labathf9077782015-08-21 09:13:53 +00002746NativeThreadLinuxSP
Todd Fialaaf245d12014-06-30 21:05:18 +00002747NativeProcessLinux::AddThread (lldb::tid_t thread_id)
2748{
2749 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
2750
2751 Mutex::Locker locker (m_threads_mutex);
2752
2753 if (log)
2754 {
2755 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
2756 __FUNCTION__,
2757 GetID (),
2758 thread_id);
2759 }
2760
2761 assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
2762
2763 // If this is the first thread, save it as the current thread
2764 if (m_threads.empty ())
2765 SetCurrentThreadID (thread_id);
2766
Pavel Labathf9077782015-08-21 09:13:53 +00002767 auto thread_sp = std::make_shared<NativeThreadLinux>(this, thread_id);
Todd Fialaaf245d12014-06-30 21:05:18 +00002768 m_threads.push_back (thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00002769 return thread_sp;
2770}
2771
Todd Fialaaf245d12014-06-30 21:05:18 +00002772Error
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002773NativeProcessLinux::FixupBreakpointPCAsNeeded(NativeThreadLinux &thread)
Todd Fialaaf245d12014-06-30 21:05:18 +00002774{
Todd Fiala75f47c32014-10-11 21:42:09 +00002775 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Todd Fialaaf245d12014-06-30 21:05:18 +00002776
2777 Error error;
2778
Todd Fialaaf245d12014-06-30 21:05:18 +00002779 // Find out the size of a breakpoint (might depend on where we are in the code).
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002780 NativeRegisterContextSP context_sp = thread.GetRegisterContext();
Todd Fialaaf245d12014-06-30 21:05:18 +00002781 if (!context_sp)
2782 {
2783 error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
2784 if (log)
2785 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
2786 return error;
2787 }
2788
2789 uint32_t breakpoint_size = 0;
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002790 error = GetSoftwareBreakpointPCOffset(breakpoint_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00002791 if (error.Fail ())
2792 {
2793 if (log)
2794 log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
2795 return error;
2796 }
2797 else
2798 {
2799 if (log)
2800 log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
2801 }
2802
2803 // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
Jaydeep Patilc60c9452015-06-23 03:37:08 +00002804 const lldb::addr_t initial_pc_addr = context_sp->GetPCfromBreakpointLocation ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002805 lldb::addr_t breakpoint_addr = initial_pc_addr;
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002806 if (breakpoint_size > 0)
Todd Fialaaf245d12014-06-30 21:05:18 +00002807 {
2808 // Do not allow breakpoint probe to wrap around.
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002809 if (breakpoint_addr >= breakpoint_size)
2810 breakpoint_addr -= breakpoint_size;
Todd Fialaaf245d12014-06-30 21:05:18 +00002811 }
2812
2813 // Check if we stopped because of a breakpoint.
2814 NativeBreakpointSP breakpoint_sp;
2815 error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
2816 if (!error.Success () || !breakpoint_sp)
2817 {
2818 // We didn't find one at a software probe location. Nothing to do.
2819 if (log)
2820 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
2821 return Error ();
2822 }
2823
2824 // If the breakpoint is not a software breakpoint, nothing to do.
2825 if (!breakpoint_sp->IsSoftwareBreakpoint ())
2826 {
2827 if (log)
2828 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
2829 return Error ();
2830 }
2831
2832 //
2833 // We have a software breakpoint and need to adjust the PC.
2834 //
2835
2836 // Sanity check.
2837 if (breakpoint_size == 0)
2838 {
2839 // Nothing to do! How did we get here?
2840 if (log)
2841 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);
2842 return Error ();
2843 }
2844
2845 // Change the program counter.
2846 if (log)
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002847 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 +00002848
2849 error = context_sp->SetPC (breakpoint_addr);
2850 if (error.Fail ())
2851 {
2852 if (log)
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002853 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 +00002854 return error;
2855 }
2856
2857 return error;
2858}
Chaoren Linfa03ad22015-02-03 01:50:42 +00002859
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00002860Error
2861NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec)
2862{
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00002863 FileSpec module_file_spec(module_path, true);
2864
Pavel Labath162fb8e2015-07-23 14:47:33 +00002865 bool found = false;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00002866 file_spec.Clear();
Pavel Labath162fb8e2015-07-23 14:47:33 +00002867 ProcFileReader::ProcessLineByLine(GetID(), "maps",
2868 [&] (const std::string &line)
2869 {
2870 SmallVector<StringRef, 16> columns;
2871 StringRef(line).split(columns, " ", -1, false);
2872 if (columns.size() < 6)
2873 return true; // continue searching
2874
2875 FileSpec this_file_spec(columns[5].str().c_str(), false);
2876 if (this_file_spec.GetFilename() != module_file_spec.GetFilename())
2877 return true; // continue searching
2878
2879 file_spec = this_file_spec;
2880 found = true;
2881 return false; // we are done
2882 });
2883
2884 if (! found)
2885 return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
2886 module_file_spec.GetFilename().AsCString(), GetID());
2887
2888 return Error();
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00002889}
Pavel Labathc0765592015-05-06 10:46:34 +00002890
Pavel Labath5eb721e2015-05-07 08:30:31 +00002891Error
Tamas Berghammer783bfc82015-06-18 20:43:56 +00002892NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef& file_name, lldb::addr_t& load_addr)
2893{
2894 load_addr = LLDB_INVALID_ADDRESS;
2895 Error error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
2896 [&] (const std::string &line) -> bool
2897 {
2898 StringRef maps_row(line);
2899
2900 SmallVector<StringRef, 16> maps_columns;
2901 maps_row.split(maps_columns, StringRef(" "), -1, false);
2902
2903 if (maps_columns.size() < 6)
2904 {
2905 // Return true to continue reading the proc file
2906 return true;
2907 }
2908
2909 if (maps_columns[5] == file_name)
2910 {
2911 StringExtractor addr_extractor(maps_columns[0].str().c_str());
2912 load_addr = addr_extractor.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2913
2914 // Return false to stop reading the proc file further
2915 return false;
2916 }
2917
2918 // Return true to continue reading the proc file
2919 return true;
2920 });
2921 return error;
2922}
2923
Pavel Labathf9077782015-08-21 09:13:53 +00002924NativeThreadLinuxSP
2925NativeProcessLinux::GetThreadByID(lldb::tid_t tid)
2926{
2927 return std::static_pointer_cast<NativeThreadLinux>(NativeProcessProtocol::GetThreadByID(tid));
2928}
2929
Tamas Berghammer783bfc82015-06-18 20:43:56 +00002930Error
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002931NativeProcessLinux::ResumeThread(NativeThreadLinux &thread, lldb::StateType state, int signo)
Pavel Labathc0765592015-05-06 10:46:34 +00002932{
Pavel Labath5eb721e2015-05-07 08:30:31 +00002933 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002934
2935 if (log)
Pavel Labath0e1d7292015-08-20 09:06:12 +00002936 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")",
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002937 __FUNCTION__, thread.GetID());
Pavel Labath5eb721e2015-05-07 08:30:31 +00002938
Pavel Labathc0765592015-05-06 10:46:34 +00002939 // Before we do the resume below, first check if we have a pending
Pavel Labath108c3252015-05-12 09:03:18 +00002940 // stop notification that is currently waiting for
Pavel Labath0e1d7292015-08-20 09:06:12 +00002941 // all threads to stop. This is potentially a buggy situation since
Pavel Labathc0765592015-05-06 10:46:34 +00002942 // we're ostensibly waiting for threads to stop before we send out the
2943 // pending notification, and here we are resuming one before we send
2944 // out the pending stop notification.
Pavel Labath0e1d7292015-08-20 09:06:12 +00002945 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID && log)
Pavel Labathc0765592015-05-06 10:46:34 +00002946 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002947 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 +00002948 }
2949
2950 // Request a resume. We expect this to be synchronous and the system
2951 // to reflect it is running after this completes.
Pavel Labath0e1d7292015-08-20 09:06:12 +00002952 switch (state)
Pavel Labathc0765592015-05-06 10:46:34 +00002953 {
Pavel Labath0e1d7292015-08-20 09:06:12 +00002954 case eStateRunning:
2955 {
Pavel Labath605b51b2016-02-23 13:56:30 +00002956 const auto resume_result = thread.Resume(signo);
Pavel Labath0e1d7292015-08-20 09:06:12 +00002957 if (resume_result.Success())
2958 SetState(eStateRunning, true);
2959 return resume_result;
Pavel Labathc0765592015-05-06 10:46:34 +00002960 }
Pavel Labath0e1d7292015-08-20 09:06:12 +00002961 case eStateStepping:
2962 {
Pavel Labath605b51b2016-02-23 13:56:30 +00002963 const auto step_result = thread.SingleStep(signo);
Pavel Labath0e1d7292015-08-20 09:06:12 +00002964 if (step_result.Success())
2965 SetState(eStateRunning, true);
2966 return step_result;
2967 }
2968 default:
2969 if (log)
2970 log->Printf("NativeProcessLinux::%s Unhandled state %s.",
2971 __FUNCTION__, StateAsCString(state));
2972 llvm_unreachable("Unhandled state for resume");
2973 }
Pavel Labathc0765592015-05-06 10:46:34 +00002974}
2975
2976//===----------------------------------------------------------------------===//
2977
2978void
Pavel Labath337f3eb2015-05-08 08:57:45 +00002979NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid)
Pavel Labathc0765592015-05-06 10:46:34 +00002980{
Pavel Labath5eb721e2015-05-07 08:30:31 +00002981 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00002982
Pavel Labath5eb721e2015-05-07 08:30:31 +00002983 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00002984 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00002985 log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ")",
Pavel Labathc0765592015-05-06 10:46:34 +00002986 __FUNCTION__, triggering_tid);
2987 }
2988
Pavel Labath0e1d7292015-08-20 09:06:12 +00002989 m_pending_notification_tid = triggering_tid;
2990
2991 // Request a stop for all the thread stops that need to be stopped
2992 // and are not already known to be stopped.
2993 for (const auto &thread_sp: m_threads)
2994 {
2995 if (StateIsRunningState(thread_sp->GetState()))
2996 static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
2997 }
2998
2999 SignalIfAllThreadsStopped();
Pavel Labathc0765592015-05-06 10:46:34 +00003000
Pavel Labath5eb721e2015-05-07 08:30:31 +00003001 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00003002 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00003003 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00003004 }
3005}
3006
3007void
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003008NativeProcessLinux::SignalIfAllThreadsStopped()
Pavel Labathc0765592015-05-06 10:46:34 +00003009{
Pavel Labath0e1d7292015-08-20 09:06:12 +00003010 if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
3011 return; // No pending notification. Nothing to do.
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003012
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003013 for (const auto &thread_sp: m_threads)
Pavel Labathc0765592015-05-06 10:46:34 +00003014 {
Pavel Labath0e1d7292015-08-20 09:06:12 +00003015 if (StateIsRunningState(thread_sp->GetState()))
3016 return; // Some threads are still running. Don't signal yet.
Pavel Labathc0765592015-05-06 10:46:34 +00003017 }
3018
Pavel Labath0e1d7292015-08-20 09:06:12 +00003019 // We have a pending notification and all threads have stopped.
3020 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
Pavel Labathc0765592015-05-06 10:46:34 +00003021
Pavel Labath0e1d7292015-08-20 09:06:12 +00003022 // Clear any temporary breakpoints we used to implement software single stepping.
3023 for (const auto &thread_info: m_threads_stepping_with_breakpoint)
Pavel Labathc0765592015-05-06 10:46:34 +00003024 {
Pavel Labath0e1d7292015-08-20 09:06:12 +00003025 Error error = RemoveBreakpoint (thread_info.second);
3026 if (error.Fail())
3027 if (log)
3028 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " remove stepping breakpoint: %s",
3029 __FUNCTION__, thread_info.first, error.AsCString());
Pavel Labathc0765592015-05-06 10:46:34 +00003030 }
Pavel Labath0e1d7292015-08-20 09:06:12 +00003031 m_threads_stepping_with_breakpoint.clear();
Pavel Labathc0765592015-05-06 10:46:34 +00003032
Pavel Labath0e1d7292015-08-20 09:06:12 +00003033 // Notify the delegate about the stop
3034 SetCurrentThreadID(m_pending_notification_tid);
3035 SetState(StateType::eStateStopped, true);
3036 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
Pavel Labathc0765592015-05-06 10:46:34 +00003037}
3038
3039void
Pavel Labathf9077782015-08-21 09:13:53 +00003040NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread)
Pavel Labathc0765592015-05-06 10:46:34 +00003041{
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003042 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3043
3044 if (log)
Pavel Labathf9077782015-08-21 09:13:53 +00003045 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, thread.GetID());
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003046
Pavel Labathf9077782015-08-21 09:13:53 +00003047 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID && StateIsRunningState(thread.GetState()))
Pavel Labathc0765592015-05-06 10:46:34 +00003048 {
3049 // We will need to wait for this new thread to stop as well before firing the
3050 // notification.
Pavel Labathf9077782015-08-21 09:13:53 +00003051 thread.RequestStop();
Pavel Labathc0765592015-05-06 10:46:34 +00003052 }
3053}
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003054
Pavel Labath19cbe962015-07-21 13:20:32 +00003055void
3056NativeProcessLinux::SigchldHandler()
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003057{
Pavel Labath19cbe962015-07-21 13:20:32 +00003058 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3059 // Process all pending waitpid notifications.
3060 while (true)
3061 {
3062 int status = -1;
3063 ::pid_t wait_pid = waitpid(-1, &status, __WALL | __WNOTHREAD | WNOHANG);
3064
3065 if (wait_pid == 0)
3066 break; // We are done.
3067
3068 if (wait_pid == -1)
3069 {
3070 if (errno == EINTR)
3071 continue;
3072
3073 Error error(errno, eErrorTypePOSIX);
3074 if (log)
3075 log->Printf("NativeProcessLinux::%s waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG) failed: %s",
3076 __FUNCTION__, error.AsCString());
3077 break;
3078 }
3079
3080 bool exited = false;
3081 int signal = 0;
3082 int exit_status = 0;
3083 const char *status_cstr = nullptr;
3084 if (WIFSTOPPED(status))
3085 {
3086 signal = WSTOPSIG(status);
3087 status_cstr = "STOPPED";
3088 }
3089 else if (WIFEXITED(status))
3090 {
3091 exit_status = WEXITSTATUS(status);
3092 status_cstr = "EXITED";
3093 exited = true;
3094 }
3095 else if (WIFSIGNALED(status))
3096 {
3097 signal = WTERMSIG(status);
3098 status_cstr = "SIGNALED";
Omair Javaiddee4a862015-08-19 10:44:16 +00003099 if (wait_pid == static_cast< ::pid_t>(GetID())) {
Pavel Labath19cbe962015-07-21 13:20:32 +00003100 exited = true;
3101 exit_status = -1;
3102 }
3103 }
3104 else
3105 status_cstr = "(\?\?\?)";
3106
3107 if (log)
3108 log->Printf("NativeProcessLinux::%s: waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG)"
3109 "=> pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
3110 __FUNCTION__, wait_pid, status, status_cstr, signal, exit_status);
3111
3112 MonitorCallback (wait_pid, exited, signal, exit_status);
3113 }
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003114}
3115
3116// Wrapper for ptrace to catch errors and log calls.
3117// 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 +00003118Error
3119NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, long *result)
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003120{
Pavel Labath4a9babb2015-06-30 17:04:49 +00003121 Error error;
3122 long int ret;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003123
3124 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
3125
3126 PtraceDisplayBytes(req, data, data_size);
3127
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003128 errno = 0;
3129 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Pavel Labath4a9babb2015-06-30 17:04:49 +00003130 ret = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003131 else
Pavel Labath4a9babb2015-06-30 17:04:49 +00003132 ret = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003133
Pavel Labath4a9babb2015-06-30 17:04:49 +00003134 if (ret == -1)
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003135 error.SetErrorToErrno();
3136
Pavel Labath4a9babb2015-06-30 17:04:49 +00003137 if (result)
3138 *result = ret;
3139
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003140 if (log)
Pavel Labath4a9babb2015-06-30 17:04:49 +00003141 log->Printf("ptrace(%d, %" PRIu64 ", %p, %p, %zu)=%lX", req, pid, addr, data, data_size, ret);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003142
3143 PtraceDisplayBytes(req, data, data_size);
3144
3145 if (log && error.GetError() != 0)
3146 {
3147 const char* str;
3148 switch (error.GetError())
3149 {
3150 case ESRCH: str = "ESRCH"; break;
3151 case EINVAL: str = "EINVAL"; break;
3152 case EBUSY: str = "EBUSY"; break;
3153 case EPERM: str = "EPERM"; break;
3154 default: str = error.AsCString();
3155 }
3156 log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
3157 }
3158
Pavel Labath4a9babb2015-06-30 17:04:49 +00003159 return error;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003160}