blob: 7203da27640e9d93161170cffa5010b162700ea4 [file] [log] [blame]
Todd Fialaaf245d12014-06-30 21:05:18 +00001//===-- NativeProcessLinux.cpp -------------------------------- -*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Todd Fialaaf245d12014-06-30 21:05:18 +000010#include "NativeProcessLinux.h"
11
12// C Includes
13#include <errno.h>
Todd Fialaaf245d12014-06-30 21:05:18 +000014#include <string.h>
15#include <stdint.h>
16#include <unistd.h>
Todd Fialaaf245d12014-06-30 21:05:18 +000017
18// C++ Includes
19#include <fstream>
Pavel Labathdf7c6992015-06-17 18:38:49 +000020#include <mutex>
Pavel Labathc0765592015-05-06 10:46:34 +000021#include <sstream>
Todd Fialaaf245d12014-06-30 21:05:18 +000022#include <string>
Pavel Labath5b981ab2015-05-29 12:53:54 +000023#include <unordered_map>
Todd Fialaaf245d12014-06-30 21:05:18 +000024
25// Other libraries and framework includes
Tamas Berghammerd8c338d2015-04-15 09:47:02 +000026#include "lldb/Core/EmulateInstruction.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000027#include "lldb/Core/Error.h"
28#include "lldb/Core/Module.h"
Oleksiy Vyalov6edef202014-11-17 22:16:42 +000029#include "lldb/Core/ModuleSpec.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000030#include "lldb/Core/RegisterValue.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000031#include "lldb/Core/State.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000032#include "lldb/Host/common/NativeBreakpoint.h"
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +000033#include "lldb/Host/common/NativeRegisterContext.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000034#include "lldb/Host/Host.h"
Zachary Turner39de3112014-09-09 20:54:56 +000035#include "lldb/Host/ThreadLauncher.h"
Pavel Labath5b981ab2015-05-29 12:53:54 +000036#include "lldb/Target/Platform.h"
Zachary Turner90aff472015-03-03 23:36:51 +000037#include "lldb/Target/Process.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000038#include "lldb/Target/ProcessLaunchInfo.h"
Pavel Labath5b981ab2015-05-29 12:53:54 +000039#include "lldb/Target/Target.h"
Chaoren Linc16f5dc2015-03-19 23:28:10 +000040#include "lldb/Utility/LLDBAssert.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000041#include "lldb/Utility/PseudoTerminal.h"
Pavel Labathf805e192015-07-07 10:08:41 +000042#include "lldb/Utility/StringExtractor.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000043
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000044#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000045#include "NativeThreadLinux.h"
46#include "ProcFileReader.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000047#include "Procfs.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000048
Tamas Berghammerd8584872015-02-06 10:57:40 +000049// System includes - They have to be included after framework includes because they define some
50// macros which collide with variable names in other modules
51#include <linux/unistd.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000052#include <sys/socket.h>
Vince Harron8b335672015-05-12 01:10:56 +000053
Pavel Labathdf7c6992015-06-17 18:38:49 +000054#include <sys/syscall.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000055#include <sys/types.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000056#include <sys/user.h>
57#include <sys/wait.h>
58
Vince Harron8b335672015-05-12 01:10:56 +000059#include "lldb/Host/linux/Personality.h"
60#include "lldb/Host/linux/Ptrace.h"
61#include "lldb/Host/linux/Signalfd.h"
Pavel Labathdf7c6992015-06-17 18:38:49 +000062#include "lldb/Host/linux/Uio.h"
Vince Harron8b335672015-05-12 01:10:56 +000063#include "lldb/Host/android/Android.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000064
Todd Fiala0bce1b62014-08-17 00:10:50 +000065#define LLDB_PERSONALITY_GET_CURRENT_SETTINGS 0xffffffff
Todd Fialaaf245d12014-06-30 21:05:18 +000066
67// Support hardware breakpoints in case it has not been defined
68#ifndef TRAP_HWBKPT
69 #define TRAP_HWBKPT 4
70#endif
71
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000072using namespace lldb;
73using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000074using namespace lldb_private::process_linux;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000075using namespace llvm;
76
Todd Fialaaf245d12014-06-30 21:05:18 +000077// Private bits we only need internally.
Pavel Labathdf7c6992015-06-17 18:38:49 +000078
79static bool ProcessVmReadvSupported()
80{
81 static bool is_supported;
82 static std::once_flag flag;
83
84 std::call_once(flag, [] {
85 Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
86
87 uint32_t source = 0x47424742;
88 uint32_t dest = 0;
89
90 struct iovec local, remote;
91 remote.iov_base = &source;
92 local.iov_base = &dest;
93 remote.iov_len = local.iov_len = sizeof source;
94
95 // We shall try if cross-process-memory reads work by attempting to read a value from our own process.
96 ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
97 is_supported = (res == sizeof(source) && source == dest);
98 if (log)
99 {
100 if (is_supported)
101 log->Printf("%s: Detected kernel support for process_vm_readv syscall. Fast memory reads enabled.",
102 __FUNCTION__);
103 else
104 log->Printf("%s: syscall process_vm_readv failed (error: %s). Fast memory reads disabled.",
105 __FUNCTION__, strerror(errno));
106 }
107 });
108
109 return is_supported;
110}
111
Todd Fialaaf245d12014-06-30 21:05:18 +0000112namespace
113{
Todd Fialaaf245d12014-06-30 21:05:18 +0000114 Error
115 ResolveProcessArchitecture (lldb::pid_t pid, Platform &platform, ArchSpec &arch)
116 {
117 // Grab process info for the running process.
118 ProcessInstanceInfo process_info;
119 if (!platform.GetProcessInfo (pid, process_info))
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000120 return Error("failed to get process info");
Todd Fialaaf245d12014-06-30 21:05:18 +0000121
122 // Resolve the executable module.
123 ModuleSP exe_module_sp;
Chaoren Line56f6dc2015-03-01 04:31:16 +0000124 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Todd Fialaaf245d12014-06-30 21:05:18 +0000125 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths ());
126 Error error = platform.ResolveExecutable(
Oleksiy Vyalov54539332014-11-17 22:42:28 +0000127 exe_module_spec,
Todd Fialaaf245d12014-06-30 21:05:18 +0000128 exe_module_sp,
129 executable_search_paths.GetSize () ? &executable_search_paths : NULL);
130
131 if (!error.Success ())
132 return error;
133
134 // Check if we've got our architecture from the exe_module.
135 arch = exe_module_sp->GetArchitecture ();
136 if (arch.IsValid ())
137 return Error();
138 else
139 return Error("failed to retrieve a valid architecture from the exe module");
140 }
141
142 void
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000143 DisplayBytes (StreamString &s, void *bytes, uint32_t count)
Todd Fialaaf245d12014-06-30 21:05:18 +0000144 {
145 uint8_t *ptr = (uint8_t *)bytes;
146 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
147 for(uint32_t i=0; i<loop_count; i++)
148 {
149 s.Printf ("[%x]", *ptr);
150 ptr++;
151 }
152 }
153
154 void
155 PtraceDisplayBytes(int &req, void *data, size_t data_size)
156 {
157 StreamString buf;
158 Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
159 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
160
161 if (verbose_log)
162 {
163 switch(req)
164 {
165 case PTRACE_POKETEXT:
166 {
167 DisplayBytes(buf, &data, 8);
168 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
169 break;
170 }
171 case PTRACE_POKEDATA:
172 {
173 DisplayBytes(buf, &data, 8);
174 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
175 break;
176 }
177 case PTRACE_POKEUSER:
178 {
179 DisplayBytes(buf, &data, 8);
180 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
181 break;
182 }
183 case PTRACE_SETREGS:
184 {
185 DisplayBytes(buf, data, data_size);
186 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
187 break;
188 }
189 case PTRACE_SETFPREGS:
190 {
191 DisplayBytes(buf, data, data_size);
192 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
193 break;
194 }
195 case PTRACE_SETSIGINFO:
196 {
197 DisplayBytes(buf, data, sizeof(siginfo_t));
198 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
199 break;
200 }
201 case PTRACE_SETREGSET:
202 {
203 // Extract iov_base from data, which is a pointer to the struct IOVEC
204 DisplayBytes(buf, *(void **)data, data_size);
205 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
206 break;
207 }
208 default:
209 {
210 }
211 }
212 }
213 }
214
Pavel Labath19cbe962015-07-21 13:20:32 +0000215 static constexpr unsigned k_ptrace_word_size = sizeof(void*);
216 static_assert(sizeof(long) >= k_ptrace_word_size, "Size of long must be larger than ptrace word size");
Pavel Labath1107b5a2015-04-17 14:07:49 +0000217} // end of anonymous namespace
218
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000219// Simple helper function to ensure flags are enabled on the given file
220// descriptor.
221static Error
222EnsureFDFlags(int fd, int flags)
223{
224 Error error;
225
226 int status = fcntl(fd, F_GETFL);
227 if (status == -1)
228 {
229 error.SetErrorToErrno();
230 return error;
231 }
232
233 if (fcntl(fd, F_SETFL, status | flags) == -1)
234 {
235 error.SetErrorToErrno();
236 return error;
237 }
238
239 return error;
240}
241
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000242NativeProcessLinux::LaunchArgs::LaunchArgs(Module *module,
Todd Fialaaf245d12014-06-30 21:05:18 +0000243 char const **argv,
244 char const **envp,
Chaoren Lind3173f32015-05-29 19:52:29 +0000245 const FileSpec &stdin_file_spec,
246 const FileSpec &stdout_file_spec,
247 const FileSpec &stderr_file_spec,
248 const FileSpec &working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000249 const ProcessLaunchInfo &launch_info)
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000250 : m_module(module),
Todd Fialaaf245d12014-06-30 21:05:18 +0000251 m_argv(argv),
252 m_envp(envp),
Chaoren Lind3173f32015-05-29 19:52:29 +0000253 m_stdin_file_spec(stdin_file_spec),
254 m_stdout_file_spec(stdout_file_spec),
255 m_stderr_file_spec(stderr_file_spec),
Todd Fiala0bce1b62014-08-17 00:10:50 +0000256 m_working_dir(working_dir),
257 m_launch_info(launch_info)
258{
259}
Todd Fialaaf245d12014-06-30 21:05:18 +0000260
261NativeProcessLinux::LaunchArgs::~LaunchArgs()
262{ }
263
Todd Fialaaf245d12014-06-30 21:05:18 +0000264// -----------------------------------------------------------------------------
265// Public Static Methods
266// -----------------------------------------------------------------------------
267
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000268Error
Pavel Labathd5b310f2015-07-09 11:51:11 +0000269NativeProcessProtocol::Launch (
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000270 ProcessLaunchInfo &launch_info,
271 NativeProcessProtocol::NativeDelegate &native_delegate,
Pavel Labath19cbe962015-07-21 13:20:32 +0000272 MainLoop &mainloop,
Todd Fialaaf245d12014-06-30 21:05:18 +0000273 NativeProcessProtocolSP &native_process_sp)
274{
275 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
276
Pavel Labathd5b310f2015-07-09 11:51:11 +0000277 lldb::ModuleSP exe_module_sp;
278 PlatformSP platform_sp (Platform::GetHostPlatform ());
279 Error error = platform_sp->ResolveExecutable(
280 ModuleSpec(launch_info.GetExecutableFile(), launch_info.GetArchitecture()),
281 exe_module_sp,
282 nullptr);
283
284 if (! error.Success())
285 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000286
287 // Verify the working directory is valid if one was specified.
Chaoren Lind3173f32015-05-29 19:52:29 +0000288 FileSpec working_dir{launch_info.GetWorkingDirectory()};
289 if (working_dir &&
290 (!working_dir.ResolvePath() ||
291 working_dir.GetFileType() != FileSpec::eFileTypeDirectory))
Todd Fialaaf245d12014-06-30 21:05:18 +0000292 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000293 error.SetErrorStringWithFormat ("No such file or directory: %s",
294 working_dir.GetCString());
295 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000296 }
297
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000298 const FileAction *file_action;
Todd Fialaaf245d12014-06-30 21:05:18 +0000299
Chaoren Lind3173f32015-05-29 19:52:29 +0000300 // Default of empty will mean to use existing open file descriptors.
301 FileSpec stdin_file_spec{};
302 FileSpec stdout_file_spec{};
303 FileSpec stderr_file_spec{};
Todd Fialaaf245d12014-06-30 21:05:18 +0000304
305 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +0000306 if (file_action)
Chaoren Lind3173f32015-05-29 19:52:29 +0000307 stdin_file_spec = file_action->GetFileSpec();
Todd Fialaaf245d12014-06-30 21:05:18 +0000308
309 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +0000310 if (file_action)
Chaoren Lind3173f32015-05-29 19:52:29 +0000311 stdout_file_spec = file_action->GetFileSpec();
Todd Fialaaf245d12014-06-30 21:05:18 +0000312
313 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +0000314 if (file_action)
Chaoren Lind3173f32015-05-29 19:52:29 +0000315 stderr_file_spec = file_action->GetFileSpec();
Todd Fiala75f47c32014-10-11 21:42:09 +0000316
317 if (log)
318 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000319 if (stdin_file_spec)
320 log->Printf ("NativeProcessLinux::%s setting STDIN to '%s'",
321 __FUNCTION__, stdin_file_spec.GetCString());
Todd Fiala75f47c32014-10-11 21:42:09 +0000322 else
323 log->Printf ("NativeProcessLinux::%s leaving STDIN as is", __FUNCTION__);
324
Chaoren Lind3173f32015-05-29 19:52:29 +0000325 if (stdout_file_spec)
326 log->Printf ("NativeProcessLinux::%s setting STDOUT to '%s'",
327 __FUNCTION__, stdout_file_spec.GetCString());
Todd Fiala75f47c32014-10-11 21:42:09 +0000328 else
329 log->Printf ("NativeProcessLinux::%s leaving STDOUT as is", __FUNCTION__);
330
Chaoren Lind3173f32015-05-29 19:52:29 +0000331 if (stderr_file_spec)
332 log->Printf ("NativeProcessLinux::%s setting STDERR to '%s'",
333 __FUNCTION__, stderr_file_spec.GetCString());
Todd Fiala75f47c32014-10-11 21:42:09 +0000334 else
335 log->Printf ("NativeProcessLinux::%s leaving STDERR as is", __FUNCTION__);
336 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000337
338 // Create the NativeProcessLinux in launch mode.
339 native_process_sp.reset (new NativeProcessLinux ());
340
341 if (log)
342 {
343 int i = 0;
344 for (const char **args = launch_info.GetArguments ().GetConstArgumentVector (); *args; ++args, ++i)
345 {
346 log->Printf ("NativeProcessLinux::%s arg %d: \"%s\"", __FUNCTION__, i, *args ? *args : "nullptr");
347 ++i;
348 }
349 }
350
351 if (!native_process_sp->RegisterNativeDelegate (native_delegate))
352 {
353 native_process_sp.reset ();
354 error.SetErrorStringWithFormat ("failed to register the native delegate");
355 return error;
356 }
357
Tamas Berghammercb84eeb2015-03-17 15:05:31 +0000358 std::static_pointer_cast<NativeProcessLinux> (native_process_sp)->LaunchInferior (
Pavel Labath19cbe962015-07-21 13:20:32 +0000359 mainloop,
Pavel Labathd5b310f2015-07-09 11:51:11 +0000360 exe_module_sp.get(),
Todd Fialaaf245d12014-06-30 21:05:18 +0000361 launch_info.GetArguments ().GetConstArgumentVector (),
362 launch_info.GetEnvironmentEntries ().GetConstArgumentVector (),
Chaoren Lind3173f32015-05-29 19:52:29 +0000363 stdin_file_spec,
364 stdout_file_spec,
365 stderr_file_spec,
Todd Fialaaf245d12014-06-30 21:05:18 +0000366 working_dir,
Todd Fiala0bce1b62014-08-17 00:10:50 +0000367 launch_info,
Todd Fialaaf245d12014-06-30 21:05:18 +0000368 error);
369
370 if (error.Fail ())
371 {
372 native_process_sp.reset ();
373 if (log)
374 log->Printf ("NativeProcessLinux::%s failed to launch process: %s", __FUNCTION__, error.AsCString ());
375 return error;
376 }
377
378 launch_info.SetProcessID (native_process_sp->GetID ());
379
380 return error;
381}
382
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000383Error
Pavel Labathd5b310f2015-07-09 11:51:11 +0000384NativeProcessProtocol::Attach (
Todd Fialaaf245d12014-06-30 21:05:18 +0000385 lldb::pid_t pid,
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000386 NativeProcessProtocol::NativeDelegate &native_delegate,
Pavel Labath19cbe962015-07-21 13:20:32 +0000387 MainLoop &mainloop,
Todd Fialaaf245d12014-06-30 21:05:18 +0000388 NativeProcessProtocolSP &native_process_sp)
389{
390 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
391 if (log && log->GetMask ().Test (POSIX_LOG_VERBOSE))
392 log->Printf ("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
393
394 // Grab the current platform architecture. This should be Linux,
395 // since this code is only intended to run on a Linux host.
Greg Clayton615eb7e2014-09-19 20:11:50 +0000396 PlatformSP platform_sp (Platform::GetHostPlatform ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000397 if (!platform_sp)
398 return Error("failed to get a valid default platform");
399
400 // Retrieve the architecture for the running process.
401 ArchSpec process_arch;
402 Error error = ResolveProcessArchitecture (pid, *platform_sp.get (), process_arch);
403 if (!error.Success ())
404 return error;
405
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +0000406 std::shared_ptr<NativeProcessLinux> native_process_linux_sp (new NativeProcessLinux ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000407
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +0000408 if (!native_process_linux_sp->RegisterNativeDelegate (native_delegate))
Todd Fialaaf245d12014-06-30 21:05:18 +0000409 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000410 error.SetErrorStringWithFormat ("failed to register the native delegate");
411 return error;
412 }
413
Pavel Labath19cbe962015-07-21 13:20:32 +0000414 native_process_linux_sp->AttachToInferior (mainloop, pid, error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000415 if (!error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +0000416 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +0000417
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +0000418 native_process_sp = native_process_linux_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +0000419 return error;
420}
421
422// -----------------------------------------------------------------------------
423// Public Instance Methods
424// -----------------------------------------------------------------------------
425
426NativeProcessLinux::NativeProcessLinux () :
427 NativeProcessProtocol (LLDB_INVALID_PROCESS_ID),
428 m_arch (),
Todd Fialaaf245d12014-06-30 21:05:18 +0000429 m_supports_mem_region (eLazyBoolCalculate),
430 m_mem_region_cache (),
Pavel Labath8c8ff7a2015-05-11 10:03:10 +0000431 m_mem_region_cache_mutex ()
Todd Fialaaf245d12014-06-30 21:05:18 +0000432{
433}
434
Todd Fialaaf245d12014-06-30 21:05:18 +0000435void
436NativeProcessLinux::LaunchInferior (
Pavel Labath19cbe962015-07-21 13:20:32 +0000437 MainLoop &mainloop,
Todd Fialaaf245d12014-06-30 21:05:18 +0000438 Module *module,
439 const char *argv[],
440 const char *envp[],
Chaoren Lind3173f32015-05-29 19:52:29 +0000441 const FileSpec &stdin_file_spec,
442 const FileSpec &stdout_file_spec,
443 const FileSpec &stderr_file_spec,
444 const FileSpec &working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000445 const ProcessLaunchInfo &launch_info,
446 Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000447{
Pavel Labath19cbe962015-07-21 13:20:32 +0000448 m_sigchld_handle = mainloop.RegisterSignal(SIGCHLD,
449 [this] (MainLoopBase &) { SigchldHandler(); }, error);
450 if (! m_sigchld_handle)
451 return;
452
Todd Fialaaf245d12014-06-30 21:05:18 +0000453 if (module)
454 m_arch = module->GetArchitecture ();
455
Chaoren Linfa03ad22015-02-03 01:50:42 +0000456 SetState (eStateLaunching);
Todd Fialaaf245d12014-06-30 21:05:18 +0000457
458 std::unique_ptr<LaunchArgs> args(
Chaoren Lind3173f32015-05-29 19:52:29 +0000459 new LaunchArgs(module, argv, envp,
460 stdin_file_spec,
461 stdout_file_spec,
462 stderr_file_spec,
463 working_dir,
464 launch_info));
Todd Fialaaf245d12014-06-30 21:05:18 +0000465
Pavel Labath19cbe962015-07-21 13:20:32 +0000466 Launch(args.get(), error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000467}
468
469void
Pavel Labath19cbe962015-07-21 13:20:32 +0000470NativeProcessLinux::AttachToInferior (MainLoop &mainloop, lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000471{
472 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
473 if (log)
474 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
475
Pavel Labath19cbe962015-07-21 13:20:32 +0000476 m_sigchld_handle = mainloop.RegisterSignal(SIGCHLD,
477 [this] (MainLoopBase &) { SigchldHandler(); }, error);
478 if (! m_sigchld_handle)
479 return;
480
Todd Fialaaf245d12014-06-30 21:05:18 +0000481 // We can use the Host for everything except the ResolveExecutable portion.
Greg Clayton615eb7e2014-09-19 20:11:50 +0000482 PlatformSP platform_sp = Platform::GetHostPlatform ();
Todd Fialaaf245d12014-06-30 21:05:18 +0000483 if (!platform_sp)
484 {
485 if (log)
486 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): no default platform set", __FUNCTION__, pid);
487 error.SetErrorString ("no default platform available");
Shawn Best50d60be2014-11-11 00:28:52 +0000488 return;
Todd Fialaaf245d12014-06-30 21:05:18 +0000489 }
490
491 // Gather info about the process.
492 ProcessInstanceInfo process_info;
Shawn Best50d60be2014-11-11 00:28:52 +0000493 if (!platform_sp->GetProcessInfo (pid, process_info))
494 {
495 if (log)
496 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): failed to get process info", __FUNCTION__, pid);
497 error.SetErrorString ("failed to get process info");
498 return;
499 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000500
501 // Resolve the executable module
502 ModuleSP exe_module_sp;
503 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
Chaoren Line56f6dc2015-03-01 04:31:16 +0000504 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Oleksiy Vyalov6edef202014-11-17 22:16:42 +0000505 error = platform_sp->ResolveExecutable(exe_module_spec, exe_module_sp,
Zachary Turner13b18262014-08-20 16:42:51 +0000506 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
Todd Fialaaf245d12014-06-30 21:05:18 +0000507 if (!error.Success())
508 return;
509
510 // Set the architecture to the exe architecture.
511 m_arch = exe_module_sp->GetArchitecture();
512 if (log)
513 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
514
515 m_pid = pid;
516 SetState(eStateAttaching);
517
Pavel Labath19cbe962015-07-21 13:20:32 +0000518 Attach(pid, error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000519}
520
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000521::pid_t
522NativeProcessLinux::Launch(LaunchArgs *args, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000523{
Todd Fiala0bce1b62014-08-17 00:10:50 +0000524 assert (args && "null args");
Todd Fialaaf245d12014-06-30 21:05:18 +0000525
526 const char **argv = args->m_argv;
527 const char **envp = args->m_envp;
Chaoren Lind3173f32015-05-29 19:52:29 +0000528 const FileSpec working_dir = args->m_working_dir;
Todd Fialaaf245d12014-06-30 21:05:18 +0000529
530 lldb_utility::PseudoTerminal terminal;
531 const size_t err_len = 1024;
532 char err_str[err_len];
533 lldb::pid_t pid;
534 NativeThreadProtocolSP thread_sp;
535
536 lldb::ThreadSP inferior;
Todd Fialaaf245d12014-06-30 21:05:18 +0000537
538 // Propagate the environment if one is not supplied.
539 if (envp == NULL || envp[0] == NULL)
540 envp = const_cast<const char **>(environ);
541
542 if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
543 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000544 error.SetErrorToGenericError();
545 error.SetErrorStringWithFormat("Process fork failed: %s", err_str);
546 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000547 }
548
549 // Recognized child exit status codes.
550 enum {
551 ePtraceFailed = 1,
552 eDupStdinFailed,
553 eDupStdoutFailed,
554 eDupStderrFailed,
555 eChdirFailed,
556 eExecFailed,
557 eSetGidFailed
558 };
559
560 // Child process.
561 if (pid == 0)
562 {
Pavel Labathd2c4c9b2015-08-18 08:23:35 +0000563 // First, make sure we disable all logging. If we are logging to stdout, our logs can be
564 // mistaken for inferior output.
565 Log::DisableAllLogChannels(nullptr);
Todd Fiala75f47c32014-10-11 21:42:09 +0000566 // FIXME consider opening a pipe between parent/child and have this forked child
Pavel Labathd2c4c9b2015-08-18 08:23:35 +0000567 // send log info to parent re: launch status.
Todd Fialaaf245d12014-06-30 21:05:18 +0000568
Todd Fiala75f47c32014-10-11 21:42:09 +0000569 // Start tracing this child that is about to exec.
Pavel Labath4a9babb2015-06-30 17:04:49 +0000570 error = PtraceWrapper(PTRACE_TRACEME, 0);
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000571 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000572 exit(ePtraceFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +0000573
Pavel Labath493c3a12015-02-04 10:36:57 +0000574 // terminal has already dupped the tty descriptors to stdin/out/err.
575 // This closes original fd from which they were copied (and avoids
576 // leaking descriptors to the debugged process.
577 terminal.CloseSlaveFileDescriptor();
578
Todd Fialaaf245d12014-06-30 21:05:18 +0000579 // Do not inherit setgid powers.
Todd Fialaaf245d12014-06-30 21:05:18 +0000580 if (setgid(getgid()) != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +0000581 exit(eSetGidFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +0000582
583 // Attempt to have our own process group.
Todd Fialaaf245d12014-06-30 21:05:18 +0000584 if (setpgid(0, 0) != 0)
585 {
Todd Fiala75f47c32014-10-11 21:42:09 +0000586 // FIXME log that this failed. This is common.
Todd Fialaaf245d12014-06-30 21:05:18 +0000587 // Don't allow this to prevent an inferior exec.
588 }
589
590 // Dup file descriptors if needed.
Chaoren Lind3173f32015-05-29 19:52:29 +0000591 if (args->m_stdin_file_spec)
592 if (!DupDescriptor(args->m_stdin_file_spec, STDIN_FILENO, O_RDONLY))
Todd Fialaaf245d12014-06-30 21:05:18 +0000593 exit(eDupStdinFailed);
594
Chaoren Lind3173f32015-05-29 19:52:29 +0000595 if (args->m_stdout_file_spec)
596 if (!DupDescriptor(args->m_stdout_file_spec, STDOUT_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +0000597 exit(eDupStdoutFailed);
598
Chaoren Lind3173f32015-05-29 19:52:29 +0000599 if (args->m_stderr_file_spec)
600 if (!DupDescriptor(args->m_stderr_file_spec, STDERR_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +0000601 exit(eDupStderrFailed);
602
Chaoren Lin9cf4f2c2015-04-23 18:28:04 +0000603 // Close everything besides stdin, stdout, and stderr that has no file
604 // action to avoid leaking
605 for (int fd = 3; fd < sysconf(_SC_OPEN_MAX); ++fd)
606 if (!args->m_launch_info.GetFileActionForFD(fd))
607 close(fd);
608
Todd Fialaaf245d12014-06-30 21:05:18 +0000609 // Change working directory
Chaoren Lind3173f32015-05-29 19:52:29 +0000610 if (working_dir && 0 != ::chdir(working_dir.GetCString()))
Todd Fialaaf245d12014-06-30 21:05:18 +0000611 exit(eChdirFailed);
612
Todd Fiala0bce1b62014-08-17 00:10:50 +0000613 // Disable ASLR if requested.
614 if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR))
615 {
616 const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
617 if (old_personality == -1)
618 {
Todd Fiala75f47c32014-10-11 21:42:09 +0000619 // Can't retrieve Linux personality. Cannot disable ASLR.
Todd Fiala0bce1b62014-08-17 00:10:50 +0000620 }
621 else
622 {
623 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality);
624 if (new_personality == -1)
625 {
Todd Fiala75f47c32014-10-11 21:42:09 +0000626 // Disabling ASLR failed.
Todd Fiala0bce1b62014-08-17 00:10:50 +0000627 }
628 else
629 {
Todd Fiala75f47c32014-10-11 21:42:09 +0000630 // Disabling ASLR succeeded.
Todd Fiala0bce1b62014-08-17 00:10:50 +0000631 }
632 }
633 }
634
Todd Fiala75f47c32014-10-11 21:42:09 +0000635 // Execute. We should never return...
Todd Fialaaf245d12014-06-30 21:05:18 +0000636 execve(argv[0],
637 const_cast<char *const *>(argv),
638 const_cast<char *const *>(envp));
Todd Fiala75f47c32014-10-11 21:42:09 +0000639
640 // ...unless exec fails. In which case we definitely need to end the child here.
Todd Fialaaf245d12014-06-30 21:05:18 +0000641 exit(eExecFailed);
642 }
643
Todd Fiala75f47c32014-10-11 21:42:09 +0000644 //
645 // This is the parent code here.
646 //
647 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
648
Todd Fialaaf245d12014-06-30 21:05:18 +0000649 // Wait for the child process to trap on its call to execve.
650 ::pid_t wpid;
651 int status;
652 if ((wpid = waitpid(pid, &status, 0)) < 0)
653 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000654 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +0000655 if (log)
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000656 log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s",
657 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000658
659 // Mark the inferior as invalid.
660 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000661 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000662
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000663 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000664 }
665 else if (WIFEXITED(status))
666 {
667 // open, dup or execve likely failed for some reason.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000668 error.SetErrorToGenericError();
Todd Fialaaf245d12014-06-30 21:05:18 +0000669 switch (WEXITSTATUS(status))
670 {
671 case ePtraceFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000672 error.SetErrorString("Child ptrace failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000673 break;
674 case eDupStdinFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000675 error.SetErrorString("Child open stdin failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000676 break;
677 case eDupStdoutFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000678 error.SetErrorString("Child open stdout failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000679 break;
680 case eDupStderrFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000681 error.SetErrorString("Child open stderr failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000682 break;
683 case eChdirFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000684 error.SetErrorString("Child failed to set working directory.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000685 break;
686 case eExecFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000687 error.SetErrorString("Child exec failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000688 break;
689 case eSetGidFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000690 error.SetErrorString("Child setgid failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000691 break;
692 default:
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000693 error.SetErrorString("Child returned unknown exit status.");
Todd Fialaaf245d12014-06-30 21:05:18 +0000694 break;
695 }
696
697 if (log)
698 {
699 log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
700 __FUNCTION__,
701 WEXITSTATUS(status));
702 }
703
704 // Mark the inferior as invalid.
705 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000706 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000707
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000708 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000709 }
Todd Fiala202ecd22014-07-10 04:39:13 +0000710 assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
Todd Fialaaf245d12014-06-30 21:05:18 +0000711 "Could not sync with inferior process.");
712
713 if (log)
714 log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
715
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000716 error = SetDefaultPtraceOpts(pid);
717 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000718 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000719 if (log)
720 log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000721 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000722
723 // Mark the inferior as invalid.
724 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000725 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000726
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000727 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000728 }
729
730 // Release the master terminal descriptor and pass it off to the
731 // NativeProcessLinux instance. Similarly stash the inferior pid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000732 m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
733 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000734
735 // Set the terminal fd to be in non blocking mode (it simplifies the
736 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
737 // descriptor to read from).
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000738 error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
739 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000740 {
741 if (log)
742 log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000743 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000744
745 // Mark the inferior as invalid.
746 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000747 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000748
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000749 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000750 }
751
752 if (log)
753 log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
754
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000755 thread_sp = AddThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000756 assert (thread_sp && "AddThread() returned a nullptr thread");
Tamas Berghammercb84eeb2015-03-17 15:05:31 +0000757 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
Pavel Labath1dbc6c92015-05-12 08:35:33 +0000758 ThreadWasCreated(pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000759
760 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000761 SetCurrentThreadID (thread_sp->GetID ());
762 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +0000763
Todd Fialaaf245d12014-06-30 21:05:18 +0000764 if (log)
765 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000766 if (error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +0000767 {
768 log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
769 }
770 else
771 {
772 log->Printf ("NativeProcessLinux::%s inferior launching failed: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000773 __FUNCTION__, error.AsCString ());
774 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000775 }
776 }
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000777 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000778}
779
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000780::pid_t
781NativeProcessLinux::Attach(lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000782{
Todd Fialaaf245d12014-06-30 21:05:18 +0000783 lldb::ThreadSP inferior;
784 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
785
786 // Use a map to keep track of the threads which we have attached/need to attach.
787 Host::TidMap tids_to_attach;
788 if (pid <= 1)
789 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000790 error.SetErrorToGenericError();
791 error.SetErrorString("Attaching to process 1 is not allowed.");
792 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000793 }
794
795 while (Host::FindProcessThreads(pid, tids_to_attach))
796 {
797 for (Host::TidMap::iterator it = tids_to_attach.begin();
798 it != tids_to_attach.end();)
799 {
800 if (it->second == false)
801 {
802 lldb::tid_t tid = it->first;
803
804 // Attach to the requested process.
805 // An attach will cause the thread to stop with a SIGSTOP.
Pavel Labath4a9babb2015-06-30 17:04:49 +0000806 error = PtraceWrapper(PTRACE_ATTACH, tid);
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000807 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000808 {
809 // No such thread. The thread may have exited.
810 // More error handling may be needed.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000811 if (error.GetError() == ESRCH)
Todd Fialaaf245d12014-06-30 21:05:18 +0000812 {
813 it = tids_to_attach.erase(it);
814 continue;
815 }
816 else
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000817 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000818 }
819
820 int status;
821 // Need to use __WALL otherwise we receive an error with errno=ECHLD
822 // At this point we should have a thread stopped if waitpid succeeds.
823 if ((status = waitpid(tid, NULL, __WALL)) < 0)
824 {
825 // No such thread. The thread may have exited.
826 // More error handling may be needed.
827 if (errno == ESRCH)
828 {
829 it = tids_to_attach.erase(it);
830 continue;
831 }
832 else
833 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000834 error.SetErrorToErrno();
835 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000836 }
837 }
838
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000839 error = SetDefaultPtraceOpts(tid);
840 if (error.Fail())
841 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000842
843 if (log)
844 log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
845
846 it->second = true;
847
848 // Create the thread, mark it as stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000849 NativeThreadProtocolSP thread_sp (AddThread (static_cast<lldb::tid_t> (tid)));
Todd Fialaaf245d12014-06-30 21:05:18 +0000850 assert (thread_sp && "AddThread() returned a nullptr");
Chaoren Linfa03ad22015-02-03 01:50:42 +0000851
852 // This will notify this is a new thread and tell the system it is stopped.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +0000853 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
Pavel Labath1dbc6c92015-05-12 08:35:33 +0000854 ThreadWasCreated(tid);
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000855 SetCurrentThreadID (thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000856 }
857
858 // move the loop forward
859 ++it;
860 }
861 }
862
863 if (tids_to_attach.size() > 0)
864 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000865 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000866 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000867 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +0000868 }
869 else
870 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000871 error.SetErrorToGenericError();
872 error.SetErrorString("No such process.");
873 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +0000874 }
875
Pavel Labathbd7cbc52015-04-20 13:53:49 +0000876 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +0000877}
878
Chaoren Lin97ccc292015-02-03 01:51:12 +0000879Error
Todd Fialaaf245d12014-06-30 21:05:18 +0000880NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
881{
882 long ptrace_opts = 0;
883
884 // Have the child raise an event on exit. This is used to keep the child in
885 // limbo until it is destroyed.
886 ptrace_opts |= PTRACE_O_TRACEEXIT;
887
888 // Have the tracer trace threads which spawn in the inferior process.
889 // TODO: if we want to support tracing the inferiors' child, add the
890 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
891 ptrace_opts |= PTRACE_O_TRACECLONE;
892
893 // Have the tracer notify us before execve returns
894 // (needed to disable legacy SIGTRAP generation)
895 ptrace_opts |= PTRACE_O_TRACEEXEC;
896
Pavel Labath4a9babb2015-06-30 17:04:49 +0000897 return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts);
Todd Fialaaf245d12014-06-30 21:05:18 +0000898}
899
900static ExitType convert_pid_status_to_exit_type (int status)
901{
902 if (WIFEXITED (status))
903 return ExitType::eExitTypeExit;
904 else if (WIFSIGNALED (status))
905 return ExitType::eExitTypeSignal;
906 else if (WIFSTOPPED (status))
907 return ExitType::eExitTypeStop;
908 else
909 {
910 // We don't know what this is.
911 return ExitType::eExitTypeInvalid;
912 }
913}
914
915static int convert_pid_status_to_return_code (int status)
916{
917 if (WIFEXITED (status))
918 return WEXITSTATUS (status);
919 else if (WIFSIGNALED (status))
920 return WTERMSIG (status);
921 else if (WIFSTOPPED (status))
922 return WSTOPSIG (status);
923 else
924 {
925 // We don't know what this is.
926 return ExitType::eExitTypeInvalid;
927 }
928}
929
Pavel Labath1107b5a2015-04-17 14:07:49 +0000930// Handles all waitpid events from the inferior process.
931void
932NativeProcessLinux::MonitorCallback(lldb::pid_t pid,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000933 bool exited,
934 int signal,
935 int status)
Todd Fialaaf245d12014-06-30 21:05:18 +0000936{
937 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
938
Todd Fialaaf245d12014-06-30 21:05:18 +0000939 // Certain activities differ based on whether the pid is the tid of the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000940 const bool is_main_thread = (pid == GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +0000941
942 // Handle when the thread exits.
943 if (exited)
944 {
945 if (log)
Chaoren Lin86fd8e42015-02-03 01:51:15 +0000946 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 +0000947
948 // This is a thread that exited. Ensure we're not tracking it anymore.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000949 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +0000950
951 if (is_main_thread)
952 {
953 // We only set the exit status and notify the delegate if we haven't already set the process
954 // state to an exited state. We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
955 // for the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000956 const bool already_notified = (GetState() == StateType::eStateExited) || (GetState () == StateType::eStateCrashed);
Todd Fialaaf245d12014-06-30 21:05:18 +0000957 if (!already_notified)
958 {
959 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +0000960 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 +0000961 // The main thread exited. We're done monitoring. Report to delegate.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000962 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +0000963
964 // Notify delegate that our process has exited.
Pavel Labath1107b5a2015-04-17 14:07:49 +0000965 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +0000966 }
967 else
968 {
969 if (log)
970 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
971 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000972 }
973 else
974 {
975 // Do we want to report to the delegate in this case? I think not. If this was an orderly
976 // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
977 // and we would have done an all-stop then.
978 if (log)
979 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 +0000980 }
Pavel Labath1107b5a2015-04-17 14:07:49 +0000981 return;
Todd Fialaaf245d12014-06-30 21:05:18 +0000982 }
983
984 // Get details on the signal raised.
985 siginfo_t info;
Pavel Labath1107b5a2015-04-17 14:07:49 +0000986 const auto err = GetSignalInfo(pid, &info);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000987 if (err.Success())
Chaoren Linfa03ad22015-02-03 01:50:42 +0000988 {
989 // We have retrieved the signal info. Dispatch appropriately.
990 if (info.si_signo == SIGTRAP)
Pavel Labath1107b5a2015-04-17 14:07:49 +0000991 MonitorSIGTRAP(&info, pid);
Chaoren Linfa03ad22015-02-03 01:50:42 +0000992 else
Pavel Labath1107b5a2015-04-17 14:07:49 +0000993 MonitorSignal(&info, pid, exited);
Chaoren Linfa03ad22015-02-03 01:50:42 +0000994 }
995 else
Todd Fialaaf245d12014-06-30 21:05:18 +0000996 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000997 if (err.GetError() == EINVAL)
Todd Fialaaf245d12014-06-30 21:05:18 +0000998 {
Chaoren Linfa03ad22015-02-03 01:50:42 +0000999 // This is a group stop reception for this tid.
Pavel Labath39036ac2015-05-21 08:32:18 +00001000 // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the
1001 // tracee, triggering the group-stop mechanism. Normally receiving these would stop
1002 // the process, pending a SIGCONT. Simulating this state in a debugger is hard and is
1003 // generally not needed (one use case is debugging background task being managed by a
1004 // shell). For general use, it is sufficient to stop the process in a signal-delivery
1005 // stop which happens before the group stop. This done by MonitorSignal and works
1006 // correctly for all signals.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001007 if (log)
Pavel Labath39036ac2015-05-21 08:32:18 +00001008 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);
1009 Resume(pid, signal);
Todd Fialaaf245d12014-06-30 21:05:18 +00001010 }
1011 else
1012 {
1013 // ptrace(GETSIGINFO) failed (but not due to group-stop).
1014
1015 // A return value of ESRCH means the thread/process is no longer on the system,
1016 // so it was killed somehow outside of our control. Either way, we can't do anything
1017 // with it anymore.
1018
Todd Fialaaf245d12014-06-30 21:05:18 +00001019 // Stop tracking the metadata for the thread since it's entirely off the system now.
Pavel Labath1107b5a2015-04-17 14:07:49 +00001020 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001021
1022 if (log)
1023 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
Chaoren Lin97ccc292015-02-03 01:51:12 +00001024 __FUNCTION__, err.AsCString(), pid, signal, status, err.GetError() == ESRCH ? "thread/process killed" : "unknown reason", is_main_thread ? "is main thread" : "is not main thread", thread_found ? "thread metadata removed" : "thread metadata not found");
Todd Fialaaf245d12014-06-30 21:05:18 +00001025
1026 if (is_main_thread)
1027 {
1028 // Notify the delegate - our process is not available but appears to have been killed outside
1029 // our control. Is eStateExited the right exit state in this case?
Pavel Labath1107b5a2015-04-17 14:07:49 +00001030 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
1031 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001032 }
1033 else
1034 {
1035 // This thread was pulled out from underneath us. Anything to do here? Do we want to do an all stop?
1036 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +00001037 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 +00001038 }
1039 }
1040 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001041}
1042
1043void
Pavel Labath426bdf82015-04-28 07:51:52 +00001044NativeProcessLinux::WaitForNewThread(::pid_t tid)
1045{
1046 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1047
1048 NativeThreadProtocolSP new_thread_sp = GetThreadByID(tid);
1049
1050 if (new_thread_sp)
1051 {
1052 // We are already tracking the thread - we got the event on the new thread (see
1053 // MonitorSignal) before this one. We are done.
1054 return;
1055 }
1056
1057 // The thread is not tracked yet, let's wait for it to appear.
1058 int status = -1;
1059 ::pid_t wait_pid;
1060 do
1061 {
1062 if (log)
1063 log->Printf ("NativeProcessLinux::%s() received thread creation event for tid %" PRIu32 ". tid not tracked yet, waiting for thread to appear...", __FUNCTION__, tid);
1064 wait_pid = waitpid(tid, &status, __WALL);
1065 }
1066 while (wait_pid == -1 && errno == EINTR);
1067 // Since we are waiting on a specific tid, this must be the creation event. But let's do
1068 // some checks just in case.
1069 if (wait_pid != tid) {
1070 if (log)
1071 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime", __FUNCTION__, tid);
1072 // The only way I know of this could happen is if the whole process was
1073 // SIGKILLed in the mean time. In any case, we can't do anything about that now.
1074 return;
1075 }
1076 if (WIFEXITED(status))
1077 {
1078 if (log)
1079 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " returned an 'exited' event. Not tracking the thread.", __FUNCTION__, tid);
1080 // Also a very improbable event.
1081 return;
1082 }
1083
1084 siginfo_t info;
1085 Error error = GetSignalInfo(tid, &info);
1086 if (error.Fail())
1087 {
1088 if (log)
1089 log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime.", __FUNCTION__, tid);
1090 return;
1091 }
1092
1093 if (((info.si_pid != 0) || (info.si_code != SI_USER)) && log)
1094 {
1095 // We should be getting a thread creation signal here, but we received something
1096 // else. There isn't much we can do about it now, so we will just log that. Since the
1097 // thread is alive and we are receiving events from it, we shall pretend that it was
1098 // created properly.
1099 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);
1100 }
1101
1102 if (log)
1103 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 ": tracking new thread tid %" PRIu32,
1104 __FUNCTION__, GetID (), tid);
1105
1106 new_thread_sp = AddThread(tid);
1107 std::static_pointer_cast<NativeThreadLinux> (new_thread_sp)->SetRunning ();
1108 Resume (tid, LLDB_INVALID_SIGNAL_NUMBER);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001109 ThreadWasCreated(tid);
Pavel Labath426bdf82015-04-28 07:51:52 +00001110}
1111
1112void
Todd Fialaaf245d12014-06-30 21:05:18 +00001113NativeProcessLinux::MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid)
1114{
1115 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1116 const bool is_main_thread = (pid == GetID ());
1117
1118 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
1119 if (!info)
1120 return;
1121
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001122 Mutex::Locker locker (m_threads_mutex);
1123
Todd Fialaaf245d12014-06-30 21:05:18 +00001124 // See if we can find a thread for this signal.
1125 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
1126 if (!thread_sp)
1127 {
1128 if (log)
1129 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
1130 }
1131
1132 switch (info->si_code)
1133 {
1134 // TODO: these two cases are required if we want to support tracing of the inferiors' children. We'd need this to debug a monitor.
1135 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
1136 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
1137
1138 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
1139 {
Pavel Labath5fd24c62015-04-23 09:04:35 +00001140 // This is the notification on the parent thread which informs us of new thread
Pavel Labath426bdf82015-04-28 07:51:52 +00001141 // creation.
1142 // We don't want to do anything with the parent thread so we just resume it. In case we
1143 // want to implement "break on thread creation" functionality, we would need to stop
1144 // here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001145
Pavel Labath426bdf82015-04-28 07:51:52 +00001146 unsigned long event_message = 0;
1147 if (GetEventMessage (pid, &event_message).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001148 {
Pavel Labath426bdf82015-04-28 07:51:52 +00001149 if (log)
Chaoren Linfa03ad22015-02-03 01:50:42 +00001150 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " received thread creation event but GetEventMessage failed so we don't know the new tid", __FUNCTION__, pid);
Pavel Labath426bdf82015-04-28 07:51:52 +00001151 } else
1152 WaitForNewThread(event_message);
Todd Fialaaf245d12014-06-30 21:05:18 +00001153
Pavel Labath5fd24c62015-04-23 09:04:35 +00001154 Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001155 break;
1156 }
1157
1158 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
Todd Fialaa9882ce2014-08-28 15:46:54 +00001159 {
1160 NativeThreadProtocolSP main_thread_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001161 if (log)
1162 log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
Todd Fialaa9882ce2014-08-28 15:46:54 +00001163
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001164 // Exec clears any pending notifications.
1165 m_pending_notification_up.reset ();
Chaoren Linfa03ad22015-02-03 01:50:42 +00001166
1167 // Remove all but the main thread here. Linux fork creates a new process which only copies the main thread. Mutexes are in undefined state.
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001168 if (log)
1169 log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
1170
1171 for (auto thread_sp : m_threads)
Todd Fialaa9882ce2014-08-28 15:46:54 +00001172 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001173 const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
1174 if (is_main_thread)
Todd Fialaa9882ce2014-08-28 15:46:54 +00001175 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001176 main_thread_sp = thread_sp;
1177 if (log)
1178 log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00001179 }
1180 else
1181 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001182 // Tell thread coordinator this thread is dead.
Todd Fialaa9882ce2014-08-28 15:46:54 +00001183 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001184 log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00001185 }
1186 }
1187
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001188 m_threads.clear ();
1189
1190 if (main_thread_sp)
1191 {
1192 m_threads.push_back (main_thread_sp);
1193 SetCurrentThreadID (main_thread_sp->GetID ());
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001194 std::static_pointer_cast<NativeThreadLinux> (main_thread_sp)->SetStoppedByExec ();
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001195 }
1196 else
1197 {
1198 SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
1199 if (log)
1200 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
1201 }
1202
Chaoren Linfa03ad22015-02-03 01:50:42 +00001203 // Tell coordinator about about the "new" (since exec) stopped main thread.
1204 const lldb::tid_t main_thread_tid = GetID ();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001205 ThreadWasCreated(main_thread_tid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001206
1207 // NOTE: ideally these next statements would execute at the same time as the coordinator thread create was executed.
1208 // Consider a handler that can execute when that happens.
Todd Fialaa9882ce2014-08-28 15:46:54 +00001209 // Let our delegate know we have just exec'd.
1210 NotifyDidExec ();
1211
1212 // If we have a main thread, indicate we are stopped.
1213 assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001214
1215 // Let the process know we're stopped.
Pavel Labathed89c7f2015-05-06 12:22:37 +00001216 StopRunningThreads (pid);
Todd Fialaa9882ce2014-08-28 15:46:54 +00001217
Todd Fialaaf245d12014-06-30 21:05:18 +00001218 break;
Todd Fialaa9882ce2014-08-28 15:46:54 +00001219 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001220
1221 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
1222 {
1223 // The inferior process or one of its threads is about to exit.
Pavel Labath6e351632015-05-15 13:30:59 +00001224 // We don't want to do anything with the thread so we just resume it. In case we
1225 // want to implement "break on thread exit" functionality, we would need to stop
1226 // here.
Chaoren Linfa03ad22015-02-03 01:50:42 +00001227
Todd Fialaaf245d12014-06-30 21:05:18 +00001228 unsigned long data = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +00001229 if (GetEventMessage(pid, &data).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001230 data = -1;
1231
1232 if (log)
1233 {
1234 log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
1235 __FUNCTION__,
1236 data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
1237 pid,
1238 is_main_thread ? "is main thread" : "not main thread");
1239 }
1240
Todd Fialaaf245d12014-06-30 21:05:18 +00001241 if (is_main_thread)
1242 {
1243 SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00001244 }
Todd Fiala75f47c32014-10-11 21:42:09 +00001245
Pavel Labath6e351632015-05-15 13:30:59 +00001246 Resume(pid, LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001247
1248 break;
1249 }
1250
1251 case 0:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001252 case TRAP_TRACE: // We receive this on single stepping.
1253 case TRAP_HWBKPT: // We receive this on watchpoint hit
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001254 if (thread_sp)
1255 {
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001256 // If a watchpoint was hit, report it
1257 uint32_t wp_index;
Omair Javaidea8c25a802015-05-15 06:29:58 +00001258 Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index, (lldb::addr_t)info->si_addr);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001259 if (error.Fail() && log)
1260 log->Printf("NativeProcessLinux::%s() "
1261 "received error while checking for watchpoint hits, "
1262 "pid = %" PRIu64 " error = %s",
1263 __FUNCTION__, pid, error.AsCString());
1264 if (wp_index != LLDB_INVALID_INDEX32)
1265 {
1266 MonitorWatchpoint(pid, thread_sp, wp_index);
1267 break;
1268 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001269 }
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001270 // Otherwise, report step over
1271 MonitorTrace(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00001272 break;
1273
1274 case SI_KERNEL:
Mohit K. Bhakkad35799962015-06-18 04:53:18 +00001275#if defined __mips__
1276 // For mips there is no special signal for watchpoint
1277 // So we check for watchpoint in kernel trap
1278 if (thread_sp)
1279 {
1280 // If a watchpoint was hit, report it
1281 uint32_t wp_index;
Jaydeep Patilc60c9452015-06-23 03:37:08 +00001282 Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index, LLDB_INVALID_ADDRESS);
Mohit K. Bhakkad35799962015-06-18 04:53:18 +00001283 if (error.Fail() && log)
1284 log->Printf("NativeProcessLinux::%s() "
1285 "received error while checking for watchpoint hits, "
1286 "pid = %" PRIu64 " error = %s",
1287 __FUNCTION__, pid, error.AsCString());
1288 if (wp_index != LLDB_INVALID_INDEX32)
1289 {
1290 MonitorWatchpoint(pid, thread_sp, wp_index);
1291 break;
1292 }
1293 }
1294 // NO BREAK
1295#endif
Todd Fialaaf245d12014-06-30 21:05:18 +00001296 case TRAP_BRKPT:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001297 MonitorBreakpoint(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00001298 break;
1299
1300 case SIGTRAP:
1301 case (SIGTRAP | 0x80):
1302 if (log)
Chaoren Linfa03ad22015-02-03 01:50:42 +00001303 log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), pid);
1304
Todd Fialaaf245d12014-06-30 21:05:18 +00001305 // Ignore these signals until we know more about them.
Pavel Labath6e351632015-05-15 13:30:59 +00001306 Resume(pid, LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00001307 break;
1308
1309 default:
1310 assert(false && "Unexpected SIGTRAP code!");
1311 if (log)
Pavel Labath6e351632015-05-15 13:30:59 +00001312 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 "tid %" PRIu64 " received unhandled SIGTRAP code: 0x%d",
1313 __FUNCTION__, GetID (), pid, info->si_code);
Todd Fialaaf245d12014-06-30 21:05:18 +00001314 break;
1315
1316 }
1317}
1318
1319void
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001320NativeProcessLinux::MonitorTrace(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
1321{
1322 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1323 if (log)
1324 log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)",
1325 __FUNCTION__, pid);
1326
1327 if (thread_sp)
1328 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
1329
1330 // This thread is currently stopped.
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001331 ThreadDidStop(pid, false);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001332
1333 // Here we don't have to request the rest of the threads to stop or request a deferred stop.
1334 // This would have already happened at the time the Resume() with step operation was signaled.
1335 // At this point, we just need to say we stopped, and the deferred notifcation will fire off
1336 // once all running threads have checked in as stopped.
1337 SetCurrentThreadID(pid);
1338 // Tell the process we have a stop (from software breakpoint).
Pavel Labathed89c7f2015-05-06 12:22:37 +00001339 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001340}
1341
1342void
1343NativeProcessLinux::MonitorBreakpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
1344{
1345 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
1346 if (log)
1347 log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
1348 __FUNCTION__, pid);
1349
1350 // This thread is currently stopped.
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001351 ThreadDidStop(pid, false);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001352
1353 // Mark the thread as stopped at breakpoint.
1354 if (thread_sp)
1355 {
1356 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByBreakpoint();
1357 Error error = FixupBreakpointPCAsNeeded(thread_sp);
1358 if (error.Fail())
1359 if (log)
1360 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
1361 __FUNCTION__, pid, error.AsCString());
Tamas Berghammerd8c338d2015-04-15 09:47:02 +00001362
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00001363 if (m_threads_stepping_with_breakpoint.find(pid) != m_threads_stepping_with_breakpoint.end())
Tamas Berghammerd8c338d2015-04-15 09:47:02 +00001364 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001365 }
1366 else
1367 if (log)
1368 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 ": "
1369 "warning, cannot process software breakpoint since no thread metadata",
1370 __FUNCTION__, pid);
1371
1372
1373 // We need to tell all other running threads before we notify the delegate about this stop.
Pavel Labathed89c7f2015-05-06 12:22:37 +00001374 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001375}
1376
1377void
1378NativeProcessLinux::MonitorWatchpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp, uint32_t wp_index)
1379{
1380 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
1381 if (log)
1382 log->Printf("NativeProcessLinux::%s() received watchpoint event, "
1383 "pid = %" PRIu64 ", wp_index = %" PRIu32,
1384 __FUNCTION__, pid, wp_index);
1385
1386 // This thread is currently stopped.
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001387 ThreadDidStop(pid, false);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001388
1389 // Mark the thread as stopped at watchpoint.
1390 // The address is at (lldb::addr_t)info->si_addr if we need it.
1391 lldbassert(thread_sp && "thread_sp cannot be NULL");
1392 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByWatchpoint(wp_index);
1393
1394 // We need to tell all other running threads before we notify the delegate about this stop.
Pavel Labathed89c7f2015-05-06 12:22:37 +00001395 StopRunningThreads(pid);
Chaoren Linc16f5dc2015-03-19 23:28:10 +00001396}
1397
1398void
Todd Fialaaf245d12014-06-30 21:05:18 +00001399NativeProcessLinux::MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited)
1400{
Todd Fiala511e5cd2014-09-11 23:29:14 +00001401 assert (info && "null info");
1402 if (!info)
1403 return;
1404
1405 const int signo = info->si_signo;
1406 const bool is_from_llgs = info->si_pid == getpid ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001407
1408 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1409
1410 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1411 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1412 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
1413 //
1414 // IOW, user generated signals never generate what we consider to be a
1415 // "crash".
1416 //
1417 // Similarly, ACK signals generated by this monitor.
1418
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001419 Mutex::Locker locker (m_threads_mutex);
1420
Todd Fialaaf245d12014-06-30 21:05:18 +00001421 // See if we can find a thread for this signal.
1422 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
1423 if (!thread_sp)
1424 {
1425 if (log)
1426 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
1427 }
1428
1429 // Handle the signal.
1430 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
1431 {
1432 if (log)
1433 log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
1434 __FUNCTION__,
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001435 Host::GetSignalAsCString(signo),
Todd Fialaaf245d12014-06-30 21:05:18 +00001436 signo,
1437 (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
1438 info->si_pid,
Todd Fiala511e5cd2014-09-11 23:29:14 +00001439 is_from_llgs ? "from llgs" : "not from llgs",
Todd Fialaaf245d12014-06-30 21:05:18 +00001440 pid);
Todd Fiala58a2f662014-08-12 17:02:07 +00001441 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001442
Todd Fiala58a2f662014-08-12 17:02:07 +00001443 // Check for new thread notification.
1444 if ((info->si_pid == 0) && (info->si_code == SI_USER))
1445 {
Pavel Labath426bdf82015-04-28 07:51:52 +00001446 // A new thread creation is being signaled. This is one of two parts that come in
1447 // a non-deterministic order. This code handles the case where the new thread event comes
1448 // before the event on the parent thread. For the opposite case see code in
1449 // MonitorSIGTRAP.
Todd Fiala58a2f662014-08-12 17:02:07 +00001450 if (log)
1451 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": new thread notification",
1452 __FUNCTION__, GetID (), pid);
1453
Pavel Labath5fd24c62015-04-23 09:04:35 +00001454 thread_sp = AddThread(pid);
1455 assert (thread_sp.get() && "failed to create the tracking data for newly created inferior thread");
1456 // We can now resume the newly created thread.
1457 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
1458 Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001459 ThreadWasCreated(pid);
Todd Fiala58a2f662014-08-12 17:02:07 +00001460 // Done handling.
1461 return;
1462 }
1463
1464 // Check for thread stop notification.
Todd Fiala511e5cd2014-09-11 23:29:14 +00001465 if (is_from_llgs && (info->si_code == SI_TKILL) && (signo == SIGSTOP))
Todd Fiala58a2f662014-08-12 17:02:07 +00001466 {
1467 // This is a tgkill()-based stop.
1468 if (thread_sp)
1469 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00001470 if (log)
1471 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
1472 __FUNCTION__,
1473 GetID (),
1474 pid);
1475
Chaoren Linaab58632015-02-03 01:50:57 +00001476 // Check that we're not already marked with a stop reason.
1477 // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
1478 // the kernel signaled us with the thread stopping which we handled and marked as stopped,
1479 // and that, without an intervening resume, we received another stop. It is more likely
1480 // that we are missing the marking of a run state somewhere if we find that the thread was
1481 // marked as stopped.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001482 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
1483 assert (linux_thread_sp && "linux_thread_sp is null!");
Chaoren Linaab58632015-02-03 01:50:57 +00001484
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001485 const StateType thread_state = linux_thread_sp->GetState ();
Chaoren Linaab58632015-02-03 01:50:57 +00001486 if (!StateIsStoppedState (thread_state, false))
1487 {
Pavel Labathed89c7f2015-05-06 12:22:37 +00001488 // An inferior thread has stopped because of a SIGSTOP we have sent it.
1489 // Generally, these are not important stops and we don't want to report them as
1490 // they are just used to stop other threads when one thread (the one with the
1491 // *real* stop reason) hits a breakpoint (watchpoint, etc...). However, in the
1492 // case of an asynchronous Interrupt(), this *is* the real stop reason, so we
1493 // leave the signal intact if this is the thread that was chosen as the
1494 // triggering thread.
1495 if (m_pending_notification_up && m_pending_notification_up->triggering_tid == pid)
Pavel Labathc4e25c92015-05-29 10:13:03 +00001496 linux_thread_sp->SetStoppedBySignal(SIGSTOP, info);
Pavel Labathed89c7f2015-05-06 12:22:37 +00001497 else
Pavel Labath05569f62015-07-23 09:09:29 +00001498 linux_thread_sp->SetStoppedWithNoReason();
Pavel Labathed89c7f2015-05-06 12:22:37 +00001499
Chaoren Linaab58632015-02-03 01:50:57 +00001500 SetCurrentThreadID (thread_sp->GetID ());
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001501 ThreadDidStop (thread_sp->GetID (), true);
Chaoren Linaab58632015-02-03 01:50:57 +00001502 }
1503 else
1504 {
1505 if (log)
1506 {
1507 // Retrieve the signal name if the thread was stopped by a signal.
1508 int stop_signo = 0;
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001509 const bool stopped_by_signal = linux_thread_sp->IsStopped (&stop_signo);
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001510 const char *signal_name = stopped_by_signal ? Host::GetSignalAsCString(stop_signo) : "<not stopped by signal>";
Chaoren Linaab58632015-02-03 01:50:57 +00001511 if (!signal_name)
1512 signal_name = "<no-signal-name>";
1513
1514 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",
1515 __FUNCTION__,
1516 GetID (),
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001517 linux_thread_sp->GetID (),
Chaoren Linaab58632015-02-03 01:50:57 +00001518 StateAsCString (thread_state),
1519 stop_signo,
1520 signal_name);
1521 }
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001522 ThreadDidStop (thread_sp->GetID (), false);
Chaoren Linaab58632015-02-03 01:50:57 +00001523 }
Todd Fiala58a2f662014-08-12 17:02:07 +00001524 }
1525
1526 // Done handling.
Todd Fialaaf245d12014-06-30 21:05:18 +00001527 return;
1528 }
1529
1530 if (log)
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001531 log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, Host::GetSignalAsCString(signo));
Todd Fialaaf245d12014-06-30 21:05:18 +00001532
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001533 // This thread is stopped.
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001534 ThreadDidStop (pid, false);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001535
Pavel Labathc4e25c92015-05-29 10:13:03 +00001536 if (thread_sp)
1537 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal(signo, info);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00001538
1539 // Send a stop to the debugger after we get all other threads to stop.
Pavel Labathed89c7f2015-05-06 12:22:37 +00001540 StopRunningThreads (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001541}
1542
Tamas Berghammere7708682015-04-22 10:00:23 +00001543namespace {
1544
1545struct EmulatorBaton
1546{
1547 NativeProcessLinux* m_process;
1548 NativeRegisterContext* m_reg_context;
Tamas Berghammere7708682015-04-22 10:00:23 +00001549
Pavel Labath6648fcc2015-04-27 09:21:14 +00001550 // eRegisterKindDWARF -> RegsiterValue
1551 std::unordered_map<uint32_t, RegisterValue> m_register_values;
1552
1553 EmulatorBaton(NativeProcessLinux* process, NativeRegisterContext* reg_context) :
Tamas Berghammere7708682015-04-22 10:00:23 +00001554 m_process(process), m_reg_context(reg_context) {}
1555};
1556
1557} // anonymous namespace
1558
1559static size_t
1560ReadMemoryCallback (EmulateInstruction *instruction,
1561 void *baton,
1562 const EmulateInstruction::Context &context,
1563 lldb::addr_t addr,
1564 void *dst,
1565 size_t length)
1566{
1567 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
1568
Chaoren Lin3eb4b452015-04-29 17:24:48 +00001569 size_t bytes_read;
Tamas Berghammere7708682015-04-22 10:00:23 +00001570 emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
1571 return bytes_read;
1572}
1573
1574static bool
1575ReadRegisterCallback (EmulateInstruction *instruction,
1576 void *baton,
1577 const RegisterInfo *reg_info,
1578 RegisterValue &reg_value)
1579{
1580 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
1581
Pavel Labath6648fcc2015-04-27 09:21:14 +00001582 auto it = emulator_baton->m_register_values.find(reg_info->kinds[eRegisterKindDWARF]);
1583 if (it != emulator_baton->m_register_values.end())
1584 {
1585 reg_value = it->second;
1586 return true;
1587 }
1588
Tamas Berghammere7708682015-04-22 10:00:23 +00001589 // The emulator only fill in the dwarf regsiter numbers (and in some case
1590 // the generic register numbers). Get the full register info from the
1591 // register context based on the dwarf register numbers.
1592 const RegisterInfo* full_reg_info = emulator_baton->m_reg_context->GetRegisterInfo(
1593 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
1594
1595 Error error = emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
Pavel Labath6648fcc2015-04-27 09:21:14 +00001596 if (error.Success())
Pavel Labath6648fcc2015-04-27 09:21:14 +00001597 return true;
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001598
Pavel Labath6648fcc2015-04-27 09:21:14 +00001599 return false;
Tamas Berghammere7708682015-04-22 10:00:23 +00001600}
1601
1602static bool
1603WriteRegisterCallback (EmulateInstruction *instruction,
1604 void *baton,
1605 const EmulateInstruction::Context &context,
1606 const RegisterInfo *reg_info,
1607 const RegisterValue &reg_value)
1608{
1609 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
Pavel Labath6648fcc2015-04-27 09:21:14 +00001610 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = reg_value;
Tamas Berghammere7708682015-04-22 10:00:23 +00001611 return true;
1612}
1613
1614static size_t
1615WriteMemoryCallback (EmulateInstruction *instruction,
1616 void *baton,
1617 const EmulateInstruction::Context &context,
1618 lldb::addr_t addr,
1619 const void *dst,
1620 size_t length)
1621{
1622 return length;
1623}
1624
1625static lldb::addr_t
1626ReadFlags (NativeRegisterContext* regsiter_context)
1627{
1628 const RegisterInfo* flags_info = regsiter_context->GetRegisterInfo(
1629 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1630 return regsiter_context->ReadRegisterAsUnsigned(flags_info, LLDB_INVALID_ADDRESS);
1631}
1632
1633Error
1634NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadProtocolSP thread_sp)
1635{
1636 Error error;
1637 NativeRegisterContextSP register_context_sp = thread_sp->GetRegisterContext();
1638
1639 std::unique_ptr<EmulateInstruction> emulator_ap(
1640 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, nullptr));
1641
1642 if (emulator_ap == nullptr)
1643 return Error("Instruction emulator not found!");
1644
1645 EmulatorBaton baton(this, register_context_sp.get());
1646 emulator_ap->SetBaton(&baton);
1647 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
1648 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
1649 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
1650 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
1651
1652 if (!emulator_ap->ReadInstruction())
1653 return Error("Read instruction failed!");
1654
Pavel Labath6648fcc2015-04-27 09:21:14 +00001655 bool emulation_result = emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
1656
1657 const RegisterInfo* reg_info_pc = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1658 const RegisterInfo* reg_info_flags = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1659
1660 auto pc_it = baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1661 auto flags_it = baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
1662
Tamas Berghammere7708682015-04-22 10:00:23 +00001663 lldb::addr_t next_pc;
1664 lldb::addr_t next_flags;
Pavel Labath6648fcc2015-04-27 09:21:14 +00001665 if (emulation_result)
Tamas Berghammere7708682015-04-22 10:00:23 +00001666 {
Pavel Labath6648fcc2015-04-27 09:21:14 +00001667 assert(pc_it != baton.m_register_values.end() && "Emulation was successfull but PC wasn't updated");
1668 next_pc = pc_it->second.GetAsUInt64();
1669
1670 if (flags_it != baton.m_register_values.end())
1671 next_flags = flags_it->second.GetAsUInt64();
Tamas Berghammere7708682015-04-22 10:00:23 +00001672 else
1673 next_flags = ReadFlags (register_context_sp.get());
1674 }
Pavel Labath6648fcc2015-04-27 09:21:14 +00001675 else if (pc_it == baton.m_register_values.end())
Tamas Berghammere7708682015-04-22 10:00:23 +00001676 {
1677 // Emulate instruction failed and it haven't changed PC. Advance PC
1678 // with the size of the current opcode because the emulation of all
1679 // PC modifying instruction should be successful. The failure most
1680 // likely caused by a not supported instruction which don't modify PC.
1681 next_pc = register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
1682 next_flags = ReadFlags (register_context_sp.get());
1683 }
1684 else
1685 {
1686 // The instruction emulation failed after it modified the PC. It is an
1687 // unknown error where we can't continue because the next instruction is
1688 // modifying the PC but we don't know how.
1689 return Error ("Instruction emulation failed unexpectedly.");
1690 }
1691
1692 if (m_arch.GetMachine() == llvm::Triple::arm)
1693 {
1694 if (next_flags & 0x20)
1695 {
1696 // Thumb mode
1697 error = SetSoftwareBreakpoint(next_pc, 2);
1698 }
1699 else
1700 {
1701 // Arm mode
1702 error = SetSoftwareBreakpoint(next_pc, 4);
1703 }
1704 }
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001705 else if (m_arch.GetMachine() == llvm::Triple::mips64
Jaydeep Patilc60c9452015-06-23 03:37:08 +00001706 || m_arch.GetMachine() == llvm::Triple::mips64el
1707 || m_arch.GetMachine() == llvm::Triple::mips
1708 || m_arch.GetMachine() == llvm::Triple::mipsel)
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001709 error = SetSoftwareBreakpoint(next_pc, 4);
Tamas Berghammere7708682015-04-22 10:00:23 +00001710 else
1711 {
1712 // No size hint is given for the next breakpoint
1713 error = SetSoftwareBreakpoint(next_pc, 0);
1714 }
1715
Tamas Berghammere7708682015-04-22 10:00:23 +00001716 if (error.Fail())
1717 return error;
1718
1719 m_threads_stepping_with_breakpoint.insert({thread_sp->GetID(), next_pc});
1720
1721 return Error();
1722}
1723
1724bool
1725NativeProcessLinux::SupportHardwareSingleStepping() const
1726{
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001727 if (m_arch.GetMachine() == llvm::Triple::arm
Jaydeep Patilc60c9452015-06-23 03:37:08 +00001728 || m_arch.GetMachine() == llvm::Triple::mips64 || m_arch.GetMachine() == llvm::Triple::mips64el
1729 || m_arch.GetMachine() == llvm::Triple::mips || m_arch.GetMachine() == llvm::Triple::mipsel)
Mohit K. Bhakkadcdc22a82015-05-07 05:56:27 +00001730 return false;
1731 return true;
Tamas Berghammere7708682015-04-22 10:00:23 +00001732}
1733
Todd Fialaaf245d12014-06-30 21:05:18 +00001734Error
1735NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
1736{
Todd Fialaaf245d12014-06-30 21:05:18 +00001737 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1738 if (log)
1739 log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
1740
Tamas Berghammere7708682015-04-22 10:00:23 +00001741 bool software_single_step = !SupportHardwareSingleStepping();
Todd Fialaaf245d12014-06-30 21:05:18 +00001742
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001743 Mutex::Locker locker (m_threads_mutex);
Chaoren Lin03f12d62015-02-03 01:50:49 +00001744
Tamas Berghammere7708682015-04-22 10:00:23 +00001745 if (software_single_step)
1746 {
1747 for (auto thread_sp : m_threads)
1748 {
1749 assert (thread_sp && "thread list should not contain NULL threads");
1750
1751 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
1752 if (action == nullptr)
1753 continue;
1754
1755 if (action->state == eStateStepping)
1756 {
1757 Error error = SetupSoftwareSingleStepping(thread_sp);
1758 if (error.Fail())
1759 return error;
1760 }
1761 }
1762 }
1763
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001764 for (auto thread_sp : m_threads)
Todd Fialaaf245d12014-06-30 21:05:18 +00001765 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001766 assert (thread_sp && "thread list should not contain NULL threads");
1767
1768 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
1769
1770 if (action == nullptr)
Todd Fialaaf245d12014-06-30 21:05:18 +00001771 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00001772 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001773 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
1774 __FUNCTION__, GetID (), thread_sp->GetID ());
1775 continue;
1776 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001777
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001778 if (log)
1779 {
1780 log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
1781 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
1782 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001783
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001784 switch (action->state)
1785 {
1786 case eStateRunning:
1787 {
1788 // Run the thread, possibly feeding it the signal.
1789 const int signo = action->signal;
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001790 ResumeThread(thread_sp->GetID (),
Pavel Labathc0765592015-05-06 10:46:34 +00001791 [=](lldb::tid_t tid_to_resume, bool supress_signal)
1792 {
1793 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
1794 // Pass this signal number on to the inferior to handle.
1795 const auto resume_result = Resume (tid_to_resume, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
1796 if (resume_result.Success())
1797 SetState(eStateRunning, true);
1798 return resume_result;
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001799 },
1800 false);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001801 break;
1802 }
1803
1804 case eStateStepping:
1805 {
1806 // Request the step.
1807 const int signo = action->signal;
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001808 ResumeThread(thread_sp->GetID (),
Pavel Labathc0765592015-05-06 10:46:34 +00001809 [=](lldb::tid_t tid_to_step, bool supress_signal)
1810 {
1811 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStepping ();
Tamas Berghammere7708682015-04-22 10:00:23 +00001812
Pavel Labathc0765592015-05-06 10:46:34 +00001813 Error step_result;
1814 if (software_single_step)
1815 step_result = Resume (tid_to_step, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
1816 else
1817 step_result = SingleStep (tid_to_step,(signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
Tamas Berghammere7708682015-04-22 10:00:23 +00001818
Pavel Labathc0765592015-05-06 10:46:34 +00001819 assert (step_result.Success() && "SingleStep() failed");
1820 if (step_result.Success())
1821 SetState(eStateStepping, true);
1822 return step_result;
Pavel Labath1dbc6c92015-05-12 08:35:33 +00001823 },
1824 false);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001825 break;
1826 }
1827
1828 case eStateSuspended:
1829 case eStateStopped:
Pavel Labath108c3252015-05-12 09:03:18 +00001830 lldbassert(0 && "Unexpected state");
Chaoren Linfa03ad22015-02-03 01:50:42 +00001831
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001832 default:
1833 return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
1834 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001835 }
1836 }
1837
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001838 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00001839}
1840
1841Error
1842NativeProcessLinux::Halt ()
1843{
1844 Error error;
1845
Todd Fialaaf245d12014-06-30 21:05:18 +00001846 if (kill (GetID (), SIGSTOP) != 0)
1847 error.SetErrorToErrno ();
1848
1849 return error;
1850}
1851
1852Error
1853NativeProcessLinux::Detach ()
1854{
1855 Error error;
1856
1857 // Tell ptrace to detach from the process.
1858 if (GetID () != LLDB_INVALID_PROCESS_ID)
1859 error = Detach (GetID ());
1860
1861 // Stop monitoring the inferior.
Pavel Labath19cbe962015-07-21 13:20:32 +00001862 m_sigchld_handle.reset();
Todd Fialaaf245d12014-06-30 21:05:18 +00001863
1864 // No error.
1865 return error;
1866}
1867
1868Error
1869NativeProcessLinux::Signal (int signo)
1870{
1871 Error error;
1872
1873 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1874 if (log)
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001875 log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
1876 __FUNCTION__, signo, Host::GetSignalAsCString(signo), GetID());
Todd Fialaaf245d12014-06-30 21:05:18 +00001877
1878 if (kill(GetID(), signo))
1879 error.SetErrorToErrno();
1880
1881 return error;
1882}
1883
1884Error
Chaoren Line9547b82015-02-03 01:51:00 +00001885NativeProcessLinux::Interrupt ()
1886{
1887 // Pick a running thread (or if none, a not-dead stopped thread) as
1888 // the chosen thread that will be the stop-reason thread.
Chaoren Line9547b82015-02-03 01:51:00 +00001889 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1890
1891 NativeThreadProtocolSP running_thread_sp;
1892 NativeThreadProtocolSP stopped_thread_sp;
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001893
1894 if (log)
1895 log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
1896
1897 Mutex::Locker locker (m_threads_mutex);
1898
1899 for (auto thread_sp : m_threads)
Chaoren Line9547b82015-02-03 01:51:00 +00001900 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001901 // The thread shouldn't be null but lets just cover that here.
1902 if (!thread_sp)
1903 continue;
Chaoren Line9547b82015-02-03 01:51:00 +00001904
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001905 // If we have a running or stepping thread, we'll call that the
1906 // target of the interrupt.
1907 const auto thread_state = thread_sp->GetState ();
1908 if (thread_state == eStateRunning ||
1909 thread_state == eStateStepping)
Chaoren Line9547b82015-02-03 01:51:00 +00001910 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001911 running_thread_sp = thread_sp;
1912 break;
1913 }
1914 else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
1915 {
1916 // Remember the first non-dead stopped thread. We'll use that as a backup if there are no running threads.
1917 stopped_thread_sp = thread_sp;
Chaoren Line9547b82015-02-03 01:51:00 +00001918 }
1919 }
1920
1921 if (!running_thread_sp && !stopped_thread_sp)
1922 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001923 Error error("found no running/stepping or live stopped threads as target for interrupt");
Chaoren Line9547b82015-02-03 01:51:00 +00001924 if (log)
Chaoren Line9547b82015-02-03 01:51:00 +00001925 log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001926
Chaoren Line9547b82015-02-03 01:51:00 +00001927 return error;
1928 }
1929
1930 NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
1931
1932 if (log)
1933 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
1934 __FUNCTION__,
1935 GetID (),
1936 running_thread_sp ? "running" : "stopped",
1937 deferred_signal_thread_sp->GetID ());
1938
Pavel Labathed89c7f2015-05-06 12:22:37 +00001939 StopRunningThreads(deferred_signal_thread_sp->GetID());
Pavel Labath45f5cb32015-05-05 15:05:50 +00001940
Tamas Berghammer5830aa72015-02-06 10:42:33 +00001941 return Error();
Chaoren Line9547b82015-02-03 01:51:00 +00001942}
1943
1944Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001945NativeProcessLinux::Kill ()
1946{
1947 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1948 if (log)
1949 log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
1950
1951 Error error;
1952
1953 switch (m_state)
1954 {
1955 case StateType::eStateInvalid:
1956 case StateType::eStateExited:
1957 case StateType::eStateCrashed:
1958 case StateType::eStateDetached:
1959 case StateType::eStateUnloaded:
1960 // Nothing to do - the process is already dead.
1961 if (log)
1962 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
1963 return error;
1964
1965 case StateType::eStateConnected:
1966 case StateType::eStateAttaching:
1967 case StateType::eStateLaunching:
1968 case StateType::eStateStopped:
1969 case StateType::eStateRunning:
1970 case StateType::eStateStepping:
1971 case StateType::eStateSuspended:
1972 // We can try to kill a process in these states.
1973 break;
1974 }
1975
1976 if (kill (GetID (), SIGKILL) != 0)
1977 {
1978 error.SetErrorToErrno ();
1979 return error;
1980 }
1981
1982 return error;
1983}
1984
1985static Error
1986ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
1987{
1988 memory_region_info.Clear();
1989
1990 StringExtractor line_extractor (maps_line.c_str ());
1991
1992 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode pathname
1993 // perms: rwxp (letter is present if set, '-' if not, final character is p=private, s=shared).
1994
1995 // Parse out the starting address
1996 lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
1997
1998 // Parse out hyphen separating start and end address from range.
1999 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
2000 return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
2001
2002 // Parse out the ending address
2003 lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
2004
2005 // Parse out the space after the address.
2006 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
2007 return Error ("malformed /proc/{pid}/maps entry, missing space after range");
2008
2009 // Save the range.
2010 memory_region_info.GetRange ().SetRangeBase (start_address);
2011 memory_region_info.GetRange ().SetRangeEnd (end_address);
2012
2013 // Parse out each permission entry.
2014 if (line_extractor.GetBytesLeft () < 4)
2015 return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
2016
2017 // Handle read permission.
2018 const char read_perm_char = line_extractor.GetChar ();
2019 if (read_perm_char == 'r')
2020 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
2021 else
2022 {
2023 assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
2024 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2025 }
2026
2027 // Handle write permission.
2028 const char write_perm_char = line_extractor.GetChar ();
2029 if (write_perm_char == 'w')
2030 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
2031 else
2032 {
2033 assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
2034 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2035 }
2036
2037 // Handle execute permission.
2038 const char exec_perm_char = line_extractor.GetChar ();
2039 if (exec_perm_char == 'x')
2040 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
2041 else
2042 {
2043 assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
2044 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2045 }
2046
2047 return Error ();
2048}
2049
2050Error
2051NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
2052{
2053 // FIXME review that the final memory region returned extends to the end of the virtual address space,
2054 // with no perms if it is not mapped.
2055
2056 // Use an approach that reads memory regions from /proc/{pid}/maps.
2057 // Assume proc maps entries are in ascending order.
2058 // FIXME assert if we find differently.
2059 Mutex::Locker locker (m_mem_region_cache_mutex);
2060
2061 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2062 Error error;
2063
2064 if (m_supports_mem_region == LazyBool::eLazyBoolNo)
2065 {
2066 // We're done.
2067 error.SetErrorString ("unsupported");
2068 return error;
2069 }
2070
2071 // If our cache is empty, pull the latest. There should always be at least one memory region
2072 // if memory region handling is supported.
2073 if (m_mem_region_cache.empty ())
2074 {
2075 error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
2076 [&] (const std::string &line) -> bool
2077 {
2078 MemoryRegionInfo info;
2079 const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
2080 if (parse_error.Success ())
2081 {
2082 m_mem_region_cache.push_back (info);
2083 return true;
2084 }
2085 else
2086 {
2087 if (log)
2088 log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
2089 return false;
2090 }
2091 });
2092
2093 // If we had an error, we'll mark unsupported.
2094 if (error.Fail ())
2095 {
2096 m_supports_mem_region = LazyBool::eLazyBoolNo;
2097 return error;
2098 }
2099 else if (m_mem_region_cache.empty ())
2100 {
2101 // No entries after attempting to read them. This shouldn't happen if /proc/{pid}/maps
2102 // is supported. Assume we don't support map entries via procfs.
2103 if (log)
2104 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
2105 m_supports_mem_region = LazyBool::eLazyBoolNo;
2106 error.SetErrorString ("not supported");
2107 return error;
2108 }
2109
2110 if (log)
2111 log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ());
2112
2113 // We support memory retrieval, remember that.
2114 m_supports_mem_region = LazyBool::eLazyBoolYes;
2115 }
2116 else
2117 {
2118 if (log)
2119 log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2120 }
2121
2122 lldb::addr_t prev_base_address = 0;
2123
2124 // FIXME start by finding the last region that is <= target address using binary search. Data is sorted.
2125 // There can be a ton of regions on pthreads apps with lots of threads.
2126 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
2127 {
2128 MemoryRegionInfo &proc_entry_info = *it;
2129
2130 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
2131 assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
2132 prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
2133
2134 // If the target address comes before this entry, indicate distance to next region.
2135 if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
2136 {
2137 range_info.GetRange ().SetRangeBase (load_addr);
2138 range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
2139 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2140 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2141 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
2142
2143 return error;
2144 }
2145 else if (proc_entry_info.GetRange ().Contains (load_addr))
2146 {
2147 // The target address is within the memory region we're processing here.
2148 range_info = proc_entry_info;
2149 return error;
2150 }
2151
2152 // The target memory address comes somewhere after the region we just parsed.
2153 }
2154
Tamas Berghammer09839c32015-07-03 09:30:19 +00002155 // If we made it here, we didn't find an entry that contained the given address. Return the
2156 // load_addr as start and the amount of bytes betwwen load address and the end of the memory as
2157 // size.
2158 range_info.GetRange ().SetRangeBase (load_addr);
2159 switch (m_arch.GetAddressByteSize())
2160 {
2161 case 4:
2162 range_info.GetRange ().SetByteSize (0x100000000ull - load_addr);
2163 break;
2164 case 8:
2165 range_info.GetRange ().SetByteSize (0ull - load_addr);
2166 break;
2167 default:
2168 assert(false && "Unrecognized data byte size");
2169 break;
2170 }
2171 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
2172 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
2173 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
Todd Fialaaf245d12014-06-30 21:05:18 +00002174 return error;
2175}
2176
2177void
2178NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
2179{
2180 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2181 if (log)
2182 log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
2183
2184 {
2185 Mutex::Locker locker (m_mem_region_cache_mutex);
2186 if (log)
2187 log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2188 m_mem_region_cache.clear ();
2189 }
2190}
2191
2192Error
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002193NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr)
Todd Fialaaf245d12014-06-30 21:05:18 +00002194{
2195 // FIXME implementing this requires the equivalent of
2196 // InferiorCallPOSIX::InferiorCallMmap, which depends on
2197 // functional ThreadPlans working with Native*Protocol.
2198#if 1
2199 return Error ("not implemented yet");
2200#else
2201 addr = LLDB_INVALID_ADDRESS;
2202
2203 unsigned prot = 0;
2204 if (permissions & lldb::ePermissionsReadable)
2205 prot |= eMmapProtRead;
2206 if (permissions & lldb::ePermissionsWritable)
2207 prot |= eMmapProtWrite;
2208 if (permissions & lldb::ePermissionsExecutable)
2209 prot |= eMmapProtExec;
2210
2211 // TODO implement this directly in NativeProcessLinux
2212 // (and lift to NativeProcessPOSIX if/when that class is
2213 // refactored out).
2214 if (InferiorCallMmap(this, addr, 0, size, prot,
2215 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
2216 m_addr_to_mmap_size[addr] = size;
2217 return Error ();
2218 } else {
2219 addr = LLDB_INVALID_ADDRESS;
2220 return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
2221 }
2222#endif
2223}
2224
2225Error
2226NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
2227{
2228 // FIXME see comments in AllocateMemory - required lower-level
2229 // bits not in place yet (ThreadPlans)
2230 return Error ("not implemented");
2231}
2232
2233lldb::addr_t
2234NativeProcessLinux::GetSharedLibraryInfoAddress ()
2235{
2236#if 1
2237 // punt on this for now
2238 return LLDB_INVALID_ADDRESS;
2239#else
2240 // Return the image info address for the exe module
2241#if 1
2242 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2243
2244 ModuleSP module_sp;
2245 Error error = GetExeModuleSP (module_sp);
2246 if (error.Fail ())
2247 {
2248 if (log)
2249 log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ());
2250 return LLDB_INVALID_ADDRESS;
2251 }
2252
2253 if (module_sp == nullptr)
2254 {
2255 if (log)
2256 log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__);
2257 return LLDB_INVALID_ADDRESS;
2258 }
2259
2260 ObjectFileSP object_file_sp = module_sp->GetObjectFile ();
2261 if (object_file_sp == nullptr)
2262 {
2263 if (log)
2264 log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__);
2265 return LLDB_INVALID_ADDRESS;
2266 }
2267
2268 return obj_file_sp->GetImageInfoAddress();
2269#else
2270 Target *target = &GetTarget();
2271 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
2272 Address addr = obj_file->GetImageInfoAddress(target);
2273
2274 if (addr.IsValid())
2275 return addr.GetLoadAddress(target);
2276 return LLDB_INVALID_ADDRESS;
2277#endif
2278#endif // punt on this for now
2279}
2280
2281size_t
2282NativeProcessLinux::UpdateThreads ()
2283{
2284 // The NativeProcessLinux monitoring threads are always up to date
2285 // with respect to thread state and they keep the thread list
2286 // populated properly. All this method needs to do is return the
2287 // thread count.
2288 Mutex::Locker locker (m_threads_mutex);
2289 return m_threads.size ();
2290}
2291
2292bool
2293NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
2294{
2295 arch = m_arch;
2296 return true;
2297}
2298
2299Error
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002300NativeProcessLinux::GetSoftwareBreakpointPCOffset (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size)
Todd Fialaaf245d12014-06-30 21:05:18 +00002301{
2302 // FIXME put this behind a breakpoint protocol class that can be
2303 // set per architecture. Need ARM, MIPS support here.
2304 static const uint8_t g_i386_opcode [] = { 0xCC };
2305
2306 switch (m_arch.GetMachine ())
2307 {
2308 case llvm::Triple::x86:
2309 case llvm::Triple::x86_64:
2310 actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
2311 return Error ();
2312
Tamas Berghammerff7fd902015-07-03 12:51:30 +00002313 case llvm::Triple::arm:
2314 case llvm::Triple::aarch64:
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00002315 case llvm::Triple::mips64:
2316 case llvm::Triple::mips64el:
Sagar Thakurce815e42015-06-03 10:14:24 +00002317 case llvm::Triple::mips:
2318 case llvm::Triple::mipsel:
Tamas Berghammerff7fd902015-07-03 12:51:30 +00002319 // On these architectures the PC don't get updated for breakpoint hits
Jaydeep Patilc60c9452015-06-23 03:37:08 +00002320 actual_opcode_size = 0;
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00002321 return Error ();
2322
Todd Fialaaf245d12014-06-30 21:05:18 +00002323 default:
2324 assert(false && "CPU type not supported!");
2325 return Error ("CPU type not supported");
2326 }
2327}
2328
2329Error
2330NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
2331{
2332 if (hardware)
2333 return Error ("NativeProcessLinux does not support hardware breakpoints");
2334 else
2335 return SetSoftwareBreakpoint (addr, size);
2336}
2337
2338Error
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002339NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint,
2340 size_t &actual_opcode_size,
2341 const uint8_t *&trap_opcode_bytes)
Todd Fialaaf245d12014-06-30 21:05:18 +00002342{
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002343 // FIXME put this behind a breakpoint protocol class that can be set per
2344 // architecture. Need MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00002345 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002346 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
2347 // linux kernel does otherwise.
2348 static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 };
Todd Fialaaf245d12014-06-30 21:05:18 +00002349 static const uint8_t g_i386_opcode [] = { 0xCC };
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00002350 static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00002351 static const uint8_t g_mips64el_opcode[] = { 0x0d, 0x00, 0x00, 0x00 };
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002352 static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde };
Todd Fialaaf245d12014-06-30 21:05:18 +00002353
2354 switch (m_arch.GetMachine ())
2355 {
Todd Fiala2afc5962014-08-21 16:42:31 +00002356 case llvm::Triple::aarch64:
2357 trap_opcode_bytes = g_aarch64_opcode;
2358 actual_opcode_size = sizeof(g_aarch64_opcode);
2359 return Error ();
2360
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002361 case llvm::Triple::arm:
2362 switch (trap_opcode_size_hint)
2363 {
2364 case 2:
2365 trap_opcode_bytes = g_thumb_breakpoint_opcode;
2366 actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
2367 return Error ();
2368 case 4:
2369 trap_opcode_bytes = g_arm_breakpoint_opcode;
2370 actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
2371 return Error ();
2372 default:
2373 assert(false && "Unrecognised trap opcode size hint!");
2374 return Error ("Unrecognised trap opcode size hint!");
2375 }
2376
Todd Fialaaf245d12014-06-30 21:05:18 +00002377 case llvm::Triple::x86:
2378 case llvm::Triple::x86_64:
2379 trap_opcode_bytes = g_i386_opcode;
2380 actual_opcode_size = sizeof(g_i386_opcode);
2381 return Error ();
2382
Sagar Thakurce815e42015-06-03 10:14:24 +00002383 case llvm::Triple::mips:
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00002384 case llvm::Triple::mips64:
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00002385 trap_opcode_bytes = g_mips64_opcode;
2386 actual_opcode_size = sizeof(g_mips64_opcode);
2387 return Error ();
2388
Sagar Thakurce815e42015-06-03 10:14:24 +00002389 case llvm::Triple::mipsel:
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00002390 case llvm::Triple::mips64el:
2391 trap_opcode_bytes = g_mips64el_opcode;
2392 actual_opcode_size = sizeof(g_mips64el_opcode);
2393 return Error ();
2394
Todd Fialaaf245d12014-06-30 21:05:18 +00002395 default:
2396 assert(false && "CPU type not supported!");
2397 return Error ("CPU type not supported");
2398 }
2399}
2400
2401#if 0
2402ProcessMessage::CrashReason
2403NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
2404{
2405 ProcessMessage::CrashReason reason;
2406 assert(info->si_signo == SIGSEGV);
2407
2408 reason = ProcessMessage::eInvalidCrashReason;
2409
2410 switch (info->si_code)
2411 {
2412 default:
2413 assert(false && "unexpected si_code for SIGSEGV");
2414 break;
2415 case SI_KERNEL:
2416 // Linux will occasionally send spurious SI_KERNEL codes.
2417 // (this is poorly documented in sigaction)
2418 // One way to get this is via unaligned SIMD loads.
2419 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
2420 break;
2421 case SEGV_MAPERR:
2422 reason = ProcessMessage::eInvalidAddress;
2423 break;
2424 case SEGV_ACCERR:
2425 reason = ProcessMessage::ePrivilegedAddress;
2426 break;
2427 }
2428
2429 return reason;
2430}
2431#endif
2432
2433
2434#if 0
2435ProcessMessage::CrashReason
2436NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
2437{
2438 ProcessMessage::CrashReason reason;
2439 assert(info->si_signo == SIGILL);
2440
2441 reason = ProcessMessage::eInvalidCrashReason;
2442
2443 switch (info->si_code)
2444 {
2445 default:
2446 assert(false && "unexpected si_code for SIGILL");
2447 break;
2448 case ILL_ILLOPC:
2449 reason = ProcessMessage::eIllegalOpcode;
2450 break;
2451 case ILL_ILLOPN:
2452 reason = ProcessMessage::eIllegalOperand;
2453 break;
2454 case ILL_ILLADR:
2455 reason = ProcessMessage::eIllegalAddressingMode;
2456 break;
2457 case ILL_ILLTRP:
2458 reason = ProcessMessage::eIllegalTrap;
2459 break;
2460 case ILL_PRVOPC:
2461 reason = ProcessMessage::ePrivilegedOpcode;
2462 break;
2463 case ILL_PRVREG:
2464 reason = ProcessMessage::ePrivilegedRegister;
2465 break;
2466 case ILL_COPROC:
2467 reason = ProcessMessage::eCoprocessorError;
2468 break;
2469 case ILL_BADSTK:
2470 reason = ProcessMessage::eInternalStackError;
2471 break;
2472 }
2473
2474 return reason;
2475}
2476#endif
2477
2478#if 0
2479ProcessMessage::CrashReason
2480NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
2481{
2482 ProcessMessage::CrashReason reason;
2483 assert(info->si_signo == SIGFPE);
2484
2485 reason = ProcessMessage::eInvalidCrashReason;
2486
2487 switch (info->si_code)
2488 {
2489 default:
2490 assert(false && "unexpected si_code for SIGFPE");
2491 break;
2492 case FPE_INTDIV:
2493 reason = ProcessMessage::eIntegerDivideByZero;
2494 break;
2495 case FPE_INTOVF:
2496 reason = ProcessMessage::eIntegerOverflow;
2497 break;
2498 case FPE_FLTDIV:
2499 reason = ProcessMessage::eFloatDivideByZero;
2500 break;
2501 case FPE_FLTOVF:
2502 reason = ProcessMessage::eFloatOverflow;
2503 break;
2504 case FPE_FLTUND:
2505 reason = ProcessMessage::eFloatUnderflow;
2506 break;
2507 case FPE_FLTRES:
2508 reason = ProcessMessage::eFloatInexactResult;
2509 break;
2510 case FPE_FLTINV:
2511 reason = ProcessMessage::eFloatInvalidOperation;
2512 break;
2513 case FPE_FLTSUB:
2514 reason = ProcessMessage::eFloatSubscriptRange;
2515 break;
2516 }
2517
2518 return reason;
2519}
2520#endif
2521
2522#if 0
2523ProcessMessage::CrashReason
2524NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
2525{
2526 ProcessMessage::CrashReason reason;
2527 assert(info->si_signo == SIGBUS);
2528
2529 reason = ProcessMessage::eInvalidCrashReason;
2530
2531 switch (info->si_code)
2532 {
2533 default:
2534 assert(false && "unexpected si_code for SIGBUS");
2535 break;
2536 case BUS_ADRALN:
2537 reason = ProcessMessage::eIllegalAlignment;
2538 break;
2539 case BUS_ADRERR:
2540 reason = ProcessMessage::eIllegalAddress;
2541 break;
2542 case BUS_OBJERR:
2543 reason = ProcessMessage::eHardwareError;
2544 break;
2545 }
2546
2547 return reason;
2548}
2549#endif
2550
Todd Fialaaf245d12014-06-30 21:05:18 +00002551Error
Chaoren Lin26438d22015-05-05 17:50:53 +00002552NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
Todd Fialaaf245d12014-06-30 21:05:18 +00002553{
Pavel Labathdf7c6992015-06-17 18:38:49 +00002554 if (ProcessVmReadvSupported()) {
2555 // The process_vm_readv path is about 50 times faster than ptrace api. We want to use
2556 // this syscall if it is supported.
2557
2558 const ::pid_t pid = GetID();
2559
2560 struct iovec local_iov, remote_iov;
2561 local_iov.iov_base = buf;
2562 local_iov.iov_len = size;
2563 remote_iov.iov_base = reinterpret_cast<void *>(addr);
2564 remote_iov.iov_len = size;
2565
2566 bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
2567 const bool success = bytes_read == size;
2568
2569 Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2570 if (log)
2571 log->Printf ("NativeProcessLinux::%s using process_vm_readv to read %zd bytes from inferior address 0x%" PRIx64": %s",
2572 __FUNCTION__, size, addr, success ? "Success" : strerror(errno));
2573
2574 if (success)
2575 return Error();
2576 // else
2577 // the call failed for some reason, let's retry the read using ptrace api.
2578 }
2579
Pavel Labath19cbe962015-07-21 13:20:32 +00002580 unsigned char *dst = static_cast<unsigned char*>(buf);
2581 size_t remainder;
2582 long data;
2583
2584 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
2585 if (log)
2586 ProcessPOSIXLog::IncNestLevel();
2587 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
2588 log->Printf ("NativeProcessLinux::%s(%p, %p, %zd, _)", __FUNCTION__, (void*)addr, buf, size);
2589
2590 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
2591 {
2592 Error error = NativeProcessLinux::PtraceWrapper(PTRACE_PEEKDATA, GetID(), (void*)addr, nullptr, 0, &data);
2593 if (error.Fail())
2594 {
2595 if (log)
2596 ProcessPOSIXLog::DecNestLevel();
2597 return error;
2598 }
2599
2600 remainder = size - bytes_read;
2601 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
2602
2603 // Copy the data into our buffer
2604 for (unsigned i = 0; i < remainder; ++i)
2605 dst[i] = ((data >> i*8) & 0xFF);
2606
2607 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2608 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
2609 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2610 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
2611 {
2612 uintptr_t print_dst = 0;
2613 // Format bytes from data by moving into print_dst for log output
2614 for (unsigned i = 0; i < remainder; ++i)
2615 print_dst |= (((data >> i*8) & 0xFF) << i*8);
Pavel Labath79203992015-07-23 13:07:37 +00002616 log->Printf ("NativeProcessLinux::%s() [0x%" PRIx64 "]:0x%" PRIx64 " (0x%" PRIx64 ")",
2617 __FUNCTION__, addr, uint64_t(print_dst), uint64_t(data));
Pavel Labath19cbe962015-07-21 13:20:32 +00002618 }
2619 addr += k_ptrace_word_size;
2620 dst += k_ptrace_word_size;
2621 }
2622
2623 if (log)
2624 ProcessPOSIXLog::DecNestLevel();
2625 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00002626}
2627
2628Error
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002629NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
2630{
2631 Error error = ReadMemory(addr, buf, size, bytes_read);
2632 if (error.Fail()) return error;
2633 return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
2634}
2635
2636Error
2637NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written)
Todd Fialaaf245d12014-06-30 21:05:18 +00002638{
Pavel Labath19cbe962015-07-21 13:20:32 +00002639 const unsigned char *src = static_cast<const unsigned char*>(buf);
2640 size_t remainder;
2641 Error error;
2642
2643 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
2644 if (log)
2645 ProcessPOSIXLog::IncNestLevel();
2646 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
Pavel Labath79203992015-07-23 13:07:37 +00002647 log->Printf ("NativeProcessLinux::%s(0x%" PRIx64 ", %p, %zu)", __FUNCTION__, addr, buf, size);
Pavel Labath19cbe962015-07-21 13:20:32 +00002648
2649 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
2650 {
2651 remainder = size - bytes_written;
2652 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
2653
2654 if (remainder == k_ptrace_word_size)
2655 {
2656 unsigned long data = 0;
2657 for (unsigned i = 0; i < k_ptrace_word_size; ++i)
2658 data |= (unsigned long)src[i] << i*8;
2659
2660 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2661 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
2662 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2663 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
2664 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
2665 (void*)addr, *(const unsigned long*)src, data);
2666
2667 error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(), (void*)addr, (void*)data);
2668 if (error.Fail())
2669 {
2670 if (log)
2671 ProcessPOSIXLog::DecNestLevel();
2672 return error;
2673 }
2674 }
2675 else
2676 {
2677 unsigned char buff[8];
2678 size_t bytes_read;
2679 error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
2680 if (error.Fail())
2681 {
2682 if (log)
2683 ProcessPOSIXLog::DecNestLevel();
2684 return error;
2685 }
2686
2687 memcpy(buff, src, remainder);
2688
2689 size_t bytes_written_rec;
2690 error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
2691 if (error.Fail())
2692 {
2693 if (log)
2694 ProcessPOSIXLog::DecNestLevel();
2695 return error;
2696 }
2697
2698 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2699 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
2700 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2701 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
2702 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
2703 (void*)addr, *(const unsigned long*)src, *(unsigned long*)buff);
2704 }
2705
2706 addr += k_ptrace_word_size;
2707 src += k_ptrace_word_size;
2708 }
2709 if (log)
2710 ProcessPOSIXLog::DecNestLevel();
2711 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002712}
2713
Chaoren Lin97ccc292015-02-03 01:51:12 +00002714Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002715NativeProcessLinux::Resume (lldb::tid_t tid, uint32_t signo)
2716{
Todd Fialaaf245d12014-06-30 21:05:18 +00002717 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2718
2719 if (log)
2720 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid,
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00002721 Host::GetSignalAsCString(signo));
Pavel Labathc7512fd2015-06-26 10:14:12 +00002722
2723
2724
2725 intptr_t data = 0;
2726
2727 if (signo != LLDB_INVALID_SIGNAL_NUMBER)
2728 data = signo;
2729
Pavel Labath19cbe962015-07-21 13:20:32 +00002730 Error error = PtraceWrapper(PTRACE_CONT, tid, nullptr, (void*)data);
Pavel Labathc7512fd2015-06-26 10:14:12 +00002731
Todd Fialaaf245d12014-06-30 21:05:18 +00002732 if (log)
Pavel Labathc7512fd2015-06-26 10:14:12 +00002733 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " result = %s", __FUNCTION__, tid, error.Success() ? "true" : "false");
2734 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002735}
2736
Chaoren Lin97ccc292015-02-03 01:51:12 +00002737Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002738NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo)
2739{
Pavel Labathc7512fd2015-06-26 10:14:12 +00002740 intptr_t data = 0;
2741
2742 if (signo != LLDB_INVALID_SIGNAL_NUMBER)
2743 data = signo;
2744
Pavel Labath19cbe962015-07-21 13:20:32 +00002745 return PtraceWrapper(PTRACE_SINGLESTEP, tid, nullptr, (void*)data);
Todd Fialaaf245d12014-06-30 21:05:18 +00002746}
2747
Chaoren Lin97ccc292015-02-03 01:51:12 +00002748Error
2749NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
Todd Fialaaf245d12014-06-30 21:05:18 +00002750{
Pavel Labath19cbe962015-07-21 13:20:32 +00002751 return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
Todd Fialaaf245d12014-06-30 21:05:18 +00002752}
2753
Chaoren Lin97ccc292015-02-03 01:51:12 +00002754Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002755NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
2756{
Pavel Labath19cbe962015-07-21 13:20:32 +00002757 return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
Todd Fialaaf245d12014-06-30 21:05:18 +00002758}
2759
Tamas Berghammerdb264a62015-03-31 09:52:22 +00002760Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002761NativeProcessLinux::Detach(lldb::tid_t tid)
2762{
Chaoren Lin97ccc292015-02-03 01:51:12 +00002763 if (tid == LLDB_INVALID_THREAD_ID)
2764 return Error();
2765
Pavel Labath19cbe962015-07-21 13:20:32 +00002766 return PtraceWrapper(PTRACE_DETACH, tid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002767}
2768
2769bool
Chaoren Lind3173f32015-05-29 19:52:29 +00002770NativeProcessLinux::DupDescriptor(const FileSpec &file_spec, int fd, int flags)
Todd Fialaaf245d12014-06-30 21:05:18 +00002771{
Chaoren Lind3173f32015-05-29 19:52:29 +00002772 int target_fd = open(file_spec.GetCString(), flags, 0666);
Todd Fialaaf245d12014-06-30 21:05:18 +00002773
2774 if (target_fd == -1)
2775 return false;
2776
Pavel Labath493c3a12015-02-04 10:36:57 +00002777 if (dup2(target_fd, fd) == -1)
2778 return false;
2779
2780 return (close(target_fd) == -1) ? false : true;
Todd Fialaaf245d12014-06-30 21:05:18 +00002781}
2782
Todd Fialaaf245d12014-06-30 21:05:18 +00002783bool
2784NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
2785{
2786 for (auto thread_sp : m_threads)
2787 {
2788 assert (thread_sp && "thread list should not contain NULL threads");
2789 if (thread_sp->GetID () == thread_id)
2790 {
2791 // We have this thread.
2792 return true;
2793 }
2794 }
2795
2796 // We don't have this thread.
2797 return false;
2798}
2799
2800NativeThreadProtocolSP
2801NativeProcessLinux::MaybeGetThreadNoLock (lldb::tid_t thread_id)
2802{
2803 // CONSIDER organize threads by map - we can do better than linear.
2804 for (auto thread_sp : m_threads)
2805 {
2806 if (thread_sp->GetID () == thread_id)
2807 return thread_sp;
2808 }
2809
2810 // We don't have this thread.
2811 return NativeThreadProtocolSP ();
2812}
2813
2814bool
2815NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
2816{
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002817 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
2818
2819 if (log)
2820 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, thread_id);
2821
2822 bool found = false;
2823
Todd Fialaaf245d12014-06-30 21:05:18 +00002824 Mutex::Locker locker (m_threads_mutex);
2825 for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
2826 {
2827 if (*it && ((*it)->GetID () == thread_id))
2828 {
2829 m_threads.erase (it);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002830 found = true;
2831 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00002832 }
2833 }
2834
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002835 // If we have a pending notification, remove this from the set.
2836 if (m_pending_notification_up)
2837 {
2838 m_pending_notification_up->wait_for_stop_tids.erase(thread_id);
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00002839 SignalIfAllThreadsStopped();
Pavel Labath1dbc6c92015-05-12 08:35:33 +00002840 }
2841
2842 return found;
Todd Fialaaf245d12014-06-30 21:05:18 +00002843}
2844
2845NativeThreadProtocolSP
2846NativeProcessLinux::AddThread (lldb::tid_t thread_id)
2847{
2848 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
2849
2850 Mutex::Locker locker (m_threads_mutex);
2851
2852 if (log)
2853 {
2854 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
2855 __FUNCTION__,
2856 GetID (),
2857 thread_id);
2858 }
2859
2860 assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
2861
2862 // If this is the first thread, save it as the current thread
2863 if (m_threads.empty ())
2864 SetCurrentThreadID (thread_id);
2865
2866 NativeThreadProtocolSP thread_sp (new NativeThreadLinux (this, thread_id));
2867 m_threads.push_back (thread_sp);
2868
2869 return thread_sp;
2870}
2871
Todd Fialaaf245d12014-06-30 21:05:18 +00002872Error
2873NativeProcessLinux::FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp)
2874{
Todd Fiala75f47c32014-10-11 21:42:09 +00002875 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Todd Fialaaf245d12014-06-30 21:05:18 +00002876
2877 Error error;
2878
2879 // Get a linux thread pointer.
2880 if (!thread_sp)
2881 {
2882 error.SetErrorString ("null thread_sp");
2883 if (log)
2884 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
2885 return error;
2886 }
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002887 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00002888
2889 // Find out the size of a breakpoint (might depend on where we are in the code).
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002890 NativeRegisterContextSP context_sp = linux_thread_sp->GetRegisterContext ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002891 if (!context_sp)
2892 {
2893 error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
2894 if (log)
2895 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
2896 return error;
2897 }
2898
2899 uint32_t breakpoint_size = 0;
Tamas Berghammer63c8be92015-04-15 09:38:48 +00002900 error = GetSoftwareBreakpointPCOffset (context_sp, breakpoint_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00002901 if (error.Fail ())
2902 {
2903 if (log)
2904 log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
2905 return error;
2906 }
2907 else
2908 {
2909 if (log)
2910 log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
2911 }
2912
2913 // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
Jaydeep Patilc60c9452015-06-23 03:37:08 +00002914 const lldb::addr_t initial_pc_addr = context_sp->GetPCfromBreakpointLocation ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002915 lldb::addr_t breakpoint_addr = initial_pc_addr;
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002916 if (breakpoint_size > 0)
Todd Fialaaf245d12014-06-30 21:05:18 +00002917 {
2918 // Do not allow breakpoint probe to wrap around.
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002919 if (breakpoint_addr >= breakpoint_size)
2920 breakpoint_addr -= breakpoint_size;
Todd Fialaaf245d12014-06-30 21:05:18 +00002921 }
2922
2923 // Check if we stopped because of a breakpoint.
2924 NativeBreakpointSP breakpoint_sp;
2925 error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
2926 if (!error.Success () || !breakpoint_sp)
2927 {
2928 // We didn't find one at a software probe location. Nothing to do.
2929 if (log)
2930 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
2931 return Error ();
2932 }
2933
2934 // If the breakpoint is not a software breakpoint, nothing to do.
2935 if (!breakpoint_sp->IsSoftwareBreakpoint ())
2936 {
2937 if (log)
2938 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
2939 return Error ();
2940 }
2941
2942 //
2943 // We have a software breakpoint and need to adjust the PC.
2944 //
2945
2946 // Sanity check.
2947 if (breakpoint_size == 0)
2948 {
2949 // Nothing to do! How did we get here?
2950 if (log)
2951 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);
2952 return Error ();
2953 }
2954
2955 // Change the program counter.
2956 if (log)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002957 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": changing PC from 0x%" PRIx64 " to 0x%" PRIx64, __FUNCTION__, GetID (), linux_thread_sp->GetID (), initial_pc_addr, breakpoint_addr);
Todd Fialaaf245d12014-06-30 21:05:18 +00002958
2959 error = context_sp->SetPC (breakpoint_addr);
2960 if (error.Fail ())
2961 {
2962 if (log)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002963 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": failed to set PC: %s", __FUNCTION__, GetID (), linux_thread_sp->GetID (), error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00002964 return error;
2965 }
2966
2967 return error;
2968}
Chaoren Linfa03ad22015-02-03 01:50:42 +00002969
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00002970Error
2971NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec)
2972{
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00002973 FileSpec module_file_spec(module_path, true);
2974
Pavel Labath162fb8e2015-07-23 14:47:33 +00002975 bool found = false;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00002976 file_spec.Clear();
Pavel Labath162fb8e2015-07-23 14:47:33 +00002977 ProcFileReader::ProcessLineByLine(GetID(), "maps",
2978 [&] (const std::string &line)
2979 {
2980 SmallVector<StringRef, 16> columns;
2981 StringRef(line).split(columns, " ", -1, false);
2982 if (columns.size() < 6)
2983 return true; // continue searching
2984
2985 FileSpec this_file_spec(columns[5].str().c_str(), false);
2986 if (this_file_spec.GetFilename() != module_file_spec.GetFilename())
2987 return true; // continue searching
2988
2989 file_spec = this_file_spec;
2990 found = true;
2991 return false; // we are done
2992 });
2993
2994 if (! found)
2995 return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
2996 module_file_spec.GetFilename().AsCString(), GetID());
2997
2998 return Error();
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00002999}
Pavel Labathc0765592015-05-06 10:46:34 +00003000
Pavel Labath5eb721e2015-05-07 08:30:31 +00003001Error
Tamas Berghammer783bfc82015-06-18 20:43:56 +00003002NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef& file_name, lldb::addr_t& load_addr)
3003{
3004 load_addr = LLDB_INVALID_ADDRESS;
3005 Error error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
3006 [&] (const std::string &line) -> bool
3007 {
3008 StringRef maps_row(line);
3009
3010 SmallVector<StringRef, 16> maps_columns;
3011 maps_row.split(maps_columns, StringRef(" "), -1, false);
3012
3013 if (maps_columns.size() < 6)
3014 {
3015 // Return true to continue reading the proc file
3016 return true;
3017 }
3018
3019 if (maps_columns[5] == file_name)
3020 {
3021 StringExtractor addr_extractor(maps_columns[0].str().c_str());
3022 load_addr = addr_extractor.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
3023
3024 // Return false to stop reading the proc file further
3025 return false;
3026 }
3027
3028 // Return true to continue reading the proc file
3029 return true;
3030 });
3031 return error;
3032}
3033
3034Error
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003035NativeProcessLinux::ResumeThread(
Pavel Labathc0765592015-05-06 10:46:34 +00003036 lldb::tid_t tid,
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003037 NativeThreadLinux::ResumeThreadFunction request_thread_resume_function,
Pavel Labathc0765592015-05-06 10:46:34 +00003038 bool error_when_already_running)
3039{
Pavel Labath5eb721e2015-05-07 08:30:31 +00003040 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003041
3042 if (log)
3043 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ", error_when_already_running: %s)",
3044 __FUNCTION__, tid, error_when_already_running?"true":"false");
Pavel Labath5eb721e2015-05-07 08:30:31 +00003045
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003046 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
3047 lldbassert(thread_sp != nullptr);
Pavel Labath5eb721e2015-05-07 08:30:31 +00003048
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003049 auto& context = thread_sp->GetThreadContext();
Pavel Labathc0765592015-05-06 10:46:34 +00003050 // Tell the thread to resume if we don't already think it is running.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003051 const bool is_stopped = StateIsStoppedState(thread_sp->GetState(), true);
Pavel Labath5eb721e2015-05-07 08:30:31 +00003052
3053 lldbassert(!(error_when_already_running && !is_stopped));
3054
Pavel Labathc0765592015-05-06 10:46:34 +00003055 if (!is_stopped)
3056 {
3057 // It's not an error, just a log, if the error_when_already_running flag is not set.
3058 // This covers cases where, for instance, we're just trying to resume all threads
3059 // from the user side.
Pavel Labath5eb721e2015-05-07 08:30:31 +00003060 if (log)
3061 log->Printf("NativeProcessLinux::%s tid %" PRIu64 " optional resume skipped since it is already running",
3062 __FUNCTION__,
3063 tid);
3064 return Error();
Pavel Labathc0765592015-05-06 10:46:34 +00003065 }
3066
3067 // Before we do the resume below, first check if we have a pending
Pavel Labath108c3252015-05-12 09:03:18 +00003068 // stop notification that is currently waiting for
Pavel Labathc0765592015-05-06 10:46:34 +00003069 // this thread to stop. This is potentially a buggy situation since
3070 // we're ostensibly waiting for threads to stop before we send out the
3071 // pending notification, and here we are resuming one before we send
3072 // out the pending stop notification.
Pavel Labath108c3252015-05-12 09:03:18 +00003073 if (m_pending_notification_up && log && m_pending_notification_up->wait_for_stop_tids.count (tid) > 0)
Pavel Labathc0765592015-05-06 10:46:34 +00003074 {
Pavel Labath108c3252015-05-12 09:03:18 +00003075 log->Printf("NativeProcessLinux::%s about to resume tid %" PRIu64 " per explicit request but we have a pending stop notification (tid %" PRIu64 ") that is actively waiting for this thread to stop. Valid sequence of events?", __FUNCTION__, tid, m_pending_notification_up->triggering_tid);
Pavel Labathc0765592015-05-06 10:46:34 +00003076 }
3077
3078 // Request a resume. We expect this to be synchronous and the system
3079 // to reflect it is running after this completes.
3080 const auto error = request_thread_resume_function (tid, false);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003081 if (error.Success())
3082 context.request_resume_function = request_thread_resume_function;
Pavel Labath5eb721e2015-05-07 08:30:31 +00003083 else if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00003084 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00003085 log->Printf("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s",
Pavel Labathc0765592015-05-06 10:46:34 +00003086 __FUNCTION__, tid, error.AsCString ());
3087 }
3088
Pavel Labath5eb721e2015-05-07 08:30:31 +00003089 return error;
Pavel Labathc0765592015-05-06 10:46:34 +00003090}
3091
3092//===----------------------------------------------------------------------===//
3093
3094void
Pavel Labath337f3eb2015-05-08 08:57:45 +00003095NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid)
Pavel Labathc0765592015-05-06 10:46:34 +00003096{
Pavel Labath5eb721e2015-05-07 08:30:31 +00003097 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
Pavel Labathc0765592015-05-06 10:46:34 +00003098
Pavel Labath5eb721e2015-05-07 08:30:31 +00003099 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00003100 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00003101 log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ")",
Pavel Labathc0765592015-05-06 10:46:34 +00003102 __FUNCTION__, triggering_tid);
3103 }
3104
Pavel Labath337f3eb2015-05-08 08:57:45 +00003105 DoStopThreads(PendingNotificationUP(new PendingNotification(triggering_tid)));
Pavel Labathc0765592015-05-06 10:46:34 +00003106
Pavel Labath5eb721e2015-05-07 08:30:31 +00003107 if (log)
Pavel Labathc0765592015-05-06 10:46:34 +00003108 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00003109 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
Pavel Labathc0765592015-05-06 10:46:34 +00003110 }
3111}
3112
3113void
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003114NativeProcessLinux::SignalIfAllThreadsStopped()
Pavel Labathc0765592015-05-06 10:46:34 +00003115{
3116 if (m_pending_notification_up && m_pending_notification_up->wait_for_stop_tids.empty ())
3117 {
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003118 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
3119
3120 // Clear any temporary breakpoints we used to implement software single stepping.
3121 for (const auto &thread_info: m_threads_stepping_with_breakpoint)
3122 {
3123 Error error = RemoveBreakpoint (thread_info.second);
3124 if (error.Fail())
3125 if (log)
3126 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " remove stepping breakpoint: %s",
3127 __FUNCTION__, thread_info.first, error.AsCString());
3128 }
3129 m_threads_stepping_with_breakpoint.clear();
3130
3131 // Notify the delegate about the stop
Pavel Labathed89c7f2015-05-06 12:22:37 +00003132 SetCurrentThreadID(m_pending_notification_up->triggering_tid);
3133 SetState(StateType::eStateStopped, true);
Pavel Labathc0765592015-05-06 10:46:34 +00003134 m_pending_notification_up.reset();
3135 }
3136}
3137
Pavel Labathc0765592015-05-06 10:46:34 +00003138void
3139NativeProcessLinux::RequestStopOnAllRunningThreads()
3140{
3141 // Request a stop for all the thread stops that need to be stopped
3142 // and are not already known to be stopped. Keep a list of all the
3143 // threads from which we still need to hear a stop reply.
3144
3145 ThreadIDSet sent_tids;
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003146 for (const auto &thread_sp: m_threads)
Pavel Labathc0765592015-05-06 10:46:34 +00003147 {
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003148 // We only care about running threads
3149 if (StateIsStoppedState(thread_sp->GetState(), true))
3150 continue;
Pavel Labathc0765592015-05-06 10:46:34 +00003151
Pavel Labath108c3252015-05-12 09:03:18 +00003152 static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
3153 sent_tids.insert (thread_sp->GetID());
Pavel Labathc0765592015-05-06 10:46:34 +00003154 }
3155
3156 // Set the wait list to the set of tids for which we requested stops.
3157 m_pending_notification_up->wait_for_stop_tids.swap (sent_tids);
3158}
3159
Pavel Labathc0765592015-05-06 10:46:34 +00003160
Pavel Labath5eb721e2015-05-07 08:30:31 +00003161Error
3162NativeProcessLinux::ThreadDidStop (lldb::tid_t tid, bool initiated_by_llgs)
Pavel Labathc0765592015-05-06 10:46:34 +00003163{
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003164 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3165
3166 if (log)
3167 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ", %sinitiated by llgs)",
3168 __FUNCTION__, tid, initiated_by_llgs?"":"not ");
3169
Pavel Labathc0765592015-05-06 10:46:34 +00003170 // Ensure we know about the thread.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003171 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
3172 lldbassert(thread_sp != nullptr);
Pavel Labathc0765592015-05-06 10:46:34 +00003173
3174 // Update the global list of known thread states. This one is definitely stopped.
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003175 auto& context = thread_sp->GetThreadContext();
3176 const auto stop_was_requested = context.stop_requested;
3177 context.stop_requested = false;
Pavel Labathc0765592015-05-06 10:46:34 +00003178
3179 // If we have a pending notification, remove this from the set.
3180 if (m_pending_notification_up)
3181 {
3182 m_pending_notification_up->wait_for_stop_tids.erase(tid);
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003183 SignalIfAllThreadsStopped();
Pavel Labathc0765592015-05-06 10:46:34 +00003184 }
3185
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003186 Error error;
3187 if (initiated_by_llgs && context.request_resume_function && !stop_was_requested)
Pavel Labathc0765592015-05-06 10:46:34 +00003188 {
3189 // We can end up here if stop was initiated by LLGS but by this time a
3190 // thread stop has occurred - maybe initiated by another event.
Pavel Labath5eb721e2015-05-07 08:30:31 +00003191 if (log)
3192 log->Printf("Resuming thread %" PRIu64 " since stop wasn't requested", tid);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003193 error = context.request_resume_function (tid, true);
3194 if (error.Fail() && log)
Pavel Labathc0765592015-05-06 10:46:34 +00003195 {
Pavel Labath5eb721e2015-05-07 08:30:31 +00003196 log->Printf("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s",
3197 __FUNCTION__, tid, error.AsCString ());
Pavel Labathc0765592015-05-06 10:46:34 +00003198 }
3199 }
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003200 return error;
Pavel Labathc0765592015-05-06 10:46:34 +00003201}
3202
3203void
Pavel Labathed89c7f2015-05-06 12:22:37 +00003204NativeProcessLinux::DoStopThreads(PendingNotificationUP &&notification_up)
Pavel Labathc0765592015-05-06 10:46:34 +00003205{
Pavel Labath5eb721e2015-05-07 08:30:31 +00003206 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3207 if (m_pending_notification_up && log)
Pavel Labathc0765592015-05-06 10:46:34 +00003208 {
3209 // Yikes - we've already got a pending signal notification in progress.
3210 // Log this info. We lose the pending notification here.
Pavel Labath5eb721e2015-05-07 08:30:31 +00003211 log->Printf("NativeProcessLinux::%s dropping existing pending signal notification for tid %" PRIu64 ", to be replaced with signal for tid %" PRIu64,
Pavel Labathc0765592015-05-06 10:46:34 +00003212 __FUNCTION__,
3213 m_pending_notification_up->triggering_tid,
3214 notification_up->triggering_tid);
3215 }
3216 m_pending_notification_up = std::move(notification_up);
3217
Pavel Labath108c3252015-05-12 09:03:18 +00003218 RequestStopOnAllRunningThreads();
Pavel Labathc0765592015-05-06 10:46:34 +00003219
Pavel Labath9eb1ecb2015-05-15 13:49:01 +00003220 SignalIfAllThreadsStopped();
Pavel Labathc0765592015-05-06 10:46:34 +00003221}
3222
3223void
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003224NativeProcessLinux::ThreadWasCreated (lldb::tid_t tid)
Pavel Labathc0765592015-05-06 10:46:34 +00003225{
Pavel Labath1dbc6c92015-05-12 08:35:33 +00003226 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
3227
3228 if (log)
3229 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, tid);
3230
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003231 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid));
3232 lldbassert(thread_sp != nullptr);
Pavel Labathc0765592015-05-06 10:46:34 +00003233
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003234 if (m_pending_notification_up && StateIsRunningState(thread_sp->GetState()))
Pavel Labathc0765592015-05-06 10:46:34 +00003235 {
3236 // We will need to wait for this new thread to stop as well before firing the
3237 // notification.
3238 m_pending_notification_up->wait_for_stop_tids.insert(tid);
Pavel Labath8c8ff7a2015-05-11 10:03:10 +00003239 thread_sp->RequestStop();
Pavel Labathc0765592015-05-06 10:46:34 +00003240 }
3241}
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003242
Pavel Labath19cbe962015-07-21 13:20:32 +00003243void
3244NativeProcessLinux::SigchldHandler()
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003245{
Pavel Labath19cbe962015-07-21 13:20:32 +00003246 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3247 // Process all pending waitpid notifications.
3248 while (true)
3249 {
3250 int status = -1;
3251 ::pid_t wait_pid = waitpid(-1, &status, __WALL | __WNOTHREAD | WNOHANG);
3252
3253 if (wait_pid == 0)
3254 break; // We are done.
3255
3256 if (wait_pid == -1)
3257 {
3258 if (errno == EINTR)
3259 continue;
3260
3261 Error error(errno, eErrorTypePOSIX);
3262 if (log)
3263 log->Printf("NativeProcessLinux::%s waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG) failed: %s",
3264 __FUNCTION__, error.AsCString());
3265 break;
3266 }
3267
3268 bool exited = false;
3269 int signal = 0;
3270 int exit_status = 0;
3271 const char *status_cstr = nullptr;
3272 if (WIFSTOPPED(status))
3273 {
3274 signal = WSTOPSIG(status);
3275 status_cstr = "STOPPED";
3276 }
3277 else if (WIFEXITED(status))
3278 {
3279 exit_status = WEXITSTATUS(status);
3280 status_cstr = "EXITED";
3281 exited = true;
3282 }
3283 else if (WIFSIGNALED(status))
3284 {
3285 signal = WTERMSIG(status);
3286 status_cstr = "SIGNALED";
Omair Javaiddee4a862015-08-19 10:44:16 +00003287 if (wait_pid == static_cast< ::pid_t>(GetID())) {
Pavel Labath19cbe962015-07-21 13:20:32 +00003288 exited = true;
3289 exit_status = -1;
3290 }
3291 }
3292 else
3293 status_cstr = "(\?\?\?)";
3294
3295 if (log)
3296 log->Printf("NativeProcessLinux::%s: waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG)"
3297 "=> pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
3298 __FUNCTION__, wait_pid, status, status_cstr, signal, exit_status);
3299
3300 MonitorCallback (wait_pid, exited, signal, exit_status);
3301 }
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003302}
3303
3304// Wrapper for ptrace to catch errors and log calls.
3305// 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 +00003306Error
3307NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, long *result)
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003308{
Pavel Labath4a9babb2015-06-30 17:04:49 +00003309 Error error;
3310 long int ret;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003311
3312 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
3313
3314 PtraceDisplayBytes(req, data, data_size);
3315
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003316 errno = 0;
3317 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Pavel Labath4a9babb2015-06-30 17:04:49 +00003318 ret = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003319 else
Pavel Labath4a9babb2015-06-30 17:04:49 +00003320 ret = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003321
Pavel Labath4a9babb2015-06-30 17:04:49 +00003322 if (ret == -1)
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003323 error.SetErrorToErrno();
3324
Pavel Labath4a9babb2015-06-30 17:04:49 +00003325 if (result)
3326 *result = ret;
3327
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003328 if (log)
Pavel Labath4a9babb2015-06-30 17:04:49 +00003329 log->Printf("ptrace(%d, %" PRIu64 ", %p, %p, %zu)=%lX", req, pid, addr, data, data_size, ret);
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003330
3331 PtraceDisplayBytes(req, data, data_size);
3332
3333 if (log && error.GetError() != 0)
3334 {
3335 const char* str;
3336 switch (error.GetError())
3337 {
3338 case ESRCH: str = "ESRCH"; break;
3339 case EINVAL: str = "EINVAL"; break;
3340 case EBUSY: str = "EBUSY"; break;
3341 case EPERM: str = "EPERM"; break;
3342 default: str = error.AsCString();
3343 }
3344 log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
3345 }
3346
Pavel Labath4a9babb2015-06-30 17:04:49 +00003347 return error;
Tamas Berghammer068f8a72015-05-26 11:58:52 +00003348}