blob: a90e0af506988be2d982b29eb036f5616515a6b1 [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"
61#include "lldb/Host/linux/Signalfd.h"
Pavel Labathdf7c6992015-06-17 18:38:49 +000062#include "lldb/Host/linux/Uio.h"
Vince Harron8b335672015-05-12 01:10:56 +000063#include "lldb/Host/android/Android.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000064
Todd Fiala0bce1b62014-08-17 00:10:50 +000065#define LLDB_PERSONALITY_GET_CURRENT_SETTINGS 0xffffffff
Todd Fialaaf245d12014-06-30 21:05:18 +000066
67// Support hardware breakpoints in case it has not been defined
68#ifndef TRAP_HWBKPT
69 #define TRAP_HWBKPT 4
70#endif
71
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000072using namespace lldb;
73using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000074using namespace lldb_private::process_linux;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000075using namespace llvm;
76
Todd Fialaaf245d12014-06-30 21:05:18 +000077// Private bits we only need internally.
Pavel Labathdf7c6992015-06-17 18:38:49 +000078
79static bool ProcessVmReadvSupported()
80{
81 static bool is_supported;
82 static std::once_flag flag;
83
84 std::call_once(flag, [] {
85 Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
86
87 uint32_t source = 0x47424742;
88 uint32_t dest = 0;
89
90 struct iovec local, remote;
91 remote.iov_base = &source;
92 local.iov_base = &dest;
93 remote.iov_len = local.iov_len = sizeof source;
94
95 // We shall try if cross-process-memory reads work by attempting to read a value from our own process.
96 ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
97 is_supported = (res == sizeof(source) && source == dest);
98 if (log)
99 {
100 if (is_supported)
101 log->Printf("%s: Detected kernel support for process_vm_readv syscall. Fast memory reads enabled.",
102 __FUNCTION__);
103 else
104 log->Printf("%s: syscall process_vm_readv failed (error: %s). Fast memory reads disabled.",
105 __FUNCTION__, strerror(errno));
106 }
107 });
108
109 return is_supported;
110}
111
Todd Fialaaf245d12014-06-30 21:05:18 +0000112namespace
113{
Todd Fialaaf245d12014-06-30 21:05:18 +0000114 Error
115 ResolveProcessArchitecture (lldb::pid_t pid, Platform &platform, ArchSpec &arch)
116 {
117 // Grab process info for the running process.
118 ProcessInstanceInfo process_info;
119 if (!platform.GetProcessInfo (pid, process_info))
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000120 return Error("failed to get process info");
Todd Fialaaf245d12014-06-30 21:05:18 +0000121
122 // Resolve the executable module.
123 ModuleSP exe_module_sp;
Chaoren Line56f6dc2015-03-01 04:31:16 +0000124 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Todd Fialaaf245d12014-06-30 21:05:18 +0000125 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths ());
126 Error error = platform.ResolveExecutable(
Oleksiy Vyalov54539332014-11-17 22:42:28 +0000127 exe_module_spec,
Todd Fialaaf245d12014-06-30 21:05:18 +0000128 exe_module_sp,
129 executable_search_paths.GetSize () ? &executable_search_paths : NULL);
130
131 if (!error.Success ())
132 return error;
133
134 // Check if we've got our architecture from the exe_module.
135 arch = exe_module_sp->GetArchitecture ();
136 if (arch.IsValid ())
137 return Error();
138 else
139 return Error("failed to retrieve a valid architecture from the exe module");
140 }
141
142 void
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000143 DisplayBytes (StreamString &s, void *bytes, uint32_t count)
Todd Fialaaf245d12014-06-30 21:05:18 +0000144 {
145 uint8_t *ptr = (uint8_t *)bytes;
146 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
147 for(uint32_t i=0; i<loop_count; i++)
148 {
149 s.Printf ("[%x]", *ptr);
150 ptr++;
151 }
152 }
153
154 void
155 PtraceDisplayBytes(int &req, void *data, size_t data_size)
156 {
157 StreamString buf;
158 Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
159 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
160
161 if (verbose_log)
162 {
163 switch(req)
164 {
165 case PTRACE_POKETEXT:
166 {
167 DisplayBytes(buf, &data, 8);
168 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
169 break;
170 }
171 case PTRACE_POKEDATA:
172 {
173 DisplayBytes(buf, &data, 8);
174 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
175 break;
176 }
177 case PTRACE_POKEUSER:
178 {
179 DisplayBytes(buf, &data, 8);
180 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
181 break;
182 }
183 case PTRACE_SETREGS:
184 {
185 DisplayBytes(buf, data, data_size);
186 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
187 break;
188 }
189 case PTRACE_SETFPREGS:
190 {
191 DisplayBytes(buf, data, data_size);
192 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
193 break;
194 }
195 case PTRACE_SETSIGINFO:
196 {
197 DisplayBytes(buf, data, sizeof(siginfo_t));
198 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
199 break;
200 }
201 case PTRACE_SETREGSET:
202 {
203 // Extract iov_base from data, which is a pointer to the struct IOVEC
204 DisplayBytes(buf, *(void **)data, data_size);
205 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
206 break;
207 }
208 default:
209 {
210 }
211 }
212 }
213 }
214
Pavel Labath19cbe962015-07-21 13:20:32 +0000215 static constexpr unsigned k_ptrace_word_size = sizeof(void*);
216 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 +0000217} // end of anonymous namespace
218
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000219// Simple helper function to ensure flags are enabled on the given file
220// descriptor.
221static Error
222EnsureFDFlags(int fd, int flags)
223{
224 Error error;
225
226 int status = fcntl(fd, F_GETFL);
227 if (status == -1)
228 {
229 error.SetErrorToErrno();
230 return error;
231 }
232
233 if (fcntl(fd, F_SETFL, status | flags) == -1)
234 {
235 error.SetErrorToErrno();
236 return error;
237 }
238
239 return error;
240}
241
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000242NativeProcessLinux::LaunchArgs::LaunchArgs(Module *module,
Todd Fialaaf245d12014-06-30 21:05:18 +0000243 char const **argv,
244 char const **envp,
Chaoren Lind3173f32015-05-29 19:52:29 +0000245 const FileSpec &stdin_file_spec,
246 const FileSpec &stdout_file_spec,
247 const FileSpec &stderr_file_spec,
248 const FileSpec &working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000249 const ProcessLaunchInfo &launch_info)
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000250 : m_module(module),
Todd Fialaaf245d12014-06-30 21:05:18 +0000251 m_argv(argv),
252 m_envp(envp),
Chaoren Lind3173f32015-05-29 19:52:29 +0000253 m_stdin_file_spec(stdin_file_spec),
254 m_stdout_file_spec(stdout_file_spec),
255 m_stderr_file_spec(stderr_file_spec),
Todd Fiala0bce1b62014-08-17 00:10:50 +0000256 m_working_dir(working_dir),
257 m_launch_info(launch_info)
258{
259}
Todd Fialaaf245d12014-06-30 21:05:18 +0000260
261NativeProcessLinux::LaunchArgs::~LaunchArgs()
262{ }
263
Todd Fialaaf245d12014-06-30 21:05:18 +0000264// -----------------------------------------------------------------------------
265// Public Static Methods
266// -----------------------------------------------------------------------------
267
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000268Error
Pavel Labathd5b310f2015-07-09 11:51:11 +0000269NativeProcessProtocol::Launch (
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000270 ProcessLaunchInfo &launch_info,
271 NativeProcessProtocol::NativeDelegate &native_delegate,
Pavel Labath19cbe962015-07-21 13:20:32 +0000272 MainLoop &mainloop,
Todd Fialaaf245d12014-06-30 21:05:18 +0000273 NativeProcessProtocolSP &native_process_sp)
274{
275 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
276
Pavel Labathd5b310f2015-07-09 11:51:11 +0000277 lldb::ModuleSP exe_module_sp;
278 PlatformSP platform_sp (Platform::GetHostPlatform ());
279 Error error = platform_sp->ResolveExecutable(
280 ModuleSpec(launch_info.GetExecutableFile(), launch_info.GetArchitecture()),
281 exe_module_sp,
282 nullptr);
283
284 if (! error.Success())
285 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000286
287 // Verify the working directory is valid if one was specified.
Chaoren Lind3173f32015-05-29 19:52:29 +0000288 FileSpec working_dir{launch_info.GetWorkingDirectory()};
289 if (working_dir &&
290 (!working_dir.ResolvePath() ||
291 working_dir.GetFileType() != FileSpec::eFileTypeDirectory))
Todd Fialaaf245d12014-06-30 21:05:18 +0000292 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000293 error.SetErrorStringWithFormat ("No such file or directory: %s",
294 working_dir.GetCString());
295 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000296 }
297
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000298 const FileAction *file_action;
Todd Fialaaf245d12014-06-30 21:05:18 +0000299
Chaoren Lind3173f32015-05-29 19:52:29 +0000300 // Default of empty will mean to use existing open file descriptors.
301 FileSpec stdin_file_spec{};
302 FileSpec stdout_file_spec{};
303 FileSpec stderr_file_spec{};
Todd Fialaaf245d12014-06-30 21:05:18 +0000304
305 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +0000306 if (file_action)
Chaoren Lind3173f32015-05-29 19:52:29 +0000307 stdin_file_spec = file_action->GetFileSpec();
Todd Fialaaf245d12014-06-30 21:05:18 +0000308
309 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +0000310 if (file_action)
Chaoren Lind3173f32015-05-29 19:52:29 +0000311 stdout_file_spec = file_action->GetFileSpec();
Todd Fialaaf245d12014-06-30 21:05:18 +0000312
313 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +0000314 if (file_action)
Chaoren Lind3173f32015-05-29 19:52:29 +0000315 stderr_file_spec = file_action->GetFileSpec();
Todd Fiala75f47c32014-10-11 21:42:09 +0000316
317 if (log)
318 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000319 if (stdin_file_spec)
320 log->Printf ("NativeProcessLinux::%s setting STDIN to '%s'",
321 __FUNCTION__, stdin_file_spec.GetCString());
Todd Fiala75f47c32014-10-11 21:42:09 +0000322 else
323 log->Printf ("NativeProcessLinux::%s leaving STDIN as is", __FUNCTION__);
324
Chaoren Lind3173f32015-05-29 19:52:29 +0000325 if (stdout_file_spec)
326 log->Printf ("NativeProcessLinux::%s setting STDOUT to '%s'",
327 __FUNCTION__, stdout_file_spec.GetCString());
Todd Fiala75f47c32014-10-11 21:42:09 +0000328 else
329 log->Printf ("NativeProcessLinux::%s leaving STDOUT as is", __FUNCTION__);
330
Chaoren Lind3173f32015-05-29 19:52:29 +0000331 if (stderr_file_spec)
332 log->Printf ("NativeProcessLinux::%s setting STDERR to '%s'",
333 __FUNCTION__, stderr_file_spec.GetCString());
Todd Fiala75f47c32014-10-11 21:42:09 +0000334 else
335 log->Printf ("NativeProcessLinux::%s leaving STDERR as is", __FUNCTION__);
336 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000337
338 // Create the NativeProcessLinux in launch mode.
339 native_process_sp.reset (new NativeProcessLinux ());
340
341 if (log)
342 {
343 int i = 0;
344 for (const char **args = launch_info.GetArguments ().GetConstArgumentVector (); *args; ++args, ++i)
345 {
346 log->Printf ("NativeProcessLinux::%s arg %d: \"%s\"", __FUNCTION__, i, *args ? *args : "nullptr");
347 ++i;
348 }
349 }
350
351 if (!native_process_sp->RegisterNativeDelegate (native_delegate))
352 {
353 native_process_sp.reset ();
354 error.SetErrorStringWithFormat ("failed to register the native delegate");
355 return error;
356 }
357
Tamas Berghammercb84eeb2015-03-17 15:05:31 +0000358 std::static_pointer_cast<NativeProcessLinux> (native_process_sp)->LaunchInferior (
Pavel Labath19cbe962015-07-21 13:20:32 +0000359 mainloop,
Pavel Labathd5b310f2015-07-09 11:51:11 +0000360 exe_module_sp.get(),
Todd Fialaaf245d12014-06-30 21:05:18 +0000361 launch_info.GetArguments ().GetConstArgumentVector (),
362 launch_info.GetEnvironmentEntries ().GetConstArgumentVector (),
Chaoren Lind3173f32015-05-29 19:52:29 +0000363 stdin_file_spec,
364 stdout_file_spec,
365 stderr_file_spec,
Todd Fialaaf245d12014-06-30 21:05:18 +0000366 working_dir,
Todd Fiala0bce1b62014-08-17 00:10:50 +0000367 launch_info,
Todd Fialaaf245d12014-06-30 21:05:18 +0000368 error);
369
370 if (error.Fail ())
371 {
372 native_process_sp.reset ();
373 if (log)
374 log->Printf ("NativeProcessLinux::%s failed to launch process: %s", __FUNCTION__, error.AsCString ());
375 return error;
376 }
377
378 launch_info.SetProcessID (native_process_sp->GetID ());
379
380 return error;
381}
382
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000383Error
Pavel Labathd5b310f2015-07-09 11:51:11 +0000384NativeProcessProtocol::Attach (
Todd Fialaaf245d12014-06-30 21:05:18 +0000385 lldb::pid_t pid,
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000386 NativeProcessProtocol::NativeDelegate &native_delegate,
Pavel Labath19cbe962015-07-21 13:20:32 +0000387 MainLoop &mainloop,
Todd Fialaaf245d12014-06-30 21:05:18 +0000388 NativeProcessProtocolSP &native_process_sp)
389{
390 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
391 if (log && log->GetMask ().Test (POSIX_LOG_VERBOSE))
392 log->Printf ("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
393
394 // Grab the current platform architecture. This should be Linux,
395 // since this code is only intended to run on a Linux host.
Greg Clayton615eb7e2014-09-19 20:11:50 +0000396 PlatformSP platform_sp (Platform::GetHostPlatform ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000397 if (!platform_sp)
398 return Error("failed to get a valid default platform");
399
400 // Retrieve the architecture for the running process.
401 ArchSpec process_arch;
402 Error error = ResolveProcessArchitecture (pid, *platform_sp.get (), process_arch);
403 if (!error.Success ())
404 return error;
405
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +0000406 std::shared_ptr<NativeProcessLinux> native_process_linux_sp (new NativeProcessLinux ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000407
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +0000408 if (!native_process_linux_sp->RegisterNativeDelegate (native_delegate))
Todd Fialaaf245d12014-06-30 21:05:18 +0000409 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000410 error.SetErrorStringWithFormat ("failed to register the native delegate");
411 return error;
412 }
413
Pavel Labath19cbe962015-07-21 13:20:32 +0000414 native_process_linux_sp->AttachToInferior (mainloop, pid, error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000415 if (!error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +0000416 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000417
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +0000418 native_process_sp = native_process_linux_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +0000419 return error;
420}
421
422// -----------------------------------------------------------------------------
423// Public Instance Methods
424// -----------------------------------------------------------------------------
425
426NativeProcessLinux::NativeProcessLinux () :
427 NativeProcessProtocol (LLDB_INVALID_PROCESS_ID),
428 m_arch (),
Todd Fialaaf245d12014-06-30 21:05:18 +0000429 m_supports_mem_region (eLazyBoolCalculate),
430 m_mem_region_cache (),
Pavel Labath0e1d7292015-08-20 09:06:12 +0000431 m_mem_region_cache_mutex(),
432 m_pending_notification_tid(LLDB_INVALID_THREAD_ID)
Todd Fialaaf245d12014-06-30 21:05:18 +0000433{
434}
435
Todd Fialaaf245d12014-06-30 21:05:18 +0000436void
437NativeProcessLinux::LaunchInferior (
Pavel Labath19cbe962015-07-21 13:20:32 +0000438 MainLoop &mainloop,
Todd Fialaaf245d12014-06-30 21:05:18 +0000439 Module *module,
440 const char *argv[],
441 const char *envp[],
Chaoren Lind3173f32015-05-29 19:52:29 +0000442 const FileSpec &stdin_file_spec,
443 const FileSpec &stdout_file_spec,
444 const FileSpec &stderr_file_spec,
445 const FileSpec &working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000446 const ProcessLaunchInfo &launch_info,
447 Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000448{
Pavel Labath19cbe962015-07-21 13:20:32 +0000449 m_sigchld_handle = mainloop.RegisterSignal(SIGCHLD,
450 [this] (MainLoopBase &) { SigchldHandler(); }, error);
451 if (! m_sigchld_handle)
452 return;
453
Todd Fialaaf245d12014-06-30 21:05:18 +0000454 if (module)
455 m_arch = module->GetArchitecture ();
456
Chaoren Linfa03ad22015-02-03 01:50:42 +0000457 SetState (eStateLaunching);
Todd Fialaaf245d12014-06-30 21:05:18 +0000458
459 std::unique_ptr<LaunchArgs> args(
Chaoren Lind3173f32015-05-29 19:52:29 +0000460 new LaunchArgs(module, argv, envp,
461 stdin_file_spec,
462 stdout_file_spec,
463 stderr_file_spec,
464 working_dir,
465 launch_info));
Todd Fialaaf245d12014-06-30 21:05:18 +0000466
Pavel Labath19cbe962015-07-21 13:20:32 +0000467 Launch(args.get(), error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000468}
469
470void
Pavel Labath19cbe962015-07-21 13:20:32 +0000471NativeProcessLinux::AttachToInferior (MainLoop &mainloop, lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000472{
473 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
474 if (log)
475 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
476
Pavel Labath19cbe962015-07-21 13:20:32 +0000477 m_sigchld_handle = mainloop.RegisterSignal(SIGCHLD,
478 [this] (MainLoopBase &) { SigchldHandler(); }, error);
479 if (! m_sigchld_handle)
480 return;
481
Todd Fialaaf245d12014-06-30 21:05:18 +0000482 // We can use the Host for everything except the ResolveExecutable portion.
Greg Clayton615eb7e2014-09-19 20:11:50 +0000483 PlatformSP platform_sp = Platform::GetHostPlatform ();
Todd Fialaaf245d12014-06-30 21:05:18 +0000484 if (!platform_sp)
485 {
486 if (log)
487 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): no default platform set", __FUNCTION__, pid);
488 error.SetErrorString ("no default platform available");
Shawn Best50d60be2014-11-11 00:28:52 +0000489 return;
Todd Fialaaf245d12014-06-30 21:05:18 +0000490 }
491
492 // Gather info about the process.
493 ProcessInstanceInfo process_info;
Shawn Best50d60be2014-11-11 00:28:52 +0000494 if (!platform_sp->GetProcessInfo (pid, process_info))
495 {
496 if (log)
497 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): failed to get process info", __FUNCTION__, pid);
498 error.SetErrorString ("failed to get process info");
499 return;
500 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000501
502 // Resolve the executable module
503 ModuleSP exe_module_sp;
504 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
Chaoren Line56f6dc2015-03-01 04:31:16 +0000505 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Oleksiy Vyalov6edef202014-11-17 22:16:42 +0000506 error = platform_sp->ResolveExecutable(exe_module_spec, exe_module_sp,
Zachary Turner13b18262014-08-20 16:42:51 +0000507 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
Todd Fialaaf245d12014-06-30 21:05:18 +0000508 if (!error.Success())
509 return;
510
511 // Set the architecture to the exe architecture.
512 m_arch = exe_module_sp->GetArchitecture();
513 if (log)
514 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
515
516 m_pid = pid;
517 SetState(eStateAttaching);
518
Pavel Labath19cbe962015-07-21 13:20:32 +0000519 Attach(pid, error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000520}
521
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000522::pid_t
523NativeProcessLinux::Launch(LaunchArgs *args, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000524{
Todd Fiala0bce1b62014-08-17 00:10:50 +0000525 assert (args && "null args");
Todd Fialaaf245d12014-06-30 21:05:18 +0000526
527 const char **argv = args->m_argv;
528 const char **envp = args->m_envp;
Chaoren Lind3173f32015-05-29 19:52:29 +0000529 const FileSpec working_dir = args->m_working_dir;
Todd Fialaaf245d12014-06-30 21:05:18 +0000530
531 lldb_utility::PseudoTerminal terminal;
532 const size_t err_len = 1024;
533 char err_str[err_len];
534 lldb::pid_t pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000535
536 // Propagate the environment if one is not supplied.
537 if (envp == NULL || envp[0] == NULL)
538 envp = const_cast<const char **>(environ);
539
540 if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
541 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000542 error.SetErrorToGenericError();
543 error.SetErrorStringWithFormat("Process fork failed: %s", err_str);
544 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000545 }
546
547 // Recognized child exit status codes.
548 enum {
549 ePtraceFailed = 1,
550 eDupStdinFailed,
551 eDupStdoutFailed,
552 eDupStderrFailed,
553 eChdirFailed,
554 eExecFailed,
Pavel Labath78856472015-08-19 13:47:57 +0000555 eSetGidFailed,
556 eSetSigMaskFailed
Todd Fialaaf245d12014-06-30 21:05:18 +0000557 };
558
559 // Child process.
560 if (pid == 0)
561 {
Pavel Labathd2c4c9b2015-08-18 08:23:35 +0000562 // First, make sure we disable all logging. If we are logging to stdout, our logs can be
563 // mistaken for inferior output.
564 Log::DisableAllLogChannels(nullptr);
Todd Fiala75f47c32014-10-11 21:42:09 +0000565 // FIXME consider opening a pipe between parent/child and have this forked child
Pavel Labathd2c4c9b2015-08-18 08:23:35 +0000566 // send log info to parent re: launch status.
Todd Fialaaf245d12014-06-30 21:05:18 +0000567
Todd Fiala75f47c32014-10-11 21:42:09 +0000568 // Start tracing this child that is about to exec.
Pavel Labath4a9babb2015-06-30 17:04:49 +0000569 error = PtraceWrapper(PTRACE_TRACEME, 0);
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000570 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000571 exit(ePtraceFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +0000572
Pavel Labath493c3a12015-02-04 10:36:57 +0000573 // terminal has already dupped the tty descriptors to stdin/out/err.
574 // This closes original fd from which they were copied (and avoids
575 // leaking descriptors to the debugged process.
576 terminal.CloseSlaveFileDescriptor();
577
Todd Fialaaf245d12014-06-30 21:05:18 +0000578 // Do not inherit setgid powers.
Todd Fialaaf245d12014-06-30 21:05:18 +0000579 if (setgid(getgid()) != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +0000580 exit(eSetGidFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +0000581
582 // Attempt to have our own process group.
Todd Fialaaf245d12014-06-30 21:05:18 +0000583 if (setpgid(0, 0) != 0)
584 {
Todd Fiala75f47c32014-10-11 21:42:09 +0000585 // FIXME log that this failed. This is common.
Todd Fialaaf245d12014-06-30 21:05:18 +0000586 // Don't allow this to prevent an inferior exec.
587 }
588
589 // Dup file descriptors if needed.
Chaoren Lind3173f32015-05-29 19:52:29 +0000590 if (args->m_stdin_file_spec)
591 if (!DupDescriptor(args->m_stdin_file_spec, STDIN_FILENO, O_RDONLY))
Todd Fialaaf245d12014-06-30 21:05:18 +0000592 exit(eDupStdinFailed);
593
Chaoren Lind3173f32015-05-29 19:52:29 +0000594 if (args->m_stdout_file_spec)
595 if (!DupDescriptor(args->m_stdout_file_spec, STDOUT_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +0000596 exit(eDupStdoutFailed);
597
Chaoren Lind3173f32015-05-29 19:52:29 +0000598 if (args->m_stderr_file_spec)
599 if (!DupDescriptor(args->m_stderr_file_spec, STDERR_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +0000600 exit(eDupStderrFailed);
601
Chaoren Lin9cf4f2c2015-04-23 18:28:04 +0000602 // Close everything besides stdin, stdout, and stderr that has no file
603 // action to avoid leaking
604 for (int fd = 3; fd < sysconf(_SC_OPEN_MAX); ++fd)
605 if (!args->m_launch_info.GetFileActionForFD(fd))
606 close(fd);
607
Todd Fialaaf245d12014-06-30 21:05:18 +0000608 // Change working directory
Chaoren Lind3173f32015-05-29 19:52:29 +0000609 if (working_dir && 0 != ::chdir(working_dir.GetCString()))
Todd Fialaaf245d12014-06-30 21:05:18 +0000610 exit(eChdirFailed);
611
Todd Fiala0bce1b62014-08-17 00:10:50 +0000612 // Disable ASLR if requested.
613 if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR))
614 {
615 const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
616 if (old_personality == -1)
617 {
Todd Fiala75f47c32014-10-11 21:42:09 +0000618 // Can't retrieve Linux personality. Cannot disable ASLR.
Todd Fiala0bce1b62014-08-17 00:10:50 +0000619 }
620 else
621 {
622 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality);
623 if (new_personality == -1)
624 {
Todd Fiala75f47c32014-10-11 21:42:09 +0000625 // Disabling ASLR failed.
Todd Fiala0bce1b62014-08-17 00:10:50 +0000626 }
627 else
628 {
Todd Fiala75f47c32014-10-11 21:42:09 +0000629 // Disabling ASLR succeeded.
Todd Fiala0bce1b62014-08-17 00:10:50 +0000630 }
631 }
632 }
633
Pavel Labath78856472015-08-19 13:47:57 +0000634 // Clear the signal mask to prevent the child from being affected by
635 // any masking done by the parent.
636 sigset_t set;
637 if (sigemptyset(&set) != 0 || pthread_sigmask(SIG_SETMASK, &set, nullptr) != 0)
638 exit(eSetSigMaskFailed);
639
Todd Fiala75f47c32014-10-11 21:42:09 +0000640 // Execute. We should never return...
Todd Fialaaf245d12014-06-30 21:05:18 +0000641 execve(argv[0],
642 const_cast<char *const *>(argv),
643 const_cast<char *const *>(envp));
Todd Fiala75f47c32014-10-11 21:42:09 +0000644
645 // ...unless exec fails. In which case we definitely need to end the child here.
Todd Fialaaf245d12014-06-30 21:05:18 +0000646 exit(eExecFailed);
647 }
648
Todd Fiala75f47c32014-10-11 21:42:09 +0000649 //
650 // This is the parent code here.
651 //
652 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
653
Todd Fialaaf245d12014-06-30 21:05:18 +0000654 // Wait for the child process to trap on its call to execve.
655 ::pid_t wpid;
656 int status;
657 if ((wpid = waitpid(pid, &status, 0)) < 0)
658 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000659 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +0000660 if (log)
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000661 log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s",
662 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000663
664 // Mark the inferior as invalid.
665 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000666 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000667
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000668 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000669 }
670 else if (WIFEXITED(status))
671 {
672 // open, dup or execve likely failed for some reason.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000673 error.SetErrorToGenericError();
Todd Fialaaf245d12014-06-30 21:05:18 +0000674 switch (WEXITSTATUS(status))
675 {
676 case ePtraceFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000677 error.SetErrorString("Child ptrace failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000678 break;
679 case eDupStdinFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000680 error.SetErrorString("Child open stdin failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000681 break;
682 case eDupStdoutFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000683 error.SetErrorString("Child open stdout failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000684 break;
685 case eDupStderrFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000686 error.SetErrorString("Child open stderr failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000687 break;
688 case eChdirFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000689 error.SetErrorString("Child failed to set working directory.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000690 break;
691 case eExecFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000692 error.SetErrorString("Child exec failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000693 break;
694 case eSetGidFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000695 error.SetErrorString("Child setgid failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000696 break;
Pavel Labath78856472015-08-19 13:47:57 +0000697 case eSetSigMaskFailed:
698 error.SetErrorString("Child failed to set signal mask.");
699 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000700 default:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000701 error.SetErrorString("Child returned unknown exit status.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000702 break;
703 }
704
705 if (log)
706 {
707 log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
708 __FUNCTION__,
709 WEXITSTATUS(status));
710 }
711
712 // Mark the inferior as invalid.
713 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000714 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000715
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000716 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000717 }
Todd Fiala202ecd22014-07-10 04:39:13 +0000718 assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
Todd Fialaaf245d12014-06-30 21:05:18 +0000719 "Could not sync with inferior process.");
720
721 if (log)
722 log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
723
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000724 error = SetDefaultPtraceOpts(pid);
725 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000726 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000727 if (log)
728 log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000729 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000730
731 // Mark the inferior as invalid.
732 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000733 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000734
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000735 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000736 }
737
738 // Release the master terminal descriptor and pass it off to the
739 // NativeProcessLinux instance. Similarly stash the inferior pid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000740 m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
741 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000742
743 // Set the terminal fd to be in non blocking mode (it simplifies the
744 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
745 // descriptor to read from).
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000746 error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
747 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000748 {
749 if (log)
750 log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000751 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000752
753 // Mark the inferior as invalid.
754 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000755 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000756
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000757 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000758 }
759
760 if (log)
761 log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
762
Pavel Labathf9077782015-08-21 09:13:53 +0000763 NativeThreadLinuxSP thread_sp = AddThread(pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000764 assert (thread_sp && "AddThread() returned a nullptr thread");
Pavel Labathf9077782015-08-21 09:13:53 +0000765 thread_sp->SetStoppedBySignal(SIGSTOP);
766 ThreadWasCreated(*thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +0000767
768 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000769 SetCurrentThreadID (thread_sp->GetID ());
770 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +0000771
Todd Fialaaf245d12014-06-30 21:05:18 +0000772 if (log)
773 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000774 if (error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +0000775 {
776 log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
777 }
778 else
779 {
780 log->Printf ("NativeProcessLinux::%s inferior launching failed: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000781 __FUNCTION__, error.AsCString ());
782 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000783 }
784 }
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000785 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000786}
787
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000788::pid_t
789NativeProcessLinux::Attach(lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000790{
Todd Fialaaf245d12014-06-30 21:05:18 +0000791 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
792
793 // Use a map to keep track of the threads which we have attached/need to attach.
794 Host::TidMap tids_to_attach;
795 if (pid <= 1)
796 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000797 error.SetErrorToGenericError();
798 error.SetErrorString("Attaching to process 1 is not allowed.");
799 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000800 }
801
802 while (Host::FindProcessThreads(pid, tids_to_attach))
803 {
804 for (Host::TidMap::iterator it = tids_to_attach.begin();
805 it != tids_to_attach.end();)
806 {
807 if (it->second == false)
808 {
809 lldb::tid_t tid = it->first;
810
811 // Attach to the requested process.
812 // An attach will cause the thread to stop with a SIGSTOP.
Pavel Labath4a9babb2015-06-30 17:04:49 +0000813 error = PtraceWrapper(PTRACE_ATTACH, tid);
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000814 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000815 {
816 // No such thread. The thread may have exited.
817 // More error handling may be needed.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000818 if (error.GetError() == ESRCH)
Todd Fialaaf245d12014-06-30 21:05:18 +0000819 {
820 it = tids_to_attach.erase(it);
821 continue;
822 }
823 else
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000824 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000825 }
826
827 int status;
828 // Need to use __WALL otherwise we receive an error with errno=ECHLD
829 // At this point we should have a thread stopped if waitpid succeeds.
830 if ((status = waitpid(tid, NULL, __WALL)) < 0)
831 {
832 // No such thread. The thread may have exited.
833 // More error handling may be needed.
834 if (errno == ESRCH)
835 {
836 it = tids_to_attach.erase(it);
837 continue;
838 }
839 else
840 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000841 error.SetErrorToErrno();
842 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000843 }
844 }
845
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000846 error = SetDefaultPtraceOpts(tid);
847 if (error.Fail())
848 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000849
850 if (log)
851 log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
852
853 it->second = true;
854
855 // Create the thread, mark it as stopped.
Pavel Labathf9077782015-08-21 09:13:53 +0000856 NativeThreadLinuxSP thread_sp (AddThread(static_cast<lldb::tid_t>(tid)));
Todd Fialaaf245d12014-06-30 21:05:18 +0000857 assert (thread_sp && "AddThread() returned a nullptr");
Chaoren Linfa03ad22015-02-03 01:50:42 +0000858
859 // This will notify this is a new thread and tell the system it is stopped.
Pavel Labathf9077782015-08-21 09:13:53 +0000860 thread_sp->SetStoppedBySignal(SIGSTOP);
861 ThreadWasCreated(*thread_sp);
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000862 SetCurrentThreadID (thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000863 }
864
865 // move the loop forward
866 ++it;
867 }
868 }
869
870 if (tids_to_attach.size() > 0)
871 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000872 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000873 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000874 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +0000875 }
876 else
877 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000878 error.SetErrorToGenericError();
879 error.SetErrorString("No such process.");
880 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000881 }
882
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000883 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000884}
885
Chaoren Lin97ccc292015-02-03 01:51:12 +0000886Error
Todd Fialaaf245d12014-06-30 21:05:18 +0000887NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
888{
889 long ptrace_opts = 0;
890
891 // Have the child raise an event on exit. This is used to keep the child in
892 // limbo until it is destroyed.
893 ptrace_opts |= PTRACE_O_TRACEEXIT;
894
895 // Have the tracer trace threads which spawn in the inferior process.
896 // TODO: if we want to support tracing the inferiors' child, add the
897 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
898 ptrace_opts |= PTRACE_O_TRACECLONE;
899
900 // Have the tracer notify us before execve returns
901 // (needed to disable legacy SIGTRAP generation)
902 ptrace_opts |= PTRACE_O_TRACEEXEC;
903
Pavel Labath4a9babb2015-06-30 17:04:49 +0000904 return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts);
Todd Fialaaf245d12014-06-30 21:05:18 +0000905}
906
907static ExitType convert_pid_status_to_exit_type (int status)
908{
909 if (WIFEXITED (status))
910 return ExitType::eExitTypeExit;
911 else if (WIFSIGNALED (status))
912 return ExitType::eExitTypeSignal;
913 else if (WIFSTOPPED (status))
914 return ExitType::eExitTypeStop;
915 else
916 {
917 // We don't know what this is.
918 return ExitType::eExitTypeInvalid;
919 }
920}
921
922static int convert_pid_status_to_return_code (int status)
923{
924 if (WIFEXITED (status))
925 return WEXITSTATUS (status);
926 else if (WIFSIGNALED (status))
927 return WTERMSIG (status);
928 else if (WIFSTOPPED (status))
929 return WSTOPSIG (status);
930 else
931 {
932 // We don't know what this is.
933 return ExitType::eExitTypeInvalid;
934 }
935}
936
Pavel Labath1107b5a2015-04-17 14:07:49 +0000937// Handles all waitpid events from the inferior process.
938void
939NativeProcessLinux::MonitorCallback(lldb::pid_t pid,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000940 bool exited,
941 int signal,
942 int status)
Todd Fialaaf245d12014-06-30 21:05:18 +0000943{
944 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
945
Todd Fialaaf245d12014-06-30 21:05:18 +0000946 // Certain activities differ based on whether the pid is the tid of the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000947 const bool is_main_thread = (pid == GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000948
949 // Handle when the thread exits.
950 if (exited)
951 {
952 if (log)
Chaoren Lin86fd8e42015-02-03 01:51:15 +0000953 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 +0000954
955 // This is a thread that exited. Ensure we're not tracking it anymore.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000956 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000957
958 if (is_main_thread)
959 {
960 // We only set the exit status and notify the delegate if we haven't already set the process
961 // state to an exited state. We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
962 // for the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000963 const bool already_notified = (GetState() == StateType::eStateExited) || (GetState () == StateType::eStateCrashed);
Todd Fialaaf245d12014-06-30 21:05:18 +0000964 if (!already_notified)
965 {
966 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +0000967 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 +0000968 // The main thread exited. We're done monitoring. Report to delegate.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000969 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +0000970
971 // Notify delegate that our process has exited.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000972 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +0000973 }
974 else
975 {
976 if (log)
977 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
978 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000979 }
980 else
981 {
982 // Do we want to report to the delegate in this case? I think not. If this was an orderly
983 // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
984 // and we would have done an all-stop then.
985 if (log)
986 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 +0000987 }
Pavel Labath1107b5a2015-04-17 14:07:49 +0000988 return;
Todd Fialaaf245d12014-06-30 21:05:18 +0000989 }
990
991 // Get details on the signal raised.
992 siginfo_t info;
Pavel Labath1107b5a2015-04-17 14:07:49 +0000993 const auto err = GetSignalInfo(pid, &info);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000994 if (err.Success())
Chaoren Linfa03ad22015-02-03 01:50:42 +0000995 {
996 // We have retrieved the signal info. Dispatch appropriately.
997 if (info.si_signo == SIGTRAP)
Pavel Labath1107b5a2015-04-17 14:07:49 +0000998 MonitorSIGTRAP(&info, pid);
Chaoren Linfa03ad22015-02-03 01:50:42 +0000999 else
Pavel Labath1107b5a2015-04-17 14:07:49 +00001000 MonitorSignal(&info, pid, exited);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001001 }
1002 else
Todd Fialaaf245d12014-06-30 21:05:18 +00001003 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001004 if (err.GetError() == EINVAL)
Todd Fialaaf245d12014-06-30 21:05:18 +00001005 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00001006 // This is a group stop reception for this tid.
Pavel Labath39036ac2015-05-21 08:32:18 +00001007 // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the
1008 // tracee, triggering the group-stop mechanism. Normally receiving these would stop
1009 // the process, pending a SIGCONT. Simulating this state in a debugger is hard and is
1010 // generally not needed (one use case is debugging background task being managed by a
1011 // shell). For general use, it is sufficient to stop the process in a signal-delivery
1012 // stop which happens before the group stop. This done by MonitorSignal and works
1013 // correctly for all signals.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001014 if (log)
Pavel Labath39036ac2015-05-21 08:32:18 +00001015 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);
1016 Resume(pid, signal);
Todd Fialaaf245d12014-06-30 21:05:18 +00001017 }
1018 else
1019 {
1020 // ptrace(GETSIGINFO) failed (but not due to group-stop).
1021
1022 // A return value of ESRCH means the thread/process is no longer on the system,
1023 // so it was killed somehow outside of our control. Either way, we can't do anything
1024 // with it anymore.
1025
Todd Fialaaf245d12014-06-30 21:05:18 +00001026 // Stop tracking the metadata for the thread since it's entirely off the system now.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001027 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001028
1029 if (log)
1030 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
Chaoren Lin97ccc292015-02-03 01:51:12 +00001031 __FUNCTION__, err.AsCString(), pid, signal, status, 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 +00001032
1033 if (is_main_thread)
1034 {
1035 // Notify the delegate - our process is not available but appears to have been killed outside
1036 // our control. Is eStateExited the right exit state in this case?
Pavel Labath1107b5a2015-04-17 14:07:49 +00001037 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
1038 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001039 }
1040 else
1041 {
1042 // This thread was pulled out from underneath us. Anything to do here? Do we want to do an all stop?
1043 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +00001044 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 +00001045 }
1046 }
1047 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001048}
1049
1050void
Pavel Labath426bdf82015-04-28 07:51:52 +00001051NativeProcessLinux::WaitForNewThread(::pid_t tid)
1052{
1053 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1054
Pavel Labathf9077782015-08-21 09:13:53 +00001055 NativeThreadLinuxSP new_thread_sp = GetThreadByID(tid);
Pavel Labath426bdf82015-04-28 07:51:52 +00001056
1057 if (new_thread_sp)
1058 {
1059 // We are already tracking the thread - we got the event on the new thread (see
1060 // MonitorSignal) before this one. We are done.
1061 return;
1062 }
1063
1064 // The thread is not tracked yet, let's wait for it to appear.
1065 int status = -1;
1066 ::pid_t wait_pid;
1067 do
1068 {
1069 if (log)
1070 log->Printf ("NativeProcessLinux::%s() received thread creation event for tid %" PRIu32 ". tid not tracked yet, waiting for thread to appear...", __FUNCTION__, tid);
1071 wait_pid = waitpid(tid, &status, __WALL);
1072 }
1073 while (wait_pid == -1 && errno == EINTR);
1074 // Since we are waiting on a specific tid, this must be the creation event. But let's do
1075 // some checks just in case.
1076 if (wait_pid != tid) {
1077 if (log)
1078 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime", __FUNCTION__, tid);
1079 // The only way I know of this could happen is if the whole process was
1080 // SIGKILLed in the mean time. In any case, we can't do anything about that now.
1081 return;
1082 }
1083 if (WIFEXITED(status))
1084 {
1085 if (log)
1086 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " returned an 'exited' event. Not tracking the thread.", __FUNCTION__, tid);
1087 // Also a very improbable event.
1088 return;
1089 }
1090
1091 siginfo_t info;
1092 Error error = GetSignalInfo(tid, &info);
1093 if (error.Fail())
1094 {
1095 if (log)
1096 log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime.", __FUNCTION__, tid);
1097 return;
1098 }
1099
1100 if (((info.si_pid != 0) || (info.si_code != SI_USER)) && log)
1101 {
1102 // We should be getting a thread creation signal here, but we received something
1103 // else. There isn't much we can do about it now, so we will just log that. Since the
1104 // thread is alive and we are receiving events from it, we shall pretend that it was
1105 // created properly.
1106 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);
1107 }
1108
1109 if (log)
1110 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 ": tracking new thread tid %" PRIu32,
1111 __FUNCTION__, GetID (), tid);
1112
Pavel Labathf9077782015-08-21 09:13:53 +00001113 new_thread_sp = AddThread(tid);
Pavel Labath0e1d7292015-08-20 09:06:12 +00001114 ResumeThread(new_thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
Pavel Labathf9077782015-08-21 09:13:53 +00001115 ThreadWasCreated(*new_thread_sp);
Pavel Labath426bdf82015-04-28 07:51:52 +00001116}
1117
1118void
Todd Fialaaf245d12014-06-30 21:05:18 +00001119NativeProcessLinux::MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid)
1120{
1121 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1122 const bool is_main_thread = (pid == GetID ());
1123
1124 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
1125 if (!info)
1126 return;
1127
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001128 Mutex::Locker locker (m_threads_mutex);
1129
Todd Fialaaf245d12014-06-30 21:05:18 +00001130 // See if we can find a thread for this signal.
Pavel Labathf9077782015-08-21 09:13:53 +00001131 NativeThreadLinuxSP thread_sp = GetThreadByID(pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001132 if (!thread_sp)
1133 {
1134 if (log)
1135 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
1136 }
1137
1138 switch (info->si_code)
1139 {
1140 // TODO: these two cases are required if we want to support tracing of the inferiors' children. We'd need this to debug a monitor.
1141 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
1142 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
1143
1144 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
1145 {
Pavel Labath5fd24c62015-04-23 09:04:35 +00001146 // This is the notification on the parent thread which informs us of new thread
Pavel Labath426bdf82015-04-28 07:51:52 +00001147 // creation.
1148 // We don't want to do anything with the parent thread so we just resume it. In case we
1149 // want to implement "break on thread creation" functionality, we would need to stop
1150 // here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001151
Pavel Labath426bdf82015-04-28 07:51:52 +00001152 unsigned long event_message = 0;
1153 if (GetEventMessage (pid, &event_message).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001154 {
Pavel Labath426bdf82015-04-28 07:51:52 +00001155 if (log)
Chaoren Linfa03ad22015-02-03 01:50:42 +00001156 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " received thread creation event but GetEventMessage failed so we don't know the new tid", __FUNCTION__, pid);
Pavel Labath426bdf82015-04-28 07:51:52 +00001157 } else
1158 WaitForNewThread(event_message);
Todd Fialaaf245d12014-06-30 21:05:18 +00001159
Pavel Labath0e1d7292015-08-20 09:06:12 +00001160 ResumeThread(thread_sp, thread_sp->GetState(), LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001161 break;
1162 }
1163
1164 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
Todd Fialaa9882ce2014-08-28 15:46:54 +00001165 {
Pavel Labathf9077782015-08-21 09:13:53 +00001166 NativeThreadLinuxSP main_thread_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001167 if (log)
1168 log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
Todd Fialaa9882ce2014-08-28 15:46:54 +00001169
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001170 // Exec clears any pending notifications.
Pavel Labath0e1d7292015-08-20 09:06:12 +00001171 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
Chaoren Linfa03ad22015-02-03 01:50:42 +00001172
1173 // 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 +00001174 if (log)
1175 log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
1176
1177 for (auto thread_sp : m_threads)
Todd Fialaa9882ce2014-08-28 15:46:54 +00001178 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001179 const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
1180 if (is_main_thread)
Todd Fialaa9882ce2014-08-28 15:46:54 +00001181 {
Pavel Labathf9077782015-08-21 09:13:53 +00001182 main_thread_sp = std::static_pointer_cast<NativeThreadLinux>(thread_sp);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001183 if (log)
1184 log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00001185 }
1186 else
1187 {
Todd Fialaa9882ce2014-08-28 15:46:54 +00001188 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001189 log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00001190 }
1191 }
1192
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001193 m_threads.clear ();
1194
1195 if (main_thread_sp)
1196 {
1197 m_threads.push_back (main_thread_sp);
1198 SetCurrentThreadID (main_thread_sp->GetID ());
Pavel Labathf9077782015-08-21 09:13:53 +00001199 main_thread_sp->SetStoppedByExec();
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001200 }
1201 else
1202 {
1203 SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
1204 if (log)
1205 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
1206 }
1207
Chaoren Linfa03ad22015-02-03 01:50:42 +00001208 // Tell coordinator about about the "new" (since exec) stopped main thread.
Pavel Labathf9077782015-08-21 09:13:53 +00001209 ThreadWasCreated(*main_thread_sp);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001210
1211 // NOTE: ideally these next statements would execute at the same time as the coordinator thread create was executed.
1212 // Consider a handler that can execute when that happens.
Todd Fialaa9882ce2014-08-28 15:46:54 +00001213 // Let our delegate know we have just exec'd.
1214 NotifyDidExec ();
1215
1216 // If we have a main thread, indicate we are stopped.
1217 assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001218
1219 // Let the process know we're stopped.
Pavel Labathed89c7f2015-05-06 12:22:37 +00001220 StopRunningThreads (pid);
Todd Fialaa9882ce2014-08-28 15:46:54 +00001221
Todd Fialaaf245d12014-06-30 21:05:18 +00001222 break;
Todd Fialaa9882ce2014-08-28 15:46:54 +00001223 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001224
1225 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
1226 {
1227 // The inferior process or one of its threads is about to exit.
Pavel Labath6e351632015-05-15 13:30:59 +00001228 // We don't want to do anything with the thread so we just resume it. In case we
1229 // want to implement "break on thread exit" functionality, we would need to stop
1230 // here.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001231
Todd Fialaaf245d12014-06-30 21:05:18 +00001232 unsigned long data = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +00001233 if (GetEventMessage(pid, &data).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001234 data = -1;
1235
1236 if (log)
1237 {
1238 log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
1239 __FUNCTION__,
1240 data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
1241 pid,
1242 is_main_thread ? "is main thread" : "not main thread");
1243 }
1244
Todd Fialaaf245d12014-06-30 21:05:18 +00001245 if (is_main_thread)
1246 {
1247 SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001248 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001249
Pavel Labath0e1d7292015-08-20 09:06:12 +00001250 ResumeThread(thread_sp, thread_sp->GetState(), LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001251
1252 break;
1253 }
1254
1255 case 0:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001256 case TRAP_TRACE: // We receive this on single stepping.
1257 case TRAP_HWBKPT: // We receive this on watchpoint hit
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001258 if (thread_sp)
1259 {
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001260 // If a watchpoint was hit, report it
1261 uint32_t wp_index;
Omair Javaidea8c25a802015-05-15 06:29:58 +00001262 Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index, (lldb::addr_t)info->si_addr);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001263 if (error.Fail() && log)
1264 log->Printf("NativeProcessLinux::%s() "
1265 "received error while checking for watchpoint hits, "
1266 "pid = %" PRIu64 " error = %s",
1267 __FUNCTION__, pid, error.AsCString());
1268 if (wp_index != LLDB_INVALID_INDEX32)
1269 {
Pavel Labathf9077782015-08-21 09:13:53 +00001270 MonitorWatchpoint(*thread_sp, wp_index);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001271 break;
1272 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001273 }
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001274 // Otherwise, report step over
1275 MonitorTrace(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00001276 break;
1277
1278 case SI_KERNEL:
Mohit K. Bhakkad35799962015-06-18 04:53:18 +00001279#if defined __mips__
1280 // For mips there is no special signal for watchpoint
1281 // So we check for watchpoint in kernel trap
1282 if (thread_sp)
1283 {
1284 // If a watchpoint was hit, report it
1285 uint32_t wp_index;
Jaydeep Patilc60c9452015-06-23 03:37:08 +00001286 Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index, LLDB_INVALID_ADDRESS);
Mohit K. Bhakkad35799962015-06-18 04:53:18 +00001287 if (error.Fail() && log)
1288 log->Printf("NativeProcessLinux::%s() "
1289 "received error while checking for watchpoint hits, "
1290 "pid = %" PRIu64 " error = %s",
1291 __FUNCTION__, pid, error.AsCString());
1292 if (wp_index != LLDB_INVALID_INDEX32)
1293 {
Pavel Labathf9077782015-08-21 09:13:53 +00001294 MonitorWatchpoint(*thread_sp, wp_index);
Mohit K. Bhakkad35799962015-06-18 04:53:18 +00001295 break;
1296 }
1297 }
1298 // NO BREAK
1299#endif
Todd Fialaaf245d12014-06-30 21:05:18 +00001300 case TRAP_BRKPT:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001301 MonitorBreakpoint(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00001302 break;
1303
1304 case SIGTRAP:
1305 case (SIGTRAP | 0x80):
1306 if (log)
Chaoren Linfa03ad22015-02-03 01:50:42 +00001307 log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), pid);
1308
Todd Fialaaf245d12014-06-30 21:05:18 +00001309 // Ignore these signals until we know more about them.
Pavel Labath0e1d7292015-08-20 09:06:12 +00001310 ResumeThread(thread_sp, thread_sp->GetState(), LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001311 break;
1312
1313 default:
1314 assert(false && "Unexpected SIGTRAP code!");
1315 if (log)
Pavel Labath6e351632015-05-15 13:30:59 +00001316 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 "tid %" PRIu64 " received unhandled SIGTRAP code: 0x%d",
1317 __FUNCTION__, GetID (), pid, info->si_code);
Todd Fialaaf245d12014-06-30 21:05:18 +00001318 break;
1319
1320 }
1321}
1322
1323void
Pavel Labathf9077782015-08-21 09:13:53 +00001324NativeProcessLinux::MonitorTrace(lldb::pid_t pid, const NativeThreadLinuxSP &thread_sp)
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001325{
1326 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1327 if (log)
1328 log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)",
1329 __FUNCTION__, pid);
1330
Pavel Labath0e1d7292015-08-20 09:06:12 +00001331 // This thread is currently stopped.
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001332 if (thread_sp)
Pavel Labathf9077782015-08-21 09:13:53 +00001333 thread_sp->SetStoppedByTrace();
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001334
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001335 // Here we don't have to request the rest of the threads to stop or request a deferred stop.
1336 // This would have already happened at the time the Resume() with step operation was signaled.
1337 // At this point, we just need to say we stopped, and the deferred notifcation will fire off
1338 // once all running threads have checked in as stopped.
1339 SetCurrentThreadID(pid);
1340 // Tell the process we have a stop (from software breakpoint).
Pavel Labathed89c7f2015-05-06 12:22:37 +00001341 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001342}
1343
1344void
Pavel Labathf9077782015-08-21 09:13:53 +00001345NativeProcessLinux::MonitorBreakpoint(lldb::pid_t pid, const NativeThreadLinuxSP &thread_sp)
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001346{
1347 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
1348 if (log)
1349 log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
1350 __FUNCTION__, pid);
1351
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001352 // Mark the thread as stopped at breakpoint.
1353 if (thread_sp)
1354 {
Pavel Labathf9077782015-08-21 09:13:53 +00001355 thread_sp->SetStoppedByBreakpoint();
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001356 Error error = FixupBreakpointPCAsNeeded(thread_sp);
1357 if (error.Fail())
1358 if (log)
1359 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
1360 __FUNCTION__, pid, error.AsCString());
Tamas Berghammerd8c338d2015-04-15 09:47:02 +00001361
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00001362 if (m_threads_stepping_with_breakpoint.find(pid) != m_threads_stepping_with_breakpoint.end())
Pavel Labathf9077782015-08-21 09:13:53 +00001363 thread_sp->SetStoppedByTrace();
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001364 }
1365 else
1366 if (log)
1367 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 ": "
1368 "warning, cannot process software breakpoint since no thread metadata",
1369 __FUNCTION__, pid);
1370
1371
1372 // We need to tell all other running threads before we notify the delegate about this stop.
Pavel Labathed89c7f2015-05-06 12:22:37 +00001373 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001374}
1375
1376void
Pavel Labathf9077782015-08-21 09:13:53 +00001377NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread, uint32_t wp_index)
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001378{
1379 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
1380 if (log)
1381 log->Printf("NativeProcessLinux::%s() received watchpoint event, "
1382 "pid = %" PRIu64 ", wp_index = %" PRIu32,
Pavel Labathf9077782015-08-21 09:13:53 +00001383 __FUNCTION__, thread.GetID(), wp_index);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001384
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001385 // Mark the thread as stopped at watchpoint.
1386 // The address is at (lldb::addr_t)info->si_addr if we need it.
Pavel Labathf9077782015-08-21 09:13:53 +00001387 thread.SetStoppedByWatchpoint(wp_index);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001388
1389 // We need to tell all other running threads before we notify the delegate about this stop.
Pavel Labathf9077782015-08-21 09:13:53 +00001390 StopRunningThreads(thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001391}
1392
1393void
Todd Fialaaf245d12014-06-30 21:05:18 +00001394NativeProcessLinux::MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited)
1395{
Todd Fiala511e5cd2014-09-11 23:29:14 +00001396 assert (info && "null info");
1397 if (!info)
1398 return;
1399
1400 const int signo = info->si_signo;
1401 const bool is_from_llgs = info->si_pid == getpid ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001402
1403 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1404
1405 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1406 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1407 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
1408 //
1409 // IOW, user generated signals never generate what we consider to be a
1410 // "crash".
1411 //
1412 // Similarly, ACK signals generated by this monitor.
1413
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001414 Mutex::Locker locker (m_threads_mutex);
1415
Todd Fialaaf245d12014-06-30 21:05:18 +00001416 // See if we can find a thread for this signal.
Pavel Labathf9077782015-08-21 09:13:53 +00001417 NativeThreadLinuxSP thread_sp = GetThreadByID(pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001418 if (!thread_sp)
1419 {
1420 if (log)
1421 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
1422 }
1423
1424 // Handle the signal.
1425 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
1426 {
1427 if (log)
1428 log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
1429 __FUNCTION__,
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001430 Host::GetSignalAsCString(signo),
Todd Fialaaf245d12014-06-30 21:05:18 +00001431 signo,
1432 (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
1433 info->si_pid,
Todd Fiala511e5cd2014-09-11 23:29:14 +00001434 is_from_llgs ? "from llgs" : "not from llgs",
Todd Fialaaf245d12014-06-30 21:05:18 +00001435 pid);
Todd Fiala58a2f662014-08-12 17:02:07 +00001436 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001437
Todd Fiala58a2f662014-08-12 17:02:07 +00001438 // Check for new thread notification.
1439 if ((info->si_pid == 0) && (info->si_code == SI_USER))
1440 {
Pavel Labath426bdf82015-04-28 07:51:52 +00001441 // A new thread creation is being signaled. This is one of two parts that come in
1442 // a non-deterministic order. This code handles the case where the new thread event comes
1443 // before the event on the parent thread. For the opposite case see code in
1444 // MonitorSIGTRAP.
Todd Fiala58a2f662014-08-12 17:02:07 +00001445 if (log)
1446 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": new thread notification",
1447 __FUNCTION__, GetID (), pid);
1448
Pavel Labathf9077782015-08-21 09:13:53 +00001449 thread_sp = AddThread(pid);
Pavel Labath5fd24c62015-04-23 09:04:35 +00001450 assert (thread_sp.get() && "failed to create the tracking data for newly created inferior thread");
1451 // We can now resume the newly created thread.
Pavel Labath0e1d7292015-08-20 09:06:12 +00001452 ResumeThread(thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
Pavel Labathf9077782015-08-21 09:13:53 +00001453 ThreadWasCreated(*thread_sp);
Todd Fiala58a2f662014-08-12 17:02:07 +00001454 // Done handling.
1455 return;
1456 }
1457
1458 // Check for thread stop notification.
Todd Fiala511e5cd2014-09-11 23:29:14 +00001459 if (is_from_llgs && (info->si_code == SI_TKILL) && (signo == SIGSTOP))
Todd Fiala58a2f662014-08-12 17:02:07 +00001460 {
1461 // This is a tgkill()-based stop.
1462 if (thread_sp)
1463 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00001464 if (log)
1465 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
1466 __FUNCTION__,
1467 GetID (),
1468 pid);
1469
Chaoren Linaab58632015-02-03 01:50:57 +00001470 // Check that we're not already marked with a stop reason.
1471 // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
1472 // the kernel signaled us with the thread stopping which we handled and marked as stopped,
1473 // and that, without an intervening resume, we received another stop. It is more likely
1474 // that we are missing the marking of a run state somewhere if we find that the thread was
1475 // marked as stopped.
Pavel Labathf9077782015-08-21 09:13:53 +00001476 const StateType thread_state = thread_sp->GetState();
Chaoren Linaab58632015-02-03 01:50:57 +00001477 if (!StateIsStoppedState (thread_state, false))
1478 {
Pavel Labathed89c7f2015-05-06 12:22:37 +00001479 // An inferior thread has stopped because of a SIGSTOP we have sent it.
1480 // Generally, these are not important stops and we don't want to report them as
1481 // they are just used to stop other threads when one thread (the one with the
1482 // *real* stop reason) hits a breakpoint (watchpoint, etc...). However, in the
1483 // case of an asynchronous Interrupt(), this *is* the real stop reason, so we
1484 // leave the signal intact if this is the thread that was chosen as the
1485 // triggering thread.
Pavel Labath0e1d7292015-08-20 09:06:12 +00001486 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID)
1487 {
1488 if (m_pending_notification_tid == pid)
Pavel Labathf9077782015-08-21 09:13:53 +00001489 thread_sp->SetStoppedBySignal(SIGSTOP, info);
Pavel Labath0e1d7292015-08-20 09:06:12 +00001490 else
Pavel Labathf9077782015-08-21 09:13:53 +00001491 thread_sp->SetStoppedWithNoReason();
Pavel Labathed89c7f2015-05-06 12:22:37 +00001492
Pavel Labath0e1d7292015-08-20 09:06:12 +00001493 SetCurrentThreadID (thread_sp->GetID ());
1494 SignalIfAllThreadsStopped();
1495 }
1496 else
1497 {
1498 // We can end up here if stop was initiated by LLGS but by this time a
1499 // thread stop has occurred - maybe initiated by another event.
Pavel Labathf9077782015-08-21 09:13:53 +00001500 Error error = ResumeThread(thread_sp, thread_sp->GetState(), 0);
Pavel Labath0e1d7292015-08-20 09:06:12 +00001501 if (error.Fail() && log)
1502 {
1503 log->Printf("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s",
Pavel Labathf9077782015-08-21 09:13:53 +00001504 __FUNCTION__, thread_sp->GetID(), error.AsCString());
Pavel Labath0e1d7292015-08-20 09:06:12 +00001505 }
1506 }
Chaoren Linaab58632015-02-03 01:50:57 +00001507 }
1508 else
1509 {
1510 if (log)
1511 {
1512 // Retrieve the signal name if the thread was stopped by a signal.
1513 int stop_signo = 0;
Pavel Labathf9077782015-08-21 09:13:53 +00001514 const bool stopped_by_signal = thread_sp->IsStopped(&stop_signo);
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001515 const char *signal_name = stopped_by_signal ? Host::GetSignalAsCString(stop_signo) : "<not stopped by signal>";
Chaoren Linaab58632015-02-03 01:50:57 +00001516 if (!signal_name)
1517 signal_name = "<no-signal-name>";
1518
1519 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",
1520 __FUNCTION__,
1521 GetID (),
Pavel Labathf9077782015-08-21 09:13:53 +00001522 thread_sp->GetID(),
Chaoren Linaab58632015-02-03 01:50:57 +00001523 StateAsCString (thread_state),
1524 stop_signo,
1525 signal_name);
1526 }
Pavel Labath0e1d7292015-08-20 09:06:12 +00001527 SignalIfAllThreadsStopped();
Chaoren Linaab58632015-02-03 01:50:57 +00001528 }
Todd Fiala58a2f662014-08-12 17:02:07 +00001529 }
1530
1531 // Done handling.
Todd Fialaaf245d12014-06-30 21:05:18 +00001532 return;
1533 }
1534
1535 if (log)
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001536 log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, Host::GetSignalAsCString(signo));
Todd Fialaaf245d12014-06-30 21:05:18 +00001537
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001538 // This thread is stopped.
Pavel Labathc4e25c92015-05-29 10:13:03 +00001539 if (thread_sp)
Pavel Labathf9077782015-08-21 09:13:53 +00001540 thread_sp->SetStoppedBySignal(signo, info);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001541
1542 // Send a stop to the debugger after we get all other threads to stop.
Pavel Labathed89c7f2015-05-06 12:22:37 +00001543 StopRunningThreads (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001544}
1545
Tamas Berghammere7708682015-04-22 10:00:23 +00001546namespace {
1547
1548struct EmulatorBaton
1549{
1550 NativeProcessLinux* m_process;
1551 NativeRegisterContext* m_reg_context;
Tamas Berghammere7708682015-04-22 10:00:23 +00001552
Pavel Labath6648fcc2015-04-27 09:21:14 +00001553 // eRegisterKindDWARF -> RegsiterValue
1554 std::unordered_map<uint32_t, RegisterValue> m_register_values;
1555
1556 EmulatorBaton(NativeProcessLinux* process, NativeRegisterContext* reg_context) :
Tamas Berghammere7708682015-04-22 10:00:23 +00001557 m_process(process), m_reg_context(reg_context) {}
1558};
1559
1560} // anonymous namespace
1561
1562static size_t
1563ReadMemoryCallback (EmulateInstruction *instruction,
1564 void *baton,
1565 const EmulateInstruction::Context &context,
1566 lldb::addr_t addr,
1567 void *dst,
1568 size_t length)
1569{
1570 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
1571
Chaoren Lin3eb4b452015-04-29 17:24:48 +00001572 size_t bytes_read;
Tamas Berghammere7708682015-04-22 10:00:23 +00001573 emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
1574 return bytes_read;
1575}
1576
1577static bool
1578ReadRegisterCallback (EmulateInstruction *instruction,
1579 void *baton,
1580 const RegisterInfo *reg_info,
1581 RegisterValue &reg_value)
1582{
1583 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
1584
Pavel Labath6648fcc2015-04-27 09:21:14 +00001585 auto it = emulator_baton->m_register_values.find(reg_info->kinds[eRegisterKindDWARF]);
1586 if (it != emulator_baton->m_register_values.end())
1587 {
1588 reg_value = it->second;
1589 return true;
1590 }
1591
Tamas Berghammere7708682015-04-22 10:00:23 +00001592 // The emulator only fill in the dwarf regsiter numbers (and in some case
1593 // the generic register numbers). Get the full register info from the
1594 // register context based on the dwarf register numbers.
1595 const RegisterInfo* full_reg_info = emulator_baton->m_reg_context->GetRegisterInfo(
1596 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
1597
1598 Error error = emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
Pavel Labath6648fcc2015-04-27 09:21:14 +00001599 if (error.Success())
Pavel Labath6648fcc2015-04-27 09:21:14 +00001600 return true;
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001601
Pavel Labath6648fcc2015-04-27 09:21:14 +00001602 return false;
Tamas Berghammere7708682015-04-22 10:00:23 +00001603}
1604
1605static bool
1606WriteRegisterCallback (EmulateInstruction *instruction,
1607 void *baton,
1608 const EmulateInstruction::Context &context,
1609 const RegisterInfo *reg_info,
1610 const RegisterValue &reg_value)
1611{
1612 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
Pavel Labath6648fcc2015-04-27 09:21:14 +00001613 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = reg_value;
Tamas Berghammere7708682015-04-22 10:00:23 +00001614 return true;
1615}
1616
1617static size_t
1618WriteMemoryCallback (EmulateInstruction *instruction,
1619 void *baton,
1620 const EmulateInstruction::Context &context,
1621 lldb::addr_t addr,
1622 const void *dst,
1623 size_t length)
1624{
1625 return length;
1626}
1627
1628static lldb::addr_t
1629ReadFlags (NativeRegisterContext* regsiter_context)
1630{
1631 const RegisterInfo* flags_info = regsiter_context->GetRegisterInfo(
1632 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1633 return regsiter_context->ReadRegisterAsUnsigned(flags_info, LLDB_INVALID_ADDRESS);
1634}
1635
1636Error
1637NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadProtocolSP thread_sp)
1638{
1639 Error error;
1640 NativeRegisterContextSP register_context_sp = thread_sp->GetRegisterContext();
1641
1642 std::unique_ptr<EmulateInstruction> emulator_ap(
1643 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, nullptr));
1644
1645 if (emulator_ap == nullptr)
1646 return Error("Instruction emulator not found!");
1647
1648 EmulatorBaton baton(this, register_context_sp.get());
1649 emulator_ap->SetBaton(&baton);
1650 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
1651 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
1652 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
1653 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
1654
1655 if (!emulator_ap->ReadInstruction())
1656 return Error("Read instruction failed!");
1657
Pavel Labath6648fcc2015-04-27 09:21:14 +00001658 bool emulation_result = emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
1659
1660 const RegisterInfo* reg_info_pc = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1661 const RegisterInfo* reg_info_flags = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1662
1663 auto pc_it = baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1664 auto flags_it = baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
1665
Tamas Berghammere7708682015-04-22 10:00:23 +00001666 lldb::addr_t next_pc;
1667 lldb::addr_t next_flags;
Pavel Labath6648fcc2015-04-27 09:21:14 +00001668 if (emulation_result)
Tamas Berghammere7708682015-04-22 10:00:23 +00001669 {
Pavel Labath6648fcc2015-04-27 09:21:14 +00001670 assert(pc_it != baton.m_register_values.end() && "Emulation was successfull but PC wasn't updated");
1671 next_pc = pc_it->second.GetAsUInt64();
1672
1673 if (flags_it != baton.m_register_values.end())
1674 next_flags = flags_it->second.GetAsUInt64();
Tamas Berghammere7708682015-04-22 10:00:23 +00001675 else
1676 next_flags = ReadFlags (register_context_sp.get());
1677 }
Pavel Labath6648fcc2015-04-27 09:21:14 +00001678 else if (pc_it == baton.m_register_values.end())
Tamas Berghammere7708682015-04-22 10:00:23 +00001679 {
1680 // Emulate instruction failed and it haven't changed PC. Advance PC
1681 // with the size of the current opcode because the emulation of all
1682 // PC modifying instruction should be successful. The failure most
1683 // likely caused by a not supported instruction which don't modify PC.
1684 next_pc = register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
1685 next_flags = ReadFlags (register_context_sp.get());
1686 }
1687 else
1688 {
1689 // The instruction emulation failed after it modified the PC. It is an
1690 // unknown error where we can't continue because the next instruction is
1691 // modifying the PC but we don't know how.
1692 return Error ("Instruction emulation failed unexpectedly.");
1693 }
1694
1695 if (m_arch.GetMachine() == llvm::Triple::arm)
1696 {
1697 if (next_flags & 0x20)
1698 {
1699 // Thumb mode
1700 error = SetSoftwareBreakpoint(next_pc, 2);
1701 }
1702 else
1703 {
1704 // Arm mode
1705 error = SetSoftwareBreakpoint(next_pc, 4);
1706 }
1707 }
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001708 else if (m_arch.GetMachine() == llvm::Triple::mips64
Jaydeep Patilc60c9452015-06-23 03:37:08 +00001709 || m_arch.GetMachine() == llvm::Triple::mips64el
1710 || m_arch.GetMachine() == llvm::Triple::mips
1711 || m_arch.GetMachine() == llvm::Triple::mipsel)
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001712 error = SetSoftwareBreakpoint(next_pc, 4);
Tamas Berghammere7708682015-04-22 10:00:23 +00001713 else
1714 {
1715 // No size hint is given for the next breakpoint
1716 error = SetSoftwareBreakpoint(next_pc, 0);
1717 }
1718
Tamas Berghammere7708682015-04-22 10:00:23 +00001719 if (error.Fail())
1720 return error;
1721
1722 m_threads_stepping_with_breakpoint.insert({thread_sp->GetID(), next_pc});
1723
1724 return Error();
1725}
1726
1727bool
1728NativeProcessLinux::SupportHardwareSingleStepping() const
1729{
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001730 if (m_arch.GetMachine() == llvm::Triple::arm
Jaydeep Patilc60c9452015-06-23 03:37:08 +00001731 || m_arch.GetMachine() == llvm::Triple::mips64 || m_arch.GetMachine() == llvm::Triple::mips64el
1732 || m_arch.GetMachine() == llvm::Triple::mips || m_arch.GetMachine() == llvm::Triple::mipsel)
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001733 return false;
1734 return true;
Tamas Berghammere7708682015-04-22 10:00:23 +00001735}
1736
Todd Fialaaf245d12014-06-30 21:05:18 +00001737Error
1738NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
1739{
Todd Fialaaf245d12014-06-30 21:05:18 +00001740 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1741 if (log)
1742 log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
1743
Tamas Berghammere7708682015-04-22 10:00:23 +00001744 bool software_single_step = !SupportHardwareSingleStepping();
Todd Fialaaf245d12014-06-30 21:05:18 +00001745
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001746 Mutex::Locker locker (m_threads_mutex);
Chaoren Lin03f12d62015-02-03 01:50:49 +00001747
Tamas Berghammere7708682015-04-22 10:00:23 +00001748 if (software_single_step)
1749 {
1750 for (auto thread_sp : m_threads)
1751 {
1752 assert (thread_sp && "thread list should not contain NULL threads");
1753
1754 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
1755 if (action == nullptr)
1756 continue;
1757
1758 if (action->state == eStateStepping)
1759 {
1760 Error error = SetupSoftwareSingleStepping(thread_sp);
1761 if (error.Fail())
1762 return error;
1763 }
1764 }
1765 }
1766
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001767 for (auto thread_sp : m_threads)
Todd Fialaaf245d12014-06-30 21:05:18 +00001768 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001769 assert (thread_sp && "thread list should not contain NULL threads");
1770
1771 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
1772
1773 if (action == nullptr)
Todd Fialaaf245d12014-06-30 21:05:18 +00001774 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00001775 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001776 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
1777 __FUNCTION__, GetID (), thread_sp->GetID ());
1778 continue;
1779 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001780
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001781 if (log)
1782 {
1783 log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
1784 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
1785 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001786
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001787 switch (action->state)
1788 {
1789 case eStateRunning:
Pavel Labath0e1d7292015-08-20 09:06:12 +00001790 case eStateStepping:
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001791 {
1792 // Run the thread, possibly feeding it the signal.
1793 const int signo = action->signal;
Pavel Labath0e1d7292015-08-20 09:06:12 +00001794 ResumeThread(std::static_pointer_cast<NativeThreadLinux>(thread_sp), action->state, signo);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001795 break;
1796 }
1797
1798 case eStateSuspended:
1799 case eStateStopped:
Pavel Labath108c3252015-05-12 09:03:18 +00001800 lldbassert(0 && "Unexpected state");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001801
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001802 default:
1803 return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
1804 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001805 }
1806 }
1807
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001808 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00001809}
1810
1811Error
1812NativeProcessLinux::Halt ()
1813{
1814 Error error;
1815
Todd Fialaaf245d12014-06-30 21:05:18 +00001816 if (kill (GetID (), SIGSTOP) != 0)
1817 error.SetErrorToErrno ();
1818
1819 return error;
1820}
1821
1822Error
1823NativeProcessLinux::Detach ()
1824{
1825 Error error;
1826
1827 // Tell ptrace to detach from the process.
1828 if (GetID () != LLDB_INVALID_PROCESS_ID)
1829 error = Detach (GetID ());
1830
1831 // Stop monitoring the inferior.
Pavel Labath19cbe962015-07-21 13:20:32 +00001832 m_sigchld_handle.reset();
Todd Fialaaf245d12014-06-30 21:05:18 +00001833
1834 // No error.
1835 return error;
1836}
1837
1838Error
1839NativeProcessLinux::Signal (int signo)
1840{
1841 Error error;
1842
1843 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1844 if (log)
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001845 log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
1846 __FUNCTION__, signo, Host::GetSignalAsCString(signo), GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +00001847
1848 if (kill(GetID(), signo))
1849 error.SetErrorToErrno();
1850
1851 return error;
1852}
1853
1854Error
Chaoren Line9547b82015-02-03 01:51:00 +00001855NativeProcessLinux::Interrupt ()
1856{
1857 // Pick a running thread (or if none, a not-dead stopped thread) as
1858 // the chosen thread that will be the stop-reason thread.
Chaoren Line9547b82015-02-03 01:51:00 +00001859 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1860
1861 NativeThreadProtocolSP running_thread_sp;
1862 NativeThreadProtocolSP stopped_thread_sp;
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001863
1864 if (log)
1865 log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
1866
1867 Mutex::Locker locker (m_threads_mutex);
1868
1869 for (auto thread_sp : m_threads)
Chaoren Line9547b82015-02-03 01:51:00 +00001870 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001871 // The thread shouldn't be null but lets just cover that here.
1872 if (!thread_sp)
1873 continue;
Chaoren Line9547b82015-02-03 01:51:00 +00001874
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001875 // If we have a running or stepping thread, we'll call that the
1876 // target of the interrupt.
1877 const auto thread_state = thread_sp->GetState ();
1878 if (thread_state == eStateRunning ||
1879 thread_state == eStateStepping)
Chaoren Line9547b82015-02-03 01:51:00 +00001880 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001881 running_thread_sp = thread_sp;
1882 break;
1883 }
1884 else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
1885 {
1886 // Remember the first non-dead stopped thread. We'll use that as a backup if there are no running threads.
1887 stopped_thread_sp = thread_sp;
Chaoren Line9547b82015-02-03 01:51:00 +00001888 }
1889 }
1890
1891 if (!running_thread_sp && !stopped_thread_sp)
1892 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001893 Error error("found no running/stepping or live stopped threads as target for interrupt");
Chaoren Line9547b82015-02-03 01:51:00 +00001894 if (log)
Chaoren Line9547b82015-02-03 01:51:00 +00001895 log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001896
Chaoren Line9547b82015-02-03 01:51:00 +00001897 return error;
1898 }
1899
1900 NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
1901
1902 if (log)
1903 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
1904 __FUNCTION__,
1905 GetID (),
1906 running_thread_sp ? "running" : "stopped",
1907 deferred_signal_thread_sp->GetID ());
1908
Pavel Labathed89c7f2015-05-06 12:22:37 +00001909 StopRunningThreads(deferred_signal_thread_sp->GetID());
Pavel Labath45f5cb32015-05-05 15:05:50 +00001910
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001911 return Error();
Chaoren Line9547b82015-02-03 01:51:00 +00001912}
1913
1914Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001915NativeProcessLinux::Kill ()
1916{
1917 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1918 if (log)
1919 log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
1920
1921 Error error;
1922
1923 switch (m_state)
1924 {
1925 case StateType::eStateInvalid:
1926 case StateType::eStateExited:
1927 case StateType::eStateCrashed:
1928 case StateType::eStateDetached:
1929 case StateType::eStateUnloaded:
1930 // Nothing to do - the process is already dead.
1931 if (log)
1932 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
1933 return error;
1934
1935 case StateType::eStateConnected:
1936 case StateType::eStateAttaching:
1937 case StateType::eStateLaunching:
1938 case StateType::eStateStopped:
1939 case StateType::eStateRunning:
1940 case StateType::eStateStepping:
1941 case StateType::eStateSuspended:
1942 // We can try to kill a process in these states.
1943 break;
1944 }
1945
1946 if (kill (GetID (), SIGKILL) != 0)
1947 {
1948 error.SetErrorToErrno ();
1949 return error;
1950 }
1951
1952 return error;
1953}
1954
1955static Error
1956ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
1957{
1958 memory_region_info.Clear();
1959
1960 StringExtractor line_extractor (maps_line.c_str ());
1961
1962 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode pathname
1963 // perms: rwxp (letter is present if set, '-' if not, final character is p=private, s=shared).
1964
1965 // Parse out the starting address
1966 lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
1967
1968 // Parse out hyphen separating start and end address from range.
1969 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
1970 return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
1971
1972 // Parse out the ending address
1973 lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
1974
1975 // Parse out the space after the address.
1976 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
1977 return Error ("malformed /proc/{pid}/maps entry, missing space after range");
1978
1979 // Save the range.
1980 memory_region_info.GetRange ().SetRangeBase (start_address);
1981 memory_region_info.GetRange ().SetRangeEnd (end_address);
1982
1983 // Parse out each permission entry.
1984 if (line_extractor.GetBytesLeft () < 4)
1985 return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
1986
1987 // Handle read permission.
1988 const char read_perm_char = line_extractor.GetChar ();
1989 if (read_perm_char == 'r')
1990 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
1991 else
1992 {
1993 assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
1994 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
1995 }
1996
1997 // Handle write permission.
1998 const char write_perm_char = line_extractor.GetChar ();
1999 if (write_perm_char == 'w')
2000 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
2001 else
2002 {
2003 assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
2004 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2005 }
2006
2007 // Handle execute permission.
2008 const char exec_perm_char = line_extractor.GetChar ();
2009 if (exec_perm_char == 'x')
2010 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
2011 else
2012 {
2013 assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
2014 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2015 }
2016
2017 return Error ();
2018}
2019
2020Error
2021NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
2022{
2023 // FIXME review that the final memory region returned extends to the end of the virtual address space,
2024 // with no perms if it is not mapped.
2025
2026 // Use an approach that reads memory regions from /proc/{pid}/maps.
2027 // Assume proc maps entries are in ascending order.
2028 // FIXME assert if we find differently.
2029 Mutex::Locker locker (m_mem_region_cache_mutex);
2030
2031 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2032 Error error;
2033
2034 if (m_supports_mem_region == LazyBool::eLazyBoolNo)
2035 {
2036 // We're done.
2037 error.SetErrorString ("unsupported");
2038 return error;
2039 }
2040
2041 // If our cache is empty, pull the latest. There should always be at least one memory region
2042 // if memory region handling is supported.
2043 if (m_mem_region_cache.empty ())
2044 {
2045 error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
2046 [&] (const std::string &line) -> bool
2047 {
2048 MemoryRegionInfo info;
2049 const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
2050 if (parse_error.Success ())
2051 {
2052 m_mem_region_cache.push_back (info);
2053 return true;
2054 }
2055 else
2056 {
2057 if (log)
2058 log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
2059 return false;
2060 }
2061 });
2062
2063 // If we had an error, we'll mark unsupported.
2064 if (error.Fail ())
2065 {
2066 m_supports_mem_region = LazyBool::eLazyBoolNo;
2067 return error;
2068 }
2069 else if (m_mem_region_cache.empty ())
2070 {
2071 // No entries after attempting to read them. This shouldn't happen if /proc/{pid}/maps
2072 // is supported. Assume we don't support map entries via procfs.
2073 if (log)
2074 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
2075 m_supports_mem_region = LazyBool::eLazyBoolNo;
2076 error.SetErrorString ("not supported");
2077 return error;
2078 }
2079
2080 if (log)
2081 log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ());
2082
2083 // We support memory retrieval, remember that.
2084 m_supports_mem_region = LazyBool::eLazyBoolYes;
2085 }
2086 else
2087 {
2088 if (log)
2089 log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2090 }
2091
2092 lldb::addr_t prev_base_address = 0;
2093
2094 // FIXME start by finding the last region that is <= target address using binary search. Data is sorted.
2095 // There can be a ton of regions on pthreads apps with lots of threads.
2096 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
2097 {
2098 MemoryRegionInfo &proc_entry_info = *it;
2099
2100 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
2101 assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
2102 prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
2103
2104 // If the target address comes before this entry, indicate distance to next region.
2105 if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
2106 {
2107 range_info.GetRange ().SetRangeBase (load_addr);
2108 range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
2109 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2110 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2111 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2112
2113 return error;
2114 }
2115 else if (proc_entry_info.GetRange ().Contains (load_addr))
2116 {
2117 // The target address is within the memory region we're processing here.
2118 range_info = proc_entry_info;
2119 return error;
2120 }
2121
2122 // The target memory address comes somewhere after the region we just parsed.
2123 }
2124
Tamas Berghammer09839c32015-07-03 09:30:19 +00002125 // If we made it here, we didn't find an entry that contained the given address. Return the
2126 // load_addr as start and the amount of bytes betwwen load address and the end of the memory as
2127 // size.
2128 range_info.GetRange ().SetRangeBase (load_addr);
2129 switch (m_arch.GetAddressByteSize())
2130 {
2131 case 4:
2132 range_info.GetRange ().SetByteSize (0x100000000ull - load_addr);
2133 break;
2134 case 8:
2135 range_info.GetRange ().SetByteSize (0ull - load_addr);
2136 break;
2137 default:
2138 assert(false && "Unrecognized data byte size");
2139 break;
2140 }
2141 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2142 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2143 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
Todd Fialaaf245d12014-06-30 21:05:18 +00002144 return error;
2145}
2146
2147void
2148NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
2149{
2150 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2151 if (log)
2152 log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
2153
2154 {
2155 Mutex::Locker locker (m_mem_region_cache_mutex);
2156 if (log)
2157 log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2158 m_mem_region_cache.clear ();
2159 }
2160}
2161
2162Error
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002163NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr)
Todd Fialaaf245d12014-06-30 21:05:18 +00002164{
2165 // FIXME implementing this requires the equivalent of
2166 // InferiorCallPOSIX::InferiorCallMmap, which depends on
2167 // functional ThreadPlans working with Native*Protocol.
2168#if 1
2169 return Error ("not implemented yet");
2170#else
2171 addr = LLDB_INVALID_ADDRESS;
2172
2173 unsigned prot = 0;
2174 if (permissions & lldb::ePermissionsReadable)
2175 prot |= eMmapProtRead;
2176 if (permissions & lldb::ePermissionsWritable)
2177 prot |= eMmapProtWrite;
2178 if (permissions & lldb::ePermissionsExecutable)
2179 prot |= eMmapProtExec;
2180
2181 // TODO implement this directly in NativeProcessLinux
2182 // (and lift to NativeProcessPOSIX if/when that class is
2183 // refactored out).
2184 if (InferiorCallMmap(this, addr, 0, size, prot,
2185 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
2186 m_addr_to_mmap_size[addr] = size;
2187 return Error ();
2188 } else {
2189 addr = LLDB_INVALID_ADDRESS;
2190 return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
2191 }
2192#endif
2193}
2194
2195Error
2196NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
2197{
2198 // FIXME see comments in AllocateMemory - required lower-level
2199 // bits not in place yet (ThreadPlans)
2200 return Error ("not implemented");
2201}
2202
2203lldb::addr_t
2204NativeProcessLinux::GetSharedLibraryInfoAddress ()
2205{
2206#if 1
2207 // punt on this for now
2208 return LLDB_INVALID_ADDRESS;
2209#else
2210 // Return the image info address for the exe module
2211#if 1
2212 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2213
2214 ModuleSP module_sp;
2215 Error error = GetExeModuleSP (module_sp);
2216 if (error.Fail ())
2217 {
2218 if (log)
2219 log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ());
2220 return LLDB_INVALID_ADDRESS;
2221 }
2222
2223 if (module_sp == nullptr)
2224 {
2225 if (log)
2226 log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__);
2227 return LLDB_INVALID_ADDRESS;
2228 }
2229
2230 ObjectFileSP object_file_sp = module_sp->GetObjectFile ();
2231 if (object_file_sp == nullptr)
2232 {
2233 if (log)
2234 log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__);
2235 return LLDB_INVALID_ADDRESS;
2236 }
2237
2238 return obj_file_sp->GetImageInfoAddress();
2239#else
2240 Target *target = &GetTarget();
2241 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
2242 Address addr = obj_file->GetImageInfoAddress(target);
2243
2244 if (addr.IsValid())
2245 return addr.GetLoadAddress(target);
2246 return LLDB_INVALID_ADDRESS;
2247#endif
2248#endif // punt on this for now
2249}
2250
2251size_t
2252NativeProcessLinux::UpdateThreads ()
2253{
2254 // The NativeProcessLinux monitoring threads are always up to date
2255 // with respect to thread state and they keep the thread list
2256 // populated properly. All this method needs to do is return the
2257 // thread count.
2258 Mutex::Locker locker (m_threads_mutex);
2259 return m_threads.size ();
2260}
2261
2262bool
2263NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
2264{
2265 arch = m_arch;
2266 return true;
2267}
2268
2269Error
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002270NativeProcessLinux::GetSoftwareBreakpointPCOffset (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size)
Todd Fialaaf245d12014-06-30 21:05:18 +00002271{
2272 // FIXME put this behind a breakpoint protocol class that can be
2273 // set per architecture. Need ARM, MIPS support here.
2274 static const uint8_t g_i386_opcode [] = { 0xCC };
2275
2276 switch (m_arch.GetMachine ())
2277 {
2278 case llvm::Triple::x86:
2279 case llvm::Triple::x86_64:
2280 actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
2281 return Error ();
2282
Tamas Berghammerff7fd902015-07-03 12:51:30 +00002283 case llvm::Triple::arm:
2284 case llvm::Triple::aarch64:
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00002285 case llvm::Triple::mips64:
2286 case llvm::Triple::mips64el:
Sagar Thakurce815e42015-06-03 10:14:24 +00002287 case llvm::Triple::mips:
2288 case llvm::Triple::mipsel:
Tamas Berghammerff7fd902015-07-03 12:51:30 +00002289 // On these architectures the PC don't get updated for breakpoint hits
Jaydeep Patilc60c9452015-06-23 03:37:08 +00002290 actual_opcode_size = 0;
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00002291 return Error ();
2292
Todd Fialaaf245d12014-06-30 21:05:18 +00002293 default:
2294 assert(false && "CPU type not supported!");
2295 return Error ("CPU type not supported");
2296 }
2297}
2298
2299Error
2300NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
2301{
2302 if (hardware)
2303 return Error ("NativeProcessLinux does not support hardware breakpoints");
2304 else
2305 return SetSoftwareBreakpoint (addr, size);
2306}
2307
2308Error
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002309NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint,
2310 size_t &actual_opcode_size,
2311 const uint8_t *&trap_opcode_bytes)
Todd Fialaaf245d12014-06-30 21:05:18 +00002312{
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002313 // FIXME put this behind a breakpoint protocol class that can be set per
2314 // architecture. Need MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00002315 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002316 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
2317 // linux kernel does otherwise.
2318 static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 };
Todd Fialaaf245d12014-06-30 21:05:18 +00002319 static const uint8_t g_i386_opcode [] = { 0xCC };
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00002320 static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00002321 static const uint8_t g_mips64el_opcode[] = { 0x0d, 0x00, 0x00, 0x00 };
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002322 static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde };
Todd Fialaaf245d12014-06-30 21:05:18 +00002323
2324 switch (m_arch.GetMachine ())
2325 {
Todd Fiala2afc5962014-08-21 16:42:31 +00002326 case llvm::Triple::aarch64:
2327 trap_opcode_bytes = g_aarch64_opcode;
2328 actual_opcode_size = sizeof(g_aarch64_opcode);
2329 return Error ();
2330
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002331 case llvm::Triple::arm:
2332 switch (trap_opcode_size_hint)
2333 {
2334 case 2:
2335 trap_opcode_bytes = g_thumb_breakpoint_opcode;
2336 actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
2337 return Error ();
2338 case 4:
2339 trap_opcode_bytes = g_arm_breakpoint_opcode;
2340 actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
2341 return Error ();
2342 default:
2343 assert(false && "Unrecognised trap opcode size hint!");
2344 return Error ("Unrecognised trap opcode size hint!");
2345 }
2346
Todd Fialaaf245d12014-06-30 21:05:18 +00002347 case llvm::Triple::x86:
2348 case llvm::Triple::x86_64:
2349 trap_opcode_bytes = g_i386_opcode;
2350 actual_opcode_size = sizeof(g_i386_opcode);
2351 return Error ();
2352
Sagar Thakurce815e42015-06-03 10:14:24 +00002353 case llvm::Triple::mips:
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00002354 case llvm::Triple::mips64:
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00002355 trap_opcode_bytes = g_mips64_opcode;
2356 actual_opcode_size = sizeof(g_mips64_opcode);
2357 return Error ();
2358
Sagar Thakurce815e42015-06-03 10:14:24 +00002359 case llvm::Triple::mipsel:
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00002360 case llvm::Triple::mips64el:
2361 trap_opcode_bytes = g_mips64el_opcode;
2362 actual_opcode_size = sizeof(g_mips64el_opcode);
2363 return Error ();
2364
Todd Fialaaf245d12014-06-30 21:05:18 +00002365 default:
2366 assert(false && "CPU type not supported!");
2367 return Error ("CPU type not supported");
2368 }
2369}
2370
2371#if 0
2372ProcessMessage::CrashReason
2373NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
2374{
2375 ProcessMessage::CrashReason reason;
2376 assert(info->si_signo == SIGSEGV);
2377
2378 reason = ProcessMessage::eInvalidCrashReason;
2379
2380 switch (info->si_code)
2381 {
2382 default:
2383 assert(false && "unexpected si_code for SIGSEGV");
2384 break;
2385 case SI_KERNEL:
2386 // Linux will occasionally send spurious SI_KERNEL codes.
2387 // (this is poorly documented in sigaction)
2388 // One way to get this is via unaligned SIMD loads.
2389 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
2390 break;
2391 case SEGV_MAPERR:
2392 reason = ProcessMessage::eInvalidAddress;
2393 break;
2394 case SEGV_ACCERR:
2395 reason = ProcessMessage::ePrivilegedAddress;
2396 break;
2397 }
2398
2399 return reason;
2400}
2401#endif
2402
2403
2404#if 0
2405ProcessMessage::CrashReason
2406NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
2407{
2408 ProcessMessage::CrashReason reason;
2409 assert(info->si_signo == SIGILL);
2410
2411 reason = ProcessMessage::eInvalidCrashReason;
2412
2413 switch (info->si_code)
2414 {
2415 default:
2416 assert(false && "unexpected si_code for SIGILL");
2417 break;
2418 case ILL_ILLOPC:
2419 reason = ProcessMessage::eIllegalOpcode;
2420 break;
2421 case ILL_ILLOPN:
2422 reason = ProcessMessage::eIllegalOperand;
2423 break;
2424 case ILL_ILLADR:
2425 reason = ProcessMessage::eIllegalAddressingMode;
2426 break;
2427 case ILL_ILLTRP:
2428 reason = ProcessMessage::eIllegalTrap;
2429 break;
2430 case ILL_PRVOPC:
2431 reason = ProcessMessage::ePrivilegedOpcode;
2432 break;
2433 case ILL_PRVREG:
2434 reason = ProcessMessage::ePrivilegedRegister;
2435 break;
2436 case ILL_COPROC:
2437 reason = ProcessMessage::eCoprocessorError;
2438 break;
2439 case ILL_BADSTK:
2440 reason = ProcessMessage::eInternalStackError;
2441 break;
2442 }
2443
2444 return reason;
2445}
2446#endif
2447
2448#if 0
2449ProcessMessage::CrashReason
2450NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
2451{
2452 ProcessMessage::CrashReason reason;
2453 assert(info->si_signo == SIGFPE);
2454
2455 reason = ProcessMessage::eInvalidCrashReason;
2456
2457 switch (info->si_code)
2458 {
2459 default:
2460 assert(false && "unexpected si_code for SIGFPE");
2461 break;
2462 case FPE_INTDIV:
2463 reason = ProcessMessage::eIntegerDivideByZero;
2464 break;
2465 case FPE_INTOVF:
2466 reason = ProcessMessage::eIntegerOverflow;
2467 break;
2468 case FPE_FLTDIV:
2469 reason = ProcessMessage::eFloatDivideByZero;
2470 break;
2471 case FPE_FLTOVF:
2472 reason = ProcessMessage::eFloatOverflow;
2473 break;
2474 case FPE_FLTUND:
2475 reason = ProcessMessage::eFloatUnderflow;
2476 break;
2477 case FPE_FLTRES:
2478 reason = ProcessMessage::eFloatInexactResult;
2479 break;
2480 case FPE_FLTINV:
2481 reason = ProcessMessage::eFloatInvalidOperation;
2482 break;
2483 case FPE_FLTSUB:
2484 reason = ProcessMessage::eFloatSubscriptRange;
2485 break;
2486 }
2487
2488 return reason;
2489}
2490#endif
2491
2492#if 0
2493ProcessMessage::CrashReason
2494NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
2495{
2496 ProcessMessage::CrashReason reason;
2497 assert(info->si_signo == SIGBUS);
2498
2499 reason = ProcessMessage::eInvalidCrashReason;
2500
2501 switch (info->si_code)
2502 {
2503 default:
2504 assert(false && "unexpected si_code for SIGBUS");
2505 break;
2506 case BUS_ADRALN:
2507 reason = ProcessMessage::eIllegalAlignment;
2508 break;
2509 case BUS_ADRERR:
2510 reason = ProcessMessage::eIllegalAddress;
2511 break;
2512 case BUS_OBJERR:
2513 reason = ProcessMessage::eHardwareError;
2514 break;
2515 }
2516
2517 return reason;
2518}
2519#endif
2520
Todd Fialaaf245d12014-06-30 21:05:18 +00002521Error
Chaoren Lin26438d22015-05-05 17:50:53 +00002522NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
Todd Fialaaf245d12014-06-30 21:05:18 +00002523{
Pavel Labathdf7c6992015-06-17 18:38:49 +00002524 if (ProcessVmReadvSupported()) {
2525 // The process_vm_readv path is about 50 times faster than ptrace api. We want to use
2526 // this syscall if it is supported.
2527
2528 const ::pid_t pid = GetID();
2529
2530 struct iovec local_iov, remote_iov;
2531 local_iov.iov_base = buf;
2532 local_iov.iov_len = size;
2533 remote_iov.iov_base = reinterpret_cast<void *>(addr);
2534 remote_iov.iov_len = size;
2535
2536 bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
2537 const bool success = bytes_read == size;
2538
2539 Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2540 if (log)
2541 log->Printf ("NativeProcessLinux::%s using process_vm_readv to read %zd bytes from inferior address 0x%" PRIx64": %s",
2542 __FUNCTION__, size, addr, success ? "Success" : strerror(errno));
2543
2544 if (success)
2545 return Error();
2546 // else
2547 // the call failed for some reason, let's retry the read using ptrace api.
2548 }
2549
Pavel Labath19cbe962015-07-21 13:20:32 +00002550 unsigned char *dst = static_cast<unsigned char*>(buf);
2551 size_t remainder;
2552 long data;
2553
2554 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
2555 if (log)
2556 ProcessPOSIXLog::IncNestLevel();
2557 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
2558 log->Printf ("NativeProcessLinux::%s(%p, %p, %zd, _)", __FUNCTION__, (void*)addr, buf, size);
2559
2560 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
2561 {
2562 Error error = NativeProcessLinux::PtraceWrapper(PTRACE_PEEKDATA, GetID(), (void*)addr, nullptr, 0, &data);
2563 if (error.Fail())
2564 {
2565 if (log)
2566 ProcessPOSIXLog::DecNestLevel();
2567 return error;
2568 }
2569
2570 remainder = size - bytes_read;
2571 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
2572
2573 // Copy the data into our buffer
2574 for (unsigned i = 0; i < remainder; ++i)
2575 dst[i] = ((data >> i*8) & 0xFF);
2576
2577 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2578 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
2579 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2580 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
2581 {
2582 uintptr_t print_dst = 0;
2583 // Format bytes from data by moving into print_dst for log output
2584 for (unsigned i = 0; i < remainder; ++i)
2585 print_dst |= (((data >> i*8) & 0xFF) << i*8);
Pavel Labath79203992015-07-23 13:07:37 +00002586 log->Printf ("NativeProcessLinux::%s() [0x%" PRIx64 "]:0x%" PRIx64 " (0x%" PRIx64 ")",
2587 __FUNCTION__, addr, uint64_t(print_dst), uint64_t(data));
Pavel Labath19cbe962015-07-21 13:20:32 +00002588 }
2589 addr += k_ptrace_word_size;
2590 dst += k_ptrace_word_size;
2591 }
2592
2593 if (log)
2594 ProcessPOSIXLog::DecNestLevel();
2595 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00002596}
2597
2598Error
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002599NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
2600{
2601 Error error = ReadMemory(addr, buf, size, bytes_read);
2602 if (error.Fail()) return error;
2603 return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
2604}
2605
2606Error
2607NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written)
Todd Fialaaf245d12014-06-30 21:05:18 +00002608{
Pavel Labath19cbe962015-07-21 13:20:32 +00002609 const unsigned char *src = static_cast<const unsigned char*>(buf);
2610 size_t remainder;
2611 Error error;
2612
2613 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
2614 if (log)
2615 ProcessPOSIXLog::IncNestLevel();
2616 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
Pavel Labath79203992015-07-23 13:07:37 +00002617 log->Printf ("NativeProcessLinux::%s(0x%" PRIx64 ", %p, %zu)", __FUNCTION__, addr, buf, size);
Pavel Labath19cbe962015-07-21 13:20:32 +00002618
2619 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
2620 {
2621 remainder = size - bytes_written;
2622 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
2623
2624 if (remainder == k_ptrace_word_size)
2625 {
2626 unsigned long data = 0;
2627 for (unsigned i = 0; i < k_ptrace_word_size; ++i)
2628 data |= (unsigned long)src[i] << i*8;
2629
2630 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2631 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
2632 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2633 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
2634 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
2635 (void*)addr, *(const unsigned long*)src, data);
2636
2637 error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(), (void*)addr, (void*)data);
2638 if (error.Fail())
2639 {
2640 if (log)
2641 ProcessPOSIXLog::DecNestLevel();
2642 return error;
2643 }
2644 }
2645 else
2646 {
2647 unsigned char buff[8];
2648 size_t bytes_read;
2649 error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
2650 if (error.Fail())
2651 {
2652 if (log)
2653 ProcessPOSIXLog::DecNestLevel();
2654 return error;
2655 }
2656
2657 memcpy(buff, src, remainder);
2658
2659 size_t bytes_written_rec;
2660 error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
2661 if (error.Fail())
2662 {
2663 if (log)
2664 ProcessPOSIXLog::DecNestLevel();
2665 return error;
2666 }
2667
2668 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2669 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
2670 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2671 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
2672 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
2673 (void*)addr, *(const unsigned long*)src, *(unsigned long*)buff);
2674 }
2675
2676 addr += k_ptrace_word_size;
2677 src += k_ptrace_word_size;
2678 }
2679 if (log)
2680 ProcessPOSIXLog::DecNestLevel();
2681 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002682}
2683
Chaoren Lin97ccc292015-02-03 01:51:12 +00002684Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002685NativeProcessLinux::Resume (lldb::tid_t tid, uint32_t signo)
2686{
Todd Fialaaf245d12014-06-30 21:05:18 +00002687 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2688
2689 if (log)
2690 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid,
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00002691 Host::GetSignalAsCString(signo));
Pavel Labathc7512fd2015-06-26 10:14:12 +00002692
2693
2694
2695 intptr_t data = 0;
2696
2697 if (signo != LLDB_INVALID_SIGNAL_NUMBER)
2698 data = signo;
2699
Pavel Labath19cbe962015-07-21 13:20:32 +00002700 Error error = PtraceWrapper(PTRACE_CONT, tid, nullptr, (void*)data);
Pavel Labathc7512fd2015-06-26 10:14:12 +00002701
Todd Fialaaf245d12014-06-30 21:05:18 +00002702 if (log)
Pavel Labathc7512fd2015-06-26 10:14:12 +00002703 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " result = %s", __FUNCTION__, tid, error.Success() ? "true" : "false");
2704 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002705}
2706
Chaoren Lin97ccc292015-02-03 01:51:12 +00002707Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002708NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo)
2709{
Pavel Labathc7512fd2015-06-26 10:14:12 +00002710 intptr_t data = 0;
2711
2712 if (signo != LLDB_INVALID_SIGNAL_NUMBER)
2713 data = signo;
2714
Pavel Labath0e1d7292015-08-20 09:06:12 +00002715 // If hardware single-stepping is not supported, we just do a continue. The breakpoint on the
2716 // next instruction has been setup in NativeProcessLinux::Resume.
2717 return PtraceWrapper(SupportHardwareSingleStepping() ? PTRACE_SINGLESTEP : PTRACE_CONT,
2718 tid, nullptr, (void*)data);
Todd Fialaaf245d12014-06-30 21:05:18 +00002719}
2720
Chaoren Lin97ccc292015-02-03 01:51:12 +00002721Error
2722NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
Todd Fialaaf245d12014-06-30 21:05:18 +00002723{
Pavel Labath19cbe962015-07-21 13:20:32 +00002724 return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
Todd Fialaaf245d12014-06-30 21:05:18 +00002725}
2726
Chaoren Lin97ccc292015-02-03 01:51:12 +00002727Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002728NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
2729{
Pavel Labath19cbe962015-07-21 13:20:32 +00002730 return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
Todd Fialaaf245d12014-06-30 21:05:18 +00002731}
2732
Tamas Berghammerdb264a62015-03-31 09:52:22 +00002733Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002734NativeProcessLinux::Detach(lldb::tid_t tid)
2735{
Chaoren Lin97ccc292015-02-03 01:51:12 +00002736 if (tid == LLDB_INVALID_THREAD_ID)
2737 return Error();
2738
Pavel Labath19cbe962015-07-21 13:20:32 +00002739 return PtraceWrapper(PTRACE_DETACH, tid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002740}
2741
2742bool
Chaoren Lind3173f32015-05-29 19:52:29 +00002743NativeProcessLinux::DupDescriptor(const FileSpec &file_spec, int fd, int flags)
Todd Fialaaf245d12014-06-30 21:05:18 +00002744{
Chaoren Lind3173f32015-05-29 19:52:29 +00002745 int target_fd = open(file_spec.GetCString(), flags, 0666);
Todd Fialaaf245d12014-06-30 21:05:18 +00002746
2747 if (target_fd == -1)
2748 return false;
2749
Pavel Labath493c3a12015-02-04 10:36:57 +00002750 if (dup2(target_fd, fd) == -1)
2751 return false;
2752
2753 return (close(target_fd) == -1) ? false : true;
Todd Fialaaf245d12014-06-30 21:05:18 +00002754}
2755
Todd Fialaaf245d12014-06-30 21:05:18 +00002756bool
2757NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
2758{
2759 for (auto thread_sp : m_threads)
2760 {
2761 assert (thread_sp && "thread list should not contain NULL threads");
2762 if (thread_sp->GetID () == thread_id)
2763 {
2764 // We have this thread.
2765 return true;
2766 }
2767 }
2768
2769 // We don't have this thread.
2770 return false;
2771}
2772
2773NativeThreadProtocolSP
2774NativeProcessLinux::MaybeGetThreadNoLock (lldb::tid_t thread_id)
2775{
2776 // CONSIDER organize threads by map - we can do better than linear.
2777 for (auto thread_sp : m_threads)
2778 {
2779 if (thread_sp->GetID () == thread_id)
2780 return thread_sp;
2781 }
2782
2783 // We don't have this thread.
2784 return NativeThreadProtocolSP ();
2785}
2786
2787bool
2788NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
2789{
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002790 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
2791
2792 if (log)
2793 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, thread_id);
2794
2795 bool found = false;
2796
Todd Fialaaf245d12014-06-30 21:05:18 +00002797 Mutex::Locker locker (m_threads_mutex);
2798 for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
2799 {
2800 if (*it && ((*it)->GetID () == thread_id))
2801 {
2802 m_threads.erase (it);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002803 found = true;
2804 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00002805 }
2806 }
2807
Pavel Labath0e1d7292015-08-20 09:06:12 +00002808 SignalIfAllThreadsStopped();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002809
2810 return found;
Todd Fialaaf245d12014-06-30 21:05:18 +00002811}
2812
Pavel Labathf9077782015-08-21 09:13:53 +00002813NativeThreadLinuxSP
Todd Fialaaf245d12014-06-30 21:05:18 +00002814NativeProcessLinux::AddThread (lldb::tid_t thread_id)
2815{
2816 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
2817
2818 Mutex::Locker locker (m_threads_mutex);
2819
2820 if (log)
2821 {
2822 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
2823 __FUNCTION__,
2824 GetID (),
2825 thread_id);
2826 }
2827
2828 assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
2829
2830 // If this is the first thread, save it as the current thread
2831 if (m_threads.empty ())
2832 SetCurrentThreadID (thread_id);
2833
Pavel Labathf9077782015-08-21 09:13:53 +00002834 auto thread_sp = std::make_shared<NativeThreadLinux>(this, thread_id);
Todd Fialaaf245d12014-06-30 21:05:18 +00002835 m_threads.push_back (thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00002836 return thread_sp;
2837}
2838
Todd Fialaaf245d12014-06-30 21:05:18 +00002839Error
Pavel Labathf9077782015-08-21 09:13:53 +00002840NativeProcessLinux::FixupBreakpointPCAsNeeded(const NativeThreadLinuxSP &thread_sp)
Todd Fialaaf245d12014-06-30 21:05:18 +00002841{
Todd Fiala75f47c32014-10-11 21:42:09 +00002842 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Todd Fialaaf245d12014-06-30 21:05:18 +00002843
2844 Error error;
2845
Todd Fialaaf245d12014-06-30 21:05:18 +00002846 if (!thread_sp)
2847 {
2848 error.SetErrorString ("null thread_sp");
2849 if (log)
2850 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
2851 return error;
2852 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002853
2854 // Find out the size of a breakpoint (might depend on where we are in the code).
Pavel Labathf9077782015-08-21 09:13:53 +00002855 NativeRegisterContextSP context_sp = thread_sp->GetRegisterContext();
Todd Fialaaf245d12014-06-30 21:05:18 +00002856 if (!context_sp)
2857 {
2858 error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
2859 if (log)
2860 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
2861 return error;
2862 }
2863
2864 uint32_t breakpoint_size = 0;
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002865 error = GetSoftwareBreakpointPCOffset (context_sp, breakpoint_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00002866 if (error.Fail ())
2867 {
2868 if (log)
2869 log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
2870 return error;
2871 }
2872 else
2873 {
2874 if (log)
2875 log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
2876 }
2877
2878 // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
Jaydeep Patilc60c9452015-06-23 03:37:08 +00002879 const lldb::addr_t initial_pc_addr = context_sp->GetPCfromBreakpointLocation ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002880 lldb::addr_t breakpoint_addr = initial_pc_addr;
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002881 if (breakpoint_size > 0)
Todd Fialaaf245d12014-06-30 21:05:18 +00002882 {
2883 // Do not allow breakpoint probe to wrap around.
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002884 if (breakpoint_addr >= breakpoint_size)
2885 breakpoint_addr -= breakpoint_size;
Todd Fialaaf245d12014-06-30 21:05:18 +00002886 }
2887
2888 // Check if we stopped because of a breakpoint.
2889 NativeBreakpointSP breakpoint_sp;
2890 error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
2891 if (!error.Success () || !breakpoint_sp)
2892 {
2893 // We didn't find one at a software probe location. Nothing to do.
2894 if (log)
2895 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
2896 return Error ();
2897 }
2898
2899 // If the breakpoint is not a software breakpoint, nothing to do.
2900 if (!breakpoint_sp->IsSoftwareBreakpoint ())
2901 {
2902 if (log)
2903 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
2904 return Error ();
2905 }
2906
2907 //
2908 // We have a software breakpoint and need to adjust the PC.
2909 //
2910
2911 // Sanity check.
2912 if (breakpoint_size == 0)
2913 {
2914 // Nothing to do! How did we get here?
2915 if (log)
2916 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);
2917 return Error ();
2918 }
2919
2920 // Change the program counter.
2921 if (log)
Pavel Labathf9077782015-08-21 09:13:53 +00002922 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": changing PC from 0x%" PRIx64 " to 0x%" PRIx64, __FUNCTION__, GetID(), thread_sp->GetID(), initial_pc_addr, breakpoint_addr);
Todd Fialaaf245d12014-06-30 21:05:18 +00002923
2924 error = context_sp->SetPC (breakpoint_addr);
2925 if (error.Fail ())
2926 {
2927 if (log)
Pavel Labathf9077782015-08-21 09:13:53 +00002928 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": failed to set PC: %s", __FUNCTION__, GetID(), thread_sp->GetID(), error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00002929 return error;
2930 }
2931
2932 return error;
2933}
Chaoren Linfa03ad22015-02-03 01:50:42 +00002934
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00002935Error
2936NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec)
2937{
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00002938 FileSpec module_file_spec(module_path, true);
2939
Pavel Labath162fb8e2015-07-23 14:47:33 +00002940 bool found = false;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00002941 file_spec.Clear();
Pavel Labath162fb8e2015-07-23 14:47:33 +00002942 ProcFileReader::ProcessLineByLine(GetID(), "maps",
2943 [&] (const std::string &line)
2944 {
2945 SmallVector<StringRef, 16> columns;
2946 StringRef(line).split(columns, " ", -1, false);
2947 if (columns.size() < 6)
2948 return true; // continue searching
2949
2950 FileSpec this_file_spec(columns[5].str().c_str(), false);
2951 if (this_file_spec.GetFilename() != module_file_spec.GetFilename())
2952 return true; // continue searching
2953
2954 file_spec = this_file_spec;
2955 found = true;
2956 return false; // we are done
2957 });
2958
2959 if (! found)
2960 return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
2961 module_file_spec.GetFilename().AsCString(), GetID());
2962
2963 return Error();
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00002964}
Pavel Labathc0765592015-05-06 10:46:34 +00002965
Pavel Labath5eb721e2015-05-07 08:30:31 +00002966Error
Tamas Berghammer783bfc82015-06-18 20:43:56 +00002967NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef& file_name, lldb::addr_t& load_addr)
2968{
2969 load_addr = LLDB_INVALID_ADDRESS;
2970 Error error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
2971 [&] (const std::string &line) -> bool
2972 {
2973 StringRef maps_row(line);
2974
2975 SmallVector<StringRef, 16> maps_columns;
2976 maps_row.split(maps_columns, StringRef(" "), -1, false);
2977
2978 if (maps_columns.size() < 6)
2979 {
2980 // Return true to continue reading the proc file
2981 return true;
2982 }
2983
2984 if (maps_columns[5] == file_name)
2985 {
2986 StringExtractor addr_extractor(maps_columns[0].str().c_str());
2987 load_addr = addr_extractor.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2988
2989 // Return false to stop reading the proc file further
2990 return false;
2991 }
2992
2993 // Return true to continue reading the proc file
2994 return true;
2995 });
2996 return error;
2997}
2998
Pavel Labathf9077782015-08-21 09:13:53 +00002999NativeThreadLinuxSP
3000NativeProcessLinux::GetThreadByID(lldb::tid_t tid)
3001{
3002 return std::static_pointer_cast<NativeThreadLinux>(NativeProcessProtocol::GetThreadByID(tid));
3003}
3004
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003005Error
Pavel Labath0e1d7292015-08-20 09:06:12 +00003006NativeProcessLinux::ResumeThread(const NativeThreadLinuxSP &thread_sp, lldb::StateType state, int signo)
Pavel Labathc0765592015-05-06 10:46:34 +00003007{
Pavel Labath5eb721e2015-05-07 08:30:31 +00003008 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003009
3010 if (log)
Pavel Labath0e1d7292015-08-20 09:06:12 +00003011 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")",
3012 __FUNCTION__, thread_sp->GetID());
Pavel Labath5eb721e2015-05-07 08:30:31 +00003013
Pavel Labathc0765592015-05-06 10:46:34 +00003014 // Before we do the resume below, first check if we have a pending
Pavel Labath108c3252015-05-12 09:03:18 +00003015 // stop notification that is currently waiting for
Pavel Labath0e1d7292015-08-20 09:06:12 +00003016 // all threads to stop. This is potentially a buggy situation since
Pavel Labathc0765592015-05-06 10:46:34 +00003017 // we're ostensibly waiting for threads to stop before we send out the
3018 // pending notification, and here we are resuming one before we send
3019 // out the pending stop notification.
Pavel Labath0e1d7292015-08-20 09:06:12 +00003020 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID && log)
Pavel Labathc0765592015-05-06 10:46:34 +00003021 {
Pavel Labath0e1d7292015-08-20 09:06:12 +00003022 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_sp->GetID(), m_pending_notification_tid);
Pavel Labathc0765592015-05-06 10:46:34 +00003023 }
3024
3025 // Request a resume. We expect this to be synchronous and the system
3026 // to reflect it is running after this completes.
Pavel Labath0e1d7292015-08-20 09:06:12 +00003027 switch (state)
Pavel Labathc0765592015-05-06 10:46:34 +00003028 {
Pavel Labath0e1d7292015-08-20 09:06:12 +00003029 case eStateRunning:
3030 {
3031 thread_sp->SetRunning();
3032 const auto resume_result = Resume(thread_sp->GetID(), signo);
3033 if (resume_result.Success())
3034 SetState(eStateRunning, true);
3035 return resume_result;
Pavel Labathc0765592015-05-06 10:46:34 +00003036 }
Pavel Labath0e1d7292015-08-20 09:06:12 +00003037 case eStateStepping:
3038 {
3039 thread_sp->SetStepping();
3040 const auto step_result = SingleStep(thread_sp->GetID(), signo);
3041 if (step_result.Success())
3042 SetState(eStateRunning, true);
3043 return step_result;
3044 }
3045 default:
3046 if (log)
3047 log->Printf("NativeProcessLinux::%s Unhandled state %s.",
3048 __FUNCTION__, StateAsCString(state));
3049 llvm_unreachable("Unhandled state for resume");
3050 }
Pavel Labathc0765592015-05-06 10:46:34 +00003051}
3052
3053//===----------------------------------------------------------------------===//
3054
3055void
Pavel Labath337f3eb2015-05-08 08:57:45 +00003056NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid)
Pavel Labathc0765592015-05-06 10:46:34 +00003057{
Pavel Labath5eb721e2015-05-07 08:30:31 +00003058 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00003059
Pavel Labath5eb721e2015-05-07 08:30:31 +00003060 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00003061 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00003062 log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ")",
Pavel Labathc0765592015-05-06 10:46:34 +00003063 __FUNCTION__, triggering_tid);
3064 }
3065
Pavel Labath0e1d7292015-08-20 09:06:12 +00003066 m_pending_notification_tid = triggering_tid;
3067
3068 // Request a stop for all the thread stops that need to be stopped
3069 // and are not already known to be stopped.
3070 for (const auto &thread_sp: m_threads)
3071 {
3072 if (StateIsRunningState(thread_sp->GetState()))
3073 static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
3074 }
3075
3076 SignalIfAllThreadsStopped();
Pavel Labathc0765592015-05-06 10:46:34 +00003077
Pavel Labath5eb721e2015-05-07 08:30:31 +00003078 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00003079 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00003080 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00003081 }
3082}
3083
3084void
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003085NativeProcessLinux::SignalIfAllThreadsStopped()
Pavel Labathc0765592015-05-06 10:46:34 +00003086{
Pavel Labath0e1d7292015-08-20 09:06:12 +00003087 if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
3088 return; // No pending notification. Nothing to do.
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003089
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003090 for (const auto &thread_sp: m_threads)
Pavel Labathc0765592015-05-06 10:46:34 +00003091 {
Pavel Labath0e1d7292015-08-20 09:06:12 +00003092 if (StateIsRunningState(thread_sp->GetState()))
3093 return; // Some threads are still running. Don't signal yet.
Pavel Labathc0765592015-05-06 10:46:34 +00003094 }
3095
Pavel Labath0e1d7292015-08-20 09:06:12 +00003096 // We have a pending notification and all threads have stopped.
3097 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
Pavel Labathc0765592015-05-06 10:46:34 +00003098
Pavel Labath0e1d7292015-08-20 09:06:12 +00003099 // Clear any temporary breakpoints we used to implement software single stepping.
3100 for (const auto &thread_info: m_threads_stepping_with_breakpoint)
Pavel Labathc0765592015-05-06 10:46:34 +00003101 {
Pavel Labath0e1d7292015-08-20 09:06:12 +00003102 Error error = RemoveBreakpoint (thread_info.second);
3103 if (error.Fail())
3104 if (log)
3105 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " remove stepping breakpoint: %s",
3106 __FUNCTION__, thread_info.first, error.AsCString());
Pavel Labathc0765592015-05-06 10:46:34 +00003107 }
Pavel Labath0e1d7292015-08-20 09:06:12 +00003108 m_threads_stepping_with_breakpoint.clear();
Pavel Labathc0765592015-05-06 10:46:34 +00003109
Pavel Labath0e1d7292015-08-20 09:06:12 +00003110 // Notify the delegate about the stop
3111 SetCurrentThreadID(m_pending_notification_tid);
3112 SetState(StateType::eStateStopped, true);
3113 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
Pavel Labathc0765592015-05-06 10:46:34 +00003114}
3115
3116void
Pavel Labathf9077782015-08-21 09:13:53 +00003117NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread)
Pavel Labathc0765592015-05-06 10:46:34 +00003118{
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003119 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3120
3121 if (log)
Pavel Labathf9077782015-08-21 09:13:53 +00003122 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, thread.GetID());
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003123
Pavel Labathf9077782015-08-21 09:13:53 +00003124 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID && StateIsRunningState(thread.GetState()))
Pavel Labathc0765592015-05-06 10:46:34 +00003125 {
3126 // We will need to wait for this new thread to stop as well before firing the
3127 // notification.
Pavel Labathf9077782015-08-21 09:13:53 +00003128 thread.RequestStop();
Pavel Labathc0765592015-05-06 10:46:34 +00003129 }
3130}
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003131
Pavel Labath19cbe962015-07-21 13:20:32 +00003132void
3133NativeProcessLinux::SigchldHandler()
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003134{
Pavel Labath19cbe962015-07-21 13:20:32 +00003135 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3136 // Process all pending waitpid notifications.
3137 while (true)
3138 {
3139 int status = -1;
3140 ::pid_t wait_pid = waitpid(-1, &status, __WALL | __WNOTHREAD | WNOHANG);
3141
3142 if (wait_pid == 0)
3143 break; // We are done.
3144
3145 if (wait_pid == -1)
3146 {
3147 if (errno == EINTR)
3148 continue;
3149
3150 Error error(errno, eErrorTypePOSIX);
3151 if (log)
3152 log->Printf("NativeProcessLinux::%s waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG) failed: %s",
3153 __FUNCTION__, error.AsCString());
3154 break;
3155 }
3156
3157 bool exited = false;
3158 int signal = 0;
3159 int exit_status = 0;
3160 const char *status_cstr = nullptr;
3161 if (WIFSTOPPED(status))
3162 {
3163 signal = WSTOPSIG(status);
3164 status_cstr = "STOPPED";
3165 }
3166 else if (WIFEXITED(status))
3167 {
3168 exit_status = WEXITSTATUS(status);
3169 status_cstr = "EXITED";
3170 exited = true;
3171 }
3172 else if (WIFSIGNALED(status))
3173 {
3174 signal = WTERMSIG(status);
3175 status_cstr = "SIGNALED";
Omair Javaiddee4a862015-08-19 10:44:16 +00003176 if (wait_pid == static_cast< ::pid_t>(GetID())) {
Pavel Labath19cbe962015-07-21 13:20:32 +00003177 exited = true;
3178 exit_status = -1;
3179 }
3180 }
3181 else
3182 status_cstr = "(\?\?\?)";
3183
3184 if (log)
3185 log->Printf("NativeProcessLinux::%s: waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG)"
3186 "=> pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
3187 __FUNCTION__, wait_pid, status, status_cstr, signal, exit_status);
3188
3189 MonitorCallback (wait_pid, exited, signal, exit_status);
3190 }
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003191}
3192
3193// Wrapper for ptrace to catch errors and log calls.
3194// 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 +00003195Error
3196NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, long *result)
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003197{
Pavel Labath4a9babb2015-06-30 17:04:49 +00003198 Error error;
3199 long int ret;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003200
3201 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
3202
3203 PtraceDisplayBytes(req, data, data_size);
3204
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003205 errno = 0;
3206 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Pavel Labath4a9babb2015-06-30 17:04:49 +00003207 ret = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003208 else
Pavel Labath4a9babb2015-06-30 17:04:49 +00003209 ret = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003210
Pavel Labath4a9babb2015-06-30 17:04:49 +00003211 if (ret == -1)
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003212 error.SetErrorToErrno();
3213
Pavel Labath4a9babb2015-06-30 17:04:49 +00003214 if (result)
3215 *result = ret;
3216
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003217 if (log)
Pavel Labath4a9babb2015-06-30 17:04:49 +00003218 log->Printf("ptrace(%d, %" PRIu64 ", %p, %p, %zu)=%lX", req, pid, addr, data, data_size, ret);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003219
3220 PtraceDisplayBytes(req, data, data_size);
3221
3222 if (log && error.GetError() != 0)
3223 {
3224 const char* str;
3225 switch (error.GetError())
3226 {
3227 case ESRCH: str = "ESRCH"; break;
3228 case EINVAL: str = "EINVAL"; break;
3229 case EBUSY: str = "EBUSY"; break;
3230 case EPERM: str = "EPERM"; break;
3231 default: str = error.AsCString();
3232 }
3233 log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
3234 }
3235
Pavel Labath4a9babb2015-06-30 17:04:49 +00003236 return error;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003237}