blob: b57e30d3c2c54a5e9f39edbf81ae9bbda6d99acd [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
10#include "lldb/lldb-python.h"
11
12#include "NativeProcessLinux.h"
13
14// C Includes
15#include <errno.h>
16#include <poll.h>
17#include <string.h>
18#include <stdint.h>
19#include <unistd.h>
Todd Fialaaf245d12014-06-30 21:05:18 +000020
21// C++ Includes
22#include <fstream>
Pavel Labathc0765592015-05-06 10:46:34 +000023#include <sstream>
Todd Fialaaf245d12014-06-30 21:05:18 +000024#include <string>
25
26// Other libraries and framework includes
27#include "lldb/Core/Debugger.h"
Tamas Berghammerd8c338d2015-04-15 09:47:02 +000028#include "lldb/Core/EmulateInstruction.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000029#include "lldb/Core/Error.h"
30#include "lldb/Core/Module.h"
Oleksiy Vyalov6edef202014-11-17 22:16:42 +000031#include "lldb/Core/ModuleSpec.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000032#include "lldb/Core/RegisterValue.h"
33#include "lldb/Core/Scalar.h"
34#include "lldb/Core/State.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000035#include "lldb/Host/common/NativeBreakpoint.h"
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +000036#include "lldb/Host/common/NativeRegisterContext.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000037#include "lldb/Host/Host.h"
Zachary Turner13b18262014-08-20 16:42:51 +000038#include "lldb/Host/HostInfo.h"
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +000039#include "lldb/Host/HostNativeThread.h"
Zachary Turner39de3112014-09-09 20:54:56 +000040#include "lldb/Host/ThreadLauncher.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000041#include "lldb/Symbol/ObjectFile.h"
Zachary Turner90aff472015-03-03 23:36:51 +000042#include "lldb/Target/Process.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000043#include "lldb/Target/ProcessLaunchInfo.h"
Chaoren Linc16f5dc2015-03-19 23:28:10 +000044#include "lldb/Utility/LLDBAssert.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000045#include "lldb/Utility/PseudoTerminal.h"
46
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000047#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000048#include "Plugins/Process/Utility/LinuxSignals.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000049#include "Utility/StringExtractor.h"
Todd Fialaaf245d12014-06-30 21:05:18 +000050#include "NativeThreadLinux.h"
51#include "ProcFileReader.h"
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000052#include "Procfs.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000053
Tamas Berghammerd8584872015-02-06 10:57:40 +000054// System includes - They have to be included after framework includes because they define some
55// macros which collide with variable names in other modules
56#include <linux/unistd.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000057#include <sys/personality.h>
58#include <sys/ptrace.h>
59#include <sys/socket.h>
Pavel Labath1107b5a2015-04-17 14:07:49 +000060#include <sys/signalfd.h>
Tamas Berghammerd8584872015-02-06 10:57:40 +000061#include <sys/syscall.h>
62#include <sys/types.h>
63#include <sys/uio.h>
64#include <sys/user.h>
65#include <sys/wait.h>
66
Tamas Berghammer1e209fc2015-03-13 11:36:47 +000067#if defined (__arm64__) || defined (__aarch64__)
68// NT_PRSTATUS and NT_FPREGSET definition
69#include <elf.h>
70#endif
71
Todd Fialacacde7d2014-09-27 16:54:22 +000072#ifdef __ANDROID__
73#define __ptrace_request int
74#define PT_DETACH PTRACE_DETACH
75#endif
Todd Fialaaf245d12014-06-30 21:05:18 +000076
77#define DEBUG_PTRACE_MAXBYTES 20
78
79// Support ptrace extensions even when compiled without required kernel support
Todd Fialadda61942014-07-02 21:34:04 +000080#ifndef PT_GETREGS
Todd Fialaaf245d12014-06-30 21:05:18 +000081#ifndef PTRACE_GETREGS
Todd Fialadda61942014-07-02 21:34:04 +000082 #define PTRACE_GETREGS 12
Todd Fialaaf245d12014-06-30 21:05:18 +000083#endif
Todd Fialadda61942014-07-02 21:34:04 +000084#endif
85#ifndef PT_SETREGS
Todd Fialaaf245d12014-06-30 21:05:18 +000086#ifndef PTRACE_SETREGS
87 #define PTRACE_SETREGS 13
88#endif
Todd Fialadda61942014-07-02 21:34:04 +000089#endif
90#ifndef PT_GETFPREGS
91#ifndef PTRACE_GETFPREGS
92 #define PTRACE_GETFPREGS 14
93#endif
94#endif
95#ifndef PT_SETFPREGS
96#ifndef PTRACE_SETFPREGS
97 #define PTRACE_SETFPREGS 15
98#endif
99#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000100#ifndef PTRACE_GETREGSET
101 #define PTRACE_GETREGSET 0x4204
102#endif
103#ifndef PTRACE_SETREGSET
104 #define PTRACE_SETREGSET 0x4205
105#endif
106#ifndef PTRACE_GET_THREAD_AREA
107 #define PTRACE_GET_THREAD_AREA 25
108#endif
109#ifndef PTRACE_ARCH_PRCTL
110 #define PTRACE_ARCH_PRCTL 30
111#endif
112#ifndef ARCH_GET_FS
113 #define ARCH_SET_GS 0x1001
114 #define ARCH_SET_FS 0x1002
115 #define ARCH_GET_FS 0x1003
116 #define ARCH_GET_GS 0x1004
117#endif
118
Todd Fiala0bce1b62014-08-17 00:10:50 +0000119#define LLDB_PERSONALITY_GET_CURRENT_SETTINGS 0xffffffff
Todd Fialaaf245d12014-06-30 21:05:18 +0000120
121// Support hardware breakpoints in case it has not been defined
122#ifndef TRAP_HWBKPT
123 #define TRAP_HWBKPT 4
124#endif
125
126// Try to define a macro to encapsulate the tgkill syscall
127// fall back on kill() if tgkill isn't available
Chaoren Linc9346592015-02-28 00:20:16 +0000128#define tgkill(pid, tid, sig) \
129 syscall(SYS_tgkill, static_cast<::pid_t>(pid), static_cast<::pid_t>(tid), sig)
Todd Fialaaf245d12014-06-30 21:05:18 +0000130
131// We disable the tracing of ptrace calls for integration builds to
132// avoid the additional indirection and checks.
133#ifndef LLDB_CONFIGURATION_BUILDANDINTEGRATION
Chaoren Lin97ccc292015-02-03 01:51:12 +0000134#define PTRACE(req, pid, addr, data, data_size, error) \
135 PtraceWrapper((req), (pid), (addr), (data), (data_size), (error), #req, __FILE__, __LINE__)
Todd Fialaaf245d12014-06-30 21:05:18 +0000136#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000137#define PTRACE(req, pid, addr, data, data_size, error) \
138 PtraceWrapper((req), (pid), (addr), (data), (data_size), (error))
Todd Fialaaf245d12014-06-30 21:05:18 +0000139#endif
140
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +0000141using namespace lldb;
142using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000143using namespace lldb_private::process_linux;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +0000144using namespace llvm;
145
Todd Fialaaf245d12014-06-30 21:05:18 +0000146// Private bits we only need internally.
147namespace
148{
Todd Fialaaf245d12014-06-30 21:05:18 +0000149 const UnixSignals&
150 GetUnixSignals ()
151 {
152 static process_linux::LinuxSignals signals;
153 return signals;
154 }
155
Pavel Labathc0765592015-05-06 10:46:34 +0000156 NativeProcessLinux::LogFunction
Chaoren Linfa03ad22015-02-03 01:50:42 +0000157 GetThreadLoggerFunction ()
158 {
159 return [](const char *format, va_list args)
160 {
161 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
162 if (log)
163 log->VAPrintf (format, args);
164 };
165 }
166
167 void
168 CoordinatorErrorHandler (const std::string &error_message)
169 {
170 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
171 if (log)
Chaoren Lin86fd8e42015-02-03 01:51:15 +0000172 log->Printf ("NativeProcessLinux::%s %s", __FUNCTION__, error_message.c_str ());
Pavel Labathc0765592015-05-06 10:46:34 +0000173 assert (false && "NativeProcessLinux error reported");
Chaoren Linfa03ad22015-02-03 01:50:42 +0000174 }
175
Todd Fialaaf245d12014-06-30 21:05:18 +0000176 Error
177 ResolveProcessArchitecture (lldb::pid_t pid, Platform &platform, ArchSpec &arch)
178 {
179 // Grab process info for the running process.
180 ProcessInstanceInfo process_info;
181 if (!platform.GetProcessInfo (pid, process_info))
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000182 return Error("failed to get process info");
Todd Fialaaf245d12014-06-30 21:05:18 +0000183
184 // Resolve the executable module.
185 ModuleSP exe_module_sp;
Chaoren Line56f6dc2015-03-01 04:31:16 +0000186 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Todd Fialaaf245d12014-06-30 21:05:18 +0000187 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths ());
188 Error error = platform.ResolveExecutable(
Oleksiy Vyalov54539332014-11-17 22:42:28 +0000189 exe_module_spec,
Todd Fialaaf245d12014-06-30 21:05:18 +0000190 exe_module_sp,
191 executable_search_paths.GetSize () ? &executable_search_paths : NULL);
192
193 if (!error.Success ())
194 return error;
195
196 // Check if we've got our architecture from the exe_module.
197 arch = exe_module_sp->GetArchitecture ();
198 if (arch.IsValid ())
199 return Error();
200 else
201 return Error("failed to retrieve a valid architecture from the exe module");
202 }
203
204 void
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000205 DisplayBytes (StreamString &s, void *bytes, uint32_t count)
Todd Fialaaf245d12014-06-30 21:05:18 +0000206 {
207 uint8_t *ptr = (uint8_t *)bytes;
208 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
209 for(uint32_t i=0; i<loop_count; i++)
210 {
211 s.Printf ("[%x]", *ptr);
212 ptr++;
213 }
214 }
215
216 void
217 PtraceDisplayBytes(int &req, void *data, size_t data_size)
218 {
219 StreamString buf;
220 Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
221 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
222
223 if (verbose_log)
224 {
225 switch(req)
226 {
227 case PTRACE_POKETEXT:
228 {
229 DisplayBytes(buf, &data, 8);
230 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
231 break;
232 }
233 case PTRACE_POKEDATA:
234 {
235 DisplayBytes(buf, &data, 8);
236 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
237 break;
238 }
239 case PTRACE_POKEUSER:
240 {
241 DisplayBytes(buf, &data, 8);
242 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
243 break;
244 }
245 case PTRACE_SETREGS:
246 {
247 DisplayBytes(buf, data, data_size);
248 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
249 break;
250 }
251 case PTRACE_SETFPREGS:
252 {
253 DisplayBytes(buf, data, data_size);
254 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
255 break;
256 }
257 case PTRACE_SETSIGINFO:
258 {
259 DisplayBytes(buf, data, sizeof(siginfo_t));
260 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
261 break;
262 }
263 case PTRACE_SETREGSET:
264 {
265 // Extract iov_base from data, which is a pointer to the struct IOVEC
266 DisplayBytes(buf, *(void **)data, data_size);
267 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
268 break;
269 }
270 default:
271 {
272 }
273 }
274 }
275 }
276
277 // Wrapper for ptrace to catch errors and log calls.
278 // Note that ptrace sets errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
279 long
Chaoren Lin97ccc292015-02-03 01:51:12 +0000280 PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, Error& error,
281 const char* reqName, const char* file, int line)
Todd Fialaaf245d12014-06-30 21:05:18 +0000282 {
283 long int result;
284
285 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
286
287 PtraceDisplayBytes(req, data, data_size);
288
Chaoren Lin97ccc292015-02-03 01:51:12 +0000289 error.Clear();
Todd Fialaaf245d12014-06-30 21:05:18 +0000290 errno = 0;
291 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Todd Fiala202ecd22014-07-10 04:39:13 +0000292 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000293 else
Todd Fiala202ecd22014-07-10 04:39:13 +0000294 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000295
Chaoren Lin97ccc292015-02-03 01:51:12 +0000296 if (result == -1)
297 error.SetErrorToErrno();
298
Todd Fialaaf245d12014-06-30 21:05:18 +0000299 if (log)
300 log->Printf("ptrace(%s, %" PRIu64 ", %p, %p, %zu)=%lX called from file %s line %d",
301 reqName, pid, addr, data, data_size, result, file, line);
302
303 PtraceDisplayBytes(req, data, data_size);
304
Chaoren Lin97ccc292015-02-03 01:51:12 +0000305 if (log && error.GetError() != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +0000306 {
307 const char* str;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000308 switch (error.GetError())
Todd Fialaaf245d12014-06-30 21:05:18 +0000309 {
310 case ESRCH: str = "ESRCH"; break;
311 case EINVAL: str = "EINVAL"; break;
312 case EBUSY: str = "EBUSY"; break;
313 case EPERM: str = "EPERM"; break;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000314 default: str = error.AsCString();
Todd Fialaaf245d12014-06-30 21:05:18 +0000315 }
Chaoren Lin97ccc292015-02-03 01:51:12 +0000316 log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
Todd Fialaaf245d12014-06-30 21:05:18 +0000317 }
318
319 return result;
320 }
321
322#ifdef LLDB_CONFIGURATION_BUILDANDINTEGRATION
323 // Wrapper for ptrace when logging is not required.
324 // Sets errno to 0 prior to calling ptrace.
325 long
Chaoren Lin97ccc292015-02-03 01:51:12 +0000326 PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, Error& error)
Todd Fialaaf245d12014-06-30 21:05:18 +0000327 {
328 long result = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000329
330 error.Clear();
Todd Fialaaf245d12014-06-30 21:05:18 +0000331 errno = 0;
332 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
Todd Fiala202ecd22014-07-10 04:39:13 +0000333 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000334 else
Todd Fiala202ecd22014-07-10 04:39:13 +0000335 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000336
337 if (result == -1)
338 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +0000339 return result;
340 }
341#endif
342
343 //------------------------------------------------------------------------------
344 // Static implementations of NativeProcessLinux::ReadMemory and
345 // NativeProcessLinux::WriteMemory. This enables mutual recursion between these
346 // functions without needed to go thru the thread funnel.
347
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000348 size_t
349 DoReadMemory(
Todd Fialaaf245d12014-06-30 21:05:18 +0000350 lldb::pid_t pid,
351 lldb::addr_t vm_addr,
352 void *buf,
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000353 size_t size,
Todd Fialaaf245d12014-06-30 21:05:18 +0000354 Error &error)
355 {
356 // ptrace word size is determined by the host, not the child
357 static const unsigned word_size = sizeof(void*);
358 unsigned char *dst = static_cast<unsigned char*>(buf);
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000359 size_t bytes_read;
360 size_t remainder;
Todd Fialaaf245d12014-06-30 21:05:18 +0000361 long data;
362
363 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
364 if (log)
365 ProcessPOSIXLog::IncNestLevel();
366 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
367 log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
368 pid, word_size, (void*)vm_addr, buf, size);
369
370 assert(sizeof(data) >= word_size);
371 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
372 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000373 data = PTRACE(PTRACE_PEEKDATA, pid, (void*)vm_addr, nullptr, 0, error);
374 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000375 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000376 if (log)
377 ProcessPOSIXLog::DecNestLevel();
378 return bytes_read;
379 }
380
381 remainder = size - bytes_read;
382 remainder = remainder > word_size ? word_size : remainder;
383
384 // Copy the data into our buffer
385 for (unsigned i = 0; i < remainder; ++i)
386 dst[i] = ((data >> i*8) & 0xFF);
387
388 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
389 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
390 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
391 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
392 {
393 uintptr_t print_dst = 0;
394 // Format bytes from data by moving into print_dst for log output
395 for (unsigned i = 0; i < remainder; ++i)
396 print_dst |= (((data >> i*8) & 0xFF) << i*8);
397 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
398 (void*)vm_addr, print_dst, (unsigned long)data);
399 }
400
401 vm_addr += word_size;
402 dst += word_size;
403 }
404
405 if (log)
406 ProcessPOSIXLog::DecNestLevel();
407 return bytes_read;
408 }
409
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000410 size_t
Todd Fialaaf245d12014-06-30 21:05:18 +0000411 DoWriteMemory(
412 lldb::pid_t pid,
413 lldb::addr_t vm_addr,
414 const void *buf,
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000415 size_t size,
Todd Fialaaf245d12014-06-30 21:05:18 +0000416 Error &error)
417 {
418 // ptrace word size is determined by the host, not the child
419 static const unsigned word_size = sizeof(void*);
420 const unsigned char *src = static_cast<const unsigned char*>(buf);
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000421 size_t bytes_written = 0;
422 size_t remainder;
Todd Fialaaf245d12014-06-30 21:05:18 +0000423
424 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
425 if (log)
426 ProcessPOSIXLog::IncNestLevel();
427 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
428 log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %u, %p, %p, %" PRIu64 ")", __FUNCTION__,
429 pid, word_size, (void*)vm_addr, buf, size);
430
431 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
432 {
433 remainder = size - bytes_written;
434 remainder = remainder > word_size ? word_size : remainder;
435
436 if (remainder == word_size)
437 {
438 unsigned long data = 0;
439 assert(sizeof(data) >= word_size);
440 for (unsigned i = 0; i < word_size; ++i)
441 data |= (unsigned long)src[i] << i*8;
442
443 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
444 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
445 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
446 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
447 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000448 (void*)vm_addr, *(const unsigned long*)src, data);
Todd Fialaaf245d12014-06-30 21:05:18 +0000449
Chaoren Lin97ccc292015-02-03 01:51:12 +0000450 if (PTRACE(PTRACE_POKEDATA, pid, (void*)vm_addr, (void*)data, 0, error))
Todd Fialaaf245d12014-06-30 21:05:18 +0000451 {
Todd Fialaaf245d12014-06-30 21:05:18 +0000452 if (log)
453 ProcessPOSIXLog::DecNestLevel();
454 return bytes_written;
455 }
456 }
457 else
458 {
459 unsigned char buff[8];
460 if (DoReadMemory(pid, vm_addr,
461 buff, word_size, error) != word_size)
462 {
463 if (log)
464 ProcessPOSIXLog::DecNestLevel();
465 return bytes_written;
466 }
467
468 memcpy(buff, src, remainder);
469
470 if (DoWriteMemory(pid, vm_addr,
471 buff, word_size, error) != word_size)
472 {
473 if (log)
474 ProcessPOSIXLog::DecNestLevel();
475 return bytes_written;
476 }
477
478 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
479 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
480 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
481 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
482 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000483 (void*)vm_addr, *(const unsigned long*)src, *(unsigned long*)buff);
Todd Fialaaf245d12014-06-30 21:05:18 +0000484 }
485
486 vm_addr += word_size;
487 src += word_size;
488 }
489 if (log)
490 ProcessPOSIXLog::DecNestLevel();
491 return bytes_written;
492 }
493
494 //------------------------------------------------------------------------------
495 /// @class Operation
496 /// @brief Represents a NativeProcessLinux operation.
497 ///
498 /// Under Linux, it is not possible to ptrace() from any other thread but the
499 /// one that spawned or attached to the process from the start. Therefore, when
500 /// a NativeProcessLinux is asked to deliver or change the state of an inferior
501 /// process the operation must be "funneled" to a specific thread to perform the
502 /// task. The Operation class provides an abstract base for all services the
503 /// NativeProcessLinux must perform via the single virtual function Execute, thus
504 /// encapsulating the code that needs to run in the privileged context.
505 class Operation
506 {
507 public:
508 Operation () : m_error() { }
509
510 virtual
511 ~Operation() {}
512
513 virtual void
514 Execute (NativeProcessLinux *process) = 0;
515
516 const Error &
517 GetError () const { return m_error; }
518
519 protected:
520 Error m_error;
521 };
522
523 //------------------------------------------------------------------------------
524 /// @class ReadOperation
525 /// @brief Implements NativeProcessLinux::ReadMemory.
526 class ReadOperation : public Operation
527 {
528 public:
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000529 ReadOperation(
Todd Fialaaf245d12014-06-30 21:05:18 +0000530 lldb::addr_t addr,
531 void *buff,
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000532 size_t size,
533 size_t &result) :
Todd Fialaaf245d12014-06-30 21:05:18 +0000534 Operation (),
535 m_addr (addr),
536 m_buff (buff),
537 m_size (size),
538 m_result (result)
539 {
540 }
541
542 void Execute (NativeProcessLinux *process) override;
543
544 private:
545 lldb::addr_t m_addr;
546 void *m_buff;
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000547 size_t m_size;
548 size_t &m_result;
Todd Fialaaf245d12014-06-30 21:05:18 +0000549 };
550
551 void
552 ReadOperation::Execute (NativeProcessLinux *process)
553 {
554 m_result = DoReadMemory (process->GetID (), m_addr, m_buff, m_size, m_error);
555 }
556
557 //------------------------------------------------------------------------------
558 /// @class WriteOperation
559 /// @brief Implements NativeProcessLinux::WriteMemory.
560 class WriteOperation : public Operation
561 {
562 public:
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000563 WriteOperation(
Todd Fialaaf245d12014-06-30 21:05:18 +0000564 lldb::addr_t addr,
565 const void *buff,
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000566 size_t size,
567 size_t &result) :
Todd Fialaaf245d12014-06-30 21:05:18 +0000568 Operation (),
569 m_addr (addr),
570 m_buff (buff),
571 m_size (size),
572 m_result (result)
573 {
574 }
575
576 void Execute (NativeProcessLinux *process) override;
577
578 private:
579 lldb::addr_t m_addr;
580 const void *m_buff;
Chaoren Lin3eb4b452015-04-29 17:24:48 +0000581 size_t m_size;
582 size_t &m_result;
Todd Fialaaf245d12014-06-30 21:05:18 +0000583 };
584
585 void
586 WriteOperation::Execute(NativeProcessLinux *process)
587 {
588 m_result = DoWriteMemory (process->GetID (), m_addr, m_buff, m_size, m_error);
589 }
590
591 //------------------------------------------------------------------------------
592 /// @class ReadRegOperation
593 /// @brief Implements NativeProcessLinux::ReadRegisterValue.
594 class ReadRegOperation : public Operation
595 {
596 public:
597 ReadRegOperation(lldb::tid_t tid, uint32_t offset, const char *reg_name,
Chaoren Lin97ccc292015-02-03 01:51:12 +0000598 RegisterValue &value)
599 : m_tid(tid),
600 m_offset(static_cast<uintptr_t> (offset)),
601 m_reg_name(reg_name),
602 m_value(value)
Todd Fialaaf245d12014-06-30 21:05:18 +0000603 { }
604
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000605 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000606
607 private:
608 lldb::tid_t m_tid;
609 uintptr_t m_offset;
610 const char *m_reg_name;
611 RegisterValue &m_value;
Todd Fialaaf245d12014-06-30 21:05:18 +0000612 };
613
614 void
615 ReadRegOperation::Execute(NativeProcessLinux *monitor)
616 {
Todd Fiala0fceef82014-09-15 17:09:23 +0000617#if defined (__arm64__) || defined (__aarch64__)
618 if (m_offset > sizeof(struct user_pt_regs))
619 {
620 uintptr_t offset = m_offset - sizeof(struct user_pt_regs);
621 if (offset > sizeof(struct user_fpsimd_state))
622 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000623 m_error.SetErrorString("invalid offset value");
624 return;
Todd Fiala0fceef82014-09-15 17:09:23 +0000625 }
Chaoren Lin97ccc292015-02-03 01:51:12 +0000626 elf_fpregset_t regs;
627 int regset = NT_FPREGSET;
628 struct iovec ioVec;
Todd Fiala0fceef82014-09-15 17:09:23 +0000629
Chaoren Lin97ccc292015-02-03 01:51:12 +0000630 ioVec.iov_base = &regs;
631 ioVec.iov_len = sizeof regs;
632 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
633 if (m_error.Success())
634 {
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000635 ArchSpec arch;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000636 if (monitor->GetArchitecture(arch))
637 m_value.SetBytes((void *)(((unsigned char *)(&regs)) + offset), 16, arch.GetByteOrder());
Todd Fiala0fceef82014-09-15 17:09:23 +0000638 else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000639 m_error.SetErrorString("failed to get architecture");
Todd Fiala0fceef82014-09-15 17:09:23 +0000640 }
641 }
642 else
643 {
644 elf_gregset_t regs;
645 int regset = NT_PRSTATUS;
646 struct iovec ioVec;
647
648 ioVec.iov_base = &regs;
649 ioVec.iov_len = sizeof regs;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000650 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
651 if (m_error.Success())
Todd Fiala0fceef82014-09-15 17:09:23 +0000652 {
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000653 ArchSpec arch;
Todd Fiala0fceef82014-09-15 17:09:23 +0000654 if (monitor->GetArchitecture(arch))
Todd Fiala0fceef82014-09-15 17:09:23 +0000655 m_value.SetBytes((void *)(((unsigned char *)(regs)) + m_offset), 8, arch.GetByteOrder());
Chaoren Lin97ccc292015-02-03 01:51:12 +0000656 else
657 m_error.SetErrorString("failed to get architecture");
Todd Fiala0fceef82014-09-15 17:09:23 +0000658 }
659 }
Mohit K. Bhakkad09ba1a32015-03-31 12:01:27 +0000660#elif defined (__mips__)
661 elf_gregset_t regs;
662 PTRACE(PTRACE_GETREGS, m_tid, NULL, &regs, sizeof regs, m_error);
663 if (m_error.Success())
664 {
665 lldb_private::ArchSpec arch;
666 if (monitor->GetArchitecture(arch))
667 m_value.SetBytes((void *)(((unsigned char *)(regs)) + m_offset), 8, arch.GetByteOrder());
668 else
669 m_error.SetErrorString("failed to get architecture");
670 }
Todd Fiala0fceef82014-09-15 17:09:23 +0000671#else
Todd Fialaaf245d12014-06-30 21:05:18 +0000672 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
673
Tamas Berghammeradf8adb2015-03-25 10:14:19 +0000674 lldb::addr_t data = static_cast<unsigned long>(PTRACE(PTRACE_PEEKUSER, m_tid, (void*)m_offset, nullptr, 0, m_error));
Chaoren Lin97ccc292015-02-03 01:51:12 +0000675 if (m_error.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +0000676 m_value = data;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000677
Todd Fialaaf245d12014-06-30 21:05:18 +0000678 if (log)
679 log->Printf ("NativeProcessLinux::%s() reg %s: 0x%" PRIx64, __FUNCTION__,
680 m_reg_name, data);
Todd Fiala0fceef82014-09-15 17:09:23 +0000681#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000682 }
683
684 //------------------------------------------------------------------------------
685 /// @class WriteRegOperation
686 /// @brief Implements NativeProcessLinux::WriteRegisterValue.
687 class WriteRegOperation : public Operation
688 {
689 public:
690 WriteRegOperation(lldb::tid_t tid, unsigned offset, const char *reg_name,
Chaoren Lin97ccc292015-02-03 01:51:12 +0000691 const RegisterValue &value)
692 : m_tid(tid),
693 m_offset(offset),
694 m_reg_name(reg_name),
695 m_value(value)
Todd Fialaaf245d12014-06-30 21:05:18 +0000696 { }
697
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000698 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000699
700 private:
701 lldb::tid_t m_tid;
702 uintptr_t m_offset;
703 const char *m_reg_name;
704 const RegisterValue &m_value;
Todd Fialaaf245d12014-06-30 21:05:18 +0000705 };
706
707 void
708 WriteRegOperation::Execute(NativeProcessLinux *monitor)
709 {
Todd Fiala0fceef82014-09-15 17:09:23 +0000710#if defined (__arm64__) || defined (__aarch64__)
711 if (m_offset > sizeof(struct user_pt_regs))
712 {
713 uintptr_t offset = m_offset - sizeof(struct user_pt_regs);
714 if (offset > sizeof(struct user_fpsimd_state))
715 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000716 m_error.SetErrorString("invalid offset value");
717 return;
Todd Fiala0fceef82014-09-15 17:09:23 +0000718 }
Chaoren Lin97ccc292015-02-03 01:51:12 +0000719 elf_fpregset_t regs;
720 int regset = NT_FPREGSET;
721 struct iovec ioVec;
Todd Fiala0fceef82014-09-15 17:09:23 +0000722
Chaoren Lin97ccc292015-02-03 01:51:12 +0000723 ioVec.iov_base = &regs;
724 ioVec.iov_len = sizeof regs;
725 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Bhushan D. Attarde9425b322015-03-12 09:17:22 +0000726 if (m_error.Success())
Chaoren Lin97ccc292015-02-03 01:51:12 +0000727 {
728 ::memcpy((void *)(((unsigned char *)(&regs)) + offset), m_value.GetBytes(), 16);
729 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Todd Fiala0fceef82014-09-15 17:09:23 +0000730 }
731 }
732 else
733 {
734 elf_gregset_t regs;
735 int regset = NT_PRSTATUS;
736 struct iovec ioVec;
737
738 ioVec.iov_base = &regs;
739 ioVec.iov_len = sizeof regs;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000740 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Bhushan D. Attarde9425b322015-03-12 09:17:22 +0000741 if (m_error.Success())
Todd Fiala0fceef82014-09-15 17:09:23 +0000742 {
743 ::memcpy((void *)(((unsigned char *)(&regs)) + m_offset), m_value.GetBytes(), 8);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000744 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, sizeof regs, m_error);
Todd Fiala0fceef82014-09-15 17:09:23 +0000745 }
746 }
Mohit K. Bhakkad09ba1a32015-03-31 12:01:27 +0000747#elif defined (__mips__)
748 elf_gregset_t regs;
749 PTRACE(PTRACE_GETREGS, m_tid, NULL, &regs, sizeof regs, m_error);
750 if (m_error.Success())
751 {
752 ::memcpy((void *)(((unsigned char *)(&regs)) + m_offset), m_value.GetBytes(), 8);
753 PTRACE(PTRACE_SETREGS, m_tid, NULL, &regs, sizeof regs, m_error);
754 }
Todd Fiala0fceef82014-09-15 17:09:23 +0000755#else
Todd Fialaaf245d12014-06-30 21:05:18 +0000756 void* buf;
757 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
758
759 buf = (void*) m_value.GetAsUInt64();
760
761 if (log)
762 log->Printf ("NativeProcessLinux::%s() reg %s: %p", __FUNCTION__, m_reg_name, buf);
Chaoren Lin97ccc292015-02-03 01:51:12 +0000763 PTRACE(PTRACE_POKEUSER, m_tid, (void*)m_offset, buf, 0, m_error);
Todd Fiala0fceef82014-09-15 17:09:23 +0000764#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000765 }
766
767 //------------------------------------------------------------------------------
768 /// @class ReadGPROperation
769 /// @brief Implements NativeProcessLinux::ReadGPR.
770 class ReadGPROperation : public Operation
771 {
772 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000773 ReadGPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
774 : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000775 { }
776
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000777 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000778
779 private:
780 lldb::tid_t m_tid;
781 void *m_buf;
782 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000783 };
784
785 void
786 ReadGPROperation::Execute(NativeProcessLinux *monitor)
787 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000788#if defined (__arm64__) || defined (__aarch64__)
789 int regset = NT_PRSTATUS;
790 struct iovec ioVec;
791
792 ioVec.iov_base = m_buf;
793 ioVec.iov_len = m_buf_size;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000794 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000795#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000796 PTRACE(PTRACE_GETREGS, m_tid, nullptr, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000797#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000798 }
799
800 //------------------------------------------------------------------------------
801 /// @class ReadFPROperation
802 /// @brief Implements NativeProcessLinux::ReadFPR.
803 class ReadFPROperation : public Operation
804 {
805 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000806 ReadFPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
807 : m_tid(tid),
808 m_buf(buf),
809 m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000810 { }
811
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000812 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000813
814 private:
815 lldb::tid_t m_tid;
816 void *m_buf;
817 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000818 };
819
820 void
821 ReadFPROperation::Execute(NativeProcessLinux *monitor)
822 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000823#if defined (__arm64__) || defined (__aarch64__)
824 int regset = NT_FPREGSET;
825 struct iovec ioVec;
826
827 ioVec.iov_base = m_buf;
828 ioVec.iov_len = m_buf_size;
Tamas Berghammer1e209fc2015-03-13 11:36:47 +0000829 PTRACE(PTRACE_GETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000830#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000831 PTRACE(PTRACE_GETFPREGS, m_tid, nullptr, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000832#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000833 }
834
835 //------------------------------------------------------------------------------
836 /// @class ReadRegisterSetOperation
837 /// @brief Implements NativeProcessLinux::ReadRegisterSet.
838 class ReadRegisterSetOperation : public Operation
839 {
840 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000841 ReadRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
842 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset)
Todd Fialaaf245d12014-06-30 21:05:18 +0000843 { }
844
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000845 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000846
847 private:
848 lldb::tid_t m_tid;
849 void *m_buf;
850 size_t m_buf_size;
851 const unsigned int m_regset;
Todd Fialaaf245d12014-06-30 21:05:18 +0000852 };
853
854 void
855 ReadRegisterSetOperation::Execute(NativeProcessLinux *monitor)
856 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000857 PTRACE(PTRACE_GETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000858 }
859
860 //------------------------------------------------------------------------------
861 /// @class WriteGPROperation
862 /// @brief Implements NativeProcessLinux::WriteGPR.
863 class WriteGPROperation : public Operation
864 {
865 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000866 WriteGPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
867 : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000868 { }
869
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000870 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000871
872 private:
873 lldb::tid_t m_tid;
874 void *m_buf;
875 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000876 };
877
878 void
879 WriteGPROperation::Execute(NativeProcessLinux *monitor)
880 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000881#if defined (__arm64__) || defined (__aarch64__)
882 int regset = NT_PRSTATUS;
883 struct iovec ioVec;
884
885 ioVec.iov_base = m_buf;
886 ioVec.iov_len = m_buf_size;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000887 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000888#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000889 PTRACE(PTRACE_SETREGS, m_tid, NULL, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000890#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000891 }
892
893 //------------------------------------------------------------------------------
894 /// @class WriteFPROperation
895 /// @brief Implements NativeProcessLinux::WriteFPR.
896 class WriteFPROperation : public Operation
897 {
898 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000899 WriteFPROperation(lldb::tid_t tid, void *buf, size_t buf_size)
900 : m_tid(tid), m_buf(buf), m_buf_size(buf_size)
Todd Fialaaf245d12014-06-30 21:05:18 +0000901 { }
902
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000903 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000904
905 private:
906 lldb::tid_t m_tid;
907 void *m_buf;
908 size_t m_buf_size;
Todd Fialaaf245d12014-06-30 21:05:18 +0000909 };
910
911 void
912 WriteFPROperation::Execute(NativeProcessLinux *monitor)
913 {
Todd Fiala6ac1be42014-08-21 16:34:03 +0000914#if defined (__arm64__) || defined (__aarch64__)
915 int regset = NT_FPREGSET;
916 struct iovec ioVec;
917
918 ioVec.iov_base = m_buf;
919 ioVec.iov_len = m_buf_size;
Chaoren Lin97ccc292015-02-03 01:51:12 +0000920 PTRACE(PTRACE_SETREGSET, m_tid, &regset, &ioVec, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000921#else
Chaoren Lin97ccc292015-02-03 01:51:12 +0000922 PTRACE(PTRACE_SETFPREGS, m_tid, NULL, m_buf, m_buf_size, m_error);
Todd Fiala6ac1be42014-08-21 16:34:03 +0000923#endif
Todd Fialaaf245d12014-06-30 21:05:18 +0000924 }
925
926 //------------------------------------------------------------------------------
927 /// @class WriteRegisterSetOperation
928 /// @brief Implements NativeProcessLinux::WriteRegisterSet.
929 class WriteRegisterSetOperation : public Operation
930 {
931 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000932 WriteRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
933 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset)
Todd Fialaaf245d12014-06-30 21:05:18 +0000934 { }
935
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000936 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000937
938 private:
939 lldb::tid_t m_tid;
940 void *m_buf;
941 size_t m_buf_size;
942 const unsigned int m_regset;
Todd Fialaaf245d12014-06-30 21:05:18 +0000943 };
944
945 void
946 WriteRegisterSetOperation::Execute(NativeProcessLinux *monitor)
947 {
Chaoren Lin97ccc292015-02-03 01:51:12 +0000948 PTRACE(PTRACE_SETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +0000949 }
950
951 //------------------------------------------------------------------------------
952 /// @class ResumeOperation
953 /// @brief Implements NativeProcessLinux::Resume.
954 class ResumeOperation : public Operation
955 {
956 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000957 ResumeOperation(lldb::tid_t tid, uint32_t signo) :
958 m_tid(tid), m_signo(signo) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000959
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000960 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000961
962 private:
963 lldb::tid_t m_tid;
964 uint32_t m_signo;
Todd Fialaaf245d12014-06-30 21:05:18 +0000965 };
966
967 void
968 ResumeOperation::Execute(NativeProcessLinux *monitor)
969 {
970 intptr_t data = 0;
971
972 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
973 data = m_signo;
974
Chaoren Lin97ccc292015-02-03 01:51:12 +0000975 PTRACE(PTRACE_CONT, m_tid, nullptr, (void*)data, 0, m_error);
976 if (m_error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +0000977 {
978 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
979
980 if (log)
Chaoren Lin97ccc292015-02-03 01:51:12 +0000981 log->Printf ("ResumeOperation (%" PRIu64 ") failed: %s", m_tid, m_error.AsCString());
Todd Fialaaf245d12014-06-30 21:05:18 +0000982 }
Todd Fialaaf245d12014-06-30 21:05:18 +0000983 }
984
985 //------------------------------------------------------------------------------
986 /// @class SingleStepOperation
987 /// @brief Implements NativeProcessLinux::SingleStep.
988 class SingleStepOperation : public Operation
989 {
990 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +0000991 SingleStepOperation(lldb::tid_t tid, uint32_t signo)
992 : m_tid(tid), m_signo(signo) { }
Todd Fialaaf245d12014-06-30 21:05:18 +0000993
Tamas Berghammerd542efd2015-03-25 15:37:56 +0000994 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +0000995
996 private:
997 lldb::tid_t m_tid;
998 uint32_t m_signo;
Todd Fialaaf245d12014-06-30 21:05:18 +0000999 };
1000
1001 void
1002 SingleStepOperation::Execute(NativeProcessLinux *monitor)
1003 {
1004 intptr_t data = 0;
1005
1006 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
1007 data = m_signo;
1008
Chaoren Lin97ccc292015-02-03 01:51:12 +00001009 PTRACE(PTRACE_SINGLESTEP, m_tid, nullptr, (void*)data, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001010 }
1011
1012 //------------------------------------------------------------------------------
1013 /// @class SiginfoOperation
1014 /// @brief Implements NativeProcessLinux::GetSignalInfo.
1015 class SiginfoOperation : public Operation
1016 {
1017 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +00001018 SiginfoOperation(lldb::tid_t tid, void *info)
1019 : m_tid(tid), m_info(info) { }
Todd Fialaaf245d12014-06-30 21:05:18 +00001020
Tamas Berghammerd542efd2015-03-25 15:37:56 +00001021 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +00001022
1023 private:
1024 lldb::tid_t m_tid;
1025 void *m_info;
Todd Fialaaf245d12014-06-30 21:05:18 +00001026 };
1027
1028 void
1029 SiginfoOperation::Execute(NativeProcessLinux *monitor)
1030 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001031 PTRACE(PTRACE_GETSIGINFO, m_tid, nullptr, m_info, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001032 }
1033
1034 //------------------------------------------------------------------------------
1035 /// @class EventMessageOperation
1036 /// @brief Implements NativeProcessLinux::GetEventMessage.
1037 class EventMessageOperation : public Operation
1038 {
1039 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +00001040 EventMessageOperation(lldb::tid_t tid, unsigned long *message)
1041 : m_tid(tid), m_message(message) { }
Todd Fialaaf245d12014-06-30 21:05:18 +00001042
Tamas Berghammerd542efd2015-03-25 15:37:56 +00001043 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +00001044
1045 private:
1046 lldb::tid_t m_tid;
1047 unsigned long *m_message;
Todd Fialaaf245d12014-06-30 21:05:18 +00001048 };
1049
1050 void
1051 EventMessageOperation::Execute(NativeProcessLinux *monitor)
1052 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001053 PTRACE(PTRACE_GETEVENTMSG, m_tid, nullptr, m_message, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001054 }
1055
1056 class DetachOperation : public Operation
1057 {
1058 public:
Chaoren Lin97ccc292015-02-03 01:51:12 +00001059 DetachOperation(lldb::tid_t tid) : m_tid(tid) { }
Todd Fialaaf245d12014-06-30 21:05:18 +00001060
Tamas Berghammerd542efd2015-03-25 15:37:56 +00001061 void Execute(NativeProcessLinux *monitor) override;
Todd Fialaaf245d12014-06-30 21:05:18 +00001062
1063 private:
1064 lldb::tid_t m_tid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001065 };
1066
1067 void
1068 DetachOperation::Execute(NativeProcessLinux *monitor)
1069 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00001070 PTRACE(PTRACE_DETACH, m_tid, nullptr, 0, 0, m_error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001071 }
Pavel Labath1107b5a2015-04-17 14:07:49 +00001072} // end of anonymous namespace
1073
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001074// Simple helper function to ensure flags are enabled on the given file
1075// descriptor.
1076static Error
1077EnsureFDFlags(int fd, int flags)
1078{
1079 Error error;
1080
1081 int status = fcntl(fd, F_GETFL);
1082 if (status == -1)
1083 {
1084 error.SetErrorToErrno();
1085 return error;
1086 }
1087
1088 if (fcntl(fd, F_SETFL, status | flags) == -1)
1089 {
1090 error.SetErrorToErrno();
1091 return error;
1092 }
1093
1094 return error;
1095}
1096
1097// This class encapsulates the privileged thread which performs all ptrace and wait operations on
1098// the inferior. The thread consists of a main loop which waits for events and processes them
1099// - SIGCHLD (delivered over a signalfd file descriptor): These signals notify us of events in
1100// the inferior process. Upon receiving this signal we do a waitpid to get more information
1101// and dispatch to NativeProcessLinux::MonitorCallback.
1102// - requests for ptrace operations: These initiated via the DoOperation method, which funnels
1103// them to the Monitor thread via m_operation member. The Monitor thread is signaled over a
1104// pipe, and the completion of the operation is signalled over the semaphore.
1105// - thread exit event: this is signaled from the Monitor destructor by closing the write end
1106// of the command pipe.
Pavel Labath45f5cb32015-05-05 15:05:50 +00001107class NativeProcessLinux::Monitor
1108{
Pavel Labath1107b5a2015-04-17 14:07:49 +00001109private:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001110 // The initial monitor operation (launch or attach). It returns a inferior process id.
1111 std::unique_ptr<InitialOperation> m_initial_operation_up;
1112
1113 ::pid_t m_child_pid = -1;
1114 NativeProcessLinux * m_native_process;
Pavel Labath1107b5a2015-04-17 14:07:49 +00001115
1116 enum { READ, WRITE };
1117 int m_pipefd[2] = {-1, -1};
1118 int m_signal_fd = -1;
1119 HostThread m_thread;
1120
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001121 // current operation which must be executed on the priviliged thread
1122 Mutex m_operation_mutex;
1123 Operation *m_operation = nullptr;
1124 sem_t m_operation_sem;
1125 Error m_operation_error;
1126
Pavel Labath45f5cb32015-05-05 15:05:50 +00001127 unsigned m_operation_nesting_level = 0;
1128
1129 static constexpr char operation_command = 'o';
1130 static constexpr char begin_block_command = '{';
1131 static constexpr char end_block_command = '}';
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001132
Pavel Labath1107b5a2015-04-17 14:07:49 +00001133 void
1134 HandleSignals();
1135
1136 void
1137 HandleWait();
1138
1139 // Returns true if the thread should exit.
1140 bool
1141 HandleCommands();
1142
1143 void
1144 MainLoop();
1145
1146 static void *
1147 RunMonitor(void *arg);
1148
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001149 Error
Pavel Labath45f5cb32015-05-05 15:05:50 +00001150 WaitForAck();
1151
1152 void
1153 BeginOperationBlock()
1154 {
1155 write(m_pipefd[WRITE], &begin_block_command, sizeof operation_command);
1156 WaitForAck();
1157 }
1158
1159 void
1160 EndOperationBlock()
1161 {
1162 write(m_pipefd[WRITE], &end_block_command, sizeof operation_command);
1163 WaitForAck();
1164 }
1165
Pavel Labath1107b5a2015-04-17 14:07:49 +00001166public:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001167 Monitor(const InitialOperation &initial_operation,
1168 NativeProcessLinux *native_process)
1169 : m_initial_operation_up(new InitialOperation(initial_operation)),
1170 m_native_process(native_process)
1171 {
1172 sem_init(&m_operation_sem, 0, 0);
1173 }
Pavel Labath1107b5a2015-04-17 14:07:49 +00001174
1175 ~Monitor();
1176
1177 Error
1178 Initialize();
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001179
1180 void
Pavel Labath45f5cb32015-05-05 15:05:50 +00001181 Terminate();
1182
1183 void
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001184 DoOperation(Operation *op);
Pavel Labath45f5cb32015-05-05 15:05:50 +00001185
1186 class ScopedOperationLock {
1187 Monitor &m_monitor;
1188
1189 public:
1190 ScopedOperationLock(Monitor &monitor)
1191 : m_monitor(monitor)
1192 { m_monitor.BeginOperationBlock(); }
1193
1194 ~ScopedOperationLock()
1195 { m_monitor.EndOperationBlock(); }
1196 };
Pavel Labath1107b5a2015-04-17 14:07:49 +00001197};
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001198constexpr char NativeProcessLinux::Monitor::operation_command;
Pavel Labath45f5cb32015-05-05 15:05:50 +00001199constexpr char NativeProcessLinux::Monitor::begin_block_command;
1200constexpr char NativeProcessLinux::Monitor::end_block_command;
Pavel Labath1107b5a2015-04-17 14:07:49 +00001201
1202Error
1203NativeProcessLinux::Monitor::Initialize()
1204{
1205 Error error;
1206
1207 // We get a SIGCHLD every time something interesting happens with the inferior. We shall be
1208 // listening for these signals over a signalfd file descriptors. This allows us to wait for
1209 // multiple kinds of events with select.
1210 sigset_t signals;
1211 sigemptyset(&signals);
1212 sigaddset(&signals, SIGCHLD);
1213 m_signal_fd = signalfd(-1, &signals, SFD_NONBLOCK | SFD_CLOEXEC);
1214 if (m_signal_fd < 0)
1215 {
1216 return Error("NativeProcessLinux::Monitor::%s failed due to signalfd failure. Monitoring the inferior will be impossible: %s",
1217 __FUNCTION__, strerror(errno));
1218
1219 }
1220
1221 if (pipe2(m_pipefd, O_CLOEXEC) == -1)
1222 {
1223 error.SetErrorToErrno();
1224 return error;
1225 }
1226
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001227 if ((error = EnsureFDFlags(m_pipefd[READ], O_NONBLOCK)).Fail()) {
1228 return error;
1229 }
1230
1231 static const char g_thread_name[] = "lldb.process.nativelinux.monitor";
1232 m_thread = ThreadLauncher::LaunchThread(g_thread_name, Monitor::RunMonitor, this, nullptr);
Pavel Labath1107b5a2015-04-17 14:07:49 +00001233 if (!m_thread.IsJoinable())
1234 return Error("Failed to create monitor thread for NativeProcessLinux.");
1235
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001236 // Wait for initial operation to complete.
Pavel Labath45f5cb32015-05-05 15:05:50 +00001237 return WaitForAck();
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001238}
1239
1240void
1241NativeProcessLinux::Monitor::DoOperation(Operation *op)
1242{
1243 if (m_thread.EqualsThread(pthread_self())) {
1244 // If we're on the Monitor thread, we can simply execute the operation.
1245 op->Execute(m_native_process);
1246 return;
1247 }
1248
1249 // Otherwise we need to pass the operation to the Monitor thread so it can handle it.
1250 Mutex::Locker lock(m_operation_mutex);
1251
1252 m_operation = op;
1253
1254 // notify the thread that an operation is ready to be processed
1255 write(m_pipefd[WRITE], &operation_command, sizeof operation_command);
1256
Pavel Labath45f5cb32015-05-05 15:05:50 +00001257 WaitForAck();
1258}
1259
1260void
1261NativeProcessLinux::Monitor::Terminate()
1262{
1263 if (m_pipefd[WRITE] >= 0)
1264 {
1265 close(m_pipefd[WRITE]);
1266 m_pipefd[WRITE] = -1;
1267 }
1268 if (m_thread.IsJoinable())
1269 m_thread.Join(nullptr);
Todd Fialaaf245d12014-06-30 21:05:18 +00001270}
1271
Pavel Labath1107b5a2015-04-17 14:07:49 +00001272NativeProcessLinux::Monitor::~Monitor()
1273{
Pavel Labath45f5cb32015-05-05 15:05:50 +00001274 Terminate();
Pavel Labath1107b5a2015-04-17 14:07:49 +00001275 if (m_pipefd[READ] >= 0)
1276 close(m_pipefd[READ]);
1277 if (m_signal_fd >= 0)
1278 close(m_signal_fd);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001279 sem_destroy(&m_operation_sem);
Pavel Labath1107b5a2015-04-17 14:07:49 +00001280}
1281
1282void
1283NativeProcessLinux::Monitor::HandleSignals()
1284{
1285 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1286
1287 // We don't really care about the content of the SIGCHLD siginfo structure, as we will get
1288 // all the information from waitpid(). We just need to read all the signals so that we can
1289 // sleep next time we reach select().
1290 while (true)
1291 {
1292 signalfd_siginfo info;
1293 ssize_t size = read(m_signal_fd, &info, sizeof info);
1294 if (size == -1)
1295 {
1296 if (errno == EAGAIN || errno == EWOULDBLOCK)
1297 break; // We are done.
1298 if (errno == EINTR)
1299 continue;
1300 if (log)
1301 log->Printf("NativeProcessLinux::Monitor::%s reading from signalfd file descriptor failed: %s",
1302 __FUNCTION__, strerror(errno));
1303 break;
1304 }
1305 if (size != sizeof info)
1306 {
1307 // We got incomplete information structure. This should not happen, let's just log
1308 // that.
1309 if (log)
1310 log->Printf("NativeProcessLinux::Monitor::%s reading from signalfd file descriptor returned incomplete data: "
1311 "structure size is %zd, read returned %zd bytes",
1312 __FUNCTION__, sizeof info, size);
1313 break;
1314 }
1315 if (log)
1316 log->Printf("NativeProcessLinux::Monitor::%s received signal %s(%d).", __FUNCTION__,
1317 Host::GetSignalAsCString(info.ssi_signo), info.ssi_signo);
1318 }
1319}
1320
1321void
1322NativeProcessLinux::Monitor::HandleWait()
1323{
1324 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1325 // Process all pending waitpid notifications.
1326 while (true)
1327 {
1328 int status = -1;
1329 ::pid_t wait_pid = waitpid(m_child_pid, &status, __WALL | WNOHANG);
1330
1331 if (wait_pid == 0)
1332 break; // We are done.
1333
1334 if (wait_pid == -1)
1335 {
1336 if (errno == EINTR)
1337 continue;
1338
1339 if (log)
1340 log->Printf("NativeProcessLinux::Monitor::%s waitpid (pid = %" PRIi32 ", &status, __WALL | WNOHANG) failed: %s",
1341 __FUNCTION__, m_child_pid, strerror(errno));
1342 break;
1343 }
1344
1345 bool exited = false;
1346 int signal = 0;
1347 int exit_status = 0;
1348 const char *status_cstr = NULL;
1349 if (WIFSTOPPED(status))
1350 {
1351 signal = WSTOPSIG(status);
1352 status_cstr = "STOPPED";
1353 }
1354 else if (WIFEXITED(status))
1355 {
1356 exit_status = WEXITSTATUS(status);
1357 status_cstr = "EXITED";
1358 exited = true;
1359 }
1360 else if (WIFSIGNALED(status))
1361 {
1362 signal = WTERMSIG(status);
1363 status_cstr = "SIGNALED";
1364 if (wait_pid == abs(m_child_pid)) {
1365 exited = true;
1366 exit_status = -1;
1367 }
1368 }
1369 else
1370 status_cstr = "(\?\?\?)";
1371
1372 if (log)
1373 log->Printf("NativeProcessLinux::Monitor::%s: waitpid (pid = %" PRIi32 ", &status, __WALL | WNOHANG)"
1374 "=> pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
1375 __FUNCTION__, m_child_pid, wait_pid, status, status_cstr, signal, exit_status);
1376
1377 m_native_process->MonitorCallback (wait_pid, exited, signal, exit_status);
1378 }
1379}
1380
1381bool
1382NativeProcessLinux::Monitor::HandleCommands()
1383{
1384 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1385
1386 while (true)
1387 {
1388 char command = 0;
1389 ssize_t size = read(m_pipefd[READ], &command, sizeof command);
1390 if (size == -1)
1391 {
1392 if (errno == EAGAIN || errno == EWOULDBLOCK)
1393 return false;
1394 if (errno == EINTR)
1395 continue;
1396 if (log)
1397 log->Printf("NativeProcessLinux::Monitor::%s exiting because read from command file descriptor failed: %s", __FUNCTION__, strerror(errno));
1398 return true;
1399 }
1400 if (size == 0) // end of file - write end closed
1401 {
1402 if (log)
1403 log->Printf("NativeProcessLinux::Monitor::%s exit command received, exiting...", __FUNCTION__);
Pavel Labath45f5cb32015-05-05 15:05:50 +00001404 assert(m_operation_nesting_level == 0 && "Unbalanced begin/end block commands detected");
Pavel Labath1107b5a2015-04-17 14:07:49 +00001405 return true; // We are done.
1406 }
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001407
1408 switch (command)
1409 {
1410 case operation_command:
1411 m_operation->Execute(m_native_process);
Pavel Labath45f5cb32015-05-05 15:05:50 +00001412 break;
1413 case begin_block_command:
1414 ++m_operation_nesting_level;
1415 break;
1416 case end_block_command:
1417 assert(m_operation_nesting_level > 0);
1418 --m_operation_nesting_level;
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001419 break;
1420 default:
1421 if (log)
1422 log->Printf("NativeProcessLinux::Monitor::%s received unknown command '%c'",
1423 __FUNCTION__, command);
1424 }
Pavel Labath45f5cb32015-05-05 15:05:50 +00001425
1426 // notify calling thread that the command has been processed
1427 sem_post(&m_operation_sem);
Pavel Labath1107b5a2015-04-17 14:07:49 +00001428 }
1429}
1430
1431void
1432NativeProcessLinux::Monitor::MainLoop()
1433{
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001434 ::pid_t child_pid = (*m_initial_operation_up)(m_operation_error);
1435 m_initial_operation_up.reset();
1436 m_child_pid = -getpgid(child_pid),
1437 sem_post(&m_operation_sem);
1438
Pavel Labath1107b5a2015-04-17 14:07:49 +00001439 while (true)
1440 {
1441 fd_set fds;
1442 FD_ZERO(&fds);
Pavel Labath45f5cb32015-05-05 15:05:50 +00001443 // Only process waitpid events if we are outside of an operation block. Any pending
1444 // events will be processed after we leave the block.
1445 if (m_operation_nesting_level == 0)
1446 FD_SET(m_signal_fd, &fds);
Pavel Labath1107b5a2015-04-17 14:07:49 +00001447 FD_SET(m_pipefd[READ], &fds);
1448
1449 int max_fd = std::max(m_signal_fd, m_pipefd[READ]) + 1;
1450 int r = select(max_fd, &fds, nullptr, nullptr, nullptr);
1451 if (r < 0)
1452 {
1453 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1454 if (log)
1455 log->Printf("NativeProcessLinux::Monitor::%s exiting because select failed: %s",
1456 __FUNCTION__, strerror(errno));
1457 return;
1458 }
1459
1460 if (FD_ISSET(m_pipefd[READ], &fds))
1461 {
1462 if (HandleCommands())
1463 return;
1464 }
1465
1466 if (FD_ISSET(m_signal_fd, &fds))
1467 {
1468 HandleSignals();
1469 HandleWait();
1470 }
1471 }
1472}
1473
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001474Error
Pavel Labath45f5cb32015-05-05 15:05:50 +00001475NativeProcessLinux::Monitor::WaitForAck()
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001476{
1477 Error error;
1478 while (sem_wait(&m_operation_sem) != 0)
1479 {
1480 if (errno == EINTR)
1481 continue;
1482
1483 error.SetErrorToErrno();
1484 return error;
1485 }
1486
1487 return m_operation_error;
1488}
1489
Pavel Labath1107b5a2015-04-17 14:07:49 +00001490void *
1491NativeProcessLinux::Monitor::RunMonitor(void *arg)
1492{
1493 static_cast<Monitor *>(arg)->MainLoop();
1494 return nullptr;
1495}
1496
1497
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001498NativeProcessLinux::LaunchArgs::LaunchArgs(Module *module,
Todd Fialaaf245d12014-06-30 21:05:18 +00001499 char const **argv,
1500 char const **envp,
Todd Fiala75f47c32014-10-11 21:42:09 +00001501 const std::string &stdin_path,
1502 const std::string &stdout_path,
1503 const std::string &stderr_path,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001504 const char *working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001505 const ProcessLaunchInfo &launch_info)
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001506 : m_module(module),
Todd Fialaaf245d12014-06-30 21:05:18 +00001507 m_argv(argv),
1508 m_envp(envp),
1509 m_stdin_path(stdin_path),
1510 m_stdout_path(stdout_path),
1511 m_stderr_path(stderr_path),
Todd Fiala0bce1b62014-08-17 00:10:50 +00001512 m_working_dir(working_dir),
1513 m_launch_info(launch_info)
1514{
1515}
Todd Fialaaf245d12014-06-30 21:05:18 +00001516
1517NativeProcessLinux::LaunchArgs::~LaunchArgs()
1518{ }
1519
Todd Fialaaf245d12014-06-30 21:05:18 +00001520// -----------------------------------------------------------------------------
1521// Public Static Methods
1522// -----------------------------------------------------------------------------
1523
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001524Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001525NativeProcessLinux::LaunchProcess (
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001526 Module *exe_module,
1527 ProcessLaunchInfo &launch_info,
1528 NativeProcessProtocol::NativeDelegate &native_delegate,
Todd Fialaaf245d12014-06-30 21:05:18 +00001529 NativeProcessProtocolSP &native_process_sp)
1530{
1531 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1532
1533 Error error;
1534
1535 // Verify the working directory is valid if one was specified.
1536 const char* working_dir = launch_info.GetWorkingDirectory ();
1537 if (working_dir)
1538 {
1539 FileSpec working_dir_fs (working_dir, true);
1540 if (!working_dir_fs || working_dir_fs.GetFileType () != FileSpec::eFileTypeDirectory)
1541 {
1542 error.SetErrorStringWithFormat ("No such file or directory: %s", working_dir);
1543 return error;
1544 }
1545 }
1546
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001547 const FileAction *file_action;
Todd Fialaaf245d12014-06-30 21:05:18 +00001548
1549 // Default of NULL will mean to use existing open file descriptors.
Todd Fiala75f47c32014-10-11 21:42:09 +00001550 std::string stdin_path;
1551 std::string stdout_path;
1552 std::string stderr_path;
Todd Fialaaf245d12014-06-30 21:05:18 +00001553
1554 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001555 if (file_action)
1556 stdin_path = file_action->GetPath ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001557
1558 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001559 if (file_action)
1560 stdout_path = file_action->GetPath ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001561
1562 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
Todd Fiala75f47c32014-10-11 21:42:09 +00001563 if (file_action)
1564 stderr_path = file_action->GetPath ();
1565
1566 if (log)
1567 {
1568 if (!stdin_path.empty ())
1569 log->Printf ("NativeProcessLinux::%s setting STDIN to '%s'", __FUNCTION__, stdin_path.c_str ());
1570 else
1571 log->Printf ("NativeProcessLinux::%s leaving STDIN as is", __FUNCTION__);
1572
1573 if (!stdout_path.empty ())
1574 log->Printf ("NativeProcessLinux::%s setting STDOUT to '%s'", __FUNCTION__, stdout_path.c_str ());
1575 else
1576 log->Printf ("NativeProcessLinux::%s leaving STDOUT as is", __FUNCTION__);
1577
1578 if (!stderr_path.empty ())
1579 log->Printf ("NativeProcessLinux::%s setting STDERR to '%s'", __FUNCTION__, stderr_path.c_str ());
1580 else
1581 log->Printf ("NativeProcessLinux::%s leaving STDERR as is", __FUNCTION__);
1582 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001583
1584 // Create the NativeProcessLinux in launch mode.
1585 native_process_sp.reset (new NativeProcessLinux ());
1586
1587 if (log)
1588 {
1589 int i = 0;
1590 for (const char **args = launch_info.GetArguments ().GetConstArgumentVector (); *args; ++args, ++i)
1591 {
1592 log->Printf ("NativeProcessLinux::%s arg %d: \"%s\"", __FUNCTION__, i, *args ? *args : "nullptr");
1593 ++i;
1594 }
1595 }
1596
1597 if (!native_process_sp->RegisterNativeDelegate (native_delegate))
1598 {
1599 native_process_sp.reset ();
1600 error.SetErrorStringWithFormat ("failed to register the native delegate");
1601 return error;
1602 }
1603
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00001604 std::static_pointer_cast<NativeProcessLinux> (native_process_sp)->LaunchInferior (
Todd Fialaaf245d12014-06-30 21:05:18 +00001605 exe_module,
1606 launch_info.GetArguments ().GetConstArgumentVector (),
1607 launch_info.GetEnvironmentEntries ().GetConstArgumentVector (),
1608 stdin_path,
1609 stdout_path,
1610 stderr_path,
1611 working_dir,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001612 launch_info,
Todd Fialaaf245d12014-06-30 21:05:18 +00001613 error);
1614
1615 if (error.Fail ())
1616 {
1617 native_process_sp.reset ();
1618 if (log)
1619 log->Printf ("NativeProcessLinux::%s failed to launch process: %s", __FUNCTION__, error.AsCString ());
1620 return error;
1621 }
1622
1623 launch_info.SetProcessID (native_process_sp->GetID ());
1624
1625 return error;
1626}
1627
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001628Error
Todd Fialaaf245d12014-06-30 21:05:18 +00001629NativeProcessLinux::AttachToProcess (
1630 lldb::pid_t pid,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001631 NativeProcessProtocol::NativeDelegate &native_delegate,
Todd Fialaaf245d12014-06-30 21:05:18 +00001632 NativeProcessProtocolSP &native_process_sp)
1633{
1634 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1635 if (log && log->GetMask ().Test (POSIX_LOG_VERBOSE))
1636 log->Printf ("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
1637
1638 // Grab the current platform architecture. This should be Linux,
1639 // since this code is only intended to run on a Linux host.
Greg Clayton615eb7e2014-09-19 20:11:50 +00001640 PlatformSP platform_sp (Platform::GetHostPlatform ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001641 if (!platform_sp)
1642 return Error("failed to get a valid default platform");
1643
1644 // Retrieve the architecture for the running process.
1645 ArchSpec process_arch;
1646 Error error = ResolveProcessArchitecture (pid, *platform_sp.get (), process_arch);
1647 if (!error.Success ())
1648 return error;
1649
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001650 std::shared_ptr<NativeProcessLinux> native_process_linux_sp (new NativeProcessLinux ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001651
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001652 if (!native_process_linux_sp->RegisterNativeDelegate (native_delegate))
Todd Fialaaf245d12014-06-30 21:05:18 +00001653 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001654 error.SetErrorStringWithFormat ("failed to register the native delegate");
1655 return error;
1656 }
1657
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001658 native_process_linux_sp->AttachToInferior (pid, error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001659 if (!error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +00001660 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00001661
Oleksiy Vyalov1339b5e2014-11-13 18:22:16 +00001662 native_process_sp = native_process_linux_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001663 return error;
1664}
1665
1666// -----------------------------------------------------------------------------
1667// Public Instance Methods
1668// -----------------------------------------------------------------------------
1669
1670NativeProcessLinux::NativeProcessLinux () :
1671 NativeProcessProtocol (LLDB_INVALID_PROCESS_ID),
1672 m_arch (),
Todd Fialaaf245d12014-06-30 21:05:18 +00001673 m_supports_mem_region (eLazyBoolCalculate),
1674 m_mem_region_cache (),
Chaoren Linfa03ad22015-02-03 01:50:42 +00001675 m_mem_region_cache_mutex (),
Pavel Labathc0765592015-05-06 10:46:34 +00001676 m_log_function (GetThreadLoggerFunction()),
1677 m_tid_map (),
1678 m_log_event_processing (false)
Todd Fialaaf245d12014-06-30 21:05:18 +00001679{
1680}
1681
1682//------------------------------------------------------------------------------
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001683// NativeProcessLinux spawns a new thread which performs all operations on the inferior process.
1684// Refer to Monitor and Operation classes to see why this is necessary.
1685//------------------------------------------------------------------------------
Todd Fialaaf245d12014-06-30 21:05:18 +00001686void
1687NativeProcessLinux::LaunchInferior (
1688 Module *module,
1689 const char *argv[],
1690 const char *envp[],
Todd Fiala75f47c32014-10-11 21:42:09 +00001691 const std::string &stdin_path,
1692 const std::string &stdout_path,
1693 const std::string &stderr_path,
Todd Fialaaf245d12014-06-30 21:05:18 +00001694 const char *working_dir,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001695 const ProcessLaunchInfo &launch_info,
1696 Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001697{
1698 if (module)
1699 m_arch = module->GetArchitecture ();
1700
Chaoren Linfa03ad22015-02-03 01:50:42 +00001701 SetState (eStateLaunching);
Todd Fialaaf245d12014-06-30 21:05:18 +00001702
1703 std::unique_ptr<LaunchArgs> args(
1704 new LaunchArgs(
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001705 module, argv, envp,
Todd Fialaaf245d12014-06-30 21:05:18 +00001706 stdin_path, stdout_path, stderr_path,
Todd Fiala0bce1b62014-08-17 00:10:50 +00001707 working_dir, launch_info));
Todd Fialaaf245d12014-06-30 21:05:18 +00001708
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001709 StartMonitorThread ([&] (Error &e) { return Launch(args.get(), e); }, error);
Chaoren Linfa03ad22015-02-03 01:50:42 +00001710 if (!error.Success ())
1711 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001712}
1713
1714void
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001715NativeProcessLinux::AttachToInferior (lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001716{
1717 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1718 if (log)
1719 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
1720
1721 // We can use the Host for everything except the ResolveExecutable portion.
Greg Clayton615eb7e2014-09-19 20:11:50 +00001722 PlatformSP platform_sp = Platform::GetHostPlatform ();
Todd Fialaaf245d12014-06-30 21:05:18 +00001723 if (!platform_sp)
1724 {
1725 if (log)
1726 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): no default platform set", __FUNCTION__, pid);
1727 error.SetErrorString ("no default platform available");
Shawn Best50d60be2014-11-11 00:28:52 +00001728 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001729 }
1730
1731 // Gather info about the process.
1732 ProcessInstanceInfo process_info;
Shawn Best50d60be2014-11-11 00:28:52 +00001733 if (!platform_sp->GetProcessInfo (pid, process_info))
1734 {
1735 if (log)
1736 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): failed to get process info", __FUNCTION__, pid);
1737 error.SetErrorString ("failed to get process info");
1738 return;
1739 }
Todd Fialaaf245d12014-06-30 21:05:18 +00001740
1741 // Resolve the executable module
1742 ModuleSP exe_module_sp;
1743 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
Chaoren Line56f6dc2015-03-01 04:31:16 +00001744 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture());
Oleksiy Vyalov6edef202014-11-17 22:16:42 +00001745 error = platform_sp->ResolveExecutable(exe_module_spec, exe_module_sp,
Zachary Turner13b18262014-08-20 16:42:51 +00001746 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
Todd Fialaaf245d12014-06-30 21:05:18 +00001747 if (!error.Success())
1748 return;
1749
1750 // Set the architecture to the exe architecture.
1751 m_arch = exe_module_sp->GetArchitecture();
1752 if (log)
1753 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
1754
1755 m_pid = pid;
1756 SetState(eStateAttaching);
1757
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001758 StartMonitorThread ([=] (Error &e) { return Attach(pid, e); }, error);
Todd Fialaaf245d12014-06-30 21:05:18 +00001759 if (!error.Success ())
1760 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00001761}
1762
Oleksiy Vyalov8bc34f42015-02-19 17:58:04 +00001763void
1764NativeProcessLinux::Terminate ()
Todd Fialaaf245d12014-06-30 21:05:18 +00001765{
Pavel Labath45f5cb32015-05-05 15:05:50 +00001766 m_monitor_up->Terminate();
Todd Fialaaf245d12014-06-30 21:05:18 +00001767}
1768
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001769::pid_t
1770NativeProcessLinux::Launch(LaunchArgs *args, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00001771{
Todd Fiala0bce1b62014-08-17 00:10:50 +00001772 assert (args && "null args");
Todd Fialaaf245d12014-06-30 21:05:18 +00001773
1774 const char **argv = args->m_argv;
1775 const char **envp = args->m_envp;
Todd Fialaaf245d12014-06-30 21:05:18 +00001776 const char *working_dir = args->m_working_dir;
1777
1778 lldb_utility::PseudoTerminal terminal;
1779 const size_t err_len = 1024;
1780 char err_str[err_len];
1781 lldb::pid_t pid;
1782 NativeThreadProtocolSP thread_sp;
1783
1784 lldb::ThreadSP inferior;
Todd Fialaaf245d12014-06-30 21:05:18 +00001785
1786 // Propagate the environment if one is not supplied.
1787 if (envp == NULL || envp[0] == NULL)
1788 envp = const_cast<const char **>(environ);
1789
1790 if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
1791 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001792 error.SetErrorToGenericError();
1793 error.SetErrorStringWithFormat("Process fork failed: %s", err_str);
1794 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001795 }
1796
1797 // Recognized child exit status codes.
1798 enum {
1799 ePtraceFailed = 1,
1800 eDupStdinFailed,
1801 eDupStdoutFailed,
1802 eDupStderrFailed,
1803 eChdirFailed,
1804 eExecFailed,
1805 eSetGidFailed
1806 };
1807
1808 // Child process.
1809 if (pid == 0)
1810 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001811 // FIXME consider opening a pipe between parent/child and have this forked child
1812 // send log info to parent re: launch status, in place of the log lines removed here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001813
Todd Fiala75f47c32014-10-11 21:42:09 +00001814 // Start tracing this child that is about to exec.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001815 PTRACE(PTRACE_TRACEME, 0, nullptr, nullptr, 0, error);
1816 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001817 exit(ePtraceFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001818
Pavel Labath493c3a12015-02-04 10:36:57 +00001819 // terminal has already dupped the tty descriptors to stdin/out/err.
1820 // This closes original fd from which they were copied (and avoids
1821 // leaking descriptors to the debugged process.
1822 terminal.CloseSlaveFileDescriptor();
1823
Todd Fialaaf245d12014-06-30 21:05:18 +00001824 // Do not inherit setgid powers.
Todd Fialaaf245d12014-06-30 21:05:18 +00001825 if (setgid(getgid()) != 0)
Todd Fialaaf245d12014-06-30 21:05:18 +00001826 exit(eSetGidFailed);
Todd Fialaaf245d12014-06-30 21:05:18 +00001827
1828 // Attempt to have our own process group.
Todd Fialaaf245d12014-06-30 21:05:18 +00001829 if (setpgid(0, 0) != 0)
1830 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001831 // FIXME log that this failed. This is common.
Todd Fialaaf245d12014-06-30 21:05:18 +00001832 // Don't allow this to prevent an inferior exec.
1833 }
1834
1835 // Dup file descriptors if needed.
Todd Fiala75f47c32014-10-11 21:42:09 +00001836 if (!args->m_stdin_path.empty ())
1837 if (!DupDescriptor(args->m_stdin_path.c_str (), STDIN_FILENO, O_RDONLY))
Todd Fialaaf245d12014-06-30 21:05:18 +00001838 exit(eDupStdinFailed);
1839
Todd Fiala75f47c32014-10-11 21:42:09 +00001840 if (!args->m_stdout_path.empty ())
Tamas Berghammer14f44762015-02-25 13:21:45 +00001841 if (!DupDescriptor(args->m_stdout_path.c_str (), STDOUT_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +00001842 exit(eDupStdoutFailed);
1843
Todd Fiala75f47c32014-10-11 21:42:09 +00001844 if (!args->m_stderr_path.empty ())
Tamas Berghammer14f44762015-02-25 13:21:45 +00001845 if (!DupDescriptor(args->m_stderr_path.c_str (), STDERR_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
Todd Fialaaf245d12014-06-30 21:05:18 +00001846 exit(eDupStderrFailed);
1847
Chaoren Lin9cf4f2c2015-04-23 18:28:04 +00001848 // Close everything besides stdin, stdout, and stderr that has no file
1849 // action to avoid leaking
1850 for (int fd = 3; fd < sysconf(_SC_OPEN_MAX); ++fd)
1851 if (!args->m_launch_info.GetFileActionForFD(fd))
1852 close(fd);
1853
Todd Fialaaf245d12014-06-30 21:05:18 +00001854 // Change working directory
1855 if (working_dir != NULL && working_dir[0])
1856 if (0 != ::chdir(working_dir))
1857 exit(eChdirFailed);
1858
Todd Fiala0bce1b62014-08-17 00:10:50 +00001859 // Disable ASLR if requested.
1860 if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR))
1861 {
1862 const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
1863 if (old_personality == -1)
1864 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001865 // Can't retrieve Linux personality. Cannot disable ASLR.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001866 }
1867 else
1868 {
1869 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality);
1870 if (new_personality == -1)
1871 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001872 // Disabling ASLR failed.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001873 }
1874 else
1875 {
Todd Fiala75f47c32014-10-11 21:42:09 +00001876 // Disabling ASLR succeeded.
Todd Fiala0bce1b62014-08-17 00:10:50 +00001877 }
1878 }
1879 }
1880
Todd Fiala75f47c32014-10-11 21:42:09 +00001881 // Execute. We should never return...
Todd Fialaaf245d12014-06-30 21:05:18 +00001882 execve(argv[0],
1883 const_cast<char *const *>(argv),
1884 const_cast<char *const *>(envp));
Todd Fiala75f47c32014-10-11 21:42:09 +00001885
1886 // ...unless exec fails. In which case we definitely need to end the child here.
Todd Fialaaf245d12014-06-30 21:05:18 +00001887 exit(eExecFailed);
1888 }
1889
Todd Fiala75f47c32014-10-11 21:42:09 +00001890 //
1891 // This is the parent code here.
1892 //
1893 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1894
Todd Fialaaf245d12014-06-30 21:05:18 +00001895 // Wait for the child process to trap on its call to execve.
1896 ::pid_t wpid;
1897 int status;
1898 if ((wpid = waitpid(pid, &status, 0)) < 0)
1899 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001900 error.SetErrorToErrno();
Todd Fialaaf245d12014-06-30 21:05:18 +00001901 if (log)
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001902 log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s",
1903 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001904
1905 // Mark the inferior as invalid.
1906 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001907 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001908
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001909 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001910 }
1911 else if (WIFEXITED(status))
1912 {
1913 // open, dup or execve likely failed for some reason.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001914 error.SetErrorToGenericError();
Todd Fialaaf245d12014-06-30 21:05:18 +00001915 switch (WEXITSTATUS(status))
1916 {
1917 case ePtraceFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001918 error.SetErrorString("Child ptrace failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001919 break;
1920 case eDupStdinFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001921 error.SetErrorString("Child open stdin failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001922 break;
1923 case eDupStdoutFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001924 error.SetErrorString("Child open stdout failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001925 break;
1926 case eDupStderrFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001927 error.SetErrorString("Child open stderr failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001928 break;
1929 case eChdirFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001930 error.SetErrorString("Child failed to set working directory.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001931 break;
1932 case eExecFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001933 error.SetErrorString("Child exec failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001934 break;
1935 case eSetGidFailed:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001936 error.SetErrorString("Child setgid failed.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001937 break;
1938 default:
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001939 error.SetErrorString("Child returned unknown exit status.");
Todd Fialaaf245d12014-06-30 21:05:18 +00001940 break;
1941 }
1942
1943 if (log)
1944 {
1945 log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
1946 __FUNCTION__,
1947 WEXITSTATUS(status));
1948 }
1949
1950 // Mark the inferior as invalid.
1951 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001952 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001953
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001954 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001955 }
Todd Fiala202ecd22014-07-10 04:39:13 +00001956 assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
Todd Fialaaf245d12014-06-30 21:05:18 +00001957 "Could not sync with inferior process.");
1958
1959 if (log)
1960 log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
1961
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001962 error = SetDefaultPtraceOpts(pid);
1963 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001964 {
Todd Fialaaf245d12014-06-30 21:05:18 +00001965 if (log)
1966 log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001967 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001968
1969 // Mark the inferior as invalid.
1970 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001971 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001972
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001973 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001974 }
1975
1976 // Release the master terminal descriptor and pass it off to the
1977 // NativeProcessLinux instance. Similarly stash the inferior pid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001978 m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1979 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00001980
1981 // Set the terminal fd to be in non blocking mode (it simplifies the
1982 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1983 // descriptor to read from).
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001984 error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
1985 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00001986 {
1987 if (log)
1988 log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001989 __FUNCTION__, error.AsCString ());
Todd Fialaaf245d12014-06-30 21:05:18 +00001990
1991 // Mark the inferior as invalid.
1992 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001993 SetState (StateType::eStateInvalid);
Todd Fialaaf245d12014-06-30 21:05:18 +00001994
Pavel Labathbd7cbc52015-04-20 13:53:49 +00001995 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00001996 }
1997
1998 if (log)
1999 log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
2000
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002001 thread_sp = AddThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002002 assert (thread_sp && "AddThread() returned a nullptr thread");
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002003 NotifyThreadCreateStopped (pid);
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002004 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
Todd Fialaaf245d12014-06-30 21:05:18 +00002005
2006 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002007 SetCurrentThreadID (thread_sp->GetID ());
2008 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +00002009
Todd Fialaaf245d12014-06-30 21:05:18 +00002010 if (log)
2011 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002012 if (error.Success ())
Todd Fialaaf245d12014-06-30 21:05:18 +00002013 {
2014 log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
2015 }
2016 else
2017 {
2018 log->Printf ("NativeProcessLinux::%s inferior launching failed: %s",
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002019 __FUNCTION__, error.AsCString ());
2020 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00002021 }
2022 }
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002023 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00002024}
2025
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002026::pid_t
2027NativeProcessLinux::Attach(lldb::pid_t pid, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00002028{
Todd Fialaaf245d12014-06-30 21:05:18 +00002029 lldb::ThreadSP inferior;
2030 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2031
2032 // Use a map to keep track of the threads which we have attached/need to attach.
2033 Host::TidMap tids_to_attach;
2034 if (pid <= 1)
2035 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002036 error.SetErrorToGenericError();
2037 error.SetErrorString("Attaching to process 1 is not allowed.");
2038 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00002039 }
2040
2041 while (Host::FindProcessThreads(pid, tids_to_attach))
2042 {
2043 for (Host::TidMap::iterator it = tids_to_attach.begin();
2044 it != tids_to_attach.end();)
2045 {
2046 if (it->second == false)
2047 {
2048 lldb::tid_t tid = it->first;
2049
2050 // Attach to the requested process.
2051 // An attach will cause the thread to stop with a SIGSTOP.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002052 PTRACE(PTRACE_ATTACH, tid, nullptr, nullptr, 0, error);
2053 if (error.Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00002054 {
2055 // No such thread. The thread may have exited.
2056 // More error handling may be needed.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002057 if (error.GetError() == ESRCH)
Todd Fialaaf245d12014-06-30 21:05:18 +00002058 {
2059 it = tids_to_attach.erase(it);
2060 continue;
2061 }
2062 else
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002063 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00002064 }
2065
2066 int status;
2067 // Need to use __WALL otherwise we receive an error with errno=ECHLD
2068 // At this point we should have a thread stopped if waitpid succeeds.
2069 if ((status = waitpid(tid, NULL, __WALL)) < 0)
2070 {
2071 // No such thread. The thread may have exited.
2072 // More error handling may be needed.
2073 if (errno == ESRCH)
2074 {
2075 it = tids_to_attach.erase(it);
2076 continue;
2077 }
2078 else
2079 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002080 error.SetErrorToErrno();
2081 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00002082 }
2083 }
2084
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002085 error = SetDefaultPtraceOpts(tid);
2086 if (error.Fail())
2087 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00002088
2089 if (log)
2090 log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
2091
2092 it->second = true;
2093
2094 // Create the thread, mark it as stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002095 NativeThreadProtocolSP thread_sp (AddThread (static_cast<lldb::tid_t> (tid)));
Todd Fialaaf245d12014-06-30 21:05:18 +00002096 assert (thread_sp && "AddThread() returned a nullptr");
Chaoren Linfa03ad22015-02-03 01:50:42 +00002097
2098 // This will notify this is a new thread and tell the system it is stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002099 NotifyThreadCreateStopped (tid);
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002100 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002101 SetCurrentThreadID (thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00002102 }
2103
2104 // move the loop forward
2105 ++it;
2106 }
2107 }
2108
2109 if (tids_to_attach.size() > 0)
2110 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002111 m_pid = pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00002112 // Let our process instance know the thread has stopped.
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002113 SetState (StateType::eStateStopped);
Todd Fialaaf245d12014-06-30 21:05:18 +00002114 }
2115 else
2116 {
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002117 error.SetErrorToGenericError();
2118 error.SetErrorString("No such process.");
2119 return -1;
Todd Fialaaf245d12014-06-30 21:05:18 +00002120 }
2121
Pavel Labathbd7cbc52015-04-20 13:53:49 +00002122 return pid;
Todd Fialaaf245d12014-06-30 21:05:18 +00002123}
2124
Chaoren Lin97ccc292015-02-03 01:51:12 +00002125Error
Todd Fialaaf245d12014-06-30 21:05:18 +00002126NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
2127{
2128 long ptrace_opts = 0;
2129
2130 // Have the child raise an event on exit. This is used to keep the child in
2131 // limbo until it is destroyed.
2132 ptrace_opts |= PTRACE_O_TRACEEXIT;
2133
2134 // Have the tracer trace threads which spawn in the inferior process.
2135 // TODO: if we want to support tracing the inferiors' child, add the
2136 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
2137 ptrace_opts |= PTRACE_O_TRACECLONE;
2138
2139 // Have the tracer notify us before execve returns
2140 // (needed to disable legacy SIGTRAP generation)
2141 ptrace_opts |= PTRACE_O_TRACEEXEC;
2142
Chaoren Lin97ccc292015-02-03 01:51:12 +00002143 Error error;
2144 PTRACE(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts, 0, error);
2145 return error;
Todd Fialaaf245d12014-06-30 21:05:18 +00002146}
2147
2148static ExitType convert_pid_status_to_exit_type (int status)
2149{
2150 if (WIFEXITED (status))
2151 return ExitType::eExitTypeExit;
2152 else if (WIFSIGNALED (status))
2153 return ExitType::eExitTypeSignal;
2154 else if (WIFSTOPPED (status))
2155 return ExitType::eExitTypeStop;
2156 else
2157 {
2158 // We don't know what this is.
2159 return ExitType::eExitTypeInvalid;
2160 }
2161}
2162
2163static int convert_pid_status_to_return_code (int status)
2164{
2165 if (WIFEXITED (status))
2166 return WEXITSTATUS (status);
2167 else if (WIFSIGNALED (status))
2168 return WTERMSIG (status);
2169 else if (WIFSTOPPED (status))
2170 return WSTOPSIG (status);
2171 else
2172 {
2173 // We don't know what this is.
2174 return ExitType::eExitTypeInvalid;
2175 }
2176}
2177
Pavel Labath1107b5a2015-04-17 14:07:49 +00002178// Handles all waitpid events from the inferior process.
2179void
2180NativeProcessLinux::MonitorCallback(lldb::pid_t pid,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +00002181 bool exited,
2182 int signal,
2183 int status)
Todd Fialaaf245d12014-06-30 21:05:18 +00002184{
2185 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
2186
Todd Fialaaf245d12014-06-30 21:05:18 +00002187 // Certain activities differ based on whether the pid is the tid of the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002188 const bool is_main_thread = (pid == GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00002189
2190 // Handle when the thread exits.
2191 if (exited)
2192 {
2193 if (log)
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002194 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 +00002195
2196 // This is a thread that exited. Ensure we're not tracking it anymore.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002197 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002198
Chaoren Linfa03ad22015-02-03 01:50:42 +00002199 // Make sure the thread state coordinator knows about this.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002200 NotifyThreadDeath (pid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002201
Todd Fialaaf245d12014-06-30 21:05:18 +00002202 if (is_main_thread)
2203 {
2204 // We only set the exit status and notify the delegate if we haven't already set the process
2205 // state to an exited state. We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
2206 // for the main thread.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002207 const bool already_notified = (GetState() == StateType::eStateExited) || (GetState () == StateType::eStateCrashed);
Todd Fialaaf245d12014-06-30 21:05:18 +00002208 if (!already_notified)
2209 {
2210 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +00002211 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 +00002212 // The main thread exited. We're done monitoring. Report to delegate.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002213 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00002214
2215 // Notify delegate that our process has exited.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002216 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00002217 }
2218 else
2219 {
2220 if (log)
2221 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
2222 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002223 }
2224 else
2225 {
2226 // Do we want to report to the delegate in this case? I think not. If this was an orderly
2227 // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
2228 // and we would have done an all-stop then.
2229 if (log)
2230 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 +00002231 }
Pavel Labath1107b5a2015-04-17 14:07:49 +00002232 return;
Todd Fialaaf245d12014-06-30 21:05:18 +00002233 }
2234
2235 // Get details on the signal raised.
2236 siginfo_t info;
Pavel Labath1107b5a2015-04-17 14:07:49 +00002237 const auto err = GetSignalInfo(pid, &info);
Chaoren Lin97ccc292015-02-03 01:51:12 +00002238 if (err.Success())
Chaoren Linfa03ad22015-02-03 01:50:42 +00002239 {
2240 // We have retrieved the signal info. Dispatch appropriately.
2241 if (info.si_signo == SIGTRAP)
Pavel Labath1107b5a2015-04-17 14:07:49 +00002242 MonitorSIGTRAP(&info, pid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002243 else
Pavel Labath1107b5a2015-04-17 14:07:49 +00002244 MonitorSignal(&info, pid, exited);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002245 }
2246 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002247 {
Chaoren Lin97ccc292015-02-03 01:51:12 +00002248 if (err.GetError() == EINVAL)
Todd Fialaaf245d12014-06-30 21:05:18 +00002249 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002250 // This is a group stop reception for this tid.
2251 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +00002252 log->Printf ("NativeThreadLinux::%s received a group stop for pid %" PRIu64 " tid %" PRIu64, __FUNCTION__, GetID (), pid);
2253 NotifyThreadStop (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002254 }
2255 else
2256 {
2257 // ptrace(GETSIGINFO) failed (but not due to group-stop).
2258
2259 // A return value of ESRCH means the thread/process is no longer on the system,
2260 // so it was killed somehow outside of our control. Either way, we can't do anything
2261 // with it anymore.
2262
Todd Fialaaf245d12014-06-30 21:05:18 +00002263 // Stop tracking the metadata for the thread since it's entirely off the system now.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002264 const bool thread_found = StopTrackingThread (pid);
Todd Fialaaf245d12014-06-30 21:05:18 +00002265
Chaoren Linfa03ad22015-02-03 01:50:42 +00002266 // Make sure the thread state coordinator knows about this.
Pavel Labath1107b5a2015-04-17 14:07:49 +00002267 NotifyThreadDeath (pid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002268
Todd Fialaaf245d12014-06-30 21:05:18 +00002269 if (log)
2270 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
Chaoren Lin97ccc292015-02-03 01:51:12 +00002271 __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 +00002272
2273 if (is_main_thread)
2274 {
2275 // Notify the delegate - our process is not available but appears to have been killed outside
2276 // our control. Is eStateExited the right exit state in this case?
Pavel Labath1107b5a2015-04-17 14:07:49 +00002277 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
2278 SetState (StateType::eStateExited, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00002279 }
2280 else
2281 {
2282 // This thread was pulled out from underneath us. Anything to do here? Do we want to do an all stop?
2283 if (log)
Pavel Labath1107b5a2015-04-17 14:07:49 +00002284 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 +00002285 }
2286 }
2287 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002288}
2289
2290void
Pavel Labath426bdf82015-04-28 07:51:52 +00002291NativeProcessLinux::WaitForNewThread(::pid_t tid)
2292{
2293 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2294
2295 NativeThreadProtocolSP new_thread_sp = GetThreadByID(tid);
2296
2297 if (new_thread_sp)
2298 {
2299 // We are already tracking the thread - we got the event on the new thread (see
2300 // MonitorSignal) before this one. We are done.
2301 return;
2302 }
2303
2304 // The thread is not tracked yet, let's wait for it to appear.
2305 int status = -1;
2306 ::pid_t wait_pid;
2307 do
2308 {
2309 if (log)
2310 log->Printf ("NativeProcessLinux::%s() received thread creation event for tid %" PRIu32 ". tid not tracked yet, waiting for thread to appear...", __FUNCTION__, tid);
2311 wait_pid = waitpid(tid, &status, __WALL);
2312 }
2313 while (wait_pid == -1 && errno == EINTR);
2314 // Since we are waiting on a specific tid, this must be the creation event. But let's do
2315 // some checks just in case.
2316 if (wait_pid != tid) {
2317 if (log)
2318 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime", __FUNCTION__, tid);
2319 // The only way I know of this could happen is if the whole process was
2320 // SIGKILLed in the mean time. In any case, we can't do anything about that now.
2321 return;
2322 }
2323 if (WIFEXITED(status))
2324 {
2325 if (log)
2326 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " returned an 'exited' event. Not tracking the thread.", __FUNCTION__, tid);
2327 // Also a very improbable event.
2328 return;
2329 }
2330
2331 siginfo_t info;
2332 Error error = GetSignalInfo(tid, &info);
2333 if (error.Fail())
2334 {
2335 if (log)
2336 log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime.", __FUNCTION__, tid);
2337 return;
2338 }
2339
2340 if (((info.si_pid != 0) || (info.si_code != SI_USER)) && log)
2341 {
2342 // We should be getting a thread creation signal here, but we received something
2343 // else. There isn't much we can do about it now, so we will just log that. Since the
2344 // thread is alive and we are receiving events from it, we shall pretend that it was
2345 // created properly.
2346 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);
2347 }
2348
2349 if (log)
2350 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 ": tracking new thread tid %" PRIu32,
2351 __FUNCTION__, GetID (), tid);
2352
2353 new_thread_sp = AddThread(tid);
2354 std::static_pointer_cast<NativeThreadLinux> (new_thread_sp)->SetRunning ();
2355 Resume (tid, LLDB_INVALID_SIGNAL_NUMBER);
Pavel Labathc0765592015-05-06 10:46:34 +00002356 NotifyThreadCreate (tid, false, CoordinatorErrorHandler);
Pavel Labath426bdf82015-04-28 07:51:52 +00002357}
2358
2359void
Todd Fialaaf245d12014-06-30 21:05:18 +00002360NativeProcessLinux::MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid)
2361{
2362 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2363 const bool is_main_thread = (pid == GetID ());
2364
2365 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
2366 if (!info)
2367 return;
2368
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002369 Mutex::Locker locker (m_threads_mutex);
2370
Todd Fialaaf245d12014-06-30 21:05:18 +00002371 // See if we can find a thread for this signal.
2372 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2373 if (!thread_sp)
2374 {
2375 if (log)
2376 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2377 }
2378
2379 switch (info->si_code)
2380 {
2381 // TODO: these two cases are required if we want to support tracing of the inferiors' children. We'd need this to debug a monitor.
2382 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
2383 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
2384
2385 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
2386 {
Pavel Labath5fd24c62015-04-23 09:04:35 +00002387 // This is the notification on the parent thread which informs us of new thread
Pavel Labath426bdf82015-04-28 07:51:52 +00002388 // creation.
2389 // We don't want to do anything with the parent thread so we just resume it. In case we
2390 // want to implement "break on thread creation" functionality, we would need to stop
2391 // here.
Todd Fialaaf245d12014-06-30 21:05:18 +00002392
Pavel Labath426bdf82015-04-28 07:51:52 +00002393 unsigned long event_message = 0;
2394 if (GetEventMessage (pid, &event_message).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00002395 {
Pavel Labath426bdf82015-04-28 07:51:52 +00002396 if (log)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002397 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 +00002398 } else
2399 WaitForNewThread(event_message);
Todd Fialaaf245d12014-06-30 21:05:18 +00002400
Pavel Labath5fd24c62015-04-23 09:04:35 +00002401 Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
Todd Fialaaf245d12014-06-30 21:05:18 +00002402 break;
2403 }
2404
2405 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
Todd Fialaa9882ce2014-08-28 15:46:54 +00002406 {
2407 NativeThreadProtocolSP main_thread_sp;
Todd Fialaaf245d12014-06-30 21:05:18 +00002408 if (log)
2409 log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
Todd Fialaa9882ce2014-08-28 15:46:54 +00002410
Chaoren Linfa03ad22015-02-03 01:50:42 +00002411 // The thread state coordinator needs to reset due to the exec.
Pavel Labathc0765592015-05-06 10:46:34 +00002412 ResetForExec ();
Chaoren Linfa03ad22015-02-03 01:50:42 +00002413
2414 // 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 +00002415 if (log)
2416 log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
2417
2418 for (auto thread_sp : m_threads)
Todd Fialaa9882ce2014-08-28 15:46:54 +00002419 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002420 const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
2421 if (is_main_thread)
Todd Fialaa9882ce2014-08-28 15:46:54 +00002422 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002423 main_thread_sp = thread_sp;
2424 if (log)
2425 log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00002426 }
2427 else
2428 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002429 // Tell thread coordinator this thread is dead.
Todd Fialaa9882ce2014-08-28 15:46:54 +00002430 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002431 log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
Todd Fialaa9882ce2014-08-28 15:46:54 +00002432 }
2433 }
2434
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002435 m_threads.clear ();
2436
2437 if (main_thread_sp)
2438 {
2439 m_threads.push_back (main_thread_sp);
2440 SetCurrentThreadID (main_thread_sp->GetID ());
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002441 std::static_pointer_cast<NativeThreadLinux> (main_thread_sp)->SetStoppedByExec ();
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002442 }
2443 else
2444 {
2445 SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
2446 if (log)
2447 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
2448 }
2449
Chaoren Linfa03ad22015-02-03 01:50:42 +00002450 // Tell coordinator about about the "new" (since exec) stopped main thread.
2451 const lldb::tid_t main_thread_tid = GetID ();
2452 NotifyThreadCreateStopped (main_thread_tid);
2453
2454 // NOTE: ideally these next statements would execute at the same time as the coordinator thread create was executed.
2455 // Consider a handler that can execute when that happens.
Todd Fialaa9882ce2014-08-28 15:46:54 +00002456 // Let our delegate know we have just exec'd.
2457 NotifyDidExec ();
2458
2459 // If we have a main thread, indicate we are stopped.
2460 assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
Chaoren Linfa03ad22015-02-03 01:50:42 +00002461
2462 // Let the process know we're stopped.
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002463 CallAfterRunningThreadsStop (pid,
2464 [=] (lldb::tid_t signaling_tid)
2465 {
2466 SetState (StateType::eStateStopped, true);
2467 });
Todd Fialaa9882ce2014-08-28 15:46:54 +00002468
Todd Fialaaf245d12014-06-30 21:05:18 +00002469 break;
Todd Fialaa9882ce2014-08-28 15:46:54 +00002470 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002471
2472 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
2473 {
2474 // The inferior process or one of its threads is about to exit.
Chaoren Linfa03ad22015-02-03 01:50:42 +00002475
2476 // This thread is currently stopped. It's not actually dead yet, just about to be.
2477 NotifyThreadStop (pid);
2478
Todd Fialaaf245d12014-06-30 21:05:18 +00002479 unsigned long data = 0;
Chaoren Lin97ccc292015-02-03 01:51:12 +00002480 if (GetEventMessage(pid, &data).Fail())
Todd Fialaaf245d12014-06-30 21:05:18 +00002481 data = -1;
2482
2483 if (log)
2484 {
2485 log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
2486 __FUNCTION__,
2487 data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
2488 pid,
2489 is_main_thread ? "is main thread" : "not main thread");
2490 }
2491
Todd Fialaaf245d12014-06-30 21:05:18 +00002492 if (is_main_thread)
2493 {
2494 SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
Todd Fialaaf245d12014-06-30 21:05:18 +00002495 }
Todd Fiala75f47c32014-10-11 21:42:09 +00002496
Chaoren Lin9d617ba2015-02-03 01:50:54 +00002497 const int signo = static_cast<int> (data);
Pavel Labathc0765592015-05-06 10:46:34 +00002498 RequestThreadResume (pid,
2499 [=](lldb::tid_t tid_to_resume, bool supress_signal)
2500 {
2501 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2502 return Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo);
2503 },
2504 CoordinatorErrorHandler);
Todd Fialaaf245d12014-06-30 21:05:18 +00002505
2506 break;
2507 }
2508
2509 case 0:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002510 case TRAP_TRACE: // We receive this on single stepping.
2511 case TRAP_HWBKPT: // We receive this on watchpoint hit
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002512 if (thread_sp)
2513 {
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002514 // If a watchpoint was hit, report it
2515 uint32_t wp_index;
2516 Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index);
2517 if (error.Fail() && log)
2518 log->Printf("NativeProcessLinux::%s() "
2519 "received error while checking for watchpoint hits, "
2520 "pid = %" PRIu64 " error = %s",
2521 __FUNCTION__, pid, error.AsCString());
2522 if (wp_index != LLDB_INVALID_INDEX32)
2523 {
2524 MonitorWatchpoint(pid, thread_sp, wp_index);
2525 break;
2526 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002527 }
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002528 // Otherwise, report step over
2529 MonitorTrace(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00002530 break;
2531
2532 case SI_KERNEL:
2533 case TRAP_BRKPT:
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002534 MonitorBreakpoint(pid, thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00002535 break;
2536
2537 case SIGTRAP:
2538 case (SIGTRAP | 0x80):
2539 if (log)
Chaoren Linfa03ad22015-02-03 01:50:42 +00002540 log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), pid);
2541
2542 // This thread is currently stopped.
2543 NotifyThreadStop (pid);
2544 if (thread_sp)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002545 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGTRAP);
Chaoren Linfa03ad22015-02-03 01:50:42 +00002546
2547
Todd Fialaaf245d12014-06-30 21:05:18 +00002548 // Ignore these signals until we know more about them.
Pavel Labathc0765592015-05-06 10:46:34 +00002549 RequestThreadResume (pid,
2550 [=](lldb::tid_t tid_to_resume, bool supress_signal)
2551 {
2552 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2553 return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER);
2554 },
2555 CoordinatorErrorHandler);
Todd Fialaaf245d12014-06-30 21:05:18 +00002556 break;
2557
2558 default:
2559 assert(false && "Unexpected SIGTRAP code!");
2560 if (log)
2561 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 "tid %" PRIu64 " received unhandled SIGTRAP code: 0x%" PRIx64, __FUNCTION__, GetID (), pid, static_cast<uint64_t> (SIGTRAP | (PTRACE_EVENT_CLONE << 8)));
2562 break;
2563
2564 }
2565}
2566
2567void
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002568NativeProcessLinux::MonitorTrace(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
2569{
2570 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2571 if (log)
2572 log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)",
2573 __FUNCTION__, pid);
2574
2575 if (thread_sp)
2576 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
2577
2578 // This thread is currently stopped.
2579 NotifyThreadStop(pid);
2580
2581 // Here we don't have to request the rest of the threads to stop or request a deferred stop.
2582 // This would have already happened at the time the Resume() with step operation was signaled.
2583 // At this point, we just need to say we stopped, and the deferred notifcation will fire off
2584 // once all running threads have checked in as stopped.
2585 SetCurrentThreadID(pid);
2586 // Tell the process we have a stop (from software breakpoint).
2587 CallAfterRunningThreadsStop(pid,
2588 [=](lldb::tid_t signaling_tid)
2589 {
2590 SetState(StateType::eStateStopped, true);
2591 });
2592}
2593
2594void
2595NativeProcessLinux::MonitorBreakpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp)
2596{
2597 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
2598 if (log)
2599 log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
2600 __FUNCTION__, pid);
2601
2602 // This thread is currently stopped.
2603 NotifyThreadStop(pid);
2604
2605 // Mark the thread as stopped at breakpoint.
2606 if (thread_sp)
2607 {
2608 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByBreakpoint();
2609 Error error = FixupBreakpointPCAsNeeded(thread_sp);
2610 if (error.Fail())
2611 if (log)
2612 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
2613 __FUNCTION__, pid, error.AsCString());
Tamas Berghammerd8c338d2015-04-15 09:47:02 +00002614
2615 auto it = m_threads_stepping_with_breakpoint.find(pid);
2616 if (it != m_threads_stepping_with_breakpoint.end())
2617 {
2618 Error error = RemoveBreakpoint (it->second);
2619 if (error.Fail())
2620 if (log)
2621 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " remove stepping breakpoint: %s",
2622 __FUNCTION__, pid, error.AsCString());
2623
2624 m_threads_stepping_with_breakpoint.erase(it);
2625 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace();
2626 }
Chaoren Linc16f5dc2015-03-19 23:28:10 +00002627 }
2628 else
2629 if (log)
2630 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 ": "
2631 "warning, cannot process software breakpoint since no thread metadata",
2632 __FUNCTION__, pid);
2633
2634
2635 // We need to tell all other running threads before we notify the delegate about this stop.
2636 CallAfterRunningThreadsStop(pid,
2637 [=](lldb::tid_t deferred_notification_tid)
2638 {
2639 SetCurrentThreadID(deferred_notification_tid);
2640 // Tell the process we have a stop (from software breakpoint).
2641 SetState(StateType::eStateStopped, true);
2642 });
2643}
2644
2645void
2646NativeProcessLinux::MonitorWatchpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp, uint32_t wp_index)
2647{
2648 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
2649 if (log)
2650 log->Printf("NativeProcessLinux::%s() received watchpoint event, "
2651 "pid = %" PRIu64 ", wp_index = %" PRIu32,
2652 __FUNCTION__, pid, wp_index);
2653
2654 // This thread is currently stopped.
2655 NotifyThreadStop(pid);
2656
2657 // Mark the thread as stopped at watchpoint.
2658 // The address is at (lldb::addr_t)info->si_addr if we need it.
2659 lldbassert(thread_sp && "thread_sp cannot be NULL");
2660 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByWatchpoint(wp_index);
2661
2662 // We need to tell all other running threads before we notify the delegate about this stop.
2663 CallAfterRunningThreadsStop(pid,
2664 [=](lldb::tid_t deferred_notification_tid)
2665 {
2666 SetCurrentThreadID(deferred_notification_tid);
2667 // Tell the process we have a stop (from watchpoint).
2668 SetState(StateType::eStateStopped, true);
2669 });
2670}
2671
2672void
Todd Fialaaf245d12014-06-30 21:05:18 +00002673NativeProcessLinux::MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited)
2674{
Todd Fiala511e5cd2014-09-11 23:29:14 +00002675 assert (info && "null info");
2676 if (!info)
2677 return;
2678
2679 const int signo = info->si_signo;
2680 const bool is_from_llgs = info->si_pid == getpid ();
Todd Fialaaf245d12014-06-30 21:05:18 +00002681
2682 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2683
2684 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
2685 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
2686 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
2687 //
2688 // IOW, user generated signals never generate what we consider to be a
2689 // "crash".
2690 //
2691 // Similarly, ACK signals generated by this monitor.
2692
Tamas Berghammer5830aa72015-02-06 10:42:33 +00002693 Mutex::Locker locker (m_threads_mutex);
2694
Todd Fialaaf245d12014-06-30 21:05:18 +00002695 // See if we can find a thread for this signal.
2696 NativeThreadProtocolSP thread_sp = GetThreadByID (pid);
2697 if (!thread_sp)
2698 {
2699 if (log)
2700 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid);
2701 }
2702
2703 // Handle the signal.
2704 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
2705 {
2706 if (log)
2707 log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
2708 __FUNCTION__,
2709 GetUnixSignals ().GetSignalAsCString (signo),
2710 signo,
2711 (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
2712 info->si_pid,
Todd Fiala511e5cd2014-09-11 23:29:14 +00002713 is_from_llgs ? "from llgs" : "not from llgs",
Todd Fialaaf245d12014-06-30 21:05:18 +00002714 pid);
Todd Fiala58a2f662014-08-12 17:02:07 +00002715 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002716
Todd Fiala58a2f662014-08-12 17:02:07 +00002717 // Check for new thread notification.
2718 if ((info->si_pid == 0) && (info->si_code == SI_USER))
2719 {
Pavel Labath426bdf82015-04-28 07:51:52 +00002720 // A new thread creation is being signaled. This is one of two parts that come in
2721 // a non-deterministic order. This code handles the case where the new thread event comes
2722 // before the event on the parent thread. For the opposite case see code in
2723 // MonitorSIGTRAP.
Todd Fiala58a2f662014-08-12 17:02:07 +00002724 if (log)
2725 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": new thread notification",
2726 __FUNCTION__, GetID (), pid);
2727
Pavel Labath5fd24c62015-04-23 09:04:35 +00002728 thread_sp = AddThread(pid);
2729 assert (thread_sp.get() && "failed to create the tracking data for newly created inferior thread");
2730 // We can now resume the newly created thread.
2731 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2732 Resume (pid, LLDB_INVALID_SIGNAL_NUMBER);
Pavel Labathc0765592015-05-06 10:46:34 +00002733 NotifyThreadCreate (pid, false, CoordinatorErrorHandler);
Todd Fiala58a2f662014-08-12 17:02:07 +00002734 // Done handling.
2735 return;
2736 }
2737
2738 // Check for thread stop notification.
Todd Fiala511e5cd2014-09-11 23:29:14 +00002739 if (is_from_llgs && (info->si_code == SI_TKILL) && (signo == SIGSTOP))
Todd Fiala58a2f662014-08-12 17:02:07 +00002740 {
2741 // This is a tgkill()-based stop.
2742 if (thread_sp)
2743 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00002744 if (log)
2745 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
2746 __FUNCTION__,
2747 GetID (),
2748 pid);
2749
Chaoren Linaab58632015-02-03 01:50:57 +00002750 // Check that we're not already marked with a stop reason.
2751 // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
2752 // the kernel signaled us with the thread stopping which we handled and marked as stopped,
2753 // and that, without an intervening resume, we received another stop. It is more likely
2754 // that we are missing the marking of a run state somewhere if we find that the thread was
2755 // marked as stopped.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002756 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
2757 assert (linux_thread_sp && "linux_thread_sp is null!");
Chaoren Linaab58632015-02-03 01:50:57 +00002758
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002759 const StateType thread_state = linux_thread_sp->GetState ();
Chaoren Linaab58632015-02-03 01:50:57 +00002760 if (!StateIsStoppedState (thread_state, false))
2761 {
2762 // An inferior thread just stopped, but was not the primary cause of the process stop.
2763 // Instead, something else (like a breakpoint or step) caused the stop. Mark the
2764 // stop signal as 0 to let lldb know this isn't the important stop.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002765 linux_thread_sp->SetStoppedBySignal (0);
Chaoren Linaab58632015-02-03 01:50:57 +00002766 SetCurrentThreadID (thread_sp->GetID ());
Pavel Labathc0765592015-05-06 10:46:34 +00002767 NotifyThreadStop (thread_sp->GetID (), true, CoordinatorErrorHandler);
Chaoren Linaab58632015-02-03 01:50:57 +00002768 }
2769 else
2770 {
2771 if (log)
2772 {
2773 // Retrieve the signal name if the thread was stopped by a signal.
2774 int stop_signo = 0;
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002775 const bool stopped_by_signal = linux_thread_sp->IsStopped (&stop_signo);
Chaoren Linaab58632015-02-03 01:50:57 +00002776 const char *signal_name = stopped_by_signal ? GetUnixSignals ().GetSignalAsCString (stop_signo) : "<not stopped by signal>";
2777 if (!signal_name)
2778 signal_name = "<no-signal-name>";
2779
2780 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",
2781 __FUNCTION__,
2782 GetID (),
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002783 linux_thread_sp->GetID (),
Chaoren Linaab58632015-02-03 01:50:57 +00002784 StateAsCString (thread_state),
2785 stop_signo,
2786 signal_name);
2787 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002788 // Tell the thread state coordinator about the stop.
2789 NotifyThreadStop (thread_sp->GetID ());
Chaoren Linaab58632015-02-03 01:50:57 +00002790 }
Todd Fiala58a2f662014-08-12 17:02:07 +00002791 }
2792
2793 // Done handling.
Todd Fialaaf245d12014-06-30 21:05:18 +00002794 return;
2795 }
2796
2797 if (log)
2798 log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, GetUnixSignals ().GetSignalAsCString (signo));
2799
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002800 // This thread is stopped.
2801 NotifyThreadStop (pid);
2802
Todd Fialaaf245d12014-06-30 21:05:18 +00002803 switch (signo)
2804 {
Todd Fiala511e5cd2014-09-11 23:29:14 +00002805 case SIGSTOP:
2806 {
2807 if (log)
2808 {
2809 if (is_from_llgs)
2810 log->Printf ("NativeProcessLinux::%s pid = %" PRIu64 " tid %" PRIu64 " received SIGSTOP from llgs, most likely an interrupt", __FUNCTION__, GetID (), pid);
2811 else
2812 log->Printf ("NativeProcessLinux::%s pid = %" PRIu64 " tid %" PRIu64 " received SIGSTOP from outside of debugger", __FUNCTION__, GetID (), pid);
2813 }
2814
Chaoren Linfa03ad22015-02-03 01:50:42 +00002815 // Resume this thread to get the group-stop mechanism to fire off the true group stops.
2816 // This thread will get stopped again as part of the group-stop completion.
Pavel Labathc0765592015-05-06 10:46:34 +00002817 RequestThreadResume (pid,
2818 [=](lldb::tid_t tid_to_resume, bool supress_signal)
2819 {
2820 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
2821 // Pass this signal number on to the inferior to handle.
2822 return Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo);
2823 },
2824 CoordinatorErrorHandler);
Todd Fiala511e5cd2014-09-11 23:29:14 +00002825 }
Todd Fialaaf245d12014-06-30 21:05:18 +00002826 break;
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002827 case SIGSEGV:
2828 case SIGILL:
2829 case SIGFPE:
2830 case SIGBUS:
2831 if (thread_sp)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002832 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetCrashedWithException (*info);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002833 break;
2834 default:
2835 // This is just a pre-signal-delivery notification of the incoming signal.
2836 if (thread_sp)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00002837 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (signo);
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002838
2839 break;
Todd Fialaaf245d12014-06-30 21:05:18 +00002840 }
Chaoren Lin86fd8e42015-02-03 01:51:15 +00002841
2842 // Send a stop to the debugger after we get all other threads to stop.
2843 CallAfterRunningThreadsStop (pid,
2844 [=] (lldb::tid_t signaling_tid)
2845 {
2846 SetCurrentThreadID (signaling_tid);
2847 SetState (StateType::eStateStopped, true);
2848 });
Todd Fialaaf245d12014-06-30 21:05:18 +00002849}
2850
Tamas Berghammere7708682015-04-22 10:00:23 +00002851namespace {
2852
2853struct EmulatorBaton
2854{
2855 NativeProcessLinux* m_process;
2856 NativeRegisterContext* m_reg_context;
Tamas Berghammere7708682015-04-22 10:00:23 +00002857
Pavel Labath6648fcc2015-04-27 09:21:14 +00002858 // eRegisterKindDWARF -> RegsiterValue
2859 std::unordered_map<uint32_t, RegisterValue> m_register_values;
2860
2861 EmulatorBaton(NativeProcessLinux* process, NativeRegisterContext* reg_context) :
Tamas Berghammere7708682015-04-22 10:00:23 +00002862 m_process(process), m_reg_context(reg_context) {}
2863};
2864
2865} // anonymous namespace
2866
2867static size_t
2868ReadMemoryCallback (EmulateInstruction *instruction,
2869 void *baton,
2870 const EmulateInstruction::Context &context,
2871 lldb::addr_t addr,
2872 void *dst,
2873 size_t length)
2874{
2875 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
2876
Chaoren Lin3eb4b452015-04-29 17:24:48 +00002877 size_t bytes_read;
Tamas Berghammere7708682015-04-22 10:00:23 +00002878 emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
2879 return bytes_read;
2880}
2881
2882static bool
2883ReadRegisterCallback (EmulateInstruction *instruction,
2884 void *baton,
2885 const RegisterInfo *reg_info,
2886 RegisterValue &reg_value)
2887{
2888 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
2889
Pavel Labath6648fcc2015-04-27 09:21:14 +00002890 auto it = emulator_baton->m_register_values.find(reg_info->kinds[eRegisterKindDWARF]);
2891 if (it != emulator_baton->m_register_values.end())
2892 {
2893 reg_value = it->second;
2894 return true;
2895 }
2896
Tamas Berghammere7708682015-04-22 10:00:23 +00002897 // The emulator only fill in the dwarf regsiter numbers (and in some case
2898 // the generic register numbers). Get the full register info from the
2899 // register context based on the dwarf register numbers.
2900 const RegisterInfo* full_reg_info = emulator_baton->m_reg_context->GetRegisterInfo(
2901 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
2902
2903 Error error = emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
Pavel Labath6648fcc2015-04-27 09:21:14 +00002904 if (error.Success())
2905 {
2906 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = reg_value;
2907 return true;
2908 }
2909 return false;
Tamas Berghammere7708682015-04-22 10:00:23 +00002910}
2911
2912static bool
2913WriteRegisterCallback (EmulateInstruction *instruction,
2914 void *baton,
2915 const EmulateInstruction::Context &context,
2916 const RegisterInfo *reg_info,
2917 const RegisterValue &reg_value)
2918{
2919 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
Pavel Labath6648fcc2015-04-27 09:21:14 +00002920 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = reg_value;
Tamas Berghammere7708682015-04-22 10:00:23 +00002921 return true;
2922}
2923
2924static size_t
2925WriteMemoryCallback (EmulateInstruction *instruction,
2926 void *baton,
2927 const EmulateInstruction::Context &context,
2928 lldb::addr_t addr,
2929 const void *dst,
2930 size_t length)
2931{
2932 return length;
2933}
2934
2935static lldb::addr_t
2936ReadFlags (NativeRegisterContext* regsiter_context)
2937{
2938 const RegisterInfo* flags_info = regsiter_context->GetRegisterInfo(
2939 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
2940 return regsiter_context->ReadRegisterAsUnsigned(flags_info, LLDB_INVALID_ADDRESS);
2941}
2942
2943Error
2944NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadProtocolSP thread_sp)
2945{
2946 Error error;
2947 NativeRegisterContextSP register_context_sp = thread_sp->GetRegisterContext();
2948
2949 std::unique_ptr<EmulateInstruction> emulator_ap(
2950 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, nullptr));
2951
2952 if (emulator_ap == nullptr)
2953 return Error("Instruction emulator not found!");
2954
2955 EmulatorBaton baton(this, register_context_sp.get());
2956 emulator_ap->SetBaton(&baton);
2957 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
2958 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
2959 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
2960 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
2961
2962 if (!emulator_ap->ReadInstruction())
2963 return Error("Read instruction failed!");
2964
Pavel Labath6648fcc2015-04-27 09:21:14 +00002965 bool emulation_result = emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
2966
2967 const RegisterInfo* reg_info_pc = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
2968 const RegisterInfo* reg_info_flags = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
2969
2970 auto pc_it = baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
2971 auto flags_it = baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
2972
Tamas Berghammere7708682015-04-22 10:00:23 +00002973 lldb::addr_t next_pc;
2974 lldb::addr_t next_flags;
Pavel Labath6648fcc2015-04-27 09:21:14 +00002975 if (emulation_result)
Tamas Berghammere7708682015-04-22 10:00:23 +00002976 {
Pavel Labath6648fcc2015-04-27 09:21:14 +00002977 assert(pc_it != baton.m_register_values.end() && "Emulation was successfull but PC wasn't updated");
2978 next_pc = pc_it->second.GetAsUInt64();
2979
2980 if (flags_it != baton.m_register_values.end())
2981 next_flags = flags_it->second.GetAsUInt64();
Tamas Berghammere7708682015-04-22 10:00:23 +00002982 else
2983 next_flags = ReadFlags (register_context_sp.get());
2984 }
Pavel Labath6648fcc2015-04-27 09:21:14 +00002985 else if (pc_it == baton.m_register_values.end())
Tamas Berghammere7708682015-04-22 10:00:23 +00002986 {
2987 // Emulate instruction failed and it haven't changed PC. Advance PC
2988 // with the size of the current opcode because the emulation of all
2989 // PC modifying instruction should be successful. The failure most
2990 // likely caused by a not supported instruction which don't modify PC.
2991 next_pc = register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
2992 next_flags = ReadFlags (register_context_sp.get());
2993 }
2994 else
2995 {
2996 // The instruction emulation failed after it modified the PC. It is an
2997 // unknown error where we can't continue because the next instruction is
2998 // modifying the PC but we don't know how.
2999 return Error ("Instruction emulation failed unexpectedly.");
3000 }
3001
3002 if (m_arch.GetMachine() == llvm::Triple::arm)
3003 {
3004 if (next_flags & 0x20)
3005 {
3006 // Thumb mode
3007 error = SetSoftwareBreakpoint(next_pc, 2);
3008 }
3009 else
3010 {
3011 // Arm mode
3012 error = SetSoftwareBreakpoint(next_pc, 4);
3013 }
3014 }
3015 else
3016 {
3017 // No size hint is given for the next breakpoint
3018 error = SetSoftwareBreakpoint(next_pc, 0);
3019 }
3020
Tamas Berghammere7708682015-04-22 10:00:23 +00003021 if (error.Fail())
3022 return error;
3023
3024 m_threads_stepping_with_breakpoint.insert({thread_sp->GetID(), next_pc});
3025
3026 return Error();
3027}
3028
3029bool
3030NativeProcessLinux::SupportHardwareSingleStepping() const
3031{
3032 return m_arch.GetMachine() != llvm::Triple::arm;
3033}
3034
Todd Fialaaf245d12014-06-30 21:05:18 +00003035Error
3036NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
3037{
Todd Fialaaf245d12014-06-30 21:05:18 +00003038 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
3039 if (log)
3040 log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
3041
Chaoren Lin03f12d62015-02-03 01:50:49 +00003042 lldb::tid_t deferred_signal_tid = LLDB_INVALID_THREAD_ID;
3043 lldb::tid_t deferred_signal_skip_tid = LLDB_INVALID_THREAD_ID;
Chaoren Linae29d392015-02-03 01:50:46 +00003044 int deferred_signo = 0;
3045 NativeThreadProtocolSP deferred_signal_thread_sp;
Chaoren Lin86fd8e42015-02-03 01:51:15 +00003046 bool stepping = false;
Tamas Berghammere7708682015-04-22 10:00:23 +00003047 bool software_single_step = !SupportHardwareSingleStepping();
Todd Fialaaf245d12014-06-30 21:05:18 +00003048
Pavel Labath45f5cb32015-05-05 15:05:50 +00003049 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003050 Mutex::Locker locker (m_threads_mutex);
Chaoren Lin03f12d62015-02-03 01:50:49 +00003051
Tamas Berghammere7708682015-04-22 10:00:23 +00003052 if (software_single_step)
3053 {
3054 for (auto thread_sp : m_threads)
3055 {
3056 assert (thread_sp && "thread list should not contain NULL threads");
3057
3058 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
3059 if (action == nullptr)
3060 continue;
3061
3062 if (action->state == eStateStepping)
3063 {
3064 Error error = SetupSoftwareSingleStepping(thread_sp);
3065 if (error.Fail())
3066 return error;
3067 }
3068 }
3069 }
3070
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003071 for (auto thread_sp : m_threads)
Todd Fialaaf245d12014-06-30 21:05:18 +00003072 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003073 assert (thread_sp && "thread list should not contain NULL threads");
3074
3075 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
3076
3077 if (action == nullptr)
Todd Fialaaf245d12014-06-30 21:05:18 +00003078 {
Chaoren Linfa03ad22015-02-03 01:50:42 +00003079 if (log)
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003080 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
3081 __FUNCTION__, GetID (), thread_sp->GetID ());
3082 continue;
3083 }
Todd Fialaaf245d12014-06-30 21:05:18 +00003084
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003085 if (log)
3086 {
3087 log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
3088 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
3089 }
Todd Fialaaf245d12014-06-30 21:05:18 +00003090
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003091 switch (action->state)
3092 {
3093 case eStateRunning:
3094 {
3095 // Run the thread, possibly feeding it the signal.
3096 const int signo = action->signal;
Pavel Labathc0765592015-05-06 10:46:34 +00003097 RequestThreadResumeAsNeeded (thread_sp->GetID (),
3098 [=](lldb::tid_t tid_to_resume, bool supress_signal)
3099 {
3100 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning ();
3101 // Pass this signal number on to the inferior to handle.
3102 const auto resume_result = Resume (tid_to_resume, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
3103 if (resume_result.Success())
3104 SetState(eStateRunning, true);
3105 return resume_result;
3106 },
3107 CoordinatorErrorHandler);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003108 break;
3109 }
3110
3111 case eStateStepping:
3112 {
3113 // Request the step.
3114 const int signo = action->signal;
Pavel Labathc0765592015-05-06 10:46:34 +00003115 RequestThreadResume (thread_sp->GetID (),
3116 [=](lldb::tid_t tid_to_step, bool supress_signal)
3117 {
3118 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStepping ();
Tamas Berghammere7708682015-04-22 10:00:23 +00003119
Pavel Labathc0765592015-05-06 10:46:34 +00003120 Error step_result;
3121 if (software_single_step)
3122 step_result = Resume (tid_to_step, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
3123 else
3124 step_result = SingleStep (tid_to_step,(signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER);
Tamas Berghammere7708682015-04-22 10:00:23 +00003125
Pavel Labathc0765592015-05-06 10:46:34 +00003126 assert (step_result.Success() && "SingleStep() failed");
3127 if (step_result.Success())
3128 SetState(eStateStepping, true);
3129 return step_result;
3130 },
3131 CoordinatorErrorHandler);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003132 stepping = true;
3133 break;
3134 }
3135
3136 case eStateSuspended:
3137 case eStateStopped:
3138 // if we haven't chosen a deferred signal tid yet, use this one.
3139 if (deferred_signal_tid == LLDB_INVALID_THREAD_ID)
Chaoren Linae29d392015-02-03 01:50:46 +00003140 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003141 deferred_signal_tid = thread_sp->GetID ();
3142 deferred_signal_thread_sp = thread_sp;
3143 deferred_signo = SIGSTOP;
Chaoren Linae29d392015-02-03 01:50:46 +00003144 }
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003145 break;
Chaoren Linfa03ad22015-02-03 01:50:42 +00003146
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003147 default:
3148 return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
3149 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
Todd Fialaaf245d12014-06-30 21:05:18 +00003150 }
3151 }
3152
Chaoren Linfa03ad22015-02-03 01:50:42 +00003153 // If we had any thread stopping, then do a deferred notification of the chosen stop thread id and signal
3154 // after all other running threads have stopped.
Chaoren Lin86fd8e42015-02-03 01:51:15 +00003155 // If there is a stepping thread involved we'll be eventually stopped by SIGTRAP trace signal.
3156 if (deferred_signal_tid != LLDB_INVALID_THREAD_ID && !stepping)
Todd Fialaaf245d12014-06-30 21:05:18 +00003157 {
Chaoren Lin03f12d62015-02-03 01:50:49 +00003158 CallAfterRunningThreadsStopWithSkipTID (deferred_signal_tid,
3159 deferred_signal_skip_tid,
Chaoren Linfa03ad22015-02-03 01:50:42 +00003160 [=](lldb::tid_t deferred_notification_tid)
3161 {
Chaoren Linae29d392015-02-03 01:50:46 +00003162 // Set the signal thread to the current thread.
Chaoren Linfa03ad22015-02-03 01:50:42 +00003163 SetCurrentThreadID (deferred_notification_tid);
Chaoren Linae29d392015-02-03 01:50:46 +00003164
3165 // Set the thread state as stopped by the deferred signo.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003166 std::static_pointer_cast<NativeThreadLinux> (deferred_signal_thread_sp)->SetStoppedBySignal (deferred_signo);
Chaoren Linae29d392015-02-03 01:50:46 +00003167
3168 // Tell the process delegate that the process is in a stopped state.
Chaoren Linfa03ad22015-02-03 01:50:42 +00003169 SetState (StateType::eStateStopped, true);
3170 });
Todd Fialaaf245d12014-06-30 21:05:18 +00003171 }
3172
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003173 return Error();
Todd Fialaaf245d12014-06-30 21:05:18 +00003174}
3175
3176Error
3177NativeProcessLinux::Halt ()
3178{
3179 Error error;
3180
Todd Fialaaf245d12014-06-30 21:05:18 +00003181 if (kill (GetID (), SIGSTOP) != 0)
3182 error.SetErrorToErrno ();
3183
3184 return error;
3185}
3186
3187Error
3188NativeProcessLinux::Detach ()
3189{
3190 Error error;
3191
3192 // Tell ptrace to detach from the process.
3193 if (GetID () != LLDB_INVALID_PROCESS_ID)
3194 error = Detach (GetID ());
3195
3196 // Stop monitoring the inferior.
Pavel Labath45f5cb32015-05-05 15:05:50 +00003197 m_monitor_up->Terminate();
Todd Fialaaf245d12014-06-30 21:05:18 +00003198
3199 // No error.
3200 return error;
3201}
3202
3203Error
3204NativeProcessLinux::Signal (int signo)
3205{
3206 Error error;
3207
3208 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3209 if (log)
3210 log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
3211 __FUNCTION__, signo, GetUnixSignals ().GetSignalAsCString (signo), GetID ());
3212
3213 if (kill(GetID(), signo))
3214 error.SetErrorToErrno();
3215
3216 return error;
3217}
3218
3219Error
Chaoren Line9547b82015-02-03 01:51:00 +00003220NativeProcessLinux::Interrupt ()
3221{
3222 // Pick a running thread (or if none, a not-dead stopped thread) as
3223 // the chosen thread that will be the stop-reason thread.
Chaoren Line9547b82015-02-03 01:51:00 +00003224 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3225
3226 NativeThreadProtocolSP running_thread_sp;
3227 NativeThreadProtocolSP stopped_thread_sp;
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003228
3229 if (log)
3230 log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
3231
Pavel Labath45f5cb32015-05-05 15:05:50 +00003232 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003233 Mutex::Locker locker (m_threads_mutex);
3234
3235 for (auto thread_sp : m_threads)
Chaoren Line9547b82015-02-03 01:51:00 +00003236 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003237 // The thread shouldn't be null but lets just cover that here.
3238 if (!thread_sp)
3239 continue;
Chaoren Line9547b82015-02-03 01:51:00 +00003240
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003241 // If we have a running or stepping thread, we'll call that the
3242 // target of the interrupt.
3243 const auto thread_state = thread_sp->GetState ();
3244 if (thread_state == eStateRunning ||
3245 thread_state == eStateStepping)
Chaoren Line9547b82015-02-03 01:51:00 +00003246 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003247 running_thread_sp = thread_sp;
3248 break;
3249 }
3250 else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
3251 {
3252 // Remember the first non-dead stopped thread. We'll use that as a backup if there are no running threads.
3253 stopped_thread_sp = thread_sp;
Chaoren Line9547b82015-02-03 01:51:00 +00003254 }
3255 }
3256
3257 if (!running_thread_sp && !stopped_thread_sp)
3258 {
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003259 Error error("found no running/stepping or live stopped threads as target for interrupt");
Chaoren Line9547b82015-02-03 01:51:00 +00003260 if (log)
Chaoren Line9547b82015-02-03 01:51:00 +00003261 log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003262
Chaoren Line9547b82015-02-03 01:51:00 +00003263 return error;
3264 }
3265
3266 NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
3267
3268 if (log)
3269 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
3270 __FUNCTION__,
3271 GetID (),
3272 running_thread_sp ? "running" : "stopped",
3273 deferred_signal_thread_sp->GetID ());
3274
3275 CallAfterRunningThreadsStop (deferred_signal_thread_sp->GetID (),
3276 [=](lldb::tid_t deferred_notification_tid)
3277 {
3278 // Set the signal thread to the current thread.
3279 SetCurrentThreadID (deferred_notification_tid);
3280
3281 // Set the thread state as stopped by the deferred signo.
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00003282 std::static_pointer_cast<NativeThreadLinux> (deferred_signal_thread_sp)->SetStoppedBySignal (SIGSTOP);
Chaoren Line9547b82015-02-03 01:51:00 +00003283
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003284 // Tell the process delegate that the process is in a stopped state.
3285 SetState (StateType::eStateStopped, true);
3286 });
Pavel Labath45f5cb32015-05-05 15:05:50 +00003287
Tamas Berghammer5830aa72015-02-06 10:42:33 +00003288 return Error();
Chaoren Line9547b82015-02-03 01:51:00 +00003289}
3290
3291Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003292NativeProcessLinux::Kill ()
3293{
3294 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3295 if (log)
3296 log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
3297
3298 Error error;
3299
3300 switch (m_state)
3301 {
3302 case StateType::eStateInvalid:
3303 case StateType::eStateExited:
3304 case StateType::eStateCrashed:
3305 case StateType::eStateDetached:
3306 case StateType::eStateUnloaded:
3307 // Nothing to do - the process is already dead.
3308 if (log)
3309 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
3310 return error;
3311
3312 case StateType::eStateConnected:
3313 case StateType::eStateAttaching:
3314 case StateType::eStateLaunching:
3315 case StateType::eStateStopped:
3316 case StateType::eStateRunning:
3317 case StateType::eStateStepping:
3318 case StateType::eStateSuspended:
3319 // We can try to kill a process in these states.
3320 break;
3321 }
3322
3323 if (kill (GetID (), SIGKILL) != 0)
3324 {
3325 error.SetErrorToErrno ();
3326 return error;
3327 }
3328
3329 return error;
3330}
3331
3332static Error
3333ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
3334{
3335 memory_region_info.Clear();
3336
3337 StringExtractor line_extractor (maps_line.c_str ());
3338
3339 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode pathname
3340 // perms: rwxp (letter is present if set, '-' if not, final character is p=private, s=shared).
3341
3342 // Parse out the starting address
3343 lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
3344
3345 // Parse out hyphen separating start and end address from range.
3346 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
3347 return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
3348
3349 // Parse out the ending address
3350 lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
3351
3352 // Parse out the space after the address.
3353 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
3354 return Error ("malformed /proc/{pid}/maps entry, missing space after range");
3355
3356 // Save the range.
3357 memory_region_info.GetRange ().SetRangeBase (start_address);
3358 memory_region_info.GetRange ().SetRangeEnd (end_address);
3359
3360 // Parse out each permission entry.
3361 if (line_extractor.GetBytesLeft () < 4)
3362 return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
3363
3364 // Handle read permission.
3365 const char read_perm_char = line_extractor.GetChar ();
3366 if (read_perm_char == 'r')
3367 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
3368 else
3369 {
3370 assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" );
3371 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
3372 }
3373
3374 // Handle write permission.
3375 const char write_perm_char = line_extractor.GetChar ();
3376 if (write_perm_char == 'w')
3377 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
3378 else
3379 {
3380 assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" );
3381 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
3382 }
3383
3384 // Handle execute permission.
3385 const char exec_perm_char = line_extractor.GetChar ();
3386 if (exec_perm_char == 'x')
3387 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
3388 else
3389 {
3390 assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" );
3391 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
3392 }
3393
3394 return Error ();
3395}
3396
3397Error
3398NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
3399{
3400 // FIXME review that the final memory region returned extends to the end of the virtual address space,
3401 // with no perms if it is not mapped.
3402
3403 // Use an approach that reads memory regions from /proc/{pid}/maps.
3404 // Assume proc maps entries are in ascending order.
3405 // FIXME assert if we find differently.
3406 Mutex::Locker locker (m_mem_region_cache_mutex);
3407
3408 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3409 Error error;
3410
3411 if (m_supports_mem_region == LazyBool::eLazyBoolNo)
3412 {
3413 // We're done.
3414 error.SetErrorString ("unsupported");
3415 return error;
3416 }
3417
3418 // If our cache is empty, pull the latest. There should always be at least one memory region
3419 // if memory region handling is supported.
3420 if (m_mem_region_cache.empty ())
3421 {
3422 error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
3423 [&] (const std::string &line) -> bool
3424 {
3425 MemoryRegionInfo info;
3426 const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
3427 if (parse_error.Success ())
3428 {
3429 m_mem_region_cache.push_back (info);
3430 return true;
3431 }
3432 else
3433 {
3434 if (log)
3435 log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
3436 return false;
3437 }
3438 });
3439
3440 // If we had an error, we'll mark unsupported.
3441 if (error.Fail ())
3442 {
3443 m_supports_mem_region = LazyBool::eLazyBoolNo;
3444 return error;
3445 }
3446 else if (m_mem_region_cache.empty ())
3447 {
3448 // No entries after attempting to read them. This shouldn't happen if /proc/{pid}/maps
3449 // is supported. Assume we don't support map entries via procfs.
3450 if (log)
3451 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
3452 m_supports_mem_region = LazyBool::eLazyBoolNo;
3453 error.SetErrorString ("not supported");
3454 return error;
3455 }
3456
3457 if (log)
3458 log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ());
3459
3460 // We support memory retrieval, remember that.
3461 m_supports_mem_region = LazyBool::eLazyBoolYes;
3462 }
3463 else
3464 {
3465 if (log)
3466 log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
3467 }
3468
3469 lldb::addr_t prev_base_address = 0;
3470
3471 // FIXME start by finding the last region that is <= target address using binary search. Data is sorted.
3472 // There can be a ton of regions on pthreads apps with lots of threads.
3473 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
3474 {
3475 MemoryRegionInfo &proc_entry_info = *it;
3476
3477 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
3478 assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
3479 prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
3480
3481 // If the target address comes before this entry, indicate distance to next region.
3482 if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
3483 {
3484 range_info.GetRange ().SetRangeBase (load_addr);
3485 range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
3486 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
3487 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
3488 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
3489
3490 return error;
3491 }
3492 else if (proc_entry_info.GetRange ().Contains (load_addr))
3493 {
3494 // The target address is within the memory region we're processing here.
3495 range_info = proc_entry_info;
3496 return error;
3497 }
3498
3499 // The target memory address comes somewhere after the region we just parsed.
3500 }
3501
3502 // If we made it here, we didn't find an entry that contained the given address.
3503 error.SetErrorString ("address comes after final region");
3504
3505 if (log)
3506 log->Printf ("NativeProcessLinux::%s failed to find map entry for address 0x%" PRIx64 ": %s", __FUNCTION__, load_addr, error.AsCString ());
3507
3508 return error;
3509}
3510
3511void
3512NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
3513{
3514 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3515 if (log)
3516 log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
3517
3518 {
3519 Mutex::Locker locker (m_mem_region_cache_mutex);
3520 if (log)
3521 log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
3522 m_mem_region_cache.clear ();
3523 }
3524}
3525
3526Error
Chaoren Lin3eb4b452015-04-29 17:24:48 +00003527NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr)
Todd Fialaaf245d12014-06-30 21:05:18 +00003528{
3529 // FIXME implementing this requires the equivalent of
3530 // InferiorCallPOSIX::InferiorCallMmap, which depends on
3531 // functional ThreadPlans working with Native*Protocol.
3532#if 1
3533 return Error ("not implemented yet");
3534#else
3535 addr = LLDB_INVALID_ADDRESS;
3536
3537 unsigned prot = 0;
3538 if (permissions & lldb::ePermissionsReadable)
3539 prot |= eMmapProtRead;
3540 if (permissions & lldb::ePermissionsWritable)
3541 prot |= eMmapProtWrite;
3542 if (permissions & lldb::ePermissionsExecutable)
3543 prot |= eMmapProtExec;
3544
3545 // TODO implement this directly in NativeProcessLinux
3546 // (and lift to NativeProcessPOSIX if/when that class is
3547 // refactored out).
3548 if (InferiorCallMmap(this, addr, 0, size, prot,
3549 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
3550 m_addr_to_mmap_size[addr] = size;
3551 return Error ();
3552 } else {
3553 addr = LLDB_INVALID_ADDRESS;
3554 return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
3555 }
3556#endif
3557}
3558
3559Error
3560NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
3561{
3562 // FIXME see comments in AllocateMemory - required lower-level
3563 // bits not in place yet (ThreadPlans)
3564 return Error ("not implemented");
3565}
3566
3567lldb::addr_t
3568NativeProcessLinux::GetSharedLibraryInfoAddress ()
3569{
3570#if 1
3571 // punt on this for now
3572 return LLDB_INVALID_ADDRESS;
3573#else
3574 // Return the image info address for the exe module
3575#if 1
3576 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3577
3578 ModuleSP module_sp;
3579 Error error = GetExeModuleSP (module_sp);
3580 if (error.Fail ())
3581 {
3582 if (log)
3583 log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ());
3584 return LLDB_INVALID_ADDRESS;
3585 }
3586
3587 if (module_sp == nullptr)
3588 {
3589 if (log)
3590 log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__);
3591 return LLDB_INVALID_ADDRESS;
3592 }
3593
3594 ObjectFileSP object_file_sp = module_sp->GetObjectFile ();
3595 if (object_file_sp == nullptr)
3596 {
3597 if (log)
3598 log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__);
3599 return LLDB_INVALID_ADDRESS;
3600 }
3601
3602 return obj_file_sp->GetImageInfoAddress();
3603#else
3604 Target *target = &GetTarget();
3605 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
3606 Address addr = obj_file->GetImageInfoAddress(target);
3607
3608 if (addr.IsValid())
3609 return addr.GetLoadAddress(target);
3610 return LLDB_INVALID_ADDRESS;
3611#endif
3612#endif // punt on this for now
3613}
3614
3615size_t
3616NativeProcessLinux::UpdateThreads ()
3617{
3618 // The NativeProcessLinux monitoring threads are always up to date
3619 // with respect to thread state and they keep the thread list
3620 // populated properly. All this method needs to do is return the
3621 // thread count.
3622 Mutex::Locker locker (m_threads_mutex);
3623 return m_threads.size ();
3624}
3625
3626bool
3627NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
3628{
3629 arch = m_arch;
3630 return true;
3631}
3632
3633Error
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003634NativeProcessLinux::GetSoftwareBreakpointPCOffset (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size)
Todd Fialaaf245d12014-06-30 21:05:18 +00003635{
3636 // FIXME put this behind a breakpoint protocol class that can be
3637 // set per architecture. Need ARM, MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00003638 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Todd Fialaaf245d12014-06-30 21:05:18 +00003639 static const uint8_t g_i386_opcode [] = { 0xCC };
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00003640 static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
Todd Fialaaf245d12014-06-30 21:05:18 +00003641
3642 switch (m_arch.GetMachine ())
3643 {
Todd Fiala2afc5962014-08-21 16:42:31 +00003644 case llvm::Triple::aarch64:
3645 actual_opcode_size = static_cast<uint32_t> (sizeof(g_aarch64_opcode));
3646 return Error ();
3647
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003648 case llvm::Triple::arm:
3649 actual_opcode_size = 0; // On arm the PC don't get updated for breakpoint hits
3650 return Error ();
3651
Todd Fialaaf245d12014-06-30 21:05:18 +00003652 case llvm::Triple::x86:
3653 case llvm::Triple::x86_64:
3654 actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
3655 return Error ();
3656
Mohit K. Bhakkade8659b52015-04-23 06:36:20 +00003657 case llvm::Triple::mips64:
3658 case llvm::Triple::mips64el:
3659 actual_opcode_size = static_cast<uint32_t> (sizeof(g_mips64_opcode));
3660 return Error ();
3661
Todd Fialaaf245d12014-06-30 21:05:18 +00003662 default:
3663 assert(false && "CPU type not supported!");
3664 return Error ("CPU type not supported");
3665 }
3666}
3667
3668Error
3669NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
3670{
3671 if (hardware)
3672 return Error ("NativeProcessLinux does not support hardware breakpoints");
3673 else
3674 return SetSoftwareBreakpoint (addr, size);
3675}
3676
3677Error
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003678NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint,
3679 size_t &actual_opcode_size,
3680 const uint8_t *&trap_opcode_bytes)
Todd Fialaaf245d12014-06-30 21:05:18 +00003681{
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003682 // FIXME put this behind a breakpoint protocol class that can be set per
3683 // architecture. Need MIPS support here.
Todd Fiala2afc5962014-08-21 16:42:31 +00003684 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003685 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
3686 // linux kernel does otherwise.
3687 static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 };
Todd Fialaaf245d12014-06-30 21:05:18 +00003688 static const uint8_t g_i386_opcode [] = { 0xCC };
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00003689 static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00003690 static const uint8_t g_mips64el_opcode[] = { 0x0d, 0x00, 0x00, 0x00 };
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003691 static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde };
Todd Fialaaf245d12014-06-30 21:05:18 +00003692
3693 switch (m_arch.GetMachine ())
3694 {
Todd Fiala2afc5962014-08-21 16:42:31 +00003695 case llvm::Triple::aarch64:
3696 trap_opcode_bytes = g_aarch64_opcode;
3697 actual_opcode_size = sizeof(g_aarch64_opcode);
3698 return Error ();
3699
Tamas Berghammer63c8be92015-04-15 09:38:48 +00003700 case llvm::Triple::arm:
3701 switch (trap_opcode_size_hint)
3702 {
3703 case 2:
3704 trap_opcode_bytes = g_thumb_breakpoint_opcode;
3705 actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
3706 return Error ();
3707 case 4:
3708 trap_opcode_bytes = g_arm_breakpoint_opcode;
3709 actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
3710 return Error ();
3711 default:
3712 assert(false && "Unrecognised trap opcode size hint!");
3713 return Error ("Unrecognised trap opcode size hint!");
3714 }
3715
Todd Fialaaf245d12014-06-30 21:05:18 +00003716 case llvm::Triple::x86:
3717 case llvm::Triple::x86_64:
3718 trap_opcode_bytes = g_i386_opcode;
3719 actual_opcode_size = sizeof(g_i386_opcode);
3720 return Error ();
3721
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00003722 case llvm::Triple::mips64:
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +00003723 trap_opcode_bytes = g_mips64_opcode;
3724 actual_opcode_size = sizeof(g_mips64_opcode);
3725 return Error ();
3726
Mohit K. Bhakkad2c2acf92015-04-09 07:12:15 +00003727 case llvm::Triple::mips64el:
3728 trap_opcode_bytes = g_mips64el_opcode;
3729 actual_opcode_size = sizeof(g_mips64el_opcode);
3730 return Error ();
3731
Todd Fialaaf245d12014-06-30 21:05:18 +00003732 default:
3733 assert(false && "CPU type not supported!");
3734 return Error ("CPU type not supported");
3735 }
3736}
3737
3738#if 0
3739ProcessMessage::CrashReason
3740NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
3741{
3742 ProcessMessage::CrashReason reason;
3743 assert(info->si_signo == SIGSEGV);
3744
3745 reason = ProcessMessage::eInvalidCrashReason;
3746
3747 switch (info->si_code)
3748 {
3749 default:
3750 assert(false && "unexpected si_code for SIGSEGV");
3751 break;
3752 case SI_KERNEL:
3753 // Linux will occasionally send spurious SI_KERNEL codes.
3754 // (this is poorly documented in sigaction)
3755 // One way to get this is via unaligned SIMD loads.
3756 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
3757 break;
3758 case SEGV_MAPERR:
3759 reason = ProcessMessage::eInvalidAddress;
3760 break;
3761 case SEGV_ACCERR:
3762 reason = ProcessMessage::ePrivilegedAddress;
3763 break;
3764 }
3765
3766 return reason;
3767}
3768#endif
3769
3770
3771#if 0
3772ProcessMessage::CrashReason
3773NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
3774{
3775 ProcessMessage::CrashReason reason;
3776 assert(info->si_signo == SIGILL);
3777
3778 reason = ProcessMessage::eInvalidCrashReason;
3779
3780 switch (info->si_code)
3781 {
3782 default:
3783 assert(false && "unexpected si_code for SIGILL");
3784 break;
3785 case ILL_ILLOPC:
3786 reason = ProcessMessage::eIllegalOpcode;
3787 break;
3788 case ILL_ILLOPN:
3789 reason = ProcessMessage::eIllegalOperand;
3790 break;
3791 case ILL_ILLADR:
3792 reason = ProcessMessage::eIllegalAddressingMode;
3793 break;
3794 case ILL_ILLTRP:
3795 reason = ProcessMessage::eIllegalTrap;
3796 break;
3797 case ILL_PRVOPC:
3798 reason = ProcessMessage::ePrivilegedOpcode;
3799 break;
3800 case ILL_PRVREG:
3801 reason = ProcessMessage::ePrivilegedRegister;
3802 break;
3803 case ILL_COPROC:
3804 reason = ProcessMessage::eCoprocessorError;
3805 break;
3806 case ILL_BADSTK:
3807 reason = ProcessMessage::eInternalStackError;
3808 break;
3809 }
3810
3811 return reason;
3812}
3813#endif
3814
3815#if 0
3816ProcessMessage::CrashReason
3817NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
3818{
3819 ProcessMessage::CrashReason reason;
3820 assert(info->si_signo == SIGFPE);
3821
3822 reason = ProcessMessage::eInvalidCrashReason;
3823
3824 switch (info->si_code)
3825 {
3826 default:
3827 assert(false && "unexpected si_code for SIGFPE");
3828 break;
3829 case FPE_INTDIV:
3830 reason = ProcessMessage::eIntegerDivideByZero;
3831 break;
3832 case FPE_INTOVF:
3833 reason = ProcessMessage::eIntegerOverflow;
3834 break;
3835 case FPE_FLTDIV:
3836 reason = ProcessMessage::eFloatDivideByZero;
3837 break;
3838 case FPE_FLTOVF:
3839 reason = ProcessMessage::eFloatOverflow;
3840 break;
3841 case FPE_FLTUND:
3842 reason = ProcessMessage::eFloatUnderflow;
3843 break;
3844 case FPE_FLTRES:
3845 reason = ProcessMessage::eFloatInexactResult;
3846 break;
3847 case FPE_FLTINV:
3848 reason = ProcessMessage::eFloatInvalidOperation;
3849 break;
3850 case FPE_FLTSUB:
3851 reason = ProcessMessage::eFloatSubscriptRange;
3852 break;
3853 }
3854
3855 return reason;
3856}
3857#endif
3858
3859#if 0
3860ProcessMessage::CrashReason
3861NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
3862{
3863 ProcessMessage::CrashReason reason;
3864 assert(info->si_signo == SIGBUS);
3865
3866 reason = ProcessMessage::eInvalidCrashReason;
3867
3868 switch (info->si_code)
3869 {
3870 default:
3871 assert(false && "unexpected si_code for SIGBUS");
3872 break;
3873 case BUS_ADRALN:
3874 reason = ProcessMessage::eIllegalAlignment;
3875 break;
3876 case BUS_ADRERR:
3877 reason = ProcessMessage::eIllegalAddress;
3878 break;
3879 case BUS_OBJERR:
3880 reason = ProcessMessage::eHardwareError;
3881 break;
3882 }
3883
3884 return reason;
3885}
3886#endif
3887
Todd Fialaaf245d12014-06-30 21:05:18 +00003888Error
Pavel Labath45f5cb32015-05-05 15:05:50 +00003889NativeProcessLinux::SetWatchpoint (lldb::addr_t addr, size_t size, uint32_t watch_flags, bool hardware)
3890{
3891 // The base SetWatchpoint will end up executing monitor operations. Let's lock the monitor
3892 // for it.
3893 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
3894 return NativeProcessProtocol::SetWatchpoint(addr, size, watch_flags, hardware);
3895}
3896
3897Error
3898NativeProcessLinux::RemoveWatchpoint (lldb::addr_t addr)
3899{
3900 // The base RemoveWatchpoint will end up executing monitor operations. Let's lock the monitor
3901 // for it.
3902 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up);
3903 return NativeProcessProtocol::RemoveWatchpoint(addr);
3904}
3905
3906Error
Chaoren Lin26438d22015-05-05 17:50:53 +00003907NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
Todd Fialaaf245d12014-06-30 21:05:18 +00003908{
3909 ReadOperation op(addr, buf, size, bytes_read);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003910 m_monitor_up->DoOperation(&op);
Todd Fialaaf245d12014-06-30 21:05:18 +00003911 return op.GetError ();
3912}
3913
3914Error
Chaoren Lin3eb4b452015-04-29 17:24:48 +00003915NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
3916{
3917 Error error = ReadMemory(addr, buf, size, bytes_read);
3918 if (error.Fail()) return error;
3919 return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
3920}
3921
3922Error
3923NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written)
Todd Fialaaf245d12014-06-30 21:05:18 +00003924{
3925 WriteOperation op(addr, buf, size, bytes_written);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003926 m_monitor_up->DoOperation(&op);
Todd Fialaaf245d12014-06-30 21:05:18 +00003927 return op.GetError ();
3928}
3929
Chaoren Lin97ccc292015-02-03 01:51:12 +00003930Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003931NativeProcessLinux::ReadRegisterValue(lldb::tid_t tid, uint32_t offset, const char* reg_name,
Tamas Berghammer1e209fc2015-03-13 11:36:47 +00003932 uint32_t size, RegisterValue &value)
Todd Fialaaf245d12014-06-30 21:05:18 +00003933{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003934 ReadRegOperation op(tid, offset, reg_name, value);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003935 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003936 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003937}
3938
Chaoren Lin97ccc292015-02-03 01:51:12 +00003939Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003940NativeProcessLinux::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
3941 const char* reg_name, const RegisterValue &value)
3942{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003943 WriteRegOperation op(tid, offset, reg_name, value);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003944 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003945 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003946}
3947
Chaoren Lin97ccc292015-02-03 01:51:12 +00003948Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003949NativeProcessLinux::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3950{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003951 ReadGPROperation op(tid, buf, buf_size);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003952 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003953 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003954}
3955
Chaoren Lin97ccc292015-02-03 01:51:12 +00003956Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003957NativeProcessLinux::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3958{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003959 ReadFPROperation op(tid, buf, buf_size);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003960 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003961 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003962}
3963
Chaoren Lin97ccc292015-02-03 01:51:12 +00003964Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003965NativeProcessLinux::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3966{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003967 ReadRegisterSetOperation op(tid, buf, buf_size, regset);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003968 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003969 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003970}
3971
Chaoren Lin97ccc292015-02-03 01:51:12 +00003972Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003973NativeProcessLinux::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size)
3974{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003975 WriteGPROperation op(tid, buf, buf_size);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003976 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003977 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003978}
3979
Chaoren Lin97ccc292015-02-03 01:51:12 +00003980Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003981NativeProcessLinux::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size)
3982{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003983 WriteFPROperation op(tid, buf, buf_size);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003984 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003985 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003986}
3987
Chaoren Lin97ccc292015-02-03 01:51:12 +00003988Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003989NativeProcessLinux::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
3990{
Chaoren Lin97ccc292015-02-03 01:51:12 +00003991 WriteRegisterSetOperation op(tid, buf, buf_size, regset);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00003992 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00003993 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00003994}
3995
Chaoren Lin97ccc292015-02-03 01:51:12 +00003996Error
Todd Fialaaf245d12014-06-30 21:05:18 +00003997NativeProcessLinux::Resume (lldb::tid_t tid, uint32_t signo)
3998{
Todd Fialaaf245d12014-06-30 21:05:18 +00003999 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4000
4001 if (log)
4002 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid,
4003 GetUnixSignals().GetSignalAsCString (signo));
Chaoren Lin97ccc292015-02-03 01:51:12 +00004004 ResumeOperation op (tid, signo);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00004005 m_monitor_up->DoOperation (&op);
Todd Fialaaf245d12014-06-30 21:05:18 +00004006 if (log)
Chaoren Lin97ccc292015-02-03 01:51:12 +00004007 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " result = %s", __FUNCTION__, tid, op.GetError().Success() ? "true" : "false");
4008 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00004009}
4010
Chaoren Lin97ccc292015-02-03 01:51:12 +00004011Error
Todd Fialaaf245d12014-06-30 21:05:18 +00004012NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo)
4013{
Chaoren Lin97ccc292015-02-03 01:51:12 +00004014 SingleStepOperation op(tid, signo);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00004015 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00004016 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00004017}
4018
Chaoren Lin97ccc292015-02-03 01:51:12 +00004019Error
4020NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
Todd Fialaaf245d12014-06-30 21:05:18 +00004021{
Chaoren Lin97ccc292015-02-03 01:51:12 +00004022 SiginfoOperation op(tid, siginfo);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00004023 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00004024 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00004025}
4026
Chaoren Lin97ccc292015-02-03 01:51:12 +00004027Error
Todd Fialaaf245d12014-06-30 21:05:18 +00004028NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
4029{
Chaoren Lin97ccc292015-02-03 01:51:12 +00004030 EventMessageOperation op(tid, message);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00004031 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00004032 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00004033}
4034
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004035Error
Todd Fialaaf245d12014-06-30 21:05:18 +00004036NativeProcessLinux::Detach(lldb::tid_t tid)
4037{
Chaoren Lin97ccc292015-02-03 01:51:12 +00004038 if (tid == LLDB_INVALID_THREAD_ID)
4039 return Error();
4040
4041 DetachOperation op(tid);
Pavel Labathbd7cbc52015-04-20 13:53:49 +00004042 m_monitor_up->DoOperation(&op);
Chaoren Lin97ccc292015-02-03 01:51:12 +00004043 return op.GetError();
Todd Fialaaf245d12014-06-30 21:05:18 +00004044}
4045
4046bool
4047NativeProcessLinux::DupDescriptor(const char *path, int fd, int flags)
4048{
4049 int target_fd = open(path, flags, 0666);
4050
4051 if (target_fd == -1)
4052 return false;
4053
Pavel Labath493c3a12015-02-04 10:36:57 +00004054 if (dup2(target_fd, fd) == -1)
4055 return false;
4056
4057 return (close(target_fd) == -1) ? false : true;
Todd Fialaaf245d12014-06-30 21:05:18 +00004058}
4059
4060void
Pavel Labathbd7cbc52015-04-20 13:53:49 +00004061NativeProcessLinux::StartMonitorThread(const InitialOperation &initial_operation, Error &error)
Todd Fialaaf245d12014-06-30 21:05:18 +00004062{
Pavel Labathbd7cbc52015-04-20 13:53:49 +00004063 m_monitor_up.reset(new Monitor(initial_operation, this));
Pavel Labath1107b5a2015-04-17 14:07:49 +00004064 error = m_monitor_up->Initialize();
4065 if (error.Fail()) {
4066 m_monitor_up.reset();
Todd Fialaaf245d12014-06-30 21:05:18 +00004067 }
4068}
4069
Todd Fialaaf245d12014-06-30 21:05:18 +00004070bool
4071NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
4072{
4073 for (auto thread_sp : m_threads)
4074 {
4075 assert (thread_sp && "thread list should not contain NULL threads");
4076 if (thread_sp->GetID () == thread_id)
4077 {
4078 // We have this thread.
4079 return true;
4080 }
4081 }
4082
4083 // We don't have this thread.
4084 return false;
4085}
4086
4087NativeThreadProtocolSP
4088NativeProcessLinux::MaybeGetThreadNoLock (lldb::tid_t thread_id)
4089{
4090 // CONSIDER organize threads by map - we can do better than linear.
4091 for (auto thread_sp : m_threads)
4092 {
4093 if (thread_sp->GetID () == thread_id)
4094 return thread_sp;
4095 }
4096
4097 // We don't have this thread.
4098 return NativeThreadProtocolSP ();
4099}
4100
4101bool
4102NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
4103{
4104 Mutex::Locker locker (m_threads_mutex);
4105 for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
4106 {
4107 if (*it && ((*it)->GetID () == thread_id))
4108 {
4109 m_threads.erase (it);
4110 return true;
4111 }
4112 }
4113
4114 // Didn't find it.
4115 return false;
4116}
4117
4118NativeThreadProtocolSP
4119NativeProcessLinux::AddThread (lldb::tid_t thread_id)
4120{
4121 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
4122
4123 Mutex::Locker locker (m_threads_mutex);
4124
4125 if (log)
4126 {
4127 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
4128 __FUNCTION__,
4129 GetID (),
4130 thread_id);
4131 }
4132
4133 assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
4134
4135 // If this is the first thread, save it as the current thread
4136 if (m_threads.empty ())
4137 SetCurrentThreadID (thread_id);
4138
4139 NativeThreadProtocolSP thread_sp (new NativeThreadLinux (this, thread_id));
4140 m_threads.push_back (thread_sp);
4141
4142 return thread_sp;
4143}
4144
Todd Fialaaf245d12014-06-30 21:05:18 +00004145Error
4146NativeProcessLinux::FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp)
4147{
Todd Fiala75f47c32014-10-11 21:42:09 +00004148 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Todd Fialaaf245d12014-06-30 21:05:18 +00004149
4150 Error error;
4151
4152 // Get a linux thread pointer.
4153 if (!thread_sp)
4154 {
4155 error.SetErrorString ("null thread_sp");
4156 if (log)
4157 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
4158 return error;
4159 }
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00004160 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp);
Todd Fialaaf245d12014-06-30 21:05:18 +00004161
4162 // Find out the size of a breakpoint (might depend on where we are in the code).
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00004163 NativeRegisterContextSP context_sp = linux_thread_sp->GetRegisterContext ();
Todd Fialaaf245d12014-06-30 21:05:18 +00004164 if (!context_sp)
4165 {
4166 error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
4167 if (log)
4168 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
4169 return error;
4170 }
4171
4172 uint32_t breakpoint_size = 0;
Tamas Berghammer63c8be92015-04-15 09:38:48 +00004173 error = GetSoftwareBreakpointPCOffset (context_sp, breakpoint_size);
Todd Fialaaf245d12014-06-30 21:05:18 +00004174 if (error.Fail ())
4175 {
4176 if (log)
4177 log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
4178 return error;
4179 }
4180 else
4181 {
4182 if (log)
4183 log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
4184 }
4185
4186 // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
4187 const lldb::addr_t initial_pc_addr = context_sp->GetPC ();
4188 lldb::addr_t breakpoint_addr = initial_pc_addr;
Chaoren Lin3eb4b452015-04-29 17:24:48 +00004189 if (breakpoint_size > 0)
Todd Fialaaf245d12014-06-30 21:05:18 +00004190 {
4191 // Do not allow breakpoint probe to wrap around.
Chaoren Lin3eb4b452015-04-29 17:24:48 +00004192 if (breakpoint_addr >= breakpoint_size)
4193 breakpoint_addr -= breakpoint_size;
Todd Fialaaf245d12014-06-30 21:05:18 +00004194 }
4195
4196 // Check if we stopped because of a breakpoint.
4197 NativeBreakpointSP breakpoint_sp;
4198 error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
4199 if (!error.Success () || !breakpoint_sp)
4200 {
4201 // We didn't find one at a software probe location. Nothing to do.
4202 if (log)
4203 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
4204 return Error ();
4205 }
4206
4207 // If the breakpoint is not a software breakpoint, nothing to do.
4208 if (!breakpoint_sp->IsSoftwareBreakpoint ())
4209 {
4210 if (log)
4211 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
4212 return Error ();
4213 }
4214
4215 //
4216 // We have a software breakpoint and need to adjust the PC.
4217 //
4218
4219 // Sanity check.
4220 if (breakpoint_size == 0)
4221 {
4222 // Nothing to do! How did we get here?
4223 if (log)
4224 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);
4225 return Error ();
4226 }
4227
4228 // Change the program counter.
4229 if (log)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00004230 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 +00004231
4232 error = context_sp->SetPC (breakpoint_addr);
4233 if (error.Fail ())
4234 {
4235 if (log)
Tamas Berghammercb84eeb2015-03-17 15:05:31 +00004236 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 +00004237 return error;
4238 }
4239
4240 return error;
4241}
Chaoren Linfa03ad22015-02-03 01:50:42 +00004242
4243void
4244NativeProcessLinux::NotifyThreadCreateStopped (lldb::tid_t tid)
4245{
4246 const bool is_stopped = true;
Pavel Labathc0765592015-05-06 10:46:34 +00004247 NotifyThreadCreate (tid, is_stopped, CoordinatorErrorHandler);
Chaoren Linfa03ad22015-02-03 01:50:42 +00004248}
4249
4250void
4251NativeProcessLinux::NotifyThreadDeath (lldb::tid_t tid)
4252{
Pavel Labathc0765592015-05-06 10:46:34 +00004253 NotifyThreadDeath (tid, CoordinatorErrorHandler);
Chaoren Linfa03ad22015-02-03 01:50:42 +00004254}
4255
4256void
4257NativeProcessLinux::NotifyThreadStop (lldb::tid_t tid)
4258{
Pavel Labathc0765592015-05-06 10:46:34 +00004259 NotifyThreadStop (tid, false, CoordinatorErrorHandler);
Chaoren Linfa03ad22015-02-03 01:50:42 +00004260}
4261
4262void
4263NativeProcessLinux::CallAfterRunningThreadsStop (lldb::tid_t tid,
4264 const std::function<void (lldb::tid_t tid)> &call_after_function)
4265{
Chaoren Lin86fd8e42015-02-03 01:51:15 +00004266 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
4267 if (log)
4268 log->Printf("NativeProcessLinux::%s tid %" PRIu64, __FUNCTION__, tid);
4269
Chaoren Linfa03ad22015-02-03 01:50:42 +00004270 const lldb::pid_t pid = GetID ();
Pavel Labathc0765592015-05-06 10:46:34 +00004271 CallAfterRunningThreadsStop (tid,
Chaoren Linfa03ad22015-02-03 01:50:42 +00004272 [=](lldb::tid_t request_stop_tid)
4273 {
Chaoren Lin37c768c2015-02-03 01:51:30 +00004274 return RequestThreadStop(pid, request_stop_tid);
Chaoren Linfa03ad22015-02-03 01:50:42 +00004275 },
4276 call_after_function,
4277 CoordinatorErrorHandler);
Chaoren Lin03f12d62015-02-03 01:50:49 +00004278}
Chaoren Linfa03ad22015-02-03 01:50:42 +00004279
Chaoren Lin03f12d62015-02-03 01:50:49 +00004280void
4281NativeProcessLinux::CallAfterRunningThreadsStopWithSkipTID (lldb::tid_t deferred_signal_tid,
4282 lldb::tid_t skip_stop_request_tid,
4283 const std::function<void (lldb::tid_t tid)> &call_after_function)
4284{
Chaoren Lin86fd8e42015-02-03 01:51:15 +00004285 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
4286 if (log)
4287 log->Printf("NativeProcessLinux::%s deferred_signal_tid %" PRIu64 ", skip_stop_request_tid %" PRIu64, __FUNCTION__, deferred_signal_tid, skip_stop_request_tid);
4288
Chaoren Lin03f12d62015-02-03 01:50:49 +00004289 const lldb::pid_t pid = GetID ();
Pavel Labathc0765592015-05-06 10:46:34 +00004290 CallAfterRunningThreadsStopWithSkipTIDs (deferred_signal_tid,
4291 skip_stop_request_tid != LLDB_INVALID_THREAD_ID ? NativeProcessLinux::ThreadIDSet {skip_stop_request_tid} : NativeProcessLinux::ThreadIDSet (),
4292 [=](lldb::tid_t request_stop_tid) { return RequestThreadStop(pid, request_stop_tid); },
4293 call_after_function,
4294 CoordinatorErrorHandler);
Chaoren Linfa03ad22015-02-03 01:50:42 +00004295}
Chaoren Lin86fd8e42015-02-03 01:51:15 +00004296
Tamas Berghammerdb264a62015-03-31 09:52:22 +00004297Error
Chaoren Lin86fd8e42015-02-03 01:51:15 +00004298NativeProcessLinux::RequestThreadStop (const lldb::pid_t pid, const lldb::tid_t tid)
4299{
4300 Log* log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
4301 if (log)
4302 log->Printf ("NativeProcessLinux::%s requesting thread stop(pid: %" PRIu64 ", tid: %" PRIu64 ")", __FUNCTION__, pid, tid);
4303
4304 Error err;
4305 errno = 0;
4306 if (::tgkill (pid, tid, SIGSTOP) != 0)
4307 {
4308 err.SetErrorToErrno ();
4309 if (log)
4310 log->Printf ("NativeProcessLinux::%s tgkill(%" PRIu64 ", %" PRIu64 ", SIGSTOP) failed: %s", __FUNCTION__, pid, tid, err.AsCString ());
4311 }
4312
4313 return err;
4314}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00004315
4316Error
4317NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec)
4318{
4319 char maps_file_name[32];
4320 snprintf(maps_file_name, sizeof(maps_file_name), "/proc/%" PRIu64 "/maps", GetID());
4321
4322 FileSpec maps_file_spec(maps_file_name, false);
4323 if (!maps_file_spec.Exists()) {
4324 file_spec.Clear();
4325 return Error("/proc/%" PRIu64 "/maps file doesn't exists!", GetID());
4326 }
4327
4328 FileSpec module_file_spec(module_path, true);
4329
4330 std::ifstream maps_file(maps_file_name);
4331 std::string maps_data_str((std::istreambuf_iterator<char>(maps_file)), std::istreambuf_iterator<char>());
4332 StringRef maps_data(maps_data_str.c_str());
4333
4334 while (!maps_data.empty())
4335 {
4336 StringRef maps_row;
4337 std::tie(maps_row, maps_data) = maps_data.split('\n');
4338
4339 SmallVector<StringRef, 16> maps_columns;
4340 maps_row.split(maps_columns, StringRef(" "), -1, false);
4341
4342 if (maps_columns.size() >= 6)
4343 {
4344 file_spec.SetFile(maps_columns[5].str().c_str(), false);
4345 if (file_spec.GetFilename() == module_file_spec.GetFilename())
4346 return Error();
4347 }
4348 }
4349
4350 file_spec.Clear();
4351 return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
4352 module_file_spec.GetFilename().AsCString(), GetID());
4353}
Pavel Labathc0765592015-05-06 10:46:34 +00004354
4355void
4356NativeProcessLinux::DoResume(
4357 lldb::tid_t tid,
4358 ResumeThreadFunction request_thread_resume_function,
4359 ErrorFunction error_function,
4360 bool error_when_already_running)
4361{
4362 // Ensure we know about the thread.
4363 auto find_it = m_tid_map.find (tid);
4364 if (find_it == m_tid_map.end ())
4365 {
4366 // We don't know about this thread. This is an error condition.
4367 std::ostringstream error_message;
4368 error_message << "error: tid " << tid << " asked to resume but tid is unknown";
4369 error_function (error_message.str ());
4370 return;
4371 }
4372 auto& context = find_it->second;
4373 // Tell the thread to resume if we don't already think it is running.
4374 const bool is_stopped = context.m_state == ThreadState::Stopped;
4375 if (!is_stopped)
4376 {
4377 // It's not an error, just a log, if the error_when_already_running flag is not set.
4378 // This covers cases where, for instance, we're just trying to resume all threads
4379 // from the user side.
4380 if (!error_when_already_running)
4381 {
4382 TSCLog ("NativeProcessLinux::%s tid %" PRIu64 " optional resume skipped since it is already running",
4383 __FUNCTION__,
4384 tid);
4385 }
4386 else
4387 {
4388 // Skip the resume call - we have tracked it to be running. And we unconditionally
4389 // expected to resume this thread. Flag this as an error.
4390 std::ostringstream error_message;
4391 error_message << "error: tid " << tid << " asked to resume but we think it is already running";
4392 error_function (error_message.str ());
4393 }
4394
4395 // Error or not, we're done.
4396 return;
4397 }
4398
4399 // Before we do the resume below, first check if we have a pending
4400 // stop notification this is currently or was previously waiting for
4401 // this thread to stop. This is potentially a buggy situation since
4402 // we're ostensibly waiting for threads to stop before we send out the
4403 // pending notification, and here we are resuming one before we send
4404 // out the pending stop notification.
4405 if (m_pending_notification_up)
4406 {
4407 if (m_pending_notification_up->wait_for_stop_tids.count (tid) > 0)
4408 {
4409 TSCLog ("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);
4410 }
4411 else if (m_pending_notification_up->original_wait_for_stop_tids.count (tid) > 0)
4412 {
4413 TSCLog ("NativeProcessLinux::%s about to resume tid %" PRIu64 " per explicit request but we have a pending stop notification (tid %" PRIu64 ") that hasn't fired yet and this is one of the threads we had been waiting on (and already marked satisfied for this tid). Valid sequence of events?", __FUNCTION__, tid, m_pending_notification_up->triggering_tid);
4414 for (auto tid : m_pending_notification_up->wait_for_stop_tids)
4415 {
4416 TSCLog ("NativeProcessLinux::%s tid %" PRIu64 " deferred stop notification still waiting on tid %" PRIu64,
4417 __FUNCTION__,
4418 m_pending_notification_up->triggering_tid,
4419 tid);
4420 }
4421 }
4422 }
4423
4424 // Request a resume. We expect this to be synchronous and the system
4425 // to reflect it is running after this completes.
4426 const auto error = request_thread_resume_function (tid, false);
4427 if (error.Success ())
4428 {
4429 // Now mark it is running.
4430 context.m_state = ThreadState::Running;
4431 context.m_request_resume_function = request_thread_resume_function;
4432 }
4433 else
4434 {
4435 TSCLog ("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s",
4436 __FUNCTION__, tid, error.AsCString ());
4437 }
4438
4439 return;
4440}
4441
4442//===----------------------------------------------------------------------===//
4443
4444void
4445NativeProcessLinux::CallAfterThreadsStop (const lldb::tid_t triggering_tid,
4446 const ThreadIDSet &wait_for_stop_tids,
4447 const StopThreadFunction &request_thread_stop_function,
4448 const ThreadIDFunction &call_after_function,
4449 const ErrorFunction &error_function)
4450{
4451 std::lock_guard<std::mutex> lock(m_event_mutex);
4452
4453 if (m_log_event_processing)
4454 {
4455 TSCLog ("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ", wait_for_stop_tids.size(): %zd)",
4456 __FUNCTION__, triggering_tid, wait_for_stop_tids.size());
4457 }
4458
4459 DoCallAfterThreadsStop(PendingNotificationUP(new PendingNotification(
4460 triggering_tid, wait_for_stop_tids, request_thread_stop_function,
4461 call_after_function, error_function)));
4462
4463 if (m_log_event_processing)
4464 {
4465 TSCLog ("NativeProcessLinux::%s event processing done", __FUNCTION__);
4466 }
4467}
4468
4469void
4470NativeProcessLinux::CallAfterRunningThreadsStop (const lldb::tid_t triggering_tid,
4471 const StopThreadFunction &request_thread_stop_function,
4472 const ThreadIDFunction &call_after_function,
4473 const ErrorFunction &error_function)
4474{
4475 std::lock_guard<std::mutex> lock(m_event_mutex);
4476
4477 if (m_log_event_processing)
4478 {
4479 TSCLog ("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ")",
4480 __FUNCTION__, triggering_tid);
4481 }
4482
4483 DoCallAfterThreadsStop(PendingNotificationUP(new PendingNotification(
4484 triggering_tid,
4485 request_thread_stop_function,
4486 call_after_function,
4487 error_function)));
4488
4489 if (m_log_event_processing)
4490 {
4491 TSCLog ("NativeProcessLinux::%s event processing done", __FUNCTION__);
4492 }
4493}
4494
4495void
4496NativeProcessLinux::CallAfterRunningThreadsStopWithSkipTIDs (lldb::tid_t triggering_tid,
4497 const ThreadIDSet &skip_stop_request_tids,
4498 const StopThreadFunction &request_thread_stop_function,
4499 const ThreadIDFunction &call_after_function,
4500 const ErrorFunction &error_function)
4501{
4502 std::lock_guard<std::mutex> lock(m_event_mutex);
4503
4504 if (m_log_event_processing)
4505 {
4506 TSCLog ("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ", skip_stop_request_tids.size(): %zd)",
4507 __FUNCTION__, triggering_tid, skip_stop_request_tids.size());
4508 }
4509
4510 DoCallAfterThreadsStop(PendingNotificationUP(new PendingNotification(
4511 triggering_tid,
4512 request_thread_stop_function,
4513 call_after_function,
4514 skip_stop_request_tids,
4515 error_function)));
4516
4517 if (m_log_event_processing)
4518 {
4519 TSCLog ("NativeProcessLinux::%s event processing done", __FUNCTION__);
4520 }
4521}
4522
4523void
4524NativeProcessLinux::SignalIfRequirementsSatisfied()
4525{
4526 if (m_pending_notification_up && m_pending_notification_up->wait_for_stop_tids.empty ())
4527 {
4528 m_pending_notification_up->call_after_function(m_pending_notification_up->triggering_tid);
4529 m_pending_notification_up.reset();
4530 }
4531}
4532
4533bool
4534NativeProcessLinux::RequestStopOnAllSpecifiedThreads()
4535{
4536 // Request a stop for all the thread stops that need to be stopped
4537 // and are not already known to be stopped. Keep a list of all the
4538 // threads from which we still need to hear a stop reply.
4539
4540 ThreadIDSet sent_tids;
4541 for (auto tid : m_pending_notification_up->wait_for_stop_tids)
4542 {
4543 // Validate we know about all tids for which we must first receive a stop before
4544 // triggering the deferred stop notification.
4545 auto find_it = m_tid_map.find (tid);
4546 if (find_it == m_tid_map.end ())
4547 {
4548 // This is an error. We shouldn't be asking for waiting pids that aren't known.
4549 // NOTE: we may be stripping out the specification of wait tids and handle this
4550 // automatically, in which case this state can never occur.
4551 std::ostringstream error_message;
4552 error_message << "error: deferred notification for tid " << m_pending_notification_up->triggering_tid << " specified an unknown/untracked pending stop tid " << m_pending_notification_up->triggering_tid;
4553 m_pending_notification_up->error_function (error_message.str ());
4554
4555 // Bail out here.
4556 return false;
4557 }
4558
4559 // If the pending stop thread is currently running, we need to send it a stop request.
4560 auto& context = find_it->second;
4561 if (context.m_state == ThreadState::Running)
4562 {
4563 RequestThreadStop (tid, context);
4564 sent_tids.insert (tid);
4565 }
4566 }
4567 // We only need to wait for the sent_tids - so swap our wait set
4568 // to the sent tids. The rest are already stopped and we won't
4569 // be receiving stop notifications for them.
4570 m_pending_notification_up->wait_for_stop_tids.swap (sent_tids);
4571
4572 // Succeeded, keep running.
4573 return true;
4574}
4575
4576void
4577NativeProcessLinux::RequestStopOnAllRunningThreads()
4578{
4579 // Request a stop for all the thread stops that need to be stopped
4580 // and are not already known to be stopped. Keep a list of all the
4581 // threads from which we still need to hear a stop reply.
4582
4583 ThreadIDSet sent_tids;
4584 for (auto it = m_tid_map.begin(); it != m_tid_map.end(); ++it)
4585 {
4586 // We only care about threads not stopped.
4587 const bool running = it->second.m_state == ThreadState::Running;
4588 if (running)
4589 {
4590 const lldb::tid_t tid = it->first;
4591
4592 // Request this thread stop if the tid stop request is not explicitly ignored.
4593 const bool skip_stop_request = m_pending_notification_up->skip_stop_request_tids.count (tid) > 0;
4594 if (!skip_stop_request)
4595 RequestThreadStop (tid, it->second);
4596
4597 // Even if we skipped sending the stop request for other reasons (like stepping),
4598 // we still need to wait for that stepping thread to notify completion/stop.
4599 sent_tids.insert (tid);
4600 }
4601 }
4602
4603 // Set the wait list to the set of tids for which we requested stops.
4604 m_pending_notification_up->wait_for_stop_tids.swap (sent_tids);
4605}
4606
4607void
4608NativeProcessLinux::RequestThreadStop (lldb::tid_t tid, ThreadContext& context)
4609{
4610 const auto error = m_pending_notification_up->request_thread_stop_function (tid);
4611 if (error.Success ())
4612 context.m_stop_requested = true;
4613 else
4614 {
4615 TSCLog ("NativeProcessLinux::%s failed to request thread stop tid %" PRIu64 ": %s",
4616 __FUNCTION__, tid, error.AsCString ());
4617 }
4618}
4619
4620
4621void
4622NativeProcessLinux::ThreadDidStop (lldb::tid_t tid, bool initiated_by_llgs, const ErrorFunction &error_function)
4623{
4624 // Ensure we know about the thread.
4625 auto find_it = m_tid_map.find (tid);
4626 if (find_it == m_tid_map.end ())
4627 {
4628 // We don't know about this thread. This is an error condition.
4629 std::ostringstream error_message;
4630 error_message << "error: tid " << tid << " asked to stop but tid is unknown";
4631 error_function (error_message.str ());
4632 return;
4633 }
4634
4635 // Update the global list of known thread states. This one is definitely stopped.
4636 auto& context = find_it->second;
4637 const auto stop_was_requested = context.m_stop_requested;
4638 context.m_state = ThreadState::Stopped;
4639 context.m_stop_requested = false;
4640
4641 // If we have a pending notification, remove this from the set.
4642 if (m_pending_notification_up)
4643 {
4644 m_pending_notification_up->wait_for_stop_tids.erase(tid);
4645 SignalIfRequirementsSatisfied();
4646 }
4647
4648 if (initiated_by_llgs && context.m_request_resume_function && !stop_was_requested)
4649 {
4650 // We can end up here if stop was initiated by LLGS but by this time a
4651 // thread stop has occurred - maybe initiated by another event.
4652 TSCLog ("Resuming thread %" PRIu64 " since stop wasn't requested", tid);
4653 const auto error = context.m_request_resume_function (tid, true);
4654 if (error.Success ())
4655 {
4656 context.m_state = ThreadState::Running;
4657 }
4658 else
4659 {
4660 TSCLog ("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s",
4661 __FUNCTION__, tid, error.AsCString ());
4662 }
4663 }
4664}
4665
4666void
4667NativeProcessLinux::DoCallAfterThreadsStop(PendingNotificationUP &&notification_up)
4668{
4669 // Validate we know about the deferred trigger thread.
4670 if (!IsKnownThread (notification_up->triggering_tid))
4671 {
4672 // We don't know about this thread. This is an error condition.
4673 std::ostringstream error_message;
4674 error_message << "error: deferred notification tid " << notification_up->triggering_tid << " is unknown";
4675 notification_up->error_function (error_message.str ());
4676
4677 // We bail out here.
4678 return;
4679 }
4680
4681 if (m_pending_notification_up)
4682 {
4683 // Yikes - we've already got a pending signal notification in progress.
4684 // Log this info. We lose the pending notification here.
4685 TSCLog ("NativeProcessLinux::%s dropping existing pending signal notification for tid %" PRIu64 ", to be replaced with signal for tid %" PRIu64,
4686 __FUNCTION__,
4687 m_pending_notification_up->triggering_tid,
4688 notification_up->triggering_tid);
4689 }
4690 m_pending_notification_up = std::move(notification_up);
4691
4692 if (m_pending_notification_up->request_stop_on_all_unstopped_threads)
4693 RequestStopOnAllRunningThreads();
4694 else
4695 {
4696 if (!RequestStopOnAllSpecifiedThreads())
4697 return;
4698 }
4699
4700 if (m_pending_notification_up->wait_for_stop_tids.empty ())
4701 {
4702 // We're not waiting for any threads. Fire off the deferred signal delivery event.
4703 m_pending_notification_up->call_after_function(m_pending_notification_up->triggering_tid);
4704 m_pending_notification_up.reset();
4705 }
4706}
4707
4708void
4709NativeProcessLinux::ThreadWasCreated (lldb::tid_t tid, bool is_stopped, const ErrorFunction &error_function)
4710{
4711 // Ensure we don't already know about the thread.
4712 auto find_it = m_tid_map.find (tid);
4713 if (find_it != m_tid_map.end ())
4714 {
4715 // We already know about this thread. This is an error condition.
4716 std::ostringstream error_message;
4717 error_message << "error: notified tid " << tid << " created but we already know about this thread";
4718 error_function (error_message.str ());
4719 return;
4720 }
4721
4722 // Add the new thread to the stop map.
4723 ThreadContext ctx;
4724 ctx.m_state = (is_stopped) ? ThreadState::Stopped : ThreadState::Running;
4725 m_tid_map[tid] = std::move(ctx);
4726
4727 if (m_pending_notification_up && !is_stopped)
4728 {
4729 // We will need to wait for this new thread to stop as well before firing the
4730 // notification.
4731 m_pending_notification_up->wait_for_stop_tids.insert(tid);
4732 m_pending_notification_up->request_thread_stop_function(tid);
4733 }
4734}
4735
4736void
4737NativeProcessLinux::ThreadDidDie (lldb::tid_t tid, const ErrorFunction &error_function)
4738{
4739 // Ensure we know about the thread.
4740 auto find_it = m_tid_map.find (tid);
4741 if (find_it == m_tid_map.end ())
4742 {
4743 // We don't know about this thread. This is an error condition.
4744 std::ostringstream error_message;
4745 error_message << "error: notified tid " << tid << " died but tid is unknown";
4746 error_function (error_message.str ());
4747 return;
4748 }
4749
4750 // Update the global list of known thread states. While this one is stopped, it is also dead.
4751 // So stop tracking it. We assume the user of this coordinator will not keep trying to add
4752 // dependencies on a thread after it is known to be dead.
4753 m_tid_map.erase (find_it);
4754
4755 // If we have a pending notification, remove this from the set.
4756 if (m_pending_notification_up)
4757 {
4758 m_pending_notification_up->wait_for_stop_tids.erase(tid);
4759 SignalIfRequirementsSatisfied();
4760 }
4761}
4762
4763void
4764NativeProcessLinux::TSCLog (const char *format, ...)
4765{
4766 va_list args;
4767 va_start (args, format);
4768
4769 m_log_function (format, args);
4770
4771 va_end (args);
4772}
4773
4774void
4775NativeProcessLinux::NotifyThreadStop (lldb::tid_t tid,
4776 bool initiated_by_llgs,
4777 const ErrorFunction &error_function)
4778{
4779 std::lock_guard<std::mutex> lock(m_event_mutex);
4780
4781 if (m_log_event_processing)
4782 {
4783 TSCLog ("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ", %sinitiated by llgs)",
4784 __FUNCTION__, tid, initiated_by_llgs?"":"not ");
4785 }
4786
4787 ThreadDidStop (tid, initiated_by_llgs, error_function);
4788
4789 if (m_log_event_processing)
4790 {
4791 TSCLog ("NativeProcessLinux::%s event processing done", __FUNCTION__);
4792 }
4793}
4794
4795void
4796NativeProcessLinux::RequestThreadResume (lldb::tid_t tid,
4797 const ResumeThreadFunction &request_thread_resume_function,
4798 const ErrorFunction &error_function)
4799{
4800 std::lock_guard<std::mutex> lock(m_event_mutex);
4801
4802 if (m_log_event_processing)
4803 {
4804 TSCLog ("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ")",
4805 __FUNCTION__, tid);
4806 }
4807
4808 DoResume(tid, request_thread_resume_function, error_function, true);
4809
4810 if (m_log_event_processing)
4811 {
4812 TSCLog ("NativeProcessLinux::%s event processing done", __FUNCTION__);
4813 }
4814}
4815
4816void
4817NativeProcessLinux::RequestThreadResumeAsNeeded (lldb::tid_t tid,
4818 const ResumeThreadFunction &request_thread_resume_function,
4819 const ErrorFunction &error_function)
4820{
4821 std::lock_guard<std::mutex> lock(m_event_mutex);
4822
4823 if (m_log_event_processing)
4824 {
4825 TSCLog ("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ")",
4826 __FUNCTION__, tid);
4827 }
4828
4829 DoResume (tid, request_thread_resume_function, error_function, false);
4830
4831 if (m_log_event_processing)
4832 {
4833 TSCLog ("NativeProcessLinux::%s event processing done", __FUNCTION__);
4834 }
4835}
4836
4837void
4838NativeProcessLinux::NotifyThreadCreate (lldb::tid_t tid,
4839 bool is_stopped,
4840 const ErrorFunction &error_function)
4841{
4842 std::lock_guard<std::mutex> lock(m_event_mutex);
4843
4844 if (m_log_event_processing)
4845 {
4846 TSCLog ("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ", is %sstopped)",
4847 __FUNCTION__, tid, is_stopped?"":"not ");
4848 }
4849
4850 ThreadWasCreated (tid, is_stopped, error_function);
4851
4852 if (m_log_event_processing)
4853 {
4854 TSCLog ("NativeProcessLinux::%s event processing done", __FUNCTION__);
4855 }
4856}
4857
4858void
4859NativeProcessLinux::NotifyThreadDeath (lldb::tid_t tid,
4860 const ErrorFunction &error_function)
4861{
4862 std::lock_guard<std::mutex> lock(m_event_mutex);
4863
4864 if (m_log_event_processing)
4865 {
4866 TSCLog ("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ")", __FUNCTION__, tid);
4867 }
4868
4869 ThreadDidDie(tid, error_function);
4870
4871 if (m_log_event_processing)
4872 {
4873 TSCLog ("NativeProcessLinux::%s event processing done", __FUNCTION__);
4874 }
4875}
4876
4877void
4878NativeProcessLinux::ResetForExec ()
4879{
4880 std::lock_guard<std::mutex> lock(m_event_mutex);
4881
4882 if (m_log_event_processing)
4883 {
4884 TSCLog ("NativeProcessLinux::%s about to process event", __FUNCTION__);
4885 }
4886
4887 // Clear the pending notification if there was one.
4888 m_pending_notification_up.reset ();
4889
4890 // Clear the stop map - we no longer know anything about any thread state.
4891 // The caller is expected to reset thread states for all threads, and we
4892 // will assume anything we haven't heard about is running and requires a
4893 // stop.
4894 m_tid_map.clear ();
4895
4896 if (m_log_event_processing)
4897 {
4898 TSCLog ("NativeProcessLinux::%s event processing done", __FUNCTION__);
4899 }
4900}
4901void
4902NativeProcessLinux::LogEnableEventProcessing (bool enabled)
4903{
4904 m_log_event_processing = enabled;
4905}
4906
4907bool
4908NativeProcessLinux::IsKnownThread (lldb::tid_t tid) const
4909{
4910 return m_tid_map.find (tid) != m_tid_map.end ();
4911}