blob: 679721c073d2bacb10d379fbb4e6a84dd7419ad2 [file] [log] [blame]
Todd Fialaaf245d12014-06-30 21:05:18 +00001//===-- NativeProcessLinux.cpp -------------------------------- -*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Todd Fialaaf245d12014-06-30 21:05:18 +000010#include "NativeProcessLinux.h"
11
12// C Includes
13#include <errno.h>
Todd Fialaaf245d12014-06-30 21:05:18 +000014#include <string.h>
15#include <stdint.h>
16#include <unistd.h>
Todd Fialaaf245d12014-06-30 21:05:18 +000017
18// C++ Includes
19#include <fstream>
Pavel Labathdf7c6992015-06-17 18:38:49 +000020#include <mutex>
Pavel Labathc0765592015-05-06 10:46:34 +000021#include <sstream>
Todd Fialaaf245d12014-06-30 21:05:18 +000022#include <string>
Pavel Labath5b981ab2015-05-29 12:53:54 +000023#include <unordered_map>
Todd Fialaaf245d12014-06-30 21:05:18 +000024
25// Other libraries and framework includes
Tamas Berghammerd8c338d2015-04-15 09:47:02 +000026#include "lldb/Core/EmulateInstruction.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000027#include "lldb/Core/Error.h"
Oleksiy Vyalov6edef202014-11-17 22:16:42 +000028#include "lldb/Core/ModuleSpec.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000029#include "lldb/Core/RegisterValue.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000030#include "lldb/Core/State.h"
31#include "lldb/Host/Host.h"
Zachary Turner39de3112014-09-09 20:54:56 +000032#include "lldb/Host/ThreadLauncher.h"
Pavel Labath2a86b552016-06-14 17:30:52 +000033#include "lldb/Host/common/NativeBreakpoint.h"
34#include "lldb/Host/common/NativeRegisterContext.h"
35#include "lldb/Symbol/ObjectFile.h"
Zachary Turner90aff472015-03-03 23:36:51 +000036#include "lldb/Target/Process.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000037#include "lldb/Target/ProcessLaunchInfo.h"
Pavel Labath5b981ab2015-05-29 12:53:54 +000038#include "lldb/Target/Target.h"
Chaoren Linc16f5dc2015-03-19 23:28:10 +000039#include "lldb/Utility/LLDBAssert.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000040#include "lldb/Utility/PseudoTerminal.h"
Pavel Labathf805e192015-07-07 10:08:41 +000041#include "lldb/Utility/StringExtractor.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000042
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000043#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000044#include "NativeThreadLinux.h"
45#include "ProcFileReader.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000046#include "Procfs.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000047
Tamas Berghammerd8584872015-02-06 10:57:40 +000048// System includes - They have to be included after framework includes because they define some
49// macros which collide with variable names in other modules
50#include <linux/unistd.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000051#include <sys/socket.h>
Vince Harron8b335672015-05-12 01:10:56 +000052
Pavel Labathdf7c6992015-06-17 18:38:49 +000053#include <sys/syscall.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000054#include <sys/types.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000055#include <sys/user.h>
56#include <sys/wait.h>
57
Vince Harron8b335672015-05-12 01:10:56 +000058#include "lldb/Host/linux/Personality.h"
59#include "lldb/Host/linux/Ptrace.h"
Pavel Labathdf7c6992015-06-17 18:38:49 +000060#include "lldb/Host/linux/Uio.h"
Vince Harron8b335672015-05-12 01:10:56 +000061#include "lldb/Host/android/Android.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000062
Todd Fiala0bce1b62014-08-17 00:10:50 +000063#define LLDB_PERSONALITY_GET_CURRENT_SETTINGS 0xffffffff
Todd Fialaaf245d12014-06-30 21:05:18 +000064
65// Support hardware breakpoints in case it has not been defined
66#ifndef TRAP_HWBKPT
67 #define TRAP_HWBKPT 4
68#endif
69
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000070using namespace lldb;
71using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000072using namespace lldb_private::process_linux;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000073using namespace llvm;
74
Todd Fialaaf245d12014-06-30 21:05:18 +000075// Private bits we only need internally.
Pavel Labathdf7c6992015-06-17 18:38:49 +000076
77static bool ProcessVmReadvSupported()
78{
79 static bool is_supported;
80 static std::once_flag flag;
81
82 std::call_once(flag, [] {
83 Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
84
85 uint32_t source = 0x47424742;
86 uint32_t dest = 0;
87
88 struct iovec local, remote;
89 remote.iov_base = &source;
90 local.iov_base = &dest;
91 remote.iov_len = local.iov_len = sizeof source;
92
93 // We shall try if cross-process-memory reads work by attempting to read a value from our own process.
94 ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
95 is_supported = (res == sizeof(source) && source == dest);
96 if (log)
97 {
98 if (is_supported)
99 log->Printf("%s: Detected kernel support for process_vm_readv syscall. Fast memory reads enabled.",
100 __FUNCTION__);
101 else
102 log->Printf("%s: syscall process_vm_readv failed (error: %s). Fast memory reads disabled.",
103 __FUNCTION__, strerror(errno));
104 }
105 });
106
107 return is_supported;
108}
109
Todd Fialaaf245d12014-06-30 21:05:18 +0000110namespace
111{
Pavel Labath2a86b552016-06-14 17:30:52 +0000112Error
113ResolveProcessArchitecture(lldb::pid_t pid, ArchSpec &arch)
114{
115 // Grab process info for the running process.
116 ProcessInstanceInfo process_info;
117 if (!Host::GetProcessInfo(pid, process_info))
118 return Error("failed to get process info");
Todd Fialaaf245d12014-06-30 21:05:18 +0000119
Pavel Labath2a86b552016-06-14 17:30:52 +0000120 // Resolve the executable module.
121 ModuleSpecList module_specs;
122 if (!ObjectFile::GetModuleSpecifications(process_info.GetExecutableFile(), 0, 0, module_specs))
123 return Error("failed to get module specifications");
124 assert(module_specs.GetSize() == 1);
Todd Fialaaf245d12014-06-30 21:05:18 +0000125
Pavel Labath2a86b552016-06-14 17:30:52 +0000126 arch = module_specs.GetModuleSpecRefAtIndex(0).GetArchitecture();
127 if (arch.IsValid())
128 return Error();
129 else
130 return Error("failed to retrieve a valid architecture from the exe module");
131}
Todd Fialaaf245d12014-06-30 21:05:18 +0000132
133 void
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000134 DisplayBytes (StreamString &s, void *bytes, uint32_t count)
Todd Fialaaf245d12014-06-30 21:05:18 +0000135 {
136 uint8_t *ptr = (uint8_t *)bytes;
137 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
138 for(uint32_t i=0; i<loop_count; i++)
139 {
140 s.Printf ("[%x]", *ptr);
141 ptr++;
142 }
143 }
144
145 void
146 PtraceDisplayBytes(int &req, void *data, size_t data_size)
147 {
148 StreamString buf;
149 Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
150 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
151
152 if (verbose_log)
153 {
154 switch(req)
155 {
156 case PTRACE_POKETEXT:
157 {
158 DisplayBytes(buf, &data, 8);
159 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
160 break;
161 }
162 case PTRACE_POKEDATA:
163 {
164 DisplayBytes(buf, &data, 8);
165 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
166 break;
167 }
168 case PTRACE_POKEUSER:
169 {
170 DisplayBytes(buf, &data, 8);
171 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
172 break;
173 }
174 case PTRACE_SETREGS:
175 {
176 DisplayBytes(buf, data, data_size);
177 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
178 break;
179 }
180 case PTRACE_SETFPREGS:
181 {
182 DisplayBytes(buf, data, data_size);
183 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
184 break;
185 }
186 case PTRACE_SETSIGINFO:
187 {
188 DisplayBytes(buf, data, sizeof(siginfo_t));
189 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
190 break;
191 }
192 case PTRACE_SETREGSET:
193 {
194 // Extract iov_base from data, which is a pointer to the struct IOVEC
195 DisplayBytes(buf, *(void **)data, data_size);
196 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
197 break;
198 }
199 default:
200 {
201 }
202 }
203 }
204 }
205
Pavel Labath19cbe962015-07-21 13:20:32 +0000206 static constexpr unsigned k_ptrace_word_size = sizeof(void*);
207 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 +0000208} // end of anonymous namespace
209
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000210// Simple helper function to ensure flags are enabled on the given file
211// descriptor.
212static Error
213EnsureFDFlags(int fd, int flags)
214{
215 Error error;
216
217 int status = fcntl(fd, F_GETFL);
218 if (status == -1)
219 {
220 error.SetErrorToErrno();
221 return error;
222 }
223
224 if (fcntl(fd, F_SETFL, status | flags) == -1)
225 {
226 error.SetErrorToErrno();
227 return error;
228 }
229
230 return error;
231}
232
Pavel Labath2a86b552016-06-14 17:30:52 +0000233NativeProcessLinux::LaunchArgs::LaunchArgs(char const **argv, char const **envp, const FileSpec &stdin_file_spec,
234 const FileSpec &stdout_file_spec, const FileSpec &stderr_file_spec,
235 const FileSpec &working_dir, const ProcessLaunchInfo &launch_info)
236 : m_argv(argv),
Todd Fialaaf245d12014-06-30 21:05:18 +0000237 m_envp(envp),
Chaoren Lind3173f32015-05-29 19:52:29 +0000238 m_stdin_file_spec(stdin_file_spec),
239 m_stdout_file_spec(stdout_file_spec),
240 m_stderr_file_spec(stderr_file_spec),
Todd Fiala0bce1b62014-08-17 00:10:50 +0000241 m_working_dir(working_dir),
242 m_launch_info(launch_info)
243{
244}
Todd Fialaaf245d12014-06-30 21:05:18 +0000245
246NativeProcessLinux::LaunchArgs::~LaunchArgs()
247{ }
248
Todd Fialaaf245d12014-06-30 21:05:18 +0000249// -----------------------------------------------------------------------------
250// Public Static Methods
251// -----------------------------------------------------------------------------
252
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000253Error
Pavel Labathd5b310f2015-07-09 11:51:11 +0000254NativeProcessProtocol::Launch (
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000255 ProcessLaunchInfo &launch_info,
256 NativeProcessProtocol::NativeDelegate &native_delegate,
Pavel Labath19cbe962015-07-21 13:20:32 +0000257 MainLoop &mainloop,
Todd Fialaaf245d12014-06-30 21:05:18 +0000258 NativeProcessProtocolSP &native_process_sp)
259{
260 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
261
Pavel Labath2a86b552016-06-14 17:30:52 +0000262 Error error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000263
264 // Verify the working directory is valid if one was specified.
Chaoren Lind3173f32015-05-29 19:52:29 +0000265 FileSpec working_dir{launch_info.GetWorkingDirectory()};
266 if (working_dir &&
267 (!working_dir.ResolvePath() ||
268 working_dir.GetFileType() != FileSpec::eFileTypeDirectory))
Todd Fialaaf245d12014-06-30 21:05:18 +0000269 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000270 error.SetErrorStringWithFormat ("No such file or directory: %s",
271 working_dir.GetCString());
272 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000273 }
274
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000275 const FileAction *file_action;
Todd Fialaaf245d12014-06-30 21:05:18 +0000276
Chaoren Lind3173f32015-05-29 19:52:29 +0000277 // Default of empty will mean to use existing open file descriptors.
278 FileSpec stdin_file_spec{};
279 FileSpec stdout_file_spec{};
280 FileSpec stderr_file_spec{};
Todd Fialaaf245d12014-06-30 21:05:18 +0000281
282 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +0000283 if (file_action)
Chaoren Lind3173f32015-05-29 19:52:29 +0000284 stdin_file_spec = file_action->GetFileSpec();
Todd Fialaaf245d12014-06-30 21:05:18 +0000285
286 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +0000287 if (file_action)
Chaoren Lind3173f32015-05-29 19:52:29 +0000288 stdout_file_spec = file_action->GetFileSpec();
Todd Fialaaf245d12014-06-30 21:05:18 +0000289
290 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +0000291 if (file_action)
Chaoren Lind3173f32015-05-29 19:52:29 +0000292 stderr_file_spec = file_action->GetFileSpec();
Todd Fiala75f47c32014-10-11 21:42:09 +0000293
294 if (log)
295 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000296 if (stdin_file_spec)
297 log->Printf ("NativeProcessLinux::%s setting STDIN to '%s'",
298 __FUNCTION__, stdin_file_spec.GetCString());
Todd Fiala75f47c32014-10-11 21:42:09 +0000299 else
300 log->Printf ("NativeProcessLinux::%s leaving STDIN as is", __FUNCTION__);
301
Chaoren Lind3173f32015-05-29 19:52:29 +0000302 if (stdout_file_spec)
303 log->Printf ("NativeProcessLinux::%s setting STDOUT to '%s'",
304 __FUNCTION__, stdout_file_spec.GetCString());
Todd Fiala75f47c32014-10-11 21:42:09 +0000305 else
306 log->Printf ("NativeProcessLinux::%s leaving STDOUT as is", __FUNCTION__);
307
Chaoren Lind3173f32015-05-29 19:52:29 +0000308 if (stderr_file_spec)
309 log->Printf ("NativeProcessLinux::%s setting STDERR to '%s'",
310 __FUNCTION__, stderr_file_spec.GetCString());
Todd Fiala75f47c32014-10-11 21:42:09 +0000311 else
312 log->Printf ("NativeProcessLinux::%s leaving STDERR as is", __FUNCTION__);
313 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000314
315 // Create the NativeProcessLinux in launch mode.
316 native_process_sp.reset (new NativeProcessLinux ());
317
318 if (log)
319 {
320 int i = 0;
321 for (const char **args = launch_info.GetArguments ().GetConstArgumentVector (); *args; ++args, ++i)
322 {
323 log->Printf ("NativeProcessLinux::%s arg %d: \"%s\"", __FUNCTION__, i, *args ? *args : "nullptr");
324 ++i;
325 }
326 }
327
328 if (!native_process_sp->RegisterNativeDelegate (native_delegate))
329 {
330 native_process_sp.reset ();
331 error.SetErrorStringWithFormat ("failed to register the native delegate");
332 return error;
333 }
334
Tamas Berghammercb84eeb2015-03-17 15:05:31 +0000335 std::static_pointer_cast<NativeProcessLinux> (native_process_sp)->LaunchInferior (
Pavel Labath19cbe962015-07-21 13:20:32 +0000336 mainloop,
Todd Fialaaf245d12014-06-30 21:05:18 +0000337 launch_info.GetArguments ().GetConstArgumentVector (),
338 launch_info.GetEnvironmentEntries ().GetConstArgumentVector (),
Chaoren Lind3173f32015-05-29 19:52:29 +0000339 stdin_file_spec,
340 stdout_file_spec,
341 stderr_file_spec,
Todd Fialaaf245d12014-06-30 21:05:18 +0000342 working_dir,
Todd Fiala0bce1b62014-08-17 00:10:50 +0000343 launch_info,
Todd Fialaaf245d12014-06-30 21:05:18 +0000344 error);
345
346 if (error.Fail ())
347 {
348 native_process_sp.reset ();
349 if (log)
350 log->Printf ("NativeProcessLinux::%s failed to launch process: %s", __FUNCTION__, error.AsCString ());
351 return error;
352 }
353
354 launch_info.SetProcessID (native_process_sp->GetID ());
355
356 return error;
357}
358
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000359Error
Pavel Labathd5b310f2015-07-09 11:51:11 +0000360NativeProcessProtocol::Attach (
Todd Fialaaf245d12014-06-30 21:05:18 +0000361 lldb::pid_t pid,
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000362 NativeProcessProtocol::NativeDelegate &native_delegate,
Pavel Labath19cbe962015-07-21 13:20:32 +0000363 MainLoop &mainloop,
Todd Fialaaf245d12014-06-30 21:05:18 +0000364 NativeProcessProtocolSP &native_process_sp)
365{
366 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
367 if (log && log->GetMask ().Test (POSIX_LOG_VERBOSE))
368 log->Printf ("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
369
Todd Fialaaf245d12014-06-30 21:05:18 +0000370 // Retrieve the architecture for the running process.
371 ArchSpec process_arch;
Pavel Labath2a86b552016-06-14 17:30:52 +0000372 Error error = ResolveProcessArchitecture(pid, process_arch);
Todd Fialaaf245d12014-06-30 21:05:18 +0000373 if (!error.Success ())
374 return error;
375
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +0000376 std::shared_ptr<NativeProcessLinux> native_process_linux_sp (new NativeProcessLinux ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000377
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +0000378 if (!native_process_linux_sp->RegisterNativeDelegate (native_delegate))
Todd Fialaaf245d12014-06-30 21:05:18 +0000379 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000380 error.SetErrorStringWithFormat ("failed to register the native delegate");
381 return error;
382 }
383
Pavel Labath19cbe962015-07-21 13:20:32 +0000384 native_process_linux_sp->AttachToInferior (mainloop, pid, error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000385 if (!error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +0000386 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000387
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +0000388 native_process_sp = native_process_linux_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +0000389 return error;
390}
391
392// -----------------------------------------------------------------------------
393// Public Instance Methods
394// -----------------------------------------------------------------------------
395
396NativeProcessLinux::NativeProcessLinux () :
397 NativeProcessProtocol (LLDB_INVALID_PROCESS_ID),
398 m_arch (),
Todd Fialaaf245d12014-06-30 21:05:18 +0000399 m_supports_mem_region (eLazyBoolCalculate),
400 m_mem_region_cache (),
Pavel Labath0e1d7292015-08-20 09:06:12 +0000401 m_pending_notification_tid(LLDB_INVALID_THREAD_ID)
Todd Fialaaf245d12014-06-30 21:05:18 +0000402{
403}
404
Todd Fialaaf245d12014-06-30 21:05:18 +0000405void
406NativeProcessLinux::LaunchInferior (
Pavel Labath19cbe962015-07-21 13:20:32 +0000407 MainLoop &mainloop,
Todd Fialaaf245d12014-06-30 21:05:18 +0000408 const char *argv[],
409 const char *envp[],
Chaoren Lind3173f32015-05-29 19:52:29 +0000410 const FileSpec &stdin_file_spec,
411 const FileSpec &stdout_file_spec,
412 const FileSpec &stderr_file_spec,
413 const FileSpec &working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000414 const ProcessLaunchInfo &launch_info,
415 Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000416{
Pavel Labath19cbe962015-07-21 13:20:32 +0000417 m_sigchld_handle = mainloop.RegisterSignal(SIGCHLD,
418 [this] (MainLoopBase &) { SigchldHandler(); }, error);
419 if (! m_sigchld_handle)
420 return;
421
Chaoren Linfa03ad22015-02-03 01:50:42 +0000422 SetState (eStateLaunching);
Todd Fialaaf245d12014-06-30 21:05:18 +0000423
424 std::unique_ptr<LaunchArgs> args(
Pavel Labath2a86b552016-06-14 17:30:52 +0000425 new LaunchArgs(argv, envp, stdin_file_spec, stdout_file_spec, stderr_file_spec, working_dir, launch_info));
Todd Fialaaf245d12014-06-30 21:05:18 +0000426
Pavel Labath19cbe962015-07-21 13:20:32 +0000427 Launch(args.get(), error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000428}
429
430void
Pavel Labath19cbe962015-07-21 13:20:32 +0000431NativeProcessLinux::AttachToInferior (MainLoop &mainloop, lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000432{
433 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
434 if (log)
435 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
436
Pavel Labath19cbe962015-07-21 13:20:32 +0000437 m_sigchld_handle = mainloop.RegisterSignal(SIGCHLD,
438 [this] (MainLoopBase &) { SigchldHandler(); }, error);
439 if (! m_sigchld_handle)
440 return;
441
Pavel Labath2a86b552016-06-14 17:30:52 +0000442 error = ResolveProcessArchitecture(pid, m_arch);
Todd Fialaaf245d12014-06-30 21:05:18 +0000443 if (!error.Success())
444 return;
445
446 // Set the architecture to the exe architecture.
Todd Fialaaf245d12014-06-30 21:05:18 +0000447 if (log)
448 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
449
450 m_pid = pid;
451 SetState(eStateAttaching);
452
Pavel Labath19cbe962015-07-21 13:20:32 +0000453 Attach(pid, error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000454}
455
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000456::pid_t
457NativeProcessLinux::Launch(LaunchArgs *args, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000458{
Todd Fiala0bce1b62014-08-17 00:10:50 +0000459 assert (args && "null args");
Todd Fialaaf245d12014-06-30 21:05:18 +0000460
461 const char **argv = args->m_argv;
462 const char **envp = args->m_envp;
Chaoren Lind3173f32015-05-29 19:52:29 +0000463 const FileSpec working_dir = args->m_working_dir;
Todd Fialaaf245d12014-06-30 21:05:18 +0000464
465 lldb_utility::PseudoTerminal terminal;
466 const size_t err_len = 1024;
467 char err_str[err_len];
468 lldb::pid_t pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000469
470 // Propagate the environment if one is not supplied.
471 if (envp == NULL || envp[0] == NULL)
472 envp = const_cast<const char **>(environ);
473
474 if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
475 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000476 error.SetErrorToGenericError();
477 error.SetErrorStringWithFormat("Process fork failed: %s", err_str);
478 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000479 }
480
481 // Recognized child exit status codes.
482 enum {
483 ePtraceFailed = 1,
484 eDupStdinFailed,
485 eDupStdoutFailed,
486 eDupStderrFailed,
487 eChdirFailed,
488 eExecFailed,
Pavel Labath78856472015-08-19 13:47:57 +0000489 eSetGidFailed,
490 eSetSigMaskFailed
Todd Fialaaf245d12014-06-30 21:05:18 +0000491 };
492
493 // Child process.
494 if (pid == 0)
495 {
Pavel Labathd2c4c9b2015-08-18 08:23:35 +0000496 // First, make sure we disable all logging. If we are logging to stdout, our logs can be
497 // mistaken for inferior output.
498 Log::DisableAllLogChannels(nullptr);
Todd Fiala75f47c32014-10-11 21:42:09 +0000499 // FIXME consider opening a pipe between parent/child and have this forked child
Pavel Labathd2c4c9b2015-08-18 08:23:35 +0000500 // send log info to parent re: launch status.
Todd Fialaaf245d12014-06-30 21:05:18 +0000501
Todd Fiala75f47c32014-10-11 21:42:09 +0000502 // Start tracing this child that is about to exec.
Pavel Labath4a9babb2015-06-30 17:04:49 +0000503 error = PtraceWrapper(PTRACE_TRACEME, 0);
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000504 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000505 exit(ePtraceFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +0000506
Pavel Labath493c3a12015-02-04 10:36:57 +0000507 // terminal has already dupped the tty descriptors to stdin/out/err.
508 // This closes original fd from which they were copied (and avoids
509 // leaking descriptors to the debugged process.
510 terminal.CloseSlaveFileDescriptor();
511
Todd Fialaaf245d12014-06-30 21:05:18 +0000512 // Do not inherit setgid powers.
Todd Fialaaf245d12014-06-30 21:05:18 +0000513 if (setgid(getgid()) != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +0000514 exit(eSetGidFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +0000515
516 // Attempt to have our own process group.
Todd Fialaaf245d12014-06-30 21:05:18 +0000517 if (setpgid(0, 0) != 0)
518 {
Todd Fiala75f47c32014-10-11 21:42:09 +0000519 // FIXME log that this failed. This is common.
Todd Fialaaf245d12014-06-30 21:05:18 +0000520 // Don't allow this to prevent an inferior exec.
521 }
522
523 // Dup file descriptors if needed.
Chaoren Lind3173f32015-05-29 19:52:29 +0000524 if (args->m_stdin_file_spec)
525 if (!DupDescriptor(args->m_stdin_file_spec, STDIN_FILENO, O_RDONLY))
Todd Fialaaf245d12014-06-30 21:05:18 +0000526 exit(eDupStdinFailed);
527
Chaoren Lind3173f32015-05-29 19:52:29 +0000528 if (args->m_stdout_file_spec)
529 if (!DupDescriptor(args->m_stdout_file_spec, STDOUT_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +0000530 exit(eDupStdoutFailed);
531
Chaoren Lind3173f32015-05-29 19:52:29 +0000532 if (args->m_stderr_file_spec)
533 if (!DupDescriptor(args->m_stderr_file_spec, STDERR_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +0000534 exit(eDupStderrFailed);
535
Chaoren Lin9cf4f2c2015-04-23 18:28:04 +0000536 // Close everything besides stdin, stdout, and stderr that has no file
537 // action to avoid leaking
538 for (int fd = 3; fd < sysconf(_SC_OPEN_MAX); ++fd)
539 if (!args->m_launch_info.GetFileActionForFD(fd))
540 close(fd);
541
Todd Fialaaf245d12014-06-30 21:05:18 +0000542 // Change working directory
Chaoren Lind3173f32015-05-29 19:52:29 +0000543 if (working_dir && 0 != ::chdir(working_dir.GetCString()))
Todd Fialaaf245d12014-06-30 21:05:18 +0000544 exit(eChdirFailed);
545
Todd Fiala0bce1b62014-08-17 00:10:50 +0000546 // Disable ASLR if requested.
547 if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR))
548 {
549 const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
550 if (old_personality == -1)
551 {
Todd Fiala75f47c32014-10-11 21:42:09 +0000552 // Can't retrieve Linux personality. Cannot disable ASLR.
Todd Fiala0bce1b62014-08-17 00:10:50 +0000553 }
554 else
555 {
556 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality);
557 if (new_personality == -1)
558 {
Todd Fiala75f47c32014-10-11 21:42:09 +0000559 // Disabling ASLR failed.
Todd Fiala0bce1b62014-08-17 00:10:50 +0000560 }
561 else
562 {
Todd Fiala75f47c32014-10-11 21:42:09 +0000563 // Disabling ASLR succeeded.
Todd Fiala0bce1b62014-08-17 00:10:50 +0000564 }
565 }
566 }
567
Pavel Labath78856472015-08-19 13:47:57 +0000568 // Clear the signal mask to prevent the child from being affected by
569 // any masking done by the parent.
570 sigset_t set;
571 if (sigemptyset(&set) != 0 || pthread_sigmask(SIG_SETMASK, &set, nullptr) != 0)
572 exit(eSetSigMaskFailed);
573
Todd Fiala75f47c32014-10-11 21:42:09 +0000574 // Execute. We should never return...
Todd Fialaaf245d12014-06-30 21:05:18 +0000575 execve(argv[0],
576 const_cast<char *const *>(argv),
577 const_cast<char *const *>(envp));
Todd Fiala75f47c32014-10-11 21:42:09 +0000578
579 // ...unless exec fails. In which case we definitely need to end the child here.
Todd Fialaaf245d12014-06-30 21:05:18 +0000580 exit(eExecFailed);
581 }
582
Todd Fiala75f47c32014-10-11 21:42:09 +0000583 //
584 // This is the parent code here.
585 //
586 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
587
Todd Fialaaf245d12014-06-30 21:05:18 +0000588 // Wait for the child process to trap on its call to execve.
589 ::pid_t wpid;
590 int status;
591 if ((wpid = waitpid(pid, &status, 0)) < 0)
592 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000593 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +0000594 if (log)
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000595 log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s",
596 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000597
598 // Mark the inferior as invalid.
599 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000600 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000601
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000602 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000603 }
604 else if (WIFEXITED(status))
605 {
606 // open, dup or execve likely failed for some reason.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000607 error.SetErrorToGenericError();
Todd Fialaaf245d12014-06-30 21:05:18 +0000608 switch (WEXITSTATUS(status))
609 {
610 case ePtraceFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000611 error.SetErrorString("Child ptrace failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000612 break;
613 case eDupStdinFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000614 error.SetErrorString("Child open stdin failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000615 break;
616 case eDupStdoutFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000617 error.SetErrorString("Child open stdout failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000618 break;
619 case eDupStderrFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000620 error.SetErrorString("Child open stderr failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000621 break;
622 case eChdirFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000623 error.SetErrorString("Child failed to set working directory.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000624 break;
625 case eExecFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000626 error.SetErrorString("Child exec failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000627 break;
628 case eSetGidFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000629 error.SetErrorString("Child setgid failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000630 break;
Pavel Labath78856472015-08-19 13:47:57 +0000631 case eSetSigMaskFailed:
632 error.SetErrorString("Child failed to set signal mask.");
633 break;
Todd Fialaaf245d12014-06-30 21:05:18 +0000634 default:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000635 error.SetErrorString("Child returned unknown exit status.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000636 break;
637 }
638
639 if (log)
640 {
641 log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
642 __FUNCTION__,
643 WEXITSTATUS(status));
644 }
645
646 // Mark the inferior as invalid.
647 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000648 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000649
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000650 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000651 }
Todd Fiala202ecd22014-07-10 04:39:13 +0000652 assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
Todd Fialaaf245d12014-06-30 21:05:18 +0000653 "Could not sync with inferior process.");
654
655 if (log)
656 log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
657
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000658 error = SetDefaultPtraceOpts(pid);
659 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000660 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000661 if (log)
662 log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000663 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000664
665 // Mark the inferior as invalid.
666 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000667 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000668
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000669 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000670 }
671
672 // Release the master terminal descriptor and pass it off to the
673 // NativeProcessLinux instance. Similarly stash the inferior pid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000674 m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
675 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000676
677 // Set the terminal fd to be in non blocking mode (it simplifies the
678 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
679 // descriptor to read from).
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000680 error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
681 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000682 {
683 if (log)
684 log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000685 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000686
687 // Mark the inferior as invalid.
688 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000689 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000690
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000691 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000692 }
693
694 if (log)
695 log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
696
Pavel Labath2a86b552016-06-14 17:30:52 +0000697 ResolveProcessArchitecture(m_pid, m_arch);
Pavel Labathf9077782015-08-21 09:13:53 +0000698 NativeThreadLinuxSP thread_sp = AddThread(pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000699 assert (thread_sp && "AddThread() returned a nullptr thread");
Pavel Labathf9077782015-08-21 09:13:53 +0000700 thread_sp->SetStoppedBySignal(SIGSTOP);
701 ThreadWasCreated(*thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +0000702
703 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000704 SetCurrentThreadID (thread_sp->GetID ());
705 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +0000706
Todd Fialaaf245d12014-06-30 21:05:18 +0000707 if (log)
708 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000709 if (error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +0000710 {
711 log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
712 }
713 else
714 {
715 log->Printf ("NativeProcessLinux::%s inferior launching failed: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000716 __FUNCTION__, error.AsCString ());
717 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000718 }
719 }
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000720 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000721}
722
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000723::pid_t
724NativeProcessLinux::Attach(lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000725{
Todd Fialaaf245d12014-06-30 21:05:18 +0000726 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
727
728 // Use a map to keep track of the threads which we have attached/need to attach.
729 Host::TidMap tids_to_attach;
730 if (pid <= 1)
731 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000732 error.SetErrorToGenericError();
733 error.SetErrorString("Attaching to process 1 is not allowed.");
734 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000735 }
736
737 while (Host::FindProcessThreads(pid, tids_to_attach))
738 {
739 for (Host::TidMap::iterator it = tids_to_attach.begin();
740 it != tids_to_attach.end();)
741 {
742 if (it->second == false)
743 {
744 lldb::tid_t tid = it->first;
745
746 // Attach to the requested process.
747 // An attach will cause the thread to stop with a SIGSTOP.
Pavel Labath4a9babb2015-06-30 17:04:49 +0000748 error = PtraceWrapper(PTRACE_ATTACH, tid);
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000749 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000750 {
751 // No such thread. The thread may have exited.
752 // More error handling may be needed.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000753 if (error.GetError() == ESRCH)
Todd Fialaaf245d12014-06-30 21:05:18 +0000754 {
755 it = tids_to_attach.erase(it);
756 continue;
757 }
758 else
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000759 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000760 }
761
762 int status;
763 // Need to use __WALL otherwise we receive an error with errno=ECHLD
764 // At this point we should have a thread stopped if waitpid succeeds.
765 if ((status = waitpid(tid, NULL, __WALL)) < 0)
766 {
767 // No such thread. The thread may have exited.
768 // More error handling may be needed.
769 if (errno == ESRCH)
770 {
771 it = tids_to_attach.erase(it);
772 continue;
773 }
774 else
775 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000776 error.SetErrorToErrno();
777 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000778 }
779 }
780
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000781 error = SetDefaultPtraceOpts(tid);
782 if (error.Fail())
783 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000784
785 if (log)
786 log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
787
788 it->second = true;
789
790 // Create the thread, mark it as stopped.
Pavel Labathf9077782015-08-21 09:13:53 +0000791 NativeThreadLinuxSP thread_sp (AddThread(static_cast<lldb::tid_t>(tid)));
Todd Fialaaf245d12014-06-30 21:05:18 +0000792 assert (thread_sp && "AddThread() returned a nullptr");
Chaoren Linfa03ad22015-02-03 01:50:42 +0000793
794 // This will notify this is a new thread and tell the system it is stopped.
Pavel Labathf9077782015-08-21 09:13:53 +0000795 thread_sp->SetStoppedBySignal(SIGSTOP);
796 ThreadWasCreated(*thread_sp);
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000797 SetCurrentThreadID (thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000798 }
799
800 // move the loop forward
801 ++it;
802 }
803 }
804
805 if (tids_to_attach.size() > 0)
806 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000807 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000808 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000809 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +0000810 }
811 else
812 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000813 error.SetErrorToGenericError();
814 error.SetErrorString("No such process.");
815 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000816 }
817
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000818 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000819}
820
Chaoren Lin97ccc292015-02-03 01:51:12 +0000821Error
Todd Fialaaf245d12014-06-30 21:05:18 +0000822NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
823{
824 long ptrace_opts = 0;
825
826 // Have the child raise an event on exit. This is used to keep the child in
827 // limbo until it is destroyed.
828 ptrace_opts |= PTRACE_O_TRACEEXIT;
829
830 // Have the tracer trace threads which spawn in the inferior process.
831 // TODO: if we want to support tracing the inferiors' child, add the
832 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
833 ptrace_opts |= PTRACE_O_TRACECLONE;
834
835 // Have the tracer notify us before execve returns
836 // (needed to disable legacy SIGTRAP generation)
837 ptrace_opts |= PTRACE_O_TRACEEXEC;
838
Pavel Labath4a9babb2015-06-30 17:04:49 +0000839 return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts);
Todd Fialaaf245d12014-06-30 21:05:18 +0000840}
841
842static ExitType convert_pid_status_to_exit_type (int status)
843{
844 if (WIFEXITED (status))
845 return ExitType::eExitTypeExit;
846 else if (WIFSIGNALED (status))
847 return ExitType::eExitTypeSignal;
848 else if (WIFSTOPPED (status))
849 return ExitType::eExitTypeStop;
850 else
851 {
852 // We don't know what this is.
853 return ExitType::eExitTypeInvalid;
854 }
855}
856
857static int convert_pid_status_to_return_code (int status)
858{
859 if (WIFEXITED (status))
860 return WEXITSTATUS (status);
861 else if (WIFSIGNALED (status))
862 return WTERMSIG (status);
863 else if (WIFSTOPPED (status))
864 return WSTOPSIG (status);
865 else
866 {
867 // We don't know what this is.
868 return ExitType::eExitTypeInvalid;
869 }
870}
871
Pavel Labath1107b5a2015-04-17 14:07:49 +0000872// Handles all waitpid events from the inferior process.
873void
874NativeProcessLinux::MonitorCallback(lldb::pid_t pid,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000875 bool exited,
876 int signal,
877 int status)
Todd Fialaaf245d12014-06-30 21:05:18 +0000878{
879 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
880
Todd Fialaaf245d12014-06-30 21:05:18 +0000881 // Certain activities differ based on whether the pid is the tid of the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000882 const bool is_main_thread = (pid == GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000883
884 // Handle when the thread exits.
885 if (exited)
886 {
887 if (log)
Chaoren Lin86fd8e42015-02-03 01:51:15 +0000888 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 +0000889
890 // This is a thread that exited. Ensure we're not tracking it anymore.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000891 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000892
893 if (is_main_thread)
894 {
895 // We only set the exit status and notify the delegate if we haven't already set the process
896 // state to an exited state. We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
897 // for the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000898 const bool already_notified = (GetState() == StateType::eStateExited) || (GetState () == StateType::eStateCrashed);
Todd Fialaaf245d12014-06-30 21:05:18 +0000899 if (!already_notified)
900 {
901 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +0000902 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 +0000903 // The main thread exited. We're done monitoring. Report to delegate.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000904 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +0000905
906 // Notify delegate that our process has exited.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000907 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +0000908 }
909 else
910 {
911 if (log)
912 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
913 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000914 }
915 else
916 {
917 // Do we want to report to the delegate in this case? I think not. If this was an orderly
918 // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
919 // and we would have done an all-stop then.
920 if (log)
921 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 +0000922 }
Pavel Labath1107b5a2015-04-17 14:07:49 +0000923 return;
Todd Fialaaf245d12014-06-30 21:05:18 +0000924 }
925
Todd Fialaaf245d12014-06-30 21:05:18 +0000926 siginfo_t info;
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000927 const auto info_err = GetSignalInfo(pid, &info);
928 auto thread_sp = GetThreadByID(pid);
929
930 if (! thread_sp)
931 {
932 // Normally, the only situation when we cannot find the thread is if we have just
933 // received a new thread notification. This is indicated by GetSignalInfo() returning
934 // si_code == SI_USER and si_pid == 0
935 if (log)
936 log->Printf("NativeProcessLinux::%s received notification about an unknown tid %" PRIu64 ".", __FUNCTION__, pid);
937
938 if (info_err.Fail())
939 {
940 if (log)
941 log->Printf("NativeProcessLinux::%s (tid %" PRIu64 ") GetSignalInfo failed (%s). Ingoring this notification.", __FUNCTION__, pid, info_err.AsCString());
942 return;
943 }
944
945 if (log && (info.si_code != SI_USER || info.si_pid != 0))
946 log->Printf("NativeProcessLinux::%s (tid %" PRIu64 ") unexpected signal info (si_code: %d, si_pid: %d). Treating as a new thread notification anyway.", __FUNCTION__, pid, info.si_code, info.si_pid);
947
948 auto thread_sp = AddThread(pid);
949 // Resume the newly created thread.
950 ResumeThread(*thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
951 ThreadWasCreated(*thread_sp);
952 return;
953 }
954
955 // Get details on the signal raised.
956 if (info_err.Success())
Chaoren Linfa03ad22015-02-03 01:50:42 +0000957 {
958 // We have retrieved the signal info. Dispatch appropriately.
959 if (info.si_signo == SIGTRAP)
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000960 MonitorSIGTRAP(info, *thread_sp);
Chaoren Linfa03ad22015-02-03 01:50:42 +0000961 else
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000962 MonitorSignal(info, *thread_sp, exited);
Chaoren Linfa03ad22015-02-03 01:50:42 +0000963 }
964 else
Todd Fialaaf245d12014-06-30 21:05:18 +0000965 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000966 if (info_err.GetError() == EINVAL)
Todd Fialaaf245d12014-06-30 21:05:18 +0000967 {
Chaoren Linfa03ad22015-02-03 01:50:42 +0000968 // This is a group stop reception for this tid.
Pavel Labath39036ac2015-05-21 08:32:18 +0000969 // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the
970 // tracee, triggering the group-stop mechanism. Normally receiving these would stop
971 // the process, pending a SIGCONT. Simulating this state in a debugger is hard and is
972 // generally not needed (one use case is debugging background task being managed by a
973 // shell). For general use, it is sufficient to stop the process in a signal-delivery
974 // stop which happens before the group stop. This done by MonitorSignal and works
975 // correctly for all signals.
Chaoren Linfa03ad22015-02-03 01:50:42 +0000976 if (log)
Pavel Labath39036ac2015-05-21 08:32:18 +0000977 log->Printf("NativeProcessLinux::%s received a group stop for pid %" PRIu64 " tid %" PRIu64 ". Transparent handling of group stops not supported, resuming the thread.", __FUNCTION__, GetID (), pid);
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000978 ResumeThread(*thread_sp, thread_sp->GetState(), LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +0000979 }
980 else
981 {
982 // ptrace(GETSIGINFO) failed (but not due to group-stop).
983
984 // A return value of ESRCH means the thread/process is no longer on the system,
985 // so it was killed somehow outside of our control. Either way, we can't do anything
986 // with it anymore.
987
Todd Fialaaf245d12014-06-30 21:05:18 +0000988 // Stop tracking the metadata for the thread since it's entirely off the system now.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000989 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000990
991 if (log)
992 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
Pavel Labathb9cc0c72015-08-24 09:22:04 +0000993 __FUNCTION__, info_err.AsCString(), pid, signal, status, info_err.GetError() == ESRCH ? "thread/process killed" : "unknown reason", is_main_thread ? "is main thread" : "is not main thread", thread_found ? "thread metadata removed" : "thread metadata not found");
Todd Fialaaf245d12014-06-30 21:05:18 +0000994
995 if (is_main_thread)
996 {
997 // Notify the delegate - our process is not available but appears to have been killed outside
998 // our control. Is eStateExited the right exit state in this case?
Pavel Labath1107b5a2015-04-17 14:07:49 +0000999 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
1000 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001001 }
1002 else
1003 {
1004 // This thread was pulled out from underneath us. Anything to do here? Do we want to do an all stop?
1005 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +00001006 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 +00001007 }
1008 }
1009 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001010}
1011
1012void
Pavel Labath426bdf82015-04-28 07:51:52 +00001013NativeProcessLinux::WaitForNewThread(::pid_t tid)
1014{
1015 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1016
Pavel Labathf9077782015-08-21 09:13:53 +00001017 NativeThreadLinuxSP new_thread_sp = GetThreadByID(tid);
Pavel Labath426bdf82015-04-28 07:51:52 +00001018
1019 if (new_thread_sp)
1020 {
1021 // We are already tracking the thread - we got the event on the new thread (see
1022 // MonitorSignal) before this one. We are done.
1023 return;
1024 }
1025
1026 // The thread is not tracked yet, let's wait for it to appear.
1027 int status = -1;
1028 ::pid_t wait_pid;
1029 do
1030 {
1031 if (log)
1032 log->Printf ("NativeProcessLinux::%s() received thread creation event for tid %" PRIu32 ". tid not tracked yet, waiting for thread to appear...", __FUNCTION__, tid);
1033 wait_pid = waitpid(tid, &status, __WALL);
1034 }
1035 while (wait_pid == -1 && errno == EINTR);
1036 // Since we are waiting on a specific tid, this must be the creation event. But let's do
1037 // some checks just in case.
1038 if (wait_pid != tid) {
1039 if (log)
1040 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime", __FUNCTION__, tid);
1041 // The only way I know of this could happen is if the whole process was
1042 // SIGKILLed in the mean time. In any case, we can't do anything about that now.
1043 return;
1044 }
1045 if (WIFEXITED(status))
1046 {
1047 if (log)
1048 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " returned an 'exited' event. Not tracking the thread.", __FUNCTION__, tid);
1049 // Also a very improbable event.
1050 return;
1051 }
1052
1053 siginfo_t info;
1054 Error error = GetSignalInfo(tid, &info);
1055 if (error.Fail())
1056 {
1057 if (log)
1058 log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime.", __FUNCTION__, tid);
1059 return;
1060 }
1061
1062 if (((info.si_pid != 0) || (info.si_code != SI_USER)) && log)
1063 {
1064 // We should be getting a thread creation signal here, but we received something
1065 // else. There isn't much we can do about it now, so we will just log that. Since the
1066 // thread is alive and we are receiving events from it, we shall pretend that it was
1067 // created properly.
1068 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);
1069 }
1070
1071 if (log)
1072 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 ": tracking new thread tid %" PRIu32,
1073 __FUNCTION__, GetID (), tid);
1074
Pavel Labathf9077782015-08-21 09:13:53 +00001075 new_thread_sp = AddThread(tid);
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001076 ResumeThread(*new_thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
Pavel Labathf9077782015-08-21 09:13:53 +00001077 ThreadWasCreated(*new_thread_sp);
Pavel Labath426bdf82015-04-28 07:51:52 +00001078}
1079
1080void
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001081NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info, NativeThreadLinux &thread)
Todd Fialaaf245d12014-06-30 21:05:18 +00001082{
1083 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001084 const bool is_main_thread = (thread.GetID() == GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001085
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001086 assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
Todd Fialaaf245d12014-06-30 21:05:18 +00001087
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001088 switch (info.si_code)
Todd Fialaaf245d12014-06-30 21:05:18 +00001089 {
1090 // TODO: these two cases are required if we want to support tracing of the inferiors' children. We'd need this to debug a monitor.
1091 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
1092 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
1093
1094 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
1095 {
Pavel Labath5fd24c62015-04-23 09:04:35 +00001096 // This is the notification on the parent thread which informs us of new thread
Pavel Labath426bdf82015-04-28 07:51:52 +00001097 // creation.
1098 // We don't want to do anything with the parent thread so we just resume it. In case we
1099 // want to implement "break on thread creation" functionality, we would need to stop
1100 // here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001101
Pavel Labath426bdf82015-04-28 07:51:52 +00001102 unsigned long event_message = 0;
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001103 if (GetEventMessage(thread.GetID(), &event_message).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001104 {
Pavel Labath426bdf82015-04-28 07:51:52 +00001105 if (log)
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001106 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " received thread creation event but GetEventMessage failed so we don't know the new tid", __FUNCTION__, thread.GetID());
Pavel Labath426bdf82015-04-28 07:51:52 +00001107 } else
1108 WaitForNewThread(event_message);
Todd Fialaaf245d12014-06-30 21:05:18 +00001109
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001110 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001111 break;
1112 }
1113
1114 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
Todd Fialaa9882ce2014-08-28 15:46:54 +00001115 {
Pavel Labathf9077782015-08-21 09:13:53 +00001116 NativeThreadLinuxSP main_thread_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001117 if (log)
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001118 log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info.si_code ^ SIGTRAP);
Todd Fialaa9882ce2014-08-28 15:46:54 +00001119
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001120 // Exec clears any pending notifications.
Pavel Labath0e1d7292015-08-20 09:06:12 +00001121 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
Chaoren Linfa03ad22015-02-03 01:50:42 +00001122
Pavel Labath57a77112016-05-16 09:18:30 +00001123 // Remove all but the main thread here. Linux fork creates a new process which only copies the main thread.
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001124 if (log)
1125 log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
1126
1127 for (auto thread_sp : m_threads)
Todd Fialaa9882ce2014-08-28 15:46:54 +00001128 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001129 const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
1130 if (is_main_thread)
Todd Fialaa9882ce2014-08-28 15:46:54 +00001131 {
Pavel Labathf9077782015-08-21 09:13:53 +00001132 main_thread_sp = std::static_pointer_cast<NativeThreadLinux>(thread_sp);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001133 if (log)
1134 log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00001135 }
1136 else
1137 {
Todd Fialaa9882ce2014-08-28 15:46:54 +00001138 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001139 log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00001140 }
1141 }
1142
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001143 m_threads.clear ();
1144
1145 if (main_thread_sp)
1146 {
1147 m_threads.push_back (main_thread_sp);
1148 SetCurrentThreadID (main_thread_sp->GetID ());
Pavel Labathf9077782015-08-21 09:13:53 +00001149 main_thread_sp->SetStoppedByExec();
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001150 }
1151 else
1152 {
1153 SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
1154 if (log)
1155 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
1156 }
1157
Chaoren Linfa03ad22015-02-03 01:50:42 +00001158 // Tell coordinator about about the "new" (since exec) stopped main thread.
Pavel Labathf9077782015-08-21 09:13:53 +00001159 ThreadWasCreated(*main_thread_sp);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001160
Todd Fialaa9882ce2014-08-28 15:46:54 +00001161 // Let our delegate know we have just exec'd.
1162 NotifyDidExec ();
1163
1164 // If we have a main thread, indicate we are stopped.
1165 assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001166
1167 // Let the process know we're stopped.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001168 StopRunningThreads(main_thread_sp->GetID());
Todd Fialaa9882ce2014-08-28 15:46:54 +00001169
Todd Fialaaf245d12014-06-30 21:05:18 +00001170 break;
Todd Fialaa9882ce2014-08-28 15:46:54 +00001171 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001172
1173 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
1174 {
1175 // The inferior process or one of its threads is about to exit.
Pavel Labath6e351632015-05-15 13:30:59 +00001176 // We don't want to do anything with the thread so we just resume it. In case we
1177 // want to implement "break on thread exit" functionality, we would need to stop
1178 // here.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001179
Todd Fialaaf245d12014-06-30 21:05:18 +00001180 unsigned long data = 0;
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001181 if (GetEventMessage(thread.GetID(), &data).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001182 data = -1;
1183
1184 if (log)
1185 {
1186 log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
1187 __FUNCTION__,
1188 data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001189 thread.GetID(),
Todd Fialaaf245d12014-06-30 21:05:18 +00001190 is_main_thread ? "is main thread" : "not main thread");
1191 }
1192
Todd Fialaaf245d12014-06-30 21:05:18 +00001193 if (is_main_thread)
1194 {
1195 SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001196 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001197
Pavel Labath86852d32015-09-01 10:59:36 +00001198 StateType state = thread.GetState();
1199 if (! StateIsRunningState(state))
1200 {
1201 // Due to a kernel bug, we may sometimes get this stop after the inferior gets a
1202 // SIGKILL. This confuses our state tracking logic in ResumeThread(), since normally,
1203 // we should not be receiving any ptrace events while the inferior is stopped. This
1204 // makes sure that the inferior is resumed and exits normally.
1205 state = eStateRunning;
1206 }
1207 ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001208
1209 break;
1210 }
1211
1212 case 0:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001213 case TRAP_TRACE: // We receive this on single stepping.
1214 case TRAP_HWBKPT: // We receive this on watchpoint hit
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001215 {
1216 // If a watchpoint was hit, report it
1217 uint32_t wp_index;
Tamas Berghammer1fa5c4b2015-10-13 16:48:04 +00001218 Error error = thread.GetRegisterContext()->GetWatchpointHitIndex(wp_index, (uintptr_t)info.si_addr);
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001219 if (error.Fail() && log)
1220 log->Printf("NativeProcessLinux::%s() "
1221 "received error while checking for watchpoint hits, "
1222 "pid = %" PRIu64 " error = %s",
1223 __FUNCTION__, thread.GetID(), error.AsCString());
1224 if (wp_index != LLDB_INVALID_INDEX32)
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001225 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001226 MonitorWatchpoint(thread, wp_index);
1227 break;
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001228 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001229
Tamas Berghammerbe379e12016-02-16 15:14:36 +00001230 // Otherwise, report step over
1231 MonitorTrace(thread);
Todd Fialaaf245d12014-06-30 21:05:18 +00001232 break;
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001233 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001234
1235 case SI_KERNEL:
Mohit K. Bhakkad35799962015-06-18 04:53:18 +00001236#if defined __mips__
1237 // For mips there is no special signal for watchpoint
1238 // So we check for watchpoint in kernel trap
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001239 {
1240 // If a watchpoint was hit, report it
1241 uint32_t wp_index;
1242 Error error = thread.GetRegisterContext()->GetWatchpointHitIndex(wp_index, LLDB_INVALID_ADDRESS);
1243 if (error.Fail() && log)
1244 log->Printf("NativeProcessLinux::%s() "
1245 "received error while checking for watchpoint hits, "
1246 "pid = %" PRIu64 " error = %s",
Mohit K. Bhakkad16ad0322015-08-28 12:08:26 +00001247 __FUNCTION__, thread.GetID(), error.AsCString());
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001248 if (wp_index != LLDB_INVALID_INDEX32)
Mohit K. Bhakkad35799962015-06-18 04:53:18 +00001249 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001250 MonitorWatchpoint(thread, wp_index);
1251 break;
Mohit K. Bhakkad35799962015-06-18 04:53:18 +00001252 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001253 }
Mohit K. Bhakkad35799962015-06-18 04:53:18 +00001254 // NO BREAK
1255#endif
Todd Fialaaf245d12014-06-30 21:05:18 +00001256 case TRAP_BRKPT:
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001257 MonitorBreakpoint(thread);
Todd Fialaaf245d12014-06-30 21:05:18 +00001258 break;
1259
1260 case SIGTRAP:
1261 case (SIGTRAP | 0x80):
1262 if (log)
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001263 log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), thread.GetID());
Chaoren Linfa03ad22015-02-03 01:50:42 +00001264
Todd Fialaaf245d12014-06-30 21:05:18 +00001265 // Ignore these signals until we know more about them.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001266 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001267 break;
1268
1269 default:
1270 assert(false && "Unexpected SIGTRAP code!");
1271 if (log)
Pavel Labath6e351632015-05-15 13:30:59 +00001272 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 "tid %" PRIu64 " received unhandled SIGTRAP code: 0x%d",
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001273 __FUNCTION__, GetID(), thread.GetID(), info.si_code);
Todd Fialaaf245d12014-06-30 21:05:18 +00001274 break;
1275
1276 }
1277}
1278
1279void
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001280NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread)
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001281{
1282 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1283 if (log)
1284 log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)",
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001285 __FUNCTION__, thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001286
Pavel Labath0e1d7292015-08-20 09:06:12 +00001287 // This thread is currently stopped.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001288 thread.SetStoppedByTrace();
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001289
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001290 StopRunningThreads(thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001291}
1292
1293void
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001294NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread)
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001295{
1296 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
1297 if (log)
1298 log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001299 __FUNCTION__, thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001300
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001301 // Mark the thread as stopped at breakpoint.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001302 thread.SetStoppedByBreakpoint();
1303 Error error = FixupBreakpointPCAsNeeded(thread);
1304 if (error.Fail())
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001305 if (log)
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001306 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
1307 __FUNCTION__, thread.GetID(), error.AsCString());
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001308
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001309 if (m_threads_stepping_with_breakpoint.find(thread.GetID()) != m_threads_stepping_with_breakpoint.end())
1310 thread.SetStoppedByTrace();
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001311
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001312 StopRunningThreads(thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001313}
1314
1315void
Pavel Labathf9077782015-08-21 09:13:53 +00001316NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread, uint32_t wp_index)
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001317{
1318 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
1319 if (log)
1320 log->Printf("NativeProcessLinux::%s() received watchpoint event, "
1321 "pid = %" PRIu64 ", wp_index = %" PRIu32,
Pavel Labathf9077782015-08-21 09:13:53 +00001322 __FUNCTION__, thread.GetID(), wp_index);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001323
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001324 // Mark the thread as stopped at watchpoint.
1325 // The address is at (lldb::addr_t)info->si_addr if we need it.
Pavel Labathf9077782015-08-21 09:13:53 +00001326 thread.SetStoppedByWatchpoint(wp_index);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001327
1328 // We need to tell all other running threads before we notify the delegate about this stop.
Pavel Labathf9077782015-08-21 09:13:53 +00001329 StopRunningThreads(thread.GetID());
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001330}
1331
1332void
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001333NativeProcessLinux::MonitorSignal(const siginfo_t &info, NativeThreadLinux &thread, bool exited)
Todd Fialaaf245d12014-06-30 21:05:18 +00001334{
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001335 const int signo = info.si_signo;
1336 const bool is_from_llgs = info.si_pid == getpid ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001337
1338 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1339
1340 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1341 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1342 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
1343 //
1344 // IOW, user generated signals never generate what we consider to be a
1345 // "crash".
1346 //
1347 // Similarly, ACK signals generated by this monitor.
1348
Todd Fialaaf245d12014-06-30 21:05:18 +00001349 // Handle the signal.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001350 if (info.si_code == SI_TKILL || info.si_code == SI_USER)
Todd Fialaaf245d12014-06-30 21:05:18 +00001351 {
1352 if (log)
1353 log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
1354 __FUNCTION__,
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001355 Host::GetSignalAsCString(signo),
Todd Fialaaf245d12014-06-30 21:05:18 +00001356 signo,
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001357 (info.si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
1358 info.si_pid,
Todd Fiala511e5cd2014-09-11 23:29:14 +00001359 is_from_llgs ? "from llgs" : "not from llgs",
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001360 thread.GetID());
Todd Fiala58a2f662014-08-12 17:02:07 +00001361 }
1362
1363 // Check for thread stop notification.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001364 if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP))
Todd Fiala58a2f662014-08-12 17:02:07 +00001365 {
1366 // This is a tgkill()-based stop.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001367 if (log)
1368 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
1369 __FUNCTION__,
1370 GetID (),
1371 thread.GetID());
1372
1373 // Check that we're not already marked with a stop reason.
1374 // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
1375 // the kernel signaled us with the thread stopping which we handled and marked as stopped,
1376 // and that, without an intervening resume, we received another stop. It is more likely
1377 // that we are missing the marking of a run state somewhere if we find that the thread was
1378 // marked as stopped.
1379 const StateType thread_state = thread.GetState();
1380 if (!StateIsStoppedState (thread_state, false))
Todd Fiala58a2f662014-08-12 17:02:07 +00001381 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001382 // An inferior thread has stopped because of a SIGSTOP we have sent it.
1383 // Generally, these are not important stops and we don't want to report them as
1384 // they are just used to stop other threads when one thread (the one with the
1385 // *real* stop reason) hits a breakpoint (watchpoint, etc...). However, in the
1386 // case of an asynchronous Interrupt(), this *is* the real stop reason, so we
1387 // leave the signal intact if this is the thread that was chosen as the
1388 // triggering thread.
1389 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID)
Chaoren Linaab58632015-02-03 01:50:57 +00001390 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001391 if (m_pending_notification_tid == thread.GetID())
1392 thread.SetStoppedBySignal(SIGSTOP, &info);
Pavel Labath0e1d7292015-08-20 09:06:12 +00001393 else
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001394 thread.SetStoppedWithNoReason();
1395
1396 SetCurrentThreadID (thread.GetID ());
1397 SignalIfAllThreadsStopped();
Chaoren Linaab58632015-02-03 01:50:57 +00001398 }
1399 else
1400 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001401 // We can end up here if stop was initiated by LLGS but by this time a
1402 // thread stop has occurred - maybe initiated by another event.
1403 Error error = ResumeThread(thread, thread.GetState(), 0);
1404 if (error.Fail() && log)
Chaoren Linaab58632015-02-03 01:50:57 +00001405 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001406 log->Printf("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s",
1407 __FUNCTION__, thread.GetID(), error.AsCString());
Chaoren Linaab58632015-02-03 01:50:57 +00001408 }
1409 }
Todd Fiala58a2f662014-08-12 17:02:07 +00001410 }
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001411 else
1412 {
1413 if (log)
1414 {
1415 // Retrieve the signal name if the thread was stopped by a signal.
1416 int stop_signo = 0;
1417 const bool stopped_by_signal = thread.IsStopped(&stop_signo);
1418 const char *signal_name = stopped_by_signal ? Host::GetSignalAsCString(stop_signo) : "<not stopped by signal>";
1419 if (!signal_name)
1420 signal_name = "<no-signal-name>";
1421
1422 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",
1423 __FUNCTION__,
1424 GetID (),
1425 thread.GetID(),
1426 StateAsCString (thread_state),
1427 stop_signo,
1428 signal_name);
1429 }
1430 SignalIfAllThreadsStopped();
1431 }
Todd Fiala58a2f662014-08-12 17:02:07 +00001432
1433 // Done handling.
Todd Fialaaf245d12014-06-30 21:05:18 +00001434 return;
1435 }
1436
1437 if (log)
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001438 log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, Host::GetSignalAsCString(signo));
Todd Fialaaf245d12014-06-30 21:05:18 +00001439
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001440 // This thread is stopped.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001441 thread.SetStoppedBySignal(signo, &info);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001442
1443 // Send a stop to the debugger after we get all other threads to stop.
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001444 StopRunningThreads(thread.GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +00001445}
1446
Tamas Berghammere7708682015-04-22 10:00:23 +00001447namespace {
1448
1449struct EmulatorBaton
1450{
1451 NativeProcessLinux* m_process;
1452 NativeRegisterContext* m_reg_context;
Tamas Berghammere7708682015-04-22 10:00:23 +00001453
Pavel Labath6648fcc2015-04-27 09:21:14 +00001454 // eRegisterKindDWARF -> RegsiterValue
1455 std::unordered_map<uint32_t, RegisterValue> m_register_values;
1456
1457 EmulatorBaton(NativeProcessLinux* process, NativeRegisterContext* reg_context) :
Tamas Berghammere7708682015-04-22 10:00:23 +00001458 m_process(process), m_reg_context(reg_context) {}
1459};
1460
1461} // anonymous namespace
1462
1463static size_t
1464ReadMemoryCallback (EmulateInstruction *instruction,
1465 void *baton,
1466 const EmulateInstruction::Context &context,
1467 lldb::addr_t addr,
1468 void *dst,
1469 size_t length)
1470{
1471 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
1472
Chaoren Lin3eb4b452015-04-29 17:24:48 +00001473 size_t bytes_read;
Tamas Berghammere7708682015-04-22 10:00:23 +00001474 emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
1475 return bytes_read;
1476}
1477
1478static bool
1479ReadRegisterCallback (EmulateInstruction *instruction,
1480 void *baton,
1481 const RegisterInfo *reg_info,
1482 RegisterValue &reg_value)
1483{
1484 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
1485
Pavel Labath6648fcc2015-04-27 09:21:14 +00001486 auto it = emulator_baton->m_register_values.find(reg_info->kinds[eRegisterKindDWARF]);
1487 if (it != emulator_baton->m_register_values.end())
1488 {
1489 reg_value = it->second;
1490 return true;
1491 }
1492
Tamas Berghammere7708682015-04-22 10:00:23 +00001493 // The emulator only fill in the dwarf regsiter numbers (and in some case
1494 // the generic register numbers). Get the full register info from the
1495 // register context based on the dwarf register numbers.
1496 const RegisterInfo* full_reg_info = emulator_baton->m_reg_context->GetRegisterInfo(
1497 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
1498
1499 Error error = emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
Pavel Labath6648fcc2015-04-27 09:21:14 +00001500 if (error.Success())
Pavel Labath6648fcc2015-04-27 09:21:14 +00001501 return true;
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001502
Pavel Labath6648fcc2015-04-27 09:21:14 +00001503 return false;
Tamas Berghammere7708682015-04-22 10:00:23 +00001504}
1505
1506static bool
1507WriteRegisterCallback (EmulateInstruction *instruction,
1508 void *baton,
1509 const EmulateInstruction::Context &context,
1510 const RegisterInfo *reg_info,
1511 const RegisterValue &reg_value)
1512{
1513 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
Pavel Labath6648fcc2015-04-27 09:21:14 +00001514 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = reg_value;
Tamas Berghammere7708682015-04-22 10:00:23 +00001515 return true;
1516}
1517
1518static size_t
1519WriteMemoryCallback (EmulateInstruction *instruction,
1520 void *baton,
1521 const EmulateInstruction::Context &context,
1522 lldb::addr_t addr,
1523 const void *dst,
1524 size_t length)
1525{
1526 return length;
1527}
1528
1529static lldb::addr_t
1530ReadFlags (NativeRegisterContext* regsiter_context)
1531{
1532 const RegisterInfo* flags_info = regsiter_context->GetRegisterInfo(
1533 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1534 return regsiter_context->ReadRegisterAsUnsigned(flags_info, LLDB_INVALID_ADDRESS);
1535}
1536
1537Error
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001538NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadLinux &thread)
Tamas Berghammere7708682015-04-22 10:00:23 +00001539{
1540 Error error;
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001541 NativeRegisterContextSP register_context_sp = thread.GetRegisterContext();
Tamas Berghammere7708682015-04-22 10:00:23 +00001542
1543 std::unique_ptr<EmulateInstruction> emulator_ap(
1544 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, nullptr));
1545
1546 if (emulator_ap == nullptr)
1547 return Error("Instruction emulator not found!");
1548
1549 EmulatorBaton baton(this, register_context_sp.get());
1550 emulator_ap->SetBaton(&baton);
1551 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
1552 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
1553 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
1554 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
1555
1556 if (!emulator_ap->ReadInstruction())
1557 return Error("Read instruction failed!");
1558
Pavel Labath6648fcc2015-04-27 09:21:14 +00001559 bool emulation_result = emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
1560
1561 const RegisterInfo* reg_info_pc = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1562 const RegisterInfo* reg_info_flags = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1563
1564 auto pc_it = baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1565 auto flags_it = baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
1566
Tamas Berghammere7708682015-04-22 10:00:23 +00001567 lldb::addr_t next_pc;
1568 lldb::addr_t next_flags;
Pavel Labath6648fcc2015-04-27 09:21:14 +00001569 if (emulation_result)
Tamas Berghammere7708682015-04-22 10:00:23 +00001570 {
Pavel Labath6648fcc2015-04-27 09:21:14 +00001571 assert(pc_it != baton.m_register_values.end() && "Emulation was successfull but PC wasn't updated");
1572 next_pc = pc_it->second.GetAsUInt64();
1573
1574 if (flags_it != baton.m_register_values.end())
1575 next_flags = flags_it->second.GetAsUInt64();
Tamas Berghammere7708682015-04-22 10:00:23 +00001576 else
1577 next_flags = ReadFlags (register_context_sp.get());
1578 }
Pavel Labath6648fcc2015-04-27 09:21:14 +00001579 else if (pc_it == baton.m_register_values.end())
Tamas Berghammere7708682015-04-22 10:00:23 +00001580 {
1581 // Emulate instruction failed and it haven't changed PC. Advance PC
1582 // with the size of the current opcode because the emulation of all
1583 // PC modifying instruction should be successful. The failure most
1584 // likely caused by a not supported instruction which don't modify PC.
1585 next_pc = register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
1586 next_flags = ReadFlags (register_context_sp.get());
1587 }
1588 else
1589 {
1590 // The instruction emulation failed after it modified the PC. It is an
1591 // unknown error where we can't continue because the next instruction is
1592 // modifying the PC but we don't know how.
1593 return Error ("Instruction emulation failed unexpectedly.");
1594 }
1595
1596 if (m_arch.GetMachine() == llvm::Triple::arm)
1597 {
1598 if (next_flags & 0x20)
1599 {
1600 // Thumb mode
1601 error = SetSoftwareBreakpoint(next_pc, 2);
1602 }
1603 else
1604 {
1605 // Arm mode
1606 error = SetSoftwareBreakpoint(next_pc, 4);
1607 }
1608 }
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001609 else if (m_arch.GetMachine() == llvm::Triple::mips64
Jaydeep Patilc60c9452015-06-23 03:37:08 +00001610 || m_arch.GetMachine() == llvm::Triple::mips64el
1611 || m_arch.GetMachine() == llvm::Triple::mips
1612 || m_arch.GetMachine() == llvm::Triple::mipsel)
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001613 error = SetSoftwareBreakpoint(next_pc, 4);
Tamas Berghammere7708682015-04-22 10:00:23 +00001614 else
1615 {
1616 // No size hint is given for the next breakpoint
1617 error = SetSoftwareBreakpoint(next_pc, 0);
1618 }
1619
Tamas Berghammere7708682015-04-22 10:00:23 +00001620 if (error.Fail())
1621 return error;
1622
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001623 m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
Tamas Berghammere7708682015-04-22 10:00:23 +00001624
1625 return Error();
1626}
1627
1628bool
1629NativeProcessLinux::SupportHardwareSingleStepping() const
1630{
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001631 if (m_arch.GetMachine() == llvm::Triple::arm
Jaydeep Patilc60c9452015-06-23 03:37:08 +00001632 || m_arch.GetMachine() == llvm::Triple::mips64 || m_arch.GetMachine() == llvm::Triple::mips64el
1633 || m_arch.GetMachine() == llvm::Triple::mips || m_arch.GetMachine() == llvm::Triple::mipsel)
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001634 return false;
1635 return true;
Tamas Berghammere7708682015-04-22 10:00:23 +00001636}
1637
Todd Fialaaf245d12014-06-30 21:05:18 +00001638Error
1639NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
1640{
Todd Fialaaf245d12014-06-30 21:05:18 +00001641 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1642 if (log)
1643 log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
1644
Tamas Berghammere7708682015-04-22 10:00:23 +00001645 bool software_single_step = !SupportHardwareSingleStepping();
Todd Fialaaf245d12014-06-30 21:05:18 +00001646
Tamas Berghammere7708682015-04-22 10:00:23 +00001647 if (software_single_step)
1648 {
1649 for (auto thread_sp : m_threads)
1650 {
1651 assert (thread_sp && "thread list should not contain NULL threads");
1652
1653 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
1654 if (action == nullptr)
1655 continue;
1656
1657 if (action->state == eStateStepping)
1658 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001659 Error error = SetupSoftwareSingleStepping(static_cast<NativeThreadLinux &>(*thread_sp));
Tamas Berghammere7708682015-04-22 10:00:23 +00001660 if (error.Fail())
1661 return error;
1662 }
1663 }
1664 }
1665
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001666 for (auto thread_sp : m_threads)
Todd Fialaaf245d12014-06-30 21:05:18 +00001667 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001668 assert (thread_sp && "thread list should not contain NULL threads");
1669
1670 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
1671
1672 if (action == nullptr)
Todd Fialaaf245d12014-06-30 21:05:18 +00001673 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00001674 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001675 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
1676 __FUNCTION__, GetID (), thread_sp->GetID ());
1677 continue;
1678 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001679
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001680 if (log)
1681 {
1682 log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
1683 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
1684 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001685
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001686 switch (action->state)
1687 {
1688 case eStateRunning:
Pavel Labath0e1d7292015-08-20 09:06:12 +00001689 case eStateStepping:
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001690 {
1691 // Run the thread, possibly feeding it the signal.
1692 const int signo = action->signal;
Pavel Labathb9cc0c72015-08-24 09:22:04 +00001693 ResumeThread(static_cast<NativeThreadLinux &>(*thread_sp), action->state, signo);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001694 break;
1695 }
1696
1697 case eStateSuspended:
1698 case eStateStopped:
Pavel Labath108c3252015-05-12 09:03:18 +00001699 lldbassert(0 && "Unexpected state");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001700
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001701 default:
1702 return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
1703 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001704 }
1705 }
1706
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001707 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00001708}
1709
1710Error
1711NativeProcessLinux::Halt ()
1712{
1713 Error error;
1714
Todd Fialaaf245d12014-06-30 21:05:18 +00001715 if (kill (GetID (), SIGSTOP) != 0)
1716 error.SetErrorToErrno ();
1717
1718 return error;
1719}
1720
1721Error
1722NativeProcessLinux::Detach ()
1723{
1724 Error error;
1725
Todd Fialaaf245d12014-06-30 21:05:18 +00001726 // Stop monitoring the inferior.
Pavel Labath19cbe962015-07-21 13:20:32 +00001727 m_sigchld_handle.reset();
Todd Fialaaf245d12014-06-30 21:05:18 +00001728
Pavel Labath7a9495b2015-09-01 15:00:51 +00001729 // Tell ptrace to detach from the process.
1730 if (GetID () == LLDB_INVALID_PROCESS_ID)
1731 return error;
1732
1733 for (auto thread_sp : m_threads)
1734 {
1735 Error e = Detach(thread_sp->GetID());
1736 if (e.Fail())
1737 error = e; // Save the error, but still attempt to detach from other threads.
1738 }
1739
Todd Fialaaf245d12014-06-30 21:05:18 +00001740 return error;
1741}
1742
1743Error
1744NativeProcessLinux::Signal (int signo)
1745{
1746 Error error;
1747
1748 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1749 if (log)
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001750 log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
1751 __FUNCTION__, signo, Host::GetSignalAsCString(signo), GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +00001752
1753 if (kill(GetID(), signo))
1754 error.SetErrorToErrno();
1755
1756 return error;
1757}
1758
1759Error
Chaoren Line9547b82015-02-03 01:51:00 +00001760NativeProcessLinux::Interrupt ()
1761{
1762 // Pick a running thread (or if none, a not-dead stopped thread) as
1763 // the chosen thread that will be the stop-reason thread.
Chaoren Line9547b82015-02-03 01:51:00 +00001764 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1765
1766 NativeThreadProtocolSP running_thread_sp;
1767 NativeThreadProtocolSP stopped_thread_sp;
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001768
1769 if (log)
1770 log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
1771
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001772 for (auto thread_sp : m_threads)
Chaoren Line9547b82015-02-03 01:51:00 +00001773 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001774 // The thread shouldn't be null but lets just cover that here.
1775 if (!thread_sp)
1776 continue;
Chaoren Line9547b82015-02-03 01:51:00 +00001777
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001778 // If we have a running or stepping thread, we'll call that the
1779 // target of the interrupt.
1780 const auto thread_state = thread_sp->GetState ();
1781 if (thread_state == eStateRunning ||
1782 thread_state == eStateStepping)
Chaoren Line9547b82015-02-03 01:51:00 +00001783 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001784 running_thread_sp = thread_sp;
1785 break;
1786 }
1787 else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
1788 {
1789 // Remember the first non-dead stopped thread. We'll use that as a backup if there are no running threads.
1790 stopped_thread_sp = thread_sp;
Chaoren Line9547b82015-02-03 01:51:00 +00001791 }
1792 }
1793
1794 if (!running_thread_sp && !stopped_thread_sp)
1795 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001796 Error error("found no running/stepping or live stopped threads as target for interrupt");
Chaoren Line9547b82015-02-03 01:51:00 +00001797 if (log)
Chaoren Line9547b82015-02-03 01:51:00 +00001798 log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001799
Chaoren Line9547b82015-02-03 01:51:00 +00001800 return error;
1801 }
1802
1803 NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
1804
1805 if (log)
1806 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
1807 __FUNCTION__,
1808 GetID (),
1809 running_thread_sp ? "running" : "stopped",
1810 deferred_signal_thread_sp->GetID ());
1811
Pavel Labathed89c7f2015-05-06 12:22:37 +00001812 StopRunningThreads(deferred_signal_thread_sp->GetID());
Pavel Labath45f5cb32015-05-05 15:05:50 +00001813
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001814 return Error();
Chaoren Line9547b82015-02-03 01:51:00 +00001815}
1816
1817Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001818NativeProcessLinux::Kill ()
1819{
1820 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1821 if (log)
1822 log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
1823
1824 Error error;
1825
1826 switch (m_state)
1827 {
1828 case StateType::eStateInvalid:
1829 case StateType::eStateExited:
1830 case StateType::eStateCrashed:
1831 case StateType::eStateDetached:
1832 case StateType::eStateUnloaded:
1833 // Nothing to do - the process is already dead.
1834 if (log)
1835 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
1836 return error;
1837
1838 case StateType::eStateConnected:
1839 case StateType::eStateAttaching:
1840 case StateType::eStateLaunching:
1841 case StateType::eStateStopped:
1842 case StateType::eStateRunning:
1843 case StateType::eStateStepping:
1844 case StateType::eStateSuspended:
1845 // We can try to kill a process in these states.
1846 break;
1847 }
1848
1849 if (kill (GetID (), SIGKILL) != 0)
1850 {
1851 error.SetErrorToErrno ();
1852 return error;
1853 }
1854
1855 return error;
1856}
1857
1858static Error
1859ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
1860{
1861 memory_region_info.Clear();
1862
1863 StringExtractor line_extractor (maps_line.c_str ());
1864
1865 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode pathname
1866 // perms: rwxp (letter is present if set, '-' if not, final character is p=private, s=shared).
1867
1868 // Parse out the starting address
1869 lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
1870
1871 // Parse out hyphen separating start and end address from range.
1872 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
1873 return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
1874
1875 // Parse out the ending address
1876 lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
1877
1878 // Parse out the space after the address.
1879 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
1880 return Error ("malformed /proc/{pid}/maps entry, missing space after range");
1881
1882 // Save the range.
1883 memory_region_info.GetRange ().SetRangeBase (start_address);
1884 memory_region_info.GetRange ().SetRangeEnd (end_address);
1885
1886 // Parse out each permission entry.
1887 if (line_extractor.GetBytesLeft () < 4)
1888 return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
1889
1890 // Handle read permission.
1891 const char read_perm_char = line_extractor.GetChar ();
1892 if (read_perm_char == 'r')
1893 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
1894 else
1895 {
1896 assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
1897 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
1898 }
1899
1900 // Handle write permission.
1901 const char write_perm_char = line_extractor.GetChar ();
1902 if (write_perm_char == 'w')
1903 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
1904 else
1905 {
1906 assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
1907 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
1908 }
1909
1910 // Handle execute permission.
1911 const char exec_perm_char = line_extractor.GetChar ();
1912 if (exec_perm_char == 'x')
1913 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
1914 else
1915 {
1916 assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
1917 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
1918 }
1919
1920 return Error ();
1921}
1922
1923Error
1924NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
1925{
1926 // FIXME review that the final memory region returned extends to the end of the virtual address space,
1927 // with no perms if it is not mapped.
1928
1929 // Use an approach that reads memory regions from /proc/{pid}/maps.
1930 // Assume proc maps entries are in ascending order.
1931 // FIXME assert if we find differently.
Todd Fialaaf245d12014-06-30 21:05:18 +00001932
1933 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1934 Error error;
1935
1936 if (m_supports_mem_region == LazyBool::eLazyBoolNo)
1937 {
1938 // We're done.
1939 error.SetErrorString ("unsupported");
1940 return error;
1941 }
1942
1943 // If our cache is empty, pull the latest. There should always be at least one memory region
1944 // if memory region handling is supported.
1945 if (m_mem_region_cache.empty ())
1946 {
1947 error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
1948 [&] (const std::string &line) -> bool
1949 {
1950 MemoryRegionInfo info;
1951 const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
1952 if (parse_error.Success ())
1953 {
1954 m_mem_region_cache.push_back (info);
1955 return true;
1956 }
1957 else
1958 {
1959 if (log)
1960 log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
1961 return false;
1962 }
1963 });
1964
1965 // If we had an error, we'll mark unsupported.
1966 if (error.Fail ())
1967 {
1968 m_supports_mem_region = LazyBool::eLazyBoolNo;
1969 return error;
1970 }
1971 else if (m_mem_region_cache.empty ())
1972 {
1973 // No entries after attempting to read them. This shouldn't happen if /proc/{pid}/maps
1974 // is supported. Assume we don't support map entries via procfs.
1975 if (log)
1976 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
1977 m_supports_mem_region = LazyBool::eLazyBoolNo;
1978 error.SetErrorString ("not supported");
1979 return error;
1980 }
1981
1982 if (log)
1983 log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ());
1984
1985 // We support memory retrieval, remember that.
1986 m_supports_mem_region = LazyBool::eLazyBoolYes;
1987 }
1988 else
1989 {
1990 if (log)
1991 log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
1992 }
1993
1994 lldb::addr_t prev_base_address = 0;
1995
1996 // FIXME start by finding the last region that is <= target address using binary search. Data is sorted.
1997 // There can be a ton of regions on pthreads apps with lots of threads.
1998 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
1999 {
2000 MemoryRegionInfo &proc_entry_info = *it;
2001
2002 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
2003 assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
2004 prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
2005
2006 // If the target address comes before this entry, indicate distance to next region.
2007 if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
2008 {
2009 range_info.GetRange ().SetRangeBase (load_addr);
2010 range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
2011 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2012 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2013 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2014
2015 return error;
2016 }
2017 else if (proc_entry_info.GetRange ().Contains (load_addr))
2018 {
2019 // The target address is within the memory region we're processing here.
2020 range_info = proc_entry_info;
2021 return error;
2022 }
2023
2024 // The target memory address comes somewhere after the region we just parsed.
2025 }
2026
Tamas Berghammer09839c32015-07-03 09:30:19 +00002027 // If we made it here, we didn't find an entry that contained the given address. Return the
2028 // load_addr as start and the amount of bytes betwwen load address and the end of the memory as
2029 // size.
2030 range_info.GetRange ().SetRangeBase (load_addr);
2031 switch (m_arch.GetAddressByteSize())
2032 {
2033 case 4:
2034 range_info.GetRange ().SetByteSize (0x100000000ull - load_addr);
2035 break;
2036 case 8:
2037 range_info.GetRange ().SetByteSize (0ull - load_addr);
2038 break;
2039 default:
2040 assert(false && "Unrecognized data byte size");
2041 break;
2042 }
2043 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2044 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2045 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
Todd Fialaaf245d12014-06-30 21:05:18 +00002046 return error;
2047}
2048
2049void
2050NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
2051{
2052 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2053 if (log)
2054 log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
2055
Todd Fialaaf245d12014-06-30 21:05:18 +00002056 if (log)
2057 log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2058 m_mem_region_cache.clear ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002059}
2060
2061Error
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002062NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr)
Todd Fialaaf245d12014-06-30 21:05:18 +00002063{
2064 // FIXME implementing this requires the equivalent of
2065 // InferiorCallPOSIX::InferiorCallMmap, which depends on
2066 // functional ThreadPlans working with Native*Protocol.
2067#if 1
2068 return Error ("not implemented yet");
2069#else
2070 addr = LLDB_INVALID_ADDRESS;
2071
2072 unsigned prot = 0;
2073 if (permissions & lldb::ePermissionsReadable)
2074 prot |= eMmapProtRead;
2075 if (permissions & lldb::ePermissionsWritable)
2076 prot |= eMmapProtWrite;
2077 if (permissions & lldb::ePermissionsExecutable)
2078 prot |= eMmapProtExec;
2079
2080 // TODO implement this directly in NativeProcessLinux
2081 // (and lift to NativeProcessPOSIX if/when that class is
2082 // refactored out).
2083 if (InferiorCallMmap(this, addr, 0, size, prot,
2084 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
2085 m_addr_to_mmap_size[addr] = size;
2086 return Error ();
2087 } else {
2088 addr = LLDB_INVALID_ADDRESS;
2089 return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
2090 }
2091#endif
2092}
2093
2094Error
2095NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
2096{
2097 // FIXME see comments in AllocateMemory - required lower-level
2098 // bits not in place yet (ThreadPlans)
2099 return Error ("not implemented");
2100}
2101
2102lldb::addr_t
2103NativeProcessLinux::GetSharedLibraryInfoAddress ()
2104{
Todd Fialaaf245d12014-06-30 21:05:18 +00002105 // punt on this for now
2106 return LLDB_INVALID_ADDRESS;
Todd Fialaaf245d12014-06-30 21:05:18 +00002107}
2108
2109size_t
2110NativeProcessLinux::UpdateThreads ()
2111{
2112 // The NativeProcessLinux monitoring threads are always up to date
2113 // with respect to thread state and they keep the thread list
2114 // populated properly. All this method needs to do is return the
2115 // thread count.
Todd Fialaaf245d12014-06-30 21:05:18 +00002116 return m_threads.size ();
2117}
2118
2119bool
2120NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
2121{
2122 arch = m_arch;
2123 return true;
2124}
2125
2126Error
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002127NativeProcessLinux::GetSoftwareBreakpointPCOffset(uint32_t &actual_opcode_size)
Todd Fialaaf245d12014-06-30 21:05:18 +00002128{
2129 // FIXME put this behind a breakpoint protocol class that can be
2130 // set per architecture. Need ARM, MIPS support here.
2131 static const uint8_t g_i386_opcode [] = { 0xCC };
Ulrich Weigandbb00d0b2016-04-14 14:28:34 +00002132 static const uint8_t g_s390x_opcode[] = { 0x00, 0x01 };
Todd Fialaaf245d12014-06-30 21:05:18 +00002133
2134 switch (m_arch.GetMachine ())
2135 {
2136 case llvm::Triple::x86:
2137 case llvm::Triple::x86_64:
2138 actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
2139 return Error ();
2140
Ulrich Weigandbb00d0b2016-04-14 14:28:34 +00002141 case llvm::Triple::systemz:
2142 actual_opcode_size = static_cast<uint32_t> (sizeof(g_s390x_opcode));
2143 return Error ();
2144
Tamas Berghammerff7fd902015-07-03 12:51:30 +00002145 case llvm::Triple::arm:
2146 case llvm::Triple::aarch64:
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00002147 case llvm::Triple::mips64:
2148 case llvm::Triple::mips64el:
Sagar Thakurce815e42015-06-03 10:14:24 +00002149 case llvm::Triple::mips:
2150 case llvm::Triple::mipsel:
Tamas Berghammerff7fd902015-07-03 12:51:30 +00002151 // On these architectures the PC don't get updated for breakpoint hits
Jaydeep Patilc60c9452015-06-23 03:37:08 +00002152 actual_opcode_size = 0;
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00002153 return Error ();
2154
Todd Fialaaf245d12014-06-30 21:05:18 +00002155 default:
2156 assert(false && "CPU type not supported!");
2157 return Error ("CPU type not supported");
2158 }
2159}
2160
2161Error
2162NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
2163{
2164 if (hardware)
2165 return Error ("NativeProcessLinux does not support hardware breakpoints");
2166 else
2167 return SetSoftwareBreakpoint (addr, size);
2168}
2169
2170Error
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002171NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint,
2172 size_t &actual_opcode_size,
2173 const uint8_t *&trap_opcode_bytes)
Todd Fialaaf245d12014-06-30 21:05:18 +00002174{
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002175 // FIXME put this behind a breakpoint protocol class that can be set per
2176 // architecture. Need MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00002177 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Tamas Berghammerbe379e12016-02-16 15:14:36 +00002178 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
2179 // linux kernel does otherwise.
2180 static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 };
Todd Fialaaf245d12014-06-30 21:05:18 +00002181 static const uint8_t g_i386_opcode [] = { 0xCC };
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00002182 static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00002183 static const uint8_t g_mips64el_opcode[] = { 0x0d, 0x00, 0x00, 0x00 };
Ulrich Weigandbb00d0b2016-04-14 14:28:34 +00002184 static const uint8_t g_s390x_opcode[] = { 0x00, 0x01 };
Tamas Berghammerbe379e12016-02-16 15:14:36 +00002185 static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde };
Todd Fialaaf245d12014-06-30 21:05:18 +00002186
2187 switch (m_arch.GetMachine ())
2188 {
Todd Fiala2afc5962014-08-21 16:42:31 +00002189 case llvm::Triple::aarch64:
2190 trap_opcode_bytes = g_aarch64_opcode;
2191 actual_opcode_size = sizeof(g_aarch64_opcode);
2192 return Error ();
2193
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002194 case llvm::Triple::arm:
2195 switch (trap_opcode_size_hint)
2196 {
2197 case 2:
2198 trap_opcode_bytes = g_thumb_breakpoint_opcode;
2199 actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
2200 return Error ();
2201 case 4:
2202 trap_opcode_bytes = g_arm_breakpoint_opcode;
2203 actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
2204 return Error ();
2205 default:
2206 assert(false && "Unrecognised trap opcode size hint!");
2207 return Error ("Unrecognised trap opcode size hint!");
2208 }
2209
Todd Fialaaf245d12014-06-30 21:05:18 +00002210 case llvm::Triple::x86:
2211 case llvm::Triple::x86_64:
2212 trap_opcode_bytes = g_i386_opcode;
2213 actual_opcode_size = sizeof(g_i386_opcode);
2214 return Error ();
2215
Sagar Thakurce815e42015-06-03 10:14:24 +00002216 case llvm::Triple::mips:
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00002217 case llvm::Triple::mips64:
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00002218 trap_opcode_bytes = g_mips64_opcode;
2219 actual_opcode_size = sizeof(g_mips64_opcode);
2220 return Error ();
2221
Sagar Thakurce815e42015-06-03 10:14:24 +00002222 case llvm::Triple::mipsel:
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00002223 case llvm::Triple::mips64el:
2224 trap_opcode_bytes = g_mips64el_opcode;
2225 actual_opcode_size = sizeof(g_mips64el_opcode);
2226 return Error ();
2227
Ulrich Weigandbb00d0b2016-04-14 14:28:34 +00002228 case llvm::Triple::systemz:
2229 trap_opcode_bytes = g_s390x_opcode;
2230 actual_opcode_size = sizeof(g_s390x_opcode);
2231 return Error ();
2232
Todd Fialaaf245d12014-06-30 21:05:18 +00002233 default:
2234 assert(false && "CPU type not supported!");
2235 return Error ("CPU type not supported");
2236 }
2237}
2238
2239#if 0
2240ProcessMessage::CrashReason
2241NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
2242{
2243 ProcessMessage::CrashReason reason;
2244 assert(info->si_signo == SIGSEGV);
2245
2246 reason = ProcessMessage::eInvalidCrashReason;
2247
2248 switch (info->si_code)
2249 {
2250 default:
2251 assert(false && "unexpected si_code for SIGSEGV");
2252 break;
2253 case SI_KERNEL:
2254 // Linux will occasionally send spurious SI_KERNEL codes.
2255 // (this is poorly documented in sigaction)
2256 // One way to get this is via unaligned SIMD loads.
2257 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
2258 break;
2259 case SEGV_MAPERR:
2260 reason = ProcessMessage::eInvalidAddress;
2261 break;
2262 case SEGV_ACCERR:
2263 reason = ProcessMessage::ePrivilegedAddress;
2264 break;
2265 }
2266
2267 return reason;
2268}
2269#endif
2270
2271
2272#if 0
2273ProcessMessage::CrashReason
2274NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
2275{
2276 ProcessMessage::CrashReason reason;
2277 assert(info->si_signo == SIGILL);
2278
2279 reason = ProcessMessage::eInvalidCrashReason;
2280
2281 switch (info->si_code)
2282 {
2283 default:
2284 assert(false && "unexpected si_code for SIGILL");
2285 break;
2286 case ILL_ILLOPC:
2287 reason = ProcessMessage::eIllegalOpcode;
2288 break;
2289 case ILL_ILLOPN:
2290 reason = ProcessMessage::eIllegalOperand;
2291 break;
2292 case ILL_ILLADR:
2293 reason = ProcessMessage::eIllegalAddressingMode;
2294 break;
2295 case ILL_ILLTRP:
2296 reason = ProcessMessage::eIllegalTrap;
2297 break;
2298 case ILL_PRVOPC:
2299 reason = ProcessMessage::ePrivilegedOpcode;
2300 break;
2301 case ILL_PRVREG:
2302 reason = ProcessMessage::ePrivilegedRegister;
2303 break;
2304 case ILL_COPROC:
2305 reason = ProcessMessage::eCoprocessorError;
2306 break;
2307 case ILL_BADSTK:
2308 reason = ProcessMessage::eInternalStackError;
2309 break;
2310 }
2311
2312 return reason;
2313}
2314#endif
2315
2316#if 0
2317ProcessMessage::CrashReason
2318NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
2319{
2320 ProcessMessage::CrashReason reason;
2321 assert(info->si_signo == SIGFPE);
2322
2323 reason = ProcessMessage::eInvalidCrashReason;
2324
2325 switch (info->si_code)
2326 {
2327 default:
2328 assert(false && "unexpected si_code for SIGFPE");
2329 break;
2330 case FPE_INTDIV:
2331 reason = ProcessMessage::eIntegerDivideByZero;
2332 break;
2333 case FPE_INTOVF:
2334 reason = ProcessMessage::eIntegerOverflow;
2335 break;
2336 case FPE_FLTDIV:
2337 reason = ProcessMessage::eFloatDivideByZero;
2338 break;
2339 case FPE_FLTOVF:
2340 reason = ProcessMessage::eFloatOverflow;
2341 break;
2342 case FPE_FLTUND:
2343 reason = ProcessMessage::eFloatUnderflow;
2344 break;
2345 case FPE_FLTRES:
2346 reason = ProcessMessage::eFloatInexactResult;
2347 break;
2348 case FPE_FLTINV:
2349 reason = ProcessMessage::eFloatInvalidOperation;
2350 break;
2351 case FPE_FLTSUB:
2352 reason = ProcessMessage::eFloatSubscriptRange;
2353 break;
2354 }
2355
2356 return reason;
2357}
2358#endif
2359
2360#if 0
2361ProcessMessage::CrashReason
2362NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
2363{
2364 ProcessMessage::CrashReason reason;
2365 assert(info->si_signo == SIGBUS);
2366
2367 reason = ProcessMessage::eInvalidCrashReason;
2368
2369 switch (info->si_code)
2370 {
2371 default:
2372 assert(false && "unexpected si_code for SIGBUS");
2373 break;
2374 case BUS_ADRALN:
2375 reason = ProcessMessage::eIllegalAlignment;
2376 break;
2377 case BUS_ADRERR:
2378 reason = ProcessMessage::eIllegalAddress;
2379 break;
2380 case BUS_OBJERR:
2381 reason = ProcessMessage::eHardwareError;
2382 break;
2383 }
2384
2385 return reason;
2386}
2387#endif
2388
Todd Fialaaf245d12014-06-30 21:05:18 +00002389Error
Chaoren Lin26438d22015-05-05 17:50:53 +00002390NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
Todd Fialaaf245d12014-06-30 21:05:18 +00002391{
Pavel Labathdf7c6992015-06-17 18:38:49 +00002392 if (ProcessVmReadvSupported()) {
2393 // The process_vm_readv path is about 50 times faster than ptrace api. We want to use
2394 // this syscall if it is supported.
2395
2396 const ::pid_t pid = GetID();
2397
2398 struct iovec local_iov, remote_iov;
2399 local_iov.iov_base = buf;
2400 local_iov.iov_len = size;
2401 remote_iov.iov_base = reinterpret_cast<void *>(addr);
2402 remote_iov.iov_len = size;
2403
2404 bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
2405 const bool success = bytes_read == size;
2406
2407 Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2408 if (log)
2409 log->Printf ("NativeProcessLinux::%s using process_vm_readv to read %zd bytes from inferior address 0x%" PRIx64": %s",
2410 __FUNCTION__, size, addr, success ? "Success" : strerror(errno));
2411
2412 if (success)
2413 return Error();
2414 // else
2415 // the call failed for some reason, let's retry the read using ptrace api.
2416 }
2417
Pavel Labath19cbe962015-07-21 13:20:32 +00002418 unsigned char *dst = static_cast<unsigned char*>(buf);
2419 size_t remainder;
2420 long data;
2421
2422 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
2423 if (log)
2424 ProcessPOSIXLog::IncNestLevel();
2425 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
2426 log->Printf ("NativeProcessLinux::%s(%p, %p, %zd, _)", __FUNCTION__, (void*)addr, buf, size);
2427
2428 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
2429 {
2430 Error error = NativeProcessLinux::PtraceWrapper(PTRACE_PEEKDATA, GetID(), (void*)addr, nullptr, 0, &data);
2431 if (error.Fail())
2432 {
2433 if (log)
2434 ProcessPOSIXLog::DecNestLevel();
2435 return error;
2436 }
2437
2438 remainder = size - bytes_read;
2439 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
2440
2441 // Copy the data into our buffer
Mohit K. Bhakkadf6ef1872015-12-23 12:34:58 +00002442 memcpy(dst, &data, remainder);
Pavel Labath19cbe962015-07-21 13:20:32 +00002443
2444 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2445 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
2446 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2447 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
2448 {
2449 uintptr_t print_dst = 0;
2450 // Format bytes from data by moving into print_dst for log output
2451 for (unsigned i = 0; i < remainder; ++i)
2452 print_dst |= (((data >> i*8) & 0xFF) << i*8);
Pavel Labath79203992015-07-23 13:07:37 +00002453 log->Printf ("NativeProcessLinux::%s() [0x%" PRIx64 "]:0x%" PRIx64 " (0x%" PRIx64 ")",
2454 __FUNCTION__, addr, uint64_t(print_dst), uint64_t(data));
Pavel Labath19cbe962015-07-21 13:20:32 +00002455 }
2456 addr += k_ptrace_word_size;
2457 dst += k_ptrace_word_size;
2458 }
2459
2460 if (log)
2461 ProcessPOSIXLog::DecNestLevel();
2462 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00002463}
2464
2465Error
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002466NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
2467{
2468 Error error = ReadMemory(addr, buf, size, bytes_read);
2469 if (error.Fail()) return error;
2470 return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
2471}
2472
2473Error
2474NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written)
Todd Fialaaf245d12014-06-30 21:05:18 +00002475{
Pavel Labath19cbe962015-07-21 13:20:32 +00002476 const unsigned char *src = static_cast<const unsigned char*>(buf);
2477 size_t remainder;
2478 Error error;
2479
2480 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
2481 if (log)
2482 ProcessPOSIXLog::IncNestLevel();
2483 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
Pavel Labath79203992015-07-23 13:07:37 +00002484 log->Printf ("NativeProcessLinux::%s(0x%" PRIx64 ", %p, %zu)", __FUNCTION__, addr, buf, size);
Pavel Labath19cbe962015-07-21 13:20:32 +00002485
2486 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
2487 {
2488 remainder = size - bytes_written;
2489 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
2490
2491 if (remainder == k_ptrace_word_size)
2492 {
2493 unsigned long data = 0;
Mohit K. Bhakkadf6ef1872015-12-23 12:34:58 +00002494 memcpy(&data, src, k_ptrace_word_size);
Pavel Labath19cbe962015-07-21 13:20:32 +00002495
2496 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2497 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
2498 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2499 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
2500 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
2501 (void*)addr, *(const unsigned long*)src, data);
2502
2503 error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(), (void*)addr, (void*)data);
2504 if (error.Fail())
2505 {
2506 if (log)
2507 ProcessPOSIXLog::DecNestLevel();
2508 return error;
2509 }
2510 }
2511 else
2512 {
2513 unsigned char buff[8];
2514 size_t bytes_read;
2515 error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
2516 if (error.Fail())
2517 {
2518 if (log)
2519 ProcessPOSIXLog::DecNestLevel();
2520 return error;
2521 }
2522
2523 memcpy(buff, src, remainder);
2524
2525 size_t bytes_written_rec;
2526 error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
2527 if (error.Fail())
2528 {
2529 if (log)
2530 ProcessPOSIXLog::DecNestLevel();
2531 return error;
2532 }
2533
2534 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2535 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
2536 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2537 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
2538 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
2539 (void*)addr, *(const unsigned long*)src, *(unsigned long*)buff);
2540 }
2541
2542 addr += k_ptrace_word_size;
2543 src += k_ptrace_word_size;
2544 }
2545 if (log)
2546 ProcessPOSIXLog::DecNestLevel();
2547 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002548}
2549
Chaoren Lin97ccc292015-02-03 01:51:12 +00002550Error
Chaoren Lin97ccc292015-02-03 01:51:12 +00002551NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
Todd Fialaaf245d12014-06-30 21:05:18 +00002552{
Pavel Labath19cbe962015-07-21 13:20:32 +00002553 return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
Todd Fialaaf245d12014-06-30 21:05:18 +00002554}
2555
Chaoren Lin97ccc292015-02-03 01:51:12 +00002556Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002557NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
2558{
Pavel Labath19cbe962015-07-21 13:20:32 +00002559 return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
Todd Fialaaf245d12014-06-30 21:05:18 +00002560}
2561
Tamas Berghammerdb264a62015-03-31 09:52:22 +00002562Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002563NativeProcessLinux::Detach(lldb::tid_t tid)
2564{
Chaoren Lin97ccc292015-02-03 01:51:12 +00002565 if (tid == LLDB_INVALID_THREAD_ID)
2566 return Error();
2567
Pavel Labath19cbe962015-07-21 13:20:32 +00002568 return PtraceWrapper(PTRACE_DETACH, tid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002569}
2570
2571bool
Chaoren Lind3173f32015-05-29 19:52:29 +00002572NativeProcessLinux::DupDescriptor(const FileSpec &file_spec, int fd, int flags)
Todd Fialaaf245d12014-06-30 21:05:18 +00002573{
Chaoren Lind3173f32015-05-29 19:52:29 +00002574 int target_fd = open(file_spec.GetCString(), flags, 0666);
Todd Fialaaf245d12014-06-30 21:05:18 +00002575
2576 if (target_fd == -1)
2577 return false;
2578
Pavel Labath493c3a12015-02-04 10:36:57 +00002579 if (dup2(target_fd, fd) == -1)
2580 return false;
2581
2582 return (close(target_fd) == -1) ? false : true;
Todd Fialaaf245d12014-06-30 21:05:18 +00002583}
2584
Todd Fialaaf245d12014-06-30 21:05:18 +00002585bool
2586NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
2587{
2588 for (auto thread_sp : m_threads)
2589 {
2590 assert (thread_sp && "thread list should not contain NULL threads");
2591 if (thread_sp->GetID () == thread_id)
2592 {
2593 // We have this thread.
2594 return true;
2595 }
2596 }
2597
2598 // We don't have this thread.
2599 return false;
2600}
2601
Todd Fialaaf245d12014-06-30 21:05:18 +00002602bool
2603NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
2604{
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002605 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
2606
2607 if (log)
2608 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, thread_id);
2609
2610 bool found = false;
2611
Todd Fialaaf245d12014-06-30 21:05:18 +00002612 for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
2613 {
2614 if (*it && ((*it)->GetID () == thread_id))
2615 {
2616 m_threads.erase (it);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002617 found = true;
2618 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00002619 }
2620 }
2621
Pavel Labath0e1d7292015-08-20 09:06:12 +00002622 SignalIfAllThreadsStopped();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002623
2624 return found;
Todd Fialaaf245d12014-06-30 21:05:18 +00002625}
2626
Pavel Labathf9077782015-08-21 09:13:53 +00002627NativeThreadLinuxSP
Todd Fialaaf245d12014-06-30 21:05:18 +00002628NativeProcessLinux::AddThread (lldb::tid_t thread_id)
2629{
2630 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
2631
Todd Fialaaf245d12014-06-30 21:05:18 +00002632 if (log)
2633 {
2634 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
2635 __FUNCTION__,
2636 GetID (),
2637 thread_id);
2638 }
2639
2640 assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
2641
2642 // If this is the first thread, save it as the current thread
2643 if (m_threads.empty ())
2644 SetCurrentThreadID (thread_id);
2645
Pavel Labathf9077782015-08-21 09:13:53 +00002646 auto thread_sp = std::make_shared<NativeThreadLinux>(this, thread_id);
Todd Fialaaf245d12014-06-30 21:05:18 +00002647 m_threads.push_back (thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00002648 return thread_sp;
2649}
2650
Todd Fialaaf245d12014-06-30 21:05:18 +00002651Error
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002652NativeProcessLinux::FixupBreakpointPCAsNeeded(NativeThreadLinux &thread)
Todd Fialaaf245d12014-06-30 21:05:18 +00002653{
Todd Fiala75f47c32014-10-11 21:42:09 +00002654 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Todd Fialaaf245d12014-06-30 21:05:18 +00002655
2656 Error error;
2657
Todd Fialaaf245d12014-06-30 21:05:18 +00002658 // Find out the size of a breakpoint (might depend on where we are in the code).
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002659 NativeRegisterContextSP context_sp = thread.GetRegisterContext();
Todd Fialaaf245d12014-06-30 21:05:18 +00002660 if (!context_sp)
2661 {
2662 error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
2663 if (log)
2664 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
2665 return error;
2666 }
2667
2668 uint32_t breakpoint_size = 0;
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002669 error = GetSoftwareBreakpointPCOffset(breakpoint_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00002670 if (error.Fail ())
2671 {
2672 if (log)
2673 log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
2674 return error;
2675 }
2676 else
2677 {
2678 if (log)
2679 log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
2680 }
2681
2682 // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
Jaydeep Patilc60c9452015-06-23 03:37:08 +00002683 const lldb::addr_t initial_pc_addr = context_sp->GetPCfromBreakpointLocation ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002684 lldb::addr_t breakpoint_addr = initial_pc_addr;
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002685 if (breakpoint_size > 0)
Todd Fialaaf245d12014-06-30 21:05:18 +00002686 {
2687 // Do not allow breakpoint probe to wrap around.
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002688 if (breakpoint_addr >= breakpoint_size)
2689 breakpoint_addr -= breakpoint_size;
Todd Fialaaf245d12014-06-30 21:05:18 +00002690 }
2691
2692 // Check if we stopped because of a breakpoint.
2693 NativeBreakpointSP breakpoint_sp;
2694 error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
2695 if (!error.Success () || !breakpoint_sp)
2696 {
2697 // We didn't find one at a software probe location. Nothing to do.
2698 if (log)
2699 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
2700 return Error ();
2701 }
2702
2703 // If the breakpoint is not a software breakpoint, nothing to do.
2704 if (!breakpoint_sp->IsSoftwareBreakpoint ())
2705 {
2706 if (log)
2707 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
2708 return Error ();
2709 }
2710
2711 //
2712 // We have a software breakpoint and need to adjust the PC.
2713 //
2714
2715 // Sanity check.
2716 if (breakpoint_size == 0)
2717 {
2718 // Nothing to do! How did we get here?
2719 if (log)
2720 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);
2721 return Error ();
2722 }
2723
2724 // Change the program counter.
2725 if (log)
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002726 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": changing PC from 0x%" PRIx64 " to 0x%" PRIx64, __FUNCTION__, GetID(), thread.GetID(), initial_pc_addr, breakpoint_addr);
Todd Fialaaf245d12014-06-30 21:05:18 +00002727
2728 error = context_sp->SetPC (breakpoint_addr);
2729 if (error.Fail ())
2730 {
2731 if (log)
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002732 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": failed to set PC: %s", __FUNCTION__, GetID(), thread.GetID(), error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00002733 return error;
2734 }
2735
2736 return error;
2737}
Chaoren Linfa03ad22015-02-03 01:50:42 +00002738
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00002739Error
2740NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec)
2741{
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00002742 FileSpec module_file_spec(module_path, true);
2743
Pavel Labath162fb8e2015-07-23 14:47:33 +00002744 bool found = false;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00002745 file_spec.Clear();
Pavel Labath162fb8e2015-07-23 14:47:33 +00002746 ProcFileReader::ProcessLineByLine(GetID(), "maps",
2747 [&] (const std::string &line)
2748 {
2749 SmallVector<StringRef, 16> columns;
2750 StringRef(line).split(columns, " ", -1, false);
2751 if (columns.size() < 6)
2752 return true; // continue searching
2753
2754 FileSpec this_file_spec(columns[5].str().c_str(), false);
2755 if (this_file_spec.GetFilename() != module_file_spec.GetFilename())
2756 return true; // continue searching
2757
2758 file_spec = this_file_spec;
2759 found = true;
2760 return false; // we are done
2761 });
2762
2763 if (! found)
2764 return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
2765 module_file_spec.GetFilename().AsCString(), GetID());
2766
2767 return Error();
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00002768}
Pavel Labathc0765592015-05-06 10:46:34 +00002769
Pavel Labath5eb721e2015-05-07 08:30:31 +00002770Error
Tamas Berghammer783bfc82015-06-18 20:43:56 +00002771NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef& file_name, lldb::addr_t& load_addr)
2772{
2773 load_addr = LLDB_INVALID_ADDRESS;
2774 Error error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
2775 [&] (const std::string &line) -> bool
2776 {
2777 StringRef maps_row(line);
2778
2779 SmallVector<StringRef, 16> maps_columns;
2780 maps_row.split(maps_columns, StringRef(" "), -1, false);
2781
2782 if (maps_columns.size() < 6)
2783 {
2784 // Return true to continue reading the proc file
2785 return true;
2786 }
2787
2788 if (maps_columns[5] == file_name)
2789 {
2790 StringExtractor addr_extractor(maps_columns[0].str().c_str());
2791 load_addr = addr_extractor.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2792
2793 // Return false to stop reading the proc file further
2794 return false;
2795 }
2796
2797 // Return true to continue reading the proc file
2798 return true;
2799 });
2800 return error;
2801}
2802
Pavel Labathf9077782015-08-21 09:13:53 +00002803NativeThreadLinuxSP
2804NativeProcessLinux::GetThreadByID(lldb::tid_t tid)
2805{
2806 return std::static_pointer_cast<NativeThreadLinux>(NativeProcessProtocol::GetThreadByID(tid));
2807}
2808
Tamas Berghammer783bfc82015-06-18 20:43:56 +00002809Error
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002810NativeProcessLinux::ResumeThread(NativeThreadLinux &thread, lldb::StateType state, int signo)
Pavel Labathc0765592015-05-06 10:46:34 +00002811{
Pavel Labath5eb721e2015-05-07 08:30:31 +00002812 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002813
2814 if (log)
Pavel Labath0e1d7292015-08-20 09:06:12 +00002815 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")",
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002816 __FUNCTION__, thread.GetID());
Pavel Labath5eb721e2015-05-07 08:30:31 +00002817
Pavel Labathc0765592015-05-06 10:46:34 +00002818 // Before we do the resume below, first check if we have a pending
Pavel Labath108c3252015-05-12 09:03:18 +00002819 // stop notification that is currently waiting for
Pavel Labath0e1d7292015-08-20 09:06:12 +00002820 // all threads to stop. This is potentially a buggy situation since
Pavel Labathc0765592015-05-06 10:46:34 +00002821 // we're ostensibly waiting for threads to stop before we send out the
2822 // pending notification, and here we are resuming one before we send
2823 // out the pending stop notification.
Pavel Labath0e1d7292015-08-20 09:06:12 +00002824 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID && log)
Pavel Labathc0765592015-05-06 10:46:34 +00002825 {
Pavel Labathb9cc0c72015-08-24 09:22:04 +00002826 log->Printf("NativeProcessLinux::%s about to resume tid %" PRIu64 " per explicit request but we have a pending stop notification (tid %" PRIu64 ") that is actively waiting for this thread to stop. Valid sequence of events?", __FUNCTION__, thread.GetID(), m_pending_notification_tid);
Pavel Labathc0765592015-05-06 10:46:34 +00002827 }
2828
2829 // Request a resume. We expect this to be synchronous and the system
2830 // to reflect it is running after this completes.
Pavel Labath0e1d7292015-08-20 09:06:12 +00002831 switch (state)
Pavel Labathc0765592015-05-06 10:46:34 +00002832 {
Pavel Labath0e1d7292015-08-20 09:06:12 +00002833 case eStateRunning:
2834 {
Pavel Labath605b51b2016-02-23 13:56:30 +00002835 const auto resume_result = thread.Resume(signo);
Pavel Labath0e1d7292015-08-20 09:06:12 +00002836 if (resume_result.Success())
2837 SetState(eStateRunning, true);
2838 return resume_result;
Pavel Labathc0765592015-05-06 10:46:34 +00002839 }
Pavel Labath0e1d7292015-08-20 09:06:12 +00002840 case eStateStepping:
2841 {
Pavel Labath605b51b2016-02-23 13:56:30 +00002842 const auto step_result = thread.SingleStep(signo);
Pavel Labath0e1d7292015-08-20 09:06:12 +00002843 if (step_result.Success())
2844 SetState(eStateRunning, true);
2845 return step_result;
2846 }
2847 default:
2848 if (log)
2849 log->Printf("NativeProcessLinux::%s Unhandled state %s.",
2850 __FUNCTION__, StateAsCString(state));
2851 llvm_unreachable("Unhandled state for resume");
2852 }
Pavel Labathc0765592015-05-06 10:46:34 +00002853}
2854
2855//===----------------------------------------------------------------------===//
2856
2857void
Pavel Labath337f3eb2015-05-08 08:57:45 +00002858NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid)
Pavel Labathc0765592015-05-06 10:46:34 +00002859{
Pavel Labath5eb721e2015-05-07 08:30:31 +00002860 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00002861
Pavel Labath5eb721e2015-05-07 08:30:31 +00002862 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00002863 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00002864 log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ")",
Pavel Labathc0765592015-05-06 10:46:34 +00002865 __FUNCTION__, triggering_tid);
2866 }
2867
Pavel Labath0e1d7292015-08-20 09:06:12 +00002868 m_pending_notification_tid = triggering_tid;
2869
2870 // Request a stop for all the thread stops that need to be stopped
2871 // and are not already known to be stopped.
2872 for (const auto &thread_sp: m_threads)
2873 {
2874 if (StateIsRunningState(thread_sp->GetState()))
2875 static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
2876 }
2877
2878 SignalIfAllThreadsStopped();
Pavel Labathc0765592015-05-06 10:46:34 +00002879
Pavel Labath5eb721e2015-05-07 08:30:31 +00002880 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00002881 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00002882 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00002883 }
2884}
2885
2886void
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00002887NativeProcessLinux::SignalIfAllThreadsStopped()
Pavel Labathc0765592015-05-06 10:46:34 +00002888{
Pavel Labath0e1d7292015-08-20 09:06:12 +00002889 if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
2890 return; // No pending notification. Nothing to do.
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00002891
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00002892 for (const auto &thread_sp: m_threads)
Pavel Labathc0765592015-05-06 10:46:34 +00002893 {
Pavel Labath0e1d7292015-08-20 09:06:12 +00002894 if (StateIsRunningState(thread_sp->GetState()))
2895 return; // Some threads are still running. Don't signal yet.
Pavel Labathc0765592015-05-06 10:46:34 +00002896 }
2897
Pavel Labath0e1d7292015-08-20 09:06:12 +00002898 // We have a pending notification and all threads have stopped.
2899 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
Pavel Labathc0765592015-05-06 10:46:34 +00002900
Pavel Labath0e1d7292015-08-20 09:06:12 +00002901 // Clear any temporary breakpoints we used to implement software single stepping.
2902 for (const auto &thread_info: m_threads_stepping_with_breakpoint)
Pavel Labathc0765592015-05-06 10:46:34 +00002903 {
Pavel Labath0e1d7292015-08-20 09:06:12 +00002904 Error error = RemoveBreakpoint (thread_info.second);
2905 if (error.Fail())
2906 if (log)
2907 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " remove stepping breakpoint: %s",
2908 __FUNCTION__, thread_info.first, error.AsCString());
Pavel Labathc0765592015-05-06 10:46:34 +00002909 }
Pavel Labath0e1d7292015-08-20 09:06:12 +00002910 m_threads_stepping_with_breakpoint.clear();
Pavel Labathc0765592015-05-06 10:46:34 +00002911
Pavel Labath0e1d7292015-08-20 09:06:12 +00002912 // Notify the delegate about the stop
2913 SetCurrentThreadID(m_pending_notification_tid);
2914 SetState(StateType::eStateStopped, true);
2915 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
Pavel Labathc0765592015-05-06 10:46:34 +00002916}
2917
2918void
Pavel Labathf9077782015-08-21 09:13:53 +00002919NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread)
Pavel Labathc0765592015-05-06 10:46:34 +00002920{
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002921 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
2922
2923 if (log)
Pavel Labathf9077782015-08-21 09:13:53 +00002924 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, thread.GetID());
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002925
Pavel Labathf9077782015-08-21 09:13:53 +00002926 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID && StateIsRunningState(thread.GetState()))
Pavel Labathc0765592015-05-06 10:46:34 +00002927 {
2928 // We will need to wait for this new thread to stop as well before firing the
2929 // notification.
Pavel Labathf9077782015-08-21 09:13:53 +00002930 thread.RequestStop();
Pavel Labathc0765592015-05-06 10:46:34 +00002931 }
2932}
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002933
Pavel Labath19cbe962015-07-21 13:20:32 +00002934void
2935NativeProcessLinux::SigchldHandler()
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002936{
Pavel Labath19cbe962015-07-21 13:20:32 +00002937 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2938 // Process all pending waitpid notifications.
2939 while (true)
2940 {
2941 int status = -1;
2942 ::pid_t wait_pid = waitpid(-1, &status, __WALL | __WNOTHREAD | WNOHANG);
2943
2944 if (wait_pid == 0)
2945 break; // We are done.
2946
2947 if (wait_pid == -1)
2948 {
2949 if (errno == EINTR)
2950 continue;
2951
2952 Error error(errno, eErrorTypePOSIX);
2953 if (log)
2954 log->Printf("NativeProcessLinux::%s waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG) failed: %s",
2955 __FUNCTION__, error.AsCString());
2956 break;
2957 }
2958
2959 bool exited = false;
2960 int signal = 0;
2961 int exit_status = 0;
2962 const char *status_cstr = nullptr;
2963 if (WIFSTOPPED(status))
2964 {
2965 signal = WSTOPSIG(status);
2966 status_cstr = "STOPPED";
2967 }
2968 else if (WIFEXITED(status))
2969 {
2970 exit_status = WEXITSTATUS(status);
2971 status_cstr = "EXITED";
2972 exited = true;
2973 }
2974 else if (WIFSIGNALED(status))
2975 {
2976 signal = WTERMSIG(status);
2977 status_cstr = "SIGNALED";
Omair Javaiddee4a862015-08-19 10:44:16 +00002978 if (wait_pid == static_cast< ::pid_t>(GetID())) {
Pavel Labath19cbe962015-07-21 13:20:32 +00002979 exited = true;
2980 exit_status = -1;
2981 }
2982 }
2983 else
2984 status_cstr = "(\?\?\?)";
2985
2986 if (log)
2987 log->Printf("NativeProcessLinux::%s: waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG)"
2988 "=> pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
2989 __FUNCTION__, wait_pid, status, status_cstr, signal, exit_status);
2990
2991 MonitorCallback (wait_pid, exited, signal, exit_status);
2992 }
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002993}
2994
2995// Wrapper for ptrace to catch errors and log calls.
2996// 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 +00002997Error
2998NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, long *result)
Tamas Berghammer068f8a72015-05-26 11:58:52 +00002999{
Pavel Labath4a9babb2015-06-30 17:04:49 +00003000 Error error;
3001 long int ret;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003002
3003 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
3004
3005 PtraceDisplayBytes(req, data, data_size);
3006
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003007 errno = 0;
3008 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Pavel Labath4a9babb2015-06-30 17:04:49 +00003009 ret = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003010 else
Pavel Labath4a9babb2015-06-30 17:04:49 +00003011 ret = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003012
Pavel Labath4a9babb2015-06-30 17:04:49 +00003013 if (ret == -1)
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003014 error.SetErrorToErrno();
3015
Pavel Labath4a9babb2015-06-30 17:04:49 +00003016 if (result)
3017 *result = ret;
3018
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003019 if (log)
Pavel Labath4a9babb2015-06-30 17:04:49 +00003020 log->Printf("ptrace(%d, %" PRIu64 ", %p, %p, %zu)=%lX", req, pid, addr, data, data_size, ret);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003021
3022 PtraceDisplayBytes(req, data, data_size);
3023
3024 if (log && error.GetError() != 0)
3025 {
3026 const char* str;
3027 switch (error.GetError())
3028 {
3029 case ESRCH: str = "ESRCH"; break;
3030 case EINVAL: str = "EINVAL"; break;
3031 case EBUSY: str = "EBUSY"; break;
3032 case EPERM: str = "EPERM"; break;
3033 default: str = error.AsCString();
3034 }
3035 log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
3036 }
3037
Pavel Labath4a9babb2015-06-30 17:04:49 +00003038 return error;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003039}