blob: b4afe6246979fc1394addf3cfe8df1c390d4d6b9 [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 Labath8c8ff7a2015-05-11 10:03:10 +0000431 m_mem_region_cache_mutex ()
Todd Fialaaf245d12014-06-30 21:05:18 +0000432{
433}
434
Todd Fialaaf245d12014-06-30 21:05:18 +0000435void
436NativeProcessLinux::LaunchInferior (
Pavel Labath19cbe962015-07-21 13:20:32 +0000437 MainLoop &mainloop,
Todd Fialaaf245d12014-06-30 21:05:18 +0000438 Module *module,
439 const char *argv[],
440 const char *envp[],
Chaoren Lind3173f32015-05-29 19:52:29 +0000441 const FileSpec &stdin_file_spec,
442 const FileSpec &stdout_file_spec,
443 const FileSpec &stderr_file_spec,
444 const FileSpec &working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000445 const ProcessLaunchInfo &launch_info,
446 Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000447{
Pavel Labath19cbe962015-07-21 13:20:32 +0000448 m_sigchld_handle = mainloop.RegisterSignal(SIGCHLD,
449 [this] (MainLoopBase &) { SigchldHandler(); }, error);
450 if (! m_sigchld_handle)
451 return;
452
Todd Fialaaf245d12014-06-30 21:05:18 +0000453 if (module)
454 m_arch = module->GetArchitecture ();
455
Chaoren Linfa03ad22015-02-03 01:50:42 +0000456 SetState (eStateLaunching);
Todd Fialaaf245d12014-06-30 21:05:18 +0000457
458 std::unique_ptr<LaunchArgs> args(
Chaoren Lind3173f32015-05-29 19:52:29 +0000459 new LaunchArgs(module, argv, envp,
460 stdin_file_spec,
461 stdout_file_spec,
462 stderr_file_spec,
463 working_dir,
464 launch_info));
Todd Fialaaf245d12014-06-30 21:05:18 +0000465
Pavel Labath19cbe962015-07-21 13:20:32 +0000466 Launch(args.get(), error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000467}
468
469void
Pavel Labath19cbe962015-07-21 13:20:32 +0000470NativeProcessLinux::AttachToInferior (MainLoop &mainloop, lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000471{
472 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
473 if (log)
474 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
475
Pavel Labath19cbe962015-07-21 13:20:32 +0000476 m_sigchld_handle = mainloop.RegisterSignal(SIGCHLD,
477 [this] (MainLoopBase &) { SigchldHandler(); }, error);
478 if (! m_sigchld_handle)
479 return;
480
Todd Fialaaf245d12014-06-30 21:05:18 +0000481 // We can use the Host for everything except the ResolveExecutable portion.
Greg Clayton615eb7e2014-09-19 20:11:50 +0000482 PlatformSP platform_sp = Platform::GetHostPlatform ();
Todd Fialaaf245d12014-06-30 21:05:18 +0000483 if (!platform_sp)
484 {
485 if (log)
486 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): no default platform set", __FUNCTION__, pid);
487 error.SetErrorString ("no default platform available");
Shawn Best50d60be2014-11-11 00:28:52 +0000488 return;
Todd Fialaaf245d12014-06-30 21:05:18 +0000489 }
490
491 // Gather info about the process.
492 ProcessInstanceInfo process_info;
Shawn Best50d60be2014-11-11 00:28:52 +0000493 if (!platform_sp->GetProcessInfo (pid, process_info))
494 {
495 if (log)
496 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): failed to get process info", __FUNCTION__, pid);
497 error.SetErrorString ("failed to get process info");
498 return;
499 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000500
501 // Resolve the executable module
502 ModuleSP exe_module_sp;
503 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
Chaoren Line56f6dc2015-03-01 04:31:16 +0000504 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Oleksiy Vyalov6edef202014-11-17 22:16:42 +0000505 error = platform_sp->ResolveExecutable(exe_module_spec, exe_module_sp,
Zachary Turner13b18262014-08-20 16:42:51 +0000506 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
Todd Fialaaf245d12014-06-30 21:05:18 +0000507 if (!error.Success())
508 return;
509
510 // Set the architecture to the exe architecture.
511 m_arch = exe_module_sp->GetArchitecture();
512 if (log)
513 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
514
515 m_pid = pid;
516 SetState(eStateAttaching);
517
Pavel Labath19cbe962015-07-21 13:20:32 +0000518 Attach(pid, error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000519}
520
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000521::pid_t
522NativeProcessLinux::Launch(LaunchArgs *args, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000523{
Todd Fiala0bce1b62014-08-17 00:10:50 +0000524 assert (args && "null args");
Todd Fialaaf245d12014-06-30 21:05:18 +0000525
526 const char **argv = args->m_argv;
527 const char **envp = args->m_envp;
Chaoren Lind3173f32015-05-29 19:52:29 +0000528 const FileSpec working_dir = args->m_working_dir;
Todd Fialaaf245d12014-06-30 21:05:18 +0000529
530 lldb_utility::PseudoTerminal terminal;
531 const size_t err_len = 1024;
532 char err_str[err_len];
533 lldb::pid_t pid;
534 NativeThreadProtocolSP thread_sp;
535
536 lldb::ThreadSP inferior;
Todd Fialaaf245d12014-06-30 21:05:18 +0000537
538 // Propagate the environment if one is not supplied.
539 if (envp == NULL || envp[0] == NULL)
540 envp = const_cast<const char **>(environ);
541
542 if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
543 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000544 error.SetErrorToGenericError();
545 error.SetErrorStringWithFormat("Process fork failed: %s", err_str);
546 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000547 }
548
549 // Recognized child exit status codes.
550 enum {
551 ePtraceFailed = 1,
552 eDupStdinFailed,
553 eDupStdoutFailed,
554 eDupStderrFailed,
555 eChdirFailed,
556 eExecFailed,
557 eSetGidFailed
558 };
559
560 // Child process.
561 if (pid == 0)
562 {
Todd Fiala75f47c32014-10-11 21:42:09 +0000563 // FIXME consider opening a pipe between parent/child and have this forked child
564 // send log info to parent re: launch status, in place of the log lines removed here.
Todd Fialaaf245d12014-06-30 21:05:18 +0000565
Todd Fiala75f47c32014-10-11 21:42:09 +0000566 // Start tracing this child that is about to exec.
Pavel Labath4a9babb2015-06-30 17:04:49 +0000567 error = PtraceWrapper(PTRACE_TRACEME, 0);
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000568 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000569 exit(ePtraceFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +0000570
Pavel Labath493c3a12015-02-04 10:36:57 +0000571 // terminal has already dupped the tty descriptors to stdin/out/err.
572 // This closes original fd from which they were copied (and avoids
573 // leaking descriptors to the debugged process.
574 terminal.CloseSlaveFileDescriptor();
575
Todd Fialaaf245d12014-06-30 21:05:18 +0000576 // Do not inherit setgid powers.
Todd Fialaaf245d12014-06-30 21:05:18 +0000577 if (setgid(getgid()) != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +0000578 exit(eSetGidFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +0000579
580 // Attempt to have our own process group.
Todd Fialaaf245d12014-06-30 21:05:18 +0000581 if (setpgid(0, 0) != 0)
582 {
Todd Fiala75f47c32014-10-11 21:42:09 +0000583 // FIXME log that this failed. This is common.
Todd Fialaaf245d12014-06-30 21:05:18 +0000584 // Don't allow this to prevent an inferior exec.
585 }
586
587 // Dup file descriptors if needed.
Chaoren Lind3173f32015-05-29 19:52:29 +0000588 if (args->m_stdin_file_spec)
589 if (!DupDescriptor(args->m_stdin_file_spec, STDIN_FILENO, O_RDONLY))
Todd Fialaaf245d12014-06-30 21:05:18 +0000590 exit(eDupStdinFailed);
591
Chaoren Lind3173f32015-05-29 19:52:29 +0000592 if (args->m_stdout_file_spec)
593 if (!DupDescriptor(args->m_stdout_file_spec, STDOUT_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +0000594 exit(eDupStdoutFailed);
595
Chaoren Lind3173f32015-05-29 19:52:29 +0000596 if (args->m_stderr_file_spec)
597 if (!DupDescriptor(args->m_stderr_file_spec, STDERR_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +0000598 exit(eDupStderrFailed);
599
Chaoren Lin9cf4f2c2015-04-23 18:28:04 +0000600 // Close everything besides stdin, stdout, and stderr that has no file
601 // action to avoid leaking
602 for (int fd = 3; fd < sysconf(_SC_OPEN_MAX); ++fd)
603 if (!args->m_launch_info.GetFileActionForFD(fd))
604 close(fd);
605
Todd Fialaaf245d12014-06-30 21:05:18 +0000606 // Change working directory
Chaoren Lind3173f32015-05-29 19:52:29 +0000607 if (working_dir && 0 != ::chdir(working_dir.GetCString()))
Todd Fialaaf245d12014-06-30 21:05:18 +0000608 exit(eChdirFailed);
609
Todd Fiala0bce1b62014-08-17 00:10:50 +0000610 // Disable ASLR if requested.
611 if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR))
612 {
613 const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
614 if (old_personality == -1)
615 {
Todd Fiala75f47c32014-10-11 21:42:09 +0000616 // Can't retrieve Linux personality. Cannot disable ASLR.
Todd Fiala0bce1b62014-08-17 00:10:50 +0000617 }
618 else
619 {
620 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality);
621 if (new_personality == -1)
622 {
Todd Fiala75f47c32014-10-11 21:42:09 +0000623 // Disabling ASLR failed.
Todd Fiala0bce1b62014-08-17 00:10:50 +0000624 }
625 else
626 {
Todd Fiala75f47c32014-10-11 21:42:09 +0000627 // Disabling ASLR succeeded.
Todd Fiala0bce1b62014-08-17 00:10:50 +0000628 }
629 }
630 }
631
Todd Fiala75f47c32014-10-11 21:42:09 +0000632 // Execute. We should never return...
Todd Fialaaf245d12014-06-30 21:05:18 +0000633 execve(argv[0],
634 const_cast<char *const *>(argv),
635 const_cast<char *const *>(envp));
Todd Fiala75f47c32014-10-11 21:42:09 +0000636
637 // ...unless exec fails. In which case we definitely need to end the child here.
Todd Fialaaf245d12014-06-30 21:05:18 +0000638 exit(eExecFailed);
639 }
640
Todd Fiala75f47c32014-10-11 21:42:09 +0000641 //
642 // This is the parent code here.
643 //
644 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
645
Todd Fialaaf245d12014-06-30 21:05:18 +0000646 // Wait for the child process to trap on its call to execve.
647 ::pid_t wpid;
648 int status;
649 if ((wpid = waitpid(pid, &status, 0)) < 0)
650 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000651 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +0000652 if (log)
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000653 log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s",
654 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000655
656 // Mark the inferior as invalid.
657 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000658 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000659
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000660 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000661 }
662 else if (WIFEXITED(status))
663 {
664 // open, dup or execve likely failed for some reason.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000665 error.SetErrorToGenericError();
Todd Fialaaf245d12014-06-30 21:05:18 +0000666 switch (WEXITSTATUS(status))
667 {
668 case ePtraceFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000669 error.SetErrorString("Child ptrace failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000670 break;
671 case eDupStdinFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000672 error.SetErrorString("Child open stdin failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000673 break;
674 case eDupStdoutFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000675 error.SetErrorString("Child open stdout failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000676 break;
677 case eDupStderrFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000678 error.SetErrorString("Child open stderr failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000679 break;
680 case eChdirFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000681 error.SetErrorString("Child failed to set working directory.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000682 break;
683 case eExecFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000684 error.SetErrorString("Child exec failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000685 break;
686 case eSetGidFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000687 error.SetErrorString("Child setgid failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000688 break;
689 default:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000690 error.SetErrorString("Child returned unknown exit status.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000691 break;
692 }
693
694 if (log)
695 {
696 log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
697 __FUNCTION__,
698 WEXITSTATUS(status));
699 }
700
701 // Mark the inferior as invalid.
702 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000703 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000704
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000705 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000706 }
Todd Fiala202ecd22014-07-10 04:39:13 +0000707 assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
Todd Fialaaf245d12014-06-30 21:05:18 +0000708 "Could not sync with inferior process.");
709
710 if (log)
711 log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
712
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000713 error = SetDefaultPtraceOpts(pid);
714 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000715 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000716 if (log)
717 log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000718 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000719
720 // Mark the inferior as invalid.
721 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000722 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000723
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000724 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000725 }
726
727 // Release the master terminal descriptor and pass it off to the
728 // NativeProcessLinux instance. Similarly stash the inferior pid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000729 m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
730 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000731
732 // Set the terminal fd to be in non blocking mode (it simplifies the
733 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
734 // descriptor to read from).
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000735 error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
736 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000737 {
738 if (log)
739 log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000740 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000741
742 // Mark the inferior as invalid.
743 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000744 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000745
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000746 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000747 }
748
749 if (log)
750 log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
751
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000752 thread_sp = AddThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000753 assert (thread_sp && "AddThread() returned a nullptr thread");
Tamas Berghammercb84eeb2015-03-17 15:05:31 +0000754 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
Pavel Labath1dbc6c92015-05-12 08:35:33 +0000755 ThreadWasCreated(pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000756
757 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000758 SetCurrentThreadID (thread_sp->GetID ());
759 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +0000760
Todd Fialaaf245d12014-06-30 21:05:18 +0000761 if (log)
762 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000763 if (error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +0000764 {
765 log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
766 }
767 else
768 {
769 log->Printf ("NativeProcessLinux::%s inferior launching failed: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000770 __FUNCTION__, error.AsCString ());
771 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000772 }
773 }
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000774 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000775}
776
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000777::pid_t
778NativeProcessLinux::Attach(lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000779{
Todd Fialaaf245d12014-06-30 21:05:18 +0000780 lldb::ThreadSP inferior;
781 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
782
783 // Use a map to keep track of the threads which we have attached/need to attach.
784 Host::TidMap tids_to_attach;
785 if (pid <= 1)
786 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000787 error.SetErrorToGenericError();
788 error.SetErrorString("Attaching to process 1 is not allowed.");
789 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000790 }
791
792 while (Host::FindProcessThreads(pid, tids_to_attach))
793 {
794 for (Host::TidMap::iterator it = tids_to_attach.begin();
795 it != tids_to_attach.end();)
796 {
797 if (it->second == false)
798 {
799 lldb::tid_t tid = it->first;
800
801 // Attach to the requested process.
802 // An attach will cause the thread to stop with a SIGSTOP.
Pavel Labath4a9babb2015-06-30 17:04:49 +0000803 error = PtraceWrapper(PTRACE_ATTACH, tid);
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000804 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000805 {
806 // No such thread. The thread may have exited.
807 // More error handling may be needed.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000808 if (error.GetError() == ESRCH)
Todd Fialaaf245d12014-06-30 21:05:18 +0000809 {
810 it = tids_to_attach.erase(it);
811 continue;
812 }
813 else
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000814 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000815 }
816
817 int status;
818 // Need to use __WALL otherwise we receive an error with errno=ECHLD
819 // At this point we should have a thread stopped if waitpid succeeds.
820 if ((status = waitpid(tid, NULL, __WALL)) < 0)
821 {
822 // No such thread. The thread may have exited.
823 // More error handling may be needed.
824 if (errno == ESRCH)
825 {
826 it = tids_to_attach.erase(it);
827 continue;
828 }
829 else
830 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000831 error.SetErrorToErrno();
832 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000833 }
834 }
835
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000836 error = SetDefaultPtraceOpts(tid);
837 if (error.Fail())
838 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000839
840 if (log)
841 log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
842
843 it->second = true;
844
845 // Create the thread, mark it as stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000846 NativeThreadProtocolSP thread_sp (AddThread (static_cast<lldb::tid_t> (tid)));
Todd Fialaaf245d12014-06-30 21:05:18 +0000847 assert (thread_sp && "AddThread() returned a nullptr");
Chaoren Linfa03ad22015-02-03 01:50:42 +0000848
849 // This will notify this is a new thread and tell the system it is stopped.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +0000850 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
Pavel Labath1dbc6c92015-05-12 08:35:33 +0000851 ThreadWasCreated(tid);
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000852 SetCurrentThreadID (thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000853 }
854
855 // move the loop forward
856 ++it;
857 }
858 }
859
860 if (tids_to_attach.size() > 0)
861 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000862 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000863 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000864 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +0000865 }
866 else
867 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000868 error.SetErrorToGenericError();
869 error.SetErrorString("No such process.");
870 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000871 }
872
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000873 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000874}
875
Chaoren Lin97ccc292015-02-03 01:51:12 +0000876Error
Todd Fialaaf245d12014-06-30 21:05:18 +0000877NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
878{
879 long ptrace_opts = 0;
880
881 // Have the child raise an event on exit. This is used to keep the child in
882 // limbo until it is destroyed.
883 ptrace_opts |= PTRACE_O_TRACEEXIT;
884
885 // Have the tracer trace threads which spawn in the inferior process.
886 // TODO: if we want to support tracing the inferiors' child, add the
887 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
888 ptrace_opts |= PTRACE_O_TRACECLONE;
889
890 // Have the tracer notify us before execve returns
891 // (needed to disable legacy SIGTRAP generation)
892 ptrace_opts |= PTRACE_O_TRACEEXEC;
893
Pavel Labath4a9babb2015-06-30 17:04:49 +0000894 return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts);
Todd Fialaaf245d12014-06-30 21:05:18 +0000895}
896
897static ExitType convert_pid_status_to_exit_type (int status)
898{
899 if (WIFEXITED (status))
900 return ExitType::eExitTypeExit;
901 else if (WIFSIGNALED (status))
902 return ExitType::eExitTypeSignal;
903 else if (WIFSTOPPED (status))
904 return ExitType::eExitTypeStop;
905 else
906 {
907 // We don't know what this is.
908 return ExitType::eExitTypeInvalid;
909 }
910}
911
912static int convert_pid_status_to_return_code (int status)
913{
914 if (WIFEXITED (status))
915 return WEXITSTATUS (status);
916 else if (WIFSIGNALED (status))
917 return WTERMSIG (status);
918 else if (WIFSTOPPED (status))
919 return WSTOPSIG (status);
920 else
921 {
922 // We don't know what this is.
923 return ExitType::eExitTypeInvalid;
924 }
925}
926
Pavel Labath1107b5a2015-04-17 14:07:49 +0000927// Handles all waitpid events from the inferior process.
928void
929NativeProcessLinux::MonitorCallback(lldb::pid_t pid,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000930 bool exited,
931 int signal,
932 int status)
Todd Fialaaf245d12014-06-30 21:05:18 +0000933{
934 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
935
Todd Fialaaf245d12014-06-30 21:05:18 +0000936 // Certain activities differ based on whether the pid is the tid of the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000937 const bool is_main_thread = (pid == GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000938
939 // Handle when the thread exits.
940 if (exited)
941 {
942 if (log)
Chaoren Lin86fd8e42015-02-03 01:51:15 +0000943 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 +0000944
945 // This is a thread that exited. Ensure we're not tracking it anymore.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000946 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000947
948 if (is_main_thread)
949 {
950 // We only set the exit status and notify the delegate if we haven't already set the process
951 // state to an exited state. We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
952 // for the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000953 const bool already_notified = (GetState() == StateType::eStateExited) || (GetState () == StateType::eStateCrashed);
Todd Fialaaf245d12014-06-30 21:05:18 +0000954 if (!already_notified)
955 {
956 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +0000957 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 +0000958 // The main thread exited. We're done monitoring. Report to delegate.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000959 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +0000960
961 // Notify delegate that our process has exited.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000962 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +0000963 }
964 else
965 {
966 if (log)
967 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
968 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000969 }
970 else
971 {
972 // Do we want to report to the delegate in this case? I think not. If this was an orderly
973 // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
974 // and we would have done an all-stop then.
975 if (log)
976 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 +0000977 }
Pavel Labath1107b5a2015-04-17 14:07:49 +0000978 return;
Todd Fialaaf245d12014-06-30 21:05:18 +0000979 }
980
981 // Get details on the signal raised.
982 siginfo_t info;
Pavel Labath1107b5a2015-04-17 14:07:49 +0000983 const auto err = GetSignalInfo(pid, &info);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000984 if (err.Success())
Chaoren Linfa03ad22015-02-03 01:50:42 +0000985 {
986 // We have retrieved the signal info. Dispatch appropriately.
987 if (info.si_signo == SIGTRAP)
Pavel Labath1107b5a2015-04-17 14:07:49 +0000988 MonitorSIGTRAP(&info, pid);
Chaoren Linfa03ad22015-02-03 01:50:42 +0000989 else
Pavel Labath1107b5a2015-04-17 14:07:49 +0000990 MonitorSignal(&info, pid, exited);
Chaoren Linfa03ad22015-02-03 01:50:42 +0000991 }
992 else
Todd Fialaaf245d12014-06-30 21:05:18 +0000993 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000994 if (err.GetError() == EINVAL)
Todd Fialaaf245d12014-06-30 21:05:18 +0000995 {
Chaoren Linfa03ad22015-02-03 01:50:42 +0000996 // This is a group stop reception for this tid.
Pavel Labath39036ac2015-05-21 08:32:18 +0000997 // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the
998 // tracee, triggering the group-stop mechanism. Normally receiving these would stop
999 // the process, pending a SIGCONT. Simulating this state in a debugger is hard and is
1000 // generally not needed (one use case is debugging background task being managed by a
1001 // shell). For general use, it is sufficient to stop the process in a signal-delivery
1002 // stop which happens before the group stop. This done by MonitorSignal and works
1003 // correctly for all signals.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001004 if (log)
Pavel Labath39036ac2015-05-21 08:32:18 +00001005 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);
1006 Resume(pid, signal);
Todd Fialaaf245d12014-06-30 21:05:18 +00001007 }
1008 else
1009 {
1010 // ptrace(GETSIGINFO) failed (but not due to group-stop).
1011
1012 // A return value of ESRCH means the thread/process is no longer on the system,
1013 // so it was killed somehow outside of our control. Either way, we can't do anything
1014 // with it anymore.
1015
Todd Fialaaf245d12014-06-30 21:05:18 +00001016 // Stop tracking the metadata for the thread since it's entirely off the system now.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001017 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001018
1019 if (log)
1020 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
Chaoren Lin97ccc292015-02-03 01:51:12 +00001021 __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 +00001022
1023 if (is_main_thread)
1024 {
1025 // Notify the delegate - our process is not available but appears to have been killed outside
1026 // our control. Is eStateExited the right exit state in this case?
Pavel Labath1107b5a2015-04-17 14:07:49 +00001027 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
1028 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001029 }
1030 else
1031 {
1032 // This thread was pulled out from underneath us. Anything to do here? Do we want to do an all stop?
1033 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +00001034 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 +00001035 }
1036 }
1037 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001038}
1039
1040void
Pavel Labath426bdf82015-04-28 07:51:52 +00001041NativeProcessLinux::WaitForNewThread(::pid_t tid)
1042{
1043 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1044
1045 NativeThreadProtocolSP new_thread_sp = GetThreadByID(tid);
1046
1047 if (new_thread_sp)
1048 {
1049 // We are already tracking the thread - we got the event on the new thread (see
1050 // MonitorSignal) before this one. We are done.
1051 return;
1052 }
1053
1054 // The thread is not tracked yet, let's wait for it to appear.
1055 int status = -1;
1056 ::pid_t wait_pid;
1057 do
1058 {
1059 if (log)
1060 log->Printf ("NativeProcessLinux::%s() received thread creation event for tid %" PRIu32 ". tid not tracked yet, waiting for thread to appear...", __FUNCTION__, tid);
1061 wait_pid = waitpid(tid, &status, __WALL);
1062 }
1063 while (wait_pid == -1 && errno == EINTR);
1064 // Since we are waiting on a specific tid, this must be the creation event. But let's do
1065 // some checks just in case.
1066 if (wait_pid != tid) {
1067 if (log)
1068 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime", __FUNCTION__, tid);
1069 // The only way I know of this could happen is if the whole process was
1070 // SIGKILLed in the mean time. In any case, we can't do anything about that now.
1071 return;
1072 }
1073 if (WIFEXITED(status))
1074 {
1075 if (log)
1076 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " returned an 'exited' event. Not tracking the thread.", __FUNCTION__, tid);
1077 // Also a very improbable event.
1078 return;
1079 }
1080
1081 siginfo_t info;
1082 Error error = GetSignalInfo(tid, &info);
1083 if (error.Fail())
1084 {
1085 if (log)
1086 log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime.", __FUNCTION__, tid);
1087 return;
1088 }
1089
1090 if (((info.si_pid != 0) || (info.si_code != SI_USER)) && log)
1091 {
1092 // We should be getting a thread creation signal here, but we received something
1093 // else. There isn't much we can do about it now, so we will just log that. Since the
1094 // thread is alive and we are receiving events from it, we shall pretend that it was
1095 // created properly.
1096 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);
1097 }
1098
1099 if (log)
1100 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 ": tracking new thread tid %" PRIu32,
1101 __FUNCTION__, GetID (), tid);
1102
1103 new_thread_sp = AddThread(tid);
1104 std::static_pointer_cast<NativeThreadLinux> (new_thread_sp)->SetRunning ();
1105 Resume (tid, LLDB_INVALID_SIGNAL_NUMBER);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001106 ThreadWasCreated(tid);
Pavel Labath426bdf82015-04-28 07:51:52 +00001107}
1108
1109void
Todd Fialaaf245d12014-06-30 21:05:18 +00001110NativeProcessLinux::MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid)
1111{
1112 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1113 const bool is_main_thread = (pid == GetID ());
1114
1115 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
1116 if (!info)
1117 return;
1118
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001119 Mutex::Locker locker (m_threads_mutex);
1120
Todd Fialaaf245d12014-06-30 21:05:18 +00001121 // See if we can find a thread for this signal.
1122 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
1123 if (!thread_sp)
1124 {
1125 if (log)
1126 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
1127 }
1128
1129 switch (info->si_code)
1130 {
1131 // TODO: these two cases are required if we want to support tracing of the inferiors' children. We'd need this to debug a monitor.
1132 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
1133 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
1134
1135 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
1136 {
Pavel Labath5fd24c62015-04-23 09:04:35 +00001137 // This is the notification on the parent thread which informs us of new thread
Pavel Labath426bdf82015-04-28 07:51:52 +00001138 // creation.
1139 // We don't want to do anything with the parent thread so we just resume it. In case we
1140 // want to implement "break on thread creation" functionality, we would need to stop
1141 // here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001142
Pavel Labath426bdf82015-04-28 07:51:52 +00001143 unsigned long event_message = 0;
1144 if (GetEventMessage (pid, &event_message).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001145 {
Pavel Labath426bdf82015-04-28 07:51:52 +00001146 if (log)
Chaoren Linfa03ad22015-02-03 01:50:42 +00001147 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 +00001148 } else
1149 WaitForNewThread(event_message);
Todd Fialaaf245d12014-06-30 21:05:18 +00001150
Pavel Labath5fd24c62015-04-23 09:04:35 +00001151 Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001152 break;
1153 }
1154
1155 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
Todd Fialaa9882ce2014-08-28 15:46:54 +00001156 {
1157 NativeThreadProtocolSP main_thread_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001158 if (log)
1159 log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
Todd Fialaa9882ce2014-08-28 15:46:54 +00001160
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001161 // Exec clears any pending notifications.
1162 m_pending_notification_up.reset ();
Chaoren Linfa03ad22015-02-03 01:50:42 +00001163
1164 // 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 +00001165 if (log)
1166 log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
1167
1168 for (auto thread_sp : m_threads)
Todd Fialaa9882ce2014-08-28 15:46:54 +00001169 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001170 const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
1171 if (is_main_thread)
Todd Fialaa9882ce2014-08-28 15:46:54 +00001172 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001173 main_thread_sp = thread_sp;
1174 if (log)
1175 log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00001176 }
1177 else
1178 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001179 // Tell thread coordinator this thread is dead.
Todd Fialaa9882ce2014-08-28 15:46:54 +00001180 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001181 log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00001182 }
1183 }
1184
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001185 m_threads.clear ();
1186
1187 if (main_thread_sp)
1188 {
1189 m_threads.push_back (main_thread_sp);
1190 SetCurrentThreadID (main_thread_sp->GetID ());
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001191 std::static_pointer_cast<NativeThreadLinux> (main_thread_sp)->SetStoppedByExec ();
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001192 }
1193 else
1194 {
1195 SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
1196 if (log)
1197 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
1198 }
1199
Chaoren Linfa03ad22015-02-03 01:50:42 +00001200 // Tell coordinator about about the "new" (since exec) stopped main thread.
1201 const lldb::tid_t main_thread_tid = GetID ();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001202 ThreadWasCreated(main_thread_tid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001203
1204 // NOTE: ideally these next statements would execute at the same time as the coordinator thread create was executed.
1205 // Consider a handler that can execute when that happens.
Todd Fialaa9882ce2014-08-28 15:46:54 +00001206 // Let our delegate know we have just exec'd.
1207 NotifyDidExec ();
1208
1209 // If we have a main thread, indicate we are stopped.
1210 assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001211
1212 // Let the process know we're stopped.
Pavel Labathed89c7f2015-05-06 12:22:37 +00001213 StopRunningThreads (pid);
Todd Fialaa9882ce2014-08-28 15:46:54 +00001214
Todd Fialaaf245d12014-06-30 21:05:18 +00001215 break;
Todd Fialaa9882ce2014-08-28 15:46:54 +00001216 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001217
1218 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
1219 {
1220 // The inferior process or one of its threads is about to exit.
Pavel Labath6e351632015-05-15 13:30:59 +00001221 // We don't want to do anything with the thread so we just resume it. In case we
1222 // want to implement "break on thread exit" functionality, we would need to stop
1223 // here.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001224
Todd Fialaaf245d12014-06-30 21:05:18 +00001225 unsigned long data = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +00001226 if (GetEventMessage(pid, &data).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001227 data = -1;
1228
1229 if (log)
1230 {
1231 log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
1232 __FUNCTION__,
1233 data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
1234 pid,
1235 is_main_thread ? "is main thread" : "not main thread");
1236 }
1237
Todd Fialaaf245d12014-06-30 21:05:18 +00001238 if (is_main_thread)
1239 {
1240 SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001241 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001242
Pavel Labath6e351632015-05-15 13:30:59 +00001243 Resume(pid, LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001244
1245 break;
1246 }
1247
1248 case 0:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001249 case TRAP_TRACE: // We receive this on single stepping.
1250 case TRAP_HWBKPT: // We receive this on watchpoint hit
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001251 if (thread_sp)
1252 {
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001253 // If a watchpoint was hit, report it
1254 uint32_t wp_index;
Omair Javaidea8c25a802015-05-15 06:29:58 +00001255 Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index, (lldb::addr_t)info->si_addr);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001256 if (error.Fail() && log)
1257 log->Printf("NativeProcessLinux::%s() "
1258 "received error while checking for watchpoint hits, "
1259 "pid = %" PRIu64 " error = %s",
1260 __FUNCTION__, pid, error.AsCString());
1261 if (wp_index != LLDB_INVALID_INDEX32)
1262 {
1263 MonitorWatchpoint(pid, thread_sp, wp_index);
1264 break;
1265 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001266 }
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001267 // Otherwise, report step over
1268 MonitorTrace(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00001269 break;
1270
1271 case SI_KERNEL:
Mohit K. Bhakkad35799962015-06-18 04:53:18 +00001272#if defined __mips__
1273 // For mips there is no special signal for watchpoint
1274 // So we check for watchpoint in kernel trap
1275 if (thread_sp)
1276 {
1277 // If a watchpoint was hit, report it
1278 uint32_t wp_index;
Jaydeep Patilc60c9452015-06-23 03:37:08 +00001279 Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index, LLDB_INVALID_ADDRESS);
Mohit K. Bhakkad35799962015-06-18 04:53:18 +00001280 if (error.Fail() && log)
1281 log->Printf("NativeProcessLinux::%s() "
1282 "received error while checking for watchpoint hits, "
1283 "pid = %" PRIu64 " error = %s",
1284 __FUNCTION__, pid, error.AsCString());
1285 if (wp_index != LLDB_INVALID_INDEX32)
1286 {
1287 MonitorWatchpoint(pid, thread_sp, wp_index);
1288 break;
1289 }
1290 }
1291 // NO BREAK
1292#endif
Todd Fialaaf245d12014-06-30 21:05:18 +00001293 case TRAP_BRKPT:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001294 MonitorBreakpoint(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00001295 break;
1296
1297 case SIGTRAP:
1298 case (SIGTRAP | 0x80):
1299 if (log)
Chaoren Linfa03ad22015-02-03 01:50:42 +00001300 log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), pid);
1301
Todd Fialaaf245d12014-06-30 21:05:18 +00001302 // Ignore these signals until we know more about them.
Pavel Labath6e351632015-05-15 13:30:59 +00001303 Resume(pid, LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001304 break;
1305
1306 default:
1307 assert(false && "Unexpected SIGTRAP code!");
1308 if (log)
Pavel Labath6e351632015-05-15 13:30:59 +00001309 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 "tid %" PRIu64 " received unhandled SIGTRAP code: 0x%d",
1310 __FUNCTION__, GetID (), pid, info->si_code);
Todd Fialaaf245d12014-06-30 21:05:18 +00001311 break;
1312
1313 }
1314}
1315
1316void
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001317NativeProcessLinux::MonitorTrace(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
1318{
1319 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1320 if (log)
1321 log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)",
1322 __FUNCTION__, pid);
1323
1324 if (thread_sp)
1325 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
1326
1327 // This thread is currently stopped.
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001328 ThreadDidStop(pid, false);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001329
1330 // Here we don't have to request the rest of the threads to stop or request a deferred stop.
1331 // This would have already happened at the time the Resume() with step operation was signaled.
1332 // At this point, we just need to say we stopped, and the deferred notifcation will fire off
1333 // once all running threads have checked in as stopped.
1334 SetCurrentThreadID(pid);
1335 // Tell the process we have a stop (from software breakpoint).
Pavel Labathed89c7f2015-05-06 12:22:37 +00001336 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001337}
1338
1339void
1340NativeProcessLinux::MonitorBreakpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
1341{
1342 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
1343 if (log)
1344 log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
1345 __FUNCTION__, pid);
1346
1347 // This thread is currently stopped.
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001348 ThreadDidStop(pid, false);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001349
1350 // Mark the thread as stopped at breakpoint.
1351 if (thread_sp)
1352 {
1353 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByBreakpoint();
1354 Error error = FixupBreakpointPCAsNeeded(thread_sp);
1355 if (error.Fail())
1356 if (log)
1357 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
1358 __FUNCTION__, pid, error.AsCString());
Tamas Berghammerd8c338d2015-04-15 09:47:02 +00001359
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00001360 if (m_threads_stepping_with_breakpoint.find(pid) != m_threads_stepping_with_breakpoint.end())
Tamas Berghammerd8c338d2015-04-15 09:47:02 +00001361 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001362 }
1363 else
1364 if (log)
1365 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 ": "
1366 "warning, cannot process software breakpoint since no thread metadata",
1367 __FUNCTION__, pid);
1368
1369
1370 // We need to tell all other running threads before we notify the delegate about this stop.
Pavel Labathed89c7f2015-05-06 12:22:37 +00001371 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001372}
1373
1374void
1375NativeProcessLinux::MonitorWatchpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp, uint32_t wp_index)
1376{
1377 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
1378 if (log)
1379 log->Printf("NativeProcessLinux::%s() received watchpoint event, "
1380 "pid = %" PRIu64 ", wp_index = %" PRIu32,
1381 __FUNCTION__, pid, wp_index);
1382
1383 // This thread is currently stopped.
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001384 ThreadDidStop(pid, false);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001385
1386 // Mark the thread as stopped at watchpoint.
1387 // The address is at (lldb::addr_t)info->si_addr if we need it.
1388 lldbassert(thread_sp && "thread_sp cannot be NULL");
1389 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByWatchpoint(wp_index);
1390
1391 // We need to tell all other running threads before we notify the delegate about this stop.
Pavel Labathed89c7f2015-05-06 12:22:37 +00001392 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001393}
1394
1395void
Todd Fialaaf245d12014-06-30 21:05:18 +00001396NativeProcessLinux::MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited)
1397{
Todd Fiala511e5cd2014-09-11 23:29:14 +00001398 assert (info && "null info");
1399 if (!info)
1400 return;
1401
1402 const int signo = info->si_signo;
1403 const bool is_from_llgs = info->si_pid == getpid ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001404
1405 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1406
1407 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1408 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1409 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
1410 //
1411 // IOW, user generated signals never generate what we consider to be a
1412 // "crash".
1413 //
1414 // Similarly, ACK signals generated by this monitor.
1415
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001416 Mutex::Locker locker (m_threads_mutex);
1417
Todd Fialaaf245d12014-06-30 21:05:18 +00001418 // See if we can find a thread for this signal.
1419 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
1420 if (!thread_sp)
1421 {
1422 if (log)
1423 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
1424 }
1425
1426 // Handle the signal.
1427 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
1428 {
1429 if (log)
1430 log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
1431 __FUNCTION__,
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001432 Host::GetSignalAsCString(signo),
Todd Fialaaf245d12014-06-30 21:05:18 +00001433 signo,
1434 (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
1435 info->si_pid,
Todd Fiala511e5cd2014-09-11 23:29:14 +00001436 is_from_llgs ? "from llgs" : "not from llgs",
Todd Fialaaf245d12014-06-30 21:05:18 +00001437 pid);
Todd Fiala58a2f662014-08-12 17:02:07 +00001438 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001439
Todd Fiala58a2f662014-08-12 17:02:07 +00001440 // Check for new thread notification.
1441 if ((info->si_pid == 0) && (info->si_code == SI_USER))
1442 {
Pavel Labath426bdf82015-04-28 07:51:52 +00001443 // A new thread creation is being signaled. This is one of two parts that come in
1444 // a non-deterministic order. This code handles the case where the new thread event comes
1445 // before the event on the parent thread. For the opposite case see code in
1446 // MonitorSIGTRAP.
Todd Fiala58a2f662014-08-12 17:02:07 +00001447 if (log)
1448 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": new thread notification",
1449 __FUNCTION__, GetID (), pid);
1450
Pavel Labath5fd24c62015-04-23 09:04:35 +00001451 thread_sp = AddThread(pid);
1452 assert (thread_sp.get() && "failed to create the tracking data for newly created inferior thread");
1453 // We can now resume the newly created thread.
1454 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
1455 Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001456 ThreadWasCreated(pid);
Todd Fiala58a2f662014-08-12 17:02:07 +00001457 // Done handling.
1458 return;
1459 }
1460
1461 // Check for thread stop notification.
Todd Fiala511e5cd2014-09-11 23:29:14 +00001462 if (is_from_llgs && (info->si_code == SI_TKILL) && (signo == SIGSTOP))
Todd Fiala58a2f662014-08-12 17:02:07 +00001463 {
1464 // This is a tgkill()-based stop.
1465 if (thread_sp)
1466 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00001467 if (log)
1468 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
1469 __FUNCTION__,
1470 GetID (),
1471 pid);
1472
Chaoren Linaab58632015-02-03 01:50:57 +00001473 // Check that we're not already marked with a stop reason.
1474 // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
1475 // the kernel signaled us with the thread stopping which we handled and marked as stopped,
1476 // and that, without an intervening resume, we received another stop. It is more likely
1477 // that we are missing the marking of a run state somewhere if we find that the thread was
1478 // marked as stopped.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001479 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
1480 assert (linux_thread_sp && "linux_thread_sp is null!");
Chaoren Linaab58632015-02-03 01:50:57 +00001481
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001482 const StateType thread_state = linux_thread_sp->GetState ();
Chaoren Linaab58632015-02-03 01:50:57 +00001483 if (!StateIsStoppedState (thread_state, false))
1484 {
Pavel Labathed89c7f2015-05-06 12:22:37 +00001485 // An inferior thread has stopped because of a SIGSTOP we have sent it.
1486 // Generally, these are not important stops and we don't want to report them as
1487 // they are just used to stop other threads when one thread (the one with the
1488 // *real* stop reason) hits a breakpoint (watchpoint, etc...). However, in the
1489 // case of an asynchronous Interrupt(), this *is* the real stop reason, so we
1490 // leave the signal intact if this is the thread that was chosen as the
1491 // triggering thread.
1492 if (m_pending_notification_up && m_pending_notification_up->triggering_tid == pid)
Pavel Labathc4e25c92015-05-29 10:13:03 +00001493 linux_thread_sp->SetStoppedBySignal(SIGSTOP, info);
Pavel Labathed89c7f2015-05-06 12:22:37 +00001494 else
Pavel Labath05569f62015-07-23 09:09:29 +00001495 linux_thread_sp->SetStoppedWithNoReason();
Pavel Labathed89c7f2015-05-06 12:22:37 +00001496
Chaoren Linaab58632015-02-03 01:50:57 +00001497 SetCurrentThreadID (thread_sp->GetID ());
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001498 ThreadDidStop (thread_sp->GetID (), true);
Chaoren Linaab58632015-02-03 01:50:57 +00001499 }
1500 else
1501 {
1502 if (log)
1503 {
1504 // Retrieve the signal name if the thread was stopped by a signal.
1505 int stop_signo = 0;
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001506 const bool stopped_by_signal = linux_thread_sp->IsStopped (&stop_signo);
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001507 const char *signal_name = stopped_by_signal ? Host::GetSignalAsCString(stop_signo) : "<not stopped by signal>";
Chaoren Linaab58632015-02-03 01:50:57 +00001508 if (!signal_name)
1509 signal_name = "<no-signal-name>";
1510
1511 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",
1512 __FUNCTION__,
1513 GetID (),
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001514 linux_thread_sp->GetID (),
Chaoren Linaab58632015-02-03 01:50:57 +00001515 StateAsCString (thread_state),
1516 stop_signo,
1517 signal_name);
1518 }
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001519 ThreadDidStop (thread_sp->GetID (), false);
Chaoren Linaab58632015-02-03 01:50:57 +00001520 }
Todd Fiala58a2f662014-08-12 17:02:07 +00001521 }
1522
1523 // Done handling.
Todd Fialaaf245d12014-06-30 21:05:18 +00001524 return;
1525 }
1526
1527 if (log)
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001528 log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, Host::GetSignalAsCString(signo));
Todd Fialaaf245d12014-06-30 21:05:18 +00001529
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001530 // This thread is stopped.
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001531 ThreadDidStop (pid, false);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001532
Pavel Labathc4e25c92015-05-29 10:13:03 +00001533 if (thread_sp)
1534 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal(signo, info);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001535
1536 // Send a stop to the debugger after we get all other threads to stop.
Pavel Labathed89c7f2015-05-06 12:22:37 +00001537 StopRunningThreads (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001538}
1539
Tamas Berghammere7708682015-04-22 10:00:23 +00001540namespace {
1541
1542struct EmulatorBaton
1543{
1544 NativeProcessLinux* m_process;
1545 NativeRegisterContext* m_reg_context;
Tamas Berghammere7708682015-04-22 10:00:23 +00001546
Pavel Labath6648fcc2015-04-27 09:21:14 +00001547 // eRegisterKindDWARF -> RegsiterValue
1548 std::unordered_map<uint32_t, RegisterValue> m_register_values;
1549
1550 EmulatorBaton(NativeProcessLinux* process, NativeRegisterContext* reg_context) :
Tamas Berghammere7708682015-04-22 10:00:23 +00001551 m_process(process), m_reg_context(reg_context) {}
1552};
1553
1554} // anonymous namespace
1555
1556static size_t
1557ReadMemoryCallback (EmulateInstruction *instruction,
1558 void *baton,
1559 const EmulateInstruction::Context &context,
1560 lldb::addr_t addr,
1561 void *dst,
1562 size_t length)
1563{
1564 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
1565
Chaoren Lin3eb4b452015-04-29 17:24:48 +00001566 size_t bytes_read;
Tamas Berghammere7708682015-04-22 10:00:23 +00001567 emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
1568 return bytes_read;
1569}
1570
1571static bool
1572ReadRegisterCallback (EmulateInstruction *instruction,
1573 void *baton,
1574 const RegisterInfo *reg_info,
1575 RegisterValue &reg_value)
1576{
1577 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
1578
Pavel Labath6648fcc2015-04-27 09:21:14 +00001579 auto it = emulator_baton->m_register_values.find(reg_info->kinds[eRegisterKindDWARF]);
1580 if (it != emulator_baton->m_register_values.end())
1581 {
1582 reg_value = it->second;
1583 return true;
1584 }
1585
Tamas Berghammere7708682015-04-22 10:00:23 +00001586 // The emulator only fill in the dwarf regsiter numbers (and in some case
1587 // the generic register numbers). Get the full register info from the
1588 // register context based on the dwarf register numbers.
1589 const RegisterInfo* full_reg_info = emulator_baton->m_reg_context->GetRegisterInfo(
1590 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
1591
1592 Error error = emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
Pavel Labath6648fcc2015-04-27 09:21:14 +00001593 if (error.Success())
Pavel Labath6648fcc2015-04-27 09:21:14 +00001594 return true;
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001595
Pavel Labath6648fcc2015-04-27 09:21:14 +00001596 return false;
Tamas Berghammere7708682015-04-22 10:00:23 +00001597}
1598
1599static bool
1600WriteRegisterCallback (EmulateInstruction *instruction,
1601 void *baton,
1602 const EmulateInstruction::Context &context,
1603 const RegisterInfo *reg_info,
1604 const RegisterValue &reg_value)
1605{
1606 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
Pavel Labath6648fcc2015-04-27 09:21:14 +00001607 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = reg_value;
Tamas Berghammere7708682015-04-22 10:00:23 +00001608 return true;
1609}
1610
1611static size_t
1612WriteMemoryCallback (EmulateInstruction *instruction,
1613 void *baton,
1614 const EmulateInstruction::Context &context,
1615 lldb::addr_t addr,
1616 const void *dst,
1617 size_t length)
1618{
1619 return length;
1620}
1621
1622static lldb::addr_t
1623ReadFlags (NativeRegisterContext* regsiter_context)
1624{
1625 const RegisterInfo* flags_info = regsiter_context->GetRegisterInfo(
1626 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1627 return regsiter_context->ReadRegisterAsUnsigned(flags_info, LLDB_INVALID_ADDRESS);
1628}
1629
1630Error
1631NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadProtocolSP thread_sp)
1632{
1633 Error error;
1634 NativeRegisterContextSP register_context_sp = thread_sp->GetRegisterContext();
1635
1636 std::unique_ptr<EmulateInstruction> emulator_ap(
1637 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, nullptr));
1638
1639 if (emulator_ap == nullptr)
1640 return Error("Instruction emulator not found!");
1641
1642 EmulatorBaton baton(this, register_context_sp.get());
1643 emulator_ap->SetBaton(&baton);
1644 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
1645 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
1646 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
1647 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
1648
1649 if (!emulator_ap->ReadInstruction())
1650 return Error("Read instruction failed!");
1651
Pavel Labath6648fcc2015-04-27 09:21:14 +00001652 bool emulation_result = emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
1653
1654 const RegisterInfo* reg_info_pc = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1655 const RegisterInfo* reg_info_flags = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1656
1657 auto pc_it = baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1658 auto flags_it = baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
1659
Tamas Berghammere7708682015-04-22 10:00:23 +00001660 lldb::addr_t next_pc;
1661 lldb::addr_t next_flags;
Pavel Labath6648fcc2015-04-27 09:21:14 +00001662 if (emulation_result)
Tamas Berghammere7708682015-04-22 10:00:23 +00001663 {
Pavel Labath6648fcc2015-04-27 09:21:14 +00001664 assert(pc_it != baton.m_register_values.end() && "Emulation was successfull but PC wasn't updated");
1665 next_pc = pc_it->second.GetAsUInt64();
1666
1667 if (flags_it != baton.m_register_values.end())
1668 next_flags = flags_it->second.GetAsUInt64();
Tamas Berghammere7708682015-04-22 10:00:23 +00001669 else
1670 next_flags = ReadFlags (register_context_sp.get());
1671 }
Pavel Labath6648fcc2015-04-27 09:21:14 +00001672 else if (pc_it == baton.m_register_values.end())
Tamas Berghammere7708682015-04-22 10:00:23 +00001673 {
1674 // Emulate instruction failed and it haven't changed PC. Advance PC
1675 // with the size of the current opcode because the emulation of all
1676 // PC modifying instruction should be successful. The failure most
1677 // likely caused by a not supported instruction which don't modify PC.
1678 next_pc = register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
1679 next_flags = ReadFlags (register_context_sp.get());
1680 }
1681 else
1682 {
1683 // The instruction emulation failed after it modified the PC. It is an
1684 // unknown error where we can't continue because the next instruction is
1685 // modifying the PC but we don't know how.
1686 return Error ("Instruction emulation failed unexpectedly.");
1687 }
1688
1689 if (m_arch.GetMachine() == llvm::Triple::arm)
1690 {
1691 if (next_flags & 0x20)
1692 {
1693 // Thumb mode
1694 error = SetSoftwareBreakpoint(next_pc, 2);
1695 }
1696 else
1697 {
1698 // Arm mode
1699 error = SetSoftwareBreakpoint(next_pc, 4);
1700 }
1701 }
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001702 else if (m_arch.GetMachine() == llvm::Triple::mips64
Jaydeep Patilc60c9452015-06-23 03:37:08 +00001703 || m_arch.GetMachine() == llvm::Triple::mips64el
1704 || m_arch.GetMachine() == llvm::Triple::mips
1705 || m_arch.GetMachine() == llvm::Triple::mipsel)
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001706 error = SetSoftwareBreakpoint(next_pc, 4);
Tamas Berghammere7708682015-04-22 10:00:23 +00001707 else
1708 {
1709 // No size hint is given for the next breakpoint
1710 error = SetSoftwareBreakpoint(next_pc, 0);
1711 }
1712
Tamas Berghammere7708682015-04-22 10:00:23 +00001713 if (error.Fail())
1714 return error;
1715
1716 m_threads_stepping_with_breakpoint.insert({thread_sp->GetID(), next_pc});
1717
1718 return Error();
1719}
1720
1721bool
1722NativeProcessLinux::SupportHardwareSingleStepping() const
1723{
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001724 if (m_arch.GetMachine() == llvm::Triple::arm
Jaydeep Patilc60c9452015-06-23 03:37:08 +00001725 || m_arch.GetMachine() == llvm::Triple::mips64 || m_arch.GetMachine() == llvm::Triple::mips64el
1726 || m_arch.GetMachine() == llvm::Triple::mips || m_arch.GetMachine() == llvm::Triple::mipsel)
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001727 return false;
1728 return true;
Tamas Berghammere7708682015-04-22 10:00:23 +00001729}
1730
Todd Fialaaf245d12014-06-30 21:05:18 +00001731Error
1732NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
1733{
Todd Fialaaf245d12014-06-30 21:05:18 +00001734 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1735 if (log)
1736 log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
1737
Tamas Berghammere7708682015-04-22 10:00:23 +00001738 bool software_single_step = !SupportHardwareSingleStepping();
Todd Fialaaf245d12014-06-30 21:05:18 +00001739
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001740 Mutex::Locker locker (m_threads_mutex);
Chaoren Lin03f12d62015-02-03 01:50:49 +00001741
Tamas Berghammere7708682015-04-22 10:00:23 +00001742 if (software_single_step)
1743 {
1744 for (auto thread_sp : m_threads)
1745 {
1746 assert (thread_sp && "thread list should not contain NULL threads");
1747
1748 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
1749 if (action == nullptr)
1750 continue;
1751
1752 if (action->state == eStateStepping)
1753 {
1754 Error error = SetupSoftwareSingleStepping(thread_sp);
1755 if (error.Fail())
1756 return error;
1757 }
1758 }
1759 }
1760
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001761 for (auto thread_sp : m_threads)
Todd Fialaaf245d12014-06-30 21:05:18 +00001762 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001763 assert (thread_sp && "thread list should not contain NULL threads");
1764
1765 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
1766
1767 if (action == nullptr)
Todd Fialaaf245d12014-06-30 21:05:18 +00001768 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00001769 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001770 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
1771 __FUNCTION__, GetID (), thread_sp->GetID ());
1772 continue;
1773 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001774
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001775 if (log)
1776 {
1777 log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
1778 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
1779 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001780
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001781 switch (action->state)
1782 {
1783 case eStateRunning:
1784 {
1785 // Run the thread, possibly feeding it the signal.
1786 const int signo = action->signal;
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001787 ResumeThread(thread_sp->GetID (),
Pavel Labathc0765592015-05-06 10:46:34 +00001788 [=](lldb::tid_t tid_to_resume, bool supress_signal)
1789 {
1790 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
1791 // Pass this signal number on to the inferior to handle.
1792 const auto resume_result = Resume (tid_to_resume, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
1793 if (resume_result.Success())
1794 SetState(eStateRunning, true);
1795 return resume_result;
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001796 },
1797 false);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001798 break;
1799 }
1800
1801 case eStateStepping:
1802 {
1803 // Request the step.
1804 const int signo = action->signal;
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001805 ResumeThread(thread_sp->GetID (),
Pavel Labathc0765592015-05-06 10:46:34 +00001806 [=](lldb::tid_t tid_to_step, bool supress_signal)
1807 {
1808 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStepping ();
Tamas Berghammere7708682015-04-22 10:00:23 +00001809
Pavel Labathc0765592015-05-06 10:46:34 +00001810 Error step_result;
1811 if (software_single_step)
1812 step_result = Resume (tid_to_step, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
1813 else
1814 step_result = SingleStep (tid_to_step,(signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
Tamas Berghammere7708682015-04-22 10:00:23 +00001815
Pavel Labathc0765592015-05-06 10:46:34 +00001816 assert (step_result.Success() && "SingleStep() failed");
1817 if (step_result.Success())
1818 SetState(eStateStepping, true);
1819 return step_result;
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001820 },
1821 false);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001822 break;
1823 }
1824
1825 case eStateSuspended:
1826 case eStateStopped:
Pavel Labath108c3252015-05-12 09:03:18 +00001827 lldbassert(0 && "Unexpected state");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001828
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001829 default:
1830 return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
1831 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001832 }
1833 }
1834
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001835 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00001836}
1837
1838Error
1839NativeProcessLinux::Halt ()
1840{
1841 Error error;
1842
Todd Fialaaf245d12014-06-30 21:05:18 +00001843 if (kill (GetID (), SIGSTOP) != 0)
1844 error.SetErrorToErrno ();
1845
1846 return error;
1847}
1848
1849Error
1850NativeProcessLinux::Detach ()
1851{
1852 Error error;
1853
1854 // Tell ptrace to detach from the process.
1855 if (GetID () != LLDB_INVALID_PROCESS_ID)
1856 error = Detach (GetID ());
1857
1858 // Stop monitoring the inferior.
Pavel Labath19cbe962015-07-21 13:20:32 +00001859 m_sigchld_handle.reset();
Todd Fialaaf245d12014-06-30 21:05:18 +00001860
1861 // No error.
1862 return error;
1863}
1864
1865Error
1866NativeProcessLinux::Signal (int signo)
1867{
1868 Error error;
1869
1870 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1871 if (log)
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001872 log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
1873 __FUNCTION__, signo, Host::GetSignalAsCString(signo), GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +00001874
1875 if (kill(GetID(), signo))
1876 error.SetErrorToErrno();
1877
1878 return error;
1879}
1880
1881Error
Chaoren Line9547b82015-02-03 01:51:00 +00001882NativeProcessLinux::Interrupt ()
1883{
1884 // Pick a running thread (or if none, a not-dead stopped thread) as
1885 // the chosen thread that will be the stop-reason thread.
Chaoren Line9547b82015-02-03 01:51:00 +00001886 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1887
1888 NativeThreadProtocolSP running_thread_sp;
1889 NativeThreadProtocolSP stopped_thread_sp;
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001890
1891 if (log)
1892 log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
1893
1894 Mutex::Locker locker (m_threads_mutex);
1895
1896 for (auto thread_sp : m_threads)
Chaoren Line9547b82015-02-03 01:51:00 +00001897 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001898 // The thread shouldn't be null but lets just cover that here.
1899 if (!thread_sp)
1900 continue;
Chaoren Line9547b82015-02-03 01:51:00 +00001901
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001902 // If we have a running or stepping thread, we'll call that the
1903 // target of the interrupt.
1904 const auto thread_state = thread_sp->GetState ();
1905 if (thread_state == eStateRunning ||
1906 thread_state == eStateStepping)
Chaoren Line9547b82015-02-03 01:51:00 +00001907 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001908 running_thread_sp = thread_sp;
1909 break;
1910 }
1911 else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
1912 {
1913 // Remember the first non-dead stopped thread. We'll use that as a backup if there are no running threads.
1914 stopped_thread_sp = thread_sp;
Chaoren Line9547b82015-02-03 01:51:00 +00001915 }
1916 }
1917
1918 if (!running_thread_sp && !stopped_thread_sp)
1919 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001920 Error error("found no running/stepping or live stopped threads as target for interrupt");
Chaoren Line9547b82015-02-03 01:51:00 +00001921 if (log)
Chaoren Line9547b82015-02-03 01:51:00 +00001922 log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001923
Chaoren Line9547b82015-02-03 01:51:00 +00001924 return error;
1925 }
1926
1927 NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
1928
1929 if (log)
1930 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
1931 __FUNCTION__,
1932 GetID (),
1933 running_thread_sp ? "running" : "stopped",
1934 deferred_signal_thread_sp->GetID ());
1935
Pavel Labathed89c7f2015-05-06 12:22:37 +00001936 StopRunningThreads(deferred_signal_thread_sp->GetID());
Pavel Labath45f5cb32015-05-05 15:05:50 +00001937
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001938 return Error();
Chaoren Line9547b82015-02-03 01:51:00 +00001939}
1940
1941Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001942NativeProcessLinux::Kill ()
1943{
1944 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1945 if (log)
1946 log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
1947
1948 Error error;
1949
1950 switch (m_state)
1951 {
1952 case StateType::eStateInvalid:
1953 case StateType::eStateExited:
1954 case StateType::eStateCrashed:
1955 case StateType::eStateDetached:
1956 case StateType::eStateUnloaded:
1957 // Nothing to do - the process is already dead.
1958 if (log)
1959 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
1960 return error;
1961
1962 case StateType::eStateConnected:
1963 case StateType::eStateAttaching:
1964 case StateType::eStateLaunching:
1965 case StateType::eStateStopped:
1966 case StateType::eStateRunning:
1967 case StateType::eStateStepping:
1968 case StateType::eStateSuspended:
1969 // We can try to kill a process in these states.
1970 break;
1971 }
1972
1973 if (kill (GetID (), SIGKILL) != 0)
1974 {
1975 error.SetErrorToErrno ();
1976 return error;
1977 }
1978
1979 return error;
1980}
1981
1982static Error
1983ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
1984{
1985 memory_region_info.Clear();
1986
1987 StringExtractor line_extractor (maps_line.c_str ());
1988
1989 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode pathname
1990 // perms: rwxp (letter is present if set, '-' if not, final character is p=private, s=shared).
1991
1992 // Parse out the starting address
1993 lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
1994
1995 // Parse out hyphen separating start and end address from range.
1996 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
1997 return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
1998
1999 // Parse out the ending address
2000 lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
2001
2002 // Parse out the space after the address.
2003 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
2004 return Error ("malformed /proc/{pid}/maps entry, missing space after range");
2005
2006 // Save the range.
2007 memory_region_info.GetRange ().SetRangeBase (start_address);
2008 memory_region_info.GetRange ().SetRangeEnd (end_address);
2009
2010 // Parse out each permission entry.
2011 if (line_extractor.GetBytesLeft () < 4)
2012 return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
2013
2014 // Handle read permission.
2015 const char read_perm_char = line_extractor.GetChar ();
2016 if (read_perm_char == 'r')
2017 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
2018 else
2019 {
2020 assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
2021 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2022 }
2023
2024 // Handle write permission.
2025 const char write_perm_char = line_extractor.GetChar ();
2026 if (write_perm_char == 'w')
2027 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
2028 else
2029 {
2030 assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
2031 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2032 }
2033
2034 // Handle execute permission.
2035 const char exec_perm_char = line_extractor.GetChar ();
2036 if (exec_perm_char == 'x')
2037 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
2038 else
2039 {
2040 assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
2041 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2042 }
2043
2044 return Error ();
2045}
2046
2047Error
2048NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
2049{
2050 // FIXME review that the final memory region returned extends to the end of the virtual address space,
2051 // with no perms if it is not mapped.
2052
2053 // Use an approach that reads memory regions from /proc/{pid}/maps.
2054 // Assume proc maps entries are in ascending order.
2055 // FIXME assert if we find differently.
2056 Mutex::Locker locker (m_mem_region_cache_mutex);
2057
2058 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2059 Error error;
2060
2061 if (m_supports_mem_region == LazyBool::eLazyBoolNo)
2062 {
2063 // We're done.
2064 error.SetErrorString ("unsupported");
2065 return error;
2066 }
2067
2068 // If our cache is empty, pull the latest. There should always be at least one memory region
2069 // if memory region handling is supported.
2070 if (m_mem_region_cache.empty ())
2071 {
2072 error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
2073 [&] (const std::string &line) -> bool
2074 {
2075 MemoryRegionInfo info;
2076 const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
2077 if (parse_error.Success ())
2078 {
2079 m_mem_region_cache.push_back (info);
2080 return true;
2081 }
2082 else
2083 {
2084 if (log)
2085 log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
2086 return false;
2087 }
2088 });
2089
2090 // If we had an error, we'll mark unsupported.
2091 if (error.Fail ())
2092 {
2093 m_supports_mem_region = LazyBool::eLazyBoolNo;
2094 return error;
2095 }
2096 else if (m_mem_region_cache.empty ())
2097 {
2098 // No entries after attempting to read them. This shouldn't happen if /proc/{pid}/maps
2099 // is supported. Assume we don't support map entries via procfs.
2100 if (log)
2101 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
2102 m_supports_mem_region = LazyBool::eLazyBoolNo;
2103 error.SetErrorString ("not supported");
2104 return error;
2105 }
2106
2107 if (log)
2108 log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ());
2109
2110 // We support memory retrieval, remember that.
2111 m_supports_mem_region = LazyBool::eLazyBoolYes;
2112 }
2113 else
2114 {
2115 if (log)
2116 log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2117 }
2118
2119 lldb::addr_t prev_base_address = 0;
2120
2121 // FIXME start by finding the last region that is <= target address using binary search. Data is sorted.
2122 // There can be a ton of regions on pthreads apps with lots of threads.
2123 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
2124 {
2125 MemoryRegionInfo &proc_entry_info = *it;
2126
2127 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
2128 assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
2129 prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
2130
2131 // If the target address comes before this entry, indicate distance to next region.
2132 if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
2133 {
2134 range_info.GetRange ().SetRangeBase (load_addr);
2135 range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
2136 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2137 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2138 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2139
2140 return error;
2141 }
2142 else if (proc_entry_info.GetRange ().Contains (load_addr))
2143 {
2144 // The target address is within the memory region we're processing here.
2145 range_info = proc_entry_info;
2146 return error;
2147 }
2148
2149 // The target memory address comes somewhere after the region we just parsed.
2150 }
2151
Tamas Berghammer09839c32015-07-03 09:30:19 +00002152 // If we made it here, we didn't find an entry that contained the given address. Return the
2153 // load_addr as start and the amount of bytes betwwen load address and the end of the memory as
2154 // size.
2155 range_info.GetRange ().SetRangeBase (load_addr);
2156 switch (m_arch.GetAddressByteSize())
2157 {
2158 case 4:
2159 range_info.GetRange ().SetByteSize (0x100000000ull - load_addr);
2160 break;
2161 case 8:
2162 range_info.GetRange ().SetByteSize (0ull - load_addr);
2163 break;
2164 default:
2165 assert(false && "Unrecognized data byte size");
2166 break;
2167 }
2168 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2169 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2170 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
Todd Fialaaf245d12014-06-30 21:05:18 +00002171 return error;
2172}
2173
2174void
2175NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
2176{
2177 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2178 if (log)
2179 log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
2180
2181 {
2182 Mutex::Locker locker (m_mem_region_cache_mutex);
2183 if (log)
2184 log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2185 m_mem_region_cache.clear ();
2186 }
2187}
2188
2189Error
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002190NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr)
Todd Fialaaf245d12014-06-30 21:05:18 +00002191{
2192 // FIXME implementing this requires the equivalent of
2193 // InferiorCallPOSIX::InferiorCallMmap, which depends on
2194 // functional ThreadPlans working with Native*Protocol.
2195#if 1
2196 return Error ("not implemented yet");
2197#else
2198 addr = LLDB_INVALID_ADDRESS;
2199
2200 unsigned prot = 0;
2201 if (permissions & lldb::ePermissionsReadable)
2202 prot |= eMmapProtRead;
2203 if (permissions & lldb::ePermissionsWritable)
2204 prot |= eMmapProtWrite;
2205 if (permissions & lldb::ePermissionsExecutable)
2206 prot |= eMmapProtExec;
2207
2208 // TODO implement this directly in NativeProcessLinux
2209 // (and lift to NativeProcessPOSIX if/when that class is
2210 // refactored out).
2211 if (InferiorCallMmap(this, addr, 0, size, prot,
2212 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
2213 m_addr_to_mmap_size[addr] = size;
2214 return Error ();
2215 } else {
2216 addr = LLDB_INVALID_ADDRESS;
2217 return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
2218 }
2219#endif
2220}
2221
2222Error
2223NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
2224{
2225 // FIXME see comments in AllocateMemory - required lower-level
2226 // bits not in place yet (ThreadPlans)
2227 return Error ("not implemented");
2228}
2229
2230lldb::addr_t
2231NativeProcessLinux::GetSharedLibraryInfoAddress ()
2232{
2233#if 1
2234 // punt on this for now
2235 return LLDB_INVALID_ADDRESS;
2236#else
2237 // Return the image info address for the exe module
2238#if 1
2239 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2240
2241 ModuleSP module_sp;
2242 Error error = GetExeModuleSP (module_sp);
2243 if (error.Fail ())
2244 {
2245 if (log)
2246 log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ());
2247 return LLDB_INVALID_ADDRESS;
2248 }
2249
2250 if (module_sp == nullptr)
2251 {
2252 if (log)
2253 log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__);
2254 return LLDB_INVALID_ADDRESS;
2255 }
2256
2257 ObjectFileSP object_file_sp = module_sp->GetObjectFile ();
2258 if (object_file_sp == nullptr)
2259 {
2260 if (log)
2261 log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__);
2262 return LLDB_INVALID_ADDRESS;
2263 }
2264
2265 return obj_file_sp->GetImageInfoAddress();
2266#else
2267 Target *target = &GetTarget();
2268 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
2269 Address addr = obj_file->GetImageInfoAddress(target);
2270
2271 if (addr.IsValid())
2272 return addr.GetLoadAddress(target);
2273 return LLDB_INVALID_ADDRESS;
2274#endif
2275#endif // punt on this for now
2276}
2277
2278size_t
2279NativeProcessLinux::UpdateThreads ()
2280{
2281 // The NativeProcessLinux monitoring threads are always up to date
2282 // with respect to thread state and they keep the thread list
2283 // populated properly. All this method needs to do is return the
2284 // thread count.
2285 Mutex::Locker locker (m_threads_mutex);
2286 return m_threads.size ();
2287}
2288
2289bool
2290NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
2291{
2292 arch = m_arch;
2293 return true;
2294}
2295
2296Error
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002297NativeProcessLinux::GetSoftwareBreakpointPCOffset (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size)
Todd Fialaaf245d12014-06-30 21:05:18 +00002298{
2299 // FIXME put this behind a breakpoint protocol class that can be
2300 // set per architecture. Need ARM, MIPS support here.
2301 static const uint8_t g_i386_opcode [] = { 0xCC };
2302
2303 switch (m_arch.GetMachine ())
2304 {
2305 case llvm::Triple::x86:
2306 case llvm::Triple::x86_64:
2307 actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
2308 return Error ();
2309
Tamas Berghammerff7fd902015-07-03 12:51:30 +00002310 case llvm::Triple::arm:
2311 case llvm::Triple::aarch64:
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00002312 case llvm::Triple::mips64:
2313 case llvm::Triple::mips64el:
Sagar Thakurce815e42015-06-03 10:14:24 +00002314 case llvm::Triple::mips:
2315 case llvm::Triple::mipsel:
Tamas Berghammerff7fd902015-07-03 12:51:30 +00002316 // On these architectures the PC don't get updated for breakpoint hits
Jaydeep Patilc60c9452015-06-23 03:37:08 +00002317 actual_opcode_size = 0;
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00002318 return Error ();
2319
Todd Fialaaf245d12014-06-30 21:05:18 +00002320 default:
2321 assert(false && "CPU type not supported!");
2322 return Error ("CPU type not supported");
2323 }
2324}
2325
2326Error
2327NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
2328{
2329 if (hardware)
2330 return Error ("NativeProcessLinux does not support hardware breakpoints");
2331 else
2332 return SetSoftwareBreakpoint (addr, size);
2333}
2334
2335Error
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002336NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint,
2337 size_t &actual_opcode_size,
2338 const uint8_t *&trap_opcode_bytes)
Todd Fialaaf245d12014-06-30 21:05:18 +00002339{
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002340 // FIXME put this behind a breakpoint protocol class that can be set per
2341 // architecture. Need MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00002342 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002343 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
2344 // linux kernel does otherwise.
2345 static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 };
Todd Fialaaf245d12014-06-30 21:05:18 +00002346 static const uint8_t g_i386_opcode [] = { 0xCC };
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00002347 static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00002348 static const uint8_t g_mips64el_opcode[] = { 0x0d, 0x00, 0x00, 0x00 };
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002349 static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde };
Todd Fialaaf245d12014-06-30 21:05:18 +00002350
2351 switch (m_arch.GetMachine ())
2352 {
Todd Fiala2afc5962014-08-21 16:42:31 +00002353 case llvm::Triple::aarch64:
2354 trap_opcode_bytes = g_aarch64_opcode;
2355 actual_opcode_size = sizeof(g_aarch64_opcode);
2356 return Error ();
2357
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002358 case llvm::Triple::arm:
2359 switch (trap_opcode_size_hint)
2360 {
2361 case 2:
2362 trap_opcode_bytes = g_thumb_breakpoint_opcode;
2363 actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
2364 return Error ();
2365 case 4:
2366 trap_opcode_bytes = g_arm_breakpoint_opcode;
2367 actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
2368 return Error ();
2369 default:
2370 assert(false && "Unrecognised trap opcode size hint!");
2371 return Error ("Unrecognised trap opcode size hint!");
2372 }
2373
Todd Fialaaf245d12014-06-30 21:05:18 +00002374 case llvm::Triple::x86:
2375 case llvm::Triple::x86_64:
2376 trap_opcode_bytes = g_i386_opcode;
2377 actual_opcode_size = sizeof(g_i386_opcode);
2378 return Error ();
2379
Sagar Thakurce815e42015-06-03 10:14:24 +00002380 case llvm::Triple::mips:
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00002381 case llvm::Triple::mips64:
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00002382 trap_opcode_bytes = g_mips64_opcode;
2383 actual_opcode_size = sizeof(g_mips64_opcode);
2384 return Error ();
2385
Sagar Thakurce815e42015-06-03 10:14:24 +00002386 case llvm::Triple::mipsel:
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00002387 case llvm::Triple::mips64el:
2388 trap_opcode_bytes = g_mips64el_opcode;
2389 actual_opcode_size = sizeof(g_mips64el_opcode);
2390 return Error ();
2391
Todd Fialaaf245d12014-06-30 21:05:18 +00002392 default:
2393 assert(false && "CPU type not supported!");
2394 return Error ("CPU type not supported");
2395 }
2396}
2397
2398#if 0
2399ProcessMessage::CrashReason
2400NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
2401{
2402 ProcessMessage::CrashReason reason;
2403 assert(info->si_signo == SIGSEGV);
2404
2405 reason = ProcessMessage::eInvalidCrashReason;
2406
2407 switch (info->si_code)
2408 {
2409 default:
2410 assert(false && "unexpected si_code for SIGSEGV");
2411 break;
2412 case SI_KERNEL:
2413 // Linux will occasionally send spurious SI_KERNEL codes.
2414 // (this is poorly documented in sigaction)
2415 // One way to get this is via unaligned SIMD loads.
2416 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
2417 break;
2418 case SEGV_MAPERR:
2419 reason = ProcessMessage::eInvalidAddress;
2420 break;
2421 case SEGV_ACCERR:
2422 reason = ProcessMessage::ePrivilegedAddress;
2423 break;
2424 }
2425
2426 return reason;
2427}
2428#endif
2429
2430
2431#if 0
2432ProcessMessage::CrashReason
2433NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
2434{
2435 ProcessMessage::CrashReason reason;
2436 assert(info->si_signo == SIGILL);
2437
2438 reason = ProcessMessage::eInvalidCrashReason;
2439
2440 switch (info->si_code)
2441 {
2442 default:
2443 assert(false && "unexpected si_code for SIGILL");
2444 break;
2445 case ILL_ILLOPC:
2446 reason = ProcessMessage::eIllegalOpcode;
2447 break;
2448 case ILL_ILLOPN:
2449 reason = ProcessMessage::eIllegalOperand;
2450 break;
2451 case ILL_ILLADR:
2452 reason = ProcessMessage::eIllegalAddressingMode;
2453 break;
2454 case ILL_ILLTRP:
2455 reason = ProcessMessage::eIllegalTrap;
2456 break;
2457 case ILL_PRVOPC:
2458 reason = ProcessMessage::ePrivilegedOpcode;
2459 break;
2460 case ILL_PRVREG:
2461 reason = ProcessMessage::ePrivilegedRegister;
2462 break;
2463 case ILL_COPROC:
2464 reason = ProcessMessage::eCoprocessorError;
2465 break;
2466 case ILL_BADSTK:
2467 reason = ProcessMessage::eInternalStackError;
2468 break;
2469 }
2470
2471 return reason;
2472}
2473#endif
2474
2475#if 0
2476ProcessMessage::CrashReason
2477NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
2478{
2479 ProcessMessage::CrashReason reason;
2480 assert(info->si_signo == SIGFPE);
2481
2482 reason = ProcessMessage::eInvalidCrashReason;
2483
2484 switch (info->si_code)
2485 {
2486 default:
2487 assert(false && "unexpected si_code for SIGFPE");
2488 break;
2489 case FPE_INTDIV:
2490 reason = ProcessMessage::eIntegerDivideByZero;
2491 break;
2492 case FPE_INTOVF:
2493 reason = ProcessMessage::eIntegerOverflow;
2494 break;
2495 case FPE_FLTDIV:
2496 reason = ProcessMessage::eFloatDivideByZero;
2497 break;
2498 case FPE_FLTOVF:
2499 reason = ProcessMessage::eFloatOverflow;
2500 break;
2501 case FPE_FLTUND:
2502 reason = ProcessMessage::eFloatUnderflow;
2503 break;
2504 case FPE_FLTRES:
2505 reason = ProcessMessage::eFloatInexactResult;
2506 break;
2507 case FPE_FLTINV:
2508 reason = ProcessMessage::eFloatInvalidOperation;
2509 break;
2510 case FPE_FLTSUB:
2511 reason = ProcessMessage::eFloatSubscriptRange;
2512 break;
2513 }
2514
2515 return reason;
2516}
2517#endif
2518
2519#if 0
2520ProcessMessage::CrashReason
2521NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
2522{
2523 ProcessMessage::CrashReason reason;
2524 assert(info->si_signo == SIGBUS);
2525
2526 reason = ProcessMessage::eInvalidCrashReason;
2527
2528 switch (info->si_code)
2529 {
2530 default:
2531 assert(false && "unexpected si_code for SIGBUS");
2532 break;
2533 case BUS_ADRALN:
2534 reason = ProcessMessage::eIllegalAlignment;
2535 break;
2536 case BUS_ADRERR:
2537 reason = ProcessMessage::eIllegalAddress;
2538 break;
2539 case BUS_OBJERR:
2540 reason = ProcessMessage::eHardwareError;
2541 break;
2542 }
2543
2544 return reason;
2545}
2546#endif
2547
Todd Fialaaf245d12014-06-30 21:05:18 +00002548Error
Chaoren Lin26438d22015-05-05 17:50:53 +00002549NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
Todd Fialaaf245d12014-06-30 21:05:18 +00002550{
Pavel Labathdf7c6992015-06-17 18:38:49 +00002551 if (ProcessVmReadvSupported()) {
2552 // The process_vm_readv path is about 50 times faster than ptrace api. We want to use
2553 // this syscall if it is supported.
2554
2555 const ::pid_t pid = GetID();
2556
2557 struct iovec local_iov, remote_iov;
2558 local_iov.iov_base = buf;
2559 local_iov.iov_len = size;
2560 remote_iov.iov_base = reinterpret_cast<void *>(addr);
2561 remote_iov.iov_len = size;
2562
2563 bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
2564 const bool success = bytes_read == size;
2565
2566 Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2567 if (log)
2568 log->Printf ("NativeProcessLinux::%s using process_vm_readv to read %zd bytes from inferior address 0x%" PRIx64": %s",
2569 __FUNCTION__, size, addr, success ? "Success" : strerror(errno));
2570
2571 if (success)
2572 return Error();
2573 // else
2574 // the call failed for some reason, let's retry the read using ptrace api.
2575 }
2576
Pavel Labath19cbe962015-07-21 13:20:32 +00002577 unsigned char *dst = static_cast<unsigned char*>(buf);
2578 size_t remainder;
2579 long data;
2580
2581 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
2582 if (log)
2583 ProcessPOSIXLog::IncNestLevel();
2584 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
2585 log->Printf ("NativeProcessLinux::%s(%p, %p, %zd, _)", __FUNCTION__, (void*)addr, buf, size);
2586
2587 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
2588 {
2589 Error error = NativeProcessLinux::PtraceWrapper(PTRACE_PEEKDATA, GetID(), (void*)addr, nullptr, 0, &data);
2590 if (error.Fail())
2591 {
2592 if (log)
2593 ProcessPOSIXLog::DecNestLevel();
2594 return error;
2595 }
2596
2597 remainder = size - bytes_read;
2598 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
2599
2600 // Copy the data into our buffer
2601 for (unsigned i = 0; i < remainder; ++i)
2602 dst[i] = ((data >> i*8) & 0xFF);
2603
2604 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2605 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
2606 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2607 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
2608 {
2609 uintptr_t print_dst = 0;
2610 // Format bytes from data by moving into print_dst for log output
2611 for (unsigned i = 0; i < remainder; ++i)
2612 print_dst |= (((data >> i*8) & 0xFF) << i*8);
Pavel Labath79203992015-07-23 13:07:37 +00002613 log->Printf ("NativeProcessLinux::%s() [0x%" PRIx64 "]:0x%" PRIx64 " (0x%" PRIx64 ")",
2614 __FUNCTION__, addr, uint64_t(print_dst), uint64_t(data));
Pavel Labath19cbe962015-07-21 13:20:32 +00002615 }
2616 addr += k_ptrace_word_size;
2617 dst += k_ptrace_word_size;
2618 }
2619
2620 if (log)
2621 ProcessPOSIXLog::DecNestLevel();
2622 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00002623}
2624
2625Error
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002626NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
2627{
2628 Error error = ReadMemory(addr, buf, size, bytes_read);
2629 if (error.Fail()) return error;
2630 return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
2631}
2632
2633Error
2634NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written)
Todd Fialaaf245d12014-06-30 21:05:18 +00002635{
Pavel Labath19cbe962015-07-21 13:20:32 +00002636 const unsigned char *src = static_cast<const unsigned char*>(buf);
2637 size_t remainder;
2638 Error error;
2639
2640 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
2641 if (log)
2642 ProcessPOSIXLog::IncNestLevel();
2643 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
Pavel Labath79203992015-07-23 13:07:37 +00002644 log->Printf ("NativeProcessLinux::%s(0x%" PRIx64 ", %p, %zu)", __FUNCTION__, addr, buf, size);
Pavel Labath19cbe962015-07-21 13:20:32 +00002645
2646 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
2647 {
2648 remainder = size - bytes_written;
2649 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
2650
2651 if (remainder == k_ptrace_word_size)
2652 {
2653 unsigned long data = 0;
2654 for (unsigned i = 0; i < k_ptrace_word_size; ++i)
2655 data |= (unsigned long)src[i] << i*8;
2656
2657 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2658 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
2659 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2660 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
2661 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
2662 (void*)addr, *(const unsigned long*)src, data);
2663
2664 error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(), (void*)addr, (void*)data);
2665 if (error.Fail())
2666 {
2667 if (log)
2668 ProcessPOSIXLog::DecNestLevel();
2669 return error;
2670 }
2671 }
2672 else
2673 {
2674 unsigned char buff[8];
2675 size_t bytes_read;
2676 error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
2677 if (error.Fail())
2678 {
2679 if (log)
2680 ProcessPOSIXLog::DecNestLevel();
2681 return error;
2682 }
2683
2684 memcpy(buff, src, remainder);
2685
2686 size_t bytes_written_rec;
2687 error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
2688 if (error.Fail())
2689 {
2690 if (log)
2691 ProcessPOSIXLog::DecNestLevel();
2692 return error;
2693 }
2694
2695 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2696 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
2697 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2698 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
2699 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
2700 (void*)addr, *(const unsigned long*)src, *(unsigned long*)buff);
2701 }
2702
2703 addr += k_ptrace_word_size;
2704 src += k_ptrace_word_size;
2705 }
2706 if (log)
2707 ProcessPOSIXLog::DecNestLevel();
2708 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002709}
2710
Chaoren Lin97ccc292015-02-03 01:51:12 +00002711Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002712NativeProcessLinux::Resume (lldb::tid_t tid, uint32_t signo)
2713{
Todd Fialaaf245d12014-06-30 21:05:18 +00002714 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2715
2716 if (log)
2717 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid,
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00002718 Host::GetSignalAsCString(signo));
Pavel Labathc7512fd2015-06-26 10:14:12 +00002719
2720
2721
2722 intptr_t data = 0;
2723
2724 if (signo != LLDB_INVALID_SIGNAL_NUMBER)
2725 data = signo;
2726
Pavel Labath19cbe962015-07-21 13:20:32 +00002727 Error error = PtraceWrapper(PTRACE_CONT, tid, nullptr, (void*)data);
Pavel Labathc7512fd2015-06-26 10:14:12 +00002728
Todd Fialaaf245d12014-06-30 21:05:18 +00002729 if (log)
Pavel Labathc7512fd2015-06-26 10:14:12 +00002730 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " result = %s", __FUNCTION__, tid, error.Success() ? "true" : "false");
2731 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002732}
2733
Chaoren Lin97ccc292015-02-03 01:51:12 +00002734Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002735NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo)
2736{
Pavel Labathc7512fd2015-06-26 10:14:12 +00002737 intptr_t data = 0;
2738
2739 if (signo != LLDB_INVALID_SIGNAL_NUMBER)
2740 data = signo;
2741
Pavel Labath19cbe962015-07-21 13:20:32 +00002742 return PtraceWrapper(PTRACE_SINGLESTEP, tid, nullptr, (void*)data);
Todd Fialaaf245d12014-06-30 21:05:18 +00002743}
2744
Chaoren Lin97ccc292015-02-03 01:51:12 +00002745Error
2746NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
Todd Fialaaf245d12014-06-30 21:05:18 +00002747{
Pavel Labath19cbe962015-07-21 13:20:32 +00002748 return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
Todd Fialaaf245d12014-06-30 21:05:18 +00002749}
2750
Chaoren Lin97ccc292015-02-03 01:51:12 +00002751Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002752NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
2753{
Pavel Labath19cbe962015-07-21 13:20:32 +00002754 return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
Todd Fialaaf245d12014-06-30 21:05:18 +00002755}
2756
Tamas Berghammerdb264a62015-03-31 09:52:22 +00002757Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002758NativeProcessLinux::Detach(lldb::tid_t tid)
2759{
Chaoren Lin97ccc292015-02-03 01:51:12 +00002760 if (tid == LLDB_INVALID_THREAD_ID)
2761 return Error();
2762
Pavel Labath19cbe962015-07-21 13:20:32 +00002763 return PtraceWrapper(PTRACE_DETACH, tid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002764}
2765
2766bool
Chaoren Lind3173f32015-05-29 19:52:29 +00002767NativeProcessLinux::DupDescriptor(const FileSpec &file_spec, int fd, int flags)
Todd Fialaaf245d12014-06-30 21:05:18 +00002768{
Chaoren Lind3173f32015-05-29 19:52:29 +00002769 int target_fd = open(file_spec.GetCString(), flags, 0666);
Todd Fialaaf245d12014-06-30 21:05:18 +00002770
2771 if (target_fd == -1)
2772 return false;
2773
Pavel Labath493c3a12015-02-04 10:36:57 +00002774 if (dup2(target_fd, fd) == -1)
2775 return false;
2776
2777 return (close(target_fd) == -1) ? false : true;
Todd Fialaaf245d12014-06-30 21:05:18 +00002778}
2779
Todd Fialaaf245d12014-06-30 21:05:18 +00002780bool
2781NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
2782{
2783 for (auto thread_sp : m_threads)
2784 {
2785 assert (thread_sp && "thread list should not contain NULL threads");
2786 if (thread_sp->GetID () == thread_id)
2787 {
2788 // We have this thread.
2789 return true;
2790 }
2791 }
2792
2793 // We don't have this thread.
2794 return false;
2795}
2796
2797NativeThreadProtocolSP
2798NativeProcessLinux::MaybeGetThreadNoLock (lldb::tid_t thread_id)
2799{
2800 // CONSIDER organize threads by map - we can do better than linear.
2801 for (auto thread_sp : m_threads)
2802 {
2803 if (thread_sp->GetID () == thread_id)
2804 return thread_sp;
2805 }
2806
2807 // We don't have this thread.
2808 return NativeThreadProtocolSP ();
2809}
2810
2811bool
2812NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
2813{
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002814 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
2815
2816 if (log)
2817 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, thread_id);
2818
2819 bool found = false;
2820
Todd Fialaaf245d12014-06-30 21:05:18 +00002821 Mutex::Locker locker (m_threads_mutex);
2822 for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
2823 {
2824 if (*it && ((*it)->GetID () == thread_id))
2825 {
2826 m_threads.erase (it);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002827 found = true;
2828 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00002829 }
2830 }
2831
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002832 // If we have a pending notification, remove this from the set.
2833 if (m_pending_notification_up)
2834 {
2835 m_pending_notification_up->wait_for_stop_tids.erase(thread_id);
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00002836 SignalIfAllThreadsStopped();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002837 }
2838
2839 return found;
Todd Fialaaf245d12014-06-30 21:05:18 +00002840}
2841
2842NativeThreadProtocolSP
2843NativeProcessLinux::AddThread (lldb::tid_t thread_id)
2844{
2845 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
2846
2847 Mutex::Locker locker (m_threads_mutex);
2848
2849 if (log)
2850 {
2851 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
2852 __FUNCTION__,
2853 GetID (),
2854 thread_id);
2855 }
2856
2857 assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
2858
2859 // If this is the first thread, save it as the current thread
2860 if (m_threads.empty ())
2861 SetCurrentThreadID (thread_id);
2862
2863 NativeThreadProtocolSP thread_sp (new NativeThreadLinux (this, thread_id));
2864 m_threads.push_back (thread_sp);
2865
2866 return thread_sp;
2867}
2868
Todd Fialaaf245d12014-06-30 21:05:18 +00002869Error
2870NativeProcessLinux::FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp)
2871{
Todd Fiala75f47c32014-10-11 21:42:09 +00002872 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Todd Fialaaf245d12014-06-30 21:05:18 +00002873
2874 Error error;
2875
2876 // Get a linux thread pointer.
2877 if (!thread_sp)
2878 {
2879 error.SetErrorString ("null thread_sp");
2880 if (log)
2881 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
2882 return error;
2883 }
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002884 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00002885
2886 // Find out the size of a breakpoint (might depend on where we are in the code).
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002887 NativeRegisterContextSP context_sp = linux_thread_sp->GetRegisterContext ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002888 if (!context_sp)
2889 {
2890 error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
2891 if (log)
2892 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
2893 return error;
2894 }
2895
2896 uint32_t breakpoint_size = 0;
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002897 error = GetSoftwareBreakpointPCOffset (context_sp, breakpoint_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00002898 if (error.Fail ())
2899 {
2900 if (log)
2901 log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
2902 return error;
2903 }
2904 else
2905 {
2906 if (log)
2907 log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
2908 }
2909
2910 // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
Jaydeep Patilc60c9452015-06-23 03:37:08 +00002911 const lldb::addr_t initial_pc_addr = context_sp->GetPCfromBreakpointLocation ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002912 lldb::addr_t breakpoint_addr = initial_pc_addr;
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002913 if (breakpoint_size > 0)
Todd Fialaaf245d12014-06-30 21:05:18 +00002914 {
2915 // Do not allow breakpoint probe to wrap around.
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002916 if (breakpoint_addr >= breakpoint_size)
2917 breakpoint_addr -= breakpoint_size;
Todd Fialaaf245d12014-06-30 21:05:18 +00002918 }
2919
2920 // Check if we stopped because of a breakpoint.
2921 NativeBreakpointSP breakpoint_sp;
2922 error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
2923 if (!error.Success () || !breakpoint_sp)
2924 {
2925 // We didn't find one at a software probe location. Nothing to do.
2926 if (log)
2927 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
2928 return Error ();
2929 }
2930
2931 // If the breakpoint is not a software breakpoint, nothing to do.
2932 if (!breakpoint_sp->IsSoftwareBreakpoint ())
2933 {
2934 if (log)
2935 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
2936 return Error ();
2937 }
2938
2939 //
2940 // We have a software breakpoint and need to adjust the PC.
2941 //
2942
2943 // Sanity check.
2944 if (breakpoint_size == 0)
2945 {
2946 // Nothing to do! How did we get here?
2947 if (log)
2948 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);
2949 return Error ();
2950 }
2951
2952 // Change the program counter.
2953 if (log)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002954 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": changing PC from 0x%" PRIx64 " to 0x%" PRIx64, __FUNCTION__, GetID (), linux_thread_sp->GetID (), initial_pc_addr, breakpoint_addr);
Todd Fialaaf245d12014-06-30 21:05:18 +00002955
2956 error = context_sp->SetPC (breakpoint_addr);
2957 if (error.Fail ())
2958 {
2959 if (log)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002960 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": failed to set PC: %s", __FUNCTION__, GetID (), linux_thread_sp->GetID (), error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00002961 return error;
2962 }
2963
2964 return error;
2965}
Chaoren Linfa03ad22015-02-03 01:50:42 +00002966
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00002967Error
2968NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec)
2969{
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00002970 FileSpec module_file_spec(module_path, true);
2971
Pavel Labath162fb8e2015-07-23 14:47:33 +00002972 bool found = false;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00002973 file_spec.Clear();
Pavel Labath162fb8e2015-07-23 14:47:33 +00002974 ProcFileReader::ProcessLineByLine(GetID(), "maps",
2975 [&] (const std::string &line)
2976 {
2977 SmallVector<StringRef, 16> columns;
2978 StringRef(line).split(columns, " ", -1, false);
2979 if (columns.size() < 6)
2980 return true; // continue searching
2981
2982 FileSpec this_file_spec(columns[5].str().c_str(), false);
2983 if (this_file_spec.GetFilename() != module_file_spec.GetFilename())
2984 return true; // continue searching
2985
2986 file_spec = this_file_spec;
2987 found = true;
2988 return false; // we are done
2989 });
2990
2991 if (! found)
2992 return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
2993 module_file_spec.GetFilename().AsCString(), GetID());
2994
2995 return Error();
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00002996}
Pavel Labathc0765592015-05-06 10:46:34 +00002997
Pavel Labath5eb721e2015-05-07 08:30:31 +00002998Error
Tamas Berghammer783bfc82015-06-18 20:43:56 +00002999NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef& file_name, lldb::addr_t& load_addr)
3000{
3001 load_addr = LLDB_INVALID_ADDRESS;
3002 Error error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
3003 [&] (const std::string &line) -> bool
3004 {
3005 StringRef maps_row(line);
3006
3007 SmallVector<StringRef, 16> maps_columns;
3008 maps_row.split(maps_columns, StringRef(" "), -1, false);
3009
3010 if (maps_columns.size() < 6)
3011 {
3012 // Return true to continue reading the proc file
3013 return true;
3014 }
3015
3016 if (maps_columns[5] == file_name)
3017 {
3018 StringExtractor addr_extractor(maps_columns[0].str().c_str());
3019 load_addr = addr_extractor.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
3020
3021 // Return false to stop reading the proc file further
3022 return false;
3023 }
3024
3025 // Return true to continue reading the proc file
3026 return true;
3027 });
3028 return error;
3029}
3030
3031Error
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003032NativeProcessLinux::ResumeThread(
Pavel Labathc0765592015-05-06 10:46:34 +00003033 lldb::tid_t tid,
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003034 NativeThreadLinux::ResumeThreadFunction request_thread_resume_function,
Pavel Labathc0765592015-05-06 10:46:34 +00003035 bool error_when_already_running)
3036{
Pavel Labath5eb721e2015-05-07 08:30:31 +00003037 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003038
3039 if (log)
3040 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ", error_when_already_running: %s)",
3041 __FUNCTION__, tid, error_when_already_running?"true":"false");
Pavel Labath5eb721e2015-05-07 08:30:31 +00003042
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003043 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
3044 lldbassert(thread_sp != nullptr);
Pavel Labath5eb721e2015-05-07 08:30:31 +00003045
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003046 auto& context = thread_sp->GetThreadContext();
Pavel Labathc0765592015-05-06 10:46:34 +00003047 // Tell the thread to resume if we don't already think it is running.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003048 const bool is_stopped = StateIsStoppedState(thread_sp->GetState(), true);
Pavel Labath5eb721e2015-05-07 08:30:31 +00003049
3050 lldbassert(!(error_when_already_running && !is_stopped));
3051
Pavel Labathc0765592015-05-06 10:46:34 +00003052 if (!is_stopped)
3053 {
3054 // It's not an error, just a log, if the error_when_already_running flag is not set.
3055 // This covers cases where, for instance, we're just trying to resume all threads
3056 // from the user side.
Pavel Labath5eb721e2015-05-07 08:30:31 +00003057 if (log)
3058 log->Printf("NativeProcessLinux::%s tid %" PRIu64 " optional resume skipped since it is already running",
3059 __FUNCTION__,
3060 tid);
3061 return Error();
Pavel Labathc0765592015-05-06 10:46:34 +00003062 }
3063
3064 // Before we do the resume below, first check if we have a pending
Pavel Labath108c3252015-05-12 09:03:18 +00003065 // stop notification that is currently waiting for
Pavel Labathc0765592015-05-06 10:46:34 +00003066 // this thread to stop. This is potentially a buggy situation since
3067 // we're ostensibly waiting for threads to stop before we send out the
3068 // pending notification, and here we are resuming one before we send
3069 // out the pending stop notification.
Pavel Labath108c3252015-05-12 09:03:18 +00003070 if (m_pending_notification_up && log && m_pending_notification_up->wait_for_stop_tids.count (tid) > 0)
Pavel Labathc0765592015-05-06 10:46:34 +00003071 {
Pavel Labath108c3252015-05-12 09:03:18 +00003072 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__, tid, m_pending_notification_up->triggering_tid);
Pavel Labathc0765592015-05-06 10:46:34 +00003073 }
3074
3075 // Request a resume. We expect this to be synchronous and the system
3076 // to reflect it is running after this completes.
3077 const auto error = request_thread_resume_function (tid, false);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003078 if (error.Success())
3079 context.request_resume_function = request_thread_resume_function;
Pavel Labath5eb721e2015-05-07 08:30:31 +00003080 else if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00003081 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00003082 log->Printf("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s",
Pavel Labathc0765592015-05-06 10:46:34 +00003083 __FUNCTION__, tid, error.AsCString ());
3084 }
3085
Pavel Labath5eb721e2015-05-07 08:30:31 +00003086 return error;
Pavel Labathc0765592015-05-06 10:46:34 +00003087}
3088
3089//===----------------------------------------------------------------------===//
3090
3091void
Pavel Labath337f3eb2015-05-08 08:57:45 +00003092NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid)
Pavel Labathc0765592015-05-06 10:46:34 +00003093{
Pavel Labath5eb721e2015-05-07 08:30:31 +00003094 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00003095
Pavel Labath5eb721e2015-05-07 08:30:31 +00003096 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00003097 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00003098 log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ")",
Pavel Labathc0765592015-05-06 10:46:34 +00003099 __FUNCTION__, triggering_tid);
3100 }
3101
Pavel Labath337f3eb2015-05-08 08:57:45 +00003102 DoStopThreads(PendingNotificationUP(new PendingNotification(triggering_tid)));
Pavel Labathc0765592015-05-06 10:46:34 +00003103
Pavel Labath5eb721e2015-05-07 08:30:31 +00003104 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00003105 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00003106 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00003107 }
3108}
3109
3110void
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003111NativeProcessLinux::SignalIfAllThreadsStopped()
Pavel Labathc0765592015-05-06 10:46:34 +00003112{
3113 if (m_pending_notification_up && m_pending_notification_up->wait_for_stop_tids.empty ())
3114 {
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003115 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
3116
3117 // Clear any temporary breakpoints we used to implement software single stepping.
3118 for (const auto &thread_info: m_threads_stepping_with_breakpoint)
3119 {
3120 Error error = RemoveBreakpoint (thread_info.second);
3121 if (error.Fail())
3122 if (log)
3123 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " remove stepping breakpoint: %s",
3124 __FUNCTION__, thread_info.first, error.AsCString());
3125 }
3126 m_threads_stepping_with_breakpoint.clear();
3127
3128 // Notify the delegate about the stop
Pavel Labathed89c7f2015-05-06 12:22:37 +00003129 SetCurrentThreadID(m_pending_notification_up->triggering_tid);
3130 SetState(StateType::eStateStopped, true);
Pavel Labathc0765592015-05-06 10:46:34 +00003131 m_pending_notification_up.reset();
3132 }
3133}
3134
Pavel Labathc0765592015-05-06 10:46:34 +00003135void
3136NativeProcessLinux::RequestStopOnAllRunningThreads()
3137{
3138 // Request a stop for all the thread stops that need to be stopped
3139 // and are not already known to be stopped. Keep a list of all the
3140 // threads from which we still need to hear a stop reply.
3141
3142 ThreadIDSet sent_tids;
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003143 for (const auto &thread_sp: m_threads)
Pavel Labathc0765592015-05-06 10:46:34 +00003144 {
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003145 // We only care about running threads
3146 if (StateIsStoppedState(thread_sp->GetState(), true))
3147 continue;
Pavel Labathc0765592015-05-06 10:46:34 +00003148
Pavel Labath108c3252015-05-12 09:03:18 +00003149 static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
3150 sent_tids.insert (thread_sp->GetID());
Pavel Labathc0765592015-05-06 10:46:34 +00003151 }
3152
3153 // Set the wait list to the set of tids for which we requested stops.
3154 m_pending_notification_up->wait_for_stop_tids.swap (sent_tids);
3155}
3156
Pavel Labathc0765592015-05-06 10:46:34 +00003157
Pavel Labath5eb721e2015-05-07 08:30:31 +00003158Error
3159NativeProcessLinux::ThreadDidStop (lldb::tid_t tid, bool initiated_by_llgs)
Pavel Labathc0765592015-05-06 10:46:34 +00003160{
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003161 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3162
3163 if (log)
3164 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ", %sinitiated by llgs)",
3165 __FUNCTION__, tid, initiated_by_llgs?"":"not ");
3166
Pavel Labathc0765592015-05-06 10:46:34 +00003167 // Ensure we know about the thread.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003168 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
3169 lldbassert(thread_sp != nullptr);
Pavel Labathc0765592015-05-06 10:46:34 +00003170
3171 // Update the global list of known thread states. This one is definitely stopped.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003172 auto& context = thread_sp->GetThreadContext();
3173 const auto stop_was_requested = context.stop_requested;
3174 context.stop_requested = false;
Pavel Labathc0765592015-05-06 10:46:34 +00003175
3176 // If we have a pending notification, remove this from the set.
3177 if (m_pending_notification_up)
3178 {
3179 m_pending_notification_up->wait_for_stop_tids.erase(tid);
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003180 SignalIfAllThreadsStopped();
Pavel Labathc0765592015-05-06 10:46:34 +00003181 }
3182
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003183 Error error;
3184 if (initiated_by_llgs && context.request_resume_function && !stop_was_requested)
Pavel Labathc0765592015-05-06 10:46:34 +00003185 {
3186 // We can end up here if stop was initiated by LLGS but by this time a
3187 // thread stop has occurred - maybe initiated by another event.
Pavel Labath5eb721e2015-05-07 08:30:31 +00003188 if (log)
3189 log->Printf("Resuming thread %" PRIu64 " since stop wasn't requested", tid);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003190 error = context.request_resume_function (tid, true);
3191 if (error.Fail() && log)
Pavel Labathc0765592015-05-06 10:46:34 +00003192 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00003193 log->Printf("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s",
3194 __FUNCTION__, tid, error.AsCString ());
Pavel Labathc0765592015-05-06 10:46:34 +00003195 }
3196 }
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003197 return error;
Pavel Labathc0765592015-05-06 10:46:34 +00003198}
3199
3200void
Pavel Labathed89c7f2015-05-06 12:22:37 +00003201NativeProcessLinux::DoStopThreads(PendingNotificationUP &&notification_up)
Pavel Labathc0765592015-05-06 10:46:34 +00003202{
Pavel Labath5eb721e2015-05-07 08:30:31 +00003203 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3204 if (m_pending_notification_up && log)
Pavel Labathc0765592015-05-06 10:46:34 +00003205 {
3206 // Yikes - we've already got a pending signal notification in progress.
3207 // Log this info. We lose the pending notification here.
Pavel Labath5eb721e2015-05-07 08:30:31 +00003208 log->Printf("NativeProcessLinux::%s dropping existing pending signal notification for tid %" PRIu64 ", to be replaced with signal for tid %" PRIu64,
Pavel Labathc0765592015-05-06 10:46:34 +00003209 __FUNCTION__,
3210 m_pending_notification_up->triggering_tid,
3211 notification_up->triggering_tid);
3212 }
3213 m_pending_notification_up = std::move(notification_up);
3214
Pavel Labath108c3252015-05-12 09:03:18 +00003215 RequestStopOnAllRunningThreads();
Pavel Labathc0765592015-05-06 10:46:34 +00003216
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003217 SignalIfAllThreadsStopped();
Pavel Labathc0765592015-05-06 10:46:34 +00003218}
3219
3220void
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003221NativeProcessLinux::ThreadWasCreated (lldb::tid_t tid)
Pavel Labathc0765592015-05-06 10:46:34 +00003222{
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003223 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3224
3225 if (log)
3226 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, tid);
3227
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003228 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
3229 lldbassert(thread_sp != nullptr);
Pavel Labathc0765592015-05-06 10:46:34 +00003230
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003231 if (m_pending_notification_up && StateIsRunningState(thread_sp->GetState()))
Pavel Labathc0765592015-05-06 10:46:34 +00003232 {
3233 // We will need to wait for this new thread to stop as well before firing the
3234 // notification.
3235 m_pending_notification_up->wait_for_stop_tids.insert(tid);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003236 thread_sp->RequestStop();
Pavel Labathc0765592015-05-06 10:46:34 +00003237 }
3238}
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003239
Pavel Labath19cbe962015-07-21 13:20:32 +00003240void
3241NativeProcessLinux::SigchldHandler()
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003242{
Pavel Labath19cbe962015-07-21 13:20:32 +00003243 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3244 // Process all pending waitpid notifications.
3245 while (true)
3246 {
3247 int status = -1;
3248 ::pid_t wait_pid = waitpid(-1, &status, __WALL | __WNOTHREAD | WNOHANG);
3249
3250 if (wait_pid == 0)
3251 break; // We are done.
3252
3253 if (wait_pid == -1)
3254 {
3255 if (errno == EINTR)
3256 continue;
3257
3258 Error error(errno, eErrorTypePOSIX);
3259 if (log)
3260 log->Printf("NativeProcessLinux::%s waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG) failed: %s",
3261 __FUNCTION__, error.AsCString());
3262 break;
3263 }
3264
3265 bool exited = false;
3266 int signal = 0;
3267 int exit_status = 0;
3268 const char *status_cstr = nullptr;
3269 if (WIFSTOPPED(status))
3270 {
3271 signal = WSTOPSIG(status);
3272 status_cstr = "STOPPED";
3273 }
3274 else if (WIFEXITED(status))
3275 {
3276 exit_status = WEXITSTATUS(status);
3277 status_cstr = "EXITED";
3278 exited = true;
3279 }
3280 else if (WIFSIGNALED(status))
3281 {
3282 signal = WTERMSIG(status);
3283 status_cstr = "SIGNALED";
3284 if (wait_pid == static_cast<::pid_t>(GetID())) {
3285 exited = true;
3286 exit_status = -1;
3287 }
3288 }
3289 else
3290 status_cstr = "(\?\?\?)";
3291
3292 if (log)
3293 log->Printf("NativeProcessLinux::%s: waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG)"
3294 "=> pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
3295 __FUNCTION__, wait_pid, status, status_cstr, signal, exit_status);
3296
3297 MonitorCallback (wait_pid, exited, signal, exit_status);
3298 }
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003299}
3300
3301// Wrapper for ptrace to catch errors and log calls.
3302// 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 +00003303Error
3304NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, long *result)
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003305{
Pavel Labath4a9babb2015-06-30 17:04:49 +00003306 Error error;
3307 long int ret;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003308
3309 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
3310
3311 PtraceDisplayBytes(req, data, data_size);
3312
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003313 errno = 0;
3314 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Pavel Labath4a9babb2015-06-30 17:04:49 +00003315 ret = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003316 else
Pavel Labath4a9babb2015-06-30 17:04:49 +00003317 ret = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003318
Pavel Labath4a9babb2015-06-30 17:04:49 +00003319 if (ret == -1)
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003320 error.SetErrorToErrno();
3321
Pavel Labath4a9babb2015-06-30 17:04:49 +00003322 if (result)
3323 *result = ret;
3324
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003325 if (log)
Pavel Labath4a9babb2015-06-30 17:04:49 +00003326 log->Printf("ptrace(%d, %" PRIu64 ", %p, %p, %zu)=%lX", req, pid, addr, data, data_size, ret);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003327
3328 PtraceDisplayBytes(req, data, data_size);
3329
3330 if (log && error.GetError() != 0)
3331 {
3332 const char* str;
3333 switch (error.GetError())
3334 {
3335 case ESRCH: str = "ESRCH"; break;
3336 case EINVAL: str = "EINVAL"; break;
3337 case EBUSY: str = "EBUSY"; break;
3338 case EPERM: str = "EPERM"; break;
3339 default: str = error.AsCString();
3340 }
3341 log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
3342 }
3343
Pavel Labath4a9babb2015-06-30 17:04:49 +00003344 return error;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003345}