blob: b69030b22a80817cf7bd5455dc518664f2a15b37 [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)):
1490 // Don't follow the child by default and resume
1491 monitor->Resume(pid, SIGCONT);
1492 break;
1493
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001494 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
1495 {
Andrew Kaylor93132f52013-05-28 23:04:25 +00001496 // The inferior process or one of its threads is about to exit.
1497 // Maintain the process or thread in a state of "limbo" until we are
1498 // explicitly commanded to detach, destroy, resume, etc.
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001499 unsigned long data = 0;
1500 if (!monitor->GetEventMessage(pid, &data))
1501 data = -1;
Andrew Kaylor93132f52013-05-28 23:04:25 +00001502 if (log)
Matt Kopecb2910442013-07-09 15:09:45 +00001503 log->Printf ("ProcessMonitor::%s() received limbo event, data = %lx, pid = %" PRIu64, __FUNCTION__, data, pid);
Stephen Wilson84ffe702011-03-30 15:55:52 +00001504 message = ProcessMessage::Limbo(pid, (data >> 8));
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001505 break;
1506 }
1507
1508 case 0:
1509 case TRAP_TRACE:
Andrew Kaylor93132f52013-05-28 23:04:25 +00001510 if (log)
1511 log->Printf ("ProcessMonitor::%s() received trace event, pid = %" PRIu64, __FUNCTION__, pid);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001512 message = ProcessMessage::Trace(pid);
1513 break;
1514
1515 case SI_KERNEL:
1516 case TRAP_BRKPT:
Andrew Kaylor93132f52013-05-28 23:04:25 +00001517 if (log)
1518 log->Printf ("ProcessMonitor::%s() received breakpoint event, pid = %" PRIu64, __FUNCTION__, pid);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001519 message = ProcessMessage::Break(pid);
1520 break;
Matt Kopece9ea0da2013-05-07 19:29:28 +00001521
1522 case TRAP_HWBKPT:
Andrew Kaylor93132f52013-05-28 23:04:25 +00001523 if (log)
1524 log->Printf ("ProcessMonitor::%s() received watchpoint event, pid = %" PRIu64, __FUNCTION__, pid);
Matt Kopece9ea0da2013-05-07 19:29:28 +00001525 message = ProcessMessage::Watch(pid, (lldb::addr_t)info->si_addr);
1526 break;
Matt Kopec4a32bf52013-07-11 20:01:22 +00001527
1528 case SIGTRAP:
1529 case (SIGTRAP | 0x80):
1530 if (log)
1531 log->Printf ("ProcessMonitor::%s() received system call stop event, pid = %" PRIu64, __FUNCTION__, pid);
1532 // Ignore these signals until we know more about them
1533 monitor->Resume(pid, eResumeSignalNone);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001534 }
1535
1536 return message;
1537}
1538
Stephen Wilson84ffe702011-03-30 15:55:52 +00001539ProcessMessage
1540ProcessMonitor::MonitorSignal(ProcessMonitor *monitor,
Greg Clayton28041352011-11-29 20:50:10 +00001541 const siginfo_t *info, lldb::pid_t pid)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001542{
1543 ProcessMessage message;
1544 int signo = info->si_signo;
1545
Andrew Kaylor93132f52013-05-28 23:04:25 +00001546 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1547
Stephen Wilson84ffe702011-03-30 15:55:52 +00001548 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1549 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1550 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
1551 //
1552 // IOW, user generated signals never generate what we consider to be a
1553 // "crash".
1554 //
1555 // Similarly, ACK signals generated by this monitor.
1556 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
1557 {
Andrew Kaylor93132f52013-05-28 23:04:25 +00001558 if (log)
Matt Kopecef143712013-06-03 18:00:07 +00001559 log->Printf ("ProcessMonitor::%s() received signal %s with code %s, pid = %d",
Andrew Kaylor93132f52013-05-28 23:04:25 +00001560 __FUNCTION__,
1561 monitor->m_process->GetUnixSignals().GetSignalAsCString (signo),
1562 (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
1563 info->si_pid);
1564
Stephen Wilson84ffe702011-03-30 15:55:52 +00001565 if (info->si_pid == getpid())
1566 return ProcessMessage::SignalDelivered(pid, signo);
1567 else
1568 return ProcessMessage::Signal(pid, signo);
1569 }
1570
Andrew Kaylor93132f52013-05-28 23:04:25 +00001571 if (log)
1572 log->Printf ("ProcessMonitor::%s() received signal %s", __FUNCTION__, monitor->m_process->GetUnixSignals().GetSignalAsCString (signo));
1573
Stephen Wilson84ffe702011-03-30 15:55:52 +00001574 if (signo == SIGSEGV) {
1575 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1576 ProcessMessage::CrashReason reason = GetCrashReasonForSIGSEGV(info);
1577 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1578 }
1579
1580 if (signo == SIGILL) {
1581 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1582 ProcessMessage::CrashReason reason = GetCrashReasonForSIGILL(info);
1583 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1584 }
1585
1586 if (signo == SIGFPE) {
1587 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1588 ProcessMessage::CrashReason reason = GetCrashReasonForSIGFPE(info);
1589 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1590 }
1591
1592 if (signo == SIGBUS) {
1593 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1594 ProcessMessage::CrashReason reason = GetCrashReasonForSIGBUS(info);
1595 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1596 }
1597
1598 // Everything else is "normal" and does not require any special action on
1599 // our part.
1600 return ProcessMessage::Signal(pid, signo);
1601}
1602
Andrew Kaylord4d54992013-09-17 00:30:24 +00001603// On Linux, when a new thread is created, we receive to notifications,
1604// (1) a SIGTRAP|PTRACE_EVENT_CLONE from the main process thread with the
1605// child thread id as additional information, and (2) a SIGSTOP|SI_USER from
1606// the new child thread indicating that it has is stopped because we attached.
1607// We have no guarantee of the order in which these arrive, but we need both
1608// before we are ready to proceed. We currently keep a list of threads which
1609// have sent the initial SIGSTOP|SI_USER event. Then when we receive the
1610// SIGTRAP|PTRACE_EVENT_CLONE notification, if the initial stop has not occurred
1611// we call ProcessMonitor::WaitForInitialTIDStop() to wait for it.
1612
1613bool
1614ProcessMonitor::WaitForInitialTIDStop(lldb::tid_t tid)
1615{
1616 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1617 if (log)
Michael Sartainc258b302013-09-18 15:32:06 +00001618 log->Printf ("ProcessMonitor::%s(%" PRIu64 ") waiting for thread to stop...", __FUNCTION__, tid);
Andrew Kaylord4d54992013-09-17 00:30:24 +00001619
1620 // Wait for the thread to stop
1621 while (true)
1622 {
1623 int status = -1;
1624 if (log)
Michael Sartainc258b302013-09-18 15:32:06 +00001625 log->Printf ("ProcessMonitor::%s(%" PRIu64 ") waitpid...", __FUNCTION__, tid);
Andrew Kaylord4d54992013-09-17 00:30:24 +00001626 lldb::pid_t wait_pid = waitpid(tid, &status, __WALL);
1627 if (status == -1)
1628 {
1629 // If we got interrupted by a signal (in our process, not the
1630 // inferior) try again.
1631 if (errno == EINTR)
1632 continue;
1633 else
1634 {
1635 if (log)
Michael Sartainc258b302013-09-18 15:32:06 +00001636 log->Printf("ProcessMonitor::%s(%" PRIu64 ") waitpid error -- %s", __FUNCTION__, tid, strerror(errno));
Andrew Kaylord4d54992013-09-17 00:30:24 +00001637 return false; // This is bad, but there's nothing we can do.
1638 }
1639 }
1640
1641 if (log)
Michael Sartainc258b302013-09-18 15:32:06 +00001642 log->Printf ("ProcessMonitor::%s(%" PRIu64 ") waitpid, status = %d", __FUNCTION__, tid, status);
Andrew Kaylord4d54992013-09-17 00:30:24 +00001643
1644 assert(wait_pid == tid);
1645
1646 siginfo_t info;
1647 int ptrace_err;
1648 if (!GetSignalInfo(wait_pid, &info, ptrace_err))
1649 {
1650 if (log)
1651 {
1652 log->Printf ("ProcessMonitor::%s() GetSignalInfo failed. errno=%d (%s)", __FUNCTION__, ptrace_err, strerror(ptrace_err));
1653 }
1654 return false;
1655 }
1656
1657 // If this is a thread exit, we won't get any more information.
1658 if (WIFEXITED(status))
1659 {
1660 m_process->SendMessage(ProcessMessage::Exit(wait_pid, WEXITSTATUS(status)));
1661 if (wait_pid == tid)
1662 return true;
1663 continue;
1664 }
1665
1666 assert(info.si_code == SI_USER);
1667 assert(WSTOPSIG(status) == SIGSTOP);
1668
1669 if (log)
1670 log->Printf ("ProcessMonitor::%s(bp) received thread stop signal", __FUNCTION__);
1671 m_process->AddThreadForInitialStopIfNeeded(wait_pid);
1672 return true;
1673 }
1674 return false;
1675}
1676
Andrew Kaylor93132f52013-05-28 23:04:25 +00001677bool
1678ProcessMonitor::StopThread(lldb::tid_t tid)
1679{
1680 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1681
1682 // FIXME: Try to use tgkill or tkill
1683 int ret = tgkill(m_pid, tid, SIGSTOP);
1684 if (log)
1685 log->Printf ("ProcessMonitor::%s(bp) stopping thread, tid = %" PRIu64 ", ret = %d", __FUNCTION__, tid, ret);
1686
1687 // This can happen if a thread exited while we were trying to stop it. That's OK.
1688 // We'll get the signal for that later.
1689 if (ret < 0)
1690 return false;
1691
1692 // Wait for the thread to stop
1693 while (true)
1694 {
1695 int status = -1;
1696 if (log)
1697 log->Printf ("ProcessMonitor::%s(bp) waitpid...", __FUNCTION__);
1698 lldb::pid_t wait_pid = ::waitpid (-1*m_pid, &status, __WALL);
1699 if (log)
1700 log->Printf ("ProcessMonitor::%s(bp) waitpid, pid = %" PRIu64 ", status = %d", __FUNCTION__, wait_pid, status);
1701
1702 if (wait_pid == -1)
1703 {
1704 // If we got interrupted by a signal (in our process, not the
1705 // inferior) try again.
1706 if (errno == EINTR)
1707 continue;
1708 else
1709 return false; // This is bad, but there's nothing we can do.
1710 }
1711
1712 // If this is a thread exit, we won't get any more information.
1713 if (WIFEXITED(status))
1714 {
1715 m_process->SendMessage(ProcessMessage::Exit(wait_pid, WEXITSTATUS(status)));
1716 if (wait_pid == tid)
1717 return true;
1718 continue;
1719 }
1720
1721 siginfo_t info;
1722 int ptrace_err;
1723 if (!GetSignalInfo(wait_pid, &info, ptrace_err))
1724 {
1725 if (log)
1726 {
1727 log->Printf ("ProcessMonitor::%s() GetSignalInfo failed.", __FUNCTION__);
1728
1729 // This would be a particularly interesting case
1730 if (ptrace_err == EINVAL)
1731 log->Printf ("ProcessMonitor::%s() in group-stop", __FUNCTION__);
1732 }
1733 return false;
1734 }
1735
1736 // Handle events from other threads
1737 if (log)
Matt Kopecef143712013-06-03 18:00:07 +00001738 log->Printf ("ProcessMonitor::%s(bp) handling event, tid == %" PRIu64, __FUNCTION__, wait_pid);
Andrew Kaylor93132f52013-05-28 23:04:25 +00001739
1740 ProcessMessage message;
1741 if (info.si_signo == SIGTRAP)
1742 message = MonitorSIGTRAP(this, &info, wait_pid);
1743 else
1744 message = MonitorSignal(this, &info, wait_pid);
1745
1746 POSIXThread *thread = static_cast<POSIXThread*>(m_process->GetThreadList().FindThreadByID(wait_pid).get());
1747
1748 // When a new thread is created, we may get a SIGSTOP for the new thread
1749 // just before we get the SIGTRAP that we use to add the thread to our
1750 // process thread list. We don't need to worry about that signal here.
1751 assert(thread || message.GetKind() == ProcessMessage::eSignalMessage);
1752
1753 if (!thread)
1754 {
1755 m_process->SendMessage(message);
1756 continue;
1757 }
1758
1759 switch (message.GetKind())
1760 {
Michael Sartainc258b302013-09-18 15:32:06 +00001761 case ProcessMessage::eAttachMessage:
Andrew Kaylor93132f52013-05-28 23:04:25 +00001762 case ProcessMessage::eInvalidMessage:
1763 break;
1764
1765 // These need special handling because we don't want to send a
1766 // resume even if we already sent a SIGSTOP to this thread. In
1767 // this case the resume will cause the thread to disappear. It is
1768 // unlikely that we'll ever get eExitMessage here, but the same
1769 // reasoning applies.
1770 case ProcessMessage::eLimboMessage:
1771 case ProcessMessage::eExitMessage:
1772 if (log)
1773 log->Printf ("ProcessMonitor::%s(bp) handling message", __FUNCTION__);
1774 // SendMessage will set the thread state as needed.
1775 m_process->SendMessage(message);
1776 // If this is the thread we're waiting for, stop waiting. Even
1777 // though this wasn't the signal we expected, it's the last
1778 // signal we'll see while this thread is alive.
1779 if (wait_pid == tid)
1780 return true;
1781 break;
1782
Matt Kopecb2910442013-07-09 15:09:45 +00001783 case ProcessMessage::eSignalMessage:
1784 if (log)
1785 log->Printf ("ProcessMonitor::%s(bp) handling message", __FUNCTION__);
1786 if (WSTOPSIG(status) == SIGSTOP)
1787 {
1788 m_process->AddThreadForInitialStopIfNeeded(tid);
1789 thread->SetState(lldb::eStateStopped);
1790 }
1791 else
1792 {
1793 m_process->SendMessage(message);
1794 // This isn't the stop we were expecting, but the thread is
1795 // stopped. SendMessage will handle processing of this event,
1796 // but we need to resume here to get the stop we are waiting
1797 // for (otherwise the thread will stop again immediately when
1798 // we try to resume).
1799 if (wait_pid == tid)
1800 Resume(wait_pid, eResumeSignalNone);
1801 }
1802 break;
1803
Andrew Kaylor93132f52013-05-28 23:04:25 +00001804 case ProcessMessage::eSignalDeliveredMessage:
1805 // This is the stop we're expecting.
1806 if (wait_pid == tid && WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP && info.si_code == SI_TKILL)
1807 {
1808 if (log)
1809 log->Printf ("ProcessMonitor::%s(bp) received signal, done waiting", __FUNCTION__);
1810 thread->SetState(lldb::eStateStopped);
1811 return true;
1812 }
1813 // else fall-through
Andrew Kaylor93132f52013-05-28 23:04:25 +00001814 case ProcessMessage::eBreakpointMessage:
1815 case ProcessMessage::eTraceMessage:
1816 case ProcessMessage::eWatchpointMessage:
1817 case ProcessMessage::eCrashMessage:
1818 case ProcessMessage::eNewThreadMessage:
1819 if (log)
1820 log->Printf ("ProcessMonitor::%s(bp) handling message", __FUNCTION__);
1821 // SendMessage will set the thread state as needed.
1822 m_process->SendMessage(message);
1823 // This isn't the stop we were expecting, but the thread is
1824 // stopped. SendMessage will handle processing of this event,
1825 // but we need to resume here to get the stop we are waiting
1826 // for (otherwise the thread will stop again immediately when
1827 // we try to resume).
1828 if (wait_pid == tid)
1829 Resume(wait_pid, eResumeSignalNone);
1830 break;
1831 }
1832 }
1833 return false;
1834}
1835
Stephen Wilson84ffe702011-03-30 15:55:52 +00001836ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001837ProcessMonitor::GetCrashReasonForSIGSEGV(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001838{
1839 ProcessMessage::CrashReason reason;
1840 assert(info->si_signo == SIGSEGV);
1841
1842 reason = ProcessMessage::eInvalidCrashReason;
1843
Greg Clayton542e4072012-09-07 17:49:29 +00001844 switch (info->si_code)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001845 {
1846 default:
1847 assert(false && "unexpected si_code for SIGSEGV");
1848 break;
Matt Kopecf8cfe6b2013-08-09 15:26:56 +00001849 case SI_KERNEL:
1850 // Linux will occasionally send spurious SI_KERNEL codes.
1851 // (this is poorly documented in sigaction)
1852 // One way to get this is via unaligned SIMD loads.
1853 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
1854 break;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001855 case SEGV_MAPERR:
1856 reason = ProcessMessage::eInvalidAddress;
1857 break;
1858 case SEGV_ACCERR:
1859 reason = ProcessMessage::ePrivilegedAddress;
1860 break;
1861 }
Greg Clayton542e4072012-09-07 17:49:29 +00001862
Stephen Wilson84ffe702011-03-30 15:55:52 +00001863 return reason;
1864}
1865
1866ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001867ProcessMonitor::GetCrashReasonForSIGILL(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001868{
1869 ProcessMessage::CrashReason reason;
1870 assert(info->si_signo == SIGILL);
1871
1872 reason = ProcessMessage::eInvalidCrashReason;
1873
1874 switch (info->si_code)
1875 {
1876 default:
1877 assert(false && "unexpected si_code for SIGILL");
1878 break;
1879 case ILL_ILLOPC:
1880 reason = ProcessMessage::eIllegalOpcode;
1881 break;
1882 case ILL_ILLOPN:
1883 reason = ProcessMessage::eIllegalOperand;
1884 break;
1885 case ILL_ILLADR:
1886 reason = ProcessMessage::eIllegalAddressingMode;
1887 break;
1888 case ILL_ILLTRP:
1889 reason = ProcessMessage::eIllegalTrap;
1890 break;
1891 case ILL_PRVOPC:
1892 reason = ProcessMessage::ePrivilegedOpcode;
1893 break;
1894 case ILL_PRVREG:
1895 reason = ProcessMessage::ePrivilegedRegister;
1896 break;
1897 case ILL_COPROC:
1898 reason = ProcessMessage::eCoprocessorError;
1899 break;
1900 case ILL_BADSTK:
1901 reason = ProcessMessage::eInternalStackError;
1902 break;
1903 }
1904
1905 return reason;
1906}
1907
1908ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001909ProcessMonitor::GetCrashReasonForSIGFPE(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001910{
1911 ProcessMessage::CrashReason reason;
1912 assert(info->si_signo == SIGFPE);
1913
1914 reason = ProcessMessage::eInvalidCrashReason;
1915
1916 switch (info->si_code)
1917 {
1918 default:
1919 assert(false && "unexpected si_code for SIGFPE");
1920 break;
1921 case FPE_INTDIV:
1922 reason = ProcessMessage::eIntegerDivideByZero;
1923 break;
1924 case FPE_INTOVF:
1925 reason = ProcessMessage::eIntegerOverflow;
1926 break;
1927 case FPE_FLTDIV:
1928 reason = ProcessMessage::eFloatDivideByZero;
1929 break;
1930 case FPE_FLTOVF:
1931 reason = ProcessMessage::eFloatOverflow;
1932 break;
1933 case FPE_FLTUND:
1934 reason = ProcessMessage::eFloatUnderflow;
1935 break;
1936 case FPE_FLTRES:
1937 reason = ProcessMessage::eFloatInexactResult;
1938 break;
1939 case FPE_FLTINV:
1940 reason = ProcessMessage::eFloatInvalidOperation;
1941 break;
1942 case FPE_FLTSUB:
1943 reason = ProcessMessage::eFloatSubscriptRange;
1944 break;
1945 }
1946
1947 return reason;
1948}
1949
1950ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001951ProcessMonitor::GetCrashReasonForSIGBUS(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001952{
1953 ProcessMessage::CrashReason reason;
1954 assert(info->si_signo == SIGBUS);
1955
1956 reason = ProcessMessage::eInvalidCrashReason;
1957
1958 switch (info->si_code)
1959 {
1960 default:
1961 assert(false && "unexpected si_code for SIGBUS");
1962 break;
1963 case BUS_ADRALN:
1964 reason = ProcessMessage::eIllegalAlignment;
1965 break;
1966 case BUS_ADRERR:
1967 reason = ProcessMessage::eIllegalAddress;
1968 break;
1969 case BUS_OBJERR:
1970 reason = ProcessMessage::eHardwareError;
1971 break;
1972 }
1973
1974 return reason;
1975}
1976
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001977void
Johnny Chen25e68e32011-06-14 19:19:50 +00001978ProcessMonitor::ServeOperation(OperationArgs *args)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001979{
Stephen Wilson570243b2011-01-19 01:37:06 +00001980 ProcessMonitor *monitor = args->m_monitor;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001981
Stephen Wilson570243b2011-01-19 01:37:06 +00001982 // We are finised with the arguments and are ready to go. Sync with the
1983 // parent thread and start serving operations on the inferior.
1984 sem_post(&args->m_semaphore);
1985
Michael Sartain704bf892013-10-09 01:28:57 +00001986 for(;;)
1987 {
Daniel Malea1efb4182013-09-16 23:12:18 +00001988 // wait for next pending operation
1989 sem_wait(&monitor->m_operation_pending);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001990
Daniel Malea1efb4182013-09-16 23:12:18 +00001991 monitor->m_operation->Execute(monitor);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001992
Daniel Malea1efb4182013-09-16 23:12:18 +00001993 // notify calling thread that operation is complete
1994 sem_post(&monitor->m_operation_done);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001995 }
1996}
1997
1998void
1999ProcessMonitor::DoOperation(Operation *op)
2000{
Daniel Malea1efb4182013-09-16 23:12:18 +00002001 Mutex::Locker lock(m_operation_mutex);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002002
Daniel Malea1efb4182013-09-16 23:12:18 +00002003 m_operation = op;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002004
Daniel Malea1efb4182013-09-16 23:12:18 +00002005 // notify operation thread that an operation is ready to be processed
2006 sem_post(&m_operation_pending);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002007
Daniel Malea1efb4182013-09-16 23:12:18 +00002008 // wait for operation to complete
2009 sem_wait(&m_operation_done);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002010}
2011
2012size_t
2013ProcessMonitor::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
2014 Error &error)
2015{
2016 size_t result;
2017 ReadOperation op(vm_addr, buf, size, error, result);
2018 DoOperation(&op);
2019 return result;
2020}
2021
2022size_t
2023ProcessMonitor::WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
2024 lldb_private::Error &error)
2025{
2026 size_t result;
2027 WriteOperation op(vm_addr, buf, size, error, result);
2028 DoOperation(&op);
2029 return result;
2030}
2031
2032bool
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00002033ProcessMonitor::ReadRegisterValue(lldb::tid_t tid, unsigned offset, const char* reg_name,
Matt Kopec7de48462013-03-06 17:20:48 +00002034 unsigned size, RegisterValue &value)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002035{
2036 bool result;
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00002037 ReadRegOperation op(tid, offset, reg_name, value, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002038 DoOperation(&op);
2039 return result;
2040}
2041
2042bool
Matt Kopec7de48462013-03-06 17:20:48 +00002043ProcessMonitor::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00002044 const char* reg_name, const RegisterValue &value)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002045{
2046 bool result;
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00002047 WriteRegOperation op(tid, offset, reg_name, value, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002048 DoOperation(&op);
2049 return result;
2050}
2051
2052bool
Matt Kopec7de48462013-03-06 17:20:48 +00002053ProcessMonitor::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size)
Stephen Wilsonade1aea2011-01-19 01:31:38 +00002054{
2055 bool result;
Matt Kopec7de48462013-03-06 17:20:48 +00002056 ReadGPROperation op(tid, buf, buf_size, result);
Stephen Wilsonade1aea2011-01-19 01:31:38 +00002057 DoOperation(&op);
2058 return result;
2059}
2060
2061bool
Matt Kopec7de48462013-03-06 17:20:48 +00002062ProcessMonitor::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size)
Stephen Wilsonade1aea2011-01-19 01:31:38 +00002063{
2064 bool result;
Matt Kopec7de48462013-03-06 17:20:48 +00002065 ReadFPROperation op(tid, buf, buf_size, result);
Stephen Wilsonade1aea2011-01-19 01:31:38 +00002066 DoOperation(&op);
2067 return result;
2068}
2069
2070bool
Matt Kopec58c0b962013-03-20 20:34:35 +00002071ProcessMonitor::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
2072{
2073 bool result;
2074 ReadRegisterSetOperation op(tid, buf, buf_size, regset, result);
2075 DoOperation(&op);
2076 return result;
2077}
2078
2079bool
Matt Kopec7de48462013-03-06 17:20:48 +00002080ProcessMonitor::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size)
Peter Collingbourne10bc0102011-06-03 20:41:02 +00002081{
2082 bool result;
Matt Kopec7de48462013-03-06 17:20:48 +00002083 WriteGPROperation op(tid, buf, buf_size, result);
Peter Collingbourne10bc0102011-06-03 20:41:02 +00002084 DoOperation(&op);
2085 return result;
2086}
2087
2088bool
Matt Kopec7de48462013-03-06 17:20:48 +00002089ProcessMonitor::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size)
Peter Collingbourne10bc0102011-06-03 20:41:02 +00002090{
2091 bool result;
Matt Kopec7de48462013-03-06 17:20:48 +00002092 WriteFPROperation op(tid, buf, buf_size, result);
Peter Collingbourne10bc0102011-06-03 20:41:02 +00002093 DoOperation(&op);
2094 return result;
2095}
2096
2097bool
Matt Kopec58c0b962013-03-20 20:34:35 +00002098ProcessMonitor::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
2099{
2100 bool result;
2101 WriteRegisterSetOperation op(tid, buf, buf_size, regset, result);
2102 DoOperation(&op);
2103 return result;
2104}
2105
2106bool
Stephen Wilson84ffe702011-03-30 15:55:52 +00002107ProcessMonitor::Resume(lldb::tid_t tid, uint32_t signo)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002108{
2109 bool result;
Andrew Kaylor93132f52013-05-28 23:04:25 +00002110 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
2111
2112 if (log)
2113 log->Printf ("ProcessMonitor::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid,
2114 m_process->GetUnixSignals().GetSignalAsCString (signo));
Stephen Wilson84ffe702011-03-30 15:55:52 +00002115 ResumeOperation op(tid, signo, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002116 DoOperation(&op);
Andrew Kaylor93132f52013-05-28 23:04:25 +00002117 if (log)
2118 log->Printf ("ProcessMonitor::%s() resuming result = %s", __FUNCTION__, result ? "true" : "false");
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002119 return result;
2120}
2121
2122bool
Stephen Wilson84ffe702011-03-30 15:55:52 +00002123ProcessMonitor::SingleStep(lldb::tid_t tid, uint32_t signo)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002124{
2125 bool result;
Stephen Wilson84ffe702011-03-30 15:55:52 +00002126 SingleStepOperation op(tid, signo, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002127 DoOperation(&op);
2128 return result;
2129}
2130
2131bool
2132ProcessMonitor::BringProcessIntoLimbo()
2133{
2134 bool result;
2135 KillOperation op(result);
2136 DoOperation(&op);
2137 return result;
2138}
2139
2140bool
Daniel Maleaa35970a2012-11-23 18:09:58 +00002141ProcessMonitor::GetSignalInfo(lldb::tid_t tid, void *siginfo, int &ptrace_err)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002142{
2143 bool result;
Daniel Maleaa35970a2012-11-23 18:09:58 +00002144 SiginfoOperation op(tid, siginfo, result, ptrace_err);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002145 DoOperation(&op);
2146 return result;
2147}
2148
2149bool
2150ProcessMonitor::GetEventMessage(lldb::tid_t tid, unsigned long *message)
2151{
2152 bool result;
2153 EventMessageOperation op(tid, message, result);
2154 DoOperation(&op);
2155 return result;
2156}
2157
Greg Clayton743ecf42012-10-16 20:20:18 +00002158lldb_private::Error
Matt Kopec085d6ce2013-05-31 22:00:07 +00002159ProcessMonitor::Detach(lldb::tid_t tid)
Stephen Wilson84ffe702011-03-30 15:55:52 +00002160{
Greg Clayton28041352011-11-29 20:50:10 +00002161 lldb_private::Error error;
Matt Kopec085d6ce2013-05-31 22:00:07 +00002162 if (tid != LLDB_INVALID_THREAD_ID)
2163 {
2164 DetachOperation op(tid, error);
Greg Clayton743ecf42012-10-16 20:20:18 +00002165 DoOperation(&op);
2166 }
Greg Clayton743ecf42012-10-16 20:20:18 +00002167 return error;
Greg Clayton542e4072012-09-07 17:49:29 +00002168}
Stephen Wilson84ffe702011-03-30 15:55:52 +00002169
2170bool
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002171ProcessMonitor::DupDescriptor(const char *path, int fd, int flags)
2172{
Peter Collingbourne62343202011-06-14 03:55:54 +00002173 int target_fd = open(path, flags, 0666);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002174
2175 if (target_fd == -1)
2176 return false;
2177
Peter Collingbourne62343202011-06-14 03:55:54 +00002178 return (dup2(target_fd, fd) == -1) ? false : true;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002179}
Stephen Wilson9212d7f2011-01-04 21:40:25 +00002180
2181void
2182ProcessMonitor::StopMonitoringChildProcess()
2183{
2184 lldb::thread_result_t thread_result;
2185
Stephen Wilsond4182f42011-02-09 20:10:35 +00002186 if (IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
Stephen Wilson9212d7f2011-01-04 21:40:25 +00002187 {
2188 Host::ThreadCancel(m_monitor_thread, NULL);
2189 Host::ThreadJoin(m_monitor_thread, &thread_result, NULL);
2190 m_monitor_thread = LLDB_INVALID_HOST_THREAD;
2191 }
2192}
Stephen Wilson84ffe702011-03-30 15:55:52 +00002193
2194void
2195ProcessMonitor::StopMonitor()
2196{
2197 StopMonitoringChildProcess();
Greg Clayton743ecf42012-10-16 20:20:18 +00002198 StopOpThread();
Daniel Malea1efb4182013-09-16 23:12:18 +00002199 sem_destroy(&m_operation_pending);
2200 sem_destroy(&m_operation_done);
2201
Andrew Kaylor5e268992013-09-14 00:17:31 +00002202 // Note: ProcessPOSIX passes the m_terminal_fd file descriptor to
2203 // Process::SetSTDIOFileDescriptor, which in turn transfers ownership of
2204 // the descriptor to a ConnectionFileDescriptor object. Consequently
2205 // even though still has the file descriptor, we shouldn't close it here.
Stephen Wilson84ffe702011-03-30 15:55:52 +00002206}
2207
2208void
Greg Clayton743ecf42012-10-16 20:20:18 +00002209ProcessMonitor::StopOpThread()
2210{
2211 lldb::thread_result_t result;
2212
2213 if (!IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
2214 return;
2215
2216 Host::ThreadCancel(m_operation_thread, NULL);
2217 Host::ThreadJoin(m_operation_thread, &result, NULL);
Daniel Malea8b9e71e2012-11-22 18:21:05 +00002218 m_operation_thread = LLDB_INVALID_HOST_THREAD;
Greg Clayton743ecf42012-10-16 20:20:18 +00002219}