blob: a0cda3485c6636c3f162738e65a6abb4a4c929b1 [file] [log] [blame]
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001//===-- ProcessMonitor.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
Daniel Malea93a64302012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
11
Stephen Wilsone6f9f662010-07-24 02:19:04 +000012// C Includes
13#include <errno.h>
14#include <poll.h>
15#include <string.h>
Daniel Maleaa85e6b62012-12-07 22:21:08 +000016#include <stdint.h>
Stephen Wilsone6f9f662010-07-24 02:19:04 +000017#include <unistd.h>
18#include <sys/ptrace.h>
19#include <sys/socket.h>
Andrew Kaylor93132f52013-05-28 23:04:25 +000020#include <sys/syscall.h>
Stephen Wilsone6f9f662010-07-24 02:19:04 +000021#include <sys/types.h>
22#include <sys/wait.h>
23
24// C++ Includes
25// Other libraries and framework includes
Johnny Chen0d5f2d42011-10-18 18:09:30 +000026#include "lldb/Core/Debugger.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000027#include "lldb/Core/Error.h"
Johnny Chen13e8e1c2011-05-13 21:29:50 +000028#include "lldb/Core/RegisterValue.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000029#include "lldb/Core/Scalar.h"
30#include "lldb/Host/Host.h"
31#include "lldb/Target/Thread.h"
32#include "lldb/Target/RegisterContext.h"
33#include "lldb/Utility/PseudoTerminal.h"
34
Johnny Chen30213ff2012-01-05 19:17:38 +000035#include "POSIXThread.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000036#include "ProcessLinux.h"
Johnny Chen30213ff2012-01-05 19:17:38 +000037#include "ProcessPOSIXLog.h"
Stephen Wilsone6f9f662010-07-24 02:19:04 +000038#include "ProcessMonitor.h"
39
Greg Clayton386ff182011-11-05 01:09:16 +000040#define DEBUG_PTRACE_MAXBYTES 20
41
Matt Kopec58c0b962013-03-20 20:34:35 +000042// Support ptrace extensions even when compiled without required kernel support
43#ifndef PTRACE_GETREGSET
44 #define PTRACE_GETREGSET 0x4204
45#endif
46#ifndef PTRACE_SETREGSET
47 #define PTRACE_SETREGSET 0x4205
48#endif
49
Matt Kopece9ea0da2013-05-07 19:29:28 +000050// Support hardware breakpoints in case it has not been defined
51#ifndef TRAP_HWBKPT
52 #define TRAP_HWBKPT 4
53#endif
54
Andrew Kaylor93132f52013-05-28 23:04:25 +000055// Try to define a macro to encapsulate the tgkill syscall
56// fall back on kill() if tgkill isn't available
57#define tgkill(pid, tid, sig) syscall(SYS_tgkill, pid, tid, sig)
58
Stephen Wilsone6f9f662010-07-24 02:19:04 +000059using namespace lldb_private;
60
Johnny Chen0d5f2d42011-10-18 18:09:30 +000061// FIXME: this code is host-dependent with respect to types and
62// endianness and needs to be fixed. For example, lldb::addr_t is
63// hard-coded to uint64_t, but on a 32-bit Linux host, ptrace requires
64// 32-bit pointer arguments. This code uses casts to work around the
65// problem.
66
67// We disable the tracing of ptrace calls for integration builds to
68// avoid the additional indirection and checks.
69#ifndef LLDB_CONFIGURATION_BUILDANDINTEGRATION
70
Greg Clayton386ff182011-11-05 01:09:16 +000071static void
72DisplayBytes (lldb_private::StreamString &s, void *bytes, uint32_t count)
73{
74 uint8_t *ptr = (uint8_t *)bytes;
75 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
76 for(uint32_t i=0; i<loop_count; i++)
77 {
78 s.Printf ("[%x]", *ptr);
79 ptr++;
80 }
81}
82
Matt Kopec58c0b962013-03-20 20:34:35 +000083static void PtraceDisplayBytes(int &req, void *data, size_t data_size)
Greg Clayton386ff182011-11-05 01:09:16 +000084{
85 StreamString buf;
Ashok Thirumurthi01186352013-03-28 16:02:31 +000086 Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
Johnny Chen30213ff2012-01-05 19:17:38 +000087 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
Greg Clayton386ff182011-11-05 01:09:16 +000088
89 if (verbose_log)
90 {
91 switch(req)
92 {
93 case PTRACE_POKETEXT:
94 {
95 DisplayBytes(buf, &data, 8);
96 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
97 break;
98 }
Greg Clayton542e4072012-09-07 17:49:29 +000099 case PTRACE_POKEDATA:
Greg Clayton386ff182011-11-05 01:09:16 +0000100 {
101 DisplayBytes(buf, &data, 8);
102 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
103 break;
104 }
Greg Clayton542e4072012-09-07 17:49:29 +0000105 case PTRACE_POKEUSER:
Greg Clayton386ff182011-11-05 01:09:16 +0000106 {
107 DisplayBytes(buf, &data, 8);
108 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
109 break;
110 }
Greg Clayton542e4072012-09-07 17:49:29 +0000111 case PTRACE_SETREGS:
Greg Clayton386ff182011-11-05 01:09:16 +0000112 {
Matt Kopec7de48462013-03-06 17:20:48 +0000113 DisplayBytes(buf, data, data_size);
Greg Clayton386ff182011-11-05 01:09:16 +0000114 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
115 break;
116 }
117 case PTRACE_SETFPREGS:
118 {
Matt Kopec7de48462013-03-06 17:20:48 +0000119 DisplayBytes(buf, data, data_size);
Greg Clayton386ff182011-11-05 01:09:16 +0000120 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
121 break;
122 }
Greg Clayton542e4072012-09-07 17:49:29 +0000123 case PTRACE_SETSIGINFO:
Greg Clayton386ff182011-11-05 01:09:16 +0000124 {
125 DisplayBytes(buf, data, sizeof(siginfo_t));
126 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
127 break;
128 }
Matt Kopec58c0b962013-03-20 20:34:35 +0000129 case PTRACE_SETREGSET:
130 {
131 // Extract iov_base from data, which is a pointer to the struct IOVEC
132 DisplayBytes(buf, *(void **)data, data_size);
133 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
134 break;
135 }
Greg Clayton386ff182011-11-05 01:09:16 +0000136 default:
137 {
138 }
139 }
140 }
141}
142
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000143// Wrapper for ptrace to catch errors and log calls.
Ashok Thirumurthi762fbd02013-03-27 21:09:30 +0000144// Note that ptrace sets errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000145extern long
Matt Kopec58c0b962013-03-20 20:34:35 +0000146PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size,
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000147 const char* reqName, const char* file, int line)
148{
Greg Clayton386ff182011-11-05 01:09:16 +0000149 long int result;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000150
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000151 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
Greg Clayton386ff182011-11-05 01:09:16 +0000152
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000153 if (log)
Matt Kopec58c0b962013-03-20 20:34:35 +0000154 log->Printf("ptrace(%s, %lu, %p, %p, %zu) called from file %s line %d",
Matt Kopec7de48462013-03-06 17:20:48 +0000155 reqName, pid, addr, data, data_size, file, line);
Greg Clayton542e4072012-09-07 17:49:29 +0000156
Matt Kopec7de48462013-03-06 17:20:48 +0000157 PtraceDisplayBytes(req, data, data_size);
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000158
159 errno = 0;
Matt Kopec58c0b962013-03-20 20:34:35 +0000160 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
161 result = ptrace(static_cast<__ptrace_request>(req), pid, *(unsigned int *)addr, data);
162 else
163 result = ptrace(static_cast<__ptrace_request>(req), pid, addr, data);
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000164
Matt Kopec7de48462013-03-06 17:20:48 +0000165 PtraceDisplayBytes(req, data, data_size);
Greg Clayton386ff182011-11-05 01:09:16 +0000166
Matt Kopec7de48462013-03-06 17:20:48 +0000167 if (log && errno != 0)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000168 {
169 const char* str;
170 switch (errno)
171 {
172 case ESRCH: str = "ESRCH"; break;
173 case EINVAL: str = "EINVAL"; break;
174 case EBUSY: str = "EBUSY"; break;
175 case EPERM: str = "EPERM"; break;
176 default: str = "<unknown>";
177 }
178 log->Printf("ptrace() failed; errno=%d (%s)", errno, str);
179 }
180
181 return result;
182}
183
Matt Kopec7de48462013-03-06 17:20:48 +0000184// Wrapper for ptrace when logging is not required.
185// Sets errno to 0 prior to calling ptrace.
186extern long
Matt Kopec58c0b962013-03-20 20:34:35 +0000187PtraceWrapper(int req, pid_t pid, void *addr, void *data, size_t data_size)
Matt Kopec7de48462013-03-06 17:20:48 +0000188{
Matt Kopec58c0b962013-03-20 20:34:35 +0000189 long result = 0;
Matt Kopec7de48462013-03-06 17:20:48 +0000190 errno = 0;
Matt Kopec58c0b962013-03-20 20:34:35 +0000191 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
192 result = ptrace(static_cast<__ptrace_request>(req), pid, *(unsigned int *)addr, data);
193 else
194 result = ptrace(static_cast<__ptrace_request>(req), pid, addr, data);
Matt Kopec7de48462013-03-06 17:20:48 +0000195 return result;
196}
197
198#define PTRACE(req, pid, addr, data, data_size) \
199 PtraceWrapper((req), (pid), (addr), (data), (data_size), #req, __FILE__, __LINE__)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000200#else
Matt Kopec7de48462013-03-06 17:20:48 +0000201 PtraceWrapper((req), (pid), (addr), (data), (data_size))
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000202#endif
203
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000204//------------------------------------------------------------------------------
205// Static implementations of ProcessMonitor::ReadMemory and
206// ProcessMonitor::WriteMemory. This enables mutual recursion between these
207// functions without needed to go thru the thread funnel.
208
209static size_t
Greg Clayton542e4072012-09-07 17:49:29 +0000210DoReadMemory(lldb::pid_t pid,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000211 lldb::addr_t vm_addr, void *buf, size_t size, Error &error)
212{
Greg Clayton542e4072012-09-07 17:49:29 +0000213 // ptrace word size is determined by the host, not the child
214 static const unsigned word_size = sizeof(void*);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000215 unsigned char *dst = static_cast<unsigned char*>(buf);
216 size_t bytes_read;
217 size_t remainder;
218 long data;
219
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000220 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000221 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000222 ProcessPOSIXLog::IncNestLevel();
223 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
Daniel Malead01b2952012-11-29 21:49:15 +0000224 log->Printf ("ProcessMonitor::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000225 pid, word_size, (void*)vm_addr, buf, size);
226
227 assert(sizeof(data) >= word_size);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000228 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
229 {
230 errno = 0;
Matt Kopec7de48462013-03-06 17:20:48 +0000231 data = PTRACE(PTRACE_PEEKDATA, pid, (void*)vm_addr, NULL, 0);
232 if (errno)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000233 {
234 error.SetErrorToErrno();
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000235 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000236 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000237 return bytes_read;
238 }
239
240 remainder = size - bytes_read;
241 remainder = remainder > word_size ? word_size : remainder;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000242
243 // Copy the data into our buffer
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000244 for (unsigned i = 0; i < remainder; ++i)
245 dst[i] = ((data >> i*8) & 0xFF);
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000246
Johnny Chen30213ff2012-01-05 19:17:38 +0000247 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
248 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
249 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
250 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
Daniel Maleac63dddd2012-12-14 21:07:07 +0000251 {
252 uintptr_t print_dst = 0;
253 // Format bytes from data by moving into print_dst for log output
254 for (unsigned i = 0; i < remainder; ++i)
255 print_dst |= (((data >> i*8) & 0xFF) << i*8);
256 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
257 (void*)vm_addr, print_dst, (unsigned long)data);
258 }
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000259
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000260 vm_addr += word_size;
261 dst += word_size;
262 }
263
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000264 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000265 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000266 return bytes_read;
267}
268
269static size_t
Greg Clayton542e4072012-09-07 17:49:29 +0000270DoWriteMemory(lldb::pid_t pid,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000271 lldb::addr_t vm_addr, const void *buf, size_t size, Error &error)
272{
Greg Clayton542e4072012-09-07 17:49:29 +0000273 // ptrace word size is determined by the host, not the child
274 static const unsigned word_size = sizeof(void*);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000275 const unsigned char *src = static_cast<const unsigned char*>(buf);
276 size_t bytes_written = 0;
277 size_t remainder;
278
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000279 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000280 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000281 ProcessPOSIXLog::IncNestLevel();
282 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
Daniel Malead01b2952012-11-29 21:49:15 +0000283 log->Printf ("ProcessMonitor::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000284 pid, word_size, (void*)vm_addr, buf, size);
285
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000286 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
287 {
288 remainder = size - bytes_written;
289 remainder = remainder > word_size ? word_size : remainder;
290
291 if (remainder == word_size)
292 {
293 unsigned long data = 0;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000294 assert(sizeof(data) >= word_size);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000295 for (unsigned i = 0; i < word_size; ++i)
296 data |= (unsigned long)src[i] << i*8;
297
Johnny Chen30213ff2012-01-05 19:17:38 +0000298 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
299 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
300 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
301 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000302 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
303 (void*)vm_addr, *(unsigned long*)src, data);
304
Matt Kopec7de48462013-03-06 17:20:48 +0000305 if (PTRACE(PTRACE_POKEDATA, pid, (void*)vm_addr, (void*)data, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000306 {
307 error.SetErrorToErrno();
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000308 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000309 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000310 return bytes_written;
311 }
312 }
313 else
314 {
315 unsigned char buff[8];
Greg Clayton542e4072012-09-07 17:49:29 +0000316 if (DoReadMemory(pid, vm_addr,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000317 buff, word_size, error) != word_size)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000318 {
319 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000320 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000321 return bytes_written;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000322 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000323
324 memcpy(buff, src, remainder);
325
Greg Clayton542e4072012-09-07 17:49:29 +0000326 if (DoWriteMemory(pid, vm_addr,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000327 buff, word_size, error) != word_size)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000328 {
329 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000330 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000331 return bytes_written;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000332 }
333
Johnny Chen30213ff2012-01-05 19:17:38 +0000334 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
335 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
336 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
337 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000338 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
339 (void*)vm_addr, *(unsigned long*)src, *(unsigned long*)buff);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000340 }
341
342 vm_addr += word_size;
343 src += word_size;
344 }
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000345 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000346 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000347 return bytes_written;
348}
349
Stephen Wilson26977162011-03-23 02:14:42 +0000350// Simple helper function to ensure flags are enabled on the given file
351// descriptor.
352static bool
353EnsureFDFlags(int fd, int flags, Error &error)
354{
355 int status;
356
357 if ((status = fcntl(fd, F_GETFL)) == -1)
358 {
359 error.SetErrorToErrno();
360 return false;
361 }
362
363 if (fcntl(fd, F_SETFL, status | flags) == -1)
364 {
365 error.SetErrorToErrno();
366 return false;
367 }
368
369 return true;
370}
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000371
372//------------------------------------------------------------------------------
373/// @class Operation
374/// @brief Represents a ProcessMonitor operation.
375///
376/// Under Linux, it is not possible to ptrace() from any other thread but the
377/// one that spawned or attached to the process from the start. Therefore, when
378/// a ProcessMonitor is asked to deliver or change the state of an inferior
379/// process the operation must be "funneled" to a specific thread to perform the
380/// task. The Operation class provides an abstract base for all services the
381/// ProcessMonitor must perform via the single virtual function Execute, thus
382/// encapsulating the code that needs to run in the privileged context.
383class Operation
384{
385public:
Daniel Maleadd15b782013-05-13 17:32:07 +0000386 virtual ~Operation() {}
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000387 virtual void Execute(ProcessMonitor *monitor) = 0;
388};
389
390//------------------------------------------------------------------------------
391/// @class ReadOperation
392/// @brief Implements ProcessMonitor::ReadMemory.
393class ReadOperation : public Operation
394{
395public:
396 ReadOperation(lldb::addr_t addr, void *buff, size_t size,
397 Error &error, size_t &result)
398 : m_addr(addr), m_buff(buff), m_size(size),
399 m_error(error), m_result(result)
400 { }
401
402 void Execute(ProcessMonitor *monitor);
403
404private:
405 lldb::addr_t m_addr;
406 void *m_buff;
407 size_t m_size;
408 Error &m_error;
409 size_t &m_result;
410};
411
412void
413ReadOperation::Execute(ProcessMonitor *monitor)
414{
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000415 lldb::pid_t pid = monitor->GetPID();
416
Greg Clayton542e4072012-09-07 17:49:29 +0000417 m_result = DoReadMemory(pid, m_addr, m_buff, m_size, m_error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000418}
419
420//------------------------------------------------------------------------------
Ed Mastea56115f2013-07-17 14:30:26 +0000421/// @class WriteOperation
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000422/// @brief Implements ProcessMonitor::WriteMemory.
423class WriteOperation : public Operation
424{
425public:
426 WriteOperation(lldb::addr_t addr, const void *buff, size_t size,
427 Error &error, size_t &result)
428 : m_addr(addr), m_buff(buff), m_size(size),
429 m_error(error), m_result(result)
430 { }
431
432 void Execute(ProcessMonitor *monitor);
433
434private:
435 lldb::addr_t m_addr;
436 const void *m_buff;
437 size_t m_size;
438 Error &m_error;
439 size_t &m_result;
440};
441
442void
443WriteOperation::Execute(ProcessMonitor *monitor)
444{
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000445 lldb::pid_t pid = monitor->GetPID();
446
Greg Clayton542e4072012-09-07 17:49:29 +0000447 m_result = DoWriteMemory(pid, m_addr, m_buff, m_size, m_error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000448}
449
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000450
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000451//------------------------------------------------------------------------------
452/// @class ReadRegOperation
453/// @brief Implements ProcessMonitor::ReadRegisterValue.
454class ReadRegOperation : public Operation
455{
456public:
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000457 ReadRegOperation(lldb::tid_t tid, unsigned offset, const char *reg_name,
Daniel Maleaf0da3712012-12-18 19:50:15 +0000458 RegisterValue &value, bool &result)
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000459 : m_tid(tid), m_offset(offset), m_reg_name(reg_name),
Daniel Maleaf0da3712012-12-18 19:50:15 +0000460 m_value(value), m_result(result)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000461 { }
462
463 void Execute(ProcessMonitor *monitor);
464
465private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000466 lldb::tid_t m_tid;
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000467 uintptr_t m_offset;
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000468 const char *m_reg_name;
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000469 RegisterValue &m_value;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000470 bool &m_result;
471};
472
473void
474ReadRegOperation::Execute(ProcessMonitor *monitor)
475{
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000476 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000477
478 // Set errno to zero so that we can detect a failed peek.
479 errno = 0;
Matt Kopec7de48462013-03-06 17:20:48 +0000480 lldb::addr_t data = PTRACE(PTRACE_PEEKUSER, m_tid, (void*)m_offset, NULL, 0);
481 if (errno)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000482 m_result = false;
483 else
484 {
485 m_value = data;
486 m_result = true;
487 }
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000488 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000489 log->Printf ("ProcessMonitor::%s() reg %s: 0x%" PRIx64, __FUNCTION__,
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000490 m_reg_name, data);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000491}
492
493//------------------------------------------------------------------------------
494/// @class WriteRegOperation
495/// @brief Implements ProcessMonitor::WriteRegisterValue.
496class WriteRegOperation : public Operation
497{
498public:
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000499 WriteRegOperation(lldb::tid_t tid, unsigned offset, const char *reg_name,
Daniel Maleaf0da3712012-12-18 19:50:15 +0000500 const RegisterValue &value, bool &result)
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000501 : m_tid(tid), m_offset(offset), m_reg_name(reg_name),
Daniel Maleaf0da3712012-12-18 19:50:15 +0000502 m_value(value), m_result(result)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000503 { }
504
505 void Execute(ProcessMonitor *monitor);
506
507private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000508 lldb::tid_t m_tid;
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000509 uintptr_t m_offset;
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000510 const char *m_reg_name;
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000511 const RegisterValue &m_value;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000512 bool &m_result;
513};
514
515void
516WriteRegOperation::Execute(ProcessMonitor *monitor)
517{
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000518 void* buf;
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000519 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000520
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000521#if __WORDSIZE == 32
522 buf = (void*) m_value.GetAsUInt32();
523#else
524 buf = (void*) m_value.GetAsUInt64();
525#endif
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000526
527 if (log)
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000528 log->Printf ("ProcessMonitor::%s() reg %s: %p", __FUNCTION__, m_reg_name, buf);
Matt Kopec7de48462013-03-06 17:20:48 +0000529 if (PTRACE(PTRACE_POKEUSER, m_tid, (void*)m_offset, buf, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000530 m_result = false;
531 else
532 m_result = true;
533}
534
535//------------------------------------------------------------------------------
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000536/// @class ReadGPROperation
537/// @brief Implements ProcessMonitor::ReadGPR.
538class ReadGPROperation : public Operation
539{
540public:
Matt Kopec7de48462013-03-06 17:20:48 +0000541 ReadGPROperation(lldb::tid_t tid, void *buf, size_t buf_size, bool &result)
542 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_result(result)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000543 { }
544
545 void Execute(ProcessMonitor *monitor);
546
547private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000548 lldb::tid_t m_tid;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000549 void *m_buf;
Matt Kopec7de48462013-03-06 17:20:48 +0000550 size_t m_buf_size;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000551 bool &m_result;
552};
553
554void
555ReadGPROperation::Execute(ProcessMonitor *monitor)
556{
Matt Kopec7de48462013-03-06 17:20:48 +0000557 if (PTRACE(PTRACE_GETREGS, m_tid, NULL, m_buf, m_buf_size) < 0)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000558 m_result = false;
559 else
560 m_result = true;
561}
562
563//------------------------------------------------------------------------------
564/// @class ReadFPROperation
565/// @brief Implements ProcessMonitor::ReadFPR.
566class ReadFPROperation : public Operation
567{
568public:
Matt Kopec7de48462013-03-06 17:20:48 +0000569 ReadFPROperation(lldb::tid_t tid, void *buf, size_t buf_size, bool &result)
570 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_result(result)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000571 { }
572
573 void Execute(ProcessMonitor *monitor);
574
575private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000576 lldb::tid_t m_tid;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000577 void *m_buf;
Matt Kopec7de48462013-03-06 17:20:48 +0000578 size_t m_buf_size;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000579 bool &m_result;
580};
581
582void
583ReadFPROperation::Execute(ProcessMonitor *monitor)
584{
Matt Kopec7de48462013-03-06 17:20:48 +0000585 if (PTRACE(PTRACE_GETFPREGS, m_tid, NULL, m_buf, m_buf_size) < 0)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000586 m_result = false;
587 else
588 m_result = true;
589}
590
591//------------------------------------------------------------------------------
Matt Kopec58c0b962013-03-20 20:34:35 +0000592/// @class ReadRegisterSetOperation
593/// @brief Implements ProcessMonitor::ReadRegisterSet.
594class ReadRegisterSetOperation : public Operation
595{
596public:
597 ReadRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset, bool &result)
598 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset), m_result(result)
599 { }
600
601 void Execute(ProcessMonitor *monitor);
602
603private:
604 lldb::tid_t m_tid;
605 void *m_buf;
606 size_t m_buf_size;
607 const unsigned int m_regset;
608 bool &m_result;
609};
610
611void
612ReadRegisterSetOperation::Execute(ProcessMonitor *monitor)
613{
614 if (PTRACE(PTRACE_GETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size) < 0)
615 m_result = false;
616 else
617 m_result = true;
618}
619
620//------------------------------------------------------------------------------
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000621/// @class WriteGPROperation
622/// @brief Implements ProcessMonitor::WriteGPR.
623class WriteGPROperation : public Operation
624{
625public:
Matt Kopec7de48462013-03-06 17:20:48 +0000626 WriteGPROperation(lldb::tid_t tid, void *buf, size_t buf_size, bool &result)
627 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_result(result)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000628 { }
629
630 void Execute(ProcessMonitor *monitor);
631
632private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000633 lldb::tid_t m_tid;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000634 void *m_buf;
Matt Kopec7de48462013-03-06 17:20:48 +0000635 size_t m_buf_size;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000636 bool &m_result;
637};
638
639void
640WriteGPROperation::Execute(ProcessMonitor *monitor)
641{
Matt Kopec7de48462013-03-06 17:20:48 +0000642 if (PTRACE(PTRACE_SETREGS, m_tid, NULL, m_buf, m_buf_size) < 0)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000643 m_result = false;
644 else
645 m_result = true;
646}
647
648//------------------------------------------------------------------------------
649/// @class WriteFPROperation
650/// @brief Implements ProcessMonitor::WriteFPR.
651class WriteFPROperation : public Operation
652{
653public:
Matt Kopec7de48462013-03-06 17:20:48 +0000654 WriteFPROperation(lldb::tid_t tid, void *buf, size_t buf_size, bool &result)
655 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_result(result)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000656 { }
657
658 void Execute(ProcessMonitor *monitor);
659
660private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000661 lldb::tid_t m_tid;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000662 void *m_buf;
Matt Kopec7de48462013-03-06 17:20:48 +0000663 size_t m_buf_size;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000664 bool &m_result;
665};
666
667void
668WriteFPROperation::Execute(ProcessMonitor *monitor)
669{
Matt Kopec7de48462013-03-06 17:20:48 +0000670 if (PTRACE(PTRACE_SETFPREGS, m_tid, NULL, m_buf, m_buf_size) < 0)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000671 m_result = false;
672 else
673 m_result = true;
674}
675
676//------------------------------------------------------------------------------
Matt Kopec58c0b962013-03-20 20:34:35 +0000677/// @class WriteRegisterSetOperation
678/// @brief Implements ProcessMonitor::WriteRegisterSet.
679class WriteRegisterSetOperation : public Operation
680{
681public:
682 WriteRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset, bool &result)
683 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset), m_result(result)
684 { }
685
686 void Execute(ProcessMonitor *monitor);
687
688private:
689 lldb::tid_t m_tid;
690 void *m_buf;
691 size_t m_buf_size;
692 const unsigned int m_regset;
693 bool &m_result;
694};
695
696void
697WriteRegisterSetOperation::Execute(ProcessMonitor *monitor)
698{
699 if (PTRACE(PTRACE_SETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size) < 0)
700 m_result = false;
701 else
702 m_result = true;
703}
704
705//------------------------------------------------------------------------------
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000706/// @class ResumeOperation
707/// @brief Implements ProcessMonitor::Resume.
708class ResumeOperation : public Operation
709{
710public:
Stephen Wilson84ffe702011-03-30 15:55:52 +0000711 ResumeOperation(lldb::tid_t tid, uint32_t signo, bool &result) :
712 m_tid(tid), m_signo(signo), m_result(result) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000713
714 void Execute(ProcessMonitor *monitor);
715
716private:
717 lldb::tid_t m_tid;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000718 uint32_t m_signo;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000719 bool &m_result;
720};
721
722void
723ResumeOperation::Execute(ProcessMonitor *monitor)
724{
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000725 intptr_t data = 0;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000726
727 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
728 data = m_signo;
729
Matt Kopec7de48462013-03-06 17:20:48 +0000730 if (PTRACE(PTRACE_CONT, m_tid, NULL, (void*)data, 0))
Andrew Kaylor93132f52013-05-28 23:04:25 +0000731 {
732 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
733
734 if (log)
735 log->Printf ("ResumeOperation (%" PRIu64 ") failed: %s", m_tid, strerror(errno));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000736 m_result = false;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000737 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000738 else
739 m_result = true;
740}
741
742//------------------------------------------------------------------------------
Ed Maste428a6782013-06-24 15:04:47 +0000743/// @class SingleStepOperation
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000744/// @brief Implements ProcessMonitor::SingleStep.
745class SingleStepOperation : public Operation
746{
747public:
Stephen Wilson84ffe702011-03-30 15:55:52 +0000748 SingleStepOperation(lldb::tid_t tid, uint32_t signo, bool &result)
749 : m_tid(tid), m_signo(signo), m_result(result) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000750
751 void Execute(ProcessMonitor *monitor);
752
753private:
754 lldb::tid_t m_tid;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000755 uint32_t m_signo;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000756 bool &m_result;
757};
758
759void
760SingleStepOperation::Execute(ProcessMonitor *monitor)
761{
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000762 intptr_t data = 0;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000763
764 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
765 data = m_signo;
766
Matt Kopec7de48462013-03-06 17:20:48 +0000767 if (PTRACE(PTRACE_SINGLESTEP, m_tid, NULL, (void*)data, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000768 m_result = false;
769 else
770 m_result = true;
771}
772
773//------------------------------------------------------------------------------
774/// @class SiginfoOperation
775/// @brief Implements ProcessMonitor::GetSignalInfo.
776class SiginfoOperation : public Operation
777{
778public:
Daniel Maleaa35970a2012-11-23 18:09:58 +0000779 SiginfoOperation(lldb::tid_t tid, void *info, bool &result, int &ptrace_err)
780 : m_tid(tid), m_info(info), m_result(result), m_err(ptrace_err) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000781
782 void Execute(ProcessMonitor *monitor);
783
784private:
785 lldb::tid_t m_tid;
786 void *m_info;
787 bool &m_result;
Daniel Maleaa35970a2012-11-23 18:09:58 +0000788 int &m_err;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000789};
790
791void
792SiginfoOperation::Execute(ProcessMonitor *monitor)
793{
Matt Kopec7de48462013-03-06 17:20:48 +0000794 if (PTRACE(PTRACE_GETSIGINFO, m_tid, NULL, m_info, 0)) {
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000795 m_result = false;
Daniel Maleaa35970a2012-11-23 18:09:58 +0000796 m_err = errno;
797 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000798 else
799 m_result = true;
800}
801
802//------------------------------------------------------------------------------
803/// @class EventMessageOperation
804/// @brief Implements ProcessMonitor::GetEventMessage.
805class EventMessageOperation : public Operation
806{
807public:
808 EventMessageOperation(lldb::tid_t tid, unsigned long *message, bool &result)
809 : m_tid(tid), m_message(message), m_result(result) { }
810
811 void Execute(ProcessMonitor *monitor);
812
813private:
814 lldb::tid_t m_tid;
815 unsigned long *m_message;
816 bool &m_result;
817};
818
819void
820EventMessageOperation::Execute(ProcessMonitor *monitor)
821{
Matt Kopec7de48462013-03-06 17:20:48 +0000822 if (PTRACE(PTRACE_GETEVENTMSG, m_tid, NULL, m_message, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000823 m_result = false;
824 else
825 m_result = true;
826}
827
828//------------------------------------------------------------------------------
829/// @class KillOperation
830/// @brief Implements ProcessMonitor::BringProcessIntoLimbo.
831class KillOperation : public Operation
832{
833public:
834 KillOperation(bool &result) : m_result(result) { }
835
836 void Execute(ProcessMonitor *monitor);
837
838private:
839 bool &m_result;
840};
841
842void
843KillOperation::Execute(ProcessMonitor *monitor)
844{
845 lldb::pid_t pid = monitor->GetPID();
846
Matt Kopec7de48462013-03-06 17:20:48 +0000847 if (PTRACE(PTRACE_KILL, pid, NULL, NULL, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000848 m_result = false;
849 else
850 m_result = true;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000851}
852
Greg Clayton28041352011-11-29 20:50:10 +0000853//------------------------------------------------------------------------------
854/// @class KillOperation
855/// @brief Implements ProcessMonitor::BringProcessIntoLimbo.
856class DetachOperation : public Operation
857{
858public:
Matt Kopec085d6ce2013-05-31 22:00:07 +0000859 DetachOperation(lldb::tid_t tid, Error &result) : m_tid(tid), m_error(result) { }
Greg Clayton28041352011-11-29 20:50:10 +0000860
861 void Execute(ProcessMonitor *monitor);
862
863private:
Matt Kopec085d6ce2013-05-31 22:00:07 +0000864 lldb::tid_t m_tid;
Greg Clayton28041352011-11-29 20:50:10 +0000865 Error &m_error;
866};
867
868void
869DetachOperation::Execute(ProcessMonitor *monitor)
870{
Matt Kopec085d6ce2013-05-31 22:00:07 +0000871 if (ptrace(PT_DETACH, m_tid, NULL, 0) < 0)
Greg Clayton28041352011-11-29 20:50:10 +0000872 m_error.SetErrorToErrno();
Greg Clayton28041352011-11-29 20:50:10 +0000873}
874
Johnny Chen25e68e32011-06-14 19:19:50 +0000875ProcessMonitor::OperationArgs::OperationArgs(ProcessMonitor *monitor)
876 : m_monitor(monitor)
877{
878 sem_init(&m_semaphore, 0, 0);
879}
880
881ProcessMonitor::OperationArgs::~OperationArgs()
882{
883 sem_destroy(&m_semaphore);
884}
885
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000886ProcessMonitor::LaunchArgs::LaunchArgs(ProcessMonitor *monitor,
887 lldb_private::Module *module,
888 char const **argv,
889 char const **envp,
890 const char *stdin_path,
891 const char *stdout_path,
Daniel Malea6217d2a2013-01-08 14:49:22 +0000892 const char *stderr_path,
893 const char *working_dir)
Johnny Chen25e68e32011-06-14 19:19:50 +0000894 : OperationArgs(monitor),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000895 m_module(module),
896 m_argv(argv),
897 m_envp(envp),
898 m_stdin_path(stdin_path),
899 m_stdout_path(stdout_path),
Daniel Malea6217d2a2013-01-08 14:49:22 +0000900 m_stderr_path(stderr_path),
901 m_working_dir(working_dir) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000902
903ProcessMonitor::LaunchArgs::~LaunchArgs()
Johnny Chen25e68e32011-06-14 19:19:50 +0000904{ }
905
906ProcessMonitor::AttachArgs::AttachArgs(ProcessMonitor *monitor,
907 lldb::pid_t pid)
908 : OperationArgs(monitor), m_pid(pid) { }
909
910ProcessMonitor::AttachArgs::~AttachArgs()
911{ }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000912
913//------------------------------------------------------------------------------
914/// The basic design of the ProcessMonitor is built around two threads.
915///
916/// One thread (@see SignalThread) simply blocks on a call to waitpid() looking
917/// for changes in the debugee state. When a change is detected a
918/// ProcessMessage is sent to the associated ProcessLinux instance. This thread
919/// "drives" state changes in the debugger.
920///
921/// The second thread (@see OperationThread) is responsible for two things 1)
Greg Clayton710dd5a2011-01-08 20:28:42 +0000922/// launching or attaching to the inferior process, and then 2) servicing
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000923/// operations such as register reads/writes, stepping, etc. See the comments
924/// on the Operation class for more info as to why this is needed.
Andrew Kaylor6578cb62013-07-09 22:36:48 +0000925ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000926 Module *module,
927 const char *argv[],
928 const char *envp[],
929 const char *stdin_path,
930 const char *stdout_path,
931 const char *stderr_path,
Daniel Malea6217d2a2013-01-08 14:49:22 +0000932 const char *working_dir,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000933 lldb_private::Error &error)
Andrew Kaylor6578cb62013-07-09 22:36:48 +0000934 : m_process(static_cast<ProcessLinux *>(process)),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000935 m_operation_thread(LLDB_INVALID_HOST_THREAD),
Matt Kopec7de48462013-03-06 17:20:48 +0000936 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000937 m_pid(LLDB_INVALID_PROCESS_ID),
938 m_terminal_fd(-1),
Daniel Malea1efb4182013-09-16 23:12:18 +0000939 m_operation(0)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000940{
Daniel Malea1efb4182013-09-16 23:12:18 +0000941 std::unique_ptr<LaunchArgs> args(new LaunchArgs(this, module, argv, envp,
942 stdin_path, stdout_path, stderr_path,
943 working_dir));
Stephen Wilson57740ec2011-01-15 00:12:41 +0000944
Daniel Malea1efb4182013-09-16 23:12:18 +0000945 sem_init(&m_operation_pending, 0, 0);
946 sem_init(&m_operation_done, 0, 0);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000947
Johnny Chen25e68e32011-06-14 19:19:50 +0000948 StartLaunchOpThread(args.get(), error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000949 if (!error.Success())
950 return;
951
952WAIT_AGAIN:
953 // Wait for the operation thread to initialize.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000954 if (sem_wait(&args->m_semaphore))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000955 {
956 if (errno == EINTR)
957 goto WAIT_AGAIN;
958 else
959 {
960 error.SetErrorToErrno();
961 return;
962 }
963 }
964
965 // Check that the launch was a success.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000966 if (!args->m_error.Success())
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000967 {
Greg Clayton743ecf42012-10-16 20:20:18 +0000968 StopOpThread();
Stephen Wilson57740ec2011-01-15 00:12:41 +0000969 error = args->m_error;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000970 return;
971 }
972
973 // Finally, start monitoring the child process for change in state.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000974 m_monitor_thread = Host::StartMonitoringChildProcess(
975 ProcessMonitor::MonitorCallback, this, GetPID(), true);
Stephen Wilsond4182f42011-02-09 20:10:35 +0000976 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000977 {
978 error.SetErrorToGenericError();
979 error.SetErrorString("Process launch failed.");
980 return;
981 }
982}
983
Andrew Kaylor6578cb62013-07-09 22:36:48 +0000984ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
Johnny Chen25e68e32011-06-14 19:19:50 +0000985 lldb::pid_t pid,
986 lldb_private::Error &error)
Andrew Kaylor6578cb62013-07-09 22:36:48 +0000987 : m_process(static_cast<ProcessLinux *>(process)),
Johnny Chen25e68e32011-06-14 19:19:50 +0000988 m_operation_thread(LLDB_INVALID_HOST_THREAD),
Matt Kopec7de48462013-03-06 17:20:48 +0000989 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
Johnny Chen25e68e32011-06-14 19:19:50 +0000990 m_pid(LLDB_INVALID_PROCESS_ID),
991 m_terminal_fd(-1),
Daniel Malea1efb4182013-09-16 23:12:18 +0000992 m_operation(0)
Johnny Chen25e68e32011-06-14 19:19:50 +0000993{
Daniel Malea1efb4182013-09-16 23:12:18 +0000994 sem_init(&m_operation_pending, 0, 0);
995 sem_init(&m_operation_done, 0, 0);
Johnny Chen25e68e32011-06-14 19:19:50 +0000996
Daniel Malea1efb4182013-09-16 23:12:18 +0000997 std::unique_ptr<AttachArgs> args(new AttachArgs(this, pid));
Johnny Chen25e68e32011-06-14 19:19:50 +0000998
999 StartAttachOpThread(args.get(), error);
1000 if (!error.Success())
1001 return;
1002
1003WAIT_AGAIN:
1004 // Wait for the operation thread to initialize.
1005 if (sem_wait(&args->m_semaphore))
1006 {
1007 if (errno == EINTR)
1008 goto WAIT_AGAIN;
1009 else
1010 {
1011 error.SetErrorToErrno();
1012 return;
1013 }
1014 }
1015
Greg Clayton743ecf42012-10-16 20:20:18 +00001016 // Check that the attach was a success.
Johnny Chen25e68e32011-06-14 19:19:50 +00001017 if (!args->m_error.Success())
1018 {
Greg Clayton743ecf42012-10-16 20:20:18 +00001019 StopOpThread();
Johnny Chen25e68e32011-06-14 19:19:50 +00001020 error = args->m_error;
1021 return;
1022 }
1023
1024 // Finally, start monitoring the child process for change in state.
1025 m_monitor_thread = Host::StartMonitoringChildProcess(
1026 ProcessMonitor::MonitorCallback, this, GetPID(), true);
1027 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
1028 {
1029 error.SetErrorToGenericError();
1030 error.SetErrorString("Process attach failed.");
1031 return;
1032 }
1033}
1034
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001035ProcessMonitor::~ProcessMonitor()
1036{
Stephen Wilson84ffe702011-03-30 15:55:52 +00001037 StopMonitor();
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001038}
1039
1040//------------------------------------------------------------------------------
1041// Thread setup and tear down.
1042void
Johnny Chen25e68e32011-06-14 19:19:50 +00001043ProcessMonitor::StartLaunchOpThread(LaunchArgs *args, Error &error)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001044{
1045 static const char *g_thread_name = "lldb.process.linux.operation";
1046
Stephen Wilsond4182f42011-02-09 20:10:35 +00001047 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001048 return;
1049
1050 m_operation_thread =
Johnny Chen25e68e32011-06-14 19:19:50 +00001051 Host::ThreadCreate(g_thread_name, LaunchOpThread, args, &error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001052}
1053
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001054void *
Johnny Chen25e68e32011-06-14 19:19:50 +00001055ProcessMonitor::LaunchOpThread(void *arg)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001056{
1057 LaunchArgs *args = static_cast<LaunchArgs*>(arg);
1058
Peter Collingbourne4aeb47e2011-06-14 03:55:49 +00001059 if (!Launch(args)) {
1060 sem_post(&args->m_semaphore);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001061 return NULL;
Peter Collingbourne4aeb47e2011-06-14 03:55:49 +00001062 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001063
Stephen Wilson570243b2011-01-19 01:37:06 +00001064 ServeOperation(args);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001065 return NULL;
1066}
1067
1068bool
1069ProcessMonitor::Launch(LaunchArgs *args)
1070{
1071 ProcessMonitor *monitor = args->m_monitor;
1072 ProcessLinux &process = monitor->GetProcess();
1073 const char **argv = args->m_argv;
1074 const char **envp = args->m_envp;
1075 const char *stdin_path = args->m_stdin_path;
1076 const char *stdout_path = args->m_stdout_path;
1077 const char *stderr_path = args->m_stderr_path;
Daniel Malea6217d2a2013-01-08 14:49:22 +00001078 const char *working_dir = args->m_working_dir;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001079
1080 lldb_utility::PseudoTerminal terminal;
1081 const size_t err_len = 1024;
1082 char err_str[err_len];
1083 lldb::pid_t pid;
1084
1085 lldb::ThreadSP inferior;
Ashok Thirumurthi01186352013-03-28 16:02:31 +00001086 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001087
Stephen Wilson57740ec2011-01-15 00:12:41 +00001088 // Propagate the environment if one is not supplied.
1089 if (envp == NULL || envp[0] == NULL)
1090 envp = const_cast<const char **>(environ);
1091
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001092 // Pseudo terminal setup.
1093 if (!terminal.OpenFirstAvailableMaster(O_RDWR | O_NOCTTY, err_str, err_len))
1094 {
1095 args->m_error.SetErrorToGenericError();
1096 args->m_error.SetErrorString("Could not open controlling TTY.");
1097 goto FINISH;
1098 }
1099
Daniel Maleaa85e6b62012-12-07 22:21:08 +00001100 if ((pid = terminal.Fork(err_str, err_len)) == -1)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001101 {
1102 args->m_error.SetErrorToGenericError();
1103 args->m_error.SetErrorString("Process fork failed.");
1104 goto FINISH;
1105 }
1106
Peter Collingbourne6a520222011-06-14 03:55:58 +00001107 // Recognized child exit status codes.
1108 enum {
1109 ePtraceFailed = 1,
1110 eDupStdinFailed,
1111 eDupStdoutFailed,
1112 eDupStderrFailed,
Daniel Malea6217d2a2013-01-08 14:49:22 +00001113 eChdirFailed,
Sylvestre Ledru77c87c02013-09-28 15:47:38 +00001114 eExecFailed,
1115 eSetGidFailed
Peter Collingbourne6a520222011-06-14 03:55:58 +00001116 };
1117
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001118 // Child process.
1119 if (pid == 0)
1120 {
1121 // Trace this process.
Matt Kopec7de48462013-03-06 17:20:48 +00001122 if (PTRACE(PTRACE_TRACEME, 0, NULL, NULL, 0) < 0)
Peter Collingbourne6a520222011-06-14 03:55:58 +00001123 exit(ePtraceFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001124
1125 // Do not inherit setgid powers.
Sylvestre Ledru77c87c02013-09-28 15:47:38 +00001126 if (setgid(getgid()) != 0)
1127 exit(eSetGidFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001128
1129 // Let us have our own process group.
1130 setpgid(0, 0);
1131
Greg Clayton710dd5a2011-01-08 20:28:42 +00001132 // Dup file descriptors if needed.
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001133 //
1134 // FIXME: If two or more of the paths are the same we needlessly open
1135 // the same file multiple times.
1136 if (stdin_path != NULL && stdin_path[0])
Peter Collingbourne62343202011-06-14 03:55:54 +00001137 if (!DupDescriptor(stdin_path, STDIN_FILENO, O_RDONLY))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001138 exit(eDupStdinFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001139
1140 if (stdout_path != NULL && stdout_path[0])
1141 if (!DupDescriptor(stdout_path, STDOUT_FILENO, O_WRONLY | O_CREAT))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001142 exit(eDupStdoutFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001143
1144 if (stderr_path != NULL && stderr_path[0])
Peter Collingbourne62343202011-06-14 03:55:54 +00001145 if (!DupDescriptor(stderr_path, STDERR_FILENO, O_WRONLY | O_CREAT))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001146 exit(eDupStderrFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001147
Daniel Malea6217d2a2013-01-08 14:49:22 +00001148 // Change working directory
1149 if (working_dir != NULL && working_dir[0])
1150 if (0 != ::chdir(working_dir))
1151 exit(eChdirFailed);
1152
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001153 // Execute. We should never return.
1154 execve(argv[0],
1155 const_cast<char *const *>(argv),
1156 const_cast<char *const *>(envp));
Peter Collingbourne6a520222011-06-14 03:55:58 +00001157 exit(eExecFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001158 }
1159
1160 // Wait for the child process to to trap on its call to execve.
Peter Collingbourne6a520222011-06-14 03:55:58 +00001161 pid_t wpid;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001162 int status;
Peter Collingbourne6a520222011-06-14 03:55:58 +00001163 if ((wpid = waitpid(pid, &status, 0)) < 0)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001164 {
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001165 args->m_error.SetErrorToErrno();
1166 goto FINISH;
1167 }
Peter Collingbourne6a520222011-06-14 03:55:58 +00001168 else if (WIFEXITED(status))
1169 {
1170 // open, dup or execve likely failed for some reason.
1171 args->m_error.SetErrorToGenericError();
1172 switch (WEXITSTATUS(status))
1173 {
Greg Clayton542e4072012-09-07 17:49:29 +00001174 case ePtraceFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001175 args->m_error.SetErrorString("Child ptrace failed.");
1176 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001177 case eDupStdinFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001178 args->m_error.SetErrorString("Child open stdin failed.");
1179 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001180 case eDupStdoutFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001181 args->m_error.SetErrorString("Child open stdout failed.");
1182 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001183 case eDupStderrFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001184 args->m_error.SetErrorString("Child open stderr failed.");
1185 break;
Daniel Malea6217d2a2013-01-08 14:49:22 +00001186 case eChdirFailed:
1187 args->m_error.SetErrorString("Child failed to set working directory.");
1188 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001189 case eExecFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001190 args->m_error.SetErrorString("Child exec failed.");
1191 break;
Sylvestre Ledru77c87c02013-09-28 15:47:38 +00001192 case eSetGidFailed:
1193 args->m_error.SetErrorString("Child setgid failed.");
1194 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001195 default:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001196 args->m_error.SetErrorString("Child returned unknown exit status.");
1197 break;
1198 }
1199 goto FINISH;
1200 }
1201 assert(WIFSTOPPED(status) && wpid == pid &&
1202 "Could not sync with inferior process.");
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001203
Matt Kopec085d6ce2013-05-31 22:00:07 +00001204 if (!SetDefaultPtraceOpts(pid))
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001205 {
1206 args->m_error.SetErrorToErrno();
1207 goto FINISH;
1208 }
1209
1210 // Release the master terminal descriptor and pass it off to the
1211 // ProcessMonitor instance. Similarly stash the inferior pid.
1212 monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1213 monitor->m_pid = pid;
1214
Stephen Wilson26977162011-03-23 02:14:42 +00001215 // Set the terminal fd to be in non blocking mode (it simplifies the
1216 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1217 // descriptor to read from).
1218 if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error))
1219 goto FINISH;
1220
Johnny Chen30213ff2012-01-05 19:17:38 +00001221 // Update the process thread list with this new thread.
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001222 // FIXME: should we be letting UpdateThreadList handle this?
1223 // FIXME: by using pids instead of tids, we can only support one thread.
Michael Sartain9f822cd2013-07-31 23:27:46 +00001224 inferior.reset(process.CreateNewPOSIXThread(process, pid));
Matt Kopecfb6ab542013-07-10 20:53:11 +00001225
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001226 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001227 log->Printf ("ProcessMonitor::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001228 process.GetThreadList().AddThread(inferior);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001229
Matt Kopecb2910442013-07-09 15:09:45 +00001230 process.AddThreadForInitialStopIfNeeded(pid);
1231
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001232 // Let our process instance know the thread has stopped.
1233 process.SendMessage(ProcessMessage::Trace(pid));
1234
1235FINISH:
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001236 return args->m_error.Success();
1237}
1238
Johnny Chen25e68e32011-06-14 19:19:50 +00001239void
1240ProcessMonitor::StartAttachOpThread(AttachArgs *args, lldb_private::Error &error)
1241{
1242 static const char *g_thread_name = "lldb.process.linux.operation";
1243
1244 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
1245 return;
1246
1247 m_operation_thread =
1248 Host::ThreadCreate(g_thread_name, AttachOpThread, args, &error);
1249}
1250
Johnny Chen25e68e32011-06-14 19:19:50 +00001251void *
1252ProcessMonitor::AttachOpThread(void *arg)
1253{
1254 AttachArgs *args = static_cast<AttachArgs*>(arg);
1255
Greg Clayton743ecf42012-10-16 20:20:18 +00001256 if (!Attach(args)) {
1257 sem_post(&args->m_semaphore);
Johnny Chen25e68e32011-06-14 19:19:50 +00001258 return NULL;
Greg Clayton743ecf42012-10-16 20:20:18 +00001259 }
Johnny Chen25e68e32011-06-14 19:19:50 +00001260
1261 ServeOperation(args);
1262 return NULL;
1263}
1264
1265bool
1266ProcessMonitor::Attach(AttachArgs *args)
1267{
1268 lldb::pid_t pid = args->m_pid;
1269
1270 ProcessMonitor *monitor = args->m_monitor;
1271 ProcessLinux &process = monitor->GetProcess();
Johnny Chen25e68e32011-06-14 19:19:50 +00001272 lldb::ThreadSP inferior;
Ashok Thirumurthi01186352013-03-28 16:02:31 +00001273 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
Johnny Chen25e68e32011-06-14 19:19:50 +00001274
Matt Kopec085d6ce2013-05-31 22:00:07 +00001275 // Use a map to keep track of the threads which we have attached/need to attach.
1276 Host::TidMap tids_to_attach;
Johnny Chen25e68e32011-06-14 19:19:50 +00001277 if (pid <= 1)
1278 {
1279 args->m_error.SetErrorToGenericError();
1280 args->m_error.SetErrorString("Attaching to process 1 is not allowed.");
1281 goto FINISH;
1282 }
1283
Matt Kopec085d6ce2013-05-31 22:00:07 +00001284 while (Host::FindProcessThreads(pid, tids_to_attach))
Johnny Chen25e68e32011-06-14 19:19:50 +00001285 {
Matt Kopec085d6ce2013-05-31 22:00:07 +00001286 for (Host::TidMap::iterator it = tids_to_attach.begin();
1287 it != tids_to_attach.end(); ++it)
1288 {
1289 if (it->second == false)
1290 {
1291 lldb::tid_t tid = it->first;
1292
1293 // Attach to the requested process.
1294 // An attach will cause the thread to stop with a SIGSTOP.
1295 if (PTRACE(PTRACE_ATTACH, tid, NULL, NULL, 0) < 0)
1296 {
1297 // No such thread. The thread may have exited.
1298 // More error handling may be needed.
1299 if (errno == ESRCH)
1300 {
1301 tids_to_attach.erase(it);
1302 continue;
1303 }
1304 else
1305 {
1306 args->m_error.SetErrorToErrno();
1307 goto FINISH;
1308 }
1309 }
1310
1311 int status;
1312 // Need to use __WALL otherwise we receive an error with errno=ECHLD
1313 // At this point we should have a thread stopped if waitpid succeeds.
1314 if ((status = waitpid(tid, NULL, __WALL)) < 0)
1315 {
1316 // No such thread. The thread may have exited.
1317 // More error handling may be needed.
1318 if (errno == ESRCH)
1319 {
1320 tids_to_attach.erase(it);
1321 continue;
1322 }
1323 else
1324 {
1325 args->m_error.SetErrorToErrno();
1326 goto FINISH;
1327 }
1328 }
1329
1330 if (!SetDefaultPtraceOpts(tid))
1331 {
1332 args->m_error.SetErrorToErrno();
1333 goto FINISH;
1334 }
1335
1336 // Update the process thread list with the attached thread.
Michael Sartain9f822cd2013-07-31 23:27:46 +00001337 inferior.reset(process.CreateNewPOSIXThread(process, tid));
Matt Kopecfb6ab542013-07-10 20:53:11 +00001338
Matt Kopec085d6ce2013-05-31 22:00:07 +00001339 if (log)
1340 log->Printf ("ProcessMonitor::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
1341 process.GetThreadList().AddThread(inferior);
1342 it->second = true;
Matt Kopecb2910442013-07-09 15:09:45 +00001343 process.AddThreadForInitialStopIfNeeded(tid);
Matt Kopec085d6ce2013-05-31 22:00:07 +00001344 }
1345 }
Johnny Chen25e68e32011-06-14 19:19:50 +00001346 }
1347
Matt Kopec085d6ce2013-05-31 22:00:07 +00001348 if (tids_to_attach.size() > 0)
Johnny Chen25e68e32011-06-14 19:19:50 +00001349 {
Matt Kopec085d6ce2013-05-31 22:00:07 +00001350 monitor->m_pid = pid;
1351 // Let our process instance know the thread has stopped.
1352 process.SendMessage(ProcessMessage::Trace(pid));
Johnny Chen25e68e32011-06-14 19:19:50 +00001353 }
Matt Kopec085d6ce2013-05-31 22:00:07 +00001354 else
1355 {
1356 args->m_error.SetErrorToGenericError();
1357 args->m_error.SetErrorString("No such process.");
1358 }
Johnny Chen25e68e32011-06-14 19:19:50 +00001359
1360 FINISH:
1361 return args->m_error.Success();
1362}
1363
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001364bool
Matt Kopec085d6ce2013-05-31 22:00:07 +00001365ProcessMonitor::SetDefaultPtraceOpts(lldb::pid_t pid)
1366{
1367 long ptrace_opts = 0;
1368
1369 // Have the child raise an event on exit. This is used to keep the child in
1370 // limbo until it is destroyed.
1371 ptrace_opts |= PTRACE_O_TRACEEXIT;
1372
1373 // Have the tracer trace threads which spawn in the inferior process.
1374 // TODO: if we want to support tracing the inferiors' child, add the
1375 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
1376 ptrace_opts |= PTRACE_O_TRACECLONE;
1377
1378 // Have the tracer notify us before execve returns
1379 // (needed to disable legacy SIGTRAP generation)
1380 ptrace_opts |= PTRACE_O_TRACEEXEC;
1381
1382 return PTRACE(PTRACE_SETOPTIONS, pid, NULL, (void*)ptrace_opts, 0) >= 0;
1383}
1384
1385bool
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001386ProcessMonitor::MonitorCallback(void *callback_baton,
1387 lldb::pid_t pid,
Peter Collingbourne2c67b9a2011-11-21 00:10:19 +00001388 bool exited,
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001389 int signal,
1390 int status)
1391{
1392 ProcessMessage message;
1393 ProcessMonitor *monitor = static_cast<ProcessMonitor*>(callback_baton);
Andrew Kaylor6578cb62013-07-09 22:36:48 +00001394 ProcessLinux *process = monitor->m_process;
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001395 assert(process);
Stephen Wilson84ffe702011-03-30 15:55:52 +00001396 bool stop_monitoring;
1397 siginfo_t info;
Daniel Maleaa35970a2012-11-23 18:09:58 +00001398 int ptrace_err;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001399
Andrew Kaylor93132f52013-05-28 23:04:25 +00001400 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1401
1402 if (exited)
1403 {
1404 if (log)
1405 log->Printf ("ProcessMonitor::%s() got exit signal, tid = %" PRIu64, __FUNCTION__, pid);
1406 message = ProcessMessage::Exit(pid, status);
1407 process->SendMessage(message);
1408 return pid == process->GetID();
1409 }
1410
Daniel Maleaa35970a2012-11-23 18:09:58 +00001411 if (!monitor->GetSignalInfo(pid, &info, ptrace_err)) {
1412 if (ptrace_err == EINVAL) {
Andrew Kaylor93132f52013-05-28 23:04:25 +00001413 if (log)
1414 log->Printf ("ProcessMonitor::%s() resuming from group-stop", __FUNCTION__);
Daniel Maleaa35970a2012-11-23 18:09:58 +00001415 // inferior process is in 'group-stop', so deliver SIGSTOP signal
1416 if (!monitor->Resume(pid, SIGSTOP)) {
1417 assert(0 && "SIGSTOP delivery failed while in 'group-stop' state");
1418 }
1419 stop_monitoring = false;
1420 } else {
1421 // ptrace(GETSIGINFO) failed (but not due to group-stop). Most likely,
1422 // this means the child pid is gone (or not being debugged) therefore
Andrew Kaylor93132f52013-05-28 23:04:25 +00001423 // stop the monitor thread if this is the main pid.
1424 if (log)
1425 log->Printf ("ProcessMonitor::%s() GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d",
1426 __FUNCTION__, strerror(ptrace_err), pid, signal, status);
1427 stop_monitoring = pid == monitor->m_process->GetID();
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +00001428 // If we are going to stop monitoring, we need to notify our process object
1429 if (stop_monitoring)
1430 {
1431 message = ProcessMessage::Exit(pid, status);
1432 process->SendMessage(message);
1433 }
Daniel Maleaa35970a2012-11-23 18:09:58 +00001434 }
1435 }
Stephen Wilson84ffe702011-03-30 15:55:52 +00001436 else {
1437 switch (info.si_signo)
1438 {
1439 case SIGTRAP:
1440 message = MonitorSIGTRAP(monitor, &info, pid);
1441 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001442
Stephen Wilson84ffe702011-03-30 15:55:52 +00001443 default:
1444 message = MonitorSignal(monitor, &info, pid);
1445 break;
1446 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001447
Stephen Wilson84ffe702011-03-30 15:55:52 +00001448 process->SendMessage(message);
Andrew Kaylor93132f52013-05-28 23:04:25 +00001449 stop_monitoring = false;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001450 }
1451
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001452 return stop_monitoring;
1453}
1454
1455ProcessMessage
Stephen Wilson84ffe702011-03-30 15:55:52 +00001456ProcessMonitor::MonitorSIGTRAP(ProcessMonitor *monitor,
Greg Clayton28041352011-11-29 20:50:10 +00001457 const siginfo_t *info, lldb::pid_t pid)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001458{
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001459 ProcessMessage message;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001460
Andrew Kaylor93132f52013-05-28 23:04:25 +00001461 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1462
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001463 assert(monitor);
1464 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001465
Stephen Wilson84ffe702011-03-30 15:55:52 +00001466 switch (info->si_code)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001467 {
1468 default:
1469 assert(false && "Unexpected SIGTRAP code!");
1470 break;
1471
Matt Kopeca360d7e2013-05-17 19:27:47 +00001472 // TODO: these two cases are required if we want to support tracing
1473 // of the inferiors' children
1474 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
1475 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
1476
Matt Kopec650648f2013-01-08 16:30:18 +00001477 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
1478 {
Andrew Kaylor93132f52013-05-28 23:04:25 +00001479 if (log)
1480 log->Printf ("ProcessMonitor::%s() received thread creation event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
1481
Matt Kopec650648f2013-01-08 16:30:18 +00001482 unsigned long tid = 0;
1483 if (!monitor->GetEventMessage(pid, &tid))
1484 tid = -1;
1485 message = ProcessMessage::NewThread(pid, tid);
1486 break;
1487 }
1488
Matt Kopeca360d7e2013-05-17 19:27:47 +00001489 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
Matt Kopec718be872013-10-09 19:39:55 +00001490 if (log)
1491 log->Printf ("ProcessMonitor::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
1492
1493 message = ProcessMessage::Exec(pid);
Matt Kopeca360d7e2013-05-17 19:27:47 +00001494 break;
1495
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001496 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
1497 {
Andrew Kaylor93132f52013-05-28 23:04:25 +00001498 // The inferior process or one of its threads is about to exit.
1499 // Maintain the process or thread in a state of "limbo" until we are
1500 // explicitly commanded to detach, destroy, resume, etc.
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001501 unsigned long data = 0;
1502 if (!monitor->GetEventMessage(pid, &data))
1503 data = -1;
Andrew Kaylor93132f52013-05-28 23:04:25 +00001504 if (log)
Matt Kopecb2910442013-07-09 15:09:45 +00001505 log->Printf ("ProcessMonitor::%s() received limbo event, data = %lx, pid = %" PRIu64, __FUNCTION__, data, pid);
Stephen Wilson84ffe702011-03-30 15:55:52 +00001506 message = ProcessMessage::Limbo(pid, (data >> 8));
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001507 break;
1508 }
1509
1510 case 0:
1511 case TRAP_TRACE:
Andrew Kaylor93132f52013-05-28 23:04:25 +00001512 if (log)
1513 log->Printf ("ProcessMonitor::%s() received trace event, pid = %" PRIu64, __FUNCTION__, pid);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001514 message = ProcessMessage::Trace(pid);
1515 break;
1516
1517 case SI_KERNEL:
1518 case TRAP_BRKPT:
Andrew Kaylor93132f52013-05-28 23:04:25 +00001519 if (log)
1520 log->Printf ("ProcessMonitor::%s() received breakpoint event, pid = %" PRIu64, __FUNCTION__, pid);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001521 message = ProcessMessage::Break(pid);
1522 break;
Matt Kopece9ea0da2013-05-07 19:29:28 +00001523
1524 case TRAP_HWBKPT:
Andrew Kaylor93132f52013-05-28 23:04:25 +00001525 if (log)
1526 log->Printf ("ProcessMonitor::%s() received watchpoint event, pid = %" PRIu64, __FUNCTION__, pid);
Matt Kopece9ea0da2013-05-07 19:29:28 +00001527 message = ProcessMessage::Watch(pid, (lldb::addr_t)info->si_addr);
1528 break;
Matt Kopec4a32bf52013-07-11 20:01:22 +00001529
1530 case SIGTRAP:
1531 case (SIGTRAP | 0x80):
1532 if (log)
1533 log->Printf ("ProcessMonitor::%s() received system call stop event, pid = %" PRIu64, __FUNCTION__, pid);
1534 // Ignore these signals until we know more about them
1535 monitor->Resume(pid, eResumeSignalNone);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001536 }
1537
1538 return message;
1539}
1540
Stephen Wilson84ffe702011-03-30 15:55:52 +00001541ProcessMessage
1542ProcessMonitor::MonitorSignal(ProcessMonitor *monitor,
Greg Clayton28041352011-11-29 20:50:10 +00001543 const siginfo_t *info, lldb::pid_t pid)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001544{
1545 ProcessMessage message;
1546 int signo = info->si_signo;
1547
Andrew Kaylor93132f52013-05-28 23:04:25 +00001548 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1549
Stephen Wilson84ffe702011-03-30 15:55:52 +00001550 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1551 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1552 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
1553 //
1554 // IOW, user generated signals never generate what we consider to be a
1555 // "crash".
1556 //
1557 // Similarly, ACK signals generated by this monitor.
1558 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
1559 {
Andrew Kaylor93132f52013-05-28 23:04:25 +00001560 if (log)
Matt Kopecef143712013-06-03 18:00:07 +00001561 log->Printf ("ProcessMonitor::%s() received signal %s with code %s, pid = %d",
Andrew Kaylor93132f52013-05-28 23:04:25 +00001562 __FUNCTION__,
1563 monitor->m_process->GetUnixSignals().GetSignalAsCString (signo),
1564 (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
1565 info->si_pid);
1566
Stephen Wilson84ffe702011-03-30 15:55:52 +00001567 if (info->si_pid == getpid())
1568 return ProcessMessage::SignalDelivered(pid, signo);
1569 else
1570 return ProcessMessage::Signal(pid, signo);
1571 }
1572
Andrew Kaylor93132f52013-05-28 23:04:25 +00001573 if (log)
1574 log->Printf ("ProcessMonitor::%s() received signal %s", __FUNCTION__, monitor->m_process->GetUnixSignals().GetSignalAsCString (signo));
1575
Stephen Wilson84ffe702011-03-30 15:55:52 +00001576 if (signo == SIGSEGV) {
1577 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1578 ProcessMessage::CrashReason reason = GetCrashReasonForSIGSEGV(info);
1579 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1580 }
1581
1582 if (signo == SIGILL) {
1583 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1584 ProcessMessage::CrashReason reason = GetCrashReasonForSIGILL(info);
1585 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1586 }
1587
1588 if (signo == SIGFPE) {
1589 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1590 ProcessMessage::CrashReason reason = GetCrashReasonForSIGFPE(info);
1591 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1592 }
1593
1594 if (signo == SIGBUS) {
1595 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1596 ProcessMessage::CrashReason reason = GetCrashReasonForSIGBUS(info);
1597 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1598 }
1599
1600 // Everything else is "normal" and does not require any special action on
1601 // our part.
1602 return ProcessMessage::Signal(pid, signo);
1603}
1604
Andrew Kaylord4d54992013-09-17 00:30:24 +00001605// On Linux, when a new thread is created, we receive to notifications,
1606// (1) a SIGTRAP|PTRACE_EVENT_CLONE from the main process thread with the
1607// child thread id as additional information, and (2) a SIGSTOP|SI_USER from
1608// the new child thread indicating that it has is stopped because we attached.
1609// We have no guarantee of the order in which these arrive, but we need both
1610// before we are ready to proceed. We currently keep a list of threads which
1611// have sent the initial SIGSTOP|SI_USER event. Then when we receive the
1612// SIGTRAP|PTRACE_EVENT_CLONE notification, if the initial stop has not occurred
1613// we call ProcessMonitor::WaitForInitialTIDStop() to wait for it.
1614
1615bool
1616ProcessMonitor::WaitForInitialTIDStop(lldb::tid_t tid)
1617{
1618 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1619 if (log)
Michael Sartainc258b302013-09-18 15:32:06 +00001620 log->Printf ("ProcessMonitor::%s(%" PRIu64 ") waiting for thread to stop...", __FUNCTION__, tid);
Andrew Kaylord4d54992013-09-17 00:30:24 +00001621
1622 // Wait for the thread to stop
1623 while (true)
1624 {
1625 int status = -1;
1626 if (log)
Michael Sartainc258b302013-09-18 15:32:06 +00001627 log->Printf ("ProcessMonitor::%s(%" PRIu64 ") waitpid...", __FUNCTION__, tid);
Andrew Kaylord4d54992013-09-17 00:30:24 +00001628 lldb::pid_t wait_pid = waitpid(tid, &status, __WALL);
1629 if (status == -1)
1630 {
1631 // If we got interrupted by a signal (in our process, not the
1632 // inferior) try again.
1633 if (errno == EINTR)
1634 continue;
1635 else
1636 {
1637 if (log)
Michael Sartainc258b302013-09-18 15:32:06 +00001638 log->Printf("ProcessMonitor::%s(%" PRIu64 ") waitpid error -- %s", __FUNCTION__, tid, strerror(errno));
Andrew Kaylord4d54992013-09-17 00:30:24 +00001639 return false; // This is bad, but there's nothing we can do.
1640 }
1641 }
1642
1643 if (log)
Michael Sartainc258b302013-09-18 15:32:06 +00001644 log->Printf ("ProcessMonitor::%s(%" PRIu64 ") waitpid, status = %d", __FUNCTION__, tid, status);
Andrew Kaylord4d54992013-09-17 00:30:24 +00001645
1646 assert(wait_pid == tid);
1647
1648 siginfo_t info;
1649 int ptrace_err;
1650 if (!GetSignalInfo(wait_pid, &info, ptrace_err))
1651 {
1652 if (log)
1653 {
1654 log->Printf ("ProcessMonitor::%s() GetSignalInfo failed. errno=%d (%s)", __FUNCTION__, ptrace_err, strerror(ptrace_err));
1655 }
1656 return false;
1657 }
1658
1659 // If this is a thread exit, we won't get any more information.
1660 if (WIFEXITED(status))
1661 {
1662 m_process->SendMessage(ProcessMessage::Exit(wait_pid, WEXITSTATUS(status)));
1663 if (wait_pid == tid)
1664 return true;
1665 continue;
1666 }
1667
1668 assert(info.si_code == SI_USER);
1669 assert(WSTOPSIG(status) == SIGSTOP);
1670
1671 if (log)
1672 log->Printf ("ProcessMonitor::%s(bp) received thread stop signal", __FUNCTION__);
1673 m_process->AddThreadForInitialStopIfNeeded(wait_pid);
1674 return true;
1675 }
1676 return false;
1677}
1678
Andrew Kaylor93132f52013-05-28 23:04:25 +00001679bool
1680ProcessMonitor::StopThread(lldb::tid_t tid)
1681{
1682 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1683
1684 // FIXME: Try to use tgkill or tkill
1685 int ret = tgkill(m_pid, tid, SIGSTOP);
1686 if (log)
1687 log->Printf ("ProcessMonitor::%s(bp) stopping thread, tid = %" PRIu64 ", ret = %d", __FUNCTION__, tid, ret);
1688
1689 // This can happen if a thread exited while we were trying to stop it. That's OK.
1690 // We'll get the signal for that later.
1691 if (ret < 0)
1692 return false;
1693
1694 // Wait for the thread to stop
1695 while (true)
1696 {
1697 int status = -1;
1698 if (log)
1699 log->Printf ("ProcessMonitor::%s(bp) waitpid...", __FUNCTION__);
1700 lldb::pid_t wait_pid = ::waitpid (-1*m_pid, &status, __WALL);
1701 if (log)
1702 log->Printf ("ProcessMonitor::%s(bp) waitpid, pid = %" PRIu64 ", status = %d", __FUNCTION__, wait_pid, status);
1703
1704 if (wait_pid == -1)
1705 {
1706 // If we got interrupted by a signal (in our process, not the
1707 // inferior) try again.
1708 if (errno == EINTR)
1709 continue;
1710 else
1711 return false; // This is bad, but there's nothing we can do.
1712 }
1713
1714 // If this is a thread exit, we won't get any more information.
1715 if (WIFEXITED(status))
1716 {
1717 m_process->SendMessage(ProcessMessage::Exit(wait_pid, WEXITSTATUS(status)));
1718 if (wait_pid == tid)
1719 return true;
1720 continue;
1721 }
1722
1723 siginfo_t info;
1724 int ptrace_err;
1725 if (!GetSignalInfo(wait_pid, &info, ptrace_err))
1726 {
1727 if (log)
1728 {
1729 log->Printf ("ProcessMonitor::%s() GetSignalInfo failed.", __FUNCTION__);
1730
1731 // This would be a particularly interesting case
1732 if (ptrace_err == EINVAL)
1733 log->Printf ("ProcessMonitor::%s() in group-stop", __FUNCTION__);
1734 }
1735 return false;
1736 }
1737
1738 // Handle events from other threads
1739 if (log)
Matt Kopecef143712013-06-03 18:00:07 +00001740 log->Printf ("ProcessMonitor::%s(bp) handling event, tid == %" PRIu64, __FUNCTION__, wait_pid);
Andrew Kaylor93132f52013-05-28 23:04:25 +00001741
1742 ProcessMessage message;
1743 if (info.si_signo == SIGTRAP)
1744 message = MonitorSIGTRAP(this, &info, wait_pid);
1745 else
1746 message = MonitorSignal(this, &info, wait_pid);
1747
1748 POSIXThread *thread = static_cast<POSIXThread*>(m_process->GetThreadList().FindThreadByID(wait_pid).get());
1749
1750 // When a new thread is created, we may get a SIGSTOP for the new thread
1751 // just before we get the SIGTRAP that we use to add the thread to our
1752 // process thread list. We don't need to worry about that signal here.
1753 assert(thread || message.GetKind() == ProcessMessage::eSignalMessage);
1754
1755 if (!thread)
1756 {
1757 m_process->SendMessage(message);
1758 continue;
1759 }
1760
1761 switch (message.GetKind())
1762 {
Michael Sartainc258b302013-09-18 15:32:06 +00001763 case ProcessMessage::eAttachMessage:
Andrew Kaylor93132f52013-05-28 23:04:25 +00001764 case ProcessMessage::eInvalidMessage:
1765 break;
1766
1767 // These need special handling because we don't want to send a
1768 // resume even if we already sent a SIGSTOP to this thread. In
1769 // this case the resume will cause the thread to disappear. It is
1770 // unlikely that we'll ever get eExitMessage here, but the same
1771 // reasoning applies.
1772 case ProcessMessage::eLimboMessage:
1773 case ProcessMessage::eExitMessage:
1774 if (log)
1775 log->Printf ("ProcessMonitor::%s(bp) handling message", __FUNCTION__);
1776 // SendMessage will set the thread state as needed.
1777 m_process->SendMessage(message);
1778 // If this is the thread we're waiting for, stop waiting. Even
1779 // though this wasn't the signal we expected, it's the last
1780 // signal we'll see while this thread is alive.
1781 if (wait_pid == tid)
1782 return true;
1783 break;
1784
Matt Kopecb2910442013-07-09 15:09:45 +00001785 case ProcessMessage::eSignalMessage:
1786 if (log)
1787 log->Printf ("ProcessMonitor::%s(bp) handling message", __FUNCTION__);
1788 if (WSTOPSIG(status) == SIGSTOP)
1789 {
1790 m_process->AddThreadForInitialStopIfNeeded(tid);
1791 thread->SetState(lldb::eStateStopped);
1792 }
1793 else
1794 {
1795 m_process->SendMessage(message);
1796 // This isn't the stop we were expecting, but the thread is
1797 // stopped. SendMessage will handle processing of this event,
1798 // but we need to resume here to get the stop we are waiting
1799 // for (otherwise the thread will stop again immediately when
1800 // we try to resume).
1801 if (wait_pid == tid)
1802 Resume(wait_pid, eResumeSignalNone);
1803 }
1804 break;
1805
Andrew Kaylor93132f52013-05-28 23:04:25 +00001806 case ProcessMessage::eSignalDeliveredMessage:
1807 // This is the stop we're expecting.
1808 if (wait_pid == tid && WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP && info.si_code == SI_TKILL)
1809 {
1810 if (log)
1811 log->Printf ("ProcessMonitor::%s(bp) received signal, done waiting", __FUNCTION__);
1812 thread->SetState(lldb::eStateStopped);
1813 return true;
1814 }
1815 // else fall-through
Andrew Kaylor93132f52013-05-28 23:04:25 +00001816 case ProcessMessage::eBreakpointMessage:
1817 case ProcessMessage::eTraceMessage:
1818 case ProcessMessage::eWatchpointMessage:
1819 case ProcessMessage::eCrashMessage:
1820 case ProcessMessage::eNewThreadMessage:
1821 if (log)
1822 log->Printf ("ProcessMonitor::%s(bp) handling message", __FUNCTION__);
1823 // SendMessage will set the thread state as needed.
1824 m_process->SendMessage(message);
1825 // This isn't the stop we were expecting, but the thread is
1826 // stopped. SendMessage will handle processing of this event,
1827 // but we need to resume here to get the stop we are waiting
1828 // for (otherwise the thread will stop again immediately when
1829 // we try to resume).
1830 if (wait_pid == tid)
1831 Resume(wait_pid, eResumeSignalNone);
1832 break;
1833 }
1834 }
1835 return false;
1836}
1837
Stephen Wilson84ffe702011-03-30 15:55:52 +00001838ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001839ProcessMonitor::GetCrashReasonForSIGSEGV(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001840{
1841 ProcessMessage::CrashReason reason;
1842 assert(info->si_signo == SIGSEGV);
1843
1844 reason = ProcessMessage::eInvalidCrashReason;
1845
Greg Clayton542e4072012-09-07 17:49:29 +00001846 switch (info->si_code)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001847 {
1848 default:
1849 assert(false && "unexpected si_code for SIGSEGV");
1850 break;
Matt Kopecf8cfe6b2013-08-09 15:26:56 +00001851 case SI_KERNEL:
1852 // Linux will occasionally send spurious SI_KERNEL codes.
1853 // (this is poorly documented in sigaction)
1854 // One way to get this is via unaligned SIMD loads.
1855 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
1856 break;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001857 case SEGV_MAPERR:
1858 reason = ProcessMessage::eInvalidAddress;
1859 break;
1860 case SEGV_ACCERR:
1861 reason = ProcessMessage::ePrivilegedAddress;
1862 break;
1863 }
Greg Clayton542e4072012-09-07 17:49:29 +00001864
Stephen Wilson84ffe702011-03-30 15:55:52 +00001865 return reason;
1866}
1867
1868ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001869ProcessMonitor::GetCrashReasonForSIGILL(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001870{
1871 ProcessMessage::CrashReason reason;
1872 assert(info->si_signo == SIGILL);
1873
1874 reason = ProcessMessage::eInvalidCrashReason;
1875
1876 switch (info->si_code)
1877 {
1878 default:
1879 assert(false && "unexpected si_code for SIGILL");
1880 break;
1881 case ILL_ILLOPC:
1882 reason = ProcessMessage::eIllegalOpcode;
1883 break;
1884 case ILL_ILLOPN:
1885 reason = ProcessMessage::eIllegalOperand;
1886 break;
1887 case ILL_ILLADR:
1888 reason = ProcessMessage::eIllegalAddressingMode;
1889 break;
1890 case ILL_ILLTRP:
1891 reason = ProcessMessage::eIllegalTrap;
1892 break;
1893 case ILL_PRVOPC:
1894 reason = ProcessMessage::ePrivilegedOpcode;
1895 break;
1896 case ILL_PRVREG:
1897 reason = ProcessMessage::ePrivilegedRegister;
1898 break;
1899 case ILL_COPROC:
1900 reason = ProcessMessage::eCoprocessorError;
1901 break;
1902 case ILL_BADSTK:
1903 reason = ProcessMessage::eInternalStackError;
1904 break;
1905 }
1906
1907 return reason;
1908}
1909
1910ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001911ProcessMonitor::GetCrashReasonForSIGFPE(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001912{
1913 ProcessMessage::CrashReason reason;
1914 assert(info->si_signo == SIGFPE);
1915
1916 reason = ProcessMessage::eInvalidCrashReason;
1917
1918 switch (info->si_code)
1919 {
1920 default:
1921 assert(false && "unexpected si_code for SIGFPE");
1922 break;
1923 case FPE_INTDIV:
1924 reason = ProcessMessage::eIntegerDivideByZero;
1925 break;
1926 case FPE_INTOVF:
1927 reason = ProcessMessage::eIntegerOverflow;
1928 break;
1929 case FPE_FLTDIV:
1930 reason = ProcessMessage::eFloatDivideByZero;
1931 break;
1932 case FPE_FLTOVF:
1933 reason = ProcessMessage::eFloatOverflow;
1934 break;
1935 case FPE_FLTUND:
1936 reason = ProcessMessage::eFloatUnderflow;
1937 break;
1938 case FPE_FLTRES:
1939 reason = ProcessMessage::eFloatInexactResult;
1940 break;
1941 case FPE_FLTINV:
1942 reason = ProcessMessage::eFloatInvalidOperation;
1943 break;
1944 case FPE_FLTSUB:
1945 reason = ProcessMessage::eFloatSubscriptRange;
1946 break;
1947 }
1948
1949 return reason;
1950}
1951
1952ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001953ProcessMonitor::GetCrashReasonForSIGBUS(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001954{
1955 ProcessMessage::CrashReason reason;
1956 assert(info->si_signo == SIGBUS);
1957
1958 reason = ProcessMessage::eInvalidCrashReason;
1959
1960 switch (info->si_code)
1961 {
1962 default:
1963 assert(false && "unexpected si_code for SIGBUS");
1964 break;
1965 case BUS_ADRALN:
1966 reason = ProcessMessage::eIllegalAlignment;
1967 break;
1968 case BUS_ADRERR:
1969 reason = ProcessMessage::eIllegalAddress;
1970 break;
1971 case BUS_OBJERR:
1972 reason = ProcessMessage::eHardwareError;
1973 break;
1974 }
1975
1976 return reason;
1977}
1978
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001979void
Johnny Chen25e68e32011-06-14 19:19:50 +00001980ProcessMonitor::ServeOperation(OperationArgs *args)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001981{
Stephen Wilson570243b2011-01-19 01:37:06 +00001982 ProcessMonitor *monitor = args->m_monitor;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001983
Stephen Wilson570243b2011-01-19 01:37:06 +00001984 // We are finised with the arguments and are ready to go. Sync with the
1985 // parent thread and start serving operations on the inferior.
1986 sem_post(&args->m_semaphore);
1987
Michael Sartain704bf892013-10-09 01:28:57 +00001988 for(;;)
1989 {
Daniel Malea1efb4182013-09-16 23:12:18 +00001990 // wait for next pending operation
1991 sem_wait(&monitor->m_operation_pending);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001992
Daniel Malea1efb4182013-09-16 23:12:18 +00001993 monitor->m_operation->Execute(monitor);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001994
Daniel Malea1efb4182013-09-16 23:12:18 +00001995 // notify calling thread that operation is complete
1996 sem_post(&monitor->m_operation_done);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001997 }
1998}
1999
2000void
2001ProcessMonitor::DoOperation(Operation *op)
2002{
Daniel Malea1efb4182013-09-16 23:12:18 +00002003 Mutex::Locker lock(m_operation_mutex);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002004
Daniel Malea1efb4182013-09-16 23:12:18 +00002005 m_operation = op;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002006
Daniel Malea1efb4182013-09-16 23:12:18 +00002007 // notify operation thread that an operation is ready to be processed
2008 sem_post(&m_operation_pending);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002009
Daniel Malea1efb4182013-09-16 23:12:18 +00002010 // wait for operation to complete
2011 sem_wait(&m_operation_done);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002012}
2013
2014size_t
2015ProcessMonitor::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
2016 Error &error)
2017{
2018 size_t result;
2019 ReadOperation op(vm_addr, buf, size, error, result);
2020 DoOperation(&op);
2021 return result;
2022}
2023
2024size_t
2025ProcessMonitor::WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
2026 lldb_private::Error &error)
2027{
2028 size_t result;
2029 WriteOperation op(vm_addr, buf, size, error, result);
2030 DoOperation(&op);
2031 return result;
2032}
2033
2034bool
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00002035ProcessMonitor::ReadRegisterValue(lldb::tid_t tid, unsigned offset, const char* reg_name,
Matt Kopec7de48462013-03-06 17:20:48 +00002036 unsigned size, RegisterValue &value)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002037{
2038 bool result;
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00002039 ReadRegOperation op(tid, offset, reg_name, value, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002040 DoOperation(&op);
2041 return result;
2042}
2043
2044bool
Matt Kopec7de48462013-03-06 17:20:48 +00002045ProcessMonitor::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00002046 const char* reg_name, const RegisterValue &value)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002047{
2048 bool result;
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00002049 WriteRegOperation op(tid, offset, reg_name, value, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002050 DoOperation(&op);
2051 return result;
2052}
2053
2054bool
Matt Kopec7de48462013-03-06 17:20:48 +00002055ProcessMonitor::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size)
Stephen Wilsonade1aea2011-01-19 01:31:38 +00002056{
2057 bool result;
Matt Kopec7de48462013-03-06 17:20:48 +00002058 ReadGPROperation op(tid, buf, buf_size, result);
Stephen Wilsonade1aea2011-01-19 01:31:38 +00002059 DoOperation(&op);
2060 return result;
2061}
2062
2063bool
Matt Kopec7de48462013-03-06 17:20:48 +00002064ProcessMonitor::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size)
Stephen Wilsonade1aea2011-01-19 01:31:38 +00002065{
2066 bool result;
Matt Kopec7de48462013-03-06 17:20:48 +00002067 ReadFPROperation op(tid, buf, buf_size, result);
Stephen Wilsonade1aea2011-01-19 01:31:38 +00002068 DoOperation(&op);
2069 return result;
2070}
2071
2072bool
Matt Kopec58c0b962013-03-20 20:34:35 +00002073ProcessMonitor::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
2074{
2075 bool result;
2076 ReadRegisterSetOperation op(tid, buf, buf_size, regset, result);
2077 DoOperation(&op);
2078 return result;
2079}
2080
2081bool
Matt Kopec7de48462013-03-06 17:20:48 +00002082ProcessMonitor::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size)
Peter Collingbourne10bc0102011-06-03 20:41:02 +00002083{
2084 bool result;
Matt Kopec7de48462013-03-06 17:20:48 +00002085 WriteGPROperation op(tid, buf, buf_size, result);
Peter Collingbourne10bc0102011-06-03 20:41:02 +00002086 DoOperation(&op);
2087 return result;
2088}
2089
2090bool
Matt Kopec7de48462013-03-06 17:20:48 +00002091ProcessMonitor::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size)
Peter Collingbourne10bc0102011-06-03 20:41:02 +00002092{
2093 bool result;
Matt Kopec7de48462013-03-06 17:20:48 +00002094 WriteFPROperation op(tid, buf, buf_size, result);
Peter Collingbourne10bc0102011-06-03 20:41:02 +00002095 DoOperation(&op);
2096 return result;
2097}
2098
2099bool
Matt Kopec58c0b962013-03-20 20:34:35 +00002100ProcessMonitor::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
2101{
2102 bool result;
2103 WriteRegisterSetOperation op(tid, buf, buf_size, regset, result);
2104 DoOperation(&op);
2105 return result;
2106}
2107
2108bool
Stephen Wilson84ffe702011-03-30 15:55:52 +00002109ProcessMonitor::Resume(lldb::tid_t tid, uint32_t signo)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002110{
2111 bool result;
Andrew Kaylor93132f52013-05-28 23:04:25 +00002112 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
2113
2114 if (log)
2115 log->Printf ("ProcessMonitor::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid,
2116 m_process->GetUnixSignals().GetSignalAsCString (signo));
Stephen Wilson84ffe702011-03-30 15:55:52 +00002117 ResumeOperation op(tid, signo, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002118 DoOperation(&op);
Andrew Kaylor93132f52013-05-28 23:04:25 +00002119 if (log)
2120 log->Printf ("ProcessMonitor::%s() resuming result = %s", __FUNCTION__, result ? "true" : "false");
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002121 return result;
2122}
2123
2124bool
Stephen Wilson84ffe702011-03-30 15:55:52 +00002125ProcessMonitor::SingleStep(lldb::tid_t tid, uint32_t signo)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002126{
2127 bool result;
Stephen Wilson84ffe702011-03-30 15:55:52 +00002128 SingleStepOperation op(tid, signo, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002129 DoOperation(&op);
2130 return result;
2131}
2132
2133bool
2134ProcessMonitor::BringProcessIntoLimbo()
2135{
2136 bool result;
2137 KillOperation op(result);
2138 DoOperation(&op);
2139 return result;
2140}
2141
2142bool
Daniel Maleaa35970a2012-11-23 18:09:58 +00002143ProcessMonitor::GetSignalInfo(lldb::tid_t tid, void *siginfo, int &ptrace_err)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002144{
2145 bool result;
Daniel Maleaa35970a2012-11-23 18:09:58 +00002146 SiginfoOperation op(tid, siginfo, result, ptrace_err);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002147 DoOperation(&op);
2148 return result;
2149}
2150
2151bool
2152ProcessMonitor::GetEventMessage(lldb::tid_t tid, unsigned long *message)
2153{
2154 bool result;
2155 EventMessageOperation op(tid, message, result);
2156 DoOperation(&op);
2157 return result;
2158}
2159
Greg Clayton743ecf42012-10-16 20:20:18 +00002160lldb_private::Error
Matt Kopec085d6ce2013-05-31 22:00:07 +00002161ProcessMonitor::Detach(lldb::tid_t tid)
Stephen Wilson84ffe702011-03-30 15:55:52 +00002162{
Greg Clayton28041352011-11-29 20:50:10 +00002163 lldb_private::Error error;
Matt Kopec085d6ce2013-05-31 22:00:07 +00002164 if (tid != LLDB_INVALID_THREAD_ID)
2165 {
2166 DetachOperation op(tid, error);
Greg Clayton743ecf42012-10-16 20:20:18 +00002167 DoOperation(&op);
2168 }
Greg Clayton743ecf42012-10-16 20:20:18 +00002169 return error;
Greg Clayton542e4072012-09-07 17:49:29 +00002170}
Stephen Wilson84ffe702011-03-30 15:55:52 +00002171
2172bool
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002173ProcessMonitor::DupDescriptor(const char *path, int fd, int flags)
2174{
Peter Collingbourne62343202011-06-14 03:55:54 +00002175 int target_fd = open(path, flags, 0666);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002176
2177 if (target_fd == -1)
2178 return false;
2179
Peter Collingbourne62343202011-06-14 03:55:54 +00002180 return (dup2(target_fd, fd) == -1) ? false : true;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002181}
Stephen Wilson9212d7f2011-01-04 21:40:25 +00002182
2183void
2184ProcessMonitor::StopMonitoringChildProcess()
2185{
2186 lldb::thread_result_t thread_result;
2187
Stephen Wilsond4182f42011-02-09 20:10:35 +00002188 if (IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
Stephen Wilson9212d7f2011-01-04 21:40:25 +00002189 {
2190 Host::ThreadCancel(m_monitor_thread, NULL);
2191 Host::ThreadJoin(m_monitor_thread, &thread_result, NULL);
2192 m_monitor_thread = LLDB_INVALID_HOST_THREAD;
2193 }
2194}
Stephen Wilson84ffe702011-03-30 15:55:52 +00002195
2196void
2197ProcessMonitor::StopMonitor()
2198{
2199 StopMonitoringChildProcess();
Greg Clayton743ecf42012-10-16 20:20:18 +00002200 StopOpThread();
Daniel Malea1efb4182013-09-16 23:12:18 +00002201 sem_destroy(&m_operation_pending);
2202 sem_destroy(&m_operation_done);
2203
Andrew Kaylor5e268992013-09-14 00:17:31 +00002204 // Note: ProcessPOSIX passes the m_terminal_fd file descriptor to
2205 // Process::SetSTDIOFileDescriptor, which in turn transfers ownership of
2206 // the descriptor to a ConnectionFileDescriptor object. Consequently
2207 // even though still has the file descriptor, we shouldn't close it here.
Stephen Wilson84ffe702011-03-30 15:55:52 +00002208}
2209
2210void
Greg Clayton743ecf42012-10-16 20:20:18 +00002211ProcessMonitor::StopOpThread()
2212{
2213 lldb::thread_result_t result;
2214
2215 if (!IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
2216 return;
2217
2218 Host::ThreadCancel(m_operation_thread, NULL);
2219 Host::ThreadJoin(m_operation_thread, &result, NULL);
Daniel Malea8b9e71e2012-11-22 18:21:05 +00002220 m_operation_thread = LLDB_INVALID_HOST_THREAD;
Greg Clayton743ecf42012-10-16 20:20:18 +00002221}