blob: 2e6c55f45c99b6887aa11d3fcdd76e8a37299c06 [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
40
Greg Clayton386ff182011-11-05 01:09:16 +000041#define DEBUG_PTRACE_MAXBYTES 20
42
Matt Kopec58c0b962013-03-20 20:34:35 +000043// Support ptrace extensions even when compiled without required kernel support
44#ifndef PTRACE_GETREGSET
45 #define PTRACE_GETREGSET 0x4204
46#endif
47#ifndef PTRACE_SETREGSET
48 #define PTRACE_SETREGSET 0x4205
49#endif
50
Matt Kopece9ea0da2013-05-07 19:29:28 +000051// Support hardware breakpoints in case it has not been defined
52#ifndef TRAP_HWBKPT
53 #define TRAP_HWBKPT 4
54#endif
55
Andrew Kaylor93132f52013-05-28 23:04:25 +000056// Try to define a macro to encapsulate the tgkill syscall
57// fall back on kill() if tgkill isn't available
58#define tgkill(pid, tid, sig) syscall(SYS_tgkill, pid, tid, sig)
59
Stephen Wilsone6f9f662010-07-24 02:19:04 +000060using namespace lldb_private;
61
Johnny Chen0d5f2d42011-10-18 18:09:30 +000062// FIXME: this code is host-dependent with respect to types and
63// endianness and needs to be fixed. For example, lldb::addr_t is
64// hard-coded to uint64_t, but on a 32-bit Linux host, ptrace requires
65// 32-bit pointer arguments. This code uses casts to work around the
66// problem.
67
68// We disable the tracing of ptrace calls for integration builds to
69// avoid the additional indirection and checks.
70#ifndef LLDB_CONFIGURATION_BUILDANDINTEGRATION
71
Greg Clayton386ff182011-11-05 01:09:16 +000072static void
73DisplayBytes (lldb_private::StreamString &s, void *bytes, uint32_t count)
74{
75 uint8_t *ptr = (uint8_t *)bytes;
76 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
77 for(uint32_t i=0; i<loop_count; i++)
78 {
79 s.Printf ("[%x]", *ptr);
80 ptr++;
81 }
82}
83
Matt Kopec58c0b962013-03-20 20:34:35 +000084static void PtraceDisplayBytes(int &req, void *data, size_t data_size)
Greg Clayton386ff182011-11-05 01:09:16 +000085{
86 StreamString buf;
Ashok Thirumurthi01186352013-03-28 16:02:31 +000087 Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
Johnny Chen30213ff2012-01-05 19:17:38 +000088 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
Greg Clayton386ff182011-11-05 01:09:16 +000089
90 if (verbose_log)
91 {
92 switch(req)
93 {
94 case PTRACE_POKETEXT:
95 {
96 DisplayBytes(buf, &data, 8);
97 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
98 break;
99 }
Greg Clayton542e4072012-09-07 17:49:29 +0000100 case PTRACE_POKEDATA:
Greg Clayton386ff182011-11-05 01:09:16 +0000101 {
102 DisplayBytes(buf, &data, 8);
103 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
104 break;
105 }
Greg Clayton542e4072012-09-07 17:49:29 +0000106 case PTRACE_POKEUSER:
Greg Clayton386ff182011-11-05 01:09:16 +0000107 {
108 DisplayBytes(buf, &data, 8);
109 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
110 break;
111 }
Greg Clayton542e4072012-09-07 17:49:29 +0000112 case PTRACE_SETREGS:
Greg Clayton386ff182011-11-05 01:09:16 +0000113 {
Matt Kopec7de48462013-03-06 17:20:48 +0000114 DisplayBytes(buf, data, data_size);
Greg Clayton386ff182011-11-05 01:09:16 +0000115 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
116 break;
117 }
118 case PTRACE_SETFPREGS:
119 {
Matt Kopec7de48462013-03-06 17:20:48 +0000120 DisplayBytes(buf, data, data_size);
Greg Clayton386ff182011-11-05 01:09:16 +0000121 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
122 break;
123 }
Greg Clayton542e4072012-09-07 17:49:29 +0000124 case PTRACE_SETSIGINFO:
Greg Clayton386ff182011-11-05 01:09:16 +0000125 {
126 DisplayBytes(buf, data, sizeof(siginfo_t));
127 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
128 break;
129 }
Matt Kopec58c0b962013-03-20 20:34:35 +0000130 case PTRACE_SETREGSET:
131 {
132 // Extract iov_base from data, which is a pointer to the struct IOVEC
133 DisplayBytes(buf, *(void **)data, data_size);
134 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
135 break;
136 }
Greg Clayton386ff182011-11-05 01:09:16 +0000137 default:
138 {
139 }
140 }
141 }
142}
143
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000144// Wrapper for ptrace to catch errors and log calls.
Ashok Thirumurthi762fbd02013-03-27 21:09:30 +0000145// 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 +0000146extern long
Matt Kopec58c0b962013-03-20 20:34:35 +0000147PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size,
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000148 const char* reqName, const char* file, int line)
149{
Greg Clayton386ff182011-11-05 01:09:16 +0000150 long int result;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000151
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000152 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
Greg Clayton386ff182011-11-05 01:09:16 +0000153
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000154 if (log)
Matt Kopec58c0b962013-03-20 20:34:35 +0000155 log->Printf("ptrace(%s, %lu, %p, %p, %zu) called from file %s line %d",
Matt Kopec7de48462013-03-06 17:20:48 +0000156 reqName, pid, addr, data, data_size, file, line);
Greg Clayton542e4072012-09-07 17:49:29 +0000157
Matt Kopec7de48462013-03-06 17:20:48 +0000158 PtraceDisplayBytes(req, data, data_size);
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000159
160 errno = 0;
Matt Kopec58c0b962013-03-20 20:34:35 +0000161 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
162 result = ptrace(static_cast<__ptrace_request>(req), pid, *(unsigned int *)addr, data);
163 else
164 result = ptrace(static_cast<__ptrace_request>(req), pid, addr, data);
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000165
Matt Kopec7de48462013-03-06 17:20:48 +0000166 PtraceDisplayBytes(req, data, data_size);
Greg Clayton386ff182011-11-05 01:09:16 +0000167
Matt Kopec7de48462013-03-06 17:20:48 +0000168 if (log && errno != 0)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000169 {
170 const char* str;
171 switch (errno)
172 {
173 case ESRCH: str = "ESRCH"; break;
174 case EINVAL: str = "EINVAL"; break;
175 case EBUSY: str = "EBUSY"; break;
176 case EPERM: str = "EPERM"; break;
177 default: str = "<unknown>";
178 }
179 log->Printf("ptrace() failed; errno=%d (%s)", errno, str);
180 }
181
182 return result;
183}
184
Matt Kopec7de48462013-03-06 17:20:48 +0000185// Wrapper for ptrace when logging is not required.
186// Sets errno to 0 prior to calling ptrace.
187extern long
Matt Kopec58c0b962013-03-20 20:34:35 +0000188PtraceWrapper(int req, pid_t pid, void *addr, void *data, size_t data_size)
Matt Kopec7de48462013-03-06 17:20:48 +0000189{
Matt Kopec58c0b962013-03-20 20:34:35 +0000190 long result = 0;
Matt Kopec7de48462013-03-06 17:20:48 +0000191 errno = 0;
Matt Kopec58c0b962013-03-20 20:34:35 +0000192 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
193 result = ptrace(static_cast<__ptrace_request>(req), pid, *(unsigned int *)addr, data);
194 else
195 result = ptrace(static_cast<__ptrace_request>(req), pid, addr, data);
Matt Kopec7de48462013-03-06 17:20:48 +0000196 return result;
197}
198
199#define PTRACE(req, pid, addr, data, data_size) \
200 PtraceWrapper((req), (pid), (addr), (data), (data_size), #req, __FILE__, __LINE__)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000201#else
Matt Kopec7de48462013-03-06 17:20:48 +0000202 PtraceWrapper((req), (pid), (addr), (data), (data_size))
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000203#endif
204
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000205//------------------------------------------------------------------------------
206// Static implementations of ProcessMonitor::ReadMemory and
207// ProcessMonitor::WriteMemory. This enables mutual recursion between these
208// functions without needed to go thru the thread funnel.
209
210static size_t
Greg Clayton542e4072012-09-07 17:49:29 +0000211DoReadMemory(lldb::pid_t pid,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000212 lldb::addr_t vm_addr, void *buf, size_t size, Error &error)
213{
Greg Clayton542e4072012-09-07 17:49:29 +0000214 // ptrace word size is determined by the host, not the child
215 static const unsigned word_size = sizeof(void*);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000216 unsigned char *dst = static_cast<unsigned char*>(buf);
217 size_t bytes_read;
218 size_t remainder;
219 long data;
220
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000221 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000222 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000223 ProcessPOSIXLog::IncNestLevel();
224 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
Daniel Malead01b2952012-11-29 21:49:15 +0000225 log->Printf ("ProcessMonitor::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000226 pid, word_size, (void*)vm_addr, buf, size);
227
228 assert(sizeof(data) >= word_size);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000229 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
230 {
231 errno = 0;
Matt Kopec7de48462013-03-06 17:20:48 +0000232 data = PTRACE(PTRACE_PEEKDATA, pid, (void*)vm_addr, NULL, 0);
233 if (errno)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000234 {
235 error.SetErrorToErrno();
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000236 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000237 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000238 return bytes_read;
239 }
240
241 remainder = size - bytes_read;
242 remainder = remainder > word_size ? word_size : remainder;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000243
244 // Copy the data into our buffer
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000245 for (unsigned i = 0; i < remainder; ++i)
246 dst[i] = ((data >> i*8) & 0xFF);
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000247
Johnny Chen30213ff2012-01-05 19:17:38 +0000248 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
249 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
250 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
251 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
Daniel Maleac63dddd2012-12-14 21:07:07 +0000252 {
253 uintptr_t print_dst = 0;
254 // Format bytes from data by moving into print_dst for log output
255 for (unsigned i = 0; i < remainder; ++i)
256 print_dst |= (((data >> i*8) & 0xFF) << i*8);
257 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
258 (void*)vm_addr, print_dst, (unsigned long)data);
259 }
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000260
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000261 vm_addr += word_size;
262 dst += word_size;
263 }
264
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000265 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000266 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000267 return bytes_read;
268}
269
270static size_t
Greg Clayton542e4072012-09-07 17:49:29 +0000271DoWriteMemory(lldb::pid_t pid,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000272 lldb::addr_t vm_addr, const void *buf, size_t size, Error &error)
273{
Greg Clayton542e4072012-09-07 17:49:29 +0000274 // ptrace word size is determined by the host, not the child
275 static const unsigned word_size = sizeof(void*);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000276 const unsigned char *src = static_cast<const unsigned char*>(buf);
277 size_t bytes_written = 0;
278 size_t remainder;
279
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000280 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000281 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000282 ProcessPOSIXLog::IncNestLevel();
283 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
Daniel Malead01b2952012-11-29 21:49:15 +0000284 log->Printf ("ProcessMonitor::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__,
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000285 pid, word_size, (void*)vm_addr, buf, size);
286
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000287 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
288 {
289 remainder = size - bytes_written;
290 remainder = remainder > word_size ? word_size : remainder;
291
292 if (remainder == word_size)
293 {
294 unsigned long data = 0;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000295 assert(sizeof(data) >= word_size);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000296 for (unsigned i = 0; i < word_size; ++i)
297 data |= (unsigned long)src[i] << i*8;
298
Johnny Chen30213ff2012-01-05 19:17:38 +0000299 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
300 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
301 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
302 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000303 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
304 (void*)vm_addr, *(unsigned long*)src, data);
305
Matt Kopec7de48462013-03-06 17:20:48 +0000306 if (PTRACE(PTRACE_POKEDATA, pid, (void*)vm_addr, (void*)data, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000307 {
308 error.SetErrorToErrno();
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000309 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000310 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000311 return bytes_written;
312 }
313 }
314 else
315 {
316 unsigned char buff[8];
Greg Clayton542e4072012-09-07 17:49:29 +0000317 if (DoReadMemory(pid, vm_addr,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000318 buff, word_size, error) != word_size)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000319 {
320 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000321 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000322 return bytes_written;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000323 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000324
325 memcpy(buff, src, remainder);
326
Greg Clayton542e4072012-09-07 17:49:29 +0000327 if (DoWriteMemory(pid, vm_addr,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000328 buff, word_size, error) != word_size)
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000329 {
330 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000331 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000332 return bytes_written;
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000333 }
334
Johnny Chen30213ff2012-01-05 19:17:38 +0000335 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
336 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
337 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
338 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000339 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
340 (void*)vm_addr, *(unsigned long*)src, *(unsigned long*)buff);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000341 }
342
343 vm_addr += word_size;
344 src += word_size;
345 }
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000346 if (log)
Johnny Chen30213ff2012-01-05 19:17:38 +0000347 ProcessPOSIXLog::DecNestLevel();
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000348 return bytes_written;
349}
350
Stephen Wilson26977162011-03-23 02:14:42 +0000351// Simple helper function to ensure flags are enabled on the given file
352// descriptor.
353static bool
354EnsureFDFlags(int fd, int flags, Error &error)
355{
356 int status;
357
358 if ((status = fcntl(fd, F_GETFL)) == -1)
359 {
360 error.SetErrorToErrno();
361 return false;
362 }
363
364 if (fcntl(fd, F_SETFL, status | flags) == -1)
365 {
366 error.SetErrorToErrno();
367 return false;
368 }
369
370 return true;
371}
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000372
373//------------------------------------------------------------------------------
374/// @class Operation
375/// @brief Represents a ProcessMonitor operation.
376///
377/// Under Linux, it is not possible to ptrace() from any other thread but the
378/// one that spawned or attached to the process from the start. Therefore, when
379/// a ProcessMonitor is asked to deliver or change the state of an inferior
380/// process the operation must be "funneled" to a specific thread to perform the
381/// task. The Operation class provides an abstract base for all services the
382/// ProcessMonitor must perform via the single virtual function Execute, thus
383/// encapsulating the code that needs to run in the privileged context.
384class Operation
385{
386public:
Daniel Maleadd15b782013-05-13 17:32:07 +0000387 virtual ~Operation() {}
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000388 virtual void Execute(ProcessMonitor *monitor) = 0;
389};
390
391//------------------------------------------------------------------------------
392/// @class ReadOperation
393/// @brief Implements ProcessMonitor::ReadMemory.
394class ReadOperation : public Operation
395{
396public:
397 ReadOperation(lldb::addr_t addr, void *buff, size_t size,
398 Error &error, size_t &result)
399 : m_addr(addr), m_buff(buff), m_size(size),
400 m_error(error), m_result(result)
401 { }
402
403 void Execute(ProcessMonitor *monitor);
404
405private:
406 lldb::addr_t m_addr;
407 void *m_buff;
408 size_t m_size;
409 Error &m_error;
410 size_t &m_result;
411};
412
413void
414ReadOperation::Execute(ProcessMonitor *monitor)
415{
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000416 lldb::pid_t pid = monitor->GetPID();
417
Greg Clayton542e4072012-09-07 17:49:29 +0000418 m_result = DoReadMemory(pid, m_addr, m_buff, m_size, m_error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000419}
420
421//------------------------------------------------------------------------------
Ed Mastea56115f2013-07-17 14:30:26 +0000422/// @class WriteOperation
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000423/// @brief Implements ProcessMonitor::WriteMemory.
424class WriteOperation : public Operation
425{
426public:
427 WriteOperation(lldb::addr_t addr, const void *buff, size_t size,
428 Error &error, size_t &result)
429 : m_addr(addr), m_buff(buff), m_size(size),
430 m_error(error), m_result(result)
431 { }
432
433 void Execute(ProcessMonitor *monitor);
434
435private:
436 lldb::addr_t m_addr;
437 const void *m_buff;
438 size_t m_size;
439 Error &m_error;
440 size_t &m_result;
441};
442
443void
444WriteOperation::Execute(ProcessMonitor *monitor)
445{
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000446 lldb::pid_t pid = monitor->GetPID();
447
Greg Clayton542e4072012-09-07 17:49:29 +0000448 m_result = DoWriteMemory(pid, m_addr, m_buff, m_size, m_error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000449}
450
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000451
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000452//------------------------------------------------------------------------------
453/// @class ReadRegOperation
454/// @brief Implements ProcessMonitor::ReadRegisterValue.
455class ReadRegOperation : public Operation
456{
457public:
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000458 ReadRegOperation(lldb::tid_t tid, unsigned offset, const char *reg_name,
Daniel Maleaf0da3712012-12-18 19:50:15 +0000459 RegisterValue &value, bool &result)
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000460 : m_tid(tid), m_offset(offset), m_reg_name(reg_name),
Daniel Maleaf0da3712012-12-18 19:50:15 +0000461 m_value(value), m_result(result)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000462 { }
463
464 void Execute(ProcessMonitor *monitor);
465
466private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000467 lldb::tid_t m_tid;
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000468 uintptr_t m_offset;
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000469 const char *m_reg_name;
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000470 RegisterValue &m_value;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000471 bool &m_result;
472};
473
474void
475ReadRegOperation::Execute(ProcessMonitor *monitor)
476{
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000477 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000478
479 // Set errno to zero so that we can detect a failed peek.
480 errno = 0;
Matt Kopec7de48462013-03-06 17:20:48 +0000481 lldb::addr_t data = PTRACE(PTRACE_PEEKUSER, m_tid, (void*)m_offset, NULL, 0);
482 if (errno)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000483 m_result = false;
484 else
485 {
486 m_value = data;
487 m_result = true;
488 }
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000489 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000490 log->Printf ("ProcessMonitor::%s() reg %s: 0x%" PRIx64, __FUNCTION__,
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000491 m_reg_name, data);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000492}
493
494//------------------------------------------------------------------------------
495/// @class WriteRegOperation
496/// @brief Implements ProcessMonitor::WriteRegisterValue.
497class WriteRegOperation : public Operation
498{
499public:
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000500 WriteRegOperation(lldb::tid_t tid, unsigned offset, const char *reg_name,
Daniel Maleaf0da3712012-12-18 19:50:15 +0000501 const RegisterValue &value, bool &result)
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000502 : m_tid(tid), m_offset(offset), m_reg_name(reg_name),
Daniel Maleaf0da3712012-12-18 19:50:15 +0000503 m_value(value), m_result(result)
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000504 { }
505
506 void Execute(ProcessMonitor *monitor);
507
508private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000509 lldb::tid_t m_tid;
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000510 uintptr_t m_offset;
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000511 const char *m_reg_name;
Johnny Chen13e8e1c2011-05-13 21:29:50 +0000512 const RegisterValue &m_value;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000513 bool &m_result;
514};
515
516void
517WriteRegOperation::Execute(ProcessMonitor *monitor)
518{
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000519 void* buf;
Ashok Thirumurthi01186352013-03-28 16:02:31 +0000520 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000521
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000522#if __WORDSIZE == 32
523 buf = (void*) m_value.GetAsUInt32();
524#else
525 buf = (void*) m_value.GetAsUInt64();
526#endif
Johnny Chen0d5f2d42011-10-18 18:09:30 +0000527
528 if (log)
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +0000529 log->Printf ("ProcessMonitor::%s() reg %s: %p", __FUNCTION__, m_reg_name, buf);
Matt Kopec7de48462013-03-06 17:20:48 +0000530 if (PTRACE(PTRACE_POKEUSER, m_tid, (void*)m_offset, buf, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000531 m_result = false;
532 else
533 m_result = true;
534}
535
536//------------------------------------------------------------------------------
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000537/// @class ReadGPROperation
538/// @brief Implements ProcessMonitor::ReadGPR.
539class ReadGPROperation : public Operation
540{
541public:
Matt Kopec7de48462013-03-06 17:20:48 +0000542 ReadGPROperation(lldb::tid_t tid, void *buf, size_t buf_size, bool &result)
543 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_result(result)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000544 { }
545
546 void Execute(ProcessMonitor *monitor);
547
548private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000549 lldb::tid_t m_tid;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000550 void *m_buf;
Matt Kopec7de48462013-03-06 17:20:48 +0000551 size_t m_buf_size;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000552 bool &m_result;
553};
554
555void
556ReadGPROperation::Execute(ProcessMonitor *monitor)
557{
Matt Kopec7de48462013-03-06 17:20:48 +0000558 if (PTRACE(PTRACE_GETREGS, m_tid, NULL, m_buf, m_buf_size) < 0)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000559 m_result = false;
560 else
561 m_result = true;
562}
563
564//------------------------------------------------------------------------------
565/// @class ReadFPROperation
566/// @brief Implements ProcessMonitor::ReadFPR.
567class ReadFPROperation : public Operation
568{
569public:
Matt Kopec7de48462013-03-06 17:20:48 +0000570 ReadFPROperation(lldb::tid_t tid, void *buf, size_t buf_size, bool &result)
571 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_result(result)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000572 { }
573
574 void Execute(ProcessMonitor *monitor);
575
576private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000577 lldb::tid_t m_tid;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000578 void *m_buf;
Matt Kopec7de48462013-03-06 17:20:48 +0000579 size_t m_buf_size;
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000580 bool &m_result;
581};
582
583void
584ReadFPROperation::Execute(ProcessMonitor *monitor)
585{
Matt Kopec7de48462013-03-06 17:20:48 +0000586 if (PTRACE(PTRACE_GETFPREGS, m_tid, NULL, m_buf, m_buf_size) < 0)
Stephen Wilsonade1aea2011-01-19 01:31:38 +0000587 m_result = false;
588 else
589 m_result = true;
590}
591
592//------------------------------------------------------------------------------
Matt Kopec58c0b962013-03-20 20:34:35 +0000593/// @class ReadRegisterSetOperation
594/// @brief Implements ProcessMonitor::ReadRegisterSet.
595class ReadRegisterSetOperation : public Operation
596{
597public:
598 ReadRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset, bool &result)
599 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset), m_result(result)
600 { }
601
602 void Execute(ProcessMonitor *monitor);
603
604private:
605 lldb::tid_t m_tid;
606 void *m_buf;
607 size_t m_buf_size;
608 const unsigned int m_regset;
609 bool &m_result;
610};
611
612void
613ReadRegisterSetOperation::Execute(ProcessMonitor *monitor)
614{
615 if (PTRACE(PTRACE_GETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size) < 0)
616 m_result = false;
617 else
618 m_result = true;
619}
620
621//------------------------------------------------------------------------------
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000622/// @class WriteGPROperation
623/// @brief Implements ProcessMonitor::WriteGPR.
624class WriteGPROperation : public Operation
625{
626public:
Matt Kopec7de48462013-03-06 17:20:48 +0000627 WriteGPROperation(lldb::tid_t tid, void *buf, size_t buf_size, bool &result)
628 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_result(result)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000629 { }
630
631 void Execute(ProcessMonitor *monitor);
632
633private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000634 lldb::tid_t m_tid;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000635 void *m_buf;
Matt Kopec7de48462013-03-06 17:20:48 +0000636 size_t m_buf_size;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000637 bool &m_result;
638};
639
640void
641WriteGPROperation::Execute(ProcessMonitor *monitor)
642{
Matt Kopec7de48462013-03-06 17:20:48 +0000643 if (PTRACE(PTRACE_SETREGS, m_tid, NULL, m_buf, m_buf_size) < 0)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000644 m_result = false;
645 else
646 m_result = true;
647}
648
649//------------------------------------------------------------------------------
650/// @class WriteFPROperation
651/// @brief Implements ProcessMonitor::WriteFPR.
652class WriteFPROperation : public Operation
653{
654public:
Matt Kopec7de48462013-03-06 17:20:48 +0000655 WriteFPROperation(lldb::tid_t tid, void *buf, size_t buf_size, bool &result)
656 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_result(result)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000657 { }
658
659 void Execute(ProcessMonitor *monitor);
660
661private:
Daniel Maleaf0da3712012-12-18 19:50:15 +0000662 lldb::tid_t m_tid;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000663 void *m_buf;
Matt Kopec7de48462013-03-06 17:20:48 +0000664 size_t m_buf_size;
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000665 bool &m_result;
666};
667
668void
669WriteFPROperation::Execute(ProcessMonitor *monitor)
670{
Matt Kopec7de48462013-03-06 17:20:48 +0000671 if (PTRACE(PTRACE_SETFPREGS, m_tid, NULL, m_buf, m_buf_size) < 0)
Peter Collingbourne10bc0102011-06-03 20:41:02 +0000672 m_result = false;
673 else
674 m_result = true;
675}
676
677//------------------------------------------------------------------------------
Matt Kopec58c0b962013-03-20 20:34:35 +0000678/// @class WriteRegisterSetOperation
679/// @brief Implements ProcessMonitor::WriteRegisterSet.
680class WriteRegisterSetOperation : public Operation
681{
682public:
683 WriteRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset, bool &result)
684 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset), m_result(result)
685 { }
686
687 void Execute(ProcessMonitor *monitor);
688
689private:
690 lldb::tid_t m_tid;
691 void *m_buf;
692 size_t m_buf_size;
693 const unsigned int m_regset;
694 bool &m_result;
695};
696
697void
698WriteRegisterSetOperation::Execute(ProcessMonitor *monitor)
699{
700 if (PTRACE(PTRACE_SETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size) < 0)
701 m_result = false;
702 else
703 m_result = true;
704}
705
706//------------------------------------------------------------------------------
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000707/// @class ResumeOperation
708/// @brief Implements ProcessMonitor::Resume.
709class ResumeOperation : public Operation
710{
711public:
Stephen Wilson84ffe702011-03-30 15:55:52 +0000712 ResumeOperation(lldb::tid_t tid, uint32_t signo, bool &result) :
713 m_tid(tid), m_signo(signo), m_result(result) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000714
715 void Execute(ProcessMonitor *monitor);
716
717private:
718 lldb::tid_t m_tid;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000719 uint32_t m_signo;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000720 bool &m_result;
721};
722
723void
724ResumeOperation::Execute(ProcessMonitor *monitor)
725{
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000726 intptr_t data = 0;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000727
728 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
729 data = m_signo;
730
Matt Kopec7de48462013-03-06 17:20:48 +0000731 if (PTRACE(PTRACE_CONT, m_tid, NULL, (void*)data, 0))
Andrew Kaylor93132f52013-05-28 23:04:25 +0000732 {
733 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
734
735 if (log)
736 log->Printf ("ResumeOperation (%" PRIu64 ") failed: %s", m_tid, strerror(errno));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000737 m_result = false;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000738 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000739 else
740 m_result = true;
741}
742
743//------------------------------------------------------------------------------
Ed Maste428a6782013-06-24 15:04:47 +0000744/// @class SingleStepOperation
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000745/// @brief Implements ProcessMonitor::SingleStep.
746class SingleStepOperation : public Operation
747{
748public:
Stephen Wilson84ffe702011-03-30 15:55:52 +0000749 SingleStepOperation(lldb::tid_t tid, uint32_t signo, bool &result)
750 : m_tid(tid), m_signo(signo), m_result(result) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000751
752 void Execute(ProcessMonitor *monitor);
753
754private:
755 lldb::tid_t m_tid;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000756 uint32_t m_signo;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000757 bool &m_result;
758};
759
760void
761SingleStepOperation::Execute(ProcessMonitor *monitor)
762{
Daniel Maleaa85e6b62012-12-07 22:21:08 +0000763 intptr_t data = 0;
Stephen Wilson84ffe702011-03-30 15:55:52 +0000764
765 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER)
766 data = m_signo;
767
Matt Kopec7de48462013-03-06 17:20:48 +0000768 if (PTRACE(PTRACE_SINGLESTEP, m_tid, NULL, (void*)data, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000769 m_result = false;
770 else
771 m_result = true;
772}
773
774//------------------------------------------------------------------------------
775/// @class SiginfoOperation
776/// @brief Implements ProcessMonitor::GetSignalInfo.
777class SiginfoOperation : public Operation
778{
779public:
Daniel Maleaa35970a2012-11-23 18:09:58 +0000780 SiginfoOperation(lldb::tid_t tid, void *info, bool &result, int &ptrace_err)
781 : m_tid(tid), m_info(info), m_result(result), m_err(ptrace_err) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000782
783 void Execute(ProcessMonitor *monitor);
784
785private:
786 lldb::tid_t m_tid;
787 void *m_info;
788 bool &m_result;
Daniel Maleaa35970a2012-11-23 18:09:58 +0000789 int &m_err;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000790};
791
792void
793SiginfoOperation::Execute(ProcessMonitor *monitor)
794{
Matt Kopec7de48462013-03-06 17:20:48 +0000795 if (PTRACE(PTRACE_GETSIGINFO, m_tid, NULL, m_info, 0)) {
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000796 m_result = false;
Daniel Maleaa35970a2012-11-23 18:09:58 +0000797 m_err = errno;
798 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000799 else
800 m_result = true;
801}
802
803//------------------------------------------------------------------------------
804/// @class EventMessageOperation
805/// @brief Implements ProcessMonitor::GetEventMessage.
806class EventMessageOperation : public Operation
807{
808public:
809 EventMessageOperation(lldb::tid_t tid, unsigned long *message, bool &result)
810 : m_tid(tid), m_message(message), m_result(result) { }
811
812 void Execute(ProcessMonitor *monitor);
813
814private:
815 lldb::tid_t m_tid;
816 unsigned long *m_message;
817 bool &m_result;
818};
819
820void
821EventMessageOperation::Execute(ProcessMonitor *monitor)
822{
Matt Kopec7de48462013-03-06 17:20:48 +0000823 if (PTRACE(PTRACE_GETEVENTMSG, m_tid, NULL, m_message, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000824 m_result = false;
825 else
826 m_result = true;
827}
828
829//------------------------------------------------------------------------------
830/// @class KillOperation
831/// @brief Implements ProcessMonitor::BringProcessIntoLimbo.
832class KillOperation : public Operation
833{
834public:
835 KillOperation(bool &result) : m_result(result) { }
836
837 void Execute(ProcessMonitor *monitor);
838
839private:
840 bool &m_result;
841};
842
843void
844KillOperation::Execute(ProcessMonitor *monitor)
845{
846 lldb::pid_t pid = monitor->GetPID();
847
Matt Kopec7de48462013-03-06 17:20:48 +0000848 if (PTRACE(PTRACE_KILL, pid, NULL, NULL, 0))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000849 m_result = false;
850 else
851 m_result = true;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000852}
853
Greg Clayton28041352011-11-29 20:50:10 +0000854//------------------------------------------------------------------------------
855/// @class KillOperation
856/// @brief Implements ProcessMonitor::BringProcessIntoLimbo.
857class DetachOperation : public Operation
858{
859public:
Matt Kopec085d6ce2013-05-31 22:00:07 +0000860 DetachOperation(lldb::tid_t tid, Error &result) : m_tid(tid), m_error(result) { }
Greg Clayton28041352011-11-29 20:50:10 +0000861
862 void Execute(ProcessMonitor *monitor);
863
864private:
Matt Kopec085d6ce2013-05-31 22:00:07 +0000865 lldb::tid_t m_tid;
Greg Clayton28041352011-11-29 20:50:10 +0000866 Error &m_error;
867};
868
869void
870DetachOperation::Execute(ProcessMonitor *monitor)
871{
Matt Kopec085d6ce2013-05-31 22:00:07 +0000872 if (ptrace(PT_DETACH, m_tid, NULL, 0) < 0)
Greg Clayton28041352011-11-29 20:50:10 +0000873 m_error.SetErrorToErrno();
Greg Clayton28041352011-11-29 20:50:10 +0000874}
875
Johnny Chen25e68e32011-06-14 19:19:50 +0000876ProcessMonitor::OperationArgs::OperationArgs(ProcessMonitor *monitor)
877 : m_monitor(monitor)
878{
879 sem_init(&m_semaphore, 0, 0);
880}
881
882ProcessMonitor::OperationArgs::~OperationArgs()
883{
884 sem_destroy(&m_semaphore);
885}
886
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000887ProcessMonitor::LaunchArgs::LaunchArgs(ProcessMonitor *monitor,
888 lldb_private::Module *module,
889 char const **argv,
890 char const **envp,
891 const char *stdin_path,
892 const char *stdout_path,
Daniel Malea6217d2a2013-01-08 14:49:22 +0000893 const char *stderr_path,
894 const char *working_dir)
Johnny Chen25e68e32011-06-14 19:19:50 +0000895 : OperationArgs(monitor),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000896 m_module(module),
897 m_argv(argv),
898 m_envp(envp),
899 m_stdin_path(stdin_path),
900 m_stdout_path(stdout_path),
Daniel Malea6217d2a2013-01-08 14:49:22 +0000901 m_stderr_path(stderr_path),
902 m_working_dir(working_dir) { }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000903
904ProcessMonitor::LaunchArgs::~LaunchArgs()
Johnny Chen25e68e32011-06-14 19:19:50 +0000905{ }
906
907ProcessMonitor::AttachArgs::AttachArgs(ProcessMonitor *monitor,
908 lldb::pid_t pid)
909 : OperationArgs(monitor), m_pid(pid) { }
910
911ProcessMonitor::AttachArgs::~AttachArgs()
912{ }
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000913
914//------------------------------------------------------------------------------
915/// The basic design of the ProcessMonitor is built around two threads.
916///
917/// One thread (@see SignalThread) simply blocks on a call to waitpid() looking
918/// for changes in the debugee state. When a change is detected a
919/// ProcessMessage is sent to the associated ProcessLinux instance. This thread
920/// "drives" state changes in the debugger.
921///
922/// The second thread (@see OperationThread) is responsible for two things 1)
Greg Clayton710dd5a2011-01-08 20:28:42 +0000923/// launching or attaching to the inferior process, and then 2) servicing
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000924/// operations such as register reads/writes, stepping, etc. See the comments
925/// on the Operation class for more info as to why this is needed.
Andrew Kaylor6578cb62013-07-09 22:36:48 +0000926ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000927 Module *module,
928 const char *argv[],
929 const char *envp[],
930 const char *stdin_path,
931 const char *stdout_path,
932 const char *stderr_path,
Daniel Malea6217d2a2013-01-08 14:49:22 +0000933 const char *working_dir,
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000934 lldb_private::Error &error)
Andrew Kaylor6578cb62013-07-09 22:36:48 +0000935 : m_process(static_cast<ProcessLinux *>(process)),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000936 m_operation_thread(LLDB_INVALID_HOST_THREAD),
Matt Kopec7de48462013-03-06 17:20:48 +0000937 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000938 m_pid(LLDB_INVALID_PROCESS_ID),
939 m_terminal_fd(-1),
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000940 m_client_fd(-1),
941 m_server_fd(-1)
942{
Greg Clayton7b0992d2013-04-18 22:45:39 +0000943 std::unique_ptr<LaunchArgs> args;
Stephen Wilson57740ec2011-01-15 00:12:41 +0000944
945 args.reset(new LaunchArgs(this, module, argv, envp,
Daniel Malea6217d2a2013-01-08 14:49:22 +0000946 stdin_path, stdout_path, stderr_path, working_dir));
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000947
948 // Server/client descriptors.
949 if (!EnableIPC())
950 {
951 error.SetErrorToGenericError();
952 error.SetErrorString("Monitor failed to initialize.");
953 }
954
Johnny Chen25e68e32011-06-14 19:19:50 +0000955 StartLaunchOpThread(args.get(), error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000956 if (!error.Success())
957 return;
958
959WAIT_AGAIN:
960 // Wait for the operation thread to initialize.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000961 if (sem_wait(&args->m_semaphore))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000962 {
963 if (errno == EINTR)
964 goto WAIT_AGAIN;
965 else
966 {
967 error.SetErrorToErrno();
968 return;
969 }
970 }
971
972 // Check that the launch was a success.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000973 if (!args->m_error.Success())
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000974 {
Greg Clayton743ecf42012-10-16 20:20:18 +0000975 StopOpThread();
Stephen Wilson57740ec2011-01-15 00:12:41 +0000976 error = args->m_error;
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000977 return;
978 }
979
980 // Finally, start monitoring the child process for change in state.
Stephen Wilson57740ec2011-01-15 00:12:41 +0000981 m_monitor_thread = Host::StartMonitoringChildProcess(
982 ProcessMonitor::MonitorCallback, this, GetPID(), true);
Stephen Wilsond4182f42011-02-09 20:10:35 +0000983 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
Stephen Wilsone6f9f662010-07-24 02:19:04 +0000984 {
985 error.SetErrorToGenericError();
986 error.SetErrorString("Process launch failed.");
987 return;
988 }
989}
990
Andrew Kaylor6578cb62013-07-09 22:36:48 +0000991ProcessMonitor::ProcessMonitor(ProcessPOSIX *process,
Johnny Chen25e68e32011-06-14 19:19:50 +0000992 lldb::pid_t pid,
993 lldb_private::Error &error)
Andrew Kaylor6578cb62013-07-09 22:36:48 +0000994 : m_process(static_cast<ProcessLinux *>(process)),
Johnny Chen25e68e32011-06-14 19:19:50 +0000995 m_operation_thread(LLDB_INVALID_HOST_THREAD),
Matt Kopec7de48462013-03-06 17:20:48 +0000996 m_monitor_thread(LLDB_INVALID_HOST_THREAD),
Johnny Chen25e68e32011-06-14 19:19:50 +0000997 m_pid(LLDB_INVALID_PROCESS_ID),
998 m_terminal_fd(-1),
Matt Kopec7de48462013-03-06 17:20:48 +0000999
Johnny Chen25e68e32011-06-14 19:19:50 +00001000 m_client_fd(-1),
1001 m_server_fd(-1)
1002{
Greg Clayton7b0992d2013-04-18 22:45:39 +00001003 std::unique_ptr<AttachArgs> args;
Johnny Chen25e68e32011-06-14 19:19:50 +00001004
1005 args.reset(new AttachArgs(this, pid));
1006
1007 // Server/client descriptors.
1008 if (!EnableIPC())
1009 {
1010 error.SetErrorToGenericError();
1011 error.SetErrorString("Monitor failed to initialize.");
1012 }
1013
1014 StartAttachOpThread(args.get(), error);
1015 if (!error.Success())
1016 return;
1017
1018WAIT_AGAIN:
1019 // Wait for the operation thread to initialize.
1020 if (sem_wait(&args->m_semaphore))
1021 {
1022 if (errno == EINTR)
1023 goto WAIT_AGAIN;
1024 else
1025 {
1026 error.SetErrorToErrno();
1027 return;
1028 }
1029 }
1030
Greg Clayton743ecf42012-10-16 20:20:18 +00001031 // Check that the attach was a success.
Johnny Chen25e68e32011-06-14 19:19:50 +00001032 if (!args->m_error.Success())
1033 {
Greg Clayton743ecf42012-10-16 20:20:18 +00001034 StopOpThread();
Johnny Chen25e68e32011-06-14 19:19:50 +00001035 error = args->m_error;
1036 return;
1037 }
1038
1039 // Finally, start monitoring the child process for change in state.
1040 m_monitor_thread = Host::StartMonitoringChildProcess(
1041 ProcessMonitor::MonitorCallback, this, GetPID(), true);
1042 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
1043 {
1044 error.SetErrorToGenericError();
1045 error.SetErrorString("Process attach failed.");
1046 return;
1047 }
1048}
1049
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001050ProcessMonitor::~ProcessMonitor()
1051{
Stephen Wilson84ffe702011-03-30 15:55:52 +00001052 StopMonitor();
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001053}
1054
1055//------------------------------------------------------------------------------
1056// Thread setup and tear down.
1057void
Johnny Chen25e68e32011-06-14 19:19:50 +00001058ProcessMonitor::StartLaunchOpThread(LaunchArgs *args, Error &error)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001059{
1060 static const char *g_thread_name = "lldb.process.linux.operation";
1061
Stephen Wilsond4182f42011-02-09 20:10:35 +00001062 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001063 return;
1064
1065 m_operation_thread =
Johnny Chen25e68e32011-06-14 19:19:50 +00001066 Host::ThreadCreate(g_thread_name, LaunchOpThread, args, &error);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001067}
1068
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001069void *
Johnny Chen25e68e32011-06-14 19:19:50 +00001070ProcessMonitor::LaunchOpThread(void *arg)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001071{
1072 LaunchArgs *args = static_cast<LaunchArgs*>(arg);
1073
Peter Collingbourne4aeb47e2011-06-14 03:55:49 +00001074 if (!Launch(args)) {
1075 sem_post(&args->m_semaphore);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001076 return NULL;
Peter Collingbourne4aeb47e2011-06-14 03:55:49 +00001077 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001078
Stephen Wilson570243b2011-01-19 01:37:06 +00001079 ServeOperation(args);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001080 return NULL;
1081}
1082
1083bool
1084ProcessMonitor::Launch(LaunchArgs *args)
1085{
1086 ProcessMonitor *monitor = args->m_monitor;
1087 ProcessLinux &process = monitor->GetProcess();
1088 const char **argv = args->m_argv;
1089 const char **envp = args->m_envp;
1090 const char *stdin_path = args->m_stdin_path;
1091 const char *stdout_path = args->m_stdout_path;
1092 const char *stderr_path = args->m_stderr_path;
Daniel Malea6217d2a2013-01-08 14:49:22 +00001093 const char *working_dir = args->m_working_dir;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001094
1095 lldb_utility::PseudoTerminal terminal;
1096 const size_t err_len = 1024;
1097 char err_str[err_len];
1098 lldb::pid_t pid;
1099
1100 lldb::ThreadSP inferior;
Ashok Thirumurthi01186352013-03-28 16:02:31 +00001101 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001102
Stephen Wilson57740ec2011-01-15 00:12:41 +00001103 // Propagate the environment if one is not supplied.
1104 if (envp == NULL || envp[0] == NULL)
1105 envp = const_cast<const char **>(environ);
1106
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001107 // Pseudo terminal setup.
1108 if (!terminal.OpenFirstAvailableMaster(O_RDWR | O_NOCTTY, err_str, err_len))
1109 {
1110 args->m_error.SetErrorToGenericError();
1111 args->m_error.SetErrorString("Could not open controlling TTY.");
1112 goto FINISH;
1113 }
1114
Daniel Maleaa85e6b62012-12-07 22:21:08 +00001115 if ((pid = terminal.Fork(err_str, err_len)) == -1)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001116 {
1117 args->m_error.SetErrorToGenericError();
1118 args->m_error.SetErrorString("Process fork failed.");
1119 goto FINISH;
1120 }
1121
Peter Collingbourne6a520222011-06-14 03:55:58 +00001122 // Recognized child exit status codes.
1123 enum {
1124 ePtraceFailed = 1,
1125 eDupStdinFailed,
1126 eDupStdoutFailed,
1127 eDupStderrFailed,
Daniel Malea6217d2a2013-01-08 14:49:22 +00001128 eChdirFailed,
Peter Collingbourne6a520222011-06-14 03:55:58 +00001129 eExecFailed
1130 };
1131
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001132 // Child process.
1133 if (pid == 0)
1134 {
1135 // Trace this process.
Matt Kopec7de48462013-03-06 17:20:48 +00001136 if (PTRACE(PTRACE_TRACEME, 0, NULL, NULL, 0) < 0)
Peter Collingbourne6a520222011-06-14 03:55:58 +00001137 exit(ePtraceFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001138
1139 // Do not inherit setgid powers.
1140 setgid(getgid());
1141
1142 // Let us have our own process group.
1143 setpgid(0, 0);
1144
Greg Clayton710dd5a2011-01-08 20:28:42 +00001145 // Dup file descriptors if needed.
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001146 //
1147 // FIXME: If two or more of the paths are the same we needlessly open
1148 // the same file multiple times.
1149 if (stdin_path != NULL && stdin_path[0])
Peter Collingbourne62343202011-06-14 03:55:54 +00001150 if (!DupDescriptor(stdin_path, STDIN_FILENO, O_RDONLY))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001151 exit(eDupStdinFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001152
1153 if (stdout_path != NULL && stdout_path[0])
1154 if (!DupDescriptor(stdout_path, STDOUT_FILENO, O_WRONLY | O_CREAT))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001155 exit(eDupStdoutFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001156
1157 if (stderr_path != NULL && stderr_path[0])
Peter Collingbourne62343202011-06-14 03:55:54 +00001158 if (!DupDescriptor(stderr_path, STDERR_FILENO, O_WRONLY | O_CREAT))
Peter Collingbourne6a520222011-06-14 03:55:58 +00001159 exit(eDupStderrFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001160
Daniel Malea6217d2a2013-01-08 14:49:22 +00001161 // Change working directory
1162 if (working_dir != NULL && working_dir[0])
1163 if (0 != ::chdir(working_dir))
1164 exit(eChdirFailed);
1165
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001166 // Execute. We should never return.
1167 execve(argv[0],
1168 const_cast<char *const *>(argv),
1169 const_cast<char *const *>(envp));
Peter Collingbourne6a520222011-06-14 03:55:58 +00001170 exit(eExecFailed);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001171 }
1172
1173 // Wait for the child process to to trap on its call to execve.
Peter Collingbourne6a520222011-06-14 03:55:58 +00001174 pid_t wpid;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001175 int status;
Peter Collingbourne6a520222011-06-14 03:55:58 +00001176 if ((wpid = waitpid(pid, &status, 0)) < 0)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001177 {
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001178 args->m_error.SetErrorToErrno();
1179 goto FINISH;
1180 }
Peter Collingbourne6a520222011-06-14 03:55:58 +00001181 else if (WIFEXITED(status))
1182 {
1183 // open, dup or execve likely failed for some reason.
1184 args->m_error.SetErrorToGenericError();
1185 switch (WEXITSTATUS(status))
1186 {
Greg Clayton542e4072012-09-07 17:49:29 +00001187 case ePtraceFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001188 args->m_error.SetErrorString("Child ptrace failed.");
1189 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001190 case eDupStdinFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001191 args->m_error.SetErrorString("Child open stdin failed.");
1192 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001193 case eDupStdoutFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001194 args->m_error.SetErrorString("Child open stdout failed.");
1195 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001196 case eDupStderrFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001197 args->m_error.SetErrorString("Child open stderr failed.");
1198 break;
Daniel Malea6217d2a2013-01-08 14:49:22 +00001199 case eChdirFailed:
1200 args->m_error.SetErrorString("Child failed to set working directory.");
1201 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001202 case eExecFailed:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001203 args->m_error.SetErrorString("Child exec failed.");
1204 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001205 default:
Peter Collingbourne6a520222011-06-14 03:55:58 +00001206 args->m_error.SetErrorString("Child returned unknown exit status.");
1207 break;
1208 }
1209 goto FINISH;
1210 }
1211 assert(WIFSTOPPED(status) && wpid == pid &&
1212 "Could not sync with inferior process.");
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001213
Matt Kopec085d6ce2013-05-31 22:00:07 +00001214 if (!SetDefaultPtraceOpts(pid))
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001215 {
1216 args->m_error.SetErrorToErrno();
1217 goto FINISH;
1218 }
1219
1220 // Release the master terminal descriptor and pass it off to the
1221 // ProcessMonitor instance. Similarly stash the inferior pid.
1222 monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
1223 monitor->m_pid = pid;
1224
Stephen Wilson26977162011-03-23 02:14:42 +00001225 // Set the terminal fd to be in non blocking mode (it simplifies the
1226 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
1227 // descriptor to read from).
1228 if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error))
1229 goto FINISH;
1230
Johnny Chen30213ff2012-01-05 19:17:38 +00001231 // Update the process thread list with this new thread.
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001232 // FIXME: should we be letting UpdateThreadList handle this?
1233 // FIXME: by using pids instead of tids, we can only support one thread.
Michael Sartain9f822cd2013-07-31 23:27:46 +00001234 inferior.reset(process.CreateNewPOSIXThread(process, pid));
Matt Kopecfb6ab542013-07-10 20:53:11 +00001235
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001236 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001237 log->Printf ("ProcessMonitor::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001238 process.GetThreadList().AddThread(inferior);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001239
Matt Kopecb2910442013-07-09 15:09:45 +00001240 process.AddThreadForInitialStopIfNeeded(pid);
1241
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001242 // Let our process instance know the thread has stopped.
1243 process.SendMessage(ProcessMessage::Trace(pid));
1244
1245FINISH:
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001246 return args->m_error.Success();
1247}
1248
1249bool
1250ProcessMonitor::EnableIPC()
1251{
1252 int fd[2];
1253
1254 if (socketpair(AF_UNIX, SOCK_STREAM, 0, fd))
1255 return false;
1256
1257 m_client_fd = fd[0];
1258 m_server_fd = fd[1];
1259 return true;
1260}
1261
Johnny Chen25e68e32011-06-14 19:19:50 +00001262void
1263ProcessMonitor::StartAttachOpThread(AttachArgs *args, lldb_private::Error &error)
1264{
1265 static const char *g_thread_name = "lldb.process.linux.operation";
1266
1267 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
1268 return;
1269
1270 m_operation_thread =
1271 Host::ThreadCreate(g_thread_name, AttachOpThread, args, &error);
1272}
1273
Johnny Chen25e68e32011-06-14 19:19:50 +00001274void *
1275ProcessMonitor::AttachOpThread(void *arg)
1276{
1277 AttachArgs *args = static_cast<AttachArgs*>(arg);
1278
Greg Clayton743ecf42012-10-16 20:20:18 +00001279 if (!Attach(args)) {
1280 sem_post(&args->m_semaphore);
Johnny Chen25e68e32011-06-14 19:19:50 +00001281 return NULL;
Greg Clayton743ecf42012-10-16 20:20:18 +00001282 }
Johnny Chen25e68e32011-06-14 19:19:50 +00001283
1284 ServeOperation(args);
1285 return NULL;
1286}
1287
1288bool
1289ProcessMonitor::Attach(AttachArgs *args)
1290{
1291 lldb::pid_t pid = args->m_pid;
1292
1293 ProcessMonitor *monitor = args->m_monitor;
1294 ProcessLinux &process = monitor->GetProcess();
Johnny Chen25e68e32011-06-14 19:19:50 +00001295 lldb::ThreadSP inferior;
Ashok Thirumurthi01186352013-03-28 16:02:31 +00001296 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
Johnny Chen25e68e32011-06-14 19:19:50 +00001297
Matt Kopec085d6ce2013-05-31 22:00:07 +00001298 // Use a map to keep track of the threads which we have attached/need to attach.
1299 Host::TidMap tids_to_attach;
Johnny Chen25e68e32011-06-14 19:19:50 +00001300 if (pid <= 1)
1301 {
1302 args->m_error.SetErrorToGenericError();
1303 args->m_error.SetErrorString("Attaching to process 1 is not allowed.");
1304 goto FINISH;
1305 }
1306
Matt Kopec085d6ce2013-05-31 22:00:07 +00001307 while (Host::FindProcessThreads(pid, tids_to_attach))
Johnny Chen25e68e32011-06-14 19:19:50 +00001308 {
Matt Kopec085d6ce2013-05-31 22:00:07 +00001309 for (Host::TidMap::iterator it = tids_to_attach.begin();
1310 it != tids_to_attach.end(); ++it)
1311 {
1312 if (it->second == false)
1313 {
1314 lldb::tid_t tid = it->first;
1315
1316 // Attach to the requested process.
1317 // An attach will cause the thread to stop with a SIGSTOP.
1318 if (PTRACE(PTRACE_ATTACH, tid, NULL, NULL, 0) < 0)
1319 {
1320 // No such thread. The thread may have exited.
1321 // More error handling may be needed.
1322 if (errno == ESRCH)
1323 {
1324 tids_to_attach.erase(it);
1325 continue;
1326 }
1327 else
1328 {
1329 args->m_error.SetErrorToErrno();
1330 goto FINISH;
1331 }
1332 }
1333
1334 int status;
1335 // Need to use __WALL otherwise we receive an error with errno=ECHLD
1336 // At this point we should have a thread stopped if waitpid succeeds.
1337 if ((status = waitpid(tid, NULL, __WALL)) < 0)
1338 {
1339 // No such thread. The thread may have exited.
1340 // More error handling may be needed.
1341 if (errno == ESRCH)
1342 {
1343 tids_to_attach.erase(it);
1344 continue;
1345 }
1346 else
1347 {
1348 args->m_error.SetErrorToErrno();
1349 goto FINISH;
1350 }
1351 }
1352
1353 if (!SetDefaultPtraceOpts(tid))
1354 {
1355 args->m_error.SetErrorToErrno();
1356 goto FINISH;
1357 }
1358
1359 // Update the process thread list with the attached thread.
Michael Sartain9f822cd2013-07-31 23:27:46 +00001360 inferior.reset(process.CreateNewPOSIXThread(process, tid));
Matt Kopecfb6ab542013-07-10 20:53:11 +00001361
Matt Kopec085d6ce2013-05-31 22:00:07 +00001362 if (log)
1363 log->Printf ("ProcessMonitor::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
1364 process.GetThreadList().AddThread(inferior);
1365 it->second = true;
Matt Kopecb2910442013-07-09 15:09:45 +00001366 process.AddThreadForInitialStopIfNeeded(tid);
Matt Kopec085d6ce2013-05-31 22:00:07 +00001367 }
1368 }
Johnny Chen25e68e32011-06-14 19:19:50 +00001369 }
1370
Matt Kopec085d6ce2013-05-31 22:00:07 +00001371 if (tids_to_attach.size() > 0)
Johnny Chen25e68e32011-06-14 19:19:50 +00001372 {
Matt Kopec085d6ce2013-05-31 22:00:07 +00001373 monitor->m_pid = pid;
1374 // Let our process instance know the thread has stopped.
1375 process.SendMessage(ProcessMessage::Trace(pid));
Johnny Chen25e68e32011-06-14 19:19:50 +00001376 }
Matt Kopec085d6ce2013-05-31 22:00:07 +00001377 else
1378 {
1379 args->m_error.SetErrorToGenericError();
1380 args->m_error.SetErrorString("No such process.");
1381 }
Johnny Chen25e68e32011-06-14 19:19:50 +00001382
1383 FINISH:
1384 return args->m_error.Success();
1385}
1386
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001387bool
Matt Kopec085d6ce2013-05-31 22:00:07 +00001388ProcessMonitor::SetDefaultPtraceOpts(lldb::pid_t pid)
1389{
1390 long ptrace_opts = 0;
1391
1392 // Have the child raise an event on exit. This is used to keep the child in
1393 // limbo until it is destroyed.
1394 ptrace_opts |= PTRACE_O_TRACEEXIT;
1395
1396 // Have the tracer trace threads which spawn in the inferior process.
1397 // TODO: if we want to support tracing the inferiors' child, add the
1398 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
1399 ptrace_opts |= PTRACE_O_TRACECLONE;
1400
1401 // Have the tracer notify us before execve returns
1402 // (needed to disable legacy SIGTRAP generation)
1403 ptrace_opts |= PTRACE_O_TRACEEXEC;
1404
1405 return PTRACE(PTRACE_SETOPTIONS, pid, NULL, (void*)ptrace_opts, 0) >= 0;
1406}
1407
1408bool
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001409ProcessMonitor::MonitorCallback(void *callback_baton,
1410 lldb::pid_t pid,
Peter Collingbourne2c67b9a2011-11-21 00:10:19 +00001411 bool exited,
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001412 int signal,
1413 int status)
1414{
1415 ProcessMessage message;
1416 ProcessMonitor *monitor = static_cast<ProcessMonitor*>(callback_baton);
Andrew Kaylor6578cb62013-07-09 22:36:48 +00001417 ProcessLinux *process = monitor->m_process;
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001418 assert(process);
Stephen Wilson84ffe702011-03-30 15:55:52 +00001419 bool stop_monitoring;
1420 siginfo_t info;
Daniel Maleaa35970a2012-11-23 18:09:58 +00001421 int ptrace_err;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001422
Andrew Kaylor93132f52013-05-28 23:04:25 +00001423 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1424
1425 if (exited)
1426 {
1427 if (log)
1428 log->Printf ("ProcessMonitor::%s() got exit signal, tid = %" PRIu64, __FUNCTION__, pid);
1429 message = ProcessMessage::Exit(pid, status);
1430 process->SendMessage(message);
1431 return pid == process->GetID();
1432 }
1433
Daniel Maleaa35970a2012-11-23 18:09:58 +00001434 if (!monitor->GetSignalInfo(pid, &info, ptrace_err)) {
1435 if (ptrace_err == EINVAL) {
Andrew Kaylor93132f52013-05-28 23:04:25 +00001436 if (log)
1437 log->Printf ("ProcessMonitor::%s() resuming from group-stop", __FUNCTION__);
Daniel Maleaa35970a2012-11-23 18:09:58 +00001438 // inferior process is in 'group-stop', so deliver SIGSTOP signal
1439 if (!monitor->Resume(pid, SIGSTOP)) {
1440 assert(0 && "SIGSTOP delivery failed while in 'group-stop' state");
1441 }
1442 stop_monitoring = false;
1443 } else {
1444 // ptrace(GETSIGINFO) failed (but not due to group-stop). Most likely,
1445 // this means the child pid is gone (or not being debugged) therefore
Andrew Kaylor93132f52013-05-28 23:04:25 +00001446 // stop the monitor thread if this is the main pid.
1447 if (log)
1448 log->Printf ("ProcessMonitor::%s() GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d",
1449 __FUNCTION__, strerror(ptrace_err), pid, signal, status);
1450 stop_monitoring = pid == monitor->m_process->GetID();
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +00001451 // If we are going to stop monitoring, we need to notify our process object
1452 if (stop_monitoring)
1453 {
1454 message = ProcessMessage::Exit(pid, status);
1455 process->SendMessage(message);
1456 }
Daniel Maleaa35970a2012-11-23 18:09:58 +00001457 }
1458 }
Stephen Wilson84ffe702011-03-30 15:55:52 +00001459 else {
1460 switch (info.si_signo)
1461 {
1462 case SIGTRAP:
1463 message = MonitorSIGTRAP(monitor, &info, pid);
1464 break;
Greg Clayton542e4072012-09-07 17:49:29 +00001465
Stephen Wilson84ffe702011-03-30 15:55:52 +00001466 default:
1467 message = MonitorSignal(monitor, &info, pid);
1468 break;
1469 }
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001470
Stephen Wilson84ffe702011-03-30 15:55:52 +00001471 process->SendMessage(message);
Andrew Kaylor93132f52013-05-28 23:04:25 +00001472 stop_monitoring = false;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001473 }
1474
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001475 return stop_monitoring;
1476}
1477
1478ProcessMessage
Stephen Wilson84ffe702011-03-30 15:55:52 +00001479ProcessMonitor::MonitorSIGTRAP(ProcessMonitor *monitor,
Greg Clayton28041352011-11-29 20:50:10 +00001480 const siginfo_t *info, lldb::pid_t pid)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001481{
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001482 ProcessMessage message;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001483
Andrew Kaylor93132f52013-05-28 23:04:25 +00001484 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1485
Johnny Chen0d5f2d42011-10-18 18:09:30 +00001486 assert(monitor);
1487 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!");
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001488
Stephen Wilson84ffe702011-03-30 15:55:52 +00001489 switch (info->si_code)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001490 {
1491 default:
1492 assert(false && "Unexpected SIGTRAP code!");
1493 break;
1494
Matt Kopeca360d7e2013-05-17 19:27:47 +00001495 // TODO: these two cases are required if we want to support tracing
1496 // of the inferiors' children
1497 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
1498 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
1499
Matt Kopec650648f2013-01-08 16:30:18 +00001500 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
1501 {
Andrew Kaylor93132f52013-05-28 23:04:25 +00001502 if (log)
1503 log->Printf ("ProcessMonitor::%s() received thread creation event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP);
1504
Matt Kopec650648f2013-01-08 16:30:18 +00001505 unsigned long tid = 0;
1506 if (!monitor->GetEventMessage(pid, &tid))
1507 tid = -1;
1508 message = ProcessMessage::NewThread(pid, tid);
1509 break;
1510 }
1511
Matt Kopeca360d7e2013-05-17 19:27:47 +00001512 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
1513 // Don't follow the child by default and resume
1514 monitor->Resume(pid, SIGCONT);
1515 break;
1516
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001517 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
1518 {
Andrew Kaylor93132f52013-05-28 23:04:25 +00001519 // The inferior process or one of its threads is about to exit.
1520 // Maintain the process or thread in a state of "limbo" until we are
1521 // explicitly commanded to detach, destroy, resume, etc.
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001522 unsigned long data = 0;
1523 if (!monitor->GetEventMessage(pid, &data))
1524 data = -1;
Andrew Kaylor93132f52013-05-28 23:04:25 +00001525 if (log)
Matt Kopecb2910442013-07-09 15:09:45 +00001526 log->Printf ("ProcessMonitor::%s() received limbo event, data = %lx, pid = %" PRIu64, __FUNCTION__, data, pid);
Stephen Wilson84ffe702011-03-30 15:55:52 +00001527 message = ProcessMessage::Limbo(pid, (data >> 8));
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001528 break;
1529 }
1530
1531 case 0:
1532 case TRAP_TRACE:
Andrew Kaylor93132f52013-05-28 23:04:25 +00001533 if (log)
1534 log->Printf ("ProcessMonitor::%s() received trace event, pid = %" PRIu64, __FUNCTION__, pid);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001535 message = ProcessMessage::Trace(pid);
1536 break;
1537
1538 case SI_KERNEL:
1539 case TRAP_BRKPT:
Andrew Kaylor93132f52013-05-28 23:04:25 +00001540 if (log)
1541 log->Printf ("ProcessMonitor::%s() received breakpoint event, pid = %" PRIu64, __FUNCTION__, pid);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001542 message = ProcessMessage::Break(pid);
1543 break;
Matt Kopece9ea0da2013-05-07 19:29:28 +00001544
1545 case TRAP_HWBKPT:
Andrew Kaylor93132f52013-05-28 23:04:25 +00001546 if (log)
1547 log->Printf ("ProcessMonitor::%s() received watchpoint event, pid = %" PRIu64, __FUNCTION__, pid);
Matt Kopece9ea0da2013-05-07 19:29:28 +00001548 message = ProcessMessage::Watch(pid, (lldb::addr_t)info->si_addr);
1549 break;
Matt Kopec4a32bf52013-07-11 20:01:22 +00001550
1551 case SIGTRAP:
1552 case (SIGTRAP | 0x80):
1553 if (log)
1554 log->Printf ("ProcessMonitor::%s() received system call stop event, pid = %" PRIu64, __FUNCTION__, pid);
1555 // Ignore these signals until we know more about them
1556 monitor->Resume(pid, eResumeSignalNone);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001557 }
1558
1559 return message;
1560}
1561
Stephen Wilson84ffe702011-03-30 15:55:52 +00001562ProcessMessage
1563ProcessMonitor::MonitorSignal(ProcessMonitor *monitor,
Greg Clayton28041352011-11-29 20:50:10 +00001564 const siginfo_t *info, lldb::pid_t pid)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001565{
1566 ProcessMessage message;
1567 int signo = info->si_signo;
1568
Andrew Kaylor93132f52013-05-28 23:04:25 +00001569 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1570
Stephen Wilson84ffe702011-03-30 15:55:52 +00001571 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1572 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1573 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
1574 //
1575 // IOW, user generated signals never generate what we consider to be a
1576 // "crash".
1577 //
1578 // Similarly, ACK signals generated by this monitor.
1579 if (info->si_code == SI_TKILL || info->si_code == SI_USER)
1580 {
Andrew Kaylor93132f52013-05-28 23:04:25 +00001581 if (log)
Matt Kopecef143712013-06-03 18:00:07 +00001582 log->Printf ("ProcessMonitor::%s() received signal %s with code %s, pid = %d",
Andrew Kaylor93132f52013-05-28 23:04:25 +00001583 __FUNCTION__,
1584 monitor->m_process->GetUnixSignals().GetSignalAsCString (signo),
1585 (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
1586 info->si_pid);
1587
Stephen Wilson84ffe702011-03-30 15:55:52 +00001588 if (info->si_pid == getpid())
1589 return ProcessMessage::SignalDelivered(pid, signo);
1590 else
1591 return ProcessMessage::Signal(pid, signo);
1592 }
1593
Andrew Kaylor93132f52013-05-28 23:04:25 +00001594 if (log)
1595 log->Printf ("ProcessMonitor::%s() received signal %s", __FUNCTION__, monitor->m_process->GetUnixSignals().GetSignalAsCString (signo));
1596
Stephen Wilson84ffe702011-03-30 15:55:52 +00001597 if (signo == SIGSEGV) {
1598 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1599 ProcessMessage::CrashReason reason = GetCrashReasonForSIGSEGV(info);
1600 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1601 }
1602
1603 if (signo == SIGILL) {
1604 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1605 ProcessMessage::CrashReason reason = GetCrashReasonForSIGILL(info);
1606 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1607 }
1608
1609 if (signo == SIGFPE) {
1610 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1611 ProcessMessage::CrashReason reason = GetCrashReasonForSIGFPE(info);
1612 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1613 }
1614
1615 if (signo == SIGBUS) {
1616 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr);
1617 ProcessMessage::CrashReason reason = GetCrashReasonForSIGBUS(info);
1618 return ProcessMessage::Crash(pid, reason, signo, fault_addr);
1619 }
1620
1621 // Everything else is "normal" and does not require any special action on
1622 // our part.
1623 return ProcessMessage::Signal(pid, signo);
1624}
1625
Andrew Kaylor93132f52013-05-28 23:04:25 +00001626bool
1627ProcessMonitor::StopThread(lldb::tid_t tid)
1628{
1629 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
1630
1631 // FIXME: Try to use tgkill or tkill
1632 int ret = tgkill(m_pid, tid, SIGSTOP);
1633 if (log)
1634 log->Printf ("ProcessMonitor::%s(bp) stopping thread, tid = %" PRIu64 ", ret = %d", __FUNCTION__, tid, ret);
1635
1636 // This can happen if a thread exited while we were trying to stop it. That's OK.
1637 // We'll get the signal for that later.
1638 if (ret < 0)
1639 return false;
1640
1641 // Wait for the thread to stop
1642 while (true)
1643 {
1644 int status = -1;
1645 if (log)
1646 log->Printf ("ProcessMonitor::%s(bp) waitpid...", __FUNCTION__);
1647 lldb::pid_t wait_pid = ::waitpid (-1*m_pid, &status, __WALL);
1648 if (log)
1649 log->Printf ("ProcessMonitor::%s(bp) waitpid, pid = %" PRIu64 ", status = %d", __FUNCTION__, wait_pid, status);
1650
1651 if (wait_pid == -1)
1652 {
1653 // If we got interrupted by a signal (in our process, not the
1654 // inferior) try again.
1655 if (errno == EINTR)
1656 continue;
1657 else
1658 return false; // This is bad, but there's nothing we can do.
1659 }
1660
1661 // If this is a thread exit, we won't get any more information.
1662 if (WIFEXITED(status))
1663 {
1664 m_process->SendMessage(ProcessMessage::Exit(wait_pid, WEXITSTATUS(status)));
1665 if (wait_pid == tid)
1666 return true;
1667 continue;
1668 }
1669
1670 siginfo_t info;
1671 int ptrace_err;
1672 if (!GetSignalInfo(wait_pid, &info, ptrace_err))
1673 {
1674 if (log)
1675 {
1676 log->Printf ("ProcessMonitor::%s() GetSignalInfo failed.", __FUNCTION__);
1677
1678 // This would be a particularly interesting case
1679 if (ptrace_err == EINVAL)
1680 log->Printf ("ProcessMonitor::%s() in group-stop", __FUNCTION__);
1681 }
1682 return false;
1683 }
1684
1685 // Handle events from other threads
1686 if (log)
Matt Kopecef143712013-06-03 18:00:07 +00001687 log->Printf ("ProcessMonitor::%s(bp) handling event, tid == %" PRIu64, __FUNCTION__, wait_pid);
Andrew Kaylor93132f52013-05-28 23:04:25 +00001688
1689 ProcessMessage message;
1690 if (info.si_signo == SIGTRAP)
1691 message = MonitorSIGTRAP(this, &info, wait_pid);
1692 else
1693 message = MonitorSignal(this, &info, wait_pid);
1694
1695 POSIXThread *thread = static_cast<POSIXThread*>(m_process->GetThreadList().FindThreadByID(wait_pid).get());
1696
1697 // When a new thread is created, we may get a SIGSTOP for the new thread
1698 // just before we get the SIGTRAP that we use to add the thread to our
1699 // process thread list. We don't need to worry about that signal here.
1700 assert(thread || message.GetKind() == ProcessMessage::eSignalMessage);
1701
1702 if (!thread)
1703 {
1704 m_process->SendMessage(message);
1705 continue;
1706 }
1707
1708 switch (message.GetKind())
1709 {
1710 case ProcessMessage::eInvalidMessage:
1711 break;
1712
1713 // These need special handling because we don't want to send a
1714 // resume even if we already sent a SIGSTOP to this thread. In
1715 // this case the resume will cause the thread to disappear. It is
1716 // unlikely that we'll ever get eExitMessage here, but the same
1717 // reasoning applies.
1718 case ProcessMessage::eLimboMessage:
1719 case ProcessMessage::eExitMessage:
1720 if (log)
1721 log->Printf ("ProcessMonitor::%s(bp) handling message", __FUNCTION__);
1722 // SendMessage will set the thread state as needed.
1723 m_process->SendMessage(message);
1724 // If this is the thread we're waiting for, stop waiting. Even
1725 // though this wasn't the signal we expected, it's the last
1726 // signal we'll see while this thread is alive.
1727 if (wait_pid == tid)
1728 return true;
1729 break;
1730
Matt Kopecb2910442013-07-09 15:09:45 +00001731 case ProcessMessage::eSignalMessage:
1732 if (log)
1733 log->Printf ("ProcessMonitor::%s(bp) handling message", __FUNCTION__);
1734 if (WSTOPSIG(status) == SIGSTOP)
1735 {
1736 m_process->AddThreadForInitialStopIfNeeded(tid);
1737 thread->SetState(lldb::eStateStopped);
1738 }
1739 else
1740 {
1741 m_process->SendMessage(message);
1742 // This isn't the stop we were expecting, but the thread is
1743 // stopped. SendMessage will handle processing of this event,
1744 // but we need to resume here to get the stop we are waiting
1745 // for (otherwise the thread will stop again immediately when
1746 // we try to resume).
1747 if (wait_pid == tid)
1748 Resume(wait_pid, eResumeSignalNone);
1749 }
1750 break;
1751
Andrew Kaylor93132f52013-05-28 23:04:25 +00001752 case ProcessMessage::eSignalDeliveredMessage:
1753 // This is the stop we're expecting.
1754 if (wait_pid == tid && WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP && info.si_code == SI_TKILL)
1755 {
1756 if (log)
1757 log->Printf ("ProcessMonitor::%s(bp) received signal, done waiting", __FUNCTION__);
1758 thread->SetState(lldb::eStateStopped);
1759 return true;
1760 }
1761 // else fall-through
Andrew Kaylor93132f52013-05-28 23:04:25 +00001762 case ProcessMessage::eBreakpointMessage:
1763 case ProcessMessage::eTraceMessage:
1764 case ProcessMessage::eWatchpointMessage:
1765 case ProcessMessage::eCrashMessage:
1766 case ProcessMessage::eNewThreadMessage:
1767 if (log)
1768 log->Printf ("ProcessMonitor::%s(bp) handling message", __FUNCTION__);
1769 // SendMessage will set the thread state as needed.
1770 m_process->SendMessage(message);
1771 // This isn't the stop we were expecting, but the thread is
1772 // stopped. SendMessage will handle processing of this event,
1773 // but we need to resume here to get the stop we are waiting
1774 // for (otherwise the thread will stop again immediately when
1775 // we try to resume).
1776 if (wait_pid == tid)
1777 Resume(wait_pid, eResumeSignalNone);
1778 break;
1779 }
1780 }
1781 return false;
1782}
1783
Stephen Wilson84ffe702011-03-30 15:55:52 +00001784ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001785ProcessMonitor::GetCrashReasonForSIGSEGV(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001786{
1787 ProcessMessage::CrashReason reason;
1788 assert(info->si_signo == SIGSEGV);
1789
1790 reason = ProcessMessage::eInvalidCrashReason;
1791
Greg Clayton542e4072012-09-07 17:49:29 +00001792 switch (info->si_code)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001793 {
1794 default:
1795 assert(false && "unexpected si_code for SIGSEGV");
1796 break;
Matt Kopecf8cfe6b2013-08-09 15:26:56 +00001797 case SI_KERNEL:
1798 // Linux will occasionally send spurious SI_KERNEL codes.
1799 // (this is poorly documented in sigaction)
1800 // One way to get this is via unaligned SIMD loads.
1801 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
1802 break;
Stephen Wilson84ffe702011-03-30 15:55:52 +00001803 case SEGV_MAPERR:
1804 reason = ProcessMessage::eInvalidAddress;
1805 break;
1806 case SEGV_ACCERR:
1807 reason = ProcessMessage::ePrivilegedAddress;
1808 break;
1809 }
Greg Clayton542e4072012-09-07 17:49:29 +00001810
Stephen Wilson84ffe702011-03-30 15:55:52 +00001811 return reason;
1812}
1813
1814ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001815ProcessMonitor::GetCrashReasonForSIGILL(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001816{
1817 ProcessMessage::CrashReason reason;
1818 assert(info->si_signo == SIGILL);
1819
1820 reason = ProcessMessage::eInvalidCrashReason;
1821
1822 switch (info->si_code)
1823 {
1824 default:
1825 assert(false && "unexpected si_code for SIGILL");
1826 break;
1827 case ILL_ILLOPC:
1828 reason = ProcessMessage::eIllegalOpcode;
1829 break;
1830 case ILL_ILLOPN:
1831 reason = ProcessMessage::eIllegalOperand;
1832 break;
1833 case ILL_ILLADR:
1834 reason = ProcessMessage::eIllegalAddressingMode;
1835 break;
1836 case ILL_ILLTRP:
1837 reason = ProcessMessage::eIllegalTrap;
1838 break;
1839 case ILL_PRVOPC:
1840 reason = ProcessMessage::ePrivilegedOpcode;
1841 break;
1842 case ILL_PRVREG:
1843 reason = ProcessMessage::ePrivilegedRegister;
1844 break;
1845 case ILL_COPROC:
1846 reason = ProcessMessage::eCoprocessorError;
1847 break;
1848 case ILL_BADSTK:
1849 reason = ProcessMessage::eInternalStackError;
1850 break;
1851 }
1852
1853 return reason;
1854}
1855
1856ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001857ProcessMonitor::GetCrashReasonForSIGFPE(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001858{
1859 ProcessMessage::CrashReason reason;
1860 assert(info->si_signo == SIGFPE);
1861
1862 reason = ProcessMessage::eInvalidCrashReason;
1863
1864 switch (info->si_code)
1865 {
1866 default:
1867 assert(false && "unexpected si_code for SIGFPE");
1868 break;
1869 case FPE_INTDIV:
1870 reason = ProcessMessage::eIntegerDivideByZero;
1871 break;
1872 case FPE_INTOVF:
1873 reason = ProcessMessage::eIntegerOverflow;
1874 break;
1875 case FPE_FLTDIV:
1876 reason = ProcessMessage::eFloatDivideByZero;
1877 break;
1878 case FPE_FLTOVF:
1879 reason = ProcessMessage::eFloatOverflow;
1880 break;
1881 case FPE_FLTUND:
1882 reason = ProcessMessage::eFloatUnderflow;
1883 break;
1884 case FPE_FLTRES:
1885 reason = ProcessMessage::eFloatInexactResult;
1886 break;
1887 case FPE_FLTINV:
1888 reason = ProcessMessage::eFloatInvalidOperation;
1889 break;
1890 case FPE_FLTSUB:
1891 reason = ProcessMessage::eFloatSubscriptRange;
1892 break;
1893 }
1894
1895 return reason;
1896}
1897
1898ProcessMessage::CrashReason
Greg Clayton28041352011-11-29 20:50:10 +00001899ProcessMonitor::GetCrashReasonForSIGBUS(const siginfo_t *info)
Stephen Wilson84ffe702011-03-30 15:55:52 +00001900{
1901 ProcessMessage::CrashReason reason;
1902 assert(info->si_signo == SIGBUS);
1903
1904 reason = ProcessMessage::eInvalidCrashReason;
1905
1906 switch (info->si_code)
1907 {
1908 default:
1909 assert(false && "unexpected si_code for SIGBUS");
1910 break;
1911 case BUS_ADRALN:
1912 reason = ProcessMessage::eIllegalAlignment;
1913 break;
1914 case BUS_ADRERR:
1915 reason = ProcessMessage::eIllegalAddress;
1916 break;
1917 case BUS_OBJERR:
1918 reason = ProcessMessage::eHardwareError;
1919 break;
1920 }
1921
1922 return reason;
1923}
1924
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001925void
Johnny Chen25e68e32011-06-14 19:19:50 +00001926ProcessMonitor::ServeOperation(OperationArgs *args)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001927{
1928 int status;
1929 pollfd fdset;
Johnny Chen25e68e32011-06-14 19:19:50 +00001930
Stephen Wilson570243b2011-01-19 01:37:06 +00001931 ProcessMonitor *monitor = args->m_monitor;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001932
1933 fdset.fd = monitor->m_server_fd;
1934 fdset.events = POLLIN | POLLPRI;
1935 fdset.revents = 0;
1936
Stephen Wilson570243b2011-01-19 01:37:06 +00001937 // We are finised with the arguments and are ready to go. Sync with the
1938 // parent thread and start serving operations on the inferior.
1939 sem_post(&args->m_semaphore);
1940
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001941 for (;;)
1942 {
1943 if ((status = poll(&fdset, 1, -1)) < 0)
1944 {
1945 switch (errno)
1946 {
1947 default:
1948 assert(false && "Unexpected poll() failure!");
1949 continue;
1950
1951 case EINTR: continue; // Just poll again.
1952 case EBADF: return; // Connection terminated.
1953 }
1954 }
1955
1956 assert(status == 1 && "Too many descriptors!");
1957
1958 if (fdset.revents & POLLIN)
1959 {
1960 Operation *op = NULL;
1961
1962 READ_AGAIN:
1963 if ((status = read(fdset.fd, &op, sizeof(op))) < 0)
1964 {
1965 // There is only one acceptable failure.
1966 assert(errno == EINTR);
1967 goto READ_AGAIN;
1968 }
Matt Kopec9eb40a92013-03-14 21:35:26 +00001969 if (status == 0)
1970 continue; // Poll again. The connection probably terminated.
Stephen Wilsone6f9f662010-07-24 02:19:04 +00001971 assert(status == sizeof(op));
1972 op->Execute(monitor);
1973 write(fdset.fd, &op, sizeof(op));
1974 }
1975 }
1976}
1977
1978void
1979ProcessMonitor::DoOperation(Operation *op)
1980{
1981 int status;
1982 Operation *ack = NULL;
1983 Mutex::Locker lock(m_server_mutex);
1984
1985 // FIXME: Do proper error checking here.
1986 write(m_client_fd, &op, sizeof(op));
1987
1988READ_AGAIN:
1989 if ((status = read(m_client_fd, &ack, sizeof(ack))) < 0)
1990 {
1991 // If interrupted by a signal handler try again. Otherwise the monitor
1992 // thread probably died and we have a stale file descriptor -- abort the
1993 // operation.
1994 if (errno == EINTR)
1995 goto READ_AGAIN;
1996 return;
1997 }
1998
1999 assert(status == sizeof(ack));
2000 assert(ack == op && "Invalid monitor thread response!");
2001}
2002
2003size_t
2004ProcessMonitor::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
2005 Error &error)
2006{
2007 size_t result;
2008 ReadOperation op(vm_addr, buf, size, error, result);
2009 DoOperation(&op);
2010 return result;
2011}
2012
2013size_t
2014ProcessMonitor::WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size,
2015 lldb_private::Error &error)
2016{
2017 size_t result;
2018 WriteOperation op(vm_addr, buf, size, error, result);
2019 DoOperation(&op);
2020 return result;
2021}
2022
2023bool
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00002024ProcessMonitor::ReadRegisterValue(lldb::tid_t tid, unsigned offset, const char* reg_name,
Matt Kopec7de48462013-03-06 17:20:48 +00002025 unsigned size, RegisterValue &value)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002026{
2027 bool result;
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00002028 ReadRegOperation op(tid, offset, reg_name, value, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002029 DoOperation(&op);
2030 return result;
2031}
2032
2033bool
Matt Kopec7de48462013-03-06 17:20:48 +00002034ProcessMonitor::WriteRegisterValue(lldb::tid_t tid, unsigned offset,
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00002035 const char* reg_name, const RegisterValue &value)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002036{
2037 bool result;
Ashok Thirumurthiacbb1a52013-05-09 19:59:47 +00002038 WriteRegOperation op(tid, offset, reg_name, value, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002039 DoOperation(&op);
2040 return result;
2041}
2042
2043bool
Matt Kopec7de48462013-03-06 17:20:48 +00002044ProcessMonitor::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size)
Stephen Wilsonade1aea2011-01-19 01:31:38 +00002045{
2046 bool result;
Matt Kopec7de48462013-03-06 17:20:48 +00002047 ReadGPROperation op(tid, buf, buf_size, result);
Stephen Wilsonade1aea2011-01-19 01:31:38 +00002048 DoOperation(&op);
2049 return result;
2050}
2051
2052bool
Matt Kopec7de48462013-03-06 17:20:48 +00002053ProcessMonitor::ReadFPR(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 ReadFPROperation op(tid, buf, buf_size, result);
Stephen Wilsonade1aea2011-01-19 01:31:38 +00002057 DoOperation(&op);
2058 return result;
2059}
2060
2061bool
Matt Kopec58c0b962013-03-20 20:34:35 +00002062ProcessMonitor::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
2063{
2064 bool result;
2065 ReadRegisterSetOperation op(tid, buf, buf_size, regset, result);
2066 DoOperation(&op);
2067 return result;
2068}
2069
2070bool
Matt Kopec7de48462013-03-06 17:20:48 +00002071ProcessMonitor::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size)
Peter Collingbourne10bc0102011-06-03 20:41:02 +00002072{
2073 bool result;
Matt Kopec7de48462013-03-06 17:20:48 +00002074 WriteGPROperation op(tid, buf, buf_size, result);
Peter Collingbourne10bc0102011-06-03 20:41:02 +00002075 DoOperation(&op);
2076 return result;
2077}
2078
2079bool
Matt Kopec7de48462013-03-06 17:20:48 +00002080ProcessMonitor::WriteFPR(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 WriteFPROperation op(tid, buf, buf_size, result);
Peter Collingbourne10bc0102011-06-03 20:41:02 +00002084 DoOperation(&op);
2085 return result;
2086}
2087
2088bool
Matt Kopec58c0b962013-03-20 20:34:35 +00002089ProcessMonitor::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset)
2090{
2091 bool result;
2092 WriteRegisterSetOperation op(tid, buf, buf_size, regset, result);
2093 DoOperation(&op);
2094 return result;
2095}
2096
2097bool
Stephen Wilson84ffe702011-03-30 15:55:52 +00002098ProcessMonitor::Resume(lldb::tid_t tid, uint32_t signo)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002099{
2100 bool result;
Andrew Kaylor93132f52013-05-28 23:04:25 +00002101 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
2102
2103 if (log)
2104 log->Printf ("ProcessMonitor::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid,
2105 m_process->GetUnixSignals().GetSignalAsCString (signo));
Stephen Wilson84ffe702011-03-30 15:55:52 +00002106 ResumeOperation op(tid, signo, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002107 DoOperation(&op);
Andrew Kaylor93132f52013-05-28 23:04:25 +00002108 if (log)
2109 log->Printf ("ProcessMonitor::%s() resuming result = %s", __FUNCTION__, result ? "true" : "false");
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002110 return result;
2111}
2112
2113bool
Stephen Wilson84ffe702011-03-30 15:55:52 +00002114ProcessMonitor::SingleStep(lldb::tid_t tid, uint32_t signo)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002115{
2116 bool result;
Stephen Wilson84ffe702011-03-30 15:55:52 +00002117 SingleStepOperation op(tid, signo, result);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002118 DoOperation(&op);
2119 return result;
2120}
2121
2122bool
2123ProcessMonitor::BringProcessIntoLimbo()
2124{
2125 bool result;
2126 KillOperation op(result);
2127 DoOperation(&op);
2128 return result;
2129}
2130
2131bool
Daniel Maleaa35970a2012-11-23 18:09:58 +00002132ProcessMonitor::GetSignalInfo(lldb::tid_t tid, void *siginfo, int &ptrace_err)
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002133{
2134 bool result;
Daniel Maleaa35970a2012-11-23 18:09:58 +00002135 SiginfoOperation op(tid, siginfo, result, ptrace_err);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002136 DoOperation(&op);
2137 return result;
2138}
2139
2140bool
2141ProcessMonitor::GetEventMessage(lldb::tid_t tid, unsigned long *message)
2142{
2143 bool result;
2144 EventMessageOperation op(tid, message, result);
2145 DoOperation(&op);
2146 return result;
2147}
2148
Greg Clayton743ecf42012-10-16 20:20:18 +00002149lldb_private::Error
Matt Kopec085d6ce2013-05-31 22:00:07 +00002150ProcessMonitor::Detach(lldb::tid_t tid)
Stephen Wilson84ffe702011-03-30 15:55:52 +00002151{
Greg Clayton28041352011-11-29 20:50:10 +00002152 lldb_private::Error error;
Matt Kopec085d6ce2013-05-31 22:00:07 +00002153 if (tid != LLDB_INVALID_THREAD_ID)
2154 {
2155 DetachOperation op(tid, error);
Greg Clayton743ecf42012-10-16 20:20:18 +00002156 DoOperation(&op);
2157 }
Greg Clayton743ecf42012-10-16 20:20:18 +00002158 return error;
Greg Clayton542e4072012-09-07 17:49:29 +00002159}
Stephen Wilson84ffe702011-03-30 15:55:52 +00002160
2161bool
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002162ProcessMonitor::DupDescriptor(const char *path, int fd, int flags)
2163{
Peter Collingbourne62343202011-06-14 03:55:54 +00002164 int target_fd = open(path, flags, 0666);
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002165
2166 if (target_fd == -1)
2167 return false;
2168
Peter Collingbourne62343202011-06-14 03:55:54 +00002169 return (dup2(target_fd, fd) == -1) ? false : true;
Stephen Wilsone6f9f662010-07-24 02:19:04 +00002170}
Stephen Wilson9212d7f2011-01-04 21:40:25 +00002171
2172void
2173ProcessMonitor::StopMonitoringChildProcess()
2174{
2175 lldb::thread_result_t thread_result;
2176
Stephen Wilsond4182f42011-02-09 20:10:35 +00002177 if (IS_VALID_LLDB_HOST_THREAD(m_monitor_thread))
Stephen Wilson9212d7f2011-01-04 21:40:25 +00002178 {
2179 Host::ThreadCancel(m_monitor_thread, NULL);
2180 Host::ThreadJoin(m_monitor_thread, &thread_result, NULL);
2181 m_monitor_thread = LLDB_INVALID_HOST_THREAD;
2182 }
2183}
Stephen Wilson84ffe702011-03-30 15:55:52 +00002184
2185void
2186ProcessMonitor::StopMonitor()
2187{
2188 StopMonitoringChildProcess();
Greg Clayton743ecf42012-10-16 20:20:18 +00002189 StopOpThread();
Stephen Wilson84ffe702011-03-30 15:55:52 +00002190 CloseFD(m_terminal_fd);
2191 CloseFD(m_client_fd);
2192 CloseFD(m_server_fd);
2193}
2194
2195void
Greg Clayton743ecf42012-10-16 20:20:18 +00002196ProcessMonitor::StopOpThread()
2197{
2198 lldb::thread_result_t result;
2199
2200 if (!IS_VALID_LLDB_HOST_THREAD(m_operation_thread))
2201 return;
2202
2203 Host::ThreadCancel(m_operation_thread, NULL);
2204 Host::ThreadJoin(m_operation_thread, &result, NULL);
Daniel Malea8b9e71e2012-11-22 18:21:05 +00002205 m_operation_thread = LLDB_INVALID_HOST_THREAD;
Greg Clayton743ecf42012-10-16 20:20:18 +00002206}
2207
2208void
Stephen Wilson84ffe702011-03-30 15:55:52 +00002209ProcessMonitor::CloseFD(int &fd)
2210{
2211 if (fd != -1)
2212 {
2213 close(fd);
2214 fd = -1;
2215 }
2216}